Old tokens never change, because of the causal mask
Why is it safe to keep old results? Because of the causal mask.
import mathimport torchdef attend(x: torch.Tensor, causal: bool = True) -> torch.Tensor: """x: (T, d), each token's query, key and value. Returns (T, d).""" T = x.size(0) att = x @ x.T / math.sqrt(x.size(1)) if causal: mask = torch.ones(T, T, dtype=torch.bool).tril() att = att.masked_fill(~mask, float("-inf")) return att.softmax(dim=-1) @ xtorch.manual_seed(0)# 5 tokens, 4 numbers eachx = torch.randn(5, 4)print(torch.allclose(attend(x[:4]), attend(x)[:4]))print(torch.allclose(attend(x[:4], causal=False), attend(x, causal=False)[:4]))
Predict
Run attend on the first 4 tokens, then on all 5, and compare the first 4 outputs. What do the two lines print, with the mask and without it?
Pick one to see what it prints.
To keep it short, attend uses each token's vector as its query, its key and its value. Here is the mask for the cat sat on the. Rows are queries and columns are keys. Tap the last column: every row above the new the has False there.
A new token changes nothing before itInteractive
rows: the query, columns: the key it looks at
thecatsatonthethecatsatonthe
allowed = torch.tril(torch.ones(T, T, dtype=torch.bool)): True on and below the diagonal, where a query may look.cat (query 1) looking at sat (key 2): a later word, so it must be hidden.
That holds in every layer. An old position's output is the next layer's input at that position, so the next layer's old keys and values come out the same too. That is why you can keep them. An encoder, which attends both ways, can't cache like this.
In the editor, attend is the function from above and x the same 5 tokens. Run two layers in a row, attend(attend(...)): set old for the first 4 tokens alone, then same and same_both_ways.
Pick an answer above to see the rest
Instructions
1
Set old: the outputs of two layers, attend(attend(...)), for the first 4 tokens alone.
2
Set same: True if old matches the first 4 outputs when all 5 tokens go through both layers.
3
Set same_both_ways the same way, with causal=False in both layers.