11.3 The KV Cache and Cache Reduction

Look closely at what GPT.generate (Section 11.2.4) does at decoding step tt: to sample token t+1t+1, it runs a full forward pass over the entire prefix x1:tx_{1:t} of length tt, reads only the last logit vector zt∈RV\mathbf{z}_t \in \mathbb{R}^V, appends xt+1x_{t+1}, and on step t+1t+1 feeds x1:t+1x_{1:t+1} through all LL blocks all over again. Because causal attention is lower-triangular, representation s≤ts \le t at every layer depends only on tokens 1,…,s1, \dots, s, so recomputing the keys and values at positions 1,…,t−11, \dots, t-1 on step tt reproduces the exact same tensors computed on step t−1t-1. Across TT generated tokens, this redundant recomputation passes O(T2)O(T^2) tokens through the weight matrices where TT would do.

Storing past keys and values in a key--value (KV) cache (Figure 11.3.1) eliminates this redundancy: at step tt, each layer projects only the single new token xtx_t into (qt,kt,vt)(\mathbf{q}_t, \mathbf{k}_t, \mathbf{v}_t), writes (kt,vt)(\mathbf{k}_t, \mathbf{v}_t) into slot tt of a pre-allocated buffer, and attends qt\mathbf{q}_t against the cached prefix (K1:t,V1:t)(\mathbf{K}_{1:t}, \mathbf{V}_{1:t}).

Eliminating redundant FLOPs, however, exposes a hardware bottleneck: memory capacity and memory bandwidth. During single-token decoding, every generated token must stream both the model weights and the entire KV cache from GPU memory (HBM) to perform a handful of matrix--vector products. At long contexts or large batches, the KV cache grows to tens of gigabytes and caps decoding throughput. The first half of this section builds the cached forward pass and analyzes prefill, decode, and batching on the hardware roofline. The second half (Section 11.3.3) compresses the KV cache along its three dimensions: head count GQA/MQA, channel width low-rank key--value projections, and sequence length sliding windows with attention sinks.

11.3.1 From Recomputation to Caching#

Figure 11.3.1:

One decoding step at position tt. Naive generation recomputes every key, value, and score row of the prefix and then uses only the last row. With a KV cache, the past keys and values are read from memory, and the step computes a single new key, value, and score row.

11.3.1.1 The Cached Forward Pass#

Why do we cache keys and values (K1:t,V1:t)(\mathbf{K}_{1:t}, \mathbf{V}_{1:t}) at each block rather than queries Q1:t\mathbf{Q}_{1:t} or residual states H1:t\mathbf{H}_{1:t}? Under causal masking, query qs\mathbf{q}_s (s<ts \lt t) is used only when emitting token s+1s+1 and is never referenced again. And caching the post-RoPE keys ks\mathbf{k}_s and values vs\mathbf{v}_s (each of shape (B,Hkv,1,dh)(B, H_{\textrm{kv}}, 1, d_h)) means past tokens never need to be re-projected by Wk,Wv\mathbf{W}_k, \mathbf{W}_v or re-rotated by RoPE.

init_cache pre-allocates zeroed key and value buffers ks, vs of shape (B,Hkv,Tmax⁡,dh)(B, H_{\textrm{kv}}, T_{\max}, d_h) for each of the LL blocks. Figure 11.3.2 shows one such buffer in the middle of generation: the slots before position tt are filled, the current step writes slot tt, and the remaining slots are still zero and hidden by the mask.

Figure 11.3.2:

The cache buffer of one block during the step at position tt (one sequence, one key--value head). Slots 0,…,t−10, \dots, t-1 hold the keys and values of earlier steps. The step writes kt\mathbf{k}_t and vt\mathbf{v}_t into slot tt. The slots after tt are still zero and the mask hides them, so query tt attends to slots 0,…,t0, \dots, t.

forward_cached(model, X, ks, vs, t) processes a slice X of nn new tokens starting at position offset t (passing offset=t to RoPE or indexing pos_emb[t:t+n]), writes their keys and values into [:, :, t:t+n, :], and attends against [:, :, :t+n, :]:

def init_cache(model, batch_size, max_len):
    """Zeroed keys and values: for every block one buffer of each, of
    shape (batch, kv heads, max_len, head width)."""
    attn = model.blks[0].attention
    shape = (batch_size, attn.num_kv_heads, max_len,
             attn.kv_hiddens // attn.num_kv_heads)
    p = next(model.parameters())
    cache = [torch.zeros(shape, device=p.device, dtype=p.dtype)
             for _ in range(2 * len(model.blks))]
    for u in cache:  # Fixed addresses, which a compiled step writes into
        torch._dynamo.mark_static_address(u)
    return cache[::2], cache[1::2]

def forward_cached(model, X, ks, vs, t):
    """Logits after the last of the new tokens X, which sit at positions
    t, t + 1, ...; writes their keys and values into the cache."""
    assert all(blk.pre_norm for blk in model.blks), 'pre-norm blocks only'
    T = X.shape[1]
    pos = t + torch.arange(T, device=X.device)  # t: an int or a tensor
    H, tables = model.token_emb(X), None
    if model.pos == 'learned':
        H = H + model.pos_emb(pos)
    else:  # RoPE angles of positions t, ..., t + T - 1, for every block
        tables = d2l.rope_tables(T, model.head_width, t, device=X.device)
    # Query t + i sees the filled positions 0, ..., t + i of the buffer
    mask = torch.arange(ks[0].shape[2], device=X.device) <= pos[:, None]
    for i, blk in enumerate(model.blks):  # Pre-norm, as in d2l.GPT
        attn = blk.attention
        q, k, v = attn.qkv(blk.norm1(H), t, tables)  # Rotated at t, ...
        ks[i][:, :, pos], vs[i][:, :, pos] = k, v    # Written in place
        # Attention over the whole buffer; each group of query heads
        # reads one key-value head: (batch, kv heads, group, T, max_len)
        q = q.unflatten(1, (attn.num_kv_heads, -1))
        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))
    return F.linear(model.norm(H[:, -1]), model.token_emb.weight), ks, vs

