Notebooks
F
FastAI
12 Optimizer

12 Optimizer

colabmachine-learninggpudeep-learningnotebooksPythonnbsfastaipytorch
[ ]
[ ]
[ ]
[ ]

Optimizers

Define the general fastai optimizer and the variants

_BaseOptimizer -

[ ]
[ ]
[ ]

Optimizer -

[ ]
[ ]

Initializing an Optimizer

params will be used to create the param_groups of the optimizer. If it's a collection (or a generator) of parameters, it will be a L containing one L with all the parameters. To define multiple parameter groups params should be passed as a collection (or a generator) of Ls.

:::{.callout-note}

In PyTorch, model.parameters() returns a generator with all the parameters, that you can directly pass to Optimizer.

:::

[ ]

cbs is a list of functions that will be composed when applying the step. For instance, you can compose a function making the SGD step, with another one applying weight decay. Additionally, each cb can have a defaults attribute that contains hyper-parameters and their default value. Those are all gathered at initialization, and new values can be passed to override those defaults with the defaults kwargs. The steppers will be called by Optimizer.step (which is the standard PyTorch name), and gradients can be cleared with Optimizer.zero_grad (also a standard PyTorch name).

Once the defaults have all been pulled off, they are copied as many times as there are param_groups and stored in hypers. To apply different hyper-parameters to different groups (differential learning rates, or no weight decay for certain layers for instance), you will need to adjust those values after the init.

[ ]

For each hyper-parameter, you can pass a slice or a collection to set them, if there are multiple parameter groups. A slice will be converted to a log-uniform collection from its beginning to its end, or if it only has an end e, to a collection of as many values as there are parameter groups that are ...,e/10,e/10,e.

Setting an hyper-parameter with a collection that has a different number of elements than the optimizer has parameter groups will raise an error.

[ ]

Basic steppers

To be able to give examples of optimizer steps, we will need some steppers, like the following:

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

:::{.callout-warning}

Weight decay and L2 regularization is the same thing for basic SGD, but for more complex optimizers, they are very different.

:::

Making the step

[ ]

This method will loop over all param groups, then all parameters for which grad is not None and call each function in stepper, passing it the parameter p with the hyper-parameters in the corresponding dict in hypers.

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

Some of the Optimizer cbs can be functions updating the state associated with a parameter. That state can then be used by any stepper. The best example is a momentum calculation.

[ ]

Statistics

[ ]

dampening=False gives the classical formula for momentum in SGD:

new_val = old_val * mom + grad

whereas dampening=True makes it an exponential moving average:

new_val = old_val * mom + grad * (1-mom)
[ ]
[ ]

dampening=False gives the classical formula for momentum in SGD:

new_val = old_val * mom + grad**2

whereas dampening=True makes it an exponential moving average:

new_val = old_val * mom + (grad**2) * (1-mom)
[ ]

Freezing part of the model

[ ]
[ ]
[ ]
[ ]

Parameters such as batchnorm weights/bias can be marked to always be in training mode, just put force_train=true in their state.

[ ]

Serializing

[ ]
[ ]
[ ]
[ ]
[ ]

Optimizers

SGD with momentum

[ ]
[ ]

Optional weight decay of wd is applied, as true weight decay (decay the weights directly) if decouple_wd=True else as L2 regularization (add the decay to the gradients).

[ ]
[ ]

Test weight decay, notice how we can see that L2 regularization is different from weight decay even for simple SGD with momentum.

[ ]

RMSProp

[ ]
[ ]

RMSProp was introduced by Geoffrey Hinton in his course. What is named sqr_mom here is the alpha in the course. Optional weight decay of wd is applied, as true weight decay (decay the weights directly) if decouple_wd=True else as L2 regularization (add the decay to the gradients).

[ ]
[ ]

Adam

[ ]
[ ]
[ ]
[ ]
[ ]

Adam was introduced by Diederik P. Kingma and Jimmy Ba in Adam: A Method for Stochastic Optimization. For consistency across optimizers, we renamed beta1 and beta2 in the paper to mom and sqr_mom. Note that our defaults also differ from the paper (0.99 for sqr_mom or beta2, 1e-5 for eps). Those values seem to be better from our experiments in a wide range of situations.

Optional weight decay of wd is applied, as true weight decay (decay the weights directly) if decouple_wd=True else as L2 regularization (add the decay to the gradients).

:::{.callout-note}

Don't forget that eps is an hyper-parameter you can change. Some models won't train without a very high eps like 0.1 (intuitively, the higher eps is, the closer we are to normal SGD). The usual default of 1e-8 is often too extreme in the sense we don't manage to get as good results as with SGD.

