8/23
Part 2 of 6 · Shapes in a modelLearn and do

Models

A model is a class with two methods:

class Proj(nn.Module):
    def __init__(self, C: int) -> None:
        super().__init__()
        self.qkv = nn.Linear(C, 3 * C)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """x: (B, T, C). Returns (B, T, 3C): queries, keys, values."""
        return self.qkv(x)


m = Proj(12)
print(m(x).shape)
torch.Size([2, 6, 36])
  • __init__ builds the layers, and it starts with super().__init__().
  • forward does the math.
  • You call the model itself, m(x), and that runs forward.

Any layer you store on self becomes part of the model, so its weights get trained and saved along with it.

But what about a tensor that should never train, like the triangle that hides later tokens? Say you store it as a plain attribute, self.mask = mask, and then call model.to("cuda"). The weights move to the GPU. The mask stays behind on the CPU, and the first forward pass fails because its tensors live in two places. The fix is self.register_buffer("mask", mask). A buffer moves and saves with the model, and it never trains. If that name escapes you in an interview, build the mask inside forward and say you'd build it once. That's a fine answer.

In the editor, write a second model the same way: MLP(C), the feed-forward part of a transformer block. It widens each position to 4 * C numbers, bends them with F.gelu, and narrows them back to C. F is torch.nn.functional, already imported in the editor, and F.gelu is the bend: it lets positive numbers through and pushes negative ones toward 0, so the two layers don't collapse into one.