Calculus & Backpropagation
Every neural network learns the same way: it measures how wrong it is, asks which way is downhill?, and takes a small step. That question is answered by calculus. This module starts with the slope of a curve, , and builds, one picture at a time, to gradients, Jacobians, Hessians and the chain rule run backwards through a computation graph: backpropagation. You finish by writing a tiny autodiff engine in Python and training something with it.
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.
Derivatives: slopes and rates of change
Watch: The essence of calculus (3Blue1Brown) Watch: The paradox of the derivative (3Blue1Brown)The derivative answers one question: if I nudge the input a tiny bit away from , how many times bigger is the change in the output? On a graph, that ratio is the slope of the line that just touches the curve at .
Start with something you already know: speed. A car's position is metres after seconds. Its average speed between two times is distance over time:
On the graph of , that's the slope of the straight line through two points on the curve, called a secant line. But a speedometer shows something stranger: the speed right now, at a single instant. How can there be a rate of change at one moment, when in a single moment nothing moves? That's the "paradox" in the 3Blue1Brown video, and calculus resolves it like this.
Pick a point and a small step . The secant slope over the short interval from to is
Now make smaller and smaller. For a smooth curve, these slopes stop changing and settle on one number. That number is the derivative of at :
The derivative is not "the change over zero time" (that would be ). It's the value the ratios approach as the time shrinks. Chapter 5 makes "approach" precise; for now, think of it as "what the ratio looks like once is so small that making it smaller doesn't change the answer any more".
Three ways to read the same number, all useful later:
- Slope: is the slope of the tangent line, the line that skims the curve at .
- Rate: it's how fast is changing per unit of input, like metres per second.
- Sensitivity: near , a small nudge in the input changes the output by about . In symbols, . This is the reading that machine learning lives on.
Why does a curve have a slope at all? Zoom in on any smooth curve far enough and it looks like a straight line. The derivative is the slope of that line. This "locally linear" picture comes back in every chapter of this module: the gradient, the Jacobian and backpropagation are all just "zoom in until it looks linear, then use the linear part".
Worked exampleThe slope of at , from scratch
Take and . The secant slope is
With the slope is 6.1; with it's 6.001. As it heads to 6, so . Sensitivity reading: change the input from 3 to 3.01 and the output goes from 9 to about . (The exact value is 9.0601; the leftover 0.0001 is the part, which is tiny when is tiny.)
Do the same algebra at a general point and you get . So the derivative of is the function : one number for every point.
Watch outCommon misconceptions
- "The derivative is the height of the graph." It's the slope at that point. is high at (height 9), but it's going down there: .
- "Just set ." You'd get , which means nothing. You simplify the ratio first (like ), and then see what it approaches.
- "Smaller is always better on a computer." In exact maths, yes. In floating point, a tiny makes a difference of two nearly equal numbers, and rounding error explodes. Steps around to work best for the symmetric difference in double precision.
- "A zero derivative means the function is zero." It means the function is flat there (momentarily not changing), like the bottom of a valley.
In ML & deep learningWhere this shows up
A model's loss measures how wrong it is as a function of a weight . The derivative says which way the loss goes if you nudge the weight: positive means "increasing makes things worse", negative means "increasing helps". Gradient descent moves the weight against the slope, , where (the learning rate) is a small step size. Every network you've heard of is trained by some version of this rule, with millions of weights instead of one.
The finite difference is also how practitioners check that their hand-written or library gradients are right ("gradient checking"), which you'll do in chapter 12.
Practice (pick one answer per question)
A ball's position is metres. What is its average velocity between and seconds?
- 4 m/s
- 8 m/s
- 6 m/s
- 2 m/s
m/s. (6 m/s is the instantaneous speed at , and 2 m/s is at ; the average lies between.)
What is the derivative of at ?
- 3
- 32
- 2
- 30
A straight line is its own tangent, so its slope is the same everywhere: 3. The "+2" only shifts it up and doesn't affect the slope.
For , the secant slope between and simplifies to…
. It tends to as . ( is the change in , before dividing by .)
Estimate for with the forward difference and .
- 2.1
- 2
- 0.21
- 1.9
. The true value is 2; the forward difference overshoots by exactly here.
A loss is , so . You're at and take one gradient-descent step with learning rate . Where do you land?
. Step against the slope: , closer to the minimum at 3. Going to 5.4 would be stepping uphill.
Near , and . Approximately what is ?
- 6.85
- 7.15
- 6.7
- 4
Sensitivity reading: , so .
Estimate for with the symmetric difference and .
- 3.01
- 3.31
- 3
- 2.71
. The true value is 3, so the error is only 0.01 . The forward difference gives , an error of 0.31. Symmetric differences cancel the leading error term, which is why gradient checkers use them.
Code it (optional: real Python runs in your browser and is graded by test cases)
Derivative rules through geometry
Watch: Derivative formulas through geometry (3Blue1Brown)You don't need to take a limit every time. A handful of rules (power rule, sums and constants, sine and cosine) cover most of what you'll meet, and each one has a picture that explains why it's true.
Chapter 1 found the derivative of by algebra. Here's a picture that does the same job and generalises. Think of as the area of a square with side . Grow the side by a tiny . The new area is made of the old square plus three new pieces:
- two thin strips along the sides, each of area ;
- a tiny corner square of area .
So . When is tiny, is tiny squared, far smaller than the strips (if , the strips are about a thousand times bigger than the corner). Ratios of the change to give . The derivative of is : it's the total length of the edges where the new area attaches.
A cube works the same way. Grow the side of by and the main new volume is three thin slabs, one on each visible face, each . The edges and corner are and pieces, negligible. So .
The pattern is the power rule:
Algebraically: expands to . Only the one term with exactly one survives the division and the limit. The rule also works for negative and fractional powers: has derivative , and has derivative .
Two rules let you combine pieces:
- Constants scale: . Stretch a graph vertically by 3 and every slope triples.
- Sums add: . Nudge , and the total change is the change in plus the change in .
Together these say differentiation is linear, the same "linear" as in linear algebra. With the power rule they handle every polynomial: . (A constant like 7 has slope 0: it never changes.)
Sine and cosine. Walk around the unit circle; your angle is , and your height is . Take a tiny step along the circle. That step is a tiny arrow tangent to the circle, of length , and it's tilted so that its vertical part is and its horizontal part is . So
Check the picture: at you're moving straight up, so grows at full speed (slope ); at the top, , you're moving sideways and the height has stopped changing (slope ). These only hold with angles in radians, where arc length equals angle.
Worked exampleDifferentiate
Take it term by term (sums add) and pull constants out (constants scale):
So . At : . A quick numeric check with agrees to many digits.
Watch outCommon misconceptions
- "." Don't drop the in front: there are faces that grow, not one.
- " or ." Write it as and apply the power rule: . ( is what you integrate to; chapter 4.)
- "The derivative of is ." It's . Just after , cos is going down from 1, so its slope must be negative.
- " in degrees." In degrees an extra factor appears. Calculus (and every ML library) uses radians.
In ML & deep learningWhere this shows up
The squared error is a power, so its derivative is just "twice the error": big mistakes push weights hard, small ones gently. Linearity of the derivative is why the gradient of a sum of per-example losses is the sum of per-example gradients, which is exactly what lets you average gradients over a mini-batch, or split a batch across GPUs and add the results. Sines and cosines show up in positional encodings of transformers and in Fourier features, and their tidy derivatives keep those layers easy to train.
Practice (pick one answer per question)
What is ?
Power rule: bring the 5 down and lower the power by one: .
What is the slope of at ?
- 1
- 0
- −1
, and . Near 0, .
For , what is ?
- 8
- 5
- 6
- −2
, so . The constant contributes nothing.
What is the derivative of at ?
. The curve is decreasing for , so a negative slope makes sense.
A square has side 3 cm. The side grows by 0.01 cm. Using the derivative (the two strips), by about how much does the area grow?
- 0.06 cm²
- 0.03 cm²
- 0.0001 cm²
- 0.09 cm²
. The exact change is ; the missing 0.0001 is the corner .
What is at ?
.
On , where is the graph of flat (zero slope)?
when , i.e. , so in that range. That's the peak of , with height . (At , , which makes itself zero, not its slope.)
Code it (optional: real Python runs in your browser and is graded by test cases)
The chain rule and the product rule
Watch: Visualizing the chain rule and product rule (3Blue1Brown)When one function feeds into another, nudges multiply: . When two functions are multiplied, nudges add up like the strips of a growing rectangle: . The chain rule is the single most important idea in this module, because backpropagation is the chain rule and nothing else.
Real functions are built from simpler ones. A neural network is a long pipeline: multiply by weights, add a bias, apply an activation, multiply again, compute a loss. So we need to know how derivatives behave when functions are composed (fed into each other) and multiplied.
The chain rule: nudges travel down a pipeline
Take . Split it into two stages: first , then . Now nudge by a tiny and follow the ripple:
- Stage 1 turns the nudge into a nudge in of size . The local stretch factor is .
- Stage 2 turns the nudge into a nudge in of size . Its stretch factor is .
Chain them: . Stretch factors multiply:
Two details trip everyone up at first. The outer derivative is evaluated at the inner value , not at : it's , not . And it doesn't matter how long the pipeline is: three stages give three factors, fifty layers give fifty factors.
The product rule: a rectangle with two growing sides
For , picture a rectangle with width and height ; its area is the product. Nudge : the width grows by , the height by . The new area adds a strip of along one side, a strip of along the other, and a corner that is tiny squared and disappears. So
The growing square of chapter 2 was the special case : . A handy consequence (the quotient rule) comes from writing and using both rules: .
Worked exampleThe sigmoid and a one-weight neuron
The sigmoid squashes any number into . Its derivative has a famously neat form, (chapter 4 derives it). Now take a neuron with one weight, prediction , and squared-error loss . This is a three-stage pipeline . The chain rule multiplies three local factors:
With , , : , , so . Negative, so increasing lowers the loss, as it should: we want to move up towards 1.
Watch outCommon misconceptions
- "" or "". The first differentiates the inside and plugs it in; the second forgets the inner factor. The answer is .
- "." Try : , but . The product rule has two terms, one per growing side.
- "The chain rule is for weird functions only." Almost every derivative you'll compute in ML is a chain: loss of activation of linear function of weights.
- ": just cancel the ." The cancellation is a great memory aid, and it gives the right answer, but the real reason is that stretch factors multiply.
In ML & deep learningWhere this shows up
Backpropagation (chapter 12) is just the chain rule run from the loss backwards: each layer multiplies the incoming gradient by its own local derivative and passes it on. Because the factors multiply, long chains can make gradients vanish (lots of factors below 1, like the sigmoid's slope, which is at most 0.25) or explode (lots of factors above 1). That's why deep networks use ReLU-like activations, careful weight initialisation, normalisation layers and residual connections: all tricks to keep the product of many chain-rule factors close to 1. The product rule appears inside gating: an LSTM or GLU output is a product , and its gradient splits into two terms exactly as above.
Practice (pick one answer per question)
What is ?
Outer derivative at the inner value, , times the inner derivative .
What is ?
Product rule: (derivative of the first) × second + first × (derivative of the second).
Let . What is ?
- 6
- 2
- 3
- 1
. At : . (Check by expanding: has derivative , which is 6 at 0.)
Using , what is the slope of the sigmoid at ?
- 0.25
- 0.5
- 1
- 0
, so . That's the sigmoid's steepest point, and it's still only 0.25, one reason sigmoids cause vanishing gradients.
What is at ?
- 24
- 12
- 6
- 8
. At : . (12 forgets the inner ; 8 is just .)
A 10-layer chain where every layer's local derivative is 0.25. Roughly how big is the derivative of the output with respect to the input?
- about
- 2.5
- 0.25
- about
Factors multiply: . This is the vanishing-gradient problem in miniature. (2.5 would be adding the factors.)
A neuron predicts with loss . With , , , what is ?
- 0.5
- −0.5
- 0.25
- 1
, . . Positive, so gradient descent will decrease , pushing towards the target 0.
Code it (optional: real Python runs in your browser and is graded by test cases)
Exponentials, , and logarithms
Watch: What's so special about Euler's number e? (3Blue1Brown) Watch: Implicit differentiation, what's going on here? (3Blue1Brown)An exponential grows at a rate proportional to its own size. The constant of proportionality is , and is the one base where that constant is exactly 1, so . The logarithm undoes the exponential, has slope , and turns products into sums, which is why ML works with log-probabilities.
Picture a population that doubles every day: . How fast is it growing at time ? Write out the secant slope:
The factors out, and what's left, , doesn't depend on at all. As it settles on a constant, about . So
The rate is proportional to the current size. That's what makes something exponential: a bigger population has more babies; a bigger balance earns more interest. The same algebra works for any base: with some constant . For , . Somewhere between 2 and 3 there's a base where the constant is exactly 1. That base is , and it's defined by this property:
is its own derivative: at every point, its slope equals its height. With the chain rule, , and any base can be rewritten with : , so . The mystery constants were natural logarithms all along: , .
The natural log, and why its slope is
The natural log undoes : and for . To find its derivative, differentiate both sides of with the chain rule (this trick is called implicit differentiation, the subject of the second video): , so
Geometrically: the graph of is the graph of mirrored in the line , which swaps rise and run, so slopes become reciprocals. Logs also turn multiplication into addition: and .
Two derivatives every ML person knows
Sigmoid. . Chain rule: . Split it as and notice the second factor is . So .
Softplus , a smooth ReLU. Chain rule: . The slope of softplus is the sigmoid.
Worked exampleSoftmax and its log
A classifier outputs scores (logits) for three classes. Softmax turns them into probabilities with exponentials, which are always positive, then normalises:
If the true class is the first, the loss is the negative log-probability, . The second form, "minus the right logit plus the log-sum-exp", is how libraries compute it: never form tiny probabilities and then take their log. And to avoid overflow with logits like 1000, subtract the largest logit first: , with .
The slope of the log-sum-exp with respect to is : softmax is the gradient of log-sum-exp. Chapter 11 uses this to show the famous result that the gradient of softmax + cross-entropy is .
Watch outCommon misconceptions
- "." That's the power rule, for where the base varies. Here the exponent varies, so it's .
- "." Logs turn products into sums, not sums into sums. That's why log-sum-exp can't be simplified further.
- "." The chain rule adds the inner slope: .
- "Softmax of (1000, 1001) is fine to compute directly." overflows to infinity in floating point. Subtract the max first; the answer doesn't change because the factor cancels top and bottom.
In ML & deep learningWhere this shows up
Exponentials make softmax, attention weights and the sigmoid. Logs make the losses: the probability of a whole dataset is a product of per-example probabilities, , which underflows to 0 for any real dataset. Its log, the log-likelihood , is a well-behaved sum whose gradient is a sum of per-example gradients. Minimising the negative log-likelihood is cross-entropy training. And because , a confidently wrong prediction (tiny for the true class) gets a huge corrective gradient.
Practice (pick one answer per question)
What is ?
Chain rule: the outer is its own derivative, times the inner slope 3.
What is the slope of at ?
- 0.5
- 2
, so .
What is at ?
, and . (12 is the power-rule mistake .)
What is the slope of softplus at ?
- 0.5
- 1
- 0.25
Its derivative is , and . ( is the value of softplus at 0, not its slope.)
Softmax of the logits is…
and , total 4, so .
Adding the same constant to every logit changes softmax how?
- Not at all
- Every probability is multiplied by
- Every probability increases by
- The largest probability grows
: the cancels. This is exactly why subtracting the max for numerical stability is allowed.
Using and the chain rule, what is at ? (Hint: .)
- 1
- 0
- 2
. At : . Neither the power rule nor the exponential rule alone works here, because both base and exponent vary.
Code it (optional: real Python runs in your browser and is graded by test cases)
Limits and the formal derivative
Watch: Limits, L'Hôpital's rule, and epsilon delta definitions (3Blue1Brown)A limit is the value a function approaches as its input closes in on a point, whether or not the function is defined there. The derivative is one particular limit, of secant slopes. The epsilon-delta definition turns "approaches" into a precise game you can win or lose.
Since chapter 1 we've been saying "let shrink to 0 and see what the ratio settles on". The word for "what it settles on" is the limit, written
It says: you can make as close to as you like by taking close enough to (but not equal to ). What happens at doesn't matter; doesn't even need to be defined there. That's the whole point for derivatives: the difference quotient is undefined at , yet it has a limit.
Example: . At it's , meaningless. Everywhere else, factor: . So the graph is the line with a single hole at , and .
The epsilon-delta game
"As close as you like" is made precise as a challenge. Someone picks a tolerance ("get within 0.01 of "). You must respond with a distance such that every within of (except itself) gives within of . If you can answer every , however small, the limit is . If there's some you can't answer, the limit isn't .
The figure lets you play. For near 0 you can always win, so . For the sign function you lose as soon as : values just left of 0 are , just right are , and no single is close to both. The limit doesn't exist.
The derivative, formally, and where it fails
Now the definition from chapter 1 is fully precise: , if that limit exists. When it doesn't, is not differentiable at . The classic example is at 0: from the right the secant slopes are all , from the left all . The two one-sided limits disagree, so there's no derivative: the graph has a corner.
L'Hôpital's rule (optional but handy)
For a limit, zoom in: near , the top is about and the bottom about . The cancels, so if ,
whenever the right side exists. For : . It's the derivative's "locally linear" picture again.
Worked exampleDerivative of straight from the definition
The on top cancels the on the bottom; now the expression makes sense at , and the limit is . That matches the power rule from chapter 2. The pattern is always the same: simplify until the troublesome cancels, then let .
Watch outCommon misconceptions
- "The limit is just ." Only for continuous functions. The whole point is cases where is undefined (like ) or different from where the graph is heading.
- "" or "". is an indeterminate form: , , . You have to look closer.
- "If the function is continuous it's differentiable." and ReLU are continuous everywhere but have no derivative at 0.
- "L'Hôpital uses the quotient rule." No: differentiate top and bottom separately.
In ML & deep learningWhere this shows up
ReLU, , has a corner at 0 just like , so it has no derivative there. Frameworks simply pick a value (PyTorch uses 0 for ReLU's slope at exactly 0); a subgradient anywhere in would do, and inputs land exactly on 0 so rarely that it doesn't matter in practice. Limits also explain numerical tricks: and are computed with special functions (np.sinc, np.expm1) near 0, because direct evaluation hits or loses precision. And a learning rate schedule that decays to 0 is a limit statement about where training ends up.
Practice (pick one answer per question)
What is ?
- 4
- 0
- Undefined
- 2
Factor and cancel: . The function is undefined at 2, but the limit exists.
What is ?
- 1
- 0
- It doesn't exist
Near 0, (its slope at 0 is 1), so the ratio tends to 1. L'Hôpital: .
What is ?
- 3
- 1
Divide top and bottom by : .
What is ?
- 1
- 0
- It doesn't exist
It's the definition of the derivative of at 0, which is . (This limit is exactly the "constant is 1" property that defines .)
For , the one-sided limits of as and are…
- and , so doesn't exist
- both 0, so
- both 1, so
- and
For : . For : . They disagree, so there's a corner and no derivative.
For , . Given , what is the largest that works?
- 0.01
- 0.03
- 0.09
- 0.1
. We need , i.e. . A line with slope 3 triples distances, so .
Use L'Hôpital's rule (twice) to find .
- 0
- 1
- 2
First: , still . Again: . (Chapter 7 gives another view: , so .)
Code it (optional: real Python runs in your browser and is graded by test cases)
Integrals and the fundamental theorem of calculus
Watch: Integration and the fundamental theorem of calculus (3Blue1Brown) Watch: What does area have to do with slope? (3Blue1Brown)An integral adds up infinitely many thin slices: is the signed area under from to . The fundamental theorem says integrating and differentiating undo each other: the rate at which the area grows is the height of the curve. In ML, integrals are how you get probabilities and expectations from a density.
Derivatives answer "how fast is it changing?". Integrals answer the reverse: "I know the rate at every moment; how much has accumulated?". If a car's speed is , then over a tiny time it travels about . Add up all those little distances from to and you get the total distance:
Each term is a thin rectangle of height and width , so the sum is the area of a staircase that hugs the graph. As the rectangles get thinner, the staircase becomes the true area under the curve. (Area below the axis counts as negative, so it's really signed area.) The sign is a stretched S, for "sum"; the is the leftover width of each slice.
The fundamental theorem: area grows at the speed of the height
Fix the left end at and let the right end move: is the area accumulated so far. Push a tiny bit further, to . The new sliver of area is a thin strip of height about and width , so , which means
That's the fundamental theorem of calculus. It turns the hard problem (adding infinitely many slices) into an easier one: find any function whose derivative is (an antiderivative), and then
For example, has derivative , so . Every derivative rule, read backwards, is an integration rule: (for ), , (for ), . The is there because constants have zero slope; it cancels in .
Densities and expectations
A continuous random variable, like a height or a measurement error, is described by a probability density . Probabilities are areas under it: , and the total area is 1. The density itself isn't a probability (it can be bigger than 1); is the probability of landing in a thin slice. The expected value (mean) is the probability-weighted average of all values, a sum of "value × probability of the slice":
Worked exampleA triangular density
Let on (and 0 elsewhere). It's a valid density: . Then:
- . Only a quarter of the mass is in the left half, because the density leans right.
- .
- , so the variance is .
Watch outCommon misconceptions
- "Integrals are always positive areas." Regions below the axis count negatively: .
- "A density value is a probability." A uniform density on has height 2. Probabilities are areas, so only is a probability.
- "." The power rule fails at ; the answer is .
- "." It's just . The left end is fixed, so only the moving edge adds area.
In ML & deep learningWhere this shows up
Almost every loss is an expectation: the "true" objective is , an integral over the data distribution. You can't compute it exactly, so you estimate it with an average over a mini-batch, which is a Monte Carlo estimate of the integral; stochastic gradient descent uses the batch average of gradients as an estimate of the gradient of that integral. Integrals also give normalising constants (why softmax divides by a sum, and why the Gaussian has a ), the KL divergence , the evidence lower bound in VAEs, and the cumulative distribution of the Gaussian that defines the GELU activation .
Practice (pick one answer per question)
What is ?
- 2
- 4
- 1
- 0
The region is a triangle with base 2 and height 2: area . Or: .
What is ?
- 1
- 2
An antiderivative is , so .
What is ?
- 2
- 0
- 1
An antiderivative of is : . (Over it would be 0, because the second hump is below the axis.)
Let . What is ?
- 4
- 8
- 2
The fundamental theorem: , so , with no integration needed. is itself, the area, not its rate of growth.
is uniform on . What is its density's height, and what is ?
- height , mean 2
- height 1, mean 2
- height 4, mean 2
- height , mean
Total area must be 1: height × 4 = 1, so . Mean , the middle, as symmetry says.
A trapezoid rule estimate of with two strips (width 1) gives…
- 3, versus the true
- exactly
- 2, versus the true
- 4, versus the true
Strips: . The curve bends upward, so straight-line tops overestimate. True value .
For the density on , what is ?
- 1
Check it's a density: . Then . It leans right even more than , so the mean is above .
Code it (optional: real Python runs in your browser and is graded by test cases)
Higher-order derivatives and Taylor series
Watch: Higher order derivatives (3Blue1Brown) Watch: Taylor series (3Blue1Brown)The second derivative measures how the slope itself changes: curvature. Stacking derivatives lets you build a polynomial that matches a function's value, slope, curvature and more at one point; that's a Taylor polynomial. The quadratic version is the model behind Newton's method and second-order optimisation, and Taylor expansions explain many approximations used in ML.
The derivative is itself a function, so you can differentiate it again. The result, , is the second derivative: the rate of change of the slope. If is position, is velocity and is acceleration.
On a graph, is curvature (strictly, "bendiness"):
- : the slope is increasing, the graph bends upward like a bowl (convex). A flat point here is a minimum.
- : the slope is decreasing, the graph bends downward like a dome. A flat point is a maximum.
- : no bending at that point, possibly an inflection, where the bend switches direction.
That gives the second-derivative test: at a point where , the sign of tells you whether you're at the bottom of a valley or the top of a hill. You can keep going: , , and so on.
Taylor polynomials: copy the derivatives
Suppose you want a simple polynomial that imitates a complicated near . Make it agree in more and more ways:
- Same value: . (A flat line.)
- Same slope too: add . (The tangent line, chapter 1's linear approximation.)
- Same curvature too: add . The is there because , and we want the second derivative of the new term to be exactly .
In general, the term has -th derivative , so to match we need . The Taylor polynomial of degree is
Around , three famous ones (each a direct consequence of the derivative rules):
For these, adding terms forever (a Taylor series) gives the function exactly, for every . Other functions only converge in a range: works only for . Near , the error of shrinks like , so even low degrees are excellent very close to the centre.
The quadratic model and Newton's method
The degree-2 Taylor polynomial is the best "bowl" fitting at : . If , the bowl's bottom is where its derivative is zero: , so . Jumping there and repeating is Newton's method for minimisation:
Compare with gradient descent, : Newton picks the step size automatically, taking big steps where the curve is gentle and small ones where it's sharp. On a perfect quadratic it lands on the minimum in one step.
Worked exampleThe approximation inside GELU
GELU, the activation in BERT and GPT, is , where is the Gaussian CDF. has no simple formula, so the original implementations used a cheap stand-in, . Where does that come from? Taylor-expand both sides around 0. and . Plug with into and keep terms up to : you get . The terms already agree, because . Matching the terms gives . The published constant 0.044715 is almost exactly this; it was nudged slightly to reduce the error over a wide range of . The result stays within about 0.0005 of the exact GELU for every : matching a few Taylor terms buys a cheap, accurate formula.
Watch outCommon misconceptions
- " means the function is increasing." That's . means the slope is increasing: bowl-shaped. at is decreasing but has .
- "Forget the factorials." Without , the -th derivatives don't match. (that's ).
- "More terms is always better." Only inside the series' range of convergence. And a Taylor polynomial is a local model: far from , even a high-degree one can be wildly off.
- "Newton's method always finds a minimum." If it jumps to a maximum of the local model, and if it can jump very far.
In ML & deep learningWhere this shows up
Every optimiser is built on a Taylor model of the loss. Gradient descent trusts the first-order (linear) model only a little way, hence the small learning rate. Second-order methods (Newton, L-BFGS, natural gradient, Shampoo, K-FAC) use the quadratic term to choose better steps; chapter 10 does this with many weights at once. Taylor expansions also justify approximations: for small (why small log-returns add), , the GELU formula above, and the analysis of why softmax with a temperature becomes uniform ().
Practice (pick one answer per question)
For , what is ?
- 12
- 6
- 8
- 24
, , so .
At a point where and , the function has…
- a local minimum
- a local maximum
- an inflection point
- no conclusion possible
Flat and bending upward: the bottom of a bowl.
The degree-2 Taylor polynomial of around 0 is…
, , . So .
Using , estimate .
- 1.105
- 1.1
- 1.11
- 1.01
. The true value is 1.10517…; the error is about the next term, .
Minimise with one Newton step starting from . Where do you land?
- , the exact minimum
, . Newton: . Since is exactly quadratic, its Taylor model is perfect, and one step finds the minimum.
What is the coefficient of in the Taylor series of around 0?
- 0
, divided by .
Use the degree-3 Taylor polynomial of around 0 to estimate .
- about 0.09533
- 0.1
- about 0.095
- about 0.10533
. The true value is 0.0953102…, so the error is about . (0.095 stops at degree 2.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Partial derivatives and the gradient
Watch: Partial derivatives, introduction (Khan Academy, Grant Sanderson) Watch: Gradient (Khan Academy) Watch: Why the gradient is the direction of steepest ascent (Khan Academy)With several inputs, you can nudge each one separately: those slopes are the partial derivatives. Stack them into a vector and you get the gradient . It points in the direction of steepest increase, its length is that steepest slope, and it's perpendicular to the level curves. Gradient descent walks the opposite way.
A model has many weights, so its loss is a function of many variables. Start with two: , a landscape where is the height above the point . There's no single "slope" now: walking east and walking north give different slopes.
The partial derivative is the slope when you nudge only and hold fixed. Practically: treat as a constant and differentiate as usual. For :
(When differentiating in , is a constant, so it vanishes; is " times a constant".) Geometrically, slice the surface with a vertical plane ; you get an ordinary curve, and is its slope.
The gradient: all the partials in one arrow
The gradient collects the partials into a vector:
Why is this vector meaningful, and not just a list? Because of local linearity. Zoom in on a smooth surface and it looks like a tilted plane. A small step changes the height by about
That's a dot product. For a unit direction , the slope in that direction (the directional derivative) is , where is the angle between and . Three consequences fall straight out of the linear algebra module's dot product:
- Steepest ascent: is largest (1) when points along . The gradient points uphill, the steepest way.
- Its length is the steepest slope: going that way, the slope is . Going the opposite way, , the slope is : steepest descent.
- Perpendicular to level curves: along a level curve (contour line) the height doesn't change, so the slope is 0 and . The gradient is at right angles to the contour through the point.
Gradient descent
To decrease as fast as possible, step against the gradient:
Near a minimum the gradient shrinks to zero, so steps shrink too; at a minimum and you stop. Everything generalises to variables unchanged: a network with a billion weights has a gradient with a billion entries, one partial derivative per weight, and descent is the same one-line update.
Worked exampleA gradient step on a stretched bowl
. Partials: , . At : , with length , the steepest slope there. The contour through is the ellipse ; its tangent direction there is , and indeed .
One descent step with : . The height drops from 4 to . Notice moved further than : the bowl is steeper in , so the gradient points more across the valley than along it, which is why descent zig-zags on stretched bowls (chapter 10 explains this with curvature).
Watch outCommon misconceptions
- "The gradient points to the minimum." It points uphill, and only locally. Even usually doesn't point straight at the minimum (on a stretched bowl it's nearly perpendicular to the direction you need).
- "The gradient is a number." It's a vector with one entry per input, living in the input space (the floor of the landscape), not on the surface.
- "Partial derivatives ignore the other variables." They hold them fixed, but the answer usually depends on them: depends on .
- "Nudging one weight at a time is just as good." For a step of fixed length, moving along the full gradient direction changes by per unit, more than either partial alone (). Coordinates cooperate.
In ML & deep learningWhere this shows up
Training a network is gradient descent on its loss over all weights, usually stochastic (the gradient is estimated from a mini-batch). Every optimiser you'll meet modifies this one step: momentum averages recent gradients to smooth out zig-zags, Adam rescales each coordinate of the gradient by its typical size, gradient clipping caps to prevent huge jumps. The gradient with respect to the input (instead of the weights) gives saliency maps ("which pixels matter?") and adversarial examples (nudge the image along to fool the model).
Practice (pick one answer per question)
For , what is at ?
- 6
- 1
- 2
- 3
Treat as a constant: . (1 is .)
What is for at ?
. It points straight away from the origin, the uphill direction of this bowl. (5 is the height .)
At some point, . What is the slope of in the direction of the unit vector ?
- 5
- 7
- 1.4
- 0
. Since points exactly along the gradient, this is the steepest possible slope, .
At a point with , along which unit direction is the slope zero?
Zero slope means perpendicular to the gradient: . That's the direction of the level curve. is steepest descent, slope .
. One gradient-descent step from with lands at…
. . (1.2, 1.6) would be a step uphill.
For , what is at ?
- 1
- 0
- −1
. ( there.)
For a loss , at , which is true?
- , so descent increases twice as fast as
- , so both weights move equally
- , so descent decreases both weights
- , so descent increases both weights
Chain rule: , . Descent moves against this, along : gets twice the push because it has twice the influence on the error.
Code it (optional: real Python runs in your browser and is graded by test cases)
The multivariable chain rule and Jacobians
Watch: Multivariable chain rule (Khan Academy, Grant Sanderson) Watch: Jacobian prerequisite knowledge (Khan Academy) Watch: The Jacobian matrix (Khan Academy)A function from numbers to numbers, zoomed in close enough, acts like a matrix. That matrix of all partial derivatives is the Jacobian. Composing functions multiplies their Jacobians, which is the chain rule for vectors, and the reason deep learning is mostly matrix multiplication.
The multivariable chain rule: add up every path
Suppose , and both and depend on a time . Nudge by . That moves by and by , and each of those moves changes . The effects add (chapter 8's ):
Read it as: for every path from to , multiply the local derivatives along the path, then add over paths. Here there are two paths, and . That one sentence is all of backpropagation; chapter 12 simply organises the bookkeeping.
The Jacobian: the best linear approximation
Now let the output be a vector too: . Each output has a gradient, and stacking those gradients as rows gives the Jacobian matrix, rows by columns:
This is local linearity once more, in full generality: near any point, a smooth map acts like the linear transformation . Its columns say where a tiny step along each input axis gets sent, exactly like the columns of a matrix in the linear algebra module say where and land. If the map is already linear, , the Jacobian is just , everywhere. And the determinant of tells you how much the map locally scales area (that's the "Jacobian determinant" in the change-of-variables formula for integrals and probability densities).
The chain rule is matrix multiplication
If , a tiny step becomes , which becomes . So
Linear maps compose by multiplying matrices; local linear approximations compose the same way. The one-variable chain rule is the case, and the "add over paths" rule is what matrix multiplication does entry by entry (a row times a column sums over the intermediate variables).
Worked examplePolar coordinates
turns polar coordinates into Cartesian ones. Its Jacobian is
The first column (step in ) points radially outward with length 1. The second (step in ) points around the circle with length : at radius , turning by moves you a distance . So a tiny rectangle becomes a patch of area , the famous extra in polar integrals. At , .
Watch outCommon misconceptions
- "The Jacobian of is ." It's : one row per output, one column per input, so that has the shape of an output.
- "In the multivariable chain rule, just multiply." You multiply along each path and add over paths. Forgetting a path (say, a weight used in two places) gives the wrong gradient.
- " in either order." Matrix products don't commute, and the shapes usually won't even allow . The outer function's Jacobian goes on the left, evaluated at .
- "The Jacobian is only for square maps." Any has one. Only the determinant needs .
In ML & deep learningWhere this shows up
A layer is a map . Its Jacobian with respect to is : the activation's slopes scale the rows of . A deep network's input-output Jacobian is the product of these, layer after layer, and its size decides whether gradients vanish or explode. In practice, frameworks never build these big matrices. Backprop multiplies a row vector (the gradient of the scalar loss) by one Jacobian at a time from the right end: a vector-Jacobian product, which is cheap. Normalising flows and diffusion models use the Jacobian determinant to track how probability density stretches.
Practice (pick one answer per question)
A function . What shape is its Jacobian?
One row per output (2), one column per input (3).
The Jacobian of the linear map is…
- , at every point
- the identity
A linear map is its own best linear approximation: .
with and . What is at ?
- 10
- 6
- 4
- 5
Two paths: . Check directly: , .
. What is the Jacobian at ?
Row 1 is . Row 2 is . (The second option is the transpose.)
By what factor does locally scale areas near ?
- 2
- 4
- 1
- 0
. A tiny square near maps to a patch of twice its area.
and . The Jacobian of is computed as…
- , a matrix
- , a matrix
- , a matrix
Outer Jacobian on the left, evaluated at the inner output: . The third option evaluates at the wrong point (it can't even take a 4-vector).
For the elementwise map on at , the Jacobian is…
- the matrix of all ones
Output depends only on input , so off-diagonal entries are 0. ReLU's slope is 1 for positive inputs and 0 for negative ones. (The second option is the output values, not slopes.) This is why backprop through an elementwise activation is just an elementwise multiply.
Code it (optional: real Python runs in your browser and is graded by test cases)
Hessians and curvature
Watch: The Hessian matrix (Khan Academy, Grant Sanderson) Watch: Multi-variable optimization & the second derivative test (Dr. Trefor Bazett)The Hessian is the matrix of all second partial derivatives. It's symmetric, and its eigenvectors point along the directions of strongest and weakest curvature, with the eigenvalues as the curvatures. All eigenvalues positive: a bowl (minimum). All negative: a dome (maximum). Mixed signs: a saddle. The spread of the eigenvalues decides how hard gradient descent finds the problem.
In one variable, told us whether a flat point was a valley or a peak (chapter 7). With two or more variables, curvature depends on direction: a mountain pass curves up along the ridge and down along the path through it. We need all the second derivatives:
This is the Hessian. The off-diagonal entries are mixed partials: how the -slope changes as you move in . For smooth functions the two mixed partials are equal, so is symmetric. Another way to see : it's the Jacobian of the gradient. The gradient is a map from inputs to vectors, and is its local linear approximation.
The quadratic model
Chapter 7's degree-2 Taylor polynomial generalises directly. For a small step from a point :
The gradient term is the tilt; the Hessian term is the bend. The curvature along a unit direction is . Because is symmetric, the linear algebra module's spectral theorem applies: has perpendicular eigenvectors with real eigenvalues . Along , the curvature is exactly , and every other direction's curvature is a weighted average of the s. So the eigenvalues are the extreme curvatures, and at a critical point (where ):
- all ( positive definite): curves up every way, a local minimum;
- all : a local maximum;
- some positive, some negative: a saddle point;
- some : the test is inconclusive (the surface is flat in that direction, to second order).
For there's a shortcut: . If it's a saddle; if , it's a min when and a max when .
Why curvature matters for training: conditioning
Near a minimum, every loss looks like a bowl . Gradient descent on it with learning rate shrinks the component of the error along eigenvector by a factor each step. Two things follow:
- Stability: if , then and that component grows: descent diverges. So must be below .
- Speed: the flattest direction then shrinks by per step. If the condition number is large, progress along the flat direction is painfully slow while the steep direction zig-zags. That's the stretched-bowl behaviour from chapter 8.
Newton's method fixes this by stepping , which rescales every eigen-direction by its own curvature and solves a quadratic in one step. The catch: for a network with weights, has entries, far too many to store or invert, which is why deep learning uses approximations.
Worked exampleClassify the critical point of
Gradient: , which is zero only at . Hessian: . Eigenvalues: (eigenvector ) and (eigenvector ). Both positive, so is a minimum. The bowl is steepest-curving along the diagonal and gentlest along . Condition number ; gradient descent is stable for .
Compare : , , eigenvalues 5 and . A saddle: up along , down along .
Watch outCommon misconceptions
- "Positive diagonal entries mean a minimum." has a positive diagonal but is a saddle. Check the eigenvalues (or the determinant).
- "The gradient is zero, so it's a minimum." It could be a maximum or a saddle. In high dimensions, almost all critical points of a loss are saddles: you'd need every one of millions of eigenvalues to be positive.
- "The Hessian is ." That outer product only uses first derivatives (it appears in Gauss-Newton approximations). The Hessian is second derivatives.
- "A bigger learning rate is always faster." Past it diverges. The steepest direction sets the speed limit for every direction.
In ML & deep learningWhere this shows up
Practitioners never form the full Hessian, but its shape governs training. Learning-rate warm-up and the "edge of stability" phenomenon are about hovering near 2. Adam and RMSProp divide each coordinate by a running scale estimate, a crude diagonal stand-in for curvature; K-FAC and Shampoo use structured approximations of (or the closely related Fisher matrix). Batch/layer normalisation and good initialisation improve conditioning. Hessian-vector products can be computed cheaply with two passes of backprop, which powers sharpness measurements (flat minima tend to generalise better), influence functions, and second-order pruning.
Practice (pick one answer per question)
What is the Hessian of ?
, , . ( is the gradient.)
The Hessian of is , with eigenvalues and . At , has…
- a saddle point
- a minimum
- a maximum
- no critical point
Mixed signs: up along (), down along ().
What are the eigenvalues of the Hessian of ?
- 3 and 1
- 2 and 2
- 2 and 1
- 3 and −1
. Trace 4, determinant 3, so : .
Which Hessian (at a critical point) gives a maximum?
First: and , so both eigenvalues are negative. Second: , a saddle despite the negative diagonal. Third: a minimum. Fourth: mixed diagonal, a saddle.
For at the point , use the quadratic model to estimate . (, .)
- 3.64
- 3.6
- 4.4
- 3.44
. Tilt: . Bend: . Total . Because is itself quadratic, the model is exact: . (3.6 is the linear model alone, which ignores the bend.)
Gradient descent on a quadratic bowl whose Hessian has eigenvalues 6 and 2. What is the largest learning rate that doesn't diverge?
Need for every eigenvalue, i.e. . The steepest direction sets the limit.
Take one Newton step on from . Where do you land?
. , and , so and . You land at , the exact minimum, as always for a quadratic.
Code it (optional: real Python runs in your browser and is graded by test cases)
Matrix calculus for machine learning
Watch: Gradient descent, how neural networks learn (3Blue1Brown) Watch: Cross entropy derivatives and backpropagation (StatQuest)You rarely need to differentiate entry by entry. Perturb the input by a small , expand, and keep the part that's linear in : whatever multiplies is the gradient. Four results cover most of ML: , , , and for softmax with cross-entropy, .
Chapter 8 defined the gradient one partial at a time. That works, but for expressions full of vectors and matrices it's slow and error-prone. Here's the faster way, built on the local-linearity idea that runs through this whole module.
The perturbation method
For a scalar function of a vector , a small change gives . So: expand , throw away anything with two or more 's, and the vector dotted with is the gradient. The gradient always has the same shape as the thing you differentiate with respect to.
- Linear: . Then . The linear part is , so . (Each weight's partial is its input: .)
- Quadratic form: . Then . The middle two are linear in , and , so the linear part is and . For symmetric , that's , the matrix version of . Its Hessian is .
- Least squares: with residual . A change in changes by , so becomes . The linear part is , so
Read it: each data point's error pushes the weights along that point's features , and the gradient adds all those pushes. Setting it to zero gives the normal equations , the closed-form solution of linear regression.
Gradients with respect to a weight matrix
A layer computes . Suppose the loss depends on , and backprop has already found . Changing by changes by , so changes by . The coefficient of is :
And the gradient that flows back to the input is . These two lines are a dense layer's entire backward pass.
Softmax + cross-entropy:
A classifier outputs logits , turns them into probabilities , and pays for the true class . Chapter 4 rewrote this as . Differentiate each piece with respect to : the first gives if and 0 otherwise; the log-sum-exp gives . With the one-hot vector of the true class:
Predicted minus actual. The true class's logit is pushed up by (a lot if the model was unsure), and every other logit is pushed down by its own probability. Logistic regression gets the same with the sigmoid and binary cross-entropy, and linear regression's MSE gives (times 2) too: these losses were chosen to pair with their output layers this way.
Worked exampleLinear regression, by gradient and by normal equations
Fit to the points . Put a column of ones in for the intercept:
At the residual is , so the gradient is : both weights should grow. The minimum solves : . Check: the residual there, , is perpendicular to both columns of , which is exactly what "gradient = 0" says.
Watch outCommon misconceptions
- " always." Only for symmetric . In general it's .
- "." Check shapes: is , so the gradient must be . Only fits. Shape-checking catches most matrix-calculus mistakes.
- "You need the full softmax Jacobian for the backward pass." Its Jacobian is , but combined with cross-entropy everything collapses to . Frameworks fuse the two for exactly this reason (and for numerical stability).
- "The gradient with respect to is ." That's , the transpose. It must match 's shape: .
In ML & deep learningWhere this shows up
These formulas are the backward pass of the most common layers. A linear layer uses and ; with a batch, sums the outer products over examples. The classification head starts backprop with . Ridge regression and weight decay add , whose gradient shrinks weights towards zero each step. Attention's scores, layer norm and the rest are handled by the same perturbation method, which is what autodiff libraries have encoded for every operation.
Practice (pick one answer per question)
For , what is ?
The gradient of a linear function with respect to is , whatever is.
What is ?
The residual is pulled back through . Only this option has the shape of .
, . What is ?
is symmetric, so . (7 is the value .)
Logits and the true class is the first. What is for softmax + cross-entropy?
, , so . Gradient descent subtracts it: the true logit goes up, the others down. The entries sum to 0, always.
A layer computes with , and backprop gives . What is ?
: row is times . It's , the shape of . (The option is .)
(not symmetric) and . What is ?
. Check directly: , whose gradient is . The wrong formula gives .
Setting the gradient of the ridge loss to zero gives which equation?
. Adding also makes the matrix invertible even when the features are redundant.
Code it (optional: real Python runs in your browser and is graded by test cases)
Backpropagation: the chain rule on a graph
Watch: Backpropagation, intuitively (3Blue1Brown) Watch: Backpropagation calculus (3Blue1Brown) Watch: Building micrograd (Andrej Karpathy)Write the computation as a graph of tiny operations. The forward pass computes every node's value. The backward pass starts with and walks the graph in reverse, each node multiplying the incoming gradient by its own local derivative and passing it to its inputs, adding wherever paths merge. That's backpropagation, and one backward pass gives the gradient for every weight at once, for about the cost of one forward pass.
Everything in this module comes together here. A neural network's loss is a huge composition of simple operations: multiply, add, , log, and so on. We want for every weight . Chapter 9's rule says: for each path from to , multiply the local derivatives along it, and add over paths. Done naively, that's hopeless (the number of paths explodes). Backprop organises it so that every local derivative is used exactly once.
Computation graphs
Take a single neuron with two inputs and a squared-error loss:
Each line is a node in a graph, with arrows from its inputs. The forward pass evaluates the nodes in order (a topological order: every node after its inputs) and stores each value; the backward pass will need them.
The backward pass
Give every node a slot grad , sometimes called its adjoint. Set 's grad to 1. Then visit nodes in reverse topological order. When you visit a node , you know (all of 's uses are later in the graph, so they've already reported in). Push it to each input with the chain rule:
The += is the "add over paths" part: if feeds several nodes, each contributes. Only a few local rules are needed:
- Add : local derivatives are 1, so it copies its gradient to both inputs (a gradient distributor).
- Multiply : gets and gets (a swap: each input's gradient is scaled by the other input's value).
- : local derivative , using the stored output.
- Power : local derivative .
Why it's efficient: reverse mode
Backprop computes the gradient of one scalar output with respect to all inputs in a single backward sweep. In Jacobian terms (chapter 9), it multiplies a row vector by one Jacobian at a time, from the loss end: , never forming a full matrix. The total cost is a small constant times the forward pass, whether the network has ten weights or a hundred billion. (The opposite, forward mode, pushes a nudge of one input forward and gets one column of the Jacobian per pass: great for few inputs, terrible for many weights.) The price is memory: every forward value must be stored until the backward pass uses it, which is why training needs more memory than inference.
Worked exampleThe neuron, by hand
Take , target .
Forward: , , , , .
Backward:
- .
- .
- The add node copies it: .
- The multiply nodes swap: , , , .
All the weight gradients are negative, so gradient descent increases , raising and pushing up towards the target 1. And gets twice 's push because its input is twice as big.
Watch outCommon misconceptions
- "Backprop is a different thing from the chain rule." It's the chain rule, applied in a clever order that reuses shared work.
- "Set the gradient, don't add." If a value is used twice (, a weight shared across time steps, a residual connection), the contributions must be summed. Overwriting is a classic autodiff bug. (So is forgetting to reset gradients to zero before the next backward pass, which is why PyTorch has
zero_grad().) - "The backward pass is much more expensive than the forward pass." It's typically about 2 to 3 times the forward cost: each operation does a little local work, once.
- "Backprop only works for neural networks." It works for any program built from differentiable pieces: physics simulators, renderers, optimisers. That's what "differentiable programming" means.
In ML & deep learningWhere this shows up
This is literally what loss.backward() does in PyTorch (and jax.grad in JAX): during the forward pass the library records each operation and its inputs in a graph (the "tape"); backward() walks it in reverse calling each operation's local backward rule, and accumulates into every parameter's .grad. The optimiser then uses those gradients. Vanishing and exploding gradients (chapter 3) are statements about the products of local derivatives along long paths; residual connections help because an add node copies the gradient straight through. Your capstone below builds a working version of this machinery in about 50 lines.
Practice (pick one answer per question)
In the backward pass, an add node with sends what to and ?
- to each
- to each
- to and to
- to and 0 to
Both local derivatives are 1, so the add node copies the gradient. (The swap rule is for multiply.)
A multiply node with , , and . What gradient does receive?
- 15
- 5
, times 5: . ( receives .)
is computed as one multiply node with both inputs equal to . After backprop from , what is ?
- 6
- 3
- 9
- 1
is used twice; each use contributes , and they add: 6, matching . An autodiff that overwrites instead of adding would give 3.
Forward pass: , . If , what is ?
- about 1.573
- about 0.924
- 2
- about 0.786
, times 2: about 1.573. (0.786 forgets the incoming gradient; 0.924 is .)
Why does reverse mode (backprop) beat forward mode for training networks?
- One scalar loss and millions of weights: one reverse pass gives every partial derivative, while forward mode needs one pass per weight
- Reverse mode needs no stored intermediate values
- Forward mode can't handle nonlinear functions
- Reverse mode gives exact derivatives, forward mode only approximations
Reverse mode costs a few forward passes per output; forward mode costs a few per input. A loss has one output and many inputs. (Both are exact; reverse mode is the one that must store activations.)
For the neuron , you find at the sum node. With , , what are and ?
- and
- and
- and
- and
The add node copies to and ; each multiply node scales it by the other input: and .
A residual block computes . If and the Jacobian of is tiny (nearly 0), what is approximately?
- : the skip connection passes the gradient through unchanged
- nearly 0, the gradient vanishes
- times the Jacobian of
Two paths add: . The identity path keeps gradients alive through very deep networks, the key idea of ResNets and of every transformer block.
Code it (optional: real Python runs in your browser and is graded by test cases)
The capstone: a tiny autodiff engine in the spirit of Karpathy's micrograd. Then a second problem does the same backward pass with matrices for a whole two-layer network.
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
Everything from the 12 chapters, compressed. On paper, it prints on its own (figures hidden).
Derivative (ch 1, 5)
: slope, rate, sensitivity.
. Numerically: , .
Corner (e.g. , ReLU at 0): one-sided limits differ, no derivative.
Rules (ch 2, 3)
; ; .
Linear: . Product: .
Chain: : stretch factors multiply.
Exp & log (ch 4)
; ; .
; softplus.
Softmax ; subtract first. .
Integrals (ch 6)
where ; .
Density: ; .
Taylor (ch 7)
.
, ,
Newton: .
Gradient (ch 8)
; slope along unit is .
Points uphill, length = steepest slope, perpendicular to level curves.
Descent: .
Jacobian & chain rule (ch 9)
(); .
. Multiply along paths, add over paths.
= local area scale.
Hessian (ch 10)
, symmetric. .
Eigenvalues all : min; all : max; mixed: saddle.
GD stable iff ; . Newton: .
Matrix calculus (ch 11)
; .
; normal eqs .
: , . Softmax + CE: .
Backprop (ch 12)
Forward: compute and store values in topological order.
Backward: ; in reverse order, .
Add copies; multiply swaps; : . Zero grads between passes.
Glossary
- Antiderivative
- A function with . Used to evaluate integrals: . (Ch 6)
- Backpropagation
- Computing the gradient of a scalar loss with respect to every parameter by applying the chain rule backwards through a computation graph, reusing shared work. (Ch 12)
- Chain rule
- The derivative of a composition is the product of the local derivatives: ; for vectors, . (Ch 3, 9)
- Computation graph
- A program drawn as nodes (operations and values) and arrows (which values feed which operations). (Ch 12)
- Condition number
- of the Hessian at a minimum. Large means a stretched bowl where gradient descent is slow. (Ch 10)
- Critical point
- A point where the gradient is zero: a minimum, a maximum or a saddle. (Ch 8, 10)
- Cross-entropy
- The loss for the true class ; with softmax, its gradient with respect to the logits is . (Ch 4, 11)
- Derivative
- The limit of secant slopes, : the slope of the tangent line, a rate of change, a sensitivity. (Ch 1)
- Directional derivative
- The slope of along a unit direction : . (Ch 8)
- Euler's number
- About 2.71828: the base whose exponential is its own derivative. (Ch 4)
- Expected value
- The probability-weighted average . (Ch 6)
- Finite difference
- A numerical derivative such as . Used for gradient checking. (Ch 1, 5)
- Fundamental theorem of calculus
- : integration and differentiation undo each other. (Ch 6)
- Gradient
- The vector of partial derivatives, . It points in the direction of steepest ascent. (Ch 8)
- Gradient descent
- Repeatedly stepping to reduce a loss. (Ch 1, 8)
- Hessian
- The symmetric matrix of second partial derivatives; its eigenvalues are the curvatures along its eigenvectors. (Ch 10)
- Integral
- : the limit of sums of thin slices, the signed area under . (Ch 6)
- Jacobian
- The matrix of partial derivatives of a map : its best local linear approximation. (Ch 9)
- Learning rate
- The step size in gradient descent. On a quadratic it must stay below . (Ch 1, 10)
- Level curve
- A curve along which is constant (a contour line). The gradient is perpendicular to it. (Ch 8)
- Limit
- The value approaches as approaches , made precise by the epsilon-delta definition. (Ch 5)
- Log-sum-exp
- , computed stably as . Its gradient is softmax. (Ch 4)
- Natural logarithm
- , the inverse of . Its derivative is , and it turns products into sums. (Ch 4)
- Newton's method
- Minimising by jumping to the bottom of the local quadratic model: , or . (Ch 7, 10)
- Partial derivative
- The slope of when only one input is nudged and the others are held fixed, . (Ch 8)
- Power rule
- . (Ch 2)
- Probability density
- A function with total area 1; probabilities are areas under it. (Ch 6)
- Product rule
- : the two strips of a growing rectangle. (Ch 3)
- Reverse mode
- Automatic differentiation that sweeps from the output back to the inputs; gives the whole gradient of one scalar in one pass. (Ch 12)
- Saddle point
- A critical point that curves up in some directions and down in others (Hessian eigenvalues of both signs). (Ch 10)
- Sigmoid
- , squashing into , with . (Ch 3, 4)
- Softmax
- : turns logits into probabilities. (Ch 4, 11)
- Tangent line
- The line through with slope ; the curve's best straight-line approximation near . (Ch 1)
- Taylor polynomial
- The polynomial matching 's value and first derivatives at a point: . (Ch 7)
- Vanishing gradient
- A gradient that shrinks towards zero because many chain-rule factors smaller than 1 are multiplied together. (Ch 3, 12)