AI Logic

Learning Rate Schedulers

Cosine Annealing (SGDR)

Updated:

Learning rate graph for cosine annealing. The horizontal axis is the epoch and the vertical axis is the learning rate. The solid line uses warm restarts: the learning rate jumps back to its maximum at epochs 10, 30 and 70, and the cycle length doubles from 10 to 20, 40 and 80 epochs. The dashed line has no restarts and decays only once over 150 epochs

What is cosine annealing?

Cosine annealing is a learning rate scheduler that lowers the learning rate from a maximum to a minimum following half of a cosine wave. Loshchilov and Hutter proposed it in 2017 as part of SGDR (Stochastic Gradient Descent with Warm Restarts) (ICLR 2017).

The learning rate ηt\eta_t is given by the following formula (Eq. (5) in the paper).

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

Here, ηmax⁡i\eta_{\max}^i and ηmin⁡i\eta_{\min}^i are the maximum and minimum learning rates of the ii-th cycle, TiT_i is the length of that cycle (in epochs), and TcurT_{cur} is the number of epochs elapsed since the cycle started. TcurT_{cur} advances with every mini-batch, so it also takes fractional values such as 0.1 and 0.2.

With ηmax⁡=0.05\eta_{\max} = 0.05, ηmin⁡=0\eta_{\min} = 0 and Ti=10T_i = 10, the values are as follows.

Elapsed epochs TcurT_{cur}02.557.510
Learning rate ηt\eta_t0.0500.0430.0250.0070

The learning rate falls slowly at the beginning and end and quickly in the middle. This realizes the usual pattern, exploring broadly with a large learning rate early on and fine-tuning with a small one at the end, as a smooth curve without discrete steps. Only the maximum, the minimum and the length need to be chosen; unlike step decay, there is no need to decide when and by what factor to lower the rate.

Warm restarts (SGDR)

SGDR repeatedly resets the learning rate to its maximum (a warm restart) and lowers it again once cosine annealing has brought it all the way down. The procedure is as follows.

  1. Choose the length of the first cycle T0T_0 and the factor TmultT_{\mathrm{mult}} by which cycles grow.
  2. Within a cycle, lower the learning rate with Eq. (5).
  3. At the end of a cycle, reset the learning rate to ηmax⁡\eta_{\max} and set the next cycle length to Ti+1=Tmult⋅TiT_{i+1} = T_{\mathrm{mult}} \cdot T_i.

The solid line in the figure at the top is an example with T0=10T_0 = 10 and Tmult=2T_{\mathrm{mult}} = 2: the cycles grow from 10 → 20 → 40 → 80 epochs, and restarts happen at epochs 10, 30 and 70. At a restart, the weights are carried over unchanged and only the learning rate is reset.

The paper aimed for anytime performance: a reasonably good model is available whenever training is stopped. The learning rate is at its minimum at the end of each cycle, so the model there is in good shape. Performance drops temporarily right after a restart, so the paper recommends using the model at the end of the last completed cycle as the result. On image classification with CIFAR-10 and CIFAR-100, the paper reports errors of 3.14% and 16.21% (state of the art at the time) using models obtained with SGDR.

If cycles double in length, as with Tmult=2T_{\mathrm{mult}} = 2, restarts occur at T0×(2k−1)T_0 \times (2^k - 1) (10, 30, 70, 150, ...). Matching the total number of training epochs to one of these boundaries lets training end exactly when the learning rate reaches its minimum.

Comparison with other learning rate schedulers

The table compares cosine annealing with the schedulers it is most often compared with, from the same viewpoints.

SchedulerHow the learning rate decreasesWhat must be set in advanceTypical use
Step decayIn steps at chosen epochsWhen to decay and by what factorTasks with well-established settings, such as image classification with CNNs
Polynomial decayPolynomially toward 0Total steps and the powerSegmentation and similar tasks
Cosine annealingSmoothly along a cosine curveTotal steps, maximum and minimumThe default choice for many tasks
SGDRCosine decay, reset to the maximum every cycleT0T_0, TmultT_{\mathrm{mult}}When intermediate models are useful or the total training time is not fixed
One CycleRaised once, then loweredTotal steps and maximumWhen fast convergence in short training is the goal
WSDHeld constant, then lowered in a short final phaseWhen to start decayingPretraining large language models and similar

