◆ AI All-in-One

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
↗ Plan a path here

Read first

Backpropagation

This leads to

Learning Rate SchedulesTraining Neural Networks in Practice
The full path from zero — 16 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Backpropagation
  17. 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.

SGD (η = 0.019, the largest stable rate) zig-zags across, crawls along: loss 1.18 after 50 steps Momentum (η = 0.01, β = 0.9) builds up speed along the valley: loss 0.15 after 50 Adam (η = 0.3) equal-sized steps in each direction: loss 0.12 after 50 Loss 0.5·x² + 50·y² (grey contours; vertical axis stretched for visibility). Start ○ at (−4, 1), minimum × at (0, 0). First 50 steps.
Fig. 1 Three optimizers on the same narrow valley, first 50 steps. SGD bounces between the walls and creeps along the floor. Momentum swings but builds up speed along the valley. Adam heads diagonally towards the minimum, because it rescales each direction separately.

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:

L(x,y)=0.5 x2+50 y2L(x, y) = 0.5\,x^2 + 50\,y^2

Its minimum is at (0,0)(0, 0), where L=0L = 0. It is a bowl, but squashed: 100 times more curved in the yy direction than in the xx direction. The gradient is (x, 100y)(x,\ 100y). 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 (−4,1)(-4, 1), where L=0.5×16+50×1=58L = 0.5 \times 16 + 50 \times 1 = 58.

SGD: the baseline

Plain stochastic gradient descent updates each parameter θ\theta by

θ←θ−η g\theta \leftarrow \theta - \eta\, g

where gg is the gradient and η\eta the learning rate. In the steep yy direction, each step multiplies yy by (1−100η)(1 - 100\eta). If η\eta is more than 0.020.02, that factor is below −1-1: yy overshoots further each step and the loss explodes. (With η=0.021\eta = 0.021 the loss reaches about 101010^{10} after 100 steps.) So the steep direction caps the learning rate.

At the largest safe rate, η=0.019\eta = 0.019, the first steps are:

  • Step 1: gradient (−4,100)(-4, 100), so we move by (−0.019×−4, −0.019×100)=(0.076,−1.9)(-0.019 \times -4,\ -0.019 \times 100) = (0.076, -1.9), landing at (−3.924,−0.9)(-3.924, -0.9). We overshot in yy from +1+1 to −0.9-0.9.
  • Step 2: gradient (−3.924,−90)(-3.924, -90), landing at (−3.849,0.81)(-3.849, 0.81).
  • Step 3: (−3.776,−0.729)(-3.776, -0.729).

The yy coordinate flips sign every step, shrinking by only 10% each time. Meanwhile xx moves by just 1.9% of its distance per step, because the learning rate that's safe for yy is tiny for xx. After 100 steps the loss is still 0.17.

Momentum: a running sum of gradients

Momentum keeps a velocity v\mathbf{v}, a decaying sum of past gradients, and steps along it:

v←β v+g,θ←θ−η v\mathbf{v} \leftarrow \beta\,\mathbf{v} + \mathbf{g}, \qquad \theta \leftarrow \theta - \eta\,\mathbf{v}

