Textbook › Part 0 Mathematical Foundations
CHAPTER 0-2

Which Way Makes It Better — Calculus

FREE20 min

Chapter 0-1 put down "laid out in a grid, it computes." This chapter is about what happens when you move something. Every training rule is a rule for picking one direction — the direction that makes things better — and what picks it is differentiation. There are only three symbols to carry: partial derivative, gradient, Jacobian. The chain rule is how you join them, and it has exactly two cases. Where the graph is a chain you multiply; where it branches you add.

First, the vocabulary for talking about shape.

1. Sets and maps — what "shape mismatch" means

Write Rn\mathbb{R}^n for the set of all lists of nn real numbers. So x∈R784x \in \mathbb{R}^{784} reads "xx is a list of 784 reals."

Definition. A rule assigning to each element of AA exactly one element of BB is a map f:A→Bf: A \to B. AA is the domain, BB the codomain.

A layer is a map. x↦Wx+bx \mapsto Wx + b with W∈R128×784W \in \mathbb{R}^{128 \times 784} is a map R784→R128\mathbb{R}^{784} \to \mathbb{R}^{128}: it takes a list of 784 and returns a list of 128.

The composite g∘fg \circ f (through ff, then through gg) is defined only when the codomain of ff equals the domain of gg. You cannot put g:R64→R10g: \mathbb{R}^{64} \to \mathbb{R}^{10} after f:R784→R128f: \mathbb{R}^{784} \to \mathbb{R}^{128}.

The shape mismatch you meet every day is the machine saying exactly this. A shape that does not line up is not a failed computation; it is a composite that was never defined. "Inner dimensions must agree," from Chapter 0-1 equation (3), is this same condition written in the language of matrices.

2. Supremum and infimum — a minimum need not exist

One more piece of vocabulary before derivatives. Without it, "when do we stop?" in Chapter 4 has nothing to stand on.

Definition. A number that is ≥\ge every element of S⊂RS \subset \mathbb{R} is an upper bound of SS. The least upper bound is the supremum sup⁡S\sup S. Symmetrically, the greatest lower bound is the infimum inf⁡S\inf S.

A maximum max⁡S\max S must both be an upper bound and belong to SS. The supremum need not belong. That is the whole difference.

Example. S={ 1−1n:n=1,2,3,… }={0, 0.5, 0.6667, 0.75, 0.8, … }S = \{\, 1 - \tfrac{1}{n} : n = 1,2,3,\dots \,\} = \{0,\ 0.5,\ 0.6667,\ 0.75,\ 0.8,\ \dots\}. Every element is below 1, and they get arbitrarily close to it, so sup⁡S=1\sup S = 1. But 1∉S1 \notin S, so SS has no maximum.

This lands directly on loss functions. Take two points: x1=+1x_1 = +1 with label y1=1y_1 = 1, and x2=−1x_2 = -1 with label y2=0y_2 = 0, predicted by p=σ(wx)p = \sigma(wx) where σ(z)=1/(1+e−z)\sigma(z) = 1/(1+e^{-z}). The mean log loss works out to L(w)=−log⁡σ(w)L(w) = -\log\sigma(w).

ww L(w)L(w)
0.5 0.4741
1 0.3133
2 0.1269
5 6.72×10−36.72\times10^{-3}
10 4.54×10−54.54\times10^{-5}
20 2.06×10−92.06\times10^{-9}

It keeps falling. inf⁡L=0\inf L = 0, but σ(w)<1\sigma(w) < 1 always holds, so 0 is never reached: this problem has no minimiser, and the weights grow without bound. What Chapter 1 of Part III measured — scaling a line up lowers the loss while the boundary stays put — was one face of this.

Add one contradicting point and it changes. Put label y3=1y_3 = 1 on x3=−1x_3 = -1: growing ww now punishes that point, so the two pressures balance somewhere. Indeed ∂L/∂w=0\partial L/\partial w = 0 is equivalent to σ(w)=2/3\sigma(w) = 2/3, giving w=log⁡2=0.6931…w = \log 2 = 0.6931\ldots and L=0.6365L = 0.6365. The minimum sits at a finite place.

Having an infimum and having a minimum are different things. On data that can be separated, the log loss has no minimiser, so "run until the loss is minimal" is not a procedure. A stopping rule has to be added by hand (Chapter 4).
Do not read a printed 0.0 as evidence that the bound was reached. In float64, $z \ge 36.7368$ makes $\sigma(z)$ round to exactly 1.0, and $-\log\sigma(z)$ prints 0.0. The mathematical value is positive: one step below that $z$ it is $2.2 \times 10^{-16}$.

