g
gcw_yatvyzfH/11
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Qwen3-8B-MLX-4bit

Chat

昇腾 NPU 适配验证报告

本仓库为 MLX 4-bit 量化格式 (bits=4, group_size=128) 的 Qwen3-8B 模型,专为 Apple Silicon (MLX 框架) 优化。

要在 华为昇腾 NPU 上使用 vLLM-Ascend 部署,需先将权重从 MLX 4-bit 格式转换为标准 HuggingFace BF16 格式。

环境配置

环境详情
操作系统aarch64 Linux (Kunpeng 920)
NPU 设备2× Ascend 910B2 (Ascend910_9362, 64GB HBM)
CANN 版本8.5.1
PyTorch2.9.0+cpu
torch_npu2.9.0.post1
vLLM / vLLM-Ascend0.18.0 / 0.18.0rc1
Transformers4.57.6

推理精度对比 (NPU vs CPU)

基线说明:使用 PyTorch CPU (float32) 作为调试基线。官方未提供 Qwen3-8B MLX 版本的 GPU/CPU 基线,本次对比旨在验证 NPU 与标准 PyTorch 推理框架的数值一致性。该 CPU 对比结果仅用于调试,不作为最终精度对齐结论。

测试设置

参数值
解码方式Greedy (do_sample=False, temperature=0.0)
NPU 精度bfloat16 (torch_npu)
CPU 精度float32 (PyTorch)
测试 prompt2 组,覆盖问答和知识类场景
生成长度5 tokens (用于 logits 级精确对比)
词汇表大小151,936

数值误差统计

指标Prompt Logits (last token)Generated Logits (10 steps)
最大绝对误差 (Max abs diff)0.3010650.419620
平均绝对误差 (Mean abs diff)0.0638900.041722
RMSE (均方根误差)0.0745150.062187
Cosine Similarity (余弦相似度)0.9997490.999823
Token prediction argmax 匹配率—100.0% (10/10)

逐 Token 对比详情

PromptStepNPU Token IDCPU Token IDMax Logit DiffArgmax Match
"Hello, what is 2+3?"17281 (▁Also)72810.210984✓
211 (,)110.171724✓
31128 (▁what)11280.220845✓
4374 (▁is)3740.115605✓
5220 (▁)2200.101952✓
"The capital of France is"112095 (▁Paris)120950.301065✓
213 (.)130.191311✓
3576 (▁The)5760.419620✓
46722 (▁capital)67220.293782✓
5315 (▁of)3150.236840✓

生成文本对比

PromptNPU (bf16) 输出CPU (fp32) 输出
"Hello, what is 2+3?"" Also, what is "" Also, what is "
"The capital of France is"" Paris. The capital of"" Paris. The capital of"

精度结论

  • Token 预测匹配率: 100.0% — NPU 与 CPU 在 greedy 解码下的输出完全一致
  • Cosine Similarity: 0.999749 — logits 分布高度一致
  • 平均相对误差: ~0.0004% — 远低于 1% 的验收阈值
  • 误差来源: NPU 使用 bfloat16(7 位尾数),CPU 使用 float32(23 位尾数),这是预期的精度截断差,不影响生成质量
  • 最终判定: ✅ PASS — NPU 推理精度与 PyTorch 标准推理框架一致

推理性能 Benchmark

输入长度输出长度平均延迟 (s)吞吐量 (tok/s)
32321.70018.8
32643.35819.1
64321.68419.0
64643.38418.9
128321.75818.2

性能分析:

  • 平均吞吐: ~18.8 tok/s (Qwen3-4B, Ascend 910B2 单卡)
  • 延迟主要与输出长度成正比,与输入长度关系较小 (prefill 时间占比低)
  • torch_npu eager 模式推理,未使用 vLLM 的 PagedAttention 优化

模型转换指南

转换方式选择

方式说明依赖
A — MLX 反量化在 macOS 上运行 MLX 反量化脚本,输出 BF16macOS + MLX
B — 下载标准权重直接从 ModelScope 下载标准 Qwen3-8B 权重网络 (~16GB)

方式 A: MLX 反量化 (推荐)

在 macOS (Apple Silicon) 上执行:

# 1. 安装依赖
pip install mlx-lm transformers safetensors torch

# 2. 运行反量化脚本 (已包含在本仓库)
python dequantize_mlx.py \
    --input /path/to/Qwen3-8B-MLX-4bit \
    --output /path/to/Qwen3-8B-BF16

方式 B: 下载标准权重

