AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⌬Neural Networks
  1. Neurons and Activation Functions
  2. Multilayer Perceptrons and Backpropagation
  3. Training Hyperparameters: Epochs, Learning Rate, Batch Size and More
  4. Optimizers: SGD, Momentum, RMSProp, Adam/AdamW and LR Schedules
  5. Regularization, Normalization and Initialization
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Neural Networks

Optimizers: SGD, Momentum, RMSProp, Adam/AdamW and LR Schedules

Gradient descent tells you which way is downhill; an optimizer decides how to walk. Momentum, adaptive per-parameter step sizes, decoupled weight decay, warmup and cosine decay — what each fixes, and the knobs that come with them.

Intermediate~30 min·6 references
Key terms
OptimizerSGD (Stochastic Gradient Descent)MomentumAdam / AdamWLearning rate scheduleLearning rate warmupWeight decayLearning rate

An Optimizer is the rule that turns gradients into weight updates. Plain Gradient descent uses the same step size for every parameter and has no memory of previous steps. That works on nicely shaped bowls, but real loss surfaces have long narrow ravines, flat plateaus, saddle points and noisy mini-batch gradients. Modern optimizers add memory (momentum) and per-parameter step sizes (adaptive methods like Adam), and are combined with a Learning rate schedule that changes η during training[1].

≈
Walking down a foggy mountain
SGD is a hiker who can only feel the slope under their feet and takes a fixed-size step that way — in a narrow ravine they zig-zag from wall to wall. Momentum is a heavy ball rolling down: it builds speed along the valley floor and its inertia cancels the side-to-side wobble. Adam is a hiker with adjustable boots: on steep, bumpy directions they take careful small steps; on gentle, consistent directions they stride out.

SGD and its problems

θ ← θ − η · g (g = gradient of the mini-batch loss)
Plain mini-batch SGD — the baseline every optimizer below modifies.
In words: “move the parameters a small step against the gradient computed on the current mini-batch.” It is plain gradient descent, except that g is estimated from a handful of examples, so every step is cheap but a little noisy.
Symbols(hover a symbol in the formula)
θ
theta — all trainable parameters, as one vector
←
assignment: overwrite θ with the right-hand side, once per iteration
η
Learning rate
g
mini-batch Gradient: the average of the per-example gradients in this batch
·
multiplication
▸Worked example
Two parameters θ = (1.0, −2.0), η = 0.1 Batch 1 gives g = (0.5, −1.0): θ ← (1.0 − 0.05, −2.0 + 0.1) = (0.95, −1.9) Batch 2 gives g = (0.3, −1.4): θ ← (0.95 − 0.03, −1.9 + 0.14) = (0.92, −1.76) The two gradients differ only because the batches hold different examples — that randomness is the “stochastic” in SGD.

Stochastic gradient descent has three classic difficulties. Ill-conditioning: when the surface is much steeper in one direction than another (a ravine), a learning rate small enough to be stable in the steep direction is painfully slow in the shallow one, and the path zig-zags. Saddle points and plateaus: the gradient is near zero, so progress stalls. Noise: mini-batch gradients jitter around the true gradient. Each optimizer below targets one or more of these[1].

Momentum

v ← β · v + g θ ← θ − η · v
v is a running (exponentially decaying) sum of past gradients. With a constant gradient, the step grows to η/(1 − β): β = 0.9 means up to 10× the plain SGD step.
In words: “velocity = β times the old velocity plus the new gradient; then step along the velocity instead of the raw gradient.” Gradients that keep pointing the same way pile up and speed you along, while those that flip sign every step cancel out — like a heavy ball rolling downhill that ignores small bumps.
Symbols(hover a symbol in the formula)
v
velocity: a decaying running sum of past gradients (starts at 0)
β
beta — Momentum coefficient: the fraction of the old velocity that is kept, typically 0.9
g
current mini-batch Gradient
θ
the parameters
η
Learning rate
←
update (overwrite): first v, then θ
·
multiplication
▸Worked example
β = 0.9, η = 0.1, v starts at 0 Constant gradient g = 1 every step: v: 1 → 0.9·1 + 1 = 1.9 → 2.71 → 3.439 → … → 1/(1 − 0.9) = 10 step η·v: 0.1 → 0.19 → 0.271 → … up to 1.0 (10× plain SGD) Zig-zag gradient g = +1, −1, +1, −1, …: v: 1 → −0.1 → 0.91 → −0.181 → 0.837 → −0.247 → … settles at about ±0.53 the back-and-forth mostly cancels, while the steady direction builds up to 10.

