Deep Optimizers & LR Schedules (SGD, Momentum, AdamW & Cosine Warmup)
Why vanilla SGD zig-zags in steep ravines, how Momentum and Adam adapt per-parameter step sizes, why AdamW's decoupled weight decay beats Adam+L2, and how Warmup + Cosine Annealing schedules modern training.
AdamW + Linear Warmup + Cosine Annealing is the default recipe behind almost every modern Transformer, ViT, and Diffusion model!
Choosing the wrong optimizer or forgetting warmup can make a 1B-parameter model diverge in the first 100 steps — while switching from Adam(weight_decay=...) to AdamW routinely improves validation accuracy immediately.
Knowing how β₁ (momentum), β₂ (adaptive scale), wd (weight decay), and lr interact lets you diagnose loss curves in seconds instead of blindly grid-searching.
Top-5 most asked Deep Learning interview question: 'Write the AdamW update equations on the board — why do we need bias correction (1 − β^t), and why is AdamW different from Adam with L2 regularization?'
In Adam, why do we divide the moving averages m_t and v_t by (1 − β₁ᵗ) and (1 − β₂ᵗ)?
- Explain why mini-batch SGD noise helps escape sharp minima and saddle points compared to full-batch GD
- Derive Heavy-Ball Momentum, RMSProp, and Adam's first/second moment estimates with bias correction
- Explain the exact mathematical difference between broken Adam+L2 and AdamW decoupled weight decay
- Implement AdamW and a Linear Warmup + Cosine Annealing LR schedule from scratch in PyTorch
Picture rolling a ball down a long, narrow ski canyon where the side walls are super steep but the downhill trail is gentle. Vanilla SGD only looks at the ground right under its feet, so it slams from the left wall to the right wall over and over. Momentum gives the ball heavy mass so left-right wall slams cancel out while downhill speed builds up. AdamW goes one step further: it gives every single weight its own personal speedometer (1/√v̂), slowing down jittery steep directions and boosting quiet gentle directions — plus a clean, steady friction pull (−ηλw) toward smaller weights!
1. Full-Batch GD vs. Mini-Batch SGD: Why Gradient Noise Is a Feature
Computing the exact gradient over 1,000,000 training examples takes forever for a single tiny weight update. Instead, Deep Learning samples a mini-batch of B = 32..1024 examples — giving 1,000× more updates per epoch and healthy random jitter that shakes the model out of sharp, brittle local minima!
The Mini-Batch Tradeoff
- Too small (): Extreme gradient variance, under-utilized GPU tensor cores, and unstable BatchNorm.
- Sweet spot (): Saturates GPU parallelism while keeping enough stochastic noise to converge to flat minima (which generalize far better on unseen test data!).
- Linear Scaling Rule: When doubling batch size with SGD/Momentum, you often scale learning rate proportionally (with warmup).
2. Momentum, RMSProp, Adam & Why AdamW Decouples Weight Decay
Press Play on the Flagship Deep Lab below to watch SGD, Momentum, RMSProp, and AdamW race head-to-head down a steep 22:1 ravine! Here is the exact math behind why AdamW wins.
Complete AdamW Update Equations (Loshchilov & Hutter, 2019)
At step with gradient :
- First moment (velocity): (default )
- Second moment (squared grad scale): (default or for LLMs)
- Bias correction:
- Decoupled Weight Decay + Adaptive Step:
Why Old Adam + L2 Was Broken
In naive Adam(weight_decay=λ), L2 regularization adds directly into the gradient: . Then Adam divides that by ! That means weights with large historical gradients barely get decayed at all, breaking regularization. AdamW applies outside the adaptive denominator so every weight decays cleanly at rate .
w_t = (1 − ηλ)w_{t-1} − η · m̂_t / (√v̂_t + ε)
Shrinks weights directly by fraction ηλ without getting distorted by √v̂_t.
√v̂ = 10) and another has tiny steady gradients (√v̂ = 0.01), AdamW gives BOTH roughly the same clean ±η step size!3. Learning Rate Schedules: Linear Warmup + Cosine Annealing
Starting at full speed (η = 3e-4) on Step 1 when weights are completely random and Adam's v_t estimate is noisy is like flooring the gas pedal on ice! Linear Warmup eases in gently for the first 5–10% of steps, then Cosine Annealing smoothly lowers the LR so the model settles deep into the minimum. Scrub the curve below!
Warmup + Cosine Annealing Formula
For current step with warmup duration , peak rate , and floor :
- Warmup ():
- Cosine Decay (): with progress ,
Production Rule of Thumb: Never apply weight decay (λ > 0) to 1D parameters (biases, LayerNorm/BatchNorm γ and β weights) — only decay 2D+ weight matrices!
Worked Example: One Exact AdamW Step by Hand
At Step t = 1, let w₀ = 2.0, g₁ = 0.5, η = 0.1, λ = 0.1, β₁ = 0.9, β₂ = 0.99, ε = 1e-8, with m₀ = 0, v₀ = 0. Compute w₁.
Warmup + Cosine Annealing LR Sweeper
In AdamW, which parameters should normally have weight_decay = 0.0?
With η_max = 1e-3, η_min = 1e-4, warmup = 100, total = 1100, what is the exact learning rate at the midpoint of cosine decay t = 600?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
For Transformers, LLMs, ViTs, and quick prototyping, AdamW is the undisputed king. For classic ResNet / CNN vision benchmarks with generous compute budgets, well-tuned SGD + Momentum (0.9) + Cosine LR can still match or slightly beat AdamW in final generalization.
Steep Ravine Optimizer Marble Race: SGD vs. Momentum vs. RMSProp vs. AdamW
Watch 4 optimizers race down an ill-conditioned valley L(w₁, w₂) = 0.08w₁² + 1.8w₂² where the vertical wall is 22× steeper than the valley floor.
m̂/√v̂ adapts step sizes per parameter, AdamW decouples weight decay cleanly outside √v̂, and Linear Warmup + Cosine Annealing schedules stable convergence.LLM & Vision Transformer Pre-training
AdamW (β₁=0.9, β₂=0.95, wd=0.1) + linear warmup + cosine decay to 10% of peak LR is the universal frontier recipe.
ImageNet ResNet Benchmarks
SGD with Nesterov Momentum 0.9 + Cosine Annealing achieves strong flat-minimum generalization.
Gradient Accumulation
Calling loss.backward() over 8 micro-batches before a single optimizer.step() simulates an 8× larger batch on a single GPU.
Fine-tuning Pretrained Models
Using a 10× smaller LR (1e-5 to 5e-5) with warmup prevents catastrophic forgetting of pretrained weights.
import math
import torch
import torch.nn as nn
# 1. From-Scratch AdamW Step (exact math)
@torch.no_grad()
def adamw_step(p, grad, m, v, t, lr=3e-4, beta1=0.9, beta2=0.999, eps=1e-8, wd=0.01):
# Decoupled weight decay directly on weights
p.mul_(1.0 - lr * wd)
# Exponential moving averages of gradient and squared gradient
m.mul_(beta1).add_(grad, alpha=1.0 - beta1)
v.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2)
# Bias correction
m_hat = m / (1.0 - beta1 ** t)
v_hat = v / (1.0 - beta2 ** t)
p.addcdiv_(m_hat, v_hat.sqrt().add_(eps), value=-lr)
# 2. Idiomatic PyTorch: Separate Decay Groups + Warmup/Cosine Schedule
model = nn.Sequential(nn.Linear(256, 256), nn.LayerNorm(256), nn.GELU(), nn.Linear(256, 10))
decay_params = [p for p in model.parameters() if p.ndim >= 2]
no_decay_params = [p for p in model.parameters() if p.ndim < 2]
optimizer = torch.optim.AdamW(
[
{"params": decay_params, "weight_decay": 0.01},
{"params": no_decay_params, "weight_decay": 0.0},
],
lr=3e-4,
betas=(0.9, 0.95),
)
def cosine_warmup_lambda(step: int, warmup: int = 100, total: int = 1000, min_ratio: float = 0.1):
if step < warmup:
return step / max(1, warmup)
p = min(1.0, (step - warmup) / max(1, total - warmup))
return min_ratio + 0.5 * (1.0 - min_ratio) * (1.0 + math.cos(math.pi * p))
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=cosine_warmup_lambda)
Adam(weight_decay=0.01) and AdamW(weight_decay=0.01) are equivalent.AdamW decouples weight decay outside 1/√v̂.scheduler.step() per epoch instead of per step for Cosine Warmup.optimizer.step(), otherwise LR stays stuck near 0.0!γ parameters and biases.p.ndim >= 2 (decay) and p.ndim < 2 (no decay).m_t + v_t).t = 1 with m₀ = 0, v₀ = 0, why is bias correction 1 / (1 − βᵗ) necessary?