mask = torch.tril(torch.ones(8, 8, dtype=torch.bool))
T = 4
print(mask[:T, :T])
tensor([[ True, False, False, False],
[ True, True, False, False],
[ True, True, True, False],
[ True, True, True, True]])
The triangle is the same on every call. So build it once in __init__, at the longest length the model takes, and cut it in forward:
Built once in __init__, cut in forwardbuilt once: block_size × block_size (5, 8)
1000000011000000111000001111000011111000
cut in forward: mask[:4, :4] (4, 4)
1000110011101111
1 means True: this key is allowed. The first panel shows the first 5 of block_size rows.
Inputs are usually shorter than block_size: a short prompt, or the first steps of generation. self.mask[:T, :T] is the top-left corner you need.
The tests build the module with two arguments, so give block_size a default. The reference uses 1024.