Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch Learning Rate Schedulers

PyTorch Learning Rate Schedulers

The learning rate is one of the most important hyperparameters in neural network training. Too large, and training oscillates or even diverges; too small, and convergence is very slow with a tendency to get stuck in local optima.

LR Scheduler (learning rate scheduler) By dynamically adjusting the learning rate during training, it balances fast convergence early on with fine-tuning later.


1. Basic concepts and usage patterns

Standard usage flow

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

model    

=

nn.

Linear

(

10

,

1

)

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

1. Create the scheduler, passing in the optimizer

scheduler

=

optim.

lr_scheduler

.

StepLR

(

optimizer

,

step_size

=

30

,

gamma

=

0.1

)

for

epoch

in

range

(

100

)

:

   

2. Train

    train

(

model

,

optimizer

)

   

3. Call scheduler.step() after each epoch

    scheduler.

step

(

)

   

4. Check the current learning rate

    current_lr

=

scheduler.

get_last_lr

(

)

[

0

]

   

print

(

f

"Epoch {epoch+1}, LR: {current_lr:.6f}"

)

When to call step()

Example

Correct: optimizer.step() first, scheduler.step() after

optimizer.

step

(

)

scheduler.

step

(

)

Wrong: scheduler.step() before optimizer.step()

PyTorch 1.1.0 and later emit a warning, and some schedulers behave abnormally

scheduler.

step

(

)

optimizer.

step

(

)

Note:optimizer.step() Must be scheduler.step() .

Viewing and saving learning rate state

Example

Get the current learning rate

current_lr

=

optimizer.

param_groups

[

0

]

[

'lr'

]

current_lr

=

scheduler.

get_last_lr

(

)

[

0

]

 

LR after the last step()

Save a checkpoint (must also save the scheduler state)

torch.

save

(

{

   

'epoch'

:          epoch

,

   

'model'

:          model.

state_dict

(

)

,

   

'optimizer'

:      optimizer.

state_dict

(

)

,

   

'scheduler'

:      scheduler.

state_dict

(

)

,

 

Don't miss this

}

,

'checkpoint.pth'

)

Restore a checkpoint

ckpt

=

torch.

load

(

'checkpoint.pth'

)

model.

load_state_dict

(

ckpt

[

'model'

]

)

optimizer.

load_state_dict

(

ckpt

[

'optimizer'

]

)

scheduler.

load_state_dict

(

ckpt

[

'scheduler'

]

)


2. Fixed decay schedulers

2.1 StepLR (step decay)

Every fixed number of step_size epochs, multiply the learning rate by gamma. One of the simplest and most commonly used schedulers.

Formula: lr = lr_base * gamma^(floor(step / step_size))

Example

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

scheduler

=

optim.

lr_scheduler

.

StepLR

(

    optimizer

,

    step_size

=

30

,

 

Decay every 30 epochs

    gamma

=

0.1

     

Multiply by 0.1 each time (i.e., reduced to 1/10)

)

LR changes:

Epoch  0-29:  0.1

Epoch 30-59:  0.01

Epoch 60-89:  0.001

Epoch 90+:    0.0001

Applicable Scenarios:Tasks with a fixed training pace and clear stages, such as training ResNet on ImageNet (90 epochs, decaying at epochs 30 and 60).


2.2 MultiStepLR (multi-milestone decay)

Decays the learning rate at specified epochs (milestones), more flexible than StepLR.

Example

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

scheduler

=

optim.

lr_scheduler

.

MultiStepLR

(

    optimizer

,

    milestones

=

[

30

,

60

,

80

]

,

 

Decay at epochs 30, 60, 80

    gamma

=

0.1

)

LR changes:

Epoch  0-29:  0.1

Epoch 30-59:  0.01

Epoch 60-79:  0.001

Epoch 80+:    0.0001

Applicable Scenarios:When you know at which epochs the model needs fine adjustments, such as the mid-to-late fine convergence stage in classification models.


