> 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/deepseek-v3.1-how-to-run-locally.md).

# DeepSeek-V3.1：如何在本地运行

DeepSeek 的 V3.1 和 **Terminus** 更新引入了混合推理推断，将“思考”和“不思考”合并到一个模型中。完整的 671B 参数模型需要 715GB 磁盘空间。量化后的动态 2-bit 版本使用 245GB（体积减少 75%）。GGUF： [**DeepSeek-V3.1-GGUF**](https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF)

{% hint style="success" %}
**新：** DeepSeek-V3.1-Terminus 现已发布： [DeepSeek-V3.1-Terminus-GGUF](https://huggingface.co/unsloth/DeepSeek-V3.1-Terminus-GGUF)\
\
[**2025 年 9 月 10 日更新：**](/docs/zh/ji-chu/unsloth-dynamic-2.0-ggufs/unsloth-dynamic-ggufs-on-aider-polyglot.md) 你们要求更难的基准测试，所以我们展示 Aider Polyglot 结果！我们的 Dynamic 3-bit DeepSeek V3.1 GGUF 得分 **75.6%**，超过了许多全精度的 SOTA LLM。 [阅读更多。](/docs/zh/ji-chu/unsloth-dynamic-2.0-ggufs/unsloth-dynamic-ggufs-on-aider-polyglot.md)

我们的 DeepSeek-V3.1 GGUF 包含 Unsloth [聊天模板修复](#chat-template-bug-fixes) 适用于 llama.cpp 支持的后端。
{% endhint %}

所有上传都使用 Unsloth [Dynamic 2.0](/docs/zh/ji-chu/unsloth-dynamic-2.0-ggufs.md) 以获得 SOTA 的 5-shot MMLU 和 KL 散度表现，这意味着你可以以极小的准确率损失运行并微调量化后的 DeepSeek LLM。

**教程导航：**

<a href="#run-in-llama.cpp" class="button secondary">在 llama.cpp 中运行</a><a href="#run-in-ollama-open-webui" class="button secondary">在 Ollama/Open WebUI 中运行</a>

## :gear: 推荐设置

1-bit 动态量化 TQ1\_0（对不重要的 MoE 层用 1bit，对重要的 MoE 用 2-4bit，其余用 6-8bit）占用 170GB 磁盘空间——这在 **1x24GB 显卡和 128GB 内存** 配合 MoE 卸载时效果很好——它也 **可在 Ollama 中原生运行**!

{% hint style="info" %}
你必须使用 `--jinja` 用于 llama.cpp 量化版本——这会使用我们的 [修复后的聊天模板](#chat-template-bug-fixes) 并启用正确的模板！如果你不使用，可能会得到错误结果 `--jinja`
{% endhint %}

2-bit 量化版可以放入 1 块 24GB GPU（并将 MoE 层卸载到内存）。如果你还额外有 128GB 内存，使用此配置时预计大约 5 token/s。建议至少拥有 226GB 内存来运行这个 2-bit 版本。为了获得最佳性能，你至少需要 226GB 统一内存，或 226GB 的 RAM+VRAM 总和，才能达到 5+ token/s。要了解如何提高生成速度并适配更长上下文， [请看这里](#improving-generation-speed).

{% hint style="success" %}
虽然不是必须的，但为了获得最佳性能，建议你的 VRAM + RAM 总和至少等于你下载的量化版本大小。如果不满足，硬盘/SSD 卸载在 llama.cpp 中也可以工作，只是推理会更慢。
{% endhint %}

## :butterfly:聊天模板错误修复

我们修复了 DeepSeek V3.1 聊天模板的一些问题，因为它们在 llama.cpp 和其他引擎中无法正常工作：

1. DeepSeek V3.1 是一个混合推理模型，这意味着你可以修改聊天模板来启用推理。引入的聊天模板 `thinking = True` ，但其他模型使用 `enable_thinking = True` 。我们增加了使用 `enable_thinking` 作为关键字的选项。
2. llama.cpp 的 jinja 渲染器通过 [minja](https://github.com/google/minja) 不允许在 `.split()` 命令中使用额外参数，因此使用 `.split(text, 1)` 在 Python 中可行，但在 minja 中不行。我们不得不修改这一点，以使 llama.cpp 能够正常工作而不报错。\
   \
   使用其他量化版本时，你会遇到以下错误：\
   `在抛出 'std::runtime_error' 实例后调用终止 what(): split 方法必须有 1 到 1 个位置参数，以及 0 到 0 个关键字参数，位于第 3 行，第 1908 列` 我们已经在所有量化版本中修复了它！

### 🐳 官方推荐设置

根据 [DeepSeek](https://huggingface.co/deepseek-ai/DeepSeek-V3.1)，以下是 V3.1 推理的推荐设置：

* 将 <mark style="background-color:green;">**temperature 设为 0.6**</mark> 以减少重复和不连贯。
* 将 <mark style="background-color:green;">**top\_p 设为 0.95**</mark> （推荐）
* **128K 上下文长度** 或更少
* 使用 `--jinja` 用于 llama.cpp 变体——我们也 **修复了一些聊天模板问题！**
* **使用** `enable_thinking = True` 以使用推理/思考模式。默认设置为非推理。

#### :1234: 聊天模板/提示格式

你不需要强制使用 `<think>\n` ，但你仍然可以添加它！在给定前缀下，DeepSeek V3.1 会以非思考模式生成对查询的响应。与 DeepSeek V3 不同，它引入了一个额外的 token `</think>`.

```
<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>
```

会强制添加 BOS，且 EOS 用于分隔每次交互。为了避免推理时出现双重 BOS token，你应只调用 `tokenizer.encode(..., add_special_tokens = False)` 因为聊天模板也会自动添加 BOS token。对于 llama.cpp / GGUF 推理，你应该跳过 BOS，因为它会自动添加。

#### :notebook\_with\_decorative\_cover: 非思考模式（使用 `thinking = False`或 `enable_thinking = False` 并且默认如此）

**首轮**

前缀： `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>`

使用给定前缀时，DeepSeek V3.1 会以非思考模式生成对查询的响应。与 DeepSeek V3 不同，它引入了一个额外的 token `</think>`.

**多轮**

上下文： `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>...<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>`

前缀： `<｜User｜>{query}<｜Assistant｜></think>`

通过将上下文与前缀拼接，我们得到了该查询的正确提示词。

#### :books: 思考模式（使用 `thinking = True`或 `enable_thinking = True` 并且默认如此）

**首轮**

前缀： `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜><think>`

思考模式的前缀与 DeepSeek-R1 类似。

**多轮**

上下文： `<｜begin▁of▁sentence｜>{system prompt}<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>...<｜User｜>{query}<｜Assistant｜></think>{response}<｜end▁of▁sentence｜>`

前缀： `<｜User｜>{query}<｜Assistant｜><think>`

多轮模板与非思考多轮聊天模板相同。这意味着最后一轮中的思考 token 会被丢弃，但 `</think>` 会在上下文的每一轮中保留。

#### :bow\_and\_arrow: 工具调用

非思考模式支持工具调用。格式如下：

`<｜begin▁of▁sentence｜>{system prompt}{tool_description}<｜User｜>{query}<｜Assistant｜></think>` 其中 tool\_description 填充在系统提示词之后的区域。

## :arrow\_forward:运行 DeepSeek-V3.1 教程：

### :llama: 在 Ollama/Open WebUI 中运行

{% stepper %}
{% step %}
安装 `ollama` 如果你还没有安装！要运行模型的更多变体， [看这里](#run-in-llama.cpp).

```bash
apt-get update
apt-get install pciutils -y
curl -fsSL https://ollama.com/install.sh | sh
```

{% endstep %}

{% step %}
运行模型！注意你也可以在另一个终端中调用 `ollama serve`如果它失败了！我们在 Hugging Face 上传中包含了所有修复和建议参数（temperature 等）在 `params` 中！\
\&#xNAN;**（新）在 Ollama 中运行 DeepSeek-V3.1 模型时，你可以使用我们的 TQ1\_0（170GB 量化版）：**

```bash
OLLAMA_MODELS=unsloth ollama serve &

OLLAMA_MODELS=unsloth ollama run hf.co/unsloth/DeepSeek-V3.1-Terminus-GGUF:TQ1_0
```

{% endstep %}

{% step %}
要运行其他量化版本，你需要先将 GGUF 分片文件合并成 1 个，如下面代码所示。然后你需要在本地运行模型。

```bash
./llama.cpp/llama-gguf-split --merge \
  DeepSeek-V3.1-Terminus-GGUF/DeepSeek-V3.1-Terminus-UD-Q2_K_XL/DeepSeek-V3.1-Terminus-UD-Q2_K_XL-00001-of-00006.gguf \
	merged_file.gguf
```

```bash
OLLAMA_MODELS=unsloth ollama serve &

OLLAMA_MODELS=unsloth ollama run merged_file.gguf
```

{% endstep %}

{% step %}
Open WebUI 还制作了一个 [分步教程](https://docs.openwebui.com/tutorials/integrations/deepseekr1-dynamic/) 讲解如何运行 R1，而对于 V3.1，你只需要把 R1 替换为新的 V3.1 量化版本。
{% endstep %}
{% endstepper %}

### ✨ 在 llama.cpp 中运行

{% stepper %}
{% step %}
获取最新的 `llama.cpp` 在 [这里的 GitHub 上](https://github.com/ggml-org/llama.cpp)。你也可以按照下面的构建说明进行操作。将 `-DGGML_CUDA=ON` 改为 `-DGGML_CUDA=OFF` 如果你没有 GPU，或者只想进行 CPU 推理。

```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-quantize llama-cli llama-gguf-split llama-mtmd-cli llama-server
cp llama.cpp/build/bin/llama-* llama.cpp
```

{% endstep %}

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

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

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

试试 `-ot ".ffn_(up)_exps.=CPU"` 如果你有更多 GPU 显存。这只会卸载 up 投影 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/DeepSeek-V3.1-GGUF"
./llama.cpp/llama-cli \
    -hf unsloth/DeepSeek-V3.1-Terminus-GGUF:UD-Q2_K_XL \
    --jinja \
    --n-gpu-layers 99 \
    --temp 0.6 \
    --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-`Q2\_K\_XL（动态 2bit 量化）或其他量化版本，例如 `Q4_K_M` 。我们 <mark style="background-color:green;">**建议使用我们的 2.7bit 动态量化**</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/DeepSeek-V3.1-Terminus-GGUF",
    local_dir = "unsloth/DeepSeek-V3.1-Terminus-GGUF",
    allow_patterns = ["*UD-Q2_K_XL*"], # 动态 2bit；动态 1bit 使用 "*UD-TQ1_0*"
)
```

{% 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/DeepSeek-V3.1-Terminus-GGUF/UD-Q2_K_XL/DeepSeek-V3.1-Terminus-UD-Q2_K_XL-00001-of-00006.gguf \
    --jinja \
    --n-gpu-layers 99 \
    --temp 0.6 \
    --top-p 0.95 \
    --min-p 0.01 \
    --ctx-size 16384 \
    --seed 3407 \
    -ot ".ffn_.*_exps.=CPU"
```

{% endcode %}
{% endstep %}

{% step %}
如果你没有足够的 RAM 和 VRAM 总和，请使用 1bit 版本（170GB）：

```python
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id = "unsloth/DeepSeek-V3.1-Terminus-GGUF",
    local_dir = "unsloth/DeepSeek-V3.1-Terminus-GGUF",
    allow_patterns = ["*UD-TQ1_0*"], # 动态 2bit 使用 "*UD-Q2_K_XL*"
)
```

{% endstep %}
{% endstepper %}

### ✨ 使用 llama-server 和 OpenAI 的 completion 库进行部署

要使用 llama-server 进行部署，请使用以下命令：

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-server \
    --model unsloth/DeepSeek-V3.1-Terminus-GGUF/DeepSeek-V3.1-Terminus-UD-TQ1_0.gguf \
    --alias "unsloth/DeepSeek-V3.1-Terminus" \
    --n-gpu-layers 999 \
    -ot ".ffn_.*_exps.=CPU" \
    --prio 3 \
    --min-p 0.01 \
    --ctx-size 16384 \
    --port 8001 \
    --jinja
```

{% endcode %}

然后使用 OpenAI 的 Python 库，先执行 `pip install openai` :

```python
from openai import OpenAI
import json
openai_client = OpenAI(
    base_url = "http://127.0.0.1:8001/v1",
    api_key = "sk-no-key-required",
)
completion = openai_client.chat.completions.create(
    model = "unsloth/DeepSeek-V3.1-Terminus",
    messages = [{"role": "user", "content": "2+2 等于多少？"},],
)
print(completion.choices[0].message.content)
```

## :minidisc:模型上传

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

* 下面是完整的 DeepSeek-V3.1 模型上传：

我们还上传了 [IQ4\_NL](https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/IQ4_NL) 和 [Q4\_1](https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/Q4_1) 量化版本，它们分别针对 ARM 和 Apple 设备运行得更快。

<table data-full-width="false"><thead><tr><th>MoE 比特数</th><th>类型 + 链接</th><th>磁盘大小</th><th>详情</th></tr></thead><tbody><tr><td>1.66bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF?show_file_info=DeepSeek-V3.1-UD-TQ1_0.gguf">TQ1_0</a></td><td><strong>170GB</strong></td><td>1.92/1.56bit</td></tr><tr><td>1.78bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ1_S">IQ1_S</a></td><td><strong>185GB</strong></td><td>2.06/1.56bit</td></tr><tr><td>1.93bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ1_M">IQ1_M</a></td><td><strong>200GB</strong></td><td>2.5/2.06/1.56</td></tr><tr><td>2.42bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ2_XXS">IQ2_XXS</a></td><td><strong>216GB</strong></td><td>2.5/2.06bit</td></tr><tr><td>2.71bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q2_K_XL">Q2_K_XL</a></td><td><strong>251GB</strong></td><td>3.5/2.5bit</td></tr><tr><td>3.12bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-IQ3_XXS">IQ3_XXS</a></td><td><strong>273GB</strong></td><td>3.5/2.06bit</td></tr><tr><td>3.5bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q3_K_XL">Q3_K_XL</a></td><td><strong>296GB</strong></td><td>4.5/3.5bit</td></tr><tr><td>4.5bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q4_K_XL">Q4_K_XL</a></td><td><strong>384GB</strong></td><td>5.5/4.5bit</td></tr><tr><td>5.5bit</td><td><a href="https://huggingface.co/unsloth/DeepSeek-V3.1-GGUF/tree/main/UD-Q5_K_XL">Q5_K_XL</a></td><td><strong>481GB</strong></td><td>6.5/5.5bit</td></tr></tbody></table>

我们也上传了以下格式的版本 [BF16 格式](https://huggingface.co/unsloth/DeepSeek-V3.1-BF16)，以及原始 [FP8（float8）格式](https://huggingface.co/unsloth/DeepSeek-V3.1).

## :snowboarder: 提升生成速度

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

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

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

试试 `-ot ".ffn_(up)_exps.=CPU"` 如果你有更多 GPU 显存。这只会卸载 up 投影 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 cache 量化为 4bit** ，例如减少 VRAM / RAM 之间的数据移动，这也能让生成过程更快。

## 📐 如何适配长上下文（完整 128K）

要适配更长上下文，你可以使用 **KV cache 量化** 将 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 cache，但你需要 **通过以下方式编译支持 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 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/deepseek-v3.1-how-to-run-locally.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.
