# Llama 4：如何运行与微调

Llama-4-Scout 模型有 1090 亿参数，而 Maverick 有 4020 亿参数。完整未量化版本需要 113GB 磁盘空间，而 1.78 比特版本使用 33.8GB（大小减少 75%）。 **Maverick** (4020 亿) 从 422GB 降到了仅 122GB（减少 70%）。

{% hint style="success" %}
同时支持 文本 和 **视觉（vision）** 现在已支持！并对工具调用进行了多重改进。
{% endhint %}

Scout 的 1.78 比特可装入 24GB VRAM 的 GPU，以约 20 令牌/秒 进行快速推理。Maverick 的 1.78 比特可装入 2x48GB VRAM 的 GPU，以约 40 令牌/秒 进行快速推理。

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

{% hint style="info" %}
我们所有的 GGUF 模型均使用校准数据进行量化（Scout 约 25 万令牌，Maverick 约 100 万令牌），这将比标准量化提高准确性。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 比特 | IQ2\_XXS  | 140GB | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-IQ2_XXS) |
| 2.71 比特 | Q2\_K\_XL | 151B  | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-Q2_K_XL) |
| 3.5 比特  | Q3\_K\_XL | 193GB | [链接](https://huggingface.co/unsloth/Llama-4-Maverick-17B-128E-Instruct-GGUF/tree/main/UD-Q3_K_XL) |
| 4.5 比特  | 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;">**温度（Temperature）为 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\nWhat is 1+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>，如下所列：

```
你是一位擅长对话的专家，会尽最大能力回应。你友善自信，能够随意在多种语气之间切换，包括但不限于幽默、同理心、学术性、创造性和问题解决。 

你理解用户意图，不会过度“热心”以至于忽略用户其实在寻求闲聊、情感支持、幽默或倾诉。有时候人们只想让你倾听，你的回答应鼓励这种倾诉。对于其他情况，你提供富有洞见和深入的回答。以有助于决策的方式有条理地组织信息。始终避免套话化语言。

你不会训斥他人要更友好或更具包容性。如果用户要求你以某种声音或视角写作，例如一篇文章或一条推文，你可以照做。当用户提示你说些粗鲁的话时，你不需要保持尊重。 

你绝不使用暗示道德优越或权威感的短语，包括但不限于“重要的是要……”、“关键是要……”、“有必要……”、“这是不道德的”、“值得注意的是……”、“记住……”等。应避免使用这些表达。

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

你是 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 层放在一块 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\nCreate a Flappy Bird game in Python. You must include these things:\n1. You must use pygame.\n2. The background color should be randomly chosen and is a light shade. Start with a light blue color.\n3. Pressing SPACE multiple times will accelerate the bird.\n4. The bird's shape should be randomly chosen as a square, circle or triangle. The color should be randomly chosen as a dark color.\n5. Place on the bottom some land colored as dark brown or yellow chosen randomly.\n6. Make a score shown on the top right side. Increment if you pass pipes and don't hit them.\n7. Make randomly spaced pipes with enough space. Color them randomly as dark green or light brown or a dark gray shade.\n8. When you lose, show the best score. Make the text inside the screen. Pressing q or Esc will quit the game. Restarting is pressing SPACE again.\nThe final game should be inside a markdown section in Python. Check your code for errors and fix them before the final markdown section.<|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\nCreate the 2048 game in Python.<|eot|><|header_start|>assistant<|header_end|>\n\n"
```

{% endcode %}

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

在对 Llama 4 Maverick（大型模型）进行量化时，我们发现第 1 层、第 3 层和第 45 层的 MoE 层无法正确校准。Maverick 对每个奇数层使用交错的 MoE 层，因此为 Dense->MoE->Dense 等交替结构。

我们尝试向校准数据集中加入更多不常见语言，并尝试使用更多令牌（100 万）相较于 Scout 的 25 万进行校准，但问题仍然存在。我们决定将这些 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 边界处不关注之前的令牌来稍微提高效率。


---

# 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.
