TExcelTAD
Home › Math for Deep Learning & LLMs › Adam and AdamW

Adam and AdamW

Adam (Kingma and Ba, 2014) combines momentum's running average of gradients with RMSProp's running average of squared gradients, plus a bias correction for the first steps. With decoupled weight decay (AdamW, Loshchilov and Hutter) it is the default optimizer for transformers and almost every LLM. Its update fits in five lines, but each line has a reason.

The algorithm

With gradient gt\mathbf{g}_t at step t=1,2,…t = 1, 2, \ldots and m0=v0=0\mathbf{m}_0 = \mathbf{v}_0 = \mathbf{0}:

mt=β1mt−1+(1−β1)gt(first moment, momentum)vt=β2vt−1+(1−β2)gt⊙gt(second moment, RMSProp)m^t=mt1−β1t,v^t=vt1−β2t(bias correction)θt=θt−1−ηm^tv^t+ϵ\begin{aligned} \mathbf{m}_t &= \beta_1\mathbf{m}_{t-1} + (1 - \beta_1)\mathbf{g}_t && \text{(first moment, momentum)} \\ \mathbf{v}_t &= \beta_2\mathbf{v}_{t-1} + (1 - \beta_2)\mathbf{g}_t \odot \mathbf{g}_t && \text{(second moment, RMSProp)} \\ \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)} \\ \boldsymbol{\theta}_t &= \boldsymbol{\theta}_{t-1} - \eta\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} \end{aligned}

Typical values: β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 (LLMs often use 0.950.95), ϵ=10−8\epsilon = 10^{-8}.

Why bias correction?

Because m0=0\mathbf{m}_0 = \mathbf{0}, the averages start biased toward zero: after one step m1=0.1g1\mathbf{m}_1 = 0.1\mathbf{g}_1. Taking expectations with stationary gradients, E[mt]=(1−β1t)E[g]\mathbb{E}[\mathbf{m}_t] = (1 - \beta_1^t)\mathbb{E}[\mathbf{g}], so dividing by 1−β1t1 - \beta_1^t removes the bias. Without it, the second moment (with β2=0.999\beta_2 = 0.999) would be tiny for the first thousand steps and the first updates huge.

python · try it yourself
import numpy as np

b1, b2 = 0.9, 0.999
g = 0.5                                     # a constant gradient
m = v = 0.0
for t in range(1, 6):
    m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g * g
    raw = m / np.sqrt(v); corrected = (m / (1 - b1**t)) / np.sqrt(v / (1 - b2**t))
    print(f"t={t}: m={m:.4f} v={v:.6f}  uncorrected step {raw:.3f}  corrected step {corrected:.3f}")
t=1: m=0.0500 v=0.000250  uncorrected step 3.162  corrected step 1.000
t=2: m=0.0950 v=0.000500  uncorrected step 4.250  corrected step 1.000
t=3: m=0.1355 v=0.000749  uncorrected step 4.950  corrected step 1.000
t=4: m=0.1719 v=0.000999  uncorrected step 5.442  corrected step 1.000
t=5: m=0.2048 v=0.001248  uncorrected step 5.797  corrected step 1.000

With a constant gradient the corrected step is exactly η\eta per coordinate from the very first step. Uncorrected, the first steps would be 3 to 6 times too large, because the second moment (with β2=0.999\beta_2 = 0.999) starts out even more biased toward zero than the first.

Properties

  • Scale invariance: multiplying the loss by a constant leaves the update unchanged.
  • Bounded steps: each coordinate moves by roughly at most η\eta per step, which makes η\eta an interpretable "trust region" in parameter space.
  • Signal-to-noise: m^/v^\hat{m}/\sqrt{\hat{v}} is near ±1\pm 1 for consistent gradients and small for noisy ones whose sign keeps flipping.

AdamW: decoupled weight decay

Adding an L2 penalty to the loss puts λθ\lambda\boldsymbol{\theta} into g\mathbf{g}, where Adam then divides it by v^\sqrt{\hat{\mathbf{v}}}: parameters with large gradients get almost no decay. AdamW applies the decay directly to the weights instead:

θt=θt−1−η(m^tv^t+ϵ+λθt−1)\boldsymbol{\theta}_t = \boldsymbol{\theta}_{t-1} - \eta\left(\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} + \lambda\boldsymbol{\theta}_{t-1}\right)

so every weight shrinks by the same factor 1−ηλ1 - \eta\lambda per step, as with SGD (Regularization).

python · try it yourself
import numpy as np

