AI Logic

Regularization

Weight Decay

Updated:

Comparison of where the weight-shrinking term enters. On the left, Adam with L2 regularization adds λθ to the loss gradient before computing the moments and divides by √v̂ when updating, so weights with larger gradients shrink less. On the right, AdamW adds the step computed from the loss gradient alone and the weight-shrinking term λθ to the update separately, so every weight approaches 0 at the same rate

Background and Overview

Weight Decay is a regularization method that pulls every weight toward 0 by a fixed fraction at each training update. Weights grow large only when truly needed to fit the training data, and the rest stay small. As a result, overfitting, where the model memorizes even the fine quirks of the training data, becomes less likely.

The idea of penalizing the size of the weights is old and has been in use since the late 1980s. In 1992, Krogh and Hertz explained theoretically why simple Weight Decay improves generalization and confirmed it with experiments on letter-to-phoneme data (NetTalk).

Weight Decay is often treated as the same thing as L2 regularization, which adds the sum of squared weights to the loss, and many libraries implement L2 regularization under the name "weight decay." However, in 2019 Loshchilov and Hutter showed that the two coincide only for plain SGD, not for optimizers such as Adam that adapt the step size per parameter. They proposed AdamW, which decouples weight shrinkage from the gradient computation. Today AdamW is widely used to train large models, starting with the Transformer.

The figure above compares where the weight-shrinking term enters for Adam with L2 regularization (left) and AdamW (right).

Theory (The Equations of L2 Regularization and Weight Decay)

Following Section 2 of Loshchilov and Hutter's paper, the two approaches are compared in equations. θ\theta denotes the weights (parameters), ft(θ)f_t(\theta) the loss on the tt-th mini-batch, and α\alpha the learning rate.

  1. L2 regularization adds the sum of squared weights to the loss. λ′\lambda' is the strength of the penalty. ftreg(θ)=ft(θ)+λ′2 ∥θ∥22f_t^{\text{reg}}(\theta) = f_t(\theta) + \frac{\lambda'}{2}\,\lVert \theta \rVert_2^2
  2. The gradient of the added term is λ′θ\lambda'\theta, so the gradient descent update becomes the following. θt+1=θt−α ∇ft(θt)−αλ′ θt\theta_{t+1} = \theta_t - \alpha\,\nabla f_t(\theta_t) - \alpha\lambda'\,\theta_t
  3. Weight Decay leaves the loss unchanged and shrinks the weights by a factor of 1−λ1-\lambda at each update. λ\lambda is the fraction shrunk per update (Equation (1) of the paper). θt+1=(1−λ) θt−α ∇ft(θt)\theta_{t+1} = (1-\lambda)\,\theta_t - \alpha\,\nabla f_t(\theta_t)
  4. Comparing 2 and 3, setting λ′=λ/α\lambda' = \lambda / \alpha makes them identical. In other words, for plain SGD, L2 regularization and Weight Decay give the same update (Proposition 1 of the paper).

The correspondence λ′=λ/α\lambda' = \lambda/\alpha in step 4 means that the optimal L2 strength λ′\lambda' is tied to the learning rate α\alpha. When the learning rate changes, λ′\lambda' must change too to keep the same amount of shrinkage. The paper showed that when searching the two separately with SGD, good combinations line up diagonally, and changing only one of them hurts performance. Written in the Weight Decay form (3), the two can be chosen almost independently.

Why They Differ with Adam (AdamW)

