torch.optim is a package implementing various optimization algorithms.
Most commonly used methods are already supported, and the interface is general
enough, so that more sophisticated ones can also be easily integrated in the
future.
How to use an optimizer
To use torch.optim you have to construct an optimizer object that will hold
the current state and will update the parameters based on the computed gradients.
Constructing it
To construct an Optimizer you have to give it an iterable containing the
parameters (all should be s) or named parameters
(tuples of (str, )) to optimize. Then,
you can specify optimizer-specific options such as the learning rate, weight decay, etc.
Optimizer s also support specifying per-parameter options. To do this, instead
of passing an iterable of Variable s, pass in an iterable of
dict s. Each of them will define a separate parameter group, and should contain
a params key, containing a list of parameters belonging to it. Other keys
should match the keyword arguments accepted by the optimizers, and will be used
as optimization options for this group.
For example, this is very useful when one wants to specify per-layer learning rates:
This means that model.base’s parameters will use a learning rate of 1e-2, whereas
model.classifier’s parameters will stick to the default learning rate of 1e-3.
Finally a momentum of 0.9 will be used for all parameters.
Also consider the following example related to the distinct penalization of parameters.
Remember that parameters() returns an iterable that
contains all learnable parameters, including biases and other
parameters that may prefer distinct penalization. To address this, one can specify
individual penalization weights for each parameter group:
In this manner, bias terms are isolated from non-bias terms, and a weight_decay
of 0 is set specifically for the bias terms, as to avoid any penalization for
this group.
Taking an optimization step
All optimizers implement a step() method, that updates the
parameters. It can be used in two ways:
optimizer.step()
This is a simplified version supported by most optimizers. The function can be
called once the gradients are computed using e.g.
backward().
Some optimization algorithms such as Conjugate Gradient and LBFGS need to
reevaluate the function multiple times, so you have to pass in a closure that
allows them to recompute your model. The closure should clear the gradients,
compute the loss, and return it.
Temporarily replace an optimizer’s parameters and state with the
supplied params and optim states, then restore them on exit.
For the duration of the context, all optimizer APIs (including
user hooks) see the swap-in values; the live optimizer is restored on
exit.
The difference between this API and optimizer.load_state_dict is
that optimizer.load_state_dict only updates the optimizer’s state
and leaves the parameters in param_groups untouched. This API also
swaps in the parameters, so that optimizer.step() acts on the
swap-in parameter tensors you supply.
Parameters:
optimizer (Optimizer) – the live optimizer; its state must already be
initialized.
swapin_parameters (dict[str, Tensor]) – tensors to use as parameters during the context,
provided in the same order as the existing input parameters to
the optimizer (most commonly in model.named_parameters()
order).
swapin_optim_state (dict[str, ) – an -shaped dict
() holding the state to
install. is keyed by packed integer parameter ids
and mirrors ,
with each entry as a list of those packed ids
and the remaining keys carrying per-group hyperparameters
(, , , , …).
Only in-place tensor edits propagate back to the user supplied
; all other side-effects (e.g.,
assigning a new tensor to the optim state)
are ignored.
Example
One use of this API is to run optimizer.step() against
FakeTensor versions of the parameters and state for nonstrict
tracing — capturing an FX graph of the step without touching the
live optimizer:
Implements stochastic gradient descent (optionally with momentum).
Many of our algorithms have various implementations optimized for performance,
readability and/or generality, so we attempt to default to the generally fastest
implementation for the current device if no particular implementation has been
specified by the user.
We have 3 major categories of implementations: for-loop, foreach (multi-tensor), and
fused. The most straightforward implementations are for-loops over the parameters with
big chunks of computation. For-looping is usually slower than our foreach
implementations, which combine parameters into a multi-tensor and run the big chunks
of computation all at once, thereby saving many sequential kernel calls. A few of our
optimizers have even faster fused implementations, which fuse the big chunks of
computation into one kernel. We can think of foreach implementations as fusing
horizontally and fused implementations as fusing vertically on top of that.
In general, the performance ordering of the 3 implementations is fused > foreach > for-loop.
So when applicable, we default to foreach over for-loop. Applicable means the foreach
implementation is available, the user has not specified any implementation-specific kwargs
(e.g., fused, foreach, differentiable), and all tensors are native. Note that while fused
should be even faster than foreach, the implementations are newer and we would like to give
them more bake-in time before flipping the switch everywhere. We summarize the stability status
for each implementation on the second table below, you are welcome to try them out though!
Below is a table showing the available and default implementations of each algorithm:
Most learning rate schedulers can be called back-to-back (also referred to as
chaining schedulers). The result is that each scheduler is applied one after the
other on the learning rate obtained by the one preceding it.
How to utilize named parameters to load optimizer state dict
The function load_state_dict() stores the optional param_names content from the
loaded state dict if present. However, the process of loading the optimizer state is not affected,
as the order of the parameters matters to maintain compatibility (in case of different ordering).
To utilize the loaded parameters names from the loaded state dict, a custom register_load_state_dict_pre_hook
needs to be implemented according to the desired behavior.
This can be useful, for instance, when the model architecture changes, but the weights and optimizer states need to
remain unchanged. The following example demonstrates how to implement this customization.
Let’s say that model implements an expert (MoE), and we want to duplicate it and resume training
for two experts, both initialized the same way as the fc layer. For the following model2 we create two layers identical to fc and resume training by loading the model weights and optimizer states from model into both fc1 and fc2 of model2 (and adjust them accordingly):
To load the state dict for optimizer2 with the state dict of the previous optimizer such that both
fc1 and fc2 will be initialized with a copy of fc optimizer states
(to resume training for each layer from fc), we can use the following hook:
defadapt_state_dict_ids(optimizer,state_dict):adapted_state_dict=deepcopy(optimizer.state_dict())# Copy setup parameters (lr, weight_decay, etc.), in case they differ in the loaded state dict.fork,vinstate_dict['param_groups'][0].items():ifknot
This ensures that the adapted state_dict with the correct states for the layers of model2 will be used
during model loading.
Note that this code is designed specifically for this example (e.g., assuming a single parameter group),
and other cases might require different adaptations.
The following example shows how to handle missing parameters in a loaded
statedict when the model structure changes.
The Model_bypass adds a new bypass layer, which is not present in the original Model1.
To resume training, a custom adapt_state_dict_missing_param hook is used to adapt the optimizer’s state_dict,
ensuring existing parameters are mapped correctly, while missing ones (like the bypass layer) remain unchanged
(as initialized in this example).
This approach enables smooth loading and resuming of the optimizer state despite model changes.
The new bypass layer will be trained from scratch:
As a third example, instead of loading a state according to the order of parameters (the default approach),
this hook can be used to load according to the parameters’ names:
EMA is a widely known technique to reduce the training time by reducing the number of weight updates needed.
It is a variation of Polyak averaging, but using exponential weights instead of equal weights across iterations.
Constructing averaged models
The AveragedModel class serves to compute the weights of the SWA or EMA model.
You can create an SWA averaged model by running:
>>> averaged_model=AveragedModel(model)
EMA models are constructed by specifying the multi_avg_fn argument as follows:
Decay is a parameter between 0 and 1 that controls how fast the averaged parameters are decayed. If not provided to torch.optim.swa_utils.get_ema_multi_avg_fn(), the default is 0.999. Decay value should be close to 1.0, as smaller values can cause optimization convergence issues.
where W_t^{\text{EMA}} is the EMA parameter at step t, W_t^{\text{model}} is the model parameter at step t, and decay is the EMA decay rate (default: 0.999).
Here the model model can be an arbitrary torch.nn.Module object. averaged_model
will keep track of the running averages of the parameters of the model. To update these
averages, you should use the update_parameters() function after the optimizer.step():
>>> averaged_model.update_parameters(model)
For SWA and EMA, this call is usually done right after the optimizer step(). In the case of SWA, this is usually skipped for some numbers of steps at the beginning of the training.
Custom averaging strategies
By default, torch.optim.swa_utils.AveragedModel computes a running equal average of
the parameters that you provide, but you can also use custom averaging functions with the
avg_fn or multi_avg_fn parameters:
avg_fn allows defining a function operating on each parameter tuple (averaged parameter, model parameter) and should return the new averaged parameter.
multi_avg_fn allows defining more efficient operations acting on a tuple of parameter lists, (averaged parameter list, model parameter list), at the same time, for example using the torch._foreach* functions. This function must update the averaged parameters in-place.
In the following example computes an exponential moving average using the parameter:
SWA learning rate schedules
Typically, in SWA the learning rate is set to a high constant value. SWALR is a
learning rate scheduler that anneals the learning rate to a fixed value, and then keeps it
constant. For example, the following code creates a scheduler that linearly anneals the
learning rate from its initial value to 0.05 in 5 epochs within each parameter group:
update_bn() is a utility function that allows to compute the batchnorm statistics for the SWA model
on a given dataloader loader at the end of training:
update_bn() applies the swa_model to every element in the dataloader and computes the activation
statistics for each batch normalization layer in the model.
Putting it all together: SWA
In the example below, swa_model is the SWA model that accumulates the averages of the weights.
We train the model for a total of 300 epochs and we switch to the SWA learning rate schedule
and start to collect SWA averages of the parameters at epoch 160:
In the example below, ema_model is the EMA model that accumulates the exponentially-decayed averages of the weights with a decay rate of 0.999.
We train the model for a total of 300 epochs and start to collect EMA averages immediately.
Update BatchNorm running_mean, running_var buffers in the model.
It performs one pass over data in loader to estimate the activation
statistics for BatchNorm layers in the model.
Parameters:
loader (torch.utils.data.DataLoader) – dataset loader to compute the
activation statistics on. Each data batch should be either a
tensor, or a list/tuple whose first element is a tensor
containing data.
model (torch.nn.Module) – model for which we seek to update BatchNorm
statistics.
device (torch.device, optional) – If set, data will be transferred to
device before being passed into model.