AI Logic

Learning Rate Schedulers

Cyclical Learning Rates

Updated:

Graphs of the three cyclical learning rate policies. The horizontal axis is the iteration (0 to 16k) and the vertical axis is the learning rate (lower bound 0.001, upper bound 0.006, stepsize 2000). The top panel, triangular, repeats the same triangle four times; the middle panel, triangular2, halves the amplitude every cycle; the bottom panel, exp_range, shrinks the amplitude smoothly by γ^it (γ = 0.99994)

What are cyclical learning rates?

Cyclical Learning Rates (CLR) is a learning rate scheduler that, instead of fixing the learning rate at one value or decreasing it monotonically, raises and lowers it periodically between a chosen lower and upper bound. Smith proposed it in 2015 (published at WACV 2017).

The starting point is the observation that raising the learning rate can temporarily hurt accuracy but benefits training in the long run. The paper states two advantages of the method.

  • Little need to fine-tune the learning rate: the lower and upper bounds can be determined with a single short trial run (the learning rate range test).
  • The same accuracy can be reached in fewer iterations: on CIFAR-10, it reached in 25,000 iterations the 81.4% accuracy that a fixed learning rate needed 70,000 iterations for.

Unlike adaptive learning rate methods (such as Adam), it adds almost no computation. It later became the basis of One Cycle, which uses a single cycle.

Theory (how the learning rate moves)

The procedure is as follows.

  1. Choose the lower bound base_lr and the upper bound max_lr, using the learning rate range test (described below).
  2. Choose the half-cycle length stepsize (in iterations). One cycle is twice the stepsize.
  3. Raise the learning rate linearly from the lower to the upper bound over stepsize iterations, then lower it linearly back to the lower bound over the next stepsize iterations. Repeat this every cycle.

The learning rate at iteration tt can be computed with the following formulas, which match the code given in the paper.

cycle=⌊1+t2 stepsize⌋,x=∣tstepsize−2 cycle+1∣\mathrm{cycle} = \left\lfloor 1 + \frac{t}{2\,\mathrm{stepsize}} \right\rfloor, \qquad x = \left| \frac{t}{\mathrm{stepsize}} - 2\,\mathrm{cycle} + 1 \right| ηt=base_lr+(max_lr−base_lr)⋅max⁡(0, 1−x)\eta_t = \mathrm{base\_lr} + \left(\mathrm{max\_lr} - \mathrm{base\_lr}\right) \cdot \max(0,\ 1 - x)

xx is 0 in the middle of a cycle (when the learning rate is at the upper bound) and 1 at the start and end of a cycle (at the lower bound). The paper's CIFAR-10 example uses base_lr = 0.001, max_lr = 0.006 and stepsize = 2,000 iterations (4,000 per cycle) (top of the figure at the top).

The paper gives three policies that differ in how the rate rises and falls (figure at the top).

PolicyHow the amplitude changes
triangularUnchanged (the same triangle repeats)
triangular2The gap between the upper and lower bounds is halved every cycle
exp_rangeShrinks by a factor of γt\gamma^{t} per iteration

Besides the triangle (linear), the paper also tried a parabolic shape (Welch window) and a sinusoidal shape (Hann window), and reports that all gave similar results. The triangle was chosen because it is the simplest.

Choosing the learning rate range and the cycle length

The lower and upper bounds are chosen with the learning rate range test (LR range test). The procedure is as follows.

  1. Train while increasing the learning rate linearly from a small to a large value over a few epochs.
  2. Plot accuracy against the learning rate.
  3. Use the learning rate at which accuracy starts to increase as the lower bound, and the one at which the increase slows, becomes ragged or turns into a decrease as the upper bound.

In the paper's CIFAR-10 example, training made progress from the start, so the lower bound was set to 0.001; above 0.006 the accuracy curve became ragged, so the upper bound was set to 0.006. As a rule of thumb when no range test is run, the paper also suggests setting the lower bound to 1/3 to 1/4 of the upper bound, based on the experience that the optimal learning rate is usually within a factor of 2 of the largest learning rate that converges.

A stepsize of 2 to 10 times the number of iterations per epoch often works well. For CIFAR-10 (50,000 training images, batch size 100), one epoch is 500 iterations, so stepsize = 2,000 corresponds to 4 epochs. The final accuracy is not very sensitive to the cycle length.

