AI Logic

Optimizers

AdamW

Updated:

How AdamW works. The left shows the training loop that repeats the forward pass, gradient computation, and the AdamW update; the right shows one step of computation: the first and second moments are computed from the gradient and bias-corrected, and separately a term λθ that shrinks the weights is added directly to the update equation

Background and overview

AdamW is an optimizer that decouples the operation that pulls weights toward 0 (weight decay) from the Adam update. Loshchilov and Hutter posted it on arXiv in 2017, and it was accepted at ICLR 2019. The W in the name stands for the decoupled Weight Decay.

Until then, many libraries implemented Adam's "weight decay" as L2 regularization that adds λθ\lambda\theta to the gradient. In plain SGD, L2 regularization and weight decay yield the same update. Adam, however, divides the gradient by a per-parameter scale, so the added λθ\lambda\theta is divided as well, and weights that had larger gradients shrink less. The paper identifies this as a major reason why Adam's generalization performance (accuracy on unseen data) tends to lose to SGD with momentum.

AdamW moves the weight-shrinking term out of Adam's computation and shrinks every weight by the same fraction. That is the only change, yet in the paper's image classification experiments the test error dropped by about 15% relative to Adam, and the learning rate and the weight decay strength became easier to tune separately. After the paper appeared, it spread through uses such as Radford et al. (2018) training a Transformer, and it is now standard for training large models. The difference between L2 regularization and weight decay itself is explained in detail in the Weight Decay article.

Theory (one step of computation)

At each training step tt, AdamW performs the following computation (Algorithm 2 of the paper). All operations are applied elementwise to the parameters.

  1. Compute the loss on a mini-batch and obtain the gradient by backpropagation. λθ\lambda\theta is not added here (the difference from Adam + L2 regularization). gt=∇ft(θt−1)g_t = \nabla f_t(\theta_{t-1})
  2. Update the first moment (mean of the gradient) and the second moment (mean of the squared gradient) with exponential moving averages. mt=β1mt−1+(1−β1) gt,vt=β2vt−1+(1−β2) gt2m_t = \beta_1 m_{t-1} + (1-\beta_1)\, g_t, \qquad v_t = \beta_2 v_{t-1} + (1-\beta_2)\, g_t^2
  3. Correct the bias in the early steps (bias correction). m^t=mt1−β1t,v^t=vt1−β2t\hat{m}_t = \frac{m_t}{1-\beta_1^t}, \qquad \hat{v}_t = \frac{v_t}{1-\beta_2^t}
  4. Determine the schedule multiplier ηt\eta_t for the learning rate (it may be constant or decreased with cosine annealing, etc.).
  5. Update the parameters by adding the Adam update and the weight-shrinking term separately. θ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)

α\alpha is the learning rate and λ\lambda is the weight decay strength (the fraction shrunk per update). The paper's defaults are the same as Adam's, α=0.001\alpha = 0.001, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}, and λ\lambda is chosen per task.

In the equation of step 5, the weight-shrinking term λθt−1\lambda\theta_{t-1} is multiplied by the schedule multiplier ηt\eta_t but not by the learning rate α\alpha. So changing α\alpha does not change the shrinking strength. This is why "the optimal learning rate and weight decay become independent". On the other hand, ηt\eta_t multiplies both, so lowering the learning rate with a schedule also weakens the shrinking by the same fraction.

Why decoupling works

When L2 regularization is added to Adam, the penalty gradient λθ\lambda\theta is divided by v^t\sqrt{\hat{v}_t} just like the loss gradient. v^t\sqrt{\hat{v}_t} is a measure of how large the gradients for that weight have been so far. L2 regularization therefore shrinks weights as follows.

  • Weights that had large gradients: v^t\sqrt{\hat{v}_t} is large, so the penalty is heavily discounted and they shrink little.
  • Weights that had small gradients: v^t\sqrt{\hat{v}_t} is small, so the penalty is not discounted and they shrink strongly.