Adam divides the gradient by the history of its magnitude (the square root of the second moment v^t\hat{v}_t) to equalize the step size across parameters. When L2 regularization is combined with Adam, the penalty gradient λθ\lambda\theta gets divided along with the gradient. The two approaches are compared using Algorithm 2 of the paper. ηt\eta_t is the multiplier from the learning rate schedule.

  1. Adam + L2 regularization: Add the penalty gradient to the loss gradient, then pass it to Adam. gt=∇ft(θt−1)+λ θt−1g_t = \nabla f_t(\theta_{t-1}) + \lambda\,\theta_{t-1}
  2. From this gtg_t, compute the first moment mtm_t and the second moment vtv_t as in Adam, and correct the bias to obtain m^t\hat{m}_t and v^t\hat{v}_t.
  3. The update divides by v^t\sqrt{\hat{v}_t}, so the penalty part is also discounted more for weights that had larger gradients. θt=θt−1−ηt α m^tv^t+ϵ\theta_t = \theta_{t-1} - \eta_t\,\alpha\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}
  4. AdamW: Do not add λθ\lambda\theta in step 1; compute mtm_t and vtv_t from the loss gradient alone. Then add the weight-shrinking term directly to the update (line 12 of Algorithm 2). θt=θt−1−ηt(α m^tv^t+ϵ+λ θt−1)\theta_t = \theta_{t-1} - \eta_t \left( \alpha\,\frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon} + \lambda\,\theta_{t-1} \right)

In step 4, every weight approaches 0 at the same rate ηtλ\eta_t\lambda. In step 3, weights with larger gradients shrink less and weights with smaller gradients shrink more. The paper showed that for optimizers that adapt the step size per parameter (updates of the form αMt∇ft\alpha M_t \nabla f_t where MtM_t is not a constant multiple of the identity), no choice of λ′\lambda' can make L2 regularization give the same update as Weight Decay (Proposition 2).

As an analogy, L2 regularization puts the "shrink the weights" instruction in the same envelope as the gradient, and Adam discounts the whole envelope. AdamW sends the shrink instruction in a separate envelope, so it is not discounted.

For SGD with momentum, the paper also separately compares feeding the L2 gradient into the momentum and decoupling the weight shrinkage (SGDW) (Algorithm 1). With SGDW as well, the optimal learning rate and Weight Decay became nearly independent.

Why It Improves Generalization

Using linear networks, Krogh and Hertz showed that Weight Decay has two effects.

  • Suppressing unnecessary components: When countless weight settings explain the training data equally well, Weight Decay picks the one with the smallest magnitude (norm). Components in directions the training data does not determine shrink toward 0 over time. The paper shows that this solution is the best on average.
  • Reducing the effect of label noise: When the targets contain noise (random errors), Weight Decay with a well-chosen strength keeps the weights from moving to fit the noise. In linear networks, the optimal strength is determined by the ratio of the noise variance to the size of the true weights and does not depend on the input distribution.

The paper explains that the same argument holds for nonlinear networks when they are linearized around the optimal weights.

Section 7.1.1 of the textbook Deep Learning (Goodfellow et al., 2016) explains how L2 regularization works by approximating the loss with a quadratic. In directions where the loss curves sharply (large eigenvalues μi\mu_i of the Hessian), the components of the unregularized optimum w∗w^* barely change. In directions of low curvature, that is, directions where moving barely changes the loss, the components are shrunk more strongly toward 0. With L2 strength λ′\lambda', the component in each direction is scaled by the following factor (Equation (7.13) of the textbook, rewritten in this article's notation).