在任意机器上执行:

pip install modelscope
python -c "
from modelscope import snapshot_download
model_dir = snapshot_download('Qwen/Qwen3-8B', cache_dir='./Qwen3-8B-BF16')
print('下载完成:', model_dir)
"

部署到 vLLM-Ascend (转换后)

# 安装 vLLM-Ascend
pip install vllm vllm-ascend

# 启动推理服务 (Atlas A2/A3 单卡)
vllm serve /path/to/Qwen3-8B-BF16 \
    --tensor-parallel-size 1 \
    --max-model-len 8192 \
    --dtype bfloat16 \
    --gpu-memory-utilization 0.9 \
    --trust-remote-code

# 测试推理
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "/path/to/Qwen3-8B-BF16",
    "messages": [{"role": "user", "content": "Hello!"}],
    "max_tokens": 100
  }'

config.json 说明

本仓库的 config.json 已移除 MLX 特有的 quantization 和 quantization_config 字段,可直接用于转换后的 BF16 模型。

验证脚本

本仓库提供以下验证脚本:

脚本说明
dequantize_mlx.pyMLX 4-bit → BF16 反量化脚本
accuracy_test.pyNPU vs CPU 精度对齐测试 (带 logits 级数值对比)
results/验证结果目录 (精度数据 + 性能数据)

Qwen3 Highlights

Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support, with the following key features:

  • Uniquely support of seamless switching between thinking mode (for complex logical reasoning, math, and coding) and non-thinking mode (for efficient, general-purpose dialogue) within single model, ensuring optimal performance across various scenarios.
  • Significantly enhancement in its reasoning capabilities, surpassing previous QwQ (in thinking mode) and Qwen2.5 instruct models (in non-thinking mode) on mathematics, code generation, and commonsense logical reasoning.
  • Superior human preference alignment, excelling in creative writing, role-playing, multi-turn dialogues, and instruction following, to deliver a more natural, engaging, and immersive conversational experience.
  • Expertise in agent capabilities, enabling precise integration with external tools in both thinking and unthinking modes and achieving leading performance among open-source models in complex agent-based tasks.
  • Support of 100+ languages and dialects with strong capabilities for multilingual instruction following and translation.

Model Overview

Qwen3-8B has the following features:

  • Type: Causal Language Models
  • Training Stage: Pretraining & Post-training
  • Number of Parameters: 8.2B
  • Number of Paramaters (Non-Embedding): 6.95B
  • Number of Layers: 36
  • Number of Attention Heads (GQA): 32 for Q and 8 for KV
  • Context Length: 32,768 natively and 131,072 tokens with YaRN.

For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our blog, GitHub, and Documentation.

Quickstart

The code of Qwen3 has been in the latest versions of both transformers (≥ 4.52.4) and mlx_lm (≥ 0.25.2), and we advise you to use the latest version of transformers and mlx_lm. Older versions (e.g., transformers<4.51.0) may raise errors like:

KeyError: 'qwen3'

Install or upgrade both packages:

pip install --upgrade transformers mlx_lm

The following contains a code snippet illustrating how to use the model generate content based on given inputs.

from mlx_lm import load, generate

model, tokenizer = load("Qwen/Qwen3-8B-MLX-4bit")
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)

Switching Between Thinking and Non-Thinking Mode

[!TIP] The enable_thinking switch is also available in APIs created by SGLang and vLLM. Please refer to our documentation for SGLang and vLLM users.

enable_thinking=True

By default, Qwen3 has thinking capabilities enabled, similar to QwQ-32B. This means the model will use its reasoning abilities to enhance the quality of generated responses. For example, when explicitly setting enable_thinking=True or leaving it as the default value in tokenizer.apply_chat_template, the model will engage its thinking mode.

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

In this mode, the model will generate think content wrapped in a <think>...</think> block, followed by the final response.

[!NOTE] For thinking mode, use Temperature=0.6, TopP=0.95, TopK=20, and MinP=0 (the default setting in generation_config.json). DO NOT use greedy decoding, as it can lead to performance degradation and endless repetitions. For more detailed guidance, please refer to the Best Practices section.

enable_thinking=False

We provide a hard switch to strictly disable the model's thinking behavior, aligning its functionality with the previous Qwen2.5-Instruct models. This mode is particularly useful in scenarios where disabling thinking is essential for enhancing efficiency.

text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=False  # Setting enable_thinking=False disables thinking mode
)

In this mode, the model will not generate any think content and will not include a <think>...</think> block.

