Sub topic 11
Context windows and the key-value cache
This chapter assumes you know causal self-attention (queries, keys, values, and the causal mask) and the decoding loop that produces one token at a time.
The context window
A model's context window is the maximum number of tokens it can process in one pass. The window holds the prompt and the text the model has generated so far. Anything outside it is invisible to the model.
Two limits cause the cutoff:
- Position handling. The model was trained on sequences up to a certain length, so positions beyond that length are unfamiliar.
- Cost. Attention compares every token with every earlier token, so compute grows roughly with the square of the sequence length.
When a conversation exceeds the window, the application must drop, truncate, or summarize older text. The model does not forget gradually. The dropped tokens are simply not in its input.
Why generation needs a cache
Generation is a loop. The model predicts one token, appends it, and predicts again. Naively, each step would rerun the whole sequence through every layer.
That is wasteful. In a causal model, the key and value vectors for an earlier token depend only on tokens at or before it. Once computed, they never change. So the model stores them. This store is the key-value cache (KV cache).
Generation therefore has two phases:
- Prefill. The model processes the whole prompt in parallel and fills the cache.
- Decode. For each new token, the model computes only that token's query, key, and value. It appends the key and value to the cache and attends over the cached keys and values.
Queries are never cached. Each query is used once, at its own position.
A runnable check
This code shows that cached, step-by-step attention gives the same result as recomputing everything. No mask is needed in the cached loop. At step t, the cache holds only positions up to t.
import numpy as np
def attend(q, K, V):
scores = K @ q / np.sqrt(len(q))
w = np.exp(scores - scores.max())
w /= w.sum()
return w @ V
rng = np.random.default_rng(0)
d = 8
x = rng.normal(size=(5, d))
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
# Recompute keys and values for the whole sequence, take the last position.
full = attend(x[-1] @ Wq, x @ Wk, x @ Wv)
# Process one token at a time, appending to a cache.
K_cache, V_cache = [], []
for t in range(len(x)):
K_cache.append(x[t] @ Wk)
V_cache.append(x[t] @ Wv)
out = attend(x[t] @ Wq, np.array(K_cache), np.array(V_cache))
print(np.allclose(out, full))The output is True.
What the cache costs
The cache trades memory for compute. Its size per token is:
2 × layers × KV heads × head dimension × bytes per value
The factor 2 covers keys and values. For a model with 32 layers, 8 KV heads, head dimension 128, and 16-bit values, that is 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or 128 KiB per token. An 8,000-token sequence needs about 1 GiB for the cache alone. This is per sequence, so serving many users at once multiplies it.
Common consequences:
- Long contexts are limited by GPU memory as well as by the model's trained length.
- Decoding is usually bound by memory bandwidth, because every step reads the whole cache.
- Techniques such as grouped-query attention reduce the number of KV heads, which shrinks the cache.
Common errors
- Assuming a larger window means better recall. Models can still use information in the middle of a long prompt poorly.
- Forgetting that the output counts toward the window. A prompt that fills the window leaves no room to generate.
- Assuming the model remembers earlier chats. Without text in the current context, it has no access to them.
Exercise
A model has 24 layers, 16 KV heads, head dimension 64, and stores values in 16 bits (2 bytes). How much KV cache does one 4,096-token sequence need?
Show answer
Per token: 2 × 24 × 16 × 64 × 2 = 98,304 bytes (96 KiB). For 4,096 tokens: 98,304 × 4,096 = 402,653,184 bytes, which is 384 MiB.