Momentum (Polyak, 1964) accumulates velocity: components of the gradient that point the same way every step add up, while components that flip sign (the zig-zag across a ravine) cancel out. Nesterov momentum evaluates the gradient at the look-ahead position, which reacts a bit faster when the ball should slow down. Sutskever et al. (2013) showed that SGD with well-tuned momentum and a good initialization can train deep and recurrent networks that were previously considered very hard to optimize[2].

RMSProp: per-parameter step sizes

s ← ρ · s + (1 − ρ) · g² θ ← θ − η · g / (√s + ε)
s tracks the recent average squared gradient of each parameter. Parameters with large, noisy gradients get smaller steps; parameters with tiny gradients get larger ones.
In words: “keep a running average s of each parameter's squared gradient; then step by the gradient divided by the square root of that average.” √s is roughly the typical gradient size, so dividing by it normalises the step: parameters with huge gradients slow down, parameters with tiny gradients speed up, and all move at a similar pace.
Symbols(hover a symbol in the formula)
s
running average of squared gradients, one per parameter (starts at 0)
ρ
rho — decay rate of the average, typically 0.9 (called alpha = 0.99 in PyTorch)
g²
the gradient squared, element by element (always ≥ 0)
g
current mini-batch Gradient
θ
the parameters
η
Learning rate, typically 0.001
√
square root: turns the mean squared gradient back into gradient units (RMS = root mean square)
ε
tiny constant (e.g. 10⁻⁸) that prevents division by zero
←
update: first s, then θ
·
multiplication
▸Worked example
ρ = 0.9, η = 0.01, s starts at 0; two parameters with very different gradients A, g = 10: s = 0.9·0 + 0.1·100 = 10 step = 0.01·10 / √10 ≈ 0.0316 B, g = 0.1: s = 0.9·0 + 0.1·0.01 = 0.001 step = 0.01·0.1 / √0.001 ≈ 0.0316 → the same step size despite a 100× difference in gradient! Next step, same gradients: A: s = 0.9·10 + 10 = 19 → step = 0.1 / √19 ≈ 0.0229 (B also ≈ 0.0229) Plain SGD with η = 0.01 would have stepped 0.1 and 0.001.

RMSProp was proposed by Geoffrey Hinton in his Coursera lecture notes rather than in a paper. Dividing by √s normalises each coordinate, which directly attacks ill-conditioning: the steep wall of a ravine gets a small step, the gentle valley floor a big one[1].

Adam = momentum + RMSProp + bias correction

