# Gemma 4 - 如何本地运行

Gemma 4 是 Google DeepMind 的新一代开放模型家族，包括 **E2B**, **E4B**, **26B-A4B**、以及 **31B。** 这些多模态、混合思考模型支持 140 多种语言，最长可达 **256K 上下文**，并提供稠密和 MoE 变体。Gemma 4 采用 Apache-2.0 许可证，可在你的本地设备上运行。

{% columns %}
{% column %} <a href="#run-gemma-4-tutorials" class="button primary">运行 Gemma 4</a><a href="gemma-4/train" class="button secondary">微调 Gemma 4</a>

**Gemma-4-E2B** 和 **E4B** 支持图像和音频。运行所需仅 **5GB 内存** （4 位）或 15GB（完整 16 位）。查看我们的 [Gemma 4 GGUF](https://huggingface.co/collections/unsloth/gemma-4).

**Gemma-4-26B-A4B** 可运行于 **18GB** （4 位）或 28GB（8 位）。 **Gemma-4-31B** 需要 **20GB 内存** （4 位）或 34GB（8 位）。
{% 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&#x26;token=eec5f2f7-b97a-4c1c-ad01-5a041c3e4013" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% hint style="success" %}
**4 月 11 日更新：** Gemma 4 现已更新，采用了 Google 更新后的聊天模板 + llama.cpp 修复。\
**不要** 将 CUDA 13.2 运行时用于任何 GGUF，否则会导致输出质量很差。

你现在可以在 [Unsloth Studio](#unsloth-studio-guide)✨
{% endhint %}

### 使用指南

Gemma 4 在推理、编程、工具使用、长上下文和智能体工作流，以及多模态任务方面表现出色。较小的 E2B 和 E4B 变体专为手机和笔记本电脑设计，而更大的模型则面向中高 CPU/VRAM 系统，例如配备 NVIDIA RTX GPU 的电脑。

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

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

* **26B-A4B** - 在速度和准确性之间取得平衡。其 MoE 设计使它比 31B 更快，且仅有 4B 激活参数。如果 RAM 有限，并且你愿意用一点质量换速度，就选它。
* **31B** - 目前最强的 Gemma 4 模型。如果你有足够内存并且能接受稍慢的速度，就选择它以获得最高质量。

#### Gemma 4 基准测试

| Gemma 4     | MMLU Pro | AIME 2026（无工具） | LiveCodeBench v6 | MMMU Pro |
| ----------- | -------: | -------------: | ---------------: | -------: |
| **31B**     |    85.2% |          89.2% |            80.0% |    76.9% |
| **26B A4B** |    82.6% |          88.3% |            77.1% |    73.8% |
| **E4B**     |    69.4% |          42.5% |            52.0% |    52.6% |
| **E2B**     |    60.0% |          37.5% |            44.0% |    44.2% |

### 硬件要求

**表：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 |
| **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`

本地推理推荐的实用默认值：

* 先从 **32K 上下文** 开始以保证响应速度，然后再增加
* 保持 **重复/存在惩罚** 为禁用或 1.0，除非你看到循环输出。
* 句末标记是 `<turn|>`

{% hint style="info" %}
Gemma 4 的最大上下文长度是 **128K** 用于 **E2B / E4B** 和 **256K** 用于 **26B A4B / 31B**.
{% endhint %}

#### 思考模式

与旧版 Gemma 聊天模板相比，Gemma 4 使用标准的 **`系统`**, **`助手`**、以及 **`用户`** 角色，并增加了显式思考控制。

**如何启用思考：**

添加标记 **`<|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\n法国的首都是哪里？<turn|>\n<|turn>model\n
```

{% endcode %}

**然后它输出：**

{% code overflow="wrap" %}

```
<|channel>thought\n用户在询问法国的首都。\n法国的首都是巴黎。<channel|>法国的首都是巴黎。<turn|>
```

{% endcode %}

**多轮对话规则：**

对于多轮对话， **只在聊天历史中保留最终可见答案**。 **不要** 把先前的思考块重新喂回下一轮。

{% code overflow="wrap" %}

```
<bos><|turn>user\n1+1 等于多少？<turn|>\n<|turn>model\n2<turn|>\n<|turn>user\n1+1 等于多少？<turn|>\n<|turn>model\n2<turn|>\n<|turn>user\n1+1 等于多少？<turn|>\n<|turn>model\n2<turn|>\n<|turn>user\n1+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 位开始，而大模型建议使用 **动态 4 位**. [Gemma 4 GGUF](https://huggingface.co/collections/unsloth/gemma-4) 或 [MLX](#mlx-dynamic-quants):

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

<a href="#unsloth-studio-guide" class="button primary">🦥 Unsloth Studio 指南</a><a href="#llama.cpp-guide" class="button primary">🦙 Llama.cpp 指南</a>

{% columns %}
{% column %}
**你可以在我们的** [**Unsloth Studio**](https://unsloth.ai/docs/zh/xin-zeng/studio)✨ **笔记本：**
{% endcolumn %}

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

### 🦥 Unsloth Studio 指南

Gemma 4 现在可以在 [Unsloth Studio](https://unsloth.ai/docs/zh/xin-zeng/studio)中运行和微调，这是我们新的本地 AI 开源网页 UI。Unsloth Studio 让你可以在以下系统上本地运行模型： **MacOS、Windows**、Linux 和：

{% columns %}
{% column %}

* 搜索、下载、 [运行 GGUF](https://unsloth.ai/docs/zh/xin-zeng/studio#run-models-locally) 和 safetensor 模型
* [**自我修复** 工具调用](https://unsloth.ai/docs/zh/xin-zeng/studio#execute-code--heal-tool-calling) + **网页搜索**
* [**代码执行**](https://unsloth.ai/docs/zh/xin-zeng/studio#run-models-locally) （Python、Bash）
* [自动推理](https://unsloth.ai/docs/zh/xin-zeng/studio#model-arena) 参数调优（temp、top-p 等）
* 通过 llama.cpp 进行快速 CPU + GPU 推理
* [训练 LLM](https://unsloth.ai/docs/zh/xin-zeng/studio#no-code-training) 速度提升 2 倍，VRAM 减少 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%2FVrLgXwplAMcvkU4owjPk%2F26b%20gif.gif?alt=media&#x26;token=8a569952-c152-435f-b815-c9f295619587" alt=""><figcaption></figcaption></figure></div>
{% endcolumn %}
{% endcolumns %}

{% stepper %}
{% step %}

#### 安装 Unsloth

在终端中运行：

**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://localhost:8888` 在浏览器中。**
{% endstep %}

{% step %}

#### 搜索并下载 Gemma 4

首次启动时，你需要创建一个密码来保护账户，并在之后重新登录。随后你会看到一个简短的引导向导，用于选择模型、数据集和基本设置。你可以随时跳过。

然后进入 [Studio Chat](https://unsloth.ai/docs/zh/xin-zeng/studio/chat) 标签页，在搜索栏中搜索 Gemma 4，并下载你想要的模型和量化版本。

<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&#x26;token=18d5918e-4f71-4e0e-b8c9-464097389835" alt="" width="375"><figcaption></figcaption></figure></div>
{% endstep %}

{% step %}

#### 运行 Gemma 4

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

更多信息请查看我们的 [Unsloth Studio 推理指南](https://unsloth.ai/docs/zh/xin-zeng/studio/chat).

<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&#x26;token=8a569952-c152-435f-b815-c9f295619587" alt="" width="563"><figcaption></figcaption></figure></div>
{% endstep %}
{% endstepper %}

### 🦙 Llama.cpp 指南

在本指南中，我们将对 26B-A4B 和 31B 使用动态 4 位，对 E2B 和 E4B 使用 8 位。参见： [Gemma 4 GGUF 集合](https://huggingface.co/collections/unsloth/gemma-4)

对于这些教程，我们将使用 [llama.cpp](https://llama.cpphttps/github.com/ggml-org/llama.cpp) 进行快速本地推理，尤其是当你有 CPU 时。

{% stepper %}
{% step %}
获取最新的 `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=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 会自动使用所需的确切数量。

**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 hf_transfer` ）。你可以选择 `UD-Q4_K_XL` 或其他量化版本，例如 `Q8_0` 。如果下载卡住了，请查看： [hugging-face-hub-xet-debugging](https://unsloth.ai/docs/zh/ji-chu/troubleshooting-and-faqs/hugging-face-hub-xet-debugging "mention")

```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*" # 动态 2bit 使用 "*UD-Q2_K_XL*"
```

{% 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}'
```

{% 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 %}
{% endstep %}
{% endstepper %}

### MLX 动态量化

我们还上传了动态 4bit 和 8bit 量化版本，作为 MacOS 设备的首次试验！

{% hint style="success" %}
现已支持 **视觉** 支持！
{% 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 %}

## Gemma 4 最佳实践

### 提示示例

#### 简单推理提示

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

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

#### OCR / 文档提示

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

```
[图像优先]
从这张收据中提取所有文本。将明细、总计、商家和日期以 JSON 返回。
```

#### 多模态比较提示

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

#### 音频 ASR 提示

```
[音频优先]
将以下英文语音片段转写成英文文本。

请遵循以下关于答案格式化的具体说明：
* 只输出转写内容，不要换行。
* 转写数字时，请写阿拉伯数字，例如写 1.7 而不是 one point seven，写 3 而不是 three。
```

#### 音频翻译提示

```
[音频优先]
先转写以下西班牙语语音片段，然后将其翻译成英文。
格式化答案时，先输出西班牙语转写，然后换一行，再输出字符串 'English: '，最后输出英文翻译。
```

### 多模态设置

为了在多模态提示中获得最佳效果，请将多模态内容放在前面：

* 将 **图像和/或音频放在文本之前**.
* 对于视频，先传入一系列帧，然后再给出指令。

#### 可变图像分辨率

Gemma 4 支持多种视觉 token 预算：

* `70`
* `140`
* `280`
* `560`
* `1120`

这样使用：

* **70 / 140**：分类、图像描述、快速视频理解
* **280 / 560**：通用多模态聊天、图表、屏幕、UI 推理
* **1120**：OCR、文档解析、手写、小字体文本

#### 音频和视频限制

* **音频** 可用 **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} 翻译。
```

#### 资源与链接

* [Hugging Face Gemma 4 博客文章](https://huggingface.co/blog/gemma4)
* [NVIDIA Gemma 4 博客文章](https://blogs.nvidia.com/blog/rtx-ai-garage-open-models-google-gemma-4)
* [Google 官方 Gemma 4 博客](https://blog.google/innovation-and-ai/technology/developers-tools/gemma-4/)

<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&#x26;token=8bd8d0e0-ccb6-4ded-b99b-2c8a18370ae5" alt=""><figcaption></figcaption></figure></div>
