> 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/grok-2.md).

# Grok 2

在本地运行 xAI 的 Grok 2 模型！

你现在可以运行 **Grok 2** （又名 Grok 2.5），由 xAI 提供的 2700 亿参数模型。全精度需要 **539GB**，而 Unsloth Dynamic 3 位版本将大小缩减至仅 **118GB** （减少 75%）。GGUF： [Grok-2-GGUF](https://huggingface.co/unsloth/grok-2-GGUF)

“ **3 位 Q3\_K\_XL** 模型可在单个 **128GB 内存的 Mac** 或 **24GB 显存 + 128GB 内存**，达到 **5+ tokens/s** 推理。感谢 llama.cpp 团队和社区 [对 Grok 2 的支持](https://github.com/ggml-org/llama.cpp/pull/15539) 并使这一切成为可能。我们也很高兴在过程中提供了一点帮助！

所有上传都使用 Unsloth [Dynamic 2.0](/docs/zh/ji-chu-zhi-shi/dynamic-3.0-ggufs.md) 在最先进的 5-shot MMLU 和 KL 散度性能方面表现出色，这意味着你可以以最小的准确率损失运行量化后的 Grok LLM。

<a href="#run-in-llama.cpp" class="button secondary">在 llama.cpp 中运行教程</a>

## :gear: 推荐设置

3 位动态量化占用 118GB（126GiB）磁盘空间——这在 128GB 内存统一内存的 Mac 上，或在一张 24GB 显存卡加 128GB 内存的机器上都能很好运行。建议至少拥有 120GB 内存来运行这个 3 位量化版本。

{% hint style="warning" %}
你必须使用 `--jinja` 用于 Grok 2。如果你不使用，可能会得到错误结果 `--jinja`
{% endhint %}

8 位量化版本大小约为 300GB，可放入一张 80GB GPU（MoE 层卸载到 RAM）。如果你还有额外的 200GB RAM，使用此配置预计可达到约 5 tokens/s。要了解如何提高生成速度并适配更长上下文， [请在此阅读](#improving-generation-speed).

{% hint style="info" %}
虽然不是必须的，但为了获得最佳性能，请让你的 VRAM + RAM 总和等于你下载的量化版本大小。否则，使用硬盘 / SSD 卸载在 llama.cpp 中也可以工作，只是推理会更慢。
{% endhint %}

### 采样参数

* Grok 2 的最大上下文长度为 128K，因此请使用 `131,072` 的上下文或更少。
* 使用 `--jinja` 适用于 llama.cpp 变体

目前没有官方的模型运行采样参数，因此你可以对大多数模型使用标准默认值：

* 将 <mark style="background-color:green;">**temperature = 1.0**</mark>
* <mark style="background-color:green;">**Min\_P = 0.01**</mark> （可选，但 0.01 效果很好，llama.cpp 默认值为 0.1）

## 运行 Grok 2 教程：

目前你只能在 llama.cpp 中运行 Grok 2。

### ✨ 在 llama.cpp 中运行

{% stepper %}
{% step %}
安装特定的 `llama.cpp` Grok 2 的 PR 于 [GitHub 上获取](https://github.com/ggml-org/llama.cpp/pull/15539)。你也可以按照下面的构建说明进行操作。将 `-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
cd llama.cpp && git fetch origin pull/15539/head:MASTER && git checkout MASTER && cd ..
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-quantize llama-cli llama-gguf-split llama-mtmd-cli llama-server
cp llama.cpp/build/bin/llama-* llama.cpp
```

{% endstep %}

{% step %}
如果你想使用 `llama.cpp` 直接加载模型，你可以使用下面的方法：（:Q3\_K\_XL）是量化类型。你也可以通过 Hugging Face 下载（第 3 点）。这类似于 `ollama run` 。使用 `export LLAMA_CACHE="folder"` 来强制 `llama.cpp` 保存到特定位置。请记住，该模型的最大上下文长度只有 128K。

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

如果你有更多一点 GPU 内存，可以尝试 `-ot ".ffn_(up|down)_exps.=CPU"` 这会卸载上投影和下投影 MoE 层。

尝试 `-ot ".ffn_(up)_exps.=CPU"` 如果你有更多 GPU 内存。这只会卸载上投影 MoE 层。

最后通过以下方式卸载所有层： `-ot ".ffn_.*_exps.=CPU"` 这会使用最少的 VRAM。

你也可以自定义正则表达式，例如 `-ot "\.(6|7|8|9|[0-9][0-9]|[0-9][0-9][0-9])\.ffn_(gate|up|down)_exps.=CPU"` 表示从第 6 层开始，只卸载 gate、up 和 down MoE 层。
{% endhint %}

```bash
export LLAMA_CACHE="unsloth/grok-2-GGUF"
./llama.cpp/llama-cli \\
    -hf unsloth/grok-2-GGUF:Q3_K_XL \
    --jinja \\
    --n-gpu-layers 99 \
    --temp 1.0 \\
    --top-p 0.95 \\
    --min-p 0.01 \
    --ctx-size 16384 \
    --seed 3407 \
    -ot ".ffn_.*_exps.=CPU"
```

{% endstep %}

{% step %}
通过以下方式下载模型（在安装 `pip install huggingface_hub hf_transfer` 之后）。你可以选择 `UD-Q3_K_XL` （动态 3 位量化）或其他量化版本，例如 `Q4_K_M` . 我们 <mark style="background-color:green;">**建议使用我们的 2.7 位动态量化**</mark><mark style="background-color:green;">**&#x20;**</mark><mark style="background-color:green;">**`UD-Q2_K_XL`**</mark><mark style="background-color:green;">**&#x20;**</mark><mark style="background-color:green;">**或更高版本，以平衡大小和准确率**</mark>.

```python
# !pip install huggingface_hub hf_transfer
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0" # 有时会触发速率限制，因此设为 0 以禁用
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/grok-2-GGUF",
    local_dir = "unsloth/grok-2-GGUF",
    allow_patterns = ["*UD-Q3_K_XL*"], # 动态 3 位
)
```

{% endstep %}

{% step %}
你可以修改 `--threads 32` CPU 线程数， `--ctx-size 16384` 用于上下文长度， `--n-gpu-layers 2` 用于 GPU 卸载的层数。如果你的 GPU 显存不足，请尝试调整它。如果你只使用 CPU 推理，也请将其移除。

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \\
    --model unsloth/grok-2-GGUF/UD-Q3_K_XL/grok-2-UD-Q3_K_XL-00001-of-00003.gguf \
    --jinja \\
    --threads -1 \\
    --n-gpu-layers 99 \
    --temp 1.0 \\
    --top-p 0.95 \\
    --min-p 0.01 \
    --ctx-size 16384 \
    --seed 3407 \
    -ot ".ffn_.*_exps.=CPU"
```

{% endcode %}
{% endstep %}
{% endstepper %}

## 模型上传

**我们所有的上传内容** - 包括那些不是基于 imatrix 或动态的版本，都使用了我们的校准数据集，该数据集专门针对对话、编码和语言任务进行了优化。

| MoE 位数 | 类型 + 链接                                                                             | 磁盘大小        | 详情            |
| ------ | ----------------------------------------------------------------------------------- | ----------- | ------------- |
| 1.66 位 | [TQ1\_0](https://huggingface.co/unsloth/grok-2-GGUF/blob/main/grok-2-UD-TQ1_0.gguf) | **81.8 GB** | 1.92/1.56 位   |
| 1.78 位 | [IQ1\_S](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-IQ1_S)             | **88.9 GB** | 2.06/1.56 位   |
| 1.93 位 | [IQ1\_M](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-IQ1_M)             | **94.5 GB** | 2.5/2.06/1.56 |
| 2.42 位 | [IQ2\_XXS](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-IQ2_XXS)         | **99.3 GB** | 2.5/2.06 位    |
| 2.71 位 | [Q2\_K\_XL](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-Q2_K_XL)        | **112 GB**  | 3.5/2.5 位     |
| 3.12 位 | [IQ3\_XXS](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-IQ3_XXS)         | **117 GB**  | 3.5/2.06 位    |
| 3.5 位  | [Q3\_K\_XL](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-Q3_K_XL)        | **126 GB**  | 4.5/3.5 位     |
| 4.5 位  | [Q4\_K\_XL](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-Q4_K_XL)        | **155 GB**  | 5.5/4.5 位     |
| 5.5 位  | [Q5\_K\_XL](https://huggingface.co/unsloth/grok-2-GGUF/tree/main/UD-Q5_K_XL)        | **191 GB**  | 6.5/5.5 位     |

## :snowboarder: 提升生成速度

如果你有更多 VRAM，可以尝试卸载更多 MoE 层，或者直接卸载整个层。

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

如果你有更多一点 GPU 内存，可以尝试 `-ot ".ffn_(up|down)_exps.=CPU"` 这会卸载上投影和下投影 MoE 层。

尝试 `-ot ".ffn_(up)_exps.=CPU"` 如果你有更多 GPU 内存。这只会卸载上投影 MoE 层。

你也可以自定义正则表达式，例如 `-ot "\.(6|7|8|9|[0-9][0-9]|[0-9][0-9][0-9])\.ffn_(gate|up|down)_exps.=CPU"` 表示从第 6 层开始，只卸载 gate、up 和 down MoE 层。

“ [最新的 llama.cpp 版本](https://github.com/ggml-org/llama.cpp/pull/14363) 还引入了高吞吐模式。使用 `llama-parallel`. 了解更多 [这里](https://github.com/ggml-org/llama.cpp/tree/master/examples/parallel). 你还可以 **将 KV 缓存量化为 4 位** 例如以减少 VRAM / RAM 数据传输，这也可以让生成过程更快。

## 📐如何容纳长上下文（完整 128K）

要容纳更长的上下文，你可以使用 **KV 缓存量化** 将 K 和 V 缓存量化为更低的位数。这也可以因为减少 RAM / VRAM 数据传输而提高生成速度。K 量化允许的选项（默认是 `f16`）包括以下内容。

`--cache-type-k f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1`

你应该使用 `_1` 这些变体以获得稍高的准确率，不过会稍慢一些。例如 `q4_1, q5_1`

你也可以量化 V 缓存，但你需要 **通过以下方式编译支持 Flash Attention 的 llama.cpp** 支持，方法是使用 `-DGGML_CUDA_FA_ALL_QUANTS=ON`，并使用 `--flash-attn` 来启用它。然后你可以将其与 `--cache-type-k` :

`--cache-type-v f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1`


---

# 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/grok-2.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.