2.3 ExponentialLR (exponential decay)

Decays every epoch; the learning rate decreases exponentially and more smoothly.

Formula: lr = lr_base * gamma^epoch

Example

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.01

)

scheduler

=

optim.

lr_scheduler

.

ExponentialLR

(

    optimizer

,

    gamma

=

0.95

 

Multiply by 0.95 each epoch

)

LR changes (first 5 epochs):

Epoch 1: 0.0100

Epoch 2: 0.0095

Epoch 3: 0.0090

Epoch 4: 0.0086

Epoch 5: 0.0081

gamma Setting it too small (e.g., 0.5) makes the learning rate rapidly approach zero; it is usually set between 0.9 and 0.99.


3. Adaptive schedulers

3.1 ReduceLROnPlateau (metric-based decay)

One of the smartest schedulers: monitors a metric (such as validation loss) and automatically lowers the learning rate when it stops improving. No need to know in advance which epoch to decay at.

Example

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.01

)

scheduler

=

optim.

lr_scheduler

.

ReduceLROnPlateau

(

    optimizer

,

    mode

=

'min'

,

     

'min': smaller monitored value is better (loss); 'max': larger is better (accuracy)

    factor

=

0.1

,

     

When triggered, lr = lr * factor

    patience

=

10

,

     

Number of epochs the metric may plateau before decaying

    threshold

=

1e-4

,

 

Improvement smaller than this value counts as no improvement

    min_lr

=

1e-6

,

     

Lower bound of learning rate; it will not go below this value

    verbose

=

True

     

Print decay information

)

for

epoch

in

range

(

100

)

:

    train_loss

=

train

(

model

,

optimizer

)

    val_loss  

=

evaluate

(

model

)

   

Unlike other schedulers, a monitored metric is passed in here

    scheduler.

step

(

val_loss

)

How to monitor Accuracy:

Example

scheduler

=

optim.

lr_scheduler

.

ReduceLROnPlateau

(

    optimizer

,

    mode

=

'max'

,

     

larger accuracy is better

    factor

=

0.5

,

    patience

=

5

,

)

scheduler.

step

(

val_accuracy

)

Applicable Scenarios:The default first choice for almost all tasks, especially when the number of epochs is uncertain or training is unstable.


3.2 CosineAnnealingLR (cosine annealing)

The learning rate follows acosine curvedecreasing smoothly from the initial value to the minimum (eta_min), avoiding the abrupt changes of step decay.

Formula: lr_t = eta_min + 0.5 * (eta_max - eta_min) * (1 + cos(t * pi / T_max)

Example

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

scheduler

=

optim.

lr_scheduler

.

CosineAnnealingLR

(

    optimizer

,

    T_max

=

100

,

   

Length of half a cycle (usually set to the total number of epochs)

    eta_min

=

1e-6

 

Minimum learning rate (default 0)

)

LR trajectory (illustration for T_max=10):

0.1 -> 0.095 -> 0.079 -> 0.055 -> 0.026 -> 0.001

             (smooth cosine curve decline)

Applicable Scenarios:Scenarios with a fixed number of training epochs; widely used in papers such as Vision Transformer and ResNet, with good convergence quality.


3.3 CosineAnnealingWarmRestarts

An upgraded version of cosine annealing that supportsperiodic restarts(Warm Restarts): after each cycle the learning rate resets to the initial value and starts a new cosine decay, allowing the model to escape local optima.

Example

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

scheduler

=

optim.

lr_scheduler

.

CosineAnnealingWarmRestarts

(

    optimizer

,

    T_0

=

10

,

     

Length of the first cycle (number of epochs)

    T_mult

=

2

,

   

Multiplier of cycle length after each restart (1 = equal length, 2 = progressively longer)

    eta_min

=

1e-6

)

Cycle lengths when T_mult=2: 10 -> 20 -> 40 -> 80 ...

LR changes (T_0=10, T_mult=1):

0.1 -> ... -> 0 -> 0.1 -> ... -> 0 -> 0.1 (restart every 10 epochs)

Applicable Scenarios:When training large models, or when you want the model to pick the best among multiple convergence points, using it with Snapshot Ensemble works very well.


4. Warmup schedulers

**Warmup** means that during the first few steps of training, the learning rate gradually rises from a very small value to the target value. Large batch size training and Transformer-like models almost always need warmup; otherwise early gradient updates are too aggressive and the model is hard to stabilize.

4.1 LinearLR (linear scheduling)

Linearly changes the learning rate over a specified number of epochs (can be used for linear warmup or linear decay).

Example

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.01

)

