> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/zh/mo-xing/tutorials/gemma-3-how-to-run-and-fine-tune.md).

# Gemma 3 - 如何运行指南

谷歌发布了 Gemma 3，新增 270M 模型，并保留之前的 1B、4B、12B 和 27B 尺寸。270M 和 1B 仅支持文本，而更大的模型同时处理文本和视觉。我们提供 GGUF，以及如何高效运行它的指南，以及如何微调和进行 [RL](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md) ，搭配 Gemma 3！

{% hint style="success" %}
**新 2025 年 8 月 14 日更新：** 试试我们的微调 [Gemma 3（270M）笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(270M\).ipynb) 和 [用于运行的 GGUF](https://huggingface.co/collections/unsloth/gemma-3-67d12b7e8816ec6efa7e4e5b).

另请参阅我们的 [Gemma 3n 指南](/docs/zh/mo-xing/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune.md).
{% endhint %}

<a href="#gmail-running-gemma-3-on-your-phone" class="button primary">运行教程</a><a href="#fine-tuning-gemma-3-in-unsloth" class="button secondary">微调教程</a>

**Unsloth 是唯一一个在 float16 机器上可用于 Gemma 3 推理和训练的框架。** 这意味着使用免费 Tesla T4 GPU 的 Colab 笔记本也可以用！

* 使用我们的工具对带视觉支持的 Gemma 3（4B）进行微调 [免费 Colab 笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\)-Vision.ipynb)

{% hint style="info" %}
根据 Gemma 团队的说法，推理的最佳配置是\
`temperature = 1.0, top_k = 64, top_p = 0.95, min_p = 0.0`
{% endhint %}

**带有最佳配置的 Unsloth Gemma 3 上传：**

| GGUF                                                                                                                                                                                                                                                                                                                                                                                                                 | Unsloth 动态 4 位 Instruct                                                                                                                                                                                                                                                                                                                                                                                                                                  | 16 位 Instruct                                                                                                                                                                                                                                                                                                                                                                   |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <ul><li><a href="https://huggingface.co/unsloth/gemma-3-270m-it-GGUF">270M</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-1b-it-GGUF">1B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-GGUF">4B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b-it-GGUF">12B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-GGUF">27B-it</a></li></ul> | <ul><li><a href="https://huggingface.co/unsloth/gemma-3-270m-it-unsloth-bnb-4bit">270M</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-1b-it-bnb-4bit">1B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-bnb-4bit">4B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b-it-unsloth-bnb-4bit">12B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-bnb-4bit">27B-it</a></li></ul> | <ul><li><a href="https://huggingface.co/unsloth/gemma-3-270m-it">270M</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-1b">1B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b">4B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b">12B-it</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b">27B-it</a></li></ul> |

## :gear: 推荐的推理设置

根据 Gemma 团队的说法，官方推荐的推理设置是：

* 温度 1.0
* Top\_K 为 64
* Min\_P 为 0.00（可选，但 0.01 也效果不错，llama.cpp 默认是 0.1）
* Top\_P 为 0.95
* 重复惩罚为 1.0。（在 llama.cpp 和 transformers 中，1.0 表示禁用）
* 聊天模板：

  <pre data-overflow="wrap"><code><strong>&#x3C;bos>&#x3C;start_of_turn>user\n你好！&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\n嘿，你好！&#x3C;end_of_turn>\n&#x3C;start_of_turn>user\n1+1 等于多少？&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\n
  </strong></code></pre>
* 带有 `\n`换行渲染的聊天模板（最后一个除外）

{% code overflow="wrap" %}

```
<bos><start_of_turn>user
你好！<end_of_turn>
<start_of_turn>model
嘿，你好！<end_of_turn>
<start_of_turn>user
1+1 等于多少？<end_of_turn>
<start_of_turn>model\n
```

{% endcode %}

{% hint style="danger" %}
llama.cpp 和其他推理引擎会自动添加一个 \<bos> - 不要添加两个 \<bos> 令牌！在向模型提示时，你应该忽略 \<bos>！
{% endhint %}

### ✨在手机上运行 Gemma 3 <a href="#gmail-running-gemma-3-on-your-phone" id="gmail-running-gemma-3-on-your-phone"></a>

