HuggingFace镜像/Qwen3-0.6B-FP8
模型介绍文件和版本分析
下载使用量0

Qwen3-0.6B-FP8

Chat

Qwen3 核心亮点

Qwen3 是通义千问系列大语言模型的最新版本,提供从稠密模型到混合专家(MoE)模型的完整产品矩阵。基于海量训练数据构建的 Qwen3,在推理能力、指令遵循、智能体功能及多语言支持方面实现突破性进展,主要特性包括:

  • 独创性支持单模型内思维模式(适用于复杂逻辑推理、数学与代码生成)与非思维模式(适用于高效通用对话)无缝切换,确保各类场景下的最优表现。
  • 推理能力显著增强,在数学运算、代码生成和常识逻辑推理任务上,全面超越前代 QwQ(思维模式)与 Qwen2.5 指令模型(非思维模式)。
  • 更优的人类偏好对齐,在创意写作、角色扮演、多轮对话及指令遵循方面表现卓越,提供更自然、生动且富有沉浸感的交互体验。
  • 专业级智能体能力,支持思维与非思维模式下精准调用外部工具,在开源模型的复杂智能体任务中保持领先性能。
  • 支持 100+ 种语言与方言,具备强大的多语言指令理解与翻译能力。

模型概览

本仓库为 Qwen3-0.6B 的 FP8 量化版本,具有以下特性:

  • 模型类型:因果语言模型
  • 训练阶段:预训练 & 后训练
  • 参数量:0.6B
  • 非嵌入参数量:0.44B
  • 层数:28
  • 注意力头数(GQA):查询头16个,键值头8个
  • 上下文长度:32,768

更多技术细节(包括基准测试、硬件需求及推理性能)请参阅我们的博客、GitHub 和文档。

[!TIP] 若出现严重重复生成现象,请参考最佳实践章节调整采样参数,建议将 presence_penalty 设为 1.5。

快速开始

Qwen3 的代码已集成至最新版 Hugging Face transformers,建议使用 transformers 的最新版本。

若使用 transformers<4.51.0 版本,您将遇到以下报错:

KeyError: 'qwen3'

以下代码片段展示了如何基于给定输入使用模型生成内容。

from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen3-0.6B-FP8"

# 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.5 创建兼容 OpenAI 的 API 端点:

  • SGLang:
    python -m sglang.launch_server --model-path Qwen/Qwen3-0.6B-FP8 --reasoning-parser qwen3
  • vLLM:
    vllm serve Qwen/Qwen3-0.6B-FP8 --enable-reasoning --reasoning-parser deepseek_r1

本地使用时,Ollama、LMStudio、MLX-LM、llama.cpp 和 KTransformers 等应用也已支持 Qwen3。

关于 FP8 的说明

为方便使用并提升性能,我们为 Qwen3 提供了 fp8 量化的模型检查点,其名称以 -FP8 结尾。量化方法为细粒度 fp8 量化,块大小为 128。您可以在 config.json 的 quantization_config 字段中找到更多细节。

您可以在 transformers、sglang 和 vllm 等推理框架中使用 Qwen3-0.6B-FP8 模型,就像使用原始的 bfloat16 模型一样。 但请注意以下已知问题:

  • transformers:
    • 目前 transformers 在分布式推理中对“细粒度 fp8”方法存在一些问题。如果在推理中使用多设备,可能需要设置环境变量 CUDA_LAUNCH_BLOCKING=1。

切换思考与非思考模式

[!TIP] enable_thinking 开关也适用于 SGLang 和 vLLM 创建的 API。 请参阅我们的文档了解 SGLang 和 vLLM 用户的使用方法。

enable_thinking=True

默认情况下,Qwen3 启用了思考能力,类似于 QwQ-32B。这意味着模型会利用其推理能力提升生成回答的质量。例如,当显式设置 enable_thinking=True 或在 tokenizer.apply_chat_template 中保留默认值时,模型会进入思考模式。

text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=True  # True is the default value for enable_thinking
)

在此模式下,模型会生成包裹在 <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  # Setting enable_thinking=False disables thinking mode
)

在此模式下,模型不会生成任何思考内容,也不会包含 <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-0.6B-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)

        # 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}")

[!注意] 出于 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

# Define LLM
llm_cfg = {
    'model': 'Qwen3-0.6B-FP8',

    # 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)

最佳实践

为获得最佳性能,我们推荐以下设置:

  1. 采样参数:

    • 思考模式(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 之间的值以减少无限重复。但数值过高可能偶尔导致语言混杂或模型性能轻微下降。
  2. 充足的输出长度:

    • 对于大多数查询,建议输出长度为 32,768 个 token。
    • 针对高复杂度问题的基准测试(如数学或编程竞赛题目),建议将最大输出长度设为 38,912 个 token。这能为模型提供充分空间生成详细且全面的回答,从而提升整体表现。
  3. 标准化输出格式:

    • 数学问题:在提示词中加入“请逐步推理,并将最终答案置于 \boxed{} 中。”
    • 选择题:在提示词中添加以下 JSON 结构以标准化回答:“请在 answer 字段中仅填写选项字母,例如 "answer": "C"。”
  4. 历史记录中不含思考内容:

    • 在多轮对话中,历史模型输出应仅包含最终回答部分,无需包含思考内容。该功能已在提供的 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}, 
}