Module 02 · Part I · Foundations
Calculus and Optimization
Derivatives, Partial Derivatives and Gradients, the Chain Rule and the Jacobian, Gradient Descent, and Backpropagation
By the end you can compute gradients through a small computation graph by hand, and explain why a learning rate can be too large.
Check yourself ▸
Before you start, can you already…
- ☐read any shape in the course, multiply matrices by hand, and explain what a projection keeps and throws away. (Module 1)
If any is shaky, the linked module teaches it.
A model learns by nudging its numbers so that its mistakes shrink. To know which way to nudge each one, it needs the derivative: how much an output changes when an input is nudged. This module builds from derivatives to the two algorithms that train every model in the course: gradient descent, which takes the steps, and backpropagation, which finds the direction of every step at once.
If you have taken a first calculus course, sections 2.1 and 2.2 are revision.
2.1 Derivatives: Slopes and the Rules for Finding ThemRun this section
The derivative or is the slope of at : how much changes per unit change in , for a change small enough that the curve looks straight. Formally it is the limit of "rise over run" as the run shrinks to zero:
In practice you combine a few known slopes with a few rules.
| function | derivative | where it appears |
|---|---|---|
| squared errors, variances | ||
| softmax (section 4.3) | ||
| the log in every loss | ||
| recurrent networks (section 5.2), soft-capping (section 16.5) | ||
| (ReLU) | for , for | feed-forward layers (section 7.4) |
The rules that combine them:
- Sum rule. The slope of is .
- Constant factor. The slope of is .
- Product rule. The slope of is .
- Quotient rule. The slope of is .
Worked example. Take . The product rule with and gives . At the slope is : nudging up by raises by about .
That last sentence is the whole use of a derivative in this course. A derivative is a prediction: change the input by a small , and the output changes by about . Training uses it to choose which way to move every number in the model.
2.2 Partial Derivatives and the Gradient
A model's loss is one number measuring its mistakes, and it depends on millions of weights, written as one long vector . The is the slope with respect to one weight, treating every other weight as a constant. One partial derivative per weight gives the :
Worked example. For , holding fixed gives , and holding fixed gives . At the gradient is .
The gradient has the same shape as . It points where the loss rises fastest, and its length says how steeply. The opposite direction lowers the loss fastest.
2.3 The Chain Rule and the JacobianRun this section
Models feed one function into the next. The chain rule: the slope of a chain is the product of the slopes of its links. If and , then
Each link's slope is taken at the point the chain actually passes through.
Worked example. Let . The inner link is , with slope . The outer link is , with slope . So . At that is ; at , and the slope has collapsed to about .
This is the danger the module ends on: one link with a tiny slope makes the whole chain's slope tiny.
Vectors In, Vectors Out: The Jacobian
Most links take a vector and return a vector, so every output entry has a slope with respect to every input entry. The table of these slopes is the Jacobian. For with of length and of length :
Row says how output responds to each input. The chain rule keeps its form: the Jacobian of a chain is the matrix product of the links' Jacobians.
Two Jacobians are worth knowing by heart:
- For a linear map , output is , so : the Jacobian is .
- For a function applied entry by entry, such as or ReLU, output depends only on input , so the Jacobian is diagonal: .
Section 4.3 works out a Jacobian that is not diagonal, the softmax's, and uses it to explain why attention divides its scores by a constant.
2.4 Gradient DescentRun this section
To reduce the loss, step a little in the direction opposite to the gradient:
The arrow means "replace with". The step size (the Greek letter eta) is the learning rate. Too small and training crawls; too large and each step overshoots, so the loss bounces or blows up.
Computing the loss over the whole training set for every step would be far too slow, so each step uses a small random of examples, whose gradient is noisy but right on average (Module 3 makes this precise). This is stochastic gradient descent (SGD). Section 10.2 covers AdamW, the variant that trains almost every large model.
The loss here is L(θ) = θ². Each step moves θ against the slope by η times the gradient. Try the four learning rates.
The loss is , whose slope is , so each step multiplies by . Before you try it, work out the largest learning rate for which still shrinks toward zero.
In words. The figure runs gradient descent on theta squared from theta equal to 1.6. With eta equal to 0.1 it creeps toward zero; with 0.4 it arrives in a few steps; with 0.9 it zig-zags but settles; with 1.1 every step lands further out and the loss grows without limit.
2.5 BackpropagationRun this section
Backpropagation (Rumelhart, Hinton & Williams, 1986) applies the chain rule from the loss backward, one operation at a time, over a computation graph: one node per operation, recorded as the forward pass (input to loss) runs.
Each operation receives , the gradient with respect to its output, and produces two things: the gradient for its own weights, and the gradient with respect to its input, passed to the operation below. For a linear layer :
The second formula is the chain rule with the Jacobian from section 2.3. The first is an outer product (section 1.3): the weight connects input to output , so its gradient is "how big input was" times "how much the loss cares about output ".
Worked example. Take one input , a weight , , then , and the loss . Go backward:
- .
- .
- , and .
The negative gradient for says that raising lowers the loss, which makes sense: a larger pushes toward 1.
The forward values sit inside each node. Step backward to multiply in one local slope at a time; the number under a node is ∂L with respect to it.
In the figure, set to . Before stepping backward, guess whether the gradient reaching gets larger or smaller than at .
In words. The figure draws the example as a chain: x and w feed a multiply, then tanh, then a squared error. Each step moves the gradient one node backward, multiplying by that node's local slope, and labels the edge with the running value. The inputs are editable.
Backpropagation visits each operation once forward and once back, so every gradient costs only about twice the loss, however many weights there are. It needs the forward values, which is why training stores activations and uses far more memory than running a model (section 11.1). In PyTorch, loss.backward() runs the backward pass for every weight.
Backpropagation agrees with finite differences
This is the standard way to test a hand-written backward pass. A relative error near 1e-7 or below means agreement; something near 1 means a bug.
2.6 What Goes Wrong in Long ChainsRun this section
Backpropagation multiplies one local slope per operation. A deep network, or one that runs over many time steps, makes a long product, and long products behave badly:
- If the typical factor is a little below 1, the product shrinks exponentially. Fifty factors of give . The weights at the start of the chain receive almost no gradient and stop learning. This is a vanishing gradient.
- If the typical factor is a little above 1, the product grows exponentially. Fifty factors of give about . The steps become huge and training blows up. This is an exploding gradient.
Flat regions produce the small factors, like the saturated of section 2.3, or a softmax pushed to a near one-hot output (section 4.3).
Much of a transformer's design keeps this product well behaved: residual connections give the gradient a path with no multiplications (section 7.2), normalization keeps values in range (section 7.3), and attention scales its scores (section 6.3). Module 5 shows the problem at its worst, in the recurrent networks that came before transformers.
Exercises
In one sentence, what does the derivative tell you about near ?
Using the quotient rule, differentiate with respect to , and simplify the result in terms of .
For , compute at , .
Backpropagate through with loss , at , . What is ?
Gradient descent on the loss multiplies by each step. Above what learning rate does it diverge?
A chain multiplies 30 factors of . What is the product, to three decimal places?
Write the Jacobian of for . What does it do to a gradient passed backward through it?
Core Academic References
- Rumelhart, Hinton & Williams (1986): Learning representations by back-propagating errors. Nature, 323: 533–536.
- Goodfellow, Bengio & Courville (2016): Deep Learning, chapters 4 and 6. MIT Press.
- Baydin et al. (2018): Automatic Differentiation in Machine Learning: a Survey. JMLR 18(153): 1–43.