Linear algebra for LLMsPart 8: Gradients through matrices
A linear layer backwards
7 min
The setup
rows of input (tokens), features in, out. The backward pass hands this layer , the gradient of the loss with respect to its output. It must produce gradients for and for .
: only one product fits
The answer must be shaped like , and it can only be built from and . The only way to multiply them into is , summing over the rows: every token contributes.
Write
: same trick
Shaped like , built from and : . It’s the vector–Jacobian product of the last deck, one row per token. Shape matching is the fastest way to get these right, and to catch a missing transpose.
Write
On numbers
Check one entry by hand: multiplies into for each row , so its gradient is . That’s entry of .
The bias
The bias was broadcast to every row (Part 4), so its gradient adds up the rows of : here . Broadcasting forward means summing backward.
Write
Backward costs twice the forward
Each matrix product in the forward pass becomes two of the same size in the backward pass. So training costs about three forward passes: FLOPs per token (next deck but one).
✏️ Your turn
Shapes for a real layer
Write the shapes of and .
Work it out on paper, then go to the next card to check.
Answer
In nn.Linear's layout
# y = x @ W.T with W stored (out, in); g = dL/dy
grad_W = g.T @ x # (out, in), same as W
grad_x = g @ W # (n, in)The same rules, transposed to match how the weight is stored.
📌 Recap
A linear layer backwards in one card
- , .
- ; : match the shapes.
- Bias gradient: sum over rows.
- Backward = two matmuls per forward matmul.
Write