Sign in

Schedulers

Learning rate schedules

Functions that set the learning rate for every training step: a warmup at the start, then a decay by step, cosine, linear, exponential, inverse square root or one cycle.

Overview

The best learning rate is not the same throughout training. At the very start the weights are random and the gradient statistics are unreliable, so a large rate can throw the model off: it helps to start small and ramp up. In the middle a large rate covers ground quickly. Near the end a small rate lets the weights settle into a minimum without bouncing around it. A schedule is a formula that gives the rate for each step number. Because it depends only on the step, it can be plotted before training and resumed from any point.

A short history

Decreasing step sizes are part of the 1951 convergence theory of Robbins and Monro. Deep learning first used step decay, cutting the rate at fixed epochs. Ilya Loshchilov and Frank Hutter proposed cosine annealing in 2016. The 2017 Transformer paper by Vaswani and colleagues used linear warmup followed by inverse square root decay, and Leslie Smith proposed the one-cycle policy around the same time. Warmup with cosine decay is now a common default.

How it works

  1. Choose a schedule and set base_lr and total_steps. Steps are counted from 0.
  2. If warmup_steps is positive, the rate rises linearly during those steps and reaches base_lr on the last of them.
  3. After warmup, the chosen shape takes over. Progress is measured from the end of warmup to the last step of the run.
  4. constant holds base_lr. step multiplies the rate by gamma every step_size steps, and exponential applies the same decay smoothly.
  5. linear and cosine move from base_lr down to min_lr by the last step. inverse_sqrt decays in proportion to one over the square root of the step.
  6. one_cycle ignores warmup_steps: it rises along a cosine curve from a low start to max_lr over the first pct_start of the run, then falls along a cosine curve to a rate far below the start.
  7. In the training loop, call step once per optimizer update and use the returned rate. lr_at gives the rate for any step without changing state.

Watch out for

  • Cosine, linear and one-cycle depend on total_steps. If the run is shortened or extended without updating it, the rate ends too high or sits at its floor for the extra steps.
  • Counting epochs where the schedule expects optimizer steps, or the reverse, stretches or compresses the whole curve by a large factor.
  • No warmup with an adaptive optimizer and a large rate can cause divergence in the first few hundred steps, before the gradient statistics have settled.
  • When resuming from a checkpoint, the step counter must be restored with load_state_dict. Otherwise the schedule restarts from warmup and the rate jumps.
  • With step decay, a gamma of 0.1 cuts the rate tenfold at once. If the drop comes too early the model freezes before it has learned enough.

Use cases

When to use it

In almost every deep learning run. Warmup followed by cosine or linear decay is the standard choice for transformers, step decay is traditional for convolutional networks, and one-cycle suits short runs on a fixed budget.

In industry

Language models
Transformer training almost always starts with a warmup of some thousand steps and then decays the rate, by cosine, linear or inverse square root.
Computer vision
ResNet training on ImageNet classically divided the rate by 10 at set epochs, and many newer recipes use cosine decay.
Fine-tuning
Pretrained models are fine-tuned with a short warmup and linear decay to zero, which protects the pretrained weights early on.

Choosing it: what must hold

  • A known or planned total number of training steps, which most decay shapes need.
  • A peak learning rate already tuned for the optimizer and batch size.
  • Warmup when using adaptive optimizers or large batches, where early steps are unstable.
  • The schedule stepped once per optimizer step or per epoch, as the chosen shape expects.

When to choose something else

IfUse instead
The length of training is not known in advanceA constant rate after warmup, or reduce the rate when validation loss stops improving
You want to use weights from late training without decaying to zeroA constant or cyclical rate with stochastic weight averaging
Loss spikes persist even with warmupGradient clipping

