25/42
Part 4 of 6 · Shapes and the maskLearn

Keep it as a buffer: saved and moved, never trained

Where the mask lives matters too.

class Masked(nn.Module):
    def __init__(self, block_size=8):
        super().__init__()
        self.proj = nn.Linear(4, 4)
        ones = torch.ones(block_size, block_size, dtype=torch.bool)
        self.register_buffer("mask", torch.tril(ones))


m = Masked()
print(list(m.state_dict()))
print([name for name, _ in m.named_parameters()])
['mask', 'proj.weight', 'proj.bias']
['proj.weight', 'proj.bias']

The mask is saved with the model, but it isn't a parameter. A buffer is a tensor the module keeps and saves but never trains:

Predict

Keep the mask as a plain attribute, self.mask = torch.tril(...), instead. Is it saved in state_dict, and does it move with .to()?

Pick an answer above to see the rest