CodeRigor

LESSON

Causal attention with a key-value cache

Split the width into heads, mask each position to its past, and reuse stored keys and values so generating one token costs one new row.

A language model reads a prefix and predicts the next token, and attention is the step where each position gathers information from the positions before it. This lesson pairs with Let's build GPT: from scratch, in code, spelled out. by Andrej Karpathy, linked under Watch & read. That video covers self-attention, the triangular mask and multi-head attention in a small language model. You build the batched multi-head version, then a second entry point that reuses stored keys and values so generating a token does not redo the work for the whole prefix.

Start with the heads. A layer projects the input x of shape (B, T, D) into queries, keys and values with matrices Wq, Wk, Wv of shape (D, D), applied as x Wᵀ. Each head then works on its own slice of dh = D / n numbers per position, so the projected tensor is reshaped to (B, n, T, dh). One matrix product per projection serves all heads at once, and the scores for every head come from a single batched product.

Splitting the width into heads
start / 3
Two steps, in this order. The reshape exposes the head axis next to the width; the transpose moves it in front of time.
Splitting the width into heads
Two steps, in this order. The reshape exposes the head axis next to the width; the transpose moves it in front of time.

The order matters, and the shapes cannot warn you. Reshaping (B, T, D) straight to (B, n, T, dh) produces the right shape, but head 0 then holds the first T·dh numbers of the flat sequence instead of the first slice of every position.

Python
import numpy as np

x = np.arange(12).reshape(1, 3, 4)            # position t holds 4t .. 4t+3
right = x.reshape(1, 3, 2, 2).transpose(0, 2, 1, 3)
wrong = x.reshape(1, 2, 3, 2)
print(right[0, 0].tolist())
print(wrong[0, 0].tolist())

The first line is head 0 as it should be: the first two numbers of each of the three positions. The second glues pieces of different positions together. Joining heads back is the same two steps reversed: transpose first, then reshape to (B, T, D).

Now the mask. For a query at position i, the score against key j is q·k divided by √dh, where dh is the size of one head. The scores for j > i are set to minus infinity before the softmax, so those keys receive weight exactly 0 and the remaining weights still sum to 1. Setting them to 0 instead leaves a finite score that still takes weight. The weights then average the values, the heads are joined and Wo, of shape (D, D), mixes them.

Generation brings a second use. Producing the next token needs that token's query, but its keys and values are scored against every earlier position's keys and values, and those never change once computed. Keep them. This is the cache: per layer, the keys and values of every earlier position, shaped (B, n, P, dh) for P positions. A call receives the new rows, projects only those, appends the new keys and values to the cache along the time axis and returns the longer cache with the output. Old queries are never needed again, so they are not stored.

Python
steps = 8
no_cache = sum(range(1, steps + 1))           # every step re-projects the whole prefix
with_cache = steps                            # every step projects one new row
print(no_cache, with_cache)
print(2 * 1000 * 64)                          # numbers stored per layer: 1000 positions, D = 64

The saving is in the projections: 36 rows instead of 8 over eight steps, and the gap grows quadratically with length. The scores of each new query still touch all stored keys, and the cache takes memory proportional to the length, here 128000 numbers per layer for 1000 positions.

The mask is where a cache is easy to get wrong. Take 3 cached positions and 2 new ones. The score table has 2 rows and 5 columns, and the first new query sits at position 3, not 0.

The mask with three cached positions and two new ones
Rows are the queries of positions 0 to 4, columns the keys. The last two rows are the new tokens; a 1 means the key is visible. The pale cells were computed in earlier calls, and only the dark ones are computed now.
The mask with three cached positions and two new ones
Rows are the queries of positions 0 to 4, columns the keys. The last two rows are the new tokens; a 1 means the key is visible. The pale cells were computed in earlier calls, and only the dark ones are computed now.

Only the last two rows are computed. Seen as a table with Tq rows and Tk columns, the allowed region is the lower triangle shifted right by Tk - Tq. With no cache the shift is 0, which is why a mask that ignores the cache passes every test that feeds a whole sequence.

Python
import numpy as np

past, new = 3, 2
allowed = np.tril(np.ones((new, past + new), dtype=int), k=past)
print(allowed.tolist())
print(np.tril(np.ones((new, past + new), dtype=int)).tolist())

Two mistakes are worth naming. One is the reshape that skips the transpose. The other is the unshifted mask, which is correct whenever the cache is empty and wrong otherwise.

The tests check the work in three ways. Your function with no cache is compared with PyTorch's own causal attention. The same input fed in many chunk sizes, one token at a time included, must equal the full result, which shows the cache changes cost and not values. Finally, a test changes later positions and checks that earlier outputs do not move. What none of this shows is that the layer is useful: it confirms the arithmetic is the standard one, not that a model built from it will learn anything.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

A language model built from a bigram baseline up to self-attention, multiple heads and a transformer block. The self-attention, masking and multi-head chapters are the ones this lesson builds on; the cache is this lesson's own addition.