查看我们的资源集获取Qwen3所有版本,包括GGUF、4位及16位格式。
学习如何正确运行Qwen3 - 阅读我们的指南。
Unsloth Dynamic 2.0实现了卓越的精度表现,超越其他主流量化方案。
| Unsloth支持模型 | 免费笔记本 | 性能提升 | 内存占用降低 |
|---|---|---|---|
| Qwen3 (14B) | ▶️ Colab启动 | 提速3倍 | 减少70% |
| GRPO with Qwen3 (8B) | ▶️ Colab启动 | 提速3倍 | 减少80% |
| Llama-3.2 (3B) | ▶️ Colab启动 | 提速2.4倍 | 减少58% |
| Llama-3.2 (11B 视觉) | ▶️ Colab启动 | 提速2倍 | 减少60% |
| Qwen2.5 (7B) | ▶️ Colab启动 | 提速2倍 | 减少60% |
| Phi-4 (14B) | ▶️ Colab启动 | 提速2倍 | 减少50% |
若您使用 llama.cpp、Ollama、Open WebUI 等工具,可在用户提示或系统消息中添加 /think 与 /no_think 指令,实现逐轮切换模型的思考模式。在多轮对话中,模型将遵循最近一次收到的指令。
以下为多轮对话示例:
> Who are you /no_think
<think>
</think>
I am Qwen, a large-scale language model developed by Alibaba Cloud. [...]
> How many 'r's are in 'strawberries'? /think
<think>
Okay, let's see. The user is asking how many times the letter 'r' appears in the word "strawberries". [...]
</think>
The word strawberries contains 3 instances of the letter r. [...]Qwen3 作为通义千问系列最新一代大语言模型,提供完整的稠密模型与混合专家(MoE)模型组合。基于大规模训练构建的 Qwen3 在推理能力、指令遵循、智能体功能及多语言支持方面实现突破性进展,具备以下核心特性:
Qwen3-14B 具备以下特性:
更多细节包括基准测试评估、硬件需求与推理性能,请参阅我们的博客、GitHub及技术文档。
Qwen3 的代码已集成至最新版 Hugging Face transformers 库,建议您使用最新版本的 transformers。
若使用 transformers<4.51.0 版本,您将会遇到以下错误:
KeyError: 'qwen3'以下代码片段展示了如何基于给定输入使用模型生成内容。
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-14B"
# load the tokenizer and the model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
# prepare the model input
prompt = "Give me a short introduction to large language model."
messages = [
{"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
# conduct text completion
generated_ids = model.generate(
**model_inputs,
max_new_tokens=32768
)
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
# parsing thinking content
try:
# rindex finding 151668 (</think>)
index = len(output_ids) - output_ids[::-1].index(151668)
except ValueError:
index = 0
thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
print("thinking content:", thinking_content)
print("content:", content)在部署方面,您可以使用 vllm>=0.8.5 或 sglang>=0.4.5.post2 来创建兼容 OpenAI 的 API 端点:
vllm serve Qwen/Qwen3-14B --enable-reasoning --reasoning-parser deepseek_r1python -m sglang.launch_server --model-path Qwen/Qwen3-14B --reasoning-parser deepseek-r1[!TIP]
enable_thinking开关同样适用于通过 vLLM 和 SGLang 创建的 API。 更多详细信息请参阅我们的文档。
enable_thinking=True默认情况下,Qwen3 已启用思考能力,类似于 QwQ-32B。这意味着模型将运用其推理能力来提升生成回答的质量。例如,当在 tokenizer.apply_chat_template 中显式设置 enable_thinking=True 或保持其默认值时,模型将进入思考模式。
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # True is the default value for enable_thinking
)在此模式下,模型将生成包裹在<think>...</think>标签块内的思考内容,随后输出最终响应。
[!注意] 使用思考模式时,请设置
Temperature=0.6、TopP=0.95、TopK=20和MinP=0(即generation_config.json中的默认配置)。切勿使用贪心解码,否则可能导致性能下降和无限重复。更详细的指导请参阅最佳实践章节。
enable_thinking=False我们提供了严格禁用模型思考行为的硬性开关,使其功能与之前的Qwen2.5-Instruct模型保持一致。在需要关闭思考功能以提升效率的场景中,此模式尤为实用。
(注:根据项目信息要求,技术参数Temperature/TopP/TopK/MinP及文件名generation_config.json保持原文,专业术语"greedy decoding"采用计算机领域通用译法"贪心解码",项目名称Qwen2.5-Instruct未作翻译,同时保持了Markdown格式和警告框的原始结构)
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False # Setting enable_thinking=False disables thinking mode
)在此模式下,模型将不会生成任何思考内容,也不会包含<think>...</think>区块。
[!注意] 对于非思考模式,建议使用
Temperature=0.7、TopP=0.8、TopK=20和MinP=0参数配置。更详细的指导请参阅最佳实践章节。
我们提供软切换机制,当启用enable_thinking=True时,用户可通过在提示词或系统消息中添加/think和/no_think指令,动态控制模型在不同对话轮次中的思考行为。在多轮对话中,模型将遵循最近接收到的指令模式。
以下是一个多轮对话示例:
from transformers import AutoModelForCausalLM, AutoTokenizer
class QwenChatbot:
def __init__(self, model_name="Qwen/Qwen3-14B"):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForCausalLM.from_pretrained(model_name)
self.history = []
def generate_response(self, user_input):
messages = self.history + [{"role": "user", "content": user_input}]
text = self.tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
inputs = self.tokenizer(text, return_tensors="pt")
response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
# Update history
self.history.append({"role": "user", "content": user_input})
self.history.append({"role": "assistant", "content": response})
return response
# Example Usage
if __name__ == "__main__":
chatbot = QwenChatbot()
# First input (without /think or /no_think tags, thinking mode is enabled by default)
user_input_1 = "How many r's in strawberries?"
print(f"User: {user_input_1}")
response_1 = chatbot.generate_response(user_input_1)
print(f"Bot: {response_1}")
print("----------------------")
# Second input with /no_think
user_input_2 = "Then, how many r's in blueberries? /no_think"
print(f"User: {user_input_2}")
response_2 = chatbot.generate_response(user_input_2)
print(f"Bot: {response_2}")
print("----------------------")
# Third input with /think
user_input_3 = "Really? /think"
print(f"User: {user_input_3}")
response_3 = chatbot.generate_response(user_input_3)
print(f"Bot: {response_3}")注意 为保持API兼容性,当启用思维模式(
enable_thinking=True)时,无论用户使用/think还是/no_think指令,模型始终会输出用<think>...</think>包裹的区块。但若思维功能被禁用,该区块内的内容可能为空。 当enable_thinking=False时,软开关将失效。无论用户输入任何/think或/no_think标签,模型既不会生成思维内容,也不会包含<think>...</think>区块。
Qwen3在工具调用能力方面表现卓越。我们推荐使用 Qwen-Agent 来充分发挥Qwen3的智能体能力。Qwen-Agent内部封装了工具调用模板和工具调用解析器,可大幅降低编码复杂度。
您可以通过MCP配置文件定义可用工具,使用Qwen-Agent的集成工具,或自行集成其他工具。
from qwen_agent.agents import Assistant
# Define LLM
llm_cfg = {
'model': 'Qwen3-14B',
# Use the endpoint provided by Alibaba Model Studio:
# 'model_type': 'qwen_dashscope',
# 'api_key': os.getenv('DASHSCOPE_API_KEY'),
# Use a custom endpoint compatible with OpenAI API:
'model_server': 'http://localhost:8000/v1', # api_base
'api_key': 'EMPTY',
# Other parameters:
# 'generate_cfg': {
# # Add: When the response content is `<think>this is the thought</think>this is the answer;
# # Do not add: When the response has been separated by reasoning_content and content.
# 'thought_in_content': True,
# },
}
# Define Tools
tools = [
{'mcpServers': { # You can specify the MCP configuration file
'time': {
'command': 'uvx',
'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
},
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
}
},
'code_interpreter', # Built-in tools
]
# Define Agent
bot = Assistant(llm=llm_cfg, function_list=tools)
# Streaming generation
messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
for responses in bot.run(messages=messages):
pass
print(responses)Qwen3 原生支持高达 32,768 个 token 的上下文长度。对于总长度(包括输入和输出)显著超过此限制的对话,我们建议使用 RoPE 缩放技术来有效处理长文本。我们已通过 YaRN 方法验证了模型在高达 131,072 个 token 的上下文长度上的性能。
目前多个推理框架支持 YaRN,例如本地使用的 transformers 和 llama.cpp,以及部署使用的 vllm 和 sglang。通常,为支持的框架启用 YaRN 有两种方法:
修改模型文件:
在 config.json 文件中,添加 rope_scaling 字段:
{
...,
"rope_scaling": {
"type": "yarn",
"factor": 4.0,
"original_max_position_embeddings": 32768
}
}对于 llama.cpp,修改后需要重新生成 GGUF 文件。
传递命令行参数:
对于 vllm,您可以使用
vllm serve ... --rope-scaling '{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072 对于 sglang,您可以使用
python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'对于 llama.cpp 中的 llama-server,您可以使用
llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768[!重要] 如果您遇到以下警告
在 'rope_type'='yarn' 的 `rope_scaling` 中存在无法识别的键:{'original_max_position_embeddings'}请升级
transformers>=4.51.0。
[!注意] 所有知名的开源框架均实现了静态 YaRN,这意味着缩放因子不随输入长度变化,可能会影响短文本的性能。 我们建议仅在需要处理长上下文时添加
rope_scaling配置。 同时建议根据需要修改factor。例如,如果您的应用典型上下文长度为 65,536 个 token,则最好将factor设置为 2.0。
[!注意]
config.json中的默认max_position_embeddings设置为 40,960。此分配包括为输出保留 32,768 个 token 和为典型提示保留 8,192 个 token,这对于涉及短文本处理的大多数场景已经足够。如果平均上下文长度不超过 32,768 个 token,我们不建议在此场景中启用 YaRN,因为它可能会降低模型性能。
[!提示] 阿里云 Model Studio 提供的端点默认支持动态 YaRN,无需额外配置。
为获得最佳性能,我们推荐以下设置:
采样参数:
enable_thinking=True)下,建议使用 Temperature=0.6、TopP=0.95、TopK=20 和 MinP=0。请勿使用贪心解码,否则可能导致性能下降和无限重复。enable_thinking=False)下,建议使用 Temperature=0.7、TopP=0.8、TopK=20 和 MinP=0。presence_penalty 参数设置在 0 到 2 之间以减少无限重复。但注意:较高值可能偶尔导致语言混杂和模型性能轻微下降。充足输出长度:常规任务建议输出长度设为 32,768 tokens。针对数学竞赛、编程竞赛等高复杂度问题的基准测试,建议将最大输出长度设为 38,912 tokens。这能为模型提供充分空间生成详尽响应,从而提升整体表现。
标准化输出格式:建议通过提示词规范模型输出格式:
answer 字段中仅填写选项字母,例如 "answer": "C""。历史记录排除思考内容:在多轮对话中,历史模型输出应仅包含最终答案部分,无需包含思考过程。本功能已在提供的 Jinja2 对话模板中实现。对于未直接使用该模板的框架,需由开发者自行确保遵循此最佳实践。
如果您觉得我们的工作对您有帮助,欢迎引用。
@misc{qwen3,
title = {Qwen3},
url = {https://qwenlm.github.io/blog/qwen3/},
author = {Qwen Team},
month = {April},
year = {2025}
}