核心定位:从 Roofline Model 出发,严格推导 Prefill(Compute-bound)和 Decode(Memory-bound)的延迟模型,深入剖析 Continuous Batching、Chunked Prefill、Prefill-Decode 分离(Disaggregation)的数学原理与工程权衡。
TTFT=Tqueue+Tprefill+Tfirst_decode E2E Latency=TTFT+Nout×TPOT 1.2 Prefill 延迟(Compute-bound 近似)
Prefill 阶段需要对整个输入序列做一次完整的 Transformer 前向传播。FLOPs 与输入长度 $T_{\text{in}}$ 成正比:
FLOPsprefill≈2×N×Tin 其中 $N$ 为模型参数量。则:
Tprefill=GPU Peak FLOPS×MFUFLOPsprefill 代入示例(7B 模型,$T_{\text{in}} = 4096$,A100 312 TFLOPS BF16,MFU $= 50%$):
Tprefill=312×1012×0.52×7×109×4096=1.56×10145.73×1013≈0.37 s 1.3 Decode 延迟(Memory-bound 近似)
Decode 阶段每步仅处理 1 个 token,但需要加载模型全部权重和 KV Cache。算术强度极低($\text{AI} \approx B$),远低于 GPU 的 Roofline 拐点。
TPOT≈Memory BandwidthMweights+MKV_accessed 代入示例(7B BF16 权重 14 GB,忽略 KV,A100 BW 2 TB/s,batch=1):
TPOT≈2 TB/s14 GB=7 ms/token Batch Size 增大时,多个请求共享一次权重加载,TPOT 均摊:
TPOTbatched≈B×BWMweights+BWMKV_per_req
2. Roofline 模型与 Prefill / Decode 的分野
算术强度 (Arithmetic Intensity):
AI=Bytes AccessedFLOPs Roofline 拐点:
AIridge=Peak BWPeak FLOPS GPU
Peak FLOPS (BF16)
Peak BW
拐点 AI
$\text{AI} \propto B \times T_{\text{in}} \gg \text{AI}_{\text{ridge}}$
$\text{AI} \propto B \ll \text{AI}_{\text{ridge}}$
提升 Bandwidth 利用率 / 增大 Batch
3. Continuous Batching(连续批处理)
3.1 传统 Static Batching 的问题
一个 Batch 中所有请求必须等最长的那个完成才能接收新请求。
Tidle=i∈batch∑(Tmax−Ti)×TPOT 当输出长度方差大时,GPU 空闲时间严重浪费。
3.2 Continuous Batching 机制
Iteration-level Scheduling:每个 Decode step 独立调度。
每步检查:
有请求输出 EOS 或达长度上限 → 移出 Running Pool。
Waiting Queue 有请求且显存(KV Cache)足够 → 加入 Running Pool。
Throughputcontinuous≈TPOTBˉactive 对比 Static Batching,吞吐提升可达 2–5×(取决于输出长度分布的方差)。
4. Chunked Prefill(分块预填充)
长 Prompt 的 Prefill 可能需要数百毫秒,期间会阻塞所有 Decode 请求,导致 TPOT 出现巨大毛刺。
将长 Prompt 切分为固定大小的 Chunk(如 $512$ token),每个 Chunk 作为一个"迭代"与 Decode 请求交替执行:
Tchunk=FLOPS×MFU2N×Csize 每个 Chunk 完成后,调度器有机会插入 Decode 迭代。
Chunk Size
Prefill 效率
Decode 抖动
经验值:$C_{\text{size}} = 256$–$512$ 是较好的平衡点。
5. Prefill-Decode 分离 (Disaggregation)
Prefill 是 Compute-bound,Decode 是 Memory-bound。两者对硬件的需求完全不同,混在一起必然导致资源利用率不佳。
{Prefill Instance:Decode Instance:需要高 FLOPS(如 H100)需要高 Bandwidth、大 HBM(如 H200) 5.2 KV Cache 传输开销
Prefill 实例计算完成后,需要将 KV Cache 传输到 Decode 实例:
Mtransfer=bytes_per_token×Tin 代入(7B GQA,$T_{\text{in}} = 4096$):
Mtransfer=128 KB×4096=512 MB 要求在可接受时间内完成传输(如 $< 100$ ms):
Required BW=0.1 s512 MB=5.12 GB/s InfiniBand / RoCE($100$–$400$ Gbps)可以满足,普通以太网可能成为瓶颈。
6.1 Latency-Throughput 曲线
Throughput↑⇔Batch Size↑⇒TPOT↑ (slightly)+TTFT↑ (queue delay) 存在一个最优 Batch Size 使得 Goodput(满足 SLO 的有效吞吐)最大:
Goodput=Total timeSLO-satisfied requests 短($<512$)/ 中($512$–$4K$)/ 长($>4K$)分桶
TTFT / TPOT / P95 / P99 / Throughput / OOM Rate / Goodput
逐步增加并发,绘制 Latency-Throughput 曲线
TTFT $< 2$ s,TPOT $< 50$ ms(示例)
"Prefill 是 Compute-bound(优化方向:FLOPs 利用率),Decode 是 Memory-bound(优化方向:Bandwidth 利用率 + 增大 Batch)。Continuous Batching 消除等待浪费,Chunked Prefill 消除阻塞抖动,Disaggregation 让硬件各司其职。"