Equations · Loshchilov and Hutter, “SGDR: Stochastic Gradient Descent with Warm Restarts” (2017)

The cosine learning-rate schedule, explained

The learning rate starts at ηmax⁡\eta_{\max} and follows half a cosine wave down to ηmin⁡\eta_{\min}: slow decline at first, faster in the middle, and a gentle landing. Most LLM training uses it, usually after a short linear warmup and without the restarts.

ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡(TcurTiπ))\eta_t = \eta_{\min} + \frac{1}{2}\left(\eta_{\max} - \eta_{\min}\right)\left(1 + \cos\left(\frac{T_{\mathrm{cur}}}{T_{i}}\pi\right)\right)

Open in the decoder →

Term by term

  1. ηt\eta_t

    The learning rate used at step (or epoch) tt.

  2. ηmin⁡, ηmax⁡\eta_{\min}, \ \eta_{\max}

    The lowest and highest learning rates. Here min⁡\min and max⁡\max are labels in subscripts, not operations.

  3. TcurTi\frac{T_{\mathrm{cur}}}{T_{i}}

    How far through the current cycle training is, from 0 to 1. TiT_i is the cycle's length; in SGDR, TcurT_{\mathrm{cur}} resets to 0 at each "warm restart". Without restarts, it is simply step / total steps.

  4. 12(1+cos⁡(…π))\frac{1}{2}\left(1 + \cos(\ldots\pi)\right)

    As the angle goes from 0 to π\pi, cos⁡\cos goes from 1 to −1-1, so this factor goes smoothly from 1 to 0.

A small worked example

ηmax⁡=0.001\eta_{\max} = 0.001, ηmin⁡=0\eta_{\min} = 0, 1000 steps. At step 0: 0.0010.001. At step 250: 0.0005×(1+cos⁡(π/4))≈0.0008540.0005 \times (1 + \cos(\pi/4)) \approx 0.000854. At step 500: cos⁡(π/2)=0\cos(\pi/2) = 0, so 0.00050.0005. At step 1000: 00.

In code

import math

def cosine_lr(step, total, lr_max, lr_min=0.0):
    return lr_min + 0.5 * (lr_max - lr_min) * (1 + math.cos(math.pi * step / total))

# PyTorch: torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=total, eta_min=lr_min)

Every symbol in it

η\etaEtaxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)max⁡(0,x)\max(0, x)Max and minab\frac{a}{b}Fractioncos⁡(u,v)=u⊤v∥u∥ ∥v∥\cos(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u}^\top \mathbf{v}}{\|\mathbf{u}\| \, \|\mathbf{v}\|}Cosineπθ(a∣s)\pi_\theta(a \mid s)Pi

Other equations