AI Logic

Learning Rate Schedulers

Warmup

Updated:

Learning rate graphs for warmup. The left panel is ResNet-50 with large mini-batches (Goyal et al.), with epochs on the horizontal axis and the learning rate on the vertical axis. Gradual warmup rises linearly from 0.1 to 3.2 over 5 epochs, constant warmup stays at 0.1 until epoch 5 and then jumps to 3.2, and the dashed line without warmup is at 3.2 from the start. The right panel is the Transformer formula, with steps on the horizontal axis: the rate rises proportionally until step 4000, peaks at about 7.0×10⁻⁴, and then decreases in inverse proportion to the square root of the step number

What is warmup?

Warmup is a way of using a learning rate scheduler that raises the learning rate gradually from a small value only during a short period at the start of training, then switches to the main schedule once the target value is reached. Moving the weights abruptly with a large learning rate at the start of training can make training break down or lower the final accuracy, and warmup prevents this.

There are two main forms of warmup.

  • Constant warmup: train with a small constant learning rate for only the first few epochs, then jump back to the target learning rate. The ResNet paper (He et al., 2015) used it for a 110-layer network.
  • Gradual warmup: raise the learning rate linearly by a fixed amount every step, from a small value to the target. Goyal et al. (2017) proposed it to train ResNet-50 with large mini-batches.

Gradual warmup is the form commonly used today. Goyal et al. showed that even with mini-batches as large as 8,192 images, gradual warmup reaches almost the same accuracy as with 256 images, and cut ImageNet training to one hour on 256 GPUs.

The idea of warmup is also built into the learning rate formula of the Transformer (Vaswani et al., 2017), and it is widely used when training large models with Adam.

Theory (how the learning rate is raised)

The procedure for gradual warmup (Goyal et al.) is as follows.

  1. Choose the target learning rate η^\hat{\eta}. Goyal et al. set η^=kη\hat{\eta} = k\eta using the "linear scaling rule": when the mini-batch is multiplied by kk, multiply the learning rate by kk as well (η\eta is the learning rate for the small mini-batch).
  2. Choose the warmup length TwT_w. The paper uses 5 epochs.
  3. At every step (one weight update), raise the learning rate by a fixed amount. The learning rate at step tt is given by the following formula.
ηt=η+(η^−η)tTw(0≤t<Tw)\eta_t = \eta + \left(\hat{\eta} - \eta\right)\frac{t}{T_w} \qquad (0 \le t < T_w)
  1. When TwT_w is reached, return to the main learning rate schedule. In the paper, training continues from there at learning rate η^\hat{\eta}, which is divided by 10 at epochs 30, 60 and 80 (step decay).

In the paper's ImageNet setting, the reference learning rate is η=0.1⋅kn256\eta = 0.1 \cdot \frac{kn}{256} (knkn is the total mini-batch size). With kn=8192kn = 8192, η^=3.2\hat{\eta} = 3.2, and warmup raises the rate from 0.10.1 to 3.23.2 over 5 epochs (left of the figure at the top).

The Transformer paper expresses warmup and decay in a single formula (Eq. (3) in the paper).

lrate=dmodel−0.5⋅min⁡(step−0.5, step⋅warmup−1.5)\mathit{lrate} = d_{\mathrm{model}}^{-0.5} \cdot \min\left(\mathit{step}^{-0.5},\ \mathit{step} \cdot \mathit{warmup}^{-1.5}\right)

While step<warmup\mathit{step} < \mathit{warmup}, the second term is smaller, so the learning rate rises in proportion to the step number. After warmup\mathit{warmup}, the first term is smaller, and the rate decreases in inverse proportion to the square root of the step number. The paper used warmup=4000\mathit{warmup} = 4000. With dmodel=512d_{\mathrm{model}} = 512 (the base model), the values are as follows (right of the figure at the top).

Step1,0002,0004,0008,00016,00040,000
Learning rate1.75×10−41.75\times10^{-4}3.49×10−43.49\times10^{-4}6.99×10−46.99\times10^{-4}4.94×10−44.94\times10^{-4}3.49×10−43.49\times10^{-4}2.21×10−42.21\times10^{-4}

The Transformer formula does not set the maximum learning rate directly. The maximum is dmodel−0.5⋅warmup−0.5d_{\mathrm{model}}^{-0.5} \cdot \mathit{warmup}^{-0.5} and changes together with dmodeld_{\mathrm{model}} and warmup\mathit{warmup}. Modern implementations often set the maximum separately and use a "linear ramp-up + decay such as cosine" shape instead.