m ← β₁·m + (1 − β₁)·g v ← β₂·v + (1 − β₂)·g²
Adam's two running averages, updated every step for every parameter.
In words: Two running averages: m is a smoothed gradient (the momentum part — which way to go) and v is a smoothed squared gradient (the RMSProp part — how big the gradients usually are). β₁ and β₂ set how long each average remembers, roughly the last 1/(1 − β) steps: ~10 steps for m and ~1000 for v.
Symbols(hover a symbol in the formula)
m
first moment: exponential moving average of the gradients (starts at 0)
v
second moment: exponential moving average of the squared gradients (starts at 0)
β₁
decay rate for m, default 0.9
β₂
decay rate for v, default 0.999
g
current mini-batch Gradient
g²
the gradient squared, element by element
←
update (overwrite) the running average
·
multiplication
▸Worked example
Defaults β₁ = 0.9, β₂ = 0.999; m = v = 0 at the start; one parameter Step 1, g = 0.5: m = 0.9·0 + 0.1·0.5 = 0.05 v = 0.999·0 + 0.001·0.25 = 0.00025 Step 2, g = 0.3: m = 0.9·0.05 + 0.1·0.3 = 0.075 v = 0.999·0.00025 + 0.001·0.09 ≈ 0.00034 Both are far too small (the gradients are 0.3–0.5, their squares 0.09–0.25) because the averages started at 0 — the next formula corrects that.
m̂ = m / (1 − β₁ᵗ) v̂ = v / (1 − β₂ᵗ) θ ← θ − η · m̂ / (√v̂ + ε)
Defaults from Kingma & Ba: η = 0.001, β₁ = 0.9, β₂ = 0.999, ε = 10⁻⁸. The bias correction fixes the fact that m and v start at 0: at step 1, m = 0.1·g but m̂ = g.
In words: “undo the start-at-zero bias by dividing m and v by (1 − βᵗ), then step by the corrected average gradient divided by the corrected RMS gradient.” The ratio m̂/√v̂ is about ±1 when gradients are consistent and smaller when they are noisy, so each parameter moves at most about η per step, whatever the scale of its gradient.
Symbols(hover a symbol in the formula)
m̂
“m-hat”: bias-corrected first moment — estimate of the average gradient
v̂
“v-hat”: bias-corrected second moment — estimate of the average squared gradient
m
raw first moment from the previous formula
v
raw second moment from the previous formula
β₁ᵗ
β₁ to the power t, where t = step number (1, 2, 3 …); 1 − β₁ᵗ starts at 0.1 and approaches 1
β₂ᵗ
β₂ to the power t; 1 − β₂ᵗ starts at 0.001, so at step 1 v is scaled up 1000×
θ
the parameters
η
Learning rate, default 0.001 — roughly the largest step a parameter takes
√
square root (of v̂, giving the RMS gradient)
ε
10⁻⁸, prevents division by zero
←
update the parameters
·
multiplication
▸Worked example
Continuing: η = 0.001, ε = 10⁻⁸, θ = 1.0 Step 1 (t = 1): m̂ = 0.05 / (1 − 0.9) = 0.5 v̂ = 0.00025 / (1 − 0.999) = 0.25 θ ← 1.0 − 0.001 · 0.5 / (√0.25 + ε) = 1.0 − 0.001 = 0.999 Step 2 (t = 2): m̂ = 0.075 / (1 − 0.81) ≈ 0.395 v̂ = 0.00033975 / 0.001999 ≈ 0.170 θ ← 0.999 − 0.001 · 0.395 / 0.412 ≈ 0.999 − 0.00096 = 0.99804 Multiply every gradient by 1000 and m̂/√v̂ stays the same — Adam ignores the gradient's scale.

Adam (Kingma & Ba, 2014) keeps both a momentum-like first moment m and an RMSProp-like second moment v[3]. Its effective step per parameter is roughly η · (direction sign), which makes it fairly insensitive to the scale of the gradients and works well out of the box. That's why it became the default for Transformers, GANs and most research code.

AdamW: weight decay done right

θ ← θ − η · ( m̂ / (√v̂ + ε) + λ · θ )
AdamW applies weight decay λ directly to the weights, outside the adaptive scaling.
In words: “take the normal Adam step, and also pull every weight a little toward zero by η·λ·θ.” Because the decay term sits outside Adam's division by √v̂, every weight shrinks by the same fraction ηλ per step — unlike adding an L2 penalty to the loss, where Adam's rescaling weakens the decay for exactly the weights with large gradients.
Symbols(hover a symbol in the formula)
θ
the parameters (weights)
←
update the parameters
η
Learning rate
m̂
bias-corrected first moment (average gradient), as in Adam
v̂
bias-corrected second moment (average squared gradient), as in Adam
√
square root
ε
tiny constant against division by zero
λ
lambda — Weight decay strength, e.g. 0.01 (PyTorch AdamW default) to 0.1
·
multiplication
▸Worked example
θ = 2.0, η = 0.001, λ = 0.01, Adam part m̂/(√v̂ + ε) = 1.0 (e.g. step 1 with a positive gradient) Decay term: λ · θ = 0.01 · 2.0 = 0.02 θ ← 2.0 − 0.001 · (1.0 + 0.02) = 2.0 − 0.00102 = 1.99898 A weight with zero gradient (Adam part 0): θ ← 2.0 − 0.001 · 0.02 = 1.99998 → after 1,000 such steps: 2 · (1 − 0.00001)¹⁰⁰⁰ ≈ 1.980 With Adam + L2 instead, the 0.02 would be added to the gradient and then divided by √v̂: strong decay for weights with tiny gradients, almost none for weights with big ones.

