The KV Cache and Cache Reduction

Dive into Deep Learning · §11.3

The KV Cache, the Hardware Roofline, and Cache Reduction
KV caching · prefill vs. decode · arithmetic intensity · batched throughput · GQA & uptraining · low-rank MLA · attention sinks

Naive Generation Performs 250× Redundant Work

Motivation

  • Naive GPT.generate (O(T^2) work): Re-runs the full prefix 3{,}584, 3{,}585, \dots, 3{,}839 at every generated token (950{,}144 token evaluations).
  • Why past recomputation is redundant: Under a causal mask, (\mathbf{k}_s, \mathbf{v}_s) at position s < t never changes when token t arrives.
  • Cached generation (O(T) work): Processes the prompt once and each new token once (3{,}840 evaluations—250\times less work).

Causality Freezes Past Keys and Values

The Caching Principle

  • What to cache at each block: Query \mathbf{q}_s (s < t) is used only when emitting token s+1 and never needed again. Only the post-RoPE keys \mathbf{K}_{1:t} and values \mathbf{V}_{1:t} are read by future steps.
  • Stage 1 — Prefill (n = T_p tokens): Processes the entire prompt in one parallel forward pass (offset = 0), populating slots 0, \dots, T_p - 1 of the cache.
  • Stage 2 — Decode (n = 1 token/step): Projects only the newest token x_t into (\mathbf{q}_t, \mathbf{k}_t, \mathbf{v}_t), writes slot t, and attends \mathbf{q}_t across cached (\mathbf{K}_{0:t}, \mathbf{V}_{0:t}).
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Pre-Allocated Static Buffers and Position Offsets

Buffer Architecture

  • Fixed-shape buffer allocation (init_cache): Pre-allocates zeroed tensors ks[i], vs[i] of shape (B, H_{\text{kv}}, T_{\max}, d_h) per block before generation begins.
  • Position offset t & boolean mask: Rotates queries/keys at offset t and masks unwritten slots > t (arange(T_max) <= pos[:, None]), keeping tensor shapes static so the compiler compiles the decode step once.

The Cached Step: Write One Slot, Read the Prefix

Implementation

Inside forward_cached, each pre-norm block projects only the new tokens X, writes k, v into pos = t + arange(T) in place, and attends across the buffer:

H = model.token_emb(X)                                # New tokens at pos = t, t+1, ...
for i, blk in enumerate(model.blks):
    q, k, v = blk.attention.qkv(blk.norm1(H), t, tables)  # RoPE rotated at offset t
    ks[i][:, :, pos], vs[i][:, :, pos] = k, v             # In-place cache update
    q = q.unflatten(1, (attn.num_kv_heads, -1))           # Group query heads per KV head
    S = q @ ks[i][:, :, None].transpose(-1, -2) / math.sqrt(q.shape[-1])
    Y = d2l.masked_softmax(S, mask) @ vs[i][:, :, None]
    H = H + attn.W_o(Y.flatten(1, 2).transpose(1, 2).flatten(2))
    H = H + blk.ffn(blk.norm2(H))

Marking cache tensors with torch._dynamo.mark_static_address(u) allows torch.compile with triton.cudagraphs=True to replay the entire decode step with near-zero Python dispatch overhead.

Verifying Exact Logit Equivalence

Correctness Verification

KV caching is not an approximation: prefilling 16 tokens and then stepping through 32 one by one gives the same logits as one uncached pass over all 48 (to rounding, \sim 10^{-7}), for rotary and learned positions alike:

for pos in ('rope', 'learned'):
    model = gpt(vocab_size=97, num_hiddens=128, num_heads=4, num_blks=3,
                pos=pos).eval()
    x = torch.randint(0, 97, (1, 48))
    ks, vs = init_cache(model, 1, 48)
    with torch.inference_mode():
        full = model(x)[0, 15:]  # Logits after positions 15, ..., 47
        logits, ks, vs = forward_cached(model, x[:, :16], ks, vs, 0)
        outs = [logits]
        for t in range(16, 48):
            logits, ks, vs = forward_cached(model, x[:, t:t + 1], ks, vs, t)
            outs.append(logits)
    err = (torch.cat(outs) - full).abs().max()
    print(f'{pos}: max |full - cached| = {err:.1e}')
rope: max |full - cached| = 9.5e-07
learned: max |full - cached| = 6.0e-07

Empirical Speedup: Over 20× Faster at 4,000 Tokens

Wall-Clock Benchmark

  • Naive step time grows linearly with context n: Recomputing the entire prefix on a 124M-parameter model reaches 33\text{--}53\text{ ms/token} at n = 4{,}032, making a 256-token continuation take over 8\text{ seconds}.
  • Cached step time stays flat (\sim 1\text{ ms/token}): Projecting a single token takes 0.8\text{--}1.3\text{ ms} across the entire 4{,}096-token range.
