Qwen3 快速上手实战指南:从 Transformers 推理到 OpenAI 兼容 API 部署与思考预算控制
发布时间:2026/9/10 15:34:28来源:尧图网络
Qwen3 快速上手实战指南从 Transformers 推理到 OpenAI 兼容 API 部署与思考预算控制【免费下载链接】Qwen1.5Qwen3 is the large language model series developed by Qwen team, Alibaba Cloud.项目地址: https://gitcode.com/GitHub_Trending/qw/Qwen1.5本指南基于 Qwen3 官方 Quickstart 文档编写帮助开发者从零开始快速跑通 Qwen3 系列模型先通过 Hugging Face Transformers 完成本地推理再切换到 ModelScope 解决下载问题随后用 SGLang / vLLM 启动 OpenAI 兼容 API 服务最后深入掌握思考Thinking模式切换与思考预算Thinking Budget的高级用法。读完本指南你将能够在本地或服务器上独立完成 Qwen3 的推理、服务化部署与推理成本控制。一、Qwen3 快速上手概览Qwen3 是阿里云 Qwen 团队开源的大语言模型系列包含多种规模的稠密模型与 MoE 模型如 0.6B、1.7B、4B、8B、14B、32B、30B-A3B、235B-A22B。本指南对应的 Quickstart 文档 主要覆盖以下内容Transformers 推理以transformers4.51.0为基础演示 Instruct-2507、Thinking-2507 与混合模式hybrid模型的调用方式ModelScope 下载与推理解决国内模型下载问题OpenAI 兼容 API使用 SGLang0.4.6.post1与 vLLM0.9.0启动服务并通过curl或openaiPython SDK 调用思考预算通过两次生成实现受限思考时长的推理策略。在动手之前建议先熟悉 Qwen3 的三种模型形态因为它们对应完全不同的调用方式模型系列思考模式支持说明Qwen3-Instruct-2507仅非思考模式输出中不会出现think/think块无需也不再支持指定enable_thinkingFalseQwen3-Thinking-2507仅思考模式默认聊天模板自动包含think输出中只出现/think结束标签属正常现象Qwen3即 Qwen3-2504思考/非思考可切换通过enable_thinking硬开关与/think、/no_think软开关控制这三者的差异会在下文各章节中反复体现务必区分清楚。二、环境准备运行 Qwen3 的最小环境要求如下Python建议 3.10 或更高版本PyTorch建议 2.6 或更高版本Transformerstransformers4.51.0硬性要求GPU推理 Qwen3-8B 等小规模模型建议至少 16GB 显存235B-A22B 等大模型需多卡张量并行下文 API 部署部分会给出 8 卡示例。安装依赖pip install transformers4.51.0 torch accelerateQwen3 模型权重可从两个渠道获取Hugging Face Hub在 Qwen3 collection 中搜索以Qwen3-开头的 checkpointModelScope国内用户推荐使用可显著缓解下载问题。如果网络环境不佳也可以先在本地用官方命令下载权重再加载见 Transformers 推理文档# Hugging Face huggingface-cli download --local-dir ./Qwen3-8B Qwen/Qwen3-8B # ModelScope国内推荐 modelscope download --local_dir ./Qwen3-8B Qwen/Qwen3-8B三、用 Transformers 跑通三种模型的推理3.1 Qwen3-Instruct-2507非思考模式推理以Qwen/Qwen3-235B-A22B-Instruct-2507为例Instruct-2507仅支持非思考模式不会生成think/think块。与 Qwen3-2504 不同指定enable_thinkingFalse不再需要也不再被支持。from transformers import AutoModelForCausalLM, AutoTokenizer model_name Qwen/Qwen3-235B-A22B-Instruct-2507 # 加载 tokenizer 和模型 tokenizer AutoTokenizer.from_pretrained(model_name) model AutoModelForCausalLM.from_pretrained( model_name, torch_dtypeauto, device_mapauto ) # 准备模型输入 prompt Give me a short introduction to large language model. messages [ {role: user, content: prompt} ] text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, ) model_inputs tokenizer([text], return_tensorspt).to(model.device) # 文本补全 generated_ids model.generate( **model_inputs, max_new_tokens16384 ) output_ids generated_ids[0][len(model_inputs.input_ids[0]):].tolist() content tokenizer.decode(output_ids, skip_special_tokensTrue) print(content:, content)推荐采样参数Instruct-2507temperature0.7、top_p0.8、top_k20、min_p0在支持的框架中可将presence_penalty调至 0~2 之间以减少重复但注意过高的presence_penalty偶尔会引发语种混杂和模型性能轻微下降Instruct-2507 可能在复杂任务上自动使用思维链CoT大多数查询建议输出长度设为16,384 tokens。3.2 Qwen3-Thinking-2507思考模式推理与思维内容解析以Qwen/Qwen3-235B-A22B-Thinking-2507为例。Thinking-2507仅支持思考模式其默认聊天模板会自动包含think来强制模型思考因此模型输出中只包含/think而没有显式think开头标签是正常现象。from transformers import AutoModelForCausalLM, AutoTokenizer model_name Qwen/Qwen3-235B-A22B-Thinking-2507 # 加载 tokenizer 和模型 tokenizer AutoTokenizer.from_pretrained(model_name) model AutoModelForCausalLM.from_pretrained( model_name, torch_dtypeauto, device_mapauto ) # 准备模型输入 prompt Give me a short introduction to large language model. messages [ {role: user, content: prompt} ] text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, ) model_inputs tokenizer([text], return_tensorspt).to(model.device) # 文本补全 generated_ids model.generate( **model_inputs, max_new_tokens32768 ) 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_tokensTrue).strip(\n) content tokenizer.decode(output_ids[index:], skip_special_tokensTrue).strip(\n) print(thinking content:, thinking_content) # 没有开头 think 标签 print(content:, content)推荐采样参数Thinking-2507temperature0.6、top_p0.95、top_k20、min_p0同样可调节presence_penalty0~2 减少重复Thinking-2507 思考深度更强强烈建议在高度复杂的推理任务中使用并配置足够大的最大生成长度。关于 token 151668 的底层原理思考内容的边界由特殊 token 标记。151668即/think结束标签的 token id151645是|im_end|。上例通过从后往前查找151668的位置来切分思考内容 / 最终回答两部分这种方法在思考预算实现第六节中也会复用。3.3 Qwen3 混合模式思考与非思考切换以Qwen/Qwen3-8B为例Qwen3Qwen3-2504默认会像 QwQ 一样先思考再回答即先输出think.../think包裹的思考内容再输出最终回答。它提供两种切换方式硬开关Hard Switch在apply_chat_template时传enable_thinkingFalse可严格禁用思考行为与之前的 Qwen2.5-Instruct 一致适合需要提升效率的场景text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, enable_thinkingTrue, # 在思考/非思考模式间切换默认 True ) # 禁用思考模式 text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, enable_thinkingFalse, # 设置 enable_thinkingFalse 禁用思考模式 )软开关Soft SwitchQwen3 也能理解用户对其思考行为的指令在用户提示或系统消息中加入/think和/no_think即可按轮次切换思考模式。多轮对话中模型遵循最近一条指令。完整示例含思考内容解析from transformers import AutoModelForCausalLM, AutoTokenizer model_name Qwen/Qwen3-8B model AutoModelForCausalLM.from_pretrained( model_name, torch_dtypeauto, device_mapauto ) tokenizer AutoTokenizer.from_pretrained(model_name) prompt Give me a short introduction to large language models. messages [{role: user, content: prompt}] text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, enable_thinkingTrue, ) model_inputs tokenizer([text], return_tensorspt).to(model.device) generated_ids model.generate(**model_inputs, max_new_tokens32768) output_ids generated_ids[0][len(model_inputs.input_ids[0]):].tolist() try: index len(output_ids) - output_ids[::-1].index(151668) except ValueError: index 0 thinking_content tokenizer.decode(output_ids[:index], skip_special_tokensTrue).strip(\n) content tokenizer.decode(output_ids[index:], skip_special_tokensTrue).strip(\n) print(thinking content:, thinking_content) print(content:, content)混合模式的推荐采样参数思考模式temperature0.6、top_p0.95、top_k20、min_p0即generation_config.json中的默认配置。不要使用贪心解码greedy decoding否则会导致性能下降和无限重复非思考模式建议temperature0.7、top_p0.8、top_k20、min_p0。3.4 从源码看加载与生成的关键点仓库 examples/demo/cli_demo.py 给出了与文档一致的工程化加载模式可作为生产参考通过AutoTokenizer.from_pretrained(args.checkpoint_path, resume_downloadTrue)与AutoModelForCausalLM.from_pretrained(..., torch_dtypeauto, device_mapauto).eval()加载模型其中device_mapauto依赖accelerate自动将模型参数分配到可用设备参见 Transformers 推理文档交互对话时使用tokenizer.apply_chat_template(conversation, add_generation_promptTrue, tokenizeFalse)拼装多轮消息并用TextIteratorStreamer实现流式输出若未传torch_dtypeauto默认是float32将占用双倍显存且计算更慢现代设备上auto通常解析为bfloat16。此外若希望获得与 vLLM/SGLang 一致的reasoning_content结构化字段可以参考 transformers.md 提供的解析函数用正则rthink\n(.)/think\n\n将思考内容提取到message[reasoning_content]。四、ModelScope解决下载问题的替代方案如果遇到模型下载问题推荐使用ModelScope。ModelScope 的编程接口与 Transformers 相似但不完全相同对于基础用法只需把导入语句从from transformers import AutoModelForCausalLM, AutoTokenizer替换为from modelscope import AutoModelForCausalLM, AutoTokenizer其余代码apply_chat_template、model.generate、解码等保持一致。更多用法可查阅 ModelScope 官方文档。对于 vLLM 与 SGLang 服务还可以通过环境变量切换到 ModelScope 下载# vLLM export VLLM_USE_MODELSCOPEtrue # SGLang export SGLANG_USE_MODELSCOPEtrue详见 vLLM 部署文档 与 SGLang 部署文档。五、OpenAI 兼容 API用 SGLang / vLLM 服务化部署你可以用 vLLM、SGLang 等框架以 OpenAI 兼容 API 的形式服务 Qwen3并使用常见 HTTP 客户端或 OpenAI SDK 与之交互。启动服务前请先安装对应框架# SGLang要求 0.4.6.post1 pip install sglang[all]0.4.6.post1 # vLLM推荐 0.9.0 pip install vllm0.9.05.1 按模型类型启动服务Qwen3-Instruct-2507以 235B-A22B-Instruct-2507 为例8 卡张量并行# SGLang python -m sglang.launch_server --model-path Qwen/Qwen3-235B-A22B-Instruct-2507 --port 8000 --tp 8 --context-length 262144 # vLLM vllm serve Qwen/Qwen3-235B-A22B-Instruct-2507 --port 8000 --tensor-parallel-size 8 --max-model-len 262144Qwen3-Thinking-2507以 235B-A22B-Thinking-2507 为例需启用 reasoning parser# SGLang python -m sglang.launch_server --model-path Qwen/Qwen3-235B-A22B-Thinking-2507 --port 8000 --tp 8 --context-length 262144 --reasoning-parser deepseek-r1 # vLLM vllm serve Qwen/Qwen3-235B-A22B-Thinking-2507 --port 8000 --tensor-parallel-size 8 --max-model-len 262144 --enable-reasoning --reasoning-parser deepseek_r1注意目前官方正在适配qwen3reasoning parser 以匹配 2507 系列的新行为请暂时使用上面的deepseek-r1/deepseek_r1解析器命令。Qwen3 混合模式以 Qwen3-8B 为例# SGLang python -m sglang.launch_server --model-path Qwen/Qwen3-8B --port 8000 --reasoning-parser qwen3 # vLLM vllm serve Qwen/Qwen3-8B --port 8000 --enable-reasoning --reasoning-parser qwen3提示请根据可用 GPU 显存调整 context length--context-length/--max-model-len。需要说明的是vLLM 默认在http://localhost:8000启动服务SGLang 默认在http://localhost:30000可用--host/--port指定地址。5.2 用 curl 调用 Chat CompletionsInstruct-2507 示例curl http://localhost:8000/v1/chat/completions -H Content-Type: application/json -d { model: Qwen/Qwen3-235B-A22B-Instruct-2507, messages: [ {role: user, content: Give me a short introduction to large language models.} ], temperature: 0.7, top_p: 0.8, top_k: 20, max_tokens: 16384 }Thinking-2507 示例curl http://localhost:8000/v1/chat/completions -H Content-Type: application/json -d { model: Qwen/Qwen3-235B-A22B-Thinking-2507, messages: [ {role: user, content: Give me a short introduction to large language models.} ], temperature: 0.6, top_p: 0.95, top_k: 20, max_tokens: 32768 }Qwen3-8B默认思考模式示例curl http://localhost:8000/v1/chat/completions -H Content-Type: application/json -d { model: Qwen/Qwen3-8B, messages: [ {role: user, content: Give me a short introduction to large language models.} ], temperature: 0.6, top_p: 0.95, top_k: 20, max_tokens: 32768 }5.3 用 openai Python SDK 调用以 vLLM 服务为例SGLang 只需把base_url换成http://localhost:30000/v1from openai import OpenAI # 设置 OpenAI 的 API key 和 API base 以使用 vLLM 的 API server openai_api_key EMPTY openai_api_base http://localhost:8000/v1 client OpenAI( api_keyopenai_api_key, base_urlopenai_api_base, ) chat_response client.chat.completions.create( modelQwen/Qwen3-235B-A22B-Instruct-2507, messages[ {role: user, content: Give me a short introduction to large language models.}, ], max_tokens16384, temperature0.7, top_p0.8, extra_body{ top_k: 20, } ) print(Chat response:, chat_response)5.4 通过 API 关闭思考混合模式 Qwen3软开关在用户查询中追加/nothink例如...models./nothink即可让 Qwen3 按轮次关闭思考。硬开关通过chat_template_kwargs传递enable_thinkingcurl http://localhost:8000/v1/chat/completions -H Content-Type: application/json -d { model: Qwen/Qwen3-8B, messages: [ {role: user, content: Give me a short introduction to large language models.} ], temperature: 0.7, top_p: 0.8, top_k: 20, max_tokens: 8192, presence_penalty: 1.5, chat_template_kwargs: {enable_thinking: false} }Python 方式注意enable_thinking需放在extra_body中因为它不是 OpenAI 标准参数from openai import OpenAI openai_api_key EMPTY openai_api_base http://localhost:8000/v1 client OpenAI(api_keyopenai_api_key, base_urlopenai_api_base) chat_response client.chat.completions.create( modelQwen/Qwen3-8B, messages[ {role: user, content: Give me a short introduction to large language models.}, ], max_tokens8192, temperature0.7, top_p0.8, presence_penalty1.5, extra_body{ top_k: 20, chat_template_kwargs: {enable_thinking: False}, } ) print(Chat response:, chat_response)说明enable_thinking参数并非 OpenAI API 标准字段不同框架的传递方式可能不同vLLM / SGLang 都要求在extra_body或请求体 JSON 的chat_template_kwargs中传递详见 vLLM 部署文档 与 SGLang 部署文档。彻底禁用思考的终极方案仓库提供了一个不含思考逻辑的自定义聊天模板 qwen3_nonthinking.jinja从模板源码看它在生成提示的末尾直接输出|im_start|assistant\nthink\n\n/think\n\n之外的内容——实际上该模板在add_generation_prompt时直接拼接think空块并以/think结束从而阻止模型输出思考内容。用它启动服务后即使模型收到/think指令也不会思考# vLLM vllm serve Qwen/Qwen3-8B --chat-template ./qwen3_nonthinking.jinja # SGLang python -m sglang.launch_server --model-path Qwen/Qwen3-8B --chat-template ./qwen3_nonthinking.jinja5.5 部署进阶要点结合 vLLM 部署文档 与 SGLang 部署文档快速上手部署时还有几个值得注意的点reasoning parser 与enable_thinkingFalse的兼容性vLLM 0.8.5 中enable_thinkingFalse与思考内容解析不兼容vLLM 0.9.0 起可通过qwen3reasoning parser 解决。若需向 API 传enable_thinkingFalse建议同时禁用思考内容解析预量化模型Qwen3 提供 FP8 与 AWQ 两种预量化版本服务命令只需把模型名换成Qwen/Qwen3-8B-FP8或Qwen/Qwen3-8B-AWQ即可张量并行--tensor-parallel-size 4会在 4 张 GPU 上做张量并行可按需调整 GPU 数量部署 235B-A22B 这类 MoE 模型时若遇到 FP8 权重的block_n不整除报错可降低张量并行度或启用 expert parallel见 vLLM 部署文档工具调用vLLM 用--enable-auto-tool-choice --tool-call-parser hermesSGLang 用--tool-call-parser qwen25详见 Function Calling 指南。六、思考预算Thinking Budget两段式生成的受限思考6.1 原理与适用场景Qwen3 支持配置思考预算thinking budget一旦思考过程达到预算上限就提前结束思考并通过一段提前停止提示early-stopping prompt引导模型生成总结。由于该特性依赖每个模型特有的定制目前在开源框架中尚未直接提供仅由阿里云百炼 Model Studio API 实现。不过利用现有开源框架可以生成两次来实现第一次生成生成到思考预算对应的 token 数检查思考是否结束若未结束追加提前停止提示第二次生成继续生成直到内容结束或达到长度上限。6.2 Transformers 两段式实现以下为 Hugging Face Transformers 的参考实现以Qwen/Qwen3-8B为例thinking_budget16仅作演示实际使用建议调高import torch from transformers import AutoModelForCausalLM, AutoTokenizer model_name Qwen/Qwen3-8B thinking_budget 16 max_new_tokens 32768 # 加载 tokenizer 和模型 model AutoModelForCausalLM.from_pretrained( model_name, torch_dtypeauto, device_mapauto ) tokenizer AutoTokenizer.from_pretrained(model_name) # 准备模型输入 prompt Give me a short introduction to large language models. messages [ {role: user, content: prompt}, ] text tokenizer.apply_chat_template( messages, tokenizeFalse, add_generation_promptTrue, enable_thinkingTrue, # 在思考/非思考模式间切换默认 True ) model_inputs tokenizer([text], return_tensorspt).to(model.device) input_length model_inputs.input_ids.size(-1) # 第一次生成直到思考预算 generated_ids model.generate( **model_inputs, max_new_tokensthinking_budget ) output_ids generated_ids[0][input_length:].tolist() # 检查生成是否已结束151645 是 |im_end| if 151645 not in output_ids: # 检查思考是否已结束151668 是 /think # 并准备第二次模型输入 if 151668 not in output_ids: print(thinking budget is reached) early_stopping_text \n\nConsidering the limited time by the user, I have to give the solution based on the thinking directly now.\n/think\n\n early_stopping_ids tokenizer([early_stopping_text], return_tensorspt, return_attention_maskFalse).input_ids.to(model.device) input_ids torch.cat([generated_ids, early_stopping_ids], dim-1) else: input_ids generated_ids attention_mask torch.ones_like(input_ids, dtypetorch.int64) # 第二次生成 generated_ids model.generate( input_idsinput_ids, attention_maskattention_mask, max_new_tokensinput_length max_new_tokens - input_ids.size(-1) # 若 max_new_tokens 不够大可能为负数提前停止文本约 24 个 token ) output_ids generated_ids[0][input_length:].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_tokensTrue).strip(\n) content tokenizer.decode(output_ids[index:], skip_special_tokensTrue).strip(\n) print(thinking content:, thinking_content) print(content:, content)运行后控制台输出效果类似thinking budget is reached thinking content: think Okay, the user is asking for a short introduction to large language models Considering the limited time by the user, I have to give the solution based on the thinking directly now. /think content: Large language models (LLMs) are advanced artificial intelligence systems trained on vast amounts of text data to understand and generate human-like language. They can perform tasks such as answering questions, writing stories, coding, and translating languages. LLMs are powered by deep learning techniques and have revolutionized natural language processing by enabling more context-aware and versatile interactions with text. Examples include models like GPT, BERT, and others developed by companies like OpenAI and Alibaba.6.3 使用建议与注意事项演示目的示例中thinking_budget16仅为展示流程实际使用不要设置这么低预算调优建议根据可接受的延迟来调节thinking_budget并且设置高于 1024才能在任务中产生有意义的改进完全不想思考怎么办如果完全不需要思考应使用硬开关enable_thinkingFalse或上文的自定义 chat template而不是把预算设得很低第二次生成的 max_new_tokensinput_length max_new_tokens - input_ids.size(-1)在预算太小、提前停止文本约 24 tokens导致长度超标时可能为负数实际使用时请保证max_new_tokens足够大。OpenAI 兼容 API 版本的思考预算仓库中的 thinking_budget.md 还提供了面向 API 服务的ThinkingBudgetClient实现思路需transformers4.51.0、openai1.65.0先调用 chat completions 拿到reasoning_content此时content可能为 None表示思考内容过长把think\n{reasoning_content}\n/think\n\n追加为 assistant 消息再以continue_final_messageTrue应用聊天模板、调用client.completions.create获取剩余的回答并对剩余 token 数为正做断言。这种模式适合部署在 vLLM/SGLang 服务上做服务端思考预算控制。七、下一步从快速上手到深入实践跑通本指南后你可以按需继续深入批量推理与流式输出、思考内容解析、长上下文YaRN见 Transformers 推理指南其中演示了pipeline()接口、device_map/torch_dtype参数含义以及通过rope_scaling将上下文扩展到 131,072 tokens 的方法本地运行llama.cpp、Ollama、LM Studio、MLX-LM 的本地推理说明见 run_locally 文档 等大规模部署SGLang / vLLM / TGI 的完整部署参数张量并行、量化模型、JSON 结构化输出、context length 与 OOM 排障见 部署文档评测复现仓库 eval/README.md 提供了用 vLLM/SGLang 启动推理服务后配合多线程推理脚本与评分脚本复现基准成绩的完整流程对话 Demo仓库 examples/demo/cli_demo.py 提供了带命令面板、历史管理、随机种子与生成配置在线调整的交互式命令行聊天示例可直接python cli_demo.py -c checkpoint运行体验。现在你可以开始尽情体验 Qwen3 模型了。【免费下载链接】Qwen1.5Qwen3 is the large language model series developed by Qwen team, Alibaba Cloud.项目地址: https://gitcode.com/GitHub_Trending/qw/Qwen1.5创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网