Simple Algorithm
Deep Learning · Representation · 24 min

Adaptive Optimizers: RMSProp, Adam & AdamW

Per-parameter step sizes, bias correction and decoupled weight decay.

One learning rate for a billion parameters is a compromise: some parameters see large, consistent gradients and others tiny, rare ones. Adaptive optimizers give every parameter its own step size, read off from the history of its gradients. Adam, the most widely used of them, adds momentum and a small statistical correction, and AdamW fixes how it interacts with weight decay. This lesson derives all three and the practical lore around them.

What you’ll learn

  • Write the AdaGrad, RMSProp and Adam updates, and explain what per-coordinate scaling does on ill-conditioned or poorly scaled problems.
  • Derive Adam's bias correction from E[vt]=(1−β2t)E[g2]\E[\mathbf v_t]=(1-\beta_2^t)\E[\mathbf g^2], and predict the size of its first steps.
  • Show why an L2 penalty inside Adam is not weight decay, and implement decoupled weight decay (AdamW) with the usual parameter groups.
  • Choose between AdamW and SGD with momentum, weigh the evidence on generalization, and count the memory cost of optimizer states.

One step size per parameter

Gradient descent's single η\eta must suit the most sharply curved direction, so directions with small gradients crawl. Worse, gradient sizes differ systematically between parameters: an embedding row for a rare word gets a gradient only when that word appears, and layers deep in a network can see gradients orders of magnitude smaller than others. The adaptive idea is to divide each coordinate's step by a running measure of that coordinate's gradient size.

AdaGrad (Duchi, Hazan & Singer, 2011) divides by the root of the sum of all past squared gradients. Rare features keep large steps, which is why it excels on sparse problems, but every step size shrinks like 1/t1/\sqrt t, often too fast for long nonconvex training runs. RMSProp (Tieleman & Hinton, 2012, in lecture notes for a course rather than a paper) replaces the sum by an exponential moving average, so the scale tracks recent gradients:

AdaGrad:  st=st−1+gt2,RMSProp:  st=ρ st−1+(1−ρ) gt2;θt+1=θt−η gtst+ϵ\text{AdaGrad:}\ \ \mathbf s_t=\mathbf s_{t-1}+\mathbf g_t^2,\qquad\text{RMSProp:}\ \ \mathbf s_t=\rho\,\mathbf s_{t-1}+(1-\rho)\,\mathbf g_t^2;\qquad\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta\,\frac{\mathbf g_t}{\sqrt{\mathbf s_t}+\epsilon}
Squares, roots and divisions act coordinate by coordinate. Dividing by st\sqrt{\mathbf s_t} is a diagonal preconditioner: it rescales each axis of parameter space, but it cannot rotate the axes.

A consequence worth absorbing: the step is nearly scale-free. Multiply the loss by 100 and every gradient grows by 100, but so does st\sqrt{\mathbf s_t}; the update barely changes, up to ϵ\epsilon. Plain SGD's step would grow by 100. It also means a coordinate with a tiny but consistent gradient moves about as far per step as one with a large gradient, which is exactly what helps near a saddle point, where the escape direction has almost no slope.

Adam and its bias correction

Adam (Kingma & Ba, 2015) combines RMSProp's scaling with momentum, keeping exponential moving averages of the gradient and of its square, then correcting both for their start at zero:

text
ADAM(θ, η = 10⁻³, β₁ = 0.9, β₂ = 0.999, ε = 10⁻⁸)
  m ← 0;  v ← 0                                  // first and second moments, one per parameter
  for t = 1, 2, …
      g ← ∇ℒ_B(θ)                                // mini-batch gradient
      m ← β₁·m + (1 − β₁)·g                      // momentum: EMA of g
      v ← β₂·v + (1 − β₂)·g ⊙ g                  // EMA of g², elementwise
      m̂ ← m / (1 − β₁ᵗ);   v̂ ← v / (1 − β₂ᵗ)     // bias correction
      θ ← θ − η · m̂ / (√v̂ + ε)                   // elementwise

