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)andxof 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,y2andy3side by side equal the full pass'sy. The problem comes in four levels:
- A pass with no cache: causal attention that returns the keys and values it computed.
- One token at a time after a prompt, with the cache growing on the time axis.
- Chunks of several new tokens with a cache, where the causal mask shifts.
CachedAttention(n_embd, n_head, n_kv_head): the cache keeps onlyn_kv_headkey/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.