Math foundations

  1. Linear warmup

    ηs=ηbase s+1W,0≤s<W\eta_s = \eta_{\text{base}}\,\frac{s + 1}{W}, \qquad 0 \le s < W

    The rate climbs in equal steps and reaches the base rate at step W−1W - 1. Small early steps protect the freshly initialised weights.

  2. Progress after warmup

    t=s−W,p=min⁡ ⁣(tT−1−W, 1)t = s - W, \qquad p = \min\!\left(\frac{t}{T - 1 - W},\ 1\right)

    tt counts the steps since warmup ended and pp runs from 0 at the end of warmup to 1 at the last step of the run. Steps past the end keep p=1p = 1.

  3. Cosine decay

    η=ηmin⁡+12 (ηbase−ηmin⁡) (1+cos⁡(πp))\eta = \eta_{\min} + \tfrac{1}{2}\,(\eta_{\text{base}} - \eta_{\min})\,\big(1 + \cos(\pi p)\big)

    Half a cosine wave from the base rate down to the minimum. It falls slowly at first, fastest in the middle and slowly again at the end.

  4. Linear decay

    η=ηbase+(ηmin⁡−ηbase) p\eta = \eta_{\text{base}} + (\eta_{\min} - \eta_{\text{base}})\,p

    A straight line from the base rate to the minimum. The rate drops by the same amount every step.

  5. Step and exponential decay

    η=ηbase γ⌊t/S⌋andη=ηbase γ t/S\eta = \eta_{\text{base}}\,\gamma^{\lfloor t / S \rfloor} \qquad \text{and} \qquad \eta = \eta_{\text{base}}\,\gamma^{\,t / S}

    Both multiply the rate by γ\gamma for every SS steps. The first does it in sudden drops and the second spreads the same decay evenly over the steps.

  6. Inverse square root

    η=ηbase W′W′+t,W′=max⁡(W,1)\eta = \eta_{\text{base}}\,\sqrt{\frac{W'}{W' + t}}, \qquad W' = \max(W, 1)

    Equal to the base rate when warmup ends, then proportional to one over the square root of the step. It never reaches zero, so it needs no fixed run length. This is the schedule of the original Transformer.

  7. One cycle

    ηstart=ηmax⁡d,ηend=ηstartdf\eta_{\text{start}} = \frac{\eta_{\max}}{d}, \qquad \eta_{\text{end}} = \frac{\eta_{\text{start}}}{d_f}

    The rate rises along a half cosine from ηstart\eta_{\text{start}} to ηmax⁡\eta_{\max}, then falls along another half cosine to ηend\eta_{\text{end}}. With the defaults the start is 25 times below the peak and the end 10000 times below the start.

Symbols

ss
the training step, counted from 0
η, ηs\eta,\ \eta_s
the learning rate, and the rate at step s
ηbase, ηmin⁡\eta_{\text{base}},\ \eta_{\min}
base_lr and min_lr
W, TW,\ T
warmup_steps and total_steps
t, pt,\ p
steps since the end of warmup, and progress from 0 to 1
γ, S\gamma,\ S
the decay factor gamma and the period step_size
ηmax⁡\eta_{\max}
max_lr, the peak rate of one_cycle
d, dfd,\ d_f
div_factor and final_div_factor

Worked by hand

Use the cosine schedule with ηbase=0.001\eta_{\text{base}} = 0.001, ηmin⁡=0\eta_{\min} = 0, W=10W = 10 warmup steps and T=111T = 111 total steps, so T−1−W=100T - 1 - W = 100. Find the rate at steps 4, 9, 35, 60 and 110.

η4=0.001×510=0.0005,η9=0.001×1010=0.001\eta_4 = 0.001 \times \frac{5}{10} = 0.0005, \qquad \eta_9 = 0.001 \times \frac{10}{10} = 0.001
s=35:p=25100,η=0.0005 (1+cos⁡π4)=0.0005×1.7071≈0.000854s = 35: \quad p = \frac{25}{100}, \quad \eta = 0.0005\,\big(1 + \cos\tfrac{\pi}{4}\big) = 0.0005 \times 1.7071 \approx 0.000854
s=60:p=50100,η=0.0005 (1+cos⁡π2)=0.0005s = 60: \quad p = \frac{50}{100}, \quad \eta = 0.0005\,\big(1 + \cos\tfrac{\pi}{2}\big) = 0.0005
s=110:p=1,η=0.0005 (1+cos⁡π)=0s = 110: \quad p = 1, \quad \eta = 0.0005\,(1 + \cos \pi) = 0

The rate climbs to 0.001 by step 9. A quarter of the way through the decay it is still at 85 percent of the base rate, at the halfway point it is exactly half, and it reaches 0 on the last step.

Visual example

Loading the example.

Try this

  • Lengthen the warm-up and watch the peak move.
  • Switch schedules: the area under the line is how far the weights can travel.

Code sample

import numpy as np
from impl import LRScheduler
from config import LRSchedulerConfig

sched = LRScheduler(LRSchedulerConfig(schedule="cosine", base_lr=0.1, total_steps=100, warmup_steps=10))
w = np.array([5.0])                      # minimise f(w) = w^2 with gradient descent
for _ in range(100):
    lr = sched.step()                    # rate for this update
    w -= lr * 2.0 * w
