Sub topic 11
Context Windows and the Key-Value Cache
This chapter covers two linked ideas: the context window, which limits how much text a model can read at once, and the key-value (KV) cache, which makes generation fast enough to be practical. It assumes you have read the chapters on self-attention and decoding. You should be comfortable with the query, key, and value matrices and with the loop that generates one token at a time.
What the context window is
The context window is the maximum number of tokens the model can process in a single sequence. It counts everything: the system prompt, the conversation history, any documents you paste in, and the tokens the model generates in reply. If the window is 8,192 tokens, a 7,000-token prompt leaves room for at most 1,192 generated tokens.
The limit comes from several places:
- Positional information. The model was trained on sequences up to some length. Positions beyond that length were never seen in training, so behavior there is unreliable.
- Attention cost. Each token attends to every earlier token, so the score matrix grows with the square of the sequence length.
- Memory. The KV cache, described below, grows linearly with sequence length and can dominate GPU memory.
Tokens, not words or characters, are the unit. A rough rule for English text is that one token is about three-quarters of a word, but the ratio varies by language and content. Code and non-English text often use more tokens per word.
Why generation repeats work
Recall the generation loop. To produce each new token, the model runs a forward pass over the sequence and reads the logits at the last position. Then it appends the sampled token and repeats.
A naive implementation recomputes everything on each step. At step t it processes all t tokens again, even though the first t − 1 tokens have not changed. Because of the causal mask, those earlier positions never depend on later ones. Their hidden states, and therefore their keys and values, are identical to what was computed on the previous step.
Total work for generating n tokens this way grows roughly with the square of n in the projection layers alone, and worse once attention is included. Most of that work is repeated.
What the KV cache stores
In self-attention, each position produces a query, a key, and a value. For the new token, the query is compared with the keys of all earlier positions, and the resulting weights mix their values. Notice the asymmetry:
- The query is needed only for the position being computed right now.
- The keys and values of earlier positions are needed again at every later step.
So the model saves each layer's keys and values for every position it has processed. That store is the KV cache. On each new step the model computes the query, key, and value for the single new token only, appends the new key and value to the cache, and attends over the whole cache.
The cache gives the same output as recomputing from scratch. It is purely an optimization, not an approximation.
Prefill and decode
Generation with a cache has two phases with different performance profiles.
| Phase | What happens | Typical bottleneck |
|---|---|---|
| Prefill | The whole prompt is processed in parallel and the cache is filled | Compute: large matrix multiplications keep the GPU busy |
| Decode | One token per step, reading the whole cache | Memory bandwidth: each step loads all weights and the cache but does little arithmetic |
This explains a common observation. A service may take a noticeable time before the first token appears (time to first token, set mostly by prefill and prompt length), and then stream tokens at a steady rate (set mostly by decode).
A minimal implementation
The code below extends the causal attention from the self-attention chapter to work one token at a time with a cache. It checks that the cached result matches the full computation.
import numpy as np
def softmax(s):
s = s - s.max(axis=-1, keepdims=True)
e = np.exp(s)
return e / e.sum(axis=-1, keepdims=True)
def full_attention(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
scores = q @ k.T / np.sqrt(k.shape[-1])
mask = np.triu(np.ones_like(scores), k=1).astype(bool)
scores = np.where(mask, -np.inf, scores)
return softmax(scores) @ v
class CachedAttention:
def __init__(self, Wq, Wk, Wv):
self.Wq, self.Wk, self.Wv = Wq, Wk, Wv
self.keys = np.empty((0, Wk.shape[1]))
self.values = np.empty((0, Wv.shape[1]))
def step(self, x_new):
# x_new: (d_model,) embedding of the newest token only
q = x_new @ self.Wq
self.keys = np.vstack([self.keys, x_new @ self.Wk])
self.values = np.vstack([self.values, x_new @ self.Wv])
scores = self.keys @ q / np.sqrt(self.keys.shape[-1])
return softmax(scores) @ self.values
rng = np.random.default_rng(0)
x = rng.normal(size=(5, 8))
Wq, Wk, Wv = (rng.normal(size=(8, 8)) for _ in range(3))
expected = full_attention(x, Wq, Wk, Wv)
cache = CachedAttention(Wq, Wk, Wv)
got = np.stack([cache.step(row) for row in x])
print(np.allclose(expected, got))
print(cache.keys.shape)Both lines of output confirm the point: the first prints True, and the second prints (5, 8), one key per processed token. No mask is needed in the cached version because the cache holds only earlier and current positions.
How big the cache gets
For each token, each layer stores one key vector and one value vector per attention head (or per key-value head, see below). The size in bytes is:
2 × layers × kvheads × headdim × bytespervalue × tokens
The leading 2 accounts for keys plus values. Consider a model with 32 layers, 32 heads of dimension 128, and 16-bit values (2 bytes):
- Per token: 2 × 32 × 32 × 128 × 2 = 524,288 bytes, or 0.5 MiB.
- For 8,192 tokens: about 4 GiB.
- For a single 100,000-token sequence: nearly 50 GiB.
This is per sequence. A server handling many users at once must hold a cache for each one, so cache memory often limits how many requests fit on a GPU, not the model weights.
Techniques that reduce cache cost
Several design choices shrink the cache or its effects:
- Multi-query and grouped-query attention. Many query heads share a smaller number of key-value heads. With 32 query heads sharing 8 key-value heads, the cache is four times smaller. Quality loss is usually small.
- Cache quantization. Storing keys and values in 8-bit or 4-bit formats instead of 16-bit reduces memory at some accuracy cost.
- Paged allocation. Instead of reserving one large contiguous block per sequence, the server allocates the cache in small fixed-size blocks. This avoids wasted space from sequences of unpredictable length.
- Prefix caching. If many requests start with the same tokens, such as a long system prompt, the server can reuse the cached keys and values for that shared prefix and skip its prefill. This works only when the prefix is identical token for token.
- Sliding-window attention. Some layers attend only to the most recent w tokens, so older entries can be dropped.
What happens at the limit
When a conversation approaches the window size, something has to give. Common strategies, each with trade-offs:
- Reject or truncate. The API returns an error, or the oldest tokens are dropped. Dropping from the front can remove the system prompt, which changes behavior, so well-built applications keep the instructions and trim the middle of the history.
- Summarize. Older turns are replaced by a model-written summary. This saves space but loses detail, and errors in the summary persist.
- Retrieve. Instead of placing every document in the prompt, the application searches for relevant passages and inserts only those.
Note that you cannot simply continue generating past the window by discarding the cache. Removing early keys and values changes what later tokens attend to, and position information then no longer matches what the model saw in training. Methods that extend the usable window, such as rescaling positions or fine-tuning on longer sequences, change the model or its positional scheme and are done before deployment.
Common errors
- Assuming the cache changes outputs. It does not. With the same sampling seed, cached and uncached generation produce the same tokens, apart from tiny floating-point differences.
- Forgetting that output tokens count. The window covers prompt plus completion. Requesting a long completion from a nearly full prompt fails or gets cut short.
- Treating the window as memory. The model has no memory between requests. Each request sends the whole conversation again, and the cache is an in-request, server-side optimization.
- Cache-unfriendly prompts. Putting changing content such as a timestamp at the start of a prompt prevents prefix reuse. Place stable text first and variable text last.
Exercise
A model has 24 layers, 16 key-value heads, head dimension 64, and stores the cache in 16-bit values (2 bytes). How many bytes does the KV cache use per token, and how large is it for a 4,096-token sequence? Give the second answer in MiB (1 MiB = 1,048,576 bytes).
Show answer
Per token: 2 × 24 × 16 × 64 × 2 = 98,304 bytes. For 4,096 tokens: 98,304 × 4,096 = 402,653,184 bytes, which is 384 MiB.
Exercise
In the CachedAttention class, why does the step method need no causal mask, even though the full version does?
Show answer
The cache contains only keys and values for the current and earlier tokens. Future positions are not in the cache yet, so the new query cannot attend to them. The mask in the full version exists to hide future positions that are present in the matrix.
Exercise
A chat application puts the current time at the top of its system prompt, followed by 2,000 tokens of fixed instructions. The server supports prefix caching, but cache hits are rare. Why, and what is the fix?
Show answer
Prefix reuse requires the leading tokens to match exactly. The timestamp changes on every request, so the prefix differs from the first tokens onward and the cached entries for the instructions cannot be reused. Move the fixed instructions to the start and put the timestamp after them (or at the end of the prompt).