μiμi+λ′\frac{\mu_i}{\mu_i + \lambda'}

Both explanations share the idea of "making small the weights that the data does not clearly call for."

Experimental Results

Results reported in the papers by Loshchilov and Hutter and by Krogh and Hertz.

TaskModelComparisonResult
CIFAR-10 image classificationResNet (26 2x96d)Adam + L2 → AdamW (learning rate 0.001)Test error dropped by about 15% relative
ImageNet32x32 image classificationResNetAdam + L2 → AdamW (learning rate 0.001)Test error dropped by about 15% relative
EEG classificationDeep4NetAdam → AdamW (same settings)Accuracy 71.37% → 73.68%
EEG classificationResNetAdam → AdamW (same settings)Accuracy 61.34% → 72.04%
NetTalk (letters to phonemes)One hidden layer (40 units, about 8,400 weights)No Weight Decay → with Weight Decay (λ=0.00008\lambda = 0.00008)Squared error dropped, and the error rate dropped slightly
  • Adam's generalization approaches SGD's: In the CIFAR-10 experiments, Adam + L2 regularization performed about the same with nonzero L2 strength as with zero. In other words, L2 regularization barely worked with Adam. Switching to AdamW brought performance close to SGD with momentum.
  • Learning rate and strength can be set separately: With AdamW and SGDW, good combinations of learning rate and Weight Decay lined up along the horizontal and vertical axes. After fixing the learning rate, tuning only Weight Decay still reaches a good value.
  • The EEG experiments are a comparison that Völker et al. provided to the paper's authors.
  • In the NetTalk experiments, Krogh and Hertz report that setting λ\lambda to 0.00005 or 0.0001 gave nearly the same curves.

Practical Considerations

The weight_decay of PyTorch's torch.optim.Adam is L2 regularization. It adds λθ\lambda\theta to the gradient before Adam's computation, so, as explained above, it does not shrink the weights by a fixed fraction. To use Weight Decay, use torch.optim.AdamW (in newer versions of PyTorch, Adam(..., decoupled_weight_decay=True) behaves the same). Meanwhile, the weight_decay of torch.optim.SGD also adds to the gradient, but without momentum it gives the same update as Weight Decay.

  • PyTorch's AdamW multiplies the shrinkage by the learning rate: PyTorch's AdamW shrinks the weights as θ←θ−γλθ\theta \leftarrow \theta - \gamma\lambda\theta (γ\gamma is the learning rate and λ\lambda is weight_decay). In the paper's equation, the shrinkage is multiplied only by the schedule multiplier ηt\eta_t, not by the learning rate α\alpha. So in PyTorch, a large change in the learning rate also changes the actual amount of shrinkage. When the learning rate schedule lowers the learning rate, the shrinkage weakens accordingly.
  • The longer the training, the smaller the optimal strength: The paper reports that the more updates (epochs or batches), the smaller the optimal Weight Decay. It therefore also proposes a normalized Weight Decay λnorm\lambda_{\text{norm}}, setting λ=λnormb/(BT)\lambda = \lambda_{\text{norm}}\sqrt{b/(BT)} from the batch size bb, the number of training examples BB, and the number of epochs TT. When the training length changes, revisit Weight Decay as well.
  • Do not make it too strong: Section 7.8 of Deep Learning warns that overly strong Weight Decay can trap training in a poor solution with weights that are too small. Decide based on validation performance.
  • Balance the strength with other regularizers: Combined with Mixup, Dropout, and the like, the regularization effects stack. After adding another regularizer, it may be better to weaken Weight Decay.
  • Combine with a learning rate schedule: The paper showed that even with Adam, gradually lowering the learning rate multiplier with cosine annealing or similar greatly improves performance.

Comparison with Other Regularizers

The table lines up regularizers that keep weights small or restrain how training proceeds, from the same viewpoints.

MethodWhere it actsEffect with AdamWhat sets its strength
L2 regularizationAdds the sum of squared weights to the lossDivided along with the gradient, so weakenedPenalty strength λ′\lambda' (tied to the learning rate)
Weight Decay (AdamW, SGDW)Shrinks the weights at each updateEvery weight shrinks at the same rateShrinkage fraction λ\lambda
L1 regularizationAdds the sum of absolute weights to the lossDivided along with the gradientPenalty strength
Early StoppingStops training partwayIndependent of the optimizerNumber of steps before stopping
DropoutDrops units during trainingIndependent of the optimizerProbability of dropping a unit
  • When training with Adam-family optimizers, use AdamW rather than L2 regularization. L2 regularization can be nearly ineffective with Adam.
  • When training with SGD, weight_decay can be used directly as Weight Decay. However, revisit the strength when changing the learning rate.
  • When many weights should be exactly 0, use L1 regularization. Weight Decay makes weights smaller overall but does not set them to 0.
  • Weight Decay is often used together with Early Stopping and Dropout. Section 7.8 of Deep Learning shows that for simple linear models, Early Stopping acts the same as L2 regularization.

PyTorch example

Show code
python
import torch
import torch.nn as nn

model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))