Why does it stabilize training?

Goyal et al. explain why the linear scaling rule works as follows. Making kk updates with a small mini-batch and one update with a kk times larger mini-batch give the same result when the gradient barely changes over those kk updates (∇l(x,wt)≈∇l(x,wt+j)\nabla l(x, w_t) \approx \nabla l(x, w_{t+j})).

However, at the start of training the network changes rapidly, so this assumption does not hold. Using a large learning rate right away moves the weights too far, and training does not progress well. Warmup holds back the learning rate until the network settles down, then raises it to the target once the assumption holds.

Gradual warmup is better than constant warmup because it does not make the learning rate jump suddenly. In the paper, when constant warmup switched the learning rate from 0.1 back to 3.2 after 5 epochs, the training error spiked at that moment. Gradual warmup avoids this spike by raising the learning rate little by little.

As an analogy, it is like not flooring the accelerator on a cold engine, but raising the revs gradually.

The reason warmup is essential for the Transformer is also related to where layer normalization is placed. This is explained in detail in Pre-LN and Post-LN.

Experimental results

Goyal et al. trained ResNet-50 on ImageNet for 90 epochs and compared warmup variants with mini-batches of 8,192 images (256 GPUs × 32 images) (Table 1 in the paper; validation error is the mean ± standard deviation over 5 runs).

SettingMini-batchLearning rateTop-1 validation error
Baseline (small mini-batch)2560.123.60% ± 0.12
No warmup8,1923.224.84% ± 0.37
Constant warmup8,1923.225.88% ± 0.56
Gradual warmup8,1923.223.74% ± 0.09
  • Only gradual warmup matched the baseline: the difference was 0.14%, and the training error curve almost overlapped with the baseline.
  • Constant warmup was worse than no warmup: the spike in training error when the learning rate was switched back persisted to the end.
  • There is a limit to how large the mini-batch can be: with the linear scaling rule and gradual warmup, validation error stayed nearly constant from 64 to 8,192 images, began to rise beyond that, and training diverged beyond 65,536 images.

In the ResNet paper by He et al. (2015), which used constant warmup, training a 110-layer network on CIFAR-10 with a learning rate of 0.1 was slow to start converging, so they trained with a learning rate of 0.01 until the training error fell below 80% (about 400 iterations) and then returned to 0.1.

Practical considerations

Warmup should normally raise the learning rate every step (mini-batch). Goyal et al. also raise it by a fixed amount every iteration. If scheduler.step() is called every epoch in PyTorch, the learning rate rises only in steps of one epoch, so a 5-epoch warmup becomes a 5-step staircase. Call step() every step and specify lengths such as total_iters in steps.

When warmup and decay are chained with PyTorch's SequentialLR, the later scheduler counts again from the switching step. For example, to decay at epoch 30 with MultiStepLR after warmup, write milestones as "30 epochs − warmup length" in steps. If this is error-prone, writing the learning rate formula directly in LambdaLR is more reliable (see the code example).

Keep the following points in mind as well.

  • Results are not very sensitive to the warmup length: Goyal et al. state that results are relatively insensitive to the exact warmup length. However, a warmup that is too short can let training break down.
  • With a small target learning rate, the benefit is smaller: warmup matters most when using large mini-batches or large learning rates.
  • start_factor of LinearLR cannot be 0: it must be greater than 0 and at most 1. To start from 0, use LambdaLR.
  • When the batch size changes, revisit the target learning rate and warmup: adding GPUs with data parallelism changes the total batch size, and the target learning rate changes with it under the linear scaling rule.

Comparison with other methods

The table compares forms of warmup from the same viewpoints.

MethodHow the learning rate is raisedWhat to chooseExample usesLimitations
No warmupTarget value from the startNothingTraining with small mini-batchesTraining tends to break down with large learning rates
Constant warmupSmall constant value, then jump backSmall value and lengthResNet-110 (CIFAR-10), fine-tuning for object detectionError can spike when the rate jumps back
Gradual warmupLinear increaseStarting value and lengthResNet-50 with large mini-batchesLength is chosen separately from the total number of steps
Transformer formulaUp in proportion to the step number, down in inverse proportion to its square rootdmodeld_{\mathrm{model}} and warmup\mathit{warmup}TransformerThe maximum cannot be set directly