The defaults are those of the original paper. Large language models commonly lower β2\beta_2 to 0.950.95, which forgets old gradient sizes faster; GPT-3 used β1=0.9\beta_1=0.9, β2=0.95\beta_2=0.95, ϵ=10−8\epsilon=10^{-8} and weight decay 0.10.1 (Brown et al., 2020).

DerivationWhy divide by 1 − β₂ᵗ
  1. vt=(1−β2)∑i=1tβ2 t−i gi2\mathbf v_t=(1-\beta_2)\sum_{i=1}^{t}\beta_2^{\,t-i}\,\mathbf g_i^2

    Unroll the recursion from v0=0\mathbf v_0=\mathbf 0: the second moment is a weighted sum of past squared gradients whose weights do not sum to one.

  2. E[vt]=E[g2] (1−β2)∑i=1tβ2 t−i=E[g2] (1−β2 t)\E[\mathbf v_t]=\E[\mathbf g^2]\,(1-\beta_2)\sum_{i=1}^t\beta_2^{\,t-i}=\E[\mathbf g^2]\,\big(1-\beta_2^{\,t}\big)

    Suppose the squared gradients are stationary, E[gi2]=E[g2]\E[\mathbf g_i^2]=\E[\mathbf g^2]. A geometric sum gives the expectation, which falls short by exactly 1−β2t1-\beta_2^t:

  3. t=1:m^1=g1,v^1=g12⟹Δθ1=−η g1∣g1∣+ϵ≈−η sign⁡(g1)t=1:\quad\hat{\mathbf m}_1=\mathbf g_1,\quad\hat{\mathbf v}_1=\mathbf g_1^2\quad\Longrightarrow\quad\Delta\boldsymbol\theta_1=-\eta\,\frac{\mathbf g_1}{\abs{\mathbf g_1}+\epsilon}\approx-\eta\,\sign(\mathbf g_1)

    So v^t=vt/(1−β2t)\hat{\mathbf v}_t=\mathbf v_t/(1-\beta_2^t) is unbiased, and likewise m^t\hat{\mathbf m}_t. The correction matters early: with β2=0.999\beta_2=0.999, v1\mathbf v_1 is a thousand times too small, and only after a few thousand steps is β2t\beta_2^t negligible. If the squared gradients drift slowly the bias is small but nonzero, which Kingma & Ba absorb into an error term.

Predict before you look

Adam with η=10−3\eta=10^{-3}, ϵ=10−8\epsilon=10^{-8} and default betas takes its first step. One parameter's first gradient is 10−410^{-4}. How far does that parameter move, in units of 10−310^{-3}?

Show the answer

1 × 10⁻³

m^1=10−4\hat m_1=10^{-4} and v^1=10−4\sqrt{\hat v_1}=10^{-4}, so the step is 10−3⋅10−4/(10−4+10−8)≈0.9999×10−310^{-3}\cdot10^{-4}/(10^{-4}+10^{-8})\approx0.9999\times10^{-3}. A parameter with gradient 100100 would move by the same amount, while SGD with the same η\eta would move this one by only 10−710^{-7}. Without bias correction the first step would be (1−β1)/1−β2≈3.16(1-\beta_1)/\sqrt{1-\beta_2}\approx3.16 times larger.

How big are Adam's steps? Kingma & Ba show that the per-coordinate step ∣Δθ∣\abs{\Delta\theta} is at most about η\eta in typical cases, and at most η(1−β1)/1−β2\eta(1-\beta_1)/\sqrt{1-\beta_2} in the worst case, when a gradient has been zero for a long time and suddenly appears. The learning rate therefore sets a trust region in parameter space, regardless of the scale of the loss. Read m^/v^\hat{\mathbf m}/\sqrt{\hat{\mathbf v}} as roughly E[g]/E[g2]=μ/μ2+σ2\E[g]/\sqrt{\E[g^2]}=\mu/\sqrt{\mu^2+\sigma^2} per coordinate: close to ±1\pm1 when the gradient's sign is consistent, and small when noise dominates. Adam takes confident steps where the signal is clear and cautious ones where it is not, an automatic annealing as the signal fades near a minimum.

