Deep learning in practice · lesson 4 of 13
Parts in this lesson
Alr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)a cosine schedule over the whole run
Blr_scheduler.SequentialLR(optimizer, [warm, cos], milestones=[3])three epochs of warm-up, then the cosine
Cscheduler.step()once per epoch, after the epoch’s optimizer.step() calls
Doptimizer.param_groups[0]["lr"]the learning rate the optimiser is using now

Learning rate schedules

Last updated

The learning rate is the setting that matters most, and the best value changes as training goes on: big steps help early, when the weights are far from anywhere good, and small steps help late, to settle into a minimum. This lesson finds a good starting rate with a quick test, then lowers it on a schedule: in steps, along a cosine, and after a short warm-up.

By the end of this lesson you can

  • Find a good learning rate with the range test
  • Lower the learning rate during training with step decay or a cosine schedule
  • Add a warm-up, and say when it helps
  • Step a PyTorch scheduler at the right moment

The learning rate range test

Training once at each of a dozen learning rates would find a good one, slowly. The range test (Smith, 2017) does it in one short run: start tiny, multiply the rate a little after every batch, and record the loss. While the rate is too small, the loss barely moves; in the right range it falls fast; too large, and it blows up.

"""The learning rate range test: raise the learning rate every batch, and watch the loss."""
import math

import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

X, y = load_digits(return_X_y=True)
data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y))
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
loader = DataLoader(data, batch_size=32, shuffle=True)

lowest, highest, n = 1e-4, 10.0, 100             # 100 batches, from 0.0001 up to 10
factor = (highest / lowest) ** (1 / (n - 1))
smooth, best, results = None, math.inf, []
step = 0
while step < n:
    for xb, yb in loader:
        if step == n:
            break
        lr = lowest * factor ** step
        for group in optimizer.param_groups:
            group["lr"] = lr
        loss = nn.functional.cross_entropy(model(xb), yb)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        smooth = loss.item() if smooth is None else 0.8 * smooth + 0.2 * loss.item()   # an average of recent losses
        results.append((lr, smooth))
        step += 1
        if smooth > 4 * min(s for _, s in results):     # it's blown up: stop
            step = n

for lr, s in results[::10]:
    print(f"lr {lr:8.4f}   loss {s:.3f}")
lr_best, s_best = min(results, key=lambda r: r[1])
print(f"lowest loss {s_best:.3f} at lr {lr_best:.3f}; stopped at lr {results[-1][0]:.3f}")
Terminal, in ml-local/7-4
(.venv) $ python range_test.py
lr   0.0001   loss 2.317
lr   0.0003   loss 2.317
lr   0.0010   loss 2.327
lr   0.0033   loss 2.317
lr   0.0105   loss 2.303
lr   0.0335   loss 2.235
lr   0.1072   loss 2.058
lr   0.3430   loss 1.228
lr   1.0975   loss 1.301
lowest loss 0.925 at lr 0.546; stopped at lr 1.963

Up to about 0.01, nothing happens: the loss stays near 2.3, a uniform guess. It falls fastest between about 0.1 and 0.3, is lowest near 0.55, and by about 2 it's blowing up. The rule of thumb is to take a rate where the loss is still falling steeply, about a fifth to a tenth of where it was lowest: 0.05 to 0.1. Not the lowest point itself, because that's already where training is about to become unstable.

The loss here is smoothed, an average that leans on the last few batches, because single batches are noisy. It costs 100 batches, under 2 epochs.

Step decay

A fixed rate has to compromise: big enough to make progress early, small enough to settle late. The oldest fix is step decay: multiply the rate by a factor, often 0.1, every few epochs. StepLR(optimizer, step_size=8, gamma=0.1) does it every 8 epochs.

A scheduler wraps the optimiser and changes its learning rate when you call scheduler.step(). Call it once per epoch, after that epoch's optimizer.step() calls. Here are four schedules, each driving the same training run, at two peak rates:

"""Four schedules driving the same training run on the digits: what each does to the learning rate, and the result."""
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from torch.optim import lr_scheduler

X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X / 16, y, test_size=0.25, random_state=0, stratify=y)
train_set = TensorDataset(torch.tensor(X_train, dtype=torch.float32), torch.tensor(y_train))
X_val, y_val = torch.tensor(X_val, dtype=torch.float32), torch.tensor(y_val)
EPOCHS = 20


def schedule(name, optimizer):
    if name == "constant":
        return lr_scheduler.LambdaLR(optimizer, lambda epoch: 1.0)
    if name == "step":
        return lr_scheduler.StepLR(optimizer, step_size=8, gamma=0.1)        # × 0.1 every 8 epochs
    if name == "cosine":
        return lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
    if name == "warm-up + cosine":
        warm = lr_scheduler.LinearLR(optimizer, start_factor=0.1, total_iters=3)
        cos = lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS - 3)
        return lr_scheduler.SequentialLR(optimizer, [warm, cos], milestones=[3])


def train(name, peak):
    torch.manual_seed(0)
    model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
    optimizer = torch.optim.SGD(model.parameters(), lr=peak, momentum=0.9)
    scheduler = schedule(name, optimizer)
    loader = DataLoader(train_set, batch_size=32, shuffle=True)
    lrs = []
    for epoch in range(EPOCHS):
        lrs.append(optimizer.param_groups[0]["lr"])
        model.train()
        for xb, yb in loader:
            loss = nn.functional.cross_entropy(model(xb), yb)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        scheduler.step()                         # once per epoch, after the epoch's steps
    model.eval()
    with torch.no_grad():
        accuracy = (model(X_val).argmax(dim=1) == y_val).float().mean().item()
    return lrs, accuracy


for peak in (0.1, 0.5):
    print(f"peak learning rate {peak}")
    for name in ("constant", "step", "cosine", "warm-up + cosine"):
        lrs, accuracy = train(name, peak)
        shown = " ".join(f"{lr:.3f}" for lr in lrs[::4])
        print(f"  {name:17} lr at epochs 0, 4, 8, 12, 16: {shown}   validation {accuracy:.3f}")
Terminal, in ml-local/7-4
(.venv) $ python schedules.py
peak learning rate 0.1
  constant          lr at epochs 0, 4, 8, 12, 16: 0.100 0.100 0.100 0.100 0.100   validation 0.976
  step              lr at epochs 0, 4, 8, 12, 16: 0.100 0.100 0.010 0.010 0.001   validation 0.973
  cosine            lr at epochs 0, 4, 8, 12, 16: 0.100 0.090 0.065 0.035 0.010   validation 0.971
  warm-up + cosine  lr at epochs 0, 4, 8, 12, 16: 0.010 0.099 0.080 0.045 0.013   validation 0.973
peak learning rate 0.5
  constant          lr at epochs 0, 4, 8, 12, 16: 0.500 0.500 0.500 0.500 0.500   validation 0.196
  step              lr at epochs 0, 4, 8, 12, 16: 0.500 0.500 0.050 0.050 0.005   validation 0.309
  cosine            lr at epochs 0, 4, 8, 12, 16: 0.500 0.452 0.327 0.173 0.048   validation 0.678
  warm-up + cosine  lr at epochs 0, 4, 8, 12, 16: 0.050 0.496 0.401 0.227 0.065   validation 0.844
Schedule plotterthe learning rate in each of 20 epochs, and where each run ended
0.50epoch 019constantvalidation 0.196stepvalidation 0.309cosinevalidation 0.678warm-up + cosinevalidation 0.844

At 0.5, past the range test's safe zone, a constant rate never settles. Lowering the rate rescues the run, and the warm-up, three gentle epochs before the full rate, rescues it most.

Cosine

