Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Optimizers

P4.1340 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

Backpropagation only measures the gradient. The optimizer is the rule that turns a stream of noisy gradients into steps, and the choice of rule changes how fast a network trains, how stable it is, and how much memory it needs.

  • Large language models are commonly trained with AdamW, so its decoupled weight decay is worth understanding exactly. (P4.17: Regularization for neural nets)
  • Every optimizer still needs a learning rate, and the rate is usually changed during training. (P4.14: Learning-rate schedules)
  • Optimizer state is a large part of training memory: Adam keeps two extra numbers per parameter. (P10.B4: Counting compute and memory, coming soon)
  • When a loss curve is flat, noisy or exploding, the optimizer and its settings are among the first things to check. (P4.22: The training recipe and debugging)

Before this: Gradient descent, Stochastic and mini-batch gradient descent, Momentum and adaptive steps (preview), Backpropagation: step by step with numbers, The PyTorch training loop

After this lesson you can

  • Write the update rules of SGD, momentum, Nesterov, AdaGrad, RMSProp, Adam and AdamW in the form PyTorch uses
  • Say what each optimizer remembers between steps, and how much memory that costs
  • Explain Adam's bias correction and why AdaGrad’s step shrinks forever
  • Explain why L2 in the gradient and decoupled weight decay differ for Adam but not for SGD
  • Choose a reasonable first optimizer, and say what the choice does not settle

P4.8 ended with a weight update: find each weight’s gradient, then move it a little against the gradient. Nothing says that the step has to be just −ηg-\eta\mathbf{g}. The gradients are the same measurements whatever you do with them. What you do with them is the optimizer, and it has a large effect on how a network trains.

P1.F5 gave a first look at the ideas: remember past gradients (momentum), and give every parameter its own step size (AdaGrad, RMSProp, Adam). This lesson uses them as a neural-network trainer would. It keeps the same notation and settings, compares the seven standard rules in one race, adds weight decay, and counts what each one costs in memory.

What an optimizer is

Training repeats three steps (P4.8): a forward pass, a backward pass, and an update. The backward pass gives the mini-batch gradient gt=∇θLB(θt)\mathbf{g}_t = \nabla_{\boldsymbol{\theta}}\mathcal{L}_B(\boldsymbol{\theta}_t) computed on a batch of BB examples. P1.F4 showed that this gradient is the true gradient plus noise. An optimizer is the rule for the update:

θt+1=θt−step(gt, gt−1, … )\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \text{step}(\mathbf{g}_t,\ \mathbf{g}_{t-1},\ \dots)

The step may depend on past gradients too, so many optimizers keep state: extra numbers stored for every parameter, updated at every step. In PyTorch (P2.7) this is the object that you create once, torch.optim.…(model.parameters(), …), and whose step() method applies the rule to the gradients that loss.backward() just left in each parameter. Swapping the optimizer changes one line of the loop.

This lesson follows PyTorch’s forms of the update rules, since that is what you will run. They match P1.F5 where P1.F5 wrote them, with β\beta called the momentum coefficient and RMSProp’s averaging constant called ρ\rho. All operations on vectors are elementwise, one parameter at a time, as in P1.F5.

The race

Every optimizer below starts from the same point (the ring) and sees the same gradients, so the trails differ only because of the step rule. Press Play and watch, then read the seven rules one at a time.

Surface:

The bowl of P1.F5 with κ = 100: loss x² + 100y², a long narrow valley.

−4−2024−202xy

Ring: the shared start. Star: a lowest point. Big marker: where each optimizer is now.

At step 120 the lowest loss among the shown optimizers is AdaGrad’s, 2.0e−21. 6 of 7 are within 0.05 of the lowest possible loss (0).

Optimizer (press to show or hide)loss nowwithin 0.05 of lowest
0.123 not yet
3.6e−4 step 73
1.3e−5 step 22
2.0e−21 step 12
0.226 step 39
3.1e−4 step 48
8.9e−5 step 47
Learning rate of:
Now: SGD 0.0095, Momentum 0.0095, Nesterov 0.005, AdaGrad 1, RMSProp 0.1, Adam 0.1, AdamW 0.1

Loss above the lowest possible value, log scale (lower is better)

0.00010.0010.010.11101001000050100step

Values below 0.0001 are drawn on the bottom line.

Fixed settings: momentum β = 0.9, RMSProp averaging 0.9, Adam β₁ = 0.9, β₂ = 0.999, ε = 10⁻⁸. The default learning rates were picked by hand for each surface so that every optimizer stays on the map; the race is a picture of how the rules behave, not a ranking of the optimizers. “Within 0.05” means the loss was at most 0.05 above its lowest possible value at some step up to the step shown.

Seven optimizers race from one start on a made-up loss surface. Each trail has its own colour, marker and dash pattern, and the list under the map says which is which. Press a name to hide or show its trail. Pick a surface, press Play, then change one optimizer's learning rate, switch gradient noise on, or move the AdamW decay λ. The default learning rates were chosen by hand for each surface, so this is a picture of how the rules behave, not a ranking.

Things to try, all with the widget’s default settings (“within 0.05” is the readout’s last column):

  • Ravine (the κ=100\kappa = 100 bowl of P1.F5, loss x2+100y2x^2 + 100y^2). Plain SGD with η=0.0095\eta = 0.0095 is still at loss 0.1230.123 after 120 steps. Momentum with the same η\eta is within 0.050.05 of the bottom from step 73, and the adaptive rules are there between step 12 and step 48. RMSProp gets within 0.050.05 at step 39 and then ends at 0.2260.226: with a constant η\eta it hovers, as P1.F5 showed.
  • Nesterov on the ravine. Its default is η=0.005\eta = 0.005. Select Nesterov under “Learning rate of” and raise it to 0.00950.0095, the value that suits SGD and momentum: the trail leaves the map at step 19. P1.F5 found the same limit for this form.
  • Saddle. The start is almost on the saddle’s ridge, so the gradient in yy is tiny. After 10 steps yy is 0.0260.026 for SGD and 0.480.48 for Adam: dividing by the size of the gradient makes the small gradient count.
  • Plateau. AdaGrad gets within 0.050.05 at step 23. The other six need between 66 and 82 steps. Momentum overshoots the lowest point on the flat left side, because on a flat region it keeps its speed.
  • Banana. Adam ends at 3.3×10−73.3\times10^{-7} and AdamW ends at 0.00980.0098, because AdamW’s decay pulls the weights toward 00 while the lowest point is at (1,1)(1, 1). Set the AdamW decay λ\lambda to 00 and its trail lies exactly on Adam’s.
  • Gradient noise on (the same seeded noise for every optimizer, standing in for mini-batches). On the ravine SGD ends at loss 2.12.1 and the other six end between 0.0970.097 and 0.360.36. Noise makes every trail hover, and a smaller η\eta makes the hovering smaller, as in P1.F4.

SGD

The plain rule from P1.F3 and P1.F4, with the mini-batch gradient:

θ←θ−η g.\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\,\mathbf{g}.

It keeps no state. Its one setting is the learning rate η\eta, and the best η\eta depends on the curvature of the loss, which is not known in advance. In a ravine it has to use a small η\eta because of the steepest direction (P1.F5), and then it crawls along the valley. In PyTorch, always set lr yourself: the library’s default for torch.optim.SGD (0.001 in PyTorch 2.9) is a placeholder, not a good value for your model.

Momentum and Nesterov

PyTorch’s torch.optim.SGD(…, momentum=μ) keeps one buffer b\mathbf{b}, the same as P1.F5’s velocity v\mathbf{v} with μ=β\mu = \beta:

b←μ b+g,θ←θ−η b.\begin{aligned} \mathbf{b} &\leftarrow \mu\,\mathbf{b} + \mathbf{g},\\ \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta\,\mathbf{b}. \end{aligned}

