# Qwen3-Coder：如何本地运行

Qwen3-Coder 是 Qwen 的新一代编码代理模型系列，提供 30B（**Qwen3-Coder-Flash**）和 480B 参数。 **Qwen3-480B-A35B-Instruct** 在编码性能上达到了与 Claude Sonnet-4、GPT-4.1 相媲美的最新水平，和 [Kimi K2](/docs/zh/mo-xing/tutorials/kimi-k2-thinking-how-to-run-locally.md)，在 Aider Polyglot 上得分 61.8%，并支持 256K（可扩展到 1M）的上下文长度。

我们还上传了具有原生 <mark style="background-color:purple;">**1M 上下文长度**</mark> 由 YaRN 扩展的 Qwen3-Coder 以及全精度的 8bit 和 16bit 版本。 [Unsloth](https://github.com/unslothai/unsloth) 现在也支持微调和 [强化学习](/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide.md) 的 Qwen3-Coder。

{% hint style="success" %}
[**更新：** 我们修复了 Qwen3-Coder 的工具调用！ ](#tool-calling-fixes)现在你可以在 llama.cpp、Ollama、LMStudio、Open WebUI、Jan 等中无缝使用工具调用。这个问题是普遍存在的，影响了所有上传（不仅仅是 Unsloth），我们已就修复与 Qwen 团队进行沟通！ [阅读更多](#tool-calling-fixes)
{% endhint %}

<a href="#run-qwen3-coder-30b-a3b-instruct" class="button primary">运行 30B-A3B</a><a href="#run-qwen3-coder-480b-a35b-instruct" class="button secondary">运行 480B-A35B</a>

{% hint style="success" %}
**是否** [**Unsloth 动态量化**](/docs/zh/ji-chu/unsloth-dynamic-2.0-ggufs.md) **有效？** 是的，而且效果很好。在第三方对 Aider Polyglot 基准的测试中， **UD-Q4\_K\_XL（276GB）** 动态量化近乎匹配了 **全 bf16（960GB）** Qwen3-coder 模型，成绩为 60.9% 对比 61.8%。 [更多细节见此处。](https://huggingface.co/unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF/discussions/8)
{% endhint %}

#### **Qwen3 Coder - Unsloth 动态 2.0 GGUFs**:

| Dynamic 2.0 GGUF（用于运行）                                                                                                                                                                                                        | 1M 上下文 Dynamic 2.0 GGUF                                                                                                                                                                                                             |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <ul><li><a href="https://huggingface.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF">30B-A3B-Instruct</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF">480B-A35B-Instruct</a></li></ul> | <ul><li><a href="https://huggingface.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-1M-GGUF">30B-A3B-Instruct</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-Coder-480B-A35B-Instruct-1M-GGUF">480B-A35B-Instruct</a></li></ul> |

## 🖥️ **运行 Qwen3-Coder**

下面是关于该 [**30B-A3B**](#run-qwen3-coder-30b-a3b-instruct) 和 [**480B-A35B**](#run-qwen3-coder-480b-a35b-instruct) 模型的变体。

### :gear: 推荐设置

Qwen 建议对两种模型使用以下推理设置：

`temperature=0.7`, `top_p=0.8`, `top_k=20`, `repetition_penalty=1.05`

* <mark style="background-color:green;">**温度 0.7**</mark>
* Top\_K 为 20
* Min\_P 为 0.00（可选，但 0.01 效果很好，llama.cpp 的默认值是 0.1）
* Top\_P 为 0.8
* <mark style="background-color:green;">**重复惩罚为 1.05**</mark>
* 聊天模板：

  ```
  <|im_start|>user
  嗨！<|im_end|>
  <|im_start|>assistant
  1+1 等于多少？<|im_end|>
  <|im_start|>user
  2<|im_end|>
  <|im_start|>assistant
  ```
* 推荐的上下文输出：65,536 令牌（可增加）。详情见此处。

**聊天模板/提示格式（换行未渲染）**

{% code overflow="wrap" %}

```
<|im_start|>user\nHey there!<|im_end|>\n<|im_start|>assistant\nWhat is 1+1?<|im_end|>\n<|im_start|>user\n2<|im_end|>\n<|im_start|>assistant\n
```

{% endcode %}

<mark style="background-color:yellow;">**用于工具调用的聊天模板**</mark> （获取旧金山当前温度）。有关如何格式化工具调用的更多细节见此处。

```
<|im_start|>user
现在旧金山的温度是多少？明天呢？<|im_end|>
<|im_start|>assistant
<tool_call>\n<function=get_current_temperature>\n<parameter=location>\nSan Francisco, CA, USA
</parameter>\n</function>\n</tool_call><|im_end|>
<|im_start|>user
<tool_response>
{"temperature": 26.1, "location": "San Francisco, CA, USA", "unit": "celsius"}
</tool_response>\n<|im_end|>
```

{% hint style="info" %}
提醒：该模型仅支持非“思考”模式，并且不会在输出中生成 `<think></think>` 块。与此同时，指定 `enable_thinking=False` 不再是必需的。
{% endhint %}

### 运行 Qwen3-Coder-30B-A3B-Instruct：

要让我们的动态 4 位量化实现 6+ 令牌/秒 的推理速度，至少需要 **18GB 的统一内存** （合并的 VRAM 和 RAM）或 **单独 18GB 的系统内存** 作为经验法则，你的可用内存应与所使用模型的大小相当或更大。例如，UD\_Q8\_K\_XL 量化（全精度）为 32.5GB，将至少需要 **33GB 的统一内存** （VRAM + RAM）或 **33GB 的内存** 以获得最佳性能。

**注意：** 模型可以在低于其总大小的内存下运行，但这会降低推理速度。只有在追求最快速度时才需要最大内存。

鉴于这是一个非思考模型，无需设置 `thinking=False` 并且模型不会生成 `<think> </think>` 块。

{% hint style="info" %}
请遵循 [**上述最佳实践**](#recommended-settings)。它们与 480B 模型相同。
{% endhint %}

#### 🦙 Ollama：运行 Qwen3-Coder-30B-A3B-Instruct 教程

1. 安装 `ollama` 如果你还没有这样做！你只能运行最大到 32B 的模型。

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

2. 运行模型！注意如果失败，您可以在另一个终端中调用 `ollama serve`我们在 Hugging Face 上传中包含了所有修复和建议参数（如 temperature 等），位于 `params` 中！

```bash
ollama run hf.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF:UD-Q4_K_XL
```

#### :sparkles: Llama.cpp：运行 Qwen3-Coder-30B-A3B-Instruct 教程

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. 您可以直接通过 HuggingFace 拉取：

   ```bash
   ./llama.cpp/llama-cli \
       -hf unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF:Q4_K_XL \
       --jinja -ngl 99 --ctx-size 32768 \
       --temp 0.7 --min-p 0.0 --top-p 0.80 --top-k 20 --repeat-penalty 1.05
   ```
3. 通过以下方式下载模型（在安装 `pip install huggingface_hub hf_transfer` ）你可以选择 UD\_Q4\_K\_XL 或其他量化版本。如果下载卡住，请参见 [Hugging Face Hub，XET 调试](/docs/zh/ji-chu/troubleshooting-and-faqs/hugging-face-hub-xet-debugging.md)

```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/Qwen3-Coder-30B-A3B-Instruct-GGUF",
    local_dir = "unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF",
    allow_patterns = ["*UD-Q4_K_XL*"],
)
```

### 运行 Qwen3-Coder-480B-A35B-Instruct：

要让我们的 1 位量化达到 6+ 令牌/秒 的推理速度，我们建议至少具备 **150GB 的统一内存** （合并的 VRAM 和 RAM）或 **单独 150GB 的系统内存** 作为经验法则，你的可用内存应与所使用模型的大小相当或更大。例如，Q2\_K\_XL 量化为 180GB，将至少需要 **180GB 的统一内存** （VRAM + RAM）或 **180GB 的内存** 以获得最佳性能。

**注意：** 模型可以在低于其总大小的内存下运行，但这会降低推理速度。只有在追求最快速度时才需要最大内存。

{% hint style="info" %}
请遵循 [**上述最佳实践**](#recommended-settings)。它们与 30B 模型相同。
{% endhint %}

#### 📖 Llama.cpp：运行 Qwen3-Coder-480B-A35B-Instruct 教程

对于 Coder-480B-A35B，我们将专门使用 Llama.cpp 以优化推理并提供大量选项。

{% hint style="success" %}
如果你想要一个 **全精度未量化版本**，请使用我们的 `Q8_K_XL、Q8_0` 或 `BF16` 版本！
{% endhint %}

1. 获取最新的 `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-cli llama-gguf-split
   cp llama.cpp/build/bin/llama-* llama.cpp
   ```
2. 你可以直接使用 llama.cpp 下载模型，但我通常建议使用 `huggingface_hub` 要直接使用 llama.cpp，请执行：

   ```bash
   ./llama.cpp/llama-cli \
       -hf unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF:Q2_K_XL \
       --ctx-size 16384 \
       --n-gpu-layers 99 \
       -ot ".ffn_.*_exps.=CPU" \
       --temp 0.7 \
       --min-p 0.0 \
       --top-p 0.8 \
       --top-k 20 \
       --repeat-penalty 1.05
   ```
3. 或者，安装后通过以下方式下载模型（ `pip install huggingface_hub hf_transfer` ）。你可以选择 UD-Q2\_K\_XL 或其他量化版本。

   ```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/Qwen3-Coder-480B-A35B-Instruct-GGUF",
       local_dir = "unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF",
       allow_patterns = ["*UD-Q2_K_XL*"],
   )
   ```
4. 以对话模式运行模型并尝试任意提示。
5. 编辑 `--threads -1` 用于设置 CPU 线程数， `--ctx-size` 262114 作为上下文长度， `--n-gpu-layers 99` 用于指定将多少层卸载到 GPU。若 GPU 出现内存不足，请尝试调整它。若仅使用 CPU 推理，请移除此项。

{% hint style="success" %}
使用 `-ot ".ffn_.*_exps.=CPU"` 将所有 MoE 层卸载到 CPU！这实际上允许你将所有非 MoE 层放到 1 张 GPU 上，从而提高生成速度。如果你有更多 GPU 容量，可以自定义正则表达式以适配更多层。更多选项讨论见 [这里](#improving-generation-speed).
{% endhint %}

{% code overflow="wrap" %}

```bash
./llama.cpp/llama-cli \
    --model unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF/UD-Q2_K_XL/Qwen3-Coder-480B-A35B-Instruct-UD-Q2_K_XL-00001-of-00004.gguf \
    --ctx-size 16384 \
    --n-gpu-layers 99 \
    -ot ".ffn_.*_exps.=CPU" \
    --temp 0.7 \
    --min-p 0.0 \
    --top-p 0.8 \
    --top-k 20 \
    --repeat-penalty 1.05
```

{% endcode %}

{% hint style="success" %}
还不要忘记新的 Qwen3 更新。运行 [**Qwen3-235B-A22B-Instruct-2507**](/docs/zh/mo-xing/tutorials/qwen3-next.md) 在本地使用 llama.cpp。
{% endhint %}

#### :tools: "content": \[{"type": "text", "text": "用 Python 创建一个 Fibonacci 函数并求 fib(20)。"}],

如果你有更多显存，可以尝试卸载更多 MoE 层，或将整个层本身卸载（offload）。

通常， `-ot ".ffn_.*_exps.=CPU"` 会将所有 MoE 层卸载到 CPU！这实际上允许你将所有非 MoE 层放在一块 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 bit** 将 KV 缓存量化为 4 位

#### :triangular\_ruler:如何适配长上下文（256K 到 1M）

要适配更长的上下文，你可以使用 <mark style="background-color:green;">**KV 缓存量化**</mark> 将 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 缓存进行量化，但你需要 <mark style="background-color:yellow;">**在编译 llama.cpp 时启用 Flash Attention 支持**</mark> 通过 `-DGGML_CUDA_FA_ALL_QUANTS=ON`，并使用 `--flash-attn` 以启用它。

我们还通过 YaRN 缩放上传了 1 百万上下文长度的 GGUF 文件 [这里](https://unsloth.ai/docs/).

## :toolbox: 工具调用修复

我们设法通过修复了工具调用，方法是 `llama.cpp --jinja` 专门用于通过 `llama-server`来提供服务！如果你正在下载我们的 30B-A3B 量化文件，不用担心，因为这些已经包含我们的修复。对于 480B-A35B 模型，请：

1. 在 <https://huggingface.co/unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF/tree/main/UD-Q2\\_K\\_XL> 下载 UD-Q2\_K\_XL 的第一个文件，并替换你当前的文件
2. 使用 `snapshot_download` 像 <https://docs.unsloth.ai/basics/qwen3-coder-how-to-run-locally#llama.cpp-run-qwen3-tutorial> 那样照常进行，这将自动覆盖旧文件
3. 通过使用新的聊天模板： `--chat-template-file`来使用。见 [GGUF 聊天模板](https://huggingface.co/unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF?chat_template=default) 或 [chat\_template.jinja](https://huggingface.co/unsloth/Qwen3-Coder-480B-A35B-Instruct/raw/main/chat_template.jinja)
4. 作为额外补充，我们还制作了一个 150GB 的单文件 UD-IQ1\_M（因此 Ollama 可用），地址为 <https://huggingface.co/unsloth/Qwen3-Coder-480B-A35B-Instruct-GGUF/blob/main/Qwen3-Coder-480B-A35B-Instruct-UD-IQ1\\_M.gguf>

这应该能解决类似问题： <https://github.com/ggml-org/llama.cpp/issues/14915>

### 使用工具调用

为工具调用格式化提示，我们用示例来展示。

我创建了一个名为 `get_current_temperature` 的 Python 函数，该函数应获取某地的当前温度。目前我们创建了一个占位函数，会始终返回 21.6 摄氏度。你应将其更改为真实函数！！

{% code overflow="wrap" %}

```python
def get_current_temperature(location: str, unit: str = "celsius"):
    """获取某地的当前温度。

    参数：
        location：要获取温度的地点，格式为 "City, State, Country"。
        unit：返回温度的单位。默认是 "celsius"。（选项：["celsius", "fahrenheit"]）

    返回：
        以字典形式返回温度、地点和单位
    """
    return {
        "temperature": 26.1, # 预配置 -> 你可以更改它！
        "location": location,
        "unit": unit,
    }
```

{% endcode %}

然后使用分词器创建整个提示：

{% code overflow="wrap" %}

```python
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("unsloth/Qwen3-Coder-480B-A35B-Instruct")

messages = [
    {'role': 'user', 'content': "What's the temperature in San Francisco now? How about tomorrow?"},
    {'content': "", 'role': 'assistant', 'function_call': None, 'tool_calls': [
        {'id': 'ID', 'function': {'arguments': {"location": "San Francisco, CA, USA"}, 'name': 'get_current_temperature'}, 'type': 'function'},
    ]},
    {'role': 'tool', 'content': '{"temperature": 26.1, "location": "San Francisco, CA, USA", "unit": "celsius"}', 'tool_call_id': 'ID'},
]

prompt = tokenizer.apply_chat_template(messages, tokenize = False)
```

{% endcode %}

## :bulb:性能基准

{% hint style="info" %}
这些官方基准针对的是完整 BF16 检查点。要使用它，只需使用我们上传的 `Q8_K_XL, Q8_0, BF16` 检查点——你仍然可以对这些版本使用像 MoE 卸载之类的技巧！
{% endhint %}

以下是 480B 模型的基准：

#### 具代理能力的编码

<table data-full-width="true"><thead><tr><th>基准</th><th>Qwen3‑Coder 480B‑A35B‑Instruct</th><th>Kimi‑K2</th><th>DeepSeek‑V3-0324</th><th>Claude 4 Sonnet</th><th>GPT‑4.1</th></tr></thead><tbody><tr><td>Terminal‑Bench</td><td><strong>37.5</strong></td><td>30.0</td><td>2.5</td><td>35.5</td><td>25.3</td></tr><tr><td>SWE‑bench 已通过 OpenHands 验证（500 回合）</td><td><strong>69.6</strong></td><td>–</td><td>–</td><td>70.4</td><td>–</td></tr><tr><td>SWE‑bench 已通过 OpenHands 验证（100 回合）</td><td><strong>67.0</strong></td><td>65.4</td><td>38.8</td><td>68.0</td><td>48.6</td></tr><tr><td>SWE‑bench 已通过私有支撑验证</td><td>–</td><td>65.8</td><td>–</td><td>72.7</td><td>63.8</td></tr><tr><td>SWE‑bench 实时</td><td><strong>26.3</strong></td><td>22.3</td><td>13.0</td><td>27.7</td><td>–</td></tr><tr><td>SWE‑bench 多语种</td><td><strong>54.7</strong></td><td>47.3</td><td>13.0</td><td>53.3</td><td>31.5</td></tr><tr><td>Multi‑SWE‑bench 迷你</td><td><strong>25.8</strong></td><td>19.8</td><td>7.5</td><td>24.8</td><td>–</td></tr><tr><td>Multi‑SWE‑bench flash</td><td><strong>27.0</strong></td><td>20.7</td><td>–</td><td>25.0</td><td>–</td></tr><tr><td>Aider‑Polyglot</td><td><strong>61.8</strong></td><td>60.0</td><td>56.9</td><td>56.4</td><td>52.4</td></tr><tr><td>Spider2</td><td><strong>31.1</strong></td><td>25.2</td><td>12.8</td><td>31.1</td><td>16.5</td></tr></tbody></table>

#### 具代理能力的浏览器使用

<table data-full-width="true"><thead><tr><th>基准</th><th>Qwen3‑Coder 480B‑A35B‑Instruct</th><th>Kimi‑K2</th><th>DeepSeek‑V3 0324</th><th>Claude Sonnet‑4</th><th>GPT‑4.1</th></tr></thead><tbody><tr><td>WebArena</td><td><strong>49.9</strong></td><td>47.4</td><td>40.0</td><td>51.1</td><td>44.3</td></tr><tr><td>Mind2Web</td><td><strong>55.8</strong></td><td>42.7</td><td>36.0</td><td>47.4</td><td>49.6</td></tr></tbody></table>

#### 具代理能力的工具使用

<table data-full-width="true"><thead><tr><th>基准</th><th>Qwen3‑Coder 480B‑A35B‑Instruct</th><th>Kimi‑K2</th><th>DeepSeek‑V3 0324</th><th>Claude Sonnet‑4</th><th>GPT‑4.1</th></tr></thead><tbody><tr><td>BFCL‑v3</td><td><strong>68.7</strong></td><td>65.2</td><td>56.9</td><td>73.3</td><td>62.9</td></tr><tr><td>TAU‑Bench 零售</td><td><strong>77.5</strong></td><td>70.7</td><td>59.1</td><td>80.5</td><td>–</td></tr><tr><td>TAU‑Bench 航空</td><td><strong>60.0</strong></td><td>53.5</td><td>40.0</td><td>60.0</td><td>–</td></tr></tbody></table>


---

# 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/qwen3-coder-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.