The momentum coefficient β\beta ("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 g/(1−β)=10gg/(1 - \beta) = 10g: an effective learning rate 10 times larger. If the gradient keeps flipping sign, consecutive contributions cancel and the velocity stays small.

With η=0.01\eta = 0.01 and β=0.9\beta = 0.9, from (−4,1)(-4, 1):

  • Step 1: v=(−4,100)\mathbf{v} = (-4, 100). Move by −0.01 v=(0.04,−1.0)-0.01\,\mathbf{v} = (0.04, -1.0) to (−3.96,0.0)(-3.96, 0.0).
  • Step 2: gradient (−3.96,0)(-3.96, 0). v=0.9×(−4,100)+(−3.96,0)=(−7.56,90)\mathbf{v} = 0.9 \times (-4, 100) + (-3.96, 0) = (-7.56, 90). Move by (0.0756,−0.9)(0.0756, -0.9) to (−3.884,−0.9)(-3.884, -0.9).

Look at xx. The first step moved it by 0.04, the second by 0.0756, almost double, because the velocity in xx is accumulating. That's the "heavy ball" building speed along the valley floor. The yy coordinate still swings, but the swings partly cancel in v\mathbf{v}. 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 yy and the flat xx. RMSProp gives each parameter its own effective learning rate. It keeps a running average of each parameter's squared gradient, ss, and divides the step by its square root:

s←ρ s+(1−ρ) g2,θ←θ−η gs+ϵs \leftarrow \rho\, s + (1 - \rho)\, g^2, \qquad \theta \leftarrow \theta - \eta\, \frac{g}{\sqrt{s} + \epsilon}

Here ρ\rho ("rho") is the averaging factor, typically 0.9 or 0.99, and ϵ\epsilon ("epsilon") is a tiny number such as 10−810^{-8} 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: mm, the average gradient (like momentum), and vv, the average squared gradient (like RMSProp):

m←β1m+(1−β1) g,v←β2v+(1−β2) g2m \leftarrow \beta_1 m + (1 - \beta_1)\, g, \qquad v \leftarrow \beta_2 v + (1 - \beta_2)\, g^2

The defaults are β1=0.9\beta_1 = 0.9 and β2=0.999\beta_2 = 0.999. 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 (1−βt)(1 - \beta^t) where tt is the step number:

m^=m1−β1t,v^=v1−β2t,θ←θ−η m^v^+ϵ\hat{m} = \frac{m}{1 - \beta_1^t}, \qquad \hat{v} = \frac{v}{1 - \beta_2^t}, \qquad \theta \leftarrow \theta - \eta\, \frac{\hat{m}}{\sqrt{\hat{v}} + \epsilon}

Work the first step by hand with η=0.3\eta = 0.3. The gradient is g=(−4,100)g = (-4, 100).

  • m=0.1×(−4,100)=(−0.4,10)m = 0.1 \times (-4, 100) = (-0.4, 10), and m^=m/(1−0.9)=(−4,100)\hat{m} = m / (1 - 0.9) = (-4, 100).
  • v=0.001×(16,10000)=(0.016,10)v = 0.001 \times (16, 10000) = (0.016, 10), and v^=v/(1−0.999)=(16,10000)\hat{v} = v / (1 - 0.999) = (16, 10000).
  • v^=(4,100)\sqrt{\hat{v}} = (4, 100), so m^/v^=(−1,1)\hat{m}/\sqrt{\hat{v}} = (-1, 1).
  • Step: −0.3×(−1,1)=(0.3,−0.3)-0.3 \times (-1, 1) = (0.3, -0.3), landing at (−3.7,0.7)(-3.7, 0.7).

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 η\eta, 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 η=0.019\eta = 0.019 11.53 1.18 0.17
Momentum η=0.01\eta = 0.01, β=0.9\beta = 0.9 4.62 0.15 0.00015
Adam η=0.3\eta = 0.3 6.96 0.12 0.00015
0.0001 0.001 0.01 0.1 1 10 100 0 25 50 75 100 step loss (log scale) SGD: 0.1725 Momentum: 0.000147 Adam: 0.000151
Fig. 2 Loss per step on a log scale. SGD's loss falls steadily but slowly. Momentum and Adam fall more than a thousand times further in 100 steps, with bumps where they overshoot and swing back.

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 λ2∥θ∥2\frac{\lambda}{2}\lVert\theta\rVert^2 to the loss, since the penalty's gradient is λθ\lambda\theta:

θ←θ−η (g+λθ)\theta \leftarrow \theta - \eta\,(g + \lambda\theta)

With Adam, the two are not the same. If you add λθ\lambda\theta to the gradient, it then gets divided by v^\sqrt{\hat{v}} 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:

θ←θ−η(m^v^+ϵ+λθ)\theta \leftarrow \theta - \eta \left( \frac{\hat{m}}{\sqrt{\hat{v}} + \epsilon} + \lambda\theta \right)

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, mm and vv, for every parameter. This optimizer state costs memory. For a 7-billion-parameter model stored in 32-bit floats, that is 7×109×2×47 \times 10^9 \times 2 \times 4 bytes =56= 56 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, η≈3×10−4\eta \approx 3 \times 10^{-4}, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 (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, η≈0.1\eta \approx 0.1 with a schedule, weight decay 10−410^{-4} to 5×10−45 \times 10^{-4}
Fine-tuning a pretrained model AdamW with a small η\eta, around 10−510^{-5} to 5×10−55 \times 10^{-5}
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 β2=0.95\beta_2 = 0.95, 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 η\eta and SGD's η\eta 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 Adam with weight_decay and thinking it's AdamW. It isn't. Switch to AdamW.
  • 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 .grad holds 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 mm and vv causes a jolt in training.
  • Making ϵ\epsilon too small in low precision. In 16-bit training, ϵ=10−8\epsilon = 10^{-8} can underflow to zero. Libraries handle this, but custom code should use a larger ϵ\epsilon (such as 10−610^{-6}) 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

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

  1. In the PyTorch race, change the valley to 0.5 * p[0]**2 + 0.5 * p[1]**2 (a round bowl) and give SGD lr=1.0. How many steps does it need? Why is a round bowl so easy?
  2. Set momentum's momentum=0.99 instead of 0.9. Does it reach a lower loss after 100 steps, or does it overshoot more?
  3. Change Adam's lr to 0.03 and 3.0. Which fails, and how?

Hint for 1: with η=1\eta = 1 on 0.5x20.5x^2, the step is x−1⋅x=0x - 1 \cdot x = 0. One step lands exactly on the minimum.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. On the valley L = 0.5x² + 50y², why can plain SGD not simply use a large learning rate to move faster along x?

  2. With momentum β = 0.9, the gradient points the same way at every step. What happens to the effective step size?

  3. On Adam's very first step, parameter A has gradient −4 and parameter B has gradient 100. With η = 0.3, how far does each move?

  4. A colleague uses torch.optim.Adam(model.parameters(), weight_decay=0.01) and calls it AdamW. What is wrong?

  5. You resume training from a checkpoint that saved only the model weights. Training with Adam jolts badly for a while. Why?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Interactive

Why Momentum Really Works

Gabriel Goh (Distill) · 2017 · Intermediate · Free

An interactive article with sliders that show exactly how momentum speeds up gradient descent on ill-conditioned problems, and when it oscillates.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Paper

Decoupled Weight Decay Regularization

Loshchilov & Hutter · 2017 · Advanced · Free

Shows that L2 regularisation and weight decay differ for Adam, and proposes AdamW, now the default optimizer for Transformers.

Docs

torch.optim

PyTorch · Intermediate · Free

Reference for PyTorch's optimizers and learning-rate schedulers, including the exact update rule each one implements.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/optimizers.md