All courses

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

▶ Watch this lesson Start the whole course

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.

Why redo work you already did?

In the generation loop, each step reruns the whole model on the full prefix, yet only the last position's logits are used. At step 1000 you recompute 999 positions you already processed at step 999. Is any of that repeated work necessary? If not, what exactly can you store and reuse, and how much memory does storing it take?

The past is frozen by the causal mask

Embeddings, norms and the MLP act on each position alone. Attention at position $s$ reads only positions $\le s$. So, layer by layer, every hidden row at position $s$ depends only on $x_{\le s}$. Tokens appended later cannot change it, so its key and value rows in every layer and head are fixed forever. Past queries are never needed again, because only the newest position needs an output. So you keep $K$ and $V$ and compute just one new row per layer.

One generation step with a cache

At step $t$, in each layer and head, let $u_t$ be the new token's normalized input row. Compute $q_t=u_tW_Q$, $k_t=u_tW_K$, $v_t=u_tW_V$. Append $k_t, v_t$ to the cached $K, V$, which now have $t$ rows. The output is $\text{softmax}(q_tK^\top/\sqrt{d_{\text{head}}})\,V$. No mask is needed, because nothing lies in the future. Cache size per sequence: $$2\cdot L\cdot h\cdot d_{\text{head}}\cdot T\cdot\text{bytes}$$ The 2 counts one key plus one value. With the usual $h\,d_{\text{head}}=d$, this is $2LdT\cdot$bytes.

Sizing the cache for a 4096-wide model

Take $L=32$, $h=32$, $d_{\text{head}}=128$ ($d=4096$), 16-bit numbers (2 bytes each) and $T=4096$. Per token: $2\cdot32\cdot32\cdot128=262{,}144$ numbers $\times2$ B $=524{,}288$ B $=0.5$ MiB. Per sequence: $0.5$ MiB $\times4096=2$ GiB. A batch of $B=8$ sequences needs 16 GiB, on top of the weights. Each sequence's cache grows by 0.5 MiB for every generated token.

Cached attention equals full recompute

This is one attention head, with head width $d_{\text{head}}=d=8$. Feeding tokens one at a time with a growing cache of $K$, $V$ rows gives exactly the outputs of the full masked computation.
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

Under causal masking, a position's hidden rows depend only on itself and earlier tokens. So its keys and values never change, and you cache them instead of recomputing them. Each step then processes only the new token. The cost is memory: $2\cdot L\cdot h\cdot d_{\text{head}}\cdot T\cdot$bytes per sequence, which grows with every token generated.

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.