naive : 256 tokens in  8.1 s =  31.5 tokens/s
cached: 256 tokens in  0.5 s = 557.2 tokens/s

The KV Cache Memory Footprint Formula

Memory Accounting

  • Storing both \mathbf{K} and \mathbf{V} across L blocks, batch size B, length n, and H_{\text{kv}} heads of width d_h at b bytes/element requires: M_{\mathrm{KV}}(n, B) = 2 \, b \, B \, L \, n \, H_{\mathrm{kv}} \, d_h \;\;\text{bytes}
  • In GPT-2 Small (FP32, 72\text{ KiB/token}), n = 4{,}096 occupies 288\text{ MiB} at B = 1 and 4.5\text{ GiB} at B = 16 (10\times the weights).
bytes_per_param = 4  # fp32 weights
weight_bytes = bytes_per_param * d2l.num_params(model)
ks, vs = init_cache(model, 1, 4096)
print(f'cache buffers {sum(u.nbytes for u in ks + vs) / 2**20:.0f} MiB, '
      f'formula {kv_cache_bytes(model, 4096) / 2**20:.0f} MiB, '
      f'weights {weight_bytes / 2**20:.0f} MiB')
cache buffers 288 MiB, formula 288 MiB, weights 471 MiB

Why Single-Token Decode Is Memory-Bandwidth Bound

The Bandwidth Floor

  • Compute vs. memory transfer: On GPT-2 Small (B = 1), 2N \approx 2.5 \times 10^8\text{ FLOPs} takes 0.003\text{ ms} at 83\text{ TFLOP/s}, yet streaming 498\text{ MB} of FP32 weights across 1\text{ TB/s} HBM imposes a hard 0.50\text{ ms/token} transfer floor.
  • Measured latency (0.8\text{--}1.3\text{ ms/token}): Sits within 1.6\text{--}2\times of the physical HBM bandwidth limit.

Prefill vs. Decode on the Hardware Roofline

The Roofline Model

  • Arithmetic intensity (I = \text{FLOPs} / \text{Bytes}): The ratio of peak compute (83\text{ TFLOP/s}) to HBM bandwidth (1\text{ TB/s}) defines the hardware ridge point at I^* \approx 82\text{ FLOPs/byte}.
  • Decode (n = 1, B = 1): Performs 2N FLOPs while reading 4N + M_{\text{KV}} bytes (I \approx 0.38\text{ FLOPs/byte} at context 2{,}048)—200\times below the ridge point (bandwidth-bound).
  • Prefill (n = 2{,}048 in parallel): Reuses each weight read across 2{,}048 tokens (I \approx 780\text{ FLOPs/byte})—well above the ridge point (compute-bound).
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Measuring Prefill vs. Decode Throughput

Roofline Verification

  • Benchmarking a 2,048-token prefill against a single-token decode step at context 2{,}048 confirms the 100\times gap between the two serving regimes:
  • TTFT is governed by compute-bound prefill, whereas ITL is governed by memory-bandwidth-bound decode.
bandwidth = 1e12  # bytes/s, about an RTX 4090
flops = 2 * d2l.num_params(model)  # One decode step at context 2048
moved = weight_bytes + kv_cache_bytes(model, 2048)
print(f'prefill: {2048 / t_prefill:6.0f} tokens/s')
print(f'decode:  {1 / t_decode:6.0f} tokens/s, bandwidth ceiling '
      f'{bandwidth / moved:.0f} tokens/s')
print(f'FLOPs per byte: decode {flops / moved:.2f}, '
      f'prefill about {2048 * flops / moved:.0f}')
prefill: 150413 tokens/s
decode:     952 tokens/s, bandwidth ceiling 1550 tokens/s
FLOPs per byte: decode 0.38, prefill about 784

Batched Decoding and the KV-Bandwidth Ceiling

Amortizing Weight Reads

Decoding B sequences simultaneously reads the model weights M_{\text{weights}} once per step for all B tokens, but must still read B distinct KV caches (B \cdot M_{\text{KV}}(n, 1) bytes):

\mathrm{Throughput}(B, n) \le \frac{B \, \mathcal{B}_{\mathrm{HBM}}}{M_{\mathrm{weights}} + B \, M_{\mathrm{KV}}(n, 1)} \;\xrightarrow{\;B \to \infty\;}\; \frac{\mathcal{B}_{\mathrm{HBM}}}{M_{\mathrm{KV}}(n, 1)}

  • Small-batch regime (B \, M_{\text{KV}} \ll M_{\text{weights}}): Weight reads dominate HBM traffic, so total throughput scales nearly linearly with B (“free batching”).
  • Half-saturation batch size (B_{1/2} = M_{\text{weights}} / M_{\text{KV}}(n, 1)): The batch size where total KV cache bytes equal the model weight bytes (B_{1/2} \approx 53 at n = 128, but B_{1/2} \approx 6.6 at n = 1{,}024).

