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

PyTorch torch.optim optimizer module

PyTorch torch.optim optimizer module

An optimizer is a core component in deep learning, responsible for adjusting model parameters based on the gradients of the loss function so that the model gradually approaches the optimal solution.

In PyTorch, the torch.optim module provides implementations of various optimization algorithms and is an indispensable tool for training neural networks.


Why optimizers are needed

Optimizers play a crucial role in deep learning, solving the tedious problem of manually updating parameters.

Common optimizer types

Different optimizers suit different scenarios; choosing the right optimizer can significantly improve training results.

Optimizer name Main Features Applicable scenarios
SGD Simple and basic, supports momentum Basic teaching, simple models, CNN
Adam Adaptive learning rate Most deep learning tasks
AdamW Adam + decoupled weight decay Tasks requiring L2 regularization
RMSprop Adaptive learning rate RNN networks, speech recognition
Adagrad Per-parameter learning rates Sparse data, text processing
Adadelta Adaptive learning rate Long-term training tasks

Core optimizer API

Mastering the basic usage flow of an optimizer is the first step in deep learning.

Basic usage flow

Using an optimizer follows a fixed pattern: create instance -> clear gradients -> backpropagate -> update parameters.

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

1. Define a simple model

class

SimpleNet

(

nn.

Module

)

:

   

def

init

(

self

)

:

       

super

(

)

.

init

(

)

       

self

.

fc

=

nn.

Linear

(

784

,

10

)

   

def

forward

(

self

,

x

)

:

       

return

self

.

fc

(

x

)

model

=

SimpleNet

(

)

2. Create an optimizer instance

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.001

)

3. Training loop

for

epoch

in

range

(

epochs

)

:

   

Forward propagation

    outputs

=

model

(

inputs

)

    loss

=

criterion

(

outputs

,

labels

)

   

Backpropagation

    optimizer.

zero_grad

(

)

 

Clear the gradient buffer to avoid gradient accumulation

    loss.

backward

(

)

       

Compute gradients

   

Parameter update

    optimizer.

step

(

)

     

Update parameters

Key methods

Optimizers provide several core methods to manage the parameter update process.

Note: You must call zero_grad() before each backpropagation, otherwise gradients will accumulate and cause unstable training. It is recommended to use zero_grad(set_to_none=True) to save GPU memory.

Saving and loading optimizer state

When resuming training, you need to save both the model and optimizer states.

Example

Save a checkpoint (saving the model, optimizer, and scheduler together)

checkpoint

=

{

   

'epoch'

: epoch

,

   

'model_state_dict'

: model.

state_dict

(

)

,

   

'optimizer_state_dict'

: optimizer.

state_dict

(

)

,

   

'scheduler_state_dict'

: scheduler.

state_dict

(

)

,

   

'loss'

: loss

,

}

torch.

save

(

checkpoint

,

'checkpoint.pth'

)

Load a Checkpoint

checkpoint

=

torch.

load

(

'checkpoint.pth'

)

model.

load_state_dict

(

checkpoint

[

'model_state_dict'

]

)

optimizer.

load_state_dict

(

checkpoint

[

'optimizer_state_dict'

]

)

scheduler.

load_state_dict

(

checkpoint

[

'scheduler_state_dict'

]

)

start_epoch

=

checkpoint

[

'epoch'

]

1


Detailed explanation of common optimizers

SGD (Stochastic Gradient Descent)

SGD is the most basic optimization algorithm, updating parameters by computing gradients over a single sample or a mini-batch. It is the cornerstone of deep learning optimization, and many advanced optimizers are built on top of SGD.

Example

SGD optimizer parameter description

params: Parameters to optimize (usually from model.parameters())

lr: Learning rate, controlling the step size of parameter updates, default 0.01

momentum: Momentum factor, used to accelerate convergence and reduce oscillation, default 0

weight_decay: L2 regularization coefficient, used to prevent overfitting, default 0

dampening: Momentum damping, controlling the computation of the momentum term, default 0

nesterov: Whether to use Nesterov momentum, default False

optimizer

=

optim.

SGD

(

    params

=

model.

parameters

(

)

,

    lr

=

0.01

,

         

Learning Rate

    momentum

=

0.9

,

     

Momentum factor

    weight_decay

=

1e-4

,

L2 regularization

    nesterov

=

True

     

Enable Nesterov momentum

)

Core parameter description:

Characteristics:

Although SGD is simple, it often achieves good results with appropriate hyperparameters and is a good starting point for learning optimization algorithms. In image classification tasks, SGD with momentum remains a mainstream choice.

