Qwen3.5-4B vLLM 部署调用实战:混合注意力架构的高吞吐推理服务指南
2026/9/12 16:14:36 网站建设 项目流程

Qwen3.5-4B vLLM 部署调用实战:混合注意力架构的高吞吐推理服务指南

【免费下载链接】self-llm《开源大模型食用指南》针对中国宝宝量身打造的基于Linux环境快速微调(全参数/Lora)、部署国内外开源大模型(LLM)/多模态大模型(MLLM)教程项目地址: https://gitcode.com/GitHub_Trending/se/self-llm

本文基于self-llm仓库中 models/Qwen3.5/01-Qwen3.5-4B-vLLM 部署调用.md 的实测记录,完整演示如何在 Linux + NVIDIA GPU 环境下,使用vLLMQwen3.5-4B这一采用 Gated Delta Network(GDN)混合注意力架构的统一视觉-语言模型进行环境搭建、模型下载、OpenAI 兼容 API 服务启动与调用(含思考模式/非思考模式、多模态图文、离线推理)。读完本文,你将掌握一套可复现、可直接落地的 vLLM 部署与调用方案,并理解 PagedAttention 内存管理、算子自动选择、KV Cache 配置等底层原理。

vLLM 简介

vLLM是一个高效的大语言模型推理和部署服务系统,其核心特性如下:

  • 高效的内存管理:通过PagedAttention算法,vLLM实现了对KV缓存的高效管理,减少了内存浪费,优化了模型的运行效率。
  • 高吞吐量vLLM支持异步处理和连续批处理请求,显著提高了模型推理的吞吐量,加速了文本生成和处理速度。
  • 易用性vLLMHuggingFace模型无缝集成,支持多种流行的大型语言模型,简化了模型部署和推理的过程,并兼容OpenAIAPI服务器。
  • 多模态vLLM同时支持文本与多模态(图像/视频)推理,Qwen3.5-4B作为统一视觉-语言底座,可在vLLM中直接提供图文服务。

Qwen3.5官方明确说明模型权重同时兼容Hugging Face TransformersvLLMSGLangKTransformers等推理框架。本教程使用vLLM进行部署,文中的启动日志与接口返回均为实测真实输出。仓库中另有 Qwen3.5-4B SGLang 部署调用 与 Qwen3.5-4B LoRA 微调记录 可作交叉参考。

关于 Qwen3.5-4B 架构

Qwen3.5-4B采用高效的混合架构:将Gated Delta Network(门控增量网络,一种线性注意力)与传统全注意力(Full Attention)层交错堆叠(每 4 层中 3 层线性注意力 + 1 层全注意力),在保持强大能力的同时大幅降低长序列的推理显存与延迟。

从仓库配套的 LoRA 微调文档 可以进一步确认:该模型的 32 层中有 24 层是 GDN 线性注意力层,其余 8 层为全注意力层;模型内置视觉编码器(Vision Encoder),支持最长262144(256K)上下文;默认开启**思维链(Thinking)**模式,在最终回答前生成<think> ... </think>推理过程。

由于该架构较新,请确保安装较新版本的vLLM(本教程实测vLLM 0.23.0)与transformers>=4.57,以保证对qwen3_5模型类型的支持。vLLM 启动时会自动识别并选用Triton/FLA GDN线性注意力算子,无需手动干预。

环境准备

本文实测基础环境如下:

---------------- ubuntu 22.04 python 3.12 NVIDIA 驱动 580.105.08(支持 CUDA 13.0) GPU: RTX 4090 D (24G) torch 2.11.0+cu128 vllm 0.23.0 ----------------

本文默认学习者已配置好Pytorch (cuda)环境,如未配置请先自行安装。

首先pip换源加速下载并安装依赖包:

python -m pip install --upgrade pip pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple pip install modelscope pip install "transformers>=4.57" pip install openai

