Adam and AdamW
Adam (Kingma and Ba, 2015) is the optimizer most people reach for first: it trains transformers, GANs, recommendation models and most research code with little tuning. It is the sum of the two previous lessons, a momentum average of the gradients on top and an RMSprop average of squared gradients underneath, plus a small correction for their start at zero. AdamW (Loshchilov and Hutter, 2019) changes one line, how weight decay is applied, and that line is why large language models are trained with AdamW and not Adam. This lesson builds both in NumPy and shows, with exact numbers, what bias correction and decoupled weight decay do.
The update
For each parameter, elementwise, with gradient at step :
with defaults , , and . The ratio is like a signal-to-noise ratio: close to when the gradient keeps a steady sign, close to 0 when it flips around. So every parameter's step is at most about , whatever the scale of its gradient. That makes a step length in parameter space, which is why one learning rate works across very different layers, and why Adam needs a schedule to settle. Derivations and the variants (AMSGrad, Adamax, NAdam) are in Adam and AdamW in Mathematics for Deep Learning.
Why bias correction
Both averages start at zero. After one step and : both are far too small, and by different amounts. Dividing by makes each an unbiased average from the first step. Feed Adam a constant gradient of 5 and look at the step divided by :
import numpy as np
def adam_step(p, g, s, lr, b1=0.9, b2=0.999, eps=1e-8, correct=True):
s["t"] = s.get("t", 0) + 1
s["m"] = b1 * s.get("m", 0) + (1 - b1) * g # first moment: mean of g
s["v"] = b2 * s.get("v", 0) + (1 - b2) * g ** 2 # second moment: mean of g^2
m, v = s["m"], s["v"]
if correct:
m = m / (1 - b1 ** s["t"])
v = v / (1 - b2 ** s["t"])
return p - lr * m / (np.sqrt(v) + eps)
# a constant gradient of 5: how big is each step, with and without bias correction?
for correct in [True, False]:
p, s, steps = 0.0, {}, []
for t in range(1, 1001):
new = adam_step(p, 5.0, s, lr=0.01, correct=correct)
steps.append(p - new); p = new
print("corrected " if correct else "uncorrected", "step / lr at t = 1, 2, 10, 100, 1000:",
" ".join(f"{steps[t - 1] / 0.01:.3f}" for t in (1, 2, 10, 100, 1000)))corrected step / lr at t = 1, 2, 10, 100, 1000: 1.000 1.000 1.000 1.000 1.000
uncorrected step / lr at t = 1, 2, 10, 100, 1000: 3.162 4.250 6.528 3.241 1.258
With bias correction, every step is exactly (ratio 1.000), as it should be for a perfectly consistent gradient. Without it, the first step is times too large, it grows to 6.5 times by step 10 (the first moment warms up in about 10 steps, the second needs about 1000), and it is still 1.26 times too large at step 1000. At the very start of training, when the weights are random and gradients are large, those oversized steps can wreck a model, so the correction is not cosmetic. (Many practitioners add a learning-rate warm-up on top, for similar reasons.)
Watch Adam in the lab
The lab's Adam uses and bias correction, with on the second slider. On the narrow valley with , Adam's first steps go diagonally: both coordinates move by about , regardless of the 10-to-1 curvature. After 60 steps the loss is about 0.022, at , still on its way: a constant step of 0.08 per coordinate covers distance slowly when the start is 2.5 away. Raise to 0.3 and it gets closer (about 0.009) but wobbles around the minimum. Try the Rosenbrock surface too: Adam follows the curved floor without the divergence that GD and momentum show at large .
L2 regularisation is not weight decay (for Adam)
For plain SGD two things are the same. L2 regularisation adds to the loss, so is added to the gradient. Weight decay shrinks the weights directly every step. With SGD,
so they are identical (Weight Decay and Dropout). With Adam they are not. If goes into the gradient, it also goes through and and is divided by : a weight whose gradients are large is barely decayed, one with small gradients is decayed strongly. AdamW takes the decay out of the gradient and applies it separately:
The two end up at different solutions. Below, a linear regression has a "loud" feature (standard deviation 10) and a "quiet" one (0.1) that matter equally, because the true weights are 0.3 and 30. Train it with full-batch Adam plus an L2 penalty, and with AdamW, both with :
import numpy as np
rng = np.random.default_rng(0)
n = 500
X = np.column_stack([rng.normal(0, 10, n), rng.normal(0, 0.1, n)]) # one loud and one quiet feature
y = X @ np.array([0.3, 30.0]) + rng.normal(0, 1, n) # both matter equally (0.3*10 = 30*0.1)
lam = 0.1
ridge = np.linalg.solve(X.T @ X / n + lam * np.eye(2), X.T @ y / n)
def train(decoupled, lr=0.01, steps=20000, b1=0.9, b2=0.999, eps=1e-8):
w, m, v = np.zeros(2), np.zeros(2), np.zeros(2)
for t in range(1, steps + 1):
g = X.T @ (X @ w - y) / n # full-batch gradient of 1/2 MSE
if not decoupled:
g = g + lam * w # Adam + L2: decay goes through m and v
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g ** 2
step = lr * (m / (1 - b1 ** t)) / (np.sqrt(v / (1 - b2 ** t)) + eps)
if decoupled:
w = w - lr * lam * w # AdamW: shrink every weight by the same factor
w = w - step
return w
ols = np.linalg.lstsq(X, y, rcond=None)[0]
print("no penalty (least squares):", np.round(ols, 3))
print("ridge, lambda 0.1 (exact): ", np.round(ridge, 3))
print("Adam + L2 lambda 0.1: ", np.round(train(False), 3))
print("AdamW weight_decay 0.1: ", np.round(train(True), 3))no penalty (least squares): [ 0.302 29.692]
ridge, lambda 0.1 (exact): [0.304 2.413]
Adam + L2 lambda 0.1: [0.304 2.413]
AdamW weight_decay 0.1: [ 0.304 10. ]
- Adam + L2 lands exactly on the ridge solution . That is no accident: Adam stops where its gradient, here , is zero, which is the ridge optimum. The quiet feature's weight is shrunk from 29.7 to 2.4, because ridge charges the same price per unit of weight, and the quiet feature needs a large weight.
- AdamW keeps the loud feature's weight at 0.304 but stops the quiet one at exactly . At that point the decay balances an Adam step of size (its gradient keeps a constant sign, so ). AdamW's decay acts on the weights in units of Adam's own steps, the same for every parameter, not on the gradient scale.
Neither answer is "right"; they are different regularisers. What made AdamW the default is practical: Loshchilov and Hutter found it generalises better than Adam with L2 on image and language models, and that the best no longer depends strongly on , so the two can be tuned separately. For transformers, AdamW with around 0.01 to 0.1 and a warm-up plus cosine schedule is the standard recipe; biases and normalisation weights are usually excluded from the decay.
In PyTorch
torch.optim.Adam(params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0): its weight_decay is the L2 version. torch.optim.AdamW(params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.01): decoupled, applied as p *= 1 - lr * weight_decay before the Adam step. Both keep two buffers per parameter, so the optimizer state is twice the size of the model: for a 7-billion-parameter model in float32, 56 GB of optimizer state alone. The optimizer comparison checks our NumPy code against both classes.
Pitfalls
Adam(weight_decay=...)when you meant AdamW. It is L2 regularisation, not decoupled decay; useAdamW.- Copying SGD's learning rate. Adam's is a step length, typically to ; SGD's 0.1 would be a disaster.
- No schedule. Steps stay about long; decay the learning rate at the end of training to settle.
- Changing without thinking. For very small gradients (or low-precision training), matters; values like are common in mixed precision.
Practice
- With and , what are the bias-correction divisors at and ?
Answer
and at ; and at .
- In the AdamW example, which weight would change if you lowered to 0.02, and to what?
Answer
The quiet feature's. The balance point becomes 50, which is beyond the unregularised value 29.7, so the decay no longer stops it there: it settles just below the least-squares value 29.692, where the shrinking Adam step and the decay balance (running the example with lam = 0.02 gives 29.645). The loud feature stays near 0.30.
- Why is Adam's update approximately invariant to multiplying the loss by 1000?
Answer
scales by 1000 and by 1000, so their ratio is unchanged (apart from ). SGD's step would grow 1000 times.
Test yourself
Without bias correction, Adam's first step for a constant gradient (with , ) is…
- exactly
- about , too large
- about , too small
- zero
What is the difference between Adam(weight_decay=λ) and AdamW(weight_decay=λ) in PyTorch?
- None
- Adam adds to the gradient (L2), which is then rescaled by ; AdamW shrinks the weights directly by , outside the adaptive scaling
- AdamW has no momentum
- Adam decays the learning rate
In the example, Adam with an L2 penalty converged to exactly the ridge solution. Why?
- Adam always finds ridge solutions
- Adam stops where its gradient, here the gradient of MSE plus the L2 term, is zero, and that is the ridge optimum
- Because the data was standardised
- By coincidence
About how large is each parameter's Adam step when its gradient has a steady sign?
- times the gradient
- about
- squared
- it depends on the loss scale