The buffer starts as b=g\mathbf{b} = \mathbf{g} at the first step, which is the same as starting from zero. All of the P1.F5 facts carry over. With a steady gradient the buffer grows to g/(1−μ)\mathbf{g}/(1-\mu), so steps along a steady slope are about 1/(1−μ)1/(1-\mu) times longer, and a gradient that flips sign cancels. With μ=0.9\mu = 0.9 that is a factor of 10. Because the steps along a steady slope are longer, momentum can overshoot more on a bumpy loss, so its best rate is often smaller than plain SGD’s. On a smooth bowl the stable range is actually wider (P1.F5), so check the rate for each optimizer. In the race both use η=0.0095\eta = 0.0095 on the ravine, and momentum is the one that reaches the bottom.

Nesterov momentum, nesterov=True, changes the step to use the new buffer once more:

b←μ b+g,θ←θ−η (g+μ b).\begin{aligned} \mathbf{b} &\leftarrow \mu\,\mathbf{b} + \mathbf{g},\\ \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta\,(\mathbf{g} + \mu\,\mathbf{b}). \end{aligned}

This looks different from P1.F5’s look-ahead form, where the gradient is computed at θ−ηβv\boldsymbol{\theta} - \eta\beta\mathbf{v}. It is the same method written for a different variable. The parameter that PyTorch stores is P1.F5’s look-ahead point θ−ηβv\boldsymbol{\theta} - \eta\beta\mathbf{v}, so the gradient PyTorch computes at the stored parameter is already the look-ahead gradient. Running both on the κ=100\kappa = 100 bowl with η=0.005\eta = 0.005 and β=0.9\beta = 0.9 and comparing PyTorch’s parameter with that look-ahead point gives the same numbers, to 4×10−164\times10^{-16} over 60 steps. So the Nesterov trail in the race is that look-ahead point. (PyTorch requires momentum above 0 and no dampening for Nesterov.) The effect is that the correction for an overshoot arrives one step sooner.

AdaGrad: add up all the squares

AdaGrad (Duchi, Hazan and Singer, 2011) keeps, for each parameter, the sum of its squared gradients, and divides the step by its square root:

G←G+g2,θ←θ−η gG+ε.\begin{aligned} G &\leftarrow G + g^2,\\ \theta &\leftarrow \theta - \frac{\eta\,g}{\sqrt{G} + \varepsilon}. \end{aligned}

PyTorch uses ε=10−10\varepsilon = 10^{-10} here. A parameter with large gradients gets a small step, and one with rare, small gradients gets a large one. This suits problems where some features appear rarely.

The weakness is in the word sum. GG only grows, so the step only shrinks. Take a gradient that is 11 at every step. After tt steps G=tG = t, so the step is η/t\eta/\sqrt{t}:

  • step 1: η\eta,
  • step 4: 0.5 η0.5\,\eta,
  • step 100: 0.1 η0.1\,\eta,
  • step 10,000: 0.01 η0.01\,\eta.

Even if the gradients later become small and the parameter should move again, GG remembers every old gradient for ever. This is why the shrinking can stall a long training run. The original paper analyses convex online problems, where the shrinking step is part of the guarantee.

RMSProp: forget the old squares

RMSProp replaces the sum by a moving average, the rule of P1.F5:

s←ρ s+(1−ρ) g2,θ←θ−η gs+ε.\begin{aligned} s &\leftarrow \rho\,s + (1-\rho)\,g^2,\\ \theta &\leftarrow \theta - \frac{\eta\,g}{\sqrt{s} + \varepsilon}. \end{aligned}

It was introduced in the slides of Geoffrey Hinton’s 2012 Coursera course, not in a paper, so you cite the course. This lesson uses ρ=0.9\rho = 0.9 as P1.F5 did and ε=10−8\varepsilon = 10^{-8}. PyTorch’s own default for the averaging constant, called alpha, is 0.990.99, and its default learning rate is 0.010.01.

The difference from AdaGrad shows when the gradients change size. Let a gradient be 11 for 100 steps and then drop to 0.10.1. Measured as a fraction of η\eta: just before the drop, at step 100, AdaGrad’s step is 0.10.1 (it has been shrinking) and RMSProp’s step is 11 (its average of squares has settled at 11). Right after the drop, AdaGrad’s step falls to 0.010.01 and stays there, because GG still holds the 100 big gradients. RMSProp’s step is 0.1050.105 right after the drop and rises to 0.2770.277 by step 120 as the average forgets the big gradients. RMSProp can recover. AdaGrad cannot.

