Calculus

Dive into Deep Learning · §1.4

Differential Calculus: Derivatives, Gradients, Jacobians, and the Chain Rule
local linear approximations · tangent slopes · steepest descent · computation DAGs · finite-difference limits

Why Calculus Drives Learning: The Compass of Optimization

Motivation

  • Smooth surrogates replace flat 0–1 accuracy: Step-function error has zero slope almost everywhere; smooth losses (cross-entropy, MSE) provide a local tangent f(x+h) \approx f(x) + f'(x)h.
  • One gradient vs. d+1 blind probes: Perturbing d = 10^9 weights one-by-one takes 10^9 forward passes, whereas \nabla_{\mathbf{w}}\mathcal{L} points uphill across all d coordinates in one backward pass.

From Secant Slopes to the Derivative

Single-Variable Calculus

  • The derivative f'(x) is the instantaneous rate of change—the limit of the secant slope between (x, f(x)) and (x+h, f(x+h)) as h \to 0: f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}
  • On L(w) = 3w^2 - 4w + 2 at w = 1, expanding L(1+h) = 1 + 2h + 3h^2 gives \frac{L(1+h)-L(1)}{h} = 2 + 3h \to 2:
for h in 10.0 ** -np.arange(1, 6):
    print(f'h = {h:.0e}   ratio = {(loss(1 + h) - loss(1)) / h:.5f}')
h = 1e-01   ratio = 2.30000
h = 1e-02   ratio = 2.03000
h = 1e-03   ratio = 2.00300
h = 1e-04   ratio = 2.00030
h = 1e-05   ratio = 2.00003

Visualizing the Tangent Line as a Local Linear Approximation