def adam_step(theta, g, state, lr=0.01, lam=0.1, decoupled=True, b1=0.9, b2=0.999, eps=1e-8):
    m, v, t = state
    if not decoupled: g = g + lam * theta               # L2 inside the gradient
    t += 1; m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g * g
    step = (m / (1 - b1**t)) / (np.sqrt(v / (1 - b2**t)) + eps)
    if decoupled: step = step + lam * theta
    return theta - lr * step, (m, v, t)
# two weights of equal size: one with large data gradients, one with zero data gradient
for decoupled in (False, True):
    th, st = np.array([1.0, 1.0]), (np.zeros(2), np.zeros(2), 0)
    for _ in range(500):
        g = np.array([np.sin(_) * 10.0, 0.0])            # noisy large gradient, zero gradient
        th, st = adam_step(th, g, st, decoupled=decoupled)
    print(("AdamW " if decoupled else "Adam+L2"), "weights after 500 steps:", np.round(th, 3))
Adam+L2 weights after 500 steps: [0.89 0.  ]
AdamW  weights after 500 steps: [0.585 0.606]

With L2-in-the-gradient, the parameter with zero data gradient decays at full speed (its v^\sqrt{\hat{v}} is just λθ\lambda\theta, so its normalized step is about 1), while the one with large gradients barely decays. AdamW shrinks both at the same rate 1−ηλ1 - \eta\lambda.

Memory cost

Adam keeps two extra numbers per parameter (m\mathbf{m}, v\mathbf{v}), usually in fp32. In standard mixed-precision training (bf16 weights and gradients, plus an fp32 master copy and the two fp32 moments: 2+2+4+4+42 + 2 + 4 + 4 + 4 bytes), that is 16 bytes per parameter: a 7B model needs about 112 GB just for weights, gradients and optimizer state, before activations (Counting Parameters and FLOPs). Memory-light variants (Adafactor, 8-bit Adam) and sharding (ZeRO) attack that cost.

In software

  • torch.optim.AdamW(params, lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1, eps=1e-8) is a typical LLM setting.
  • torch.optim.Adam(weight_decay=…) implements the L2 version, not AdamW.
  • Adam is used with a warmup and decay schedule (Schedules and Clipping).

Go further: Comparing Optimizers and Checking Them Against torch.optim runs these updates through one interface, with practical defaults.

Exercises

Exercise 1: First step

At t=1t = 1 with gradient gg (scalar, ϵ=0\epsilon = 0), what is Adam's step?

Answer

ηsign⁡(g)\eta\operatorname{sign}(g).

Solution

m^1=g\hat{m}_1 = g, v^1=g2\hat{v}_1 = g^2, so the step is ηg/∣g∣\eta g/\lvert g \rvert. The first step has size η\eta in every coordinate with a nonzero gradient, whatever the gradient's magnitude.

Exercise 2: Bias correction factor

With β2=0.999\beta_2 = 0.999, what is 1−β2t1 - \beta_2^t at t=10t = 10 and t=1000t = 1000?

Answer

About 0.009950.00995 and 0.6320.632.

Solution

1−0.99910≈0.009951 - 0.999^{10} \approx 0.00995; 1−0.9991000≈1−e−1=0.6321 - 0.999^{1000} \approx 1 - e^{-1} = 0.632. Without correction, v^\hat{v} would be about 100 times too small at step 10.

Exercise 3: Optimizer memory (code)

Compute the training memory for weights (fp32 master copy), bf16 gradients and Adam's two fp32 moments for a 1.3B-parameter model.

Answer

About 18.2 GB (14 bytes per parameter).

Solution

4 (weights) + 2 (gradients) + 4 + 4 (moments) = 14 bytes; with fp32 gradients it would be 16.

python · try it yourself
N = 1.3e9
print(round(N * (4 + 2 + 4 + 4) / 1e9, 1), "GB")
18.2 GB

Test yourself

Adam's mt\mathbf{m}_t and vt\mathbf{v}_t are…

  1. the weights and biases
  2. moving averages of the gradient and the squared gradient
  3. the learning rate and momentum
  4. the Hessian and its inverse

Why does Adam divide by 1−βt1 - \beta^t?

  1. To decay the learning rate
  2. To correct the bias toward zero caused by initializing the averages at zero
  3. To add noise
  4. To clip gradients

How does AdamW differ from Adam with an L2 penalty?

  1. It uses no second moment
  2. It applies weight decay directly to the weights instead of through the adaptive gradient
  3. It has no momentum
  4. It is identical