7/23
Part 2 of 6 · Shapes in a modelLearn and do
Layers
nn.Linear(12, 8) is a layer that turns 12 numbers into 8. Hand it a tensor of any shape, as long as the last axis is 12, and it transforms every token's row:
# 12 numbers in, 8 out
lin = nn.Linear(12, 8)
print(lin(x).shape)
torch.Size([2, 6, 8])
Only the last axis changed. The 2 sentences and their 6 tokens passed straight through.
Inside, a linear layer is one matrix multiply plus a bias. Here's the detail that trips people up in interviews: PyTorch stores the weight out by in, (8, 12), not (12, 8). So the formula needs a transpose:
print(lin.weight.shape, lin.bias.shape)
print(torch.allclose(lin(x), x @ lin.weight.T + lin.bias))
torch.Size([8, 12]) torch.Size([8])
True
torch.allclose checks that two tensors match, up to tiny rounding. They do: the layer is exactly x @ lin.weight.T + lin.bias.
In the editor, x is the same (2, 6, 12) tensor. Build lin, a layer from 12 numbers to 8. Then store lin(x) in out, and the shape of lin.weight in w_shape.