Where We Are
A derivative tells us how the loss changes when we move one parameter.
But a real model has many parameters. Changing one at a time is not enough.
Can we describe all those directions of change with one object — and find the direction that rises fastest?
Next → Gradients.
1. The Problem: What Is the Slope of a Bowl?
Chapter 018 closed on a question, and it is worth restating in full before we touch any mathematics.
Our house-price office now records two measurements per house — the data from Chapter 005:
| House | Rooms | Area (sq ft) | Price (₹ lakh) |
|---|---|---|---|
| A | 2 | 800 | 9 |
| B | 2 | 1200 | 11 |
| C | 3 | 900 | 11.5 |
| D | 4 | 1600 | 17 |
Chapter 005 found the rule hiding in this table:
Check house C: ✓. Our model has the same shape with the numbers left blank:
Three dials. is ₹ lakh per room, is ₹ lakh per square foot, is the price of the bare plot. And the loss is Chapter 1’s mean squared error:
Now stand somewhere on that loss and ask Chapter 018’s question: how steep is it here?
The question has no answer. Not “we don’t know the answer yet” — the question is incomplete. Turning up might raise the loss. Turning up at the same moment might lower it. Turning both up together does something else again. There is no single number called “the slope”, because the loss does not have one slope; it has a different slope for every direction you could move in.
Think — With one dial, “left” and “right” were the only choices, and one number covered both (its sign chose the side). With two dials you can move in a full circle of directions, and with a billion dials in a space of directions so large it has no picture. A single number cannot possibly describe all of them.
Pinning a dial so we can draw
To keep pictures possible for the next several sections, we do exactly what Chapter 018 did: pin one dial at its true value and watch the other two move. Chapter 018 pinned ; we pin
and study the surface . This is a convenience, not a cheat — and it is temporary. Everything we build will be stated for dials, and §22 puts back.
With pinned at its true value, the remaining two dials still have a perfect answer waiting at , where the loss is exactly zero.
The surface, in closed form
We can write down exactly, and it is worth doing because every number in this chapter will be checkable by hand afterwards.
Our prediction for house is . The truth is . Subtract:
The area term cancels completely — both lines price area identically, because we pinned correctly. Write and for “how wrong each dial is”. Then
Split the sum into three pieces and pull out everything that does not depend on :
Both leftovers are properties of the four houses alone:
Sanity-check it at the origin, , . Predictions are , errors are , so
And the formula gives ✓. Two completely different routes, same number.
Notice the . That is exactly the that Chapter 005 §10 used to explain why raw features are badly scaled, and the same quantity Chapter 1 §10 called for its own data. The steepness of a loss valley along a feature is always that feature’s mean square. It keeps returning because it is the same fact.
2. What Would a Solution Need?
Before inventing anything, list what an honest answer must do.
- Give one number per dial, not one number overall. We have to know what to do with and what to do with , separately, because we have to set them separately.
- Combine into an answer for any direction. Once we know the per-dial numbers, we must be able to say how steep the surface is along any direction, including diagonals nobody asked about in advance.
- Name the steepest direction. Of the infinitely many ways to walk, one is downhill fastest. We want it, not just a direction that happens to work.
- Scale to a billion dials. Anything requiring a picture, or requiring us to try each direction, is dead on arrival.
- Survive composition. Our loss is not a formula in — it is a formula in the predictions, which are a formula in . Whatever we build must handle a quantity that reaches the parameters only through other quantities.
Requirements 1–3 occupy the first half of this chapter. Requirement 5 is the second half, and it is the one that will still be doing work in Chapter 083.
3. First Attempt: Nudge Both Dials Together
The obvious move is to copy Chapter 018 exactly. It measured a slope by nudging the input and dividing:
We have two inputs, so nudge them both:
This is perfectly well defined. It produces a number. Let us see what the number is worth.
At this comes out to (the notebook checks it numerically in Step 3). Negative — so the loss falls when we turn both dials up together. Useful? A little. But now ask the question we actually need answered: by how much should we turn up , and by how much ? The number has nothing to say. It would be whether the truth were ” is doing all the work” or ” is doing all the work” or anything in between. One number cannot instruct two dials. Requirement 1, violated on the first line.
It is worse than uninformative. It actively lies.
A Tempting Wrong Idea
“Nudge everything together and read one slope. If it comes out zero, we are at the bottom.”
Stand at . Nudge both dials together and the measurement reads exactly zero. By this test we have arrived: the ground is flat, training is finished, go home.
The loss there is , and the true minimum — where the loss is — sits at , a distance of away. We are nowhere near the bottom and the instrument says we are standing on it.
Why? Because at that point is too large and is too small by amounts that happen to cancel. The individual slopes are and . Moving both dials up in lockstep really does leave the loss unchanged — we have measured one direction out of infinitely many, and picked one that happens to run along the contour. The instrument is not broken; it answered a different question from the one we asked.
The failure is precise, and it tells us what to fix: we must stop mixing the dials. If we want to know what is doing, we must move and nothing else.
4. The Discovery: Nudge One Dial, Hold the Others
Here is the whole idea, and it is almost embarrassingly simple once the failure above has made it necessary.
To find out what one dial is doing, freeze every other dial and vary only that one.
The instant you freeze , the function stops being a surface and becomes a curve — a function of the single variable — and Chapter 018 knows exactly what to do with those. So:
Read it aloud, slowly:
“Partial dee L by dee : nudge by a tiny amount, leave exactly where it is, see how much moves, and divide by the size of the nudge.”
This is a partial derivative. The word “partial” is doing exactly one job: reminding you that this measurement is about part of the input, with the rest held still.
Likewise, freezing and varying :
The curly
The symbol is a stylised letter d, and it is not the same as Chapter 018’s . The difference is a promise about context:
| Symbol | Read as | Promises |
|---|---|---|
| “dee f by dee x” | depends on and nothing else | |
| “partial dee f by dee x” | depends on other things too, and they are being held fixed |
That is the entire distinction. is a warning label: other variables exist; I am ignoring them on purpose.
Never read as a number being divided. As with in Chapter 018 §6, is one indivisible symbol shaped like a fraction.
The three levels
| Level | A partial derivative is… |
|---|---|
| 💡 Intuition | A mixing desk has many sliders. To learn what one slider does, you push that one and listen. Push three at once and you cannot tell which caused what. |
| ✏️ Numbers | At : nudge alone and falls at a rate of per unit. Nudge alone and falls at a rate of per unit. Two different numbers, from the same point. |
| 🎓 Abstraction | , where is the vector that is in slot and everywhere else. |
That last line says the general thing in one breath: move along axis only. Chapter 005’s basis vectors have quietly come back to work.
How to actually compute one
The mechanical rule falls straight out of the definition, and it is the only rule you need:
Treat every other variable as if it were a constant, then differentiate with Chapter 018’s rules.
Because that is literally what “hold them fixed” means. If is not moving, then , , and are all just numbers as far as is concerned — and Chapter 018 §7 told us the derivative of a constant is zero.
Try it on something small, to build the reflex. Let .
Differentiating with respect to , treat as a number, say : , whose derivative is . Put back:
Differentiating with respect to , treat as a number: , whose derivative is the coefficient :
Two different functions, from one . That is normal and it is the point.
5. Deriving Our Two Partials
Now do it for the loss that matters. We will get the same two answers by three different routes, because agreement between independent derivations is the only real proof that we have not fooled ourselves.
Route 1 — from the closed form
Hold fixed, so is a constant. Differentiate term by term with the sum, constant-multiple and power rules from Chapter 018 §7:
- — the bracket is a constant multiplier, and has derivative
- — a pure constant
Now hold fixed and do the same in :
Look at what the middle term did. contains a , and contains a . The dials are coupled. How steeply the loss climbs in the direction depends on where currently is. This is not an artefact of our algebra — it is why tuning parameters one at a time is such a miserable way to train a model, and it is why the cross term exists at all. It exists because rooms and the bias are correlated across our four houses: every house has some rooms, so raising and raising do partly overlapping jobs.
Route 2 — from the sum, without the closed form
The closed form was a luxury of this tiny problem. In general we have only
Differentiate inside the sum — legal, because the sum rule from Chapter 018 §7 says the derivative of a sum is the sum of the derivatives, and is a constant multiple. For one term, with :
That step used the chain rule, which we have not derived yet — §16 does, properly, and §19 returns to redo this line honestly. For now note only that , so nudging by changes by exactly , giving . Therefore
These are exactly the two formulas Chapter 1 §11 handed over on trust, promising a derivation later. This is later.
Read them in English:
- is the average error, weighted by how many rooms each house has. A house with 4 rooms pushes on the rooms-weight four times as hard as a house with 1 room, because changing the rooms-weight moves that house’s prediction four times as much.
- is the average error, plain. Every house pushes on the bias equally hard, because the bias moves every prediction by the same amount.
The structure is the same in both: error how much this parameter moves that prediction. Hold onto that sentence. In Chapter 083 it becomes backpropagation, and in Chapter 085 it becomes .
Route 3 — numerically
The notebook (Step 5) computes both partials with the finite-difference recipe from Chapter 018 §11, , and asserts agreement with Routes 1 and 2 at four different points. That is a gradient check, and it is the single most useful debugging tool in this entire subject: when you derive a gradient by hand and implement it, you compare it against finite differences before you trust one line of it.
6. ✏️ Hand Calculation — Both Partials at the Origin
Start ignorant: , (with pinned at ).
Predict.
Errors. .
Loss.
Partial with respect to — error times rooms, averaged, doubled:
Partial with respect to — error, averaged, doubled:
Cross-check with the closed form. ✓ and ✓.
Read the answer. Both partials are negative, so both dials are too small — raising either one lowers the loss. And ‘s slope is nearly three times steeper than ‘s, which makes sense: a one-unit change in the rooms-weight moves every prediction by 2 to 4 lakh, while a one-unit change in the bias moves every prediction by exactly 1.
The notebook asserts every number in this box: , , , and the four predictions.
7. From Many Slopes to One Object: The Gradient
We have two numbers where we used to have one. With three dials we would have three; with a billion, a billion. Carrying them around as loose scalars is exactly the mess Chapter 005 solved for house measurements, and the solution is the same: put them in a vector.
This is the gradient. The symbol is an upside-down Greek delta, pronounced “nabla” or just spoken as “grad”: is read “grad L” or “the gradient of L”.
At our origin:
Three things are true about this object, and each one is doing work:
It is a vector, so it has a length. From Chapter 005 §6:
It is a vector, so it has a direction. And §10 will prove that direction is the single most important fact about the point we are standing on.
It lives in the same space as the parameters. because . This is not a coincidence, it is a structural guarantee, and §22 makes it a safety check.
Intuition — The gradient is not “the slope.” It is the complete slope report: one entry per dial, saying how sensitive the loss is to that dial right now. Chapter 1 wrote in its update rule and told you to take it on faith. Here it is.
General definition
For any function of variables :
Nothing changes when is a billion except the amount of storage. That is requirement 4, satisfied — the gradient is a list, and lists scale.
Common Mistake — saying “the gradient of at .” The gradient is evaluated at a point in parameter space, , not at a single coordinate. Change and both entries of change, as §5 showed.
8. The Linear Approximation: What the Gradient Predicts
We have per-dial slopes. Requirement 2 asks for a slope along any direction. Getting there needs one idea, and it is the idea that makes the gradient more than bookkeeping.
Suppose we move from to , with both changes small. How much does change?
Split the move into two legs — first east, then north:
This is exact — the two middle terms cancel, nothing has been approximated yet. Now handle each leg.
Leg 1 varies only , which is precisely what measures, so for small ,
Leg 2 varies only , so
That partial is evaluated at a slightly shifted point. If the partials are continuous — which for our polynomial loss they certainly are — the shift changes them by an amount that vanishes as , and the error it introduces is second-order small. Replacing it with the partial at our own point:
And the right-hand side is a dot product — Chapter 005 §7, the operation we invented to multiply a list of weights against a list of measurements:
This is the multivariable version of "". With one dial, the derivative told you what a small step does. With many dials, the gradient dotted with your step tells you what that step does. The gradient is the machine that converts a proposed move into a predicted change in loss.
Check it numerically
At , propose the step . Prediction:
Truth: , so the actual change is . The prediction is wrong by about — and the error shrinks like the square of the step size, which the notebook checks in Step 8 by halving the step and watching the error fall by four.
The tangent plane
Geometrically, is the equation of a plane touching the bowl at our point — the exact analogue of Chapter 018 §9’s tangent line. One dial gave a tangent line; two dials give a tangent plane; dials give a tangent hyperplane nobody can draw and everybody can compute with.
9. Directional Derivatives: Steepness in Any Direction You Choose
Now requirement 2 is one line away.
Pick a direction and walk in it. A direction is a unit vector — Chapter 005 §6 — meaning , so that “distance travelled” means what it says. Step a distance along it: . The directional derivative is the rate of change of per unit of distance travelled in that direction:
Substitute the linear approximation from §8, with :
Divide by — and the cancels exactly, as it did in Chapter 018 §4 — leaving
One dot product answers every direction at once. We computed two numbers, and from them we can now report the steepness along any of the infinitely many directions in the plane, without measuring any of them.
The full report at
. Dot it with various unit directions:
| Direction | Meaning | Reading | |
|---|---|---|---|
| raise only | steeply downhill | ||
| lower only | steeply uphill | ||
| raise only | downhill, gently | ||
| lower only | uphill, gently | ||
| raise both equally | downhill — but not the best | ||
| lower both equally | uphill | ||
| along the contour | perfectly flat | ||
| the steepest descent | downhill, fastest possible |
Every one of these comes from the same two numbers and one dot product. The notebook verifies each row against a direct finite difference in Step 5.
Two rows deserve attention immediately.
The diagonal — “turn both dials up equally”, the intuitive move — gives . The last row gives . The intuitive move is 10% worse than the best available. With two dials that is a mild waste; with a billion dials, systematically moving in a direction that is not the steepest is the difference between training finishing this week and never.
And the row that reads exactly : there is a direction in which the loss does not change at all, to first order. You can walk along it and get nowhere. That direction is not a curiosity — §11 shows it is the contour line through our point, and §12 shows what happens to people who ignore it.
10. Why the Gradient Is the Direction of Steepest Ascent
Now requirement 3, and this is the theorem the whole chapter is built to prove.
We want the unit vector that makes as large as possible. Chapter 005 §8 derived, from the law of cosines, the identity that settles it:
Apply it with and , remembering :
where is the angle between our chosen direction and the gradient. Now stare at that for a second, because it contains the entire answer.
is a fixed positive number — it does not depend on which direction we pick. The only thing we control is , and cosine lives in . So:
| Meaning | |||
|---|---|---|---|
| maximum — steepest ascent | |||
| flat — along the contour | |||
| minimum — steepest descent |
That is not a definition, a convention or an analogy. It is a consequence of the dot product formula, which was itself a consequence of the law of cosines in Chapter 005. We derived it.
Check the numbers
At , . The theorem says no direction can beat for descent. Look back at §9’s table: east gave , the diagonal gave , and the direction gave exactly ✓. Nothing beat it, and the steepest-descent direction hit the bound exactly, as it must.
Precision matters here. “Steepest” is measured with respect to the ordinary Euclidean length of a step — the we have been using since Chapter 005. Measure step size differently and a different direction wins. This is not pedantry: it is exactly the door that Chapter 32’s optimizers (Adam rescales each coordinate) and Chapter 56’s metrized deep learning walk through. For now, Euclidean, and we will say so every time it matters.
And “steepest” means locally, at this point, for an infinitesimal step. Nothing here says the gradient direction is a good direction to travel any appreciable distance. §12 is about people who forget this.
11. The Geometry: Contour Lines and Perpendicularity
There is a picture underneath §10, and it is the picture to carry for the rest of the course.
A contour (or level set) of is the set of parameter pairs that produce the same loss — the loop you would walk along a hillside without going up or down. On a map they are the concentric rings around a peak; on our loss they are concentric rings around .
For our quadratic loss they are ellipses. The set is
and the cross term is exactly what tilts them off the axes.
b
│ ╱‾‾‾‾‾‾‾‾╲ each ring is one loss value
3 │ ╱ ╱‾‾‾╲ ╲
│ │ │ ⭐ │ │ ⭐ = (2, 1), L = 0
1 │ │ ╲ ___ ╱ │
│ ╲ ╱ rings are long and thin:
-1 │ ╲_______╱ one direction is ~122× steeper
└──────────────────────── w₁
0 1 2 3 4
Now the key fact, and it follows immediately from §9 and §10:
The gradient at a point is perpendicular to the contour through that point.
Why: walking along the contour leaves unchanged, so the directional derivative along the contour’s tangent is zero. But , so — and Chapter 005 §8 told us a zero dot product means orthogonal, a angle. Nothing more is needed.
Verify it at . The gradient is . A perpendicular direction is normalised, i.e. — flip the components and negate one, the standard trick in two dimensions. Dot them:
And the notebook walks a distance along that tangent and finds the loss moved from to — flat to seven decimal places, exactly as first-order theory demands.
Intuition — Water poured on a hillside runs perpendicular to the contour lines, because that is the fastest way down. The gradient is the same statement written in algebra.
12. ⚠️ A Tempting Wrong Idea: The Gradient Points At the Minimum
Here is a belief that is almost universal among people meeting gradients for the first time, is very nearly true in easy cases, and is flatly false.
“The gradient points uphill, so minus the gradient points towards the bottom. Follow it and you go straight to the answer.”
The first clause is proven. The second does not follow from it, and the difference is the reason Chapter 32 exists.
Stand at . Read that point carefully: is already exactly correct. The rooms-weight is 2, the truth. Only the bias is wrong — it is 3 when it should be 1. The minimum is straight below us: the direction to it is .
Compute the gradient:
Steepest descent says: decrease . Decrease the one dial that is already perfect, and decrease it hard — of the step is spent on and only on the bias, the parameter that is actually wrong.
The angle between the steepest-descent direction and the direction to the minimum is
Seventy degrees off target. And yet it is not a mistake — the loss really does fall faster that way. Step a distance downhill and the loss drops from to . Step the same distance straight at the minimum and it only drops to . The gradient is telling the truth about the next instant and saying nothing whatever about the destination.
Why this happens. The contours are tilted ellipses, not circles. On a circular bowl, perpendicular-to-the-contour really does aim at the centre, and gradient descent goes straight home. On a stretched, tilted bowl it does not, and the more stretched the bowl, the worse the aim. The stretch factor has a name we already met: Chapter 005 §10 called it the condition number, and Chapter 023 will compute it for this exact loss.
What to take from this: the gradient is a local instrument. It is a compass, not a map. Chapter 023 builds an algorithm that uses a compass repeatedly and shows exactly what that costs.
13. When Partials Are Not Enough
Everything from §8 onward rested on one approximation: . It is worth knowing that this can fail, because the failure explains why textbooks are careful about a word we have been using loosely.
Having partial derivatives is weaker than being well approximated by a plane. Partials only probe two directions — along the axes. A function can be perfectly well behaved along both axes and insane everywhere else.
The standard example:
Along the -axis, , so for every . Flat. So . By symmetry . Both partials exist and are zero, so , and the linear approximation predicts is flat near the origin.
Now walk the diagonal, :
for every non-zero , however small. Approach the origin along the diagonal and sits stubbornly at ; approach along an axis and it is . The function is not even continuous at the origin, let alone flat. The directional derivative along the diagonal is — it does not exist.
So gave and the truth was . Partials existing is not enough.
The condition that is enough, and that is what “differentiable” means for several variables, is the existence of a genuine linear approximation:
The useful practical theorem: if all the partial derivatives exist and are continuous near a point, the function is differentiable there. Our loss is a polynomial, so its partials are polynomials, so they are continuous everywhere, so we are safe everywhere. Every loss in this course built from sums, products and smooth activations is safe for the same reason — and the exceptions (ReLU’s corner, Chapter 018 §13) are known, named and handled deliberately rather than accidentally.
14. The Problem Again: Our Loss Is Built By Composition
We have the gradient and we know what it means. But look back at §5, Route 2, where an unexplained step sat in the middle of the derivation:
We got away with it because our model is linear and the algebra was easy to check another way. That luck is about to run out, and it is worth seeing why now rather than in Chapter 083.
The loss does not depend on directly. It depends on it through a chain:
flowchart LR
A["w₁, w₂, b<br/>parameters"] --> B["ŷ = w₁r + w₂a + b<br/>prediction"]
B --> C["e = ŷ − y<br/>error"]
C --> D["ℓ = e²<br/>squared error"]
D --> E["L = mean of ℓ<br/>loss"]
Change , and the prediction moves; because the prediction moved, the error moves; because the error moved, its square moves; because the squares moved, their average moves. Four links, and we want the rate of change across the whole chain.
This is not a quirk of our example. Every model in this course is a composition, and the deeper the model the longer the chain. A 50-layer network has a chain of 50 links between a first-layer weight and the loss. If we cannot differentiate through composition, we cannot train anything.
That is requirement 5, and it needs its own discovery cycle.
15. First Attempt: Expand Everything
The direct approach: substitute every link into the next until only remains, then differentiate the result.
Take house A alone: , , , with pinned at and the bias written as .
Expand:
Differentiate with §4’s rule, holding fixed:
At this is . Correct — the notebook confirms it.
So it works. Why is it not the answer?
Because the expansion is a dead end. Three reasons, in increasing order of seriousness:
- It does not survive size. That was one house with a linear model. Four houses triples the algebra. A two-layer network with a nonlinearity in between produces an expression you cannot write on a page, and a 50-layer network produces one you cannot write in this universe.
- It throws away structure. The expansion mixes into one lump, destroying the information that this number is twice the error, times the number of rooms. That structure is what makes the formula computable at scale.
- It cannot be automated as written. A framework cannot symbolically expand a 50-layer network. It needs a rule that works link by link, locally, using only what is at hand.
A Tempting Wrong Idea
” depends on and depends on , so is just — the rate at which the square grows.”
That is at our point, and the true answer is . Off by a factor of exactly — which is , the number of rooms.
The missing factor is the whole content of the next section. The error does not move at the same speed as ; it moves twice as fast, because one extra ₹ lakh per room raises a two-room house’s prediction by ₹2 lakh. Ignoring the exchange rate between links is the most common gradient bug there is.
What we need is a rule that composes rates of change. Something that says: if changes times as fast as , and changes times as fast as , then changes times as fast as .
Everyone’s instinct fills that blank with . Let us find out whether the instinct is right.
16. The Discovery: The Chain Rule
The child’s version
Bicycle gears. Turn the pedals once and the chainring turns once. The chainring drives the rear sprocket at 3 turns per turn. The wheel is bolted to the sprocket, so it turns 1-for-1 with it, and the bike moves 2 metres per wheel turn.
How far does the bike go per pedal turn?
Nobody hesitates over that. Rates along a chain multiply. The chain rule says calculus behaves exactly like gears, and the honest question is why that needs proving at all.
It needs proving because a derivative is an instantaneous rate, and each gear ratio in a real function changes as you move. The chainring ratio at is not the ratio at . So the multiplication has to be justified, and the justification has to say where each factor is evaluated.
The derivation
Let and , so — read “f of g of x”, the composition. We want .
Start from Chapter 018’s definition. Nudge by and let be the resulting change in :
Then changes from to , and
Now the trick, and it is a single algebraic move: multiply and divide by .
Two difference quotients, exactly the shape Chapter 018 defined. Now let . Because is differentiable it is continuous, so too — the inner nudge shrinks along with the outer one. The first factor heads to and the second to :
or, in Leibniz’s notation, in the form everybody remembers:
This is why Chapter 018 §6 insisted that Leibniz’s notation was worth learning even though it is not a fraction. Written this way the chain rule looks like cancelling — which is not what is happening, but the notation was deliberately designed so that the true rule looks like the false operation. That is good design, and it is why won.
Where each factor is evaluated matters, and the boxed formula says so: is evaluated at — the value the inner function actually produced — not at . Getting this wrong is the second most common gradient bug, after forgetting a factor entirely.
A gap worth naming. The step “multiply and divide by ” needs , and can be zero for arbitrarily small (if is locally constant). The repair is standard: define for and , which makes continuous at ; then holds for every small , including those where , and the limit goes through. The idea is unchanged; the bookkeeping is just made airtight. Berkeley (Chapter 018 §5) would have asked, and he would have deserved an answer.
Use it on our chain
Back to house A, the chain , at , .
Compute each link’s local rate — each one is a one-line derivative of a simple function:
| Link | Function | Local rate | Value at our point |
|---|---|---|---|
| from | |||
| from | |||
| from |
Multiply along the chain:
Exactly the that §15’s brute-force expansion produced — and obtained without expanding anything. Each factor came from differentiating a formula with at most two symbols in it.
And the same three factors, with the last one swapped, give the bias:
This is the shape of backpropagation. You never differentiate the whole network. You differentiate each link — one tiny, local, obvious derivative — and multiply along the path. Chapter 083 gives this an algorithm and a direction of travel; the mathematics is already here.
17. The Multivariable Chain Rule: Adding Up the Paths
One gap remains. Our real loss is an average over four houses, so reaches through four separate predictions, not one. Chains that fork need a rule for recombining.
The statement
Suppose and each depends on . Then
In English: multiply along each path, then add over the paths. Every route from to contributes, and their contributions are independent, so they sum.
The derivation
It falls straight out of §8’s linear approximation. Nudge by . Each intermediate moves by approximately . The linear approximation for says
Divide by and let ; the approximations become exact in the limit because their errors are second-order in :
Why a sum, intuitively — if a change in raises your electricity bill by ₹30 and your water bill by ₹20, your total bill rises by ₹50. Separate channels of influence add.
A test we can check completely
Let , with and . Two paths from to .
Local rates: , , , .
Multiply along paths and add:
Now check directly: , and the power rule gives ✓. At : both ways. The rule survives a case where we know the answer independently.
18. The Product Rule, For Free
Chapter 018 §7 derived four differentiation rules and postponed two. One of them just fell out of §17 without any extra work — notice that the calculation above never used the specific forms , until the last step.
Redo it in general. Let where and are both functions of . The multivariable chain rule with gives
The product rule, derived rather than memorised. And the multivariable chain rule explains the thing that makes students suspicious about it: why two terms? Because there are two paths — can reach the product by moving , or by moving , and both happen at once.
Check from the definition too, so it rests on more than one argument. Expand by adding and subtracting in the numerator:
Let : by continuity, and the two quotients become and . Same answer, .
The quotient rule follows the same way and we will not need it until Chapter 039’s sigmoid, where we will derive it there.
19. Rebuilding Our Partials With the Chain Rule
Now return to §5 Route 2 and pay off the step we borrowed.
depends on through the four predictions . That is four paths, so §17 applies with :
Compute the two kinds of factor separately.
How the loss responds to one prediction. . Only the term contains ; all the others are constants as far as is concerned. So
How one prediction responds to . , so nudging by moves by exactly :
Multiply along each path and add over paths:
The formulas Chapter 1 asserted, now derived twice from two directions, with no unexplained steps left.
Hand Calculation — the paths, one by one, at
Errors , so the four “how much does the loss care about this prediction” factors are :
House contribution A B C D sum For the bias every , so the contributions are the factors themselves: .
Both match §6 exactly. Note who pushed hardest: house D, with the largest error and the most rooms, supplied of the — almost half. Large-error, large-input examples dominate a gradient. That single observation explains outlier sensitivity (Chapter 22), why inputs are normalised (Chapter 33), and why gradients explode in badly scaled networks.
20. The Computational Graph
The chain rule suggests a way of organising a calculation that will become, in Chapter 089, an actual data structure.
Draw the computation as a graph: nodes are quantities, edges are “this is computed from that”, and each edge carries its local derivative.
flowchart LR
W["w₁"] -- "∂ŷ/∂w₁ = r" --> Y["ŷ"]
A2["w₂"] -- "∂ŷ/∂w₂ = a" --> Y
B["b"] -- "∂ŷ/∂b = 1" --> Y
Y -- "∂e/∂ŷ = 1" --> E["e"]
E -- "∂ℓ/∂e = 2e" --> Lc["ℓ"]
Lc -- "∂L/∂ℓ = 1/n" --> L["L"]
Two passes over this graph do everything:
Forward — walk left to right, computing values. . This is just making a prediction and scoring it.
Backward — walk right to left, multiplying local derivatives. Start at with the seed , and at each edge multiply by that edge’s local rate. Where edges merge, add, by §17.
Run it backward for house A at :
| At node | Accumulated | Reached by |
|---|---|---|
| seed | ||
| (A’s share) | ||
| (A’s share) |
Those are exactly house A’s rows in §19’s table. Do it for all four houses and add at the parameter nodes, and you have the full gradient.
Count the work. The forward pass evaluates the model once. The backward pass walks the same graph once more, doing one multiplication per edge. One backward pass produces the derivative with respect to every parameter, for a cost comparable to one forward pass — regardless of how many parameters there are.
Compare with Chapter 018 §11’s numerical derivative, which needs a fresh forward pass per parameter. For parameters that is forward passes per step versus one. This ratio is the reason deep learning is possible at all, and Chapters 27 and 31 are where we build it properly.
21. 📜 History Lens — Leibniz, and the Naming of
Imagine you are Gottfried Wilhelm Leibniz in the 1670s. You have no derivative notation, because nobody does. You are working on tangents to curves, and you keep meeting quantities built out of other quantities — a curve defined through an auxiliary variable, which is itself defined through another.
You need two things at once: a way to write a rate of change, and a way to combine rates along a chain. Leibniz produced both in the same years, and they are the same invention. He wrote the rate of change of with respect to as , picturing it as a ratio of infinitely small differences. Then chaining is immediate on the page: , which looks like cancellation.
The notation was shaped so that true rules would look obvious. Newton’s dot notation, , said nothing about with respect to what, and the chain rule in it is a thing you must remember rather than a thing you can see. Leibniz’s notation won across Europe, and it is the notation this course uses.
📜 The manipulation was not rigorous at the time — that is Berkeley’s complaint from Chapter 018 §5, and it took Cauchy and Weierstrass to repair. The repaired version is §16: no infinitely small quantities, just two difference quotients and a limit.
The symbol has a stranger history. William Rowan Hamilton used an inverted delta as a differential operator in his work on quaternions in the 1840s. It had no spoken name for years, which made lecturing awkward. The name “nabla” — after an ancient harp of roughly that triangular shape — is generally credited to a suggestion made to Peter Guthrie Tait, who used and popularised the operator; Tait’s collaborators, including Maxwell, corresponded about the name with some amusement. Accounts of exactly who proposed it differ, so we will not pretend to a single definitive story.
Two centuries separate the chain rule from its first use in training a machine. The mathematics was finished long before anybody had a reason to run it a trillion times.
22. Shapes
From Chapter 008 onward we track dimensions, because shapes rule out wrong formulas before arithmetic gets a chance to.
Take the honest three-parameter model, , with houses and features.
| Object | Shape | Why |
|---|---|---|
| — feature matrix | one row per house, one column per feature | |
| — weights | one weight per feature | |
| — bias | scalar | one number added to every prediction |
| one prediction per house | ||
| one error per house | ||
| scalar | one number for the whole dataset | |
| one sensitivity per prediction | ||
| one slope per weight | ||
| scalar | one slope for the bias |
The rule worth memorising: the gradient of a scalar with respect to a thing has the same shape as that thing. is a scalar and is , so is . If your gradient has a different shape from your parameter, you cannot even perform the update — the subtraction is undefined. This check catches real bugs, and it is the check that will keep you alive in Chapter 085.
Shape reasoning rules out a wrong formula
Suppose someone proposes and someone else proposes . Check shapes without computing anything:
Both pass, so shapes do not settle it — but a third proposal, , has against and does not even multiply. Rejected in two seconds, no arithmetic. (The correct one is ; Chapter 038 derives the matrix form in full.)
The full gradient, in real units
Put back and compute at — all three dials ignorant. Predictions are all zero, so errors are and .
Look at those magnitudes. The area component is 1,195 times larger than the bias component — not because area matters more, but because area is measured in hundreds while rooms are measured in ones. A single step size has to serve all three. Chapter 005 §10 predicted exactly this disaster from the condition number; here it is, written as a gradient. Chapter 023 will show what it does to training, and Chapter 33 will fix it properly.
23. 🔬 The Experiment: Which Direction Is Really Steepest?
Predict before reading on. Stand at , where . Sweep a unit direction all the way around the circle, from to , and plot the directional derivative against the angle.
- What shape is that plot? A straight line, a parabola, a sine wave, or something spikier?
- How many angles give exactly zero, and are they related?
- The most negative value is . What is the most positive?
- The direction “raise both dials equally” gives . Roughly how many degrees off the best direction is it?
Run it (notebook Step 9) and the answer to (1) is a cosine wave — not approximately, exactly. §10 already told us why:
That is a cosine of amplitude . The plot is a scaled cosine, and the following are immediate:
| Question | Answer | Why |
|---|---|---|
| Shape | cosine, amplitude | , §10 |
| Zeros | exactly two, apart | at and — the two ways to walk the contour |
| Maximum | at , along | |
| Diagonal’s penalty | about off |
The last row is the one to sit with. “Turn both dials up equally” is nearly degrees away from the best direction here, and gives up of the available descent — on a two-parameter problem with a mild tilt. Chapter 023 measures what that costs when it is repeated a thousand times.
Second prediction. Now move to , where . Before running: will the cosine wave have a different amplitude? A different phase? Both?
24. How It Breaks
| Failure | What it looks like | Why |
|---|---|---|
| Nudging several parameters together | “slope is zero” at a point that is not a minimum | §3. One number cannot instruct many dials, and the direction you happened to pick may lie along a contour. |
| Forgetting a chain factor | gradient off by a constant factor; training too slow or explosive | §15. The vs mistake: the exchange rate between links was dropped. |
| Evaluating at the wrong place | gradient plausible but wrong; loss falls then stalls | §16. must be evaluated at , the value produced, not at . |
| Forgetting to sum over paths | gradient is one house’s worth instead of all four | §17. Forked chains add; using one branch silently divides the gradient by . |
| Assuming aims at the minimum | surprise that training zig-zags | §12. It is perpendicular to the contour, not aimed at the centre, unless the contours are circles. |
| Trusting partials without differentiability | linear approximation confidently wrong | §13. has both partials zero at a point where it is not continuous. |
| Unnormalised direction vector | directional derivative scales with the vector’s length | §9. is per unit distance; if your “rate” is doubled. |
| Mismatched shapes | ValueError at the update, or worse, silent broadcasting | §22. must have ‘s shape. |
25. 🎯 Machine Learning Connection
| This chapter | In machine learning |
|---|---|
| partial derivative | how sensitive the loss is to one weight, everything else fixed |
| the gradient | the object every optimizer consumes; w.grad in PyTorch |
| gradient norm — monitored during training; the quantity in gradient clipping (Ch 32, 40) | |
| is steepest descent | why the update rule has a minus sign, now for many dials |
| the first-order model that every gradient method is built on | |
| gradient ⊥ contours | why training zig-zags in a stretched valley (Ch 08, 32) |
| chain rule | backpropagation (Ch 27) — the entire algorithm is this rule plus bookkeeping |
| multivariable chain rule, summing over paths | why gradients accumulate at a node used more than once (Ch 31) |
| the “upstream gradient” or that flows backward through a layer (Ch 28) | |
| computational graph | what an autodiff framework literally builds at runtime (Ch 31) |
| finite-difference check | gradcheck — how you verify a hand-derived gradient before trusting it |
Chapter 1’s update rule can finally be read with nothing taken on faith:
“Compute how the loss responds to every parameter (§4–§7); that collection points in the direction of steepest increase (§10); so move against it (the minus sign), scaled by .”
Every clause is now a theorem we proved. Except one — the .
26. Distinctions That Matter
| — depends on alone | — others exist and are held fixed |
| Partial derivative — a number, along one axis | Gradient — a vector, all axes at once |
| Gradient — a vector of slopes | Directional derivative — a number, for one chosen direction |
| Direction of steepest ascent — | Rate of steepest ascent — |
| — points uphill | — points downhill |
| Perpendicular to the contour — always true | Pointing at the minimum — only for circular contours (§12) |
| Partials exist — weak | Differentiable — a genuine tangent plane exists (§13) |
| Chain rule — one path, multiply | Multivariable chain rule — many paths, multiply then add |
| Forward pass — values, left to right | Backward pass — derivatives, right to left |
| — an intermediate quantity | — a parameter we are allowed to change |
27. What We Discovered
- A function of many variables has no single slope; “how steep is it here?” is incomplete until a direction is named.
- Nudging all the dials together gives one number that cannot instruct them separately — and can read exactly zero at a point that is not a minimum.
- The fix is to freeze everything but one dial, which turns the surface back into a curve that Chapter 018 already understands. That is the partial derivative.
- Computing one is mechanical: treat every other variable as a constant.
- Our loss’s partials are coupled — contains — because rooms and the bias do overlapping work across the data.
- Collected into a vector, the partials form the gradient, which lives in the same space as the parameters.
- The gradient converts a proposed step into a predicted change in loss: . That is a tangent plane.
- Hence the steepness along any direction is one dot product, — two numbers answer infinitely many questions.
- Because , the steepest ascent is along and the steepest descent along . Chapter 005’s law of cosines proved it.
- The gradient is perpendicular to the contour through the point — and therefore does not generally point at the minimum. At it is off.
- Partials existing is not enough for the linear approximation to hold; continuity of the partials is the practical guarantee.
- A loss is a composition, and rates along a chain multiply: , derived by multiplying and dividing by the intermediate change.
- Where a chain forks, contributions add — and that single fact hands us the product rule for free.
- Together they let a gradient be computed link by link on a graph, never by expanding the whole expression. One backward pass, all parameters.
28. Mathematics We Built
For our house-price loss with pinned at :
and in the general form, for any linear model:
29. What Each Symbol Means
| Symbol | English | In code |
|---|---|---|
| “partial” — others held fixed | — | |
| nudge only; how fast does move? | dL_dw1 | |
| “grad L” — all the partials, as a vector | grad | |
| the gradient with respect to specifically | grad | |
| steepness in the steepest direction | np.linalg.norm(grad) | |
| a unit direction, | u / np.linalg.norm(u) | |
| rate of change per unit distance along | grad @ u | |
| the axis direction: 1 in slot , 0 elsewhere | np.eye(n)[j] | |
| a proposed step in parameter space | delta | |
| all parameters together | (w1, w2, b) | |
| error on example , | e[i] | |
| how much the loss cares about prediction | dL_dyhat[i] | |
| , | how wrong each dial is | — |
| (returning in Ch 08) an eigenvalue of the curvature | eigvals |
30. One-Minute Explanation
Explain this with no equations at all:
You are standing on a hillside in fog. You cannot see the valley. You are allowed to feel the ground in exactly two directions — due east and due north — and nothing else. How can two measurements tell you which of the infinitely many directions is the steepest way down, and why is that direction not the direction the valley bottom is in?
If your explanation uses the word “gradient” without saying what was measured to get it, you are quoting.
31. Exercises
Level 1 — Observe. Look at §9’s table of directional derivatives. (a) Two rows differ only in sign — why must that always happen for opposite directions? (b) One row is exactly zero; what are you standing on if you walk that way? (c) Now look at §12: the gradient at has a positive component even though is already perfect. Explain in one sentence what the cross term has to do with this. (d) In §22, while . Does that mean area matters a thousand times more than the plot? Justify your answer in terms of units.
Level 2 — Calculate (by hand, no code). For : (a) find and ; (b) evaluate both at and write ; (c) compute and the unit vector of steepest ascent; (d) compute for , and confirm it is smaller than your answer to (c); (e) find a non-zero direction in which does not change at , and verify it by taking a dot product.
Level 3 — Derive. (a) Starting from with , derive using the multivariable chain rule, showing every path. (b) Show that setting all three partials to zero gives three linear equations in — the normal equations that Chapter 038 solves. (c) Prove from that if there are exactly two directions with , and that they are opposite. (d) Derive the quotient rule from the product rule plus the chain rule applied to .
Level 4 — Investigate (notebook Steps 8–11). Reproduce §23’s cosine sweep at , then at , then at . The amplitude and phase both change — explain what each one is measuring. Then do the sweep at the minimum : what happens to the plot, and what does that tell you about how gradient methods behave as they converge? Finally, break something on purpose: implement with the factor omitted and see how far off the finite-difference check is at three different points. Is the error a constant factor, or does it vary?
Level 5 — Design. A colleague proposes “coordinate descent”: instead of using the gradient, minimise the loss over alone (with fixed), then over alone (with fixed), then repeat. (a) For our loss, derive the closed-form optimal given , and the optimal given . (b) Will it reach ? (c) On which loss surfaces would it be fast, and on which would it crawl? Relate your answer to the cross term. (d) Now design a variant that is guaranteed to be at least as fast as steepest descent on every quadratic, and say honestly what it costs to compute.
32. Common Mistakes
| Mistake | Why it is wrong |
|---|---|
| ” and are interchangeable.” | promises other variables exist and are frozen. Using hides a dependency you must not forget. §4 |
| “The gradient is a slope.” | It is a vector of slopes. It has a length and a direction; a slope has neither. §7 |
| ” points at the minimum.” | It is perpendicular to the contour. At it misses by . §12 |
| ” points downhill.” | It points uphill. is downhill. That is where the minus sign comes from. §10 |
| “The direction vector’s length does not matter.” | is per unit distance; an unnormalised scales the answer. §9 |
| “Both partials are zero, so we are at a minimum.” | Zero gradient also happens at maxima and saddle points. Chapter 023 §11. |
| ” because depends on .” | Missing the factor . Off by exactly the exchange rate between the links. §15 |
| “Evaluate at in the chain rule.” | Evaluate it at — the value the inner function produced. §16 |
| “One path is enough.” | Forked chains add over paths. Using one branch silently scales the gradient. §17 |
| “Partials exist, so the tangent plane is valid.” | is the counterexample. Continuity of the partials is what you need. §13 |
33. Socratic Questions
Answers are deliberately not given.
- §3’s “nudge both together” reading was , un-normalised. Is that a bad measurement or a correct answer to the wrong question? What exactly did it measure?
- The gradient is perpendicular to the contour. Contours are curves in 2-D and surfaces in 3-D. In a billion dimensions, what is the contour, and how many independent directions are there in which the loss does not change to first order?
- §10 proved steepest descent given that step size is measured by Euclidean length. What would the “steepest” direction become if you instead measured a step by its largest single coordinate? (This is not idle — it is roughly what Adam does. Ch 32.)
- The product rule has two terms because there are two paths. How many terms does the derivative of have, and can you say why without doing any algebra?
- Chapter 018 said the derivative of a constant is zero. In we treated as a constant — yet is a variable we intend to change. Is there any contradiction? What precisely does the partial derivative claim, and what does it not claim?
- Backpropagation costs about one forward pass for all parameters. Numerical differentiation costs one forward pass per parameter. Where did the saving come from — what is the backward pass reusing that the numerical method recomputes?
- Our loss had a cross term, so its contours are tilted ellipses. What would have to be true of the four houses for the cross term to vanish? (Compute and think about what would make it zero.)
34. 🔭 Bridge to Chapter 023
We came in with an incomplete question and we are leaving with a complete answer.
“How steep is a bowl?” had no answer. “How steep is it in direction ?” has exactly one, — and of all the directions, is provably the fastest way down. Our loss at is , and the gradient says: raise both dials, and raise the rooms-weight about three times harder than the bias.
So we know which way. We do not know anything else.
Look at the size of that gradient: . If we take that literally as a step — move in and in — we land at , which is absurdly far past the answer at . The loss there is not ; it is enormous. The gradient’s length is a rate, not a distance. It tells you how fast the ground is falling right here, and that promise expires immediately, because §12 showed the direction itself changes as soon as you move.
So the questions pile up, and none of them is answered by anything in this chapter:
- How far should we step? Chapter 1 called the scale factor and chose it by taste. Chapter 018 showed that for one parameter the ceiling is — but was a single number, and our curvature now has four entries: , , and two mixed ones. What is the ceiling now?
- How often? One step took us nowhere near the bottom. Ten? Two thousand? How do we know when to stop?
- Does repeating it even work? The gradient is honest only about the next instant. Nothing yet proves that following it over and over arrives anywhere at all.
We know which way is downhill — but how far do we step, and how often?
That is where Chapter 023 begins. It turns the compass into an algorithm, proves when the algorithm converges and when it explodes, and — using Chapter 014’s eigenvalues on Chapter 018’s curvature — predicts the exact learning rate at which our own loss blows up, before running a single step.