安装vLLMvLLM 0.23.0是基于CUDA 13编译的版本,其编译扩展vllm._C依赖libcudart.so.13;而默认从镜像源安装的torch是 CPU 版本,无法使用 GPU。因此需要先从 PyTorch 官方源安装带 CUDA 的torch 2.11.0

# 先装带 CUDA 的 torch(vLLM 0.23 需要 torch==2.11.0) pip install torch==2.11.0 torchvision==0.26.0 torchaudio==2.11.0 \ --index-url https://download.pytorch.org/whl/cu128 # 再装 vLLM(会自动拉取 flashinfer、cutlass-dsl、humming-kernels 等依赖) pip install "vllm==0.23.0"

重要:设置 CUDA 库搜索路径。由于vLLM 0.23.0是 CUDA 13 构建,而上面装的是torch+cu128,启动时会报ImportError: libcudart.so.13: cannot open shared object filevLLM的依赖已经把 CUDA 13 运行库装到了site-packages/nvidia/下,只需把这些路径加入LD_LIBRARY_PATH即可:

# 写入 ~/.bashrc 永久生效 NVLIB=$(find /root/miniconda3/lib/python3.12/site-packages/nvidia -type d -name lib | tr '\n' ':') echo "export LD_LIBRARY_PATH=\${NVLIB}\${LD_LIBRARY_PATH:-}" >> ~/.bashrc source ~/.bashrc # 验证 vLLM 可正常导入 python -c "import vllm; print(vllm.__version__)"

若你的显卡驱动支持 CUDA 13(如本文 580.105.08),也可以直接安装torch+cu130--index-url https://download.pytorch.org/whl/cu130),与vLLM 0.23.0完全匹配,则无需上述LD_LIBRARY_PATH设置。

安装顺序的经验总结:由于vLLM 0.23.0torch版本有强约束(torch==2.11.0),务必先通过 PyTorch 官方索引安装带 CUDA 的 torch,再安装 vLLM;若先装 vLLM 再装 torch,容易因 torch 被覆盖为 CPU 版本或版本不匹配导致vllm._C编译扩展加载失败。

模型下载

使用 modelscope 中的snapshot_download函数下载模型,第一个参数为模型名称,参数cache_dir为模型的下载路径。

新建model_download.py文件并在其中输入以下内容,粘贴代码后记得保存文件。

# model_download.py from modelscope import snapshot_download model_dir = snapshot_download('Qwen/Qwen3.5-4B', cache_dir='/root/autodl-tmp') print(f"模型下载完成,保存路径为:{model_dir}")

然后在终端中输入python model_download.py执行下载,这里需要耐心等待一段时间直到模型下载完成。

注意:记得修改cache_dir为你的模型下载路径哦~

创建兼容 OpenAI API 接口的服务器

Qwen3.5-4B兼容OpenAI API协议,我们可以直接使用vLLM创建OpenAI API服务器。默认会在http://localhost:8000启动服务器,实现模型列表、completionschat completions端口。

常用启动参数

参数作用本文建议值
--host/--port指定地址与端口0.0.0.0/8000
--model模型路径/root/autodl-tmp/Qwen/Qwen3.5-4B
--served-model-name服务对外的模型名称Qwen3.5-4B
--max-model-len模型最大上下文长度4B 模型在 24G 显存上建议4096,显存富余可调大
--gpu-memory-utilizationGPU 显存占用比例默认0.9,显存紧张可调低
--trust-remote-code信任远程代码需显式开启

复制以下命令到终端,即可启动 Qwen3.5-4B 的 API 服务:

vllm serve /root/autodl-tmp/Qwen/Qwen3.5-4B \ --served-model-name Qwen3.5-4B \ --max-model-len 4096 \ --gpu-memory-utilization 0.9 \ --trust-remote-code \ --host 0.0.0.0 --port 8000

启动日志解读

