Lesson 8 of 87 min
Momentum and Adam
When one learning rate can't suit every weight, momentum lets steps that agree build up speed, and Adam gives each weight its own step size.
After this lesson you can explain what momentum and per-parameter step sizes fix.
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.
Momentum, written out
PyTorch's SGD with momentum=0.9 keeps a running step, v: nine tenths of the last one plus the new slope. The weights move by the learning rate times v. Written out by hand, it lands where PyTorch did: b at 4.40. x and mass are the video's penguins, the flipper in millimeters from 200.
wb = torch.zeros(2, requires_grad=True)
v = torch.zeros(2)
for step in range(50):
((wb[0] * x + wb[1] - mass) ** 2).mean().backward()
with torch.no_grad():
v = 0.9 * v + wb.grad
wb -= 0.005 * v
wb.grad = None
print(wb)tensor([0.0418, 4.4027], requires_grad=True)
Adam, written out
Adam keeps two running averages for each weight: m of its slopes, its momentum, and s of their squares, how big they have been. The step is the learning rate times m over the square root of s. Dividing by 1 - 0.9 ** t and 1 - 0.999 ** t fixes the first steps. It lands on PyTorch's 3.83.
wb = torch.zeros(2, requires_grad=True)
m, s = torch.zeros(2), torch.zeros(2)
for t in range(1, 51):
((wb[0] * x + wb[1] - mass) ** 2).mean().backward()
with torch.no_grad():
m = 0.9 * m + 0.1 * wb.grad
s = 0.999 * s + 0.001 * wb.grad ** 2
wb -= 0.1 * (m / (1 - 0.9 ** t)) / ((s / (1 - 0.999 ** t)).sqrt() + 1e-8)
wb.grad = None
print(wb)tensor([0.0548, 3.8343], requires_grad=True)
AdamW and weight decay
Weight decay pulls every weight a little toward zero each step, so a big network leans less on a few weights. Adam adds the pull to the slope, where its division shrinks it. AdamW takes it off the weight apart (Loshchilov and Hutter). On two weights it only gets in the way. AdamW pulls with 0.01 by default.
for Opt in [torch.optim.Adam, torch.optim.AdamW]:
wb = torch.zeros(2, requires_grad=True)
opt = Opt([wb], lr=0.1, weight_decay=0.1)
for step in range(50):
loss = ((wb[0] * x + wb[1] - mass) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
print(Opt.__name__, round(wb[1].item(), 2))
print(torch.optim.AdamW([wb]).defaults["weight_decay"])Adam 3.75 AdamW 3.16 0.01
Or put the inputs on one scale
The valley came from the units, so the other fix is the input itself: take away its average and divide by its spread. Then the bowl is round again, and plain steps at 0.1 reach the bottom, 0.155, in 50 steps. A network still uses Adam, because its millions of weights inside are on every scale.
xs = (x - x.mean()) / x.std()
wb = torch.zeros(2, requires_grad=True)
opt = torch.optim.SGD([wb], lr=0.1)
for step in range(50):
loss = ((wb[0] * xs + wb[1] - mass) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
print(round(loss.item(), 3))0.155
Other names you will meet
nesterov=True looks one step ahead before it pushes. Its steps across are larger, and at the video's 0.005 it climbs out. RMSprop and Adagrad are older cousins of Adam. Muon is newer, in PyTorch since 2.9, and still being tested against AdamW. It only steps weights that are tables of numbers, so the rest goes to AdamW.
wb = torch.zeros(2, requires_grad=True)
opt = torch.optim.SGD([wb], lr=0.005, momentum=0.9, nesterov=True)
for step in range(50):
loss = ((wb[0] * x + wb[1] - mass) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
print(f"{loss.item():.2g}")5.1e+34
layer = torch.nn.Linear(4, 3)
opt = torch.optim.Muon([layer.weight])
torch.optim.Muon(layer.parameters())ValueError: Muon only supports 2D parameters whereas we found a parameter with size: torch.Size([3])
Run on Python 3.13, PyTorch 2.15.0, pandas 3.1.1 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: Stochastic gradient descent
Your data holds 1,000 examples, and your code has DataLoader(data, batch_size=64, shuffle=True). How many times does opt.step() run in one epoch?
2 of 3
Your code says torch.optim.Adam(model.parameters()), with no learning rate. After many steps, the loss has hardly moved. What do you try?
3 of 3
With momentum, each step is the new push plus nine tenths of the step before. Along a valley's floor, the push is 0.1 every step, and the first step is 0.1. How long is the third step?
The ideas in this lesson
- A long, narrow valley
- When the loss is far steeper along one weight than another, one learning rate is too big for one and too small for the other.
- Momentum
- Each step keeps most of the step before: pushes that agree build up speed, and pushes that flip back and forth cancel.
- Adam
- Each weight gets its own step size from its own recent slopes, so every weight moves about the learning rate a step.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Millimeters
Here's a puzzle. Gradient descent takes this line to the bottom fast. Now measure the flipper in smaller units. Same data. Same best line. With the best learning rate, is it still as fast?
The bowl becomes a valley
In millimeters, the flipper's numbers are ten times bigger. So a tiny turn of w moves every guess ten times as much.
Along w, the bowl's walls get very steep. Along b, nothing changed. So the round bowl becomes a long, narrow valley. Its floor runs along b.
We start where a model knows nothing, at zero, zero, with a loss of eighteen point three.
Too large leaps across
So why not a bigger learning rate? Both weights share one, and here the most they can take is five thousandths. Go just past it, to six thousandths. What happens?
The steps across the steep walls leap from side to side. Each one lands a little higher... and it climbs out. After ten steps, the loss is over five hundred.
Small enough crawls
So back to five thousandths. The steps across are safe now. But a step is the learning rate times the slope. And along the floor, the slope is small. So each step moves b only a tiny bit: four hundredths. So, no. Even after fifty steps, more than twice as many, the loss is still six point six. It would need about four hundred steps.
If you said yes: the units changed the bowl's shape. The steepest weight sets the learning rate... and the gentlest one crawls.
Momentum
So how do you go faster along the floor, without leaping across?
Keep most of the last step.
Each step is the new push, the slope where the walker stands, plus nine tenths of the step before. That's momentum.
Along the floor, the pushes all point the same way, so they add up. The walker speeds up, like a ball rolling down a long slope. Four hundredths a step, then eight, then eleven... up to twenty-three. A ball could keep speeding up. Here a step can grow to ten times a plain one, at most.
Pushes that flip cancel
Across the valley, the pushes flip from side to side. So they cancel, and the zigzag dies down. And like a ball, it rolls a little past the bottom, then comes back. After fifty steps: zero point two two. Plain steps were at six point six, with the same learning rate.
A step for each weight
So momentum built up speed. But its steps still grow with the slope. So its learning rate had to fit the steepest wall. What if each weight's step didn't depend on how steep its slope is?
Adam
That's Adam. For each weight, Adam remembers how big that weight's slopes have been lately. Then it divides the weight's step by that size.
A big slope is divided by a big number. A small slope, by a small one. So each weight moves about the learning rate every step, until it gets close to the bottom.
On the first step, plain steps move w fourteen hundredths, and b only four hundredths.
Adam, at a learning rate of zero point one, moves each of them one tenth. On top of that, Adam uses momentum too.
After fifty steps, its loss is zero point two six.
The units stop mattering
Here, Adam does about the same as momentum. So what did it fix?
Go back to the flipper in centimeters.
The same Adam, at the same zero point one, gets to zero point two six in fifty steps... just like in millimeters.
Plain steps needed a much smaller learning rate once the units changed. With a step size for each weight, the units stop mattering.
Adam still has a learning rate
So Adam doesn't need a learning rate at all?
Leave it at PyTorch's default, a thousandth. That's the value it uses unless you set one. Where will it be after fifty steps?
Hardly anywhere. Each weight moves about one thousandth a step. The loss is still seventeen point one. Adam has a learning rate, and you choose it the same way as any other. Try a thousandth, a hundredth, a tenth, and one, in short runs. At one, the loss climbs before it falls. So keep a tenth.
In code
Now in real code. Here's the loop from gradient descent: fifty steps, with the flipper in millimeters. How to step is one line, which PyTorch calls the optimizer.
First, PyTorch's SGD.
That's plain gradient descent, at five thousandths.
b ends at one point six four.
The bottom is at four point one six.
Now add momentum, nine tenths.
Where will b end up?
Four point four: just past the bottom, still rolling. Change it to Adam, at zero point one: three point eight three. Nearly there.
Most training code you'll read uses AdamW: Adam with one small change. Hugging Face's Trainer uses it, unless you tell it otherwise.
In your own code, it's one line: AdamW, the model's weights, and a learning rate you chose.
The idea
So here's the idea. Momentum builds up speed where the pushes agree. Adam gives every weight its own step size, so the units stop mattering.
And both still need a learning rate.
The lab
That's the end of this unit. In the lab, you use these two lessons together. You write mini-batches, momentum and Adam yourself.
A step size for each weight
So momentum builds speed, and Adam gives each weight its own step. Now try it on this lesson's page, and take the quiz. Make plain steps climb out of the valley.
You use this lesson in Lab 3: Batches, momentum and Adam, written by hand, which comes next.
Facts last checked on .
