Q
Qwen/Qwen3-235B-A22B
模型介绍模型推理文件和版本分析
下载使用量0

Qwen3-235B-A22B

聊天

Qwen3 亮点

Qwen3 是 Qwen 系列中的最新一代大型语言模型,提供了一系列密集型和混合专家(MoE)模型。在广泛训练的基础上,Qwen3 在推理、指令跟随、代理能力和多语言支持等方面取得了突破性进展,具备以下关键特性:

  • 在单个模型中独特支持无缝切换思考模式(适用于复杂的逻辑推理、数学和编程)和非思考模式(适用于高效、通用对话),确保在各种场景下实现最优性能。
  • 显著增强了其推理能力,在数学、代码生成和常识逻辑推理方面超越了之前的 QwQ(思考模式)和 Qwen2.5 指令模型(非思考模式)。
  • 卓越的人类偏好对齐,在创意写作、角色扮演、多轮对话和指令跟随方面表现出色,提供更加自然、引人入胜和沉浸式的对话体验。
  • 在代理能力方面的专业性,使得在与外部工具的精确集成方面,无论是在思考模式还是非思考模式下均达到领先性能,特别是在复杂的基于代理的任务中。
  • 支持超过 100 种语言和方言,具备强大的多语言指令跟随和翻译能力。

模型概述

Qwen3-235B-A22B 具有以下特点:

  • 类型:因果语言模型
  • 训练阶段:预训练和后训练
  • 参数总数:2350 亿,激活 220 亿
  • 非嵌入参数数量:2340 亿
  • 层数:94
  • 注意力头数(GQA):Q 有 64 个,KV 有 4 个
  • 专家数:128
  • 激活的专家数:8
  • 上下文长度:原生支持 32,768,通过 YaRN 可扩展至 131,072 tokens.

更多详细信息,包括基准评估、硬件需求和推理性能,请参考我们的 博客、GitHub 和 文档。

快速入门

Qwen3-MoE 的代码已经集成在最新的 Hugging Face transformers 库中,我们建议您使用 transformers 的最新版本。

使用 transformers<4.51.0,您会遇到以下错误:

KeyError: 'qwen3_moe'

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

from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen3-235B-A22B"

# 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-235B-A22B --reasoning-parser qwen3 --tp 8
  • vLLM:
    vllm serve Qwen/Qwen3-235B-A22B --enable-reasoning --reasoning-parser deepseek_r1

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

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

[!TIP] 在 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  # 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-235B-A22B"):
        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-235B-A22B',

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

处理长文本

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

[!IMPORTANT] 如果您遇到以下警告

在 'rope_scaling' 中识别到 'rope_type'='yarn' 的未知键:{'original_max_position_embeddings'}

请升级至 transformers>=4.51.0。

[!NOTE] 所有知名的开源框架都实现了静态 YaRN,这意味着缩放因子与输入长度无关,可能会对短文本的性能造成影响。 我们建议仅在处理长上下文时添加 rope_scaling 配置。 也建议根据需要修改 factor 参数。例如,如果应用程序的典型上下文长度为 65,536 个 token,最好将 factor 设置为 2.0。

[!NOTE] config.json 中的默认 max_position_embeddings 设置为 40,960。此分配包括为输出预留 32,768 个 token 和为典型提示预留 8,192 个 token,这对于大多数涉及短文本处理的情况来说已经足够。如果平均上下文长度不超过 32,768 个 token,我们不建议在此情况下启用 YaRN,因为它可能会潜在地降低模型性能。

[!TIP] 阿里巴巴模型工作室提供的端点默认支持动态 YaRN,无需额外配置。

最佳实践

为了达到最佳性能,我们推荐以下设置:

  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. 标准化输出格式:我们建议在基准测试时使用提示来标准化模型输出。

    • 数学问题:在提示中包含 "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"."
  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}, 
}

请提供需要翻译的英文文本以及您期望的翻译风格的具体要求,这样我才能准确地进行翻译。