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.

Builds onModule 1·
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.

Open in Colab
4 Hours·Core·Foundational·0/6

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 f′(x)f'(x) or dfdx\frac{df}{dx} is the slope of ff at xx: how much f(x)f(x) changes per unit change in xx, 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:

f′(x)=lim⁡h→0f(x+h)−f(x)hf'(x) = \lim_{h \to 0} \frac{f(x + h) - f(x)}{h}

In practice you combine a few known slopes with a few rules.

functionderivativewhere it appears
xnx^nnxn−1n x^{n-1}squared errors, variances
exe^xexe^xsoftmax (section 4.3)
1/x1/xthe log in every loss
tanh⁡x\tanh x1−tanh⁡2x1 - \tanh^2 xrecurrent networks (section 5.2), soft-capping (section 16.5)
max⁡(0,x)\max(0, x) (ReLU)11 for x>0x > 0, 00 for x<0x < 0feed-forward layers (section 7.4)

The rules that combine them:

  • Sum rule. The slope of f+gf + g is f′+g′f' + g'.
  • Constant factor. The slope of cfc f is cf′c f'.
  • Product rule. The slope of fgf g is f′g+fg′f' g + f g'.
  • Quotient rule. The slope of f/gf / g is f′g−fg′g2\frac{f' g - f g'}{g^2}.

Worked example. Take f(x)=x2exf(x) = x^2 e^x. The product rule with x2x^2 and exe^x gives f′(x)=2x⋅ex+x2⋅ex=(2x+x2)exf'(x) = 2x \cdot e^x + x^2 \cdot e^x = (2x + x^2)e^x. At x=1x = 1 the slope is : nudging xx up by 0.0010.001 raises ff by about 0.008150.00815.

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 f′(x) Δxf'(x)\,\Delta x. 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 :

∇θL=[∂L∂θ1, ∂L∂θ2, …, ∂L∂θn]\nabla_\theta \mathcal{L} = \left[\frac{\partial \mathcal{L}}{\partial \theta_1}, \, \frac{\partial \mathcal{L}}{\partial \theta_2}, \, \dots, \, \frac{\partial \mathcal{L}}{\partial \theta_n}\right]

Worked example. For L(a,b)=a2b+3b\mathcal{L}(a, b) = a^2 b + 3b, holding bb fixed gives ∂L/∂a=2ab\partial \mathcal{L}/\partial a = 2ab, and holding aa fixed gives ∂L/∂b=a2+3\partial \mathcal{L}/\partial b = a^2 + 3. At a=1,b=2a = 1, b = 2 the gradient is [4,4][4, 4].

The gradient has the same shape as θ\theta. 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 y=g(x)y = g(x) and z=f(y)z = f(y), then

dzdx=dzdy⋅dydx\frac{dz}{dx} = \frac{dz}{dy} \cdot \frac{dy}{dx}

Each link's slope is taken at the point the chain actually passes through.

Worked example. Let z=tanh⁡(3x)z = \tanh(3x). The inner link is y=3xy = 3x, with slope 33. The outer link is z=tanh⁡yz = \tanh y, with slope 1−tanh⁡2y1 - \tanh^2 y. So dzdx=(1−tanh⁡2(3x))⋅3\frac{dz}{dx} = (1 - \tanh^2(3x)) \cdot 3. At x=0x = 0 that is 33; at x=1x = 1, tanh⁡3≈0.995\tanh 3 \approx 0.995 and the slope has collapsed to about 0.030.03.

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 x\mathbf{x} of length nn and y\mathbf{y} of length mm:

J=∂y∂x=[∂y1∂x1⋯∂y1∂xn⋮⋱⋮∂ym∂x1⋯∂ym∂xn]J = \frac{\partial \mathbf{y}}{\partial \mathbf{x}} = \begin{bmatrix} \frac{\partial y_1}{\partial x_1} & \cdots & \frac{\partial y_1}{\partial x_n} \\ \vdots & \ddots & \vdots \\ \frac{\partial y_m}{\partial x_1} & \cdots & \frac{\partial y_m}{\partial x_n} \end{bmatrix}

Row ii says how output ii 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 y=xW\mathbf{y} = \mathbf{x}W, output jj is , so ∂yj/∂xi=Wij\partial y_j / \partial x_i = W_{ij}: the Jacobian is .
  • For a function applied entry by entry, such as tanh⁡\tanh or ReLU, output ii depends only on input ii, so the Jacobian is diagonal: diag⁡(1−tanh⁡2x1,…,1−tanh⁡2xn)\operatorname{diag}(1 - \tanh^2 x_1, \dots, 1 - \tanh^2 x_n).

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:

θ⟵θ−η ∇θL\theta \longleftarrow \theta - \eta \, \nabla_\theta \mathcal{L}