Using forward_cached, generate_cached splits generation into two stages: (1) prefill, which processes the entire prompt of length TpT_p in one parallel call (t = 0, n = T_p), and (2) decode, which processes one newly sampled token per step (n = 1 at offset t = T_p, T_p+1, ...):

def sample(logits, temperature=1.0, top_k=None):
    """One token per row of logits (batch, vocab), as generate draws it."""
    logits = logits / temperature
    if top_k is not None:
        cutoff = torch.topk(logits, top_k).values[:, -1:]
        logits = logits.masked_fill(logits < cutoff, -torch.inf)
    return torch.multinomial(F.softmax(logits, -1), 1)

# One-token steps of fixed shape, compiled once and replayed as CUDA graphs
# (mode='reduce-overhead' sets the first option; the second turns off a
# one-pass softmax that does not apply to a single query over a long cache)
decode_step = torch.compile(forward_cached, dynamic=True, options={
    'triton.cudagraphs': True, 'online_softmax': False})

@torch.inference_mode()
def decode(model, logits, ks, vs, t, num_tokens, temperature=1.0,
           top_k=None):
    """Sample num_tokens tokens per sequence, the first from logits and
    each next one after a step at positions t, t + 1, ...; returns them as
    (batch, num_tokens), and the cache."""
    pos = torch.arange(t, t + num_tokens, device=logits.device)
    tokens = [sample(logits, temperature, top_k)]
    for i in range(num_tokens - 1):  # No step after the last token
        logits, ks, vs = decode_step(model, tokens[-1], ks, vs, pos[i])
        tokens.append(sample(logits, temperature, top_k))
    return torch.cat(tokens, 1), ks, vs

@d2l.add_to_class(d2l.GPT)
def generate_cached(self, prefix, num_tokens, temperature=1.0, top_k=None):
    """Sample as generate does, but never recompute the prefix."""
    assert len(prefix) + num_tokens <= self.max_len, 'cache overflow'
    X = torch.tensor(prefix, device=next(self.parameters()).device)[None]
    ks, vs = init_cache(self, 1, len(prefix) + num_tokens)
    with torch.inference_mode():  # Prefill: the whole prompt in one call
        logits, ks, vs = forward_cached(self, X, ks, vs, 0)
    tokens = decode(self, logits, ks, vs, len(prefix), num_tokens,
                    temperature, top_k)[0]
    return list(prefix) + tokens[0].tolist()

11.3.1.2 Checking Exact Equivalence#

Before timing generate_cached, we verify that prefilling a prompt and stepping one token at a time through the cache produces the exact same logits (to within floating-point rounding ∼10−6\sim 10^{-6}) as running model(X) on the full sequence at once, for both pos='rope' and pos='learned':

gpt = d2l.GPT

We now instantiate a 3-block GPT under both rotary (pos='rope') and learned absolute (pos='learned') positional embeddings, prefill the first 1616 tokens of a 4848-token sequence in one call, step through the remaining 3232 positions one token at a time, and measure the maximum absolute discrepancy against the full uncached forward pass model(x):

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

11.3.1.3 Measuring the Quadratic-to-Linear Speedup#

On a 12-layer GPT-2-sized model (d=768,H=12,L=12d = 768, H = 12, L = 12), comparing the wall-clock time of one uncached forward pass over nn tokens (time_forward, which naive decoding repeats at every step) against one cached decode step at context length nn (time_decode) shows why caching is mandatory for long-context generation:

torch.set_float32_matmul_precision('high')  # fp32 matmuls may use tf32
device = d2l.try_gpu()
model = gpt(vocab_size=50257, num_hiddens=768, num_heads=12, num_blks=12,
            max_len=4096).to(device).eval()  # GPT-2's vocabulary and size
print(f'{d2l.num_params(model) / 1e6:.0f}M parameters')
124M parameters

Next, we define two timing helpers using d2l.Benchmark: time_forward(model, n) measures a compiled full-prefix forward pass over nn tokens, while time_decode(model, batch_size, n) averages the wall-clock latency of 3232 single-token cached decode steps starting at context length nn:

def time_forward(model, n):
    """Seconds for a compiled forward pass over n random tokens."""
    device = next(model.parameters()).device
    x = torch.randint(0, model.token_emb.num_embeddings, (1, n),
                      device=device)
    forward = torch.compile(model)
    with torch.inference_mode():
        return d2l.Benchmark(lambda: forward(x)[:, -1]).time

def time_decode(model, batch_size, n):
    """Seconds per decode step for batch_size sequences at context n,
    averaged over 32 steps."""
    device = next(model.parameters()).device
    logits = torch.zeros(batch_size, model.token_emb.num_embeddings,
                         device=device)  # Uniform: random first tokens
    ks, vs = init_cache(model, batch_size, n + 32)
    return d2l.Benchmark(
        lambda: decode(model, logits, ks, vs, n, 33)).time / 32

