A model has millions of weights, and training means nudging all of them at once so the loss drops. This lesson builds the one tool that tells you which nudge to make: the gradient.
In M4 you took the derivative of a function with one input and read it as a slope. A real loss has one input per weight, so one slope is not enough: you need a slope for every weight and a rule for combining them into one move. That rule is gradient descent. The statistics course, Lesson 8 (The Statistics Behind Training a Model), describes how it behaves in practice. This lesson shows where the update comes from, computes it by hand, and explains why it works, using the dot product from M1 and the matrix idea from M2.
A loss is one number that says how badly a model is doing on its training data. It depends on the model's weights. To draw it, shrink the model to two weights, called w1 and w2. The loss is now a function of two inputs, written L(w1, w2).
Say a team fits a tiny model with two weights and finds that its loss works out to:
Both terms are squares, so the loss is never negative. It is exactly 0 only when w1 = 3 and w2 = 1. That point is the best pair of weights. The factor 4 means that a miss in w2 costs four times as much as an equal miss in w1.
| (w1, w2) | Calculation | L |
|---|---|---|
| (0, 3) | (0−3)² + 4(3−1)² = 9 + 16 | 25 |
| (3, 3) | (3−3)² + 4(3−1)² = 0 + 16 | 16 |
| (0, 1) | (0−3)² + 4(1−1)² = 9 + 0 | 9 |
| (1, 1) | (1−3)² + 4(1−1)² = 4 + 0 | 4 |
| (3, 1) | 0 + 0 | 0 |
Think of the loss as height. Each pair of weights is a spot on the ground, and L is the altitude there. The set of all spots forms a loss surface, a landscape with hills and valleys. Training is a walk: start somewhere (weights are usually initialized randomly), and move toward lower ground. For this loss the landscape is a single bowl. Real networks have the same structure with millions or billions of horizontal directions instead of two, which nobody can draw but the math carries over unchanged.
A partial derivative is an ordinary derivative taken with respect to one input while every other input is held fixed. The symbol ∂L/∂w1 reads "the partial derivative of L with respect to w1." The curly ∂ (instead of a straight d) is the reminder that other inputs exist and are being held still.
To compute ∂L/∂w1, treat w2 as a constant. Then 4(w2 − 1)² is just a number that does not change with w1, so its derivative is 0. The first term follows the power rule from M4:
Evaluate both at the starting point (w1, w2) = (0, 3):
Read these as slopes. A partial of −6 for w1 says: raising w1 a little lowers the loss, at about 6 units of loss per unit of weight. A partial of +16 for w2 says: raising w2 raises the loss, fast. You can check this with an actual small nudge of 0.01:
The measured slopes (−5.99 and +16.04) match the formulas (−6 and 16) up to the small error from using a nudge of 0.01 instead of an infinitely small one.
Collect the partials into a vector. That vector is the gradient, written ∇L (read "del L" or "grad L"):
Two facts make the gradient the central object of training:
At the minimum (3, 1), both partials are 0: ∂L/∂w1 = 2(3−3) = 0 and ∂L/∂w2 = 8(1−1) = 0. The gradient is the zero vector, its length is 0, and there is no uphill direction because the ground is level. A gradient of length near 0 is the usual sign that training has settled somewhere.
Training wants the fastest drop, so the natural move is "go against the gradient." Here is the reason that it is correct, using the dot product from M1.
Suppose you take a tiny step in some direction given by a unit vector u (a vector of length 1). The rate at which the loss changes along that step is the directional derivative, and it equals the dot product of the gradient with u:
This equality is the one-variable slope rule applied along a straight line through the point; the multi-variable version is a standard result, and this lesson states it without proof. Given that, the question is easy. |∇L| is fixed by where you stand, so the only thing you control is cos θ:
Check it with numbers at (0, 3), where ∇L = (−6, 16):
| Direction of step | Unit vector u | ∇L · u | Meaning |
|---|---|---|---|
| Increase w1 only | (1, 0) | (−6)(1) + 16(0) = −6 | drops, slowly |
| Decrease w2 only | (0, −1) | (−6)(0) + 16(−1) = −16 | drops, fast |
| Exactly −∇L | (6, −16) / 17.09 = (0.351, −0.936) | −2.107 − 14.981 = −17.09 | steepest drop |
No direction beats −17.09, because −|∇L| is the smallest value the dot product can reach. A caveat: this is a statement about a very short step. The gradient describes the slope exactly where you stand, and the slope can change as you move. For a step of length 0.1 along −∇L, the true change in L is −1.67, a bit less than the straight-line prediction of 0.1 × (−17.09) = −1.71, because the bowl curves.
Gradient descent repeats one move. Take the current weight vector w, compute ∇L there, and step against it by a scaled amount:
The Greek letter η (eta) is the learning rate, a positive number that scales the step. The arrow ← means "replace the old value with the right-hand side." Written per weight, this is w1 ← w1 − η ∂L/∂w1 and the same for w2. Both weights update together, using the gradient computed before either one moved.
Use η = 0.1, starting at (0, 3) where L = 25. Every number below was checked in Python.
Look at what happened. The loss fell from 25 to about 2.4 in three steps. The steep weight w2 was almost solved by step 2 (it is 1.08, target 1), while the shallow weight w1 is still crawling toward 3 (it is 1.464). The reason is in the gradient: it was large along w2 early on and shrinks as the weight approaches the minimum, so the steps shrink on their own. Left to run, the same rule reaches L ≈ 0.104 after 10 steps and about 0.0000138 after 30.
Same loss, same start (0, 3), three different values of η.
Step 1 gives (0 − 0.01×(−6), 3 − 0.01×16) = (0.06, 2.84), with L = 22.19. The direction is right but the step is tiny. After 30 steps the weights are at about (1.36, 1.16) and L is still 2.79, a loss that η = 0.1 reached in 3 steps. Nothing breaks. It is just slow, and on a real model "slow" means paying for more GPU hours.
The loss started at 25 and is now 120 and growing. Each step overshoots the valley floor in the w2 direction and lands higher on the other wall. The distance of w2 from its best value (1) goes 2, then −2.8, then 3.92, then −5.488: it flips sign and multiplies by 1.4 each step, because the update is w2 − 1 ← (1 − 0.3 × 8)(w2 − 1) = −1.4 (w2 − 1). After 8 steps, L is about 3,485. This is divergence. In a real training run it shows up as a loss curve that shoots up or turns into NaN.
The boundary sits between the cases: with η = 0.25 the factor is 1 − 0.25 × 8 = −1, and w2 bounces between 3 and −1 forever without improving, while w1 settles at 3 and L stays near 16.
The weights w are learned by the gradient steps. η is not: no gradient step adjusts it, and nothing in the data names the best value. You pick it before training starts, which makes it a hyperparameter. The safe range depends on the loss surface: here the steep direction (factor 8) rules out η above 0.25, and the shallow direction (factor 2) would have tolerated up to 1. In practice a team tries a few values, runs short experiments, and compares the validation loss, the same discipline the statistics course, Lesson 8, applies to every training choice. Many setups also lower η over the course of training.
Drawing a 3-D surface on a page is awkward. A contour plot is the map version: look down on the (w1, w2) plane and draw a closed curve through every point that has the same loss, like the elevation lines on a hiking map. The five rings below have L = 1, 4, 9, 16 and 25. They are ellipses because the loss is stretched four times as hard along w2 as along w1.
Two facts to carry around. The gradient at any point is perpendicular to the contour through it and points toward the next-higher ring; walking along a ring changes nothing (cos θ = 0 from section 4). And rings packed close together mean steep ground and a long gradient. Here the rings are tightly packed vertically, which is why the first step moves so far vertically and why a large η overshoots there.
The bowl above has one low point. Gradient descent stops making progress wherever ∇L = 0, and on a harder landscape that can happen in places that are not the global minimum. Points where the gradient is zero come in several kinds:
Here is a saddle you can check by hand. Take L(w1, w2) = w1² − w2². Its gradient is (2w1, −2w2), which is (0, 0) at the origin. But L(0.1, 0) = 0.01 is higher than L(0, 0) = 0, while L(0, 0.1) = −0.01 is lower. Sliding along w1 goes up, sliding along w2 goes down. The origin is a pass, not a floor, and a gradient of exactly zero there tells you nothing about which way is down.
The gradient collects first derivatives. The second derivatives tell you about curvature: how quickly the slope changes as you move. For several weights there are many of them, one for each pair of weights, and they are arranged in a matrix (M2) called the Hessian, written H. Entry (i, j) is the second partial derivative ∂²L/∂wi∂wj: differentiate with respect to wj, then differentiate that result with respect to wi.
For our loss, the first partials were 2(w1 − 3) and 8(w2 − 1). Differentiating them again:
The big diagonal entry 8 says the ground curves sharply in the w2 direction; the 2 says it curves gently in the w1 direction. That is the same stretching the contour plot showed, and it is why the safe learning rate was limited by the 8 (section 6). For the saddle w1² − w2², the Hessian is diag(2, −2): the negative entry marks the direction in which the surface curves downward.
That is all you need from the Hessian here. A model with n weights has an n × n Hessian, which for a billion weights is 1018 entries, far too many to store, so large-model training mostly uses the gradient alone plus cheaper curvature approximations.
The loss for a real model is an average over the training set: the average of one loss per example. Because the derivative of a sum is the sum of the derivatives, the gradient of an average is the average of the per-example gradients. Computing that over every example, millions or billions of them, for every single step is too expensive. So training uses a mini-batch: a small random sample of the examples, with the gradient averaged over just those.
Here is a toy version. A team has 6 training examples. For the weight w1, the per-example gradients are:
Every batch has the right sign (negative), but the size of the estimate swings from −2 to −8 around a true value of −5. Across all 15 possible batches of 2 from these 6 examples, the estimate ranges from −9 to −1. Across all 15 possible batches of 4, it ranges only from −7 to −3. Bigger batches give estimates that cluster closer to the truth.
This is the same idea as sampling in the statistics course, Lesson 5 (From Sample to Population: Estimation & the Central Limit Theorem): a sample mean is an unbiased but noisy estimate of the population mean, and its noise shrinks roughly like 1/√n as the sample size n grows. Here the "population" is the full training set, the "sample" is the mini-batch, and the quantity being estimated is the gradient. Unbiased means that averaged over many random batches, the estimate lands on the true gradient. Noisy means any single step points slightly off from the true downhill direction. The statistics course, Lesson 8, covers how this noise shows up in training curves.
NaN: the divergence of section 6, a learning rate too large for the steepest direction. Lower η first.Leads into M6: you can now use a gradient but not yet compute one for a deep network. M6 covers the chain rule and backpropagation, the method that produces every partial derivative in a single backward pass.
1. For a loss L(w1, w2), what does the partial derivative ∂L/∂w1 measure?
2. At weights (1, 1) the gradient is ∇L = (3, −4). With learning rate η = 0.5, what are the weights after one gradient descent step?
3. Why is −∇L the direction of steepest descent?
4. A team raises the learning rate and the loss goes 25, 33, 62, 121, ... What is the most likely cause?
5. How does a mini-batch gradient relate to the gradient over the full training set?