启动过程中会打印大量日志,关键的实测启动日志如下(vLLM 识别出Qwen3_5ForConditionalGeneration架构,并为线性注意力层选用 GDN 算子):

对应的关键日志行(已去除颜色码):

(APIServer) INFO [model.py:611] Resolved architecture: Qwen3_5ForConditionalGeneration (APIServer) INFO [model.py:1745] Using max model len 4096 (EngineCore) INFO [core.py:113] Initializing a V1 LLM engine (v0.23.0) ... (EngineCore) INFO [topk_topp_sampler.py:55] Using FlashInfer for top-p & top-k sampling. (EngineCore) INFO [gpu_model_runner.py:5092] Starting to load model /root/autodl-tmp/Qwen/Qwen3.5-4B... (EngineCore) INFO [qwen_gdn_linear_attn.py:228] Using Triton/FLA GDN prefill kernel (requested=auto, head_k_dim=128). (EngineCore) INFO [cuda.py:378] Using FLASH_ATTN attention backend out of potential backends: ['FLASH_ATTN', 'FLASHINFER', 'TRITON_ATTN', 'FLEX_ATTENTION']. (EngineCore) INFO [default_loader.py:397] Loading weights took 2.35 seconds (EngineCore) INFO [gpu_model_runner.py:5187] Model loading took 8.61 GiB memory and 3.16 seconds (EngineCore) INFO [monitor.py:53] torch.compile took 48.51 s in total (EngineCore) INFO [gpu_worker.py:480] Available KV cache memory: 10.21 GiB (EngineCore) INFO [kv_cache_utils.py:1744] GPU KV cache size: 235,706 tokens (EngineCore) INFO [core.py:306] init engine (profile, create kv cache, warmup model) took 286.39 s (compilation: 48.51 s) (APIServer) INFO: Application startup complete.

从日志可以读出以下关键信息:

  • 架构自动识别Resolved architecture: Qwen3_5ForConditionalGeneration,vLLM 无需手动指定模型类型;
  • GDN 算子自动启用qwen_gdn_linear_attn.py:228输出Using Triton/FLA GDN prefill kernel (requested=auto, head_k_dim=128),说明 vLLM 已为混合架构中的线性注意力层自动选用 GDN 加速算子;同时全注意力层选用FLASH_ATTN后端(候选列表中还包含FLASHINFERTRITON_ATTNFLEX_ATTENTION);
  • 内存布局:模型权重加载占用8.61 GiB,可用 KV cache 显存10.21 GiB,GPU KV cache 容量235,706 tokens——这正是 PagedAttention 分页管理 KV 缓存的结果;
  • 首次启动耗时torch.compile编译约48.51 s,引擎初始化(profile、创建 KV cache、warmup)总计约286.39 s

说明:首次启动会触发torch.compile编译与 profiling warmup(实测初始化耗时约 286s),编译结果会缓存到~/.cache/vllm/,后续启动会明显加快。出现Application startup complete.即说明服务成功启动。

验证服务:查看模型列表

通过curl命令查看当前的模型列表:

curl http://localhost:8000/v1/models

实测返回值如下所示:

{ "object": "list", "data": [ { "id": "Qwen3.5-4B", "object": "model", "created": 1781610820, "owned_by": "vllm", "root": "/root/autodl-tmp/Qwen/Qwen3.5-4B", "parent": null, "max_model_len": 4096 } ] }

/v1/models返回的max_model_len与启动参数--max-model-len一致,owned_byvllm;若需在代码中动态获取服务能力,可先请求该接口读取字段后再发起调用。

思考模式与非思考模式

Qwen3.5默认开启思考模式。在chat/completions接口中,可通过chat_template_kwargs.enable_thinking请求级别控制:

  • 默认(思考模式):模型先输出<think> ... </think>推理过程,再给出最终答案
  • 非思考模式:传入enable_thinking=false,模型不输出<think>标签

用 curl 测试 Chat Completions(思考模式)