With SGD, adding an L2 penalty (λ/2)‖θ‖² to the loss is the same as shrinking weights each step (Weight decay). With Adam it is not: the L2 gradient λθ gets divided by √v̂, so weights with large gradients are barely regularized. Loshchilov & Hutter showed that decoupling the decay from the gradient step (AdamW) regularizes properly, generalizes better and makes the best λ much less dependent on η[4]. In PyTorch, torch.optim.Adam(weight_decay=…) is the coupled L2 version; use torch.optim.AdamW for decoupled decay[6].

OptimizerExtra state per parameterStrengthsWatch out forTypical η
SGD0Simple, minimal memorySlow in ravines, sensitive to η0.01–0.1
SGD + momentum1 (v)Fast and often best generalization for CNNsNeeds η schedule tuning0.01–0.1 (β = 0.9)
RMSProp1 (s)Handles ill-conditioning; used in early deep RLNo momentum by default1e-4–1e-3
Adam / AdamW2 (m, v)Robust defaults; standard for Transformers2× extra memory: 7B params × 2 × 4 bytes ≈ 56 GB of optimizer state in fp321e-4–3e-3

Learning rate schedules and warmup

A fixed learning rate is a compromise: large steps are good early (fast progress), small steps are good late (settling into a minimum instead of bouncing around it). A Learning rate schedule gets both. Common shapes: step decay (÷10 at fixed epochs, classic for ResNets), cosine annealing (smooth decay along half a cosine; Loshchilov & Hutter's SGDR)[5], linear decay (common for BERT-style fine-tuning), one-cycle (up then down) and reduce-on-plateau (cut η when validation loss stalls).

η_t = η_min + ½ (η_max − η_min) · (1 + cos(π · t / T))
Cosine annealing from η_max at step t = 0 to η_min at step T.
In words: “start at the maximum learning rate and glide down to the minimum along half a cosine wave.” The cosine goes from +1 (t = 0) to −1 (t = T), so ½(1 + cos) goes smoothly from 1 to 0: the rate stays high for a while, drops fastest in the middle, and flattens out gently at the end.
Symbols(hover a symbol in the formula)
η_t
Learning rate at step (or epoch) t
η_min
final, smallest learning rate (often 0 or ~1% of η_max)
η_max
starting, largest learning rate
½
one half: rescales (1 + cos), which runs from 2 to 0, to the range 1 … 0
cos
cosine: cos 0 = 1, cos(π/2) = 0, cos π = −1
π
pi ≈ 3.1416; π·t/T runs from 0 to π — half a cosine wave
t
current step
T
total number of steps in the schedule
·
multiplication
▸Worked example
η_max = 0.1, η_min = 0.001, T = 100 steps → ½(η_max − η_min) = 0.0495 t = 0: cos 0 = 1 η = 0.001 + 0.0495·2 = 0.1 t = 25: cos(π/4) ≈ 0.707 η = 0.001 + 0.0495·1.707 ≈ 0.0855 t = 50: cos(π/2) = 0 η = 0.001 + 0.0495·1 = 0.0505 t = 75: cos(3π/4) ≈ −0.707 η = 0.001 + 0.0495·0.293 ≈ 0.0155 t = 100: cos π = −1 η = 0.001 + 0 = 0.001

Warmup starts with a tiny learning rate and ramps it up linearly over the first few hundred or thousand steps. Early on, weights are random, gradients are large and erratic, and Adam's variance estimate v is based on very few samples — a full-size step can throw the model into a bad region it never recovers from. The original Transformer used 4,000 warmup steps (Vaswani et al., 2017), and the linear scaling rule for large batches relies on warmup too. A typical modern recipe: linear warmup for ~1–5% of steps, then cosine decay to ~10% of the peak.

Loading interactive…
Race SGD, Momentum, RMSProp and Adam from the same starting point on different 2D loss surfaces. Click the plot to choose a start.
  1. The ravine: choose the Rosenbrock-like ravine and enable all four. SGD zig-zags across the narrow valley and crawls along its floor; Momentum overshoots at first, then accelerates along the valley; RMSProp and Adam head more directly toward the valley floor because they rescale each axis.
  2. Momentum β: set β = 0 — Momentum's path becomes identical to SGD. Raise it to 0.9, then 0.99: the ball overshoots and circles longer before settling. High β = more inertia.
  3. Learning rate: raise it until SGD starts bouncing between the valley walls or flies off; Adam usually tolerates a different range because its step size doesn't scale with the gradient magnitude. Lower it and watch every optimizer slow down.
  4. Saddle: start near the saddle point. SGD lingers where the gradient is tiny; momentum and the adaptive methods escape faster.
  5. Bumpy surface: on the bumpy function, try several start points. Momentum can roll through small bumps that trap SGD — but no optimizer is guaranteed to find the global minimum.
knobMomentum β (Adam: β₁)
What it is
How much of the previous velocity is kept each step — the “memory length” of the gradient average (≈ 1/(1 − β) steps).
↑ If you increase it
Smoother, faster travel along consistent directions and better noise averaging; but more overshoot and oscillation around the minimum. The effective step size grows (η/(1 − β)), so you may need to lower η.
↓ If you decrease it
More responsive but noisier; at β = 0 it is plain SGD (zig-zag in ravines).
Typical values
0.9 (SGD momentum, Adam β₁). Sometimes 0.95–0.99.
knobAdam β₂
What it is
Decay rate of the running average of squared gradients — how many recent steps Adam uses to estimate each parameter's gradient scale (≈ 1/(1 − β₂)).
↑ If you increase it
Smoother, longer-memory estimate (0.999 ≈ last 1000 steps). Stable in steady regimes, but reacts slowly when gradients suddenly grow, which can cause loss spikes in large-model training.
↓ If you decrease it
Adapts faster to changing gradient scales (0.95 ≈ last 20 steps); often used for large Transformers/LLMs for stability, at the cost of noisier step sizes.
Typical values
0.999 (default); 0.95–0.98 for LLM pretraining.
knobAdam ε (epsilon)
What it is
A small constant added to √v̂ to avoid division by zero; also caps the maximum step for parameters with tiny gradients.
↑ If you increase it
Adam behaves more like SGD with momentum (less adaptive), steps get smaller for low-gradient parameters; sometimes improves stability.
↓ If you decrease it
Fully adaptive; with very small v̂ the steps can become large and unstable, especially in low-precision (fp16) training.
Typical values
1e-8 (default); 1e-6 or larger in some mixed-precision setups.
knobWeight decay λ (AdamW)
What it is
How strongly every weight is pulled toward zero at each step, independent of the gradient.
↑ If you increase it
Stronger regularization: smaller weights, smoother functions, less overfitting. Too large and the model underfits (training loss stays high).
↓ If you decrease it
Less regularization; at 0 the weights are free to grow, which can increase overfitting.
Typical values
AdamW: 0.01–0.1 (PyTorch default 0.01). SGD: 1e-4–5e-4. Usually not applied to biases and normalization weights.
knobWarmup length
What it is
Number of initial steps over which the learning rate ramps from ~0 to its peak.
↑ If you increase it
Safer start, tolerates higher peak learning rates and larger batches; but wastes some steps at low LR (slower early progress).
↓ If you decrease it
Faster start, but large models/high LRs may spike or diverge in the first steps. Zero warmup is usually fine for small models with SGD.
Typical values
1–5% of total steps; a few hundred to a few thousand steps for Transformers; 5 epochs in Goyal et al.
knobSchedule decay / final learning rate
What it is
How fast and how far the learning rate decreases after warmup (e.g. cosine to η_min, ÷10 steps, linear to 0).
↑ If you increase it
Decaying further/faster (lower final LR) lets the model settle into a minimum — typically a visible drop in loss near the end; too-early decay freezes learning before it is done.
↓ If you decrease it
Keeping the LR high longer explores more but the loss stays noisy and never fully settles.
Typical values
Cosine to 0–10% of peak; step decay ×0.1 at ~30/60/90% of training.
python
import torch
from torch.optim.lr_scheduler import LinearLR, CosineAnnealingLR, SequentialLR

model = MyModel()
decay, no_decay = [], []
for name, p in model.named_parameters():
    (no_decay if p.ndim < 2 else decay).append(p)      # biases & norm weights: no decay

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

total_steps, warmup_steps = 10_000, 500
sched = SequentialLR(
    opt,
    schedulers=[
        LinearLR(opt, start_factor=0.01, total_iters=warmup_steps),            # warmup
        CosineAnnealingLR(opt, T_max=total_steps - warmup_steps, eta_min=3e-5),  # decay
    ],
    milestones=[warmup_steps],
)

for step in range(total_steps):
    loss = compute_loss(model, next_batch())
    opt.zero_grad()
    loss.backward()
    opt.step()
    sched.step()        # this schedule is defined in steps, so call it every step
AdamW with decoupled weight decay (no decay on biases/norms), linear warmup and cosine decay, using PyTorch's built-in schedulers[6].
!
Common pitfalls
Watch out for these:
  • Reusing an SGD learning rate for Adam (0.1 with Adam usually diverges) — or Adam's 1e-3 for SGD (very slow).
  • `Adam(weight_decay=…)` is not AdamW. It's L2 regularization coupled to the adaptive scaling.
  • Resuming training without the optimizer state: Adam's m and v restart from zero and the schedule restarts — save and load optimizer.state_dict() and scheduler.state_dict() in checkpoints.
  • Adaptive methods are not always better: Wilson et al. (2017) found well-tuned SGD + momentum generalizing better than Adam on several vision benchmarks. Try both when it matters.
  • Scheduler called at the wrong granularity (per epoch vs per step).
▸Go deeper: why bias correction, and newer optimizers

Unrolling m_t = (1 − β₁) Σ β₁^(t−i) g_i shows that if all g_i had the same expected value, E[m_t] = (1 − β₁ᵗ)·E[g]. Dividing by (1 − β₁ᵗ) removes this shrinkage toward the zero initialization — it matters most in the first ~1/(1 − β) steps, especially for v with β₂ = 0.999[3].

Newer optimizers target memory or scale: Adafactor (Shazeer & Stern, 2018) factorizes v to save memory; LAMB (You et al., 2019) adds layer-wise trust ratios for huge batches; Lion (Chen et al., 2023) uses only the sign of a momentum update and keeps one state tensor. AdamW with warmup + cosine remains the most common default[1].

Quiz

1.
Why does momentum help in a long, narrow ravine?
2.
What is the practical difference between Adam(weight_decay=0.01) and AdamW(weight_decay=0.01) in PyTorch?
3.
A large Transformer's loss spikes to NaN in the first 50 steps, but trains fine if you start from a checkpoint at step 2000. What is the most targeted fix?
4.
With β = 0.9 and a constant gradient, how large does the momentum step become compared with plain SGD at the same η?
5.
Your validation loss drops sharply right at the end of training when using cosine decay. Why?
Score: 0/5

References

  1. [1]
    An overview of gradient descent optimization algorithms
    PaperRuder2016arxiv.org
  2. [2]
    On the importance of initialization and momentum in deep learning
    PaperSutskever, Martens, Dahl & Hinton2013proceedings.mlr.press
  3. [3]
    Adam: A Method for Stochastic Optimization
    PaperKingma & Ba2014arxiv.org
  4. [4]
    Decoupled Weight Decay Regularization
    PaperLoshchilov & Hutter2017arxiv.org
  5. [5]
    SGDR: Stochastic Gradient Descent with Warm Restarts
    PaperLoshchilov & Hutter2016arxiv.org
  6. [6]
    torch.optim — optimizers and learning rate schedulers
    DocsPyTorchdocs.pytorch.org
← Previous
Training Hyperparameters: Epochs, Learning Rate, Batch Size and More
Next →
Regularization, Normalization and Initialization