How KV-Cache Works: Prefill vs. Autoregressive Decode & VRAM Math
Why autoregressive generation wastes O(T²) FLOPs without caching, how KV-Cache turns each new token into O(T) work, why Prefill is compute-bound while Decode is memory-bandwidth-bound, and the exact KV-Cache VRAM formula.
The KV-Cache stores previously computed Key and Value tensors in GPU VRAM during autoregressive generation so each new token only computes its own Q, K, V instead of recomputing the entire prompt.
Without KV-Cache, generating a 2,000-token reply repeats quadratic O(T²) work on every single word, making real-time chat 100× slower.
KV-Cache is the #1 reason ChatGPT streams at 80 tokens/sec instead of 2 tokens/sec — and also the #1 memory bottleneck in production LLM serving!
Every inference engine (vLLM, TensorRT-LLM, SGLang, llama.cpp) is architected around managing KV-Cache VRAM budgets, Prefill/Decode disaggregation, and batch-size capacity planning.
Understanding why TTFT (Time To First Token) scales with prompt length while ITL (Inter-Token Latency) scales with GPU memory bandwidth lets you choose the right GPU and context budget immediately.
The single most common Generative AI systems interview question: 'Derive the KV-Cache memory formula for a 70B model at 32K context in FP16, and explain why Decode is memory-bound!'
During autoregressive decoding (batch size = 1, FP16), generating 1 single new token on a 7B model requires reading ~14 GB of weights from GPU HBM. Which hardware resource is the primary bottleneck?
- Explain why causal masking guarantees that past Key and Value vectors never change as new tokens are generated
- Contrast Phase 1 (Prefill: compute-bound parallel GEMM, governs TTFT) with Phase 2 (Decode: memory-bandwidth-bound GEMV, governs tokens/sec)
- Compute exact KV-Cache VRAM usage in gigabytes from layers L, KV heads H_kv, head dim d_k, sequence length T, batch size B, and precision bytes
- Diagnose why long-context LLM serving hits Out-Of-Memory (OOM) on KV-Cache long before model weights fill the GPU
Imagine writing a 10-page essay where, before writing every single new word, you throw away your notes and re-read all previous pages from word 1 — that is LLM inference without KV-Cache ( wasted work!). Because causal attention only looks backward, once token 17 has computed its Key and Value , those two vectors never change for the rest of the conversation. KV-Cache simply keeps a growing notebook of in GPU VRAM so step only projects the single newest token !
1. Why Causal Attention Makes Past Keys & Values Immutable
Compare the left side (no cache: recomputing the entire prefix every step) with the right side (KV-Cache: computing only 1 new query and appending 1 row ).
From Projections to Cached Steps
At generation step , we only need the output hidden state for the newest token :
- Compute only the newest vectors: , , (shape per head).
- Append and to the cached matrices:
- Compute vector-matrix attention for the single query : Notice we do not cache Queries — past queries are never needed again because past tokens already produced their outputs!
2. The Two Phases of LLM Inference: Prefill vs. Decode
Toggle between Phase 1: Prefill and Phase 2: Decode in the mini-lab below to see why LLM serving has two completely opposite hardware bottlenecks!
Roofline Contrast: GEMM vs. GEMV
- Phase 1 — Prefill (Prompt Processing): All prompt tokens run in parallel as a matrix-matrix multiply (GEMM) of shape . Arithmetic intensity is high compute-bound (saturates GPU Tensor Cores). Governs TTFT and populates the initial KV-Cache.
- Phase 2 — Decode (Token Generation): Generates 1 token at a time via vector-matrix multiply (GEMV) of shape . Every single output token must stream the entire model weights + KV-Cache from HBM memory-bandwidth-bound. Governs tokens/sec!
- Max Theoretical Decode Speed (Batch = 1): On an H100 (3,350 GB/s) running a 70B FP16 model (~140 GB), batch=1 speed is capped at regardless of how fast Tensor Cores are!
Prefill vs. Decode Bottleneck Switcher
Processes all prompt tokens simultaneously in one matrix-matrix multiply, saturating GPU Tensor Cores and filling the initial KV-Cache.
3. Exact KV-Cache VRAM Math & Why Long Context OOMs
Every token you add to the prompt or batch linearly expands GPU memory across every layer and every KV head. Let's dissect the exact formula used in production capacity planning.
The Production KV-Cache Memory Equation
For standard FP16 / BF16 (), this simplifies to bytes!
Bytes = 2 × L × H_kv × d_k × T × B × b
We store two separate tensors per layer: K and V (never Q).
Worked Example: Sizing KV-Cache for a 70B MHA Model at 32K Context
Suppose an older 70B MHA model has L=80 layers, H_kv=64 heads, d_k=128, FP16 (2 bytes), T=32,768 tokens, Batch B=1.
!
Which tensor is NEVER stored inside the KV-Cache during autoregressive LLM inference?
Why does increasing the Decode batch size from B=1 to B=32 dramatically increase total GPU throughput (tokens/sec) with almost no increase in per-user latency?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
No — it is 100% mathematically identical (up to tiny floating-point rounding differences). KV-Cache is a pure dynamic programming / memoization optimization that avoids redundant projections.
Autoregressive KV-Cache Growth & FLOPs Savings Animator
Watch each generated token append 1 new Key/Value row to the KV-Cache instead of recomputing all previous tokens from scratch.
2 · L · H_kv · d_k · T · B · b) to turn autoregressive decoding from recomputation into work — splitting inference into compute-bound Prefill (TTFT) and memory-bandwidth-bound Decode (tokens/sec).vLLM PagedAttention & Prefix Caching
Breaks KV-Cache into fixed-size 16-token virtual memory pages to eliminate VRAM fragmentation and share system-prompt KV blocks across users.
Prefill / Decode Disaggregation
Large serving clusters assign dedicated compute-optimized GPU pools to Prefill and memory-bandwidth-optimized pools to Decode so long prompts never stall streaming users.
import torch
import torch.nn.functional as F
# Autoregressive KV-Cache: O(1) incremental decode instead of O(T^2) recomputation
def cached_attention_step(q_new, k_new, v_new, kv_cache=None):
# q_new, k_new, v_new: [B, H, 1, D_head]
if kv_cache is None:
k_all, v_all = k_new, v_new
else:
k_prev, v_prev = kv_cache
k_all = torch.cat([k_prev, k_new], dim=2)
v_all = torch.cat([v_prev, v_new], dim=2)
out = F.scaled_dot_product_attention(q_new, k_all, v_all)
return out, (k_all, v_all)
B, H, D = 1, 8, 64
# Prefill 12 prompt tokens once, then decode 3 tokens incrementally
cache = (torch.randn(B, H, 12, D), torch.randn(B, H, 12, D))
for step in range(3):
out, cache = cached_attention_step(torch.randn(B, H, 1, D), torch.randn(B, H, 1, D), torch.randn(B, H, 1, D), cache)
print("KV-Cache length after 3 decode steps:", cache[0].shape[2], "| Output:", tuple(out.shape))
2 × L × H_kv × d_k × T × B × bytes — the 2 is for K + V, and H_kv (not query heads H_q) determines cache size!