Chapter 7 of 40 · ~24 min read & lab+85 XP
Chapter 7 · Generative AI

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.

What Is It?

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.

Why Is It Required?

Without KV-Cache, generating a 2,000-token reply repeats quadratic O(T²) work on every single word, making real-time chat 100× slower.

Everyday Analogy: Keeping your solved math scratchpad open instead of re-deriving steps 1 through 49 every time you write step 50.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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.

Data Scientist

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.

Interview & Debug Edge

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!'

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
K1:t,V1:tK_{1:t}, V_{1:t}Say aloud:“cached Keys & Values up to step t”
Plain-English Meaning
Stored (t × d_k) Key and Value tensors per layer & KV head so past tokens are never recomputed
Everyday Example
Step t appends just 1 row: K_t, V_t
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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 (O(T2)O(T^2) wasted work!). Because causal attention only looks backward, once token 17 has computed its Key k17k_{17} and Value v17v_{17}, those two vectors never change for the rest of the conversation. KV-Cache simply keeps a growing notebook of (k1..kt−1,v1..vt−1)(k_1..k_{t-1}, v_1..v_{t-1}) in GPU VRAM so step tt only projects the single newest token xtx_t!

1. Why Causal Attention Makes Past Keys & Values Immutable

Everyday Story First (Zero Math Yet!)

Compare the left side (no cache: recomputing the entire prefix every step) with the right side (KV-Cache: computing only 1 new query qtq_t and appending 1 row (kt,vt)(k_t, v_t)).

KV-Cache: Stop Recomputing Past Keys & Values on Every Generated Token!Without KV-Cache (Wasteful O(T²))Step 500: Re-project tokens 1..500Step 501: Re-project tokens 1..501!99.8% redundant work every step!With KV-Cache (Fast O(T) Append ✓)Compute ONLY q_t, k_t, v_t (1 token!)K_cache ← cat([K_cache, k_t])Exact same math, 10–50× faster decode!
Without KV-Cache, generating token T recomputes K and V for all T−1 previous tokens (O(T²) wasted work); KV-Cache appends just 1 new K/V row per step (O(T) total!).

From O(T2)O(T^2) Projections to O(T)O(T) Cached Steps

At generation step tt, we only need the output hidden state for the newest token xtx_t:

  1. Compute only the newest vectors: qt=xtWQq_t = x_t W_Q, kt=xtWKk_t = x_t W_K, vt=xtWVv_t = x_t W_V (shape 1×dk1 \times d_k per head).
  2. Append ktk_t and vtv_t to the cached matrices: K1:t=concat(K1:t−1,kt),V1:t=concat(V1:t−1,vt)K_{1:t} = \text{concat}(K_{1:t-1}, k_t), \quad V_{1:t} = \text{concat}(V_{1:t-1}, v_t)
  3. Compute vector-matrix attention for the single query qtq_t: Attn(qt,K1:t,V1:t)=softmax ⁣(qtK1:t⊤dk)V1:t\text{Attn}(q_t, K_{1:t}, V_{1:t}) = \text{softmax}\!\left(\frac{q_t K_{1:t}^\top}{\sqrt{d_k}}\right) V_{1:t} Notice we do not cache Queries QQ — past queries are never needed again because past tokens already produced their outputs!

2. The Two Phases of LLM Inference: Prefill vs. Decode

Everyday Story First (Zero Math Yet!)

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!

The Two Phases of LLM Inference: Prefill (Compute) vs. Decode (Memory Bandwidth)Phase 1: Prefill (TTFT)Matrix × Matrix (T_prompt × D)High Arithmetic Intensity → Compute-BoundPopulates initial KV-Cache in 1 pass!Phase 2: Decode (Tokens/sec)Vector × Matrix (1 × D per step)Reads ALL weights + KV-Cache from HBM!Memory-Bandwidth Bound (needs Batching!)
Prefill runs all prompt tokens in 1 parallel GEMM (compute-bound, high GPU utilization), while Decode generates 1 token per step reloading all weights from HBM (memory-bandwidth bound!).