Some rules of thumb for choosing:

  • If the total number of steps is fixed, start with cosine annealing: it has few settings and is used as a standard choice for training many models.
  • If it is not decided when training will stop, consider SGDR: every cycle ends with a model trained at the minimum learning rate.

Practical considerations

Cosine annealing requires the training length to be fixed in advance. If training stops earlier than planned, the model is left with a learning rate that has not fully decayed. In PyTorch, T_max of CosineAnnealingLR is counted in calls to scheduler.step(). If step() is called every mini-batch, set T_max to the total number of steps, not the number of epochs.

Keep the following points in mind as well.

  • It is often combined with warmup: for large models such as the Transformer, a common combination is a warmup that raises the learning rate from 0 over the first few hundred to few thousand steps, followed by cosine decay.
  • Set the minimum ηmin⁡\eta_{\min} to 0 or to a positive value much smaller than the maximum: with 0, the last updates almost stop. If training may be continued later, a small positive value is easier to work with.
  • When using SGDR in PyTorch, pass fractional epochs every mini-batch: calling CosineAnnealingWarmRestarts as scheduler.step(epoch + i / iters) advances TcurT_{cur} every mini-batch, as in the paper.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn


# Eq. (5) from the paper. Computes the values in the table above
def cosine_lr(t_cur, t_i, eta_max=0.05, eta_min=0.0):
    return eta_min + 0.5 * (eta_max - eta_min) * (1 + math.cos(math.pi * t_cur / t_i))

print([round(cosine_lr(t, 10), 3) for t in [0, 2.5, 5, 7.5, 10]])
# [0.05, 0.043, 0.025, 0.007, 0.0]


# Example of SGDR (with warm restarts) in PyTorch
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9)
# T_0 = 10 epochs; each cycle is twice as long as the last (10, 20, 40, 80 epochs)
scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=10, T_mult=2, eta_min=0.0)
criterion = nn.CrossEntropyLoss()

epochs = 150      # 10 + 20 + 40 + 80 = 150: stops at the end of the 4th cycle (minimum learning rate)
iters = 100       # Mini-batches per epoch (dummy)
for epoch in range(epochs):
    for i in range(iters):
        images = torch.randn(64, 1, 28, 28)
        labels = torch.randint(0, 10, (64,))
        optimizer.zero_grad()
        loss = criterion(model(images), labels)
        loss.backward()
        optimizer.step()
        # Update the learning rate every mini-batch by passing a fractional epoch
        scheduler.step(epoch + i / iters)


# Cosine annealing without restarts: T_max is the number of step() calls
# (the number of epochs if step() is called every epoch, the total number of steps if every mini-batch)
optimizer2 = torch.optim.SGD(model.parameters(), lr=0.05)
scheduler2 = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer2, T_max=150, eta_min=0.0)

FAQ

Q. What is the difference between CosineAnnealingLR and CosineAnnealingWarmRestarts?
A.

CosineAnnealingLR lowers the learning rate from the maximum to the minimum over T_max (with no restarts). CosineAnnealingWarmRestarts implements SGDR and resets the learning rate to the maximum every cycle, with cycle lengths set by T_0 and T_mult. The former suits a fixed total number of steps; the latter suits cases where intermediate models are also useful.

Q. Should warm restarts always be used?
A.

No. Today, cosine annealing without restarts (usually with warmup) is more common. Restarts help when it is not decided when training will stop, or when models from the ends of several cycles are to be collected and used together.

Q. How should the maximum learning rate be chosen?
A.

A common approach is to start from a learning rate that trains well without a scheduler, or a slightly larger value. In the paper's CIFAR experiments, SGD is used with a maximum of 0.05.

References

  1. I. Loshchilov and F. Hutter, "SGDR: Stochastic Gradient Descent with Warm Restarts," ICLR, 2017.
  2. PyTorch Documentation, "CosineAnnealingLR."
  3. PyTorch Documentation, "CosineAnnealingWarmRestarts."