Lesson 11 of 187 min
Warmup and learning-rate schedules
Change the learning rate as training goes: raise it slowly at the start, so Adam's first steps stay small, and lower it towards 0 at the end, so the network can settle.
After this lesson you can choose a schedule and say why warmup helps.
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.
Step the schedule once a step
The video's schedule counts steps: 100 of warmup, then 1,250 of the cosine. Call sched.step() once an epoch instead, as many examples do, and the warmup lasts 100 epochs. It never ends: the rate stays under a third of the peak, and the run gets 94.2%, not 98.1%. No error tells you, so print the rate now and then.
warm_cos = lambda opt: SequentialLR(opt, [LinearLR(opt, start_factor=0.01, total_iters=100),
CosineAnnealingLR(opt, T_max=1250)], milestones=[100])
rates, right = train(0.1, warm_cos)
print("each step: ", round(rates[45], 4), round(rates[-1], 7), right)
rates, right = train(0.1, warm_cos, per_epoch=True)
print("each epoch:", round(rates[45], 4), round(rates[-1], 4), right)each step: 0.0456 2e-07 0.9806 each epoch: 0.002 0.0297 0.9417
The whole schedule as one function
Many training scripts, nanochat's among them, write the whole shape as one function of the step and hand it to LambdaLR. The function gives a share of the peak: 0.01 at the start, 1 at step 100, then half a cosine down to 0. It sets the video's rates, and the run gets the same 98.1%.
def shape(step, warmup=100, total=1350):
if step < warmup:
return 0.01 + 0.99 * step / warmup
return 0.5 * (1 + math.cos(math.pi * (step - warmup) / (total - warmup)))
rates, right = train(0.1, lambda opt: LambdaLR(opt, shape))
print(round(rates[0], 6), round(rates[100], 6), f"{rates[1349]:.2e}", right)0.001 0.1 1.58e-07 0.9806
Other shapes
Two older shapes still show up. Steps: hold the rate, then cut it by ten every so many steps (StepLR), long the usual way to train image networks. One cycle: up for the first part of the run, then down (OneCycleLR). Both beat 0.1 held here. Neither beats warmup and a cosine.
_, steps = train(0.1, lambda opt: StepLR(opt, step_size=450, gamma=0.1))
_, one = train(0.1, lambda opt: OneCycleLR(opt, max_lr=0.1, total_steps=1350))
_, held = train(0.1, None)
print(steps, one, held)0.9528 0.9778 0.9083
A cosine or a straight line
A straight line down to 0 works too. The cosine stays near the peak longer, and gets small sooner at the end: 0.094 against the line's 0.084 at step 300, 0.0035 against 0.012 at step 1,200. Here the cosine gets 98.1%, the line 97.5%. On another network the line may win: try both.
warm_line = lambda opt: SequentialLR(opt, [LinearLR(opt, start_factor=0.01, total_iters=100),
LinearLR(opt, start_factor=1.0, end_factor=0.0, total_iters=1250)],
milestones=[100])
rates_c, cos_right = train(0.1, warm_cos)
rates_l, line_right = train(0.1, warm_line)
print(round(rates_c[300], 4), round(rates_l[300], 4), round(rates_c[1200], 4), round(rates_l[1200], 4), cos_right, line_right)0.0938 0.084 0.0035 0.012 0.9806 0.975
When a schedule doesn't help
At a rate that is small already, lesson 5's 0.001, a cosine only slows the run: 92.8%, below the 95.3% of the rate held. A schedule is what lets a bigger peak work. Warmup matters more as networks get deeper: lesson 6's 20-layer network with skips and no norm got 34% at 0.03 without warmup, and 93% with it.
_, small_held = train(0.001, None)
_, small_cos = train(0.001, lambda opt: CosineAnnealingLR(opt, T_max=1350))
print(small_held, small_cos)0.9528 0.9278
Run on Python 3.13.3, PyTorch 2.15.0, scikit-learn 1.9.1 and NumPy 2.5.5. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Gradient descent and the learning rate
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?
2 of 3
You train the digits network with Adam at 0.3, with a cosine decay and no warmup. In its very first steps, the loss jumps from about 2.4 to over 10. Why?
3 of 3
You train with Adam at a peak of 0.2, with warmup: the rate starts at a hundredth of the peak, then climbs to it over the first 100 steps. About how far does Adam's very first step move each weight?
The ideas in this lesson
- Learning-rate decay
- Lower the learning rate as training goes, to near 0 by the end, so the big early steps can settle.
- Warmup
- Start the learning rate small and raise it to its peak over the first steps, while Adam's numbers settle.
- Choosing a schedule
- Warm up over the first few steps, then lower the rate to near 0: smoothly, or held and lowered at the end.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Why not one rate?
Here's a mystery. Big language models aren't trained at one learning rate. The rate starts tiny, climbs, then slowly falls to almost nothing. Why not keep one good rate all the way?
A hundred times bigger
Take our digits network. At its usual learning rate, zero point zero zero one, it gets about ninety-five percent right. Now make the rate a hundred times bigger, zero point one, and keep it there for all thirty epochs. At the end, will it get more right, about the same, or fewer?
One rate is a trade
The learning rate sets how far each step goes.
At zero point one, the network is quicker at first. After one epoch, it's eighty-eight percent right, while the small rate had forty-six.
But at the end, its steps are too big to settle. Its validation loss goes up and down, from one epoch to the next. It ends at about ninety-one percent... fewer.
Big steps help early, and hurt late.
A decay
So can we have both?
Change the rate as training goes on. That's a schedule.
Thirty epochs of forty-five steps make thirteen hundred and fifty steps.
Start at zero point one, and lower the rate a little every step, down to zero at the last one. That's a decay.
A cosine decay follows half a wave: slow at first, fastest in the middle, and slow at the end.
With a cosine decay, the run at zero point one gets about ninety-six percent. And its validation loss is steady at the end.
Both
Big steps early, small steps late. The schedule gives you both.
The first steps spike
A learning rate can change as training goes on, and a decay lowers it to zero by the end. So why not start even bigger?
Zero point three, with the cosine. Will it train?
Its first steps spike.
After its very first step, the loss jumps from about two point four to over ten. And it ends at about eighty-three percent.
Adam's first step
Why?
Adam keeps two numbers for every weight, from the slopes it has seen.
It gives each weight a step about the size of the learning rate. At the very first step, those numbers come from just one batch... so every weight moves by the full rate. Big slope or tiny, it doesn't matter. Each weight starts at about zero point zero seven. A step of zero point one moves it by more than its own size, and the loss rises a little. A step of zero point three moves it by about four times its size. The loss jumps to over ten, and the run never fully recovers.
Warmup
So keep the first steps small. Call the highest rate the peak: here, zero point three. Start at a hundredth of the peak. Then raise the rate in a straight line, up to the peak, over the first hundred steps.
It's like driving: you pull out of a parking space slowly, and speed up on the open road.
The first step moves every weight by just zero point zero zero three. And by step one hundred, Adam's two numbers come from many batches, not one. That's warmup. At zero point three, there's no spike now: the highest loss is the very first one. It ends at about ninety-five percent, up from eighty-three without warmup. That's as good as the small, steady rate.
It takes both
So is warmup enough?
Spot what goes wrong here.
This is warmup, then zero point three held to the end. The validation loss goes up and down, as high as two point six... and it ends at about forty-seven percent. You need both.
Back at zero point one: a cosine alone gave about ninety-six. With warmup too, it gets about ninety-eight percent. That's the best run here.
Choosing a schedule
A schedule warms the learning rate up, then lowers it. So how do you choose one? Warm up over a small fraction of the steps: here, a hundred out of thirteen hundred and fifty. Try a few peaks.
Then decay to near zero, or to a small fraction of the peak, by the end. Llama 3's biggest model did just that. It warmed up over eight thousand steps. Then it fell along a cosine, to a hundredth of its peak, over more than a million steps.
Hold, then lower it at the end
Some newer runs hold the peak for a while first, and only lower it later in the run.
nanochat trains a small chatbot from scratch. It warms up for forty steps. Then it holds.
Then, over about its last two thirds, it falls in a straight line, down to five percent of the peak.
While the rate holds, you can still decide how long to train, and start the fall when you're ready.
On our digits, holding and then falling gives ninety-seven and a half percent.
In code
In code, make the optimizer with the peak, zero point one. The warmup's line starts at a hundredth of the peak, and climbs over the first hundred steps. The cosine's line runs the other twelve hundred and fifty steps, down to zero. A third line puts the two one after the other, switching at step one hundred.
After every optimizer step, the schedule steps too. It prints the rate: zero point zero zero one at the first step, a hundredth of the peak. Zero point one at step one hundred. And almost zero at the last. The run gets about ninety-eight percent.
Warm up, then decay
So, warm up, so that Adam's first steps stay small. And decay, so that the end can settle.
The lab
That's the end of this unit. In its lab, you use these three lessons to write a training run that checks itself as it goes.
Slowly, then let it fall
Raise the rate slowly, then let it fall. Now try it on this lesson's page, and take the quiz. Beat the best run in this video.
You use this lesson in Lab 4: A training run that checks itself, which comes next.
Facts last checked on .