:::

[ ]

RAdam

RAdam (for rectified Adam) was introduced by Zhang et al. in On the Variance of the Adaptive Learning Rate and Beyond to slightly modify the Adam optimizer to be more stable at the beginning of training (and thus not require a long warmup). They use an estimate of the variance of the moving average of the squared gradients (the term in the denominator of traditional Adam) and rescale this moving average by this term before performing the update.

This version also incorporates SAdam; set beta to enable this (definition same as in the paper).

[ ]
[ ]

This is the effective correction reported to the adam step for 500 iterations in RAdam. We can see how it goes from 0 to 1, mimicking the effect of a warm-up.

[ ]
Output
[ ]

QHAdam

QHAdam (for Quasi-Hyperbolic Adam) was introduced by Ma & Yarats in Quasi-Hyperbolic Momentum and Adam for Deep Learning as a "computationally cheap, intuitive to interpret, and simple to implement" optimizer. Additional code can be found in their qhoptim repo. QHAdam is based on QH-Momentum, which introduces the immediate discount factor nu, encapsulating plain SGD (nu = 0) and momentum (nu = 1). QH-Momentum is defined below, where g_t+1 is the update of the moment. An interpretation of QHM is as a nu-weighted average of the momentum update step and the plain SGD update step.

θ_t+1 ← θ_t − lr * [(1 − nu) · ∇L_t(θ_t) + nu · g_t+1]

QHAdam takes the concept behind QHM above and applies it to Adam, replacing both of Adam’s moment estimators with quasi-hyperbolic terms.

The paper's suggested default parameters are mom = 0.999, sqr_mom = 0.999, nu_1 = 0.7 and and nu_2 = 1.0. When training is not stable, it is possible that setting nu_2 < 1 can improve stability by imposing a tighter step size bound. Note that QHAdam recovers Adam when nu_1 = nu_2 = 1.0. QHAdam recovers RMSProp (Hinton et al., 2012) when nu_1 = 0 and nu_2 = 1, and NAdam (Dozat, 2016) when nu_1 = mom and nu_2 = 1.

Optional weight decay of wd is applied, as true weight decay (decay the weights directly) if decouple_wd=True else as L2 regularization (add the decay to the gradients).

[ ]
[ ]
[ ]

LARS/LARC

[ ]
[ ]
[ ]

The LARS optimizer was first introduced in Large Batch Training of Convolutional Networks then refined in its LARC variant (original LARS is with clip=False). A learning rate is computed for each individual layer with a certain trust_coefficient, then clipped to be always less than lr.

Optional weight decay of wd is applied, as true weight decay (decay the weights directly) if decouple_wd=True else as L2 regularization (add the decay to the gradients).

[ ]
[ ]

LAMB

[ ]
[ ]

LAMB was introduced in Large Batch Optimization for Deep Learning: Training BERT in 76 minutes. Intuitively, it's LARC applied to Adam. As in Adam, we renamed beta1 and beta2 in the paper to mom and sqr_mom. Note that our defaults also differ from the paper (0.99 for sqr_mom or beta2, 1e-5 for eps). Those values seem to be better from our experiments in a wide range of situations.

Optional weight decay of wd is applied, as true weight decay (decay the weights directly) if decouple_wd=True else as L2 regularization (add the decay to the gradients).

[ ]

Lookahead -

Lookahead was introduced by Zhang et al. in Lookahead Optimizer: k steps forward, 1 step back. It can be run on top of any optimizer and consists in having the final weights of the model be a moving average. In practice, we update our model using the internal optimizer but keep a copy of old weights that and every k steps, we change the weights by a moving average of the fast weights (the ones updated by the inner optimizer) with the slow weights (the copy of old weights). Those slow weights act like a stability mechanism.

[ ]
[ ]
[ ]

OptimWrapper -

OptimWrapper provides simple functionality to use existing optimizers constructed with torch.optim.Optimizer.

[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

To use an existing PyTorch optimizer, you can define an optimizer function like this:

[ ]

Or if you already have a built optimizer, pass in only opt:

[ ]

When passing a built optimizer to Learner, instead of resetting the optimizer Learner.fit will clear the optimizer state if reset_opt=True or when calling Learner.fit for the first time.

To prevent Learner from clearing the optimizer state when calling Learner.fit for the first time, assign the optimizer directly to Learner.opt:

opt = torch.optim.SGD([tensor([1,2,3])], lr=1e-2)
learn = Learner(..., opt_func=None)
learn.opt = OptimWrapper(opt=opt)
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]

Export -

[ ]
[ ]