Chapter 15 of 42 · ~30 min read & lab+85 XP
Chapter 15 · Deep Learning

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.

Why ML Engineers & Data Scientists Actually Need This

AdamW + Linear Warmup + Cosine Annealing is the default recipe behind almost every modern Transformer, ViT, and Diffusion model!

ML / AI Engineer

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.

Data Scientist

Knowing how β₁ (momentum), β₂ (adaptive scale), wd (weight decay), and lr interact lets you diagnose loss curves in seconds instead of blindly grid-searching.

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

In Adam, why do we divide the moving averages m_t and v_t by (1 − β₁ᵗ) and (1 − β₂ᵗ)?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
m_tSay aloud:“first moment (momentum)”
Plain-English Meaning
Exponential moving average of past gradients (direction/velocity)
Everyday Example
m_t = β₁ m_{t-1} + (1−β₁) g_t
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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!

Batch GD vs. Mini-Batch SGD: Why Controlled Gradient Noise Helps GeneralizeFlat Minimum w*Full-Batch GD (1 step = entire dataset)Mini-Batch SGD (B = 64: fast updates + saddle-point escape!)
Full-batch GD takes slow, smooth steps across the entire dataset; mini-batch SGD takes fast, noisy steps whose jitter actually helps escape sharp local minima and saddle points.

The Mini-Batch Tradeoff

  • Too small (B=1..4B = 1..4): Extreme gradient variance, under-utilized GPU tensor cores, and unstable BatchNorm.
  • Sweet spot (B=32..512B = 32..512): 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 BB with SGD/Momentum, you often scale learning rate η\eta proportionally (with warmup).

2. Momentum, RMSProp, Adam & Why AdamW Decouples Weight Decay

Everyday Story First (Zero Math Yet!)

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.

Momentum Velocity Cancellation + AdamW Decoupled Weight DecaySteep Ravine: SGD Zig-Zags vs. MomentumUp/down walls cancel; valley velocity accumulates!Why AdamW Beats Adam + L2Broken Adam + L2: g_t ← g_t + λwDecay gets divided by √v_t (weak on big grads!)AdamW (Decoupled): Standard for LLMs & ViTsw ← w − ηλw − η · m̂ / (√v̂ + ε)
Momentum damps oscillations along steep ravine walls while accelerating down the valley floor; AdamW decouples weight decay directly from the adaptive gradient scaling so regularization works cleanly.

Complete AdamW Update Equations (Loshchilov & Hutter, 2019)

At step t≥1t \ge 1 with gradient gt=∇wL(wt−1)g_t = \nabla_w \mathcal{L}(w_{t-1}):

  1. First moment (velocity): mt=β1mt−1+(1−β1)gtm_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t (default β1=0.9\beta_1 = 0.9)
  2. Second moment (squared grad scale): vt=β2vt−1+(1−β2)gt2v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2 (default β2=0.999\beta_2 = 0.999 or 0.950.95 for LLMs)
  3. Bias correction: m^t=mt1−β1t,v^t=vt1−β2t\hat{m}_t = \frac{m_t}{1 - \beta_1^t}, \quad \hat{v}_t = \frac{v_t}{1 - \beta_2^t}
  4. Decoupled Weight Decay + Adaptive Step: wt=wt−1−ηλwt−1−ηm^tv^t+ϵw_t = w_{t-1} - \eta \lambda w_{t-1} - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

Why Old Adam + L2 Was Broken

In naive Adam(weight_decay=λ), L2 regularization adds λw\lambda w directly into the gradient: gt←gt+λwg_t \leftarrow g_t + \lambda w. Then Adam divides that λw\lambda w by v^t\sqrt{\hat{v}_t}! That means weights with large historical gradients barely get decayed at all, breaking regularization. AdamW applies −ηλw-\eta\lambda w outside the adaptive denominator so every weight decays cleanly at rate ηλ\eta\lambda.

Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of the AdamW Weight Update

w_t = (1 − ηλ)w_{t-1} − η · m̂_t / (√v̂_t + ε)

Decoupled Weight Decay

Shrinks weights directly by fraction ηλ without getting distorted by √v̂_t.

