Math for ML / Optimization
0 / 12
Module 4

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 θ←θ−η ∇L(θ)\theta \leftarrow \theta - \eta\,\nabla L(\theta), 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.
Chapter 1

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 (theta): the numbers the model is allowed to change. A line y^=wx+b\hat y = wx + b has two, ww and bb. GPT-style models have billions.
  • Data: examples (xi,yi)(x_i, y_i) of inputs and the answers we want.
  • A loss function L(θ)L(\theta): a single number that is small when the model's predictions y^i\hat y_i match the answers yiy_i and big when they don't.

The most common loss for predicting numbers is the mean squared error (MSE):

L(w,b)=1n∑i=1n(wxi+b⏟y^i−yi)2.L(w,b) = \frac{1}{n}\sum_{i=1}^{n} \big(\underbrace{w x_i + b}_{\hat y_i} - y_i\big)^2 .

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 (w,b)(w, b) 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, min⁡θL(θ)\min_\theta L(\theta).
  • The minimizer is where that happens, written θ∗=arg⁡min⁡θL(θ)\theta^* = \arg\min_\theta L(\theta). 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.

The map is the loss landscape of fitting a line to five points: horizontal is the slope ww, vertical is the intercept bb. Drag the gold dot: the inset shows the line you've chosen and its errors (red bars). Darker teal means a smaller loss. The red arrow points downhill, which is where chapter 2 starts.

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 y^=wx\hat y = wx (no intercept) to two points, (1,1)(1, 1) and (2,3)(2, 3). The loss is

L(w)=12[(w⋅1−1)2+(w⋅2−3)2].L(w) = \tfrac12\big[(w\cdot1-1)^2 + (w\cdot2-3)^2\big].
  • At w=1w=1: 12[02+(−1)2]=0.5\tfrac12[0^2 + (-1)^2] = 0.5.
  • At w=2w=2: 12[12+12]=1\tfrac12[1^2 + 1^2] = 1.
  • Expanding, L(w)=12[5w2−14w+10]L(w) = \tfrac12[5w^2 - 14w + 10], a parabola (a 1D bowl). Its lowest point is where the slope L′(w)=5w−7L'(w) = 5w - 7 is zero: w∗=7/5=1.4w^* = 7/5 = 1.4.
  • At w=1.4w = 1.4: 12[0.42+(−0.2)2]=12[0.16+0.04]=0.1\tfrac12[0.4^2 + (-0.2)^2] = \tfrac12[0.16+0.04] = 0.1. So the minimizer is w∗=1.4w^*=1.4 and the minimum value is 0.10.1 (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 (w=1.4w = 1.4). 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?

  1. A single number measuring how badly the model's predictions match the data, as a function of the parameters
  2. The list of training examples the model got wrong
  3. The amount by which each parameter changes in one training step
  4. 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 y^=(2,4)\hat y = (2, 4) for two examples whose true answers are y=(1,4)y = (1, 4). What is the mean squared error?

  1. 0.5
  2. 1
  3. 0.25
  4. 2

Errors are 2−1=12-1 = 1 and 4−4=04 - 4 = 0. Squared: 1 and 0. Mean: (1+0)/2=0.5(1+0)/2 = 0.5. (Forgetting to divide by nn gives 1.)

For L(w)=(w−3)2+1L(w) = (w-3)^2 + 1, what is arg⁡min⁡wL(w)\arg\min_w L(w)?

  1. 3
  2. 1
  3. 0
  4. −3

The squared term is smallest (zero) at w=3w = 3, so the minimizer is w∗=3w^* = 3. The minimum value is L(3)=1L(3) = 1, which is the tempting wrong answer.

Minimize L(w)=(w−2)2+(w−4)2L(w) = (w-2)^2 + (w-4)^2. Where is the minimizer?

  1. w=3w = 3
  2. w=2w = 2
  3. w=6w = 6
  4. w=4w = 4

L′(w)=2(w−2)+2(w−4)=4w−12=0L'(w) = 2(w-2) + 2(w-4) = 4w - 12 = 0, so w=3w = 3. In general, the number that minimizes a sum of squared distances to some points is their average.

A model is y^=w1x1+w2x2+w3x3+b\hat y = w_1x_1 + w_2x_2 + w_3x_3 + b. How many coordinates does a single point of its loss landscape's map (its parameter space) have?

  1. 4
  2. 3
  3. 5
  4. 1

The map is the space of parameters: w1,w2,w3,bw_1, w_2, w_3, b, 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, ∑(y^i−yi)\sum (\hat y_i - y_i)?

  1. Without squaring, positive and negative errors cancel, so a terrible model could score 0
  2. Squaring makes the loss smaller, so training is faster
  3. Squared errors are always less than 1
  4. 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 cc for every example, and the targets are 1,2,91, 2, 9. Which cc minimizes the mean absolute error 13∑∣c−yi∣\frac13\sum|c - y_i|? (Compare with what MSE would choose.)

  1. 2 (the median), while MSE would pick 4 (the mean)
  2. 4 (the mean), the same as MSE
  3. 9, the largest target
  4. 5, halfway between the smallest and largest

MAE at c=2c=2: (1+0+7)/3=8/3(1+0+7)/3 = 8/3. At c=4c=4: (3+2+5)/3=10/3(3+2+5)/3 = 10/3. Moving cc away from the median increases the distance to more points than it decreases, so the median wins. MSE is minimized by the mean, 44. 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)

Chapter 2

Gradient descent: walk downhill, repeat

Watch: Gradient descent, how neural networks learn (3Blue1Brown) Watch: Gradient Descent, Step-by-Step (StatQuest)

The gradient ∇f\nabla f points in the direction where ff climbs fastest. Gradient descent takes a small step the opposite way, x←x−η ∇f(x)x \leftarrow x - \eta\,\nabla f(x), 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, f(x1,…,xn)f(x_1, \dots, x_n), the gradient is the vector of partial derivatives:

∇f(x)=(∂f∂x1,…,∂f∂xn).\nabla f(x) = \left(\frac{\partial f}{\partial x_1}, \dots, \frac{\partial f}{\partial x_n}\right).

Each entry says how fast ff 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 dd changes it by about

f(x+d)≈f(x)+∇f(x)⋅d.f(x + d) \approx f(x) + \nabla f(x)\cdot d .

The dot product ∇f⋅d=∣∇f∣ ∣d∣cos⁡θ\nabla f \cdot d = |\nabla f|\,|d|\cos\theta is biggest when dd points along ∇f\nabla f and most negative when it points exactly the other way (cos⁡θ=−1\cos\theta = -1). So among all steps of a given length, −∇f-\nabla f decreases ff the most. It's also perpendicular to the contour lines: walking along a contour keeps ff constant, so the gradient has no component along it.

The algorithm

Pick a start x0x_0 and a learning rate (step size) η>0\eta > 0. Then repeat

xk+1=xk−η ∇f(xk).x_{k+1} = x_k - \eta\,\nabla f(x_k).

Stop when the gradient is tiny, the loss stops improving, or you run out of time. Notice the step is η\eta 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.

A landscape with four valleys. Drag the gold start point, then press Step or Run. The red arrow is −∇f-\nabla f at the current point (always perpendicular to the contours). Different starts roll into different valleys. Push the learning-rate slider up past about 0.2–0.3 (the limit depends on how steep the valley is) and watch the path start bouncing and then fly off: that's divergence, the subject of chapter 3.

Worked exampleTwo steps by hand

Minimize f(x,y)=x2+3y2f(x, y) = x^2 + 3y^2 from (2,1)(2, 1) with η=0.1\eta = 0.1. The gradient is ∇f=(2x, 6y)\nabla f = (2x,\ 6y).

  • Step 1. ∇f(2,1)=(4,6)\nabla f(2, 1) = (4, 6). New point: (2,1)−0.1 (4,6)=(1.6, 0.4)(2, 1) - 0.1\,(4, 6) = (1.6,\ 0.4). The loss falls from f=4+3=7f = 4 + 3 = 7 to 2.56+0.48=3.042.56 + 0.48 = 3.04.
  • Step 2. ∇f(1.6,0.4)=(3.2,2.4)\nabla f(1.6, 0.4) = (3.2, 2.4). New point: (1.6,0.4)−0.1 (3.2,2.4)=(1.28, 0.16)(1.6, 0.4) - 0.1\,(3.2, 2.4) = (1.28,\ 0.16), with f=1.6384+0.0768=1.7152f = 1.6384 + 0.0768 = 1.7152.

Notice yy shrinks much faster than xx (by 0.4× per step versus 0.8×), because the bowl is steeper in yy. 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 η\eta." The step is η ∣∇f∣\eta\,|\nabla f|. The learning rate is a multiplier, not a distance.
  • "Add the gradient to go downhill." The sign matters: +∇f+\nabla f 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 ∇L\nabla L for a neural network: one backward pass gives the partial derivative for every one of millions of weights. The optimizer then applies the update θ←θ−η∇L\theta \leftarrow \theta - \eta \nabla L, 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 f(x,y)=x2+3y2f(x,y) = x^2 + 3y^2 at (1,2)(1, 2)?

  1. (2,12)(2, 12)
  2. (2,6)(2, 6)
  3. (1,12)(1, 12)
  4. (13,0)(13, 0)

∇f=(2x,6y)=(2,12)\nabla f = (2x, 6y) = (2, 12). Using 3y3y instead of 6y6y gives (2,6)(2,6); 1313 is the function value, not a derivative.

Gradient descent moves the parameters…

  1. in the direction of −∇f-\nabla f, the steepest downhill direction
  2. in the direction of +∇f+\nabla f
  3. straight toward the global minimum
  4. along the contour line through the current point

+∇f+\nabla f 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 f(x)=x2f(x) = x^2 from x0=3x_0 = 3 with learning rate η=0.1\eta = 0.1. What is x1x_1?

  1. 2.4
  2. 2.7
  3. 3.6
  4. 2.9

f′(3)=6f'(3) = 6, so x1=3−0.1⋅6=2.4x_1 = 3 - 0.1\cdot 6 = 2.4. (2.7 forgets the factor 2 in f′f'; 3.6 adds the gradient.)

Minimize f(x,y)=x2+3y2f(x,y) = x^2 + 3y^2 from (2,1)(2, 1) with η=0.1\eta = 0.1. Where are you after one step?

  1. (1.6,0.4)(1.6, 0.4)
  2. (1.8,0.7)(1.8, 0.7)
  3. (2.4,1.6)(2.4, 1.6)
  4. (1.6,0.7)(1.6, 0.7)

∇f(2,1)=(4,6)\nabla f(2,1) = (4, 6), so (2,1)−0.1(4,6)=(1.6,0.4)(2,1) - 0.1(4,6) = (1.6, 0.4). (1.8,0.7)(1.8, 0.7) forgets the factors of 2; (2.4,1.6)(2.4, 1.6) steps uphill.

At some point ∇f=(3,4)\nabla f = (3, 4). Using the linear approximation f(x+d)≈f(x)+∇f⋅df(x+d) \approx f(x) + \nabla f\cdot d, by about how much does a gradient step with η=0.01\eta = 0.01 lower ff?

  1. 0.25
  2. 0.05
  3. 0.07
  4. 2.5

The step is d=−0.01 (3,4)d = -0.01\,(3,4), so ∇f⋅d=−0.01 (9+16)=−0.25\nabla f\cdot d = -0.01\,(9 + 16) = -0.25. In general one small step lowers ff by about η ∣∇f∣2\eta\,|\nabla f|^2. (0.05 uses ∣∇f∣=5|\nabla f| = 5 instead of its square.)