Decoupled weight decay: AdamW

Two regularizers that are the same thing for SGD come apart for Adam. An L2 penalty adds λ2∥θ∥2\frac\lambda2\norm{\boldsymbol\theta}^2 to the loss, so its gradient adds λθ\lambda\boldsymbol\theta. Weight decay shrinks the weights directly, θ←(1−ηλ)θ\boldsymbol\theta\leftarrow(1-\eta\lambda)\boldsymbol\theta, at every step. For plain SGD the two are identical, since θ−η(g+λθ)=(1−ηλ)θ−ηg\boldsymbol\theta-\eta(\mathbf g+\lambda\boldsymbol\theta)=(1-\eta\lambda)\boldsymbol\theta-\eta\mathbf g.

DerivationAn L2 penalty inside Adam is not weight decay
  1. Δθi=−η gi+λθiv^i+ϵ=−η giv^i+ϵ−ηλv^i+ϵ⏟decay rate of θi θi\Delta\theta_i=-\eta\,\frac{g_i+\lambda\theta_i}{\sqrt{\hat v_i}+\epsilon}=-\eta\,\frac{g_i}{\sqrt{\hat v_i}+\epsilon}-\underbrace{\frac{\eta\lambda}{\sqrt{\hat v_i}+\epsilon}}_{\text{decay rate of }\theta_i}\,\theta_i

    Put the penalty's gradient into Adam. Take β1=0\beta_1=0 for clarity; the penalty then travels through the same per-coordinate division as the data gradient:

  2. decay of θidecay of θj=v^j+ϵv^i+ϵ\frac{\text{decay of }\theta_i}{\text{decay of }\theta_j}=\frac{\sqrt{\hat v_j}+\epsilon}{\sqrt{\hat v_i}+\epsilon}

    Each weight now decays at its own rate, inversely proportional to its typical gradient size: weights that receive large gradients are barely regularized, those with small gradients are shrunk hard. (And λθ\lambda\boldsymbol\theta also leaks into v^\hat{\mathbf v}.) The regularization is coupled to the preconditioner in a way nobody chose.

  3. θ←θ−η(m^v^+ϵ+λ θ)\boldsymbol\theta\leftarrow\boldsymbol\theta-\eta\Big(\frac{\hat{\mathbf m}}{\sqrt{\hat{\mathbf v}}+\epsilon}+\lambda\,\boldsymbol\theta\Big)

    AdamW (Loshchilov & Hutter, 2019) decouples the decay from the gradient-based update, so every weight shrinks by the same factor, exactly as in SGD:

Loshchilov & Hutter found that decoupling makes the best weight decay far less dependent on the learning rate and substantially improves Adam's generalization, closing much of its gap with SGD on image classification. Conventions differ slightly: their paper multiplies the decay by a schedule factor but not by the base rate, while PyTorch's AdamW multiplies λ\lambda by the current learning rate, as written above. It is also standard not to decay biases or the gains of normalization layers, which only rescale activations. Why weight decay matters even when it barely regularizes, through its interaction with normalization and the effective learning rate, is the subject of What Weight Decay Really Does in the Regularization topic.

python
import torch

decay, no_decay = [], []
for name, p in model.named_parameters():
    # matrices and embeddings get weight decay; biases and norm gains do not
    (decay if p.ndim >= 2 else no_decay).append(p)

opt = torch.optim.AdamW(
    [{'params': decay, 'weight_decay': 0.1},
     {'params': no_decay, 'weight_decay': 0.0}],
    lr=3e-4, betas=(0.9, 0.95), eps=1e-8)

A typical setup for a transformer, as of the mid-2020s. PyTorch's default weight_decay for AdamW is 0.010.01; language-model recipes often use 0.10.1 together with β2=0.95\beta_2=0.95, warmup and a decaying schedule.

Adam or SGD?