3. Partial derivatives — move exactly one

Definition. The partial derivative of f:Rn→Rf: \mathbb{R}^n \to \mathbb{R} in the ii-th variable is

∂f∂xi(x)  =  lim⁡t→0f(x1,…,xi+t,…,xn)−f(x)t\frac{\partial f}{\partial x_i}(x) \;=\; \lim_{t \to 0} \frac{f(x_1, \dots, x_i + t, \dots, x_n) - f(x)}{t}
(1)

Equation (1) does one thing: hold the others still, move one. How many times more the output moved is the partial derivative.

Worked numbers. For f(x,y)=x2y+3yf(x,y) = x^2 y + 3y we get ∂f/∂x=2xy\partial f/\partial x = 2xy and ∂f/∂y=x2+3\partial f/\partial y = x^2 + 3. At (x,y)=(2,3)(x,y) = (2,3), f=21f = 21, ∂f/∂x=12\partial f/\partial x = 12, ∂f/∂y=7\partial f/\partial y = 7.

A formula derived by hand can be checked by moving things.

∂f∂xi(x)  ≈  f(x+hei)−f(x−hei)2h\frac{\partial f}{\partial x_i}(x) \;\approx\; \frac{f(x + h e_i) - f(x - h e_i)}{2h}
(2)

Here eie_i has a 1 in slot ii and zeros elsewhere, and hh is small. Equation (2) is the central difference. Measuring the example above with h=10−5h = 10^{-5} gives 12.000000000112.0000000001 and 7.00000000007.0000000000 — at most 9.0×10−119.0 \times 10^{-11} away from the analytic values.

This check is a working tool: when you doubt a backward pass you wrote, compare it against equation (2) first. It is not for training — each parameter costs two forward passes, so 785 parameters cost 1,570 of them. It exists to verify, nothing else.

4. The gradient — stack the partials and you get the steepest direction

Definition. The gradient of f:Rn→Rf: \mathbb{R}^n \to \mathbb{R} is the vector of its partials,

∇f(x)  =  (∂f∂x1, …, ∂f∂xn)⊤∈Rn\nabla f(x) \;=\; \left( \frac{\partial f}{\partial x_1}, \ \dots, \ \frac{\partial f}{\partial x_n} \right)^{\top} \in \mathbb{R}^n
(3)

What makes the gradient special is that stacking alone already gives the steepest direction. That is provable.

How much ff moves along a unit direction uu is the derivative at t=0t=0 of the one-variable function φ(t)=f(x+tu)\varphi(t) = f(x + tu). Applying the chain rule componentwise,

Duf(x)  =  φ′(0)  =  ∑i=1n∂f∂xiui  =  ∇f(x)⊤uD_u f(x) \;=\; \varphi'(0) \;=\; \sum_{i=1}^{n} \frac{\partial f}{\partial x_i} u_i \;=\; \nabla f(x)^{\top} u
(4)

This is the directional derivative. Equation (4) is an inner product — the same shape as equation (1) of Chapter 0-1 — so ∇f⊤u=∥∇f∥ ∥u∥cos⁡θ=∥∇f∥cos⁡θ\nabla f^{\top} u = \|\nabla f\|\,\|u\|\cos\theta = \|\nabla f\|\cos\theta and therefore

−∥∇f(x)∥  ≤  Duf(x)  ≤  ∥∇f(x)∥-\|\nabla f(x)\| \;\le\; D_u f(x) \;\le\; \|\nabla f(x)\|
(5)

The right equality holds only when cos⁡θ=1\cos\theta = 1, i.e. u=∇f/∥∇f∥u = \nabla f/\|\nabla f\|. The gradient direction increases ff fastest, and its negative decreases it fastest. The ceiling on the rate of increase is ∥∇f∥\|\nabla f\| itself.

Worked numbers. At (2,3)(2,3) above, ∇f=(12,7)⊤\nabla f = (12,7)^{\top} and ∥∇f∥=193=13.8924\|\nabla f\| = \sqrt{193} = 13.8924. Rotating the direction away and measuring:

offset from the gradient directional derivative ∥∇f∥cos⁡θ\lVert\nabla f\rVert\cos\theta
0° 13.8924 13.8924
30° 12.0312 12.0312
60° 6.9462 6.9462
90° 0.0000 0.0000

