AI Logic

Learning Rate Schedulers

One-cycle

Updated:

Graphs of the learning rate and momentum in One Cycle. The horizontal axis is the epoch (100 epochs in total). The top panel shows the learning rate: the solid line, the paper's 1cycle, rises linearly from 0.1 to 1.0 over 45 epochs, returns to 0.1 at epoch 90 and drops even lower in the last 10 epochs. The dashed line, the default of PyTorch's OneCycleLR, peaks at epoch 30 and rises and falls along a cosine curve. The bottom panel shows momentum, which moves opposite to the learning rate, falling from 0.95 to 0.85 and back

What is One Cycle?

One Cycle (written 1cycle in the paper) is a learning rate scheduler that, only once over the whole of training, raises the learning rate from a small value to a large one, lowers it again, and finally takes it far below the starting value. At the same time, it moves momentum in the opposite direction to the learning rate. Smith and Topin proposed it in 2017 as a way to trigger "super-convergence", which finishes training an order of magnitude faster.

It builds on cyclical learning rates, which Smith proposed in 2015. Cyclical learning rates repeat many up-and-down cycles, whereas One Cycle uses only one cycle and spends the remaining short period driving the learning rate all the way down.

The effect is large: in the paper, on CIFAR-10 with ResNet-56, standard step decay reached 91.2% accuracy in about 80,000 iterations, while One Cycle reached 92.4% in 10,000 iterations.

Theory (how the learning rate and momentum move)

The One Cycle procedure is as follows.

  1. Determine the maximum learning rate with the learning rate range test (LR range test). Train briefly while increasing the learning rate linearly from a small value, and take the learning rate at which accuracy starts to drop (loss starts to rise) as the maximum ηmax⁡\eta_{\max}.
  2. Choose the minimum learning rate ηmin⁡\eta_{\min}. Smith (2018) suggests 1/10 to 1/20 of the maximum for a single cycle and notes that 1/10 seems to work well.
  3. First half: raise the learning rate linearly from ηmin⁡\eta_{\min} to ηmax⁡\eta_{\max}. The number of steps this takes (stepsize) is half of a cycle that is slightly shorter than the whole training run.
  4. Second half: over the same length, lower the learning rate linearly from ηmax⁡\eta_{\max} to ηmin⁡\eta_{\min}.
  5. Final short period: lower the learning rate to a value several orders of magnitude below ηmin⁡\eta_{\min}.
  6. Move momentum opposite to the learning rate. While the learning rate rises, lower momentum from a large value (e.g. 0.95) to a small one (e.g. 0.85); while it falls, bring momentum back up.

The solid line in the figure at the top is the setting for the wide ResNet (CIFAR-10) in Table 2 of the paper. The learning rate rises from 0.1 to 1.0 over 45 epochs, returns to 0.1 over the next 45 epochs, and drops further in the remaining 10 epochs (100 epochs in total). Momentum moves between 0.95 and 0.85, opposite to the learning rate.

The learning rate at step tt of the first half (0≤t≤0 \le t \le stepsize) is given by the following formula.

ηt=ηmin⁡+(ηmax⁡−ηmin⁡)tstepsize\eta_t = \eta_{\min} + \left(\eta_{\max} - \eta_{\min}\right)\frac{t}{\mathrm{stepsize}}

The default shape of PyTorch's OneCycleLR differs from the paper. The learning rate peaks at 30% of training (pct_start=0.3), rises and falls along a cosine curve (anneal_strategy='cos'), and decays all the way in a single phase without a separate final segment (the dashed line in the figure at the top). The starting value is 1/25 of the maximum (div_factor=25), and the final value is a further 1/10,000 of that (final_div_factor=1e4). To get the paper's three phases, set three_phase=True; for straight lines, set anneal_strategy='linear'.

Why does it train so fast?