Gradient descent lands exactly on a point where ∇f=0\nabla f = 0. What happens next, and what kind of point is it?

  1. It stays put forever; the point could be a minimum, a maximum or a saddle point
  2. It stays put, and the point must be the global minimum
  3. It keeps moving because of the learning rate
  4. It stays put, and the point must be a local minimum

The update adds −η⋅0=0-\eta\cdot 0 = 0, 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 f(w)=(w−5)2f(w) = (w-5)^2 from w0=1w_0 = 1 with η=0.25\eta = 0.25. What is w3w_3?

  1. 4.5
  2. 5
  3. 4
  4. 4.75

w←w−0.25⋅2(w−5)=w−0.5(w−5)w \leftarrow w - 0.25\cdot2(w-5) = w - 0.5(w - 5): each step halves the distance to 5. Distances: 4, 2, 1, 0.5, so w1=3,w2=4,w3=4.5w_1 = 3, w_2 = 4, w_3 = 4.5. It never quite reaches 5 in finitely many steps.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 3

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 1−ηλ1 - \eta\lambda per step. It converges only if η<2/λmax⁡\eta \lt 2/\lambda_{\max}, and its speed is set by the ratio κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}, the condition number.

The learning rate η\eta 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 f(x)=12λx2f(x) = \tfrac12\lambda x^2, a parabola with curvature f′′(x)=λf''(x) = \lambda. Its gradient is λx\lambda x, so a gradient step is

xk+1=xk−ηλxk=(1−ηλ) xk.x_{k+1} = x_k - \eta\lambda x_k = (1 - \eta\lambda)\,x_k .

Every step multiplies xx by the same number r=1−ηλr = 1 - \eta\lambda, so xk=rkx0x_k = r^k x_0. Everything depends on rr:

  • 0<r<10 \lt r \lt 1 (η<1/λ\eta \lt 1/\lambda): smooth, steady approach from one side. Tiny η\eta means rr is close to 1: very slow.
  • r=0r = 0 (η=1/λ\eta = 1/\lambda): one step lands exactly at the minimum.
  • −1<r<0-1 \lt r \lt 0 (1/λ<η<2/λ1/\lambda \lt \eta \lt 2/\lambda): overshoots to the other side each time, but by less, so it still converges while zig-zagging.
  • ∣r∣≥1|r| \ge 1 (η≥2/λ\eta \ge 2/\lambda): each overshoot is as big or bigger than the last. It diverges.

So the rule is: stable iff 0<η<2/λ0 \lt \eta \lt 2/\lambda. Steeper curvature means a smaller safe step.

Gradient descent on f(x)=x2f(x)=x^2 (curvature 2). Drag the red start point and move the η\eta slider, or try the presets. Watch the factor 1−2η1 - 2\eta: positive and near 1 crawls, 0 lands in one step, negative zig-zags, and past η=1\eta = 1 the steps grow.

Many dimensions: the eigenvalues take over

A general quadratic bowl is f(x)=12x⊤Axf(x) = \tfrac12 x^\top A x with AA symmetric and positive definite (this is what any smooth loss looks like near a minimum). The gradient is AxAx, so

xk+1=xk−ηAxk=(I−ηA) xk.x_{k+1} = x_k - \eta A x_k = (I - \eta A)\,x_k .

This is where linear algebra pays off. Write xx in the eigenvector basis of AA (eigenvalues λ1,…,λn\lambda_1, \dots, \lambda_n). In that basis AA just stretches each coordinate, so the update splits into nn independent 1D problems: the ii-th coordinate gets multiplied by 1−ηλi1 - \eta\lambda_i each step. The eigenvalues are the curvatures along the eigen-directions.

  • Stability needs every factor below 1 in size, so η<2/λmax⁡\eta \lt 2/\lambda_{\max}. The steepest direction sets the speed limit.
  • Speed is set by the slowest factor. With η\eta capped by λmax⁡\lambda_{\max}, the flattest direction (λmin⁡\lambda_{\min}) gets a factor near 1−λmin⁡/λmax⁡1 - \lambda_{\min}/\lambda_{\max}: painfully close to 1 if the bowl is long and thin.

The ratio κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} is the condition number. The best single learning rate balances the two extreme directions so that they shrink equally fast: η∗=2/(λmin⁡+λmax⁡)\eta^* = 2/(\lambda_{\min} + \lambda_{\max}), giving a factor of (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1) per step. For κ=1\kappa = 1 (a round bowl) that's 0: one step. For κ=100\kappa = 100 it's 99/101≈0.9899/101 \approx 0.98: hundreds of steps. That zig-zag across a narrow valley while creeping along it is the signature of a badly conditioned problem.

Gradient descent on f=12(x2+κy2)f = \tfrac12(x^2 + \kappa y^2). Raise κ\kappa to stretch the bowl, and adjust η\eta. The readout shows the shrink factor along each eigen-direction: whichever is larger limits the speed, and if the yy factor passes 1 the path flies off. Use the best η balances them.

Worked exampleA bowl with κ = 10

Let A=(10010)A = \begin{pmatrix}1 & 0\\ 0 & 10\end{pmatrix}, so λmin⁡=1\lambda_{\min} = 1, λmax⁡=10\lambda_{\max} = 10, κ=10\kappa = 10.

  • Largest stable rate: η<2/10=0.2\eta \lt 2/10 = 0.2.
  • η=0.1\eta = 0.1: factors 1−0.1=0.91 - 0.1 = 0.9 along xx and 1−1=01 - 1 = 0 along yy. yy is solved in one step, but xx only shrinks 10% per step: shrinking it 1000-fold takes ⌈ln⁡1000/ln⁡(1/0.9)⌉=66\lceil \ln 1000 / \ln(1/0.9)\rceil = 66 steps.
  • Best rate η∗=2/11≈0.182\eta^* = 2/11 \approx 0.182: factors 1−2/11=9/111 - 2/11 = 9/11 and 1−20/11=−9/111 - 20/11 = -9/11, equal in size. 9/11≈0.8189/11 \approx 0.818, and 1000-fold takes ⌈ln⁡1000/ln⁡(11/9)⌉=35\lceil \ln 1000/\ln(11/9)\rceil = 35 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 η\eta is simply above 2/λmax⁡2/\lambda_{\max} 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, κ\kappa 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 κ\kappa. 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 2/λmax⁡2/\lambda_{\max}, which you don't know in advance.

Practice (pick one answer per question)

Gradient descent on f(x)=x2f(x) = x^2 with η=0.25\eta = 0.25. Each step multiplies xx by…

  1. 0.5
  2. 0.75
  3. 0.25
  4. −0.5

f′(x)=2xf'(x) = 2x, so x←x−0.25⋅2x=(1−0.5)x=0.5xx \leftarrow x - 0.25\cdot 2x = (1 - 0.5)x = 0.5x. The curvature is 2, not 1, which is why 0.75 is wrong.

Gradient descent on f(x)=x2f(x) = x^2 with η=1.2\eta = 1.2. What happens?

  1. It diverges: each step multiplies xx by −1.4
  2. It converges, zig-zagging
  3. It converges in one step
  4. It converges slowly from one side

The factor is 1−2(1.2)=−1.41 - 2(1.2) = -1.4. Its size is above 1, so ∣x∣|x| grows by 40% each step while flipping sign. The limit is η<2/f′′=1\eta \lt 2/f'' = 1.

What is the largest learning rate for which gradient descent converges on f(x)=2x2f(x) = 2x^2 (i.e. the boundary value)?

  1. 0.5
  2. 1
  3. 0.25
  4. 2

f′′(x)=4f''(x) = 4, so we need η<2/4=0.5\eta \lt 2/4 = 0.5. (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?

  1. 25
  2. 48
  3. 100
  4. 52

κ=λmax⁡/λmin⁡=50/2=25\kappa = \lambda_{\max}/\lambda_{\min} = 50/2 = 25. It's a ratio, not a difference.

For f(x)=12x⊤Axf(x) = \tfrac12 x^\top A x with A=(3113)A = \begin{pmatrix}3 & 1\\ 1 & 3\end{pmatrix}, what is the largest stable learning rate (the boundary)?

  1. 0.5
  2. 2/32/3
  3. 1
  4. 0.4

The eigenvalues are 3±13 \pm 1: 4 and 2. Stability needs η<2/λmax⁡=2/4=0.5\eta \lt 2/\lambda_{\max} = 2/4 = 0.5. Reading the diagonal entry 3 as the curvature gives 2/32/3, which would diverge along the eigenvector (1,1)(1,1).

With Hessian eigenvalues 2 and 50 and the best fixed learning rate η∗=2/(λmin⁡+λmax⁡)\eta^* = 2/(\lambda_{\min} + \lambda_{\max}), by what factor does the error shrink per step (in the worst direction)?

  1. about 0.923
  2. about 0.96
  3. 0.5
  4. about 0.038

κ=25\kappa = 25, and the factor is (κ−1)/(κ+1)=24/26≈0.923(\kappa - 1)/(\kappa + 1) = 24/26 \approx 0.923. Check: η∗=2/52\eta^* = 2/52, so 1−2η∗≈0.9231 - 2\eta^* \approx 0.923 and 1−50η∗≈−0.9231 - 50\eta^* \approx -0.923. (0.038 is η∗\eta^* itself.)

For A=diag⁡(1,100)A = \operatorname{diag}(1, 100) and η=0.019\eta = 0.019, which direction limits the speed of convergence, and what is its per-step factor?

  1. The λ=1\lambda = 1 direction, factor 0.981
  2. The λ=100\lambda = 100 direction, factor 0.9
  3. The λ=100\lambda = 100 direction, factor −0.9
  4. Both equally, factor 0.95

Factors: ∣1−0.019∣=0.981|1 - 0.019| = 0.981 and ∣1−1.9∣=0.9|1 - 1.9| = 0.9. The larger one, 0.981, is the bottleneck: the flat direction. That's typical: the rate is capped (here just under 2/1002/100) by the steep direction, so the flat one crawls.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 4

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:

L(θ)=1N∑i=1Nℓi(θ),∇L(θ)=1N∑i=1N∇ℓi(θ).L(\theta) = \frac1N\sum_{i=1}^{N}\ell_i(\theta), \qquad \nabla L(\theta) = \frac1N\sum_{i=1}^{N}\nabla\ell_i(\theta).

Computing the exact gradient means touching all NN examples, and NN 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 BB of bb examples (typically 32 to a few thousand) and use their average gradient instead:

gB(θ)=1b∑i∈B∇ℓi(θ),θ←θ−η gB(θ).g_B(\theta) = \frac1b\sum_{i\in B}\nabla\ell_i(\theta), \qquad \theta \leftarrow \theta - \eta\, g_B(\theta).

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 σ2\sigma^2, the average of bb independent ones has variance σ2/b\sigma^2/b, so its standard deviation shrinks like 1/b1/\sqrt{b}. Quadrupling the batch only halves the noise.

That 1/b1/\sqrt{b} 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: b=1b = 1 is stochastic gradient descent (SGD) in the strict sense; 1<b<N1 \lt b \lt N is mini-batch GD; people loosely call all of it "SGD". One pass through the whole dataset is an epoch: with NN examples and batch size bb, that's ⌈N/b⌉\lceil N/b\rceil steps. In practice you shuffle the data each epoch and walk through it in chunks, so every example is used once per epoch.

Fitting a line to 60 noisy points; the map is the (w,b)(w, b) loss landscape. Press Run: the blue path uses all 60 points every step, the gold path uses a random mini-batch. Small batches wander, but head the same way and cost far less per step. Raise the batch size and the gold path tightens toward the blue one. Near the bottom the gold path never quite settles: it jitters around the minimum.

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 η\eta and shrinks with bb. 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 θ\theta are 2,−1,4,32, -1, 4, 3.

  • The full gradient is their mean: (2−1+4+3)/4=2(2 - 1 + 4 + 3)/4 = 2.
  • Shuffle into two mini-batches of 2, say {2,−1}\{2, -1\} and {4,3}\{4, 3\}. Their gradients are 0.50.5 and 3.53.5: 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 12/6=212/6 = 2, exactly the full gradient. Unbiased.

One epoch here is 4/2=24/2 = 2 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 2\sqrt{2}.
  • "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?

  1. 500
  2. 100
  3. 5,000,000
  4. 50,000

One epoch uses every example once: 50,000/100=50050{,}000/100 = 500 steps.

Gradient descent that uses a batch of exactly one example per step is usually called…

  1. stochastic gradient descent
  2. full-batch gradient descent
  3. Newton's method
  4. momentum

Batch size 1 is the original "stochastic" gradient descent. Batch size NN is full-batch; anything in between is mini-batch.

Per-example gradients are 1,3,5,71, 3, 5, 7 (one parameter). What is the gradient from the mini-batch {3,7}\{3, 7\}?

  1. 5
  2. 10
  3. 4
  4. 2.5

A mini-batch gradient is the mean of its examples' gradients: (3+7)/2=5(3 + 7)/2 = 5. (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)?

  1. It halves
  2. It drops to a quarter
  3. It doubles
  4. It stays the same

Variance scales like 1/b1/b, so it drops by 4×; the standard deviation is its square root, so it drops by 4=2\sqrt{4} = 2.

Why does SGD make progress even though each step uses a noisy gradient?

  1. A random mini-batch gradient is an unbiased estimate: on average it equals the true gradient
  2. The noise always points toward the minimum
  3. Mini-batch gradients are always smaller than the true gradient
  4. 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.

N=1000N = 1000 examples, batch size 32, and the last batch of each epoch may be smaller. How many steps per epoch?

  1. 32
  2. 31
  3. 31.25
  4. 33

1000/32=31.251000/32 = 31.25: 31 full batches use 992 examples, and the remaining 8 form a 32nd, smaller batch. So ⌈31.25⌉=32\lceil 31.25\rceil = 32. (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?

  1. 0.4
  2. 0.2
  3. 0.025
  4. 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 η\eta by 4 keeps the distance travelled per epoch similar: 0.40.4. (Scaling with 4\sqrt{4} 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)

Chapter 5

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):

vk+1=β vk+∇f(xk),xk+1=xk−η vk+1,v_{k+1} = \beta\, v_k + \nabla f(x_k), \qquad x_{k+1} = x_k - \eta\, v_{k+1},

starting from v0=0v_0 = 0. The new number β\beta (usually 0.9) says how much of the old velocity survives each step: it's like friction, with β=0\beta = 0 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:

vk+1=∇f(xk)+β ∇f(xk−1)+β2 ∇f(xk−2)+⋯v_{k+1} = \nabla f(x_k) + \beta\,\nabla f(x_{k-1}) + \beta^2\,\nabla f(x_{k-2}) + \cdots

Two cases explain everything:

  • The gradient keeps pointing the same way (along the valley floor). Then vv approaches g(1+β+β2+⋯ )=g/(1−β)g(1 + \beta + \beta^2 + \cdots) = g/(1-\beta). With β=0.9\beta = 0.9 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, g−βg+β2g−⋯=g/(1+β)g - \beta g + \beta^2 g - \cdots = g/(1+\beta), 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 η\eta and β\beta, the per-step factor improves from about 1−1/κ1 - 1/\kappa to about 1−1/κ1 - 1/\sqrt{\kappa}. For κ=100\kappa = 100 that's roughly 10 times fewer steps.

A long, tilted valley. Press Run: blue is plain gradient descent, gold is momentum with the same η\eta. Momentum overshoots a little at first (it's a heavy ball), then races along the valley floor. Set β\beta to 0 and the two paths coincide; push β\beta toward 0.98 and the ball swings around much longer before settling.

Two ways of writing it, and Nesterov

You'll also see the averaged form (used in Andrew Ng's course): v←βv+(1−β)∇fv \leftarrow \beta v + (1-\beta)\nabla f, x←x−ηvx \leftarrow x - \eta v. Here vv is an exponentially weighted average of gradients rather than a sum, so it's (1−β)(1-\beta) times smaller. The two forms produce identical paths if you rescale the learning rate: averaged form with η\eta equals summed form with η(1−β)\eta(1-\beta). 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, ∇f(xk−ηβvk)\nabla f(x_k - \eta\beta v_k), instead of at xkx_k. 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 g=2g = 2 (a straight ramp), with η=0.1\eta = 0.1 and β=0.9\beta = 0.9.

  • v1=0.9⋅0+2=2v_1 = 0.9\cdot0 + 2 = 2: step of 0.1⋅2=0.20.1\cdot 2 = 0.2, the same as plain GD.
  • v2=0.9⋅2+2=3.8v_2 = 0.9\cdot2 + 2 = 3.8: step 0.38.
  • v3=0.9⋅3.8+2=5.42v_3 = 0.9\cdot3.8 + 2 = 5.42: step 0.542.
  • In the long run v→2/(1−0.9)=20v \to 2/(1-0.9) = 20: 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 η\eta.
  • "Momentum can't diverge if GD doesn't." The stable range changes. On a quadratic, heavy-ball momentum is stable when 0<ηλ<2(1+β)0 \lt \eta\lambda \lt 2(1+\beta) for every eigenvalue, so with vv as a sum it tolerates a larger ηλ\eta\lambda than GD, but its effective step is also 1/(1−β)1/(1-\beta) times larger.
  • "The two momentum formulas are different algorithms." They differ only by a rescaling of η\eta.

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 ~1/(1−β)1/(1-\beta) 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 β=0.9\beta = 0.9 and a gradient that stays constant at gg, the velocity v←βv+gv \leftarrow \beta v + g approaches…

  1. 10g10g
  2. 0.9g0.9g
  3. gg
  4. 9g9g

The fixed point solves v=0.9v+gv = 0.9v + g, so v=g/(1−0.9)=10gv = g/(1 - 0.9) = 10g.

Momentum helps most when the loss landscape…

  1. is a long, narrow valley where plain GD zig-zags
  2. is a perfectly round bowl
  3. has a gradient of exactly zero
  4. 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 η\eta is already ideal.

v0=0v_0 = 0, β=0.5\beta = 0.5, and the gradient is 4 at every step. What is v3v_3 (using v←βv+gv \leftarrow \beta v + g)?

  1. 7
  2. 6
  3. 8
  4. 12

v1=4v_1 = 4, v2=0.5⋅4+4=6v_2 = 0.5\cdot4 + 4 = 6, v3=0.5⋅6+4=7v_3 = 0.5\cdot6 + 4 = 7. (It's heading toward 4/(1−0.5)=84/(1-0.5) = 8.)

With β=0.99\beta = 0.99, along a direction where the gradient is constant the velocity grows to about how many times a single gradient?

  1. 100
  2. 99
  3. 10
  4. 1.01

1/(1−β)=1/0.01=1001/(1-\beta) = 1/0.01 = 100.

v0=0v_0 = 0, β=0.9\beta = 0.9. The gradient is +1+1 at the first step and −1-1 at the second. What is v2v_2?

  1. −0.1
  2. −1
  3. 0
  4. −1.9

v1=1v_1 = 1, then v2=0.9⋅1+(−1)=−0.1v_2 = 0.9\cdot1 + (-1) = -0.1. The flip almost cancels the old velocity, so the step is only a tenth of plain GD's: oscillations get damped.

The averaged form v←0.9v+0.1∇fv \leftarrow 0.9v + 0.1\nabla f, x←x−0.1vx \leftarrow x - 0.1v gives exactly the same path as the summed form v←0.9v+∇fv \leftarrow 0.9v + \nabla f, x←x−η′vx \leftarrow x - \eta' v when η′\eta' is…

  1. 0.01
  2. 0.1
  3. 1
  4. 0.09

The averaged velocity is (1−β)=0.1(1-\beta) = 0.1 times the summed one at every step, so 0.1⋅vavg=0.1⋅0.1⋅vsum0.1\cdot v_{\text{avg}} = 0.1\cdot0.1\cdot v_{\text{sum}}. Hence η′=η(1−β)=0.01\eta' = \eta(1-\beta) = 0.01.

Heavy-ball momentum on f(x)=12λx2f(x) = \tfrac12\lambda x^2 is stable exactly when 0<ηλ<2(1+β)0 \lt \eta\lambda \lt 2(1+\beta). With λ=10\lambda = 10 and β=0.9\beta = 0.9, what is the largest stable η\eta (the boundary)?

  1. 0.38
  2. 0.2
  3. 0.02
  4. 3.8

η<2(1+0.9)/10=3.8/10=0.38\eta \lt 2(1+0.9)/10 = 3.8/10 = 0.38. Plain GD's limit would be 2/10=0.22/10 = 0.2. (Forgetting to divide by λ\lambda gives 3.8.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 6

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 1−βt1-\beta^t.

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):

s←ρ s+(1−ρ) g2,x←x−η gs+ϵ.s \leftarrow \rho\, s + (1-\rho)\, g^2, \qquad x \leftarrow x - \eta\,\frac{g}{\sqrt{s} + \epsilon}.

Everything is element-wise: each parameter has its own ss. Typical values are ρ=0.9\rho = 0.9 and a tiny ϵ\epsilon like 10−810^{-8} to avoid dividing by zero. If a parameter's gradients are around 100, s≈100\sqrt{s} \approx 100 and its step is about η\eta. If another's are around 0.01, s≈0.01\sqrt{s} \approx 0.01 and its step is also about η\eta. 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 vt=βvt−1+(1−β)gtv_t = \beta v_{t-1} + (1-\beta)g_t. Unrolled, vt=(1−β)∑k=1tβt−kgkv_t = (1-\beta)\sum_{k=1}^{t}\beta^{t-k} g_k: recent values count most, and the average effectively covers the last 1/(1−β)1/(1-\beta) or so steps. But we start from v0=0v_0 = 0, and the weights (1−β)(1+β+⋯+βt−1)(1-\beta)(1 + \beta + \cdots + \beta^{t-1}) add up to only 1−βt1 - \beta^t, not 1. At t=1t = 1 with β=0.9\beta = 0.9 the "average" is 0.1 g10.1\,g_1: ten times too small.

The fix is simple: divide by the total weight. The bias-corrected average is

v^t=vt1−βt.\hat v_t = \frac{v_t}{1 - \beta^t}.

At t=1t=1, v^1=0.1g1/0.1=g1\hat v_1 = 0.1 g_1/0.1 = g_1, exactly right. As tt grows, βt→0\beta^t \to 0 and the correction fades away. If every gkg_k equals the same number cc, then vt=c(1−βt)v_t = c(1-\beta^t) and v^t=c\hat v_t = c exactly, at every step.

Noisy data hovering around 5 (grey dots), with its exponentially weighted average. The red curve starts at 0 and takes a while to climb up to the data; the green bias-corrected curve is right from the first step. Raise β\beta and the average gets smoother, the start-up lag gets longer, and the correction matters more.

Adam = momentum + RMSProp + bias correction

Adam ("adaptive moment estimation") keeps both averages for every parameter, corrects both, and combines them. At step t=1,2,…t = 1, 2, \dots with gradient gtg_t:

mt=β1mt−1+(1−β1) gtm^t=mt/(1−β1t)vt=β2vt−1+(1−β2) gt2v^t=vt/(1−β2t)xt=xt−1−η m^tv^t+ϵ\begin{aligned} m_t &= \beta_1 m_{t-1} + (1-\beta_1)\,g_t & \hat m_t &= m_t/(1-\beta_1^t)\\ v_t &= \beta_2 v_{t-1} + (1-\beta_2)\,g_t^2 & \hat v_t &= v_t/(1-\beta_2^t)\\ x_t &= x_{t-1} - \eta\,\frac{\hat m_t}{\sqrt{\hat v_t} + \epsilon} \end{aligned}

The defaults are β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}, and η=0.001\eta = 0.001 (often 3e-4 for transformers). mm is the momentum ("which way, on average?") and vv the scale ("how big, on average?"). Their ratio is roughly "signal over noise": close to ±1\pm1 when the gradient is consistent, and small when it keeps changing sign.

Why the correction matters so much for Adam. β2=0.999\beta_2 = 0.999 averages over about 1000 steps, so without correction vv stays far too small for hundreds of steps. At step 1, the uncorrected ratio is m1/v1=0.1g/0.001g2≈3.16 sign(g)m_1/\sqrt{v_1} = 0.1g/\sqrt{0.001g^2} \approx 3.16\,\text{sign}(g): a first step more than three times bigger than intended, in a direction based on one noisy gradient. With correction, m^1/v^1=g/∣g∣=±1\hat m_1/\sqrt{\hat v_1} = g/|g| = \pm1, so the first step has size exactly η\eta.

Four optimizers race on the same surface from the same start. On the Rosenbrock banana (minimum at the green dot), plain GD barely gets into the curved valley, momentum swings along it, and the adaptive methods take near-constant-size steps. Switch to the stretched bowl, drag the start, and try the learning-rate multiplier: notice how RMSProp, with no momentum, ends up jittering around the minimum at a fixed step size.

Worked exampleAdam's first step

One parameter, first gradient g1=0.5g_1 = 0.5, defaults β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, η=0.001\eta = 0.001 (ignore ϵ\epsilon).

  • m1=0.1⋅0.5=0.05m_1 = 0.1\cdot0.5 = 0.05, and m^1=0.05/(1−0.9)=0.5\hat m_1 = 0.05/(1-0.9) = 0.5.
  • v1=0.001⋅0.25=0.00025v_1 = 0.001\cdot0.25 = 0.00025, and v^1=0.00025/(1−0.999)=0.25\hat v_1 = 0.00025/(1-0.999) = 0.25, so v^1=0.5\sqrt{\hat v_1} = 0.5.
  • Step: η⋅0.5/0.5=0.001\eta\cdot 0.5/0.5 = 0.001. The parameter moves by exactly η\eta, whatever the size of g1g_1.
  • Without correction: 0.05/0.00025≈3.1620.05/\sqrt{0.00025} \approx 3.162, a step of 0.00316.

Watch outCommon misconceptions

  • "Adam doesn't need a learning rate." It still has η\eta, 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 η\eta times the gradient." Its step is roughly η\eta 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.optim.AdamW(model.parameters(), lr=3e-4). Per-parameter scaling matters there because different layers (embeddings, attention, layer norms) have gradients of wildly different sizes. Adam does cost memory: it stores mm and vv, 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 β=0.9\beta = 0.9, the bias-correction factor 1/(1−βt)1/(1-\beta^t) at step t=1t = 1 is…

  1. 10
  2. 0.1
  3. 1
  4. 0.9

1/(1−0.9)=1/0.1=101/(1 - 0.9) = 1/0.1 = 10. It exactly undoes the factor 1−β=0.11 - \beta = 0.1 that the first average was shrunk by.

RMSProp divides each parameter's gradient by…

  1. the square root of a running average of that parameter's squared gradients
  2. the number of parameters
  3. the running average of the loss
  4. the size of the whole gradient vector

Each parameter keeps its own ss, an average of g2g^2, and the step is ηg/(s+ϵ)\eta g/(\sqrt{s} + \epsilon). Dividing by the norm of the whole vector is what gradient clipping does (chapter 12), and it's not per-parameter.

RMSProp with s0=0s_0 = 0, ρ=0.9\rho = 0.9 and first gradient g=2g = 2. What is s1s_1?

  1. 0.4
  2. 3.6
  3. 0.2
  4. 4

s1=0.9⋅0+0.1⋅22=0.4s_1 = 0.9\cdot0 + 0.1\cdot 2^2 = 0.4. (0.2 forgets to square; 3.6 swaps ρ\rho and 1−ρ1-\rho.) The step is then η⋅2/0.4≈3.16η\eta\cdot 2/\sqrt{0.4} \approx 3.16\eta, the start-up overshoot that bias correction would fix.

Ignoring ϵ\epsilon, how big is Adam's very first step (per parameter, with a nonzero gradient)?

  1. exactly η\eta
  2. η ∣g1∣\eta\,|g_1|
  3. 10η10\eta
  4. η/∣g1∣\eta/\sqrt{|g_1|}

m^1=g1\hat m_1 = g_1 and v^1=g12\hat v_1 = g_1^2, so the step is η g1/∣g1∣=±η\eta\,g_1/|g_1| = \pm\eta.

Two parameters have gradients that stay constant at 100 and at 0.01. After many Adam steps, how do their step sizes compare?

  1. Both steps are about η\eta
  2. The first steps 10,000 times further
  3. The second steps 10,000 times further
  4. The first steps 100 times further

For a constant gradient cc, m^→c\hat m \to c and v^→∣c∣\sqrt{\hat v} \to |c|, so each step is η c/∣c∣=±η\eta\,c/|c| = \pm\eta. Adam is invariant to rescaling a parameter's gradient; plain GD would step 10,000 times further on the first.

With β2=0.999\beta_2 = 0.999, at step t=10t = 10 the correction v^10=v10/(1−0.99910)\hat v_{10} = v_{10}/(1 - 0.999^{10}) multiplies v10v_{10} by about…

  1. 100
  2. 10
  3. 1000
  4. 1.01

0.99910≈0.990040.999^{10} \approx 0.99004, so 1−0.99910≈0.009951 - 0.999^{10} \approx 0.00995 and the factor is about 100.5100.5. Ten steps in, vv 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, ϵ→0\epsilon \to 0), how big is the first step?

  1. about 3.16η3.16\eta
  2. exactly η\eta
  3. about 0.1η0.1\eta
  4. about 31.6η31.6\eta

m1=0.1gm_1 = 0.1g and v1=0.001 ∣g∣≈0.0316∣g∣\sqrt{v_1} = \sqrt{0.001}\,|g| \approx 0.0316|g|. The ratio is 0.1/0.0316≈3.160.1/0.0316 \approx 3.16. The two missing corrections, 10 for mm and 1000 for vv (1000≈31.6\sqrt{1000} \approx 31.6 after the square root), don't cancel.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 7

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. ff is convex if for any two points a,ba, b and any t∈[0,1]t \in [0, 1],

f(ta+(1−t)b)≤tf(a)+(1−t)f(b).f\big(t a + (1-t) b\big) \le t f(a) + (1-t) f(b).

The left side is the curve between aa and bb; the right side is the straight chord joining (a,f(a))(a, f(a)) and (b,f(b))(b, f(b)). Convex means the curve never pokes above any chord. A useful special case is t=12t = \tfrac12: the value at the midpoint is at most the average of the end values.

2. The tangent test (for differentiable ff). Every tangent line (or plane) lies below the graph:

f(y)≥f(x)+∇f(x)⋅(y−x)for all x,y.f(y) \ge f(x) + \nabla f(x)\cdot(y - x) \quad \text{for all } x, y.

This one is the key to everything. If ∇f(x)=0\nabla f(x) = 0, it says f(y)≥f(x)f(y) \ge f(x) for every yy: a flat point is automatically a global minimum.

3. The curvature test (for twice-differentiable ff). In 1D, f′′(x)≥0f''(x) \ge 0 everywhere. In many dimensions, the Hessian matrix of second derivatives is positive semidefinite everywhere: all its eigenvalues are ≥0\ge 0, so the function curves upward (or is flat) in every direction.

Drag the two gold ends of the chord. Where the curve pokes above the chord the gap is shaded red. For the convex functions (x2/2x^2/2, ∣x∣+x/3|x| + x/3, ex/4e^x/4) no chord ever fails, even across the kink of ∣x∣|x|. For the two non-convex ones, find a chord that fails: put the ends on either side of a bump.

Why convex problems are easy

  • No bad local minima. Every local minimum is global. Suppose xx is a local minimum but some yy has f(y)<f(x)f(y) \lt f(x). The chord from xx to yy slopes down, and by convexity the curve lies on or below it. So even points a tiny step from xx toward yy are lower than f(x)f(x), which contradicts "local minimum".
  • The minimizers form one connected blob (a convex set), and if ff 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 μ>0\mu > 0 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 f(Ax+b)f(Ax + b), is convex. Products of convex functions are not always convex.

This gives the ML catalogue: the MSE of a linear model, ∥Xw−y∥2\|Xw - y\|^2, is convex in ww (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) f(x)=x2f(x) = x^2 by the midpoint test. f(a)+f(b)2−f(a+b2)=a2+b22−a2+2ab+b24=(a−b)24≥0\frac{f(a) + f(b)}2 - f\big(\frac{a+b}2\big) = \frac{a^2 + b^2}{2} - \frac{a^2 + 2ab + b^2}{4} = \frac{(a - b)^2}{4} \ge 0. The chord's midpoint is never below the curve.

(b) f(x,y)=x2+xy+y2f(x, y) = x^2 + xy + y^2 by the Hessian. H=(2112)H = \begin{pmatrix}2 & 1\\1 & 2\end{pmatrix}, with eigenvalues 33 and 11 (eigenvectors (1,1)(1,1) and (1,−1)(1,-1)). Both positive, so ff is (strictly) convex with a single minimum at (0,0)(0, 0).

(c) A non-convex one. f(x)=x4/4−x2f(x) = x^4/4 - x^2: f′′(x)=3x2−2f''(x) = 3x^2 - 2, which is −2<0-2 \lt 0 at x=0x = 0. Midpoint test with a=−1,b=1a = -1, b = 1: f(0)=0f(0) = 0, but the average of the ends is −0.75-0.75. The curve pokes above the chord.

Watch outCommon misconceptions

  • "Convex functions must be smooth." ∣x∣|x| and max⁡(0,x)\max(0, x) are convex with kinks. The chord test doesn't need derivatives.
  • "Convex means it has a minimum." exe^x 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 ex/4e^x/4.
  • "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?

  1. x2x^2
  2. −x2-x^2
  3. sin⁡x\sin x
  4. x3x^3

x2x^2 has f′′=2≥0f'' = 2 \ge 0. −x2-x^2 is concave (f′′=−2f'' = -2), sin⁡x\sin x curves both ways, and x3x^3 has f′′=6xf'' = 6x, negative for x<0x \lt 0.

For a convex function, a local minimum is…

  1. always a global minimum
  2. never a global minimum
  3. always the unique minimizer
  4. 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 f(x,y)=x2+xy+y2f(x,y) = x^2 + xy + y^2 is (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix}. What are its eigenvalues, and is ff convex?

  1. 3 and 1: convex
  2. 2 and 2: convex
  3. 3 and −1: not convex
  4. 1 and 1: convex

For (abba)\begin{pmatrix}a&b\\b&a\end{pmatrix} the eigenvalues are a±b=3,1a \pm b = 3, 1. Both positive, so the Hessian is positive definite and ff is strictly convex. (Reading the diagonal gives "2 and 2", which ignores the off-diagonal coupling.)

For f(x)=x4−2x2f(x) = x^4 - 2x^2, what is f′′(0)f''(0), and what does it tell you?

  1. −4, so ff is not convex
  2. 0, so ff is convex
  3. 4, so ff is convex
  4. −2, so ff is not convex

