15/23
Part 5 of 6 · Hide the futureLearn and do
A triangle averages the past
A language model predicts each token from the tokens before it. So when sat looks around, it must not see on, the and mat. Attention does that with a mask.
Start with the shape of the idea: a lower triangle of ones, each row divided by its own sum.
X = torch.tensor([[[1., 2.], [3., 4.], [5., 6.]]])
tril = torch.tril(torch.ones(3, 3))
wei = tril / tril.sum(dim=1, keepdim=True)
print(wei)
print(wei @ X)
tensor([[1.0000, 0.0000, 0.0000],
[0.5000, 0.5000, 0.0000],
[0.3333, 0.3333, 0.3333]])
tensor([[[1., 2.],
[2., 3.],
[3., 4.]]])
wei (3, 3)thecatsatthe100cat1/21/20sat1/31/31/3
Each row is the average of the token itself and every token before it. Above the diagonal everything is 0, so no token reads the future. Row 2 of the result is the average of [1, 2], [3, 4] and [5, 6], which is [3, 4].
The same triangle averages any rows in order, not only tokens. In the editor, X holds Ana's scores on four tests, in the order she took them, one row per test. Build tril, then wei, then avg, so that row t of avg is her average over tests 0 to t.