Adam: momentum plus a step size per parameter

Adam (Kingma and Ba, posted December 2014, published at ICLR 2015) combines both ideas. It keeps a moving average m\mathbf{m} of the gradient (momentum) and a moving average s\mathbf{s} of its square (RMSProp), and divides one by the root of the other. For step number t=1,2,…t = 1, 2, \dots:

m←β1m+(1−β1) g,s←β2s+(1−β2) g2,m^=m1−β1 t,s^=s1−β2 t,θ←θ−η m^s^+ε.\begin{aligned} \mathbf{m} &\leftarrow \beta_1\mathbf{m} + (1-\beta_1)\,\mathbf{g},\\ \mathbf{s} &\leftarrow \beta_2\mathbf{s} + (1-\beta_2)\,\mathbf{g}^2,\\ \hat{\mathbf{m}} &= \frac{\mathbf{m}}{1-\beta_1^{\,t}},\qquad \hat{\mathbf{s}} = \frac{\mathbf{s}}{1-\beta_2^{\,t}},\\ \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta\,\frac{\hat{\mathbf{m}}}{\sqrt{\hat{\mathbf{s}}} + \varepsilon}. \end{aligned}

The defaults are η=10−3\eta = 10^{-3}, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and ε=10−8\varepsilon = 10^{-8}, the same in the paper and in PyTorch. Here β2=0.999\beta_2 = 0.999 means the average of squares remembers about the last 1/(1−β2)=10001/(1-\beta_2) = 1000 steps, and β1=0.9\beta_1 = 0.9 means the gradient average remembers about 10.

The correction. Both averages start at 00, so in the first steps they are too small. Take a gradient g=2g = 2 at every step:

  • step 1: m=0.1⋅2=0.2m = 0.1\cdot 2 = 0.2 and s=0.001⋅4=0.004s = 0.001\cdot 4 = 0.004. The corrected values are m^=0.2/0.1=2\hat m = 0.2/0.1 = 2 and s^=0.004/0.001=4\hat s = 0.004/0.001 = 4, the true values. The step is η⋅2/4=η\eta\cdot 2/\sqrt{4} = \eta.
  • steps 2 to 5: the corrected values stay 22 and 44, so every step is η\eta.

Without the correction the ratio is wrong. Both mm and ss are too small, but ss is much more so, because 1−β21-\beta_2 is only 0.0010.001, and ss sits under a square root. The uncorrected step m/sm/\sqrt{s} would be 3.16 η3.16\,\eta at step 1, 6.5 η6.5\,\eta at step 10, and it only returns to 1.03 η1.03\,\eta around step 3000. So the correction mainly protects the first steps from being far too long.

What size is an Adam step? For a steady gradient it is about η\eta whatever the size of the gradient. For a gradient that is pure noise with no steady sign it is smaller: m^\hat m averages the noise toward zero while s^\sqrt{\hat s} keeps the noise size, and a simulation of independent noise gives a root-mean-square ratio of 0.2290.229, matching (1−β1)/(1+β1)\sqrt{(1-\beta_1)/(1+\beta_1)}. So Adam moves fast where the gradient has a consistent sign and slowly where it is mostly noise. One parameter with gradient 33 and one with gradient −0.002-0.002 both take steps of size η\eta in the first step. For η=0.1\eta = 0.1, SGD would move them by 0.30.3 and 0.00020.0002.

Like momentum, Adam’s step does not point along −g-\mathbf{g}, so an individual step can raise the loss (P1.C6, P1.F5). Adam is also not a second-order method. It divides by a running size of gradients, not by curvature (P1.F5, P1.F6).

AdamW: decay the weights directly

Weight decay pulls every weight toward zero, so that large weights are discouraged (P3.A6, P4.17). For plain SGD there are two ways to write it, and they are the same update. Add λθ\lambda\boldsymbol{\theta} to the gradient (an L2 penalty λ2∥θ∥2\tfrac{\lambda}{2}\lVert\boldsymbol{\theta}\rVert^2), or shrink the weights by a factor each step:

θ←θ−η(g+λθ)=(1−ηλ) θ−η g.\begin{aligned} \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta(\mathbf{g} + \lambda\boldsymbol{\theta})\\ &= (1-\eta\lambda)\,\boldsymbol{\theta} - \eta\,\mathbf{g}. \end{aligned}

In Adam they are different. If you add λθ\lambda\boldsymbol{\theta} to the gradient, it goes into m\mathbf{m} and s\mathbf{s} and is divided by s^\sqrt{\hat{\mathbf{s}}} like any other gradient, so the strength of the decay depends on the size of that parameter’s gradients. AdamW (Loshchilov and Hutter, posted November 2017, published at ICLR 2019, as “Decoupled Weight Decay Regularization”) applies the decay outside the adaptive step:

θ←(1−ηλ) θ,θ←θ−η m^s^+ε\begin{aligned} \boldsymbol{\theta} &\leftarrow (1-\eta\lambda)\,\boldsymbol{\theta},\\ \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta\,\frac{\hat{\mathbf{m}}}{\sqrt{\hat{\mathbf{s}}} + \varepsilon} \end{aligned}

with m\mathbf{m} and s\mathbf{s} computed from the loss gradient alone. The two lines are one PyTorch step.

An example with numbers. Two parameters both sit at θ=2\theta = 2. Let λ=0.1\lambda = 0.1 and η=0.01\eta = 0.01, and let the loss gradient be steady: −0.1-0.1 for parameter A and −10-10 for parameter B (negative means the loss wants θ\theta to grow). Running Adam for many steps with these steady gradients and then taking one step gives the numbers below. (Treat the gradients as steady and θ\theta as still near 22 when we look at one step. This is a simplification to keep the arithmetic clear.)

  • Without decay: both parameters move by +0.01+0.01. Adam ignores the size of the gradient.
  • L2 inside Adam: the gradient Adam sees is −0.1+0.2=+0.1-0.1 + 0.2 = +0.1 for A and −10+0.2=−9.8-10 + 0.2 = -9.8 for B. A moves by −0.01-0.01: the penalty won and reversed the step. B moves by +0.01+0.01, exactly as if there were no penalty at all, because 0.20.2 is small next to 9.89.8.
  • AdamW: the decay is ηλθ=0.002\eta\lambda\theta = 0.002 for both. Both move by +0.01−0.002=+0.008+0.01 - 0.002 = +0.008.

So with L2 in Adam the same λ\lambda regularizes A strongly and B almost not at all, and which is which depends on the gradient history. With AdamW every weight is pulled the same fraction. Real gradients are noisy, so the effect is less clean. The paper reports that decoupling made Adam’s generalization better, and AdamW is the common choice when Adam is used with weight decay. In PyTorch, Adam(weight_decay=λ) adds λθ\lambda\boldsymbol{\theta} to the gradient (L2) and its default is 00, while AdamW decays directly and its default is 0.010.01.

What the state costs

Each rule keeps different numbers for every parameter:

  • SGD: none.
  • Momentum and Nesterov: one buffer, the size of the parameters.
  • AdaGrad and RMSProp: one buffer (the sum or average of squares).
  • Adam and AdamW: two buffers, m\mathbf{m} and s\mathbf{s}, plus a step counter.

For a model with 10910^9 parameters in fp32 (4 bytes each, P1.G1), the weights are 4 GB. Their gradients are another 4 GB. Momentum adds 4 GB and Adam adds 8 GB, so Adam training holds 4+4+8=164 + 4 + 8 = 16 GB before it stores any activations. Real training setups often keep extra copies, such as higher-precision weights when the model itself is in 16-bit, and P10.B4 counts the total. The point here is that the choice of optimizer is also a memory choice: Adam’s state costs twice the weights.

Which one should I use?