[!NOTE] For non-thinking mode, we suggest using Temperature=0.7, TopP=0.8, TopK=20, and MinP=0. For more detailed guidance, please refer to the Best Practices section.

Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input

We provide a soft switch mechanism that allows users to dynamically control the model's behavior when enable_thinking=True. Specifically, you can add /think and /no_think to user prompts or system messages to switch the model's thinking mode from turn to turn. The model will follow the most recent instruction in multi-turn conversations.

Here is an example of a multi-turn conversation:

from mlx_lm import load, generate


class QwenChatbot:
    def __init__(self, model_name="Qwen/Qwen3-8B-MLX-4bit"):
        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] For API compatibility, when enable_thinking=True, regardless of whether the user uses /think or /no_think, the model will always output a block wrapped in <think>...</think>. However, the content inside this block may be empty if thinking is disabled. When enable_thinking=False, the soft switches are not valid. Regardless of any /think or /no_think tags input by the user, the model will not generate think content and will not include a <think>...</think> block.

Agentic Use

Qwen3 excels in tool calling capabilities. We recommend using Qwen-Agent to make the best use of agentic ability of Qwen3. Qwen-Agent encapsulates tool-calling templates and tool-calling parsers internally, greatly reducing coding complexity.

To define the available tools, you can use the MCP configuration file, use the integrated tool of Qwen-Agent, or integrate other tools by yourself.

from qwen_agent.agents import Assistant

# Define LLM
llm_cfg = {
    "model": "Qwen3-8B-MLX-4bit",

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

Processing Long Texts

Qwen3 natively supports context lengths of up to 32,768 tokens. For conversations where the total length (including both input and output) significantly exceeds this limit, we recommend using RoPE scaling techniques to handle long texts effectively. We have validated the model's performance on context lengths of up to 131,072 tokens using the YaRN method.

YaRN is currently supported by several inference frameworks, e.g., transformers and llama.cpp for local use, vllm and sglang for deployment. In general, there are two approaches to enabling YaRN for supported frameworks:

  • Modifying the model files: In the config.json file, add the rope_scaling fields:
    {
        ...,
        "rope_scaling": {
            "rope_type": "yarn",
            "factor": 4.0,
            "original_max_position_embeddings": 32768
        }
    }

[!IMPORTANT] If you encounter the following warning

Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}

please upgrade transformers>=4.51.0.

[!NOTE] All the notable open-source frameworks implement static YaRN, which means the scaling factor remains constant regardless of input length, potentially impacting performance on shorter texts. We advise adding the rope_scaling configuration only when processing long contexts is required. It is also recommended to modify the factor as needed. For example, if the typical context length for your application is 65,536 tokens, it would be better to set factor as 2.0.

[!NOTE] The default max_position_embeddings in config.json is set to 40,960. This allocation includes reserving 32,768 tokens for outputs and 8,192 tokens for typical prompts, which is sufficient for most scenarios involving short text processing. If the average context length does not exceed 32,768 tokens, we do not recommend enabling YaRN in this scenario, as it may potentially degrade model performance.

[!TIP] The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.

Best Practices

To achieve optimal performance, we recommend the following settings:

  1. Sampling Parameters:

    • For thinking mode (enable_thinking=True), use Temperature=0.6, TopP=0.95, TopK=20, and MinP=0. DO NOT use greedy decoding, as it can lead to performance degradation and endless repetitions.
    • For non-thinking mode (enable_thinking=False), we suggest using Temperature=0.7, TopP=0.8, TopK=20, and MinP=0.
    • For supported frameworks, you can adjust the presence_penalty parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
  2. Adequate Output Length: We recommend using an output length of 32,768 tokens for most queries. For benchmarking on highly complex problems, such as those found in math and programming competitions, we suggest setting the max output length to 38,912 tokens. This provides the model with sufficient space to generate detailed and comprehensive responses, thereby enhancing its overall performance.

  3. Standardize Output Format: We recommend using prompts to standardize model outputs when benchmarking.

    • Math Problems: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
    • Multiple-Choice Questions: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the answer field with only the choice letter, e.g., "answer": "C"."
  4. No Thinking Content in History: In multi-turn conversations, the historical model output should only include the final output part and does not need to include the thinking content. It is implemented in the provided chat template in Jinja2. However, for frameworks that do not directly use the Jinja2 chat template, it is up to the developers to ensure that the best practice is followed.

Citation

If you find our work helpful, feel free to give us a cite.

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