Linear algebra for LLMsPart 8: Gradients through matrices
The chain rule as matrix products
6 min
The Jacobian
For a function from vectors to vectors, the derivative is a matrix: row holds the slopes of output with respect to every input. Shape , outputs by inputs.
Write
A linear map is its own Jacobian
, so . The best linear approximation of a linear map is the map itself.
Composing functions multiplies Jacobians
The chain rule for vectors is a matrix product, in the same right-to-left order as composing maps (Part 3). A network is a long composition, so its derivative is a long product of Jacobians.
Write
Elementwise functions have diagonal Jacobians
Output depends only on input , so the Jacobian is diagonal, and multiplying by it is just (Part 2). Code never builds it.
Backprop: start from the loss
The loss is a scalar, so is a single row. Multiplying from the left keeps a row vector at every step: a vector–Jacobian product, cheap. Multiplying the Jacobians together first would build big matrices for nothing. That’s why gradients flow backward, from the loss to the input.
Write
✏️ Your turn
One backward step
Write .
Work it out on paper, then go to the next card to check.
Answer
The upstream row times the Jacobian . In column layout the same thing is written .
In PyTorch
torch.autograd.functional.jacobian(f, x) # the full J, for small checks
torch.autograd.grad(L, x) # what backward computes: a VJPIn a transformer
Autograd stores what each operation needs for its vector–Jacobian product during the forward pass (the activations), then runs the products in reverse. That stored data is why training uses far more memory than inference.
📌 Recap
The chain rule in one card
- Jacobian: ; for , .
- Composition multiplies Jacobians; elementwise functions give diagonals ().
- Backprop multiplies a row vector by Jacobians, from the loss backward.
Write