In AdamW the penalty is not divided, so every weight approaches 0 at the same rate ηtλ\eta_t\lambda. The paper shows this difference with two propositions.

  • It cannot be replaced by L2 regularization: for optimizers whose update has the form θt+1=θt−αMt∇ft(θt)\theta_{t+1} = \theta_t - \alpha M_t \nabla f_t(\theta_t) with MtM_t not a constant multiple of the identity (those that vary the step size per parameter, like Adam), no choice of L2 strength λ′\lambda' yields the same update as weight decay (Proposition 2).
  • Weight decay corresponds to scale-adjusted L2 regularization: assuming the step-size matrix is fixed as Mt=diag(s)−1M_t = \mathrm{diag}(s)^{-1}, weight decay is equivalent to L2 regularization with each weight weighted by si\sqrt{s_i} (Proposition 3). In other words, weights that had larger gradients are regularized more strongly than under L2 regularization.

As an analogy, L2 regularization puts the "shrink the weights" instruction in the same envelope as the gradient when handing it to Adam, so the whole envelope gets discounted. AdamW hands over the shrinking instruction in a separate envelope, so it is not discounted.

The paper also notes that in the framework of Aitchison (2018), which views adaptive optimizers as Bayesian filters, what arises naturally is the form of weight decay, not L2 regularization.

Experimental results

The paper compared Adam + L2 regularization with AdamW on image classification on CIFAR-10 and ImageNet32x32 (ImageNet downsampled to 32×32 pixels). The models were ResNets with the same configuration as Gastaldi (2017) (26 2x64d and 26 2x96d), with a batch size of 128.

TaskModelComparisonResult
CIFAR-10ResNetAdam + L2 → AdamW (learning rate 0.001)Test error dropped by about 15% relative
ImageNet32x32ResNetAdam + 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%
  • The learning rate and weight decay can be chosen separately: in a grid over learning rates and strengths, the good combinations for Adam + L2 lay along a diagonal, and changing only one of them hurt performance. With AdamW, the good combinations lined up horizontally and vertically, and tuning only the strength with the learning rate fixed still reached good values. SGD with momentum showed the same tendency with SGDW, which decouples weight decay.
  • L2 regularization was barely working in Adam: the best result of Adam + L2 was almost the same as with the L2 strength set to 0. The best result of AdamW matched SGD with momentum.
  • Lower test error at the same training loss: in long training runs of 1800 epochs, AdamW had lower test error than Adam even at similar training loss. This shows that it is not merely optimizing faster but generalizing better.
  • Schedules help: comparing a constant learning rate, step decay, and cosine annealing, AdamW came out ahead in every case. Cosine annealing was the best, and AdamWR, which adds warm restarts, reached good results up to about 10 times faster than AdamW at the time of the first restart.
  • The EEG experiments are a comparison that Völker et al. provided to the paper's authors.

Practical caveats

torch.optim.Adam(weight_decay=...) is not AdamW. The weight_decay of PyTorch's Adam is L2 regularization that adds λθ\lambda\theta to the gradient, which, as explained above, does not work well as weight decay. To use weight decay, use torch.optim.AdamW (in newer versions of PyTorch, Adam(..., decoupled_weight_decay=True) also behaves like AdamW). Also note that the defaults differ: weight_decay is 0 for Adam and 0.01 for AdamW.

PyTorch's AdamW multiplies the shrinking amount by the learning rate. PyTorch shrinks with θ←θ−γλθ\theta \leftarrow \theta - \gamma\lambda\theta (γ\gamma is lr and λ\lambda is weight_decay). In the paper's equation, only the schedule multiplier ηt\eta_t multiplies the shrinking amount, not the learning rate α\alpha. As a result, the paper's λ\lambda and PyTorch's weight_decay are related by λpaper=γ λPyTorch\lambda_{\text{paper}} = \gamma\,\lambda_{\text{PyTorch}}. In PyTorch, changing the learning rate substantially also changes the actual shrinking by the same factor, so revisit weight_decay whenever the learning rate changes.

  • Set the strength according to training length: the paper reports that the more updates there are, the smaller the optimal weight decay strength becomes. 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 (Appendix B.1).
  • Combine it with a learning rate schedule: Adam adjusts step sizes automatically, but lowering the global learning rate multiplier with a schedule still improves results considerably. For large models, combining warmup with cosine annealing is common.
  • Memory is the same as Adam: it keeps mtm_t and vtv_t for each parameter, so it needs additional memory equal to two copies of the parameters.

Comparison with other optimizers

Focusing on how weight decay is applied, the table lists AdamW and closely related optimizers.