Adam (Adaptive Moment Estimation)

Adam is currently one of the most commonly used optimizers, combining the advantages of momentum and adaptive learning rates. It adaptively adjusts the learning rate of each parameter by computing first- and second-order moment estimates of the gradients.

Example

Adam optimizer parameter description

params: Parameters to optimize

lr: Learning rate, default 0.001 (recommended value)

betas: Coefficients for computing moving averages of the gradient and its square (beta1, beta2)

        beta1 controls the first-moment estimate (momentum), default 0.9

        beta2 controls the second-moment estimate (variance), default 0.999

eps: Numerical stability term to prevent division by zero, default 1e-8

weight_decay: L2 regularization coefficient, default 0

amsgrad: Whether to use the AMSGrad variant, default False

optimizer

=

optim.

Adam

(

    params

=

model.

parameters

(

)

,

    lr

=

0.001

,

                     

A smaller learning rate is recommended

    betas

=

(

0.9

,

0.999

)

,

           

Commonly used momentum parameters

    eps

=

1e-8

,

                     

Numerical stability term

    weight_decay

=

1e-4

,

           

L2 regularization

    amsgrad

=

False

                 

Whether to use AMSGrad

)

Core parameter description:

Characteristics:

Adam is the default choice for most deep learning tasks, but in certain scenarios (such as GANs and reinforcement learning) you may need to try other optimizers.

AdamW (Adam with Weight Decay)

AdamW is an improved version of Adam that decouples weight decay from gradient updates, which is theoretically better for convergence. In practice, AdamW usually performs better than Adam.

Example

AdamW optimizer

Main difference from Adam: the implementation of weight_decay is different

AdamW's weight decay is more correct and does not affect gradient computation

optimizer

=

optim.

AdamW

(

    params

=

model.

parameters

(

)

,

    lr

=

0.001

,

    betas

=

(

0.9

,

0.999

)

,

    weight_decay

=

0.01

,

   

Weight decay coefficient, usually set larger than in Adam

    amsgrad

=

False

)

Recommended configuration: AdamW typically uses a weight_decay of 0.01

while Adam typically uses 0.001

If your task requires weight decay (L2 regularization), AdamW is strongly recommended over Adam.

RMSprop

RMSprop is an adaptive learning rate optimizer particularly suited to non-stationary objectives and recurrent neural networks.

Example

RMSprop optimizer

Normalizes the learning rate by dividing by the exponentially weighted average of gradients

optimizer

=

optim.

RMSprop

(

    params

=

model.

parameters

(

)

,

    lr

=

0.01

,

             

Learning Rate

    alpha

=

0.99

,

           

Exponential decay rate for squared gradients

    eps

=

1e-8

,

             

Numerical stability term

    weight_decay

=

0

,

       

L2 regularization

    momentum

=

0

,

           

Momentum factor

    centered

=

False

       

Whether to center the gradients

)

Adagrad

Adagrad is suitable for sparse data; it adaptively adjusts the learning rate for each parameter.

Example

Adagrad optimizer

Suitable for optimizing sparse data, it uses smaller learning rates for frequently updated parameters

optimizer

=

optim.

Adagrad

(

    params

=

model.

parameters

(

)

,

    lr

=

0.01

,

             

Learning Rate

    lr_decay

=

0

,

           

Learning rate decay

    weight_decay

=

0

,

     

L2 regularization

    initial_accumulator_value

=

0

 

Initial accumulator value

)


Advanced optimizer techniques

Learning rate scheduling

Learning rate scheduling allows dynamic adjustment of the learning rate during training, which can often significantly improve model convergence.

Example: Various learning rate schedulers

from

torch.

optim

.

lr_scheduler

import

(

    StepLR

,

               

Step decay

    MultiStepLR

,

         

Multi-milestone decay

    ExponentialLR

,

       

Exponential decay

    CosineAnnealingLR

,

   

Cosine annealing

    ReduceLROnPlateau

,

   

Automatic adjustment based on metrics

)

Method 1: StepLR - decay every 30 epochs

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

scheduler

=

StepLR

(

optimizer

,

step_size

=

30

,

gamma

=

0.1

)

Method 2: MultiStepLR - decay at specified epochs

optimizer

=

optim.

SGD

(

model.

parameters

(

)

,

lr

=

0.1

)

scheduler

=

MultiStepLR

(

optimizer

,

milestones

=

[

30

,

60

,

80

]

,

gamma

=

0.1

)

