opensi·si

This page contains the API reference documentation for the learning rate schedulers included in timm, and an

Learning Rate Schedulers

This page contains the API reference documentation for the learning rate schedulers included in timm, and an overview of how they are created and stepped.

Usage

Schedulers are created by name with create_scheduler_v2, which returns the scheduler and the total number of epochs to train (including any warmup prefix, cycles and cooldown, see below). Unlike torch.optim.lr_scheduler, timm schedulers do not count steps themselves. They are designed to be stateless: the lr is a function of the schedule configuration and an explicit epoch or update count, so resuming a run only needs the epoch, and no scheduler state is stored in checkpoints. The training loop passes the epoch or update count in explicitly:

  • scheduler.step(epoch) at the end of each epoch, with the index of the next epoch (epoch + 1)
  • scheduler.step_update(num_updates) after each optimizer update, with the number of updates so far

A scheduler is stepped either per epoch or per update (step_on_epochs), the other call is a no-op, so a training loop can make both calls and support either.

import timm
from timm.optim import create_optimizer_v2
from timm.scheduler import create_scheduler_v2

model = timm.create_model('resnet50')
optimizer = create_optimizer_v2(model, opt='adamw', lr=1e-3, weight_decay=0.05)
updates_per_epoch = len(loader)  # optimizer updates per epoch

# Cosine decay w/ 5 epochs of linear warmup, stepped per update for a smooth schedule.
scheduler, num_epochs = create_scheduler_v2(
    optimizer,
    sched='cosine',
    num_epochs=100,
    warmup_epochs=5,
    min_lr=1e-6,
    step_on_epochs=False,
    updates_per_epoch=updates_per_epoch,
)

num_updates = 0
for epoch in range(num_epochs):
    for batch in loader:
        ...  # forward, backward, optimizer.step()
        num_updates += 1
        scheduler.step_update(num_updates=num_updates)
    scheduler.step(epoch + 1)  # pass the eval metric too for 'plateau', scheduler.step(epoch + 1, metric)

Durations (num_epochs, warmup_epochs, decay_epochs, ...) are always given in epochs, the factory converts them to updates when step_on_epochs=False. Schedulers can also be constructed directly from their classes, durations are then in the unit they are stepped in (t_in_epochs).

The training script (train.py) exposes the factory arguments through these flags:

  • --sched selects the schedule.
  • --epochs sets the schedule length.
  • --sched-on-updates steps per update instead of per epoch.
  • --warmup-epochs sets the warmup duration.
  • --warmup-lr sets the initial warmup learning rate.
  • --warmup-prefix adds warmup before the schedule instead of overlapping its start.
  • --min-lr sets the minimum learning rate.
  • --decay-epochs sets the step-decay interval or the final decay duration for WSD / rsqrt.
  • --decay-milestones sets the decay epochs for the multistep schedule.
  • --decay-rate sets the decay factor, or the power for the polynomial schedule.
  • --cooldown-epochs adds epochs at the minimum learning rate after the schedule ends.
  • --patience-epochs sets the plateau scheduler's patience.
  • --lr-noise selects the part of the schedule with learning rate noise.
  • --lr-noise-pct limits the noise magnitude.
  • --lr-noise-std sets the noise standard deviation.
  • --lr-cycle-mul sets the cycle length multiplier.
  • --lr-cycle-decay sets the peak learning rate multiplier between cycles.
  • --lr-cycle-limit sets the number of cycles.
  • --lr-k-decay sets k-decay for cosine / polynomial schedules.
  • --lr-decay-fn selects the final decay function for WSD / rsqrt.
  • --lr-stable-timescale sets the rsqrt stable-phase timescale.

Schedules

sched Class Schedule
cosine CosineLRScheduler Cosine annealing from the base lr to min_lr (SGDR), optional restarts (cycles) and k-decay
tanh TanhLRScheduler Hyperbolic tangent decay (paper), optional restarts
poly PolyLRScheduler Polynomial decay to min_lr, the power is given by decay_rate, optional restarts and k-decay
step StepLRScheduler lr multiplied by decay_rate every decay_epochs
multistep MultiStepLRScheduler lr multiplied by decay_rate at each of the decay_milestones epochs
plateau PlateauLRScheduler Deprecated. lr multiplied by decay_rate when the eval metric hasn't improved for patience_epochs, per epoch stepping only
wsd WSDLRScheduler Warmup-stable-decay (MiniCPM), constant lr then a decay to min_lr over the final decay_epochs, 1-sqrt decay by default (paper)
rsqrt WSDLRScheduler Reciprocal square root decay w/ a linear cooldown over the final decay_epochs (Big Vision)

