跳到主要内容

35 · 推理服务:从 PagedAttention 到连续批处理

训练把算力花在反向传播,推理只做前向,但它的瓶颈完全不同:prefill 是算力受限的大矩阵乘,decode 是带宽受限的逐 token 生成(32 的 roofline)。vLLM 与 SGLang 的所有设计——分页 KV cache、连续批处理、前缀缓存、chunked prefill——都是围绕这两个阶段的矛盾展开的。

1. Prefill 与 decode:两种完全不同的负载​

阶段并行度算术强度瓶颈优化手段
Prefill整个 prompt 一次性过高( 的 GEMM)算力(TFLOPS)FlashAttention、chunked prefill、tensor parallel
Decode每步 1 token低(每权重只用一次)带宽(GB/s)大 batch、权重量化、投机解码、KV 分页

把两者混在一个 batch 里会互相拖累:prefill 的长序列把 decode 的延迟顶上去(head-of-line blocking),所以现代引擎默认开启 chunked prefill——把长 prompt 切成固定大小的块,与 decode 交错调度。

def roofline(params_b, seq, batch, peak_tflops=989, bw_gbs=3350, bytes_per=2):
"""返回 prefill / decode 的理论上限(tokens/s)"""
# prefill: 每 token 6N FLOPs(前向 2N,但 prefill 一次处理 s 个 token)
compute_bound = peak_tflops * 1e12 / (2 * params_b * 1e9)
# decode: 每 token 读一遍权重
mem_bound = bw_gbs * 1e9 / (2 * params_b * 1e9) * batch
return compute_bound, mem_bound

print(f"{'模型':<8}{'prefill 上限':<16}{'decode 上限 bs=1':<18}{'decode bs=32':<16}{'受限于'}")
print("-" * 70)
for p in (7, 70):
cb, mb = roofline(p, 1, 1)
print(f"{p}B{'':<5}{cb:>10,.0f} tok/s{'':<3}{mb:>10,.0f}{'':<6}{mb*32:>10,.0f}{'':<5}"
f"{'算力(prefill) / 带宽(decode)'}")
print("\nprefill 能跑到万级 tok/s,decode 单请求只有百级——差了两个数量级。")
print("所以「推理慢」几乎总是 decode 问题,而 decode 的唯一解是把 batch 堆大(或量化权重)。")

2. PagedAttention:把 KV cache 变成「虚拟内存」​

朴素实现按 max_model_len 预分配连续显存:请求只说 20 个 token,也要占满 4096 的位置。PagedAttention 借用操作系统分页思想:KV 存成固定大小的 block(默认 16 token),逻辑块通过 block table 映射到物理块,按需分配、可共享。

import random
random.seed(0)

BLOCK = 16
reqs = [40, 130, 260, 500] # 四条请求的实际生成长度
max_len = 512 # 朴素方案预分配上限

