Linear algebra for LLMsPart 8: Gradients through matrices
Gradients have shapes
5 min
One slope per parameter
The loss is one number. Nudge one entry and changes at some rate: that rate is entry of the gradient. So the gradient of a weight is another matrix.
Write
has the shape of : one slope per entry.
The gradient of a dot product
Each appears once, multiplied by , so its slope is . With , the gradient is : the weight paired with the biggest input matters most.
Write
.
And of a squared length
Each term has slope . This is weight decay’s pull: it shrinks every weight in proportion to its size.
Gradient descent
The gradient points uphill, so step the other way, scaled by the learning rate . With : before the step , after it .
Write
. Here : .
✏️ Your turn
One step
Write the gradient and after one step.
Work it out on paper, then go to the next card to check.
Answer
goes from 0 to : down, as it should.
In PyTorch
loss.backward()
w.grad.shape == w.shape # True: one slope per parameter
with torch.no_grad():
w -= lr * w.grad📌 Recap
Gradients have shapes in one card
- has ’s shape.
- ; .
- Descent: .
Write
The three lines above.