要在手机上运行这些模型，我们建议使用任何可在手机等边缘设备上本地运行 GGUF 的移动应用。微调后，你可以将其导出为 GGUF，然后在手机上本地运行。请确保你的手机有足够的内存/算力来处理这些模型，因为它可能会过热，所以我们建议在此用例中使用 Gemma 3 270M 或 Gemma 3n 模型。你可以尝试 [开源项目 AnythingLLM 的](https://github.com/Mintplex-Labs/anything-llm) 移动应用，你可以在 [这里下载 Android 版](https://play.google.com/store/apps/details?id=com.anythingllm) 或 [ChatterUI](https://github.com/Vali-98/ChatterUI)，这些都是在手机上运行 GGUF 的优秀应用。

{% hint style="success" %}
记住，对于所有教程，你可以将模型名称 'gemma-3-27b-it-GGUF' 更改为任何 Gemma 模型，例如 'gemma-3-270m-it-GGUF:Q8\_K\_XL'。
{% endhint %}

## :llama: 教程：如何在 Ollama 中运行 Gemma 3

1. 安装 `ollama` 如果你还没有的话！

```bash
apt-get update
apt-get install pciutils -y
curl -fsSL https://ollama.com/install.sh | sh
```

2. 运行模型！注意如果失败，你可以在另一个终端中调用 `ollama serve`！我们已在 Hugging Face 上传中包含所有修复和建议参数（如 temperature 等）在 `params` 在我们的 Hugging Face 上传中！你可以将模型名称 'gemma-3-27b-it-GGUF' 更改为任何 Gemma 模型，例如 'gemma-3-270m-it-GGUF:Q8\_K\_XL'。

```bash
ollama run hf.co/unsloth/gemma-3-27b-it-GGUF:Q4_K_XL
```

## 📖 教程：如何在 llama.cpp 中运行 Gemma 3 27B

1. 获取最新的 `llama.cpp` 在 [这里的 GitHub 上](https://github.com/ggml-org/llama.cpp)。你也可以按照下面的构建说明进行操作。将 `-DGGML_CUDA=ON` 改为 `-DGGML_CUDA=OFF` 如果你没有 GPU，或者只想进行 CPU 推理。 **对于 Apple Mac / Metal 设备**，设置 `-DGGML_CUDA=OFF` 然后照常继续——Metal 支持默认开启。

```bash
apt-get update
apt-get install pciutils build-essential cmake curl libcurl4-openssl-dev -y
git clone https://github.com/ggml-org/llama.cpp
cmake llama.cpp -B llama.cpp/build \
    -DBUILD_SHARED_LIBS=ON -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-quantize llama-cli llama-gguf-split llama-mtmd-cli
cp llama.cpp/build/bin/llama-* llama.cpp
```

2. 如果你想要使用 `llama.cpp` 直接加载模型时，你可以使用下面的命令：(:Q4\_K\_XL) 是量化类型。你也可以通过 Hugging Face 下载（第 3 点）。这与 `ollama run`

```bash
./llama.cpp/llama-mtmd-cli \
    -hf unsloth/gemma-3-4b-it-GGUF:Q4_K_XL
```

3. **或者** 下载模型通过（在安装 `pip install huggingface_hub hf_transfer` 之后）。你可以选择 Q4\_K\_M，或其他量化版本（如 BF16 全精度）。更多版本见： <https://huggingface.co/unsloth/gemma-3-27b-it-GGUF>

```python
# !pip install huggingface_hub hf_transfer
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/gemma-3-27b-it-GGUF",
    local_dir = "unsloth/gemma-3-27b-it-GGUF",
    allow_patterns = ["*Q4_K_XL*", "mmproj-BF16.gguf"], # 用于 Q4_K_M
)
```

4. 运行 Unsloth 的 Flappy Bird 测试
5. 编辑 `--threads 32` 来设置 CPU 线程数， `--ctx-size 16384` 用于上下文长度（Gemma 3 支持 128K 上下文长度！）， `--n-gpu-layers 99` 来设置 GPU 卸载层数。如果你的 GPU 显存不足，可以尝试调整它。如果你只进行 CPU 推理，也请移除它。
6. 对于对话模式：

```bash
./llama.cpp/llama-mtmd-cli \
    --model unsloth/gemma-3-27b-it-GGUF/gemma-3-27b-it-Q4_K_XL.gguf \\
    --mmproj unsloth/gemma-3-27b-it-GGUF/mmproj-BF16.gguf \\
    --ctx-size 16384 \
    --n-gpu-layers 99 \
    --seed 3407 \
    --prio 2 \\
    --temp 1.0 \\
    --repeat-penalty 1.0 \\
    --min-p 0.01 \
    --top-k 64 \\
    --top-p 0.95
```

7. 对于非对话模式来测试 Flappy Bird：

```bash
./llama.cpp/llama-cli \
    --model unsloth/gemma-3-27b-it-GGUF/gemma-3-27b-it-Q4_K_XL.gguf \\
    --ctx-size 16384 \
    --n-gpu-layers 99 \
    --seed 3407 \
    --prio 2 \\
    --temp 1.0 \\
    --repeat-penalty 1.0 \\
    --min-p 0.01 \
    --top-k 64 \\
    --top-p 0.95 \
    -no-cnv \\
    --prompt "<start_of_turn>user\n用 Python 创建一个 Flappy Bird 游戏。你必须包含这些内容：\n1. 你必须使用 pygame。\n2. 背景颜色应随机选择，并且是浅色。以浅蓝色开始。\n3. 多次按下 SPACE 会使小鸟加速。\n4. 小鸟的形状应随机选择为正方形、圆形或三角形。颜色应随机选择为深色。\n5. 在底部放一些随机选择为深棕色或黄色的土地。\n6. 在右上角显示分数。成功通过管道且没有撞上它们时加分。\n7. 制作间距随机且有足够空隙的管道。将它们随机设为深绿色、浅棕色或深灰色。\n8. 当你失败时，显示最高分。让文字显示在屏幕内。按 q 或 Esc 将退出游戏。重新开始则再次按 SPACE。\n最终游戏应位于 Python 的 markdown 区块中。在最终 markdown 区块之前检查你的代码是否有错误并修复它们。<end_of_turn>\n<start_of_turn>model\n"
```

来自我们的 <https://unsloth.ai/blog/deepseekr1-dynamic> 1.58bit 博客的完整输入是：

{% hint style="danger" %}
记得移除 \<bos>，因为 Gemma 3 会自动添加一个 \<bos>！
{% endhint %}

{% code overflow="wrap" %}

```
<start_of_turn>user
用 Python 创建一个 Flappy Bird 游戏。你必须包含这些内容：
1. 你必须使用 pygame。
2. 背景颜色应随机选择，并且是浅色。以浅蓝色开始。
3. 多次按下 SPACE 会使小鸟加速。
4. 小鸟的形状应随机选择为正方形、圆形或三角形。颜色应随机选择为深色。
5. 在底部放一些随机选择为深棕色或黄色的土地。
6. 在右上角显示分数。成功通过管道且没有撞上它们时加分。
7. 制作间距随机且有足够空隙的管道。将它们随机设为深绿色、浅棕色或深灰色。
8. 当你失败时，显示最高分。让文字显示在屏幕内。按 q 或 Esc 将退出游戏。重新开始则再次按 SPACE。
最终游戏应位于 Python 的 markdown 区块中。在最终 markdown 区块之前检查你的代码是否有错误
```

{% endcode %}

## :sloth: 在 Unsloth 中微调 Gemma 3

**Unsloth 是唯一一个在 float16 机器上可用于 Gemma 3 推理和训练的框架。** 这意味着使用免费 Tesla T4 GPU 的 Colab 笔记本也可以用！

* 试试我们的新 [Gemma 3（270M）笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(270M\).ipynb) 这使得 270M 参数模型在下棋方面非常聪明，并且可以预测下一步棋。
* 使用我们的笔记本对 Gemma 3（4B）进行微调，适用于： [**文本**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\).ipynb) 或 [**视觉**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3_\(4B\)-Vision.ipynb)
* 或者微调 [Gemma 3n（E4B）](/docs/zh/mo-xing/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune.md) 搭配 [文本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3N_\(4B\)-Conversational.ipynb) • [视觉](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3N_\(4B\)-Vision.ipynb) • [音频](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Gemma3N_\(4B\)-Audio.ipynb)

{% hint style="warning" %}
在尝试对 Gemma 3 进行完整微调（FFT）时，float16 设备上的所有层默认都会变为 float32。Unsloth 期望 float16，并会动态上转换。要修复此问题，请运行 `model.to(torch.float16)` 在加载之后，或者使用支持 bfloat16 的 GPU。
{% endhint %}

### Unsloth 微调修复

我们在 Unsloth 中的解决方案分三部分：

1. 将所有中间激活保持为 bfloat16 格式——也可以是 float32，但这会使用 2 倍更多的 VRAM 或内存（通过 Unsloth 的异步梯度检查点）
2. 使用张量核心以 float16 完成所有矩阵乘法，但在没有 Pytorch 混合精度 autocast 帮助的情况下，手动进行上转换/下转换。
3. 将所有不需要矩阵乘法的其他操作（如 layernorm）上转换为 float32。

## 🤔 Gemma 3 修复分析

<figure><img src="/files/533b606bdabdfcdab376f4f8aca58d858a072a70" alt="" width="563"><figcaption><p>Gemma 3 1B 到 27B 超过了 float16 的最大值 65504</p></figcaption></figure>

首先，在我们微调或运行 Gemma 3 之前，我们发现当使用 float16 混合精度时，梯度和 **激活会变成无穷大** 不幸的是。这会发生在 T4 GPU、RTX 20x 系列和 V100 GPU 上，因为它们只有 float16 张量核心。

对于更新的 GPU，如 RTX 30x 或更高版本、A100、H100 等，这些 GPU 有 bfloat16 张量核心，所以这个问题不会出现！ **但是为什么？**

<figure><img src="/files/25ac4df3e07b12a73b74df539aafa9a968b2eeae" alt="" width="375"><figcaption><p>维基百科 <a href="https://en.wikipedia.org/wiki/Bfloat16_floating-point_format">https://en.wikipedia.org/wiki/Bfloat16_floating-point_format</a></p></figcaption></figure>

Float16 只能表示最高到 **65504**，而 bfloat16 可以表示高达 **10^38**的巨大数值！但请注意，两种数值格式都只使用 16 位！这是因为 float16 分配了更多位，因此能更好地表示更小的小数，而 bfloat16 不能很好地表示分数。

但为什么用 float16？我们直接用 float32 不就行了吗！可惜 GPU 上的 float32 在矩阵乘法方面非常慢——有时慢 4 到 10 倍！所以我们不能这样做。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://unsloth.ai/docs/zh/mo-xing/tutorials/gemma-3-how-to-run-and-fine-tune.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