naive = sum(max_len for _ in reqs)
paged = sum(-(-L // BLOCK) * BLOCK for L in reqs) # 向上取整到块

print(f"{'请求':<8}{'实际长度':<10}{'朴素预留':<10}{'分页占用':<10}{'块数'}")
print("-" * 48)
for i, L in enumerate(reqs):
b = -(-L // BLOCK)
print(f"#{i:<7}{L:<10}{max_len:<10}{b*BLOCK:<10}{b}")
print(f"\n合计:朴素 {naive} token,分页 {paged} token,节省 {1 - paged/naive:.0%}")
print("若四条请求共享同一段系统提示,block table 还能让它们指向同一批物理块(copy-on-write 共享),")
print("这就是 vLLM 的 prefix sharing,也是 SGLang RadixAttention 的基础。")

3. 连续批处理:别让 GPU 等最慢的那条​

静态批处理要等一个 batch 里所有请求都结束才换下一批:短请求早退场,槽位空转。连续批处理(iteration-level scheduling)每步都重新组 batch,谁结束就立刻补新请求进来——GPU 的空槽被压到接近 0。

import random
random.seed(5)

def simulate(mode, slots=8, n_req=60, span=20, lmin=3, lmax=9):
"""60 条请求在 20 步内陆续到达,比较两种调度下的槽位占用"""
arrivals = [i * span // n_req for i in range(n_req)]
lengths = [random.randint(lmin, lmax) for _ in arrivals]
queue, active, occ, t = list(zip(arrivals, lengths)), [], [], 0
while queue or active:
if mode == "continuous":
while queue and queue[0][0] <= t and len(active) < slots:
active.append(queue.pop(0)[1])
elif not active: # 静态:整批清空才收下一批
while queue and queue[0][0] <= t and len(active) < slots:
active.append(queue.pop(0)[1])
occ.append(len(active))
active = [v - 1 for v in active]
active = [v for v in active if v > 0]
t += 1
return occ

results = {}
for mode in ("static", "continuous"):
occ = simulate(mode)
results[mode] = (sum(occ) / (len(occ) * 8), len(occ), occ[:12])

for mode, label in (("static", "静态批处理"), ("continuous", "连续批处理")):
util, steps, head = results[mode]
print(f"{label:<10} 利用率 {util:.0%} 总步数 {steps} 前 12 步占用 {head}")

speedup = results["static"][1] / results["continuous"][1]
print(f"\n同样 60 条请求,静态批处理要 {results['static'][1]} 步,连续批处理只要 {results['continuous'][1]} 步,")
print(f"端到端吞吐差 {speedup:.2f}×——而 kernel 一行没改,差别全在调度表。")

4. 前缀缓存:把「重复的系统提示」只算一次​

多轮对话与 Agent 场景里,每条请求都以同一段 system prompt 开头。RadixAttention 用基数树缓存「已计算过的 token 前缀」,命中时直接复用对应 block 的 KV,只对新增部分做 prefill。

SYS = list(range(100, 116))                    # 系统提示占 16 个 token
prompts = [
SYS + [201, 202, 203],
SYS + [201, 202, 204, 205],
SYS + [301, 302],
]

def common_prefix(a, b):
n = 0
for x, y in zip(a, b):
if x != y:
break
n += 1
return n

hit = sum(common_prefix(p, prompts[0]) for p in prompts)
total = sum(len(p) for p in prompts)
print(f"三条请求总 prompt {total} token,共享系统提示 {len(SYS)} token")
print(f"逐条命中长度 {[common_prefix(p, prompts[0]) for p in prompts]},命中合计 {hit} token")
print(f"→ 省下 {hit/total:.0%} 的 prefill;按 16 token 的 block 对齐,正好复用 {len(SYS)//16} 个物理块")
print("\nAgent 多轮场景里系统提示与历史对话都命中,前缀命中率常达 80%+,")
print("这也是 SGLang(RadixAttention)在 agent 负载上明显快于 vLLM 的原因。")
def slo_throughput(max_num_seqs, tokens_per_seq=512, bw_gbs=3350, params_b=7):
"""decode 带宽受限:单请求延迟固定,总吞吐随 batch 线性涨,直到算力封顶"""
per_seq_lat = tokens_per_seq * 2 * params_b * 1e9 / (bw_gbs * 1e9) # 秒
total = max_num_seqs * tokens_per_seq / per_seq_lat
compute_cap = 989 * 1e12 / (2 * params_b * 1e9)
return min(total, compute_cap), per_seq_lat

print(f"{'max_num_seqs':<14}{'总吞吐(tok/s)':<18}{'单请求延迟(s)'}")
print("-" * 48)
for n in (1, 8, 32, 128, 256):
tp, lat = slo_throughput(n)
print(f"{n:<14}{tp:<18,.0f}{lat*1000:.0f} ms")

print("\n吞吐随 batch 线性涨,但单请求延迟不变(带宽受限阶段),直到算力封顶;")
print("真实系统里延迟会因排队而上涨,所以 max_num_seqs 要按 P99 SLO 反推,而不是拉满。")

5. 引擎对照与上线清单​

引擎调度KV 管理强项弱项
vLLM连续批处理 + chunked prefillPagedAttention生态最全、模型支持广极端 agent 负载略逊
SGLangRadixAttention + 前后端分离基数树前缀复用多轮/Agent 命中率高生态较新
TensorRT-LLM静态图 + in-flight batching自管理 paged KV单机极致性能编译期绑定,改模型成本高
HF TGI连续批处理paged KV部署简单高并发下调度较弱

上线前按顺序核对:KV 显存预算(block 数 = 剩余显存 / 每 block 字节)→ max_num_seqs(按 P99 SLO 反推)→ 是否开 prefix cache(多轮必开)→ chunked prefill 块大小(长 prompt 场景 512~1024)→ 量化格式(34)。

站内关联与参考来源​

  • 前置:32 · 显存与 MFU、34 · 量化
  • 延伸:19 · 投机解码、17 · 生成策略
  • 融合参考:chunhuizhang/llm_inference_serving 的 paged_attention/{block_table,fragmentation}.ipynb、scheduling/{continuous_batching,chunked_prefill}.ipynb、sglang/{radix_cache}.ipynb、llm_gpu_benchmark 的 serving/{throughput_latency}.ipynb。