Some rules of thumb for choosing:

  • When in doubt, combine gradual warmup with a decay schedule: following warmup with cosine annealing or step decay is common.
  • To keep the learning rate constant for most of training, consider WSD: it holds the rate constant after warmup and lowers it at the end.
  • To reduce the need for warmup itself, revisit the model or the optimizer: the Pre-LN Transformer and RAdam are methods that aim to make warmup unnecessary.

One Cycle can also be seen as a method that stretches the ramp-up period to nearly half of training.

PyTorch example

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

model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
criterion = nn.CrossEntropyLoss()
epochs, iters = 90, 100          # Mini-batches per epoch (dummy)


# ── 1. Gradual warmup of Goyal et al. (0.1 -> 3.2 over 5 epochs) + step decay ──
# LambdaLR sets the LR to "optimizer lr x function value". Here lr = 1.0, so the function returns the LR itself
eta, eta_hat = 0.1, 3.2
warmup = 5 * iters               # Warmup length (in steps)

def goyal_lr(step):              # step is the number of scheduler.step() calls (from 0)
    if step < warmup:
        return eta + (eta_hat - eta) * step / warmup
    epoch = step / iters
    return eta_hat * 0.1 ** sum(epoch >= m for m in (30, 60, 80))

optimizer = torch.optim.SGD(model.parameters(), lr=1.0, momentum=0.9, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=goyal_lr)

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()
        scheduler.step()         # Call every mini-batch (calling every epoch gives a 5-step staircase)


# ── 2. Chaining built-in schedulers: LinearLR (warmup) -> CosineAnnealingLR ──
total = epochs * iters
optimizer2 = torch.optim.SGD(model.parameters(), lr=3.2, momentum=0.9)
warm = torch.optim.lr_scheduler.LinearLR(optimizer2, start_factor=0.1 / 3.2, end_factor=1.0, total_iters=warmup)
# The later scheduler in SequentialLR counts again from the switching step -> length is total - warmup
cos = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer2, T_max=total - warmup)
scheduler2 = torch.optim.lr_scheduler.SequentialLR(optimizer2, schedulers=[warm, cos], milestones=[warmup])


# ── 3. Transformer Eq. (3): lrate = d_model^-0.5 * min(step^-0.5, step * warmup^-1.5) ──
d_model, warmup_steps = 512, 4000

def transformer_lr(step):
    step = step + 1              # Count from 1 because step^-0.5 is undefined at step = 0
    return d_model ** -0.5 * min(step ** -0.5, step * warmup_steps ** -1.5)

optimizer3 = torch.optim.Adam(model.parameters(), lr=1.0, betas=(0.9, 0.98), eps=1e-9)
scheduler3 = torch.optim.lr_scheduler.LambdaLR(optimizer3, lr_lambda=transformer_lr)
print(f"{transformer_lr(3999):.2e}")   # Peak at step 4000: 6.99e-04

FAQ

Q. How many steps should warmup last?
A.

There is no fixed value. Goyal et al.'s ImageNet experiments used 5 epochs, and the Transformer paper used 4,000 steps. Goyal et al. state that results are relatively insensitive to the exact warmup length. If the loss becomes erratic or diverges early in training, try a longer warmup or a lower target learning rate.

Q. Is warmup needed with Adam too?
A.

It is often needed. The Transformer paper combines Adam with warmup, and this is the standard combination for large models. On the other hand, some methods, such as the Pre-LN Transformer and RAdam, aim to make warmup unnecessary.

Q. How does warmup relate to fine-tuning?
A.

A short warmup is also commonly used when fine-tuning a pretrained model. Goyal et al. note that constant warmup was particularly helpful for object detection and segmentation, where pretrained layers are fine-tuned together with newly initialized layers.

References

  1. P. Goyal, P. Dollár, R. Girshick, P. Noordhuis, L. Wesolowski, A. Kyrola, A. Tulloch, Y. Jia, and K. He, "Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour," arXiv:1706.02677, 2017.
  2. K. He, X. Zhang, S. Ren, and J. Sun, "Deep Residual Learning for Image Recognition," CVPR, 2016.
  3. A. Vaswani et al., "Attention Is All You Need," NeurIPS, 2017.
  4. PyTorch Documentation, "LinearLR."
  5. PyTorch Documentation, "SequentialLR."