f′(x)=4x3−4xf'(x) = 4x^3 - 4x, f′′(x)=12x2−4f''(x) = 12x^2 - 4, so f′′(0)=−4<0f''(0) = -4 \lt 0: the graph curves downward there (it's a local maximum between two valleys at x=±1x = \pm1).

For f(x)=x4/4−x2f(x) = x^4/4 - x^2, compare f(0)f(0) with the average (f(−1)+f(1))/2(f(-1) + f(1))/2. What do you conclude?

  1. f(0)=0>−0.75f(0) = 0 \gt -0.75: the midpoint is above the chord, so ff is not convex
  2. f(0)=0<0.75f(0) = 0 \lt 0.75: consistent with convexity
  3. They're equal, so ff is linear between −1 and 1
  4. f(0)=−0.75f(0) = -0.75: the midpoint is below the chord, so ff is convex

f(±1)=1/4−1=−0.75f(\pm1) = 1/4 - 1 = -0.75, so the chord's midpoint height is −0.75-0.75, while f(0)=0f(0) = 0 is higher. One failing chord is enough to prove non-convexity. (Passing one chord would prove nothing.)

The Hessian of f(x,y)=12x2+2xy+12y2f(x,y) = \tfrac12x^2 + 2xy + \tfrac12y^2 is (1221)\begin{pmatrix}1&2\\2&1\end{pmatrix}. Is ff convex?

  1. No: the eigenvalues are 3 and −1
  2. Yes: all entries are positive
  3. Yes: the eigenvalues are 3 and 1
  4. Yes: the trace is positive

Eigenvalues 1±21 \pm 2: 3 and −1. Along (1,−1)(1, -1) the function curves downward (it's a saddle). Positive entries or a positive trace don't make a matrix positive semidefinite; the determinant 1−4=−3<01 - 4 = -3 \lt 0 already gives it away.

ff and gg are convex functions of xx. Which combination is not guaranteed to be convex?

  1. f(x)⋅g(x)f(x)\cdot g(x)
  2. f(x)+g(x)f(x) + g(x)
  3. max⁡(f(x),g(x))\max(f(x), g(x))
  4. 3f(x)3f(x)

Sums, maxima and nonnegative multiples preserve convexity. Products don't: f(x)=xf(x) = x and g(x)=x2g(x) = x^2 are both convex, but x3x^3 is not.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 8

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 ∇f=0\nabla f = 0 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: f′′>0f'' \gt 0 is a valley bottom, f′′<0f'' \lt 0 a hilltop. In many dimensions we need the second derivatives in every direction at once.

The Hessian

The Hessian of f(x1,…,xn)f(x_1, \dots, x_n) is the n×nn \times n matrix of second partial derivatives,

Hij=∂2f∂xi ∂xj.H_{ij} = \frac{\partial^2 f}{\partial x_i\,\partial x_j}.

For smooth functions it's symmetric (Hij=HjiH_{ij} = H_{ji}), 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

f(x+d)≈f(x)+∇f(x)⋅d+12 d⊤Hd.f(x + d) \approx f(x) + \nabla f(x)\cdot d + \tfrac12\, d^\top H d .

At a critical point the middle term vanishes, so near it the function is just the quadratic 12d⊤Hd\tfrac12 d^\top H d. Write dd in the eigenvector basis, d=∑ciuid = \sum c_i u_i, and this becomes 12∑iλici2\tfrac12\sum_i \lambda_i c_i^2: each eigenvector is a direction, and its eigenvalue is the curvature along it.

  • All λi>0\lambda_i \gt 0 (positive definite): up in every direction. A local minimum.
  • All λi<0\lambda_i \lt 0: 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 λi=0\lambda_i = 0: the test is inconclusive in those flat directions; higher-order terms decide.

In 2D there's a shortcut: det⁡H=λ1λ2\det H = \lambda_1\lambda_2 and tr⁡H=λ1+λ2\operatorname{tr} H = \lambda_1 + \lambda_2. A negative determinant means opposite signs, so a saddle; a positive determinant with a positive trace means a minimum.

The surface f=12(ax2+2cxy+by2)f = \tfrac12(ax^2 + 2cxy + by^2), whose Hessian is (accb)\begin{pmatrix}a & c\\ c & b\end{pmatrix}. Drag to rotate. The arrows on the floor are the Hessian's eigenvectors, labelled with their eigenvalues (green for positive, red for negative), and the thick curves are the surface sliced along them. Try the presets, then set a=b=0.5a = b = 0.5 and slowly raise cc: the bowl turns into a saddle exactly when cc passes 0.5 and det⁡H\det H changes sign.

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 nn variables, imagine each Hessian eigenvalue is equally likely to be positive or negative. Then the chance that all nn are positive (a true minimum) is 2−n2^{-n}. With n=1000n = 1000 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 f(x,y)=x3−3x+y2f(x, y) = x^3 - 3x + y^2.

  • Gradient: ∇f=(3x2−3, 2y)\nabla f = (3x^2 - 3,\ 2y). Setting it to zero gives x=±1x = \pm1, y=0y = 0: critical points (1,0)(1, 0) and (−1,0)(-1, 0).
  • Hessian: H=(6x002)H = \begin{pmatrix}6x & 0\\ 0 & 2\end{pmatrix}.
  • At (1,0)(1, 0): eigenvalues 66 and 22, both positive. A local minimum, with f(1,0)=1−3=−2f(1, 0) = 1 - 3 = -2.
  • At (−1,0)(-1, 0): eigenvalues −6-6 and 22. A saddle: going along yy is uphill, going along xx is downhill. (f(−1,0)=2f(-1,0) = 2.)

Note (1,0)(1, 0) is only a local minimum: f→−∞f \to -\infty as x→−∞x \to -\infty. This ff 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. (1221)\begin{pmatrix}1 & 2\\2 & 1\end{pmatrix} 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 λmax⁡\lambda_{\max} 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 λmax⁡\lambda_{\max} rises until it hovers near 2/η2/\eta: 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?

  1. a saddle point
  2. a local minimum
  3. a local maximum
  4. 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…

  1. the matrix of its second partial derivatives
  2. the vector of its first partial derivatives
  3. the inverse of its gradient
  4. the matrix whose columns are its eigenvectors

Hij=∂2f/∂xi∂xjH_{ij} = \partial^2 f/\partial x_i \partial x_j. The vector of first derivatives is the gradient.

f(x,y)=x2−y2f(x,y) = x^2 - y^2 has a critical point at the origin. Starting just next to it, which direction leads downhill fastest?

  1. along the yy-axis (either way)
  2. along the xx-axis
  3. along the line y=xy = x
  4. none: the origin is a minimum

H=diag⁡(2,−2)H = \operatorname{diag}(2, -2). The eigenvalue −2 belongs to the yy direction, where f=−y2f = -y^2 falls. Along y=xy = x, f=0f = 0: flat.

What are the eigenvalues of the Hessian of f(x,y)=x2+4xy+y2f(x, y) = x^2 + 4xy + y^2?

  1. 6 and −2
  2. 2 and 2
  3. 4 and 0
  4. 6 and 2

H=(2442)H = \begin{pmatrix}2 & 4\\ 4 & 2\end{pmatrix} (note ∂2f/∂x∂y=4\partial^2 f/\partial x\partial y = 4). Eigenvalues 2±4=6,−22 \pm 4 = 6, -2: the origin is a saddle.

At a critical point with H=diag⁡(4,−2)H = \operatorname{diag}(4, -2), you move by d=(0.1,0.1)d = (0.1, 0.1). By the second-order approximation, how much does ff change?

  1. +0.01
  2. +0.02
  3. −0.01
  4. +0.06

12d⊤Hd=12(4⋅0.01−2⋅0.01)=12(0.02)=0.01\tfrac12 d^\top H d = \tfrac12(4\cdot0.01 - 2\cdot0.01) = \tfrac12(0.02) = 0.01. The uphill xx part outweighs the downhill yy 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?

  1. 1/10241/1024
  2. 1/201/20
  3. 1/21/2
  4. 1/1001/100

All 10 must be positive: (1/2)10=1/1024(1/2)^{10} = 1/1024. With millions of parameters, minima would be astronomically rare among critical points under this toy model; most are saddles.

For f(x,y)=x3−3x+y2f(x,y) = x^3 - 3x + y^2, what is the point (−1,0)(-1, 0)?

  1. a saddle point
  2. a local minimum
  3. a local maximum
  4. not a critical point

∇f(−1,0)=(3−3,0)=(0,0)\nabla f(-1, 0) = (3 - 3, 0) = (0, 0), so it's critical. H=diag⁡(6x,2)=diag⁡(−6,2)H = \operatorname{diag}(6x, 2) = \operatorname{diag}(-6, 2): mixed signs, so a saddle. (Its twin (1,0)(1, 0) is the local minimum.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 9

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 λ2∥w∥2\tfrac\lambda2\|w\|^2 shrinks every weight smoothly toward zero (that's "weight decay"). An L1 penalty λ∥w∥1\lambda\|w\|_1 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

minimizeL(w)+λ R(w),\text{minimize}\quad L(w) + \lambda\,R(w),

where RR measures the size of ww and λ≥0\lambda \ge 0 sets the trade-off. The two classics are

  • L2 (ridge): R(w)=12∥w∥22=12∑iwi2R(w) = \tfrac12\|w\|_2^2 = \tfrac12\sum_i w_i^2.
  • L1 (lasso): R(w)=∥w∥1=∑i∣wi∣R(w) = \|w\|_1 = \sum_i |w_i|.

L2 is weight decay

The gradient of λ2∥w∥2\tfrac\lambda2\|w\|^2 is just λw\lambda w. So a gradient step on the regularized loss is

w←w−η(∇L(w)+λw)=(1−ηλ) w−η∇L(w).w \leftarrow w - \eta\big(\nabla L(w) + \lambda w\big) = (1 - \eta\lambda)\,w - \eta\nabla L(w).

Before the usual step, every weight is multiplied by 1−ηλ1 - \eta\lambda, 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 tt matching each λ\lambda) to a constraint: minimize L(w)L(w) subject to R(w)≤tR(w) \le t. In 2D the allowed region is a disk for L2 and a diamond ∣w1∣+∣w2∣≤t|w_1| + |w_2| \le t 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.

Purple ellipses are contours of the loss, centred on the purple dot (the unregularized best fit; drag it). The gold region is the budget. The red dot is the best point inside the budget, where the bold ellipse just touches it. With the L1 diamond, drag the centre around and watch the answer snap to a corner (a weight exactly 0). Switch to the L2 circle and it slides smoothly. Try 500 random problems counts how often each gives a zero.

The algebra: soft thresholding

The 1D problem shows the same thing with formulas. Minimize 12(w−z)2+λR(w)\tfrac12(w - z)^2 + \lambda R(w), where zz is what the data alone wants.

  • L2 (R=12w2R = \tfrac12w^2): setting the derivative w−z+λww - z + \lambda w to zero gives w∗=z/(1+λ)w^* = z/(1 + \lambda). Shrunk, but zero only if z=0z = 0.
  • L1 (R=∣w∣R = |w|): the answer is the soft-thresholding function w∗=sign⁡(z)max⁡(∣z∣−λ,0)w^* = \operatorname{sign}(z)\max(|z| - \lambda, 0). Every value with ∣z∣≤λ|z| \le \lambda becomes exactly 0, and the rest move λ\lambda toward 0.

The kink of ∣w∣|w| at 0 is what does it: its slope jumps from −1-1 to +1+1, so near zero the penalty pushes with constant force λ\lambda, not a force that fades like λw\lambda w. Because ∣w∣|w| isn't differentiable at 0, L1 problems are solved with subgradients or proximal steps: take a gradient step on LL, then apply soft thresholding with threshold ηλ\eta\lambda (the ISTA algorithm).

Worked exampleSame data, two penalties

Minimize 12(w−3)2+penalty\tfrac12(w - 3)^2 + \text{penalty}.

  • L2 with λ=1\lambda = 1: w∗=3/(1+1)=1.5w^* = 3/(1 + 1) = 1.5. With λ=4\lambda = 4: 3/5=0.63/5 = 0.6. Never zero.
  • L1 with λ=1\lambda = 1: w∗=3−1=2w^* = 3 - 1 = 2. With λ=4\lambda = 4: ∣3∣≤4|3| \le 4, so w∗=0w^* = 0 exactly.

Check the L1 answer at λ=4\lambda = 4: for small w>0w \gt 0 the objective's slope is (w−3)+4>0(w - 3) + 4 \gt 0, and for small w<0w \lt 0 it is (w−3)−4<0(w - 3) - 4 \lt 0. So w=0w = 0 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 λ\lambda is scaled). For Adam they differ: the L2 gradient λw\lambda w gets divided by v^\sqrt{\hat v} like everything else, so weights with large gradients are barely regularized. AdamW applies the decay w←w−ηλww \leftarrow w - \eta\lambda w separately ("decoupled"), which works better.
  • "More regularization is always safer." Too large a λ\lambda 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.linear_model.Ridge, 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, η=0.1\eta = 0.1 and λ=0.01\lambda = 0.01, each step multiplies the weights by what factor before the loss-gradient step?

  1. 0.999
  2. 0.99
  3. 0.9
  4. 1.001

1−ηλ=1−0.001=0.9991 - \eta\lambda = 1 - 0.001 = 0.999. Using 1−λ1-\lambda gives 0.99; using 1−η1 - \eta gives 0.9.

Which penalty tends to produce weights that are exactly zero?

  1. L1, λ∑∣wi∣\lambda\sum|w_i|
  2. L2, λ2∑wi2\tfrac\lambda2\sum w_i^2
  3. Both equally
  4. 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 12(w−3)2+λ2w2\tfrac12(w - 3)^2 + \tfrac\lambda2 w^2 with λ=2\lambda = 2. What is w∗w^*?

  1. 1
  2. 1.5
  3. 0
  4. 3

Derivative: (w−3)+2w=0(w - 3) + 2w = 0, so 3w=33w = 3 and w∗=3/(1+2)=1w^* = 3/(1 + 2) = 1.

Soft thresholding S(z,τ)=sign⁡(z)max⁡(∣z∣−τ,0)S(z, \tau) = \operatorname{sign}(z)\max(|z| - \tau, 0). What is S(0.7,0.5)S(0.7, 0.5)?

  1. 0.2
  2. 0
  3. 0.7
  4. 1.2

∣0.7∣>0.5|0.7| \gt 0.5, so it survives and moves 0.5 toward zero: 0.7−0.5=0.20.7 - 0.5 = 0.2. (S(0.3,0.5)S(0.3, 0.5) would be 0.)

Minimize 12(w−3)2+λ∣w∣\tfrac12(w - 3)^2 + \lambda|w|. What is the smallest λ\lambda for which w∗=0w^* = 0?

  1. 3
  2. 1.5
  3. 6
  4. 9

The solution is S(3,λ)=max⁡(3−λ,0)S(3, \lambda) = \max(3 - \lambda, 0), which hits 0 when λ≥3\lambda \ge 3. Intuition: the penalty's constant push λ\lambda must beat the data's pull, which is 3 at w=0w = 0.

Ridge regression without intercept on data x=(1,2)x = (1, 2), y=(1,3)y = (1, 3): minimize ∑i(wxi−yi)2+λw2\sum_i(wx_i - y_i)^2 + \lambda w^2 with λ=2\lambda = 2. What is w∗w^*?

  1. 1
  2. 1.4
  3. 7/3
  4. 0.7

Derivative: 2∑xi(wxi−yi)+2λw=02\sum x_i(wx_i - y_i) + 2\lambda w = 0, so w=∑xiyi/(∑xi2+λ)=7/(5+2)=1w = \sum x_iy_i/(\sum x_i^2 + \lambda) = 7/(5 + 2) = 1. Without the penalty it would be 7/5=1.47/5 = 1.4.

Why does adding an L2 term λw\lambda w to the gradient inside Adam regularize differently from AdamW's decoupled weight decay?

  1. Adam divides the λw\lambda w term by v^\sqrt{\hat v}, so weights with large gradient history get much less shrinkage
  2. Adam ignores the λw\lambda w term because bias correction removes it
  3. They're identical; AdamW only changes the default learning rate
  4. Adam applies the L2 term twice, once in mm and once in vv

In Adam the whole gradient, penalty included, is rescaled per parameter by 1/v^1/\sqrt{\hat v}. So the effective decay is uneven: large-gradient weights are barely decayed. AdamW instead multiplies every weight by 1−ηλ1 - \eta\lambda outside the adaptive step, restoring uniform weight decay.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 10

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 ff while staying on a constraint curve g=0g = 0, look for the point where a level curve of ff just touches the constraint. There the two gradients are parallel: ∇f=λ∇g\nabla f = \lambda\nabla g. The number λ\lambda, 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:

minimize f(x)subject tog(x)=0.\text{minimize } f(x) \quad\text{subject to}\quad g(x) = 0 .

The tangency picture

Walk along the constraint curve and watch the value of ff. If the curve crosses a level curve of ff 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

∇f(x)=λ ∇g(x)for some number λ,g(x)=0.\nabla f(x) = \lambda\,\nabla g(x) \quad\text{for some number } \lambda, \qquad g(x) = 0 .

That's n+1n + 1 equations for the nn coordinates plus λ\lambda. A neat way to package them: define the Lagrangian L(x,λ)=f(x)−λ g(x)\mathcal L(x, \lambda) = f(x) - \lambda\, g(x). Setting all its partial derivatives to zero gives exactly the tangency condition (∇xL=0\nabla_x\mathcal L = 0) and the constraint (∂L/∂λ=−g=0\partial\mathcal L/\partial\lambda = -g = 0). A constrained problem becomes an unconstrained "find the flat point" problem in one more variable.

Purple: level curves of ff, an elliptical bowl centred at the purple dot. Gold: the constraint. Slide the gold point along the constraint and watch the arrows ∇f\nabla f (purple) and ∇g\nabla g (gold). Where the bold level curve just touches the constraint, the arrows line up and the readout reports the multiplier λ\lambda. Drag the centre, switch between the circle and the line, and press Slide to the best point.

What λ means

If the constraint is g(x)=cg(x) = c and you nudge cc, the optimal value f∗(c)f^*(c) changes at rate df∗dc=λ\frac{df^*}{dc} = \lambda. So λ\lambda 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, h(x)≤0h(x) \le 0 (e.g. ∥w∥2≤t\|w\|^2 \le t). 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 λ\lambda in the penalty form corresponds to a budget tt 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).

x←ΠC(x−η∇f(x)).x \leftarrow \Pi_C\big(x - \eta\nabla f(x)\big).

Projections are cheap for common sets: onto the ball ∥x∥≤r\|x\| \le r, rescale xx to length rr if it's too long; onto a box a≤xi≤ba \le x_i \le b, clip each coordinate. For convex sets and convex ff this converges to the constrained minimum.

Worked exampleClosest point on a line

Minimize f(x,y)=x2+y2f(x, y) = x^2 + y^2 (squared distance from the origin) subject to x+2y=5x + 2y = 5, i.e. g=x+2y−5=0g = x + 2y - 5 = 0.

  • ∇f=(2x,2y)\nabla f = (2x, 2y), ∇g=(1,2)\nabla g = (1, 2). Tangency: 2x=λ2x = \lambda, 2y=2λ2y = 2\lambda, so x=λ/2x = \lambda/2, y=λy = \lambda.
  • Constraint: λ/2+2λ=5\lambda/2 + 2\lambda = 5, so λ=2\lambda = 2, giving (x,y)=(1,2)(x, y) = (1, 2) and f=5f = 5.
  • Check: (1,2)(1, 2) is a multiple of the line's normal (1,2)(1, 2), as the closest point should be. Its distance from the origin is 5\sqrt{5}.
  • Meaning of λ\lambda: for the line x+2y=cx + 2y = c the same steps give f∗(c)=c2/5f^*(c) = c^2/5, and df∗/dc=2c/5=2df^*/dc = 2c/5 = 2 at c=5c = 5. That's λ\lambda.

Watch outCommon misconceptions

  • "At the constrained minimum, ∇f=0\nabla f = 0." Usually not: ff would still like to go downhill, but the constraint blocks it. ∇f\nabla f points straight into the wall (along ∇g\nabla g).
  • "The gradients must point the same way." Parallel or opposite: λ\lambda can be negative for equality constraints. Its sign matters only for inequalities.
  • "Every solution of ∇f=λ∇g\nabla f = \lambda\nabla g 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 ff on the curve g=0g = 0 (a regular point), the gradients ∇f\nabla f and ∇g\nabla g are…

  1. parallel
  2. perpendicular
  3. both zero
  4. equal

The level curve of ff is tangent to the constraint curve, so their normals (the gradients) line up: ∇f=λ∇g\nabla f = \lambda\nabla g. They needn't be equal (λ≠1\lambda \ne 1 in general), and ∇f\nabla f is usually not zero.

Maximize f(x,y)=xyf(x, y) = xy subject to x+y=10x + y = 10. What is the maximum value?

  1. 25
  2. 50
  3. 100
  4. 24

∇f=(y,x)=λ(1,1)\nabla f = (y, x) = \lambda(1, 1) gives x=yx = y, and then x=y=5x = y = 5, f=25f = 25. (λ=5\lambda = 5.) Other splits like 4⋅6=244\cdot6 = 24 are smaller.

Minimize x2+y2x^2 + y^2 subject to x+y=2x + y = 2. Where is the minimizer?

  1. (1,1)(1, 1)
  2. (2,0)(2, 0)
  3. (0,0)(0, 0)
  4. (0.5,1.5)(0.5, 1.5)

(2x,2y)=λ(1,1)(2x, 2y) = \lambda(1, 1) gives x=yx = y, so x=y=1x = y = 1 with value 2. The origin is the unconstrained minimum but isn't on the line; (2,0)(2, 0) gives 4.

Projected gradient descent with the constraint ∥w∥≤1\|w\| \le 1. A gradient step lands at (3,4)(3, 4). Where does the projection put it?

  1. (0.6,0.8)(0.6, 0.8)
  2. (1,1)(1, 1)
  3. (3,4)(3, 4)
  4. (0.75,1)(0.75, 1)

∥(3,4)∥=5>1\|(3,4)\| = 5 \gt 1, so rescale to length 1: (3,4)/5=(0.6,0.8)(3, 4)/5 = (0.6, 0.8). Clipping each coordinate to 1 gives (1,1)(1,1), which is outside the ball (length 2\sqrt{2}).

Project the point (1.5,−0.2)(1.5, -0.2) onto the box 0≤x≤1, 0≤y≤10 \le x \le 1,\ 0 \le y \le 1.

  1. (1,0)(1, 0)
  2. (1,−0.2)(1, -0.2)
  3. (0.88,0)(0.88, 0)
  4. (0.75,0)(0.75, 0)

For a box, the nearest point clips each coordinate separately: 1.5→11.5 \to 1, −0.2→0-0.2 \to 0.

For "minimize x2+y2x^2 + y^2 subject to x+y=cx + y = c", the optimal value is c2/2c^2/2 and the multiplier is λ=c\lambda = c. If cc goes from 2 to 2.1, by about how much does the optimal value rise?

  1. 0.2
  2. 0.1
  3. 2
  4. 0.4

The rate of change is λ=2\lambda = 2, so the rise is about 2×0.1=0.22 \times 0.1 = 0.2. (Exactly: 2.12/2−22/2=2.205−2=0.2052.1^2/2 - 2^2/2 = 2.205 - 2 = 0.205.)

Minimize (x−3)2(x - 3)^2 subject to x≤1x \le 1. Using the KKT condition f′(x)+μ=0f'(x) + \mu = 0 on the active boundary (with L=f+μ(x−1)\mathcal L = f + \mu(x - 1), μ≥0\mu \ge 0), what are x∗x^* and μ\mu?

  1. x∗=1x^* = 1, μ=4\mu = 4
  2. x∗=3x^* = 3, μ=0\mu = 0
  3. x∗=1x^* = 1, μ=−4\mu = -4
  4. x∗=1x^* = 1, μ=2\mu = 2

The unconstrained minimum x=3x = 3 violates x≤1x \le 1, so the constraint is active: x∗=1x^* = 1. Then f′(1)=2(1−3)=−4f'(1) = 2(1 - 3) = -4, and −4+μ=0-4 + \mu = 0 gives μ=4≥0\mu = 4 \ge 0 ✓. 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)

Chapter 11

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, x←x−H−1∇fx \leftarrow x - H^{-1}\nabla f. 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 xkx_k, approximate ff by its second-order Taylor polynomial, a parabola:

q(x)=f(xk)+f′(xk)(x−xk)+12f′′(xk)(x−xk)2.q(x) = f(x_k) + f'(x_k)(x - x_k) + \tfrac12 f''(x_k)(x - x_k)^2 .

If f′′(xk)>0f''(x_k) \gt 0 this parabola has a lowest point, where q′(x)=f′(xk)+f′′(xk)(x−xk)=0q'(x) = f'(x_k) + f''(x_k)(x - x_k) = 0. Jump there:

