Qwen3系列大语言模型的GPTQ-Int4量化版本,支持思维与非思维模式无缝切换,提升推理、指令遵循和多语言表现,适用于复杂任务与高效对话场景。【此简介由AI生成】
library_name: transformers license: apache-2.0 license_link: https://huggingface.co/Qwen/Qwen3-30B-A3B/blob/main/LICENSE pipeline_tag: text-generation base_model: Qwen/Qwen3-30B-A3B
Qwen3-30B-A3B-GPTQ-Int4
Qwen3 亮点特性
Qwen3 是 Qwen 系列的最新一代大语言模型,提供了全面的密集型和混合专家(MoE)模型套件。经过大规模训练,Qwen3 在推理能力、指令遵循、智能体能力和多语言支持方面实现了突破性进展,主要特性如下:
- 模型内部支持思考模式与非思考模式无缝切换:思考模式适用于复杂逻辑推理、数学和代码任务,非思考模式适用于高效的通用对话,确保在不同场景下均能发挥最佳性能。
- 推理能力显著增强:在思考模式下超越前代 QwQ 模型,在非思考模式下超越 Qwen2.5 指令模型,尤其在数学、代码生成和常识逻辑推理方面表现突出。
- 卓越的人类偏好对齐:在创意写作、角色扮演、多轮对话和指令遵循等任务上表现优异,提供更自然、更具吸引力和沉浸式的对话体验。
- 强大的智能体能力:支持在思考和非思考模式下与外部工具精准集成,在复杂智能体任务中取得开源模型领先性能。
- 支持 100 余种语言和方言:具备强大的多语言指令遵循和翻译能力。
模型概述
Qwen3-30B-A3B 具有以下特性:
- 类型:因果语言模型
- 训练阶段:预训练与后训练
- 参数数量:总计 305 亿,激活参数 33 亿
- 非嵌入参数数量:299 亿
- 层数:48
- 注意力头数(GQA):Q 头 32 个,KV 头 4 个
- 专家数量:128
- 激活专家数量:8
- 上下文长度:原生支持 32,768 tokens,通过 YaRN 可扩展至 131,072 tokens
- 量化方式:GPTQ 4 位
快速入门
Qwen3-MoE 的代码已集成到最新版的 Hugging Face transformers 中,建议您使用最新版本的 transformers。
若使用 transformers<4.51.0,您将遇到以下错误:
KeyError: 'qwen3_moe'
以下是一段代码示例,展示了如何使用模型根据给定输入生成内容。
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-30B-A3B-GPTQ-Int4"
# 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.4 来创建兼容 OpenAI 的 API 端点:
- SGLang:
python -m sglang.launch_server --model-path Qwen/Qwen3-30B-A3B-GPTQ-Int4 --reasoning-parser qwen3 - vLLM:
vllm serve Qwen/Qwen3-30B-A3B-GPTQ-Int4 --enable-reasoning --reasoning-parser deepseek_r1
有关更多使用指南,另请查阅我们的 GPTQ 文档。
思维模式与非思维模式的切换
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>...</RichMediaReference> 块中的思考内容,随后给出最终回应。
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 # Setting enable_thinking=False disables thinking mode
)
在此模式下,模型不会生成任何思考内容,也不会包含 </think>...</RichMediaReference> 块。
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)
# 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}")
Note
为保证 API 兼容性,当 enable_thinking=True 时,无论用户使用 /think 还是 /no_think,模型始终会输出一个用 </think>...</RichMediaReference> 包裹的区块。不过,若思考功能被禁用,该区块内的内容可能为空。
当 enable_thinking=False 时,软开关失效。无论用户输入任何 /think 或 /no_think 标签,模型都不会生成思考内容,也不会包含 </think>...superscript: 区块。
智能体使用
Qwen3 在工具调用能力方面表现出色。我们建议使用 Qwen-Agent 以充分发挥 Qwen3 的智能体能力。Qwen-Agent 内部封装了工具调用模板和工具调用解析器,大幅降低了编码复杂度。
要定义可用工具,您可以使用 MCP 配置文件、使用 Qwen-Agent 的集成工具,或自行集成其他工具。
from qwen_agent.agents import Assistant
# Define LLM
llm_cfg = {
'model': 'Qwen3-30B-A3B-GPTQ-Int4',
# 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 上下文长度下的性能。
目前已有多个推理框架支持 YaRN,例如用于本地使用的 transformers,以及用于部署的 vllm 和 sglang。通常,在支持的框架中启用 YaRN 有两种方法:
-
修改模型文件: 在
config.json文件中,添加rope_scaling字段:{ ..., "rope_scaling": { "rope_type": "yarn", "factor": 4.0, "original_max_position_embeddings": 32768 } } -
通过命令行参数:
对于
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}}'
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,无需额外配置。
性能表现
| 模式 | 量化类型 | LiveBench 2024-11-25 | GPQA | MMLU-Redux | AIME24 |
|---|---|---|---|---|---|
| Thinking | bf16 | 74.3 | 65.8 | 89.5 | 80.4 |
| Thinking | GPTQ-int4 | 71.5 | 60.1 | 88.8 | 79.5 |
| Non-Thinking | bf16 | 59.4 | 54.8 | 84.1 | - |
| Non-Thinking | GPTQ-int4 | 57.2 | 50.4 | 83.5 | - |
最佳实践
为获得最佳性能,我们建议采用以下设置:
-
采样参数:
- 对于思考模式(
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 之间调整,以减少无限重复。我们强烈建议将量化模型的此值设置为 1.5。不过,使用更高的值偶尔可能导致语言混用,并使模型性能略有下降。
- 对于思考模式(
-
足够的输出长度:我们建议大多数查询使用 32,768 个 tokens 的输出长度。对于高度复杂问题的基准测试,例如数学和编程竞赛中的题目,建议将最大输出长度设置为 38,912 个 tokens。这为模型提供了足够的空间来生成详细且全面的响应,从而提升其整体性能。
-
标准化输出格式:在进行基准测试时,建议使用提示词来标准化模型输出。
- 数学问题:在提示词中包含“请逐步推理,并将最终答案放在 \boxed{} 内。”
- 多项选择题:在提示词中添加以下 JSON 结构以标准化响应:“请在
answer字段中仅用选项字母展示您的选择,例如:"answer": "C"。”
-
历史记录中不包含思考内容:在多轮对话中,历史模型输出应仅包含最终输出部分,无需包含思考内容。这在提供的 Jinja2 对话模板中已实现。但对于未直接使用 Jinja2 对话模板的框架,需由开发人员确保遵循此最佳实践。
引用
如果您觉得我们的工作对您有所帮助,欢迎引用我们的成果。
@misc{qwen3technicalreport,
title={Qwen3 Technical Report},
author={Qwen Team},
year={2025},
eprint={2505.09388},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2505.09388},
}