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.
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].
SGD and its problems
- θ
- 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
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
- 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
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
- 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
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
- 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
- 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
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
- θ
- 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
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].
| Optimizer | Extra state per parameter | Strengths | Watch out for | Typical η |
|---|---|---|---|---|
| SGD | 0 | Simple, minimal memory | Slow in ravines, sensitive to η | 0.01–0.1 |
| SGD + momentum | 1 (v) | Fast and often best generalization for CNNs | Needs η schedule tuning | 0.01–0.1 (β = 0.9) |
| RMSProp | 1 (s) | Handles ill-conditioning; used in early deep RL | No momentum by default | 1e-4–1e-3 |
| Adam / AdamW | 2 (m, v) | Robust defaults; standard for Transformers | 2× extra memory: 7B params × 2 × 4 bytes ≈ 56 GB of optimizer state in fp32 | 1e-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
- 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
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.
- 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.
- 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.
- 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.
- Saddle: start near the saddle point. SGD lingers where the gradient is tiny; momentum and the adaptive methods escape faster.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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- 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()andscheduler.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
Adam(weight_decay=0.01) and AdamW(weight_decay=0.01) in PyTorch?References
- [1]An overview of gradient descent optimization algorithmsPaperRuder2016arxiv.org
- [2]On the importance of initialization and momentum in deep learningPaperSutskever, Martens, Dahl & Hinton2013proceedings.mlr.press
- [3]Adam: A Method for Stochastic OptimizationPaperKingma & Ba2014arxiv.org
- [4]Decoupled Weight Decay RegularizationPaperLoshchilov & Hutter2017arxiv.org
- [5]SGDR: Stochastic Gradient Descent with Warm RestartsPaperLoshchilov & Hutter2016arxiv.org
- [6]torch.optim — optimizers and learning rate schedulersDocsPyTorchdocs.pytorch.org