curl http://localhost:8000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "Qwen3.5-4B", "messages": [ {"role": "user", "content": "5的阶乘是多少?"} ], "temperature": 1.0, "top_p": 0.95, "max_tokens": 768, "extra_body": {"chat_template_kwargs": {"enable_thinking": true}} }'

实测返回值如下所示(content中先是<think> ... </think>思考过程,其后是最终答案,finish_reasonstop表示正常结束):

{ "id": "chatcmpl-984a75743a984720", "object": "chat.completion", "model": "Qwen3.5-4B", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Here's a thinking process that leads to the answer:\n\n1. **Analyze the Request:** 用户问的是 5 的阶乘 ...\n2. **Define Factorial:** n! = n × (n-1) × ... × 1\n3. **Calculate 5!:** 5 × 4 = 20, 20 × 3 = 60, 60 × 2 = 120, 120 × 1 = 120\n...\n</think>\n\n5 的阶乘(记作 5!)是 **120**。\n\n计算过程如下:\n$$5! = 5 \\times 4 \\times 3 \\times 2 \\times 1 = 120$$" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 16, "completion_tokens": 590, "total_tokens": 606 } }

可以看到,开启思考模式时,模型先在<think> ... </think>中给出推理过程,再输出最终答案5 的阶乘是 120usage字段返回了本次请求的 token 消耗明细,可用于计费与限流统计。

用 Python 脚本请求(非思考模式)

# vllm_openai_chat_completions.py from openai import OpenAI client = OpenAI( api_key="sk-xxx", # 随便填写,只是为了通过接口参数校验 base_url="http://localhost:8000/v1", ) # 非思考模式:传入 enable_thinking=false chat_outputs = client.chat.completions.create( model="Qwen3.5-4B", messages=[{"role": "user", "content": "用一句话介绍深度学习。"}], extra_body={"chat_template_kwargs": {"enable_thinking": False}}, ) print(chat_outputs.choices[0].message.content)
python vllm_openai_chat_completions.py

实测发现:Qwen3.5-4B即使在非思考模式下,也可能在content开头先输出一段简短的「思考过程」文字(不再用<think>标签包裹),随后才给出最终回答,且小模型容易在max_tokens较小时被截断(finish_reason: length)。如需直接、简短的回答,可适当调大max_tokens或换用更大的型号。

运行时日志

在请求处理过程中,API后端会持续打印对应的日志与统计信息(吞吐、显存占用等),便于观测服务状态。实测的运行时日志如下:

(EngineCore) INFO [core.py:306] init engine (profile, create kv cache, warmup model) took 286.39 s (compilation: 48.51 s) (APIServer) INFO [base.py:227] Multi-modal warmup completed in 25.118s (APIServer) INFO: Application startup complete. (APIServer) INFO: 127.0.0.1:34042 - "POST /v1/chat/completions HTTP/1.1" 200 OK (APIServer) INFO [loggers.py:271] Engine 000: Avg prompt throughput: 0.9 tokens/s, Avg generation throughput: 6.3 tokens/s, Running: 1 reqs, Waiting: 0 reqs, GPU KV cache usage: 0.6% (APIServer) INFO: 127.0.0.1:41708 - "POST /v1/chat/completions HTTP/1.1" 200 OK

日志中的关键指标解读:

  • Multi-modal warmup completed in 25.118s:由于模型自带视觉编码器,vLLM 启动时会对多模态组件做预热;
  • Avg prompt throughput/Avg generation throughput:分别为输入(prefill)与输出(decode)阶段的平均吞吐,6.3 tokens/s为实测的单请求生成吞吐;
  • GPU KV cache usage: 0.6%:当前 KV cache 占用率,可用于判断服务的并发余量。

多模态(图文)调用示例

由于Qwen3.5-4B自带视觉编码器,vLLM部署后也支持图像输入:

# vllm_multimodal.py from openai import OpenAI client = OpenAI(api_key="sk-xxx", base_url="http://localhost:8000/v1") response = client.chat.completions.create( model="Qwen3.5-4B", messages=[{ "role": "user", "content": [ {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}, {"type": "text", "text": "请描述这张图片的内容。"}, ], }], ) print(response.choices[0].message.content)

提示:多模态请求需要 vLLM 加载模型的视觉部分。若只需文本服务、希望进一步节省显存,可使用--limit-mm-per-prompt '{"image": 0}'关闭图像输入。

离线推理(可选)

除启动服务外,也可以直接用vLLMLLM引擎做离线推理:

# vllm_model.py from vllm import LLM, SamplingParams from transformers import AutoTokenizer model = '/root/autodl-tmp/Qwen/Qwen3.5-4B' tokenizer = AutoTokenizer.from_pretrained(model, use_fast=False) messages = [{"role": "user", "content": "你是谁?"}] text = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, enable_thinking=False, # 关闭思考模式 ) # 官方推荐非思考模式参数:temperature=0.7, top_p=0.8, top_k=20, presence_penalty=1.5 sampling_params = SamplingParams(temperature=0.7, top_p=0.8, top_k=20, max_tokens=512, presence_penalty=1.5) llm = LLM(model=model, max_model_len=4096, trust_remote_code=True) outputs = llm.generate([text], sampling_params) print(outputs[0].outputs[0].text)

与在线服务模式相比,离线推理直接实例化LLM引擎,省去了 HTTP 层的开销,适合批量评测、数据处理等脚本化场景;在线模式则适合对外提供服务、支撑多客户端并发请求。

采样参数建议

采样参数建议(来自 Qwen 官方)

  • 思考模式(通用任务):temperature=1.0, top_p=0.95, top_k=20, presence_penalty=1.5
  • 思考模式(精确编码):temperature=0.6, top_p=0.95, top_k=20, presence_penalty=0.0
  • 非思考模式(通用任务):temperature=0.7, top_p=0.8, top_k=20, presence_penalty=1.5

注意:不同推理框架对采样参数的支持情况略有差异,请以实际为准。

不同任务建议按上述参数组合进行配置:通用任务采用较高的随机性(temperature=1.0)与presence_penalty=1.5抑制重复;精确编码类任务降低temperature并关闭presence_penalty,以获得更确定、更严谨的输出;非思考模式则建议temperature=0.7, top_p=0.8兼顾流畅与稳定。

小结

本文基于vLLM 0.23.0完成了Qwen3.5-4B从环境搭建、模型下载到 OpenAI 兼容 API 服务的完整部署闭环,并覆盖了思考/非思考模式、多模态图文输入与离线推理三种典型调用方式。部署过程中有两点最值得注意:

  1. 版本强约束vLLM 0.23.0需要torch==2.11.0且基于 CUDA 13 构建,安装时务必先装带 CUDA 的 torch,再按本文方式设置LD_LIBRARY_PATH,否则会报libcudart.so.13缺失;
  2. 架构适配无需干预:vLLM 会自动识别Qwen3_5ForConditionalGeneration架构并为 GDN 线性注意力层启用Triton/FLA算子,首次启动的编译与 warmup 耗时较长属正常现象,缓存后再次启动会显著加快。

仓库中models/Qwen3.5目录还提供 SGLang 部署教程 与 LoRA 微调教程,分别覆盖另一主流推理框架与微调侧实践,可供对比选型。该模型在 support_model.md 的 Qwen3.5 章节中亦有收录索引,说明其是本仓库长期维护的教程对象。

【免费下载链接】self-llm《开源大模型食用指南》针对中国宝宝量身打造的基于Linux环境快速微调(全参数/Lora)、部署国内外开源大模型(LLM)/多模态大模型(MLLM)教程项目地址: https://gitcode.com/GitHub_Trending/se/self-llm

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询