Qwen3 是通义千问系列大语言模型的最新版本,提供了一系列密集型和混合专家(MoE)模型。基于大规模训练,Qwen3 在推理、指令遵循、智能体能力和多语言支持方面实现了突破性进展,主要特点包括:
Qwen3-8B 具有以下特性:
更多细节,包括基准评估、硬件需求和推理性能,请参阅我们的博客、GitHub 和文档。
Qwen3 的代码已集成至最新版 Hugging Face transformers,建议使用最新版本。
若使用 transformers<4.51.0,您将遇到以下错误:
KeyError: 'qwen3'以下代码片段展示了如何基于给定输入使用该模型生成内容。
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-8B"
# 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)部署时,您可以使用 sglang>=0.4.6.post1 或 vllm>=0.8.5 创建兼容 OpenAI 的 API 服务端点:
python -m sglang.launch_server --model-path Qwen/Qwen3-8B --reasoning-parser qwen3vllm serve Qwen/Qwen3-8B --enable-reasoning --reasoning-parser deepseek_r1对于本地使用,Ollama、LMStudio、MLX-LM、llama.cpp 和 KTransformers 等应用也已支持 Qwen3 模型。
[!TIP]
enable_thinking开关同样适用于 SGLang 和 vLLM 创建的 API 服务。 具体使用方法请参阅 SGLang 和 vLLM 的官方文档。
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 模型保持一致。该模式在需要禁用思考以提升效率的场景中尤为实用。
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-8B"):
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-8B',
# 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 tokens 的上下文长度。对于输入输出总长度远超该限制的对话场景,我们推荐使用 RoPE 插值技术来高效处理长文本。通过 YaRN 方法,我们已验证模型在 131,072 tokens 上下文长度下的性能表现。
目前,transformers 和 llama.cpp 等本地推理框架,以及 vllm 和 sglang 等部署框架均已支持 YaRN。对于已支持该技术的框架,通常有两种启用方式:
修改模型文件:
在 config.json 中添加 rope_scaling 字段:
{
...,
"rope_scaling": {
"rope_type": "yarn",
"factor": 4.0,
"original_max_position_embeddings": 32768
}
}若使用 llama.cpp,修改后需重新生成 GGUF 文件。
命令行传参:
vllm 用户可执行:
vllm serve ... --rope-scaling '{"rope_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":{"rope_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[!IMPORTANT] 若出现以下警告:
Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}请升级
transformers>=4.51.0。
[!NOTE] 当前主流开源框架均采用静态 YaRN 实现,即无论输入长度如何,缩放因子始终保持不变,这可能影响短文本场景的性能表现。
建议仅在需要处理长上下文时添加rope_scaling配置,并根据实际需求调整factor参数。例如,若典型上下文长度为 65,536 tokens,更推荐设置factor为 2.0。
[!NOTE]
config.json中默认的max_position_embeddings为 40,960,该设计预留了 32,768 tokens 用于输出和 8,192 tokens 用于常规提示,足以覆盖大多数短文本处理场景。若平均上下文长度未超过 32,768 tokens,不建议启用 YaRN,以免潜在影响模型性能。
[!TIP] 阿里云模型服务平台(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 以缓解无限重复问题,但过高值可能偶尔导致语言混杂和轻微性能下降。充足输出长度:
标准化输出格式:
基准测试时推荐通过提示词规范输出格式:
answer 字段中仅填写选项字母,如 "answer": "C"”。历史对话不包含思考内容:
在多轮对话中,历史模型输出应仅包含最终回答部分,无需保留思考过程。该逻辑已通过 Jinja2 聊天模板实现。对于未直接使用该模板的框架,需开发者自行确保遵循此最佳实践。
如果您觉得我们的工作有帮助,欢迎引用。
@misc{qwen3,
title = {Qwen3},
url = {https://qwenlm.github.io/blog/qwen3/},
author = {Qwen Team},
month = {April},
year = {2025}
}