Best on a larger screen — the animation and controls have more room to breathe.
Inputs

KV Cache: Prefill & Decode

The KV cache splits autoregressive language-model inference into two phases: a parallel Prefill pass over the prompt that stores each token's Key (K) and Value (V) vectors, followed by token-by-token Decode steps that project only the new token and reuse cached K and V instead of recomputing the entire prefix.

Without caching, generating token L re-runs projections and causal attention across all L positions even though nothing in positions 0..L−2 changed. With a KV cache, every output distribution stays mathematically identical to full recomputation (max |ΔP| = 0 in exact arithmetic; GPU kernels can still differ at floating-point rounding precision due to GEMM vs GEMV reduction order) while Decode drops from quadratic O(L²d) attention work per step to linear O(Ld) reads from memory.

Why Earlier K and V Never Change (and Why Q Is Dropped)

Causal masking restricts position i to attend only to keys at positions j ≤ i (Causal Masking & Autoregressive Training). Appending a new token at position t never alters earlier embeddings, earlier positional vectors, or earlier causal hidden states. Consequently, for every j < t, the key vector k_j and value vector v_j computed during Prefill or an earlier Decode step are invariant forever within that sequence.

Query vectors (q_j) behave differently:

def prefill(prompt_tokens, W_Q, W_K, W_V):
    x = [embed(tok) + pe(pos) for pos, tok in enumerate(prompt_tokens)]
    Q = [x_i @ W_Q for x_i in x]
    K_cache = [x_i @ W_K for x_i in x]
    V_cache = [x_i @ W_V for x_i in x]
    attn_last = causal_attention_row(Q[-1], K_cache, V_cache)
    return sample_next(x[-1] + attn_last), K_cache, V_cache

def decode_step(new_token, pos, K_cache, V_cache, W_Q, W_K, W_V):
    x_t = embed(new_token) + pe(pos)      # stamp absolute position t
    q_t, k_t, v_t = x_t @ W_Q, x_t @ W_K, x_t @ W_V
    K_cache.append(k_t)
    V_cache.append(v_t)
    attn_t = causal_attention_row(q_t, K_cache, V_cache)  # 1 row, L pairs
    return sample_next(x_t + attn_t)

Once Q[-1] finishes scoring the last prompt row, no q_j for j < t is ever needed again—that is why production systems maintain a KV cache, never a QKV cache. Each Decode step still stamps the token's true absolute position pos = t into positional encoding before projecting q_t, k_t, and v_t so the resulting vectors match a fresh full-prefix pass.

KV Cache Step by Step

The default trace runs KV Cache on the four-token prompt [A, B, C, B] (P = 4, d = 4, √d_k = 2) for D = 3 Decode steps (N = 7 total processed positions):

StageLength LNew projActive Q·K pairsKV slotsTop probs [A, B, C, D] → Pickmax |ΔP|
Prefill44104[0.043, 0.143, 0.190, 0.624] → D0.000000
Decode 15155[0.031, 0.046, 0.674, 0.249] → C0.000000
Decode 26166[0.022, 0.040, 0.320, 0.618] → D0.000000
Decode 37177[0.036, 0.085, 0.598, 0.281] → C0.000000
  1. Prefill projects P = 4 tokens in parallel. All four prompt tokens [A, B, C, B] at positions 0..3 project together to Q, K, and V (4 projections).
  2. Prefill scores the 4 × 4 causal lower triangle. Evaluating rows 0..3 together computes 4(4 + 1) / 2 = 10 causal Q·K dot products. Row 3 assigns weights [0.64, 0.15, 0.13, 0.08], pulling heavily from anchor 0:A's Value vector.
  3. Prefill caches K and V, then drops Q. Four (k_j, v_j) pairs (32 scalars) lock into the KV Cache rack while Q is discarded. Row 3 emits D (p = 0.624), matching full causal recomputation (max |ΔP| = 0.000000).
  4. Decode 1 (L = 5) reuses slots 0..3. Only the newly emitted D at pos 4 projects into q_4, k_4, v_4 (+1 projection) and appends (k_4, v_4) to slot 4. Attention computes only row 4 (5 Q·K pairs instead of 15), emitting C (p = 0.674, ΔP = 0).
  5. Decode 2 (L = 6) proves long-range cache reuse. New token C at pos 5 projects once, appends to slot 5, and attends 0.80 back to cached 0:A. Skipping rows 0..4 cuts Decode 2 from 21 pairs to 6 while still emitting D (p = 0.618, ΔP = 0).
  6. Decode 3 (L = 7) and controlled comparison. Position 6:D adds 1 projection and 7 pairs (p = 0.598 → C). Across all 7 positions, KV Cache uses 7 projections and 28 Q·K pairs (4 total generated tokens [D, C, D, C]), whereas No Cache burns 22 projections and 74 Q·K pairs (3.6× more total Decode Q·K pairs at 64 vs 18, and 4× on Step 3 alone at 28 vs 7) for the exact same output.

