文章目录
一、关于 Qwen3-235B-A22B
基础信息
- HuggingFace :https://huggingface.co/Qwen/Qwen3-235B-A22B
- 开发团队:Qwen Team
- 模型类型:混合专家(MoE)架构的因果语言模型
- 官方资源:Chat Demo | GitHub | 文档
Qwen3 亮点
Qwen3 是通义千问系列最新一代大语言模型,提供完整的稠密模型与混合专家(MoE)模型组合。
基于大规模训练,Qwen3 在推理能力、指令跟随、智能体功能及多语言支持方面实现突破性进展,具有以下核心特性:
- 独创性支持思维模式(适用于复杂逻辑推理、数学与编程)与非思维模式(适用于高效通用对话)在单一模型内无缝切换,确保各类场景下的最优表现
- 显著增强的推理能力,在数学解题、代码生成与常识逻辑推理方面,全面超越前代QwQ(思维模式)与Qwen2.5 instruct模型(非思维模式)
- 卓越的人类偏好对齐,在创意写作、角色扮演、多轮对话及指令跟随场景表现突出,提供更自然、引人入胜的对话体验
- 专业的智能体能力,可在思维/非思维模式下精准对接外部工具,在开源模型中保持复杂智能体任务的领先性能
- 支持100+种语言与方言,具备强大的多语言指令跟随与翻译能力
模型概览
Qwen3-235B-A22B 具备以下特性:
- 类型:因果语言模型
- 训练阶段:预训练 & 后训练
- 参数量:总计2350亿,激活220亿
- 非嵌入参数量:2340亿
- 层数:94
- 注意力头数(GQA):查询头64个,键值头4个
- 专家数:128
- 激活专家数:8
- 上下文长度:原生支持32,768 tokens,通过YaRN扩展至131,072 tokens
更多细节(包括基准测试、硬件要求和推理性能)请参阅我们的博客、GitHub和文档。
二、快速开始
Qwen3-MoE 的代码已集成至最新版 Hugging Face transformers
,建议您使用最新版本的 transformers
。
若使用 transformers<4.51.0
版本,将会遇到以下错误:
KeyError: 'qwen3_moe'
以下代码片段展示了如何基于给定输入使用模型生成内容。
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-235B-A22B"
# 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 端点:
SGLang
python -m sglang.launch_server --model-path Qwen/Qwen3-235B-A22B --reasoning-parser qwen3 --tp 8
vLLM
vllm serve Qwen/Qwen3-235B-A22B --enable-reasoning --reasoning-parser deepseek_r1
对于本地使用,Ollama、LMStudio、MLX-LM、llama.cpp 和 KTransformers 等应用程序也已支持 Qwen3。
四、思维模式与非思维模式切换
enable_thinking
开关同样适用于通过 SGLang 和 vLLM 创建的 API。
具体使用方法请参阅 SGLang 和 vLLM 的文档说明。
1、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
中的默认配置)。
切勿使用贪婪解码,否则可能导致性能下降和无限重复。更多详细指导请参阅最佳实践章节。
2、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
参数设置。更多详细指南请参阅最佳实践章节。
3、高级用法:通过用户输入切换思考与非思考模式
我们提供了一种软切换机制,当enable_thinking=True
时,允许用户动态控制模型的行为。具体来说,您可以在用户提示或系统消息中添加/think
和/no_think
指令,实现逐轮切换模型的思考模式。在多轮对话中,模型会遵循最近收到的指令。
以下是一个多轮对话示例:
from transformers import AutoModelForCausalLM, AutoTokenizer
class QwenChatbot:
def __init__(self, model_name="Qwen/Qwen3-235B-A22B"):
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-235B-A22B',
# 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 的框架,通常有两种启用方式:
1、修改模型文件:
在 config.json
文件中添加 rope_scaling
字段:
{
...,
"rope_scaling": {
"rope_type": "yarn",
"factor": 4.0,
"original_max_position_embeddings": 32768
}
}
对于 llama.cpp
,修改后需要重新生成 GGUF 文件。
2、传递命令行参数的方法:
对于 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
如果你遇到以下警告,请升级至 transformers>=4.51.0
。
Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
所有主流开源框架均采用静态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,无需额外配置。
六、最佳实践
为了获得最佳性能,我们推荐以下设置:
1、采样参数:
* For thinking mode (`enable_thinking=True`), use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0`. **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions.
* For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
* For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
2、适当的输出长度:对于大多数查询,我们建议使用32,768个token的输出长度。针对数学和编程竞赛等高复杂度问题的基准测试,建议将最大输出长度设置为38,912个token。这为模型提供了充足空间来生成详细全面的响应,从而提升其整体表现。
3、标准化输出格式:在进行基准测试时,我们建议通过提示词来规范模型的输出格式。
* **Math Problems**: Include "Please reason step by step, and put your final answer within \\boxed{}." in the prompt.
* **Multiple-Choice Questions**: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the `answer` field with only the choice letter, e.g., `"answer": "C"`."
4、历史记录中不包含思考内容:在多轮对话中,历史模型输出应仅包含最终输出部分,无需包含思考过程。该功能已在提供的Jinja2聊天模板中实现。但对于未直接使用Jinja2聊天模板的框架,需要开发者自行确保遵循这一最佳实践。
2025-05-05(一)