Chapter 16: Optimization
Training a model means minimizing an average loss using noisy gradients. Everything an optimizer does answers one of three questions. Which direction should the step go? That is the gradient, smoothed by momentum. How far should it go in each coordinate? That is the learning rate, which Adam scales per parameter. How should the step size change over time? That is the schedule. Convex theory gives the vocabulary and the convergence rates. Neural networks break its assumptions, but its intuitions survive, and the tools in this chapter are the ones every model in the series trains with.
Concepts from other sections (20)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay
- Bias correction: dividing and by and to undo the zero initialization. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay
- Decoupled weight decay: shrinking the weights outside the gradient path, as in SGDW and AdamW. Read more: 16.2 The Optimizer protocol: SGD, momentum, Nesterov, weight decay
- Regularization: penalizing model complexity to trade bias for lower variance. Read more: Chapter 1: Statistical Learning in AI Engineering
- Learning-rate schedule: a function from the step number to the learning rate. Read more: 16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping
- Gradient clipping: rescaling all gradients by one factor when their global norm exceeds a limit. Read more: 16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping
- Backtracking line search: trying until the Armijo condition holds. Read more: 16.1 Convexity, smoothness, gradient descent, and Armijo line search
- Nesterov momentum: momentum with a look-ahead, stepping along . Read more: 16.2 The Optimizer protocol: SGD, momentum, Nesterov, weight decay
- Coupled weight decay: adding to the gradient before the momentum buffer; the gradient of an L2 penalty. Read more: 16.2 The Optimizer protocol: SGD, momentum, Nesterov, weight decay
- Warmup-stable-decay (WSD): warmup, a long constant phase at the peak, and a short final decay. Read more: 16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping
- Noam schedule: , linear rise then inverse-square-root decay. Read more: 16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping
- DPO: minimizing over preference pairs, equivalent to fitting the KL-regularized reward objective. Read more: 18.2 Direct preference optimization and IPO in AI Engineering
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Eigenvector / eigenvalue: a non-zero and scalar with . Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Geometric series: , with partial sum and limit for . Read more: 8.2 Series convergence, the EMA as a geometric series, and bias correction
- Pure function: a function whose output depends only on its inputs and which mutates nothing. Read more: Chapter 4: Coding and Design Patterns in Software Engineering
- Power iteration: repeated multiplication and normalization, converging to the dominant eigenvector. Read more: 9.4 Eigenvalues, power iteration, and the spectral radius
- Hessian-vector product: , the derivative of the gradient along , computed without forming . Read more: 14.4 Hessian-vector products and the recompute-versus-memory schedule
- Probability density function (PDF): for a continuous random variable, a function that integrates to 1, with ; a density value is not itself a probability. Read more: Chapter 13: Probability and Statistics
The chapter starts with plain gradient descent, where the theory is exact: on a quadratic, the step must stay under , and the number of steps grows with the condition number . The gap shrinks by about per step. Next it wraps that update behind a common Optimizer protocol and adds momentum, Nesterov, and weight decay. Then it builds Adam and AdamW, where bias correction fixes the first steps and decoupled weight decay keeps regularization out of the adaptive scale. Last come learning-rate schedules and gradient clipping, which often decide whether a run trains at all. Two problem sets check the derivations by hand. The second one also covers Lagrangians, duality, and the KL-regularized objective behind direct preference optimization.
Optimizers are stateful objects, and that fact runs through the whole chapter. To resume a run bit for bit, the checkpoint must hold the moments, the step count, and the position in the schedule. Each implementation is checked against PyTorch’s trajectory, so recipes written for PyTorch carry over unchanged.
Learning objectives
- Derive the stability limit and the rate of gradient descent, and use a backtracking line search when is unknown.
- Implement SGD with momentum, Nesterov momentum, and coupled weight decay behind a resumable
Optimizerprotocol.- Implement Adam and AdamW with bias correction and decoupled weight decay, and match PyTorch step for step.
- Build cosine, warmup-stable-decay, and Noam schedules and global-norm gradient clipping, with correct phase boundaries.
- Solve KKT, duality, and KL-regularized problems by hand, including the derivation behind DPO.
Before you begin
Section titled “Before you begin”You should be comfortable with gradients and Hessians from Calculus 3, eigenvalues from Linear Algebra, and geometric series from Precalculus, which explain both bias correction and warmup schedules. The gradients these optimizers consume come from Matrix Calculus and Autodiff. Its section Hessian-vector products and the recompute-versus-memory schedule supplies the curvature tools for going beyond first-order methods.
In this chapter
Section titled “In this chapter”- Convexity, smoothness, gradient descent, and Armijo line search derives the step-size limit and the rate, then builds gradient descent and a backtracking line search that handle divergence and NaN correctly.
- The Optimizer protocol: SGD, momentum, Nesterov, weight decay defines the four-method interface every optimizer shares and builds a PyTorch-compatible SGD that resumes bit for bit.
- Adam and AdamW: bias correction and decoupled weight decay derives Adam’s two moving averages, the bias correction, and why weight decay must be decoupled, then implements both to match torch exactly.
- Learning-rate schedules (cosine, WSD, Noam) and gradient clipping builds three schedules as pure functions of the step, along with global-norm clipping that keeps the update direction.
- Optimization problem set, part a: convexity, GD rates, momentum, Adam has 17 problems with worked answers on convexity, gradient descent rates, momentum, and Adam.
- Optimization problem set, part b: constrained optimization, duality, and DPO has 18 optional problems on KKT conditions, duality, and the KL-regularized optimum that DPO relies on.
Where this chapter leads
Section titled “Where this chapter leads”In AI Engineering, Training loop and the autograd bigram trains with these optimizers, and every later model in that book does too. Training and Post-Training in AI Engineering covers optimizer memory and large-scale training practice. Beyond this chapter, the same ideas extend to curvature. The top Hessian eigenvalue can be found by power iteration on Hessian-vector products, and gradient descent stays stable only while , which is the edge of stability. Muon orthogonalizes the momentum of 2D weights with Newton-Schulz iterations.
Further reading
Section titled “Further reading”- Boyd and Vandenberghe, Convex Optimization (free PDF), chapters 2, 3, and 9 for convexity and descent methods; Nocedal and Wright, Numerical Optimization (Springer, 2nd ed.).
- Kingma and Ba, Adam, and Loshchilov and Hutter, Decoupled Weight Decay Regularization, both worth reading in full.
- Goh, Why Momentum Really Works. It pairs well with plotting every optimizer on a 2D ill-conditioned quadratic before you trust it on a network.
- Cohen et al., Gradient Descent on Neural Networks Typically Occurs at the Edge of Stability.
- Jordan, Muon.