模型简介
模型特点
模型能力
使用案例
库名称:transformers
许可证:apache-2.0
许可证链接:https://huggingface.co/Qwen/Qwen3-1.7B/blob/main/LICENSE
流水线标签:文本生成
基础模型:Qwen/Qwen3-1.7B
Qwen3-1.7B-GPTQ-Int8
Qwen3亮点
Qwen3是通义千问系列大语言模型的最新版本,提供密集型和混合专家(MoE)模型的完整套件。基于大规模训练,Qwen3在推理、指令遵循、智能体能力和多语言支持方面实现了突破性进展,主要特点包括:
- 独特支持单一模型内思维模式(用于复杂逻辑推理、数学和编码)与非思维模式(用于高效通用对话)无缝切换,确保各类场景下的最优性能。
- 显著增强推理能力,在数学、代码生成和常识逻辑推理方面超越前代QwQ(思维模式)和Qwen2.5指令模型(非思维模式)。
- 卓越的人类偏好对齐,在创意写作、角色扮演、多轮对话和指令遵循方面表现优异,提供更自然、引人入胜的对话体验。
- 专精智能体能力,可在思维与非思维模式下精准集成外部工具,在开源模型的复杂智能体任务中领先。
- 支持100+种语言和方言,具备强大的多语言指令遵循和翻译能力。
模型概览
Qwen3-1.7B具有以下特性:
-
类型:因果语言模型
-
训练阶段:预训练与后训练
-
参数量:17亿
-
非嵌入参数量:14亿
-
层数:28
-
注意力头数(GQA):查询头16个,键值头8个
-
上下文长度:32,768
-
量化方式:GPTQ 8位
更多细节,包括基准评估、硬件要求和推理性能,请参阅我们的博客、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-1.7B-GPTQ-Int8"
# 加载分词器与模型
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.4
创建OpenAI兼容API端点:
- SGLang:
python -m sglang.launch_server --model-path Qwen/Qwen3-1.7B-GPTQ-Int8 --reasoning-parser qwen3
- vLLM:
vllm serve Qwen/Qwen3-1.7B-GPTQ-Int8 --enable-reasoning --reasoning-parser deepseek_r1
另请参阅GPTQ文档获取更多使用指南。
思维与非思维模式切换
[!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 # 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 # 设为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-1.7B-GPTQ-Int8"):
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()
# 首次输入(无/think或/no_think标签,默认启用思维模式)
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
时,软开关无效。无论用户输入何种标签,模型均不会生成思维内容或包含<think>...</think>
块。
智能体应用
Qwen3在工具调用方面表现卓越。推荐使用Qwen-Agent充分发挥其智能体能力。Qwen-Agent内置工具调用模板和解析器,大幅降低编码复杂度。
定义可用工具时,可使用MCP配置文件、Qwen-Agent集成工具或自行集成其他工具。
from qwen_agent.agents import Assistant
# 定义大语言模型配置
llm_cfg = {
'model': 'Qwen/Qwen3-1.7B-GPTQ-Int8',
# 使用阿里云模型服务端点:
# '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)
性能
模式 | 量化类型 | LiveBench 2024-11-25 | GPQA | MMLU-Redux |
---|---|---|---|---|
思维模式 | bf16 | 51.1 | 40.1 | 73.9 |
思维模式 |