Agreeing with ∥∇f∥cos⁡θ\|\nabla f\|\cos\theta to four decimals. It is 0 at 90° because that direction runs along the contour.

5. The Jacobian — the derivative of a map is a matrix

One output is served by a gradient, but a layer has 128 of them.

Definition. The Jacobian matrix of f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m is

Jf(x)  =  (∂fi∂xj)i=1,…,mj=1,…,n∈Rm×nJ_f(x) \;=\; \left( \frac{\partial f_i}{\partial x_j} \right)_{\substack{i = 1,\dots,m \\ j = 1,\dots,n}} \in \mathbb{R}^{m \times n}
(6)

The shape need not be memorised: rows count outputs, columns count inputs. With m=1m = 1 it is (1,n)(1,n) — the gradient laid on its side.

In deep learning two cases cover almost everything.

(a) A linear layer. For z=Wxz = Wx with W∈R128×784W \in \mathbb{R}^{128 \times 784}, ∂zi/∂xj=Wij\partial z_i/\partial x_j = W_{ij}, so J=WJ = W. The weights are the Jacobian.

(b) An elementwise activation. If a=φ(z)a = \varphi(z) applies componentwise, ai=φ(zi)a_i = \varphi(z_i), then ∂ai/∂zj=0\partial a_i/\partial z_j = 0 whenever i≠ji \neq j, so

J=diag(φ′(z1),…,φ′(z128))J = \mathrm{diag}\big(\varphi'(z_1), \dots, \varphi'(z_{128})\big)

a diagonal matrix. This decides the shape of the code. Multiplying by a diagonal matrix is the same as multiplying elementwise, which is why the equations in Chapter 3 carry a Hadamard product ∘\circ (Chapter 0-1, equation (4)) instead of a matrix product. The storage differs too: as a (128,128)(128,128) matrix it is 16,38416{,}384 numbers; as a diagonal, 128128 — a factor of 128.

(c) A general example. For g(x,y)=(x2, x+y)g(x,y) = (x^2,\ x+y),

Jg=(2x011),Jg(2,3)=(4011)J_g = \begin{pmatrix} 2x & 0 \\ 1 & 1 \end{pmatrix}, \qquad J_g(2,3) = \begin{pmatrix} 4 & 0 \\ 1 & 1 \end{pmatrix}

Measuring all four entries with the central difference of equation (2), the largest gap was 3.8×10−113.8 \times 10^{-11}.

6. The chain rule — multiply along a chain, add across a branch

In one variable, (h∘g)′(x)=h′(g(x)) g′(x)(h \circ g)'(x) = h'(g(x))\, g'(x): a product of local slopes. For maps the shape is identical, with the product becoming a matrix product.

Jf∘g(x)  =  Jf(g(x))  Jg(x)J_{f \circ g}(x) \;=\; J_f\big(g(x)\big)\; J_g(x)
(7)

Check the shapes in equation (7). With g:Rn→Rkg: \mathbb{R}^n \to \mathbb{R}^k and f:Rk→Rmf: \mathbb{R}^k \to \mathbb{R}^m, the right side is (m,k)×(k,n)→(m,n)(m,k) \times (k,n) \to (m,n); the left is the derivative of a map Rn→Rm\mathbb{R}^n \to \mathbb{R}^m, so (m,n)(m,n). They agree — because the condition for a composite to exist (section 1) and the condition for a matrix product to exist (Chapter 0-1, equation (3)) were the same condition all along.

Written in components, you can see where the addition comes from.

∂(f∘g)i∂xj  =  ∑p=1k∂fi∂up⋅∂gp∂xj\frac{\partial (f \circ g)_i}{\partial x_j} \;=\; \sum_{p=1}^{k} \frac{\partial f_i}{\partial u_p} \cdot \frac{\partial g_p}{\partial x_j}
(8)

The sum in equation (8) is a sum over paths. There are kk routes from xjx_j to (f∘g)i(f\circ g)_i, one per intermediate upu_p. Multiply the local slopes along each route, then add the routes up. Chain: multiply. Branch: add. That is the entire rule.

FIG 1On the "chain" side, the tangents of g and h (the local slopes) are multiplied and compared with the tangent of the composite — the product matches the measured slope for every pair and every x. On the "branch" side the two routes from x to y are added. Drop one route and the total parts company with the measurement, which is exactly what a forgotten branch does in code

Numerical check. Put f(u,v)=uvf(u,v) = uv after g(x,y)=(x2, x+y)g(x,y) = (x^2,\ x+y); the composite is h(x,y)=x2(x+y)h(x,y) = x^2(x+y). At (2,3)(2,3),

Jf=(v, u)=(5, 4),JfJg=(5, 4)(4011)=(24, 4)J_f = (v,\ u) = (5,\ 4), \qquad J_f J_g = (5,\ 4)\begin{pmatrix} 4 & 0 \\ 1 & 1 \end{pmatrix} = (24,\ 4)

Differentiating directly: ∂h/∂x=3x2+2xy=24\partial h/\partial x = 3x^2 + 2xy = 24 and ∂h/∂y=x2=4\partial h/\partial y = x^2 = 4. They match, and the gap against the central difference was 1.5×10−101.5\times10^{-10}.

The order you multiply in sets the cost

Chain equation (7) across the layers and you get a run of matrix products. The order is yours to choose (matrix products are associative) — and the choice is worth a factor of ten.

Take three stages going from the loss (one output) back toward the input: J1∈R1×10J_1 \in \mathbb{R}^{1 \times 10}, J2∈R10×128J_2 \in \mathbb{R}^{10 \times 128}, J3∈R128×784J_3 \in \mathbb{R}^{128 \times 784}.

order multiplications
from the left, ((J1J2)J3)((J_1 J_2) J_3) 1,280+100,352=101,6321{,}280 + 100{,}352 = 101{,}632
from the right, (J1(J2J3))(J_1 (J_2 J_3)) 1,003,520+7,840=1,011,3601{,}003{,}520 + 7{,}840 = 1{,}011{,}360

9.95 times. Multiplying from the left, what sits in your hands is always a row vector; a (128,784)(128,784) matrix is never formed. Multiplying from the right, it is.

Backpropagation is not a new rule. It is equation (7) multiplied from the left. When there is one output (the loss) and millions of inputs, left-to-right is the cheap order — that, and nothing else, is why it runs "backwards." Chapter 3 opens it up.

A common misreading: "follow the gradient and you take the shortest path to the valley"

Section 4 proved "steepest at this point." Nothing there says anything about the length of the journey. Measure it and the difference shows up plainly.

Take f(x,y)=(x2+10y2)/2f(x,y) = (x^2 + 10y^2)/2, whose valley floor is the origin, and descend from (10,1)(10,1) with η=0.18\eta = 0.18.

value
straight-line distance to the origin 10.0499
length of the path actually travelled 13.4655 (1.34×)
angle between the first step and the direction to the floor 39.29°
steps to get within radius 0.01 of the origin 35

The path is 1.34× long because of the sign of the yy component. The first six values are −0.8000-0.8000, +0.6400+0.6400, −0.5120-0.5120, +0.4096+0.4096, −0.3277-0.3277, +0.2621+0.2621 — it crosses over on every step. Curvature along yy is ten times tighter, so a step sized for xx must overshoot in yy. It zigzags across the valley while creeping toward the centre.

Line the curvature up across axes and the gap disappears. From the same start, f(x,y)=(x2+y2)/2f(x,y) = (x^2+y^2)/2 gives a path length of 10.0402 — the straight-line 10.0499 minus the 0.01 radius where we stopped. Same 35 steps. What created the detour was not the gradient but the difference in curvature between axes.

The gradient points out a direction and says nothing about distance. The step size (learning rate) is a separate decision, and where axes curve differently no single step size suits them all. That is what momentum and Adam are for (Chapter 4).

Exercises

The answers are folded away. Work them first.

Exercise 1. Let W∈R128×784W \in \mathbb{R}^{128 \times 784}, z=Wxz = Wx, and a=tanh⁡(z)a = \tanh(z) componentwise. (a) Shape and contents of the Jacobian of x↦zx \mapsto z. (b) Shape and contents for z↦az \mapsto a. (c) Shape for x↦ax \mapsto a. (d) Why does the code never hold (b) as a matrix?

Show the answer

(a) (128,784)(128, 784), and it is WW itself, since ∂zi/∂xj=Wij\partial z_i/\partial x_j = W_{ij}.

(b) A (128,128)(128,128) diagonal matrix. For i≠ji \neq j, aia_i does not involve zjz_j, so the entry is 0. The diagonal entries are 1−tanh⁡2(zi)1 - \tanh^2(z_i).

(c) (128,784)(128, 784). By equation (7), J=diag(1−tanh⁡2z) WJ = \mathrm{diag}(1-\tanh^2 z)\, W, and (128,128)×(128,784)→(128,784)(128,128) \times (128,784) \to (128,784).

