Linear algebra for LLMsPart 8: Gradients through matrices
Softmax and cross-entropy
6 min
The loss on one position
are the logits for one position, is the index of the token that actually came next (Part 6).
Its gradient is
Write out, differentiate, and the softmax comes back. The gradient on the logits is the predicted distribution minus the one-hot target.
Write
On numbers
The correct logit gets , so descent pushes it up. Every wrong logit gets , pushed down in proportion to how much probability it stole. The entries sum to 0.
✏️ Your turn
Gradient by hand
Write .
Work it out on paper, then go to the next card to check.
Answer
A confident correct prediction (0.7) gets a small push; a perfect one () would get none.
The softmax Jacobian
On its own, softmax mixes every input into every output: . Combined with cross-entropy, most of it cancels into , which is why frameworks fuse the two (F.cross_entropy takes logits, not probabilities).
In a transformer
Inside attention there’s no cross-entropy to cancel against, so the backward pass multiplies by for every row of attention weights.
Write
In PyTorch
# mean over all B·T positions
loss = F.cross_entropy(logits.view(-1, V), targets.view(-1))
# never pass logits.softmax(-1): it expects raw logits📌 Recap
Softmax and cross-entropy in one card
- , .
- : sums to 0.
- Softmax alone: , used inside attention.
Write