MethodWeight-shrinking operationHow weights shrinkRelation to the learning rateMain uses
SGD + L2 (SGD(weight_decay=...))Adds λθ\lambda\theta to the gradientConstant fraction without momentumOptimal strength is tied to the learning rateCNNs for image classification
SGDWShrinks separately from the updateConstant fractionNearly independentProposed in the paper. An improvement on SGD
Adam + L2 (Adam(weight_decay=...))Adds λθ\lambda\theta to the gradientWeaker for weights with larger gradientsTiedThe former standard. Now discouraged
AdamWShrinks separately from the updateConstant fractionNearly independentStandard for large models such as Transformers

A rough guide for choosing:

  • If you use Adam and want weight decay (regularization), switch to AdamW: the code change is one line, and the learning rate and strength can then be tuned separately.
  • For training CNNs for image classification, compare with SGD with momentum: in the paper AdamW matched SGD, but results vary by task.
  • For very large batch sizes, also consider LARS and similar methods: they equalize step sizes per layer and keep training stable even with large learning rates.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of PyTorch's AdamW, written following the procedure in the official documentation
def adamw_step(theta, grad, m, v, t, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, weight_decay=1e-2):
    theta = theta - lr * weight_decay * theta   # shrink the weights (decoupled from the gradient; PyTorch also multiplies by lr)
    m = beta1 * m + (1 - beta1) * grad          # moments are computed from the 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


# Check that it gives the same result as PyTorch's AdamW
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_adam_l2 = w.detach().clone().requires_grad_(True)
w_manual = w.detach().clone()
m = torch.zeros_like(w_manual)
v = torch.zeros_like(w_manual)
opt_adamw = torch.optim.AdamW([w], lr=1e-3, weight_decay=1e-2)
opt_adam_l2 = torch.optim.Adam([w_adam_l2], lr=1e-3, weight_decay=1e-2)  # this is L2 regularization

for t in range(1, 11):
    for param, opt in [(w, opt_adamw), (w_adam_l2, opt_adam_l2)]:
        loss = ((param - 3.0) ** 2).sum()
        opt.zero_grad()
        loss.backward()
        if param is w:
            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
print(torch.allclose(w.detach(), w_adam_l2.detach()))   # False: a different update from Adam(weight_decay)


# Use in actual training (example: separate parameters with and without weight decay)
model = nn.Sequential(nn.Linear(512, 512), nn.LayerNorm(512), nn.ReLU(), nn.Linear(512, 10))
decay, no_decay = [], []
for name, p in model.named_parameters():
    (no_decay if p.ndim < 2 else decay).append(p)  # example: do not shrink biases and normalization weights (1-D)
optimizer = torch.optim.AdamW(
    [{"params": decay, "weight_decay": 0.05}, {"params": no_decay, "weight_decay": 0.0}],
    lr=3e-4, betas=(0.9, 0.999),
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=1000)  # gradually lower the learning rate multiplier

x = torch.randn(32, 512)                       # dummy mini-batch
y = torch.randint(0, 10, (32,))
optimizer.zero_grad()
loss = nn.functional.cross_entropy(model(x), y)
loss.backward()
optimizer.step()
scheduler.step()

FAQ

Q. How do Adam and AdamW differ?
A.

Only in how the weight-shrinking term is applied. Adam's weight_decay adds λθ\lambda\theta to the gradient, so it is divided by the second moment and the shrinkage varies from weight to weight. AdamW shrinks every weight by the same fraction, separately from the gradient-based update. Without weight decay (strength 0), the two give the same update.

Q. What value should weight_decay be?
A.

PyTorch's default is 0.01. The optimal value depends on the task, and the paper reports that longer training tends to favor smaller values. Since PyTorch also multiplies the shrinking by the learning rate, revisit weight_decay whenever the learning rate changes, and choose it based on validation performance.

Q. Is AdamW always better than Adam?
A.

If weight decay is applied, AdamW is the usual choice. In the paper's image classification, it generalized better than Adam + L2 regularization. Without weight decay, however, it gives the same update as Adam, so there is no difference.

References

  1. I. Loshchilov and F. Hutter, "Decoupled Weight Decay Regularization," ICLR, 2019.
  2. D. P. Kingma and J. Ba, "Adam: A Method for Stochastic Optimization," ICLR, 2015.
  3. PyTorch Documentation, "torch.optim.AdamW."
  4. PyTorch Documentation, "torch.optim.Adam."