模型概述
模型特點
模型能力
使用案例
🚀 Qwen3-1.7B-GPTQ-Int8
Qwen3-1.7B-GPTQ-Int8是Qwen系列最新大語言模型,在推理、指令遵循、智能體能力和多語言支持等方面有顯著提升,支持思維模式與非思維模式無縫切換。
🚀 快速開始
Qwen3的代碼已集成在最新的Hugging Face transformers
庫中,建議使用最新版本的transformers
。
若使用transformers<4.51.0
,會遇到如下錯誤:
KeyError: 'qwen3'
以下代碼展示瞭如何基於給定輸入使用該模型生成內容:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-1.7B-GPTQ-Int8"
# 加載分詞器和模型
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.4
創建與OpenAI兼容的API端點:
- SGLang:
python -m sglang.launch_server --model-path Qwen/Qwen3-1.7B-GPTQ-Int8 --reasoning-parser qwen3
- vLLM:
vllm serve Qwen/Qwen3-1.7B-GPTQ-Int8 --enable-reasoning --reasoning-parser deepseek_r1
更多使用指南請參考GPTQ文檔。
✨ 主要特性
Qwen3是Qwen系列的最新一代大語言模型,提供了一套全面的密集模型和專家混合(MoE)模型。基於大量訓練,Qwen3在推理、指令遵循、智能體能力和多語言支持方面取得了突破性進展,具有以下關鍵特性:
- 單模型內獨特支持思維模式(用於複雜邏輯推理、數學和編碼)和非思維模式(用於高效通用對話)無縫切換,確保在各種場景下都能實現最佳性能。
- 推理能力顯著增強,在數學、代碼生成和常識邏輯推理方面超越了之前的QwQ(思維模式)和Qwen2.5指令模型(非思維模式)。
- 卓越的人類偏好對齊,在創意寫作、角色扮演、多輪對話和指令遵循方面表現出色,提供更自然、引人入勝和沉浸式的對話體驗。
- 強大的智能體能力,能夠在思維和非思維模式下精確集成外部工具,在複雜的基於智能體的任務中在開源模型中取得領先性能。
- 支持100多種語言和方言,具備強大的多語言指令遵循和翻譯能力。
📦 安裝指南
此部分文檔未提及具體安裝步驟,可參考快速開始部分使用相關庫和命令。
💻 使用示例
基礎用法
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-1.7B-GPTQ-Int8"
# 加載分詞器和模型
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)
高級用法
思維模式與非思維模式切換
# 思維模式
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=True # True是enable_thinking的默認值
)
# 非思維模式
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False # 設置enable_thinking=False禁用思維模式
)
通過用戶輸入切換思維模式
from transformers import AutoModelForCausalLM, AutoTokenizer
class QwenChatbot:
def __init__(self, model_name="Qwen/Qwen3-1.7B-GPTQ-Int8"):
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}")
智能體使用
from qwen_agent.agents import Assistant
# 定義大語言模型
llm_cfg = {
'model': 'Qwen/Qwen3-1.7B-GPTQ-Int8',
# 使用阿里雲魔搭提供的端點:
# '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-1.7B 具有以下特點:
屬性 | 詳情 |
---|---|
模型類型 | 因果語言模型 |
訓練階段 | 預訓練和後訓練 |
參數數量 | 17億 |
非嵌入參數數量 | 14億 |
層數 | 28 |
注意力頭數量(GQA) | Q為16,KV為8 |
上下文長度 | 32768 |
量化方式 | GPTQ 8位 |
更多詳細信息,包括基準評估、硬件要求和推理性能,請參考博客、GitHub和文檔。
思維與非思維模式切換
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
來逐輪切換模型的思維模式。模型將遵循多輪對話中的最新指令。
⚠️ 重要提示
對於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的集成工具或自行集成其他工具。
性能
模式 | 量化類型 | LiveBench 2024 - 11 - 25 | GPQA | MMLU - Redux |
---|---|---|---|---|
思維 | bf16 | 51.1 | 40.1 | 73.9 |
思維 | GPTQ - int8 | 49.8 | 39.1 | 74.9 |
非思維 | bf16 | 35.6 | 28.6 | 64.4 |
非思維 | GPTQ - int8 | 35.5 | 28.3 | 63.0 |
最佳實踐
為了實現最佳性能,建議進行以下設置:
- 採樣參數:
- 對於思維模式(
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
參數以減少無限重複。強烈建議對量化模型將此值設置為1.5。但是,使用較高的值可能偶爾會導致語言混合和模型性能略有下降。
- 對於思維模式(
- 足夠的輸出長度:對於大多數查詢,建議使用32768個標記的輸出長度。對於高度複雜問題的基準測試,例如數學和編程競賽中的問題,建議將最大輸出長度設置為38912個標記。這為模型提供了足夠的空間來生成詳細和全面的響應,從而提高其整體性能。
- 標準化輸出格式:在進行基準測試時,建議使用提示來標準化模型輸出。
- 數學問題:在提示中包含“請逐步推理,並將最終答案放在\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許可證,詳情請見許可證鏈接。



