Deep Learning Slides 📂 Introduction · 18 of 18 40 min read

Optimizers in Deep Learning

A complete, visual tour of deep learning optimizers — from plain gradient descent through momentum, AdaGrad, RMSProp, and Adam. Learn how each one navigates the loss landscape, why Adam's bias correction matters, when to reach for AdamW, and exactly which optimizer to pick for vision, transformers, RNNs, and sparse data.

Optimizers in Deep Learning

Every neural network learns by rolling downhill on a loss landscape it cannot see. The optimizer is the strategy that decides each step — how far, which direction, and how to remember where it has been. From plain gradient descent to Adam, this is the full tour.
The Descent Problem Momentum & Adaptive Rates Adam & AdamW What to Use When

Press Next → or use ← → arrow keys

Section 01

The Blindfolded Hiker

Picture a hiker dropped somewhere on a foggy mountain range, blindfolded, trying to reach the lowest valley. They can only feel the slope under their feet. That slope is the gradient; the mountain is the loss landscape; and the walking strategy is the optimizer.

local valley global min start
🧭
One rule, endless strategies

Every optimizer answers the same question — “given the slope, where do I step next?” — but the smart ones also remember momentum and adapt their stride to the terrain.

Section 02

Gradient Descent — The Core Step

Every optimizer is a twist on one update: move the parameters a little bit in the direction that reduces the loss fastest — the negative gradient.

θt+1 = θt − η · ∇L(θt)
parameters ← parameters − (learning rate × gradient)
🗺️
Batch GD
Uses the whole dataset per step. Exact direction, but slow and memory-hungry on big data.
🎲
Stochastic GD
One sample per step. Noisy and fast; the jitter can even help escape shallow traps.
📦
Mini-batch SGD
A batch of 32–512 samples. The practical standard — stable gradients, GPU-friendly.
🎚️
η (the learning rate) is the single most important knob

Too large and the hiker leaps over the valley; too small and they crawl. Nearly every practical failure of training traces back to a bad learning rate — not the choice of optimizer.

Section 03

The Ravine Problem

Real loss surfaces have ravines — long narrow valleys, steep across, gently sloping along. Plain SGD overreacts to the steep walls and zig-zags, wasting most of its motion bouncing side to side instead of travelling down the valley floor.

min SGD — oscillates + momentum — glides
Same landscape, very different journey

The fix isn't a smaller learning rate (that just crawls) — it's memory. If the optimizer remembers its recent direction, side-to-side wobbles cancel out and forward progress adds up.

Section 04

Momentum & Nesterov

Momentum gives the hiker inertia. Instead of stepping by the raw gradient, we accumulate a running velocity — a heavy ball rolling downhill smooths over bumps and powers through flat stretches.

vt = β · vt−1 + η · ∇L(θt)
velocity = decayed past velocity + new gradient step
θt+1 = θt − vt
step by the velocity, not the raw gradient (β ≈ 0.9)
Classic Momentum

Looks at the gradient where it is now, then adds it to the velocity. Damps oscillation and accelerates through ravines and plateaus.

Nesterov Look-ahead (NAG)

First jumps ahead by the current velocity, then measures the gradient there. This peek forward corrects overshoot earlier — usually a little faster and more stable.

🎳
Why it works

Along the valley floor gradients keep pointing the same way, so velocity compounds. Across the walls they flip sign every step, so they cancel. Momentum keeps the useful motion and kills the wasteful kind.

Section 05

AdaGrad — A Rate Per Parameter

Momentum still uses one learning rate for every weight. But some features fire constantly and others are rare. AdaGrad gives each parameter its own learning rate, shrinking it in proportion to how much that parameter has already been updated.

Gt = Gt−1 + (∇L)2
accumulate squared gradients, per parameter
θt+1 = θt − η / √(Gt + ε) · ∇L
big history → small step; small history → big step
Win Sparse data

Rare words and embeddings get large updates when they finally appear; common features get gently nudged. Ideal for bag-of-words and text models.

Flaw The rate dies

Gt only ever grows, so the effective learning rate marches monotonically toward zero. In a deep network, training eventually stalls and cannot recover.

Section 06

RMSProp — Fading Memory

RMSProp keeps AdaGrad's per-parameter idea but fixes the dying rate. Instead of summing squared gradients forever, it keeps an exponentially-weighted moving average — recent terrain matters, ancient history fades.

E[g2]t = β · E[g2]t−1 + (1−β) · (∇L)2
decaying average of squared gradients (β ≈ 0.9–0.99)
θt+1 = θt − η / √(E[g2]t + ε) · ∇L
effective rate stays bounded — it never crashes to zero

The difference is dramatic. Watch the effective learning rate as training goes on:

eff. LR step 1 100 1000 RMSProp — stable AdaGrad — dying
🔁
Born in a lecture

Hinton introduced RMSProp in a 2012 Coursera class and never formally published it. It became the go-to for RNNs and reinforcement learning, where gradients swing wildly.

Section 07

Adam — Best of Both Worlds

Adam (Adaptive Moment Estimation) fuses the two great ideas: momentum (a running average of the gradient) and RMSProp's per-parameter scaling (a running average of the squared gradient).

gradient∇L 1st moment mmomentum (mean) 2nd moment vadaptive scale (var) updateθ step
The default optimizer of modern deep learning

Momentum decides which way to go; the second moment decides how big each parameter's step should be. Together they converge fast on almost any architecture with little tuning.

Section 08

Adam in Four Steps

The complete update per iteration, with defaults β1=0.9, β2=0.999, η=3e−4, ε=1e−8:

StepFormulaWhat it does
1 — First momentmt = β1mt−1 + (1−β1)∇Lrunning mean (momentum)
2 — Second momentvt = β2vt−1 + (1−β2)(∇L)2running mean of squares
3 — Bias correctiont = mt/(1−β1t) , v̂t = vt/(1−β2t)fix the cold start
4 — Updateθt+1 = θt − η · m̂t / (√v̂t + ε)the actual step
🧊
Why bias correction exists

m and v both start at zero, so early estimates are biased toward zero — the optimizer would tiptoe for the first few steps. Dividing by (1−βt) rescales them so the very first step is already full-sized.

Section 09

Bias Correction, Concretely

Take the very first step with β1=0.9 and a gradient g1=0.5. Without correction the momentum estimate is ten times too small:

1
Raw first moment: m1 = 0.9·0 + 0.1·0.5 = 0.05 — badly underestimates the true gradient of 0.5.
2
Correction factor at t=1: 1 − β11 = 1 − 0.9 = 0.1.
3
Corrected: m̂1 = 0.05 / 0.1 = 0.5 ✓ — exactly the real gradient. Full-speed from step one.
4
By t=100, β1100 ≈ 0, so the factor ≈ 1.000003 — correction quietly switches itself off.
🎯
Self-calibrating

The correction is huge exactly when it's needed (the start) and vanishes exactly when it isn't (later). No tuning, no warm-up hack — it just works.

Section 10

Always Reach for AdamW

Plain Adam(weight_decay=...) mixes weight decay into the gradient, where the adaptive scaling then distorts it. AdamW decouples weight decay — applying it directly to the weights — which is what regularization was always supposed to do.

Avoid Adam + L2

Decay is scaled by the per-parameter learning rate, so heavily-updated weights are barely regularized. The regularization strength becomes tangled with the gradient magnitude.

Use AdamW

Weight decay is applied separately and uniformly. Cleaner generalization, and the reason it's the exclusive choice for training modern transformers.

🤖
What the big models use

GPT, BERT, T5 and essentially every large transformer are trained with AdamW — typically lr=3e-4, weight_decay=0.01, plus a warm-up schedule.

Section 11

Five Traps in the Landscape

Optimizers exist because the terrain fights back. These are the five hazards every training run must survive:

