库名称:transformers
许可证:apache-2.0
许可证链接:https://huggingface.co/Qwen/Qwen3-30B-A3B/blob/main/LICENSE
任务标签:文本生成
基础模型:Qwen/Qwen3-30B-A3B
Qwen3-30B-A3B-GPTQ-Int4
Qwen3 亮点
Qwen3 是通义千问系列大语言模型的最新版本,提供稠密模型与混合专家(MoE)模型的完整组合。基于大规模训练,Qwen3 在推理、指令遵循、智能体能力和多语言支持方面实现了突破性进展,主要特性包括:
- 独特支持单模型内思维模式(用于复杂逻辑推理、数学和代码)与非思维模式(高效通用对话)的无缝切换,确保各类场景下的最优表现。
- 显著增强的推理能力,在数学、代码生成和常识逻辑推理任务上超越前代 QwQ(思维模式)和 Qwen2.5 指令模型(非思维模式)。
- 卓越的人类偏好对齐,在创意写作、角色扮演、多轮对话和指令遵循方面表现优异,提供更自然、引人入胜的对话体验。
- 专业的智能体能力,支持思维与非思维模式下与外部工具精准集成,在开源模型的复杂智能体任务中达到领先水平。
- 支持 100+ 种语言和方言,具备强大的多语言指令遵循与翻译能力。
模型概览
Qwen3-30B-A3B 特性:
- 类型:因果语言模型
- 训练阶段:预训练 & 后训练
- 参数量:总计 30.5B,激活 3.3B
- 非嵌入参数量:29.9B
- 层数:48
- 注意力头数(GQA):Q 头 32,KV 头 4
- 专家数:128
- 激活专家数:8
- 上下文长度:原生支持 32,768 词元,通过 YaRN 扩展至 131,072 词元。
- 量化方式:GPTQ 4-bit
更多细节(包括基准测试、硬件需求和推理性能)请参阅博客、GitHub 和文档。
快速开始
Qwen3-MoE 代码已集成至最新版 Hugging Face transformers
,建议使用最新版本。
若使用 transformers<4.51.0
将报错:
KeyError: 'qwen3_moe'
以下代码示例展示如何基于给定输入生成内容:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-30B-A3B-GPTQ-Int4"
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
)
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:
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.4
创建 OpenAI 兼容 API 端点:
更多使用指南请参阅 GPTQ 文档。
思维与非思维模式切换
[!TIP]
enable_thinking
开关同样适用于 SGLang 和 vLLM 创建的 API。
具体配置请参考 SGLang 和 vLLM 文档。
enable_thinking=True
默认启用思维模式(类似 QwQ-32B),模型将运用推理能力提升生成质量。例如显式设置 enable_thinking=True
或保持 tokenizer.apply_chat_template
默认值时:
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-30B-A3B-GPTQ-Int4"):
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 = "草莓中有多少个字母 r?"
print(f"用户:{user_input_1}")
response_1 = chatbot.generate_response(user_input_1)
print(f"助手:{response_1}")
print("----------------------")
user_input_2 = "蓝莓中有多少个字母 r? /no_think"
print(f"用户:{user_input_2}")
response_2 = chatbot.generate_response(user_input_2)
print(f"助手:{response_2}")
print("----------------------")
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 配置文件、Qwen-Agent 集成工具或自定义工具:
from qwen_agent.agents import Assistant
llm_cfg = {
'model': 'Qwen3-30B-A3B-GPTQ-Int4',
'model_server': 'http://localhost:8000/v1',
'api_key': 'EMPTY',
}
tools = [
{'mcpServers': {
'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 词元的上下文长度。若输入输出总长远超此限制,推荐使用 RoPE 缩放技术。我们已通过 YaRN 方法验证模型在 131,072 词元长度下的性能。
当前 transformers
(本地使用)、vllm
和 sglang