Lesson 5 of 87 min
The chain rule
When one thing moves the next, their rates multiply: the slope of a loss built from pieces is the rates of its pieces multiplied.
After this lesson you can differentiate a function built from other functions.
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.
Walk the chain back yourself
grad_fn is the last link PyTorch wrote down, and each link keeps the ones before it in next_functions. Follow them from the loss and you get the penguin's chain backwards: the square, the minus, the plus, the times, then w itself, where backward() leaves the slope.
w = torch.tensor(0.0, requires_grad=True)
loss = (w * 3 + 4.2 - 5.7) ** 2
link = loss.grad_fn
while link is not None:
print(type(link).__name__)
link = link.next_functions[0][0] if link.next_functions else NonePowBackward0 SubBackward0 AddBackward0 MulBackward0 AccumulateGrad
How papers write it
Papers write a rate as d over d: the chain rule is dL/dw = dL/dmiss × dmiss/dguess × dguess/dw. torch.autograd.grad gives the loss's rate at each box on the way back. It is −3 at the miss, still −3 at the guess, since the minus link's rate is 1, and −9 at w.
w = torch.tensor(0.0, requires_grad=True)
guess = w * 3 + 4.2
miss = guess - 5.7
loss = miss ** 2
print(torch.autograd.grad(loss, [miss, guess, w]))(tensor(-3.), tensor(-3.), tensor(-9.))
Where two paths meet, they add
Here w reaches y along two paths: w * w, with a rate of 2 × 2 = 4, and 3 * w, with a rate of 3. Along each path the rates multiply. Where paths meet, they add: 4 + 3 = 7. GPT-2's chain is full of branches: 846 links, and its longest path back is 564.
w = torch.tensor(2.0, requires_grad=True)
y = w * w + 3 * w
y.backward()
print(w.grad)tensor(7.)
Many small rates in a row
Fifty links, each with a rate of 0.5. Their product is about 0.0000000000000009, so w gets almost no slope and hardly learns. Deep networks have the same trouble, called a vanishing gradient. The Deep Learning course shows how networks are built to avoid it.
w = torch.tensor(1.0, requires_grad=True)
out = w
for _ in range(50):
out = out * 0.5
out.backward()
print(w.grad)tensor(8.8818e-16)
Run on Python 3.13, PyTorch 2.15.0 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The derivative
You nudge a weight from 3 to 3.01, and the loss goes from 5.00 to 4.97. About what is the derivative there?
2 of 3
Every training script calls loss.backward(). What does it do?
3 of 3
Nudge a weight, and a model's guess moves 4 times as much. Nudge the guess, and the loss falls half as much as the guess rises: a rate of −0.5. What is the loss's rate for the weight?
The ideas in this lesson
- Chain rule
- When one thing moves the next, their rates multiply: a chain's rate is its links' rates multiplied.
- Backward through the chain
- `backward()` starts at the loss and multiplies the rates back through every link, so each weight gets its slope.
It leans on
- Backpropagation
Transcript
What the video says, part by part. Press a time to watch from there.
Three wheels
Here's a puzzle. Three wheels are joined by belts. The first wheel spins the second three times as fast. The second spins the third twice as fast.
Spin the first wheel once. How many times does the third one spin?
Six, not five
Each wheel has a rate: how many spins it makes for one spin of the wheel before it. The first wheel spins once. So the second spins three times. And each of those three spins gives the third wheel two. That's six. Not five. If you said five, you added the rates. It's the usual mistake.
A loss is a chain
Here's one penguin. Its flipper is twenty-three centimeters, and its mass is five point seven kilos. And here's the line that guesses its mass, with its two weights, w and b. Right now, w is zero and b is four point two. The flat line. The line measures the flipper from twenty centimeters, so this penguin sits at three. Now follow it through. w makes the guess: four point two. The guess makes the miss: minus one point five. And the miss, squared, is its loss: two point two five. Three links in a row, like the wheels. A nudge to w passes along all of them.
A rate for each link
So how much does each link move the next one?
To find out, we nudge each link.
Nudge w by a hundredth.
The guess moves three hundredths: three times as much, because this penguin sits three centimeters past the mark. So the first rate is three.
Nudge the guess, and the miss moves by exactly the same amount. A rate of one.
The square's rate
Now the last link. Nudge the miss from minus one point five to minus one point four nine. The square falls a little: two point two five becomes two point two two. It fell three hundredths, for a nudge of one hundredth. That's a rate of minus three.
A wheel's rate never changes. But the square's rate depends on how big the miss is... so we read each rate at the values the chain has right now.
Multiply the rates
So when you nudge w, how fast does the loss move?
Multiply, just like the wheels.
Three, times one, times minus three... is minus nine.
The nudge of a hundredth becomes three hundredths. It stays three hundredths.
Then it turns into minus nine hundredths.
The chain rule
Let's check it against the loss itself. At w equals a hundredth, the loss is two point one six.
It fell by about nine hundredths. That's a rate of minus eight point nine one... about minus nine. The rate of a chain is the rates of its links, multiplied. That's the chain rule. So turn w up, and the loss falls nine times as much.
Adding goes the wrong way
But why multiply? Why not add them? Three, plus one, minus three... is plus one. What's wrong with that?
Plus one says the loss rises with w, so you'd turn w down. But the loss falls.
Adding sends you the wrong way.
Each link makes whatever nudge reaches it bigger or smaller. So the rates multiply.
Every weight
Now, a real network has millions of weights, and many more links than three. How does it get the slope of every one?
Backward through every link
The same way. GPT-2, a model that writes text, has over a hundred million weights. Between its loss and its first weights, there are hundreds of links. PyTorch's backward, the call that fills in every slope, starts at the loss. It goes back through the links, one by one, multiplying the rates, until every weight has its slope. All those slopes together are the gradient. That's backpropagation. It's the chain rule, run backwards from the loss. How it handles a whole network is a lesson of its own.
A zero stops it
One more thing. What if one rate on the way back is zero?
Going back from the loss, the first link you come to is the square. Turn w up to one half. Now the line guesses this penguin's five point seven kilos exactly. The miss is zero, so the square is at its bottom. Nudge the miss either way, and the square barely moves: its rate there is zero. So the product is zero, from the very first link back. This penguin... doesn't move w at all. The line already gets it right.
In code
Now in real code: the penguin's chain, in PyTorch.
First, w.
It's made with requires grad set to true, which asks PyTorch to follow everything done with it. Then three lines: the guess, the miss, the loss.
As PyTorch works the loss out, it writes each link down. Print the loss. Two point two five, and beside it, PowBackward: the last link it wrote down. The square.
Now call backward. What will w dot grad hold?
Minus nine. The rates, multiplied. And for all three hundred and forty-two penguins, one line.
Their loss is the average, with a chain for each penguin.
So w dot grad is the average of their rates: minus one point nine six.
Nudge w at zero on all the penguins, and you'd find the same.
Every training script calls backward. This is what it does.
The idea
So here's the idea. Along a chain, the rates multiply: that's the chain rule. And backward does it for you, from the loss back to every weight.
Rates in a chain multiply
So along a chain, the rates multiply. Now try it on this lesson's page, and take the quiz. Make the whole chain's rate zero.
You use this lesson in Lab 2: Get a two-layer line off the saddle, after Loss landscapes.
Facts last checked on .
