TExcelTAD

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 gt\mathbf{g}_t at step t=1,2,…t = 1, 2, \ldots:

mt=β1mt−1+(1−β1) gtfirst moment: average gradientvt=β2vt−1+(1−β2) gt2second moment: average squared gradientm^t=mt1−β1t,v^t=vt1−β2tbias correctionwt=wt−1−η m^tv^t+ϵ\begin{aligned} \mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1 - \beta_1) \, \mathbf{g}_t && \text{first moment: average gradient} \\ \mathbf{v}_t &= \beta_2 \mathbf{v}_{t-1} + (1 - \beta_2) \, \mathbf{g}_t^2 && \text{second moment: average squared gradient} \\ \hat{\mathbf{m}}_t &= \frac{\mathbf{m}_t}{1 - \beta_1^t}, \quad \hat{\mathbf{v}}_t = \frac{\mathbf{v}_t}{1 - \beta_2^t} && \text{bias correction} \\ \mathbf{w}_t &= \mathbf{w}_{t-1} - \eta \, \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} \end{aligned}

with defaults β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8} and η=10−3\eta = 10^{-3}. The ratio m^/v^\hat{m}/\sqrt{\hat{v}} is like a signal-to-noise ratio: close to ±1\pm 1 when the gradient keeps a steady sign, close to 0 when it flips around. So every parameter's step is at most about η\eta, whatever the scale of its gradient. That makes η\eta 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 m1=(1−β1)g=0.1gm_1 = (1 - \beta_1) g = 0.1g and v1=(1−β2)g2=0.001g2v_1 = (1 - \beta_2) g^2 = 0.001 g^2: both are far too small, and by different amounts. Dividing by 1−βt1 - \beta^t makes each an unbiased average from the first step. Feed Adam a constant gradient of 5 and look at the step divided by η\eta:

python · try it yourself
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 η\eta (ratio 1.000), as it should be for a perfectly consistent gradient. Without it, the first step is 0.10.001=3.162\frac{0.1}{\sqrt{0.001}} = 3.162 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 β2=0.999\beta_2 = 0.999 and bias correction, with β1\beta_1 on the second slider. On the narrow valley with η=0.08\eta = 0.08, Adam's first steps go diagonally: both coordinates move by about η\eta, regardless of the 10-to-1 curvature. After 60 steps the loss is about 0.022, at (−0.189,−0.065)(-0.189, -0.065), still on its way: a constant step of 0.08 per coordinate covers distance slowly when the start is 2.5 away. Raise η\eta 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 η\eta.

−2−1012−202Loss contours: narrow valleyxy10−610−410−211001040204060stepLoss f(x, y), log scalepath / lossstartminimumAdam: step ≈ η per coordinate

L2 regularisation is not weight decay (for Adam)

For plain SGD two things are the same. L2 regularisation adds λ2∥w∥2\frac{\lambda}{2} \lVert \mathbf{w} \rVert^2 to the loss, so λw\lambda \mathbf{w} is added to the gradient. Weight decay shrinks the weights directly every step. With SGD,

w−η(g+λw)=(1−ηλ)w−ηg,\mathbf{w} - \eta (\mathbf{g} + \lambda \mathbf{w}) = (1 - \eta \lambda) \mathbf{w} - \eta \mathbf{g},

so they are identical (Weight Decay and Dropout). With Adam they are not. If λw\lambda \mathbf{w} goes into the gradient, it also goes through m\mathbf{m} and v\mathbf{v} and is divided by v^\sqrt{\hat{\mathbf{v}}}: 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:

wt=wt−1−η λ wt−1−η m^tv^t+ϵ.\mathbf{w}_t = \mathbf{w}_{t-1} - \eta \, \lambda \, \mathbf{w}_{t-1} - \eta \, \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} .

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 λ=0.1\lambda = 0.1:

python · try it yourself
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 (0.304,2.413)(0.304, 2.413). That is no accident: Adam stops where its gradient, here ∇MSE+λw\nabla \text{MSE} + \lambda \mathbf{w}, 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 10.0=1/λ10.0 = 1/\lambda. At that point the decay ηλw=η\eta \lambda w = \eta balances an Adam step of size η\eta (its gradient keeps a constant sign, so m^/v^=1\hat{m}/\sqrt{\hat{v}} = 1). 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 λ\lambda no longer depends strongly on η\eta, so the two can be tuned separately. For transformers, AdamW with λ\lambda 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; use AdamW.
  • Copying SGD's learning rate. Adam's η\eta is a step length, typically 10−410^{-4} to 3×10−33 \times 10^{-3}; SGD's 0.1 would be a disaster.
  • No schedule. Steps stay about η\eta long; decay the learning rate at the end of training to settle.
  • Changing ϵ\epsilon without thinking. For very small gradients (or low-precision training), ϵ\epsilon matters; values like 10−610^{-6} are common in mixed precision.

Practice

  1. With β1=0.9\beta_1 = 0.9 and β2=0.999\beta_2 = 0.999, what are the bias-correction divisors at t=1t = 1 and t=10t = 10?
Answer

1−0.9=0.11 - 0.9 = 0.1 and 1−0.999=0.0011 - 0.999 = 0.001 at t=1t = 1; 1−0.910≈0.6511 - 0.9^{10} \approx 0.651 and 1−0.99910≈0.009961 - 0.999^{10} \approx 0.00996 at t=10t = 10.

  1. In the AdamW example, which weight would change if you lowered λ\lambda to 0.02, and to what?
Answer

The quiet feature's. The balance point 1/λ1/\lambda 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.

  1. Why is Adam's update approximately invariant to multiplying the loss by 1000?
Answer

m^\hat{m} scales by 1000 and v^\sqrt{\hat{v}} by 1000, so their ratio is unchanged (apart from ϵ\epsilon). SGD's step would grow 1000 times.

Test yourself

Without bias correction, Adam's first step for a constant gradient (with β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999) is…

  1. exactly η\eta
  2. about 3.16η3.16\eta, too large
  3. about 0.1η0.1\eta, too small
  4. zero

What is the difference between Adam(weight_decay=λ) and AdamW(weight_decay=λ) in PyTorch?

  1. None
  2. Adam adds λw\lambda \mathbf{w} to the gradient (L2), which is then rescaled by v^\sqrt{\hat{v}}; AdamW shrinks the weights directly by ηλw\eta\lambda\mathbf{w}, outside the adaptive scaling
  3. AdamW has no momentum
  4. Adam decays the learning rate

In the example, Adam with an L2 penalty converged to exactly the ridge solution. Why?

  1. Adam always finds ridge solutions
  2. Adam stops where its gradient, here the gradient of MSE plus the L2 term, is zero, and that is the ridge optimum
  3. Because the data was standardised
  4. By coincidence

About how large is each parameter's Adam step when its gradient has a steady sign?

  1. η\eta times the gradient
  2. about η\eta
  3. η\eta squared
  4. it depends on the loss scale