Sweeping the context length nn across powers of two from 256256 to 4,0324{,}032 tokens contrasts the linear growth of each uncached step against the nearly flat latency of a cached decode step:

lengths, t_naive, t_cached = [256, 512, 1024, 2048, 4032], [], []
for n in lengths:
    t_naive.append(time_forward(model, n))
    t_cached.append(time_decode(model, 1, n))
    print(f'n={n:4d}: naive {1e3 * t_naive[-1]:5.1f} ms, '
          f'cached {1e3 * t_cached[-1]:4.1f} ms per token')
n= 256: naive   2.7 ms, cached  0.9 ms per token
n= 512: naive   3.3 ms, cached  0.9 ms per token
n=1024: naive   6.5 ms, cached  0.9 ms per token
n=2048: naive  13.6 ms, cached  1.0 ms per token
n=4032: naive  33.2 ms, cached  1.2 ms per token

Plotting both per-token latency curves on log--log axes shows a naive step whose cost grows in proportion to the context length nn and a cached step that is nearly flat (the new query is still scored against all nn cached keys, but this cost has a small constant):

d2l.plot(lengths, [[1e3 * t for t in t_naive], [1e3 * t for t in t_cached]],
         'context length', 'ms per token', legend=['naive', 'cached'],
         xscale='log', yscale='log')

Cumulated over an end-to-end generation of 256256 new tokens after a 3,5843{,}584-token prompt, replacing model.generate with model.generate_cached yields more than an order-of-magnitude wall-clock speedup:

prefix = list(range(3584))  # Any token ids will do for timing
for name, gen in (('naive ', model.generate),
                  ('cached', model.generate_cached)):
    t = d2l.Benchmark(lambda: gen(prefix, 256), warmup=1, repeats=1).time
    print(f'{name}: 256 tokens in {t:4.1f} s = {256 / t:5.1f} tokens/s')
naive : 256 tokens in  8.1 s =  31.5 tokens/s
cached: 256 tokens in  0.5 s = 557.2 tokens/s

11.3.2 Memory Capacity and the Hardware Roofline#

For a model with LL blocks, batch size BB, sequence length nn, and HkvH_{\textrm{kv}} key--value heads of width dhd_h stored at bb bytes per number (b=4b = 4 for FP32, 22 for BF16/FP16, 11 for FP8), each block stores two tensors (K\mathbf{K} and V\mathbf{V}) of shape (B,Hkv,n,dh)(B, H_{\textrm{kv}}, n, d_h). The total KV cache footprint is therefore

MKV(n,B)  =  2 b B L n Hkv dh    bytes.(11.3.1)M_{\textrm{KV}}(n, B) \;=\; 2 \, b \, B \, L \, n \, H_{\textrm{kv}} \, d_h \;\;\textrm{bytes}. \tag{11.3.1}
def kv_cache_bytes(model, num_tokens, batch_size=1, bytes_per_elem=4):
    """Bytes of the keys and values of num_tokens positions in every block
    of a GPT, for batch_size sequences."""
    attn = model.blks[0].attention
    return (2 * len(model.blks) * attn.kv_hiddens * num_tokens * batch_size
            * bytes_per_elem)

Evaluating kv_cache_bytes on our 124M-parameter FP32 model at n=4,096n = 4{,}096 tokens confirms that the allocated cache buffers match (11.3.1) (288 MiB288\textrm{ MiB}) and already exceed half the 471 MiB471\textrm{ MiB} footprint of the model 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

11.3.2.1 Prefill vs. Decode on the Roofline#

Why did a 2,048-token prefill take nearly the same order of magnitude of time per call as some fifteen single-token decode steps? The roofline model (Figure 11.3.3) explains the difference via arithmetic intensity (FLOPs performed per byte transferred between HBM and the compute units):

  • Prefill (n=2048n = 2048 tokens in parallel, compute-bound): Each weight matrix W\mathbf{W} is read from HBM once and multiplied by BnB n token vectors (2BnNparams2 B n N_{\textrm{params}} FLOPs across bwNparamsb_w N_{\textrm{params}} weight bytes), giving an arithmetic intensity of ∼2Bn/bw≫80 FLOPs/byte\sim 2 B n / b_w \gg 80\textrm{ FLOPs/byte}—well above the GPU's ridge point, saturating the tensor cores.
  • Single-stream decode (B=1,n=1B = 1, n = 1 token per step, memory-bandwidth bound): Each step performs only 2Nparams2 N_{\textrm{params}} matrix--vector FLOPs while streaming all bwNparamsb_w N_{\textrm{params}} weight bytes plus MKV(n,1)M_{\textrm{KV}}(n, 1) cache bytes from HBM, giving an arithmetic intensity of ≤2/bw≈0.5 FLOPs/byte\le 2 / b_w \approx 0.5\textrm{ FLOPs/byte} (in FP32, or 1.0 FLOP/byte1.0\textrm{ FLOP/byte} in BF16)—more than 100×100\times below the compute roof.
Figure 11.3.3:

The fp32 roofline of an RTX 4090. Attainable throughput is the smaller of the compute roof, about 83 TFLOP/s, and the arithmetic intensity times the memory bandwidth of about 1 TB/s; the two meet at the ridge point of about 82 FLOPs per byte. A decode step of a GPT-2-sized model at a context of 2,048 tokens performs 0.38 FLOPs per byte and sits far down the bandwidth slope; a prefill of 2,048 tokens, at about 780 counting weights and cache only, sits under the roof.

t_prefill = time_forward(model, 2048)
t_decode = time_decode(model, 1, 2048)

Comparing the resulting token throughputs and arithmetic intensities against a 1 TB/s1\textrm{ TB/s} HBM bandwidth budget shows why single-stream decode sits near the memory-bandwidth ceiling while a 2,0482{,}048-token prefill achieves more than 100×100\times higher throughput:

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

11.3.2.2 Batched Decoding#

Because a single-stream decode step (B=1B = 1) spends its time streaming the model's weight bytes Mweights=bwNparamsM_{\textrm{weights}} = b_w N_{\textrm{params}} from HBM, decoding a batch of BB sequences simultaneously reuses each weight read across all BB tokens while reading BB distinct KV caches (B MKV(n,1)B \, M_{\textrm{KV}}(n, 1) bytes). At memory bandwidth BHBM\mathcal{B}_{\textrm{HBM}} (bytes/s), the bandwidth-limited decode throughput (tokens/s) is

Throughput(B,n)  ≤  B BHBMMweights+B MKV(n,1).(11.3.2)\textrm{Throughput}(B, n) \;\le\; \frac{B \, \mathcal{B}_{\textrm{HBM}}}{M_{\textrm{weights}} + B \, M_{\textrm{KV}}(n, 1)}. \tag{11.3.2}

At small batch sizes (B MKV≪MweightsB \, M_{\textrm{KV}} \ll M_{\textrm{weights}}), throughput grows nearly linearly with BB ("free batching"); as BB or nn grows large (B MKV≫MweightsB \, M_{\textrm{KV}} \gg M_{\textrm{weights}}), KV cache reads dominate HBM traffic and throughput saturates at the KV-bandwidth ceiling BHBM/MKV(n,1)\mathcal{B}_{\textrm{HBM}} / M_{\textrm{KV}}(n, 1):

batches, measured, bounds = [1, 4, 16, 64], [], []
for n in (128, 1024):
    measured.append([b / time_decode(model, b, n) for b in batches])
    nc = kv_cache_bytes(model, n)  # One sequence's cache
    bounds.append([b * bandwidth / (weight_bytes + b * nc) for b in batches])
    print(f'n={n}: ' + ', '.join(f'{r:.0f}' for r in measured[-1])
          + ' tokens/s')
d2l.plot(batches, measured + bounds, 'batch size', 'tokens per second',
         legend=['n=128', 'n=1024'], fmts=('C0-o', 'C1-s', 'C0:', 'C1:'),
         xscale='log', yscale='log', legend_loc='lower right')
n=128: 1173, 3574, 12353, 32525 tokens/s
n=1024: 1104, 2783, 6507, 9902 tokens/s

11.3.3 Shrinking the KV Cache#

Because both memory capacity ((11.3.1)) and the large-batch decode throughput ceiling ((11.3.2)) are governed by the per-sequence cache size MKV(n,1)=2bLnHkvdhM_{\textrm{KV}}(n, 1) = 2 b L n H_{\textrm{kv}} d_h, modern Transformer architectures compress the product n⋅Hkv⋅dhn \cdot H_{\textrm{kv}} \cdot d_h along three orthogonal axes:

  1. Fewer key--value heads (Hkv<HH_{\textrm{kv}} \lt H): Grouped-query attention (GQA) (Ainslie et al., 2023) and multi-query attention (MQA) (Shazeer, 2019) share each key--value head across G=H/HkvG = H / H_{\textrm{kv}} query heads (Figure 11.3.4).
  2. Narrower per-token representations (2Hkvdh→r2 H_{\textrm{kv}} d_h \to r): Low-rank key--value projections and Multi-Head Latent Attention (MLA) (DeepSeek-AI et al., 2024) compress all heads' keys and values into a low-dimensional latent vector (Section 11.3.3.2).
  3. Shorter cached context (n→w+sn \to w + s): Sliding-window attention evicts tokens older than a window ww, while keeping s≥1s \ge 1 initial attention sink tokens (Xiao et al., 2024) so the softmax denominator remains stable (Section 11.3.3.3).
Figure 11.3.4:

Query heads and the key--value heads they read. Multi-head attention gives every query head its own key--value head; grouped-query attention shares one per group of query heads; multi-query attention shares a single one across all of them. The cache scales with the number of key--value heads.

11.3.3.1 Axis 1: Grouped-Query Attention and Checkpoint Uptraining#

Our CausalAttention class (Section 11.2) already accepts num_kv_heads: setting Hkv=H/GH_{\textrm{kv}} = H / G shrinks Wqkv\mathbf{W}_{qkv} and cuts MKVM_{\textrm{KV}} by a factor of G=H/HkvG = H / H_{\textrm{kv}}. Moreover, Ainslie et al. (2023) showed that an existing multi-head checkpoint (Hkv=HH_{\textrm{kv}} = H) can be converted into a GQA or MQA model by mean-pooling each group of GG key and value projection heads (pool_heads) and uptraining for a small fraction (∼5–10%\sim 5\text{--}10\%) of the original training budget.