In our example: η=1e-3, λ=0.01 → 0.99999·w
Put it together with real numbers: If a weight has huge oscillating gradients (√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

Everyday Story First (Zero Math Yet!)

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!

Modern Standard Schedule: Linear Warmup → Cosine Annealing → Floor η_minWarmup (5-10%)Cosine Decay: η_min + ½(η_max − η_min)(1 + cos(π·p))η_maxη_min
Linear warmup protects early random weights from huge Adam variance spikes, then cosine annealing smoothly lowers the learning rate into a fine-grained minimum.

Warmup + Cosine Annealing Formula

For current step t∈[0,T]t \in [0, T] with warmup duration TwT_w, peak rate ηmax⁡\eta_{\max}, and floor ηmin⁡\eta_{\min}:

  • Warmup (t<Twt < T_w): η(t)=ηmax⁡⋅tTw\eta(t) = \eta_{\max} \cdot \frac{t}{T_w}
  • Cosine Decay (t≥Twt \ge T_w): with progress p=t−TwT−Tw∈[0,1]p = \frac{t - T_w}{T - T_w} \in [0, 1], η(t)=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡(πp))\eta(t) = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\big(1 + \cos(\pi p)\big)

Production Rule of Thumb: Never apply weight decay (λ > 0) to 1D parameters (biases, LayerNorm/BatchNorm γ and β weights) — only decay 2D+ weight matrices!

Walk Through With Me · Interactive Worked Example

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₁.

11. Update biased moments m₁ and v₁Step 1 / 4

m1=0.1(0.5)=0.05,v1=0.01(0.25)=0.0025m_1 = 0.1(0.5) = 0.05, \quad v_1 = 0.01(0.25) = 0.0025

Teacher's Note: Both are tiny because m₀ = v₀ = 0.
Animated Mini-Lab • Ch 10

Warmup + Cosine Annealing LR Sweeper

Cosine Annealing • η = 2.91e-4
η_max = 3.0e-4η_min = 3.0e-5
Pause & Check · Quick Intuition Pulse

In AdamW, which parameters should normally have weight_decay = 0.0?

Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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.

Interactive Visual Lab
Lab Challenge: Watch all 4 optimizers race down the steep 22:1 ravine in the Deep Lab below and adjust LR Multiplier & AdamW λ to see AdamW converge fastest!
Interactive Animation • Ch 10 Deep Lab

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.

Step 0/40
w* (0,0)
SGD
Loss: 6.312
Momentum
Loss: 6.312
RMSProp
Loss: 6.312
AdamW
Loss: 6.312
0%
Ravine Optimization Race
Intuition Takeaway: Momentum damps ravine oscillations, Adam's bias-corrected m̂/√v̂ adapts step sizes per parameter, AdamW decouples weight decay cleanly outside √v̂, and Linear Warmup + Cosine Annealing schedules stable convergence.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Claiming Adam(weight_decay=0.01) and AdamW(weight_decay=0.01) are equivalent.
Best Practice: They are ONLY equivalent for vanilla SGD; in adaptive optimizers, AdamW decouples weight decay outside 1/√v̂.
Trap #2: Calling scheduler.step() per epoch instead of per step for Cosine Warmup.
Best Practice: Step-based warmup/cosine schedulers must step after every optimizer.step(), otherwise LR stays stuck near 0.0!
Trap #3: Applying weight decay to LayerNorm/BatchNorm γ parameters and biases.
Best Practice: Split parameters into p.ndim >= 2 (decay) and p.ndim < 2 (no decay).
Trap #4: Forgetting AdamW's 8 bytes/param VRAM cost (m_t + v_t).
Best Practice: Account for 2 FP32 optimizer states per trainable parameter when budgeting GPU memory.
Chapter Mastery Check (+85 XP)
Score: 0 / 5
1What is the exact difference between AdamW and Adam with L2 regularization?
2Why does Momentum accelerate convergence in a steep, narrow loss ravine?
3Why is Linear Learning Rate Warmup critical at the start of AdamW training?
4How many extra FP32 optimizer state tensors per parameter does AdamW store?
5At t = 1 with m₀ = 0, v₀ = 0, why is bias correction 1 / (1 − βᵗ) necessary?

Apply What You Learned — Solve Matching Coding Problems