模型概述
模型特點
模型能力
使用案例
🚀 Qwen3-235B-A22B
本項目包含由JustinJJA將Qwen 3 235B A22B模型量化為INT4 / W4A16的版本,在顯著減少內存佔用的同時保持了準確性。
🚀 快速開始
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
- 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;
# # 不添加:當響應已被reasoning_content和content分隔時。
# '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個標記的上下文長度上的性能。
目前,transformers
和 llama.cpp
等幾個推理框架支持本地使用YaRN,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
升級到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個標記。這為模型提供了足夠的空間來生成詳細和全面的響應,從而提高其整體性能。
- 標準化輸出格式:在進行基準測試時,建議使用提示來標準化模型輸出。
- 數學問題:在提示中包含“請逐步推理,並將最終答案放在 \boxed{} 內。”
- 多項選擇題:在提示中添加以下JSON結構以標準化響應:“請在
answer
字段中僅用選項字母顯示您的選擇,例如"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許可證。
推理說明
使用 vllm>=0.8.5
最大 -tp 4
,對於8個GPU,使用 -tp 4 -pp 2
運行以下命令:
VLLM serve justinjja/Qwen3-235B-A22B-INT4-W4A16 -tp 4
量化代碼可在此處找到:https://huggingface.co/justinjja/Qwen3-235B-A22B-INT4-W4A16/blob/main/quantization_script.py