In the canvas, skipped causal rows turn muted teal (cached) while only the active Decode row burns amber (active/last row); under No Cache, recomputed past rows flash brick (recomputed) and under Window (W = 4), evicted early columns appear cross-hatched gray (evicted).

Compute vs Memory: O(L²) Attention Becomes O(L) Cache Reads

PolicyStep-L projectionsStep-L causal Q·KPersistent KV memoryExact parity (ΔP = 0)?
KV Cache1 (O(d²))L (O(Ld))2 · L · d floats (O(Ld))Yes — exact
No CacheL (O(Ld²))L(L+1)/2 (O(L²d))0 persistent slotsYes — exact
Sliding Window (W)1 (O(d²))min(L, W) (O(Wd))2 · min(L, W) · d floats (O(Wd))Only while L ≤ W

Across a full N = P + D run, caching cuts total attention work from O(N³d) to O(N²d) and eliminates N(N−1)/2 − P(P−1)/2 redundant earlier-row recomputations. The price is memory footprint and memory bandwidth: every Decode step must stream all 2 · L · d cached floats per head and layer from memory to score 1 query token—which is why real LLM inference transitions from compute-bound Prefill to memory-bandwidth-bound Decode.

At production scale, that linear cache budget becomes the dominant capacity constraint: for a 70B-class model (80 layers, 8 GQA KV heads × 128 dim in BF16), storing (K, V) takes 2 × 80 × 8 × 128 × 2 = 327,680 bytes (320 KiB) per token, so one 32,768-token sequence holds 10.0 GiB of KV cache that must stream from HBM on every Decode step. Because Prefill sets time-to-first-token (TTFT) while KV streaming drives time-per-output-token (TPOT) and caps concurrent batch size, serving engines reuse shared system-prompt slots via Prefix Caching, and teams reach for GQA, FP8 KV quantization, or bounded windows when hitting HBM capacity.

KV Cache Edge Cases: Window Eviction and Prefix Edits

  • Exact boundary while L ≤ W: Under Window (W = 4) with prompt P = 3, both Prefill (L = 3) and Decode 1 (L = 4) fit inside capacity 4 with zero eviction and max |ΔP| = 0. Eviction starts only once L = 5 at Decode 2 (0:A dropped, output flips D → C).
  • Silent drift before an argmax flip: On the default prompt P = 4 under Window (W = 4), Decode 1 evicts 0:A when row 4 only gave 0:A 4% attention weight. Probabilities shift by max |ΔP| = 0.0326, yet C still wins argmax; only on Decode 2 (when C needed 80% attention to 0:A) does output visibly flip from D to C (ΔP = 0.5293). Production streaming decoders pin early "attention sink" tokens rather than using pure FIFO for this exact reason.
  • Prompt exceeding the window during Prefill: When P = 5 > W = 4, FIFO eviction drops 0:A inside Prefill itself, immediately flipping the very first emitted token from D to C (ΔP = 0.4521).
  • Invalidation on prefix edit: Changing any token at position k leaves cached K/V for 0..k−1 valid (since causal attention never reads forward), but invalidates position k and every later slot > k.

Common KV Cache Mistakes

  • Thinking the KV cache is an approximation. An unbounded causal KV cache computes the exact same mathematical function as full-sequence recomputation (ΔP = 0); approximations happen only when you evict, quantize, or share KV entries across layers/positions.
  • Assuming Q is cached alongside K and V. Caching Q wastes memory because past queries never participate in future rows' attention scores.
  • Resetting Decode position indices to 0. Feeding pe(0) instead of pe(pos) for new Decode tokens breaks positional alignment with the cached K/V entries and invalidates parity (ΔP > 0).
  • Concluding single-layer No Cache only computes 1 row. In a one-layer model, the very last row alone suffices to predict the next token; in real multi-layer Transformers, every non-final layer must recompute all L hidden states 0..L−1 to feed the layer above it, which is why the No Cache baseline accounts all L projections and L(L+1)/2 causal pairs.

A Note on Simplification

This visualization isolates a single causal attention head (d = 4, √d_k = 2) with hand-set projection weights, an identity output head, and explicit sinusoidal positional encodings (omitting RoPE, feed-forward layers, layer norms, multi-head/grouped-query attention, batching, PagedAttention, prefix caching, and KV quantization). Work is measured in token projections, Q·K pairs, stored scalars, and cache reads rather than fabricated GPU timings. Continue to Decoding Strategies to see how probabilities become sampled tokens, or revisit Attention Mechanism for the full single-step Q/K/V arithmetic.