模型简介
模型特点
模型能力
使用案例
🚀 Qwen3-1.7B-GPTQ-Int8
Qwen3-1.7B-GPTQ-Int8是Qwen系列最新大语言模型,在推理、指令遵循、智能体能力和多语言支持等方面有显著提升,支持思维模式与非思维模式无缝切换。
🚀 快速开始
Qwen3的代码已集成在最新的Hugging Face transformers
库中,建议使用最新版本的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 = "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 # 在思维和非思维模式之间切换。默认为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:
# rindex查找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-1.7B-GPTQ-Int8 --reasoning-parser qwen3
- vLLM:
vllm serve Qwen/Qwen3-1.7B-GPTQ-Int8 --enable-reasoning --reasoning-parser deepseek_r1
更多使用指南请参考GPTQ文档。
✨ 主要特性
Qwen3是Qwen系列的最新一代大语言模型,提供了一套全面的密集模型和专家混合(MoE)模型。基于大量训练,Qwen3在推理、指令遵循、智能体能力和多语言支持方面取得了突破性进展,具有以下关键特性:
- 单模型内独特支持思维模式(用于复杂逻辑推理、数学和编码)和非思维模式(用于高效通用对话)无缝切换,确保在各种场景下都能实现最佳性能。
- 推理能力显著增强,在数学、代码生成和常识逻辑推理方面超越了之前的QwQ(思维模式)和Qwen2.5指令模型(非思维模式)。
- 卓越的人类偏好对齐,在创意写作、角色扮演、多轮对话和指令遵循方面表现出色,提供更自然、引人入胜和沉浸式的对话体验。
- 强大的智能体能力,能够在思维和非思维模式下精确集成外部工具,在复杂的基于智能体的任务中在开源模型中取得领先性能。
- 支持100多种语言和方言,具备强大的多语言指令遵循和翻译能力。
📦 安装指南
此部分文档未提及具体安装步骤,可参考快速开始部分使用相关库和命令。
💻 使用示例
基础用法
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 = "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 # 在思维和非思维模式之间切换。默认为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:
# rindex查找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)
高级用法
思维模式与非思维模式切换
# 思维模式
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # True是enable_thinking的默认值
)
# 非思维模式
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False # 设置enable_thinking=False禁用思维模式
)
通过用户输入切换思维模式
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 = "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("----------------------")
# 第二次输入带/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("----------------------")
# 第三次输入带/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}")
智能体使用
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>this is the thought</think>this is the answer;
# # 不添加:当响应已通过推理内容和内容分开时。
# '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/ Introduce the latest developments of Qwen'}]
for responses in bot.run(messages=messages):
pass
print(responses)
📚 详细文档
模型概述
Qwen3-1.7B 具有以下特点:
属性 | 详情 |
---|---|
模型类型 | 因果语言模型 |
训练阶段 | 预训练和后训练 |
参数数量 | 17亿 |
非嵌入参数数量 | 14亿 |
层数 | 28 |
注意力头数量(GQA) | Q为16,KV为8 |
上下文长度 | 32768 |
量化方式 | GPTQ 8位 |
更多详细信息,包括基准评估、硬件要求和推理性能,请参考博客、GitHub和文档。
思维与非思维模式切换
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>
块中的思维内容,随后是最终响应。
⚠️ 重要提示
对于思维模式,使用
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 # 设置enable_thinking=False禁用思维模式
)
在这种模式下,模型将不会生成任何思维内容,也不会包含<think>...</think>
块。
⚠️ 重要提示
对于非思维模式,建议使用
Temperature=0.7
、TopP=0.8
、TopK=20
和MinP=0
。更多详细指导,请参考最佳实践部分。
高级用法:通过用户输入切换思维和非思维模式
提供了一个软开关机制,允许用户在enable_thinking=True
时动态控制模型的行为。具体来说,可以在用户提示或系统消息中添加/think
和/no_think
来逐轮切换模型的思维模式。模型将遵循多轮对话中的最新指令。
⚠️ 重要提示
对于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的集成工具或自行集成其他工具。
性能
模式 | 量化类型 | LiveBench 2024 - 11 - 25 | GPQA | MMLU - Redux |
---|---|---|---|---|
思维 | bf16 | 51.1 | 40.1 | 73.9 |
思维 | GPTQ - int8 | 49.8 | 39.1 | 74.9 |
非思维 | bf16 | 35.6 | 28.6 | 64.4 |
非思维 | GPTQ - int8 | 35.5 | 28.3 | 63.0 |
最佳实践
为了实现最佳性能,建议进行以下设置:
- 采样参数:
- 对于思维模式(
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
。 - 对于支持的框架,可以在0到2之间调整
presence_penalty
参数以减少无限重复。强烈建议对量化模型将此值设置为1.5。但是,使用较高的值可能偶尔会导致语言混合和模型性能略有下降。
- 对于思维模式(
- 足够的输出长度:对于大多数查询,建议使用32768个标记的输出长度。对于高度复杂问题的基准测试,例如数学和编程竞赛中的问题,建议将最大输出长度设置为38912个标记。这为模型提供了足够的空间来生成详细和全面的响应,从而提高其整体性能。
- 标准化输出格式:在进行基准测试时,建议使用提示来标准化模型输出。
- 数学问题:在提示中包含“请逐步推理,并将最终答案放在\boxed{}内。”
- 多项选择题:在提示中添加以下JSON结构以标准化响应:“请在
answer
字段中仅使用选项字母显示您的选择,例如"answer": "C"
。”
- 历史记录中无思维内容:在多轮对话中,历史模型输出应仅包括最终输出部分,不需要包括思维内容。这在Jinja2提供的聊天模板中已实现。但是,对于不直接使用Jinja2聊天模板的框架,由开发人员确保遵循最佳实践。
引用
如果您认为我们的工作有帮助,请引用:
@misc{qwen3,
title = {Qwen3},
url = {https://qwenlm.github.io/blog/qwen3/},
author = {Qwen Team},
month = {April},
year = {2025}
}
🔧 技术细节
此部分文档未提及具体技术细节。
📄 许可证
本项目采用Apache 2.0许可证,详情请见许可证链接。