🕳️
Local Minima
A valley that isn't the deepest. Plain SGD can settle here; momentum and noise help escape.
🐴
Saddle Points
Down in one direction, up in another, flat at the centre. Gradients vanish and progress stalls.
🏜️
Plateaus
Vast near-flat regions with tiny gradients. Without momentum the optimizer barely moves.
🏞️
Ravines
Steep across, gentle along. Raw SGD oscillates off the walls instead of flowing down.
📐
Ill-conditioning
Curvature wildly different by direction. Per-parameter rates (Adam) are the cure.
🧗
The Job
A good optimizer keeps moving through all five — that's the whole design goal.
Section 12

The Optimizer Scorecard

Four workhorses, side by side. There is no universal winner — only the right tool for the terrain.

PropertySGDAdaGradRMSPropAdam
Adaptive LRNoYesYesYes
MomentumOptionalNoOptionalBuilt-in
LR stabilityFixed↓ to 0BoundedBounded
Extra memory01 array1 array2 arrays
Bias correctionNoNoNoYes
Best forVisionSparse NLPRNN / RLDefault
GeneralizationBestGoodGoodSometimes worse
⚖️
Adam is fastest, SGD often generalizes best

Adam converges quickly but can land in sharp minima; well-tuned SGD+momentum finds flatter ones that transfer better — which is why vision leaderboards still favour it.

Section 13

How They Converge

A typical training run: Adam plunges early, RMSProp tracks close behind, and SGD is slower but often settles to a lower final loss given enough epochs and a schedule.

loss epochs → Adam — fastest early RMSProp SGD+mom — lowest final
📉
Prototype with Adam, polish with SGD

A common recipe: start with Adam(3e-4) to get a model working fast, then, if every last point of accuracy matters, switch to tuned SGD+momentum with a learning-rate schedule.

Section 14

What to Use, When

Matching the optimizer to the task saves far more time than tweaking it blindly:

TaskRecommended setupWhy
Vision (CNNs)SGD(lr=0.1, momentum=0.9) + CosineAnnealingLRflatter minima, best generalization
NLP / TransformersAdamW(lr=3e-4, weight_decay=0.01) + warmupthe field-wide standard
RNNs / LSTMsRMSProp(lr=1e-3) + clip_grad_norm(1.0)tames exploding gradients
Reinforcement learningRMSProp(lr=2.5e-4) or Adam(3e-4)adapts to non-stationary rewards
Sparse featuresAdagrad(lr=0.05) or Adambig updates for rare inputs
💻
One line to start almost anything

optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4) — a strong, forgiving default for a first run on nearly any architecture.

Section 15

Eight Golden Rules

1
Start with Adam(3e-4) for fast prototyping on any architecture.
2
Prefer AdamW over Adam whenever you use weight decay.
3
The learning rate matters more than the optimizer — tune it first.
4
Always call optimizer.zero_grad() before loss.backward() — gradients accumulate by default.
5
Add a schedule (CosineAnnealingLR, OneCycleLR) — fixed rates are rarely optimal.
6
Clip gradients for RNNs: clip_grad_norm_(max_norm=1.0).
7
For the last few points of accuracy in vision, finish with SGD+momentum.
8
AdaGrad isn't obsolete — still ideal for sparse, shallow models.
Recap

The One-Screen Cheat Sheet

η
tune this before anything else
0.9
momentum β (and Adam β1)
3e-4
the “Karpathy” Adam LR
AdamW
default for transformers
🧠 Remember the lineage

GD → add momentum (memory of direction) → add adaptivity (AdaGrad) → fix the dying rate (RMSProp) → combine both (Adam) → fix decay (AdamW).

🎯 Pick in one breath

Vision → SGD+mom. Transformers → AdamW. RNN/RL → RMSProp. Sparse → AdaGrad. Unsure → Adam(3e-4).

🏔️
The whole idea in one line

An optimizer turns a blindfolded stumble downhill into a confident, adaptive descent — remembering where it's been and adjusting its stride to the ground beneath each parameter.

You have completed Introduction. View all sections →