A driver does not use one speed for a whole trip. On the highway she goes fast to cover distance. Near the parking space she slows down, because at high speed she would overshoot it. Training a network has the same two jobs: cover a lot of ground at the start, and place the parameters precisely at the end.
The speed in training is the learning rate (P1.F3). So far it was one number, picked once. A learning-rate schedule is a rule that gives , the rate for update number . Where the analogy breaks: a driver sees the parking space, but the optimizer cannot see how close it is. A schedule is a plan made before training starts, from the length of the run and from experience.
Why one rate is not enough
P1.F4 showed that a mini-batch gradient is the true gradient plus noise, and that with a constant the parameters hover in a noise ball around the minimum instead of settling. Take its one-parameter model: a bowl with curvature , and noise in each gradient with variance (P1.F4’s ). The distance from the minimum then follows , and once it has settled its spread is
This is the formula of the P1.F4 Go-deeper box with and noise variance . The numbers:
- : spread .
- : spread .
- : spread .
A ten times smaller rate gives about times less wobble. So the end of training wants a small .
The start wants the opposite. Begin units from the minimum with no noise, and each step multiplies the distance by . After 50 steps the distance is with , but with : the small rate has barely started. Large is fast and wobbly, small is quiet and slow, so a schedule goes large first and small later.
P1.F4 also showed the cost of shrinking too fast: on its example (batch 4, , 40 epochs) the decayed run ended from the minimum and the constant run away. A schedule is a design decision with a downside in both directions. The noise ball is one reason to decay. Warmup, below, is a different reason to change , at the very start.
The menu of schedules
Each schedule below gives for update out of updates in total. The peak rate is , and a final rate is where decay stops.
Step decay. Multiply by a factor (often ) every updates or epochs:
It is simple, and it was a common recipe in image-classification training. The rate sits flat and then drops suddenly, which shows as a staircase in the loss curve.
Exponential decay. A smooth version of the same idea, with a constant factor per update. Choosing the factor so that the rate arrives at after updates gives
Inverse-time and inverse-square-root decay. The rate has the shape that satisfies the Robbins–Monro conditions of P1.F4. A slower fall, , was used in the original transformer (Vaswani and others, 2017): the rate rose linearly for warmup updates and then decreased in proportion to the inverse square root of the update number. Their formula was , with Adam settings and . For it peaks at at update and is half of that, , at update . This shape has no fixed end, so it suits a run whose length is not known in advance.
Cosine annealing. Follow half a cosine wave from the peak down to a final value:
The rate falls slowly at first, fastest in the middle and slowly again at the end, and it is exactly half-way, when , at . The cosine form comes from Loshchilov and Hutter (SGDR, arXiv 2016, ICLR 2017). Their paper also proposed warm restarts: after a cycle of updates the rate jumps back to the peak and a new cosine cycle starts, usually a longer one. In PyTorch, CosineAnnealingWarmRestarts(T_0=10, T_mult=2) multiplies the cycle length by , so the restarts fall at updates , and .
Linear warmup. Start small and raise the rate linearly to the peak over the first updates, then hand over to another schedule:
Why do this? Two explanations have support, and the picture is not settled:
- Early gradients can be large and the network changes fast. Goyal and others (2017) argued that the rule “scale with the batch size” (P4.15) assumes the gradient barely changes between nearby steps, and that this fails at the start of training, when the network changes rapidly. They raised the rate in a straight line over the first 5 epochs, from to for a batch of 8192, and found that a flat low rate followed by a sudden jump could make the training error spike.
- Adam’s statistics start poor. Liu and others (2019) proposed that the adaptive step size of Adam has a very large variance in the first updates, because its squared-gradient average rests on few gradients, and that warmup acts as a way to reduce it. This is an explanation offered with evidence, not a closed question.
Warmup is not a cure for a bad rate, and a small network may not need it. In the widget’s model it is not needed to keep training stable: it only delays the first progress.
Warmup plus cosine. Warmup up to the peak, then a cosine down to a small final value, is a common default for modern training runs. As one documented example, GPT-3 (Brown and others, 2020) used a linear warmup over the first 375 million tokens and a cosine decay down to 10 percent of the peak over 260 billion tokens, after which training continued at 10 percent.
One-cycle. Smith and Topin (2017, “super-convergence”) used a single cycle: the rate rises to a large peak and then falls, in one pass through the training. PyTorch’s OneCycleLR has these defaults: start at , rise along a cosine for the first 30 percent of the updates, then fall along a cosine to . By default it also moves the momentum the other way, from down to at the peak and back, which the widget does not copy. Smith and Topin reported much faster training on some image tasks. Whether it helps on a given problem is something to test.
Here are three shapes side by side for over updates. The step decay drops by every updates, and the other two end at (exponential) and (cosine). The last row is the formula’s value at , which is one past the final update.
| step | exponential | cosine | |
|---|---|---|---|
| 0 | 0.1 | 0.1 | 0.1 |
| 25 | 0.1 | 0.0316 | 0.0854 |
| 50 | 0.01 | 0.01 | 0.05 |
| 75 | 0.001 | 0.00316 | 0.0146 |
| 100 | 0.0001 | 0.001 | 0 |
Two more tools are worth knowing by name. Linear decay to zero is another common ending. ReduceLROnPlateau is the one schedule that looks at the loss: PyTorch’s version multiplies the rate by when a monitored number (such as the validation loss) has not improved for 10 checks, by default.
The schedule designer
The widget trains one fixed small network (2-8-1 tanh, 200 points in an XOR pattern, plain SGD, batches of 8, 300 updates) with the schedule you build. The network and data are those of the P4.13 cell, with a little less overlap between the blobs. The upper chart is and the lower one is the loss on all 200 points. A dashed grey line shows a constant rate equal to the peak, for comparison.
Things to try, with the widget’s fixed settings (final , warmup updates, step drop every updates):
- A peak that is too big. Constant at ends at loss , its lowest value on the way was , and its last 50 values spread with a standard deviation of . Step decay ends at , cosine at and one-cycle at , each with a spread of or less. Not every decay helps: exponential ends at and warmup plus cosine at .
- A good peak. At constant ends at with a spread of , cosine at , warmup plus cosine at and step at . The final losses are close, and decay mainly removes the wobble. Warmup is not needed here: the loss falls below after updates with warmup and after without it.
- A peak that is too small. At constant ends at , cosine at and step at . At nothing has trained: every schedule ends between and , close to the starting loss of . Decay shrinks a rate that was already modest, so on a short run it costs progress. A schedule does not rescue a poor peak.
- The floor. A 3000-update cosine run from down to ends at , so about is roughly how low this network gets in that run. The blobs overlap, so some points cannot be classified correctly.
- Range test. The loss is lowest, , at and goes above at . The suggestion, a tenth of the lowest-loss rate, is .
The learning-rate range test
How do you pick the peak in the first place? Leslie Smith’s Cyclical Learning Rates (arXiv 2015, WACV 2017) describes a short run with the rate increasing, to find sensible bounds for it. The abstract describes the increase as linear. Many tools now grow the rate by a constant factor (exponentially) so that every decade of rates gets equal attention:
- Start from a fresh model and a tiny rate such as .
- Run a few hundred updates, multiplying by a fixed factor each time, up to something like . The widget uses 150 updates, a factor of about per update.
- Record the loss after each update and plot it against .
- The loss is flat while is too small, falls, reaches a low point, and then rises and blows up.
- Choose a peak well below the rate where the loss is lowest. A common rule of thumb is a tenth of it. Some guides pick the rate where the loss falls fastest instead.
Why below the lowest point? In the sweep the rate rises every update, so the loss at a rate has had little time to settle, and a rate that works for a 150-update sweep can still be too big for a run of 15,000 updates. The numbers show how loose the test is: with a sweep of 200 updates instead of 150 (same range) the lowest-loss rate moves from to . The test gives the right order of magnitude, not an exact answer. In the widget the curve stays almost flat (above ) until is about , because this network starts on a plateau, so at the suggested the sweep’s loss has not fallen yet. A constant for 300 updates still ends at . A sweep shows how the loss responds as rises, not what a long run would reach. Check the suggested peak with a real short run.
Interactions
- Batch size (P4.15). A larger batch has less noise and tolerates a larger . The rule of Goyal and others, scale in proportion to , was paired with a warmup, as above. When the batch size changes, the number of updates per epoch changes too, so a schedule counted in epochs and one counted in updates stop agreeing.
- Adam (P4.13). Adam does not remove the need for a schedule. With a steady gradient its step is about , so directly sets how far each parameter moves. In AdamW the decay is per update, so a schedule scales the weight decay too.
- The run length. Cosine, one-cycle and step decay need in advance. If you stop early, the rate was still large. Inverse-square-root decay and a constant rate do not have this problem.
Schedules in PyTorch
Schedulers live in torch.optim.lr_scheduler. A scheduler wraps an optimizer and changes the lr stored in it each time you call scheduler.step(). The order matters: call optimizer.step() first and scheduler.step() after it. In the other order PyTorch warns that it will skip the first value of the schedule.
The second choice is the unit. StepLR(step_size=3) drops the rate after every 3 calls of scheduler.step(). Called once per epoch, that is every 3 epochs. Called once per batch, it is every 3 updates. Smooth schedules (cosine, one-cycle, warmup) are normally stepped once per update, and OneCycleLR expects that. ReduceLROnPlateau is stepped with the monitored value, scheduler.step(val_loss).
Intuition
A schedule trades speed for precision on a timetable. Early on, big steps cover ground, and the noise matters little because you are far from the minimum and the true gradient is large. Late in training the true gradient can be small next to the noise, so smaller steps are needed to average the noise out. Warmup protects the very first updates, when the network and the optimizer’s statistics are least settled. The range test is a cheap experiment to learn how big a step the loss tolerates.
Math
With updates, peak , final rate and update number :
- Constant: .
- Step: .
- Exponential: .
- Cosine: .
- Warmup plus cosine: for , then the cosine with replaced by and by .
- One-cycle (PyTorch defaults): with , rise from to along a cosine for , then fall along a cosine to at .
- Inverse square root (Vaswani and others): , with .
- Noise ball (one parameter): spread for curvature and noise variance .
- Range test: for .
Code
PyTorch schedulers on a dummy optimizer (momentum SGD, peak , 100 updates). The program prints the rate that the update would use, at four update numbers (run locally with PyTorch 2.9.1):
import torch
from torch import nn
from torch.optim import lr_scheduler as S
model = nn.Linear(2, 1)
def lrs(make, steps=100):
opt = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
sched = make(opt)
out = []
for t in range(steps):
out.append(opt.param_groups[0]["lr"]) # rate of this update
opt.step() # first the optimizer ...
sched.step() # ... then the scheduler
return out
warm = 10
make = {
"StepLR(30, 0.1)": lambda o: S.StepLR(o, step_size=30, gamma=0.1),
"CosineAnnealingLR": lambda o: S.CosineAnnealingLR(o, T_max=100),
"OneCycleLR": lambda o: S.OneCycleLR(o, max_lr=0.1,
total_steps=100),
"LambdaLR warmup": lambda o: S.LambdaLR(
o, lambda t: (t + 1) / warm if t < warm else 1.0),
}
at = [0, 30, 60, 99]
print("update", *[f"{t:>7}" for t in at])
for name, f in make.items():
L = lrs(f)
print(f"{name}")
print(" ", *[f"{L[t]:7.4f}" for t in at])update 0 30 60 99
StepLR(30, 0.1)
0.1000 0.0100 0.0010 0.0001
CosineAnnealingLR
0.1000 0.0794 0.0345 0.0000
OneCycleLR
0.0040 0.0999 0.0589 0.0000
LambdaLR warmup
0.0100 0.1000 0.1000 0.1000LambdaLR multiplies the starting rate by the number that the function returns, which is how a warmup is written by hand. A warmup followed by a cosine can be built from LinearLR and CosineAnnealingLR joined by SequentialLR. OneCycleLR reaches its peak of at update (30 percent of , minus one), so the at update is just past the top.
A schedule by hand
Peak , a warmup of updates and a cosine over the remaining updates, ending at .
- Update : .
- Update : .
- Update : , the peak.
- Update : the cosine starts, with , so the rate is again.
- Update : , which is half of , so the rate is .
- Update : , so the rate is .
Try it: four schedules, two peaks
This cell trains the same network as the widget with constant, step, cosine and warmup-plus-cosine schedules, at a peak of and at a peak of . It prints the final loss and the wobble: the standard deviation of the loss over the last 50 updates. It runs in about a second. Change the peaks, the warmup length or the final rate, or add an exponential schedule.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the code gives this (on the machine used for this lesson):
peak eta 1.0: final, wobble
constant 0.160 0.017
step 0.193 0.000
cosine 0.164 0.000
warm+cos 0.152 0.000
peak eta 3.0: final, wobble
constant 0.289 0.047
step 0.170 0.000
cosine 0.152 0.000
warm+cos 0.193 0.001
What to notice, and what not to conclude:
- A constant rate keeps wobbling. At its last 50 losses spread with a standard deviation of , and every decayed schedule has or less.
- The best schedule depends on the peak. At warmup plus cosine is lowest and the four finals lie within . At cosine is lowest, and warmup plus cosine ends behind step decay.
- These are one seed on a small made-up problem. The gap between and says how the rules behave here, not which one wins on a real network.
Check your understanding
In the one-parameter noise model, the rate is cut from to . What happens to the spread of the parameter around the minimum once it has settled?
The spread is , so it falls with the square root of . A tenfold fall would need the variance to be proportional to . The gradient noise is the same, but each step passes on less of it, because the step is multiplied by .
Which statement about warmup is best supported?
Goyal and others found that a sudden jump after a low rate could make the large-batch training error spike, and a gradual ramp avoided it. In the widget the small network does not need warmup at all: at a peak of it only delays the first progress. Warmup does not replace decay, since the two address different ends of training.
A cosine schedule has peak , final rate and . What is the rate at ?
At the cosine term is , so the rate is . The value is the start, is the end, and is what you would get by halving twice.
In a range test the loss is lowest at . Which peak rate is the better choice for the training run?
During the sweep the rate rises at every update, so the loss at a rate has had little time to settle. A rate that looks best there is often too big for a long run, and in the widget a constant already ends with a large wobble. A rate at the bottom of the sweep is safe but so slow that the loss has barely moved.
A training loop calls scheduler.step() before optimizer.step(). What does PyTorch warn about?
PyTorch warns that calling the scheduler first skips the first value of the schedule, so update 0 already uses the value meant for update 1. It does not zero the rate, change the optimizer or touch the gradients.
Exercises
- A step schedule has and drops by every updates. What is the rate at update ?
Show answer
drops, so . - A cosine schedule has peak , final rate and . What is the rate at ?
Show answer
, the value in the table above. - A warmup lasts updates to a peak of , with the rule . What is the rate at update , and at update ?
Show answer
At update : . At update : , the peak. - For the original transformer schedule with warmup updates, how does the rate at update compare with the peak?
Show answer
After the peak the rate is proportional to , so at four times the update number it is of the peak. - An exponential schedule should go from to in updates by multiplying by the same factor at each update. What is ?
Show answer
, so . - A model trains for 10 epochs of 500 batches.
StepLR(step_size=3)is meant to drop the rate every 3 epochs. After how many updates does the first drop happen ifscheduler.step()is called once per batch by mistake, and what was intended?Show answer
Called per batch, the first drop comes after 3 updates, since the scheduler counts calls. The intended drop was after 3 epochs, which is updates. Call it once per epoch, or usestep_size=1500with per-update calls.
Next: P4.15 looks at batch size and how it interacts with the learning rate, P4.22 uses loss curves to diagnose training, and P4.23 searches over hyperparameters, starting with the learning rate.