Step decay has abrupt drops, and two settings to choose. The cosine schedule (Loshchilov and Hutter, 2017) glides from the peak ηmax⁡ to a floor ηmin⁡ along half a cosine wave over T epochs:

ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡πtT).

At t=0 the cosine is 1, so η0=ηmax⁡; at t=T it's −1, so ηT=ηmin⁡. It stays high for longer than a straight line would, then falls fastest in the middle and flattens out at the end. Its only setting is T, the length of the run. CosineAnnealingLR(optimizer, T_max=EPOCHS) uses ηmin⁡=0 unless you set eta_min.

Compare the two halves of the table:

  • At a peak of 0.1, the rate the range test suggested, every schedule lands at 97.1–97.6%. The constant rate is even a little ahead. On a small, easy problem with a well-chosen rate, a schedule has little to add.
  • At 0.5, too high, the constant rate never settles: 19.6%. Lowering it rescues the run, and the smoother the fall, the better: step decay 30.9%, cosine 67.8%.

Schedules earn their keep on long runs and large models, where the end of training is a long, slow settle. Cosine is the common default.

Warm-up

At 0.5, the best schedule of all was warm-up plus cosine: 84.4%. For the first 3 epochs, the rate climbs from a tenth of the peak to the peak (LinearLR), and only then does the cosine begin (SequentialLR joins them at epoch 3).

Why it helps: at the very start the weights are random, so the gradients are big and point in unreliable directions, and with Adam the running averages of lesson 7.3 haven't settled yet. A full-size step then can throw the weights somewhere they never recover from, as Adam at 1 did in lesson 7.3. A few small steps first get the weights somewhere sensible. Warm-up matters most with large learning rates, large batches (Goyal and others, 2017) and transformers (Stage 10).

The warm-up didn't make 0.5 a good rate: 84.4% is far below the 97% that 0.1 reached without any schedule. Find the rate first; a schedule is a refinement, not a rescue.

Wrong way: stepping the schedule every batch

T_max=20 means 20 calls of scheduler.step(). Meant as epochs, called every batch:

"""The wrong way: a schedule set up in epochs, stepped every batch."""
import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from torch.optim import lr_scheduler

X, y = load_digits(return_X_y=True)
data = TensorDataset(torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y))
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
optimizer = torch.optim.SGD(model.parameters(), lr=0.5, momentum=0.9)
scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=20)   # meant: 20 epochs
loader = DataLoader(data, batch_size=32, shuffle=True)
print("batches per epoch:", len(loader))

lrs = []
for epoch in range(3):
    for xb, yb in loader:
        loss = nn.functional.cross_entropy(model(xb), yb)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        lrs.append(optimizer.param_groups[0]["lr"])
        scheduler.step()                         # wrong: every batch, not every epoch
print("lr at batches 0, 10, 20, ..., 50:", " ".join(f"{lr:.3f}" for lr in lrs[:60:10]))
Terminal, in ml-local/7-4
(.venv) $ python per_batch.py
batches per epoch: 57
lr at batches 0, 10, 20, ..., 50: 0.500 0.250 0.000 0.250 0.500 0.250

With 57 batches per epoch, the "20-epoch" cosine reaches zero after 20 batches, a third of the first epoch. Then, past its end, the cosine formula keeps going and climbs back up: 0.5 again at batch 40. The rate cycles every 40 batches instead of falling once over the run. Nothing warns you.

The fix is to match the units: call scheduler.step() once per epoch, as in schedules.py, or, to step it every batch, give T_max in batches: T_max=EPOCHS * len(loader). Then print the rate now and then, as these scripts do. Reading optimizer.param_groups[0]["lr"] costs nothing, and it's the only way to see the schedule you really ran.

Check what you learned

In the range test, the smoothed loss is lowest at a learning rate of about 0.55. Which rate do you train with?
What does a cosine schedule with T_max = 20 do over 20 epochs?
At a peak of 0.1, every schedule ended at 97–98%, the constant rate included. What does that tell you?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning