Optimization
Training a model means finding the parameters that make a loss small. This module is about how that search works: rolling downhill with gradient descent , choosing the step size, adding momentum, adapting per-parameter step sizes with Adam, and the geometry (convexity, saddle points, constraints, curvature) that decides when it's easy and when it's hard. Every chapter has a figure where you can watch an optimizer move.
How to use this module
- Watch, then play. Chapters link to the best videos on each idea. Watch, then come back and drag the figure until it feels obvious.
- Questions get harder as you go: Warm-up Practice Think Challenge. Pick one answer, press Check answer, and the worked solution opens.
- Code it: Python runs in your browser and is graded by test cases. The first run downloads Python (internet needed once).
- Your progress is saved in this browser. Tick "mark as done" at the end of each chapter.
What optimization is: losses and loss landscapes
Watch: What Is Mathematical Optimization? (Visually Explained) Watch: Gradient descent, how neural networks learn (3Blue1Brown)A model has knobs (its parameters). A loss function turns "how wrong is the model on the data?" into one number. Training means turning the knobs to make that number as small as possible, and you can picture it as walking around a landscape looking for the lowest valley.
Every model in machine learning, from a straight line to a language model, has the same three ingredients:
- Parameters (theta): the numbers the model is allowed to change. A line has two, and . GPT-style models have billions.
- Data: examples of inputs and the answers we want.
- A loss function : a single number that is small when the model's predictions match the answers and big when they don't.
The most common loss for predicting numbers is the mean squared error (MSE):
Each term is one error, squared. Squaring does two jobs: it makes every error count as positive (so a +2 miss and a −2 miss don't cancel), and it punishes big misses much more than small ones. For yes/no questions we'll later use other losses (like cross-entropy), but the story is the same: one number that measures badness.
Now the key picture. Fix the data. Then the loss depends only on the parameters. For the line, every choice of is a point on a flat map, and the loss at that point is a height. Plot the height over the whole map and you get a surface: the loss landscape. Training is the search for its lowest point.
Two words you'll see constantly:
- The minimum value is the lowest height, .
- The minimizer is where that happens, written . For a model, the minimizer is what you actually want: it's the trained weights.
A global minimum is lower than every other point. A local minimum is only lower than its neighbours: a dip in the terrain that isn't the deepest valley. Simple losses like the one above have a single bowl-shaped valley. Neural network landscapes are much bumpier, and chapters 7 and 8 are about what that means.
With two parameters we can draw the landscape as a contour map, like a hiking map: each curve joins points of equal loss, and darker shading means lower loss. With a million parameters we can't draw it, but the same words (valleys, slopes, flat regions, saddle points) still describe what an optimizer runs into.
Why not just solve it?
For the line, you can solve for the minimizer with algebra (set the derivatives to zero; that's least squares). For almost every interesting model there's no formula. What we can always do is stand at one point, measure the slope of the landscape there, and take a step downhill. Do that thousands of times and you've trained a model. The whole module is about doing that well.
Worked exampleThe landscape of a one-parameter model
Fit (no intercept) to two points, and . The loss is
- At : .
- At : .
- Expanding, , a parabola (a 1D bowl). Its lowest point is where the slope is zero: .
- At : . So the minimizer is and the minimum value is (not zero: no line through the origin hits both points).
Watch outCommon misconceptions
- "The landscape is drawn over the data." No: it's drawn over the parameters. The data is fixed and baked into the shape of the surface. A different dataset gives a different landscape.
- "A loss of zero is the goal." Zero training loss usually means the model memorised the data, noise included. What we really care about is loss on new data; chapter 9 (regularization) is one way of steering toward that.
- "Minimum and minimizer are the same thing." The minimum is a height (0.1 above); the minimizer is a location (). Training returns the location.
- "More parameters means a harder landscape to search." Not necessarily. Very large networks often have landscapes where many directions lead downhill, which is part of why they train well.
In ML & deep learningWhere this shows up
Every training loop you'll ever write has the shape "compute the loss on some data, compute how it changes with each parameter, nudge the parameters". In PyTorch that's loss = loss_fn(model(x), y); loss.backward(); optimizer.step(). The model defines the landscape, the loss defines the height, and the optimizer (SGD, Adam, …) decides how to walk. Choosing the loss is a modelling decision: MSE for numbers, cross-entropy for classes, and many others (Huber, contrastive, …) shape the landscape differently.
Practice (pick one answer per question)
In machine learning, what is a loss function?
- A single number measuring how badly the model's predictions match the data, as a function of the parameters
- The list of training examples the model got wrong
- The amount by which each parameter changes in one training step
- The model's prediction for a new input
The loss takes the parameters (with the data held fixed) and returns one number: small for good fits, big for bad ones. Training minimizes it.
A model predicts for two examples whose true answers are . What is the mean squared error?
- 0.5
- 1
- 0.25
- 2
Errors are and . Squared: 1 and 0. Mean: . (Forgetting to divide by gives 1.)
For , what is ?
- 3
- 1
- 0
- −3
The squared term is smallest (zero) at , so the minimizer is . The minimum value is , which is the tempting wrong answer.
Minimize . Where is the minimizer?
, so . In general, the number that minimizes a sum of squared distances to some points is their average.
A model is . How many coordinates does a single point of its loss landscape's map (its parameter space) have?
- 4
- 3
- 5
- 1
The map is the space of parameters: , so 4 numbers. The landscape (map plus height) would need a 5th axis for the loss, which is why we can't draw it and rely on 2D slices instead.
Why do we square the errors instead of just adding them up, ?
- Without squaring, positive and negative errors cancel, so a terrible model could score 0
- Squaring makes the loss smaller, so training is faster
- Squared errors are always less than 1
- Adding raw errors gives a loss that can't be differentiated
Predictions that are 5 too high on one example and 5 too low on another would sum to 0. Squaring makes every error count, and it also makes big misses count extra. (The plain sum is perfectly differentiable; it's just useless as a measure of badness.)
You must predict one constant for every example, and the targets are . Which minimizes the mean absolute error ? (Compare with what MSE would choose.)
- 2 (the median), while MSE would pick 4 (the mean)
- 4 (the mean), the same as MSE
- 9, the largest target
- 5, halfway between the smallest and largest
MAE at : . At : . Moving away from the median increases the distance to more points than it decreases, so the median wins. MSE is minimized by the mean, . The choice of loss changes the answer: MAE is less pulled by the outlier 9.
Code it (optional: real Python runs in your browser and is graded by test cases)
Gradient descent: walk downhill, repeat
Watch: Gradient descent, how neural networks learn (3Blue1Brown) Watch: Gradient Descent, Step-by-Step (StatQuest)The gradient points in the direction where climbs fastest. Gradient descent takes a small step the opposite way, , and repeats until the ground is flat.
Imagine standing on a foggy hillside. You can't see the valley, but you can feel which way the ground slopes under your feet. A sensible plan: step a little in the steepest downhill direction, feel again, step again. That's gradient descent.
The gradient
For a function of several variables, , the gradient is the vector of partial derivatives:
Each entry says how fast changes if you nudge just that one coordinate. Together they make an arrow on the map with two key properties:
- it points in the direction of steepest ascent, and
- its length is how steep that climb is. At the bottom of a valley (or any flat spot) the gradient is the zero vector.
Why steepest? Zoom in far enough and any smooth function looks like a tilted plane. Moving by a small vector changes it by about
The dot product is biggest when points along and most negative when it points exactly the other way (). So among all steps of a given length, decreases the most. It's also perpendicular to the contour lines: walking along a contour keeps constant, so the gradient has no component along it.
The algorithm
Pick a start and a learning rate (step size) . Then repeat
Stop when the gradient is tiny, the loss stops improving, or you run out of time. Notice the step is times the gradient, so steps automatically shrink as the ground flattens out near a minimum. Run the figure and you'll see big strides on steep slopes and tiny shuffles at the bottom.
Worked exampleTwo steps by hand
Minimize from with . The gradient is .
- Step 1. . New point: . The loss falls from to .
- Step 2. . New point: , with .
Notice shrinks much faster than (by 0.4× per step versus 0.8×), because the bowl is steeper in . That imbalance is exactly what chapter 3 analyses.
Watch outCommon misconceptions
- "The gradient points toward the minimum." It points in the steepest local direction, perpendicular to the contour. In a long, tilted valley that can be almost sideways to the direction of the minimum.
- "Gradient descent finds the global minimum." It finds a point where the gradient is zero, usually the bottom of whichever valley you started in (try different starts in the figure).
- "The step length is ." The step is . The learning rate is a multiplier, not a distance.
- "Add the gradient to go downhill." The sign matters: is uphill. Getting it wrong is a classic bug; the loss climbs instead of falling.
In ML & deep learningWhere this shows up
Backpropagation (the algorithm behind loss.backward()) is just an efficient way to compute for a neural network: one backward pass gives the partial derivative for every one of millions of weights. The optimizer then applies the update , or a smarter variant from chapters 4–6. Every modern network, from image classifiers to large language models, is trained by some form of this one-line rule.
Practice (pick one answer per question)
What is the gradient of at ?
. Using instead of gives ; is the function value, not a derivative.
Gradient descent moves the parameters…
- in the direction of , the steepest downhill direction
- in the direction of
- straight toward the global minimum
- along the contour line through the current point
is steepest ascent, so we go the opposite way. Moving along a contour keeps the loss constant, and GD has no idea where the global minimum is.
Minimize from with learning rate . What is ?
- 2.4
- 2.7
- 3.6
- 2.9
, so . (2.7 forgets the factor 2 in ; 3.6 adds the gradient.)
Minimize from with . Where are you after one step?
, so . forgets the factors of 2; steps uphill.
At some point . Using the linear approximation , by about how much does a gradient step with lower ?
- 0.25
- 0.05
- 0.07
- 2.5
The step is , so . In general one small step lowers by about . (0.05 uses instead of its square.)
Gradient descent lands exactly on a point where . What happens next, and what kind of point is it?
- It stays put forever; the point could be a minimum, a maximum or a saddle point
- It stays put, and the point must be the global minimum
- It keeps moving because of the learning rate
- It stays put, and the point must be a local minimum
The update adds , so nothing moves. Zero gradient only says "flat": the top of a hill and the centre of a saddle are flat too (chapter 8). In practice noise (chapter 4) nudges you off maxima and saddles.
Minimize from with . What is ?
- 4.5
- 5
- 4
- 4.75
: each step halves the distance to 5. Distances: 4, 2, 1, 0.5, so . It never quite reaches 5 in finitely many steps.
Code it (optional: real Python runs in your browser and is graded by test cases)
Learning rates: too small, too big, and why eigenvalues decide
Watch: Normalizing Inputs (DeepLearning.AI, Andrew Ng) Watch: Eigenvectors and eigenvalues (3Blue1Brown)On a quadratic bowl, gradient descent shrinks the error along each eigenvector of the curvature matrix by a factor per step. It converges only if , and its speed is set by the ratio , the condition number.
The learning rate is the most important knob in training. Too small and you crawl. Too big and you bounce out of the valley. To see exactly where the boundaries are, study the one landscape we can solve completely: a quadratic bowl.
One dimension first
Take , a parabola with curvature . Its gradient is , so a gradient step is
Every step multiplies by the same number , so . Everything depends on :
- (): smooth, steady approach from one side. Tiny means is close to 1: very slow.
- (): one step lands exactly at the minimum.
- (): overshoots to the other side each time, but by less, so it still converges while zig-zagging.
- (): each overshoot is as big or bigger than the last. It diverges.
So the rule is: stable iff . Steeper curvature means a smaller safe step.
Many dimensions: the eigenvalues take over
A general quadratic bowl is with symmetric and positive definite (this is what any smooth loss looks like near a minimum). The gradient is , so
This is where linear algebra pays off. Write in the eigenvector basis of (eigenvalues ). In that basis just stretches each coordinate, so the update splits into independent 1D problems: the -th coordinate gets multiplied by each step. The eigenvalues are the curvatures along the eigen-directions.
- Stability needs every factor below 1 in size, so . The steepest direction sets the speed limit.
- Speed is set by the slowest factor. With capped by , the flattest direction () gets a factor near : painfully close to 1 if the bowl is long and thin.
The ratio is the condition number. The best single learning rate balances the two extreme directions so that they shrink equally fast: , giving a factor of per step. For (a round bowl) that's 0: one step. For it's : hundreds of steps. That zig-zag across a narrow valley while creeping along it is the signature of a badly conditioned problem.
Worked exampleA bowl with κ = 10
Let , so , , .
- Largest stable rate: .
- : factors along and along . is solved in one step, but only shrinks 10% per step: shrinking it 1000-fold takes steps.
- Best rate : factors and , equal in size. , and 1000-fold takes steps.
Notice the best rate deliberately makes the steep direction zig-zag (negative factor) to go faster in the flat one.
Watch outCommon misconceptions
- "A smaller learning rate is always safer, so just make it tiny." Safer, yes; but the slow direction then barely moves and you waste most of your compute.
- "Divergence means the gradient was computed wrong." Often the gradient is fine and is simply above somewhere along the path.
- "Zig-zagging means the learning rate is too big." Zig-zag with shrinking amplitude still converges; the best fixed rate actually zig-zags in the steepest direction.
- "Condition number is about the data size." It's about the shape of the bowl: how different the curvatures are in different directions.
In ML & deep learningWhere this shows up
Feature scaling is conditioning in disguise. If one input is measured in metres and another in millimetres, the loss is a thousand times steeper in one weight's direction than another, is huge, and gradient descent zig-zags. Normalizing inputs to mean 0 and variance 1 rounds out the bowl. Batch normalization, layer normalization and careful weight initialization do the same job inside a network. Momentum (chapter 5), Adam (chapter 6) and Newton's method (chapter 11) are different ways of fighting a large . And the usual practice of trying learning rates on a log scale (1e-4, 3e-4, 1e-3, …) comes from the fact that the useful range is bounded by , which you don't know in advance.
Practice (pick one answer per question)
Gradient descent on with . Each step multiplies by…
- 0.5
- 0.75
- 0.25
- −0.5
, so . The curvature is 2, not 1, which is why 0.75 is wrong.
Gradient descent on with . What happens?
- It diverges: each step multiplies by −1.4
- It converges, zig-zagging
- It converges in one step
- It converges slowly from one side
The factor is . Its size is above 1, so grows by 40% each step while flipping sign. The limit is .
What is the largest learning rate for which gradient descent converges on (i.e. the boundary value)?
- 0.5
- 1
- 0.25
- 2
, so we need . (Using the coefficient 2 instead of the curvature 4 gives the wrong answer 1.)
A quadratic loss has Hessian eigenvalues 2 and 50. What is its condition number?
- 25
- 48
- 100
- 52
. It's a ratio, not a difference.
For with , what is the largest stable learning rate (the boundary)?
- 0.5
- 1
- 0.4
The eigenvalues are : 4 and 2. Stability needs . Reading the diagonal entry 3 as the curvature gives , which would diverge along the eigenvector .
With Hessian eigenvalues 2 and 50 and the best fixed learning rate , by what factor does the error shrink per step (in the worst direction)?
- about 0.923
- about 0.96
- 0.5
- about 0.038
, and the factor is . Check: , so and . (0.038 is itself.)
For and , which direction limits the speed of convergence, and what is its per-step factor?
- The direction, factor 0.981
- The direction, factor 0.9
- The direction, factor −0.9
- Both equally, factor 0.95
Factors: and . The larger one, 0.981, is the bottleneck: the flat direction. That's typical: the rate is capped (here just under ) by the steep direction, so the flat one crawls.
Code it (optional: real Python runs in your browser and is graded by test cases)
Stochastic and mini-batch gradient descent
Watch: Mini Batch Gradient Descent (DeepLearning.AI, Andrew Ng) Watch: Understanding Mini-Batch Gradient Descent (DeepLearning.AI) Watch: Stochastic Gradient Descent, Clearly Explained (StatQuest)The loss is an average over all training examples, so its gradient is an average too. Instead of computing it exactly over millions of examples, estimate it from a small random mini-batch. The estimate is noisy but correct on average, and it's so much cheaper that you can take many more steps.
A training loss is almost always an average of per-example losses:
Computing the exact gradient means touching all examples, and can be billions of tokens or millions of images. One exact step could take hours. That's full-batch (or just "batch") gradient descent.
The mini-batch idea
Pick a random subset of examples (typically 32 to a few thousand) and use their average gradient instead:
This is like estimating an election result from a poll. Two facts make it work:
- It's unbiased: if the batch is chosen uniformly at random, the expected mini-batch gradient equals the true gradient. On average you're walking in the right direction.
- Its noise shrinks with batch size: if single-example gradients have variance , the average of independent ones has variance , so its standard deviation shrinks like . Quadrupling the batch only halves the noise.
That is the economic heart of it. A batch of 100 costs 100× less than a batch of 10,000 but is only 10× noisier. Early in training, when you're far from the minimum and the gradient is big, a rough direction is plenty, and taking 100 cheap steps beats taking one perfect one.
Vocabulary: is stochastic gradient descent (SGD) in the strict sense; is mini-batch GD; people loosely call all of it "SGD". One pass through the whole dataset is an epoch: with examples and batch size , that's steps. In practice you shuffle the data each epoch and walk through it in chunks, so every example is used once per epoch.
The noise floor, and why it isn't all bad
Noise has a cost: with a fixed learning rate, SGD doesn't converge to the exact minimum. Near the bottom the true gradient is tiny but the mini-batch noise isn't, so the parameters keep jittering in a small cloud whose size grows with and shrinks with . That's one reason learning rates are lowered late in training (chapter 12).
Noise also helps. It knocks the parameters off saddle points and out of sharp, narrow dips, and there's evidence that the flatter regions SGD tends to settle in generalize better to new data. Full-batch GD on a neural network is not just slower; it often ends up somewhere slightly worse.
Worked exampleA mini-batch gradient is right on average
A one-parameter model has 4 training examples whose gradients at the current are .
- The full gradient is their mean: .
- Shuffle into two mini-batches of 2, say and . Their gradients are and : both wrong, one too small, one too big.
- There are 6 possible pairs, with mini-batch gradients 0.5, 3, 2.5, 1.5, 1 and 3.5. Their average is , exactly the full gradient. Unbiased.
One epoch here is steps, and each step costs half as much as a full-batch step.
Watch outCommon misconceptions
- "SGD follows the true gradient, just faster." Each step follows a noisy estimate; only on average does it point the right way.
- "Bigger batches are always better." Bigger batches give cleaner gradients but fewer steps per epoch, and past a point (the "critical batch size") doubling the batch barely helps. They can also generalize a little worse.
- "Doubling the batch halves the noise." It divides the variance by 2, so the standard deviation drops only by .
- "An epoch is one step." An epoch is one full pass over the data, which is many steps.
In ML & deep learningWhere this shows up
Every deep network is trained on mini-batches: a PyTorch DataLoader(dataset, batch_size=64, shuffle=True) is exactly the "shuffle, then walk through in chunks" recipe above. Batch size is chosen mostly by GPU memory and throughput (GPUs process a batch of 256 nearly as fast as a batch of 32). When people scale up the batch they often scale up the learning rate in proportion (the "linear scaling rule"), usually with a warmup (chapter 12). Large language models use batches of millions of tokens, split across many GPUs whose gradients are averaged, which is just a very large mini-batch.
Practice (pick one answer per question)
A dataset has 50,000 examples and the batch size is 100. How many steps make one epoch?
- 500
- 100
- 5,000,000
- 50,000
One epoch uses every example once: steps.
Gradient descent that uses a batch of exactly one example per step is usually called…
- stochastic gradient descent
- full-batch gradient descent
- Newton's method
- momentum
Batch size 1 is the original "stochastic" gradient descent. Batch size is full-batch; anything in between is mini-batch.
Per-example gradients are (one parameter). What is the gradient from the mini-batch ?
- 5
- 10
- 4
- 2.5
A mini-batch gradient is the mean of its examples' gradients: . (The full gradient is 4, so this batch overshoots a bit.) Summing instead of averaging gives 10.
You raise the batch size from 16 to 64. How does the standard deviation of the mini-batch gradient change (independent samples)?
- It halves
- It drops to a quarter
- It doubles
- It stays the same
Variance scales like , so it drops by 4×; the standard deviation is its square root, so it drops by .
Why does SGD make progress even though each step uses a noisy gradient?
- A random mini-batch gradient is an unbiased estimate: on average it equals the true gradient
- The noise always points toward the minimum
- Mini-batch gradients are always smaller than the true gradient
- Each mini-batch has its own minimum, and these all coincide
The expected value of a uniformly random mini-batch gradient is the full gradient, so the errors average out over many steps. Individual batches can point quite wrong; and different batches generally do have different minima.
examples, batch size 32, and the last batch of each epoch may be smaller. How many steps per epoch?
- 32
- 31
- 31.25
- 33
: 31 full batches use 992 examples, and the remaining 8 form a 32nd, smaller batch. So . (A step count can't be fractional; with drop_last=True it would be 31.)
A model trains well with batch size 256 and learning rate 0.1. Using the linear scaling rule, what learning rate would you start from at batch size 1024?
- 0.4
- 0.2
- 0.025
- 0.1
A batch 4× bigger gives a gradient with 4× less variance, and one step at batch 1024 replaces 4 steps at batch 256. Scaling by 4 keeps the distance travelled per epoch similar: . (Scaling with gives 0.2, which some people use for Adam; dividing is backwards.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Momentum: a heavy ball rolling downhill
Watch: Gradient Descent With Momentum (DeepLearning.AI, Andrew Ng) Watch: Exponentially Weighted Averages (DeepLearning.AI)Momentum keeps a running "velocity" that adds up recent gradients. Gradients that keep pointing the same way pile up and speed you along; gradients that flip back and forth cancel out. It fixes much of the zig-zag from chapter 3 for almost no extra cost.
Plain gradient descent has no memory: each step looks only at the slope right here. In a long, narrow valley that's a disaster. The slope points mostly across the valley, so you bounce wall to wall while barely creeping along the floor (chapter 3's zig-zag).
Picture a heavy ball instead of a hiker. The ball builds up speed in a direction it keeps being pushed, and its inertia smooths out pushes that keep flipping. That's momentum (also called the heavy-ball method):
starting from . The new number (usually 0.9) says how much of the old velocity survives each step: it's like friction, with giving plain gradient descent back.
What the velocity really is
Unroll the recursion and the velocity is a weighted sum of all past gradients, with older ones fading geometrically:
Two cases explain everything:
- The gradient keeps pointing the same way (along the valley floor). Then approaches . With that's 10 times a single gradient: you accelerate along consistent directions.
- The gradient flips sign every step (bouncing across the valley). Then the terms alternate, , about half a gradient. The oscillation is damped instead of amplified.
So momentum automatically gives a big effective step in flat, consistent directions and a small one in steep, oscillating ones: exactly the imbalance a badly conditioned bowl needs. For quadratics one can show that with well-chosen and , the per-step factor improves from about to about . For that's roughly 10 times fewer steps.
Two ways of writing it, and Nesterov
You'll also see the averaged form (used in Andrew Ng's course): , . Here is an exponentially weighted average of gradients rather than a sum, so it's times smaller. The two forms produce identical paths if you rescale the learning rate: averaged form with equals summed form with . PyTorch's SGD(momentum=0.9) uses the summed form.
Nesterov momentum is a small twist: compute the gradient at the point where the velocity is about to carry you, , instead of at . It's like looking ahead before you step, and it corrects overshoot a little earlier. It's a one-flag option (nesterov=True) in most libraries.
Worked exampleBuilding up speed on a constant slope
Suppose the gradient is a constant (a straight ramp), with and .
- : step of , the same as plain GD.
- : step 0.38.
- : step 0.542.
- In the long run : steps of 2, ten times what plain GD would take.
Watch outCommon misconceptions
- "Momentum makes every step bigger." Only in directions where the gradient is consistent. In oscillating directions it makes the effective step smaller.
- "β close to 1 is always better." More momentum means more overshoot and longer swinging around the minimum. 0.9 is the usual default; 0.99 needs a smaller .
- "Momentum can't diverge if GD doesn't." The stable range changes. On a quadratic, heavy-ball momentum is stable when for every eigenvalue, so with as a sum it tolerates a larger than GD, but its effective step is also times larger.
- "The two momentum formulas are different algorithms." They differ only by a rescaling of .
In ML & deep learningWhere this shows up
"SGD with momentum 0.9" is the classic recipe for training convolutional networks (ResNets on ImageNet were trained this way), and momentum is built into Adam as its first moment (chapter 6). It also smooths out mini-batch noise: averaging the last ~ gradients is like using a bigger batch for the direction. Gabriel Goh's Distill article Why Momentum Really Works has beautiful interactive versions of this chapter's eigenvalue analysis.
Practice (pick one answer per question)
With and a gradient that stays constant at , the velocity approaches…
The fixed point solves , so .
Momentum helps most when the loss landscape…
- is a long, narrow valley where plain GD zig-zags
- is a perfectly round bowl
- has a gradient of exactly zero
- is a single straight line
In a narrow valley, momentum cancels the side-to-side bouncing and builds speed along the floor. In a round bowl plain GD with a good is already ideal.
, , and the gradient is 4 at every step. What is (using )?
- 7
- 6
- 8
- 12
, , . (It's heading toward .)
With , along a direction where the gradient is constant the velocity grows to about how many times a single gradient?
- 100
- 99
- 10
- 1.01
.
, . The gradient is at the first step and at the second. What is ?
- −0.1
- −1
- 0
- −1.9
, then . The flip almost cancels the old velocity, so the step is only a tenth of plain GD's: oscillations get damped.
The averaged form , gives exactly the same path as the summed form , when is…
- 0.01
- 0.1
- 1
- 0.09
The averaged velocity is times the summed one at every step, so . Hence .
Heavy-ball momentum on is stable exactly when . With and , what is the largest stable (the boundary)?
- 0.38
- 0.2
- 0.02
- 3.8
. Plain GD's limit would be . (Forgetting to divide by gives 3.8.)
Code it (optional: real Python runs in your browser and is graded by test cases)
RMSProp and Adam: a step size for every parameter
Watch: RMSProp (DeepLearning.AI, Andrew Ng) Watch: Adam Optimization Algorithm (DeepLearning.AI) Watch: Bias Correction of Exponentially Weighted Averages (DeepLearning.AI)RMSProp divides each parameter's gradient by a running average of its recent size, so steep and shallow directions take similar-sized steps. Adam combines that with momentum, and fixes the fact that both running averages start at zero with a "bias correction" that divides by .
Momentum fights bad conditioning by remembering the past. A different idea: if one parameter's gradients are consistently huge and another's are tiny, why use the same learning rate for both? Give each parameter its own step size, scaled by how big its gradients typically are.
RMSProp
Keep, for every parameter, an exponentially weighted average of its squared gradient, and divide the step by its square root (the "root mean square", hence the name):
Everything is element-wise: each parameter has its own . Typical values are and a tiny like to avoid dividing by zero. If a parameter's gradients are around 100, and its step is about . If another's are around 0.01, and its step is also about . The steep direction is slowed down, the flat one sped up. Only the sign and consistency of the gradient matter much, not its scale.
Exponentially weighted averages and their start-up problem
Both momentum and RMSProp use a running average . Unrolled, : recent values count most, and the average effectively covers the last or so steps. But we start from , and the weights add up to only , not 1. At with the "average" is : ten times too small.
The fix is simple: divide by the total weight. The bias-corrected average is
At , , exactly right. As grows, and the correction fades away. If every equals the same number , then and exactly, at every step.
Adam = momentum + RMSProp + bias correction
Adam ("adaptive moment estimation") keeps both averages for every parameter, corrects both, and combines them. At step with gradient :
The defaults are , , , and (often 3e-4 for transformers). is the momentum ("which way, on average?") and the scale ("how big, on average?"). Their ratio is roughly "signal over noise": close to when the gradient is consistent, and small when it keeps changing sign.
Why the correction matters so much for Adam. averages over about 1000 steps, so without correction stays far too small for hundreds of steps. At step 1, the uncorrected ratio is : a first step more than three times bigger than intended, in a direction based on one noisy gradient. With correction, , so the first step has size exactly .
Worked exampleAdam's first step
One parameter, first gradient , defaults , , (ignore ).
- , and .
- , and , so .
- Step: . The parameter moves by exactly , whatever the size of .
- Without correction: , a step of 0.00316.
Watch outCommon misconceptions
- "Adam doesn't need a learning rate." It still has , and it matters a lot. What Adam removes is the sensitivity to each parameter's gradient scale.
- "Bias correction corrects a bias in the gradients." The gradients are fine; it corrects the bias from starting the running averages at zero.
- "Adam's step is times the gradient." Its step is roughly times a number between −1 and 1 per coordinate; the gradient's magnitude is mostly divided out.
- "RMSProp is Adam." RMSProp has no momentum term and (in its usual form) no bias correction.
In ML & deep learningWhere this shows up
Adam, and its variant AdamW (chapter 9), is the default optimizer for transformers, language models, diffusion models and most new architectures: torch.. Per-parameter scaling matters there because different layers (embeddings, attention, layer norms) have gradients of wildly different sizes. Adam does cost memory: it stores and , two extra numbers per parameter, which for a 7-billion-parameter model is tens of gigabytes. That's why memory-saving variants (8-bit Adam, Adafactor) exist.
Practice (pick one answer per question)
With , the bias-correction factor at step is…
- 10
- 0.1
- 1
- 0.9
. It exactly undoes the factor that the first average was shrunk by.
RMSProp divides each parameter's gradient by…
- the square root of a running average of that parameter's squared gradients
- the number of parameters
- the running average of the loss
- the size of the whole gradient vector
Each parameter keeps its own , an average of , and the step is . Dividing by the norm of the whole vector is what gradient clipping does (chapter 12), and it's not per-parameter.
RMSProp with , and first gradient . What is ?
- 0.4
- 3.6
- 0.2
- 4
. (0.2 forgets to square; 3.6 swaps and .) The step is then , the start-up overshoot that bias correction would fix.
Ignoring , how big is Adam's very first step (per parameter, with a nonzero gradient)?
- exactly
and , so the step is .
Two parameters have gradients that stay constant at 100 and at 0.01. After many Adam steps, how do their step sizes compare?
- Both steps are about
- The first steps 10,000 times further
- The second steps 10,000 times further
- The first steps 100 times further
For a constant gradient , and , so each step is . Adam is invariant to rescaling a parameter's gradient; plain GD would step 10,000 times further on the first.
With , at step the correction multiplies by about…
- 100
- 10
- 1000
- 1.01
, so and the factor is about . Ten steps in, still holds only about 1% of its eventual weight, which is why correcting it matters for so long.
If you forget bias correction in Adam (defaults, ), how big is the first step?
- about
- exactly
- about
- about
and . The ratio is . The two missing corrections, 10 for and 1000 for ( after the square root), don't cancel.
Code it (optional: real Python runs in your browser and is graded by test cases)
Convexity: why some problems are easy
Watch: Convexity and The Principle of Duality (Visually Explained)A function is convex if every chord between two points on its graph lies on or above the graph: a bowl with no bumps. For convex functions every local minimum is a global minimum, so "walk downhill until it's flat" is guaranteed to find the best answer.
Gradient descent only sees the ground under its feet. It stops wherever the ground is flat. On a bumpy landscape that might be a shallow dip far from the deepest valley. So the natural question is: when is "locally flat" the same as "globally best"? The answer, and the most useful single idea in optimization, is convexity.
Three equivalent ways to say "convex"
1. The chord test. is convex if for any two points and any ,
The left side is the curve between and ; the right side is the straight chord joining and . Convex means the curve never pokes above any chord. A useful special case is : the value at the midpoint is at most the average of the end values.
2. The tangent test (for differentiable ). Every tangent line (or plane) lies below the graph:
This one is the key to everything. If , it says for every : a flat point is automatically a global minimum.
3. The curvature test (for twice-differentiable ). In 1D, everywhere. In many dimensions, the Hessian matrix of second derivatives is positive semidefinite everywhere: all its eigenvalues are , so the function curves upward (or is flat) in every direction.
Why convex problems are easy
- No bad local minima. Every local minimum is global. Suppose is a local minimum but some has . The chord from to slopes down, and by convexity the curve lies on or below it. So even points a tiny step from toward are lower than , which contradicts "local minimum".
- The minimizers form one connected blob (a convex set), and if is strictly convex (strict inequality in the chord test, e.g. Hessian positive definite) there's exactly one.
- Guarantees. Gradient descent with a suitable learning rate provably converges to the global minimum, with known rates. With strong convexity (curvature at least everywhere) it converges geometrically, just like chapter 3's bowls.
Building convex functions
You rarely check convexity from scratch. Instead, use rules that preserve it: sums of convex functions are convex; a convex function times a nonnegative number is convex; the maximum of convex functions is convex; and a convex function of a linear (affine) expression, like , is convex. Products of convex functions are not always convex.
This gives the ML catalogue: the MSE of a linear model, , is convex in (a convex function of an affine expression). Logistic regression's cross-entropy loss is convex. Adding an L2 or L1 penalty keeps it convex. But stack two layers with a nonlinearity in between, and convexity is gone: neural network losses are non-convex.
Worked exampleChecking convexity two ways
(a) by the midpoint test. . The chord's midpoint is never below the curve.
(b) by the Hessian. , with eigenvalues and (eigenvectors and ). Both positive, so is (strictly) convex with a single minimum at .
(c) A non-convex one. : , which is at . Midpoint test with : , but the average of the ends is . The curve pokes above the chord.
Watch outCommon misconceptions
- "Convex functions must be smooth." and are convex with kinks. The chord test doesn't need derivatives.
- "Convex means it has a minimum." is convex and never reaches its lower bound 0. Convexity says a minimum, if it exists, is global.
- "Convex means U-shaped and symmetric." A straight line is convex (chords lie exactly on it), and so is the lopsided .
- "Non-convex problems can't be solved." Neural networks are non-convex and train fine. You just lose the guarantee; chapter 8 explains why it often works anyway.
In ML & deep learningWhere this shows up
Classical ML is full of convex problems: linear and ridge regression, logistic regression, lasso, support vector machines. That's why sklearn fits them reliably to the same answer every time, regardless of initialization, often with specialised solvers. Deep learning gave that up for expressive power: a network's loss is non-convex, so random seeds give different solutions. Convexity still shows up locally (near a good minimum the loss looks like a convex bowl, which is what chapter 3's analysis assumes) and in pieces, e.g. the last layer of a classifier with the rest frozen is a convex logistic-regression problem.
Practice (pick one answer per question)
Which of these functions of one variable is convex everywhere?
has . is concave (), curves both ways, and has , negative for .
For a convex function, a local minimum is…
- always a global minimum
- never a global minimum
- always the unique minimizer
- a saddle point
Convexity rules out bad local minima: any local minimum is global. It need not be unique (a flat-bottomed convex function has many minimizers); strict convexity gives uniqueness.
The Hessian of is . What are its eigenvalues, and is convex?
- 3 and 1: convex
- 2 and 2: convex
- 3 and −1: not convex
- 1 and 1: convex
For the eigenvalues are . Both positive, so the Hessian is positive definite and is strictly convex. (Reading the diagonal gives "2 and 2", which ignores the off-diagonal coupling.)
For , what is , and what does it tell you?
- −4, so is not convex
- 0, so is convex
- 4, so is convex
- −2, so is not convex
, , so : the graph curves downward there (it's a local maximum between two valleys at ).
For , compare with the average . What do you conclude?
- : the midpoint is above the chord, so is not convex
- : consistent with convexity
- They're equal, so is linear between −1 and 1
- : the midpoint is below the chord, so is convex
, so the chord's midpoint height is , while is higher. One failing chord is enough to prove non-convexity. (Passing one chord would prove nothing.)
The Hessian of is . Is convex?
- No: the eigenvalues are 3 and −1
- Yes: all entries are positive
- Yes: the eigenvalues are 3 and 1
- Yes: the trace is positive
Eigenvalues : 3 and −1. Along the function curves downward (it's a saddle). Positive entries or a positive trace don't make a matrix positive semidefinite; the determinant already gives it away.
and are convex functions of . Which combination is not guaranteed to be convex?
Sums, maxima and nonnegative multiples preserve convexity. Products don't: and are both convex, but is not.
Code it (optional: real Python runs in your browser and is graded by test cases)
Local minima, saddle points and the Hessian
Watch: The Hessian matrix (Khan Academy) Watch: Multi-variable Optimization & the Second Derivative Test (Dr. Trefor Bazett) Watch: The Problem of Local Optima (DeepLearning.AI)Where the gradient is zero, the Hessian (the matrix of second derivatives) tells you what kind of flat spot you're on. All eigenvalues positive: a minimum. All negative: a maximum. Mixed signs: a saddle, which curves up in some directions and down in others. In high dimensions, saddles vastly outnumber bad local minima.
A point where is called a critical point (or stationary point). Gradient descent slows to a stop near every one of them, but they come in different kinds. In 1D, the second derivative sorts them: is a valley bottom, a hilltop. In many dimensions we need the second derivatives in every direction at once.
The Hessian
The Hessian of is the matrix of second partial derivatives,
For smooth functions it's symmetric (), so by the spectral theorem it has real eigenvalues and perpendicular eigenvectors. Its job is to describe curvature. Taylor's theorem to second order says
At a critical point the middle term vanishes, so near it the function is just the quadratic . Write in the eigenvector basis, , and this becomes : each eigenvector is a direction, and its eigenvalue is the curvature along it.
- All (positive definite): up in every direction. A local minimum.
- All : down in every direction. A local maximum.
- Some positive, some negative: a saddle point, like a mountain pass or a horse saddle. Up along some eigenvectors, down along others.
- Some : the test is inconclusive in those flat directions; higher-order terms decide.
In 2D there's a shortcut: and . A negative determinant means opposite signs, so a saddle; a positive determinant with a positive trace means a minimum.
Saddles in high dimensions
Here's a heuristic that changed how people think about neural network training. At a random critical point of a function of variables, imagine each Hessian eigenvalue is equally likely to be positive or negative. Then the chance that all are positive (a true minimum) is . With that's essentially zero: almost every critical point is a saddle. Real landscapes aren't that random, but the conclusion has held up in experiments: in big networks, critical points with high loss are overwhelmingly saddles, and the local minima that do exist tend to have loss close to the global one.
Saddles still cause trouble. Near one the gradient is tiny, so gradient descent can spend a long time on a plateau before it drifts off along a negative-curvature direction. What gets it off: the mini-batch noise of chapter 4 (any nudge along a downhill eigenvector grows), momentum that carries it through, and adaptive methods that boost the tiny gradients in flat directions.
Worked exampleFind and classify the critical points
Take .
- Gradient: . Setting it to zero gives , : critical points and .
- Hessian: .
- At : eigenvalues and , both positive. A local minimum, with .
- At : eigenvalues and . A saddle: going along is uphill, going along is downhill. (.)
Note is only a local minimum: as . This isn't convex, so there's no guarantee that local means global.
Watch outCommon misconceptions
- "Zero gradient means a minimum." It means a critical point: minimum, maximum or saddle. Check the Hessian.
- "Check the signs of the diagonal entries." The diagonal gives curvature along the coordinate axes only. has a positive diagonal and is a saddle. Use eigenvalues (or the determinant in 2D).
- "Neural nets get stuck in bad local minima all the time." In large networks, slowdowns are much more often saddles and plateaus than bad minima.
- "Gradient descent can never escape a saddle." Exactly at one, the gradient is zero. But almost any perturbation along a negative-curvature direction grows, so noisy GD escapes. Saddles slow it down rather than trap it.
In ML & deep learningWhere this shows up
The Hessian's eigenvalues describe the "sharpness" of a minimum. Researchers track the top eigenvalue during training (it can be estimated with Hessian-vector products without ever forming the matrix), and an observed effect called the "edge of stability" is that with gradient descent rises until it hovers near : exactly chapter 3's stability limit. Flat minima (small eigenvalues) are associated with better generalization, which motivates methods like sharpness-aware minimization (SAM). The Hessian's condition number also explains why some networks train slowly, and it's the matrix that Newton's method (chapter 11) inverts.
Practice (pick one answer per question)
At a critical point the Hessian has eigenvalues 3 and −2. What kind of point is it?
- a saddle point
- a local minimum
- a local maximum
- impossible to tell
Mixed signs: it curves up along one eigenvector and down along the other. That's a saddle.
The Hessian of a function is…
- the matrix of its second partial derivatives
- the vector of its first partial derivatives
- the inverse of its gradient
- the matrix whose columns are its eigenvectors
. The vector of first derivatives is the gradient.
has a critical point at the origin. Starting just next to it, which direction leads downhill fastest?
- along the -axis (either way)
- along the -axis
- along the line
- none: the origin is a minimum
. The eigenvalue −2 belongs to the direction, where falls. Along , : flat.
What are the eigenvalues of the Hessian of ?
- 6 and −2
- 2 and 2
- 4 and 0
- 6 and 2
(note ). Eigenvalues : the origin is a saddle.
At a critical point with , you move by . By the second-order approximation, how much does change?
- +0.01
- +0.02
- −0.01
- +0.06
. The uphill part outweighs the downhill part in this direction. (Forgetting the ½ gives 0.02.)
If each of the 10 Hessian eigenvalues at a random critical point were independently positive or negative with probability ½, what's the chance it's a local minimum?
All 10 must be positive: . With millions of parameters, minima would be astronomically rare among critical points under this toy model; most are saddles.
For , what is the point ?
- a saddle point
- a local minimum
- a local maximum
- not a critical point
, so it's critical. : mixed signs, so a saddle. (Its twin is the local minimum.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Regularization: L2 vs L1, and weight decay
Watch: Regularization Part 1: Ridge (L2) Regression (StatQuest) Watch: Regularization Part 2: Lasso (L1) Regression (StatQuest) Watch: Regularization (DeepLearning.AI, Andrew Ng)Regularization adds a penalty on the size of the weights to the loss. An L2 penalty shrinks every weight smoothly toward zero (that's "weight decay"). An L1 penalty pushes weights to become exactly zero, because its constraint region is a diamond whose corners sit on the axes.
A model that fits its training data perfectly often fits the noise too, and does badly on new data (overfitting). One cure is to prefer "simpler" parameter vectors: ones with small weights. We change the objective to
where measures the size of and sets the trade-off. The two classics are
- L2 (ridge): .
- L1 (lasso): .
L2 is weight decay
The gradient of is just . So a gradient step on the regularized loss is
Before the usual step, every weight is multiplied by , slightly less than 1: the weights decay toward zero unless the data keeps pushing them up. A weight that the loss doesn't care about shrinks geometrically, but never reaches exactly zero.
The geometry: why L1 gives zeros
Penalizing size is equivalent (for a suitable budget matching each ) to a constraint: minimize subject to . In 2D the allowed region is a disk for L2 and a diamond for L1. Now picture the loss's contour ellipses centred at the unregularized best fit, outside the region. Grow the ellipse until it first touches the region: that touching point is the answer.
- A disk is smooth and round, so the first touch can be anywhere on it. Landing exactly on an axis would be a coincidence.
- A diamond has sharp corners on the axes. An expanding ellipse very often hits a corner first, and at a corner one coordinate is exactly 0.
In high dimensions the L1 ball has even more corners and edges lying in coordinate subspaces, so solutions with many exact zeros (sparse solutions) are typical. That's why lasso does feature selection: it switches irrelevant features off completely.
The algebra: soft thresholding
The 1D problem shows the same thing with formulas. Minimize , where is what the data alone wants.
- L2 (): setting the derivative to zero gives . Shrunk, but zero only if .
- L1 (): the answer is the soft-thresholding function . Every value with becomes exactly 0, and the rest move toward 0.
The kink of at 0 is what does it: its slope jumps from to , so near zero the penalty pushes with constant force , not a force that fades like . Because isn't differentiable at 0, L1 problems are solved with subgradients or proximal steps: take a gradient step on , then apply soft thresholding with threshold (the ISTA algorithm).
Worked exampleSame data, two penalties
Minimize .
- L2 with : . With : . Never zero.
- L1 with : . With : , so exactly.
Check the L1 answer at : for small the objective's slope is , and for small it is . So is the bottom of a V-shaped valley.
Watch outCommon misconceptions
- "L2 regularization sets small weights to zero." It shrinks them proportionally; they approach zero but don't reach it. Exact zeros are L1's signature.
- "Weight decay and L2 regularization are always the same." For plain SGD, yes (up to how is scaled). For Adam they differ: the L2 gradient gets divided by like everything else, so weights with large gradients are barely regularized. AdamW applies the decay separately ("decoupled"), which works better.
- "More regularization is always safer." Too large a underfits: all weights get crushed toward zero and the model ignores the data.
- "Regularize the bias too." Usually biases (and often normalization parameters) are excluded; penalizing them doesn't reduce model complexity in a useful way.
In ML & deep learningWhere this shows up
Ridge and lasso regression are standard tools (sklearn., Lasso), and lasso's zeros are used to pick features. In deep learning, weight decay is nearly universal: AdamW(params, lr=3e-4, weight_decay=0.1) is a typical language-model setting. L1-style penalties appear in sparse autoencoders (used to find interpretable features inside language models), and in pruning, where many weights are pushed to zero to make networks smaller and faster. Other regularizers (dropout, data augmentation, early stopping) don't change the loss formula but serve the same goal.
Practice (pick one answer per question)
With L2 weight decay, and , each step multiplies the weights by what factor before the loss-gradient step?
- 0.999
- 0.99
- 0.9
- 1.001
. Using gives 0.99; using gives 0.9.
Which penalty tends to produce weights that are exactly zero?
- L1,
- L2,
- Both equally
- Neither; only pruning does that
L1's diamond-shaped constraint has corners on the axes, and its soft-thresholding solution maps a whole interval of values to exactly 0. L2 only shrinks.
Minimize with . What is ?
- 1
- 1.5
- 0
- 3
Derivative: , so and .
Soft thresholding . What is ?
- 0.2
- 0
- 0.7
- 1.2
, so it survives and moves 0.5 toward zero: . ( would be 0.)
Minimize . What is the smallest for which ?
- 3
- 1.5
- 6
- 9
The solution is , which hits 0 when . Intuition: the penalty's constant push must beat the data's pull, which is 3 at .
Ridge regression without intercept on data , : minimize with . What is ?
- 1
- 1.4
- 7/3
- 0.7
Derivative: , so . Without the penalty it would be .
Why does adding an L2 term to the gradient inside Adam regularize differently from AdamW's decoupled weight decay?
- Adam divides the term by , so weights with large gradient history get much less shrinkage
- Adam ignores the term because bias correction removes it
- They're identical; AdamW only changes the default learning rate
- Adam applies the L2 term twice, once in and once in
In Adam the whole gradient, penalty included, is rescaled per parameter by . So the effective decay is uneven: large-gradient weights are barely decayed. AdamW instead multiplies every weight by outside the adaptive step, restoring uniform weight decay.
Code it (optional: real Python runs in your browser and is graded by test cases)
Constrained optimization and Lagrange multipliers
Watch: Lagrange multipliers, using tangency to solve constrained optimization (Khan Academy) Watch: Lagrange Multipliers: Geometric Meaning & Full Example (Dr. Trefor Bazett)To minimize while staying on a constraint curve , look for the point where a level curve of just touches the constraint. There the two gradients are parallel: . The number , the Lagrange multiplier, measures how much the best value would improve if you relaxed the constraint.
So far the parameters could go anywhere. Often they can't: probabilities must add to 1, a weight vector must have bounded norm, a portfolio's weights must sum to your budget. That's constrained optimization:
The tangency picture
Walk along the constraint curve and watch the value of . If the curve crosses a level curve of at an angle, then sliding one way along the constraint goes to lower level curves, and you can still improve. You can't improve only where the constraint runs along a level curve: where the two curves are tangent.
Gradients are perpendicular to level curves (chapter 2). If two curves are tangent at a point, their perpendiculars line up, so
That's equations for the coordinates plus . A neat way to package them: define the Lagrangian . Setting all its partial derivatives to zero gives exactly the tangency condition () and the constraint (). A constrained problem becomes an unconstrained "find the flat point" problem in one more variable.
What λ means
If the constraint is and you nudge , the optimal value changes at rate . So is the "price" of the constraint: how much better you could do per unit of loosening. In economics it's called a shadow price. A multiplier of 0 means the constraint isn't costing you anything.
Inequalities and KKT, in brief
Many ML constraints are inequalities, (e.g. ). Then either the unconstrained minimum already satisfies it (the constraint is inactive, multiplier 0) or the answer lies on the boundary (active) and the Lagrange condition holds with a multiplier of a definite sign. These rules are the KKT conditions; the key one, "multiplier × constraint = 0", is called complementary slackness. The L1 diamond and L2 disk of chapter 9 are exactly such inequality constraints, and each in the penalty form corresponds to a budget through the multiplier.
Projected gradient descent
For simple constraint sets there's an even easier method: take a normal gradient step, then project back onto the allowed set (move to its nearest point).
Projections are cheap for common sets: onto the ball , rescale to length if it's too long; onto a box , clip each coordinate. For convex sets and convex this converges to the constrained minimum.
Worked exampleClosest point on a line
Minimize (squared distance from the origin) subject to , i.e. .
- , . Tangency: , , so , .
- Constraint: , so , giving and .
- Check: is a multiple of the line's normal , as the closest point should be. Its distance from the origin is .
- Meaning of : for the line the same steps give , and at . That's .
Watch outCommon misconceptions
- "At the constrained minimum, ." Usually not: would still like to go downhill, but the constraint blocks it. points straight into the wall (along ).
- "The gradients must point the same way." Parallel or opposite: can be negative for equality constraints. Its sign matters only for inequalities.
- "Every solution of is the minimum." Tangency also happens at the constrained maximum (the circle in the figure has both). Compare the candidates' values.
- "Projection works for any constraint set." Projecting onto a complicated or non-convex set can be as hard as the original problem.
In ML & deep learningWhere this shows up
Support vector machines are derived with Lagrange multipliers: the "support vectors" are exactly the training points whose constraints are active (non-zero multiplier). The softmax function falls out of maximizing entropy subject to "probabilities sum to 1" and a fixed expected score. Projected or clipped updates are everywhere: weight clipping in early GANs, max-norm constraints on weights, keeping probabilities on the simplex, and the trust-region idea behind reinforcement-learning methods like TRPO (a KL-divergence constraint, handled with a multiplier) and its simpler cousin PPO.
Practice (pick one answer per question)
At the minimum of on the curve (a regular point), the gradients and are…
- parallel
- perpendicular
- both zero
- equal
The level curve of is tangent to the constraint curve, so their normals (the gradients) line up: . They needn't be equal ( in general), and is usually not zero.
Maximize subject to . What is the maximum value?
- 25
- 50
- 100
- 24
gives , and then , . (.) Other splits like are smaller.
Minimize subject to . Where is the minimizer?
gives , so with value 2. The origin is the unconstrained minimum but isn't on the line; gives 4.
Projected gradient descent with the constraint . A gradient step lands at . Where does the projection put it?
, so rescale to length 1: . Clipping each coordinate to 1 gives , which is outside the ball (length ).
Project the point onto the box .
For a box, the nearest point clips each coordinate separately: , .
For "minimize subject to ", the optimal value is and the multiplier is . If goes from 2 to 2.1, by about how much does the optimal value rise?
- 0.2
- 0.1
- 2
- 0.4
The rate of change is , so the rise is about . (Exactly: .)
Minimize subject to . Using the KKT condition on the active boundary (with , ), what are and ?
- ,
- ,
- ,
- ,
The unconstrained minimum violates , so the constraint is active: . Then , and gives ✓. It's the force the wall must push back with.
Code it (optional: real Python runs in your browser and is graded by test cases)
Newton's method and second-order ideas
Watch: Newton's Method in Optimization (Visually Explained) Watch: Newton's method (for optimization), intuition (mathematicalmonk)Gradient descent uses only the slope. Newton's method also uses the curvature: it fits a parabola (a quadratic bowl) to the function at the current point and jumps straight to that bowl's bottom, . Near a minimum it converges astonishingly fast, but each step is expensive and it can misbehave far away.
Chapter 3 showed that gradient descent's speed is limited by curvature: one learning rate must serve both steep and flat directions. What if we knew the curvature in every direction and could scale each step perfectly?
In one dimension
Near the current point , approximate by its second-order Taylor polynomial, a parabola:
If this parabola has a lowest point, where . Jump there:
Compare gradient descent, : Newton is gradient descent with the learning rate , chosen automatically from the local curvature. That's exactly chapter 3's ideal rate . (It's also Newton's root-finding method applied to : we're looking for where the slope is zero.)
In many dimensions
The quadratic model uses the gradient and the Hessian, , and its minimizer gives the Newton step:
In the Hessian's eigenvector basis, divides each component of the gradient by its own curvature : a separate, perfect learning rate for every eigen-direction. The condition number stops mattering. On an exact quadratic bowl, Newton reaches the minimum in one step, whatever is.
Near a minimum, Newton converges quadratically: the error roughly squares each step, . Once the error is 0.01, the next is about 0.0001, then : the number of correct digits doubles every step. Gradient descent only converges linearly (the error shrinks by a constant factor).
Why deep learning doesn't use it (directly)
- Cost. With parameters the Hessian has entries and solving takes about operations. For , numbers is terabytes. For , forget it.
- Non-convexity. If has negative eigenvalues (a saddle region, chapter 8), the "bottom" of the quadratic model is actually a saddle or a peak, and Newton happily jumps toward it. Pure Newton is attracted to saddles.
- Noise. With mini-batches, the Hessian estimate is noisy and the method's precision is wasted.
Practical fixes: damping (, which blends Newton with gradient descent and keeps the step sane), line search (shrink the step until the loss actually drops), and quasi-Newton methods like BFGS and L-BFGS that build a cheap approximation of from recent gradients. For least-squares problems, Gauss–Newton and Levenberg–Marquardt use a positive semidefinite approximation of .
Worked exampleWatching the digits double
Minimize (for ); the minimum is at . Here and , so the Newton step is
From : , , , . The errors are : each one is exactly the square of the one before, since .
Watch outCommon misconceptions
- "Newton always goes downhill." Only if is positive definite. Where the step heads toward a maximum, and far from the minimum it can overshoot wildly (see in the figure).
- "Newton needs a learning rate." Pure Newton uses step size 1; the curvature sets the scale. Damped versions add a step size for safety.
- "Adam is a second-order method." Adam's is a per-parameter scale from squared gradients, not curvature. It's sometimes described as a crude diagonal preconditioner, but it doesn't use the Hessian.
- "Compute explicitly." Never: solve the linear system . It's cheaper and more accurate.
In ML & deep learningWhere this shows up
Newton's method (as "iteratively reweighted least squares") is how classic statistics packages fit logistic regression, and L-BFGS is the default solver for sklearn's LogisticRegression. In deep learning, second-order ideas appear in approximate forms: K-FAC and Shampoo build block-wise approximations of curvature, and Shampoo-style preconditioners have won recent optimizer benchmarks. Hessian-vector products (computable at the cost of a couple of backward passes) are used to measure sharpness and in influence functions. And the "natural gradient", which uses the Fisher information matrix as the curvature, is a close cousin of Newton's method used in reinforcement learning.
Practice (pick one answer per question)
Newton's method for minimizing a 1D function updates to…
Minimize the local parabola: . The formula is Newton's method for finding a root of , and is gradient descent.
Newton's method on , starting anywhere. Where is it after one step?
- exactly at
- halfway to 2
- at
- it depends on the learning rate
The function is its own quadratic model, so the jump to the model's bottom lands on the true minimum: .
Minimize with Newton's method from . What is ?
- 1
- 2
- 0.5
- −1
, . At 0: , , so . (The true minimizer is .)
Newton's method on from . Where does the first step land?
and , so and . One step on any quadratic, despite .
Newton's method is converging quadratically and the current error is about . Roughly what is the error two steps later?
Squaring each step: (taking the constant as about 1).
A model has parameters. How many entries does its Hessian have?
An matrix: entries, about 4 terabytes in 32-bit floats. Solving with it naively costs about operations, which is the other option's number.
Minimize with Newton's method from . What is , and did the loss go down?
- , and the loss went up
- , and the loss went down
- , and the loss went down
- , and the loss went down
, . Step: . Since , Newton jumped toward the local maximum at 0: but , higher. (The minimizers are at .)
Code it (optional: real Python runs in your browser and is graded by test cases)
Learning-rate schedules and practical training
Watch: Learning Rate Decay (DeepLearning.AI, Andrew Ng) Watch: Vanishing/Exploding Gradients (DeepLearning.AI)The best learning rate changes during training: start gently (warmup), go big while you're far from the minimum, then decay so the noisy steps settle down (step, exponential or cosine decay). Gradient clipping caps the size of any single step so one bad batch can't wreck the run.
Everything so far used a fixed . Real training runs almost never do. Two lessons from earlier chapters explain why:
- From chapter 4: with mini-batches, a fixed leaves the parameters jittering in a cloud around the minimum, and the cloud shrinks with . To settle down, lower late in training.
- From chapter 3: the safe step size is about , and early in training the landscape can be much sharper (and Adam's running averages less reliable) than later. A big right at the start can blow up.
So a schedule gives the learning rate as a function of the step .
Decay schedules
- Step decay: multiply by a factor (often 0.1) at fixed milestones, e.g. epochs 30, 60, 90. The loss curve drops sharply after each cut. Classic for ResNets.
- Exponential decay: with slightly below 1 (per step or per epoch). A smooth version of step decay.
- Linear decay: straight down from the peak to (nearly) zero at the end.
- Cosine decay: over steps from to , It stays near the peak for a while, falls fastest in the middle, and flattens gently at the end. It has no milestones to tune, which is a big reason it became the default for transformers.
Warmup
Linear warmup ramps from 0 (or tiny) up to the peak over the first few hundred or thousand steps: . Early on, the weights are random, gradients can be large and erratic, and Adam's estimate is based on very few samples. Small steps at the start let things settle before the big steps begin. Warmup is what lets large batches and large peak learning rates train stably; without it, many transformer runs diverge in the first few hundred steps. The typical modern recipe is "linear warmup, then cosine decay".
Gradient clipping
Sometimes one batch produces an enormous gradient: a sharp cliff in the landscape, an exploding recurrent network, a rare weird example. One step of size can undo hours of training. Clipping by norm caps the size of the gradient vector at a threshold without changing its direction:
If nothing happens. If it's bigger, the vector is shrunk to length exactly . (Clipping by value, which clamps each coordinate to separately, is cruder: it changes the direction.) Typical thresholds are 1.0 for transformers. Clipping is applied to the whole gradient vector across all parameters, after backpropagation and before the optimizer step.
A practical checklist
- Find the learning rate first. Try a few values on a log scale (1e-4, 3e-4, 1e-3, …) for a short run, or do an "LR range test": increase exponentially over a few hundred steps and note where the loss starts to explode. Pick something a few times below that.
- Watch the loss curve. Loss going to NaN or shooting up: too high, missing clipping, or a bug. Loss falling painfully slowly in a straight line: probably too low.
- Check the gradient norm. Logging each step reveals spikes that clipping should catch.
- Keep a validation set and stop (or keep the best checkpoint) when validation loss stops improving: early stopping, a free regularizer.
- Change one thing at a time, and when you change the batch size, revisit the learning rate (chapter 4).
Worked exampleWarmup + cosine, and a clip
A run has 1000 steps: 100 steps of linear warmup to , then cosine decay to 0 over the remaining 900.
- Step 50: halfway through warmup, .
- Step 100: the peak, .
- Step 550: 450 of 900 decay steps, so and .
- Step 1000: .
Clipping: with , the gradient has norm 5, so it becomes . The gradient (norm 0.5) is left alone.
Watch outCommon misconceptions
- "Adam adapts the step size, so it doesn't need a schedule." Adam adapts relative step sizes across parameters. Its global still benefits from warmup and decay, and transformer recipes always use both.
- "Clipping changes the gradient direction." Norm clipping only rescales; value clipping is the one that bends it.
- "Decay the learning rate as early as possible." Decaying too early freezes progress while you're still far from a good region. Most of a cosine schedule is spent at fairly high rates.
- "Warmup is about the model, not the optimizer." It's mostly about the optimizer's early instability: huge early gradients, a sharp landscape at initialization, and Adam's second-moment estimates built from few samples.
In ML & deep learningWhere this shows up
A typical large-language-model recipe is AdamW with , weight decay 0.1, gradient clipping at norm 1.0, a linear warmup over the first ~2000 steps, and cosine decay to about 10% of the peak. In PyTorch: torch. before optimizer.step(), and a scheduler such as CosineAnnealingLR or a warmup lambda stepped after each update. Some recent runs use "warmup-stable-decay" schedules: hold the peak for most of training, then decay quickly at the end, which makes it easy to continue training later.
Practice (pick one answer per question)
Step decay starts at and multiplies by 0.1 at epochs 30 and 60. What is at epoch 65?
- 0.001
- 0.01
- 0.0001
- 0.1
Two cuts have happened (at 30 and 60): .
Clip the gradient by norm with threshold .
, so scale by : , length 5, same direction. is value clipping; is the unit vector.
Cosine decay from to 0 over steps. What is the learning rate at ?
- 0
, so . At the midpoint, cosine and linear decay agree.
Linear warmup over 2000 steps to a peak of . What is the learning rate at step 500?
.
Cosine decay from 1 (the peak) to 0. What fraction of the peak remains a quarter of the way through, at ?
- about 0.854
- 0.75
- about 0.707
- 0.5
. Linear decay would give 0.75: cosine stays high for longer at the start.
Exponential decay (per epoch). What is after 20 epochs?
- about 0.036
- 0
- 0.095
- about 0.064
, so . (Subtracting 5% of the initial value each epoch would wrongly give 0 after 20 epochs.)
The gradient is and . Norm clipping gives approximately . What does clipping by value (each entry to ) give, and what's wrong with it?
- : the direction turns noticeably toward the first axis
- : the same as norm clipping
- : nothing is clipped
- : every entry is set to the threshold
Value clipping only touches entries bigger than 3: . The ratio of the entries changes from 1:24 to 1:6, so the update points in a different direction. Norm clipping keeps the 1:24 ratio: with .
Code it (optional: real Python runs in your browser and is graded by test cases)
Final tests
3 full-length tests covering the whole module, with single-concept and multi-concept questions and Python problems graded by test cases. You get a score, a chapter-by-chapter breakdown and the worked answer to every question. Your best score is saved in this browser.
One-page cheat sheet
The whole module, compressed. On paper, it prints on its own (figures hidden).
Losses & landscapes (1)
MSE ; training =
Minimum = lowest value; minimizer = where it happens.
Gradient descent (2)
; = steepest descent, ⟂ contours
One small step lowers by .
Learning rate on a quadratic (3)
: each eigen-direction × per step
Stable iff ; best
Rate ,
Mini-batches (4)
: unbiased; std
Steps per epoch . Linear scaling: .
Momentum (5)
;
Constant gradient: . Alternating: .
Averaged form with = summed form with .
RMSProp & Adam (6)
RMSProp: ,
Adam: as EWAs of ; ,
; first step size = . Defaults 0.9, 0.999, 1e-8.
Convexity (7)
Chord:
Tangent: ; Hessian PSD
Local min = global min. Preserved by +, max, scaling, affine inputs.
Hessian & critical points (8)
Eigenvalues all : min; all : max; mixed: saddle; a zero: inconclusive
2D: ⇒ saddle.
Regularization (9)
L2: (weight decay); ⇒
L1: soft threshold ⇒ exact zeros
Ridge: . AdamW = decoupled decay.
Constraints (10)
s.t. : ,
. KKT: inactive ⇒ multiplier 0.
Projected GD: ; ball: rescale, box: clip.
Newton (11)
1D: ; nD: solve ,
Exact in 1 step on quadratics; quadratic convergence near a minimum.
memory, time; needs .
Schedules & clipping (12)
Warmup: . Cosine:
Step: × 0.1 at milestones. Exponential: .
Clip by norm: .
Glossary
- Adam
- An optimizer that keeps bias-corrected running averages of the gradient (momentum) and of its square (scale) for every parameter, and steps by their ratio. (Ch 6)
- AdamW
- Adam with weight decay applied directly to the weights instead of being added to the gradient. (Ch 9)
- Bias correction
- Dividing a running average started at 0 by , so early estimates aren't shrunk toward zero. (Ch 6)
- Condition number κ
- of the Hessian: how stretched the bowl is. Large κ means slow gradient descent. (Ch 3)
- Convex function
- One whose chords lie on or above its graph; every local minimum is global. (Ch 7)
- Cosine schedule
- A learning rate that follows half a cosine wave from its peak down to a minimum. (Ch 12)
- Critical point
- A point where the gradient is zero: a minimum, maximum or saddle. (Ch 8)
- Divergence
- Iterates growing without bound, typically because . (Ch 3)
- Epoch
- One full pass over the training set: mini-batch steps. (Ch 4)
- Gradient
- The vector of partial derivatives; it points in the direction of steepest ascent. (Ch 2)
- Gradient clipping
- Shrinking a gradient whose norm exceeds a threshold to length , keeping its direction. (Ch 12)
- Gradient descent
- Repeating . (Ch 2)
- Hessian
- The symmetric matrix of second partial derivatives; its eigenvalues are curvatures. (Ch 8, 11)
- KKT conditions
- The optimality conditions for inequality constraints, including "multiplier × constraint = 0". (Ch 10)
- L1 / L2 regularization
- Adding (gives sparse weights) or (shrinks weights) to the loss. (Ch 9)
- Lagrange multiplier
- The in ; the rate at which the best value changes as the constraint is relaxed. (Ch 10)
- Learning rate η
- The multiplier on the gradient in each update; the step size. (Ch 2, 3)
- Loss function
- A single number measuring how badly a model with given parameters fits the data. (Ch 1)
- Loss landscape
- The loss viewed as a height over the space of parameters. (Ch 1)
- Mini-batch
- A random subset of training examples used to estimate the gradient. (Ch 4)
- Minimizer (argmin)
- The parameter value where the minimum is achieved, as opposed to the minimum value itself. (Ch 1)
- Momentum
- Adding a decaying sum of past gradients to the update, so consistent directions speed up and oscillations cancel. (Ch 5)
- Newton's method
- Jumping to the minimum of the local quadratic model: . (Ch 11)
- Projected gradient descent
- A gradient step followed by moving back to the nearest allowed point. (Ch 10)
- RMSProp
- Dividing each parameter's gradient by the root of a running average of its squares. (Ch 6)
- Saddle point
- A critical point that curves up in some directions and down in others (mixed-sign Hessian eigenvalues). (Ch 8)
- Soft thresholding
- : the L1 proximal step that sets small values to exactly 0. (Ch 9)
- Stochastic gradient descent (SGD)
- Gradient descent using noisy gradients from single examples or mini-batches. (Ch 4)
- Warmup
- Ramping the learning rate up from near zero over the first steps of training. (Ch 12)
- Weight decay
- Multiplying weights by each step; equals L2 regularization for plain SGD. (Ch 9)