Linear algebra for LLMsPart 6: The rest of the transformer
Linear layers in code
5 min
What nn.Linear computes
nn.Linear(in, out) stores as and a bias of length . Input , output : any leading axes (batch, tokens) come along for free.
Write
A small one by hand
In 2, out 3. , plus the bias .
Each output is a dot product with a row of W
Row of the stored weight belongs to output feature . That’s why PyTorch stores : each row is one output’s “detector”, contiguous in memory.
Write
Count the parameters
Llama’s linear layers have no biases, so a projection is just its weight: almost 59 million numbers, one of three in each MLP.
✏️ Your turn
GPT-2's MLP input
How many parameters, bias included?
Work it out on paper, then go to the next card to check.
Answer
In code
lin = nn.Linear(4096, 14336, bias=False)
lin.weight.shape # torch.Size([14336, 4096])
y = lin(x) # x: (B, T, 4096) → y: (B, T, 14336)In a transformer
When you load a checkpoint, mlp.up_proj.weight with shape [14336, 4096] reads as (out, in): this layer maps 4,096 features to 14,336.
📌 Recap
Linear layers in one card
- , with stored .
- Output is .
- Parameters: (Llama: no bias).
Write