Measured Decode Throughput vs. Batch Size

Amortizing Weight Reads

n=128: 1173, 3574, 12353, 32525 tokens/s
n=1024: 1104, 2783, 6507, 9902 tokens/s

Three Orthogonal Axes for Shrinking the KV Cache

Cache Compression Overview

  • Because both VRAM capacity and the large-batch throughput ceiling \mathcal{B}_{\text{HBM}} / M_{\text{KV}}(n, 1) scale inversely with M_{\text{KV}}(n, 1) = 2 b L n H_{\text{kv}} d_h, modern LLMs compress all three factors:
    1. Head count (H_{\text{kv}}): GQA and MQA (4\text{--}8\times).
    2. Feature width (2 H_{\text{kv}} d_h): Low-rank SVD / MLA (6\text{--}16\times).
    3. Sequence length (n): Sliding window w + s sinks.

Axis 1: Grouped-Query (GQA) and Multi-Query Attention

Sharing Key–Value Heads

  • Multi-Head Attention (MHA, H_{\text{kv}} = H): Every query head has its own private key and value head.
  • Multi-Query Attention (MQA, H_{\text{kv}} = 1, Shazeer 2019): All H query heads share a single key and value head, cutting the cache by H\times.
  • Grouped-Query Attention (GQA, 1 < H_{\text{kv}} < H, Ainslie et al. 2023): Partitions H query heads into H_{\text{kv}} groups of size G = H / H_{\text{kv}}, cutting the cache by G\times while matching MHA quality (used in Llama 3 and Qwen3).
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Converting MHA Checkpoints via GQA Uptraining

Checkpoint Uptraining

Can we convert an already-trained multi-head checkpoint (H_{\text{kv}} = H) into a GQA model (H_{\text{kv}} = H/G) without retraining from scratch?

\mathbf{W}_k^{(\mathcal{G})} = \frac{1}{G}\sum_{h \in \mathcal{G}} \mathbf{W}_k^{(h)}, \qquad \mathbf{W}_v^{(\mathcal{G})} = \frac{1}{G}\sum_{h \in \mathcal{G}} \mathbf{W}_v^{(h)}

run 1, trained from scratch: H_kv=8 1.34, H_kv=2 1.35, H_kv=2 for 50 steps only 2.66
  H_kv=8 converted by mean : 2.76, after 50 steps 1.62, after 100 steps 1.47
  H_kv=8 converted by first: 2.83, after 50 steps 1.89, after 100 steps 1.71
run 2, trained from scratch: H_kv=8 1.34, H_kv=2 1.35, H_kv=2 for 50 steps only 2.66
  H_kv=8 converted by mean : 2.75, after 50 steps 1.62, after 100 steps 1.46
  H_kv=8 converted by first: 2.71, after 50 steps 1.79, after 100 steps 1.64
  • Trained from scratch: GQA (H_{\text{kv}} = 2, 4\times smaller cache) matches MHA (H_{\text{kv}} = 8) at 1.34\text{ nats/byte}.
  • Mean-pooling + 5\text{--}10\% uptraining: Zero-shot conversion starts near 2.8\text{ nats}, but just 100 steps (10\%) of uptraining recovers to 1.47\text{--}1.48\text{ nats}—far ahead of keeping only the first head (first) or training from scratch for 50 steps (2.7\text{ nats}).

Axis 2: Low-Rank KV Subspaces & Latent Attention (MLA)

Low-Rank KV Compression

  • Post-hoc SVD projection (6\times): Projecting GPT-2’s 1{,}536-dim [\mathbf{k}_t; \mathbf{v}_t] onto its top r = 256 singular vectors preserves perplexity (37 vs. 36).
  • Multi-Head Latent Attention (MLA, DeepSeek-V2/V3): Caches a shared latent \mathbf{c}_t \in \mathbb{R}^{r} (r = 512) and absorbs the up-projections into \mathbf{W}_q and \mathbf{W}_o during decode.
rank 512 of 768: loss 3.55, perplexity 35
rank 256 of 768: loss 3.61, perplexity 37
rank 128 of 768: loss 4.14, perplexity 63

Axis 3: Sliding Windows Fail Without Attention Sinks

The Attention Sink Phenomenon

  • On pretrained GPT-2, a pure sliding window (w = 256, s = 0) causes tail perplexity to jump from 36 to \approx 3{,}840.
  • Why? Because softmax weights must sum to 1, idle heads place 30\%\text{--}57\% of their weight onto token 0. Evicting token 0 once t \ge w scrambles the residual stream.
