Step 6 of 6
Optimization & loss landscapes
Gradient descent, learning rates, convexity, saddle points, and momentum - the optimization ideas that make training work (or not).
14 min read
Knowing the gradient tells you which way is downhill. But getting to the bottom - quickly, reliably, and without overshooting - requires understanding the shape of the landscape you're traversing.
Gradient descent: the simplest optimizer#
The update rule is deceptively simple: compute the gradient of the loss with respect to every parameter, then step in the opposite direction:
Vanilla gradient descent: subtract the gradient, scaled by the learning rate η.
In practice, stochastic gradient descent (SGD) estimates the gradient from a random mini-batch rather than the full dataset. This is faster per step, introduces helpful noise (which can escape shallow local minima), and scales to datasets that don't fit in memory.
- Mini-batch
- A small random subset of the training data used to estimate the gradient at each step - balances speed and gradient quality.
- Hyperparameter
- A setting chosen before training begins (like learning rate or batch size) rather than learned from data - tuning these is a major part of ML practice.
- Local minimum
- A point where the loss is lower than all nearby points but not necessarily the global lowest - gradient descent can get trapped here.
- 01Sample a mini-batch from the training data
- 02Forward pass: compute predictions and loss
- 03Backward pass: compute gradients via backprop
- 04Update: w ← w − η · ∇L
- 05Repeat until convergence
Learning rate: the most important hyperparameter#
The learning rate η controls step size. Get it wrong and everything breaks:
| Learning rate | Behavior |
|---|---|
| Too large | Loss oscillates or diverges - you overshoot the minimum |
| Too small | Training is painfully slow - you barely move |
| Just right | Smooth convergence to a good minimum |
| Decaying schedule | Start fast, slow down as you approach the minimum |
Learning rate schedules reduce η over time. Common choices: step decay (halve every N epochs), cosine annealing (smooth cosine curve from η_max to η_min), and warmup + decay (ramp up from near-zero, then decay - standard for transformers).
Convexity: when the landscape is kind#
A function is convex if the line segment between any two points lies above the function - it's shaped like a bowl. Convex problems have a single global minimum, and gradient descent is guaranteed to find it.
Linear regression, logistic regression, and SVMs have convex loss functions. Neural networks do not - their loss surfaces are highly non-convex, with many local minima, saddle points, and flat regions.
A function f is convex if for all x, y and 0 ≤ t ≤ 1: f(tx + (1−t)y) ≤ t·f(x) + (1−t)·f(y).
In ML: despite non-convexity, large neural networks often converge well. Research suggests this is because most local minima in high-dimensional spaces have similar loss values - the real obstacle is saddle points, not bad minima.
Saddle points: the real enemy#
In high dimensions, saddle points vastly outnumber local minima. A saddle point has zero gradient (the optimizer gets stuck) but is a minimum in some directions and a maximum in others - like the center of a horse saddle.
SGD's mini-batch noise helps escape saddle points: the random perturbations push the optimizer away from unstable equilibria. Second-order methods (which use curvature information) can detect saddle points by looking at negative eigenvalues of the Hessian - but they're too expensive for large models.
Momentum: remembering where you've been#
Momentum adds a fraction of the previous update to the current one, like a ball rolling downhill that accumulates velocity:
Momentum: v accumulates a running average of past gradients. The update moves in the direction of accumulated momentum, not just the current gradient.
This accelerates convergence in consistent gradient directions and dampens oscillation in noisy directions. The hyperparameter β (typically 0.9) controls how much history to keep.
Adam: the default optimizer#
Adam (Adaptive Moment Estimation) combines momentum with per-parameter adaptive learning rates. It maintains two running averages: the first moment (mean of gradients, like momentum) and the second moment (mean of squared gradients, like RMSProp):
Adam: m tracks the gradient direction, v tracks the gradient magnitude. Each parameter gets its own effective learning rate: η/√v.
Parameters with consistently large gradients get smaller effective learning rates (they're already moving fast). Parameters with small, noisy gradients get larger effective rates (they need more push). This is why Adam works well on problems with sparse gradients and ill-conditioned curvature.
Weight decay and AdamW#
Weight decay shrinks weights toward zero at each step, acting as a regularizer:
AdamW: apply weight decay directly to the weights, separately from the gradient. This is the correct formulation - not L2 regularization in the loss.
AdamW decouples weight decay from the gradient update. This matters: L2 regularization added to the loss interacts badly with Adam's adaptive rates (the regularization gradient gets scaled down for parameters with large second moments, defeating its purpose). AdamW is the standard optimizer for modern transformer training.
- AdamW
- A corrected version of Adam that applies weight decay directly to the weights instead of through the loss - the standard optimizer for training transformers.
- Weight decay
- Shrinks weights toward zero at each step, preventing any single weight from growing too large - acts as a regularizer that keeps models simpler.
- First moment / Second moment
- In Adam: the first moment tracks the average gradient direction (momentum), the second moment tracks average gradient magnitude - together they adapt the learning rate per parameter.
Where it shows up in ML#
SGD + momentum for vision
ResNets, ConvNets, and many vision models train with SGD, momentum β = 0.9, and a cosine learning rate schedule.
AdamW for transformers
LLMs, BERT, GPT, and most transformer models train with AdamW, warmup + cosine decay, and weight decay ~0.01-0.1.
Learning rate warmup
Ramp from near-zero to peak learning rate over the first ~1% of training to stabilize Adam's moment estimates.
Gradient clipping prevents explosions
Cap the gradient norm before the update: if ‖∇L‖ > threshold, scale ∇L down. Essential for training RNNs and some transformers.