Optimization: from gradient descent to Adam
How a model actually learns, and why the step size is everything
Everything before this lesson told you which way is downhill; this lesson is about how to walk. Gradient descent, its stochastic mini-batch version, momentum, and adaptive methods like Adam are the algorithms that train every model from linear regression (3.2 Linear regression) to frontier LLMs (8.1 The LLM lifecycle and model landscape). You will see exactly why the learning rate is the most important hyperparameter (4.5 Optimizers and learning-rate schedules, 4.8 Training dynamics and debugging), why narrow valleys make plain gradient descent zigzag, what momentum fixes, and what Adam's update equations actually compute.
You'll be able to
- Define the optimization problem, convexity, and the difference between local minima, global minima and saddle points
- Derive the stable step-size range for gradient descent on a quadratic and relate convergence speed to the condition number
- Explain stochastic gradient descent as an unbiased noisy estimate and reason about batch size
- Write and interpret the update equations of momentum, RMSProp, Adam and AdamW, including bias correction, and describe standard learning-rate schedules
Key ideas
- Convex losses have only global minima and provable convergence; deep nets are non-convex with many saddles, yet first-order methods work.
- On a quadratic with curvature a, GD converges iff η < 2/a; in many dimensions η < 2/λmax, while progress along the flattest direction scales with 1/κ — the zigzag of narrow valleys.
- SGD's mini-batch gradient is unbiased with variance ∝ 1/|B|; the noise costs accuracy but helps escape saddles and regularizes.
Show 5 more key ideas
- Momentum (v ← βv + g) builds speed along consistent directions (up to 1/(1−β)× the step) and cancels oscillations, improving κ to about √κ.
- Adam: m and v are EMAs of g and g²; bias-correct by 1 − βᵗ; step η m̂/(√v̂ + ε) is a per-parameter signal-to-noise ratio; defaults 0.9, 0.999, 1e−8.
- AdamW decouples weight decay from the adaptive step and is the default for transformers.
- Warmup then cosine decay is the standard schedule; the learning rate is the single most important hyperparameter.
- Lagrange multipliers (∇f = λ∇g) connect constraints to penalties: regularization is constrained optimization.
Suggested path through this lesson
The problem
Training means solving for a loss averaged over data. A point is a local minimum if no small move decreases and a global minimum if nothing anywhere does. A function is convex if the line segment between any two points on its graph lies above the graph — equivalently, by 1.5 Multivariable and matrix calculus, its Hessian is positive semidefinite everywhere — and for convex functions every local minimum is global, gradient descent provably converges, and the models of Phase 3 (linear and logistic regression, SVMs) are all convex. Deep networks are not: their landscapes have many minima and vast numbers of saddle points. Remarkably, it does not matter much; the surprising empirical fact is that first-order methods find excellent minima anyway, and 4.5 Optimizers and learning-rate schedules and 4.7 Regularization in deep nets explore why.
Gradient descent and the step size
The basic update is , with learning rate . To see what does, take the one-dimensional quadratic with curvature . Then and
The iterates converge if and only if , that is, . For they slide smoothly to zero; for they overshoot and oscillate with shrinking amplitude; at they land exactly in one step (Newton's method); beyond they diverge. In many dimensions the quadratic decouples along the Hessian's eigenvectors (1.3 Eigen-things, SVD and low rank), each with its own curvature : the stable range is set by the largest curvature, , but convergence along the smallest is then governed by . The ratio — the condition number — determines the number of steps: a loss shaped like a long narrow valley forces tiny steps along the valley floor while bouncing between its walls. This is the zigzag you see in the demo. For a general smooth loss whose gradient changes at rate at most (an "-smooth" function), guarantees the loss decreases at every step.
Intuition. The learning rate is a bet about curvature. Too small and you crawl; too large and you overshoot the walls of the steepest direction. Everything after this section is a way to make that bet smarter.
Stochastic gradient descent
The full gradient costs a pass over the entire dataset. Stochastic gradient descent uses a random mini-batch instead:
The estimate is unbiased, so on average each step points downhill, and its noise shrinks with batch size (the sample-mean variance of 1.8 Statistics essentials). One pass over the data is an epoch. The noise is a feature as well as a cost: it helps escape saddles and poor minima and acts as an implicit regularizer (4.7 Regularization in deep nets). Larger batches give cleaner gradients and better hardware utilization but fewer updates per epoch, so the learning rate is usually raised with the batch size (4.5 Optimizers and learning-rate schedules).
Momentum and Nesterov acceleration
Plain gradient descent forgets the past at every step. Momentum keeps a running velocity,
with . Along a consistent downhill direction the velocity builds up to — an effective step ten times larger — while in a direction where the gradient flips sign every step the contributions cancel. Momentum therefore accelerates along the valley floor and damps the wall-to-wall oscillation, improving the dependence on the condition number from to roughly steps. Nesterov momentum evaluates the gradient at the look-ahead point , which corrects the velocity a step earlier and is slightly more stable.
Adaptive methods: AdaGrad, RMSProp, Adam and AdamW
Different parameters see different gradient scales — embeddings for rare tokens get tiny, infrequent gradients; biases get large ones. Adaptive methods give each parameter its own step size by normalizing with a running estimate of its gradient magnitude. AdaGrad accumulates and steps ; because only grows, its steps shrink to nothing. RMSProp fixes that with an exponential moving average, . Adam combines RMSProp with momentum and corrects both moving averages for their start at zero:
with defaults , , . The update is a signal-to-noise ratio: the mean gradient divided by its root-mean-square, so each parameter moves at a scale set by regardless of how large or small its raw gradients are.
Math check (bias correction). Unrolling, . If the gradients have a stationary mean , then by the geometric series. Dividing by makes the estimate unbiased; the same argument gives for . Without it, early steps would be far too small for and the ratio far too large.
AdamW separates weight decay from the gradient: . Adding an term to the loss instead would get divided by and shrink for parameters with large gradients — not what you want from regularization. AdamW is the default optimizer for transformers (4.5 Optimizers and learning-rate schedules, 7.8 Build GPT from scratch (nanoGPT walkthrough)).
Learning-rate schedules
Even the right should change over training. Warmup — increasing linearly from near zero over the first few hundred or thousand steps — prevents the huge early updates that occur while Adam's second-moment estimate is still unreliable and the loss landscape is at its steepest. Afterwards a cosine decay
shrinks the step to let the iterates settle into a minimum; step decays and the one-cycle policy are alternatives. Fine-tuning uses small (around for full fine-tuning, for LoRA, 8.2 Fine-tuning and PEFT); pretraining from scratch uses larger values with long warmup. The learning-rate range test of 4.8 Training dynamics and debugging finds the useful range empirically.
Constrained optimization and Lagrange multipliers
To minimize subject to , note that at an optimum the gradient of must be perpendicular to the constraint surface — otherwise you could slide along the constraint and improve. That is, for some Lagrange multiplier , which you find by solving the stationarity conditions of the Lagrangian . Inequality constraints add sign conditions (the KKT conditions). Two places this matters on the path: the SVM's dual problem (3.10 Support vector machines and kernels) is built from the Lagrangian of the margin constraints, and a norm penalty in a loss is the Lagrangian form of the constraint — regularization is constrained optimization (3.6 Regularization and generalization). The maximum-entropy characterization of the Gaussian in 1.6 Probability I: random variables and distributions is also a Lagrangian calculation.
Worked example: a narrow valley
Take : curvatures and , condition number . Gradient descent needs . With , starting at : is multiplied by each step (overshoot and oscillate) and by , so after 10 steps and — both directions crawl, for opposite reasons. With , converges fast () but barely moves (). Momentum with at reaches the same accuracy in a few steps. Run exactly this in the demo; then switch to Adam and notice that it moves both coordinates at similar speed because it normalizes each by its own gradient scale.
Where this shows up later
- Fitting linear and logistic regression by gradient descent — 3.2 Linear regression, 3.3 Logistic regression and softmax classification; the SVM dual — 3.10 Support vector machines and kernels; regularization as a constraint — 3.6 Regularization and generalization.
- Optimizers, schedules, warmup, gradient clipping and batch-size scaling in practice — 4.5 Optimizers and learning-rate schedules; diagnosing learning-rate problems — 4.8 Training dynamics and debugging; implicit regularization of SGD — 4.7 Regularization in deep nets.
- Pretraining and fine-tuning recipes — 7.8 Build GPT from scratch (nanoGPT walkthrough), 8.2 Fine-tuning and PEFT; policy-gradient optimization in RL — 4.11 Reinforcement learning essentials.
Common pitfalls (4)
- Using the same learning rate for SGD and Adam; Adam's normalized step means its good learning rates are typically 10–100× smaller.
- Skipping warmup with Adam on a transformer and watching the loss spike in the first few hundred steps.
- Implementing weight decay as an ℓ₂ loss term under Adam (which weakens it for large-gradient parameters) instead of AdamW's decoupled form.
- Blaming the model when the loss plateaus; the learning rate or schedule is the first suspect.
Recap: all 8 key points
- Convex losses have only global minima and provable convergence; deep nets are non-convex with many saddles, yet first-order methods work.
- On a quadratic with curvature a, GD converges iff η < 2/a; in many dimensions η < 2/λmax, while progress along the flattest direction scales with 1/κ — the zigzag of narrow valleys.
- SGD's mini-batch gradient is unbiased with variance ∝ 1/|B|; the noise costs accuracy but helps escape saddles and regularizes.
- Momentum (v ← βv + g) builds speed along consistent directions (up to 1/(1−β)× the step) and cancels oscillations, improving κ to about √κ.
- Adam: m and v are EMAs of g and g²; bias-correct by 1 − βᵗ; step η m̂/(√v̂ + ε) is a per-parameter signal-to-noise ratio; defaults 0.9, 0.999, 1e−8.
- AdamW decouples weight decay from the adaptive step and is the default for transformers.
- Warmup then cosine decay is the standard schedule; the learning rate is the single most important hyperparameter.
- Lagrange multipliers (∇f = λ∇g) connect constraints to penalties: regularization is constrained optimization.
Watch
The loss landscape picture and why the gradient is the direction to move.
Read
Try it live
Interactive demo
runs in your browserExercises
- By hand: the stability boundary
For , find the largest stable learning rate, then compute 5 steps of gradient descent from at and at . Expected: stable range ; at , oscillates with factor while shrinks by per step; at the roles reverse.
- NumPy: implement four optimizers
Write GD, momentum, RMSProp and Adam as functions that take a gradient function and return the trajectory. Run all four on the narrow valley above and on the Rosenbrock function from , and plot the paths over contour lines. Expected: GD zigzags, momentum overshoots then settles, Adam takes evenly sized steps; on Rosenbrock all need thousands of steps, and the learning rate that works for Adam (around ) is far smaller than for GD.
- Experiment: warmup and cosine schedules
Implement a schedule function (linear warmup over 100 steps to , cosine decay to over 1000 steps) and plot it. Then train a tiny NumPy logistic-regression model on a toy dataset with Adam with and without warmup, logging the loss. Expected: the scheduled run has a smoother early loss curve and ends at a lower loss.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →