Lesson 4 of 189 min
Backpropagation
The network keeps every value on the way forward; one pass back from the loss multiplies the rates along each path and adds where paths meet, giving every weight its slope.
After this lesson you can trace how the error reaches every weight through a computational graph, and say what loss.backward() does.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
The rate at each box
Multiply uses the other input. Square uses twice the input. Add sends 1 to both inputs and subtract sends 1 and −1. ReLU gives 1 above zero and 0 below. PyTorch uses 0 at zero. The mean of two sends half to each.
import torch
x, y = (torch.tensor(v, requires_grad=True) for v in (2., 3.))
boxes = [x * y, x**2, x + y, x - y, x.relu(), (-x).relu(),
(x * 0).relu(), torch.stack([x, y]).mean()]
for box in boxes:
rates = torch.autograd.grad(box, (x, y), allow_unused=True)
print(tuple(None if r is None else r.item() for r in rates))(3.0, 2.0) (4.0, None) (1.0, 1.0) (1.0, -1.0) (1.0, None)
The final rows show ReLU below and at zero, then the mean. None marks an unused input.
Run backward on the same graph
PyTorch usually releases the values it saved for backward after using them. A second call on this same square will fail. Pass retain_graph=True on the first call when you need the same graph twice. In a training loop, the next forward pass normally makes a fresh graph. PyTorch’s backward reference
x = torch.tensor(2., requires_grad=True)
loss = x.square()
loss.backward()
try:
loss.backward()
except RuntimeError as error:
print(str(error).split(".")[0])Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed)
x.grad = None
loss = x.square()
loss.backward(retain_graph=True)
loss.backward()
print(x.grad.item())8.0
Add gradients on purpose
Run backward on each small batch, then take one optimizer step. If the batches have the same size and each loss is a mean, divide each loss by the number of batches. This gives the same gradient as one mean over all the examples. Nanochat’s training loop
weight = torch.tensor(2., requires_grad=True)
optimizer = torch.optim.SGD([weight], lr=0.1)
optimizer.zero_grad()
for target in (1., 5.):
loss = (weight - target).square() / 2
loss.backward()
print(round(weight.grad.item(), 2))
optimizer.step()
print(round(weight.item(), 2))-2.0 2.2
Follow one weight forward
Forward mode takes one input direction through the calculation and tells you how the outputs move. Here, (1, 0) changes only the first weight. Reverse mode starts from the single loss and gives both slopes in one pass. That’s the useful shape for training, where there’s one loss and many weights. PyTorch’s guide to the two modes
def loss(weights):
w1, w2 = weights
return (w1 * w2 - 1).square()
weights = torch.tensor([2., 3.])
_, slope_w1 = torch.func.jvp(loss, (weights,), (torch.tensor([1., 0.]),))
print(slope_w1.item())
print(torch.func.jacrev(loss)(weights).tolist())30.0 [30.0, 20.0]
Read a small backward engine
In Andrej Karpathy’s micrograd, each Value holds one number. Read Value.__mul__ to see a rate applied, then Value.backward to see the graph visited in reverse. Install it with pip install micrograd to try the same multiply and square.
from micrograd.engine import Value
w1, w2 = Value(2.), Value(3.)
loss = (w1 * w2 - 1)**2
loss.backward()
print(loss.data, w1.grad, w2.grad)25.0 30.0 20.0
Run on Python 3.13.3, PyTorch 2.15.0 and micrograd 0.1.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The chain rule
Every training script calls loss.backward(). What does it do?
2 of 3
The digits network has 2,410 weights. Nudging each weight in turn takes one more forward pass for every weight. About how much work does loss.backward() take to find every slope, forward and back together?
3 of 3
A box works out guess = h * w2 + 4.2. The forward pass kept h = 3, and w2 is 0.5. On the way back, a slope of 2 reaches the guess. What slope does w2 get?
The ideas in this lesson
- Computational graph
- The network's work drawn as boxes, each value with an arrow to every box that uses it; the forward pass keeps every value.
- Backpropagation
- One pass back from the loss gives every weight its slope: multiply along each path, add where paths meet.
- Automatic differentiation
- PyTorch writes each box down as the forward pass runs; `backward()` walks that record and adds each slope into `.grad`.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Backpropagation
Here's a question. Every training script has one line: loss dot backward. It tells every weight which way to move, and how much. A big network has millions of weights. And this one line works them all out, fast. So what does loss dot backward actually do?
The answer, and the slow way
Here's the answer in one line. Loss dot backward starts at the loss, and goes back through the network once. On the way, it hands every weight its slope. If you guessed it nudges each weight in turn, that would work too.
Nudge one weight a little, and watch how far the loss moves: that's its slope. But it's one run of the network for every weight. Almost twenty-five hundred runs, for a small network that reads digits.
Over a hundred million, for GPT-2.
So how does one pass back do it?
The forward pass
Here's a small network that guesses a penguin's mass from its flipper. It multiplies the flipper by a weight, w1. Then comes a ReLU. Then it multiplies by a second weight, w2, and adds four point two, the penguins' average mass.
One penguin: its flipper is twenty-two centimeters, two more than twenty. It weighs four point seven kilos. Its total, the flipper times w1, is two times one: two.
ReLU keeps it, since it's above zero. Call it h: two. Times zero point five, plus four point two: the guess is five point two.
The miss, the guess minus the real mass, is zero point five. Squared, that's the loss: zero point two five.
That run, from the flipper to the loss, is the forward pass.
And it keeps every value it made.
A graph
In a chain, like the chain rule's, each box feeds only the next one. Here, w1 joins at the first box, and w2 joins at the guess. Two arrows go into that box.
Draw each value as a box, with an arrow to every box that uses it, and the work is a graph. It's called the computational graph.
Back to w2
A network's work is kept as a graph of boxes. So how does the error get back to w2?
Start at the loss, with a slope of one. Go back one box at a time, and multiply by each box's rate, as the chain rule does. The square's rate is twice the miss: one. The miss moves with the guess: one. At the guess, w2 was multiplied by h. So on the way back, what does w2's slope get multiplied by?
By h. Two.
Nudge w2, and the guess moves twice as much, because w2 was multiplied by h. And h is a value the forward pass kept.
So w2's slope is two.
On to w1
And w1, further back? The slope at the guess, one, goes on to h. Its rate there is w2, zero point five, since h was multiplied by w2.
Then ReLU. Its rate is one, because its total was above zero. Below zero, its rate would be zero, and the slope would stop there.
Last, w1. It was multiplied by the flipper, so its rate is the flipper: two. So w1's slope is one. Check it with a nudge: move w1 up a hundredth, and the loss moves about a hundredth.
A weight used twice
What if a weight is used twice?
Take a batch of two penguins. The second one has a flipper of twenty-one centimeters, one more than twenty. It weighs four point two kilos.
It goes through the same two weights. Its guess is four point seven, and its miss is zero point five, like the first penguin's. So now each weight has two arrows going out, one to each penguin. The batch's loss is the average of the two penguins' losses: still zero point two five.
Slopes add where paths meet
Now go back from the batch's loss. The average halves what reaches each penguin, so each path starts at a half.
The first penguin's path brings w2 a slope of one. The second penguin's path brings it zero point five.
Where paths meet... the slopes add.
So w2's slope is one point five.
And w1 gets zero point five plus zero point two five: zero point seven five. In a real network, every weight is used by every example in the batch.
Each box once
So why is one pass back enough?
Each box's slope is worked out once, and every box further back uses that number.
Look at the digits network. Each of its thirty-two neurons in between gets ten slopes, one from each score. It adds them up once. Then all sixty-four weights coming into it use that one number. Forward and back together take about as long as three forward passes. Nudging every weight in turn takes over seven hundred times as long. And for GPT-2, on this computer, it's a tenth of a second... compared to about fifty-four days.
That's backpropagation. One pass back from the loss gives every weight its slope.
PyTorch writes the graph down
Backpropagation needs the graph of every box, kept from the forward pass. So who draws it? You never did.
In PyTorch, you create the two weights as tensors, and turn on one setting. It tells PyTorch to track them. Then come the two penguins, the guess and the loss. As each line runs, PyTorch writes its box down. Print the loss: zero point two five. And beside it, MeanBackward. That's the last box it wrote: the average.
loss.backward() and .grad
Now call loss dot backward. It walks that record back from the loss, and puts each weight's slope in its dot grad. PyTorch works out the slopes by itself, from its record. That's called automatic differentiation. What will w2 dot grad print?
One point five, the same as we got by hand. And w1 dot grad, zero point seven five.
Backward only finds the slopes. It's the optimizer's step that moves the weights.
.grad adds up
Now run it all again, like a training loop does: the guess, the loss, then backward. And now, w2 dot grad is three. What went wrong?
Backward adds each slope into dot grad. It's the same rule as where paths meet. To PyTorch, a second call looks just like a second path. So every training step clears the slopes first, with the optimizer's zero grad.
In code: the digits network
The same line on the digits network. One call of loss dot backward fills in a slope for every one of its weights. That's almost twenty-five hundred slopes. They come in four tensors, shaped like the weights themselves. It's the line every training step runs.
One pass back
So, the forward pass keeps every value. Then one pass back from the loss multiplies by rates read off those values, and adds where paths meet. That gives every weight its slope, for the work of a few forward passes. PyTorch keeps the record, and adds into dot grad.
Every slope
One pass back from the loss gives every weight its slope. Now try it on this lesson's page, and take the quiz. Find where one weight gets no slope, but the other does.
You use this lesson in Lab 2: Train the digit reader, after The training loop.
Facts last checked on .
