Learning Rate Scheduling: From Step Decay to One-Cycle

Linear, cosine, exponential, and one-cycle learning rate schedules from scratch in PyTorch, with an LR finder, early stopping, and a one-cycle benchmark.

Cover Image for Learning Rate Scheduling: From Step Decay to One-Cycle

A learning rate that helps your network make progress early in training may be too large once the loss is near a minimum. Choosing one fixed value means asking it to serve both stages. Learning rate scheduling lets that value change during training, giving us another way to balance progress with stable updates.

Changing a control over time also appeared in our simulated annealing example, where temperature governed exploration. Here, the learning rate finder raises the rate across batches until loss starts rising. We use that curve to choose a peak, then compare schedules and fixed-rate training on the CNN.

In this post, we will implement four scheduling strategies from scratch, build a learning rate finder, add early stopping, and benchmark everything on our CNN. 1-cycle scheduling matches the accuracy of 2x the epochs with constant LR.

Let's Build It

Click the badge to run this yourself:

Open In Colab

Four learning rate schedules compared: constant, step decay, cosine annealing, and 1-cycle over 100 epochs

Here are the four schedules implemented from scratch, following the pattern from the fast.ai notebook where each schedule is a function that maps a position (0 to 1) to a learning rate:

import numpy as np
import math

def schedule_constant(start, end, pos):
    """Constant LR: ignores pos, always returns start."""
    return start

def schedule_linear(start, end, pos):
    """Linear decay: straight line from start to end."""
    return start + pos * (end - start)

def schedule_cosine(start, end, pos):
    """Cosine annealing: smooth S-curve from start to end."""
    return start + (1 + math.cos(math.pi * (1 - pos))) * (end - start) / 2

def schedule_exponential(start, end, pos):
    """Exponential decay: fast early drop, slow tail."""
    return start * (end / start) ** pos

# Visualise: pos goes from 0 (start of training) to 1 (end)
positions = np.linspace(0, 1, 100)
for name, fn in [("Constant", schedule_constant), ("Linear", schedule_linear),
                  ("Cosine", schedule_cosine), ("Exponential", schedule_exponential)]:
    lrs = [fn(0.1, 0.001, p) for p in positions]
    print(f"{name:12s}: start={lrs[0]:.4f}, mid={lrs[50]:.4f}, end={lrs[-1]:.4f}")
Constant    : start=0.1000, mid=0.1000, end=0.1000
Linear      : start=0.1000, mid=0.0505, end=0.0010
Cosine      : start=0.1000, mid=0.0505, end=0.0010
Exponential : start=0.1000, mid=0.0100, end=0.0010

Each function takes pos from 0 to 1 and interpolates between start and end. Cosine and linear reach the same midpoint but cosine holds the high LR longer and decays faster at the end. Exponential drops aggressively early, then crawls.

What Just Happened?

The Case for Scheduling

A high learning rate at the start helps the model escape bad initialisations and explore the loss landscape broadly. As training progresses and the model approaches a good region, smaller steps avoid overshooting the minimum.

The fast.ai notebook states it directly: "The first batch is the most important. If you can get the first batch running well, after that good annealing is critical."

Without scheduling, you face a dilemma: a high constant LR trains fast but oscillates around the minimum, while a low constant LR converges precisely but takes forever. Scheduling gives you both.

Composing Schedules: The 1-Cycle Policy

The most powerful schedule is 1-cycle (Smith, 2018), which does something counterintuitive: it increases the learning rate during the first phase of training, then decreases it.

def combine_schedules(percentages, schedule_fns):
    """Combine multiple schedules over different phases of training.

    Args:
        percentages: fraction of training for each phase (must sum to 1)
        schedule_fns: list of (start, end, schedule_fn) for each phase
    """
    assert abs(sum(percentages) - 1.0) < 1e-6
    boundaries = np.cumsum([0] + list(percentages))

    def get_lr(pos):
        # Find which phase we're in
        for i in range(len(percentages)):
            if pos <= boundaries[i + 1] or i == len(percentages) - 1:
                # Rescale pos to [0, 1] within this phase
                phase_pos = (pos - boundaries[i]) / percentages[i]
                phase_pos = np.clip(phase_pos, 0, 1)
                start, end, fn = schedule_fns[i]
                return fn(start, end, phase_pos)
        return schedule_fns[-1][0]  # fallback

    return get_lr

