模型概述
模型特點
模型能力
使用案例
🚀 Qwen3-4B
Qwen3-4B是Qwen系列的最新大語言模型,支持多種格式,具備強大的推理、指令遵循、智能體和多語言能力。可免費微調,還能導出到Ollama、llama.cpp或HF等。
🚀 快速開始
Qwen3的代碼已集成在最新的Hugging Face transformers
庫中,建議使用最新版本的 transformers
。若使用 transformers<4.51.0
,會遇到如下錯誤:
KeyError: 'qwen3'
以下是使用該模型根據給定輸入生成內容的代碼片段:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-4B"
# 加載分詞器和模型
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)
對於部署,可以使用 vllm>=0.8.5
或 sglang>=0.4.5.post2
創建兼容OpenAI的API端點:
- vLLM:
vllm serve Qwen/Qwen3-4B --enable-reasoning --reasoning-parser deepseek_r1
- SGLang:
python -m sglang.launch_server --model-path Qwen/Qwen3-4B --reasoning-parser deepseek-r1
✨ 主要特性
Qwen3亮點
Qwen3是Qwen系列的最新一代大語言模型,提供了一套全面的密集模型和專家混合(MoE)模型。基於廣泛的訓練,Qwen3在推理、指令遵循、智能體能力和多語言支持方面取得了突破性進展,具有以下關鍵特性:
- 獨特支持單模型內思維模式無縫切換:在“思考模式”(用於複雜邏輯推理、數學和編碼)和“非思考模式”(用於高效通用對話)之間無縫切換,確保在各種場景下都能實現最佳性能。
- 顯著增強推理能力:在數學、代碼生成和常識邏輯推理方面超越了之前的QwQ(思考模式)和Qwen2.5指令模型(非思考模式)。
- 卓越的人類偏好對齊:在創意寫作、角色扮演、多輪對話和指令遵循方面表現出色,提供更自然、引人入勝和沉浸式的對話體驗。
- 強大的智能體能力:能夠在思考和非思考模式下精確集成外部工具,在複雜的基於智能體的任務中在開源模型中取得領先性能。
- 支持100多種語言和方言:具備強大的多語言指令遵循和翻譯能力。
模型概述
Qwen3-4B 具有以下特點:
屬性 | 詳情 |
---|---|
模型類型 | 因果語言模型 |
訓練階段 | 預訓練和後訓練 |
參數數量 | 40億 |
非嵌入參數數量 | 36億 |
層數 | 36 |
注意力頭數量(GQA) | Q為32,KV為8 |
上下文長度 | 原生支持32,768,使用YaRN可支持 131,072個token |
更多詳情,包括基準評估、硬件要求和推理性能,請參考博客、GitHub和文檔。
💻 使用示例
基礎用法
思考模式與非思考模式切換
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-4B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
messages = [{"role": "user", "content": "Give me a short introduction to large language model."}]
# 思考模式
text_thinking = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True
)
model_inputs_thinking = tokenizer([text_thinking], return_tensors="pt").to(model.device)
generated_ids_thinking = model.generate(
**model_inputs_thinking,
max_new_tokens=32768
)
output_ids_thinking = generated_ids_thinking[0][len(model_inputs_thinking.input_ids[0]):].tolist()
try:
index_thinking = len(output_ids_thinking) - output_ids_thinking[::-1].index(151668)
except ValueError:
index_thinking = 0
thinking_content = tokenizer.decode(output_ids_thinking[:index_thinking], skip_special_tokens=True).strip("\n")
content_thinking = tokenizer.decode(output_ids_thinking[index_thinking:], skip_special_tokens=True).strip("\n")
print("Thinking mode - Thinking content:", thinking_content)
print("Thinking mode - Content:", content_thinking)
# 非思考模式
text_non_thinking = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False
)
model_inputs_non_thinking = tokenizer([text_non_thinking], return_tensors="pt").to(model.device)
generated_ids_non_thinking = model.generate(
**model_inputs_non_thinking,
max_new_tokens=32768
)
output_ids_non_thinking = generated_ids_non_thinking[0][len(model_inputs_non_thinking.input_ids[0]):].tolist()
content_non_thinking = tokenizer.decode(output_ids_non_thinking, skip_special_tokens=True).strip("\n")
print("Non-thinking mode - Content:", content_non_thinking)
高級用法
通過用戶輸入切換思考和非思考模式
from transformers import AutoModelForCausalLM, AutoTokenizer
class QwenChatbot:
def __init__(self, model_name="Qwen/Qwen3-4B"):
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}")
智能體使用
import os
from qwen_agent.agents import Assistant
# 定義大語言模型
llm_cfg = {
'model': 'Qwen3-4B',
# 使用阿里雲魔搭提供的端點:
# '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']
},
}
},
'code_interpreter', # 內置工具
]
# 定義智能體
bot = Assistant(llm=llm_cfg, function_list=tools)
# 流式生成
messages = [{'role': 'user', 'content': 'What time is it?'}]
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": { "type": "yarn", "factor": 4.0, "original_max_position_embeddings": 32768 } }
llama.cpp
,修改後需要重新生成GGUF文件。 - 傳遞命令行參數:
對於
vllm
,可以使用:
對於vllm serve ... --rope-scaling '{"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":{"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個token,最好將factor
設置為2.0。config.json
中的默認max_position_embeddings
設置為40,960。此分配包括為輸出保留32,768個token和為典型提示保留8,192個token,這足以滿足大多數短文本處理場景。如果平均上下文長度不超過32,768個token,不建議在此場景中啟用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
。 - 對於受支持的框架,可以在0到2之間調整
presence_penalty
參數以減少無限重複。但是,使用較高的值可能偶爾會導致語言混合和模型性能略有下降。
- 思考模式(
- 足夠的輸出長度:對於大多數查詢,建議使用32,768個token的輸出長度。對於高度複雜問題的基準測試,如數學和編程競賽中的問題,建議將最大輸出長度設置為38,912個token。這為模型提供了足夠的空間來生成詳細和全面的響應,從而提高其整體性能。
- 標準化輸出格式:在進行基準測試時,建議使用提示來標準化模型輸出。
- 數學問題:在提示中包含 "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}
}
其他信息
- 查看所有版本的Qwen3,包括GGUF、4位和16位格式。
- 學習正確運行Qwen3。
- Unsloth Dynamic 2.0 實現了卓越的準確性,優於其他領先的量化方法。
免費使用Google Colab筆記本 微調Qwen3 (14B)。閱讀關於Qwen3支持的博客,查看其他筆記本。運行並將微調後的模型導出到Ollama、llama.cpp或HF。
Unsloth支持 | 免費筆記本 | 性能 | 內存使用 |
---|---|---|---|
Qwen3 (14B) | ▶️ 在Colab上開始 | 快3倍 | 減少70% |
GRPO with Qwen3 (8B) | ▶️ 在Colab上開始 | 快3倍 | 減少80% |
Llama-3.2 (3B) | ▶️ 在Colab上開始 | 快2.4倍 | 減少58% |
Llama-3.2 (11B vision) | ▶️ 在Colab上開始 | 快2倍 | 減少60% |
Qwen2.5 (7B) | ▶️ 在Colab上開始 | 快2倍 | 減少60% |
Phi-4 (14B) | ▶️ 在Colab上開始 | 快2倍 | 減少50% |



