# Gemma 3 - 如何运行指南

Google 发布了 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 笔记本也可以用！

* 使用我们的支持视觉的 [免费 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 Dynamic 4-bit 指令版                                                                                                                                                                                                                                                                                                                                                                                                                    | 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</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 团队的说法，官方推荐的推理设置是：

* Temperature 为 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，然后在手机上本地运行。请确保你的手机有足够的 RAM/性能来处理这些模型，因为它可能会过热，所以我们建议在这个用例中使用 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 区块中。检查你的代码是否有错误
```

{% 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 中的解决方案分为 3 部分：

1. 将所有中间激活保持为 bfloat16 格式——也可以是 float32，但这会使用 2 倍更多的 VRAM 或 RAM（通过 Unsloth 的异步梯度检查点）
2. 所有矩阵乘法都用 tensor cores 以 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 tensor cores。

对于更新的 GPU，例如 RTX 30x 或更高、A100、H100 等，这些 GPU 有 bfloat16 tensor cores，所以这个问题不会发生！ **但为什么呢？**

<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: 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:

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

The question should be specific, self-contained, and written in natural language.
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.