Common options

  • Warmup. warmup_epochs of linear warmup from warmup_lr to the base lr, supported by all schedules.
    • warmup_prefix: by default the warmup overlaps the start of the schedule (the schedule is computed from epoch 0, warmup replaces its first epochs), so num_epochs is the total length. With warmup_prefix=True the schedule starts after the warmup and the warmup is added to the total.
    • For wsd and rsqrt the stable phase always starts after the warmup, w/o warmup_prefix the stable and decay phases are fitted into num_epochs - warmup_epochs so num_epochs remains the total.
  • min_lr: the lr the decaying schedules (cosine, tanh, poly, wsd, rsqrt) reach at the end, and a lower bound for plateau.

The plateau schedule is deprecated and will be removed in a future release. It never fit the stateless design above: its lr depends on the history of the eval metric rather than on the epoch, and that history (best metric, patience and cooldown counters) is not saved in checkpoints, so a resumed run restarts the plateau logic. Checkpoint support will not be added. A validation plateau is also a weak signal for when to anneal; a fixed schedule such as cosine or wsd is reproducible and resumes exactly, and a WSD sweep (see Hyperparameter Sweeps) compares cooldowns at several budgets from one stable run.

  • cooldown_epochs: epochs held at min_lr after the schedule ends (cosine, tanh, poly, wsd, rsqrt), added to the returned num_epochs. As the schedule reaches min_lr one step after its last step, a cooldown epoch is also a way to train at min_lr when stepping per epoch.
  • Cycles (cosine, tanh, poly): cycle_limit > 1 restarts the schedule, each cycle cycle_mul times longer and w/ its peak lr multiplied by cycle_decay relative to the previous. The returned num_epochs covers all cycles.
  • k_decay (cosine, poly): k-decay changes the shape of the decay (t ** k), k > 1 keeps the lr high for longer.
  • Noise: noise adds random multiplicative lr noise over a range of the schedule, given as fractions of num_epochs (a start, or a start and an end), limited by noise_pct.

WSD and rsqrt

The WSDLRScheduler has three phases: a linear warmup, a stable phase and a decay to min_lr.

  • decay_epochs sets the final decay duration. A value in (0, 1) is a fraction of the stable + decay length, 20% by default.
  • decay_fn (--lr-decay-fn) selects 1-sqrt (default for wsd), linear (default for rsqrt), cosine, power or exp.
  • stable_timescale (--lr-stable-timescale, in epochs) controls the rsqrt stable phase, which decays as (1 + t / timescale) ** -0.5 from the end of warmup. It defaults to the warmup length and must be set when there is no warmup.

The class also supports a generalized power stable phase and custom decay functions.

The final anneal is where WSD schedules get most of their benefit, so step per update (--sched-on-updates), or add a cooldown epoch, when the decay phase is only a few epochs long. Stepped per epoch, the last epoch of a short decay is noticeably above min_lr (~10% of the base lr for the last of 5 decay epochs w/ 1-sqrt).

# 300 epochs, 5 epoch warmup, constant lr, then a 1-sqrt decay over the final 20%
scheduler, num_epochs = create_scheduler_v2(
    optimizer, sched='wsd', num_epochs=300, warmup_epochs=5, decay_epochs=0.2,
    step_on_epochs=False, updates_per_epoch=updates_per_epoch,
)

Parameter group lr scales

Param groups w/ an lr_scale field (e.g. layer-wise lr decay groups from param_groups_layer_decay) get the scheduled lr multiplied by their scale. The base lr of each group is recorded as initial_lr in the group when the scheduler is created.

Resuming

As the step counts are passed in, a scheduler for a resumed run is set up by creating it as for the original run and stepping it to the resume point, scheduler.step(start_epoch) or scheduler.step_update(start_epoch * updates_per_epoch). state_dict() / load_state_dict() save and restore the scheduler's attributes.

API

Factory functions

[[autodoc]] timm.scheduler.scheduler_factory.create_scheduler [[autodoc]] timm.scheduler.scheduler_factory.create_scheduler_v2

Scheduler Classes

[[autodoc]] timm.scheduler.cosine_lr.CosineLRScheduler [[autodoc]] timm.scheduler.multistep_lr.MultiStepLRScheduler [[autodoc]] timm.scheduler.plateau_lr.PlateauLRScheduler [[autodoc]] timm.scheduler.poly_lr.PolyLRScheduler [[autodoc]] timm.scheduler.step_lr.StepLRScheduler [[autodoc]] timm.scheduler.tanh_lr.TanhLRScheduler [[autodoc]] timm.scheduler.wsd_lr.WSDLRScheduler

Source and license

Source: timm documentation, adapted for this site. Licensing and attribution follow the terms of the upstream project.