Method 3: CosineAnnealingLR - cosine annealing

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.001

)

scheduler

=

CosineAnnealingLR

(

optimizer

,

T_max

=

50

,

eta_min

=

1e-6

)

Method 4: ReduceLROnPlateau - automatic adjustment based on a monitored metric

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.001

)

scheduler

=

ReduceLROnPlateau

(

    optimizer

,

mode

=

'min'

,

   

Monitor loss

    factor

=

0.5

,

               

Decay factor

    patience

=

5

,

               

Number of epochs to wait

    verbose

=

True

               

Print information

)

Training loop

for

epoch

in

range

(

100

)

:

    train_loss

=

train

(

...

)

    val_loss

=

validate

(

...

)

   

Schedulers such as StepLR

    scheduler.

step

(

)

   

ReduceLROnPlateau requires the monitored metric to be passed in

    scheduler.

step

(

val_loss

)

Learning rate schedulers need to be used together with an optimizer; step() must be called after optimizer.step(), otherwise the learning rate may be updated incorrectly.

Parameter group optimization

Parameter groups allow different learning rates to be set for different layers, which is particularly useful in transfer learning.

Example

Parameter group optimization example

Set different learning rates for different layers

Typically: the backbone uses a smaller learning rate, and the classification head uses a larger one

optimizer

=

optim.

SGD

(

[

   

{

'params'

: model.

base

.

parameters

(

)

,

'lr'

:

1e-3

}

,

     

Base layers: large learning rate

   

{

'params'

: model.

classifier

.

parameters

(

)

,

'lr'

:

1e-2

}

Classification layer: large learning rate

]

,

lr

=

1e-4

)

 

Global default learning rate (used when no parameter group is specified)

A more common way of writing this in practice

optimizer

=

optim.

Adam

(

[

   

{

'params'

: model.

fc

.

parameters

(

)

,

'lr'

:

1e-3

}

,

     

Classification head

   

{

'params'

:

[

p

for

n

,

p

in

model.

named_parameters

(

)

   

Backbone network

               

if

not

n.

startswith

(

'fc'

)

]

,

     

'lr'

:

1e-5

}

,

]

)

Gradient clipping

Gradient clipping can prevent exploding gradients and improve training stability. It is especially useful in deep networks such as RNNs and LSTMs.

Example

import

torch.

nn

as

nn

Gradient clipping example

max_norm: The maximum norm of gradients; gradients exceeding this value are scaled

norm_type: The type of norm, default 2 (L2 norm)

nn.

utils

.

clip_grad_norm_

(

model.

parameters

(

)

,

max_norm

=

1.0

)

Where to use it in the training loop

for

epoch

in

range

(

epochs

)

:

    optimizer.

zero_grad

(

)

    outputs

=

model

(

inputs

)

    loss

=

criterion

(

outputs

,

labels

)

    loss.

backward

(

)

   

Clip gradients after loss.backward() and before optimizer.step()

    nn.

utils

.

clip_grad_norm_

(

model.

parameters

(

)

,

max_norm

=

1.0

)

    optimizer.

step

(

)

Another way to clip gradients: clipping by value

for

param

in

model.

parameters

(

)

:

   

if

param.

grad

is

not

None

:

        param.

grad

.

data

.

clamp_

(

min

=

1.0

,

max

=

1.0

)

Gradient clipping is a common technique for training deep neural networks (especially RNNs, LSTMs, etc.), effectively preventing training collapse caused by exploding gradients.

Gradient accumulation

When GPU memory is insufficient, gradient accumulation can be used to simulate the effect of training with a large batch size.

Example

Gradient accumulation example

Actual batch_size = batch_size * accumulation_steps

accumulation_steps

=

4

 

Accumulate 4 small batches

optimizer.

zero_grad

(

)

for

i

,

(

inputs

,

labels

)

in

enumerate

(

train_loader

)

:

    outputs

=

model

(

inputs

)

    loss

=

criterion

(

outputs

,

labels

)

   

Divide the loss by the number of accumulation steps to average it

    loss

=

loss / accumulation_steps

    loss.

backward

(

)

   

Update parameters once every specified number of accumulation steps

   

if

(

i +

1

)

% accumulation_steps

==

0

:

        nn.

utils

.

clip_grad_norm_

(

model.

parameters

(

)

,

max_norm

=

1.0

)

        optimizer.

step

(

)

        optimizer.

zero_grad

(

)

Handle the remaining gradients

if

(

i +

1

)

