# Qwen3 - 如何运行与微调

Qwen 的全新 Qwen3 模型在推理、遵循指令、智能体能力和多语言支持方面带来了最先进的进展。

{% hint style="success" %}
**全新！** Qwen3 已于 2025 年 7 月更新。运行并微调最新模型： [**Qwen-2507**](https://unsloth.ai/docs/zh/mo-xing/tutorials/qwen3-next)
{% endhint %}

所有上传都使用 Unsloth [Dynamic 2.0](https://unsloth.ai/docs/zh/ji-chu/unsloth-dynamic-2.0-ggufs) 用于 SOTA 5-shot MMLU 和 KL 散度性能，这意味着你可以以最小的精度损失运行并微调量化的 Qwen LLM。

我们还上传了原生 128K 上下文长度的 Qwen3。Qwen 通过使用 YaRN 将其原始 40K 窗口扩展到 128K 来实现这一点。

[使用 Unsloth 进行](https://github.com/unslothai/unsloth) 现在也支持微调和 [强化学习（RL）](https://unsloth.ai/docs/zh/kai-shi-shi-yong/reinforcement-learning-rl-guide) Qwen3 和 Qwen3 MOE 模型——速度快 2 倍，显存占用减少 70%，上下文长度延长 8 倍。你可以使用我们的 [Colab 笔记本免费微调 Qwen3（14B）。](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(14B\)-Reasoning-Conversational.ipynb)

<a href="#running-qwen3" class="button primary">运行 Qwen3 教程</a> <a href="#fine-tuning-qwen3-with-unsloth" class="button secondary">微调 Qwen3</a>

#### **Qwen3 - Unsloth Dynamic 2.0** 使用最佳配置：

| Dynamic 2.0 GGUF（用于运行）                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | 128K 上下文 GGUF                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Dynamic 4-bit Safetensor（用于微调/部署）                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <ul><li><a href="https://huggingface.co/unsloth/Qwen3-0.6B-GGUF">0.6B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-1.7B-GGUF">1.7B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-4B-GGUF">4B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-8B-GGUF">8B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-14B-GGUF">14B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-30B-A3B-GGUF">30B-A3B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-32B-GGUF">32B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-235B-A22B-GGUF">235B-A22B</a></li></ul> | <ul><li><a href="https://huggingface.co/unsloth/Qwen3-4B-128K-GGUF">4B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-8B-128K-GGUF">8B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-14B-128K-GGUF">14B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-30B-A3B-128K-GGUF">30B-A3B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-32B-128K-GGUF">32B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-235B-A22B-128K-GGUF">235B-A22B</a></li></ul> | <ul><li><a href="https://huggingface.co/unsloth/Qwen3-0.6B-unsloth-bnb-4bit">0.6B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-1.7B-unsloth-bnb-4bit">1.7B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-4B-unsloth-bnb-4bit">4B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-8B-unsloth-bnb-4bit">8B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-14B-unsloth-bnb-4bit">14B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-30B-A3B-bnb-4bit">30B-A3B</a></li><li><a href="https://huggingface.co/unsloth/Qwen3-32B-unsloth-bnb-4bit">32B</a></li></ul> |

## 🖥️ **运行 Qwen3**

为了实现每秒 6+ token 的推理速度，我们建议你的可用内存应与所用模型的大小相当或更大。例如，一个 30GB 的 1-bit 量化模型至少需要 150GB 内存。Q2\_K\_XL 量化版大小为 180GB，至少需要 **180GB 统一内存** （VRAM + RAM）或 **180GB RAM** 才能获得最佳性能。

**注意：** 模型可以在 **小于其大小的总内存** 下运行（即更少的 VRAM、更少的 RAM，或更低的总内存）。不过，这会导致更慢的推理速度。只有当你想最大化吞吐量并获得最快的推理时间时，才需要充足的内存。

### :gear: 官方推荐设置

根据 Qwen 的建议，以下是推理推荐设置：

| 非思考模式设置：                                                 | 思考模式设置：                                                  |
| -------------------------------------------------------- | -------------------------------------------------------- |
| <mark style="background-color:blue;">**温度 = 0.7**</mark> | <mark style="background-color:blue;">**温度 = 0.6**</mark> |
| Min\_P = 0.0（可选，但 0.01 也很好，llama.cpp 默认是 0.1）            | Min\_P = 0.0                                             |
| Top\_P = 0.8                                             | Top\_P = 0.95                                            |
| TopK = 20                                                | TopK = 20                                                |

**聊天模板/提示格式：**

{% code overflow="wrap" %}

```
<|im_start|>user\n2+2 等于多少？<|im_end|>\n<|im_start|>assistant\n
```

{% endcode %}

{% hint style="success" %}
对于非思考模式，我们特意将 \<think> 和 \</think> 留空：
{% endhint %}

{% code overflow="wrap" %}

```
<|im_start|>user\n2+2 等于多少？<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n
```

{% endcode %}

{% hint style="warning" %}
**对于思考模式，不要使用贪婪解码**，因为这可能导致性能下降和无限重复。
{% endhint %}

### 在思考模式与非思考模式之间切换

Qwen3 模型内置“思考模式”，可增强推理并提升回答质量——类似于 [QwQ-32B](https://unsloth.ai/docs/zh/mo-xing/tutorials/qwq-32b-how-to-run-effectively) 的工作方式。切换说明会因你使用的推理引擎而异，因此请确保使用正确的说明。

#### llama.cpp 和 Ollama 的说明：

你可以在 `/think` 和 `/no_think` 加入到用户提示或系统消息中，以在不同轮次间切换模型的思考模式。模型会遵循多轮对话中最新的指令。

以下是一个多轮对话示例：

```
> 你是谁 /no_think

<think>

</think>

我是通义千问（Qwen），由阿里云开发的大规模语言模型。[...]

> 'strawberries' 里有多少个 'r'？ /think

<think>
好的，让我看看。用户在问单词“strawberries”中字母 'r' 出现了多少次。[...]
</think>

单词 strawberries 中字母 r 出现了 3 次。[...]
```

#### transformers 和 vLLM 的说明：

**思考模式：**

`enable_thinking=True`

默认情况下，Qwen3 会启用思考。当你调用 `tokenizer.apply_chat_template`时， **你不需要手动设置任何内容。**

```python
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=True  # 默认值为 True
)
```

在思考模式下，模型会在最终答案之前额外生成一个 `<think>...</think>` 块——这让它可以“规划”并优化回答。

**非思考模式：**

`enable_thinking=False`

启用非思考模式会让 Qwen3 跳过所有思考步骤，像普通 LLM 一样工作。

```python
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=False  # 禁用思考模式
)
```

此模式会直接给出最终回答——没有 `<think>` 块，也没有思维链。

### 🦙 Ollama：运行 Qwen3 教程

1. 安装 `ollama` 如果你还没有安装的话！你只能运行大小不超过 32B 的模型。要运行完整的 235B-A22B 模型， [请看这里](#running-qwen3-235b-a22b).

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

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

```bash
ollama run hf.co/unsloth/Qwen3-8B-GGUF:UD-Q4_K_XL
```

3. 要禁用思考，请使用（或者你也可以在系统提示中设置它）：

```
>>> 在这里写下你的提示 /nothink
```

{% hint style="warning" %}
如果你遇到循环问题，Ollama 可能把你的上下文长度窗口设成了 2,048 左右。如果是这样，把它提高到 32,000，再看看问题是否仍然存在。
{% endhint %}

### 📖 Llama.cpp：运行 Qwen3 教程

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 或其他量化版本。

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

3. 运行模型并尝试任意提示。

```bash
./llama.cpp/llama-cli \
    --model unsloth/Qwen3-14B-GGUF/Qwen3-14B-UD-Q2_K_XL.gguf \
    --ctx-size 16384 \
    --n-gpu-layers 99 \
    -ot ".ffn_.*_exps.=CPU" \
    --seed 3407 \
    --prio 3 \
    --temp 0.6 \
    --min-p 0.0 \
    --top-p 0.95 \
    --top-k 20 \
    -no-cnv
```

要禁用思考，请使用（或者你也可以在系统提示中设置它）：

```
>>> 在这里写下你的提示 /nothink
```

### 运行 Qwen3-235B-A22B

对于 Qwen3-235B-A22B，我们将专门使用 Llama.cpp 进行优化推理，并提供大量选项。

1. 我们的步骤与上面类似，但这次还需要执行额外步骤，因为这个模型太大了。
2. 通过以下方式下载模型（在安装之后 `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"] = "1"
   from huggingface_hub import snapshot_download
   snapshot_download(
       repo_id = "unsloth/Qwen3-235B-A22B-GGUF",
       local_dir = "unsloth/Qwen3-235B-A22B-GGUF",
       allow_patterns = ["*UD-Q2_K_XL*"],
   )
   ```
3. 运行模型并尝试任意提示。
4. 编辑 `--threads 32` CPU 线程数， `--ctx-size 16384` 用于上下文长度， `--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/Qwen3-235B-A22B-GGUF/Qwen3-235B-A22B-UD-Q2_K_XL.gguf \
    --ctx-size 16384 \
    --n-gpu-layers 99 \
    -ot ".ffn_.*_exps.=CPU" \
    --seed 3407 \
    --prio 3 \
    --temp 0.6 \
    --min-p 0.0 \
    --top-p 0.95 \
    --top-k 20 \
    -no-cnv \
    --prompt "<|im_start|>user\n用 Python 创建一个 Flappy Bird 游戏。你必须包含以下内容：\n1. 必须使用 pygame。\n2. 背景颜色应随机选择，并且是浅色。起始颜色为浅蓝色。\n3. 多次按下 SPACE 会加速小鸟。\n4. 小鸟的形状应随机选择为正方形、圆形或三角形。颜色应随机选择为深色。\n5. 在底部放一些随机选择为深棕色或黄色的土地。\n6. 在右上角显示分数。通过管道而且没有撞到它们时加分。\n7. 生成间距随机且留有足够空隙的管道。颜色随机为深绿色、浅棕色或深灰色调。\n8. 当你失败时，显示最高分。文本应在屏幕内。按 q 或 Esc 退出游戏。重新开始按 SPACE。\n最终游戏应作为 Python 的 markdown 区块呈现。在最终 markdown 区块之前检查代码是否有错误并修复它们。<|im_end|>\n<|im_start|>assistant\n"
```

{% endcode %}

## 🦥 使用 Unsloth 微调 Qwen3

Unsloth 让 Qwen3 的微调速度快 2 倍，显存使用减少 70%，并支持 8 倍更长的上下文长度。Qwen3（14B）在 Google Colab 的 16GB VRAM Tesla T4 GPU 上也能轻松运行。

由于 Qwen3 同时支持推理和非推理，你可以用非推理数据集来微调它，但这可能会影响其推理能力。如果你想保留它的推理能力（可选），可以使用直接回答和思维链示例的混合。使用 <mark style="background-color:green;">75% 推理</mark> 和 <mark style="background-color:green;">25% 非推理</mark> 作为数据集中的比例，以让模型保留其推理能力。

我们的对话式笔记本使用了 75% 的 NVIDIA 开放数学推理数据集和 25% 的 Maxime FineTome 数据集（非推理）的组合。以下是用于微调 Qwen3 的免费 Unsloth Colab 笔记本：

* [Qwen3（14B）推理 + 对话式笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(14B\)-Reasoning-Conversational.ipynb) （推荐）
* [**Qwen3（4B）**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(4B\)-GRPO.ipynb) **- 高级 GRPO LoRA**
* [Qwen3（14B）Alpaca 笔记本](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(14B\)-Alpaca.ipynb) （用于基础模型）

如果你使用的是旧版 Unsloth 和/或在本地微调，请安装最新版 Unsloth：

```
pip install --upgrade --force-reinstall --no-cache-dir unsloth unsloth_zoo
```

### Qwen3 MOE 模型微调

微调支持包括我们新的 2026 [更快的 MOE ](https://unsloth.ai/docs/zh/ji-chu/faster-moe)更新：30B-A3B 和 235B-A22B。Qwen3-30B-A3B 在 Unsloth 下只需 17.5GB VRAM 即可运行。微调 MoE 时——将路由层一并微调可能不是好主意，因此我们默认禁用了它。

30B-A3B 可放入 17.5GB VRAM，但你可能会缺少 RAM 或磁盘空间，因为在进行 QLoRA 微调时，完整的 16-bit 模型必须先下载并在运行时转换为 4-bit。这是由于直接导入 4-bit BnB MOE 模型时存在问题。此问题仅影响 MOE 模型。

```python
from unsloth import FastModel
import torch
model, tokenizer = FastModel.from_pretrained(
    model_name = "unsloth/Qwen3-30B-A3B",
    max_seq_length = 2048, # 长上下文可任选！
    load_in_4bit = True,  # 使用 4 位量化以减少内存
    load_in_8bit = False, # [新！] 稍微更准确，但占用 2 倍内存
    full_finetuning = False, # [新！] 现在我们支持完整微调！
    # token = "hf_...", # 如果使用受限模型请使用这个
)
```

### 笔记本指南：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-1cfff4a8a728737598e1432529da745d58e71248%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

要使用这些笔记本，只需点击 Runtime，然后选择 Run all。你可以在笔记本中把设置改成你想要的任何值。我们已默认自动设置好。将模型名称改成你喜欢的即可，只要与 Hugging Face 上的模型名称匹配，例如 'unsloth/Qwen3-8B' 或 'unsloth/Qwen3-0.6B-unsloth-bnb-4bit'。

还有其他可切换的设置：

* **`max_seq_length = 2048`** – 控制上下文长度。虽然 Qwen3 支持 40960，但我们建议测试时使用 2048。Unsloth 支持 8× 更长上下文的微调。
* **`load_in_4bit = True`** – 启用 4 位量化，在 16GB GPU 上微调时可将内存使用减少 4 倍。
* 对于 **完整微调** - 设置 `full_finetuning = True` 和 **8 位微调** - 设置 `load_in_8bit = True`

如果你想阅读一份关于如何使用 Unsloth 笔记本进行微调的完整端到端指南，或者只是想了解微调、创建 [数据集](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/datasets-guide) 等内容，请查看我们的 [完整指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide):

{% content-ref url="../../kai-shi-shi-yong/fine-tuning-llms-guide" %}
[fine-tuning-llms-guide](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide)
{% endcontent-ref %}

{% content-ref url="../../kai-shi-shi-yong/fine-tuning-llms-guide/datasets-guide" %}
[datasets-guide](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide/datasets-guide)
{% endcontent-ref %}

### 使用 Qwen3 进行 GRPO

我们为微调 Qwen3 制作了一个新的高级 GRPO 笔记本。学习使用我们新的基于距离的奖励函数（答案越接近，奖励越高）以及 Hugging Face 的 Open-R1 数学数据集。Unsloth 现在还拥有更好的评估，并使用最新版本的 vLLM。

[**Qwen3（4B）**](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_\(4B\)-GRPO.ipynb) **笔记本 - 高级 GRPO LoRA**

了解以下内容：

* 在 Qwen3（基础版）中启用推理，并引导其执行特定任务
* 通过预微调绕过 GRPO 倾向于学习格式的缺点
* 通过新的正则表达式匹配提高评估准确率
* 除了 'think' 之外的自定义 GRPO 模板，例如 \<start\_working\_out>\</end\_working\_out>
* 基于距离的评分：更好的答案得分更高（例如，答案是 10 时预测 9）并且会惩罚离群值

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-be34c101c627020c7a6cfb6cd249f2462587d235%2Fqwen33%20mascot.png?alt=media" alt=""><figcaption></figcaption></figure>


---

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