模型简介
模型特点
模型能力
使用案例
库名称:transformers
许可证:apache-2.0
许可证链接:https://huggingface.co/Qwen/Qwen3-4B/blob/main/LICENSE
任务标签:文本生成
基础模型:
- Qwen/Qwen3-4B-Base
Qwen3-4B
Qwen3 亮点
Qwen3 是通义千问系列大语言模型的最新版本,提供密集型和混合专家(MoE)模型的完整套件。基于大规模训练,Qwen3 在推理、指令遵循、智能体能力和多语言支持方面实现了突破性进展,主要特点包括:
- 独特支持单一模型内思维模式(用于复杂逻辑推理、数学和编程)与非思维模式(用于高效通用对话)无缝切换,确保各类场景下的最佳性能。
- 显著增强的推理能力,在数学、代码生成和常识逻辑推理方面超越前代 QwQ(思维模式)和 Qwen2.5 指令模型(非思维模式)。
- 卓越的人类偏好对齐,在创意写作、角色扮演、多轮对话和指令遵循方面表现优异,提供更自然、引人入胜的对话体验。
- 专业的智能体能力,支持在思维与非思维模式下精准集成外部工具,在开源模型的复杂智能体任务中领先。
- 支持 100+ 种语言和方言,具备强大的多语言指令遵循和翻译能力。
模型概览
Qwen3-4B 具有以下特性:
- 类型:因果语言模型
- 训练阶段:预训练与后训练
- 参数量:4.0B
- 非嵌入参数量:3.6B
- 层数:36
- 注意力头数(GQA):Q 为 32,KV 为 8
- 上下文长度:原生支持 32,768,通过 YaRN 扩展至 131,072 tokens。
更多细节(包括基准评估、硬件要求和推理性能)请参考我们的博客、GitHub 和文档。
[!TIP]
若遇到严重重复生成问题,请参考最佳实践优化采样参数,并将presence_penalty
设为 1.5。
快速开始
Qwen3 的代码已集成至最新版 Hugging Face transformers
,建议使用最新版本。
若使用 transformers<4.51.0
,将报错:
KeyError: 'qwen3'
以下代码示例展示如何基于给定输入生成内容:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-4B"
# 加载分词器与模型
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
# 准备模型输入
prompt = "简要介绍大语言模型。"
messages = [
{"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # 切换思维/非思维模式,默认为 True
)
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
# 执行文本补全
generated_ids = model.generate(
**model_inputs,
max_new_tokens=32768
)
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
# 解析思维内容
try:
# 反向查找 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)
print("回复内容:", content)
部署时,可使用 sglang>=0.4.6.post1
或 vllm>=0.8.5
创建 OpenAI 兼容的 API 端点:
- SGLang:
python -m sglang.launch_server --model-path Qwen/Qwen3-4B --reasoning-parser qwen3
- vLLM:
vllm serve Qwen/Qwen3-4B --enable-reasoning --reasoning-parser deepseek_r1
本地使用支持 Ollama、LMStudio、MLX-LM、llama.cpp 和 KTransformers。
思维与非思维模式切换
[!TIP]
enable_thinking
开关也适用于 SGLang 和 vLLM 创建的 API。
详见 SGLang 和 vLLM 文档。
enable_thinking=True
默认启用思维模式(类似 QwQ-32B),模型将运用推理能力提升生成质量。例如显式设置 enable_thinking=True
或使用默认值时:
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # 默认值
)
此模式下,模型会生成包裹在 <think>...</think>
中的思维内容,后接最终回复。
[!NOTE]
思维模式建议使用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 # 禁用思维模式
)
此模式下,模型不会生成 <think>...</think>
内容。
[!NOTE]
非思维模式建议使用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-4B"):
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)
# 更新历史
self.history.append({"role": "user", "content": user_input})
self.history.append({"role": "assistant", "content": response})
return response
# 使用示例
if __name__ == "__main__":
chatbot = QwenChatbot()
# 首次输入(无标签,默认启用思维模式)
user_input_1 = "strawberries 中有几个 r?"
print(f"用户:{user_input_1}")
response_1 = chatbot.generate_response(user_input_1)
print(f"助手:{response_1}")
print("----------------------")
# 第二次输入带 /no_think
user_input_2 = "blueberries 中有几个 r? /no_think"
print(f"用户:{user_input_2}")
response_2 = chatbot.generate_response(user_input_2)
print(f"助手:{response_2}")
print("----------------------")
# 第三次输入带 /think
user_input_3 = "真的吗? /think"
print(f"用户:{user_input_3}")
response_3 = chatbot.generate_response(user_input_3)
print(f"助手:{response_3}")
[!NOTE]
为兼容 API,当enable_thinking=True
时,无论用户使用/think
或/no_think
,模型总会输出<think>...</think>
包裹块(禁用思维时内容可能为空)。
当enable_thinking=False
时,软开关无效,模型不会生成思维内容。
智能体应用
Qwen3 在工具调用方面表现卓越,推荐使用 Qwen-Agent 最大化其能力。Qwen-Agent 封装了工具调用模板和解析器,大幅降低编码复杂度。
定义可用工具可通过 MCP 配置文件、集成工具或自定义工具实现:
from qwen_agent.agents import Assistant
# 定义 LLM
llm_cfg = {
'model': 'Qwen3-4B',
# 使用阿里云灵积端点:
# 'model_type': 'qwen_dashscope',
# 'api_key': os.getenv('DASHSCOPE_API_KEY'),
# 使用兼容 OpenAI API 的自定义端点:
'model_server': 'http://localhost:8000/v1', # api_base
'api_key': 'EMPTY',
# 其他参数:
# 'generate_cfg': {
# # 添加:当响应含 `<think>思考内容</think>回复`
# # 不添加:当响应已分离为 reasoning_content 和 content
# 'thought_in_content': True,
# },
}
# 定义工具
tools = [
{'mcpServers': { # 指定 MCP 配置文件
'time': {
'command': 'uvx',
'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
},
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
}
},
'code_interpreter', # 内置工具
]
# 定义智能体
bot = Assistant(llm=llm_cfg, function_list=tools)
# 流式生成
messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ 介绍 Qwen 最新进展'}]
for responses in bot.run(messages=messages):
pass
print(responses)
处理长文本
Qwen3 原生支持 32,768 tokens 上下文长度。若输入输出总长度远超此限制,推荐使用 RoPE 缩放技术(如 YaRN)扩展至 131,072 tokens。
YaRN 当前支持 transformers
、llama.cpp
(本地)、vllm
和 sglang
(部署)。启用方式有两种:
-
修改模型文件:
在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 ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
- vLLM:
[!IMPORTANT]
若出现警告:Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
请升级至
transformers>=4.51.0
。
[!NOTE]
主流开源框架均实现静态 YaRN,缩放因子固定,可能影响短文本性能。
建议仅在处理长文本时启用,并根据典型上下文长度调整factor
(如 65,536 tokens 时设为 2.0)。
[!NOTE]
config.json
中默认max_position_embeddings
为 40,960(保留 32,768 tokens 输出 + 8,192 tokens 典型输入)。若平均上下文长度不超 32,768 tokens,不建议启用 YaRN。
[!TIP]
阿里云灵积端点默认支持动态 YaRN,无需额外配置。
最佳实践
推荐以下设置以获得最优性能:
-
采样参数:
- 思维模式:
Temperature=0.6
、TopP=0.95
、TopK=20
、MinP=0
,禁用贪心解码。 - 非思维模式:
Temperature=0.7
、TopP=0.8
、TopK=20
、MinP=0
。 - 支持框架中,
presence_penalty
设为 0-2 可减少重复(过高可能导致语言混杂)。
- 思维模式:
-
充足输出长度:
- 常规查询建议 32,768 tokens。
- 数学/编程竞赛等复杂问题建议 38,912 tokens。
-
标准化输出格式:
- 数学题:提示中加入“请逐步推理,并将最终答案放入 \boxed{}。”
- 选择题:提示中加入 JSON 结构如
"answer": "C"
。
-
历史记录不含思维内容:多轮对话中,历史输出应仅含最终回复(Jinja2 模板已实现,其他框架需开发者确保)。
引用
如果觉得我们的工作有帮助,欢迎引用:
@misc{qwen3,
title = {Qwen3},
url = {https://qwenlm.github.io/blog/qwen3/},
author = {Qwen Team},
month = {April},
year = {2025}
}


