# Gemma 3 - 运行指南

Google 发布了 Gemma 3，新增 270M 模型，并保留之前的 1B、4B、12B 和 27B 尺寸。270M 和 1B 为仅文本模型，而更大型号支持文本和视觉。我们提供 GGUF，并提供如何有效运行它的指南，以及如何微调与执行 [强化学习](https://unsloth.ai/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide) 使用 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) 和 [用于运行的 GGUFs](https://huggingface.co/collections/unsloth/gemma-3-67d12b7e8816ec6efa7e4e5b).

另见我们的 [Gemma 3n 指南](https://unsloth.ai/docs/zh/mo-xing/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune).
{% 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 位 指令版                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <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</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-GGUF">4B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b-it-GGUF">12B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-GGUF">27B</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</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b-it-bnb-4bit">4B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-unsloth-bnb-4bit">12B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b-it-bnb-4bit">27B</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</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-4b">4B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-12b">12B</a></li><li><a href="https://huggingface.co/unsloth/gemma-3-27b">27B</a></li></ul> |

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

根据 Gemma 团队，官方推荐的推理设置为：

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

  <pre data-overflow="wrap"><code><strong>&#x3C;bos>&#x3C;start_of_turn>user\nHello!&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\nHey there!&#x3C;end_of_turn>\n&#x3C;start_of_turn>user\nWhat is 1+1?&#x3C;end_of_turn>\n&#x3C;start_of_turn>model\n
  </strong></code></pre>
* 带有以下内容的聊天模板 `\n`换行已渲染（最后一行除外）

{% code overflow="wrap" %}

```
<bos><start_of_turn>user
Hello!<end_of_turn>
<start_of_turn>model
Hey there!<end_of_turn>
<start_of_turn>user
What is 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\nCreate a Flappy Bird game in Python. You must include these things:\n1. You must use pygame.\n2. The background color should be randomly chosen and is a light shade. Start with a light blue color.\n3. Pressing SPACE multiple times will accelerate the bird.\n4. The bird's shape should be randomly chosen as a square, circle or triangle. The color should be randomly chosen as a dark color.\n5. Place on the bottom some land colored as dark brown or yellow chosen randomly.\n6. Make a score shown on the top right side. Increment if you pass pipes and don't hit them.\n7. Make randomly spaced pipes with enough space. Color them randomly as dark green or light brown or a dark gray shade.\n8. When you lose, show the best score. Make the text inside the screen. Pressing q or Esc will quit the game. Restarting is pressing SPACE again.\nThe final game should be inside a markdown section in Python. Check your code for errors and fix them before the final markdown section.<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）](https://unsloth.ai/docs/zh/mo-xing/tutorials/gemma-3-how-to-run-and-fine-tune/gemma-3n-how-to-run-and-fine-tune) 使用 [文本](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 倍以上的显存或内存（通过 Unsloth 的异步梯度检查点），
2. 使用张量核在 float16 中执行所有矩阵乘法，但手动进行上/下转换，而不是依赖 Pytorch 的混合精度 autocast，
3. 将所有不需要矩阵乘法的选项（如 layernorm）上采样为 float32，

## 🤔 Gemma 3 修复分析

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-6d6081cbb6f8b4b999c57803ac863c0ee9636ee1%2Foutput(1).png?alt=media" alt="" width="563"><figcaption><p>Gemma 3 的 1B 到 27B 超出了 float16 的最大值 65504</p></figcaption></figure>

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

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

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-e616649aa69253e34ea1d92b291dbda62d08044a%2Ffloat16%20bfloat16.png?alt=media" 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 无法很好地表示小数部分。

但为什么不用 float32？可惜在 GPU 上 float32 进行矩阵乘法非常慢 —— 有时慢 4 到 10 倍！所以我们不能这样做。
