Q
Qwen/Qwen3-1.7B-MLX-8bit
模型介绍文件和版本分析
下载使用量0

Qwen3-1.7B

Chat

Qwen3 亮点特性

Qwen3 是 Qwen 系列的最新一代大语言模型,提供了全面的密集型和混合专家(MoE)模型套件。经过大规模训练,Qwen3 在推理能力、指令遵循、智能体能力和多语言支持方面实现了突破性进展,主要特点如下:

  • 支持在单一模型内无缝切换思考模式(适用于复杂逻辑推理、数学和编码任务)和非思考模式(适用于高效的通用对话),确保在不同场景下均能发挥最佳性能。
  • 推理能力显著增强,在数学、代码生成和常识逻辑推理任务上超越了前代 QwQ(思考模式下)和 Qwen2.5 指令模型(非思考模式下)。
  • 卓越的人类偏好对齐,在创意写作、角色扮演、多轮对话和指令遵循方面表现出色,提供更自然、更具吸引力和沉浸感的对话体验。
  • 强大的智能体能力,支持在思考和非思考模式下与外部工具精准集成,在复杂智能体任务中取得开源模型领先性能。
  • 支持 100 余种语言及方言,具备强大的多语言指令遵循和翻译能力。

模型概述

Qwen3-1.7B 具有以下特性:

  • 类型:因果语言模型
  • 训练阶段:预训练与后训练
  • 参数数量:1.7B
  • 非嵌入层参数数量:1.4B
  • 层数:28
  • 注意力头数(GQA):Q 头 16 个,KV 头 8 个
  • 上下文长度:32,768

更多详情,包括基准测试评估、硬件要求和推理性能,请参阅我们的 博客、GitHub 和 文档。

快速入门

Qwen3 的代码已包含在 transformers(≥4.52.4 版本) 和 mlx_lm(≥0.25.2 版本) 的最新版本中,建议使用最新版的 transformers 和 mlx_lm。 旧版本(例如 transformers<4.51.0)可能会引发如下错误:

KeyError: 'qwen3'

安装或升级这两个软件包:

pip install --upgrade transformers mlx_lm

以下是一个代码片段,展示了如何使用模型根据给定输入生成内容。

from mlx_lm import load, generate

model, tokenizer = load("Qwen/Qwen3-1.7B-MLX-8bit")
prompt = "Hello, please introduce yourself and tell me what you can do."

if tokenizer.chat_template is not None:
    messages = [{"role": "user", "content": prompt}]
    prompt = tokenizer.apply_chat_template(
        messages,
        add_generation_prompt=True
    )

response = generate(
    model,
    tokenizer,
    prompt=prompt,
    verbose=True,
    max_tokens=1024
)

print(response)

在思考模式与非思考模式之间切换

[!TIP] enable_thinking 开关在由 SGLang 和 vLLM 创建的 API 中同样可用。 SGLang 用户和 vLLM 用户请分别参考我们的文档 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  # True is the default value for enable_thinking
)

在此模式下,模型会先生成包裹在 </think>...superscript: 块中的思考内容,随后给出最终响应。

[!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 mlx_lm import load, generate


class QwenChatbot:
    def __init__(self, model_name="Qwen/Qwen3-1.7B-MLX-8bit"):
        self.model, self.tokenizer = load(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
        )

        response = generate(
            self.model,
            self.tokenizer,
            prompt=text,
            verbose=True,
            max_tokens=32768
        )
        # 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 are 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 are 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-1.7B-MLX-8bit",

    # 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 个 tokens 的输出长度。在数学和编程竞赛等高度复杂问题的基准测试中,建议将最大输出长度设置为 38,912 个 tokens。这为模型生成详细且全面的响应提供了足够的空间,从而提升其整体性能。

  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}, 
}