There is no optimizer that is best for every problem, and the gap between them depends a lot on how well each learning rate is tuned. These are common habits, not rules:

  • AdamW with a tuned learning rate and a schedule (P4.14) is a common first choice for transformers and large language models. The paper’s η=10−3\eta = 10^{-3} is a starting point, and good values for a particular model are often different.
  • SGD with momentum (often μ=0.9\mu = 0.9) is still common for some image models, and it needs less memory. People disagree about when it generalizes better than Adam, and the answer depends on the model and the tuning.
  • Why Adam is often easier to get working. Its step for each parameter is about η\eta whatever the size of that parameter’s gradient. In a network the gradients of different layers can differ in size by large factors, and one SGD rate has to suit all of them. Adam’s per-parameter scaling relieves that, which is a reason it is a popular default. It is not a guarantee of a better result.
  • Adam still needs help. A constant learning rate leaves it hovering (P4.14), and exploding gradients are handled separately (P4.16).
  • Tune the learning rate first. The “Try it” cell below shows that the best learning rate is different for each optimizer, and that at one shared rate they can look very different.

The recipe in one place

Intuition

An optimizer is a rule for turning noisy gradient arrows into steps. Momentum adds memory of the direction, so the steady part builds up and the zig-zag cancels. Adaptive rules add memory of the gradient’s size, so every parameter moves at a similar pace. Adam has both memories. AdamW additionally shrinks the weights by a fixed fraction each step, outside the adaptive rule, so that the shrinking does not depend on gradient size.

Math

With gradient gt\mathbf{g}_t at step tt (elementwise operations, state starting at 0\mathbf{0}):

  • SGD: θ←θ−ηg\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\mathbf{g}.
  • Momentum: b←μb+g\mathbf{b} \leftarrow \mu\mathbf{b} + \mathbf{g}; θ←θ−ηb\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\mathbf{b}.
  • Nesterov: the same b\mathbf{b}; θ←θ−η(g+μb)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta(\mathbf{g} + \mu\mathbf{b}).
  • AdaGrad: G←G+g2\mathbf{G} \leftarrow \mathbf{G} + \mathbf{g}^2; θ←θ−ηg/(G+ε)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\mathbf{g}/(\sqrt{\mathbf{G}} + \varepsilon), with ε=10−10\varepsilon = 10^{-10}.
  • RMSProp: s←ρs+(1−ρ)g2\mathbf{s} \leftarrow \rho\mathbf{s} + (1-\rho)\mathbf{g}^2; θ←θ−ηg/(s+ε)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\mathbf{g}/(\sqrt{\mathbf{s}} + \varepsilon).
  • Adam: m,s\mathbf{m}, \mathbf{s} as above, m^=m/(1−β1t)\hat{\mathbf{m}} = \mathbf{m}/(1-\beta_1^t), s^=s/(1−β2t)\hat{\mathbf{s}} = \mathbf{s}/(1-\beta_2^t); θ←θ−ηm^/(s^+ε)\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\hat{\mathbf{m}}/(\sqrt{\hat{\mathbf{s}}} + \varepsilon).
  • AdamW: first θ←(1−ηλ)θ\boldsymbol{\theta} \leftarrow (1-\eta\lambda)\boldsymbol{\theta}, then the Adam step with the loss gradient only.
  • Why bias correction: E[mt]=(1−β1t) E[g]\mathbb{E}[\mathbf{m}_t] = (1-\beta_1^t)\,\mathbb{E}[\mathbf{g}] for a steady gradient, so dividing by 1−β1t1-\beta_1^t removes the start-up shrinkage. The same holds for s\mathbf{s} with β2\beta_2.
  • Gradient noise only: for independent noise with standard deviation σ\sigma, Var(m)=1−β11+β1σ2\mathrm{Var}(m) = \tfrac{1-\beta_1}{1+\beta_1}\sigma^2 in the long run.

Code

The update rules in NumPy, for one parameter array p with gradient g (the optimizer class in the “Try it” cell is the same idea):

# Adam, one step (t = 1, 2, ...); m and s start as zeros
m = 0.9 * m + 0.1 * g
s = 0.999 * s + 0.001 * g * g
mh = m / (1 - 0.9 ** t)
sh = s / (1 - 0.999 ** t)
p -= lr * mh / (np.sqrt(sh) + 1e-8)
# AdamW: before the lines above, add  p *= 1 - lr * wd

In PyTorch, swapping the optimizer is one line. The program below creates each optimizer, takes one step on a made-up batch, and counts the extra numbers each one stores (run locally with PyTorch 2.9.1):

import torch
from torch import nn

