Level 3 In-Depth AI · Deep Learning
Optimizers: SGD, Momentum and Adam
The optimizer decides how to turn gradients into weight updates. Plain gradient descent zig-zags in narrow valleys; momentum builds up speed, and Adam gives every parameter its own step size. Compared here on the same problem with real numbers, plus AdamW, weight decay and how to choose.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 16 concepts →
- Quiz
- 5 questions ↓
Read first
BackpropagationThe full path from zero — 16 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- Optimizers: SGD, Momentum and Adam
Read them roughly in this order. See it on the concept map →
Why it matters
Backpropagation tells you the gradient: which way is uphill for every weight. It doesn't tell you how far to step, or whether to trust this one noisy gradient or blend it with earlier ones. That's the job of the optimizer, the rule that turns gradients into weight updates.
Plain Gradient Descent is the simplest optimizer, and it works. But on the long, narrow valleys that real loss landscapes are full of, it wastes most of its effort bouncing from wall to wall. Better optimizers can train the same network in a fraction of the steps, which for large models means weeks of GPU time and a lot of money. Most modern models, including most large language models as of late 2026, are trained with AdamW, though a few frontier runs (Moonshot's Kimi models, for example) have switched to the newer Muon optimizer. Image models are often still trained with SGD with momentum. This chapter explains both, shows them racing on the same problem, and ends with practical advice on choosing and setting them.
The intuition
Picture a ball rolling down a long, narrow ravine that slopes gently along its length but has steep walls.
Plain gradient descent is a hiker who, at every step, looks only at the slope under their feet and walks straight downhill. In a ravine, "straight downhill" points mostly across the ravine, towards the nearest wall, not along it towards the exit. So the hiker crosses to the far wall, turns around, crosses back, and inches forward with each crossing.
Momentum is a heavy ball. It remembers which way it was already moving. The side-to-side pushes alternate and mostly cancel out, while the gentle push along the ravine is the same every step and keeps adding up. The ball picks up speed in the direction that matters.
Adam is a hiker who measures, for each direction separately, how steep things usually are, and takes steps of similar size in every direction: short, careful steps across the steep walls and confident strides along the gentle floor.
Key idea SGD steps along the current gradient. Momentum steps along a running average of gradients, so consistent directions speed up and oscillations cancel. Adam also divides each parameter's step by the typical size of its gradient, giving every parameter its own learning rate. AdamW adds weight decay done correctly, and is the default for most deep learning today.
How it works
The test problem
To compare optimizers fairly, we use one function with a known answer:
Its minimum is at , where . It is a bowl, but squashed: 100 times more curved in the direction than in the direction. The gradient is . Such a mismatch between directions is called ill-conditioning, and real networks are full of it, typically far worse than 100 to 1. Every optimizer starts at , where .
SGD: the baseline
Plain stochastic gradient descent updates each parameter by
where is the gradient and the learning rate. In the steep direction, each step multiplies by . If is more than , that factor is below : overshoots further each step and the loss explodes. (With the loss reaches about after 100 steps.) So the steep direction caps the learning rate.
At the largest safe rate, , the first steps are:
- Step 1: gradient , so we move by , landing at . We overshot in from to .
- Step 2: gradient , landing at .
- Step 3: .
The coordinate flips sign every step, shrinking by only 10% each time. Meanwhile moves by just 1.9% of its distance per step, because the learning rate that's safe for is tiny for . After 100 steps the loss is still 0.17.
Momentum: a running sum of gradients
Momentum keeps a velocity , a decaying sum of past gradients, and steps along it:
The momentum coefficient ("beta") is usually 0.9. Each step, the old velocity keeps 90% of its value and the new gradient is added. If the gradient points the same way every step, the velocity grows towards : an effective learning rate 10 times larger. If the gradient keeps flipping sign, consecutive contributions cancel and the velocity stays small.
With and , from :
- Step 1: . Move by to .
- Step 2: gradient . . Move by to .
Look at . The first step moved it by 0.04, the second by 0.0756, almost double, because the velocity in is accumulating. That's the "heavy ball" building speed along the valley floor. The coordinate still swings, but the swings partly cancel in . After 100 steps the loss is 0.00015, over 1,000 times lower than SGD's.
A small variant, Nesterov momentum, computes the gradient at the point the velocity is about to carry you to, rather than where you are. It reacts a little faster when the ball should slow down. In PyTorch it's SGD(..., momentum=0.9, nesterov=True).
RMSProp: a step size per parameter
Momentum fixes the direction problem but not the scale problem: one learning rate still has to suit both the steep and the flat . RMSProp gives each parameter its own effective learning rate. It keeps a running average of each parameter's squared gradient, , and divides the step by its square root:
Here ("rho") is the averaging factor, typically 0.9 or 0.99, and ("epsilon") is a tiny number such as that prevents division by zero. The square root of the average squared gradient, the root mean square, measures how big that parameter's gradients usually are. Dividing by it means parameters with big gradients take smaller steps and parameters with small gradients take bigger ones. Optimizers that do this are called adaptive learning rate methods.
Adam: momentum plus RMSProp
Adam ("adaptive moment estimation") combines both ideas. For each parameter it keeps two running averages: , the average gradient (like momentum), and , the average squared gradient (like RMSProp):
The defaults are and . Both averages start at zero, so for the first few steps they are biased towards zero. Adam corrects for this with bias correction, dividing by where is the step number:
Work the first step by hand with . The gradient is .
- , and .
- , and .
- , so .
- Step: , landing at .
Both coordinates moved by exactly 0.3, even though one gradient was 25 times bigger than the other. On the first step Adam ignores the size of the gradient and keeps only its sign. Later steps blend in history, but the principle holds: Adam's step size is set by , not by the gradient's scale. That makes it forgiving. Badly scaled layers, tiny gradients deep in the network and features of different sizes all get sensible steps. After 100 steps on our valley, Adam's loss is 0.00015, level with momentum.
The race in numbers:
| Optimizer | Settings | Loss at step 10 | Step 50 | Step 100 |
|---|---|---|---|---|
| SGD | 11.53 | 1.18 | 0.17 | |
| Momentum | , | 4.62 | 0.15 | 0.00015 |
| Adam | 6.96 | 0.12 | 0.00015 |
Don't over-read a toy problem. On a perfectly round bowl, plain SGD is just as good as anything else. The advantage of momentum and Adam grows with ill-conditioning, which is exactly the situation in deep networks.
Weight decay and AdamW
Weight decay shrinks every weight a little towards zero at each step. It is a form of Regularization: L1 and L2: it discourages large weights, which tends to make models smoother and less prone to Overfitting and the Bias–Variance Tradeoff. With plain SGD, weight decay is identical to adding an L2 penalty to the loss, since the penalty's gradient is :
With Adam, the two are not the same. If you add to the gradient, it then gets divided by along with everything else. Weights with large gradients get very little decay, and weights with small gradients get a lot, which isn't what you want. AdamW fixes this by applying the decay directly to the weights, separately from the adaptive step:
In PyTorch, torch.optim.Adam(..., weight_decay=0.01) does the old, coupled version. torch.optim.AdamW(..., weight_decay=0.01) does the decoupled one. Use AdamW.
The price of state
Adam remembers two numbers, and , for every parameter. This optimizer state costs memory. For a 7-billion-parameter model stored in 32-bit floats, that is bytes GB on top of the weights and gradients. SGD with momentum needs one number per parameter, and plain SGD none. Memory-saving variants, such as 8-bit Adam or sharding the state across GPUs, exist mainly because of this. See Distributed Training.
How to choose
| Situation | Good default |
|---|---|
| Almost anything, especially Transformers and language models | AdamW, , , (0.95 for large language models), weight decay 0.01–0.1 |
| Image classification with CNNs, when you can tune carefully | SGD with momentum 0.9, with a schedule, weight decay to |
| Fine-tuning a pretrained model | AdamW with a small , around to |
| Memory is the bottleneck | SGD with momentum, or a memory-saving Adam variant |
These are starting points, not laws. The learning rate always matters more than the choice of optimizer, and it is usually changed during training: see Learning Rate Schedules. GPT-3, for example, was trained with Adam using , gradient clipping at 1.0 and weight decay of 0.1.
In code
The race above, using PyTorch's built-in optimizers. Each optimizer gets the same starting point and runs for 100 steps:
import torch
def loss_fn(p): # a long, narrow valley: 100x steeper across than along
return 0.5 * p[0]**2 + 50 * p[1]**2
for name, make_opt in [("SGD", lambda ps: torch.optim.SGD(ps, lr=0.019)),
("Momentum", lambda ps: torch.optim.SGD(ps, lr=0.01, momentum=0.9)),
("Adam", lambda ps: torch.optim.Adam(ps, lr=0.3))]:
p = torch.tensor([-4.0, 1.0], requires_grad=True)
opt = make_opt([p])
history = []
for step in range(100):
loss = loss_fn(p)
history.append(loss.item())
opt.zero_grad(); loss.backward(); opt.step()
history.append(loss_fn(p).item())
print(f"{name:8s} loss at step 0: {history[0]:.1f} 10: {history[10]:.3f} "
f"50: {history[50]:.4f} 100: {history[100]:.6f}")
# SGD loss at step 0: 58.0 10: 11.530 50: 1.1762 100: 0.172541
# Momentum loss at step 0: 58.0 10: 4.623 50: 0.1506 100: 0.000147
# Adam loss at step 0: 58.0 10: 6.960 50: 0.1216 100: 0.000151
The update rules are short enough to write yourself. This NumPy version of Adam reproduces PyTorch's numbers:
import numpy as np
def grad(p): # gradient of 0.5 x^2 + 50 y^2
return np.array([p[0], 100 * p[1]])
p = np.array([-4.0, 1.0])
m, v = np.zeros(2), np.zeros(2)
lr, b1, b2, eps = 0.3, 0.9, 0.999, 1e-8
for t in range(1, 4):
g = grad(p)
m = b1 * m + (1 - b1) * g # running average of gradients
v = b2 * v + (1 - b2) * g**2 # running average of squared gradients
m_hat, v_hat = m / (1 - b1**t), v / (1 - b2**t) # bias correction
p = p - lr * m_hat / (np.sqrt(v_hat) + eps)
print(t, p.round(4))
# 1 [-3.7 0.7]
# 2 [-3.4008 0.4073]
# 3 [-3.1032 0.132 ]
In a real training script you typically write opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01) and leave the rest at its defaults.
Common pitfalls
- Comparing optimizers at the same learning rate. Adam's and SGD's mean different things. Adam's is roughly the step size per parameter; SGD's multiplies the raw gradient. Typical good values differ by 100 to 1,000 times. Tune each separately.
- Using
Adamwithweight_decayand thinking it's AdamW. It isn't. Switch toAdamW. - Decaying everything. Weight decay on biases and normalisation-layer scales usually hurts a little. Many training scripts put those parameters in a separate group with
weight_decay=0. - Forgetting
zero_grad(). Every optimizer assumes.gradholds this step's gradient only. - Resuming without the optimizer state. When you save a checkpoint, save
opt.state_dict()as well as the model. Restarting Adam with empty and causes a jolt in training. - Making too small in low precision. In 16-bit training, can underflow to zero. Libraries handle this, but custom code should use a larger (such as ) or compute the optimizer in 32-bit. See Mixed Precision Training.
Watch out Adam's forgiveness hides problems. Because it rescales every gradient, a network with badly broken gradients can still appear to train, slowly. If Adam trains but SGD with a reasonable learning rate diverges or stalls completely, check your gradients and initialisation. See Vanishing and Exploding Gradients.
Where it leads
- Learning Rate Schedules: warmup and decay, which matter as much as the optimizer.
- Regularization: L1 and L2 and Dropout and Regularizing Neural Networks: weight decay is one of several ways to fight overfitting.
- Training Neural Networks in Practice: a full practical recipe.
- Distributed Training and Mixed Precision Training: how optimizer state is split and stored at scale.
- Newer optimizers keep appearing. Methods such as Lion, Shampoo and Muon have been used or tested in large training runs, and Muon (or variants such as MuonClip) has trained some frontier models, but as of late 2026 AdamW remains the common default.
A bit of history
Boris Polyak introduced the heavy-ball (momentum) method in 1964, and Yurii Nesterov his accelerated variant in 1983, both for general optimisation. Rumelhart, Hinton and Williams used momentum in their 1986 backpropagation work. In 2011, John Duchi, Elad Hazan and Yoram Singer published AdaGrad, which divides each parameter's step by the square root of the sum of all its past squared gradients. That sum only grows, so AdaGrad's steps eventually shrink to almost nothing. Geoffrey Hinton proposed RMSProp, which uses a decaying average instead, in a 2012 Coursera lecture; it was never formally published.
Diederik Kingma and Jimmy Ba published Adam in 2014, and it quickly became the default. In 2017, Ashia Wilson and colleagues showed that adaptive methods sometimes generalise worse than well-tuned SGD on image tasks, and Ilya Loshchilov and Frank Hutter showed that weight decay had been implemented wrongly in Adam, proposing AdamW. AdamW became the standard for Transformers and, as of late 2026, remains the most common choice.
Try it
- In the PyTorch race, change the valley to
0.5 * p[0]**2 + 0.5 * p[1]**2(a round bowl) and give SGDlr=1.0. How many steps does it need? Why is a round bowl so easy?- Set momentum's
momentum=0.99instead of 0.9. Does it reach a lower loss after 100 steps, or does it overshoot more?- Change Adam's
lrto 0.03 and 3.0. Which fails, and how?Hint for 1: with on , the step is . One step lands exactly on the minimum.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Why Momentum Really Works
An interactive article with sliders that show exactly how momentum speeds up gradient descent on ill-conditioned problems, and when it oscillates.
An overview of gradient descent optimization algorithms
A clear, widely read survey of SGD, momentum, Nesterov, AdaGrad, RMSProp, Adam and related methods, with the update rules side by side.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Adam: A Method for Stochastic Optimization
The Adam optimiser, still the default for training most neural networks.
Decoupled Weight Decay Regularization
Shows that L2 regularisation and weight decay differ for Adam, and proposes AdamW, now the default optimizer for Transformers.
torch.optim
Reference for PyTorch's optimizers and learning-rate schedulers, including the exact update rule each one implements.
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/optimizers.md