xk+1=xk−f′(xk)f′′(xk).x_{k+1} = x_k - \frac{f'(x_k)}{f''(x_k)} .

Compare gradient descent, xk+1=xk−ηf′(xk)x_{k+1} = x_k - \eta f'(x_k): Newton is gradient descent with the learning rate η=1/f′′(xk)\eta = 1/f''(x_k), chosen automatically from the local curvature. That's exactly chapter 3's ideal rate 1/λ1/\lambda. (It's also Newton's root-finding method applied to f′f': we're looking for where the slope is zero.)

The solid curve is ff; the dashed gold parabola is Newton's local quadratic model at the red point. Press Newton step to jump to the model's lowest point. On the quadratic it lands in one step. On log⁡cosh⁡x\log\cosh x, start at 0.9 and it converges in a few steps; drag the start past about 1.1 and the steps overshoot more each time. On the quartic, start between the valleys (where f′′<0f'' \lt 0) and Newton heads for the hilltop.

In many dimensions

The quadratic model uses the gradient and the Hessian, q(x+d)=f(x)+∇f⋅d+12d⊤Hdq(x + d) = f(x) + \nabla f\cdot d + \tfrac12 d^\top H d, and its minimizer gives the Newton step:

xk+1=xk−H−1∇f(xk)(in practice: solve Hd=∇f for d).x_{k+1} = x_k - H^{-1}\nabla f(x_k) \qquad\text{(in practice: solve } H d = \nabla f \text{ for } d\text{)}.

In the Hessian's eigenvector basis, H−1H^{-1} divides each component of the gradient by its own curvature λi\lambda_i: 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 κ\kappa is.

Near a minimum, Newton converges quadratically: the error roughly squares each step, ek+1≈Cek2e_{k+1} \approx C e_k^2. Once the error is 0.01, the next is about 0.0001, then 10−810^{-8}: the number of correct digits doubles every step. Gradient descent only converges linearly (the error shrinks by a constant factor).

The Rosenbrock banana again. Press One step each: blue is gradient descent, gold is Newton. From the classic start (−1.2,1)(-1.2, 1), Newton takes a wild second step (its quadratic model is poor out there) but then converges to the minimum at (1,1)(1,1) in about five steps; gradient descent needs thousands. Drag the start to explore.

Why deep learning doesn't use it (directly)

  • Cost. With nn parameters the Hessian has n2n^2 entries and solving Hd=∇fHd = \nabla f takes about n3n^3 operations. For n=106n = 10^6, n2=1012n^2 = 10^{12} numbers is terabytes. For n=109n = 10^9, forget it.
  • Non-convexity. If HH 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 (H+μIH + \mu I, 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 H−1H^{-1} from recent gradients. For least-squares problems, Gauss–Newton and Levenberg–Marquardt use a positive semidefinite approximation of HH.

Worked exampleWatching the digits double

Minimize f(x)=x−ln⁡xf(x) = x - \ln x (for x>0x \gt 0); the minimum is at x=1x = 1. Here f′(x)=1−1/xf'(x) = 1 - 1/x and f′′(x)=1/x2f''(x) = 1/x^2, so the Newton step is

x−1−1/x1/x2=x−(x2−x)=2x−x2.x - \frac{1 - 1/x}{1/x^2} = x - (x^2 - x) = 2x - x^2 .

From x0=0.5x_0 = 0.5: x1=0.75x_1 = 0.75, x2=0.9375x_2 = 0.9375, x3=0.99609375x_3 = 0.99609375, x4≈0.9999847x_4 \approx 0.9999847. The errors 1−xk1 - x_k are 0.5, 0.25, 0.0625, 0.0039, 0.00001530.5,\ 0.25,\ 0.0625,\ 0.0039,\ 0.0000153: each one is exactly the square of the one before, since 1−(2x−x2)=(1−x)21 - (2x - x^2) = (1 - x)^2.

Watch outCommon misconceptions

  • "Newton always goes downhill." Only if HH is positive definite. Where f′′<0f'' \lt 0 the step heads toward a maximum, and far from the minimum it can overshoot wildly (see log⁡cosh⁡\log\cosh 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 v^\sqrt{\hat v} 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 H−1H^{-1} explicitly." Never: solve the linear system Hd=∇fHd = \nabla f. 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 xx to…

  1. x−f′(x)/f′′(x)x - f'(x)/f''(x)
  2. x−f(x)/f′(x)x - f(x)/f'(x)
  3. x−ηf′(x)x - \eta f'(x)
  4. x−f′′(x)/f′(x)x - f''(x)/f'(x)

Minimize the local parabola: x−f′/f′′x - f'/f''. The formula x−f/f′x - f/f' is Newton's method for finding a root of ff, and x−ηf′x - \eta f' is gradient descent.

Newton's method on f(x)=3(x−2)2+1f(x) = 3(x - 2)^2 + 1, starting anywhere. Where is it after one step?

  1. exactly at x=2x = 2
  2. halfway to 2
  3. at x=1x = 1
  4. 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: x−6(x−2)/6=2x - 6(x-2)/6 = 2.

Minimize f(x)=ex−2xf(x) = e^x - 2x with Newton's method from x0=0x_0 = 0. What is x1x_1?

  1. 1
  2. 2
  3. 0.5
  4. −1

f′(x)=ex−2f'(x) = e^x - 2, f′′(x)=exf''(x) = e^x. At 0: f′=−1f' = -1, f′′=1f'' = 1, so x1=0−(−1)/1=1x_1 = 0 - (-1)/1 = 1. (The true minimizer is ln⁡2≈0.693\ln 2 \approx 0.693.)

Newton's method on f(x,y)=x2+5y2f(x, y) = x^2 + 5y^2 from (2,1)(2, 1). Where does the first step land?

  1. (0,0)(0, 0)
  2. (1,0)(1, 0)
  3. (−2,−9)(-2, -9)
  4. (1.6,0)(1.6, 0)

∇f=(4,10)\nabla f = (4, 10) and H=diag⁡(2,10)H = \operatorname{diag}(2, 10), so H−1∇f=(2,1)H^{-1}\nabla f = (2, 1) and (2,1)−(2,1)=(0,0)(2,1) - (2,1) = (0, 0). One step on any quadratic, despite κ=5\kappa = 5.

Newton's method is converging quadratically and the current error is about 10−210^{-2}. Roughly what is the error two steps later?

  1. 10−810^{-8}
  2. 10−410^{-4}
  3. 10−610^{-6}
  4. 2.5×10−32.5\times10^{-3}

Squaring each step: 10−2→10−4→10−810^{-2} \to 10^{-4} \to 10^{-8} (taking the constant as about 1).

A model has 10610^6 parameters. How many entries does its Hessian have?

  1. 101210^{12}
  2. 10610^6
  3. 2×1062\times10^6
  4. 101810^{18}

An n×nn\times n matrix: (106)2=1012(10^6)^2 = 10^{12} entries, about 4 terabytes in 32-bit floats. Solving with it naively costs about n3=1018n^3 = 10^{18} operations, which is the other option's number.

Minimize f(x)=x4/4−x2f(x) = x^4/4 - x^2 with Newton's method from x0=0.5x_0 = 0.5. What is x1x_1, and did the loss go down?

  1. x1=−0.2x_1 = -0.2, and the loss went up
  2. x1=1.2x_1 = 1.2, and the loss went down
  3. x1=−0.2x_1 = -0.2, and the loss went down
  4. x1=1.4x_1 = 1.4, and the loss went down

f′(0.5)=0.125−1=−0.875f'(0.5) = 0.125 - 1 = -0.875, f′′(0.5)=0.75−2=−1.25f''(0.5) = 0.75 - 2 = -1.25. Step: 0.5−(−0.875)/(−1.25)=0.5−0.7=−0.20.5 - (-0.875)/(-1.25) = 0.5 - 0.7 = -0.2. Since f′′<0f'' \lt 0, Newton jumped toward the local maximum at 0: f(0.5)≈−0.234f(0.5) \approx -0.234 but f(−0.2)≈−0.040f(-0.2) \approx -0.040, higher. (The minimizers are at ±2\pm\sqrt{2}.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 12

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 η\eta. Real training runs almost never do. Two lessons from earlier chapters explain why:

  • From chapter 4: with mini-batches, a fixed η\eta leaves the parameters jittering in a cloud around the minimum, and the cloud shrinks with η\eta. To settle down, lower η\eta late in training.
  • From chapter 3: the safe step size is about 2/λmax⁡2/\lambda_{\max}, and early in training the landscape can be much sharper (and Adam's running averages less reliable) than later. A big η\eta right at the start can blow up.

So a schedule ηt\eta_t gives the learning rate as a function of the step tt.

Decay schedules

  • Step decay: multiply η\eta 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: ηt=η0 γt\eta_t = \eta_0\,\gamma^t with γ\gamma 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 TT steps from ηmax⁡\eta_{\max} to ηmin⁡\eta_{\min}, ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡πtT).\eta_t = \eta_{\min} + \tfrac12(\eta_{\max} - \eta_{\min})\Big(1 + \cos\frac{\pi t}{T}\Big). 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 η\eta from 0 (or tiny) up to the peak over the first few hundred or thousand steps: ηt=ηmax⁡⋅t/Twarm\eta_t = \eta_{\max}\cdot t/T_{\text{warm}}. Early on, the weights are random, gradients can be large and erratic, and Adam's estimate v^\hat v 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".

A learning-rate schedule over 1000 steps, as a multiple of the peak rate. Pick a schedule, set the warmup length and the floor (the minimum rate for cosine, linear and exponential), and drag the red dot along the curve to read off the rate at any step. The shaded area is proportional to the total distance the optimizer is allowed to travel.

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 η⋅104\eta\cdot10^4 can undo hours of training. Clipping by norm caps the size of the gradient vector at a threshold cc without changing its direction:

g←g⋅min⁡(1, c∥g∥).g \leftarrow g\cdot\min\Big(1,\ \frac{c}{\|g\|}\Big).

If ∥g∥≤c\|g\| \le c nothing happens. If it's bigger, the vector is shrunk to length exactly cc. (Clipping by value, which clamps each coordinate to [−c,c][-c, c] 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.

Drag the red gradient's tip. The dashed gold circle has radius cc. Inside it, the gradient is left alone; outside, the green clipped vector keeps the same direction with length exactly cc. Tick compare value clipping to see the box version, which bends the direction whenever one coordinate is clipped more than another.

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 η\eta 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: η\eta too high, missing clipping, or a bug. Loss falling painfully slowly in a straight line: η\eta probably too low.
  • Check the gradient norm. Logging ∥g∥\|g\| 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 ηmax⁡=3×10−4\eta_{\max} = 3\times10^{-4}, then cosine decay to 0 over the remaining 900.

  • Step 50: halfway through warmup, η=3×10−4⋅50/100=1.5×10−4\eta = 3\times10^{-4}\cdot 50/100 = 1.5\times10^{-4}.
  • Step 100: the peak, 3×10−43\times10^{-4}.
  • Step 550: 450 of 900 decay steps, so 12(1+cos⁡(π/2))=0.5\tfrac12(1 + \cos(\pi/2)) = 0.5 and η=1.5×10−4\eta = 1.5\times10^{-4}.
  • Step 1000: 12(1+cos⁡π)=0\tfrac12(1 + \cos\pi) = 0.

Clipping: with c=1c = 1, the gradient (3,4)(3, 4) has norm 5, so it becomes (3,4)/5=(0.6,0.8)(3, 4)/5 = (0.6, 0.8). The gradient (0.3,0.4)(0.3, 0.4) (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 η\eta 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 β2=0.95\beta_2 = 0.95, 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.nn.utils.clip_grad_norm_(model.parameters(), 1.0) 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 η=0.1\eta = 0.1 and multiplies by 0.1 at epochs 30 and 60. What is η\eta at epoch 65?

  1. 0.001
  2. 0.01
  3. 0.0001
  4. 0.1

Two cuts have happened (at 30 and 60): 0.1×0.1×0.1=0.0010.1 \times 0.1 \times 0.1 = 0.001.

Clip the gradient g=(6,8)g = (6, 8) by norm with threshold c=5c = 5.

  1. (3,4)(3, 4)
  2. (5,5)(5, 5)
  3. (6,8)(6, 8)
  4. (0.6,0.8)(0.6, 0.8)

∥g∥=10>5\|g\| = 10 \gt 5, so scale by 5/105/10: (3,4)(3, 4), length 5, same direction. (5,5)(5,5) is value clipping; (0.6,0.8)(0.6, 0.8) is the unit vector.

Cosine decay from 10−310^{-3} to 0 over T=1000T = 1000 steps. What is the learning rate at t=500t = 500?

  1. 5×10−45\times10^{-4}
  2. 10−310^{-3}
  3. 0
  4. 7.07×10−47.07\times10^{-4}

12(1+cos⁡(π/2))=12\tfrac12(1 + \cos(\pi/2)) = \tfrac12, so η=5×10−4\eta = 5\times10^{-4}. At the midpoint, cosine and linear decay agree.

Linear warmup over 2000 steps to a peak of 6×10−46\times10^{-4}. What is the learning rate at step 500?

  1. 1.5×10−41.5\times10^{-4}
  2. 3×10−43\times10^{-4}
  3. 6×10−46\times10^{-4}
  4. 1.2×10−31.2\times10^{-3}

6×10−4⋅500/2000=6×10−4⋅0.25=1.5×10−46\times10^{-4}\cdot 500/2000 = 6\times10^{-4}\cdot0.25 = 1.5\times10^{-4}.

Cosine decay from 1 (the peak) to 0. What fraction of the peak remains a quarter of the way through, at t=T/4t = T/4?

  1. about 0.854
  2. 0.75
  3. about 0.707
  4. 0.5

12(1+cos⁡(π/4))=12(1+0.7071)≈0.854\tfrac12(1 + \cos(\pi/4)) = \tfrac12(1 + 0.7071) \approx 0.854. Linear decay would give 0.75: cosine stays high for longer at the start.

Exponential decay ηt=0.1⋅0.95t\eta_t = 0.1\cdot0.95^t (per epoch). What is η\eta after 20 epochs?

  1. about 0.036
  2. 0
  3. 0.095
  4. about 0.064

0.9520≈0.35850.95^{20} \approx 0.3585, so η≈0.0358\eta \approx 0.0358. (Subtracting 5% of the initial value each epoch would wrongly give 0 after 20 epochs.)

The gradient is g=(0.5,12)g = (0.5, 12) and c=3c = 3. Norm clipping gives approximately (0.125,2.997)(0.125, 2.997). What does clipping by value (each entry to [−3,3][-3, 3]) give, and what's wrong with it?

  1. (0.5,3)(0.5, 3): the direction turns noticeably toward the first axis
  2. (0.125,2.997)(0.125, 2.997): the same as norm clipping
  3. (0.5,12)(0.5, 12): nothing is clipped
  4. (3,3)(3, 3): every entry is set to the threshold

Value clipping only touches entries bigger than 3: (0.5,12)→(0.5,3)(0.5, 12) \to (0.5, 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: g⋅3/∥g∥g\cdot 3/\|g\| with ∥g∥≈12.01\|g\| \approx 12.01.

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 =1n∑(y^i−yi)2= \frac1n\sum(\hat y_i - y_i)^2; training = arg⁡min⁡θL(θ)\arg\min_\theta L(\theta)

Minimum = lowest value; minimizer = where it happens.

Gradient descent (2)

x←x−η∇f(x)x \leftarrow x - \eta\nabla f(x); −∇f-\nabla f = steepest descent, ⟂ contours

One small step lowers ff by ≈η∥∇f∥2\approx \eta\|\nabla f\|^2.

Learning rate on a quadratic (3)

f=12x⊤Axf = \tfrac12x^\top Ax: each eigen-direction × (1−ηλi)(1 - \eta\lambda_i) per step

Stable iff η<2/λmax⁡\eta \lt 2/\lambda_{\max}; best η∗=2/(λmin⁡+λmax⁡)\eta^* = 2/(\lambda_{\min} + \lambda_{\max})

Rate (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1), κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}

Mini-batches (4)

gB=1b∑i∈B∇ℓig_B = \frac1b\sum_{i\in B}\nabla\ell_i: unbiased; std ∝1/b\propto 1/\sqrt{b}

Steps per epoch =⌈N/b⌉= \lceil N/b\rceil. Linear scaling: η∝b\eta \propto b.

Momentum (5)

v←βv+∇fv \leftarrow \beta v + \nabla f; x←x−ηvx \leftarrow x - \eta v

Constant gradient: v→g/(1−β)v \to g/(1 - \beta). Alternating: ≈g/(1+β)\approx g/(1 + \beta).

Averaged form with η\eta = summed form with η(1−β)\eta(1 - \beta).

RMSProp & Adam (6)

RMSProp: s←ρs+(1−ρ)g2s \leftarrow \rho s + (1-\rho)g^2, x←x−ηg/(s+ϵ)x \leftarrow x - \eta g/(\sqrt{s} + \epsilon)

Adam: m,vm, v as EWAs of g,g2g, g^2; m^=m/(1−β1t)\hat m = m/(1 - \beta_1^t), v^=v/(1−β2t)\hat v = v/(1 - \beta_2^t)

x←x−ηm^/(v^+ϵ)x \leftarrow x - \eta\hat m/(\sqrt{\hat v} + \epsilon); first step size = η\eta. Defaults 0.9, 0.999, 1e-8.

Convexity (7)

Chord: f(ta+(1−t)b)≤tf(a)+(1−t)f(b)f(ta + (1-t)b) \le tf(a) + (1-t)f(b)

Tangent: f(y)≥f(x)+∇f(x)⋅(y−x)f(y) \ge f(x) + \nabla f(x)\cdot(y - x); Hessian PSD

Local min = global min. Preserved by +, max, c≥0c \ge 0 scaling, affine inputs.

Hessian & critical points (8)

f(x+d)≈f+∇f⋅d+12d⊤Hdf(x + d) \approx f + \nabla f\cdot d + \tfrac12d^\top Hd

Eigenvalues all >0\gt 0: min; all <0\lt 0: max; mixed: saddle; a zero: inconclusive

2D: det⁡H<0\det H \lt 0 ⇒ saddle.

Regularization (9)

L2: w←(1−ηλ)w−η∇Lw \leftarrow (1 - \eta\lambda)w - \eta\nabla L (weight decay); 12(w−z)2+λ2w2\tfrac12(w-z)^2 + \tfrac\lambda2w^2 ⇒ z/(1+λ)z/(1+\lambda)

L1: soft threshold sign⁡(z)max⁡(∣z∣−λ,0)\operatorname{sign}(z)\max(|z| - \lambda, 0) ⇒ exact zeros

Ridge: w=(X⊤X+λI)−1X⊤yw = (X^\top X + \lambda I)^{-1}X^\top y. AdamW = decoupled decay.

Constraints (10)

min⁡f\min f s.t. g=0g = 0: ∇f=λ∇g\nabla f = \lambda\nabla g, L=f−λg\mathcal L = f - \lambda g

λ=df∗/dc\lambda = df^*/dc. KKT: inactive ⇒ multiplier 0.

Projected GD: x←ΠC(x−η∇f)x \leftarrow \Pi_C(x - \eta\nabla f); ball: rescale, box: clip.

Newton (11)

1D: x←x−f′/f′′x \leftarrow x - f'/f''; nD: solve Hd=∇fHd = \nabla f, x←x−dx \leftarrow x - d

Exact in 1 step on quadratics; quadratic convergence near a minimum.

n2n^2 memory, n3n^3 time; needs H≻0H \succ 0.

Schedules & clipping (12)

Warmup: ηmax⁡t/Tw\eta_{\max}t/T_w. Cosine: ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡πtT)\eta_{\min} + \tfrac12(\eta_{\max} - \eta_{\min})(1 + \cos\frac{\pi t}{T})

Step: × 0.1 at milestones. Exponential: η0γt\eta_0\gamma^t.

Clip by norm: g←gmin⁡(1,c/∥g∥)g \leftarrow g\min(1, c/\|g\|).

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 1−βt1 - \beta^t, so early estimates aren't shrunk toward zero. (Ch 6)
Condition number κ
λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min} 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 η>2/λmax⁡\eta \gt 2/\lambda_{\max}. (Ch 3)
Epoch
One full pass over the training set: ⌈N/b⌉\lceil N/b\rceil 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 cc to length cc, keeping its direction. (Ch 12)
Gradient descent
Repeating x←x−η∇f(x)x \leftarrow x - \eta\nabla f(x). (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 λ∥w∥1\lambda\|w\|_1 (gives sparse weights) or λ2∥w∥2\tfrac\lambda2\|w\|^2 (shrinks weights) to the loss. (Ch 9)
Lagrange multiplier
The λ\lambda in ∇f=λ∇g\nabla f = \lambda\nabla g; 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: x←x−H−1∇fx \leftarrow x - H^{-1}\nabla f. (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
sign⁡(z)max⁡(∣z∣−t,0)\operatorname{sign}(z)\max(|z| - t, 0): 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 1−ηλ1 - \eta\lambda each step; equals L2 regularization for plain SGD. (Ch 9)

Where to go next