Linear warmup: over the first 5 epochs, lr grows linearly from 0.01*0.1=0.001 to 0.01

warmup_scheduler

=

optim.

lr_scheduler

.

LinearLR

(

    optimizer

,

    start_factor

=

0.1

,

 

Initial lr = base_lr * start_factor

    end_factor

=

1.0

,

   

Final lr = base_lr * end_factor

    total_iters

=

5

     

Completed over 5 epochs

)

LR changes: 0.001 -> 0.003 -> 0.005 -> 0.007 -> 0.009 -> 0.01


4.2 ConstantLR (constant phase)

For a specified number of epochs, fixes the learning rate at base_lr × factor, then restores the original value.

Example

Use base_lr * 0.5 for the first 5 epochs, then return to normal

scheduler

=

optim.

lr_scheduler

.

ConstantLR

(

    optimizer

,

    factor

=

0.5

,

    total_iters

=

5

)


4.3 SequentialLR (combined scheduling)

Chaining multiple schedulersin orderis the standard way to implement a combined 'warmup + decay' strategy.

Example

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.01

)

Phase 1: warmup (first 5 epochs, LR grows linearly from 0.001 to 0.01)

warmup

=

optim.

lr_scheduler

.

LinearLR

(

    optimizer

,

start_factor

=

0.1

,

end_factor

=

1.0

,

total_iters

=

5

)

Phase 2: cosine annealing (remaining 95 epochs)

cosine

=

optim.

lr_scheduler

.

CosineAnnealingLR

(

    optimizer

,

T_max

=

95

,

eta_min

=

1e-6

)

Combination: run warmup first, switch to cosine after the 5th epoch

scheduler

=

optim.

lr_scheduler

.

SequentialLR

(

    optimizer

,

    schedulers

=

[

warmup

,

cosine

]

,

    milestones

=

[

5

]

         

Switch at the 5th epoch

)

Usage is identical to a normal scheduler

for

epoch

in

range

(

100

)

:

    train

(

...

)

    scheduler.

step

(

)

Applicable Scenarios:The standard for Transformer training (warmup + cosine annealing); the pretraining of BERT, GPT, and ViT all use this strategy.


5. Cyclic schedulers

5.1 CyclicLR (cyclic learning rate)

The learning rate cycles base_lr and max_lr betweenperiodically, helping the model explore a broader parameter space and escape saddle points.

Example

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.01

)

scheduler

=

optim.

lr_scheduler

.

CyclicLR

(

    optimizer

,

    base_lr

=

0.001

,

         

Lower bound of learning rate

    max_lr

=

0.01

,

           

Upper bound of learning rate

    step_size_up

=

2000

,

     

Number of iterations to rise from base_lr to max_lr

    step_size_down

=

2000

,

   

Number of iterations to fall from max_lr to base_lr (default equals step_size_up)

    mode

=

'triangular'

,

     

Triangular cycle (constant amplitude)

   

mode='triangular2' # amplitude halves each cycle

   

mode='exp_range' # amplitude decays exponentially

)

CyclicLR is called per step (batch), not per epoch

for

epoch

in

range

(

num_epochs

)

:

   

for

