模型概述
模型特點
模型能力
使用案例
🚀 Qwen3-235B-A22B-AWQ
Qwen3-235B-A22B-AWQ 是基於 Qwen3-235B-A22B 模型的 AWQ 量化版本,可用於文本生成等自然語言處理任務。本項目提供了該模型的使用示例、部署方法等內容,幫助用戶快速上手。
🚀 快速開始
環境準備
Qwen3-MoE 的代碼已集成在最新的 Hugging Face transformers
庫中,建議使用最新版本的 transformers
。若使用 transformers<4.51.0
,會遇到如下錯誤:
KeyError: 'qwen3_moe'
代碼示例
以下是一個使用該模型根據給定輸入生成內容的代碼片段:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-235B-A22B"
# 加載分詞器和模型
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-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。
✨ 主要特性
Qwen3 亮點
Qwen3 是通義大模型系列的最新一代,提供了一套全面的密集模型和專家混合(MoE)模型。基於大量訓練,Qwen3 在推理、指令遵循、智能體能力和多語言支持方面取得了突破性進展,具有以下關鍵特性:
- 獨特支持單模型內思考模式(用於複雜邏輯推理、數學和編碼)和非思考模式(用於高效通用對話)無縫切換,確保在各種場景下都能實現最佳性能。
- 顯著增強推理能力,在數學、代碼生成和常識邏輯推理方面超越了之前的 QwQ(思考模式)和 Qwen2.5 指令模型(非思考模式)。
- 卓越的人類偏好對齊,在創意寫作、角色扮演、多輪對話和指令遵循方面表現出色,提供更自然、引人入勝和沉浸式的對話體驗。
- 強大的智能體能力,能夠在思考和非思考模式下精確集成外部工具,並在複雜的基於智能體的任務中在開源模型中取得領先性能。
- 支持 100 多種語言和方言,具備強大的多語言指令遵循和翻譯能力。
Qwen3-235B-A22B 模型概述
屬性 | 詳情 |
---|---|
模型類型 | 因果語言模型 |
訓練階段 | 預訓練和後訓練 |
參數數量 | 總共 235B,激活 22B |
非嵌入參數數量 | 234B |
層數 | 94 |
注意力頭數量(GQA) | Q 為 64,KV 為 4 |
專家數量 | 128 |
激活專家數量 | 8 |
上下文長度 | 原生支持 32,768,使用 YaRN 可支持 131,072 個標記 |
更多詳細信息,包括基準評估、硬件要求和推理性能,請參考博客、GitHub和文檔。
💻 使用示例
基礎用法
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-235B-A22B"
# 加載分詞器和模型
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)
高級用法:思考和非思考模式切換
思考模式(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-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)
# 更新歷史記錄
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-235B-A22B',
# 使用阿里雲魔搭提供的端點:
# '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 個標記的上下文長度。對於總長度(包括輸入和輸出)顯著超過此限制的對話,建議使用 RoPE 縮放技術來有效處理長文本。已使用 YaRN 方法驗證了模型在長達 131,072 個標記的上下文長度上的性能。
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 個標記,最好將factor
設置為 2.0。
⚠️ 重要提示
config.json
中的默認max_position_embeddings
設置為 40,960。此分配包括為輸出保留 32,768 個標記和為典型提示保留 8,192 個標記,這對於大多數短文本處理場景來說已經足夠。如果平均上下文長度不超過 32,768 個標記,不建議在這種情況下啟用 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
。 - 對於支持的框架,可以將
presence_penalty
參數調整為 0 到 2 之間的值,以減少無限重複。但是,使用較高的值可能偶爾會導致語言混合和模型性能略有下降。
- 對於思考模式(
-
足夠的輸出長度:對於大多數查詢,建議使用 32,768 個標記的輸出長度。對於高度複雜問題的基準測試,例如數學和編程競賽中的問題,建議將最大輸出長度設置為 38,912 個標記。這為模型提供了足夠的空間來生成詳細和全面的響應,從而提高其整體性能。
-
標準化輸出格式:建議在基準測試時使用提示來標準化模型輸出。
- 數學問題:在提示中包含 "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{qwen3,
title = {Qwen3},
url = {https://qwenlm.github.io/blog/qwen3/},
author = {Qwen Team},
month = {April},
year = {2025}
}
📄 許可證
本項目採用 Apache-2.0 許可證。



