TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Learning-Rate Schedules and Warm-Up

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 η\eta 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 w←w−η(∇L+ξ)\mathbf{w} \leftarrow \mathbf{w} - \eta(\nabla L + \boldsymbol{\xi}), where ξ\boldsymbol{\xi} is the batch noise (Batch Size, Iterations and Epochs). Even at the minimum, where ∇L=0\nabla L = 0, the noise term moves the weights by about η∥ξ∥\eta \lVert \boldsymbol{\xi} \rVert per step. With a constant η\eta the iterates therefore wander in a cloud around the minimum whose size grows with η\eta, and the loss stalls at a floor above the optimum. Shrinking η\eta shrinks the cloud. Stochastic-approximation theory makes this precise: SGD converges when ∑tηt=∞\sum_t \eta_t = \infty (you can still travel any distance) and ∑tηt2<∞\sum_t \eta_t^2 < \infty (the noise adds up to something finite), for example ηt∝1/t\eta_t \propto 1/t (SGD Convergence, Learning-Rate Schedules and Clipping).

The common schedules

With peak rate η0\eta_0, EE epochs and ee the current epoch (counted from 0):

Schedule Formula Typical use
constant ηe=η0\eta_e = \eta_0 baselines, short fine-tunes with Adam
step decay ηe=η0⋅γ⌊e/s⌋\eta_e = \eta_0 \cdot \gamma^{\lfloor e/s \rfloor}, e.g. γ=0.1\gamma = 0.1 every s=30s = 30 epochs classic CNN recipes (ResNet)
exponential ηe=η0γe\eta_e = \eta_0 \gamma^e older recipes
cosine ηe=η02(1+cos⁡(πe/E))\eta_e = \frac{\eta_0}{2}\big(1 + \cos(\pi e / E)\big) the modern default
linear warm-up ηe=η0(e+1)/W\eta_e = \eta_0 (e + 1)/W for e<We < W, then any decay over the remaining E−WE - W 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 γ\gamma 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 L∗=0.05+1.2ηL^* = 0.05 + 1.2\eta 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 η0\eta_0 with the constant schedule (slow, but a low floor), then a large one.

0.000.050.10020406080100ηLearning rate η per epoch012020406080100epochlossLoss (toy model, not real training)Schedulesconstantstepcosinewarm-up + cosineIllustrative only:the loss is a toyformula, not realtraining.Final loss (toy model)constant: 0.170step: 0.089cosine: 0.074warm-up + cosine: 0.075

The schedules in code

The same four formulas the lab uses, with η0=0.1\eta_0 = 0.1, 100 epochs, step decay every 30 epochs and a 5-epoch warm-up:

python · try it yourself
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 η0/2\eta_0/2 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 (B=8B = 8) on a linear regression with noisy targets, 1000 training rows, 30 epochs, η0=0.05\eta_0 = 0.05 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.

python · try it yourself
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 η\eta 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:

text
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 rate

The 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 η0\eta_0 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 EE, so "the first 50 epochs" of a 100-epoch run are not a 50-epoch run.

Practice

  1. Cosine schedule, η0=0.2\eta_0 = 0.2, E=40E = 40. What is η\eta at epochs 10, 20 and 30?
Answer

η=0.1(1+cos⁡(πe/40))\eta = 0.1(1 + \cos(\pi e/40)): at e=10e = 10, 0.1(1+cos⁡(π/4))≈0.17070.1(1 + \cos(\pi/4)) \approx 0.1707; at 20, 0.1(1+0)=0.10.1(1 + 0) = 0.1; at 30, 0.1(1−0.7071)≈0.02930.1(1 - 0.7071) \approx 0.0293.

  1. Step decay with γ=0.5\gamma = 0.5 every 10 epochs, η0=0.08\eta_0 = 0.08. What is the rate at epoch 35?
Answer

⌊35/10⌋=3\lfloor 35/10 \rfloor = 3 halvings: 0.08⋅0.53=0.010.08 \cdot 0.5^3 = 0.01.

  1. 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 η\eta times the noise; only a decaying η\eta removes that.

Test yourself

Why does a decaying learning rate reach a lower loss than a constant one with mini-batch SGD?

  1. It uses fewer epochs
  2. Smaller late steps shrink the cloud of iterates that gradient noise creates around the minimum
  3. It changes the loss function
  4. It increases the batch size

A cosine schedule with peak η0\eta_0 over EE epochs has which value at the midpoint e=E/2e = E/2?

  1. η0\eta_0
  2. η0/2\eta_0/2
  3. 00
  4. η0/10\eta_0/10

What is learning-rate warm-up for?

  1. Lowering the rate at the end of training
  2. Ramping the rate up at the start, so the first steps on random weights and fresh optimizer statistics are not too large
  3. Warming the GPU
  4. 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)?

  1. 0
  2. about 0.0045
  3. about 0.08
  4. about 0.5