inputs

,

labels

in

train_loader:

        optimizer.

zero_grad

(

)

        loss

=

criterion

(

model

(

inputs

)

,

labels

)

        loss.

backward

(

)

        optimizer.

step

(

)

        scheduler.

step

(

)

   

Call after each batch

Comparison of three modes:

mode Amplitude change Feature
triangular Unchanged Stable exploration, suitable for early stages
triangular2 Halves each cycle Explore first, then converge
exp_range Exponential decay Eventually converges smoothly

5.2 OneCycleLR (one-cycle policy)

One of the best-performing schedulers, the 1-Cycle Policy proposed by fastai. The whole training has just one cycle: the learning rate first rises then falls, while momentum changes in the opposite direction.

Faster training, usually needing only 1/5~1/10 of the epochs of traditional training to reach the same accuracy.

Example

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.01

,

momentum

=

0.9

)

steps_per_epoch

=

len

(

train_loader

)

scheduler

=

optim.

lr_scheduler

.

OneCycleLR

(

    optimizer

,

    max_lr

=

0.1

,

                             

Peak learning rate

    steps_per_epoch

=

steps_per_epoch

,

       

Number of steps per epoch

    epochs

=

10

,

                             

Total number of epochs

    pct_start

=

0.3

,

                         

First 30% for warmup rise

    anneal_strategy

=

'cos'

,

                 

Decay strategy ('cos' or 'linear')

    div_factor

=

25

,

                         

Initial lr = max_lr / div_factor

    final_div_factor

=

1e4

                   

Final lr = max_lr / final_div_factor

)

Initial lr = 0.1 / 25 = 0.004

Peak lr = 0.1 (at 30%)

Final lr = 0.1 / 10000 = 0.00001

Also called per batch

for

epoch

in

range

(

10

)

:

   

for

inputs

,

labels

in

train_loader:

        optimizer.

zero_grad

(

)

        loss

=

criterion

(

model

(

inputs

)

,

labels

)

        loss.

backward

(

)

        optimizer.

step

(

)

        scheduler.

step

(

)

   

Call after each batch

Applicable Scenarios:First choice when computational resources are limited and ideas need quick validation;max_lr It is recommended to determine the optimal value with the LR Finder tool.


6. Custom schedulers

6.1 LambdaLR (functional customization)

Fully customize the scheduling strategy by passing a Lambda function (takes the epoch number, returns a learning rate multiplier).

Example

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.01

)

Example 1: classic Transformer warmup strategy

lr ∝ min(step^-0.5, step × warmup_steps^-1.5)

def

transformer_lr

(

epoch

,

warmup_epochs

=

10

,

d_model

=

512

)

:

   

if

epoch

==

0

:

       

return

1e-7

/

0.01

         

Avoid division by zero

    step

=

epoch +

1

    warmup

=

warmup_epochs

   

return

(

d_model ** -

0.5

)

min

(

step ** -

0.5

,

step * warmup ** -

1.5

)

/

0.01

scheduler

=

optim.

lr_scheduler

.

LambdaLR

(

optimizer

,

lr_lambda

=

transformer_lr

)

Example 2: polynomial decay (lr decreases linearly/polynomially from the initial value to 0)

def

polynomial_decay

(

epoch

,

total_epochs

=

100

,

power

=

1.0

)

:

   

return

max

(

(

1

)

** power

,

0.0

)

scheduler

=

optim.

lr_scheduler

.

LambdaLR

(

optimizer

,

lr_lambda

=

polynomial_decay

)

Example 3: grouped learning rates (different strategies for different parameter groups)

optimizer

=

optim.

Adam

(

[

   

{

'params'

: model.

backbone

.

parameters

(

)

,

'lr'

:

1e-4

}

,

   

{

'params'

: model.

head

.

parameters

(

)

,

   

'lr'

:

1e-3

}

,

]

)

One lambda function per parameter group

scheduler

