PART 1 · VISUAL CONCEPT 04

Prefill, Decode & KV-Cache

Why does generating token #500 stay fast with a KV-Cache—and why does the GPU suddenly starve on memory bandwidth instead of compute?

Interactive Lab 01 · O(n) vs. O(n²) Generation

Step Token-by-Token: KV-Cache ON vs. Recomputing From Scratch

Step 0 / 8 (Prefill)
PHASE 1: PREFILL (Parallel Matrix-Matrix)
Attention Compute Grid (12×12 Q × Kᵀ) Parallel GEMM · 4 rows at once
Cyan = Prefill GEMM · Rose = Active Decode Row · Amber = Redundant Recompute
GPU VRAM KV-Cache Buffer Prefilled 4 (K, V) pairs
K Cache (Keys)
V Cache (Values)
CACHE DISABLED Recomputing K & V for all tokens every step
This Step Dot-Products 10 ops 4 prompt rows parallel
Cumulative Ops Saved 0.0% Baseline prefill step
Active Bottleneck Compute (TTFT) Tensor Cores saturated
Cached KV Vectors 4 / 12 slots HBM resident (K + V)
Interactive Lab 02 · H100 80GB HBM3 & Roofline

VRAM Budget & Compute vs. Memory-Bandwidth Roofline

Drag context length and batch size to see KV-Cache overtake model weights—and why batching rescues GPU utilization during Decode.

FITS IN 80GB H100
Context Length (n) 8K tokens
Batch Size (B) B = 8 users
H100 80GB HBM3 VRAM Allocation 24.0 / 80 GB
Weights: 16.0 GB · KV-Cache: 8.0 GB · Total: 24.0 / 80 GB
KV = 2 × L × H_kv × d × bytes × n × B
Prefill vs. Decode Hardware Utilization H100 Roofline
Prefill (GEMM) Compute
Tensor Cores94%
HBM3 Bandwidth22%
Decode (B=8) BW-Bound
Tensor Cores22%
HBM3 Bandwidth96%
Batching amortizes weight reads across users!
Mental Model · Pure Standard-Library Python

kv_cache_decode.py — The Entire Idea in 22 Lines

kv_cache_decode.py

      

Why Only K & V (Never Q)?

Past queries already produced their outputs. Only the newest token's Q_t asks questions of all cached past Keys and Values.

TTFT vs. TPOT Split

Prefill sets Time-to-First-Token (compute-bound GEMM). Decode sets Time-Per-Output-Token (HBM3 memory-bandwidth-bound).

GQA Cuts VRAM by 8×

Grouped-Query Attention shares 1 KV head across 8 Query heads—shrinking the KV-Cache 8× with negligible quality loss.