Shelves / AI and ML Foundations
AI·146
Calculus
The mathematics of learning by adjustment: limits and derivatives as rates of change, rules of differentiation, partial derivatives and gradients as the direction of steepest ascent, the chain rule and why it is all of backpropagation, Jacobians and vector-Jacobian products, Hessians, curvature and convexity, Taylor approximations, gradient descent and its variants (momentum, Adam) derived from first principles, learning-rate behaviour, constrained optimisation with Lagrange multipliers, numerical gradient checking, and a working reverse-mode automatic differentiation engine built from scratch in Python and compared with PyTorch, JAX, Rust and Julia.
Start here: how a model knows which way to adjust
Training means adjusting millions of parameters so the loss goes down. The question at every step is: if I nudge this parameter a little, how does the loss change? That's a derivative. With many parameters, the derivatives together form the gradient, a vector pointing in the direction of steepest increase; stepping the other way reduces the loss. The chain rule lets us compute it through a whole network, layer by layer, which is what backpropagation and PyTorch's autograd do automatically.
Three ways to get a derivative
For f(x) = x³ − 2x + sin x at x = 1.3, the exact derivative 3x² − 2 + cos x is 3.3374988286:
autograd (PyTorch): 3.3374988286 exact to all digits shown
finite difference, h = 1e-1: 3.3470532201 error 9.6e-03 (step too coarse)
finite difference, h = 1e-4: 3.3374988382 error 9.6e-09
finite difference, h = 1e-8: 3.3374987940 error 3.5e-08
finite difference, h = 1e-12: 3.3379410347 error 4.4e-04 (rounding error takes over)
Autograd applies the chain rule to the actual operations, so it's exact up to floating-point rounding and costs about one extra pass. Finite differences ("nudge and measure") are approximate, need one evaluation per parameter, and get worse when the step is too small because of rounding. They're still useful for one thing: checking that a hand-written gradient is right (gradient checking).
The learning rate decides everything
Gradient descent on a valley shaped like f(w) = (w₁ − 3)² + 10(w₂ + 1)², whose minimum is at (3, −1), for 50 steps from (0, 0):
learning rate 0.01: w = (1.907, −1.000) loss 1.24 too slow
learning rate 0.05: w = (2.985, −1.000) loss 0.000295
learning rate 0.09: w = (3.000, −1.000) loss 3.5e-08 about right
learning rate 0.11: w = (3.000, 9,099.4) loss 5.75e+08 diverged
The valley is 10× steeper in w₂ than in w₁. Above a learning rate of 0.1 (= 1 ÷ the steep direction's curvature of 10), each step in w₂ overshoots by more than it corrects, and the loss explodes. Below it, the shallow w₁ direction crawls. Real loss surfaces have this mismatch in millions of directions at once, which is why optimisers like Adam scale steps per parameter, and why learning-rate warm-up and schedules exist.
Gradients can vanish
The gradient reaching the first layer of a stack of layers (average size):
sigmoid, default init: depth 2: 2.0e-01 depth 10: 2.6e-08 depth 30: 1.8e-25
ReLU, default init: depth 2: 2.5e+00 depth 10: 1.3e-03 depth 30: 1.0e-11
ReLU, He initialisation: depth 2: 6.6e+00 depth 10: 1.5e+01 depth 30: 6.0e+00
The chain rule multiplies one factor per layer. A sigmoid's derivative is at most 0.25, so thirty of them shrink the gradient to nothing, and the early layers stop learning. ReLU (derivative 1 where active) plus initialisation scaled to keep signals the same size layer to layer (He initialisation) kept the gradient healthy at depth 30. Residual connections and normalisation layers (chapter 153) are the other two inventions that made deep networks trainable.
How deep to go in calculus
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain derivatives, gradients and why gradient descent works |
| L2 | Use autograd to train models and choose a sensible learning rate |
| L3 | Derive gradients with the chain rule (including for softmax and cross-entropy) and explain backpropagation |
| L4 | Diagnose exploding, vanishing and noisy gradients and check gradients numerically |
| L5 | Choose optimisers, schedules, initialisation and normalisation for a training setup |
| L6 | Develop optimisation methods and training recipes at scale |
Why calculus
Training a model means finding parameters θ that minimise a loss L(θ). With millions or billions of parameters, we can't search blindly; we need to know, for each parameter, which way to nudge it and by how much to reduce the loss. That information is the gradient, and computing it efficiently through deep compositions of functions is the chain rule, implemented as backpropagation / reverse-mode automatic differentiation. Calculus also explains why training succeeds or fails: learning rates, curvature, saddle points, vanishing and exploding gradients.
Derivatives
Rate of change
The derivative of f at x is the instantaneous rate of change: the slope of the tangent line:
f′(x) = lim_{h→0} [f(x + h) − f(x)] / h
Interpretation for ML: if f′(x) = 3, increasing x by a tiny amount ε increases f by about 3ε. To decrease f, move x opposite to the sign of f′.
Rules
| Rule | Formula |
|---|---|
| Constant | (c)′ = 0 |
| Power | (xⁿ)′ = n xⁿ⁻¹ |
| Exponential, log | (eˣ)′ = eˣ; (ln x)′ = 1/x |
| Sum | (f + g)′ = f′ + g′ |
| Product | (fg)′ = f′g + fg′ |
| Quotient | (f/g)′ = (f′g − fg′)/g² |
| Chain | (f(g(x)))′ = f′(g(x)) · g′(x) |
Derivatives of functions used constantly in ML:
| Function | Derivative | Role |
|---|---|---|
| Sigmoid σ(x) = 1/(1 + e⁻ˣ) | σ(x)(1 − σ(x)) | Logistic regression, gates; max derivative 0.25 → vanishing gradients |
| tanh x | 1 − tanh² x | RNN activations |
| ReLU max(0, x) | 1 if x > 0 else 0 | Default hidden activation; "dead" units when always negative |
| GELU / SiLU (x·σ(x)) | smooth approximations | Transformers' MLPs |
| softplus ln(1 + eˣ) | σ(x) | Smooth ReLU |
| MSE (ŷ − y)² | 2(ŷ − y) | Regression loss |
| −log p | −1/p | Cross-entropy |
| Softmax + cross-entropy w.r.t. logits | p − y (one-hot) | Classification and LLM training (beautifully simple, chapter 147) |
import numpy as np
sig = lambda x: 1 / (1 + np.exp(-x))
x, h = 0.7, 1e-6
numeric = (sig(x + h) - sig(x - h)) / (2 * h) # central difference
analytic = sig(x) * (1 - sig(x))
numeric, analytic # both ≈ 0.2217
Partial derivatives and gradients
Partial derivatives
For a function of several variables f(x₁, …, xₙ), the partial derivative ∂f/∂xᵢ is the rate of change when only xᵢ varies, others held fixed.
Example: f(x, y) = x²y + 3y → ∂f/∂x = 2xy, ∂f/∂y = x² + 3.
The gradient
The gradient collects all partial derivatives into a vector:
∇f(x) = (∂f/∂x₁, …, ∂f/∂xₙ)
Key facts:
- ∇f points in the direction of steepest ascent; −∇f is steepest descent.
- Its magnitude is the rate of increase in that direction.
- It's perpendicular to contour lines (level sets) of f.
- The directional derivative in unit direction u is ∇f · u (dot product, chapter 145): maximised when u is aligned with ∇f.
- At a (local) minimum, maximum or saddle point, ∇f = 0.
The chain rule
Single variable
If y = f(u) and u = g(x), then dy/dx = (dy/du)(du/dx). Composition of functions → multiplication of local derivatives.
Multivariable and computational graphs
When a variable influences the output through several paths, the derivative is the sum over paths of products of local derivatives. A model is a computational graph: nodes are operations (multiply, add, matmul, ReLU, softmax), edges carry values. The chain rule tells us how the final loss depends on every intermediate value.
Example: L = (w·x + b − y)², with w = 2, x = 3, b = 1, y = 5.
- Forward: z = w·x = 6; a = z + b = 7; e = a − y = 2; L = e² = 4.
- Backward (local derivatives multiplied from the output back):
- ∂L/∂e = 2e = 4
- ∂L/∂a = ∂L/∂e · ∂e/∂a = 4 · 1 = 4
- ∂L/∂b = ∂L/∂a · 1 = 4
- ∂L/∂z = ∂L/∂a · 1 = 4
- ∂L/∂w = ∂L/∂z · x = 4 · 3 = 12
- ∂L/∂x = ∂L/∂z · w = 4 · 2 = 8
Backpropagation is this computation organised efficiently: a forward pass stores intermediate values; a backward pass visits nodes in reverse topological order, each multiplying the incoming gradient by its local derivative and passing results to its inputs (summing when a value is used in several places). Cost: about 2–3× the forward pass, regardless of the number of parameters, which is why we can train billion-parameter models.
Jacobians and vector-Jacobian products
For a vector-valued function f: ℝⁿ → ℝᵐ, the Jacobian J is the m × n matrix of all partial derivatives: Jᵢⱼ = ∂fᵢ/∂xⱼ. It's the best linear approximation of f near x: f(x + δ) ≈ f(x) + Jδ.
- Chain rule for vector functions: J_{f∘g} = J_f · J_g (matrix multiplication of Jacobians).
- For a linear layer y = Wx, the Jacobian ∂y/∂x is W itself; ∂L/∂W = (∂L/∂y) xᵀ (an outer product).
Materialising full Jacobians is expensive (a layer mapping 4096 → 4096 has a 16M-entry Jacobian per example). Autodiff never builds them; it computes products:
- Reverse mode (backprop) computes vector-Jacobian products vᵀJ: one backward pass gives the gradient of a scalar output with respect to all inputs. Ideal for ML (one scalar loss, millions of parameters).
- Forward mode computes Jacobian-vector products Jv: one pass gives the derivative of all outputs with respect to one input direction. Ideal when inputs are few and outputs many; implemented with dual numbers.
# Gradient of a linear layer + MSE, derived by hand and checked numerically
rng = np.random.default_rng(0)
W = rng.normal(size=(3, 4)); x = rng.normal(size=4); t = rng.normal(size=3)
def loss(W): return 0.5 * np.sum((W @ x - t) ** 2)
dy = W @ x - t # ∂L/∂y
grad_W = np.outer(dy, x) # ∂L/∂W = (∂L/∂y) xᵀ
eps = 1e-6; num = np.zeros_like(W) # numerical check, entry by entry
for i in range(3):
for j in range(4):
Wp = W.copy(); Wp[i, j] += eps; Wm = W.copy(); Wm[i, j] -= eps
num[i, j] = (loss(Wp) - loss(Wm)) / (2 * eps)
np.max(np.abs(num - grad_W)) # ~1e-10: hand-derived gradient is correct
Hessians, curvature and convexity
The Hessian H is the matrix of second derivatives: Hᵢⱼ = ∂²f/∂xᵢ∂xⱼ (symmetric for smooth f). It describes curvature:
- At a critical point (∇f = 0): all eigenvalues of H positive → local minimum; all negative → maximum; mixed signs → saddle point.
- Large eigenvalues = sharp curvature in that direction; small = flat. The ratio of largest to smallest (condition number) determines how hard plain gradient descent finds the problem (the zig-zag in narrow valleys).
- Convex functions (H positive semi-definite everywhere; the chord between any two points lies above the curve) have no bad local minima: any local minimum is global. Linear regression with MSE and logistic regression are convex; deep networks are not, yet gradient methods work remarkably well in practice, partly because in very high dimensions most critical points are saddles rather than poor minima, and stochastic noise helps escape them.
Second-order methods (Newton's method: θ ← θ − H⁻¹∇L) converge fast near minima but need Hessians (n² entries: impossible for large models); quasi-Newton methods (L-BFGS) approximate them and are used for small/medium problems; adaptive optimisers (Adam) use cheap per-parameter curvature proxies.
Taylor approximations
Near a point a, a smooth function is approximated by its Taylor series:
f(a + δ) ≈ f(a) + ∇f(a)ᵀδ + ½ δᵀH(a)δ
- The first-order (linear) approximation justifies gradient descent: a small step δ = −η∇f decreases f by about η‖∇f‖².
- The second-order term explains when steps are too large: if η exceeds 2/λ_max (λ_max = largest Hessian eigenvalue), the quadratic term dominates and the loss increases: divergence.
Gradient descent
The algorithm
θ_{t+1} = θ_t − η ∇L(θ_t)
where η is the learning rate (step size).
- Batch gradient descent: gradient over the whole dataset each step: accurate but slow per step.
- Stochastic gradient descent (SGD): gradient from one example: noisy but cheap.
- Mini-batch SGD: gradient from a batch (e.g. 32–4096 examples): the standard; noise acts as regularisation; batches use hardware efficiently (chapter 151).
Learning rate behaviour
In practice learning rates are scheduled: warm-up (start small to avoid early instability), then decay (cosine, linear, step) to settle into a minimum (chapter 151).
Momentum and adaptive methods
Momentum accumulates a velocity that smooths zig-zags and speeds progress along consistent directions:
v ← β v + ∇L(θ); θ ← θ − η v (β ≈ 0.9)
Adam (adaptive moment estimation) keeps exponential moving averages of gradients (first moment m) and squared gradients (second moment v) per parameter, scaling each parameter's step by its recent gradient magnitude:
m ← β₁m + (1 − β₁)g; v ← β₂v + (1 − β₂)g² m̂ = m/(1 − β₁ᵗ); v̂ = v/(1 − β₂ᵗ) (bias correction) θ ← θ − η m̂ / (√v̂ + ε)
AdamW decouples weight decay from the gradient update (θ ← θ − ηλθ separately), the default optimiser for Transformers. Others: RMSProp, Adagrad, Lion, Adafactor (memory-efficient), Shampoo/SOAP and Muon (newer optimisers using matrix structure, increasingly used for large models).
# Minimise an ill-conditioned quadratic L(θ) = ½ θᵀ A θ with plain GD, momentum and Adam
A = np.diag([1.0, 50.0]) # curvatures 1 and 50: condition number 50
grad = lambda th: A @ th
def run(step_fn, steps=200):
th, state = np.array([5.0, 5.0]), {}
for t in range(1, steps + 1):
th = step_fn(th, grad(th), state, t)
return 0.5 * th @ A @ th # final loss
def gd(th, g, s, t, lr=0.035): return th - lr * g # lr must be < 2/50 = 0.04
def momentum(th, g, s, t, lr=0.01, beta=0.9):
s["v"] = beta * s.get("v", 0) + g; return th - lr * s["v"]
def adam(th, g, s, t, lr=0.1, b1=0.9, b2=0.999, eps=1e-8):
s["m"] = b1 * s.get("m", 0) + (1 - b1) * g
s["v"] = b2 * s.get("v", 0) + (1 - b2) * g * g
mh, vh = s["m"] / (1 - b1**t), s["v"] / (1 - b2**t)
return th - lr * mh / (np.sqrt(vh) + eps)
print(run(gd), run(momentum), run(adam)) # momentum and Adam reach far lower loss in 200 steps
Constrained optimisation: Lagrange multipliers
To maximise f(x) subject to g(x) = 0, at the optimum the gradients are parallel: ∇f = λ∇g (otherwise you could move along the constraint and improve f). Introduce the Lagrangian ℒ(x, λ) = f(x) − λg(x) and set its gradient to zero.
PCA's derivation (chapter 145) is exactly this: maximise wᵀCw subject to wᵀw = 1 → ∇(wᵀCw) = λ∇(wᵀw) → 2Cw = 2λw → w is an eigenvector. Support vector machines (chapter 148) use the generalisation to inequality constraints (KKT conditions). In deep learning, constraints are usually handled with penalties (regularisation) or projections instead.
Automatic differentiation from scratch
Three ways to get derivatives:
| Method | How | Problems |
|---|---|---|
| Symbolic | Manipulate formulas (computer algebra) | Expression swell; doesn't handle control flow well |
| Numerical | Finite differences | Slow (one evaluation per parameter), inaccurate (rounding vs truncation error) |
| Automatic | Apply the chain rule to the actual sequence of operations executed | Exact to floating-point precision, efficient: what ML frameworks use |
A minimal reverse-mode autodiff engine on scalars (in the spirit of Andrej Karpathy's micrograd) shows that backpropagation is just bookkeeping:
import math
class Value:
"""A scalar that remembers how it was computed, so gradients can flow back."""
def __init__(self, data, parents=(), op=""):
self.data, self.grad = data, 0.0
self._parents, self._op = parents, op
self._backward = lambda: None
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), "+")
def _backward():
self.grad += out.grad # d(a+b)/da = 1
other.grad += out.grad
out._backward = _backward
return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), "*")
def _backward():
self.grad += other.data * out.grad # d(ab)/da = b
other.grad += self.data * out.grad
out._backward = _backward
return out
def __pow__(self, k):
out = Value(self.data ** k, (self,), f"**{k}")
def _backward():
self.grad += k * self.data ** (k - 1) * out.grad
out._backward = _backward
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,), "tanh")
def _backward():
self.grad += (1 - t * t) * out.grad
out._backward = _backward
return out
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
__radd__ = __add__
__rmul__ = __mul__
def backward(self):
order, seen = [], set()
def topo(v): # reverse topological order of the graph
if v not in seen:
seen.add(v)
for p in v._parents: topo(p)
order.append(v)
topo(self)
self.grad = 1.0 # dL/dL = 1
for v in reversed(order):
v._backward()
# The worked example from above: L = (w·x + b − y)²
w, x, b, y = Value(2.0), Value(3.0), Value(1.0), Value(5.0)
L = (w * x + b - y) ** 2
L.backward()
print(L.data, w.grad, x.grad, b.grad) # 4.0 12.0 8.0 4.0 — matches the hand computation
# Train a single tanh neuron to fit y = tanh(2x − 1) with gradient descent
import random
random.seed(0)
data = [(xv, math.tanh(2 * xv - 1)) for xv in [random.uniform(-2, 2) for _ in range(30)]]
w, b = Value(random.uniform(-1, 1)), Value(0.0)
for step in range(300):
loss = sum(((w * xv + b).tanh() - yv) ** 2 for xv, yv in data) * (1 / len(data))
w.grad = b.grad = 0.0 # reset gradients each step
loss.backward()
w.data -= 0.5 * w.grad; b.data -= 0.5 * b.grad
print(round(w.data, 2), round(b.data, 2)) # ≈ 2.0, −1.0
Real frameworks do exactly this on tensors instead of scalars, with hand-written backward rules (vector-Jacobian products) for each operation, GPU kernels, memory optimisations (checkpointing), and graph compilation.
# PyTorch: same example, autograd on tensors
import torch
w = torch.tensor(2.0, requires_grad=True); x = torch.tensor(3.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True); y = torch.tensor(5.0)
L = (w * x + b - y) ** 2
L.backward()
w.grad, x.grad, b.grad # tensor(12.), tensor(8.), tensor(4.)
# JAX: functional autodiff — grad transforms a function into its gradient function
import jax, jax.numpy as jnp
def L(params, x, y):
w, b = params
return (w * x + b - y) ** 2
jax.grad(L)((2.0, 1.0), 3.0, 5.0) # (12.0, 4.0) — gradient w.r.t. params
jax.jacfwd(jnp.sin)(0.0), jax.hessian(lambda z: z**3)(2.0) # forward mode, Hessian: 1.0, 12.0
// Rust: candle (Hugging Face) tensors with autograd
use candle_core::{Device, Var, Tensor};
let dev = Device::Cpu;
let w = Var::new(2.0f32, &dev)?; let b = Var::new(1.0f32, &dev)?;
let (x, y) = (Tensor::new(3.0f32, &dev)?, Tensor::new(5.0f32, &dev)?);
let l = ((w.as_tensor() * &x)? + b.as_tensor())?.sub(&y)?.sqr()?;
let grads = l.backward()?;
grads.get(&w).unwrap().to_scalar::<f32>()?; // 12.0
# Julia: Zygote (source-to-source reverse mode) or ForwardDiff (dual numbers)
using Zygote, ForwardDiff
L(w, b) = (w * 3.0 + b - 5.0)^2
gradient(L, 2.0, 1.0) # (12.0, 4.0)
ForwardDiff.derivative(x -> sin(x)^2, 1.0) # forward mode via dual numbers
Forward mode with dual numbers
Forward-mode AD evaluates functions on dual numbers a + bε with ε² = 0: f(a + ε) = f(a) + f′(a)ε, so the derivative falls out of ordinary arithmetic:
class Dual:
def __init__(self, a, b=0.0): self.a, self.b = a, b # value, derivative
def __add__(s, o): o = o if isinstance(o, Dual) else Dual(o); return Dual(s.a + o.a, s.b + o.b)
def __mul__(s, o): o = o if isinstance(o, Dual) else Dual(o); return Dual(s.a * o.a, s.a * o.b + s.b * o.a)
__radd__, __rmul__ = __add__, __mul__
f = lambda x: 3 * x * x + 2 * x + 1
r = f(Dual(2.0, 1.0)) # seed derivative 1
r.a, r.b # (17.0, 14.0): f(2) = 17, f′(2) = 6·2 + 2 = 14
Gradient problems in deep networks
Calculus also explains failure modes (chapter 151 covers remedies):
- Vanishing gradients: multiplying many local derivatives smaller than 1 (sigmoid's max 0.25, tanh in saturation, recurrent matrices with eigenvalues < 1) shrinks gradients exponentially with depth → early layers stop learning. Remedies: ReLU-family activations, residual connections (gradient highways), normalisation, careful initialisation, LSTMs/gating for RNNs.
- Exploding gradients: products of factors > 1 grow exponentially → NaNs and divergence. Remedies: gradient clipping, normalisation, initialisation, lower learning rates.
- Non-differentiable points (ReLU at 0, max, argmax, sampling): frameworks use subgradients or estimators (straight-through estimator, reparameterisation trick).
- Numerical precision: low-precision formats (fp16) underflow small gradients; mixed precision uses loss scaling (chapter 152, 165).
Lab: derivatives, learning rates and vanishing gradients
PyTorch 2.14.1 on the lab machine's CPU, float64 for the derivative checks and float32 elsewhere.
Experiment 1: autograd versus finite differences
| Method | f′(1.3) | Error |
|---|---|---|
| analytic 3x² − 2 + cos x | 3.3374988286 | — |
| autograd | 3.3374988286 | < 1e-10 |
| central difference, h = 1e-1 | 3.3470532201 | 9.6e-03 |
| h = 1e-4 | 3.3374988382 | 9.6e-09 |
| h = 1e-8 | 3.3374987940 | 3.5e-08 |
| h = 1e-12 | 3.3379410347 | 4.4e-04 |
Central differences have truncation error ∝ h² and rounding error ∝ ε/h (ε ≈ 1e-16 in float64), so the best step is around ε^(1/3) ≈ 1e-5, matching the table's sweet spot. torch.autograd.gradcheck uses exactly this comparison (in float64) to validate custom operations.
Experiment 2: learning rate on an ill-conditioned valley
f(w) = (w₁ − 3)² + 10(w₂ + 1)²; Hessian eigenvalues 2 and 20 (condition number 10); 50 steps from (0, 0):
| Learning rate | w after 50 steps | Loss |
|---|---|---|
| 0.01 | (1.907, −1.000) | 1.24 |
| 0.05 | (2.985, −1.000) | 2.95e-4 |
| 0.09 | (3.000, −1.000) | 3.54e-8 |
| 0.11 | (3.000, 9,099.426) | 5.75e+8 |
For a quadratic, gradient descent converges if the learning rate is below 2/λ_max = 0.1; the slow direction then shrinks by a factor (1 − lr × λ_min) per step. At lr 0.01 that's 0.98 per step (0.98⁵⁰ ≈ 0.36 of the way left, hence w₁ ≈ 1.9); at 0.09 it's 0.82 per step. The w₂ coordinate at 0.11 grew by |1 − 0.11 × 20| = 1.2× per step. The ratio λ_max/λ_min (the condition number) is what makes plain gradient descent slow; momentum and adaptive methods (Adam) help, and normalising inputs (chapter 144) reduces it at the source.
Experiment 3: gradient flow through depth
Mean |∂(sum of outputs)/∂W₁| for stacks of 64-unit layers on a random 64×64 batch:
| Activation / init | depth 2 | depth 10 | depth 30 |
|---|---|---|---|
| sigmoid, PyTorch default | 2.00e-1 | 2.60e-8 | 1.84e-25 |
| ReLU, PyTorch default | 2.51e+0 | 1.26e-3 | 1.01e-11 |
| ReLU, He (Kaiming) normal, zero bias | 6.62e+0 | 1.50e+1 | 5.96e+0 |
PyTorch's default nn.Linear init (uniform with bound 1/√fan_in) is tuned for neither case here, which is why even ReLU decayed with depth. He initialisation draws weights with variance 2/fan_in so that ReLU, which zeroes half its inputs, keeps the signal's variance constant from layer to layer. Plotting per-layer gradient norms during real training (or logging them to TensorBoard or W&B) is the standard diagnostic.
Try it yourself
- Add momentum (β = 0.9) to Experiment 2 and find the largest stable learning rate and the steps needed to reach loss < 1e-6.
- Run Experiment 2 with Adam (
torch.optim.Adam) at lr 0.1 and compare. - Add a residual connection (
h = h + relu(L(h))) to the depth-30 sigmoid stack and remeasure. - Use
torch.autograd.gradcheckto verify a hand-written softmax-cross-entropy function.
Revision sheet: calculus
Key ideas
- Derivative = rate of change; partial derivatives per input; gradient = vector of partials, direction of steepest ascent.
- Chain rule: derivative of a composition = product of local derivatives; backpropagation applies it in reverse through the computational graph.
- Autograd (reverse-mode automatic differentiation): exact gradients for all parameters at about the cost of one extra pass.
- Jacobian (vector → vector derivatives), Hessian (second derivatives, curvature).
- Gradient descent stability: lr < 2/λ_max for quadratics; condition number slows convergence.
- Optimisers: SGD, momentum, Adam/AdamW; learning-rate warm-up and decay.
- Gradient health: vanishing/exploding gradients; fixes: ReLU-family activations, careful initialisation, normalisation, residual connections, gradient clipping.
- Key derivatives: softmax + cross-entropy gradient = p − y.
Numbers to remember
- Lab: best finite-difference step ≈ 1e-5 in float64; h = 1e-12 lost 4 digits.
- Lab: valley with curvatures 2 and 20 diverged above lr 0.1.
- Lab: 30 sigmoid layers → gradient 1.8e-25; ReLU + He init → ≈6.
Pitfalls
- Learning rate tuned on one batch size or model size and reused elsewhere.
- Forgetting to zero gradients between steps (they accumulate in PyTorch).
- Computing gradients through code you meant to treat as constant (use
detach/no_grad). - Sigmoid/tanh in deep stacks without normalisation or residuals.
- Ignoring exploding gradients (use clipping, check norms).
Glossary
- Computational graph: operations recorded for backpropagation.
- Learning-rate schedule: changing the step size over training.
- Gradient clipping: capping the gradient norm.
- Condition number: ratio of largest to smallest curvature.
- He / Xavier initialisation: variance-preserving weight scales for ReLU / tanh.