torch.manual_seed(0)
model = nn.Sequential(nn.Linear(2, 8), nn.Tanh(), nn.Linear(8, 1))
n = sum(p.numel() for p in model.parameters())
print("parameters:", n)

x, y = torch.randn(32, 2), torch.rand(32, 1).round()
opts = {
    "SGD":          torch.optim.SGD(model.parameters(), lr=0.1),
    "SGD+momentum": torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9),
    "Nesterov":     torch.optim.SGD(model.parameters(), lr=0.1,
                                    momentum=0.9, nesterov=True),
    "RMSprop":      torch.optim.RMSprop(model.parameters(), lr=0.01),
    "Adam":         torch.optim.Adam(model.parameters(), lr=1e-3),
    "AdamW":        torch.optim.AdamW(model.parameters(), lr=1e-3,
                                      weight_decay=0.01),
}
for name, opt in opts.items():
    opt.zero_grad()
    loss = nn.functional.binary_cross_entropy_with_logits(model(x), y)
    loss.backward()
    opt.step()                       # the first step creates the state
    extra = sum(t.numel() for s in opt.state.values()
                for k, t in s.items() if k != "step")
    print(f"{name:13s} {extra:3d} extra floats")

first = next(iter(model.parameters()))
print(sorted(opts["Adam"].state[first]))
parameters: 33
SGD             0 extra floats
SGD+momentum   33 extra floats
Nesterov       33 extra floats
RMSprop        33 extra floats
Adam           66 extra floats
AdamW          66 extra floats
['exp_avg', 'exp_avg_sq', 'step']

With 33 parameters, momentum keeps 33 extra numbers and Adam keeps 66, the same ratio as the 10910^9 example. The names exp_avg and exp_avg_sq are m\mathbf{m} and s\mathbf{s}.

Try it: the same network, five optimizers

A small network (2 inputs, 8 tanh units, 1 output) is trained on 200 made-up points in an XOR pattern: four noisy blobs, where the two on one diagonal are class 0 and the two on the other are class 1. Backpropagation is written by hand, mini-batches have 32 points, and each optimizer runs 200 steps at each of five learning rates. The table shows the loss on all 200 points after the last step. The cell runs in a few seconds. You can change the rates, or add "nesterov" or "adagrad" to the code.

Try it: five optimizers, five learning rates

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the code gives this table (on the machine used for this lesson):

loss after 200 steps; columns:
          0.003 0.01  0.03  0.1   0.3  
sgd       0.691 0.681 0.668 0.581 0.334
momentum  0.669 0.598 0.360 0.257 0.243
rmsprop   0.608 0.302 0.258 0.274 0.288
adam      0.602 0.296 0.252 0.244 0.229
adamw     0.603 0.297 0.253 0.239 0.275
best rate on this grid:
  sgd       0.3
  momentum  0.3
  rmsprop   0.03
  adam      0.3
  adamw     0.1

What to notice, and what not to conclude:

  • At one shared rate the optimizers look very different. At 0.010.01, SGD is still at 0.6810.681 (a coin flip would give 0.6930.693), while the adaptive rules are near 0.300.30.
  • The best rate differs. RMSProp’s best on this grid is 0.030.03, and its loss gets worse at 0.30.3. SGD is still improving at the edge of the grid (0.3340.334 at rate 0.30.3), so this grid does not show how good it could get. The grid is the same for all five, which is not the same as fair tuning.
  • The overlap of the blobs sets a floor. The best losses are all close to 0.230.23 to 0.260.26, because points from different classes overlap. A single seed on a small made-up problem tells you how the rules behave, not which one is better in general.
  • AdamW and Adam are close here. With λ=0.01\lambda = 0.01 and 200 steps the decay is small, since each step only shrinks the weights by ηλ\eta\lambda, at most 0.0030.003 for η=0.3\eta = 0.3.

Check your understanding

  1. For which optimizer are L2 regularization in the gradient and decoupled weight decay the same update?

  2. A gradient is 1 at every step. How does the AdaGrad step change over time?

  3. Why does Adam divide m\mathbf{m} and s\mathbf{s} by 1−β1t1-\beta_1^t and 1−β2t1-\beta_2^t?

  4. A model has 10910^9 parameters in fp32. How much extra memory does the Adam state need, beyond the weights and gradients?

  5. Which statement about choosing an optimizer is best supported?

