AdamW: Decoupling Weight Decay from Adam's Adaptive Update
L2 regularization and weight decay are equivalent in SGD but not in Adam: the L2 gradient is rescaled by the second-moment estimate, so weights with large gradients are decayed less. AdamW applies the decay directly to the weights. We verify the propositions in code and check PyTorch's convention.
On this page
Why this paper is worth reading
AdamW is the default optimizer for training large models today, yet many people treat it as “Adam with weight decay” and never ask why it needed its own name. This paper (Loshchilov and Hutter, posted in November 2017, ICLR 2019) answers that question: in an adaptive optimizer such as Adam, “L2 regularization” and “weight decay” are not the same thing, even though the deep learning libraries of the time used one name for both.
The backdrop was a common belief: Adam converges fast, but the best image-classification results still came from SGD with momentum, so Adam was thought to generalize worse. The authors argue that an important reason is that L2 regularization barely works in Adam, rather than Adam being inherently worse.
The core finding: two regularizers part ways inside Adam
Weight decay (Hanson and Pratt, 1988) shrinks the parameters by a fixed proportion at every step:
L2 regularization instead adds to the loss, so its gradient takes part in the update together with the loss gradient. The paper gives three propositions:
| Proposition | Statement | Consequence |
|---|---|---|
| 1 | In standard SGD, with , L2 regularization and weight decay produce identical iterates | Equivalent, but the best is coupled to the learning rate |
| 2 | For any optimizer with preconditioner (Adam is one), no L2 coefficient is equivalent to weight decay | Not equivalent in Adam |
| 3 | With a fixed preconditioner , weight decay equals an L2 penalty weighted by | Parameters with a large gradient history (large ) are decayed more |
The intuition fits in one sentence: Adam divides each parameter’s gradient by the magnitude of its gradient history. The L2 gradient sits inside the total gradient and is divided by the same magnitude, so weights with large gradients are barely decayed; weight decay bypasses that step and shrinks every weight by the same proportion.
What AdamW changes
In Adam with L2, line 6 of Algorithm 2 adds to the gradient , and both and then contain it. AdamW takes that term out and puts it in the parameter update on line 12:
The moment estimates see only the loss gradient, while the decay acts directly on the parameters. Here is a schedule multiplier (for example cosine annealing) that scales both the update and the decay. The paper adds two companion suggestions:
- Normalized weight decay. The best varies with training length, so the paper proposes , with the batch size, the number of training samples and the total number of epochs.
- Cosine annealing with warm restarts. Applied to Adam this gives AdamWR, which returns a decent solution whenever you stop it.
Verifying it in code
The code below does four things: (1) checks Proposition 1; (2) illustrates the intuition behind Proposition 2 with two pure-noise weights, one with gradient standard deviation 10 and one with 0.1, and compares the weight magnitudes under Adam+L2 and AdamW; (3) compares the paper’s Algorithm 2 with torch.optim.AdamW; (4) works out the normalized weight decay numbers.
import numpy as np
import torch
rng = np.random.default_rng(0)
def adam_dir(g, m, v, t, b1=0.9, b2=0.999, eps=1e-8):
"""One Adam step: returns new m, v and the normalized direction."""
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g * g
return m, v, (m / (1 - b1**t)) / (np.sqrt(v / (1 - b2**t)) + eps)
# 1) Proposition 1: in SGD, L2 (lam' = lam / alpha) equals weight decay
alpha, lam, A = 0.1, 0.01, np.array([3.0, 0.5])
th_l2 = th_wd = np.array([1.0, -2.0])
for _ in range(200):
noise = rng.normal(size=2) # both runs see the same minibatch noise
th_l2 = th_l2 - alpha * (A * th_l2 + noise + (lam / alpha) * th_l2)
th_wd = (1 - lam) * th_wd - alpha * (A * th_wd + noise)
print(f"SGD max|L2 - decay| = {np.abs(th_l2 - th_wd).max():.1e}")
# 2) Two pure-noise weights (gradient std 10 and 0.1): Adam+L2 vs AdamW
sigma = np.array([10.0, 0.1])
a, c, lam_w = 1e-3, 0.1, 1e-3 # learning rate, L2 coefficient, AdamW decay
runs, steps = 200, 60000
for name in ("Adam+L2", "AdamW"):
th = np.zeros((runs, 2))
m = np.zeros_like(th)
v = np.zeros_like(th)
for t in range(1, steps + 1):
g = rng.normal(size=th.shape) * sigma
if name == "Adam+L2":
g = g + c * th # the L2 gradient is rescaled by the 2nd moment
m, v, d = adam_dir(g, m, v, t)
th = th - a * d
if name == "AdamW":
th = th - lam_w * th # decay outside the preconditioner
rms = np.sqrt((th**2).mean(axis=0))
print(f"{name:8s} RMS sigma=10: {rms[0]:.4f} sigma=0.1: {rms[1]:.4f}")
# Prediction: with decay rate d per step the stationary RMS is about
# a / sqrt(2d); after `steps` steps multiply by sqrt(1 - exp(-2d * steps))
for label, d in [("AdamW (both)", lam_w), ("L2, sigma=10", a * c / 10),
("L2, sigma=0.1", a * c / 0.1)]:
pred = a / np.sqrt(2 * d) * np.sqrt(1 - np.exp(-2 * d * steps))
print(f"predicted RMS, {label:13s} decay {d:.0e}/step: {pred:.4f}")
# 3) Paper's Algorithm 2 vs torch.optim.AdamW (decay = lr * weight_decay)
lr, wd, p0 = 1e-2, 0.1, rng.normal(size=5)
th, m, v = p0.copy(), np.zeros(5), np.zeros(5)
w = torch.tensor(p0, dtype=torch.float64, requires_grad=True)
opt = torch.optim.AdamW([w], lr=lr, weight_decay=wd)
for t in range(1, 101):
g = rng.normal(size=5)
m, v, d = adam_dir(g, m, v, t)
th = th - lr * d - (lr * wd) * th # the paper's lambda = lr * wd
w.grad = torch.tensor(g, dtype=torch.float64)
opt.step()
diff = np.abs(th - w.detach().numpy()).max()
print("torch", torch.__version__, f" max|paper - torch| = {diff:.1e}")
# 4) Normalized weight decay: lam = lam_norm * sqrt(b / (B * T))
b, B, T, lam_norm = 128, 50_000, 100, 0.05
print(f"CIFAR-10 lam = {lam_norm * np.sqrt(b / (B * T)):.3e}")
ratio = np.sqrt(1_200_000 / 50_000) # an ImageNet32x32 epoch is 24x larger
print(f"ImageNet32 / CIFAR-10 raw-lam ratio = {ratio:.2f}")
Output (plain NumPy plus PyTorch 2.10.0 on CPU, a few seconds; the last digits may differ in another environment):
SGD max|L2 - decay| = 5.6e-17
Adam+L2 RMS sigma=10: 0.1819 sigma=0.1: 0.0226
AdamW RMS sigma=10: 0.0231 sigma=0.1: 0.0222
predicted RMS, AdamW (both) decay 1e-03/step: 0.0224
predicted RMS, L2, sigma=10 decay 1e-05/step: 0.1869
predicted RMS, L2, sigma=0.1 decay 1e-03/step: 0.0224
torch 2.10.0 max|paper - torch| = 1.1e-16
CIFAR-10 lam = 2.530e-04
ImageNet32 / CIFAR-10 raw-lam ratio = 4.90
How to read these numbers:
- Proposition 1 holds. The two SGD trajectories, with L2 and with weight decay, differ only by floating-point rounding ().
- The intuition behind Proposition 2 holds. Both weights receive pure-noise gradients, so there is no signal to preserve and only the decay holds them back. Under AdamW their RMS values are nearly equal (0.0231 and 0.0222); under Adam+L2 the weight with the noisier gradient is about 8 times larger (0.1819 versus 0.0226). The reason is that the effective decay rate of the L2 term is only : per step at against at , and the predictions computed from those rates (0.1869 and 0.0224) match the simulation. This is a toy setup that shows the direction and magnitude of “being rescaled by the preconditioner”; it is not a claim about real networks.
- PyTorch’s convention differs from the paper’s by a learning-rate factor. In the paper’s Algorithm 2 the decay term is not multiplied by , while
torch.optim.AdamWmultiplies the parameters by ; the two agree bit for bit () when . So in PyTorch, holdingweight_decayfixed and changing only the learning rate also changes the per-step decay, and the paper’s benefit of decoupling the decay from the learning rate is only partly kept under that convention. - A normalized-decay example. For CIFAR-10 (50,000 images), batch size 128, 100 epochs and we get . An ImageNet32x32 epoch has 1.2 million images, 24 times CIFAR-10, and , consistent with the paper’s remark that without normalization would have been roughly 5 times too large.
The paper’s experiments
The paper uses 26-layer 2x64d and 2x96d ResNets (11.6M and 25.6M parameters, following the Shake-Shake setup) on CIFAR-10 and ImageNet32x32, with the batch size fixed at 128.
| Experiment | Setup | Finding |
|---|---|---|
| Learning-rate schedules (Fig. 1) | 100 epochs; fixed rate, step drops, cosine annealing | AdamW beats Adam+L2 under all three schedules, with bigger gaps for better schedules; cosine annealing is clearly best |
| Hyperparameter coupling (Fig. 2) | Grid over learning rate and decay; SGD vs SGDW, Adam vs AdamW | The best L2 region lies along a diagonal (the two hyperparameters are coupled); after decoupling the search is closer to “one at a time”. The best Adam+L2 results with nonzero L2 are no better than with none () |
| Long training (Fig. 3) | 1800 epochs; 12 L2 settings for Adam, 7 normalized-decay settings for AdamW | AdamW reaches lower training loss and lower test error, and lower test error at similar training loss |
| Warm restarts (Fig. 4) | AdamWR vs AdamW | AdamWR is up to 10 times faster than AdamW at the first restart; with the default learning rate 0.001, AdamW cuts test error by 15% relative to Adam (on both CIFAR-10 and ImageNet32x32) |
The paper also lists uses by other groups: face detection (WIDER FACE), intracranial EEG (AdamW versus Adam at the same hyperparameters: 73.68% versus 71.37% and 72.04% versus 61.34% accuracy), and Radford et al. (2018) training a Transformer with AdamW.
Limitations and cautions
- Image classification only. The experiments are CIFAR-10 and ImageNet32x32 with ResNet plus Shake-Shake; conclusions for language models and Transformers come from later practice, not from this paper. The authors themselves write that the results need to be verified on a wider range of tasks.
- Normalization is an empirical choice. The authors stress that is “one possibility informed by few experiments” and that better scaling rules likely exist.
- No variance estimates. The results are single runs over hyperparameter grids plus learning curves; the words “seed” and “standard deviation” never appear in the paper, so the 15% relative improvement is an order of magnitude, not an exact value.
- Names in libraries. The paper notes that libraries of the time called L2 regularization weight decay; today
torch.optim.Adam’sweight_decayis still the L2 (coupled) form, and you needtorch.optim.AdamWfor the decoupled version. - Parameter conventions. See point 3 above: PyTorch’s
weight_decaydiffers from the paper’s by a learning-rate factor. Convert before copying numbers from the paper into PyTorch.
What to take from this paper
- L2 regularization equals weight decay in SGD but not in Adam. Adam rescales each parameter’s gradient, and the L2 gradient is rescaled along with it.
- AdamW changes one thing. The decay moves out of the gradient into the parameter update; everything else, including memory use, is the same as Adam.
- How decay strength and learning rate interact. The paper decouples them; in practice check the library’s convention, for example PyTorch’s
lr×weight_decay. - It is not a silver bullet. The paper’s evidence is on image classification; AdamW’s place in LLM training is the result of a large body of later practice.
Further reading
- Paper: Decoupled Weight Decay Regularization
- Related wiki pages: Optimizers and Training Stability (AdamW hyperparameters, learning-rate schedules and loss spikes), The Pretraining Pipeline
- Glossary: AdamW
FAQ
- What is the difference between AdamW and Adam with L2 regularization?
- With L2 regularization the penalty gradient λθ is added to the loss gradient and the sum is then rescaled by the second-moment estimate √v̂, so parameters with a large gradient history are decayed less. AdamW applies the decay as a separate step θ←θ−λθ that bypasses the rescaling, so every parameter decays by the same proportion. In SGD the two are equivalent; in Adam they are not.
- Is weight_decay in torch.optim.AdamW the same as the paper's λ?
- They differ by a learning-rate factor. The paper's Algorithm 2 subtracts η_t·λ·θ per step, without the base learning rate α, while torch.optim.AdamW multiplies the parameters by 1−lr·weight_decay, so the paper's λ equals lr×weight_decay. In the experiment below the two agree to about 1e-16 after 100 steps. The consequence is that in PyTorch, changing the learning rate at a fixed weight_decay also changes the per-step decay.
- Why do almost all LLM pretraining runs use AdamW?
- The paper itself only shows that AdamW beats Adam with L2 on image classification (CIFAR-10 and ImageNet32x32) and has no language-model experiments. It was adopted for Transformer training soon after (Section 4.5 of the paper mentions the GPT-1 authors using it), and the Llama 2 report uses AdamW with β2=0.95 and weight decay 0.1. In practice AdamW keeps Adam's insensitivity to gradient scale while making the regularization strength controllable.
- What is "normalized weight decay" in the paper?
- The paper proposes writing the decay as λ=λ_norm·√(b/(B·T)), where b is the batch size, B the number of training samples and T the number of epochs, so that the best λ_norm changes little with training length. The authors say this is just one possible normalization backed by limited experiments. Large-model training usually uses a fixed decay value such as 0.1 instead.