Learning-Rate Schedules and Warm-Up
A fixed learning rate forces a compromise. Large steps make fast progress early, but with noisy mini-batch gradients they keep the weights bouncing around the minimum and never settle. Small steps settle, but take forever to get there. A learning-rate schedule changes during training to get both: large while far from the minimum, small at the end. A warm-up adds a short ramp at the very start, because the first steps on random weights are the most fragile. Almost every modern training recipe uses both.
Why decay helps: the noise floor
With mini-batch gradients the update is , where is the batch noise (Batch Size, Iterations and Epochs). Even at the minimum, where , the noise term moves the weights by about per step. With a constant the iterates therefore wander in a cloud around the minimum whose size grows with , and the loss stalls at a floor above the optimum. Shrinking shrinks the cloud. Stochastic-approximation theory makes this precise: SGD converges when (you can still travel any distance) and (the noise adds up to something finite), for example (SGD Convergence, Learning-Rate Schedules and Clipping).
The common schedules
With peak rate , epochs and the current epoch (counted from 0):
| Schedule | Formula | Typical use |
|---|---|---|
| constant | baselines, short fine-tunes with Adam | |
| step decay | , e.g. every epochs | classic CNN recipes (ResNet) |
| exponential | older recipes | |
| cosine | the modern default | |
| linear warm-up | for , then any decay over the remaining epochs | transformers, large batches, Adam |
| one-cycle | warm up to a high peak, then anneal to almost zero | fast training of CNNs |
| reduce on plateau | multiply by when the validation loss stops improving | when the length of training is unknown |
Schedules can be applied per epoch (as here) or per step; per step is smoother and is what transformer recipes do.
The lab
The lab draws the four main schedules and a loss driven by them. The loss is an illustrative toy formula, not real training (it relaxes towards a floor that grows with the step size, as the lab says on screen), but it shows the pattern just described: the constant rate makes the fastest start and ends highest; the decaying schedules end lower. Try a small with the constant schedule (slow, but a low floor), then a large one.
The schedules in code
The same four formulas the lab uses, with , 100 epochs, step decay every 30 epochs and a 5-epoch warm-up:
import math
def lr_at(kind, e, lr0=0.1, E=100, every=30, W=5):
if kind == "constant":
return lr0
if kind == "step": # x0.1 every `every` epochs
return lr0 * 0.1 ** (e // every)
if kind == "cosine":
return lr0 * 0.5 * (1 + math.cos(math.pi * e / E))
if e < W: # warm-up: linear ramp to lr0
return lr0 * (e + 1) / W
return lr0 * 0.5 * (1 + math.cos(math.pi * (e - W) / (E - W)))
epochs = [0, 2, 4, 5, 29, 30, 50, 60, 90, 99]
print("epoch " + "".join(f"{e:>8d}" for e in epochs))
for kind in ["constant", "step", "cosine", "warmup+cos"]:
print(f"{kind:10s} " + "".join(f"{lr_at(kind, e):8.4f}" for e in epochs))epoch 0 2 4 5 29 30 50 60 90 99
constant 0.1000 0.1000 0.1000 0.1000 0.1000 0.1000 0.1000 0.1000 0.1000 0.1000
step 0.1000 0.1000 0.1000 0.1000 0.1000 0.0100 0.0100 0.0010 0.0001 0.0001
cosine 0.1000 0.0999 0.0996 0.0994 0.0806 0.0794 0.0500 0.0345 0.0024 0.0000
warmup+cos 0.0200 0.0600 0.1000 0.1000 0.0851 0.0839 0.0541 0.0377 0.0027 0.0000
Cosine stays high for a long time (still 0.08 after 30 % of training), passes at the midpoint and spends the last tenth of training at almost zero. Step decay makes the same journey in jumps.
A real run: constant versus decaying
Mini-batch SGD () on a linear regression with noisy targets, 1000 training rows, 30 epochs, for every schedule. Linear regression has an exact optimum (least squares), so the code can report how far each run is from it: the excess training MSE.
import math
import numpy as np
from sklearn.datasets import make_regression
X, y = make_regression(n_samples=1200, n_features=20, noise=60.0, random_state=0)
y = y / y.std() # targets of unit scale
X_tr, y_tr, X_val, y_val = X[:1000], y[:1000], X[1000:], y[1000:]
def lr_at(kind, e, lr0, E, every=10, W=3):
if kind == "constant": return lr0
if kind == "step": return lr0 * 0.1 ** (e // every)
if kind == "cosine": return lr0 * 0.5 * (1 + math.cos(math.pi * e / E))
if e < W: return lr0 * (e + 1) / W
return lr0 * 0.5 * (1 + math.cos(math.pi * (e - W) / (E - W)))
def train(kind, lr0=0.05, E=30, B=8):
rng = np.random.default_rng(0)
w = np.zeros(20)
for e in range(E):
lr = lr_at(kind, e, lr0, E) # one learning rate per epoch
order = rng.permutation(len(y_tr))
for s in range(0, len(y_tr), B):
idx = order[s:s + B]
w -= lr * X_tr[idx].T @ (X_tr[idx] @ w - y_tr[idx]) / len(idx)
return np.mean((X_tr @ w - y_tr) ** 2), np.mean((X_val @ w - y_val) ** 2)
w_best = np.linalg.lstsq(X_tr, y_tr, rcond=None)[0]
best_tr = np.mean((X_tr @ w_best - y_tr) ** 2)
print(f"least squares (the optimum): train MSE {best_tr:.4f} val MSE {np.mean((X_val @ w_best - y_val) ** 2):.4f}")
for kind in ["constant", "step", "cosine", "warmup+cos"]:
tr, va = train(kind)
print(f"{kind:10s} excess train MSE {tr - best_tr:.5f} val MSE {va:.4f}")least squares (the optimum): train MSE 0.0856 val MSE 0.0786
constant excess train MSE 0.00452 val MSE 0.0821
step excess train MSE 0.00001 val MSE 0.0786
cosine excess train MSE 0.00000 val MSE 0.0788
warmup+cos excess train MSE 0.00000 val MSE 0.0788
The constant rate stalls about 0.0045 above the optimum, roughly 5 % of the training MSE: that is the noise floor. All three decaying schedules reach the least-squares solution, and their validation MSE (0.0786 to 0.0788) matches it. The constant run's validation MSE is worse too, 0.0821. Warm-up changes nothing here: this problem is convex and the weights start at zero, so the first steps are harmless.
Why warm-up
Warm-up matters for deep networks, especially transformers trained with Adam. At the start the weights are random, the gradients are large and erratic, and Adam's second-moment estimate is built from only a few steps, so its per-parameter step sizes are unreliable. A full-size step then can push the network into a bad region (activations saturate, the loss spikes, sometimes it never recovers). Ramping up over the first few hundred or thousand steps lets the statistics and the network settle. With the linear scaling rule for large batches, warm-up is what makes the large peak rate usable. Typical length: 1 to 10 % of training.
In PyTorch
torch.optim.lr_scheduler has StepLR, ExponentialLR, CosineAnnealingLR, OneCycleLR, LinearLR (for warm-up), SequentialLR (to chain warm-up and decay) and ReduceLROnPlateau. The pattern is one call per step or per epoch, after the optimizer step:
sched = CosineAnnealingLR(opt, T_max=num_epochs)
for epoch in range(num_epochs):
train_one_epoch(model, opt) # calls opt.step() for every batch
sched.step() # then update the learning rateThe scheduler's state belongs in the checkpoint, or a resumed run restarts the schedule.
Pitfalls
- Calling
sched.step()per batch when the schedule was sized in epochs (or the reverse): the decay finishes after a fraction of an epoch, or never. - Combining a schedule with early stopping that stops before the low-rate phase: the best part of cosine is its end.
- Tuning the peak rate with one schedule and training with another. The best for cosine is usually higher than for a constant rate.
- Comparing models trained with different numbers of epochs but the same cosine schedule length: the schedule depends on , so "the first 50 epochs" of a 100-epoch run are not a 50-epoch run.
Practice
- Cosine schedule, , . What is at epochs 10, 20 and 30?
Answer
: at , ; at 20, ; at 30, .
- Step decay with every 10 epochs, . What is the rate at epoch 35?
Answer
halvings: .
- Why does a constant learning rate leave the loss above the optimum in the noisy run, but not with full-batch gradient descent on the same convex problem?
Answer
With full batches the gradient is exact and vanishes at the minimum, so the steps shrink to zero by themselves. With mini-batches the gradient noise does not vanish at the minimum, so each step keeps moving the weights by about times the noise; only a decaying removes that.
Test yourself
Why does a decaying learning rate reach a lower loss than a constant one with mini-batch SGD?
- It uses fewer epochs
- Smaller late steps shrink the cloud of iterates that gradient noise creates around the minimum
- It changes the loss function
- It increases the batch size
A cosine schedule with peak over epochs has which value at the midpoint ?
What is learning-rate warm-up for?
- Lowering the rate at the end of training
- Ramping the rate up at the start, so the first steps on random weights and fresh optimizer statistics are not too large
- Warming the GPU
- Reducing the number of parameters
In the regression run, how far above the least-squares optimum did the constant learning rate stall (excess training MSE)?
- 0
- about 0.0045
- about 0.08
- about 0.5