=

optim.

lr_scheduler

.

LambdaLR

(

    optimizer

,

    lr_lambda

=

[

       

lambda

epoch:

0.95

** epoch

,

   

backbone: slow decay

       

lambda

epoch:

0.85

** epoch

,

   

head: fast decay

   

]

)


6.2 Subclassing LRScheduler

When more complex logic is needed, subclass LRScheduler(PyTorch >= 2.0, in older versions it is _LRScheduler) to implement full customization:

Example

from

torch.

optim

.

lr_scheduler

import

LRScheduler

import

math

class

WarmupCosineScheduler

(

LRScheduler

)

:

   

"""
    Warmup + cosine annealing combined scheduler (manual implementation)
    - Linear warmup for the first warmup_epochs epochs
    - Then cosine annealing down to min_lr
    """

   

def

init

(

self

,

optimizer

,

warmup_epochs

,

total_epochs

,

                 min_lr

=

1e-6

,

last_epoch

=

1

)

:

       

self

.

warmup_epochs

=

warmup_epochs

       

self

.

total_epochs

 

=

total_epochs

       

self

.

min_lr

       

=

min_lr

       

super

(

)

.

init

(

optimizer

,

last_epoch

)

   

def

get_lr

(

self

)

:

        epoch

=

self

.

last_epoch

       

Warmup phase: linear increase

       

if

epoch

<

self

.

warmup_epochs

:

            warmup_factor

=

(

epoch +

1

)

/

self

.

warmup_epochs

           

return

[

base_lr * warmup_factor

for

base_lr

in

self

.

base_lrs

]

       

Cosine annealing phase

        progress

=

(

epoch -

self

.

warmup_epochs

)

/

(

           

self

.

total_epochs

self

.

warmup_epochs

       

)

        cosine_factor

=

0.5

(

1

math

.

cos

(

math

.

pi

)

)

       

return

[

           

self

.

min_lr

(

base_lr -

self

.

min_lr

)

           

for

base_lr

in

self

.

base_lrs

       

]

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.01

)

scheduler

=

WarmupCosineScheduler

(

    optimizer

,

    warmup_epochs

=

10

,

    total_epochs

=

100

,

    min_lr

=

1e-6

)


7. Scheduler Visualization Comparison

The following code plots the LR curves of each scheduler for intuitive comparison:

Example

import

torch

import

torch.

optim

as

optim

import

matplotlib.

pyplot

as

plt

def

simulate_lr

(

scheduler_fn

,

epochs

=

100

,

steps_per_epoch

=

None

)

:

   

"""Simulate and record the learning rate changes of the scheduler"""

    model    

=

torch.

nn

.

Linear

(

1

,

1

)

    optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

    scheduler

=

scheduler_fn

(

optimizer

)

    lrs

=

[

]

   

if

steps_per_epoch:

       

Schedulers called per step

       

for

_

in

range

(

epochs

)

:

           

for

_

in

range

(

steps_per_epoch

)

:

                optimizer.

step

(

)

                scheduler.

step

(

)

                lrs.

append

(

optimizer.

param_groups

[

0

]

[

'lr'

]

)

   

else

:

       

Schedulers called per epoch

       

for

_

in

range

(

epochs

)

:

            optimizer.

step

(

)

            scheduler.

step

(

)

            lrs.

append

(

optimizer.

param_groups

[

0

]

[

'lr'

]

)

   

return

lrs

schedulers

=

{

   

'StepLR(step=30, gamma=0.1)'

:

       

lambda

opt: optim.

lr_scheduler

.

StepLR

(

opt

,

30

,

0.1

)

,

   

'CosineAnnealingLR'

:

       

lambda

opt: optim.

lr_scheduler

.

CosineAnnealingLR

(

opt

,

T_max

=

100

)

,

   

'ExponentialLR(gamma=0.95)'

:

       

lambda

opt: optim.

lr_scheduler

.

ExponentialLR

(

opt

,

0.95

)

,

   

'CosineWarmRestarts(T0=25)'

:

       

lambda

opt: optim.

lr_scheduler

.

CosineAnnealingWarmRestarts

(

opt

,

T_0

=

25

)

,

}

