M4-058M4: Sequences & TransformersKV Cache & Inference OptimizationsEasy
⚡Flashcard Drill➔Mastery:
Differences Between Prefill and Decode Phases in LLM Inference
🎯 Active Recall Self-Check (Draft First, Verify After)
Login-free practice tracker: recall core answer, audit pitfalls, and log review status.
Step 1 · Draft your concise answer & assumptions
Step 2 · Check Pitfalls & Follow-up Inquiries
📐 Mathematical Definition
⚡ One-Sentence Core Answer
The prefill phase processes the prompt in parallel and is compute-bound, whereas the decode phase generates tokens autoregressively one by one and is memory-bandwidth bound.
📌 Key Takeaways
- •Prefill (Time-to-First-Token / TTFT): computes for all prompt tokens simultaneously in parallel; high arithmetic intensity, saturating GPU Tensor Cores (compute-bound)
- •Decode (Time-Per-Output-Token / TPOT): generates one token per step ( length is 1); reads the entire historical KV cache for a tiny matrix-vector multiplication, severely constrained by memory bandwidth (memory-bound)
- •Different optimization objectives: Prefill prioritizes FlashAttention, tensor parallelism, and prompt caching; Decode prioritizes batching concurrency, GQA, quantization, and speculative decoding
📐 Mathematical Derivations
Mathematical Mechanism: Prefill Phase: Given prompt length , the input is . are computed in a single forward pass. The attention computation involves GEMM (General Matrix Multiply): . The arithmetic intensity is approximately , which scales with . For moderate to large (e.g., ), operational intensity surpasses the GPU hardware balance point (e.g., ~150 FLOPs/byte on A100), placing prefill squarely in the compute-bound regime. Decode Phase: At generation step , the query is a single vector . The model must load the model weights () and all cached keys and values from HBM. The operations are GEMV (General Matrix-Vector Multiply). FLOPs executed are , while bytes transferred are . The arithmetic intensity is FLOP/byte, orders of magnitude below hardware compute capability (~312 TFLOPs vs 2 TB/s HBM bandwidth), making decode strictly memory bandwidth-bound.
🏭 Production Trade-offs
Deep Dive & Engineering Trade-offs: ① Interference in Co-located Serving: When prefill requests (bursty, high compute, monopolizing GPU cores) and decode requests (latency-sensitive, low compute, high bandwidth) share the same GPU, prefill execution causes massive latency spikes (TPOT jitter) for ongoing decode requests. ② Mitigation: Chunked Prefill: Splitting long prompt prefills into smaller chunks (e.g., 512 tokens) and co-scheduling them alongside decode batches to smooth out GPU execution. ③ Architectural Evolution: PD Disaggregation: Physically separating prefill instances and decode instances onto dedicated GPU clusters, transferring KV caches over high-speed networks (InfiniBand/PCIe Gen5) to achieve optimal hardware utilization. ④ Batching Impact: Increasing batch size during decode amortizes weight loading across multiple requests, converting GEMV toward GEMM and boosting throughput at the cost of higher latency. ⑤ Interview Strategy: Frame the answer around the Roofline Model, contrasting TTFT vs. TPOT metrics and highlighting system-level scheduling solutions like vLLM and TensorRT-LLM.
⚠️ Common Interview Pitfalls
- ✕Assuming both prefill and decode phases are compute-bound or that adding more compute always speeds up decoding
- ✕Failing to distinguish TTFT from TPOT when discussing latency SLAs
- ✕Ignoring the severe GPU resource contention caused by running prefill and decode concurrently on the same device
🎯 Interviewer Follow-up Inquiries
- ?How does Chunked Prefill improve decode latency jitter?
- ?Under what conditions does PD Disaggregation justify the network overhead of KV cache transfer?
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
📚
Associated Knowledge Base Guides & Mindmaps
中文速览与面试要点
解释 prefill 与 decode 两阶段的差异。
prefill 并行处理输入(compute-bound、算力密集);decode 逐 token 生成(memory-bound、读 KV);两者需不同优化。
核心要点
- 数学机理: prefill(预填充) ——处理用户输入的整段 prompt(长度 L),所有位置的 Q/K/V 可 一次性并行计算 (类似训练的前向),注意力是 L×L 的大矩阵运算,FFN 是 L×d×d 的大矩阵乘;故 prefill 是 compute-bound (受算力限制),且能高效利用张量核心。 decode(解码) ——逐 token 生成,每步只有 1 个 query,需读取 整个 KV cache (长度 S)做注意力;每步的 FLOPs 很小但访存量 ∝S,故是 memory-bound (受带宽限制),且并行度低(batch×heads)。 关键指标 :(a) TTFT(Time To First Token) ——首 token 延迟,主要由 prefill 决定(∝ prompt 长度);(b) TPOT(Time Per Output Token) ——每输出 token 的延迟,由 decode 决定(∝ 读取 KV 的量);(c) 吞吐 ——由两阶段的效率与批大小共同决定。 为什么需不同优化 ——prefill 适合 大 batch 的矩阵乘 (算力密集,batch 越大越好);decode 适合 大 batch 以摊薄 KV 读取 (带宽密集,batch 越大 KV 复用越高)。故推理引擎需 分别调优 ,甚至 分离部署 (PD 分离)。 两阶段的显存需求也不同 ——prefill 需大量激活显存(大矩阵中间结果),decode 需大量 KV cache 显存。
- 深度剖析与工程权衡:① 'chunked prefill' ——把长 prompt 的 prefill 切成多个 chunk 逐步处理,与 decode 请求 混批 ,使 (a) 长 prompt 不阻塞短请求(改善延迟)、(b) 计算与带宽资源互补(prefill 算力密集、decode 带宽密集,混批可同时利用);这是现代推理引擎(vLLM、TensorRT-LLM)的关键调度技术。② PD 分离(disaggregation) ——把 prefill 与 decode 部署在 不同实例 (各自用最适合的硬件/并行策略),通过高速网络传递 KV cache;优点是各阶段可独立扩缩容、避免相互干扰,代价是 KV 传输开销。③ batch 策略的差异 ——prefill 用'大 batch + 长序列'填满算力;decode 用'尽量大的 batch'摊薄 KV 读取;两者的最优 batch 大小不同,故混批需调度算法(如 Sarathi-Serve 的 chunked prefill + piggybacking)。④ 与投机解码的关系 ——投机解码在 decode 阶段一次验证多个 token,把'每步 1 个 query'变成'每步 k 个 query',从而提升 decode 的算术强度(更接近 prefill 的效率);这是'把 decode 变 compute-bound'的思路。⑤ 与 KV 压缩的关系 ——decode 的瓶颈是读 KV,故 MQA/GQA/MLA/KV 量化直接改善 TPOT。⑥ 面试要点 ——被问'prefill 与 decode 的区别',应给出' 并行度(L vs 1)+ 瓶颈(算力 vs 带宽)+ 指标(TTFT vs TPOT)+ 优化方向 '四维对比,并说明'chunked prefill / PD 分离'的工程动机;这是推理系统类问题的核心考点。
- prefill:整段输入并行,大矩阵乘,算力受限
- decode:每步 1 token,读整个 KV cache,带宽受限
- TTFT 由 prefill 决定;TPOT 由 decode 决定
常见陷阱
- 把 prefill 与 decode 的瓶颈当作同类
- 忽略 TTFT 与 TPOT 的区分