scores = torch.zeros(T, T)
att = scores.masked_fill(~mask[:T, :T], float("-inf"))
print(att)
print(att.softmax(dim=-1))
tensor([[0., -inf, -inf, -inf],
[0., 0., -inf, -inf],
[0., 0., 0., -inf],
[0., 0., 0., 0.]])
tensor([[1.0000, 0.0000, 0.0000, 0.0000],
[0.5000, 0.5000, 0.0000, 0.0000],
[0.3333, 0.3333, 0.3333, 0.0000],
[0.2500, 0.2500, 0.2500, 0.2500]])
The triangle is True where a key is allowed. masked_fill writes where its mask is True, so pass the flip, ~mask[:T, :T]. Pass the triangle itself and you hide the past and the diagonal, and leave the future open.
The mask goes on the scores, before the softmax. Minus infinity becomes a weight of exactly 0, and the weights left in each row still add up to 1.
One (T, T) mask serves every sequence and every head:
The mask lines up with the last two axes, and repeats over every sequence and head.