vLLM/SGLang/TensorRT-LLM、PagedAttention、Continuous Batching、Speculative Decoding
大模型推理引擎是连接模型与用户的关键中间件,负责批处理调度、显存管理、KV Cache优化和高效kernel调度。三大主流引擎各有侧重。
| 特性 | vLLM | SGLang | TensorRT-LLM |
|---|---|---|---|
| 开发方 | UC Berkeley | UC Berkeley (Lianmin) | NVIDIA |
| 核心创新 | PagedAttention | RadixAttention + 结构化生成 | Tensor Core深度融合 |
| 吞吐量 | 高 | 最高(复杂场景) | 最高(NVIDIA GPU) |
| 延迟 | 中 | 低(前缀复用) | 最低(kernel优化) |
| 易用性 | 高(OpenAI兼容API) | 高(类vLLM接口) | 中(需构建引擎) |
| 硬件支持 | NVIDIA/AMD/CPU | NVIDIA/AMD | 仅NVIDIA |
| 量化支持 | AWQ/GPTQ/FP8/INT8 | AWQ/GPTQ/FP8 | INT4/INT8/FP8 |
| 结构化生成 | outlines(基础) | 原生(regex/JSON/EBNF) | 有限支持 |
| 适用场景 | 通用在线服务 | Agent/多轮/结构化 | 极致延迟/吞吐 |
PagedAttention(vLLM, Kwon et al., 2023)借鉴操作系统的虚拟内存分页机制,将KV Cache按固定大小的block存储,消除内存碎片,实现近乎零浪费的显存利用。
传统推理为每个请求预分配最大长度的连续KV Cache空间。问题:(1) 内部碎片——实际输出远短于最大长度时浪费显存;(2) 外部碎片——请求释放后留下不连续空间;(3) 共享内存无法实现——同一前缀的请求无法复用KV Cache。
# PagedAttention: 分页KV Cache管理
import torch
class PagedAttentionCache:
"""
分页KV Cache: 将KV Cache分成固定大小的block
每个block存储block_size个token的KV
"""
def __init__(
self,
num_layers,
num_heads,
head_dim,
num_blocks, # 总block数 (决定显存容量)
block_size=16, # 每block的token数 (通常16)
dtype=torch.float16,
):
self.block_size = block_size
self.num_blocks = num_blocks
# 物理存储: 所有block连续分配
# shape: [num_blocks, num_layers, 2(K+V), num_heads, block_size, head_dim]
self.kv_cache = torch.zeros(
num_blocks, num_layers, 2, num_heads, block_size, head_dim,
dtype=dtype, device="cuda"
)
# 空闲block池
self.free_blocks = list(range(num_blocks))
# 每个序列的block映射表 (逻辑->物理)
self.block_tables = {} # {seq_id: [physical_block_ids]}
def allocate(self, seq_id, num_tokens):
"""为序列分配KV Cache blocks"""
num_blocks_needed = (num_tokens + self.block_size - 1) // self.block_size
if len(self.free_blocks) < num_blocks_needed:
raise RuntimeError("显存不足")
# 从空闲池分配
allocated = [self.free_blocks.pop() for _ in range(num_blocks_needed)]
self.block_tables[seq_id] = allocated
def append_kv(self, seq_id, token_positions, new_k, new_v, layer_idx):
"""将新的K/V写入对应block"""
block_table = self.block_tables[seq_id]
for i, pos in enumerate(token_positions):
block_idx = pos // self.block_size # 逻辑block索引
offset = pos % self.block_size # block内偏移
physical_block = block_table[block_idx]
# 写入物理block
self.kv_cache[physical_block, layer_idx, 0, :, offset] = new_k[i]
self.kv_cache[physical_block, layer_idx, 1, :, offset] = new_v[i]
def get_block_table(self, seq_id):
"""获取序列的物理block映射表 (用于attention计算)"""
return self.block_tables[seq_id]
def free(self, seq_id):
"""释放序列的blocks回空闲池"""
for block_id in self.block_tables[seq_id]:
self.free_blocks.append(block_id)
del self.block_tables[seq_id]
def can_share_prefix(self, new_tokens, existing_seq_id):
"""检查是否可以共享前缀KV Cache (prefix caching)"""
existing_table = self.block_tables[existing_seq_id]
# 比较token前缀, 匹配的block可以共享
return compute_shared_blocks(new_tokens, existing_table)
| 方法 | 显存利用率 | 碎片 | 最大并发 | 前缀共享 |
|---|---|---|---|---|
| 预分配 | ~20-40% | 严重 | 低 | 不支持 |
| 动态分配 | ~60-80% | 中等 | 中 | 不支持 |
| PagedAttention | >95% | 几乎无 | 高 | 支持 |
传统批处理在所有请求完成后才能释放batch槽位,导致短请求等待长请求。Continuous Batching在每个token生成后动态加入/移除请求,保持GPU持续高利用率。
# Continuous Batching调度器
import time
from collections import deque
class ContinuousBatchingScheduler:
"""
动态批处理: 每个iteration后检查:
- 完成的请求移出batch
- 等待的请求加入batch
- 保持batch大小接近max_batch_size
"""
def __init__(self, max_batch_size=256, max_tokens_per_batch=8192):
self.max_batch_size = max_batch_size
self.max_tokens_per_batch = max_tokens_per_batch
self.running = [] # 正在运行的请求
self.waiting = deque() # 等待队列
def add_request(self, request):
"""添加新请求到等待队列"""
self.waiting.append(request)
def schedule(self):
"""调度: 返回当前iteration要执行的batch"""
# Step 1: 移除已完成的请求
self.running = [req for req in self.running
if not req.is_finished()]
# Step 2: 从等待队列添加新请求
while self.waiting and len(self.running) < self.max_batch_size:
# 检查token预算
total_tokens = sum(req.num_tokens for req in self.running)
new_req = self.waiting[0]
if total_tokens + new_req.num_tokens > self.max_tokens_per_batch:
break # 超出token预算, 等下轮
self.running.append(self.waiting.popleft())
return self.running
def run(self, model, kv_cache):
"""主循环: continuous batching推理"""
while self.running or self.waiting:
batch = self.schedule()
if not batch:
continue
# 执行一步推理 (所有请求并行生成一个token)
for req in batch:
if req.is_prefill_phase:
# Prefill: 处理整个prompt
output = model.prefill(req.prompt, kv_cache, req.seq_id)
req.is_prefill_phase = False
else:
# Decode: 生成一个token
token = model.decode(kv_cache, req.seq_id)
req.add_token(token)
# 检查停止条件
if token == model.eos_token or req.num_tokens >= req.max_tokens:
req.finish()
| 批处理方式 | 吞吐量 (tok/s) | GPU利用率 | P99延迟 |
|---|---|---|---|
| 静态批处理 | ~2000 | ~40% | 高(等待最长请求) |
| Continuous Batching | ~8000 | ~90% | 低(即时加入) |
| CB + PagedAttention | ~12000 | ~95% | 低 |
Speculative Decoding(Leviathan et al., 2023)使用一个小模型快速生成多个候选token,大模型并行验证,接受正确的前缀。在保持输出完全一致的前提下加速2-3倍。
给定大模型p和草稿模型q:(1) 草稿模型自回归生成γ个候选token;(2) 大模型并行计算这γ个token的概率;(3) 逐个检查:若p(x) ≥ q(x)则接受,否则以概率p(x)/q(x)接受,拒绝则从修正分布resample。保证最终分布与大模型完全一致。
import torch
import torch.nn.functional as F
# Speculative Decoding完整实现
def speculative_decode(
target_model, # 大模型 (验证)
draft_model, # 小模型 (草稿)
input_ids, # 当前序列
gamma=4, # 草稿长度
max_tokens=100,
):
"""
投机解码: 保证输出分布与target_model完全一致
"""
generated = input_ids.clone()
while generated.shape[1] < input_ids.shape[1] + max_tokens:
# Step 1: 草稿模型快速生成gamma个候选token
draft_tokens = []
draft_probs = []
current = generated
for _ in range(gamma):
with torch.no_grad():
logits = draft_model(current)
probs = F.softmax(logits[:, -1, :], dim=-1)
# 采样
token = torch.multinomial(probs, num_samples=1)
draft_tokens.append(token)
draft_probs.append(probs)
current = torch.cat([current, token], dim=-1)
draft_tokens = torch.cat(draft_tokens, dim=-1) # [1, gamma]
# Step 2: 大模型并行验证 (一次前向传播)
with torch.no_grad():
verify_input = torch.cat([generated, draft_tokens[:, :-1]], dim=-1)
target_logits = target_model(verify_input)
target_probs = F.softmax(target_logits[:, -gamma:, :], dim=-1)
# Step 3: 逐个验证 (接受/拒绝)
accepted = 0
for i in range(gamma):
draft_token = draft_tokens[:, i]
p = target_probs[:, i, draft_token] # 大模型概率
q = draft_probs[i][:, draft_token] # 草稿模型概率
# 接受条件: r < min(1, p/q)
r = torch.rand(1, device=p.device)
if r < torch.min(torch.ones_like(p), p / q.clamp(min=1e-10)):
# 接受这个token
generated = torch.cat([generated, draft_token.unsqueeze(-1)], dim=-1)
accepted += 1
else:
# 拒绝: 从修正分布采样
# rescale: norm(max(0, p - q))
adjusted_probs = torch.clamp(target_probs[:, i, :] - draft_probs[i], min=0)
adjusted_probs = adjusted_probs / adjusted_probs.sum()
resampled = torch.multinomial(adjusted_probs, num_samples=1)
generated = torch.cat([generated, resampled], dim=-1)
break
# 如果所有gamma个token都被接受, 额外采样一个
if accepted == gamma:
with torch.no_grad():
logits = target_model(generated)
probs = F.softmax(logits[:, -1, :], dim=-1)
extra_token = torch.multinomial(probs, num_samples=1)
generated = torch.cat([generated, extra_token], dim=-1)
return generated
| 草稿模型 | 接受率 | 加速比 | 输出一致性 |
|---|---|---|---|
| 同系列小模型 | ~80% | 2.5-3× | 100%一致 |
| 蒸馏模型 | ~90% | 3-4× | 100%一致 |
| n-gram模型 | ~60% | 1.5-2× | 100%一致 |
| Medusa多头 | N/A | 2-3× | 100%一致 |
多轮对话和Agent场景中,多个请求共享相同的前缀(system prompt、few-shot examples)。Prefix Caching复用已计算的KV Cache,避免重复计算。
# RadixAttention: 用Radix Tree管理前缀复用
class RadixTreeNode:
"""Radix Tree节点: 存储token序列和对应的KV Cache blocks"""
def __init__(self):
self.token_ids = [] # 该节点的token序列
self.children = {} # 子节点 (token_id -> node)
self.kv_cache_blocks = [] # 对应的物理KV Cache blocks
self.ref_count = 0 # 引用计数 (LRU用)
self.last_access = 0 # 最后访问时间
class RadixAttentionCache:
"""
RadixAttention: 用Radix Tree自动发现和管理前缀复用
- 插入新序列时自动匹配最长公共前缀
- 共享前缀的KV Cache blocks
- LRU淘汰不活跃的blocks
"""
def __init__(self, kv_cache_manager):
self.root = RadixTreeNode()
self.kv_cache = kv_cache_manager # PagedAttention cache
self.global_time = 0
def match_prefix(self, token_ids):
"""在Radix Tree中匹配最长公共前缀, 返回复用的blocks"""
node = self.root
matched_blocks = []
matched_len = 0
remaining = token_ids
while remaining:
# 找到匹配的子节点
first_token = remaining[0]
if first_token not in node.children:
break
child = node.children[first_token]
# 匹配child的token序列
match_len = 0
for i, t in enumerate(child.token_ids):
if i >= len(remaining) or remaining[i] != t:
break
match_len += 1
# 复用匹配的KV Cache blocks
matched_blocks.extend(child.kv_cache_blocks[:match_len])
matched_len += match_len
remaining = remaining[match_len:]
if match_len == len(child.token_ids):
node = child # 完全匹配, 继续向下
else:
break # 部分匹配, 需要分裂
return matched_blocks, matched_len, remaining
def insert(self, token_ids, kv_blocks):
"""插入新序列, 自动复用前缀"""
matched_blocks, matched_len, remaining = self.match_prefix(token_ids)
# 只需要计算remaining部分的KV Cache
# matched_blocks直接复用!
if remaining:
# 插入新节点到Radix Tree
self._insert_tokens(self.root, remaining, kv_blocks[len(matched_blocks):])
return matched_len, len(remaining) # 复用长度, 需计算长度
def evict_lru(self):
"""LRU淘汰: 释放最久未访问的blocks"""
# 找到ref_count=0且last_access最老的节点
# 释放其kv_cache_blocks回空闲池
pass
| 场景 | 前缀复用率 | TTFT加速 | 说明 |
|---|---|---|---|
| 多轮对话 | 80-95% | 5-10× | 历史消息完全复用 |
| Agent工具调用 | 70-90% | 3-5× | system prompt+工具定义复用 |
| Few-shot推理 | 90-99% | 10× | 示例前缀完全复用 |
| 独立请求 | 0% | 1× | 无前缀可复用 |
Prefill阶段(处理prompt)计算密集,Decode阶段(生成token)访存密集。混合时prefill会阻塞decode,导致延迟尖峰。Chunked Prefill将长prompt分块处理,与decode交替执行。
# Chunked Prefill: 将长prompt分块, 与decode交替
class ChunkedPrefillScheduler:
"""
每个iteration:
1. 优先执行decode (低延迟)
2. 用剩余token预算执行prefill chunk
3. 长prompt分多次完成prefill
"""
def __init__(self, max_tokens_per_iter=512, chunk_size=512):
self.max_tokens_per_iter = max_tokens_per_iter
self.chunk_size = chunk_size
self.decode_queue = [] # decode请求
self.prefill_queue = [] # prefill请求 (可能分块)
def schedule(self):
"""调度一个iteration的token预算"""
token_budget = self.max_tokens_per_iter
batch = {"decode": [], "prefill": []}
# Step 1: 优先调度所有decode (每个请求1个token)
for req in self.decode_queue:
if token_budget <= 0:
break
batch["decode"].append(req)
token_budget -= 1
# Step 2: 用剩余预算调度prefill chunks
while self.prefill_queue and token_budget > 0:
req = self.prefill_queue[0]
# 计算本次chunk大小
remaining = len(req.prompt) - req.prefill_progress
chunk_len = min(remaining, self.chunk_size, token_budget)
# 调度这个chunk
batch["prefill"].append({
"request": req,
"start": req.prefill_progress,
"length": chunk_len,
})
req.prefill_progress += chunk_len
token_budget -= chunk_len
# 如果prefill完成, 移到decode队列
if req.prefill_progress >= len(req.prompt):
self.prefill_queue.pop(0)
self.decode_queue.append(req)
return batch
def run_iteration(self, model, kv_cache):
"""执行一个iteration: decode + prefill chunk混合"""
batch = self.schedule()
# 一次前向传播同时处理decode和prefill chunk
# 利用attention的causal mask正确处理混合batch
if batch["decode"] or batch["prefill"]:
outputs = model.forward_mixed(batch, kv_cache)
return outputs
# vLLM基础部署: OpenAI兼容API
pip install vllm
# 单GPU部署
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-8B-Instruct \
--port 8000 \
--max-model-len 8192
# 使用Python API
from vllm import LLM, SamplingParams
llm = LLM(model="meta-llama/Meta-Llama-3-8B-Instruct", max_model_len=8192)
sampling = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=500)
outputs = llm.generate(["什么是深度学习?", "解释量子计算。"], sampling)
for output in outputs:
print(output.outputs[0].text)
# 多GPU张量并行
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-70B-Instruct \
--tensor-parallel-size 4 \
--port 8000 \
--max-model-len 32768
# AWQ量化部署
python -m vllm.entrypoints.openai.api_server \
--model TheBloke/Llama-3-70B-AWQ \
--quantization awq \
--port 8000
# FP8量化 (H100)
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-70B-Instruct \
--quantization fp8 \
--kv-cache-dtype fp8 \
--port 8000
# 长上下文 + Chunked Prefill + Speculative Decoding
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-8B-Instruct \
--max-model-len 1048576 \
--enable-chunked-prefill \
--speculative-model meta-llama/Meta-Llama-3-1B-Instruct \
--num-speculative-tokens 5 \
--gpu-memory-utilization 0.95 \
--port 8000
# 管道并行 + 张量并行混合
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3-70B-Instruct \
--tensor-parallel-size 2 \
--pipeline-parallel-size 2 \
--port 8000
SGLang原生支持正则表达式、JSON Schema、EBNF等约束生成,保证输出符合指定格式。这对Agent工具调用、数据提取等场景至关重要。
# SGLang结构化生成
import sglang as sgl
# 启动引擎
engine = sgl.Engine(
model_path="meta-llama/Meta-Llama-3-8B-Instruct",
port=30000,
)
# 1. JSON约束生成
json_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0, "maximum": 150},
"skills": {"type": "array", "items": {"type": "string"}},
},
"required": ["name", "age", "skills"],
}
response = engine.generate(
"请生成一个软件工程师的个人信息JSON。",
json_schema=json_schema,
)
print(response) # 保证输出是合法JSON
# 2. 正则约束生成
response = engine.generate(
"请生成一个手机号码。",
regex=r"1[3-9]\d{9}", # 中国手机号正则
)
# 3. EBNF语法约束 (更灵活)
ebnf_grammar = """
root ::= answer
answer ::= "Yes" | "No" | "Maybe"
"""
response = engine.generate(
"Is Python a good language for beginners?",
ebnf=ebnf_grammar,
)
# 4. 多轮对话 + 前缀复用 (自动)
def multi_turn_chat(engine, system_prompt, messages):
"""SGLang自动复用前缀KV Cache"""
# RadixAttention自动发现共享前缀
# 多轮对话中历史消息KV Cache完全复用
full_prompt = system_prompt
for msg in messages:
full_prompt += f"\n{msg['role']}: {msg['content']}"
return engine.generate(full_prompt, temperature=0.7)
# TensorRT-LLM构建流程
from tensorrt_llm import LLM, BuildConfig, ModelConfig
# Step 1: 配置模型
model_config = ModelConfig(
model_dir="meta-llama/Meta-Llama-3-8B-Instruct",
architecture="LlamaForCausalLM",
)
# Step 2: 构建配置
build_config = BuildConfig(
max_batch_size=256,
max_input_len=8192,
max_output_len=2048,
max_num_tokens=8192,
# 量化配置
quant_config={
"quant_algo": "W8A8", # 权重8bit, 激活8bit
"calib_algo": "max_entropy",
},
# 并行配置
tensor_parallel=1,
pipeline_parallel=1,
# plugin配置
use_gpt_attention_plugin=True,
use_gemm_plugin=True,
use_layernorm_plugin=True,
)
# Step 3: 构建引擎 (一次性, 离线)
llm = LLM(model_config, build_config)
llm.build() # 生成TensorRT engine文件
# Step 4: 保存引擎
llm.save("./llama3-8b-trt-llm")
# Step 5: 加载并推理
llm = LLM.from_engine("./llama3-8b-trt-llm")
output = llm.generate(
["什么是深度学习?"],
max_new_tokens=100,
temperature=0.7,
)
# 使用Triton部署TensorRT-LLM引擎
# 1. 准备模型仓库
mkdir -p models/llama3/1
cp llama3-8b-trt-llm/engine models/llama3/1/
# 2. 配置文件 models/llama3/config.pbtxt
cat > models/llama3/config.pbtxt << 'EOF'
name: "llama3"
backend: "tensorrtllm"
max_batch_size: 256
input [
{ name: "text_input" data_type: TYPE_STRING dims: [1] },
{ name: "max_tokens" data_type: TYPE_INT32 dims: [1] }
]
output [
{ name: "text_output" data_type: TYPE_STRING dims: [1] }
]
EOF
# 3. 启动Triton
docker run --gpus all -p8000:8000 -v$(pwd)/models:/models \
nvcr.io/nvidia/tritonserver:latest \
tritonserver --model-repository=/models
# 4. 客户端请求
curl -X POST localhost:8000/v2/models/llama3/infer \
-d '{"inputs": [{"name": "text_input", "data": ["Hello"]}, {"name": "max_tokens", "data": [100]}]}'
| 优化项 | 方法 | 预期提升 | 适用场景 |
|---|---|---|---|
| 批处理 | Continuous Batching | 3-5× | 在线服务 |
| KV Cache | PagedAttention | 2-3×并发 | 所有场景 |
| 权重量化 | AWQ/GPTQ INT4 | 2-3×速度 | 显存受限 |
| KV量化 | FP8/INT8 KV | 2×并发 | 长上下文 |
| 投机解码 | Speculative Decoding | 2-3× | 有合适小模型 |
| 前缀复用 | Prefix Caching | 5-10× TTFT | 多轮/Agent |
| Chunked Prefill | 分块prefill | 降低P99 | 混合长短请求 |
| 张量并行 | TP=N | ~N×吞吐 | 多GPU |
| FlashAttention | FA2/FA3 | 2×注意力 | 所有场景 |
| 编译优化 | torch.compile | 1.3-2× | PyTorch原生 |
| Graph Capture | CUDA Graph | 1.2-1.5× | 固定shape |
| Prefix Sharing | RadixAttention | 自动 | SGLang |
| 维度 | 离线推理 | 在线推理 |
|---|---|---|
| 延迟要求 | 无 | P99 < 1-3s |
| 吞吐优先 | 是 | 否(延迟优先) |
| 批大小 | 大(数百-数千) | 动态(continuous) |
| 引擎选择 | vLLM(offline mode) | vLLM/SGLang(server) |
| 量化 | INT4(省显存) | FP8(低延迟) |
| 并行 | 数据并行 | 张量并行 |
# 推理成本分析
def analyze_inference_cost(
model_size_gb, # 模型大小(GB)
gpu_memory_gb, # GPU显存(GB)
gpu_cost_per_hour, # GPU每小时成本($)
throughput_tokens_per_s,# 吞吐量(tok/s)
avg_tokens_per_request, # 每请求平均token
):
"""分析推理成本"""
# 需要的GPU数
num_gpus = math.ceil(model_size_gb / gpu_memory_gb)
# 每秒请求数
requests_per_s = throughput_tokens_per_s / avg_tokens_per_request
# 每百万token成本
tokens_per_hour = throughput_tokens_per_s * 3600
cost_per_million_tokens = (num_gpus * gpu_cost_per_hour) / (tokens_per_hour / 1e6)
return {
"num_gpus": num_gpus,
"requests_per_s": requests_per_s,
"cost_per_million_tokens": cost_per_million_tokens,
"monthly_cost": num_gpus * gpu_cost_per_hour * 24 * 30,
}
# 示例对比
# Llama-3-70B FP16 on 2xA100-80GB
fp16 = analyze_inference_cost(140, 80, 1.8, 3000, 500)
# Llama-3-70B INT4 on 1xA100-80GB
int4 = analyze_inference_cost(35, 80, 1.8, 6000, 500)
# Llama-3-70B FP8 on 1xA100-80GB
fp8 = analyze_inference_cost(70, 80, 1.8, 4500, 500)
print(f"FP16: ${fp16['cost_per_million_tokens']:.2f}/M tokens, {fp16['num_gpus']} GPUs")
print(f"INT4: ${int4['cost_per_million_tokens']:.2f}/M tokens, {int4['num_gpus']} GPUs")
print(f"FP8: ${fp8['cost_per_million_tokens']:.2f}/M tokens, {fp8['num_gpus']} GPUs")
# KV Cache显存计算
def calc_kv_cache_memory(
num_layers, # 层数
num_kv_heads, # KV头数 (GQA中可能少于query头)
head_dim, # 每头维度
max_seq_len, # 最大序列长度
batch_size, # 批大小
dtype_bytes=2, # FP16=2, FP8=1, INT4=0.5
):
"""
KV Cache显存 = 2(K+V) * L * H_kv * D * S * B * dtype_bytes
"""
kv_cache_per_token = 2 * num_layers * num_kv_heads * head_dim * dtype_bytes
total_memory = kv_cache_per_token * max_seq_len * batch_size
return {
"per_token_bytes": kv_cache_per_token,
"total_gb": total_memory / (1024**3),
"max_concurrent": None, # 需要GPU显存信息
}
# Llama-3-70B: 80层, 8 KV头(GQA), 128维, FP16
info = calc_kv_cache_memory(80, 8, 128, 4096, 1)
print(f"每token KV Cache: {info['per_token_bytes']} bytes")
print(f"单请求4K上下文: {info['total_gb']:.2f} GB")
# A100-80GB可用显存计算
def max_concurrent_requests(
gpu_memory_gb, model_weight_gb, kv_per_token_bytes, max_seq_len
):
"""计算最大并发请求数"""
available = (gpu_memory_gb - model_weight_gb) * 1024**3 * 0.9 # 90%利用率
kv_per_request = kv_per_token_bytes * max_seq_len
return int(available / kv_per_request)
# A100-80GB, 70B模型INT4(35GB), 4K上下文
max_concurrent = max_concurrent_requests(80, 35, 327680, 4096)
print(f"最大并发: {max_concurrent}")
| 参数 | 默认 | 说明 | 调优建议 |
|---|---|---|---|
| gpu_memory_utilization | 0.9 | GPU显存使用比例 | 0.9-0.95(留余量) |
| max_num_seqs | 256 | 最大并发序列 | 根据显存调整 |
| max_num_batched_tokens | 2048 | 每iteration最大token | 长上下文需增大 |
| block_size | 16 | PagedAttention块大小 | 16(通常最优) |
| swap_space | 4 | CPU交换空间(GB) | 0(通常不需要) |
| enable_prefix_caching | False | 前缀缓存 | 多轮对话设True |
# SGLang: 程序级优化 (fork/join并行)
import sglang as sgl
# SGLang支持程序级优化: fork/join并行采样
@sgl.prompt
def multi_branch_reasoning(s, question):
s += f"Question: {question}\n"
# fork: 并行生成多个推理路径
branches = s.fork(3) # 3条并行路径
for branch in branches:
branch += "Let me think step by step.\n" + sgl.gen(max_tokens=200)
# join: 合并结果, 选最佳
s += "Best answer: " + sgl.gen(max_tokens=100, temperature=0.0)
# 运行: SGLang自动优化KV Cache复用
result = multi_branch_reasoning.run(question="如何减少碳排放?")
# SGLang vs vLLM 在Agent场景的性能
# Agent场景: 多轮对话 + 工具调用 + 前缀复用
# SGLang: RadixAttention自动复用, 2-5x更快
# vLLM: 需要手动启用prefix_caching
# vLLM离线批量推理 (最大吞吐)
from vllm import LLM, SamplingParams
# 离线模式: 无需server, 直接批量推理
llm = LLM(
model="meta-llama/Meta-Llama-3-8B-Instruct",
max_model_len=8192,
gpu_memory_utilization=0.95,
# 优化选项
enable_prefix_caching=True, # 前缀缓存
use_v2_block_manager=True, # V2块管理器
enforce_eager=False, # 使用CUDA Graph
)
# 批量推理
prompts = [f"问题{i}: ..." for i in range(10000)]
sampling = SamplingParams(temperature=0.7, max_tokens=500)
# vLLM自动批处理 + PagedAttention
outputs = llm.generate(prompts, sampling)
# 统计吞吐
total_tokens = sum(len(o.outputs[0].token_ids) for o in outputs)
print(f"总token: {total_tokens}")
| 场景 | vLLM | SGLang | TensorRT-LLM |
|---|---|---|---|
| 单轮问答 | 1.0× | 1.1× | 1.5× |
| 多轮对话 | 1.0× | 2.5× | 1.3× |
| Agent工具调用 | 1.0× | 3.0× | 1.2× |
| 结构化生成 | 0.8× | 2.0× | 1.0× |
| 批量离线 | 1.0× | 1.0× | 1.4× |
| 长上下文 | 1.0× | 1.2× | 1.3× |
# TensorRT-LLM In-Flight Batching (类似Continuous Batching)
from tensorrt_llm.runtime import ModelRunner
# In-Flight Batching: TRT-LLM的动态批处理
runner = ModelRunner.from_engine(
"./llama3-8b-trt-llm",
max_batch_size=256,
max_num_tokens=8192, # 动态token预算
enable_inflight_batching=True,
)
# 动态提交请求
while True:
# 非阻塞提交新请求
while request_queue:
req = request_queue.pop()
runner.submit(req.input_ids, req.max_tokens)
# 非阻塞获取已完成请求
completed = runner.get_completed()
for req_id, output in completed:
send_response(req_id, output)
| 量化方案 | 显存(70B) | 吞吐 | 质量损失 | 推荐引擎 |
|---|---|---|---|---|
| FP16 | 140GB | 1.0× | 0% | vLLM/TRT-LLM |
| FP8 | 70GB | 1.5× | <1% | vLLM/TRT-LLM |
| INT8(W8A8) | 70GB | 1.6× | ~1% | TRT-LLM |
| INT4(AWQ) | 35GB | 2.0× | ~2% | vLLM/SGLang |
| INT4(GPTQ) | 35GB | 1.8× | ~2% | vLLM/SGLang |
| INT4+FP8 KV | 35GB | 2.5× | ~3% | vLLM |
# 推理成本优化策略
def estimate_inference_cost(
model_size_gb, gpu_type="A100-80GB",
gpu_cost_per_hour=1.5, # $/hour
avg_tokens_per_request=500,
requests_per_day=100000,
):
"""估算推理成本"""
# 1. GPU数量
gpus_needed = int(model_size_gb / 70) + 1 # A100-80GB
# 2. 日成本
daily_cost = gpus_needed * gpu_cost_per_hour * 24
# 3. 每token成本
# 假设吞吐: 3000 tokens/s (8B), 800 tokens/s (70B)
throughput = 800 if model_size_gb > 30 else 3000
tokens_per_day = throughput * 86400 * 0.5 # 50%利用率
cost_per_token = daily_cost / tokens_per_day
return {
"gpus": gpus_needed,
"daily_cost": daily_cost,
"cost_per_1k_tokens": cost_per_token * 1000,
"cost_per_request": cost_per_token * avg_tokens_per_request,
}
# 70B模型INT4量化部署
cost = estimate_inference_cost(35)
print(f"GPU数: {cost['gpus']}, 日成本: ${cost['daily_cost']:.0f}")
print(f"每1K token成本: ${cost['cost_per_1k_tokens']:.4f}")