Module 02 — Calculus, Multivariable Calculus and Automatic Differentiation
⬅️ Module 01 · 🗺️ Curriculum · 🏠 Home · Module 03 ➡️
Level: Foundational · Prerequisites: Module 01, single-variable calculus · Time: about 7–9 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Overview and learning goals
Training a neural network means minimising a scalar loss $L(\theta)$ over millions or billions of parameters. Calculus tells us which direction lowers the loss (the gradient), how curved the loss is (the Hessian), and how to propagate sensitivities through a composition of many functions (the chain rule). Automatic differentiation turns the chain rule into an algorithm that is the engine behind every deep-learning framework.
After this module you should be able to:
- differentiate compositions of functions and explain why the chain rule drives backpropagation;
- compute gradients, Jacobians and Hessians and interpret them geometrically;
- derive matrix-form gradients with correct shapes;
- explain forward- vs reverse-mode automatic differentiation and vector–Jacobian products;
- verify any gradient implementation with finite differences.
Beginner: the big picture
A derivative answers: if I nudge the input a little, how much does the output change? For $f(x)=x^2$ at $x=3$ the derivative is $6$: a nudge of $+0.01$ changes $f$ by about $+0.06$. With many inputs, the gradient collects one such sensitivity per input. Gradient descent repeatedly steps against the gradient to reduce a loss.
A network is a long chain: input $\to$ layer 1 $\to$ layer 2 $\to\dots\to$ loss. The chain rule says the sensitivity of the loss to an early quantity is the product of the local sensitivities along the way. Backpropagation computes those products efficiently by working backwards once.
flowchart LR
x["x = 2"] --> z["z = w*x + b"]
w["w = 0.5"] --> z
b["b = -1"] --> z
z --> s["s = sigmoid(z)"]
s --> L["L = (s - t)^2"]
t["t = 1"] --> L
L -.->|"dL/ds = 2(s-t)"| s
s -.->|"ds/dz = s(1-s)"| z
z -.->|"dz/dw = x, dz/db = 1"| w
Loading
Figure 2.1 — A computational graph. Solid arrows: forward pass. Dashed arrows: local derivatives multiplied backwards. Original diagram.
Core concepts and derivations
Limits, continuity and differentiability
$f$ is differentiable at $x$ if $f'(x)=\lim_{h\to0}\frac{f(x+h)-f(x)}{h}$ exists. Differentiable implies continuous, not conversely: $\lvert x\rvert$ is continuous but not differentiable at 0. ReLU has the same kink; frameworks use a subgradient (conventionally $0$) there, which works in practice because the kink is a measure-zero event.
Derivative rules and the chain rule
Linearity, product $(uv)'=u'v+uv'$, quotient, and the chain rule $\frac{d}{dx}f(g(x))=f'(g(x))\,g'(x)$. Example: the logistic sigmoid $\sigma(z)=(1+e^{-z})^{-1}$ gives
$$\sigma'(z)=\frac{e^{-z}}{(1+e^{-z})^2}=\sigma(z)\bigl(1-\sigma(z)\bigr),$$
with maximum $1/4$ at $z=0$ — the root of vanishing gradients in deep sigmoid networks (Modules 05, 09).
Partial, directional and total derivatives
For $f:\mathbb{R}^n\to\mathbb{R}$, $\partial f/\partial x_i$ varies one coordinate with others fixed. The directional derivative along a unit vector $\mathbf{u}$ is $D_{\mathbf{u}}f=\nabla f^\top\mathbf{u}$. When variables depend on a common parameter $t$, the total derivative is $\frac{df}{dt}=\sum_i\frac{\partial f}{\partial x_i}\frac{dx_i}{dt}$ — the multivariable chain rule.
By Cauchy–Schwarz, $\nabla f^\top\mathbf{u}\le\lVert\nabla f\rVert$ with equality iff $\mathbf{u}\parallel\nabla f$. Hence $\nabla f$ points in the direction of steepest ascent, and $-\nabla f$ of steepest descent. Also $\nabla f$ is orthogonal to level sets $\{f=c\}$: along a curve $\mathbf{x}(t)$ inside the level set, $\frac{d}{dt}f(\mathbf{x}(t))=\nabla f^\top\dot{\mathbf{x}}=0$.
Jacobians and vector-valued functions
For $\mathbf{f}:\mathbb{R}^n\to\mathbb{R}^m$ the Jacobian $J\in\mathbb{R}^{m\times n}$ has $J_{ij}=\partial f_i/\partial x_j$ and gives the best linear approximation $\mathbf{f}(\mathbf{x}+\mathbf{\delta})\approx\mathbf{f}(\mathbf{x})+J\mathbf{\delta}$. The chain rule becomes a matrix product: $J_{\mathbf{g}\circ\mathbf{f}}=J_{\mathbf{g}}\,J_{\mathbf{f}}$. Elementwise activations have diagonal Jacobians $\mathrm{diag}(\phi'(\mathbf{z}))$; softmax has the dense Jacobian $\mathrm{diag}(\mathbf{p})-\mathbf{p}\mathbf{p}^\top$.
Hessians, curvature and Taylor approximation
The Hessian $H_{ij}=\partial^2f/\partial x_i\partial x_j$ is symmetric (for $C^2$ functions). The second-order Taylor expansion is
$$f(\mathbf{x}+\mathbf{\delta})\approx f(\mathbf{x})+\nabla f(\mathbf{x})^\top\mathbf{\delta}+\frac12\mathbf{\delta}^\top H\mathbf{\delta} .$$
Curvature along a unit direction $\mathbf{u}$ is $\mathbf{u}^\top H\mathbf{u}$, bounded by the extreme eigenvalues. Minimising this quadratic yields Newton's step $\mathbf{\delta}=-H^{-1}\nabla f$; gradient descent with step $\eta$ is stable only if $\eta<2/\lambda_{\max}(H)$ (Module 08).
Computational graphs and reverse-mode autodiff
Any program is a graph of elementary operations. Two ways to apply the chain rule:
-
Forward mode propagates tangents from inputs; one pass yields one column of $J$ (a Jacobian–vector product, JVP). Efficient when inputs $\ll$ outputs.
-
Reverse mode propagates adjoints $\bar v=\partial L/\partial v$ from the loss backwards; one pass yields the gradient of a scalar w.r.t. all inputs (a vector–Jacobian product, VJP). Efficient when outputs $\ll$ inputs — exactly the deep-learning case ($L$ is scalar, $\theta$ is huge).
Reverse mode costs a small constant multiple of the forward pass but must store intermediate activations — the source of training's memory footprint and of activation checkpointing (Module 24).
Vector–Jacobian and Jacobian–vector products
Reverse mode never forms $J$. Given the upstream adjoint $\mathbf{v}=\partial L/\partial\mathbf{y}$ it computes $\mathbf{v}^\top J$ directly. For a linear layer $\mathbf{y}=W\mathbf{x}$: $\partial L/\partial\mathbf{x}=W^\top\mathbf{v}$ and $\partial L/\partial W=\mathbf{v}\mathbf{x}^\top$. Forming the full Jacobian of an elementwise ReLU on a 4096-vector would waste $4096^2$ entries; its VJP is just $\mathbf{v}\odot\mathbf{1}[\mathbf{z}>0]$.
Matrix differentiation and shape-aware derivatives
Use the rule: the gradient has the same shape as the variable. Derivation for $Y=XW$ with upstream gradient $G=\partial L/\partial Y\in\mathbb{R}^{B\times d_{out}}$: since $dY=X\,dW$,
$$dL=\langle G,\,X\,dW\rangle_F=\mathrm{tr}\!\left(G^\top X\,dW\right)=\langle X^\top G,\,dW\rangle_F\;\Longrightarrow\;\frac{\partial L}{\partial W}=X^\top G,\qquad \frac{\partial L}{\partial X}=GW^\top,\qquad \frac{\partial L}{\partial b}=\mathbf{1}^\top G .$$
Shape check: $X^\top G$ is $(d_{in}\times B)(B\times d_{out})=d_{in}\times d_{out}$ ✓. The bias gradient sums over the batch because $b$ was broadcast.
Finite-difference gradient checks
The central difference $\frac{f(\theta+h\mathbf{e}_i)-f(\theta-h\mathbf{e}_i)}{2h}$ has error $O(h^2)$ (forward difference: $O(h)$). Compare to the analytic gradient with a relative error $\frac{\lVert g_a-g_n\rVert}{\lVert g_a\rVert+\lVert g_n\rVert}$; in float64 with $h\approx10^{-5}$ expect $<10^{-6}$. Do this on a tiny network, with deterministic data and no dropout.
Network: $z=wx+b$, $s=\sigma(z)$, $L=(s-t)^2$ with $x=2$, $w=0.5$, $b=-1$, $t=1$.
Forward: $z=0$, $s=0.5$, $L=0.25$.
Backward: $\partial L/\partial s=2(s-t)=-1$; $\partial s/\partial z=s(1-s)=0.25$; so $\partial L/\partial z=-0.25$; then $\partial L/\partial w=-0.25\cdot x=-0.5$ and $\partial L/\partial b=-0.25$.
Check: $L(w=0.5+10^{-5})$ and $L(w=0.5-10^{-5})$ differ by $\approx-10^{-5}$, so the central difference is $\approx-0.5$ ✓.
import numpy as np
def loss(w, b, x=2.0, t=1.0):
s = 1 / (1 + np.exp(-(w * x + b)))
return (s - t) ** 2
def grad(w, b, x=2.0, t=1.0): # analytic (backprop by hand)
s = 1 / (1 + np.exp(-(w * x + b)))
dz = 2 * (s - t) * s * (1 - s)
return dz * x, dz
def num_grad(f, params, h=1e-5): # central differences
g = []
for i in range(len(params)):
p, m = list(params), list(params)
p[i] += h; m[i] -= h
g.append((f(*p) - f(*m)) / (2 * h))
return np.array(g)
ga, gn = np.array(grad(0.5, -1.0)), num_grad(loss, (0.5, -1.0))
print(ga, gn, np.linalg.norm(ga - gn) / (np.linalg.norm(ga) + np.linalg.norm(gn)))
import torch
w = torch.tensor(0.5, requires_grad=True); b = torch.tensor(-1.0, requires_grad=True)
L = (torch.sigmoid(w * 2 + b) - 1) ** 2
L.backward(); print(w.grad, b.grad) # tensor(-0.5), tensor(-0.25)
-
Hessian–vector products $H\mathbf{v}=\nabla(\nabla L^\top\mathbf{v})$ cost about two backward passes and enable Newton–CG, curvature estimation and sharpness analysis without forming $H$.
-
Checkpointing trades compute for memory by recomputing activations during the backward pass.
-
Non-differentiable operations: straight-through estimators, score-function (REINFORCE) gradients and the reparameterisation trick (Module 18) estimate gradients through sampling or rounding.
-
Implicit differentiation differentiates through fixed points and optimisation layers without unrolling.
-
Numerical stability: compute $\log\sum e^{z_i}$ with the max-shift trick; fused softmax–cross-entropy avoids overflow and cancellation.
-
Higher-order and per-sample gradients (e.g.
torch.func, JAX vmap(grad)) underpin differential privacy and meta-learning.
Pitfalls and best practices
- Gradients accumulate in PyTorch: call
optimizer.zero_grad() each step.
- Detaching a tensor (
.detach(), torch.no_grad()) silently stops gradient flow.
- In-place operations can overwrite values needed by the backward pass.
- Gradient checks fail near kinks (ReLU at 0) and with stochastic layers; check in eval mode with smooth activations.
- A loss that is a mean versus a sum changes the gradient scale by $B$; know which one you use.
Conceptual questions and answers
Q1. Why does the negative gradient give the direction of steepest descent?
Show answer
For a unit step direction $\mathbf{u}$, the first-order change in $f$ is $\nabla f^\top\mathbf{u}=\lVert\nabla f\rVert\cos\theta$, which is minimised (most negative) at $\theta=\pi$, i.e. $\mathbf{u}=-\nabla f/\lVert\nabla f\rVert$.
Q2. Why is reverse mode used for training and not forward mode?
Show answer
Training differentiates one scalar loss with respect to enormous numbers of parameters. Reverse mode obtains the entire gradient in one backward pass; forward mode would need one pass per parameter.
Q3. What is a vector–Jacobian product and why never build the Jacobian?
Show answer
It is $\mathbf{v}^\top J$ — the upstream gradient times the local Jacobian. Frameworks implement each operation's VJP directly, which is far cheaper in time and memory than materialising $J$ (e.g. $n^2$ entries for an $n$-dimensional elementwise op).
Q4. Derive $\partial L/\partial W$ for $Y=XW$.
Show answer
$dY=X\,dW\Rightarrow dL=\langle G,X\,dW\rangle=\langle X^\top G,dW\rangle$, hence $\nabla_WL=X^\top G$, with the shape of $W$.
Q5. Why does ReLU not break backpropagation despite not being differentiable at 0?
Show answer
The kink is a single point; inputs hit it with probability zero for continuous data, and a subgradient (0 or 1) is a valid choice. Training is correct in practice; only finite-difference checks near 0 are unreliable.
Q6. What does the Hessian tell you that the gradient does not?
Show answer
Curvature: how quickly the gradient changes. It determines stable step sizes, distinguishes minima from saddles and measures conditioning.
Q7. Why is the central difference more accurate than the forward difference?
Show answer
Taylor expanding $f(x\pm h)$, the $O(h)$ error terms cancel in the symmetric difference, leaving $O(h^2)$.
Q8. Why must a gradient have the same shape as its parameter?
Show answer
The update $\theta\leftarrow\theta-\eta\nabla_\theta L$ subtracts elementwise, and each gradient entry is the sensitivity of $L$ to the corresponding parameter entry.
Q9. Why does activation memory dominate training memory, and how does checkpointing help?
Show answer
Reverse mode needs intermediate values from the forward pass. Checkpointing stores only a subset and recomputes the rest during backward, cutting memory at the cost of roughly one extra forward pass.
Q10. How would you detect a wrong backward implementation?
Show answer
Run a gradient check against central finite differences on a tiny deterministic model in float64; a relative error much larger than $10^{-6}$ points to a bug in that layer's backward.
Sources and further reading
- Baydin, A. G., Pearlmutter, B. A., Radul, A. A., & Siskind, J. M. (2018). Automatic differentiation in machine learning: a survey. JMLR, 18(153).
- Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536.
- Petersen, K. B., & Pedersen, M. S. (2012). The Matrix Cookbook. Technical University of Denmark.
- Goodfellow, Bengio & Courville (2016). Deep Learning, §4.3 and Ch. 6.
- Pearlmutter, B. A. (1994). Fast exact multiplication by the Hessian. Neural Computation, 6(1).
⬅️ Module 01 · 🗺️ Curriculum · 🏠 Home · Module 03 ➡️