The paper recommends stopping training at the end of a cycle (when the learning rate is at the lower bound), because accuracy is highest there. It also notes that replacing each stage of fixed-learning-rate training with 3 or more cycles trains the network sufficiently, and 4 or more cycles works even better.

Why does raising and lowering help?

The paper gives two reasons.

  • It moves quickly across the flat regions around saddle points: the paper cites the argument by Dauphin et al. that the difficulty in minimizing the loss comes from saddle points (points that are a valley in one direction and a peak in another) rather than poor local minima. Gradients are small around saddle points, which slows training. Raising the learning rate allows faster traversal of these flat regions.
  • It keeps using learning rates near the optimum: the optimal learning rate is likely to lie between the bounds found by the range test, so near-optimal learning rates are used throughout training.

To check whether raising the learning rate is really necessary, the paper also tried a policy that lowers the learning rate linearly from the upper to the lower bound and then keeps it at the lower bound (decay). On CIFAR-10 its accuracy stayed at 78.5%, short of the 81.4% of cyclical learning rates. The paper concludes that both raising and lowering the learning rate contribute.

As an analogy, it is like repeatedly picking up the pace on flat stretches of a mountain trail and walking carefully on steep descents.

Experimental results

The paper compared the method with a fixed learning rate (and its standard schedule) on CIFAR-10, CIFAR-100 and ImageNet (Tables 1 and 4 in the paper).

Data and modelPolicyIterationsAccuracy
CIFAR-10, Caffe CNNFixed70,00081.4%
CIFAR-10, Caffe CNNtriangular225,00081.4%
CIFAR-10, Caffe CNNexp (exponential decay)70,00079.1%
CIFAR-10, Caffe CNNexp_range42,00082.2%
ImageNet, AlexNetFixed400,00058.0%
ImageNet, AlexNettriangular2400,00058.4%
ImageNet, GoogLeNetFixed420,00063.0%
ImageNet, GoogLeNettriangular2420,00064.4%
  • On CIFAR-10, it reached the same accuracy in just over a third of the iterations: triangular2 reached in 25,000 iterations the 81.4% that a fixed learning rate needed 70,000 iterations for.
  • ResNet-style models matched or exceeded the baseline: on CIFAR-10, ResNet reached 92.8%, 93.3% and 91.8% with fixed learning rates (0.1, 0.2, 0.3) and 93.6% with cyclical learning rates (0.1 to 0.3). DenseNet improved from 94.5% to 94.9% (Table 4; average of 5 runs).
  • Combined with adaptive methods, the benefit was sometimes smaller: with Adam, against 81.4% for a fixed learning rate over 70,000 iterations, cyclical learning rates gave 79.8% at 25,000 iterations and 81.1% at 70,000 iterations (Table 3).

Practical considerations

PyTorch's CyclicLR assumes scheduler.step() is called every mini-batch. step_size_up (the half cycle) is counted in iterations and defaults to 2000. If step() is called every epoch, one cycle takes 4,000 epochs and the learning rate barely rises.

CyclicLR also cycles momentum by default (cycle_momentum=True). Momentum is max_momentum (default 0.9) when the learning rate is at the lower bound and base_momentum (default 0.8) at the upper bound. For optimizers with betas, such as Adam, β1\beta_1 is cycled. Optimizers with neither momentum nor betas raise an error, so set cycle_momentum=False. This is a PyTorch feature not found in the paper.

Keep the following points in mind as well.

  • Stop at the end of a cycle: stopping when the learning rate is near the upper bound leaves a model whose accuracy has dropped. Make the total number of iterations an integer multiple of one cycle (twice the stepsize).
  • A temporary drop in accuracy is normal: accuracy can dip while the learning rate is rising. The paper itself starts from the observation that this temporary dip benefits training in the long run.
  • The exp_range formula can differ between implementations: the paper says the boundary values decline by γt\gamma^{t}, whereas PyTorch's mode='exp_range' keeps the lower bound fixed and multiplies the gap between the upper and lower bounds by γt\gamma^{t}. The figure at the top follows the PyTorch form.

Comparison with other learning rate schedulers

The table compares cyclical learning rates with the schedulers they are often compared with, from the same viewpoints.

