What is weight decay in neural network training?
Last updated
Weight decay shrinks every weight toward zero by a small fraction at each update, w ← (1 − ηλ)w − η∇L. This biases the model toward smaller weights, and therefore smoother, less overfit functions.
Relation to L2 regularization:
With plain SGD, adding
(λ/2)||w||²to the loss gives exactly the same update, so the two are equivalent.With adaptive optimizers (Adam), they differ. An L2 gradient gets divided by the per-parameter adaptive scale, so weights with large gradient history are barely decayed.
AdamW decouples the decay: it subtracts
ηλwdirectly, outside the adaptive step. This is the standard choice for transformers.
Why it helps:
Small weights limit how sharply the function can change, which reduces effective capacity and variance.
Bayesian view: a Gaussian prior on the weights.
With BatchNorm or LayerNorm, the weights are scale-invariant. Decay then mainly raises the effective learning rate rather than restricting capacity.
Practice:
Typical λ: about 1e-4 to 5e-4 for SGD on CNNs, and about 0.01–0.1 for AdamW.
Usually exclude biases and normalization gains or offsets from decay.
[lang:python]
decay, no_decay = [], []
for n, p in model.named_parameters():
(no_decay if p.ndim == 1 else decay).append(p) # biases, norm params
opt = torch.optim.AdamW([
{"params": decay, "weight_decay": 0.05},
{"params": no_decay, "weight_decay": 0.0},
], lr=3e-4)