plt.

figure

(

figsize

=

(

12

,

5

)

)

for

name

,

fn

in

schedulers.

items

(

)

:

    plt.

plot

(

simulate_lr

(

fn

)

,

label

=

name

)

plt.

xlabel

(

'Epoch'

)

plt.

ylabel

(

'Learning Rate'

)

plt.

title

(

'PyTorch LR Scheduler Comparison'

)

plt.

legend

(

)

plt.

grid

(

True

,

alpha

=

0.3

)

plt.

tight_layout

(

)

plt.

savefig

(

'lr_schedulers.png'

,

dpi

=

150

)

plt.

show

(

)


8. Complete Training Template

A production-grade training template integrating warmup + cosine annealing, model saving and resuming:

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

from

torch.

optim

.

lr_scheduler

import

SequentialLR

,

LinearLR

,

CosineAnnealingLR

Hyperparameters

EPOCHS      

=

100

WARMUP_EPOCHS

=

5

BASE_LR      

=

1e-3

MIN_LR      

=

1e-6

SAVE_PATH    

=

'best_model.pth'

device

=

torch.

device

(

'cuda'

if

torch.

cuda

.

is_available

(

)

else

'cpu'

)

Model / optimizer / scheduler

model    

=

MyModel

(

)

.

to

(

device

)

optimizer

=

optim.

AdamW

(

model.

parameters

(

)

,

lr

=

BASE_LR

,

weight_decay

=

1e-4

)

criterion

=

nn.

CrossEntropyLoss

(

label_smoothing

=

0.1

)

Warmup 5 epochs + cosine annealing 95 epochs

warmup_sched

=

LinearLR

(

optimizer

,

start_factor

=

0.1

,

total_iters

=

WARMUP_EPOCHS

)

cosine_sched

=

CosineAnnealingLR

(

optimizer

,

T_max

=

EPOCHS - WARMUP_EPOCHS

,

eta_min

=

MIN_LR

)

scheduler    

=

SequentialLR

(

optimizer

,

[

warmup_sched

,

cosine_sched

]

,

milestones

=

[

WARMUP_EPOCHS

]

)

Restore a checkpoint

start_epoch

=

0

best_acc    

=

0.0

try

:

    ckpt

=

torch.

load

(

SAVE_PATH

,

map_location

=

device

)

    model.

load_state_dict

(

ckpt

[

'model'

]

)

    optimizer.

load_state_dict

(

ckpt

[

'optimizer'

]

)

    scheduler.

load_state_dict

(

ckpt

[

'scheduler'

]

)

    start_epoch

=

ckpt

[

'epoch'

]

1

    best_acc    

=

ckpt

[

'best_acc'

]

   

print

(

f

"Resumed from Epoch {start_epoch}, best accuracy {best_acc:.4f}"

)

except

FileNotFoundError:

   

print

(

"Training from scratch"

)

Training loop

history

=

{

'train_loss'

:

[

]

,

'val_acc'

:

[

]

,

'lr'

:

[

]

}

for

epoch

in

range

(

start_epoch

,

EPOCHS

)

:

   

Training

    model.

train

(

)

    total_loss

=

0.0

   

for

inputs

,

labels

in

train_loader:

        inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

        optimizer.

zero_grad

(

)

        loss

=

criterion

(

model

(

inputs

)

,

labels

)

        loss.

backward

(

)

        torch.

nn

.

utils

.

clip_grad_norm_

(

model.

parameters

(

)

,

max_norm

=

1.0

)

 

Gradient clipping

        optimizer.

step

(

)

        total_loss +

=

loss.

item

(

)

   