The generalization debate. Wilson, Roelofs, Stern, Srebro & Recht (2017) built a linearly separable problem on which gradient descent reaches zero test error while AdaGrad, RMSProp and Adam reach test error close to one half, and found that on several deep-learning benchmarks adaptive methods generalized worse than SGD, sometimes by a large margin, even when they trained faster. Choi et al. (2019) countered that such comparisons hinge on the tuning protocol. Adam includes momentum SGD as a limit (with a large ϵ\epsilon, its update approaches momentum SGD with learning rate η/ϵ\eta/\epsilon), so with enough tuning it should never lose, and in their experiments adaptive methods never underperformed momentum or plain gradient descent.

Practice, as of the mid-2020s. AdamW is the standard for transformers in language and vision, and for diffusion models. SGD with momentum remains common in convolutional image-classification recipes, where it is well understood and tuned. Why SGD struggles on transformers in particular has several competing explanations, the subject of the first Emergence lesson below.

OptimizerState per parameterNotes
SGDnonethe baseline
SGD with momentum11 (velocity)common for CNNs
Adam, AdamW22 (m\mathbf m, v\mathbf v)standard for transformers
Adafactorm\mathbf m optional; v\mathbf v factored into row and column statisticssublinear memory for the second moment (Shazeer & Stern, 2018)
8-bit Adam22, stored in 8 bits with block-wise scalesabout a quarter of the state memory (Dettmers, Lewis, Shleifer & Zettlemoyer, 2022)
With mixed-precision training, Adam needs about 16 bytes per parameter: 16-bit weights and gradients (2 + 2 bytes) plus 32-bit master weights, m\mathbf m and v\mathbf v (12 bytes), the accounting behind ZeRO's sharding of optimizer states (Rajbhandari et al., 2020).
Check your understanding

You accidentally multiply your loss by 100 (say, by summing instead of averaging over a batch of 100) and keep every hyperparameter. What happens?

  1. SGD's steps become 100 times larger and may diverge, while Adam's steps barely change
  2. Both optimizers take 100 times larger steps
  3. Adam's steps become 100 times larger, while SGD's barely change
  4. Neither changes, because the minimizer is the same
Show the answer

A. SGD's steps become 100 times larger and may diverge, while Adam's steps barely change

SGD's step is ηg\eta\mathbf g, proportional to the loss scale. Adam divides m^\hat{\mathbf m} by v^\sqrt{\hat{\mathbf v}}, and both scale by 100, so the ratio is unchanged up to the effect of ϵ\epsilon. A plain SGD recipe must rescale η\eta by 1/1001/100 to compensate.

Key takeaways

  • Adaptive methods divide each coordinate's step by a running root-mean-square of its gradients: AdaGrad sums squares (good for sparse features, but steps shrink like 1/t1/\sqrt t), RMSProp and Adam use moving averages. The result is a diagonal preconditioner and a nearly scale-free step.
  • Adam keeps moving averages m\mathbf m and v\mathbf v with E[vt]=(1−β2t)E[g2]\E[\mathbf v_t]=(1-\beta_2^t)\E[\mathbf g^2], so it divides by 1−βt1-\beta^t to remove the bias from starting at zero. Its first step is about η sign⁡(g1)\eta\,\sign(\mathbf g_1), and its steps are roughly bounded by η\eta per coordinate.
  • An L2 penalty inside Adam is divided by v^\sqrt{\hat{\mathbf v}} and decays each weight at a different rate; AdamW applies −ηλθ-\eta\lambda\boldsymbol\theta outside the preconditioner, usually skipping biases and normalization gains.
  • AdamW is the standard for transformers and SGD with momentum is still common for CNNs. Claims that adaptive methods generalize worse depend heavily on tuning, since Adam contains momentum SGD as a limit. Adam's two states cost 8 bytes per parameter, 16 in all with mixed precision.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Adam runs with β2=0.999\beta_2=0.999 but without bias correction. Right after the first step, how does v1\mathbf v_1 compare with E[g2]\E[\mathbf g^2]?

  1. It is unbiased, since it is an average of squared gradients
  2. It is about 10001000 times too large
  3. It is too small by a factor 1−β2=0.0011-\beta_2=0.001, which would make the first steps too large
  4. It is too small by a factor β2=0.999\beta_2=0.999, a negligible difference
