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 . 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 computed on a batch of examples. P1.F4 showed that this gradient is the true gradient plus noise. An optimizer is the rule for the update:
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 called the momentum coefficient and RMSProp’s averaging constant called . 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.
Things to try, all with the widget’s default settings (“within 0.05” is the readout’s last column):
- Ravine (the bowl of P1.F5, loss ). Plain SGD with is still at loss after 120 steps. Momentum with the same is within of the bottom from step 73, and the adaptive rules are there between step 12 and step 48. RMSProp gets within at step 39 and then ends at : with a constant it hovers, as P1.F5 showed.
- Nesterov on the ravine. Its default is . Select Nesterov under “Learning rate of” and raise it to , 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 is tiny. After 10 steps is for SGD and for Adam: dividing by the size of the gradient makes the small gradient count.
- Plateau. AdaGrad gets within 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 and AdamW ends at , because AdamW’s decay pulls the weights toward while the lowest point is at . Set the AdamW decay to 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 and the other six end between and . Noise makes every trail hover, and a smaller makes the hovering smaller, as in P1.F4.
SGD
The plain rule from P1.F3 and P1.F4, with the mini-batch gradient:
It keeps no state. Its one setting is the learning rate , and the best depends on the curvature of the loss, which is not known in advance. In a ravine it has to use a small 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 , the same as P1.F5’s velocity with :
The buffer starts as 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 , so steps along a steady slope are about times longer, and a gradient that flips sign cancels. With 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 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:
This looks different from P1.F5’s look-ahead form, where the gradient is computed at . It is the same method written for a different variable. The parameter that PyTorch stores is P1.F5’s look-ahead point , so the gradient PyTorch computes at the stored parameter is already the look-ahead gradient. Running both on the bowl with and and comparing PyTorch’s parameter with that look-ahead point gives the same numbers, to 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:
PyTorch uses 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. only grows, so the step only shrinks. Take a gradient that is at every step. After steps , so the step is :
- step 1: ,
- step 4: ,
- step 100: ,
- step 10,000: .
Even if the gradients later become small and the parameter should move again, 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:
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 as P1.F5 did and . PyTorch’s own default for the averaging constant, called alpha, is , and its default learning rate is .
The difference from AdaGrad shows when the gradients change size. Let a gradient be for 100 steps and then drop to . Measured as a fraction of : just before the drop, at step 100, AdaGrad’s step is (it has been shrinking) and RMSProp’s step is (its average of squares has settled at ). Right after the drop, AdaGrad’s step falls to and stays there, because still holds the 100 big gradients. RMSProp’s step is right after the drop and rises to 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 of the gradient (momentum) and a moving average of its square (RMSProp), and divides one by the root of the other. For step number :
The defaults are , , and , the same in the paper and in PyTorch. Here means the average of squares remembers about the last steps, and means the gradient average remembers about 10.
The correction. Both averages start at , so in the first steps they are too small. Take a gradient at every step:
- step 1: and . The corrected values are and , the true values. The step is .
- steps 2 to 5: the corrected values stay and , so every step is .
Without the correction the ratio is wrong. Both and are too small, but is much more so, because is only , and sits under a square root. The uncorrected step would be at step 1, at step 10, and it only returns to 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 whatever the size of the gradient. For a gradient that is pure noise with no steady sign it is smaller: averages the noise toward zero while keeps the noise size, and a simulation of independent noise gives a root-mean-square ratio of , matching . So Adam moves fast where the gradient has a consistent sign and slowly where it is mostly noise. One parameter with gradient and one with gradient both take steps of size in the first step. For , SGD would move them by and .
Like momentum, Adam’s step does not point along , 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 to the gradient (an L2 penalty ), or shrink the weights by a factor each step:
In Adam they are different. If you add to the gradient, it goes into and and is divided by 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:
with and computed from the loss gradient alone. The two lines are one PyTorch step.
An example with numbers. Two parameters both sit at . Let and , and let the loss gradient be steady: for parameter A and for parameter B (negative means the loss wants 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 as still near when we look at one step. This is a simplification to keep the arithmetic clear.)
- Without decay: both parameters move by . Adam ignores the size of the gradient.
- L2 inside Adam: the gradient Adam sees is for A and for B. A moves by : the penalty won and reversed the step. B moves by , exactly as if there were no penalty at all, because is small next to .
- AdamW: the decay is for both. Both move by .
So with L2 in Adam the same 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 to the gradient (L2) and its default is , while AdamW decays directly and its default is .
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, and , plus a step counter.
For a model with 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 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 is a starting point, and good values for a particular model are often different.
- SGD with momentum (often ) 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 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 at step (elementwise operations, state starting at ):
- SGD: .
- Momentum: ; .
- Nesterov: the same ; .
- AdaGrad: ; , with .
- RMSProp: ; .
- Adam: as above, , ; .
- AdamW: first , then the Adam step with the loss gradient only.
- Why bias correction: for a steady gradient, so dividing by removes the start-up shrinkage. The same holds for with .
- Gradient noise only: for independent noise with standard deviation , 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 * wdIn 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 example. The names exp_avg and exp_avg_sq are and .
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.
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 , SGD is still at (a coin flip would give ), while the adaptive rules are near .
- The best rate differs. RMSProp’s best on this grid is , and its loss gets worse at . SGD is still improving at the edge of the grid ( at rate ), 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 to , 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 and 200 steps the decay is small, since each step only shrinks the weights by , at most for .
Check your understanding
For which optimizer are L2 regularization in the gradient and decoupled weight decay the same update?
For plain SGD, equals shrinking by and then stepping. In Adam, RMSProp and AdaGrad the added is divided by a running size of the gradients, so the two versions differ.
A gradient is 1 at every step. How does the AdaGrad step change over time?
After steps the sum is , so the step is : at step 100. The step stays constant at for Adam with a steady gradient, and the forgetting belongs to RMSProp and Adam, whose averages drop old values.
Why does Adam divide and by and ?
With a steady gradient the corrected values equal the true ones from step 1, so the step is . Without it the step is at step 1. The correction does not decay the learning rate, shrink the weights (that is weight decay) or remove the need for , which guards against division by zero.
A model has parameters in fp32. How much extra memory does the Adam state need, beyond the weights and gradients?
Adam keeps two buffers, and , each the size of the weights: GB GB. A single 4 GB buffer is momentum or RMSProp, and 16 GB is the total of weights, gradients and Adam state, not the extra for the state.
Which statement about choosing an optimizer is best supported?
In the table of this lesson the best rate differs from optimizer to optimizer, and at a shared rate of SGD barely trained. No optimizer wins everywhere, AdaGrad's shrinking step can stall long runs, and Nesterov with the same rate can even diverge where plain momentum settles (the ravine race).
Exercises
- A parameter has a steady gradient of . With AdaGrad ( ignored), what is the step size in units of at step 1, and at step 16?
Show answer
The sum of squares is , so the step is . At step 1 it is and at step 16 it is . The size of the gradient cancels. - At the first Adam step, a parameter has gradient . Find , , , and the step (ignore ).
Show answer
and . Then and . The step is . - With momentum and a steady gradient of , the buffer approaches what value, and what step does give?
Show answer
, so the step is per step, ten times the plain SGD step of . - One weight has , and . How much does the AdamW decay line move it? What would the L2 term add to the gradient?
Show answer
The decay multiplies by , so becomes , a move of . The L2 term would add to the gradient before Adam rescales it. - Using the memory rule of this lesson, how much memory does the optimizer state need for a model with fp32 parameters, with SGD plus momentum and with Adam?
Show answer
One fp32 buffer is GB, so momentum needs GB and Adam needs GB. - In the race on the ravine, Nesterov at 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 answer
A 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.