We compare training our 6-block byte-level GPT (H=8H = 8) from scratch for 1,000 steps at Hkv∈{8,2}H_{\textrm{kv}} \in \{8, 2\} (and at Hkv=2H_{\textrm{kv}} = 2 for only 50 steps) against converting the trained Hkv=8H_{\textrm{kv}} = 8 checkpoint down to Hkv=2H_{\textrm{kv}} = 2, by mean-pooling and by keeping the first head of each group, both zero-shot (0 steps) and after 50 and 100 steps (10%10\%) of uptraining, in two runs:

def pool_heads(target, source, pool):
    """Load the weights of source into target, which has fewer key-value
    heads. Each key (and value) projection of target is the mean of those
    of a group of consecutive heads of source (pool='mean'), or the first
    of them (pool='first')."""
    src, tgt = source.blks[0].attention, target.blks[0].attention
    group = src.num_kv_heads // tgt.num_kv_heads
    state = source.state_dict()
    for name, W in state.items():
        if name.endswith('W_qkv.weight'):  # Rows: d queries, keys, values
            q, k, v = W.split([W.shape[1], src.kv_hiddens, src.kv_hiddens])
            k, v = (u.unflatten(0, (tgt.num_kv_heads, group, -1))
                    for u in (k, v))
            k, v = ((u.mean(1) if pool == 'mean' else u[:, 0]).flatten(0, 1)
                    for u in (k, v))
            state[name] = torch.cat([q, k, v])
    target.load_state_dict(state)
    return target.to(next(source.parameters()).device)

We now train our 6-block byte-level GPT on WikiText103 at Hkv∈{8,2}H_{\textrm{kv}} \in \{8, 2\} and evaluate pool_heads with both 'mean' and 'first' head pooling across 00, 5050, and 100100 uptraining steps:

data = d2l.WikiText103(batch_size=64, num_steps=128)

