14/26
Part 3 of 4 · The mask, and the cache you returnLearn and do
A worked example: three tokens, one at a time
Here is the whole cached step, worked by hand on three tokens.
q = torch.tensor([[1, 0], [0, 1], [1, 1]], dtype=torch.float64)
k = torch.tensor([[1, 0], [1, 1], [0, 1]], dtype=torch.float64)
v = torch.tensor([[10, 0], [0, 10], [10, 10]], dtype=torch.float64)
# one token per step
for t in range(3):
# the cache after the append
keys, values = k[:t + 1], v[:t + 1]
w = (q[t] @ keys.T / math.sqrt(2)).softmax(dim=-1)
print(w.round(decimals=2).tolist(), (w @ values).round(decimals=1).tolist())
[1.0] [10.0, 0.0]
[0.33, 0.67] [3.3, 6.7]
[0.25, 0.5, 0.25] [5.0, 7.5]
Each step adds one key and one value, then scores one new query against everything stored. Now run all three tokens through one causal pass, with no cache:
mask = torch.ones(3, 3, dtype=torch.bool).tril()
w = (q @ k.T / math.sqrt(2)).masked_fill(~mask, float("-inf")).softmax(dim=-1)
print((w @ v).round(decimals=1).tolist())
One causal pass over all three tokens, no cache. What comes out?
Pick one to see what it prints.
Pick an answer above to see the rest