> 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/qwen3-how-to-run-and-fine-tune.md).

# Qwen3 - 如何运行与微调

学习如何使用 Unsloth + 我们的 Dynamic 2.0 量化版本在本地运行和微调 Qwen3。

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

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

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

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

[Unsloth](https://github.com/unslothai/unsloth) 现在还支持微调和 [强化学习（RL）](/docs/zh/kuai-su-kai-shi/reinforcement-learning-rl-guide.md) Qwen3 和 Qwen3 MOE 模型——速度快 2 倍，显存占用减少 70%，上下文长度延长 8 倍。使用我们的免费 [Colab 笔记本。](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 内存。180GB 的 Q2\_K\_XL 量化模型将至少需要 **180GB 统一内存** （VRAM + RAM）或 **180GB RAM** 才能获得最佳性能。

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

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

根据 Qwen 的说法，以下是推荐的推理设置：

| 非思考模式设置：                                                          | 思考模式设置：                                                           |
| ----------------------------------------------------------------- | ----------------------------------------------------------------- |
| <mark style="background-color:blue;">**Temperature = 0.7**</mark> | <mark style="background-color:blue;">**Temperature = 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](/docs/zh/mo-xing/tutorials/qwq-32b-how-to-run-effectively.md) 的工作方式。切换说明会因你使用的推理引擎而异，因此请确保使用正确的说明。

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

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

多轮对话示例如下：

```
> 你是谁 /no_think

<think>

</think>

我是 Qwen，一款由阿里云开发的大规模语言模型。[...]

> 'strawberries' 里有几个 'r'？ /think

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

单词 strawberries 中包含 3 个字母 r。[...]
```

#### 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 显存 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）推理 + 对话 notebook](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 ](/docs/zh/ji-chu-zhi-shi/faster-moe.md)更新：30B-A3B 和 235B-A22B。Qwen3-30B-A3B 在 Unsloth 下只需 17.5GB 显存即可运行。对于 MOE 的微调——可能不建议微调路由层，因此我们默认将其禁用。

30B-A3B 可装入 17.5GB 显存，但你可能会缺少 RAM 或磁盘空间，因为用于 QLoRA 微调时必须下载完整的 16 位模型并在运行时转换为 4 位。这是由于直接导入 4 位 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, # [NEW!] 稍微更准确，使用 2 倍内存
    full_finetuning = False, # [NEW!] 我们现在支持完整微调！
    # 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 笔记本进行微调的完整端到端指南，或者只是想了解微调、创建 [datasets](/docs/zh/kuai-su-kai-shi/fine-tuning-llms-guide/datasets-guide.md) 等内容，请查看我们的 [完整指南](/docs/zh/kuai-su-kai-shi/fine-tuning-llms-guide.md):

{% content-ref url="/pages/e722e86e330786e5915445b91f900d9f9e0ba067" %}
[Fine-tuning Guide](/docs/zh/kuai-su-kai-shi/fine-tuning-llms-guide.md)
{% endcontent-ref %}

{% content-ref url="/pages/e3d8f41874867d09291eadcea96a34bf92b096a7" %}
[数据集指南](/docs/zh/kuai-su-kai-shi/fine-tuning-llms-guide/datasets-guide.md)
{% endcontent-ref %}

### 使用 Qwen3 的 GRPO

我们为微调 Qwen3 制作了一个新的高级 GRPO 笔记本。学习如何使用我们新的基于接近度的奖励函数（答案越接近 = 奖励越高）以及 Hugging Face 的 Open-R1 数学数据集。\nUnsloth 现在还有更好的评估，并使用最新版 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
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/qwen3-how-to-run-and-fine-tune.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.
