Sign in

Weight decay

Weight decay and L2 regularisation

Shrinks the weights a little on every step to discourage large values, either directly (decoupled) or through an L2 term in the gradient.

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

  1. Create a WeightDecay and choose mode and rate.
  2. 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.
  3. After computing the gradients and before the optimizer step, call apply with the parameters, the gradients and the learning rate of this step.
  4. In decoupled mode, each decayed parameter is multiplied in place by one minus lr times rate, and the gradients are returned unchanged.
  5. In l2 mode, rate times the parameter is added to the gradient of each decayed parameter, and the parameters are left untouched.
  6. Pass the returned gradients to the optimizer.
  7. 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

IfUse instead
You want some weights driven exactly to zeroL1 regularisation (lasso)
The network overfits despite weight decayDropout, data augmentation or early stopping
The model underfitsLower or remove the decay, or use a larger model

Math foundations

  1. The L2 penalty

    R(w)=λ2 ∥w∥2=λ2∑iwi2R(w) = \frac{\lambda}{2}\,\lVert w \rVert^2 = \frac{\lambda}{2} \sum_i w_i^2

    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.

  2. Its gradient

    ∇wR=λ w\nabla_w R = \lambda\,w

    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.

  3. SGD with the L2 term

    w←w−η (g+λw)=(1−ηλ) w−η gw \leftarrow w - \eta\,(g + \lambda w) = (1 - \eta \lambda)\,w - \eta\,g

    Rearranging shows that the L2 term in SGD is the same as first shrinking the weight by the factor 1−ηλ1 - \eta\lambda and then taking the ordinary step. That is why it is called weight decay.

  4. Decoupled decay

    w←(1−ηλ) w,then the optimizer step on gw \leftarrow (1 - \eta \lambda)\,w, \qquad \text{then the optimizer step on } g

    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.

  5. Why L2 differs in Adam

    Δw=−η m^v^+ϵ,m^, v^ built from g+λw\Delta w = -\eta\,\frac{\hat{m}}{\sqrt{\hat{v}} + \epsilon}, \qquad \hat{m},\ \hat{v} \text{ built from } g + \lambda w

    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.

  6. Decay over many steps

    (1−ηλ)T≈e−ηλT(1 - \eta \lambda)^{T} \approx e^{-\eta \lambda T}

    With no gradient at all, a weight shrinks exponentially. It falls to about 37 percent after 1/(ηλ)1 / (\eta \lambda) steps, which gives a feel for how strong a setting is.

Symbols

w, wiw,\ w_i
the weights being decayed, and one of them
λ\lambda
the decay coefficient (rate)
R(w)R(w)
the L2 penalty
gg
the gradient of the loss without the penalty
η\eta
the learning rate of this step (lr)
m^, v^\hat{m},\ \hat{v}
Adam's running averages of the gradient and of its square
ϵ\epsilon
a small number that prevents division by zero
Δw\Delta w
the change Adam makes to a weight in one step
TT
a number of training steps

Worked by hand

One weight w=2w = 2 has gradient g=0.5g = 0.5. Use η=0.1\eta = 0.1 and λ=0.01\lambda = 0.01. Apply both modes and follow each with a plain SGD step.

R(w)=0.012×22=0.02R(w) = \frac{0.01}{2} \times 2^2 = 0.02
l2:g+λw=0.5+0.01×2=0.52,w=2−0.1×0.52=1.948\text{l2:} \quad g + \lambda w = 0.5 + 0.01 \times 2 = 0.52, \qquad w = 2 - 0.1 \times 0.52 = 1.948
decoupled:w=(1−0.1×0.01)×2=1.998,w=1.998−0.1×0.5=1.948\text{decoupled:} \quad w = (1 - 0.1 \times 0.01) \times 2 = 1.998, \qquad w = 1.998 - 0.1 \times 0.5 = 1.948

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 e−1e^{-1} times the start, and confirm that the excluded parameters did not change. Then set exclude_1d to false and repeat.

Check on learning

  1. 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 g+λwg + \lambda w in place of gg, and look at what divides the λw\lambda w part.

  2. 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.

  3. 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.

  4. 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.