Validation

    model.

eval

(

)

    correct

=

0

   

with

torch.

no_grad

(

)

:

       

for

inputs

,

labels

in

val_loader:

            inputs

,

labels

=

inputs.

to

(

device

)

,

labels.

to

(

device

)

            correct +

=

(

model

(

inputs

)

.

argmax

(

1

)

==

labels

)

.

sum

(

)

.

item

(

)

    avg_loss

=

total_loss /

len

(

train_loader

)

    val_acc  

=

correct /

len

(

val_loader.

dataset

)

    cur_lr  

=

scheduler.

get_last_lr

(

)

[

0

]

   

Log & print

    history

[

'train_loss'

]

.

append

(

avg_loss

)

    history

[

'val_acc'

]

.

append

(

val_acc

)

    history

[

'lr'

]

.

append

(

cur_lr

)

   

print

(

f

"Epoch {epoch+1:3d}/{EPOCHS} | "

          f

"Loss: {avg_loss:.4f} | Acc: {val_acc:.4f} | LR: {cur_lr:.2e}"

)

   

Scheduler step

    scheduler.

step

(

)

   

Save best model

   

if

val_acc

best_acc:

        best_acc

=

val_acc

        torch.

save

(

{

           

'epoch'

:      epoch

,

           

'model'

:      model.

state_dict

(

)

,

           

'optimizer'

:  optimizer.

state_dict

(

)

,

           

'scheduler'

:  scheduler.

state_dict

(

)

,

           

'best_acc'

:   best_acc

,

       

}

,

SAVE_PATH

)

       

print

(

f

" Save best model, Acc: {best_acc:.4f}"

)

print

(

f

"\nTraining complete, best validation accuracy: {best_acc:.4f}"

)


9. Scheduler Selection Guide

Recommendations by task type

Scenario Recommended scheduler Reason
Quick experiments / prototyping ReduceLROnPlateau No hyperparameter tuning needed, adaptive decay
Image classification (fixed epochs) CosineAnnealingLR Smooth decay, good convergence quality
Transformer / BERT LinearLR + CosineAnnealingLR Warmup is essential
Limited resources, fast training OneCycleLR Same accuracy in 1/5 the time
Large model fine-tuning (fine-tune) LinearLR(warmup) + ConstantLR Stable fine-tuning with low learning rate
Uncertain number of epochs ReduceLROnPlateau Automatic response, no reliance on a fixed schedule
Object detection (YOLO/Faster-RCNN) MultiStepLR / OneCycleLR Clear decay points or pursuit of speed
Want to escape local optima CosineAnnealingWarmRestarts Periodic restarts to explore parameter space

Common configuration combos

Example

Combo 1: Warmup + cosine annealing (Transformer standard)

SequentialLR

(

[

LinearLR

(

5

epochs

)

,

CosineAnnealingLR

(

95

epochs

)

]

)

Combo 2: Monitor validation set + automatic decay (general first choice)

ReduceLROnPlateau

(

mode

=

'min'

,

patience

=

5

,

factor

=

0.5

)

Combo 3: OneCycleLR (first choice for fast training)

OneCycleLR

(

max_lr

=

0.1

,

total_steps

=

total_steps

,

pct_start

=

0.3

)

Combo 4: Traditional step decay (CV classic)

MultiStepLR

(

milestones

=

[

30

,

60

,

90

]

,

gamma

=

0.1

)

Common Pitfalls Quick Reference

Problem Solution
Scheduler not taking effect Checks scheduler.step() whether optimizer.step() after called
CyclicLR / OneCycleLR no change These two are triggered per batch call, not per epoch
ReduceLROnPlateau not triggering Checks mode whether set correctly (loss uses 'min', accuracy uses 'max')
LR incorrect after resuming training Check whether saved and loaded scheduler.state_dict()
Multiple parameter group LR settings Use LambdaLR Pass a list, one lambda per parameter group