> 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/gemma-4.md). Agents can also search and read this documentation through its [MCP server](https://unsloth.ai/docs/~gitbook/mcp).

# Gemma 4 - 如何本地运行

在本地运行 Google 的新 Gemma 4 模型，包括 E2B、E4B、26B A4B 和 31B。

Gemma 4 是 Google DeepMind 推出的全新开放模型系列，包含 **12B**, **E2B**, **E4B**, **26B-A4B**和 **31B。** 这些多模态混合推理模型支持 140 多种语言，支持最高 **256K 上下文**，并提供稠密和 MoE 变体。Gemma 4 采用 Apache-2.0 许可证，可在本地设备上运行。

**Gemma-4-12B** 是新推出的模型，支持统一的文本、图像和音频功能。它可在 **8GB** 内存（4 位量化）或 14GB 内存（8 位量化）下运行。 **Gemma-4-E2B** 和 **E4B** 也支持图像和音频。通过 GGUF、MLX 或 NVFP4 量化版本运行时，需 **5GB 内存** （4 位量化）或 15GB 内存（完整 16 位）。

<a href="https://unsloth.ai/docs/zh/mo-xing/gemma-4.md#run-gemma-4-tutorials" class="button primary">运行 Gemma 4</a><a href="https://unsloth.ai/docs/zh/mo-xing/gemma-4/train.md" class="button secondary">微调 Gemma 4</a><a href="https://unsloth.ai/docs/zh/mo-xing/gemma-4/qat.md" class="button primary">Gemma 4 QAT</a><a href="https://unsloth.ai/docs/zh/mo-xing/mtp.md#gemma-4-mtp" class="button secondary">Gemma 4 MTP</a>

{% hint style="success" %}
**全新：** [**Gemma 4 MTP 现已推出**](https://unsloth.ai/docs/zh/mo-xing/mtp.md)**！MTP 可将推理速度提升 1.4 至 2.2 倍，且不会降低准确率。可直接在** [**Unsloth Studio**](https://unsloth.ai/docs/zh/mo-xing/mtp.md#unsloth-studio-mtp-guide)**.**
{% endhint %}

{% columns %}
{% column %}
**Gemma-4-26B-A4B** 可在 **18GB** 内存（4 位量化）或 28GB 内存（8 位量化）下运行。 **Gemma-4-31B** 需要 **20GB 内存** （4 位量化）或 34GB 内存（8 位量化）。

现在，你可以运行所有 GGUF 和 [MLX](#mlx-dynamic-quants) 模型，并在 [Unsloth Studio](#unsloth-studio-guide) 中微调 Gemma 4（见右侧）。

[**QAT** 变体](https://unsloth.ai/docs/zh/mo-xing/gemma-4/qat.md) 可在保持模型质量的同时，将 Gemma 4 的内存需求降低约 3 倍。
{% endcolumn %}

{% column %}

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FstfdTMsoBMmsbQsgQ1Ma%2Flandscape%20clip%20gemma.gif?alt=media&amp;token=eec5f2f7-b97a-4c1c-ad01-5a041c3e4013" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% hint style="success" %}
**6 月 9 日：** [Gemma 4 MTP](https://unsloth.ai/docs/zh/mo-xing/mtp.md) 现已推出。

**6 月 5 日：** [Gemma 4 QAT](https://unsloth.ai/docs/zh/mo-xing/gemma-4/qat.md) 正式发布。

**6月2日：** Gemma 4 12B Unified 已发布。

**4月20日：** 我们进行了 [Gemma 4 GGUF 基准测试](#unsloth-gguf-benchmarks) 帮助你挑选最合适的量化版本。
{% endhint %}

### 使用指南

Gemma 4 擅长推理、编程、工具使用、长上下文和智能体工作流，以及多模态任务。较小的 E2B 和 E4B 版本面向手机和笔记本电脑，而较大的模型则适用于中高端 CPU / VRAM 系统，例如搭载 NVIDIA RTX GPU 的 PC。

| Gemma 4 版本      | 详情                                       | 最适合                     |
| --------------- | ---------------------------------------- | ----------------------- |
| **E2B**         | <p>稠密 + PLE（128K 上下文）<br>支持：文本、图像、音频</p> | 适用于手机 / 边缘推理、ASR、语音翻译   |
| **E4B**         | <p>稠密 + PLE（128K 上下文）<br>支持：文本、图像、音频</p> | 适用于笔记本电脑和快速本地多模态应用的小型模型 |
| **12B Unified** | <p>稠密（256K 上下文）<br>支持：文本、图像、音频</p>       | 适用于笔记本电脑和本地多模态应用的中型模型   |
| **26B-A4B**     | <p>MoE（256K 上下文）<br>支持：文本、图像</p>         | 在计算机操作场景中，速度与质量的平衡最佳    |
| **31B**         | <p>稠密（256K 上下文）<br>支持：文本、图像</p>          | 性能最强，但推理速度较慢            |

**查看 Gemma 4：** [**性能基准测试**](#official-gemma-benchmarks) **和** [**GGUF 基准测试**](#unsloth-gguf-benchmarks)**.**

**我应该选择 26B-A4B 还是 31B？**

* **26B-A4B** — 兼顾速度与准确性。其 MoE 设计仅激活 4B 参数，因此比 31B 更快。如果内存有限，并且愿意牺牲一些质量来换取速度，就选它。
* **31B** — 目前性能最强的 Gemma 4 模型。如果内存充足，且能接受稍慢的速度，可选择它以获得最高质量。

### 硬件要求

**表：Gemma 4 推理 GGUF 建议硬件要求** （单位 = 总内存：RAM + VRAM，或统一内存）。你可以在 macOS、NVIDIA RTX GPU 等设备上使用 Gemma 4。

| Gemma 4 版本      |      4 位 |      8 位 | BF16 / FP16 |
| --------------- | -------: | -------: | ----------: |
| **E2B**         |     4 GB |   5–8 GB |       10 GB |
| **E4B**         | 5.5–6 GB |  9–12 GB |       16 GB |
| **12B Unified** |   7–8 GB | 13–14 GB |       25 GB |
| **26B A4B**     | 16–18 GB | 28–30 GB |       52 GB |
| **31B**         | 17–20 GB | 34–38 GB |       62 GB |

{% hint style="info" %}
一般来说，可用内存总量至少应大于你下载的量化模型的大小。如果内存不足，llama.cpp 仍可通过部分使用 RAM／磁盘卸载来运行，但生成速度会变慢。所需算力也会增加，具体取决于你使用的上下文窗口。
{% endhint %}

### 推荐设置

建议使用 Google 为 Gemma 4 设置的默认参数：

* `temperature = 1.0`
* `top_p = 0.95`
* `top_k = 64`

{% hint style="info" %}
Gemma 4 的最大上下文长度为 **128K** ，适用于 **E2B** / **E4B** 和 `262,144` ，适用于 **12B** / **26B A4B** / **31B**.
{% endhint %}

#### 思考模式

与旧版 Gemma 聊天模板相比，Gemma 4 使用标准的 **`system`**, **`assistant`**&#x548C; **`user`** 角色，并添加了显式的思考控制。

**启用思考的方法：**

在 **`<|think|>`** 系统提示词 **开头添加该标记**.

{% columns %}
{% column %}
**已启用思考**

```
<|think|>
你是一名谨慎的编程助手。请清晰地解释你的回答。
```

{% endcolumn %}

{% column %}
**已禁用思考**

```
你是一名谨慎的编程助手。请清晰地解释你的回答。
```

{% endcolumn %}
{% endcolumns %}

**输出行为：**

{% columns %}
{% column %}
启用思考后，模型会在最终答案之前输出其内部推理通道。

```
<|channel>thought
[内部推理]
<channel|>
[最终答案]
```

{% endcolumn %}

{% column %}
禁用思考时，较大的模型仍可能在最终答案之前输出一个 **空的思考区块** 。

```
<|channel>thought
<channel|>
[最终答案]
```

{% endcolumn %}
{% endcolumns %}

**例如，使用“**&#x6CD5;国的首都是哪里？”：

{% code overflow="wrap" %}

```
<bos><|turn>system\n<|think|><turn|>\n<|turn>user\nWhat is the capital of France?<turn|>\n<|turn>model\n
```

{% endcode %}

**然后它会输出：**

{% code overflow="wrap" %}

```
<|channel>thought\nThe user is asking for the capital of France.\nThe capital of France is Paris.<channel|>The capital of France is Paris.<turn|>
```

{% endcode %}

**多轮对话规则：**

对于多轮对话， **聊天记录中只保留最终可见的答案**。请勿 **不** 将之前的思考块传回下一轮。

{% code overflow="wrap" %}

```
<bos><|turn>user\nWhat is 1+1?<turn|>\n<|turn>model\n2<turn|>\n<|turn>user\nWhat is 1+1?<turn|>\n<|turn>model\n2<turn|>\n<|turn>user\nWhat is 1+1?<turn|>\n<|turn>model\n2<turn|>\n<|turn>user\nWhat is 1+1?<turn|>\n<|turn>model\n2<turn|>\n
```

{% endcode %}

**如何禁用思考：**

注意 `llama-cli` 可能无法可靠地运行，因此请使用 `llama-server` 来禁用推理：

{% hint style="warning" %}
若要 [禁用思考/推理](#how-to-enable-or-disable-reasoning-and-thinking)，请使用 `--chat-template-kwargs '{"enable_thinking":false}'`

如果您使用的是 **Windows** PowerShell，请使用： `--chat-template-kwargs "{\"enable_thinking\":false}"`

'true' 和 'false' 可以互换使用。
{% endhint %}

## 运行 Gemma 4 教程

由于 Gemma 4 GGUF 有多种尺寸，建议小型模型从 8 位量化开始，大型模型则从 [**动态**](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/dynamic-3.0-ggufs.md) **4 位**. [Gemma 4 GGUF](https://huggingface.co/collections/unsloth/gemma-4) 或 [MLX](#mlx-dynamic-quants) 或 [NVFP4](#nvfp4-guide):

| [E2B](https://huggingface.co/unsloth/gemma-4-E2B-it-GGUF) | [E4B](https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF) | [12b](https://huggingface.co/unsloth/gemma-4-12b-it-GGUF) | [26B-A4B](https://huggingface.co/unsloth/gemma-4-26B-A4B-it-GGUF) | [31B](https://huggingface.co/unsloth/gemma-4-31B-it-GGUF) |
| --------------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------- |

<a href="https://unsloth.ai/docs/zh/mo-xing/gemma-4.md#unsloth-studio-guide" class="button primary">🦥 Unsloth Desktop 指南</a><a href="https://unsloth.ai/pages/10f714f4a513e0d0a86b6f9d5945f9014729b035#llama.cpp-guide" class="button primary">🦙 Llama.cpp 指南</a><a href="https://unsloth.ai/docs/zh/mo-xing/gemma-4.md#nvfp4-guide" class="button primary">NVFP4 指南</a>

{% columns %}
{% column %}
**你可以通过我们的** [**Unsloth Studio**](https://unsloth.ai/docs/zh/xin/studio.md)✨ **笔记本免费运行和训练 Gemma 4：**
{% endcolumn %}

{% column %}
{% embed url="<https://colab.research.google.com/github/unslothai/unsloth/blob/main/studio/Unsloth_Studio_Colab.ipynb>" %}
{% endcolumn %}
{% endcolumns %}

### 🦥 Unsloth 指南

现在可以在 [Unsloth Desktop](https://unsloth.ai/docs/zh/xin/studio.md)中运行和微调 Gemma 4。这是我们全新的开源桌面 UI，可在本地运行 AI。Unsloth Studio 支持在以下系统本地运行模型： **MacOS、Windows**、Linux，以及：

{% columns %}
{% column %}

* 搜索、下载， [运行 GGUF](https://unsloth.ai/docs/zh/xin/studio.md#run-models-locally) 和 safetensors 模型
* [**自我修复** 工具调用](https://unsloth.ai/docs/zh/xin/studio.md#execute-code--heal-tool-calling) + **网页搜索**
* [**代码执行**](https://unsloth.ai/docs/zh/xin/studio.md#run-models-locally) （Python、Bash）
* [自动推理](https://unsloth.ai/docs/desktop#feature-deep-dive) 参数调优（temp、top-p 等）
* 通过 llama.cpp 实现快速 CPU + GPU 推理
* [训练 LLM](https://unsloth.ai/docs/zh/xin/studio.md#no-code-training) 速度提升 2 倍，显存占用减少 70%
  {% endcolumn %}

{% column %}

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FpAGvwjGD0iVMZKBoyu7m%2Fgreeennn.png?alt=media&amp;token=d17a5528-8375-444c-9aff-f9e9f7903bcd" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% stepper %}
{% step %}

#### 安装 Unsloth

最简单的入门方式是下载 [Unsloth Desktop 应用](https://unsloth.ai/docs/zh/desktop.md)。支持 [macOS](https://unsloth.ai/docs/zh/kuai-su-kai-shi/install/mac.md), [Windows](https://unsloth.ai/docs/zh/kuai-su-kai-shi/install/windows-installation.md)和 [Linux](https://unsloth.ai/docs/zh/kuai-su-kai-shi/install/linux.md).

<a href="https://unsloth.ai/download" class="button primary" data-icon="down-to-bracket">下载 Unsloth</a>

* <i class="fa-apple">:apple:</i> [下载 macOS 版](https://unsloth.ai/download/mac)
* <i class="fa-windows">:windows:</i> [下载 Windows 版](https://unsloth.ai/download/windows)
* <i class="fa-linux">:linux:</i> [下载 Linux 版](https://unsloth.ai/download/linux)

或者，如果你更喜欢手动安装：

**macOS、Linux、WSL：**

```bash
curl -fsSL https://unsloth.ai/install.sh | sh
```

**Windows PowerShell：**

```bash
irm https://unsloth.ai/install.ps1 | iex
```

{% endstep %}

{% step %}

#### 启动 Unsloth

**macOS、Linux、WSL 和 Windows：**

```bash
unsloth studio -H 0.0.0.0 -p 8888
```

然后在浏览器中打开 `http://127.0.0.1:8888` 或你的专属 URL。

**通过 HTTPS 和 Cloudflare 安全启动 Unsloth**

**新功能！** Unsloth 现在可通过免费的 Cloudflare 隧道，以安全的 HTTPS 方式启动。使用以下命令（适用于 Windows、Mac 和 Linux）：

```bash
unsloth studio --secure
```

{% endstep %}

{% step %}

#### 搜索并下载 Gemma 4

首次启动时，你需要创建密码来保护账户，然后重新登录。

然后前往 [Unsloth Chat](https://unsloth.ai/docs/zh/xin/studio/chat.md) 选项卡，在搜索栏中搜索 Gemma 4，然后下载所需的模型和量化版本。Unsloth 支持最新的 Gemma-4-12B Unified 模型。

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FpYoNILI8NFMl8QaQlc7V%2FScreenshot%202026-04-02%20at%2010.37.32%E2%80%AFPM.png?alt=media&amp;token=18d5918e-4f71-4e0e-b8c9-464097389835" alt="" width="375"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}

#### 运行 Gemma 4

使用 Unsloth Studio 时，推理参数应会自动设置，但你仍可以手动更改。你还可以编辑上下文长度、聊天模板及其他设置。你可以运行 GGUF 和 MLX 文件。

如需了解更多信息，请参阅我们的 [Unsloth Studio 推理指南](https://unsloth.ai/docs/zh/xin/studio/chat.md).

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FVrLgXwplAMcvkU4owjPk%2F26b%20gif.gif?alt=media&amp;token=8a569952-c152-435f-b815-c9f295619587" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}
{% endstepper %}

### 🦙 Llama.cpp 指南

本指南中，12B、26B-A4B 和 31B 模型将使用动态 4 位量化，E2B 和 E4B 则使用 8 位量化。另请参阅： [Gemma 4 GGUF 集合](https://huggingface.co/collections/unsloth/gemma-4)

这些教程将使用 [llama.cpp](llama.cpphttps://github.com/ggml-org/llama.cpp) 进行快速本地推理，尤其适合使用 CPU 的情况。

{% stepper %}
{% step %}
获取最新版本的 `llama.cpp` **，可在** [**此处的 GitHub**](https://github.com/ggml-org/llama.cpp)上获取。你也可以按照下面的说明进行构建。如果没有 GPU，或只想使用 CPU 推理，请将 `-DGGML_CUDA=ON` 改为 `-DGGML_CUDA=OFF` 。 **对于 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=OFF -DGGML_CUDA=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-cli llama-mtmd-cli llama-server llama-gguf-split
cp llama.cpp/build/bin/llama-* llama.cpp
```

{% endstep %}

{% step %}
如果你想直接使用 `llama.cpp` 加载模型，可以根据各个模型使用以下命令。 `UD-Q4_K_XL` 是量化类型。你也可以通过 Hugging Face 下载（步骤 3）。这与 `ollama run` 。使用 `export LLAMA_CACHE="folder"` 来强制 `llama.cpp` 保存到指定位置。无需设置上下文长度，因为 llama.cpp 会自动使用所需的精确长度。

{% hint style="warning" %}
要 [禁用思考/推理](#how-to-enable-or-disable-reasoning-and-thinking)，请使用： `--chat-template-kwargs '{"enable_thinking":false}'`

**Windows** Powershell： `--chat-template-kwargs "{\"enable_thinking\":false}"`

可交替使用 '`true`' 和 '`false`'。
{% endhint %}

**12B：**

```bash
export LLAMA_CACHE="unsloth/gemma-4-12B-it-GGUF"
./llama.cpp/llama-cli \
    -hf unsloth/gemma-4-12b-it-GGUF:UD-Q4_K_XL \
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64
```

**26B-A4B：**

```bash
export LLAMA_CACHE="unsloth/gemma-4-26B-A4B-it-GGUF"
./llama.cpp/llama-cli \
    -hf unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL \
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64
```

**31B：**

```bash
export LLAMA_CACHE="unsloth/gemma-4-31B-it-GGUF"
./llama.cpp/llama-cli \
    -hf unsloth/gemma-4-31B-it-GGUF:UD-Q4_K_XL \
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64
```

**E4B：**

```bash
export LLAMA_CACHE="unsloth/gemma-4-E4B-it-GGUF"
./llama.cpp/llama-cli \
    -hf unsloth/gemma-4-E4B-it-GGUF:Q8_0 \
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64
```

**E2B：**

```bash
export LLAMA_CACHE="unsloth/gemma-4-E2B-it-GGUF"
./llama.cpp/llama-cli \
    -hf unsloth/gemma-4-E2B-it-GGUF:Q8_0 \
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64
```

{% endstep %}

{% step %}
安装 `pip install huggingface_hub`后，也可以通过以下代码手动下载模型。你可以选择 `UD-Q4_K_XL` 或其他量化版本，例如 `Q8_0` 。如果下载卡住，请参阅： [Hugging Face Hub、XET 调试](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/troubleshooting-and-faqs/hugging-face-hub-xet-debugging.md)

```bash
hf download unsloth/gemma-4-26B-A4B-it-GGUF \
    --local-dir unsloth/gemma-4-26B-A4B-it-GGUF \
    --include "*mmproj-BF16*" \
    --include "*UD-Q4_K_XL*" # Use "*UD-Q2_K_XL*" for Dynamic 2bit
```

{% endstep %}

{% step %}
然后以对话模式运行模型（使用视觉功能时需搭配 `mmproj-F16`):

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \
    --model unsloth/gemma-4-26B-A4B-it-GGUF/gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf \
    --mmproj unsloth/gemma-4-26B-A4B-it-GGUF/mmproj-BF16.gguf \
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64
```

{% endcode %}
{% endstep %}

{% step %}

#### 部署 Llama-server

要在 llama-server 上部署 Gemma-4，请使用：

```bash
./llama.cpp/llama-server \
    --model unsloth/gemma-4-26B-A4B-it-GGUF/gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf \
    --mmproj unsloth/gemma-4-26B-A4B-it-GGUF/mmproj-BF16.gguf \
    --temp 1.0 \
    --top-p 0.95 \
    --top-k 64 \
    --alias "unsloth/gemma-4-26B-A4B-it-GGUF" \
    --port 8001 \
    --chat-template-kwargs '{"enable_thinking":true}'
```

{% endstep %}
{% endstepper %}

### MLX 动态量化

我们还上传了动态 4 位和 8 位量化版本，作为首次面向 MacOS 设备的试用！MLX 量化版本支持 **视觉功能。**

{% hint style="success" %}
所有 MLX 量化版本现在都可在[ Unsloth Studio](#unsloth-studio-guide)!
{% endhint %}

| Gemma 4 | 4 位 MLX                                                             | 8 位 MLX                                                          |
| ------- | ------------------------------------------------------------------- | ---------------------------------------------------------------- |
| 31B     | [链接](https://huggingface.co/unsloth/gemma-4-31b-it-UD-MLX-4bit)     | [链接](https://huggingface.co/unsloth/gemma-4-31b-it-MLX-8bit)     |
| 26B-A4B | [链接](https://huggingface.co/unsloth/gemma-4-26b-a4b-it-UD-MLX-4bit) | [链接](https://huggingface.co/unsloth/gemma-4-26b-a4b-it-MLX-8bit) |
| E4B     | [链接](https://huggingface.co/unsloth/gemma-4-E4B-it-UD-MLX-4bit)     | [链接](https://huggingface.co/unsloth/gemma-4-E4B-it-MLX-8bit)     |
| E2B     | [链接](https://huggingface.co/unsloth/gemma-4-E2B-it-UD-MLX-4bit)     | [链接](https://huggingface.co/unsloth/gemma-4-E2B-it-MLX-8bit)     |

试用方法：

{% code overflow="wrap" %}

```bash
curl -fsSL https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/scripts/install_gemma4_mlx.sh | sh
source ~/.unsloth/unsloth_gemma4_mlx/bin/activate
python -m mlx_vlm.chat --model unsloth/gemma-4-26b-a4b-it-UD-MLX-4bit
```

{% endcode %}

### **NVFP4 指南**

我们已上传 [Dynamic NVFP4](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/nvfp4.md) Gemma 4 量化版本，可在 NVIDIA Blackwell GPU 上实现更快的 4 位推理。以下是运行包括 Gemma 4 在内的模型所需的硬件配置，以及可获得的整体加速效果：

| Gemma 4 版本                                                         |  所需显存 | 比 BF16 快 |
| ------------------------------------------------------------------ | ----: | -------: |
| [E2B](https://huggingface.co/unsloth/gemma-4-E2B-it-NVFP4)         |  7 GB | 快 1.12 倍 |
| [E4B](https://huggingface.co/unsloth/gemma-4-E4B-it-NVFP4)         |  9 GB | 快 1.22 倍 |
| [12B Unified](https://huggingface.co/unsloth/gemma-4-12b-it-NVFP4) | 11 GB | 快 1.26 倍 |
| [26B A4B](https://huggingface.co/unsloth/gemma-4-26B-A4B-it-NVFP4) | 26 GB | 快 1.41 倍 |
| [31B](https://huggingface.co/unsloth/gemma-4-31B-it-NVFP4)         | 32 GB | 快 1.45 倍 |

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FZw91MhTauyOZGP5HT7bl%2Fimage.png?alt=media&amp;token=ae0051a9-af39-4ef7-8ed2-9f8c1fff33fc" alt="" width="563"><figcaption></figcaption></figure>

#### **vLLM 教程：**

要运行 NVFP4 量化版本，请参阅下方命令，在 [vLLM](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/inference-and-deployment/vllm-guide.md) 和 [SGLang](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/inference-and-deployment/sglang-guide.md) 中运行 Gemma-4-26B-A4B（也可以将模型名称改为 `gemma-4-31B-it-NVFP4` 等）。另外，切勿选择任何 MoE 后端——让 vLLM 自行选择即可。比如 Marlin 会慢 2.5 倍！请参阅 [#marlin-vs-flashinfer-vs-cutlass-vs-cute-dsl](#marlin-vs-flashinfer-vs-cutlass-vs-cute-dsl "mention")如果你使用的是 DGX Spark，请参阅 [#dgx-spark-serving](#dgx-spark-serving "mention") 必须使用 `--moe-backend flashinfer_b12x` 否则推理速度会慢得多。

要在单独的 venv 中安装 vLLM：

{% code overflow="wrap" expandable="true" %}

```bash
uv venv unsloth-nvfp4-env --python 3.13
source unsloth-nvfp4-env/bin/activate
uv pip install "vllm>=0.25.0" "flashinfer-python>=0.6.13" "nvidia-cutlass-dsl>=4.5.2" \
    --torch-backend=auto
```

{% endcode %}

接下来，启动 26B MoE 变体服务：

```shell
vllm serve unsloth/gemma-4-26B-A4B-it-NVFP4
```

将 `unsloth/gemma-4-26B-A4B-it-NVFP4` 替换为任意 [可用的 NVFP4](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/nvfp4.md#overview) 量化模型名称！

要启用 MTP / 投机解码（解码速度更快，但吞吐量会有所降低），请使用：

```bash
vllm serve unsloth/gemma-4-26B-A4B-it-NVFP4
    --speculative-config '{"method": "mtp", "num_speculative_tokens": 2}'
```

如果遇到 Torchcodec 问题，请先执行以下命令，然后重新启动 vLLM。

{% code overflow="wrap" expandable="true" %}

```bash
sudo apt-get update
sudo apt-get install -y ffmpeg
```

{% endcode %}

#### **使用 NVFP4 量化模型的 DGX Spark**

为确保 DGX Spark 使用了正确的内核（否则推理速度会 **慢 2 倍**），请先检查：

{% code overflow="wrap" expandable="true" %}

```bash
python -c "
import torch; from vllm.utils.flashinfer import has_flashinfer_b12x_gemm as g, has_flashinfer_b12x_moe as m
cap = torch.cuda.get_device_capability(); print('cap', cap, '| b12x gemm', g(), '| b12x moe', m()); assert cap[0] == 12 and g() and m(), 'b12x unavailable: serving would degrade to marlin W4A16'"
```

{% endcode %}

这条命令不应报错——如果报错，请更新 vLLM 或重新安装：

{% code overflow="wrap" expandable="true" %}

```bash
uv venv unsloth-nvfp4-env --python 3.13
source unsloth-nvfp4-env/bin/activate
uv pip install "vllm>=0.25.0" "flashinfer-python>=0.6.13" "nvidia-cutlass-dsl>=4.5.2" \
    --torch-backend=auto
```

{% endcode %}

然后，在 DGX Spark 上使用 vLLM 部署：

{% code overflow="wrap" expandable="true" %}

```shellscript
export CUTE_DSL_ARCH=sm_121a
vllm serve unsloth/gemma-4-26B-A4B-it-NVFP4 --moe-backend flashinfer_b12x
```

{% endcode %}

如果遇到 Torchcodec 问题，请先执行以下命令，然后重新启动 vLLM。

{% code overflow="wrap" expandable="true" %}

```bash
sudo apt-get update
sudo apt-get install -y ffmpeg
```

{% endcode %}

#### **SGLang 教程：**

```bash
python -m sglang.launch_server --model-path unsloth/gemma-4-31B-it-NVFP4 --speculative-algorithm NEXTN \
     --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4
```

### Ollama 指南

Ollama 现在已能很好地支持 Unsloth GGUF。使用 `curl -fsSL https://ollama.com/install.sh | sh` 在 Linux 上安装 Ollama，或 `irm https://ollama.com/install.ps1 | iex` 在 Windows 上安装。\
\
若要使用单个量化文件（小于 50GB），请运行：

{% code overflow="wrap" %}

```bash
ollama run hf.co/unsloth/gemma-4-26B-A4B-it-GGUF:UD-Q4_K_XL
```

{% endcode %}

对于较大的 BF16 分片等多个分片，请执行：

{% code overflow="wrap" %}

```bash
pip install -U huggingface_hub

# 分两次下载 mmproj 和 BF16
hf download unsloth/gemma-4-26B-A4B-it-GGUF --include "BF16/*" \
    --local-dir gemma4
hf download unsloth/gemma-4-26B-A4B-it-GGUF --include "mmproj-BF16.gguf" \
    --local-dir gemma4

mv gemma4/mmproj-BF16.gguf gemma4/BF16/
echo "FROM ./gemma4/BF16" > Modelfile

ollama create unsloth-gemma4 -f Modelfile
ollama run unsloth-gemma4
```

{% endcode %}

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FjflAyMZg9ZaSmeUL7LlQ%2Fimage.png?alt=media&amp;token=ddda55e7-0526-4fe0-99bc-d0cb4d05f7fa" alt="" width="563"><figcaption></figcaption></figure></div>

{% hint style="info" %}
如果看到 `Error: 500 Internal Server Error: unable to load model` 请通过以下命令更新 Ollama： `curl -fsSL https://ollama.com/install.sh | sh` 或者使用 PowerShell 安装命令。
{% endhint %}

## Gemma 4 最佳实践

### 提示词示例

#### 简单推理提示词

```
系统：
<|think|>
你是一名严谨的推理助手。

用户：
一列火车上午 8:15 发车，上午 11:47 到达。旅程持续了多长时间？
```

#### OCR／文档提示词

对于 OCR，请使用 **较高的视觉 token 预算** 例如 **560** 或 **1120**.

```
[先放图片]
提取这张收据中的所有文本。以 JSON 格式返回商品明细、总额、商家和日期。
```

#### 多模态对比提示词

```
[图片 1]
[图片 2]
比较这两张屏幕截图，并告诉我哪一张更可能让新用户感到困惑。
```

#### 音频 ASR 提示词

```
将以下 {LANGUAGE} 语音片段转写为 {LANGUAGE} 文本。

请遵循以下具体格式要求：
* 只输出转写内容，不要换行。
* 转写数字时请使用数字形式，例如写作 1.7 而不是 one point seven，写作 3 而不是 three。
```

#### 音频翻译提示词

```
转写以下 {SOURCE_LANGUAGE} 语音片段，然后将其翻译成 {TARGET_LANGUAGE}。格式要求：先输出 {SOURCE_LANGUAGE} 转写内容，接着换行，然后输出字符串 '{TARGET_LANGUAGE}: '，最后输出 {TARGET_LANGUAGE} 翻译内容。
```

### 多模态设置

要让多模态提示词取得最佳效果，请将多模态内容放在前面：

* 将 **图片和/或音频放在文本之前**.
* 对于视频，请先传入一系列帧，再提供指令。

#### 音频和视频限制

* **音频** 可用于 **12B**, **E2B** 和 **E4B** 仅限这些型号。
* 音频最长支持 **30 秒**.
* 视频最长支持 **60 秒** 假设以 **每秒 1 帧** 进行处理。

#### 音频提示模板

**ASR 提示**

```
将以下 {LANGUAGE} 语音片段转写为 {LANGUAGE} 文本。

请遵循以下具体格式要求：
* 只输出转写内容，不要换行。
* 转写数字时请使用数字形式，例如写作 1.7 而不是 one point seven，写作 3 而不是 three。
```

**语音翻译提示**

```
将以下语音片段转写为 {SOURCE_LANGUAGE}，然后翻译成 {TARGET_LANGUAGE}。
整理答案时，先输出 {SOURCE_LANGUAGE} 转写文本，然后换行，再输出字符串 '{TARGET_LANGUAGE}: '，最后输出 {TARGET_LANGUAGE} 翻译。
```

## 📊 基准测试

### Unsloth GGUF 基准测试

我们对不同提供商的 Gemma 4 GGUF 进行了平均 KL 散度基准测试，帮助你选择最佳量化版本（数值越低越好）。

* KL 散度显示，所有 Unsloth GGUF 均位于 SOTA 帕累托前沿
* KLD 显示量化模型与原始 BF16 输出分布的匹配程度，可用于判断保留的准确率。

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2F8y2cQ4VFqGEJLBS8PKZV%2Fgemma%20426b%20bench.lossless.webp?alt=media" alt=""><figcaption><p>26B A4B - KLD 基准测试（数值越低越好）</p></figcaption></figure></div>

### 官方 Gemma 基准测试

**文本/代码基准测试**

| 基准测试                | Gemma 4 31B | Gemma 4 26B A4B | Gemma 4 12B Unified | Gemma 4 E4B | Gemma 4 E2B | Gemma 3 27B（不启用思考） |
| ------------------- | ----------- | --------------- | ------------------- | ----------- | ----------- | ------------------ |
| MMLU Pro            | 85.2%       | 82.6%           | 77.2%               | 69.4%       | 60.0%       | 67.6%              |
| AIME 2026（不使用工具）    | 89.2%       | 88.3%           | 77.5%               | 42.5%       | 37.5%       | 20.8%              |
| LiveCodeBench v6    | 80.0%       | 77.1%           | 72.0%               | 52.0%       | 44.0%       | 29.1%              |
| Codeforces ELO      | 2150        | 1718            | 1659                | 940         | 633         | 110                |
| GPQA Diamond        | 84.3%       | 82.3%           | 78.8%               | 58.6%       | 43.4%       | 42.4%              |
| Tau2                | 76.9%       | 68.2%           | 69.0%               | 42.2%       | 24.5%       | 16.2%              |
| HLE（不使用工具）          | 19.5%       | 8.7%            | 5.2%                | -           | -           | -                  |
| HLE（使用搜索）           | 26.5%       | 17.2%           | -                   | -           | -           | -                  |
| BigBench Extra Hard | 74.4%       | 64.8%           | 53.0%               | 33.1%       | 21.9%       | 19.3%              |
| MMMLU               | 88.4%       | 86.3%           | 83.4%               | 76.6%       | 67.4%       | 70.7%              |

**视觉基准测试**

| MMMU Pro                 | 76.9% | 73.8% | 69.1% | 52.6% | 44.2% | 49.7% |
| ------------------------ | ----- | ----- | ----- | ----- | ----- | ----- |
| OmniDocBench 1.5（数值越低越好） | 0.131 | 0.149 | 0.164 | 0.181 | 0.290 | 0.365 |
| MATH-Vision              | 85.6% | 82.4% | 79.7% | 59.5% | 52.4% | 46.0% |
| MedXPertQA MM            | 61.3% | 58.1% | 48.7% | 28.7% | 23.5% | -     |

**音频基准测试**

| CoVoST                 | -     | -     | 38.5<sup>\*</sup>  | 35.54 | 33.47 | -     |
| ---------------------- | ----- | ----- | ------------------ | ----- | ----- | ----- |
| FLEURS（数值越低越好）         | -     | -     | 0.069<sup>\*</sup> | 0.08  | 0.09  | -     |
| **长上下文**               |       |       |                    |       |       |       |
| MRCR v2 8 个线索 128k（平均） | 66.4% | 44.1% | 43.4%              | 25.4% | 19.1% | 13.5% |

<div data-with-frame="true"><figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FfKaFMy7LHQYNKpfsf7Zy%2Fgemma%204%20banner.png?alt=media&amp;token=8bd8d0e0-ccb6-4ded-b99b-2c8a18370ae5" alt=""><figcaption></figcaption></figure></div>


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/zh/mo-xing/gemma-4.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
