Lesson 4 of 89 min
Gradient descent and the learning rate
Step against the uphill arrow again and again, taking the largest share of it that still makes the loss fall steadily.
After this lesson you can minimise a function by stepping downhill, and recognise a step that is too small or too large.
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 default is not a choice
Leave out lr and PyTorch picks one for you: 0.001, for SGD and for Adam. Hugging Face's Trainer starts at 0.00005. These are only starting points, made for no model in particular. On the penguins, 0.001 would take thousands of steps. x and mass are the video's penguins.
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
print(torch.optim.SGD([w, b]).defaults["lr"])
print(torch.optim.Adam([w, b]).defaults["lr"])0.001 0.001
When the loss turns into nan
In the video the loss climbed to a big number. Let it climb longer and the number gets too big for the computer to hold: it becomes inf, and then nan, "not a number". A loss of nan in your training means the same thing as a climbing one: lower the learning rate.
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=1.0)
for step in range(100):
loss = ((w * x + b - mass) ** 2).mean()
opt.zero_grad()
loss.backward()
opt.step()
if step + 1 in (10, 30, 40, 100):
print(step + 1, loss.item())10 516260416.0 30 4.59938868095809e+27 40 inf 100 nan
Why zero_grad is in the loop
backward() adds the new slopes to the ones already in .grad. Without opt.zero_grad(), every step uses the sum of all the slopes so far, so the steps keep growing. Here is the video's loop with that one line left out: after twenty steps the loss is still near where it started.
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=0.1)
for step in range(20):
loss = ((w * x + b - mass) ** 2).mean()
loss.backward()
opt.step()
print(w, b)
print(((w * x + b - mass) ** 2).mean())tensor(-0.6487, requires_grad=True) tensor(8.1659, requires_grad=True) tensor(17.9892, grad_fn=<MeanBackward0>)
Find a first value in one run
Instead of several short runs, make one run where the learning rate grows a little at every step, and see where the loss was lowest. A common start is about ten times smaller. Here the lowest loss came at about 0.75, so you would start near 0.075, close to the video's 0.1. fastai's `lr_find` does this for you.
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=0.0001)
seen = []
for step in range(30):
loss = ((w * x + b - mass) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
seen.append((round(loss.item(), 3), round(opt.param_groups[0]["lr"], 4)))
opt.param_groups[0]["lr"] *= 1.5
print(min(seen))(0.155, 0.7482)
Where too large begins
On the penguins' bowl the line between falling and climbing is close to 0.5. At 0.5 the walker still arrives, slowly, jumping across the bottom at almost the same length each time. Just above it, every jump gets longer. A bowl that curves more sharply has this line at a smaller learning rate.
for lr in [0.3, 0.5, 0.52, 0.55]:
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=lr)
for step in range(100):
loss = ((w * x + b - mass) ** 2).mean()
opt.zero_grad()
loss.backward()
opt.step()
print(lr, round(loss.item(), 3))0.3 0.155 0.5 0.306 0.52 685930.5 0.55 877028295311360.0
Run on Python 3.13, PyTorch 2.15.0, pandas 3.1.1, scikit-learn 1.9.1 and transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Partial derivatives and the gradient
At one point on the bowl, the slope along w is 6 and the slope along b is 8. How long is the gradient's arrow there?
2 of 3
Your training code has torch.optim.SGD([w, b], lr=1.0), and the loss it prints climbs at every step. What do you change?
3 of 3
You stand at weights (0, 0). The gradient there, the uphill arrow, is [-3, -8]. The learning rate is 0.1. After one step, what is the second weight, b?
The ideas in this lesson
- Gradient descent
- Step against the uphill arrow by a fixed share of it, and repeat until the loss stops falling.
- Learning rate
- The share of the arrow each step takes: too small crawls, too large leaps past the bottom and climbs away.
- Reading the loss curve
- The loss drawn step by step shows whether the learning rate is too small, right or too large.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Three walkers
Here's a bet. Three walkers stand on one hill, in thick fog. They can only feel the ground under their feet. Each takes the same number of steps down. One takes tiny steps. One takes medium steps. And one takes huge steps. Who ends up lowest?
The loss bowl
Here's a line that guesses a penguin's mass from its flipper. It has two weights, w and b: the two numbers it can change. For every pair of weights, there's a loss, the number for how wrong the line is. Put the weights on the floor and the loss as the height... and you get a bowl. We start where a model knows nothing, at zero, zero. The loss is eighteen point three. We want the bottom.
Against the arrow
But in the fog, we can't see the bottom. We only know the slope under our feet.
That slope is the gradient: here, minus two point seven three, minus eight point four. It's an arrow that points uphill, longer where it's steeper. We want to go down. So we step the other way... against the arrow.
How far to step
How far do we step?
Not the whole arrow. Just a tenth of it, turned around.
A tenth of the arrow, turned around, is zero point two seven, zero point eight four. We started at zero, zero, so we land at zero point two seven, zero point eight four. And the loss drops from eighteen point three to eleven point four.
That tenth... is the learning rate.
The rule
So here's the whole rule. New weights equal old weights, minus the learning rate times the gradient. That's the step we just took. Both slopes were below zero, so taking away a tenth of them made both weights bigger.
Now the arrow here is minus one point four nine, minus six point six seven. Where does the next step land?
A tenth of it, turned around, is zero point one five, zero point six seven. Add that on: zero point four two, one point five one.
Again and again
Now do it again. At the new point, a new arrow. A new step. And again. The loss goes eighteen point three... eleven point four... seven point two... four point six.
Step against the arrow, again and again, until the loss stops falling. That's gradient descent.
Steps shrink
In gradient descent, every step is the same share of the uphill arrow. That share is the learning rate. But the steps aren't all the same length. The second arrow is shorter, so the second step is too. The first step was zero point eight eight long. The second is zero point six eight. Near the bottom the ground is flatter, so the arrows shrink, and the steps shrink with them. A real walker's steps would stay the same length. These shrink by themselves.
Bigger is not faster
Then why not a big learning rate, to get there in a few steps? Here are three walkers on this bowl, at three learning rates: one hundredth, one tenth, and zero point six.
Twenty steps each.
The tiny steps... are still at a loss of about eight.
The medium steps... are at the bottom. The medium walker ends up lowest.
And the huge steps... climbed right out of the bowl. A loss of over seven hundred thousand.
If you bet on the huge steps, that's the usual mistake. Big steps look like the fast way.
Why too large climbs
Here's why. At zero point six, the first jump goes past the bottom. And the loss even falls, to three point seven.
But then it jumps back across, and lands farther out on the other side.
Farther out means steeper ground, and a longer arrow.
So, will the next jump be longer, or shorter?
Longer. And the one after, even longer. The loss goes up to about six, then nearly doubles with every jump: eleven, twenty-one, forty. A real walker never jumps over a whole valley. This one does, on every step.
Too small crawls
So is a tiny learning rate the safe choice?
Safe, yes. But slow.
At one hundredth, the first step takes the loss from eighteen point three to seventeen point five.
After twenty steps, it's still at about eight.
The medium walker passed that in two steps.
To get where one tenth got in twenty steps, it needs over two hundred.
And on a real model, every step costs time.
Which walker are you?
Here's the catch. A real model doesn't have two weights. It has millions. Nobody can draw that bowl. So how would you know which walker you are?
The loss curve
A model learns by stepping downhill, and each step is a share of the slope: the learning rate. You can't see its bowl. But you can always see the loss. Write it down at every step, and draw it as a line. That drawing... is the loss curve. Here's the run at one tenth: a fast drop, then flat, at the bottom.
Three curves
Two more runs, with no labels. One slides down gently, and it's still falling at the end. The other climbs, faster at every step. Which one had the learning rate too small, and which too large?
The climbing one is too large. That one's easy. The gentle slide is too small, and it's the tricky one. It looks like it's working... but it never flattens.
Ten times smaller
So say your loss keeps climbing, step after step. What do you change?
Lower the learning rate. About ten times lower. Then run it again. Zero point six becomes zero point zero six... and the loss falls.
Try a few
And when you start?
Nobody knows the right value in advance. It depends on the model, and good values differ a lot from one model to the next. So try a few in short runs, each ten times smaller than the last.
One, a tenth, a hundredth, and a thousandth.
At one, the loss climbs. The rest fall, and one tenth falls the fastest. So keep the largest one whose loss falls steadily.
In code
Now in real code. Here are the two weights in PyTorch, both at zero.
SGD is PyTorch's gradient descent. It takes the weights, and the learning rate: lr, set to zero point one.
Then a loop runs twenty steps. Each one works out the loss. Zero grad clears the slopes from the step before. Backward finds the new ones.
And step is the rule: each weight minus the learning rate times its slope.
So where will the weights end up?
Zero point five, and four point one one. The line runs right through the penguins. That lr is in every training script. It's the first number people change.
The largest step that still falls
So here's the idea. Step against the uphill arrow, and take the largest share of it that still makes the loss fall, steadily.
The lab
That's the end of this unit. In the lab, you use these four lessons together. You find the middle of one kind of penguin, by walking downhill.
The largest step
So take the largest step that still makes the loss fall. Now try it on this lesson's page, and take the quiz. Find a learning rate that beats the medium walker.
You use this lesson in Lab 1: Find the Gentoos' middle, by walking downhill, which comes next.
Facts last checked on .