SchedulerHow the learning rate movesWhat must be set in advanceTypical use
Cyclical learning ratesMany triangular round trips between the lower and upper boundsLower bound, upper bound, stepsizeWhen reducing learning rate tuning effort
One CycleRaised and lowered only once, then lowered sharply at the endTotal steps and maximumWhen fast convergence in short training is the goal
SGDR (cosine annealing)Cosine decay, jumping back to the maximum every cycleT0T_0, TmultT_{\mathrm{mult}}When intermediate models are also useful
Step decayIn steps at chosen timesWhen to decay and by what factorReproducing tasks with established settings

Some rules of thumb for choosing:

  • With a new model or dataset and no idea of a good learning rate, run a range test first: the range test alone helps set a fixed learning rate or the maximum for other schedulers.
  • If the training length is fixed, also compare One Cycle: One Cycle is cyclical learning rates with a single cycle, and the paper's author recommends it for super-convergence.
  • The difference from SGDR is how the rate rises: cyclical learning rates raise the learning rate gradually and linearly, while SGDR jumps straight back to the maximum. The paper's author describes SGDR as the method closest to cyclical learning rates.

PyTorch example

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


# Same computation as the code in the paper (triangular); matches the formulas above
def triangular_lr(it, base_lr=0.001, max_lr=0.006, stepsize=2000):
    cycle = math.floor(1 + it / (2 * stepsize))
    x = abs(it / stepsize - 2 * cycle + 1)
    return base_lr + (max_lr - base_lr) * max(0.0, 1 - x)

print([round(triangular_lr(t), 4) for t in [0, 1000, 2000, 3000, 4000]])
# [0.001, 0.0035, 0.006, 0.0035, 0.001]


model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
scheduler = torch.optim.lr_scheduler.CyclicLR(
    optimizer,
    base_lr=0.001,          # Lower bound (LR where accuracy starts to rise in the range test)
    max_lr=0.006,           # Upper bound (LR where the accuracy curve becomes ragged in the range test)
    step_size_up=2000,      # Iterations per half cycle (2-10x the iterations per epoch is a good guide)
    mode="triangular2",     # "triangular" / "triangular2" / "exp_range" (exp_range also takes gamma)
    cycle_momentum=True,    # Default: moves momentum inversely, 0.9 (LR at lower bound) to 0.8 (at upper bound)
)

iters_per_epoch = 500
total = 4 * 2 * 2000        # 4 cycles: an integer multiple of one cycle so training stops at a cycle end (LR at lower bound)
for it in range(total):
    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


# LR range test: train briefly while increasing the LR linearly and record accuracy (loss)
optimizer2 = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
# Raise from 1e-4 to 100x (1e-2) over 8 epochs. LinearLR cannot exceed a factor of 1, so use LambdaLR
range_test = torch.optim.lr_scheduler.LambdaLR(optimizer2, lr_lambda=lambda it: 1 + 99 * it / (8 * iters_per_epoch))

FAQ

Q. Which should be used, cyclical learning rates or One Cycle?
A.

If the training length is fixed and training should finish quickly, One Cycle is a good candidate. One Cycle uses a single cycle of cyclical learning rates and lowers the learning rate sharply at the end; the author proposed it in a later paper for super-convergence. When still looking for a reasonable learning rate, combining a range test with cyclical learning rates is easy.

Q. Doesn't raising the learning rate break training?
A.

If the upper bound is chosen with a range test, the learning rate never becomes large enough to make training diverge. Accuracy may dip temporarily while the rate is rising, but the paper reports that this benefits training in the long run. Stop at the end of a cycle (with the learning rate at the lower bound).

Q. Do cyclical learning rates work with Adam?
A.

They can, but the benefit may be smaller. In the paper's CIFAR-10 experiments, combining Adam with cyclical learning rates did not reach the same accuracy in shorter training than a fixed learning rate. Note also that using PyTorch's CyclicLR with Adam cycles β1 by default.

References

  1. L. N. Smith, "Cyclical Learning Rates for Training Neural Networks," IEEE Winter Conference on Applications of Computer Vision (WACV), 2017.
  2. L. N. Smith and N. Topin, "Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates," arXiv:1708.07120, 2017.
  3. PyTorch Documentation, "CyclicLR."