The paper explains why One Cycle trains quickly and well as follows.

  • Large learning rates act as regularization: training with a large learning rate itself suppresses overfitting. Smith (2018) states that large learning rates bring two benefits: regularization that prevents overfitting, and fast training.
  • Starting small keeps training from breaking down: using a large learning rate right away can prevent training from starting at all, but ramping up from a small value lets training enter the large-learning-rate regime after convergence has begun. This is the same idea as warmup.
  • A sharp final decrease allows fine adjustment: ending with a large learning rate cannot get close to the bottom of the loss valley. Lowering the learning rate by several orders of magnitude in the final segment lets training finish after accuracy has fully risen.
  • Lowering momentum keeps training stable at large learning rates: Smith (2018) reports that lowering momentum while raising the learning rate gives the same accuracy as the best constant momentum and, in addition, stabilizes training at large learning rates.

The paper also describes the idea behind One Cycle as a combination of curriculum learning, which moves from easy to hard problems, and simulated annealing, which raises the temperature and then lowers it gradually.

Because large learning rates already regularize, other forms of regularization must be weakened. In the paper, with Weight Decay at 10−410^{-4} or less, learning rates up to 3 could be used, but at 10−310^{-3} training failed at large learning rates. Smith stresses the importance of balancing the total amount of regularization for each dataset and model.

Experimental results

Smith and Topin (2017) compared One Cycle with standard step decay (piecewise constant in the paper) on CIFAR-10 and other datasets (Figure 1 and Tables 1 and 2 in the paper; ±\pm is the standard deviation).

Data and modelStep decayOne Cycle
CIFAR-10, ResNet-5691.2% (about 80,000 iterations)92.4% (10,000 iterations)
CIFAR-10, wide ResNet90.3% ± 1.0 (800 epochs)91.9% ± 0.2 (100 epochs)
CIFAR-10, DenseNet-4092.7% ± 0.2 (400 epochs)92.8% ± 0.1 (150 epochs)
CIFAR-100, ResNet-5661.6% ± 0.9 (200 epochs)69.0% ± 0.4 (100 epochs)
MNIST, LeNet99.00% ± 0.04 (85 epochs)99.25% ± 0.03 (12 epochs)
  • It reached equal or better accuracy with a fraction of the training: for ResNet-56 on CIFAR-10 in particular, it used 1/8 of the iterations.
  • The less training data, the larger the gap: with CIFAR-10 reduced to 10,000 training images, step decay reached 71.4% and One Cycle 80.6% (Table 1).
  • Super-convergence did not occur with Adam: combined with One Cycle, super-convergence occurred with Nesterov momentum, AdaDelta and AdaGrad, but the paper reports that it could not be achieved with Adam.

Smith (2018) studied the effect of momentum with ResNet-56 on CIFAR-10. With the learning rate moving between 0.08 and 0.8, moving momentum inversely between 0.95 and 0.8 gave 92.0% ± 0.2, a constant 0.95 gave 92.1% ± 0.1, and a constant 0.85 gave 90.8% ± 0.3. Cycling momentum gives almost the same accuracy as the best constant value.

Practical considerations

PyTorch's OneCycleLR assumes scheduler.step() is called every mini-batch. total_steps (or epochs and steps_per_epoch) is counted in steps. If it is called every epoch, training ends with the learning rate barely having risen. Conversely, calling step() more than total_steps times raises an error, so pass the correct number of steps.

OneCycleLR and CyclicLR also overwrite momentum by default (cycle_momentum=True). For optimizers with betas, such as Adam, β1\beta_1 is cycled between 0.85 and 0.95 instead of momentum. Optimizers with neither momentum nor betas raise an error, so set cycle_momentum=False.

Keep the following points in mind as well.

  • Choose the maximum learning rate with a range test: the maxima that worked in the paper were 1 for the wide ResNet, 3 for ResNet-56 and 4 for DenseNet, far larger than typical settings (around 0.1). However, not every model can use large learning rates, so use a range test to check where accuracy holds up.
  • The training length must be fixed in advance: the shape of the learning rate depends on the total number of steps, so training cannot be extended midway. To extend it, start over.
  • It works well with large batches: in the paper, larger batch sizes allowed larger learning rates and were better suited to super-convergence.

