vLLM — 高吞吐推理加速
简介
vLLM 通过 PagedAttention 技术将 LLM 推理吞吐量提升 24x,是生产环境本地模型部署的首选。
bash
pip install vllm核心优势
- PagedAttention:KV Cache 分页管理,显存利用率提升 3-4x
- 连续批处理:动态合并请求,GPU 利用率接近 100%
- 前缀缓存:相同 system prompt 的 KV Cache 复用
离线批量推理
python
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2-7B-Instruct",
gpu_memory_utilization=0.85,
max_model_len=4096,
dtype="float16"
)
sampling_params = SamplingParams(
temperature=0.7,
top_p=0.9,
max_tokens=512,
stop=["<|endoftext|>"]
)
# 批量处理(自动优化)
prompts = [f"分析企业{i}的贷款风险" for i in range(100)]
outputs = llm.generate(prompts, sampling_params)
for i, output in enumerate(outputs):
print(f"企业{i}: {output.outputs[0].text[:100]}")OpenAI 兼容 API 服务
bash
# 启动服务
python -m vllm.entrypoints.openai.api_server \
--model Qwen/Qwen2-7B-Instruct \
--host 0.0.0.0 \
--port 8080 \
--max-model-len 8192 \
--gpu-memory-utilization 0.9 \
--enable-prefix-caching \ # 启用前缀缓存
--served-model-name qwen2-7bpython
# 客户端(与 OpenAI SDK 完全兼容)
from openai import OpenAI
client = OpenAI(api_key="vllm", base_url="http://localhost:8080/v1")
# 流式输出
stream = client.chat.completions.create(
model="qwen2-7b",
messages=[{"role": "user", "content": "分析银行股投资价值"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")性能对比
| 方案 | 吞吐量(tokens/s) | 显存利用率 |
|---|---|---|
| HuggingFace 原生 | ~100 | 40-60% |
| vLLM | ~2400 | 85-95% |
| vLLM + 前缀缓存 | ~3000+ | 85-95% |
Docker 部署
dockerfile
FROM vllm/vllm-openai:latest
ENV MODEL_NAME=Qwen/Qwen2-7B-Instruct
ENV GPU_MEMORY_UTILIZATION=0.9
CMD python -m vllm.entrypoints.openai.api_server \
--model $MODEL_NAME \
--host 0.0.0.0 \
--port 8080 \
--gpu-memory-utilization $GPU_MEMORY_UTILIZATION \
--enable-prefix-caching选型建议
- API 调用(千问/ChatGLM):无需 vLLM,直接调用云端 API
- 私有化部署 < 10 QPS:Ollama 更简单
- 私有化部署 > 10 QPS:vLLM 是必选