A KV cache for decoding one token at a time
A KV cache keeps the keys and values that attention already computed for earlier tokens, so a model that writes text one token at a time doesn't compute them again. Candidates report it two ways: as the follow-up in an ML debugging round, after they fixed a small GPT, and as a question in a technical screen, What is a KV cache?
This lesson first shows why a cache saves work and why the saved keys and values never go stale. Then it builds the cached step one piece at a time, each with a small task: where the new keys go, the shapes, the shifted mask and the cache you return. It ends on what the cache costs in memory and how serving systems shrink it. The whole problem comes back at the end, as the lesson's practice, from a blank file. It reads:
Write
CachedAttention(n_embd, n_head), causal multi-head self-attention that can take a sequence in pieces.self.qkv = nn.Linear(C, 3 * C)makes the queries, keys and values, the heads are(B, n_head, T, C // n_head), andself.projis the output layer.
forward(x, cache=None)returns(y, cache).
xis(B, T_new, C): the new tokens only.cacheisNoneor a pair(k, v), each(B, n_head, T_past, head_dim): the keys and values of every earlier token.- The new tokens sit at positions
T_pasttoT_past + T_new - 1. They attend to every past token, and causally to each other.- Return
y,(B, T_new, C), and the cache grown toT_past + T_newtokens.Feeding a sequence in pieces must give exactly what one full pass gives.