The arrow means "replace θ\theta with". The step size η\eta (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.

Figure 2.4
Gradient descent and the learning rate

The loss here is L(θ) = θ². Each step moves θ against the slope by η times the gradient. Try the four learning rates.

One weight, so the loss is a curve. With millions of weights the same rule runs along every axis at once, and the steepest axis sets the largest safe η.
Predict, then try

The loss is θ2\theta^2, whose slope is 2θ2\theta, so each step multiplies θ\theta by 1−2η1 - 2\eta. Before you try it, work out the largest learning rate for which θ\theta 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 ∂L/∂y\partial \mathcal{L} / \partial \mathbf{y}, 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 y=xW\mathbf{y} = \mathbf{x} W:

∂L∂W=x⊤∂L∂y,∂L∂x=∂L∂yW⊤\frac{\partial \mathcal{L}}{\partial W} = \mathbf{x}^\top \frac{\partial \mathcal{L}}{\partial \mathbf{y}}, \quad \frac{\partial \mathcal{L}}{\partial \mathbf{x}} = \frac{\partial \mathcal{L}}{\partial \mathbf{y}} W^\top

The second formula is the chain rule with the Jacobian W⊤W^\top from section 2.3. The first is an outer product (section 1.3): the weight WijW_{ij} connects input ii to output jj, so its gradient is "how big input ii was" times "how much the loss cares about output jj".

Worked example. Take one input x=2x = 2, a weight w=0.5w = 0.5, y=wx=1y = wx = 1, then a=tanh⁡(y)≈0.762a = \tanh(y) \approx 0.762, and the loss L=(a−1)2≈0.0567\mathcal{L} = (a - 1)^2 \approx 0.0567. Go backward:

  1. ∂L/∂a=2(a−1)≈−0.477\partial \mathcal{L}/\partial a = 2(a - 1) \approx -0.477.
  2. ∂L/∂y=−0.477⋅(1−a2)≈−0.477⋅0.420≈−0.200\partial \mathcal{L}/\partial y = -0.477 \cdot (1 - a^2) \approx -0.477 \cdot 0.420 \approx -0.200.
  3. ∂L/∂w=−0.200⋅x≈−0.401\partial \mathcal{L}/\partial w = -0.200 \cdot x \approx -0.401, and ∂L/∂x=−0.200⋅w≈−0.100\partial \mathcal{L}/\partial x = -0.200 \cdot w \approx -0.100.

The negative gradient for ww says that raising ww lowers the loss, which makes sense: a larger ww pushes aa toward 1.

Figure 2.5
Backpropagation walks the chain rule from the loss to the inputs

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.

Every backward step multiplies by the slope of one operation, evaluated at the forward value. A flat tanh (large |y|) puts a near-zero factor in the chain.
Predict, then try

In the figure, set xx to 44. Before stepping backward, guess whether the gradient reaching ww gets larger or smaller than at x=2x = 2.

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.

Browser lab

Backpropagation agrees with finite differences

For a small tanh network (2 → 6 → 6 → 2) on 16 points, compute every weight’s gradient twice: by backpropagation (section 2.5), and numerically, by nudging the weight up and down by 0.00001 and measuring the change in loss. If the chain rule is applied correctly, the two agree to many digits for every weight.

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 0.90.9 give 0.950≈0.0050.9^{50} \approx 0.005. 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 1.11.1 give about 117117. The steps become huge and training blows up. This is an exploding gradient.

Flat regions produce the small factors, like the saturated tanh⁡\tanh 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

Check

In one sentence, what does the derivative f′(x)=5f'(x) = 5 tell you about ff near xx?

Apply

Using the quotient rule, differentiate p=eaea+ebp = \dfrac{e^{a}}{e^{a} + e^{b}} with respect to aa, and simplify the result in terms of pp.

Apply

For L(a,b)=(ab−1)2\mathcal{L}(a, b) = (ab - 1)^2, compute ∂L/∂a\partial \mathcal{L} / \partial a at a=2a = 2, b=1b = 1.

Apply

Backpropagate through y=tanh⁡(wx)y = \tanh(wx) with loss L=y\mathcal{L} = y, at x=1x = 1, w=0w = 0. What is ∂L/∂w\partial \mathcal{L}/\partial w?

Apply

Gradient descent on the loss θ2\theta^2 multiplies θ\theta by (1−2η)(1 - 2\eta) each step. Above what learning rate does it diverge?

Apply

A chain multiplies 30 factors of 0.80.8. What is the product, to three decimal places?

Extend

Write the Jacobian of y=ReLU⁡(x)\mathbf{y} = \operatorname{ReLU}(\mathbf{x}) for x=[2,−1,0.5]\mathbf{x} = [2, -1, 0.5]. 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.