# Llama 4：如何运行和微调

Llama-4-Scout 模型有 1090 亿参数，而 Maverick 有 4020 亿参数。完整的未量化版本需要 113GB 磁盘空间，而 1.78-bit 版本只需 33.8GB（体积减少 75%）。 **Maverick** （402Bs）从 422GB 降到了仅 122GB（-70%）。

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

Scout 1.78-bit 可放入一块 24GB VRAM 的 GPU 中，实现约 20 tokens/秒的快速推理。Maverick 1.78-bit 可放入 2 块 48GB VRAM 的 GPU 中，实现约 40 tokens/秒的快速推理。

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

{% hint style="info" %}
我们所有的 GGUF 模型都使用校准数据进行量化（Scout 约 25 万个 token，Maverick 约 100 万个 token），这将比标准量化提高准确率。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-bit（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\n1+1 等于多少？<|eot|><|header_start|>assistant<|header_end|>\n\n
```

{% endcode %}

* BOS 令牌 `<|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，依此类推。

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

<figure><img src="/files/3ff3b9775c2a16e8288c64ad6fc677bf1f341fed" 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="/files/a2925bdaf916d08dfc76af61bb707a88acbf1ae6" alt=""><figcaption></figcaption></figure>

我们还必须转换 `torch.nn.Parameter` 改为 `torch.nn.Linear` 用于 MoE 层，以允许进行 4bit 量化。这也意味着我们必须重写并修补通用的 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> 用于 8bit。

<figure><img src="/files/8f38bd169f7626c7401ed259031d560879803b4f" alt="" width="375"><figcaption></figcaption></figure>

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


---

# 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/llama-4-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.