# 1. AdamW: decouples weight shrinkage from the gradient update (Weight Decay). Default is weight_decay=0.01
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

# 2. Adam's weight_decay is L2 regularization that adds λθ to the gradient (not the same as AdamW)
#    In newer versions of PyTorch, Adam(..., decoupled_weight_decay=True) behaves the same as AdamW
optimizer_adam_l2 = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=0.01)

# 3. SGD's weight_decay also adds λθ to the gradient. Without momentum, it gives the same update as Weight Decay
optimizer_sgd = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)


# One AdamW step (line 12 of Algorithm 2 in the paper).
# To match PyTorch, the shrinkage is "learning rate × weight_decay" (in the paper, η_t × λ)
def adamw_step(theta, grad, m, v, t, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, wd=0.01):
    theta = theta - lr * wd * theta            # shrink the weights (separately from the gradient)
    m = beta1 * m + (1 - beta1) * grad         # build the moments from the loss gradient only
    v = beta2 * v + (1 - beta2) * grad ** 2
    m_hat = m / (1 - beta1 ** t)
    v_hat = v / (1 - beta2 ** t)
    theta = theta - lr * m_hat / (v_hat.sqrt() + eps)
    return theta, m, v


# One Adam + L2 regularization step (line 6 of Algorithm 2 adds λθ to the gradient)
def adam_l2_step(theta, grad, m, v, t, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, wd=0.01):
    grad = grad + wd * theta                   # the penalty gradient is also divided by √v̂
    m = beta1 * m + (1 - beta1) * grad
    v = beta2 * v + (1 - beta2) * grad ** 2
    m_hat = m / (1 - beta1 ** t)
    v_hat = v / (1 - beta2 ** t)
    theta = theta - lr * m_hat / (v_hat.sqrt() + eps)
    return theta, m, v


# Check that it matches PyTorch's AdamW
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
m = torch.zeros_like(w_manual)
v = torch.zeros_like(w_manual)
opt = torch.optim.AdamW([w], lr=1e-3, weight_decay=0.01)

for t in range(1, 11):
    loss = ((w - 3.0) ** 2).sum()
    opt.zero_grad()
    loss.backward()
    grad = w.grad.detach().clone()
    opt.step()
    w_manual, m, v = adamw_step(w_manual, grad, m, v, t)

print(torch.allclose(w.detach(), w_manual, atol=1e-6))  # should be True

FAQ

Q. Are L2 regularization and Weight Decay the same thing?
A.

With plain SGD without momentum, they give the same update (when the L2 strength λ′ is set to the shrinkage fraction λ divided by the learning rate α). With optimizers such as Adam that adapt the step size per parameter, they do not match, because the gradient of the L2 penalty also gets divided by the gradient magnitude.

Q. Is it fine to use Adam's weight_decay?
A.

The weight_decay of PyTorch's torch.optim.Adam works as L2 regularization, so it is not Weight Decay that shrinks weights by a fixed fraction. In Loshchilov and Hutter's experiments, L2 regularization with Adam had almost no effect. To use Weight Decay, choose torch.optim.AdamW.

Q. How strong should it be?
A.

There is no fixed answer; decide based on validation performance. The default for PyTorch's AdamW is 0.01. Papers on image classification with SGD often use values such as 1e-4 (for example, the experiments in the Manifold Mixup paper). The optimal value tends to get smaller as training gets longer, so revisit it when changing the training length.

References

  1. A. Krogh and J. A. Hertz, "A Simple Weight Decay Can Improve Generalization," NIPS 4, 1992.
  2. I. Loshchilov and F. Hutter, "Decoupled Weight Decay Regularization," ICLR, 2019.
  3. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016. Chapter 7: Regularization for Deep Learning.
  4. PyTorch Documentation, "torch.optim.AdamW."
  5. PyTorch Documentation, "torch.optim.Adam."