% accumulation_steps

!=

0

:

    optimizer.

step

(

)

    optimizer.

zero_grad

(

)


Complete training example

The following is a complete training flow demonstrating optimizer best practices.

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

from

torch.

optim

.

lr_scheduler

import

CosineAnnealingLR

Configure

DEVICE

=

torch.

device

(

'cuda'

if

torch.

cuda

.

is_available

(

)

else

'cpu'

)

EPOCHS

=

100

BATCH_SIZE

=

32

LR

=

1e-3

Create the model and move it to the device

model

=

SimpleNet

(

)

.

to

(

DEVICE

)

Loss function and optimizer

criterion

=

nn.

CrossEntropyLoss

(

)

optimizer

=

optim.

AdamW

(

model.

parameters

(

)

,

lr

=

LR

,

weight_decay

=

0.01

)

Learning rate scheduler (cosine annealing)

scheduler

=

CosineAnnealingLR

(

optimizer

,

T_max

=

EPOCHS

,

eta_min

=

1e-6

)

Training loop

best_acc

=

0.0

for

epoch

in

range

(

EPOCHS

)

:

    model.

train

(

)

    total_loss

=

0.0

    correct

=

0

   

for

inputs

,

labels

in

train_loader:

        inputs

=

inputs.

to

(

DEVICE

)

        labels

=

labels.

to

(

DEVICE

)

       

Clear gradients (set_to_none=True is recommended)

        optimizer.

zero_grad

(

set_to_none

=

True

)

       

Forward propagation

        outputs

=

model

(

inputs

)

        loss

=

criterion

(

outputs

,

labels

)

       

Backpropagation

        loss.

backward

(

)

       

Gradient clipping (to prevent exploding gradients)

        nn.

utils

.

clip_grad_norm_

(

model.

parameters

(

)

,

max_norm

=

1.0

)

       

Update parameters

        optimizer.

step

(

)

       

Statistics

        total_loss +

=

loss.

item

(

)

        correct +

=

(

outputs.

argmax

(

1

)

==

labels

)

.

sum

(

)

.

item

(

)

   

Update the learning rate

    scheduler.

step

(

)

   

Print training information

    avg_loss

=

total_loss /

len

(

train_loader

)

    accuracy

=

correct /

len

(

train_loader.

dataset

)

    current_lr

=

scheduler.

get_last_lr

(

)

[

0

]

   

print

(

f

"Epoch {epoch+1}/{EPOCHS} | Loss: {avg_loss:.4f} | "

          f

"Acc: {accuracy:.4f} | LR: {current_lr:.6f}"

)

   

Save the best model

   

if

accuracy

best_acc:

        best_acc

=

accuracy

        torch.

save

(

{

           

'epoch'

: epoch

,

           

'model_state_dict'

: model.

state_dict

(

)

,

           

'optimizer_state_dict'

: optimizer.

state_dict

(

)

,

           

'scheduler_state_dict'

: scheduler.

state_dict

(

)

,

           

'best_acc'

: best_acc

,

       

}

,

'best_model.pth'

)

print

(

f

"Training complete, best accuracy: {best_acc:.4f}"

)


Optimizer selection guide

Choosing the right optimizer depends on the specific task, data characteristics, and training stage.

Select by task

Different task types have different optimizer recommendations.

Task Type Recommended optimizer Recommended learning rate Notes
Image classification (CNN) SGD + Momentum 0.01 ~ 0.1 Slow convergence but high accuracy
Image classification (CNN) AdamW 0.001 Fast convergence
NLP / Transformer AdamW 1e-5 ~ 1e-4 Smaller learning rate
RNN / LSTM RMSprop / Adam 0.001 Adaptive learning rate
GAN Adam (G) / Adam (D) 0.0001 Smaller learning rate
Reinforcement Learning Adam / RMSprop 0.0001 ~ 0.001 Depends on the specific task
Quick experiments Adam / AdamW 0.001 Fast convergence

Performance Comparison

Optimizer Convergence speed Memory Usage Hyperparameter sensitivity Final accuracy
SGD + Momentum Slow Low High High
Adam fast Medium Low Medium
AdamW fast Medium Low High
RMSprop Medium Medium Medium Medium
Adagrad Medium High Medium Low

Common issues and solutions

The choice of optimizer is not absolute; it is recommended to start with Adam or AdamW and consider other optimizers if the results are unsatisfactory. For specific tasks, experiments may be needed to determine the optimal choice.

For more detailed information, refer to PyTorch official documentation.