Roofline Contrast: GEMM vs. GEMV

  • Phase 1 — Prefill (Prompt Processing): All PP prompt tokens run in parallel as a matrix-matrix multiply (GEMM) of shape (P×D)⋅(D×D)(P \times D) \cdot (D \times D). Arithmetic intensity is high   ⟹  \implies 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 (1×D)⋅(D×D)(1 \times D) \cdot (D \times D). Every single output token must stream the entire model weights + KV-Cache from HBM   ⟹  \implies memory-bandwidth-bound. Governs tokens/sec!
  • Max Theoretical Decode Speed (Batch = 1): tok/smax⁡≈GPU HBM Bandwidth (GB/s)Model Weights (GB)+KV-Cache (GB)\text{tok/s}_{\max} \approx \frac{\text{GPU HBM Bandwidth (GB/s)}}{\text{Model Weights (GB)} + \text{KV-Cache (GB)}} On an H100 (3,350 GB/s) running a 70B FP16 model (~140 GB), batch=1 speed is capped at ≈3350/140≈24 tok/s\approx 3350 / 140 \approx 24\text{ tok/s} regardless of how fast Tensor Cores are!
Animated Mini-Lab • 2.1

Prefill vs. Decode Bottleneck Switcher

Compute-Bound Parallel GEMM (Determines TTFT)

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

Everyday Story First (Zero Math Yet!)

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.

Exact KV-Cache Memory Equation (Bytes)VRAM_KV = 2 (K&V) × L × H_kv × d_k × T × B × bytesExample: LLaMA-70B (MHA: H_kv=64, L=80, d_k=128, FP16=2B) at T=32K, B=1 → 83.9 GB!With GQA-8 (H_kv=8 instead of 64) → Drops 8× down to 10.5 GB! ✓
KV-Cache VRAM = 2 × L × H_kv × d_k × T × B × bytes_per_elem — at 128K context on a 70B MHA model, KV-Cache alone can exceed the model's weights!

The Production KV-Cache Memory Equation

KV Bytes=2×L×Hkv×dk×T×B×bytes_per_elem\text{KV Bytes} = 2 \times L \times H_{\text{kv}} \times d_k \times T \times B \times \text{bytes\_per\_elem} For standard FP16 / BF16 (bytes_per_elem=2\text{bytes\_per\_elem} = 2), this simplifies to 4⋅L⋅Hkv⋅dk⋅T⋅B4 \cdot L \cdot H_{\text{kv}} \cdot d_k \cdot T \cdot B bytes!

Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of the KV-Cache VRAM Formula

Bytes = 2 × L × H_kv × d_k × T × B × b

Keys + Values

We store two separate tensors per layer: K and V (never Q).

In our example: 2 tensors
Put it together with real numbers: LLaMA-3-8B (L=32, H_kv=8, d_k=128, FP16 b=2) uses 2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KB per token! At 128K context, a SINGLE user consumes 16.4 GB of KV-Cache — as large as the entire 8B model weights!
Walk Through With Me · Interactive Worked Example

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.

11. Compute bytes per single tokenStep 1 / 3

2×80×64×128×2=2,621,440 bytes=2.5 MB per token2 \times 80 \times 64 \times 128 \times 2 = 2,621,440\text{ bytes} = 2.5\text{ MB per token}!

Teacher's Note: Every single word generated costs 2.5 MB of HBM on an MHA 70B model!
Pause & Check · Quick Intuition Pulse

Which tensor is NEVER stored inside the KV-Cache during autoregressive LLM inference?

Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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 K,VK, V projections.

Interactive Visual Lab
Lab Challenge: Run the 60 FPS KV-Cache Animator past 40% progress and toggle Cache ON vs. OFF to compare O(T)O(T) vs. O(T2)O(T^2) work.
Interactive Animation • 2.1 Deep Lab

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.

Cumulative K/V Projections: 1 vs. 1
The
compute K,V
quick
pending
brown
pending
fox
pending
jumps
pending
over
pending
the
pending
dog
pending
0%
Decoding Step t = 1 ("The")
Intuition Takeaway: KV-Cache trades GPU VRAM (2 · L · H_kv · d_k · T · B · b) to turn autoregressive decoding from O(T2)O(T^2) recomputation into O(T)O(T) work — splitting inference into compute-bound Prefill (TTFT) and memory-bandwidth-bound Decode (tokens/sec).
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting the factor of 2 in the KV-Cache memory formula (or multiplying by H_q instead of H_kv on GQA models).
Best Practice: Always write 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!
Trap #2: Claiming KV-Cache is used during LLM pre-training.
Best Practice: Pre-training uses teacher forcing where all T tokens are processed in 1 parallel forward pass — KV-Cache is ONLY used during autoregressive inference!
Chapter Mastery Check (+85 XP)
Score: 0 / 2
1For a model with L=32 layers, H_kv=8 KV heads, d_k=128, FP16 (2 bytes/elem), how much KV-Cache memory does 1 token consume?
2Which metric is primarily governed by the compute-bound Prefill phase?

Apply What You Learned — Solve Matching Coding Problems