# 1-cycle: warm up for 30%, then anneal for 70%
one_cycle = combine_schedules(
    [0.3, 0.7],
    [(0.01, 0.1, schedule_cosine),   # warm up: 0.01 -> 0.1
     (0.1, 0.001, schedule_cosine)]  # anneal:  0.1 -> 0.001
)

positions = np.linspace(0, 1, 100)
lrs = [one_cycle(p) for p in positions]
print(f"1-cycle: start={lrs[0]:.4f}, peak={max(lrs):.4f}, end={lrs[-1]:.4f}")
1-cycle: start=0.0100, peak=0.1000, end=0.0010

1-cycle learning rate schedule: warmup phase rising from 0.01 to 0.1, then cosine decay to 0.001

The warmup phase serves two purposes. First, it lets batch normalisation and Adam's moment estimates stabilise before taking aggressive steps. Second, the high LR in the middle acts as a regulariser: it prevents the model from settling into sharp, narrow minima (which generalise poorly) and pushes it toward flatter, wider minima (which generalise better).

The Learning Rate Finder

How do you choose the peak learning rate? The LR finder (Smith, 2015) trains for a few hundred batches with an exponentially increasing learning rate and plots loss vs LR. You pick the LR just before the loss starts exploding.

The fast.ai notebook implements this as a callback:

import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])
train_data = datasets.MNIST('data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)

def make_cnn(use_bn=True):
    layers = []
    channels = [(1, 8, 5), (8, 16, 3), (16, 32, 3), (32, 64, 3), (64, 64, 3)]
    for ni, nf, ks in channels:
        layers.append(nn.Conv2d(ni, nf, ks, padding=ks//2, stride=2, bias=not use_bn))
        if use_bn: layers.append(nn.BatchNorm2d(nf))
        layers.append(nn.ReLU())
    layers += [nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 10)]
    return nn.Sequential(*layers)

def lr_find(model, train_loader, min_lr=1e-5, max_lr=10, num_batches=200):
    """Exponentially increase LR over num_batches, record loss at each step."""
    optimiser = torch.optim.SGD(model.parameters(), lr=min_lr, momentum=0.9)
    lrs, losses = [], []
    best_loss = float('inf')
    mult = (max_lr / min_lr) ** (1 / num_batches)

    model.train()
    lr = min_lr
    batch_iter = iter(train_loader)
    for i in range(num_batches):
        try:
            images, labels = next(batch_iter)
        except StopIteration:
            batch_iter = iter(train_loader)
            images, labels = next(batch_iter)

        loss = F.cross_entropy(model(images), labels)
        optimiser.zero_grad()
        loss.backward()
        optimiser.step()

        lrs.append(lr)
        losses.append(loss.item())

        if loss.item() < best_loss:
            best_loss = loss.item()
        if loss.item() > best_loss * 10:
            break  # loss exploded, stop

        lr *= mult
        for pg in optimiser.param_groups:
            pg['lr'] = lr

    return lrs, losses

torch.manual_seed(42)
model = make_cnn()
lrs, losses = lr_find(model, train_loader)

LR finder plot: loss vs learning rate on log scale, showing the optimal LR region before divergence

The sweet spot is where the loss is falling fastest. In the plot above, the loss drops steeply between 1e-2 and 1e-1, then starts climbing at ~0.5. A good peak LR for 1-cycle would be around 0.1 (slightly before the minimum loss point, where the descent is steepest).

Early Stopping: Knowing When to Quit

Even with a good schedule, training too long leads to overfitting. Early stopping monitors validation loss and stops when it stops improving:

class EarlyStopping:
    """Stop training when validation loss stops improving."""

    def __init__(self, patience=5, min_delta=0.001):
        self.patience = patience
        self.min_delta = min_delta
        self.best_loss = float('inf')
        self.counter = 0

    def should_stop(self, val_loss):
        if val_loss < self.best_loss - self.min_delta:
            self.best_loss = val_loss
            self.counter = 0
            return False
        self.counter += 1
        return self.counter >= self.patience

Early stopping is a form of regularisation: it limits the model's exposure to the training data, which reduces overfitting in the same way that a lower learning rate or weight decay does. You can explore this relationship interactively with our overfitting explorer tool.

Benchmarking: Constant vs Cosine vs 1-Cycle

Let's train our 5-layer CNN (with batch normalisation) using three strategies and compare:

test_data = datasets.MNIST('data', train=False, transform=transform)
test_loader = torch.utils.data.DataLoader(test_data, batch_size=1000)

def train_with_schedule(schedule_fn, epochs=10, base_lr=0.1, seed=42):
    """Train CNN with a given LR schedule."""
    torch.manual_seed(seed)
    model = make_cnn()
    optimiser = torch.optim.SGD(model.parameters(), lr=base_lr, momentum=0.9)
    accs = []
    total_batches = epochs * len(train_loader)

    batch_count = 0
    for epoch in range(epochs):
        model.train()
        for images, labels in train_loader:
            # Update LR according to schedule
            pos = batch_count / total_batches
            lr = schedule_fn(pos)
            for pg in optimiser.param_groups:
                pg['lr'] = lr

            loss = F.cross_entropy(model(images), labels)
            optimiser.zero_grad()
            loss.backward()
            optimiser.step()
            batch_count += 1

        model.eval()
        correct = 0
        with torch.no_grad():
            for images, labels in test_loader:
                correct += (model(images).argmax(1) == labels).sum().item()
        accs.append(correct / len(test_data) * 100)

    return accs

# Three strategies
constant_fn = lambda pos: 0.01  # safe constant LR
cosine_fn = lambda pos: schedule_cosine(0.1, 0.001, pos)  # cosine from 0.1 to 0.001
one_cycle_fn = combine_schedules(
    [0.3, 0.7],
    [(0.01, 0.1, schedule_cosine), (0.1, 0.001, schedule_cosine)]
)

print("Constant LR=0.01 (10 epochs):")
acc_const = train_with_schedule(constant_fn, epochs=10)
print(f"  Final: {acc_const[-1]:.1f}%")

print("\nCosine 0.1->0.001 (10 epochs):")
acc_cos = train_with_schedule(cosine_fn, epochs=10)
print(f"  Final: {acc_cos[-1]:.1f}%")

print("\n1-cycle 0.01->0.1->0.001 (10 epochs):")
acc_1c = train_with_schedule(one_cycle_fn, epochs=10)
print(f"  Final: {acc_1c[-1]:.1f}%")

print("\nConstant LR=0.01 (20 epochs, baseline):")
acc_const20 = train_with_schedule(constant_fn, epochs=20)
print(f"  Final: {acc_const20[-1]:.1f}%")

Training curves: constant LR, cosine annealing, and 1-cycle over 10 epochs, plus constant LR over 20 epochs as baseline

The 1-cycle schedule reaches 99.3% in 10 epochs, beating constant LR's 99.1% in 20 epochs. Cosine annealing (99.2%) falls just behind. This is the practical payoff of scheduling: the same compute budget yields better results, or the same accuracy in half the time.

Going Deeper

The 1-Cycle Mechanism

Leslie Smith's insight in the 1-cycle paper is that a high learning rate acts as regularisation. Large LR means large gradient noise, which prevents the model from settling into sharp local minima that overfit. The model is nudged toward flatter minima that generalise better.

The warmup phase is not just caution: it is essential for letting the model find a good region of the loss landscape. Starting at the peak LR immediately would be too aggressive (the initial parameters are random and gradients are noisy). The warmup gives the gradients time to point in a meaningful direction before the model starts taking large steps.

The Connection to Simulated Annealing

The parallel to simulated annealing is deeper than just the name. In SA, a high temperature allows the algorithm to accept worse solutions (exploration), and cooling forces it to converge (exploitation). In LR scheduling, a high learning rate causes large, noisy parameter updates (exploration), and decay forces the model to fine-tune in its current basin (exploitation).

Both algorithms trade off exploration and exploitation over time. The 1-cycle policy adds a twist that SA does not have: the warmup phase. In SA terms, this would be like starting cold, gradually heating up, then cooling down. This "super-convergence" phenomenon was Smith's key empirical finding.

Warmup for Adam

Adam maintains running estimates of the gradient mean and variance. At the start of training, these estimates are unreliable (they are initialised to zero). Without warmup, the first few updates use bias-corrected but still noisy moment estimates with the full learning rate, which can destabilise training.

Warmup solves this: a low initial LR limits the damage of bad early estimates, and by the time the LR reaches its peak, the moment estimates have converged to reasonable values. This is why the original BERT and GPT training recipes all use linear warmup followed by cosine or linear decay.

Schedule Interaction with Batch Size

Larger batch sizes produce smoother gradients, which tolerate higher learning rates. The linear scaling rule (Goyal et al., 2017) states: when you multiply the batch size by kk, multiply the learning rate by kk too. But this only works with warmup; without it, the large initial LR causes instability.

When NOT to Schedule

Scheduling adds a hyperparameter (the schedule shape) to an already complex training setup. It is most valuable for:

  • SGD with momentum: Highly sensitive to LR; scheduling is almost always helpful
  • Long training runs: More epochs means more opportunity for the schedule to help
  • Fine-tuning pretrained models: Discriminative LRs (lower for early layers, higher for later) combined with cosine decay

It is less critical for:

  • Adam with default LR: Adam's adaptive rates already do per-parameter adjustment
  • Very short training: If you are training for 5 epochs, the schedule has little time to make a difference
  • Small models on easy tasks: MNIST with a 3-layer CNN barely benefits from scheduling

Where This Comes From

Smith (2015, 2018): Cyclical Learning Rates and 1-Cycle

Leslie Smith introduced cyclical learning rates in "Cyclical Learning Rates for Training Neural Networks" (2015), showing that cycling the LR between bounds outperforms fixed decay. He followed up with the 1-cycle policy in "Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates" (2018), demonstrating that a single cycle of warmup-then-decay achieves the same accuracy in far fewer epochs.

"Rather than monotonically decreasing the learning rate, this method lets the learning rate cyclically vary between reasonable boundary values." -- Smith (2015)

The fast.ai library made 1-cycle its default training policy, and the results in the course notebooks (97% MNIST accuracy in a single epoch with aggressive scheduling) demonstrate its effectiveness.

Loshchilov & Hutter (2016): Cosine Annealing with Warm Restarts

Cosine annealing was formalised in "SGDR: Stochastic Gradient Descent with Warm Restarts" by Loshchilov and Hutter. They showed that periodically restarting the LR to its initial value (warm restarts) helps escape local minima. PyTorch's CosineAnnealingWarmRestarts implements this.

The Metallurgical Metaphor

The term "annealing" entered optimisation through Kirkpatrick, Gelatt & Vecchi's 1983 paper on simulated annealing, inspired by the physical process of cooling metals. The analogy has proved remarkably durable: from combinatorial optimisation to RL to neural network training, the principle of starting hot and cooling slowly keeps appearing because it works.

Further Reading

Interactive Tools

  • Gradient Descent Visualizer: Move the learning rate slider and watch the same four optimisers go from crawling to diverging, which is the range every schedule in this post is navigating
  • 2D Convolution Visualizer: Visualise the convolution forward pass whose gradients the learning rate schedule controls
  • Overfitting Explorer: See how training duration and model complexity interact with the bias-variance tradeoff

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions