模型简介
模型特点
模型能力
使用案例
🚀 Qwen3-4B-FP8
Qwen3-4B-FP8是Qwen3-4B的FP8版本模型,具备强大的推理、多语言支持等能力,能带来自然流畅的对话体验。
🚀 快速开始
Qwen3的代码已集成在最新的Hugging Face transformers
库中,建议使用最新版本的 transformers
。
若使用 transformers<4.51.0
,会遇到如下错误:
KeyError: 'qwen3'
以下代码片段展示了如何基于给定输入使用该模型生成内容:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-4B-FP8"
# 加载分词器和模型
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.5
创建兼容OpenAI的API端点:
- SGLang:
python -m sglang.launch_server --model-path Qwen/Qwen3-4B-FP8 --reasoning-parser qwen3
- vLLM:
vllm serve Qwen/Qwen3-4B-FP8 --enable-reasoning --reasoning-parser deepseek_r1
对于本地使用,Ollama、LMStudio、MLX-LM、llama.cpp和KTransformers等应用程序也已支持Qwen3。
✨ 主要特性
Qwen3亮点
Qwen3是Qwen系列的最新一代大语言模型,提供了一套全面的密集模型和混合专家(MoE)模型。基于大量训练,Qwen3在推理、指令遵循、智能体能力和多语言支持方面取得了突破性进展,具有以下关键特性:
- 独特支持在单个模型内无缝切换“思考模式”(用于复杂逻辑推理、数学和编码)和“非思考模式”(用于高效的通用对话),确保在各种场景下都能实现最佳性能。
- 推理能力显著增强,在数学、代码生成和常识逻辑推理方面超越了之前的QwQ(思考模式)和Qwen2.5指令模型(非思考模式)。
- 高度符合人类偏好,在创意写作、角色扮演、多轮对话和指令遵循方面表现出色,提供更自然、引人入胜和沉浸式的对话体验。
- 具备强大的智能体能力,能够在思考和非思考模式下精确集成外部工具,并在复杂的基于智能体的任务中在开源模型中取得领先性能。
- 支持100多种语言和方言,具备强大的多语言指令遵循和翻译能力。
📦 模型概述
本仓库包含 Qwen3-4B 的FP8版本,具有以下特点:
属性 | 详情 |
---|---|
模型类型 | 因果语言模型 |
训练阶段 | 预训练和后训练 |
参数数量 | 40亿 |
参数数量(非嵌入层) | 36亿 |
层数 | 36 |
注意力头数量(GQA) | Q为32,KV为8 |
上下文长度 | 原生支持32,768个token,使用YaRN可支持131,072个token |
更多详细信息,包括基准评估、硬件要求和推理性能,请参考我们的博客、GitHub和文档。
⚠️ 重要提示
如果遇到严重的无限重复问题,请参考最佳实践部分获取最佳采样参数,并将
presence_penalty
设置为1.5。
💻 使用示例
基础用法
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-4B-FP8"
# 加载分词器和模型
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)
高级用法
思考模式与非思考模式切换
from transformers import AutoModelForCausalLM, AutoTokenizer
class QwenChatbot:
def __init__(self, model_name="Qwen/Qwen3-4B-FP8"):
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': 'Qwen3-4B-FP8',
# 使用阿里云魔搭平台提供的端点:
# '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)
🔧 FP8说明
为了方便使用和提高性能,我们为Qwen3提供了以 -FP8
结尾的 fp8
量化模型检查点。量化方法是块大小为128的细粒度 fp8
量化。你可以在 config.json
文件的 quantization_config
字段中找到更多详细信息。
可以使用包括 transformers
、sglang
和 vllm
在内的多个推理框架,像使用原始的bfloat16模型一样使用Qwen3-4B-FP8模型。
然而,请注意以下已知问题:
transformers
:- 目前
transformers
中的“细粒度fp8”方法在分布式推理中存在问题。如果在推理中使用多个设备,可能需要设置环境变量CUDA_LAUNCH_BLOCKING=1
。
- 目前
🔧 思考模式与非思考模式切换
💡 使用建议
SGLang和vLLM创建的API也支持
enable_thinking
开关。请参考我们为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>
块中的思考内容,然后是最终响应。
⚠️ 重要提示
对于思考模式,请使用
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
来逐轮切换模型的思考模式。在多轮对话中,模型将遵循最新的指令。
以下是一个多轮对话的示例:
from transformers import AutoModelForCausalLM, AutoTokenizer
class QwenChatbot:
def __init__(self, model_name="Qwen/Qwen3-4B-FP8"):
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}")
⚠️ 重要提示
为了保证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的集成工具或自行集成其他工具。
from qwen_agent.agents import Assistant
# 定义大语言模型
llm_cfg = {
'model': 'Qwen3-4B-FP8',
# 使用阿里云魔搭平台提供的端点:
# '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原生支持高达32,768个token的上下文长度。对于总长度(包括输入和输出)显著超过此限制的对话,建议使用RoPE缩放技术来有效处理长文本。我们使用YaRN方法验证了模型在长达131,072个token的上下文长度上的性能。
目前,YaRN得到了多个推理框架的支持,例如本地使用的 transformers
和 llama.cpp
,以及用于部署的 vllm
和 sglang
。一般来说,对于支持的框架,有两种启用YaRN的方法:
-
修改模型文件: 在
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
,可以使用:llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
⚠️ 重要提示
如果遇到以下警告:
Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
请升级
transformers>=4.51.0
。
⚠️ 重要提示
所有著名的开源框架都实现了静态YaRN,这意味着缩放因子无论输入长度如何都保持不变,可能会影响较短文本的性能。 建议仅在需要处理长上下文时添加
rope_scaling
配置。 也建议根据需要修改factor
。例如,如果应用程序的典型上下文长度为65,536个token,最好将factor
设置为2.0。
⚠️ 重要提示
config.json
中的默认max_position_embeddings
设置为40,960。此分配包括为输出保留32,768个token和为典型提示保留8,192个token,这对于大多数短文本处理场景来说已经足够。如果平均上下文长度不超过32,768个token,不建议在这种情况下启用YaRN,因为这可能会降低模型性能。
💡 使用建议
阿里云魔搭平台提供的端点默认支持动态YaRN,无需额外配置。
🔧 最佳实践
为了实现最佳性能,建议进行以下设置:
-
采样参数:
- 对于思考模式(
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
参数以减少无限重复。但是,使用较高的值可能偶尔会导致语言混合和模型性能略有下降。
- 对于思考模式(
-
足够的输出长度:对于大多数查询,建议使用32,768个token的输出长度。对于高度复杂问题的基准测试,如数学和编程竞赛中的问题,建议将最大输出长度设置为38,912个token。这为模型提供了足够的空间来生成详细和全面的响应,从而提高其整体性能。
-
标准化输出格式:在进行基准测试时,建议使用提示来标准化模型输出。
- 数学问题:在提示中包含 “Please reason step by step, and put your final answer within \boxed{}.”。
- 选择题:在提示中添加以下JSON结构以标准化响应:“Please show your choice in the
answer
field with only the choice letter, e.g.,"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},
}
📄 许可证
本项目采用 Apache-2.0 许可证。