def trained(num_kv_heads, num_steps=1000):
    """A d2l.GPT trained from scratch with the recipe of the GPT section."""
    lm = gpt(len(data.vocab), num_kv_heads=num_kv_heads)
    optimizer = d2l.LMOptimizer(lm, lr=2e-3, num_steps=num_steps,
                                warmup=min(100, num_steps // 10))
    d2l.train_steps(lm, data, optimizer, num_steps)
    return lm

def val_loss(lm):
    return math.log(d2l.lm_perplexity(lm, data.val_dataloader()))

for run in (1, 2):
    mha = trained(8)
    print(f'run {run}, trained from scratch: H_kv=8 {val_loss(mha):.2f}, '
          f'H_kv=2 {val_loss(trained(2)):.2f}, '
          f'H_kv=2 for 50 steps only {val_loss(trained(2, 50)):.2f}')
    for pool in ('mean', 'first'):
        lm = pool_heads(gpt(len(data.vocab), num_kv_heads=2), mha, pool)
        losses = [val_loss(lm)]
        optimizer = d2l.LMOptimizer(lm, lr=3e-4, num_steps=10**9, warmup=0)
        for _ in range(2):  # Uptraining at a constant rate
            d2l.train_steps(lm, data, optimizer, 50)
            losses.append(val_loss(lm))
        print(f'  H_kv=8 converted by {pool:5s}: {losses[0]:.2f}, after 50 '
              f'steps {losses[1]:.2f}, after 100 steps {losses[2]:.2f}')
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

Sharing keys and values across 4 query heads (Hkv=2H_{\textrm{kv}} = 2, a 4×4\times smaller KV cache) costs no measurable quality when trained from scratch (1.34--1.35 against 1.34 nats/byte). Head pooling starts near 2.8 nats/byte, and 100 steps of uptraining bring the mean-pooled model to about 1.47, roughly 90% of the way back, while 50 steps from scratch reach only about 2.7 and keeping the first head of each group trails mean-pooling after uptraining.

11.3.3.2 Axis 2: Low-Rank Key--Value Projections#

Instead of reducing the number of heads HkvH_{\textrm{kv}}, can we compress the 2d2 d-dimensional concatenated key--value vector [kt;vt]∈R2d[\mathbf{k}_t; \mathbf{v}_t] \in \mathbb{R}^{2d} of each token at layer ii into a rank-rr subspace (r≪2dr \ll 2d)? We test this directly on pretrained GPT-2 Small (124M, where d=768d = 768 and 2d=15362d = 1536) on a passage of T=1024T = 1024 tokens of The Time Machine:

gpt2, enc = d2l.load_gpt2().to(device), d2l.gpt2_tokenizer()
fname = d2l.download(d2l.DATA_URL + 'timemachine.txt', '../data',
                     '090b5e7e70c295757f55df93cb0a180b9691891a')
tokens = torch.tensor(enc.encode(open(fname).read()), device=device)
x, calib = tokens[None, :1024], tokens[None, 1024:2048]
print(f'{len(tokens)} tokens of The Time Machine')
44073 tokens of The Time Machine

To intercept and transform the keys and values inside every layer without rewriting GPT, we define forward_blocks(model, X, attn_fn), which delegates block ii's attention to a callback attn_fn(q, k, v, i), and verify that standard causal attention matches gpt2(x) to within 10−510^{-5} while establishing our baseline tail_loss on positions 512…1023512 \dots 1023:

def forward_blocks(model, X, attn_fn):
    """The forward pass of a d2l.GPT with attention computed by
    attn_fn(q, k, v, i) in block i, on inputs of shape (batch, heads,
    length, head width)."""
    assert all(blk.pre_norm for blk in model.blks), 'pre-norm blocks only'
    H = model.token_emb(X)
    if model.pos == 'learned':
        H = H + model.pos_emb(torch.arange(X.shape[1], device=X.device))
    for i, blk in enumerate(model.blks):
        attn = blk.attention
        Y = attn_fn(*attn.qkv(blk.norm1(H)), i)
        H = H + attn.W_o(Y.transpose(1, 2).flatten(2))
        H = H + blk.ffn(blk.norm2(H))
    return F.linear(model.norm(H), model.token_emb.weight)

def tail_loss(logits, X):
    """Mean loss of the next-token predictions from position 512 on."""
    return F.cross_entropy(logits[0, 512:-1], X[0, 513:])

causal = lambda q, k, v, i: F.scaled_dot_product_attention(
    q, k, v, is_causal=True)
with torch.inference_mode():
    logits = forward_blocks(gpt2, x, causal)
    print(f'helper vs model: max deviation '
          f'{(logits - gpt2(x)).abs().max():.1e}')
    full = tail_loss(logits, x)
print(f'full attention: loss {full:.2f}, perplexity {full.exp():.0f}')
helper vs model: max deviation 0.0e+00
full attention: loss 3.58, perplexity 36

Using the next 1,024 tokens of the book (calib) to fit an empirical PCA/SVD basis Ui∈R2d×r\mathbf{U}_i \in \mathbb{R}^{2d \times r} for each layer's concatenated key--value rows (fit_bases) and projecting the keys and values of the evaluated passage x onto the top r∈{512,256,128}r \in \{512, 256, 128\} directions (projected) measures how compressible GPT-2's KV cache is even without retraining:

def kv_rows(k, v):
    """Keys and values of all heads of each token as one row: (T, 2d)."""
    return torch.cat([u[0].transpose(0, 1).flatten(1) for u in (k, v)], 1)

def fit_bases(model, X):
    """Right singular vectors of the key-value rows of X in every block."""
    bases = []
    def fit(q, k, v, i):
        bases.append(torch.linalg.svd(kv_rows(k, v), full_matrices=False)[2])
        return causal(q, k, v, i)
    forward_blocks(model, X, fit)
    return bases

def projected(bases, r):
    """Attention with keys and values projected onto the top r bases."""
    def attn_fn(q, k, v, i):
        P = bases[i][:r]  # (r, 2d), orthonormal rows
        KV = kv_rows(k, v) @ P.T @ P
        k, v = (u.unflatten(1, (k.shape[1], -1)).transpose(0, 1)[None]
                for u in KV.chunk(2, 1))
        return causal(q, k, v, i)
    return attn_fn

with torch.inference_mode():
    bases = fit_bases(gpt2, calib)
    for r in (512, 256, 128):
        loss = tail_loss(forward_blocks(gpt2, x, projected(bases, r)), x)
        print(f'rank {r} of 768: loss {loss:.2f}, '
              f'perplexity {loss.exp():.0f}')
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

Because each block computes its 2d2d keys and values from one dd-dimensional input with one matrix and one bias, they lie in an affine subspace of only d=768d = 768 dimensions, the "of 768" in the output. Even post-hoc linear projection compresses GPT-2's KV vectors by 6×6\times (r=256r = 256 out of 2d=15362d = 1536) with no measurable degradation (3.61 against 3.58 nats), while r=128r = 128 costs more than half a nat; when the low-rank bottleneck is trained end-to-end as in DeepSeek-V2/V3's Multi-Head Latent Attention (MLA) (DeepSeek-AI et al., 2024), a single 512-dimensional latent vector replaces all heads' keys and values at >16×>16\times compression.

11.3.3.3 Axis 3: Sliding Windows and Attention Sinks#

Our third axis bounds the sequence length nn stored in the cache to a rolling window of the ww most recent tokens (Section 10.6). However, if we apply a pure sliding window (w=256w = 256) to pretrained GPT-2 on a 1,024-token passage, cross-entropy on the tail tokens (t≥512t \ge 512) jumps from ∼3.6\sim 3.6 nats to over 88 nats.

To see why, sink_mass measures the average attention probability that queries at positions t≥64t \ge 64 assign to token 0 (the very first token of the sequence) in each of GPT-2's 12 layers:

def sink_mass(model, X):
    """Mean attention weight on token 0 of the queries from position 64
    on, one entry per block."""
    masses = []
    def watch(q, k, v, i):  # Explicit causal attention
        scores = q @ k.transpose(-1, -2) / math.sqrt(q.shape[-1])
        alpha = d2l.masked_softmax(scores, d2l.causal_mask(
            q.shape[2], device=q.device))
        masses.append(alpha[..., 64:, 0].mean())
        return alpha @ v
    forward_blocks(model, X, watch)
    return masses

with torch.inference_mode():
    masses = sink_mass(gpt2, x)
print('mean attention weight on token 0 (uniform would be about 0.003)')
print('block ' + ''.join(f'{i:6d}' for i in range(len(masses))))
print('weight' + ''.join(f'{m:6.2f}' for m in torch.stack(masses).tolist()))
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

In the middle and upper layers of GPT-2, queries place 30% to nearly 60% of their entire attention weight on token 0, regardless of what word sits at position 0. Because softmax probabilities must sum to 11, attention heads use the earliest token(s), the only positions visible to every causal query, as a default attention sink (Xiao et al., 2024) when no local token matches. Once a pure sliding window slides past position 0 (t≥wt \ge w), removing token 0 from the softmax denominator forces that 30–60%30\text{--}60\% probability mass onto the remaining window tokens and scrambles the residual stream.

Keeping just s∈{1,4}s \in \{1, 4\} initial sink tokens fixed at the front of the cache alongside the w=256w = 256 most recent tokens (w+sw + s cached tokens in total) restores GPT-2's validation loss almost completely to its full-context baseline:

j = torch.arange(x.shape[1], device=device)
allowed = d2l.causal_mask(x.shape[1], device=device)
w = 256  # The window: each query sees itself and the 255 tokens before it
window = allowed & (j[:, None] - j[None, :] < w)
with torch.inference_mode():
    for nsink in (0, 1, 4):
        mask = window | (allowed & (j[None, :] < nsink))
        loss = tail_loss(forward_blocks(
            gpt2, x, lambda q, k, v, i: F.scaled_dot_product_attention(
                q, k, v, attn_mask=mask)), x)
        print(f'window {w} + {nsink} sink tokens: loss {loss:.2f}, '
              f'perplexity {loss.exp():.0f}')
print(f'full attention:            loss {full:.2f}, '
      f'perplexity {full.exp():.0f}')
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

11.3.4 Comparison of Cache-Reduction Methods#

Table 11.3.1. Summary of KV cache reduction mechanisms along the three factors of MKV=2bBLnHkvdhM_{\textrm{KV}} = 2 b B L n H_{\textrm{kv}} d_h.
MethodFactor reducedStored numbers per sequenceNeeds training?
Shared KV heads (GQA, MQA) (Shazeer, 2019; Ainslie et al., 2023)Heads Hkv<HH_{\textrm{kv}} \lt H2LnHkvdh2 L n H_{\textrm{kv}} d_hYes: train from scratch or uptrain (∼5–10%\sim 5\text{--}10\%)
Low-rank latent (MLA) (DeepSeek-AI et al., 2024)Width 2Hkvdh→r2 H_{\textrm{kv}} d_h \to r≈Lnr\approx L n r (plus a small rotary key)Yes for MLA; a post-hoc SVD basis works to ∼6×\sim 6\times
Sliding window with sinks (Xiao et al., 2024)Length n→w+sn \to w + s2L(w+s)Hkvdh2 L (w + s) H_{\textrm{kv}} d_hWorks zero-shot on pretrained models when s≥1s \ge 1

11.3.5 Summary#

KV caching stores the post-RoPE keys and values of past tokens so each decoding step projects only the single new token (n = 1), reducing projection work across TT generated tokens from O(T2)O(T^2) to O(T)O(T) token evaluations (and attention scoring from O(T3)O(T^3) to O(T2)O(T^2)) while producing identical logits. On the hardware roofline (Figure 11.3.3), serving splits into compute-bound prefill (n=Tpn = T_p prompt tokens processed in parallel at high arithmetic intensity) and memory-bandwidth-bound decode (n=1n = 1 token per step at low arithmetic intensity). Batched decoding amortizes weight reads across BB concurrent sequences ((11.3.2)), scaling throughput linearly with BB until KV cache traffic dominates and throughput saturates at BHBM/MKV(n,1)\mathcal{B}_{\textrm{HBM}} / M_{\textrm{KV}}(n, 1). To raise both capacity and large-batch throughput, modern architectures compress MKV=2bLnHkvdhM_{\textrm{KV}} = 2 b L n H_{\textrm{kv}} d_h ((11.3.1)) along three orthogonal axes (Table 11.3.1): head count GQA/MQA, channel width low-rank KV / MLA, and sequence length sliding windows with attention sinks.

11.3.6 Exercises#

  1. Cache memory and batch limits of a 70B model. Llama 3.1 70B has L=80L = 80 layers, hidden size d=8192d = 8192, H=64H = 64 query heads (dh=128d_h = 128), and Hkv=8H_{\textrm{kv}} = 8 key--value heads, stored in BF16 (b=2b = 2 bytes).

    1. Use (11.3.1) to compute the KV cache size MKV(n,1)M_{\textrm{KV}}(n, 1) of a single sequence at full context length n=131,072n = 131{,}072 (128K128\textrm{K}), and compare it with what the cache would cost under standard MHA (Hkv=64H_{\textrm{kv}} = 64).
    2. On an 8-GPU node with 8×80=640 GB8 \times 80 = 640\textrm{ GB} of total HBM (of which 140 GB140\textrm{ GB} holds the BF16 model weights), what is the maximum batch size BB of 128K128\textrm{K}-token sequences that can fit in the remaining 500 GB500\textrm{ GB} under GQA (Hkv=8H_{\textrm{kv}} = 8) versus MHA (Hkv=64H_{\textrm{kv}} = 64)?
  2. Batched decode throughput and the KV-bandwidth ceiling. Serve the 70B model of 1 at context length n=32,768n = 32{,}768 on a system with aggregate HBM bandwidth BHBM=24 TB/s\mathcal{B}_{\textrm{HBM}} = 24\textrm{ TB/s} and Mweights=140 GBM_{\textrm{weights}} = 140\textrm{ GB}.

    1. Evaluate the bandwidth upper bound (11.3.2) at batch sizes B∈{1,8,32,128,512}B \in \{1, 8, 32, 128, 512\} for both GQA (Hkv=8H_{\textrm{kv}} = 8) and MHA (Hkv=64H_{\textrm{kv}} = 64).
    2. At what batch size B1/2B_{1/2} does each configuration reach half of its asymptotic ceiling lim⁡B→∞Throughput(B,n)=BHBM/MKV(n,1)\lim_{B \to \infty} \textrm{Throughput}(B, n) = \mathcal{B}_{\textrm{HBM}} / M_{\textrm{KV}}(n, 1)?
  3. Prefix sharing across KK completions. Suppose K=16K = 16 sequences in a batch share a common system prompt of nshared=4096n_{\textrm{shared}} = 4096 tokens and each has generated nunique=256n_{\textrm{unique}} = 256 unique tokens. Modify the denominator of (11.3.2) when the shared prefix KV cache is stored and read once per step for all KK sequences, and compute the resulting throughput speedup at K=16K = 16 for the 70B GQA model.

  4. INT8 / FP8 KV cache quantization. Store the cached keys and values of GPT-2 in forward_blocks using symmetric per-token 8-bit integer quantization: for each token vector u∈Rd\mathbf{u} \in \mathbb{R}^d, compute scale s=max⁡j∣uj∣/127s = \max_j |u_j| / 127, quantize u~=s⋅round(u/s)\tilde{\mathbf{u}} = s \cdot \textrm{round}(\mathbf{u} / s), and use u~\tilde{\mathbf{u}} in attention. Measure the change in tail_loss on x when quantizing keys and values to 8 bits (4×4\times smaller than our FP32 cache, 2×2\times smaller than BF16) versus 4 bits (max / 7, 8×8\times / 4×4\times).

  5. Attention sinks and a virtual sink logit (softmax1\textrm{softmax}_1). Xiao et al. (2024) and gpt-oss (Table 11.2.2) note that a head needs an attention sink because standard softmax forces attention weights to sum to 11.

    1. Replace the softmax in forward_blocks with softmax1(s)j=esjeb+∑mesm\textrm{softmax}_1(\mathbf{s})_j = \frac{e^{s_j}}{e^{b} + \sum_{m} e^{s_m}} (adding a non-token sink logit b=5.0b = 5.0 to the denominator without adding any value vector).
    2. Evaluate the pure sliding window (w=256,s=0w = 256, s = 0 kept sink tokens) on GPT-2 with b=5.0b = 5.0. How much of the s=0s = 0 loss spike does the virtual denominator logit eliminate?
  6. Absorbing low-rank key--value reconstructions into Wq\mathbf{W}_q and Wo\mathbf{W}_o. Suppose layer ℓ\ell compresses each token jj into a single latent vector cj∈Rr\mathbf{c}_j \in \mathbb{R}^r (r≪dhHr \ll d_h H), from which head mm's key and value are reconstructed via kj,m=cjBk,m\mathbf{k}_{j,m} = \mathbf{c}_j \mathbf{B}_{k,m} and vj,m=cjBv,m\mathbf{v}_{j,m} = \mathbf{c}_j \mathbf{B}_{v,m} (Bk,m,Bv,m∈Rr×dh\mathbf{B}_{k,m}, \mathbf{B}_{v,m} \in \mathbb{R}^{r \times d_h}).

    1. Show that qt,mkj,m⊤=(xtWq,mBk,m⊤)cj⊤\mathbf{q}_{t,m}\mathbf{k}_{j,m}^\top = (\mathbf{x}_t \mathbf{W}_{q,m} \mathbf{B}_{k,m}^\top)\mathbf{c}_j^\top and (∑jαt,j(m)vj,m)Wo,m=(∑jαt,j(m)cj)(Bv,mWo,m)\bigl(\sum_j \alpha_{t,j}^{(m)} \mathbf{v}_{j,m}\bigr)\mathbf{W}_{o,m} = \bigl(\sum_j \alpha_{t,j}^{(m)} \mathbf{c}_j\bigr)(\mathbf{B}_{v,m}\mathbf{W}_{o,m}).
    2. Explain why absorbing Bk,m⊤\mathbf{B}_{k,m}^\top into Wq,m\mathbf{W}_{q,m} and Bv,m\mathbf{B}_{v,m} into Wo,m\mathbf{W}_{o,m} during decoding avoids ever materializing the full keys kj,m\mathbf{k}_{j,m} or values vj,m\mathbf{v}_{j,m} in HBM, and explain why DeepSeek-V2/V3 applies RoPE to a separate narrow decoupled key kjRoPE\mathbf{k}_j^{\textrm{RoPE}} rather than rotating cjBk,m\mathbf{c}_j \mathbf{B}_{k,m}.
  7. Implementing a fixed-size streaming ring-buffer cache. Write a StreamingCache variant of init_cache and forward_cached that pre-allocates only s+ws + w token slots per layer (retaining the first s=4s = 4 sink positions in slots 0…s−10 \dots s-1 and overwriting slots s+((t−s) mod w)s + ((t - s) \bmod w) in a circular buffer for t≥st \ge s), and verify that it generates 2,048 tokens using constant O(s+w)O(s + w) cache memory. gpt2 has only 1,024 learned positions, so either use a model with rotary positions (pos='rope'), whose position index may grow without bound, or assign each token of gpt2 the position of its cache slot, as Xiao et al. (2024) do.

Discussions