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):
| Stage | Length L | New proj | Active Q·K pairs | KV slots | Top probs [A, B, C, D] → Pick | max |ΔP| |
|---|---|---|---|---|---|---|
| Prefill | 4 | 4 | 10 | 4 | [0.043, 0.143, 0.190, 0.624] → D | 0.000000 |
| Decode 1 | 5 | 1 | 5 | 5 | [0.031, 0.046, 0.674, 0.249] → C | 0.000000 |
| Decode 2 | 6 | 1 | 6 | 6 | [0.022, 0.040, 0.320, 0.618] → D | 0.000000 |
| Decode 3 | 7 | 1 | 7 | 7 | [0.036, 0.085, 0.598, 0.281] → C | 0.000000 |
- Prefill projects
P = 4tokens in parallel. All four prompt tokens[A, B, C, B]at positions0..3project together toQ,K, andV(4projections). - Prefill scores the
4 × 4causal lower triangle. Evaluating rows0..3together computes4(4 + 1) / 2 = 10causalQ·Kdot products. Row3assigns weights[0.64, 0.15, 0.13, 0.08], pulling heavily from anchor0:A's Value vector. - Prefill caches
KandV, then dropsQ. Four(k_j, v_j)pairs (32scalars) lock into the KV Cache rack whileQis discarded. Row3emitsD(p = 0.624), matching full causal recomputation (max |ΔP| = 0.000000). - Decode 1 (
L = 5) reuses slots0..3. Only the newly emittedDatpos 4projects intoq_4, k_4, v_4(+1projection) and appends(k_4, v_4)to slot4. Attention computes only row4(5Q·Kpairs instead of15), emittingC(p = 0.674,ΔP = 0). - Decode 2 (
L = 6) proves long-range cache reuse. New tokenCatpos 5projects once, appends to slot5, and attends0.80back to cached0:A. Skipping rows0..4cuts Decode 2 from21pairs to6while still emittingD(p = 0.618,ΔP = 0). - Decode 3 (
L = 7) and controlled comparison. Position6:Dadds 1 projection and 7 pairs (p = 0.598→C). Across all 7 positions, KV Cache uses7projections and28Q·Kpairs (4total generated tokens[D, C, D, C]), whereas No Cache burns22projections and74Q·Kpairs (3.6× more total Decode Q·K pairs at64vs18, and4× on Step 3 alone at28vs7) 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
| Policy | Step-L projections | Step-L causal Q·K | Persistent KV memory | Exact parity (ΔP = 0)? |
|---|---|---|---|---|
| KV Cache | 1 (O(d²)) | L (O(Ld)) | 2 · L · d floats (O(Ld)) | Yes — exact |
| No Cache | L (O(Ld²)) | L(L+1)/2 (O(L²d)) | 0 persistent slots | Yes — 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: UnderWindow (W = 4)with promptP = 3, both Prefill (L = 3) and Decode 1 (L = 4) fit inside capacity4with zero eviction andmax |ΔP| = 0. Eviction starts only onceL = 5at Decode 2 (0:Adropped, output flipsD → C). - Silent drift before an argmax flip: On the default prompt
P = 4underWindow (W = 4), Decode 1 evicts0:Awhen row4only gave0:A4%attention weight. Probabilities shift bymax |ΔP| = 0.0326, yetCstill wins argmax; only on Decode 2 (whenCneeded80%attention to0:A) does output visibly flip fromDtoC(Δ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 drops0:Ainside Prefill itself, immediately flipping the very first emitted token fromDtoC(ΔP = 0.4521). - Invalidation on prefix edit: Changing any token at position
kleaves cachedK/Vfor0..k−1valid (since causal attention never reads forward), but invalidates positionkand 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
Qis cached alongsideKandV. CachingQwastes memory because past queries never participate in future rows' attention scores. - Resetting Decode position indices to
0. Feedingpe(0)instead ofpe(pos)for new Decode tokens breaks positional alignment with the cachedK/Ventries and invalidates parity (ΔP > 0). - Concluding single-layer
No Cacheonly 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 allLhidden states0..L−1to feed the layer above it, which is why theNo Cachebaseline accounts allLprojections andL(L+1)/2causal 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.
Keep exploring
A few lessons that share the same technique or lead into the next idea.
Found a mistake or something unclear?