Local Linearity

  • First-order Taylor expansion around a: f(x) \approx f(a) + f'(a)(x - a) At w = 1 (L(1) = 1, L'(1) = 2), the tangent line is T(w) = 1 + 2(w - 1) = 2w - 1.
  • Why local linearity justifies gradient descent: For a small step \Delta w = -\eta L'(w) with learning rate \eta > 0: L\big(w - \eta L'(w)\big) \approx L(w) - \eta \big[L'(w)\big]^2 < L(w)
  • Stepping from w = 1 with \eta = 0.1 gives w = 1 - 0.1(2) = 0.8, lowering L from 1.0 to 0.72 (tangent prediction: 0.60). Setting L'(w^*) = 6w^* - 4 = 0 locates the global minimum w^* = 2/3.

Elementary Differentiation Rules and the Product Rule

Analytical Differentiation

Function Derivative \frac{d}{dx} Rule Formula
Constant C 0 Linearity (\alpha u + \beta v)' = \alpha u' + \beta v'
Power x^n n x^{n-1} Product (u\,v)' = u'v + u\,v'
Exp e^x e^x Quotient (u/v)' = (u'v - u\,v')/v^2
Log \ln x 1/x 3w^2 - 4w + 2 3(2w) - 4(1) = 6w - 4
  • Product rule geometry: Expanding a rectangle f(x)g(x) by h adds two strips g(x)f'(x)h + f(x)g'(x)h plus an O(h^2) corner that vanishes as h \to 0.

Partial Derivatives: Slicing a Multivariate Surface

Multivariate Calculus

  • For f: \mathbb{R}^n \to \mathbb{R}, the partial derivative \frac{\partial f}{\partial x_i} holds all coordinates fixed except x_i, measuring the slope of a 1D slice: \frac{\partial f}{\partial x_i} = \lim_{h \to 0} \frac{f(x_1, \ldots, x_i + h, \ldots, x_n) - f(x_1, \ldots, x_n)}{h}
  • On our line loss L(w_1, w_2) = \|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2 at \mathbf{w} = (1, 0), slicing gives L(w_1, 0) = 3w_1^2 - 4w_1 + 2 and L(1, w_2) = 5w_2^2 + 4w_2 + 1, so \frac{\partial L}{\partial w_1} = 2 and \frac{\partial L}{\partial w_2} = 4:
w = np.array([1.0, 0.0])
numerical_gradient(line_loss, w)
array([2.000003, 4.000005])
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The Gradient Vector: Steepest Ascent, Descent, and Level Curves

Gradient Geometry

  • Stacking all n partial derivatives forms the gradient \nabla_{\mathbf{x}} f(\mathbf{x}) = \big[\frac{\partial f}{\partial x_1}, \ldots, \frac{\partial f}{\partial x_n}\big]^\top \in \mathbb{R}^n.
  • By Cauchy–Schwarz, the directional rate of change along unit vector \mathbf{u} at angle \theta to \nabla f(\mathbf{x}) is D_{\mathbf{u}} f(\mathbf{x}) = \nabla f(\mathbf{x})^\top \mathbf{u} = \|\nabla f(\mathbf{x})\|_2 \cos\theta:
    • Steepest ascent (\theta = 0^\circ): \nabla f(\mathbf{x}) points directly uphill.
    • Steepest descent (\theta = 180^\circ): -\nabla f(\mathbf{x}) points directly downhill.
    • Orthogonal to level curves (\theta = 90^\circ): D_{\mathbf{u}} f = 0 along contours f(\mathbf{x}) = c.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Multivariate Linear Approximation and the Gradient Descent Step

First-Order Optimization

Perturbing all n coordinates simultaneously by \boldsymbol{\epsilon} \in \mathbb{R}^n sums the linear changes across every axis:

f(\mathbf{x} + \boldsymbol{\epsilon}) \approx f(\mathbf{x}) + \nabla_{\mathbf{x}} f(\mathbf{x})^\top \boldsymbol{\epsilon}

  • Guaranteed local decrease: Choosing the gradient descent step \boldsymbol{\epsilon} = -\eta \nabla_{\mathbf{x}} f(\mathbf{x}) with a small learning rate \eta > 0 gives: f\big(\mathbf{x} - \eta \nabla_{\mathbf{x}} f(\mathbf{x})\big) \approx f(\mathbf{x}) - \eta \big\|\nabla_{\mathbf{x}} f(\mathbf{x})\big\|_2^2 \le f(\mathbf{x})
  • So long as \nabla_{\mathbf{x}} f(\mathbf{x}) \neq \mathbf{0} and \eta is small enough for the linear approximation to hold, every step strictly decreases f.
  • Why gradient descent zigzags: On our line model at \mathbf{w}_0 = [1, 0]^\top, \nabla L(\mathbf{w}_0) = [2, 4]^\top. One step with \eta = 0.1 updates: \mathbf{w}_1 = \begin{bmatrix} 1 \\ 0 \end{bmatrix} - 0.1 \begin{bmatrix} 2 \\ 4 \end{bmatrix} = \begin{bmatrix} 0.8 \\ -0.4 \end{bmatrix}, \quad L(\mathbf{w}_1) = 0.40 < 1.0
  • Because -\nabla L is perpendicular to the elliptical contours rather than pointing at the center \mathbf{w}^* = [7/6, -1/2]^\top, the trajectory zigzags down the valley.

The Multivariate Chain Rule and Computation DAGs

Compositions & DAGs

  • Single-path chain rule: When z = f(u) and u = g(x), local sensitivities multiply along the edge sequence x \to u \to z: \frac{dz}{dx} = \frac{dz}{du}\frac{du}{dx}
  • Multivariate chain rule on a DAG: When y = f(\mathbf{u}) depends on intermediate nodes u_1, \ldots, u_m and each u_i = g_i(\mathbf{x}) depends on inputs x_1, \ldots, x_n: \frac{\partial y}{\partial x_j} = \sum_{i=1}^m \frac{\partial y}{\partial u_i} \frac{\partial u_i}{\partial x_j} \quad \Longleftrightarrow \quad \nabla_{\mathbf{x}} y = \mathbf{J}^\top \nabla_{\mathbf{u}} y
  • Graph rule: Multiply edge weights (local derivatives) along each directed path from x_j to y, then sum over all parallel paths.

Worked Example: Summing Parallel Paths on a Computation DAG

Multivariate Chain Rule in Action

For z = u^2 + v with u = x_1 x_2 and v = x_2^2 at (x_1, x_2) = (1, 2):

  • Forward (blue): u = 2,\; v = 4 \implies z = 2^2 + 4 = 8.
  • Backward (red): Upstream adjoints are \frac{\partial z}{\partial u} = 2u = 4 and \frac{\partial z}{\partial v} = 1: \frac{\partial z}{\partial x_1} = 4 \cdot 2 = 8, \quad \frac{\partial z}{\partial x_2} = 4(1) + 1(4) = 8
  • Reusing \frac{\partial z}{\partial u} = 4 avoids symbolic expansion of z(x_1, x_2).

Matrix Calculus Identities and Vector-Valued Jacobians

Vector & Matrix Calculus

Expression Function f(\mathbf{x}) Gradient / Jacobian Deep Learning Application
Linear form \mathbf{a}^\top \mathbf{x} \nabla_{\mathbf{x}}(\mathbf{a}^\top \mathbf{x}) = \mathbf{a} Linear neuron \mathbf{w}^\top \mathbf{x} + b
Quadratic form \mathbf{x}^\top \mathbf{A} \mathbf{x} \nabla_{\mathbf{x}}(\mathbf{x}^\top \mathbf{A} \mathbf{x}) = (\mathbf{A} + \mathbf{A}^\top)\mathbf{x} Hessian terms (2\mathbf{A}\mathbf{x} if \mathbf{A} = \mathbf{A}^\top)
Squared L_2 norm \|\mathbf{x}\|_2^2 = \mathbf{x}^\top \mathbf{x} \nabla_{\mathbf{x}}\|\mathbf{x}\|_2^2 = 2\mathbf{x} Weight decay & MSE residuals
Least squares \|\mathbf{X}\mathbf{w} - \mathbf{y}\|_2^2 \nabla_{\mathbf{w}} L = 2\mathbf{X}^\top(\mathbf{X}\mathbf{w} - \mathbf{y}) Linear regression batch gradient
Vector map \mathbf{f}: \mathbb{R}^n \to \mathbb{R}^m \mathbf{J}_{\mathbf{f}}(\mathbf{x}) \in \mathbb{R}^{m \times n},\; (\mathbf{J}_{\mathbf{f}})_{ij} = \frac{\partial f_i}{\partial x_j} Chaining layers: \mathbf{J}_{\mathbf{f} \circ \mathbf{g}} = \mathbf{J}_{\mathbf{f}}\mathbf{J}_{\mathbf{g}}

For any affine map \mathbf{u} = \mathbf{A}\mathbf{x} + \mathbf{b}, \mathbf{J}_{\mathbf{u}}(\mathbf{x}) = \mathbf{A}, so propagating \nabla_{\mathbf{u}} y backward multiplies by \mathbf{A}^\top: \nabla_{\mathbf{x}} y = \mathbf{A}^\top \nabla_{\mathbf{u}} y.

From Chain Rule to Backpropagation: Vector–Jacobian Products

Forward & Backward Passes

  • Two-stage graph (\mathbf{w} \to \mathbf{r} \to L): Forward computes \mathbf{r} = \mathbf{X}\mathbf{w} - \mathbf{y} and L = \|\mathbf{r}\|_2^2.
  • Backward VJP: Propagates \nabla_{\mathbf{r}} L = 2\mathbf{r} into \nabla_{\mathbf{w}} L = \mathbf{X}^\top (2\mathbf{r}) in O(mn) FLOPs:
r = X @ w - y    # forward: errors, from which the loss is r @ r
grad_r = 2 * r   # backward: gradient of the loss with respect to r
X.T @ grad_r     # backward: gradient with respect to w
array([2., 4.])

Why Not Just Use Numerical Finite Differences?

Numerical vs. Analytical Differentiation

Approximating f'(x) \approx \frac{f(x+h) - f(x)}{h} has two fatal flaws in deep learning:

  1. The Numerical V-Curve:
    • Too large h: Taylor truncation error grows as O(h) (or O(h^2) for central differences).
    • Too small h: Subtracting nearly equal floats f(x+h) - f(x) erases mantissa bits (catastrophic cancellation, error \sim \epsilon / h, capping float32 at \sim 4 valid digits).
  2. Computational O(d) Blowup: Perturbing d = 10^9 weights requires 10^9 + 1 forward passes per step, whereas reverse-mode AD (§1.5) takes one backward pass.

Concept Check: Gradients, Level Curves, and the Chain Rule

Check Your Understanding

  1. Gradient geometry: At \mathbf{x} = (1, 2), \nabla f(\mathbf{x}) = [3, -4]^\top. What is the unit vector \mathbf{u}^* of steepest descent, the rate D_{\mathbf{u}^*} f(\mathbf{x}), and a vector tangent to the level curve?
  2. Matrix calculus trap: For non-symmetric \mathbf{A} = [[1, 2], [0, 1]] and \mathbf{x} = [1, 1]^\top, what is \nabla_{\mathbf{x}}(\mathbf{x}^\top \mathbf{A} \mathbf{x})? Why is 2\mathbf{A}\mathbf{x} wrong?
  3. Scaling to deep networks: For d = 10^8 parameters, how many forward passes does central differencing require per step versus backpropagation?

Answers:

  1. \|\nabla f\|_2 = 5 \implies \mathbf{u}^* = \mathbf{[-3/5,\, 4/5]^\top} with rate -\|\nabla f\|_2 = \mathbf{-5}. Tangent vector: \mathbf{[4, 3]^\top} (3(4) - 4(3) = 0).
  2. \nabla_{\mathbf{x}}(\mathbf{x}^\top \mathbf{A} \mathbf{x}) = (\mathbf{A} + \mathbf{A}^\top)\mathbf{x} = \mathbf{[4, 4]^\top} (since \mathbf{A} \neq \mathbf{A}^\top, 2\mathbf{A}\mathbf{x} = [6, 2]^\top misses the transposed product-rule term).
  3. Central differences require 2d = 2 \times 10^8 forward passes; backpropagation takes 1 forward + 1 backward pass (\approx 2\text{--}3\times one forward pass).

Summary: Calculus Objects, Shapes, Geometry, and Optimization Roles

Key Takeaways

Calculus Object Formula Shape Geometric Meaning Deep Learning Role
Derivative f'(x) \lim_{h \to 0} \frac{f(x+h)-f(x)}{h} () Tangent slope at x 1D linear approx f(x+h) \approx f(x) + f'(x)h
Partial \frac{\partial f}{\partial x_i} Derivative with x_{j \neq i} fixed () Axis-i slice slope Sensitivity of loss to single weight w_i
Gradient \nabla_{\mathbf{x}} f(\mathbf{x}) [\partial f/\partial x_1, \ldots, \partial f/\partial x_n]^\top (n,) Points uphill \perp contours Descent step \mathbf{w} \leftarrow \mathbf{w} - \eta \nabla_{\mathbf{w}}\mathcal{L}
Jacobian \mathbf{J}_{\mathbf{f}}(\mathbf{x}) (\mathbf{J}_{\mathbf{f}})_{ij} = \partial f_i / \partial x_j (m, n) Local linear map \mathbf{J}\mathbf{h} Layer-to-layer sensitivity matrix
Chain rule (VJP) \nabla_{\mathbf{x}} y = \mathbf{J}_{\mathbf{u}}(\mathbf{x})^\top \nabla_{\mathbf{u}} y (n,) Sum over all DAG paths Reverse-mode backpropagation (§1.5)
Finite difference \frac{f(x+h)-f(x-h)}{2h} 2d evals Secant slope on [x-h, x+h] Unit-test gradient checks in float64