2/26
Part 1 of 4 · Why a cache helpsLearn

Fed in pieces, the sequence must give what one full pass gives

The problem's own example feeds five tokens whole, then as a prompt of three and two single tokens:

Call, with attn = CachedAttention(16, 2) and x of shape (1, 5, 16)yKeys in the cache
y, cache = attn(x)(1, 5, 16)(1, 2, 5, 8)
y1, cache = attn(x[:, :3])(1, 3, 16)(1, 2, 3, 8)
y2, cache = attn(x[:, 3:4], cache)(1, 1, 16)(1, 2, 4, 8)
y3, cache = attn(x[:, 4:5], cache)(1, 1, 16)(1, 2, 5, 8)

y1, y2 and y3 side by side equal the full pass's y. The problem comes in four levels:

  1. A pass with no cache: causal attention that returns the keys and values it computed.
  2. One token at a time after a prompt, with the cache growing on the time axis.
  3. Chunks of several new tokens with a cache, where the causal mask shifts.
  4. CachedAttention(n_embd, n_head, n_kv_head): the cache keeps only n_kv_head key/value heads, each shared by a group of query heads.

Watch the third number in the last column. That's the time axis, and it grows by one token with each cached call, from 3 to 5.