Overview
A model with very large weights can fit the training data in a jagged, fragile way that does not carry over to new data. Weight decay pushes against that. On every step each weight is pulled a small fraction of the way toward zero, so a weight stays large only if the data keeps pushing it there. There are two ways to do it. The L2 way adds a penalty on the squared weights to the loss, which adds a pull to the gradient. The decoupled way multiplies the weights by a number just below one, separately from the gradient step. With plain SGD the two give the same result. With Adam they do not.
A short history
Penalising large coefficients goes back to ridge regression, published by Arthur Hoerl and Robert Kennard in 1970. For neural networks, Stephen Hanson and Lorien Pratt described weight decay in 1988, and Anders Krogh and John Hertz showed in 1991 that it improves generalisation. In 2017 Ilya Loshchilov and Frank Hutter showed that an L2 term behaves differently inside Adam and proposed the decoupled form used in AdamW.
How it works
- Create a WeightDecay and choose mode and rate.
- split_param_groups sorts the parameters into decay and no_decay. Arrays with fewer than two dimensions, and names containing an entry of exclude_names, are not decayed.
- After computing the gradients and before the optimizer step, call apply with the parameters, the gradients and the learning rate of this step.
- In decoupled mode, each decayed parameter is multiplied in place by one minus lr times rate, and the gradients are returned unchanged.
- In l2 mode, rate times the parameter is added to the gradient of each decayed parameter, and the parameters are left untouched.
- Pass the returned gradients to the optimizer.
- penalty reports the L2 penalty value, which is the loss term that l2 mode differentiates.
Watch out for
- With Adam, L2 mode is not uniform decay. The decay term is divided by the same running gradient scale as the gradient, so weights with large gradients are barely decayed. Use decoupled mode.
- Decaying biases and normalisation gains gives little regularisation and can hurt, because those parameters set offsets and scales and do not fit patterns. Keep the exclusions on.
- In decoupled mode the shrink per step is the learning rate times the rate. A schedule that lowers the learning rate also weakens the decay, so the two settings must be tuned together.
- The name exclusions work only for dictionary parameters. For a list, only the dimension rule applies, so a two-dimensional array you wanted to exclude is decayed.
- Do not also set weight decay inside the optimizer. The weights would be decayed twice on every step.
Use cases
When to use it
As the default regulariser for neural networks. Use decoupled mode with Adam-style optimizers, which is what AdamW does, and exclude biases and normalisation parameters.
In industry
- Language models
- Transformers are trained with AdamW and decoupled weight decay, usually applied to weight matrices but not to biases or normalisation parameters.
- Computer vision
- ImageNet classifiers trained with SGD use a small L2 weight decay as a standard part of the recipe.
- Statistics and risk modelling
- Ridge and regularised logistic regression use the same L2 penalty to stabilise coefficients when inputs are correlated.
Choosing it: what must hold
- A model with enough capacity to overfit, or weights that grow without limit during training.
- A decay strength tuned together with the learning rate, since the two interact.
- With Adam-type optimizers, the decoupled form. An L2 term in the gradient is rescaled per weight and loses its meaning.
- Parameter groups that exclude biases and normalisation scales from decay.
When to choose something else
| If | Use instead |
|---|---|
| You want some weights driven exactly to zero | L1 regularisation (lasso) |
| The network overfits despite weight decay | Dropout, data augmentation or early stopping |
| The model underfits | Lower or remove the decay, or use a larger model |
Math foundations
The L2 penalty
A cost added to the loss that grows with the squared size of the weights. Large weights are penalised much more than small ones. This is what penalty returns.
Its gradient
The penalty adds to each weight's gradient a pull toward zero that is proportional to the weight itself. This is the term l2 mode adds to the gradients.
SGD with the L2 term
Rearranging shows that the L2 term in SGD is the same as first shrinking the weight by the factor and then taking the ordinary step. That is why it is called weight decay.
Decoupled decay
The shrink is applied directly and never passes through the optimizer. Every decayed weight loses the same fraction per step, whatever the optimizer does to the gradient.
Why L2 differs in Adam
In Adam the gradient, with the decay term inside it, is divided by a running estimate of its own size. A weight with large gradients has a large divisor, so its decay is scaled down.
Decay over many steps
With no gradient at all, a weight shrinks exponentially. It falls to about 37 percent after steps, which gives a feel for how strong a setting is.
Symbols
- the weights being decayed, and one of them
- the decay coefficient (rate)
- the L2 penalty
- the gradient of the loss without the penalty
- the learning rate of this step (lr)
- Adam's running averages of the gradient and of its square
- a small number that prevents division by zero
- the change Adam makes to a weight in one step
- a number of training steps
Worked by hand
One weight has gradient . Use and . Apply both modes and follow each with a plain SGD step.
Both modes give 1.948 under plain SGD, as the algebra predicts. Under Adam the two would differ, because the extra 0.02 in the gradient would be rescaled along with the rest.
Visual example
Loading the example.
Try this
- Raise the decay: weights the loss does not defend shrink toward zero faster.
Code sample
import numpy as np
from impl import WeightDecay
from config import WeightDecayConfig
params = {"layer.weight": np.ones((2, 2)), "layer.bias": np.ones(2)}
wd = WeightDecay(WeightDecayConfig(mode="decoupled", rate=0.1))
print(wd.split_param_groups(params)) # {'decay': ['layer.weight'], 'no_decay': ['layer.bias']}
lr = 0.5
grads = {"layer.weight": np.zeros((2, 2)), "layer.bias": np.zeros(2)}
grads = wd.apply(params, grads, lr) # weight shrinks to 0.95, bias stays 1.0
for name in params: # then the optimizer step, here plain SGD
params[name] -= lr * grads[name]Read the implementation (63 lines)
"""Weight decay on plain NumPy arrays: decoupled (AdamW style) or as an L2 gradient term, with the usual
split of parameters into a decayed and a non-decayed group.
NumPy only. Parameters are a list of arrays or a dict of name -> array. Call `apply` between computing the
gradients and the optimizer step: it returns the gradients the optimizer should use and, in decoupled mode,
shrinks the decayed parameters in place.
"""
from __future__ import annotations
import numpy as np
try:
from .config import WeightDecayConfig
except ImportError: # run from the template's own folder
from config import WeightDecayConfig
class WeightDecay:
"""Applies weight decay to the parameters that should get it."""
def __init__(self, config: WeightDecayConfig | None = None) -> None:
self.config = config or WeightDecayConfig()
def is_decayed(self, key, param: np.ndarray) -> bool:
"""Whether one parameter gets weight decay. key: its dict name or list index."""
cfg = self.config
if cfg.exclude_1d and np.ndim(param) < 2:
return False
if isinstance(key, str) and any(part in key.lower() for part in cfg.exclude_names):
return False
return True
def split_param_groups(self, params) -> dict:
"""Split parameter keys into {"decay": [...], "no_decay": [...]} (names for a dict, indices for a list)."""
items = params.items() if isinstance(params, dict) else enumerate(params)
groups: dict = {"decay": [], "no_decay": []}
for key, p in items:
groups["decay" if self.is_decayed(key, p) else "no_decay"].append(key)
return groups
def penalty(self, params) -> float:
"""The L2 penalty 0.5 * rate * sum of squared decayed weights (the loss term "l2" mode differentiates)."""
total = sum(float(np.sum(np.square(params[k]))) for k in self.split_param_groups(params)["decay"])
return 0.5 * self.config.rate * total
def apply(self, params, grads, lr: float):
"""Apply the decay for one training step and return the gradients to hand to the optimizer.
params: list or dict of float arrays. grads: same structure. lr: the learning rate of this step.
"l2": returns new gradients with rate * param added for decayed parameters; params untouched.
"decoupled": multiplies decayed parameters in place by (1 - lr * rate) and returns grads unchanged.
"""
decay = self.split_param_groups(params)["decay"]
rate = self.config.rate
if self.config.mode == "decoupled":
for k in decay:
params[k] *= 1.0 - lr * rate
return grads
out = dict(grads) if isinstance(grads, dict) else list(grads)
for k in decay:
if out[k] is not None:
out[k] = np.asarray(out[k], dtype=float) + rate * params[k]
return out- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build a dictionary of parameters with a weight matrix, a bias vector and an array named norm_gain, and print WeightDecay.split_param_groups for it. Set all gradients to zero and call apply 1000 times in decoupled mode with lr 0.1 and rate 0.01, set through WeightDecayConfig. Compare the final weight matrix with the prediction times the start, and confirm that the excluded parameters did not change. Then set exclude_1d to false and repeat.
Check on learning
- With plain SGD the two modes are identical. What exactly does Adam do to the gradient that breaks the equivalence?
A way to think about it
Write the Adam step with in place of , and look at what divides the part.
- Why are biases and normalisation gains usually excluded from weight decay? What role do they play that the main weights do not?
A way to think about it
A bias shifts an output and a gain rescales it. Ask whether pulling them toward zero makes the function simpler or just moves it.
- In decoupled mode with a cosine learning rate schedule, how does the strength of the decay change during training? Is that intended?
A way to think about it
The shrink factor contains the learning rate. Follow it as the rate falls to zero, and think about what the weights do in the last steps.
- A weight's gradient is zero on average but noisy. Under weight decay, what size does the weight settle at, and what does that say about weights the data does not need?
A way to think about it
Balance a steady pull toward zero against random kicks with no preferred direction. Compare with a weight whose gradient consistently pushes it away from zero.