(d) Because it means storing 16,25616{,}256 zeros. Of the 1282=16,384128^2 = 16{,}384 entries only the 128 on the diagonal mean anything. Multiplying by a diagonal matrix equals multiplying elementwise, so the code keeps one (128,)(128,) vector and uses a Hadamard product. The ∘\circ in Chapter 3's equations is this diagonality restated.

Exercise 2. Consider S={ −log⁡σ(z):z∈R }S = \{\, -\log\sigma(z) : z \in \mathbb{R} \,\}. (a) What is inf⁡S\inf S, and does it belong to SS? (b) Is SS bounded above? (c) How does the answer to (a) look in float64?

Show the answer

(a) inf⁡S=0\inf S = 0, and it does not belong. σ(z)∈(0,1)\sigma(z) \in (0,1) for every real zz, so −log⁡σ(z)>0-\log\sigma(z) > 0; meanwhile σ(z)→1\sigma(z) \to 1 as z→∞z \to \infty, so the values come arbitrarily close to 0. An infimum without a minimum — the same shape as {1−1/n}\{1-1/n\} in the text.

(b) No. As z→−∞z \to -\infty, σ(z)→0\sigma(z) \to 0 and −log⁡σ(z)→+∞-\log\sigma(z) \to +\infty, so sup⁡S=+∞\sup S = +\infty. This is why missing one point confidently costs without limit — the same thing as paying −log⁡0.05=2.9957-\log 0.05 = 2.9957 in Exercise 3 of Chapter 1 (Part III).

(c) It prints 0.0, because σ(z)\sigma(z) rounds to exactly 1.0 once z≥36.7368z \ge 36.7368. The mathematical value is positive; one step below that zz it is 2.2×10−162.2\times10^{-16}. A screen reading "loss 0" is not evidence that the bound was attained.

Exercise 3. Split y=(x+1)x2y = (x+1)x^2 into the two routes u=x+1u = x+1 and v=x2v = x^2. At x=2x = 2: (a) the product along each route and their sum; (b) the value by direct differentiation; (c) what do you get counting only the upper route, and what has gone wrong?

Show the answer

(a) u=3u = 3, v=4v = 4. With ∂y/∂u=v=4\partial y/\partial u = v = 4 and du/dx=1du/dx = 1, the upper route is 4×1=44 \times 1 = 4. With ∂y/∂v=u=3\partial y/\partial v = u = 3 and dv/dx=2x=4dv/dx = 2x = 4, the lower route is 3×4=123 \times 4 = 12. The sum is 16.

(b) y=x3+x2y = x^3 + x^2, so dy/dx=3x2+2x=12+4=16dy/dx = 3x^2 + 2x = 12 + 4 = 16. They match (the central difference gives 16.00000000116.000000001).

(c) You get 4, one quarter of the right answer. xx enters both uu and vv, so moving xx moves both at once. Counting one route asserts that "vv does not move" — a different premise, not a smaller calculation.

The same shape appears in code. A residual connection y=x+F(x)y = x + F(x) has two routes from xx to yy, so dy/dx=1+F′(x)dy/dx = 1 + F'(x). With F(x)=tanh⁡(0.8x)F(x) = \tanh(0.8x) at x=0.6x = 0.6, F′(x)=0.6407F'(x) = 0.6407 and dy/dx=1.6407dy/dx = 1.6407. Counting only the FF side gives 0.64070.6407 — below 1, so stacking thins the signal. The "1" contributed by the identity route is what keeps it from thinning.

What this chapter does not say

  • Points where the derivative does not exist are left out. ReLU has no slope at z=0z=0. Implementations pick one subgradient (usually 0) and move on; that choice is not justified here.
  • Second derivatives (the Hessian) are not used. We measured that differing curvature makes training harder, but handling curvature itself as a matrix (second-order methods) is only touched on in Chapter 4.
  • The rigorous (ε\varepsilon-δ\delta) definitions of limit and continuity are not laid down. Supremum and infimum were brought in for one purpose: to say that a minimum need not exist.
  • How automatic differentiation is implemented — what the graph holds and how much memory it costs — is Chapter 3. This chapter is only the rule.
  • Every number in the text was computed and checked (central-difference agreement for the partials and the Jacobian, the directional derivative against ∥∇f∥cos⁡θ\|\nabla f\|\cos\theta, JfJgJ_fJ_g against direct differentiation, the w=log⁡2w = \log 2 minimum, the descent path length and step count, and the float64 rounding threshold).

Going deeper

Comments

Sign in to comment