mean attention weight on token 0 (uniform would be about 0.003)
block      0     1     2     3     4     5     6     7     8     9    10    11
weight  0.00  0.01  0.11  0.30  0.32  0.51  0.46  0.57  0.48  0.48  0.45  0.34

Restoring Sliding-Window Perplexity With Sink Tokens

StreamingLLM & Sinks

Retaining just s \in \{1, 4\} initial attention sink tokens permanently in cache slots 0 \dots s-1 alongside the w = 256 rolling window slots (w + s cached tokens total, Xiao et al. 2024) cures the collapse zero-shot:

window 256 + 0 sink tokens: loss 8.25, perplexity 3842
window 256 + 1 sink tokens: loss 3.86, perplexity 47
window 256 + 4 sink tokens: loss 3.76, perplexity 43
full attention:            loss 3.58, perplexity 36

Keeping a single sink token (s = 1) drops perplexity from \approx 3{,}840 back to 47 (s = 4 reaches 43, vs. 36 for full 1{,}024-token attention). Modern architectures (such as gpt-oss) go one step further by giving each attention head a learnable virtual sink bias in the softmax denominator.

Concept Check: Roofline and KV Cache Sizing

Check Your Understanding

Work through these three serving calculations:

  1. 70B GQA cache footprint: Llama 3.1 70B has L = 80 layers, H = 64 query heads, H_{\text{kv}} = 8 KV heads of width d_h = 128, and BF16 weights (140\text{ GB}) and cache (b = 2\text{ B}). How many kilobytes per token does its KV cache use, and at what context length n does a single sequence’s cache equal the 140\text{ GB} weights (with GQA vs. MHA)?
  2. Half-saturation batch size: For GPT-2 Small in FP32 (M_{\text{weights}} \approx 498\text{ MB}, 72\text{ KiB/token}), at what batch size B_{1/2} does KV cache traffic equal weight traffic at context n = 4{,}096, and what is the asymptotic decode throughput ceiling at 1\text{ TB/s}?
  3. Window + sink memory: How much memory does a streaming cache with window w = 256 and s = 4 sinks use on GPT-2 Small (FP32) when generating 100{,}000 tokens?

Concept Check: Roofline and KV Cache Sizing (answers)

Check Your Understanding

Answers:

  1. 2 \times 2 \times 80 \times 8 \times 128 = 327{,}680\text{ B} = 320\text{ KiB/token} under GQA (8\times smaller than MHA’s 2.5\text{ MiB/token}). One sequence equals the 140\text{ GB} weights at n \approx 427\text{K} tokens with GQA, vs. only 53\text{K} tokens with MHA.
  2. At n = 4{,}096, one cache is 302\text{ MB}, so B_{1/2} = 498 / 302 \approx 1.6 sequences, and throughput can never exceed 10^{12} / (3.02 \times 10^8) \approx \mathbf{3{,}310\text{ tokens/s}} at any batch size.
  3. Constant (256 + 4) \times 72\text{ KiB} = 18.3\text{ MiB} at any sequence length (vs. 6.9\text{ GiB} for an unwindowed 100\text{K} cache).

Summary: Serving Regimes and KV Cache Compression

Key Takeaways

Concept / Method Mathematical Relation / Rule Systems & Architectural Takeaway
Cached Decoding Cache post-RoPE (\mathbf{K}_{1:t}, \mathbf{V}_{1:t}), step with n = 1 Cuts the weight FLOPs of T-token generation from O(T^2) to O(T) with identical logits
KV Cache Footprint M_{\text{KV}}(n, B) = 2 b B L n H_{\text{kv}} d_h Grows linearly with batch B and context n (288\text{ MiB} at n = 4096 on GPT-2)
Prefill vs. Decode I_{\text{prefill}} \approx \frac{2Bn}{b_w} \gg I^*; I_{\text{decode}} \le \frac{2}{b_w} \ll I^* Prefill is compute-bound (>10^5\text{ tok/s}); decode is bandwidth-bound (\sim 10^3\text{ tok/s})
Batched Decode \text{Throughput}(B,n) \le \frac{B \mathcal{B}_{\text{HBM}}}{M_{\text{weights}} + B M_{\text{KV}}(n,1)} Linear speedup for B \ll B_{1/2}; saturates at \mathcal{B}_{\text{HBM}} / M_{\text{KV}}(n,1)
GQA / MQA Share 1 KV head across G = H / H_{\text{kv}} query heads Shrinks cache by G\times; MHA checkpoints convert via mean-pooling + 5\text{--}10\% uptraining
Low-Rank / MLA & Sinks Rank-r latent \mathbf{c}_t \in \mathbb{R}^r; window w + s sinks Compresses width 6\text{--}16\times; s \ge 1 sink tokens prevent sliding-window softmax collapse