Repository navigation
Module 02
⬅️ 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
Training a neural network means minimising a scalar loss
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.
A derivative answers: if I nudge the input a little, how much does the output change? For
A network is a long chain: input
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
Figure 2.1 — A computational graph. Solid arrows: forward pass. Dashed arrows: local derivatives multiplied backwards. Original diagram.
Linearity, product
with maximum
For
By Cauchy–Schwarz,
For
The Hessian
Curvature along a unit direction
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).
Reverse mode never forms
Use the rule: the gradient has the same shape as the variable. Derivation for
Shape check:
The central difference
Network:
Forward:
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, JAXvmap(grad)) underpin differential privacy and meta-learning.
- 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.
Q1. Why does the negative gradient give the direction of steepest descent?
For a unit step direction
Q2. Why is reverse mode used for training and not forward mode?
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?
It is
Q4. Derive $\partial L/\partial W$ for $Y=XW$.
Q5. Why does ReLU not break backpropagation despite not being differentiable at 0?
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?
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?
Taylor expanding
Q8. Why must a gradient have the same shape as its parameter?
The update
Q9. Why does activation memory dominate training memory, and how does checkpointing help?
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?
Run a gradient check against central finite differences on a tiny deterministic model in float64; a relative error much larger than
- 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 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24