Show the answer

C. It is too small by a factor 1−β2=0.0011-\beta_2=0.001, which would make the first steps too large

v1=(1−β2)g12=0.001 g12\mathbf v_1=(1-\beta_2)\mathbf g_1^2=0.001\,\mathbf g_1^2, because the average starts at zero. Dividing by v1\sqrt{\mathbf v_1} would then inflate the step. The correction divides by 1−β2t1-\beta_2^t, exactly the missing weight.

Question 2

Why is adding an L2 penalty λ2∥θ∥2\frac\lambda2\norm{\boldsymbol\theta}^2 to the loss not the same as weight decay when training with Adam?

  1. Because Adam ignores the penalty's gradient
  2. Because the penalty's gradient λθ\lambda\boldsymbol\theta is divided by v^\sqrt{\hat{\mathbf v}}, so weights with large gradient histories are decayed less than others
  3. Because L2 penalties only work with convex losses
  4. They are the same; AdamW only changes the default value of λ\lambda
Show the answer

B. Because the penalty's gradient λθ\lambda\boldsymbol\theta is divided by v^\sqrt{\hat{\mathbf v}}, so weights with large gradient histories are decayed less than others

Inside Adam the decay rate of θi\theta_i becomes ηλ/(v^i+ϵ)\eta\lambda/(\sqrt{\hat v_i}+\epsilon), different for every coordinate. AdamW applies −ηλθ-\eta\lambda\boldsymbol\theta outside the preconditioner, so all weights shrink by the same factor, as with SGD.

Question 3

About how much memory do the weights, gradients and optimizer states take when a 1-billion-parameter model is trained with mixed-precision Adam, by the 16-bytes-per-parameter accounting?

  1. 4 GB
  2. 8 GB
  3. 32 GB
  4. 16 GB
Show the answer

D. 16 GB

2+22+2 bytes for 16-bit weights and gradients, plus 1212 bytes for 32-bit master weights, m\mathbf m and v\mathbf v: 16×10916\times10^9 bytes. Activations come on top. This is why optimizer states are sharded across devices in large-scale training.

Question 4

Choi et al. (2019) argued that, with enough tuning, Adam should never underperform momentum SGD. What is the argument?

  1. Adam always converges faster on convex problems
  2. Adam's bias correction removes the noise that slows SGD
  3. Adam generalizes better because its steps are bounded
  4. With a large ϵ\epsilon, Adam's update approaches momentum SGD with learning rate η/ϵ\eta/\epsilon, so a more general optimizer contains its special case
Show the answer

D. With a large ϵ\epsilon, Adam's update approaches momentum SGD with learning rate η/ϵ\eta/\epsilon, so a more general optimizer contains its special case

When ϵ≫v^\epsilon\gg\sqrt{\hat{\mathbf v}}, the update ηm^/(v^+ϵ)≈(η/ϵ)m^\eta\hat{\mathbf m}/(\sqrt{\hat{\mathbf v}}+\epsilon)\approx(\eta/\epsilon)\hat{\mathbf m} is momentum SGD. Comparisons in which Adam loses often tuned its ϵ\epsilon and betas less than they tuned SGD's learning rate.

Go deeper

Further reading

  • J. Duchi, E. Hazan & Y. Singer, "Adaptive subgradient methods for online learning and stochastic optimization," Journal of Machine Learning Research 12, 2121–2159 (2011).
  • D. P. Kingma & J. Ba, "Adam: A method for stochastic optimization," ICLR (2015).
  • I. Loshchilov & F. Hutter, "Decoupled weight decay regularization," ICLR (2019).
  • A. C. Wilson, R. Roelofs, M. Stern, N. Srebro & B. Recht, "The marginal value of adaptive gradient methods in machine learning," NeurIPS (2017).