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:
--schedselects the schedule.--epochssets the schedule length.--sched-on-updatessteps per update instead of per epoch.--warmup-epochssets the warmup duration.--warmup-lrsets the initial warmup learning rate.--warmup-prefixadds warmup before the schedule instead of overlapping its start.--min-lrsets the minimum learning rate.--decay-epochssets the step-decay interval or the final decay duration for WSD / rsqrt.--decay-milestonessets the decay epochs for the multistep schedule.--decay-ratesets the decay factor, or the power for the polynomial schedule.--cooldown-epochsadds epochs at the minimum learning rate after the schedule ends.--patience-epochssets the plateau scheduler's patience.--lr-noiseselects the part of the schedule with learning rate noise.--lr-noise-pctlimits the noise magnitude.--lr-noise-stdsets the noise standard deviation.--lr-cycle-mulsets the cycle length multiplier.--lr-cycle-decaysets the peak learning rate multiplier between cycles.--lr-cycle-limitsets the number of cycles.--lr-k-decaysets k-decay for cosine / polynomial schedules.--lr-decay-fnselects the final decay function for WSD / rsqrt.--lr-stable-timescalesets 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_epochsof linear warmup fromwarmup_lrto 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), sonum_epochsis the total length. Withwarmup_prefix=Truethe schedule starts after the warmup and the warmup is added to the total.- For
wsdandrsqrtthe stable phase always starts after the warmup, w/owarmup_prefixthe stable and decay phases are fitted intonum_epochs - warmup_epochssonum_epochsremains the total.
min_lr: the lr the decaying schedules (cosine,tanh,poly,wsd,rsqrt) reach at the end, and a lower bound forplateau.
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 atmin_lrafter the schedule ends (cosine,tanh,poly,wsd,rsqrt), added to the returnednum_epochs. As the schedule reachesmin_lrone step after its last step, a cooldown epoch is also a way to train atmin_lrwhen stepping per epoch.- Cycles (
cosine,tanh,poly):cycle_limit > 1restarts the schedule, each cyclecycle_multimes longer and w/ its peak lr multiplied bycycle_decayrelative to the previous. The returnednum_epochscovers all cycles. k_decay(cosine,poly): k-decay changes the shape of the decay (t ** k),k > 1keeps the lr high for longer.- Noise:
noiseadds random multiplicative lr noise over a range of the schedule, given as fractions ofnum_epochs(a start, or a start and an end), limited bynoise_pct.
WSD and rsqrt
The WSDLRScheduler has three phases: a linear warmup, a stable phase and
a decay to min_lr.
decay_epochssets 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) selects1-sqrt(default forwsd),linear(default forrsqrt),cosine,powerorexp.stable_timescale(--lr-stable-timescale, in epochs) controls thersqrtstable phase, which decays as(1 + t / timescale) ** -0.5from 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.