print(sched.lr_at(9), sched.lr_at(99))   # 0.1 at the end of warmup, 0.0 at the end
Read the implementation (88 lines)
"""Learning-rate schedules: constant, step, exponential, linear, cosine, inverse square root and one-cycle,
all with optional linear warmup.

Standard library and NumPy only. A schedule is a pure function of the step number (`lr_at`), so it can be
plotted, tested and resumed from any step. `step` is the stateful convenience used inside a training loop.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import LRSchedulerConfig
except ImportError:  # run from the template's own folder
    from config import LRSchedulerConfig


def _cosine(start: float, end: float, progress: float) -> float:
    """Half-cosine from `start` (progress 0) to `end` (progress 1)."""
    return end + 0.5 * (start - end) * (1.0 + math.cos(math.pi * progress))


class LRScheduler:
    """Gives the learning rate for every training step."""

    def __init__(self, config: LRSchedulerConfig | None = None) -> None:
        self.config = config or LRSchedulerConfig()
        self.step_count = 0  # number of calls to `step` so far
        self.last_lr = self.lr_at(0)

    def lr_at(self, step: int) -> float:
        """Learning rate for the given 0-based step. Steps past `total_steps` keep the final behaviour."""
        cfg = self.config
        if step < 0:
            raise ValueError("step must be >= 0")
        if cfg.schedule == "one_cycle":
            return self._one_cycle(step)
        if step < cfg.warmup_steps:
            return cfg.base_lr * (step + 1) / cfg.warmup_steps
        t = step - cfg.warmup_steps  # steps since the end of warmup
        horizon = max(cfg.total_steps - 1 - cfg.warmup_steps, 1)  # t at the last step of the run
        progress = min(t / horizon, 1.0)
        if cfg.schedule == "constant":
            return cfg.base_lr
        if cfg.schedule == "step":
            return cfg.base_lr * cfg.gamma ** (t // cfg.step_size)
        if cfg.schedule == "exponential":
            return cfg.base_lr * cfg.gamma ** (t / cfg.step_size)
        if cfg.schedule == "linear":
            return cfg.base_lr + (cfg.min_lr - cfg.base_lr) * progress
        if cfg.schedule == "cosine":
            return _cosine(cfg.base_lr, cfg.min_lr, progress)
        # inverse_sqrt: equal to base_lr at the end of warmup, then proportional to 1 / sqrt(step)
        offset = max(cfg.warmup_steps, 1)
        return cfg.base_lr * math.sqrt(offset / (offset + t))

    def _one_cycle(self, step: int) -> float:
        """Cosine rise from max_lr / div_factor to max_lr, then cosine fall to start / final_div_factor."""
        cfg = self.config
        start = cfg.max_lr / cfg.div_factor
        end = start / cfg.final_div_factor
        peak_step = max(cfg.pct_start * cfg.total_steps - 1.0, 0.0)
        last_step = max(cfg.total_steps - 1, 1)
        if step <= peak_step and peak_step > 0:
            return _cosine(start, cfg.max_lr, step / peak_step)
        progress = min((step - peak_step) / max(last_step - peak_step, 1e-12), 1.0)
        return _cosine(cfg.max_lr, end, progress)

    def step(self) -> float:
        """Return the rate for the current step and advance the counter. Call once per optimizer update."""
        self.last_lr = self.lr_at(self.step_count)
        self.step_count += 1
        return self.last_lr

    def schedule(self, n_steps: int | None = None) -> np.ndarray:
        """All rates for steps 0..n_steps-1 as an array (n_steps defaults to `total_steps`)."""
        n = self.config.total_steps if n_steps is None else n_steps
        return np.array([self.lr_at(s) for s in range(n)])

    def state_dict(self) -> dict:
        """State needed to resume: the step counter."""
        return {"step_count": self.step_count}

    def load_state_dict(self, state: dict) -> None:
        """Resume from a saved `state_dict`."""
        self.step_count = int(state["step_count"])
        self.last_lr = self.lr_at(max(self.step_count - 1, 0))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

For each of the seven schedules, build an LRScheduler through LRSchedulerConfig with total_steps 1000 and warmup_steps 50, call schedule, and plot the seven curves on one chart. Check that lr_at(49) equals base_lr. Then call step 300 times, save state_dict, load it into a fresh LRScheduler, and confirm that the next call to step returns the same rate as the original would.

Check on learning

  1. Why can a learning rate that works well at step 5000 make training diverge at step 5? What is different about the model at the start?
    A way to think about it

    Think about how reliable the running averages of an adaptive optimizer are after a handful of batches, and how large the gradients of random weights can be.

  2. Cosine and linear decay both go from the base rate to the minimum. Where in the run does cosine spend more time at a high rate, and what might that buy?
    A way to think about it

    Compare the two formulas at a quarter and at three quarters of the way. A high rate explores, a low rate refines.

  3. You planned 10000 steps with cosine decay to zero, then decide to train 5000 more with the same scheduler. What rate do the extra steps get, and what should you have done?
    A way to think about it

    Check what progress is after the planned end. Then think about what the schedule would look like if the total had been 15000 from the start.

  4. Step decay at fixed points often produces a visible sudden drop in the loss right after each cut. Why does lowering the rate make the loss fall at once?
    A way to think about it

    With a large rate the weights bounce around the bottom of a valley at a height set by the step size. Ask what happens to that height when the steps shrink.