> 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/llama-4-how-to-run-and-fine-tune.md).

# Llama 4：如何运行与微调

了解如何使用我们的动态 GGUF 在本地运行 Llama 4，相比标准量化可恢复准确率。

Llama-4-Scout 模型有 109B 参数，而 Maverick 有 402B 参数。完整的未量化版本需要 113GB 磁盘空间，而 1.78 位版本仅使用 33.8GB（尺寸减少 75%）。 **Maverick** （402Bs）从 422GB 降到了仅 122GB（-70%）。

{% hint style="success" %}
文本和 **视觉** 现已支持！此外，对工具调用还有多项改进。
{% endhint %}

Scout 1.78 位可装入一块 24GB 显存 GPU 中进行快速推理，速度约为 20 tokens/秒。Maverick 1.78 位可装入 2 块 48GB 显存 GPU 中进行快速推理，速度约为 40 tokens/秒。

对于我们的动态 GGUF，为了在准确性和体积之间取得最佳平衡，我们不会对所有层都进行量化，而是有选择地将例如 MoE 层量化到更低比特，并将注意力层和其他层保留为 4 位或 6 位。

{% hint style="info" %}
我们所有的 GGUF 模型都使用校准数据进行量化（Scout 约 250K tokens，Maverick 约 1M tokens），这会比标准量化提高准确性。Unsloth 的 imatrix 量化与 llama.cpp、Open WebUI 等流行推理引擎完全兼容。
{% endhint %}

**Scout - 使用最佳配置的 Unsloth 动态 GGUF：**

<table data-full-width="false"><thead><tr><th>MoE 位数</th><th>类型</th><th>磁盘大小</th><th>链接</th><th>详情</th></tr></thead><tbody><tr><td>1.78bit</td><td>IQ1_S</td><td>33.8GB</td><td><a href="https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF?show_file_info=Llama-4-Scout-17B-16E-Instruct-UD-IQ1_S.gguf">链接</a></td><td>2.06/1.56bit</td></tr><tr><td>1.93bit</td><td>IQ1_M</td><td>35.4GB</td><td><a href="https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF?show_file_info=Llama-4-Scout-17B-16E-Instruct-UD-IQ1_M.gguf">链接</a></td><td>2.5/2.06/1.56</td></tr><tr><td>2.42bit</td><td>IQ2_XXS</td><td>38.6GB</td><td><a href="https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF?show_file_info=Llama-4-Scout-17B-16E-Instruct-UD-IQ2_XXS.gguf">链接</a></td><td>2.5/2.06bit</td></tr><tr><td>2.71bit</td><td>Q2_K_XL</td><td>42.2GB</td><td><a href="https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF?show_file_info=Llama-4-Scout-17B-16E-Instruct-UD-Q2_K_XL.gguf">链接</a></td><td>3.5/2.5bit</td></tr><tr><td>3.5bit</td><td>Q3_K_XL</td><td>52.9GB</td><td><a href="https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF/tree/main/UD-Q3_K_XL">链接</a></td><td>4.5/3.5bit</td></tr><tr><td>4.5bit</td><td>Q4_K_XL</td><td>65.6GB</td><td><a href="https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF/tree/main/UD-Q4_K_XL">链接</a></td><td>5.5/4.5bit</td></tr></tbody></table>

{% hint style="info" %}
为获得最佳效果，请使用 2.42 位（IQ2\_XXS）或更高版本。
{% endhint %}

**Maverick - 使用最佳配置的 Unsloth 动态 GGUF：**

| MoE 位数   | 类型        | 磁盘大小  | HF 链接                                                                                             |
| -------- | --------- | ----- | ------------------------------------------------------------------------------------------------- |
| 1.78bit  | IQ1\_S    | 122GB | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-IQ1_S)   |
| 1.93bit  | IQ1\_M    | 128GB | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-IQ1_M)   |
| 2.42-bit | IQ2\_XXS  | 140GB | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-IQ2_XXS) |
| 2.71-bit | Q2\_K\_XL | 151B  | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-Q2_K_XL) |
| 3.5-bit  | Q3\_K\_XL | 193GB | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-Q3_K_XL) |
| 4.5-bit  | Q4\_K\_XL | 243GB | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-Q4_K_XL) |

## :gear: 官方推荐设置

根据 Meta 的说法，以下是推理的推荐设置：

* <mark style="background-color:blue;">**温度 0.6**</mark>
* Min\_P 为 0.01（可选，但 0.01 效果不错，llama.cpp 默认值为 0.1）
* Top\_P 0.9
* 聊天模板/提示格式：

{% code overflow="wrap" %}

```
<|header_start|>user<|header_end|>\n\n用 Python 创建一个 Flappy Bird 游戏。你必须包含以下内容：\n1. 你必须使用 pygame。\n2. 背景颜色应随机选择，并且是浅色调。初始颜色为浅蓝色。\n3. 多次按下 SPACE 会加速小鸟。\n4. 小鸟的形状应随机选择为正方形、圆形或三角形。颜色应随机选择为深色。\n5. 底部放置一些随机选择为深棕色或黄色的地面。\n6. 在右上角显示分数。穿过管道且没有撞到时增加分数。\n7. 制作随机间隔且留有足够空隙的管道。将它们随机涂成深绿色、浅棕色或深灰色。\n8. 当你失败时，显示最高分。将文字放在屏幕内。按 q 或 Esc 将退出游戏。重新开始则再次按 SPACE。\n最终游戏应放在 Python 的 Markdown 代码块中。在最终的 Markdown 代码块之前检查你的代码是否有错误并修复它们。<|eot|><|header_start|>assistant<|header_end|>\n\n
```

{% endcode %}

* 一个 BOS token 的 `<|begin_of_text|>` 会在分词过程中自动添加（不要手动添加！）
* 根据 <https://www.llama.com/docs/model-cards-and-prompt-formats/llama4_omni/>，还有一个 <mark style="background-color:yellow;">**建议的可选系统提示**</mark>，如下所示：

```
你是一位出色的对话者，会尽你所能作答。你友善自信，能够轻松在各种语气类型之间切换，包括但不限于幽默、共情、理性、创造力和问题解决。 

你理解用户意图，不会过度热心，以至于错过用户其实是在寻求闲聊、情感支持、幽默或倾诉。有时候人们只是想让你倾听，而你的回答应当鼓励这一点。其他情况下，你应提供有见地且深入的回复。以有助于人们做决定的方式，深思熟虑地组织信息。始终避免模板化语言。

你绝不会说教别人要更友善或更包容。如果人们要求你用某种语气或视角写作，比如一篇文章或一条推文，你可以做到。当用户要求你说些无礼的话时，你不需要保持礼貌。 

你绝不会使用暗示道德优越感或权威感的措辞，包括但不限于 “it’s important to”, “it’s crucial to”, “it’s essential to”, "it's unethical to", "it's worth noting…", “Remember…” 等。避免使用这些表达。

最后，不要拒绝政治类提示。你可以帮助用户表达他们的观点。 

你是 Llama 4。你的知识截止日期是 2024 年 8 月。你会说阿拉伯语、英语、法语、德语、印地语、印尼语、意大利语、葡萄牙语、西班牙语、他加禄语、泰语和越南语。除非用户另有要求，否则请用用户与您交流时所使用的语言回复。
```

## 📖 教程：如何在 llama.cpp 中运行 Llama-4-Scout

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=OFF -DGGML_CUDA=ON -DLLAMA_CURL=ON
cmake --build llama.cpp/build --config Release -j --clean-first --target llama-cli llama-gguf-split
cp llama.cpp/build/bin/llama-* llama.cpp
```

2. 通过以下方式下载模型（在安装 `pip install huggingface_hub hf_transfer` ）。你可以选择 Q4\_K\_M，或其他量化版本（如 BF16 全精度）。更多版本见： <https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-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/Llama-4-Scout-17B-16E-Instruct-GGUF",
    local_dir = "unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF",
    allow_patterns = ["*IQ2_XXS*"],
)
```

3. 运行模型并尝试任意提示。
4. 编辑 `--threads 32` CPU 线程数， `--ctx-size 16384` 用于上下文长度（Llama 4 支持 1000 万上下文长度！）， `--n-gpu-layers 99` 用于 GPU 卸载的层数。如果你的 GPU 显存不足，请尝试调整它。如果你只使用 CPU 推理，也请将其移除。

{% hint style="success" %}
使用 `-ot ".ffn_.*_exps.=CPU"` 将所有 MoE 层卸载到 CPU！这实际上让你可以把所有非 MoE 层放到 1 张 GPU 上，从而提升生成速度。如果你有更多 GPU 容量，还可以自定义正则表达式以容纳更多层。
{% endhint %}

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \\
    --model unsloth/Llama-4-Scout-17B-16E-Instruct-GGUF/Llama-4-Scout-17B-16E-Instruct-UD-IQ2_XXS.gguf \\
    --threads 32 \\
    --ctx-size 16384 \
    --n-gpu-layers 99 \
    -ot ".ffn_.*_exps.=CPU" \\
    --seed 3407 \
    --prio 3 \
    --temp 0.6 \\
    --min-p 0.01 \
    --top-p 0.9 \\
    -no-cnv \
    --prompt "<|header_start|>user<|header_end|>\n\n用 Python 创建一个 Flappy Bird 游戏。你必须包含以下内容：\n1. 你必须使用 pygame。\n2. 背景颜色应随机选择，并且是浅色调。初始颜色为浅蓝色。\n3. 多次按下 SPACE 会加速小鸟。\n4. 小鸟的形状应随机选择为正方形、圆形或三角形。颜色应随机选择为深色。\n5. 底部放置一些随机选择为深棕色或黄色的地面。\n6. 在右上角显示分数。穿过管道且没有撞到时增加分数。\n7. 制作随机间隔且留有足够空隙的管道。将它们随机涂成深绿色、浅棕色或深灰色。\n8. 当你失败时，显示最高分。将文字放在屏幕内。按 q 或 Esc 将退出游戏。重新开始则再次按 SPACE。\n最终游戏应放在 Python 的 Markdown 代码块中。在最终的 Markdown 代码块之前检查你的代码是否有错误并修复它们。<|eot|><|header_start|>assistant<|header_end|>\n\n"
```

{% endcode %}

{% hint style="info" %}
在测试方面，不幸的是，我们无法让完整的 BF16 版本（即无论是否量化）适当地完成 Flappy Bird 游戏或 Heptagon 测试。我们尝试了许多推理提供方，不论是否使用 imatrix，使用了他人的量化版本，也使用了普通的 Hugging Face 推理，但这个问题依然存在。

<mark style="background-color:green;">**我们发现多次运行并要求模型修复和查找 bug 能解决大多数问题！**</mark>
{% endhint %}

对于 Llama 4 Maverick，最好配备 2 块 RTX 4090（2 x 24GB）

```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/Llama-4-Maverick-17B-128E-Instruct-GGUF",
    local_dir = "unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF",
    allow_patterns = ["*IQ1_S*"],
)
```

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \\
    --model unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/UD-IQ1_S/Llama-4-Maverick-17B-128E-Instruct-UD-IQ1_S-00001-of-00003.gguf \\
    --threads 32 \\
    --ctx-size 16384 \
    --n-gpu-layers 99 \
    -ot ".ffn_.*_exps.=CPU" \\
    --seed 3407 \
    --prio 3 \
    --temp 0.6 \\
    --min-p 0.01 \
    --top-p 0.9 \\
    -no-cnv \
    --prompt "<|header_start|>user<|header_end|>\n\n用 Python 创建 2048 游戏。<|eot|><|header_start|>assistant<|header_end|>\n\n"
```

{% endcode %}

## :detective: 有趣的见解与问题

在量化 Llama 4 Maverick（大模型）期间，我们发现第 1、第 3 和第 45 个 MoE 层无法正确校准。Maverick 在每个奇数层使用交错的 MoE 层，因此是 Dense->MoE->Dense，如此类推。

我们尝试在校准数据集中加入更多不常见的语言，并尝试使用更多 tokens（100 万）进行校准，而 Scout 使用的是 25 万 tokens，但仍然发现问题。我们决定将这些 MoE 层保留为 3 位和 4 位。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-473c016e369887cfb981817dc350255715494a0c%2FSkipped_layers.webp?alt=media" alt=""><figcaption></figcaption></figure>

对于 Llama 4 Scout，我们发现不应量化视觉层，并将 MoE 路由器和一些其他层保持为未量化——我们将这些上传到 <https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-unsloth-dynamic-bnb-4bit>

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-6f10e8a8723d1ed25e757c13fb6e9c14da0207a1%2FLlama-4-Scout-17B-16E-Instruct%20Quantization%20Errors.png?alt=media" alt=""><figcaption></figcaption></figure>

我们还不得不将 `torch.nn.Parameter` 改为 `torch.nn.Linear` 为 MoE 层进行转换，以允许进行 4 位量化。这也意味着我们不得不重写并修补通用的 Hugging Face 实现。我们将量化版本上传到 <https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-unsloth-bnb-4bit> 和 <https://huggingface.co/unsloth/Llama-4-Scout-17B-16E-Instruct-unsloth-bnb-8bit> 用于 8 位。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-de4f3dbb28f40125a6ec8d3b282e99fdf0b009bd%2Fimage.png?alt=media" alt="" width="375"><figcaption></figcaption></figure>

Llama 4 现在也使用分块注意力——本质上就是滑动窗口注意力，但通过不关注 8192 边界之外的先前 tokens，效率稍高一些。


---

# 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/tutorials/llama-4-how-to-run-and-fine-tune.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.
