11.3 The KV Cache and Cache Reduction
Look closely at what GPT.generate (Section 11.2.4) does at decoding step : to sample token , it runs a full forward pass over the entire prefix of length , reads only the last logit vector , appends , and on step feeds through all blocks all over again. Because causal attention is lower-triangular, representation at every layer depends only on tokens , so recomputing the keys and values at positions on step reproduces the exact same tensors computed on step . Across generated tokens, this redundant recomputation passes tokens through the weight matrices where would do.
Storing past keys and values in a key--value (KV) cache (Figure 11.3.1) eliminates this redundancy: at step , each layer projects only the single new token into , writes into slot of a pre-allocated buffer, and attends against the cached prefix .
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#
One decoding step at position . 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 at each block rather than queries or residual states ? Under causal masking, query () is used only when emitting token and is never referenced again. And caching the post-RoPE keys and values (each of shape ) means past tokens never need to be re-projected by or re-rotated by RoPE.
init_cache pre-allocates zeroed key and value buffers ks, vs of shape for each of the blocks. Figure 11.3.2 shows one such buffer in the middle of generation: the slots before position are filled, the current step writes slot , and the remaining slots are still zero and hidden by the mask.
The cache buffer of one block during the step at position (one sequence, one key--value head). Slots hold the keys and values of earlier steps. The step writes and into slot . The slots after are still zero and the mask hides them, so query attends to slots .
forward_cached(model, X, ks, vs, t) processes a slice X of 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, vsUsing forward_cached, generate_cached splits generation into two stages: (1) prefill, which processes the entire prompt of length 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 ) as running model(X) on the full sequence at once, for both pos='rope' and pos='learned':
gpt = d2l.GPTWe now instantiate a 3-block GPT under both rotary (pos='rope') and learned absolute (pos='learned') positional embeddings, prefill the first tokens of a -token sequence in one call, step through the remaining 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 (), comparing the wall-clock time of one uncached forward pass over tokens (time_forward, which naive decoding repeats at every step) against one cached decode step at context length (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 tokens, while time_decode(model, batch_size, n) averages the wall-clock latency of single-token cached decode steps starting at context length :
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 / 32Sweeping the context length across powers of two from to 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 and a cached step that is nearly flat (the new query is still scored against all 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 new tokens after a -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 blocks, batch size , sequence length , and key--value heads of width stored at bytes per number ( for FP32, for BF16/FP16, for FP8), each block stores two tensors ( and ) of shape . The total KV cache footprint is therefore
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 tokens confirms that the allocated cache buffers match (11.3.1) () and already exceed half the 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 ( tokens in parallel, compute-bound): Each weight matrix is read from HBM once and multiplied by token vectors ( FLOPs across weight bytes), giving an arithmetic intensity of —well above the GPU's ridge point, saturating the tensor cores.
- Single-stream decode ( token per step, memory-bandwidth bound): Each step performs only matrix--vector FLOPs while streaming all weight bytes plus cache bytes from HBM, giving an arithmetic intensity of (in FP32, or in BF16)—more than below the compute roof.
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 HBM bandwidth budget shows why single-stream decode sits near the memory-bandwidth ceiling while a -token prefill achieves more than 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 () spends its time streaming the model's weight bytes from HBM, decoding a batch of sequences simultaneously reuses each weight read across all tokens while reading distinct KV caches ( bytes). At memory bandwidth (bytes/s), the bandwidth-limited decode throughput (tokens/s) is
At small batch sizes (), throughput grows nearly linearly with ("free batching"); as or grows large (), KV cache reads dominate HBM traffic and throughput saturates at the KV-bandwidth ceiling :
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 , modern Transformer architectures compress the product along three orthogonal axes:
- Fewer key--value heads (): Grouped-query attention (GQA) (Ainslie et al., 2023) and multi-query attention (MQA) (Shazeer, 2019) share each key--value head across query heads (Figure 11.3.4).
- Narrower per-token representations (): 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).
- Shorter cached context (): Sliding-window attention evicts tokens older than a window , while keeping initial attention sink tokens (Xiao et al., 2024) so the softmax denominator remains stable (Section 11.3.3.3).
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 shrinks and cuts by a factor of . Moreover, Ainslie et al. (2023) showed that an existing multi-head checkpoint () can be converted into a GQA or MQA model by mean-pooling each group of key and value projection heads (pool_heads) and uptraining for a small fraction () of the original training budget.
We compare training our 6-block byte-level GPT () from scratch for 1,000 steps at (and at for only 50 steps) against converting the trained checkpoint down to , by mean-pooling and by keeping the first head of each group, both zero-shot (0 steps) and after 50 and 100 steps () 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 and evaluate pool_heads with both 'mean' and 'first' head pooling across , , and 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 (, a 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 , can we compress the -dimensional concatenated key--value vector of each token at layer into a rank- subspace ()? We test this directly on pretrained GPT-2 Small (124M, where and ) on a passage of 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 's attention to a callback attn_fn(q, k, v, i), and verify that standard causal attention matches gpt2(x) to within while establishing our baseline tail_loss on positions :
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 for each layer's concatenated key--value rows (fit_bases) and projecting the keys and values of the evaluated passage x onto the top 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 keys and values from one -dimensional input with one matrix and one bias, they lie in an affine subspace of only dimensions, the "of 768" in the output. Even post-hoc linear projection compresses GPT-2's KV vectors by ( out of ) with no measurable degradation (3.61 against 3.58 nats), while 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 compression.
11.3.3.3 Axis 3: Sliding Windows and Attention Sinks#
Our third axis bounds the sequence length stored in the cache to a rolling window of the most recent tokens (Section 10.6). However, if we apply a pure sliding window () to pretrained GPT-2 on a 1,024-token passage, cross-entropy on the tail tokens () jumps from nats to over nats.
To see why, sink_mass measures the average attention probability that queries at positions 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 , 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 (), removing token 0 from the softmax denominator forces that probability mass onto the remaining window tokens and scrambles the residual stream.
Keeping just initial sink tokens fixed at the front of the cache alongside the most recent tokens ( 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#
| Method | Factor reduced | Stored numbers per sequence | Needs training? |
|---|---|---|---|
| Shared KV heads (GQA, MQA) (Shazeer, 2019; Ainslie et al., 2023) | Heads | Yes: train from scratch or uptrain () | |
| Low-rank latent (MLA) (DeepSeek-AI et al., 2024) | Width | (plus a small rotary key) | Yes for MLA; a post-hoc SVD basis works to |
| Sliding window with sinks (Xiao et al., 2024) | Length | Works zero-shot on pretrained models when |
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 generated tokens from to token evaluations (and attention scoring from to ) while producing identical logits. On the hardware roofline (Figure 11.3.3), serving splits into compute-bound prefill ( prompt tokens processed in parallel at high arithmetic intensity) and memory-bandwidth-bound decode ( token per step at low arithmetic intensity). Batched decoding amortizes weight reads across concurrent sequences ((11.3.2)), scaling throughput linearly with until KV cache traffic dominates and throughput saturates at . To raise both capacity and large-batch throughput, modern architectures compress ((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#
-
Cache memory and batch limits of a 70B model. Llama 3.1 70B has layers, hidden size , query heads (), and key--value heads, stored in BF16 ( bytes).
- Use (11.3.1) to compute the KV cache size of a single sequence at full context length (), and compare it with what the cache would cost under standard MHA ().
- On an 8-GPU node with of total HBM (of which holds the BF16 model weights), what is the maximum batch size of -token sequences that can fit in the remaining under GQA () versus MHA ()?
-
Batched decode throughput and the KV-bandwidth ceiling. Serve the 70B model of 1 at context length on a system with aggregate HBM bandwidth and .
- Evaluate the bandwidth upper bound (11.3.2) at batch sizes for both GQA () and MHA ().
- At what batch size does each configuration reach half of its asymptotic ceiling ?
-
Prefix sharing across completions. Suppose sequences in a batch share a common system prompt of tokens and each has generated unique tokens. Modify the denominator of (11.3.2) when the shared prefix KV cache is stored and read once per step for all sequences, and compute the resulting throughput speedup at for the 70B GQA model.
-
INT8 / FP8 KV cache quantization. Store the cached keys and values of GPT-2 in
forward_blocksusing symmetric per-token 8-bit integer quantization: for each token vector , compute scale , quantize , and use in attention. Measure the change intail_lossonxwhen quantizing keys and values to 8 bits ( smaller than our FP32 cache, smaller than BF16) versus 4 bits (max / 7, / ). -
Attention sinks and a virtual sink logit (). 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 .
- Replace the softmax in
forward_blockswith (adding a non-token sink logit to the denominator without adding any value vector). - Evaluate the pure sliding window ( kept sink tokens) on GPT-2 with . How much of the loss spike does the virtual denominator logit eliminate?
- Replace the softmax in
-
Absorbing low-rank key--value reconstructions into and . Suppose layer compresses each token into a single latent vector (), from which head 's key and value are reconstructed via and ().
- Show that and .
- Explain why absorbing into and into during decoding avoids ever materializing the full keys or values in HBM, and explain why DeepSeek-V2/V3 applies RoPE to a separate narrow decoupled key rather than rotating .
-
Implementing a fixed-size streaming ring-buffer cache. Write a
StreamingCachevariant ofinit_cacheandforward_cachedthat pre-allocates only token slots per layer (retaining the first sink positions in slots and overwriting slots in a circular buffer for ), and verify that it generates 2,048 tokens using constant cache memory.gpt2has 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 ofgpt2the position of its cache slot, as Xiao et al. (2024) do.