Exercises

  1. A parameter has a steady gradient of 44. With AdaGrad (ε\varepsilon ignored), what is the step size in units of η\eta at step 1, and at step 16?
    Show answerThe sum of squares is 16t16t, so the step is η⋅4/16t=η/t\eta\cdot 4/\sqrt{16t} = \eta/\sqrt{t}. At step 1 it is η\eta and at step 16 it is η/4=0.25η\eta/4 = 0.25\eta. The size of the gradient cancels.
  2. At the first Adam step, a parameter has gradient g=5g = 5. Find mm, ss, m^\hat m, s^\hat s and the step (ignore ε\varepsilon).
    Show answerm=0.1⋅5=0.5m = 0.1\cdot 5 = 0.5 and s=0.001⋅25=0.025s = 0.001\cdot 25 = 0.025. Then m^=0.5/0.1=5\hat m = 0.5/0.1 = 5 and s^=0.025/0.001=25\hat s = 0.025/0.001 = 25. The step is η⋅5/25=η\eta\cdot 5/\sqrt{25} = \eta.
  3. With momentum μ=0.9\mu = 0.9 and a steady gradient of 22, the buffer approaches what value, and what step does η=0.01\eta = 0.01 give?
    Show answerb→2/(1−0.9)=20\mathbf{b} \to 2/(1-0.9) = 20, so the step is 0.01⋅20=0.20.01\cdot 20 = 0.2 per step, ten times the plain SGD step of 0.020.02.
  4. One weight has θ=3\theta = 3, η=0.1\eta = 0.1 and λ=0.5\lambda = 0.5. How much does the AdamW decay line move it? What would the L2 term add to the gradient?
    Show answerThe decay multiplies θ\theta by 1−ηλ=0.951-\eta\lambda = 0.95, so θ\theta becomes 2.852.85, a move of −0.15-0.15. The L2 term would add λθ=1.5\lambda\theta = 1.5 to the gradient before Adam rescales it.
  5. Using the memory rule of this lesson, how much memory does the optimizer state need for a model with 3×1083\times 10^8 fp32 parameters, with SGD plus momentum and with Adam?
    Show answerOne fp32 buffer is 3×108×4=1.23\times10^8\times 4 = 1.2 GB, so momentum needs 1.21.2 GB and Adam needs 2.42.4 GB.
  6. In the race on the ravine, Nesterov at η=0.0095\eta = 0.0095 leaves the map while momentum at the same rate settles. What does this say about copying a learning rate from one optimizer to another?
    Show answerA rate that is stable for one rule can be too big for another, even a close relative. The stable range depends on the rule (for Nesterov in this form it is narrower than for the heavy ball, as P1.F5 found), so each optimizer’s rate has to be tuned or checked separately.

Next: P4.14 changes the learning rate during training (warmup, decay, cosine), P4.16 handles exploding gradients with clipping, and P4.17 returns to weight decay with dropout and early stopping.

Key takeaways

  • An optimizer takes the mini-batch gradient g\mathbf{g} and returns a step. The backward pass is the same for all of them. Only the step rule and the state it keeps change.
  • Momentum keeps one velocity per parameter. AdaGrad, RMSProp and Adam divide each parameter's step by a running size of its own gradients. Adam does both and corrects the start-up bias of its two averages.
  • AdaGrad's sum of squares only grows, so its steps shrink for ever. RMSProp and Adam use a moving average, so they can recover.
  • For plain SGD, L2 in the gradient and weight decay are the same update. For Adam the L2 term is rescaled like any other gradient, so AdamW shrinks the weights directly instead.
  • Adam keeps two extra numbers per parameter, momentum one. For a model with 10910^9 fp32 parameters that is 8 GB and 4 GB on top of 4 GB of weights.
  • No optimizer wins everywhere. AdamW with a tuned learning rate is a common first choice for transformers, and SGD with momentum is still common for some vision models. Each needs its own learning rate.
Found a mistake? Tell us