Comparison with other methods

The table compares One Cycle with the schedulers it is often compared with, from the same viewpoints.

SchedulerHow the learning rate movesWhat must be set in advanceTypical use
One CycleRaised once, lowered, then lowered sharply at the endTotal steps and maximumWhen fast convergence in short training is the goal
Cyclical learning ratesMany round trips between the upper and lower boundsUpper bound, lower bound, cycle lengthWhen reducing learning rate tuning effort
Cosine annealingLowered from the maximum along a cosine curveTotal steps, maximum and minimumThe default choice for many tasks
Step decayIn steps at chosen timesWhen to decay and by what factorReproducing tasks with established settings
Warmup + decayBriefly raised, then loweredWarmup length and decay shapeLarge models and large batches

Some rules of thumb for choosing:

  • With limited compute and training with SGD, try One Cycle: in the paper, it reached the same accuracy with a fraction of the training.
  • When training a large model with Adam, start with warmup + cosine annealing: in the paper, super-convergence did not occur in combination with Adam.
  • Shortening the ramp-up phase of One Cycle makes it close to warmup + decay: reducing pct_start in PyTorch gives this shape.

PyTorch example

Show code
python
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, steps_per_epoch = 100, 100                # pass len(data_loader) as steps_per_epoch

# lr is overwritten by the scheduler, so this value is not used
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.OneCycleLR(
    optimizer,
    max_lr=1.0,                  # Maximum found with the LR range test
    epochs=epochs,
    steps_per_epoch=steps_per_epoch,
    pct_start=0.45,              # Peak at 45% of training (matches the paper's wide ResNet setting)
    anneal_strategy="linear",    # Linear, as in the paper (default is "cos")
    div_factor=10.0,             # Initial value = max_lr / 10 = 0.1
    final_div_factor=100.0,      # Final value = 0.1 / 100 = 0.001
    three_phase=True,            # Three phases: up -> down to the initial value -> sharp final decrease
    cycle_momentum=True,         # Move momentum opposite to the learning rate
    base_momentum=0.85,          # Momentum when the LR is at its maximum
    max_momentum=0.95,           # Momentum when the LR is at its minimum
)

for epoch in range(epochs):
    model.train()
    for _ in range(steps_per_epoch):
        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 (up to epochs * steps_per_epoch times in total)


# With Adam, betas[0] (β1) is cycled between 0.85 and 0.95 instead of momentum.
# Set cycle_momentum=False to keep it fixed
optimizer2 = torch.optim.Adam(model.parameters(), lr=1e-3)
scheduler2 = torch.optim.lr_scheduler.OneCycleLR(optimizer2, max_lr=1e-3, total_steps=10_000, cycle_momentum=False)

FAQ

Q. What is the difference between One Cycle and cyclical learning rates?
A.

Cyclical learning rates repeat many up-and-down cycles between upper and lower bounds. One Cycle goes up and down only once and, in a short final period, lowers the learning rate to several orders of magnitude below the lower bound. One Cycle is a slight modification of cyclical learning rates that makes super-convergence easier to achieve.

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

Use the learning rate range test. Train briefly while increasing the learning rate linearly from a small value, and take the learning rate at which accuracy starts to drop as the maximum. For a single cycle, about 1/10 of the maximum is a good guide for the minimum.

Q. Are the defaults of PyTorch's OneCycleLR good enough?
A.

In many cases they can be tried as they are. Note, however, that the default shape differs from the paper: it peaks at 30% of training and rises and falls along a cosine curve. To match the paper, set three_phase=True and anneal_strategy='linear', and adjust pct_start accordingly.

References

  1. L. N. Smith and N. Topin, "Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates," arXiv:1708.07120, 2017.
  2. L. N. Smith, "A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, momentum, and weight decay," arXiv:1803.09820, 2018.
  3. L. N. Smith, "Cyclical Learning Rates for Training Neural Networks," WACV, 2017.
  4. PyTorch Documentation, "OneCycleLR."