The KV cache
Explain why keys and values of past tokens never change under causal masking, so they can be cached instead of recomputed at every step. Compute the cache size: 2·L·h·d_head·T·bytes per sequence, a key and a value per head, layer and token.
Builds on: Autoregressive generation loop
What the animation says
Redoing old work
Here's the generation loop. Each step runs the whole model on the full prefix. But only the last position's scores pick the next token. Every other row is thrown away. At step one thousand, you recompute nine hundred ninety-nine positions you already processed at step nine hundred ninety-nine. Is that work needed? It hinges on one thing: can a new token change what earlier positions computed? Predict: when a token is appended, do the keys at earlier positions change?
The past is frozen
They never change. Embeddings, norms and the MLP each act on one position alone. Attention at a position reads only that position and earlier ones. The mask blocks the future. So layer by layer, every row at a position depends only on tokens up to it. A later token can't reach back. That fixes its key and value rows, in every layer and every head, forever. And past queries? Only the newest position needs an output, so they're never used again. Tap the two kinds of rows worth storing.
One step with a cache
Now one step. The new token's normalized row enters a layer and a head. It makes just three new rows: a query, a key, and a value. The key and value join the cache, which now holds t rows. The query scores every cached key, divided by the square root of the head width. A softmax turns the scores into weights on the values. In code, this loop appends one key and one value per token. Its outputs match the full masked computation exactly. One question: does this step still need the causal mask?
Sizing the cache
No mask is needed. The price is memory. Let's size it for a model four thousand ninety-six wide. Thirty-two layers, thirty-two heads, head width one hundred twenty-eight, sixteen-bit numbers. Per token, each head stores one key and one value: two times one hundred twenty-eight numbers. Times thirty-two heads and thirty-two layers: two hundred sixty-two thousand numbers. At two bytes each, that's half a mebibyte. Over four thousand ninety-six tokens, that's two gibibytes for one sequence. Now serve a batch of eight such sequences. How much cache?
The trade
Sixteen gibibytes, on top of the model weights. Each sequence keeps its own cache. And it grows: every generated token adds another half mebibyte per sequence. So: under causal masking, keys and values never change. Cache them, and each step processes only the new token. The cost is two, times layers, times heads, times head width, times tokens, times bytes per number. Compute saved, memory spent.
The past is frozen by the causal mask
One generation step with a cache
Sizing the cache for a 4096-wide model
Cached attention equals full recompute
import numpy as np
rng = np.random.default_rng(0); d = 8
Wq, Wk, Wv = (rng.standard_normal((d, d)) for _ in range(3))
X = rng.standard_normal((5, d)) # 5 token rows
def attn(q, K, V): s = q @ K.T / np.sqrt(d); a = np.exp(s - s.max(-1, keepdims=True)); return (a / a.sum(-1, keepdims=True)) @ V
S = (X @ Wq) @ (X @ Wk).T / np.sqrt(d); S[np.triu_indices(5, 1)] = -np.inf
A = np.exp(S - S.max(-1, keepdims=True)); full = (A / A.sum(-1, keepdims=True)) @ (X @ Wv)
Kc, Vc, out = [], [], []
for x in X:
Kc.append(x @ Wk); Vc.append(x @ Wv); out.append(attn(x @ Wq, np.array(Kc), np.array(Vc)))
print(np.allclose(full, np.array(out))) # True
What to remember
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.
Bytewise
All courses