11/26
Part 3 of 4 · The mask, and the cache you returnLearn and do
The scores have one row for each new token
With a cache, the score matrix changes shape.
# the keys of 4 tokens, after the cat
k = torch.randn(2, 4, 4, 8)
# the new token's query
q = torch.randn(2, 4, 1, 8)
print((q @ k.transpose(-2, -1)).shape)
torch.Size([2, 4, 1, 4])
full pass (4, 4)thecatsatonthe1000cat1100sat1110on1111
cached step for on (1, 4)thecatsatonon1111
Rows are queries, columns are keys, and 1 means the query may read the key.
The cached step computes only the last row of the full pass. That is where the saving comes from.
Order matters in the cat. Column j of the scores has to be position j, because the mask is built on that. Past first, then new.
Here is every shape in a cached step, with H heads of size d, cached tokens and new ones:
| Tensor | Shape | What it is |
|---|---|---|
x | (B, T_new, C) | the new tokens only |
q, k, v | (B, H, T_new, d) | after the split, view and transpose |
cache[0], cache[1] | (B, H, T_past, d) | keys and values of every earlier token |
k, v after the cat | (B, H, T_past + T_new, d) | past first, then new |
q @ k.transpose(-2, -1) | (B, H, T_new, T_past + T_new) | new queries scored against every key |
mask | (T_new, T_past + T_new) | broadcasts over B and H |
att @ v | (B, H, T_new, d) | one blended value per new token |
y | (B, T_new, C) | after transpose, reshape and proj |
In the editor, q and k hold one query and one key for each of the 4 tokens of the cat sat on. Set full, every query against every key, then step, the last query against every key, then same.