Backpropagation from scratch¶
Backpropagation computes the gradient of one scalar loss with respect to every weight in a network, for roughly the price of two more forward passes. It is nothing but the chain rule, applied from the output backwards so that every shared sub-result is computed once.
10,000 ft
Training a neural network means nudging millions or billions of parameters downhill on a loss. Gradient descent needs the gradient, and backpropagation is how every network, from a 1989 digit reader to a 2026 frontier LLM, gets it. Before 1986 nobody had a widely known, practical way to train hidden layers (neurons and MLPs); after it, depth became a question of engineering. Backprop is the special case, for neural networks, of reverse-mode automatic differentiation, and its two failure modes, vanishing and exploding gradients, shaped the activations, initialisation schemes and residual connections that modern networks use.
2,000 ft
Run the network forward and keep every intermediate value. At the loss, the gradient with respect to the logits is simply prediction minus target. Walk the layers in reverse: each layer turns the gradient at its output into (a) gradients for its own weights and (b) the gradient at its input, which it hands to the layer below.
- Forward: compute and cache every pre-activation \(\mathbf{z}_\ell\) and activation \(\mathbf{h}_\ell\).
- Seed: \(\boldsymbol{\delta}_L = \partial L/\partial \mathbf{z}_L\), which is \(\mathbf{p} - \mathbf{y}\) for the standard heads.
- Weights: \(\partial L/\partial W_\ell = \boldsymbol{\delta}_\ell\,\mathbf{h}_{\ell-1}^\top\), \(\partial L/\partial \mathbf{b}_\ell = \boldsymbol{\delta}_\ell\).
- Pass down: \(\boldsymbol{\delta}_{\ell-1} = (W_\ell^\top \boldsymbol{\delta}_\ell) \odot \phi'(\mathbf{z}_{\ell-1})\).
- Step: \(W \leftarrow W - \eta\,\partial L/\partial W\) for every layer, then repeat with the next batch.
Ground level¶
The credit-assignment problem¶
A network's output is wrong. Which of its 535,818 weights (the MNIST MLP from the previous page) should change, in which direction, and by how much? The gradient \(\nabla_\theta L\) answers all three at once. The question is how to compute it.
Finite differences perturb each parameter and re-run the network: \(\partial L/\partial\theta_i \approx (L(\theta + \varepsilon\mathbf{e}_i) - L(\theta - \varepsilon\mathbf{e}_i))/2\varepsilon\). That is \(2P\) forward passes for \(P\) parameters: about a million passes for the small MLP and \(1.4 \times 10^{10}\) for a 7-billion-parameter model, per step. It is also numerically fragile. Symbolic differentiation writes out a formula for each partial derivative, but the expressions share enormous common sub-terms and blow up in size. Backpropagation computes all \(P\) partial derivatives exactly (to floating-point precision) in one backward sweep whose cost is a small constant times the forward pass. That gap, a factor of \(P\), is the reason deep learning exists.
The chain rule on a worked example¶
Take a tiny network and push real numbers through it. Input \(\mathbf{x} = (1, 2)\), label \(y = 1\), two hidden ReLU units, one sigmoid output, binary cross-entropy loss:
Forward.
| Quantity | Formula | Value |
|---|---|---|
| \(\mathbf{z}_1\) | \(W_1\mathbf{x} + \mathbf{b}_1\) | \((0.5 - 0.6 - 0.1,\; 0.2 + 0.8 - 0.1) = (-0.2,\; 0.9)\) |
| \(\mathbf{h}\) | \(\operatorname{ReLU}(\mathbf{z}_1)\) | \((0,\; 0.9)\) |
| \(z_2\) | \(\mathbf{w}_2^\top\mathbf{h} + b_2\) | \(0 - 0.54 + 0.05 = -0.49\) |
| \(p\) | \(\sigma(z_2)\) | \(0.3799\) |
| \(L\) | \(-\log p\) | \(0.9679\) |
Backward, one local derivative at a time, each multiplied by the gradient arriving from above:
| Gradient | Rule | Value |
|---|---|---|
| \(\partial L/\partial z_2\) | sigmoid + BCE: \(p - y\) | \(-0.6201\) |
| \(\partial L/\partial \mathbf{w}_2\) | \((\partial L/\partial z_2)\,\mathbf{h}\) | \((0,\; -0.5581)\) |
| \(\partial L/\partial b_2\) | \(\partial L/\partial z_2\) | \(-0.6201\) |
| \(\partial L/\partial \mathbf{h}\) | \((\partial L/\partial z_2)\,\mathbf{w}_2\) | \((-0.4341,\; 0.3721)\) |
| \(\partial L/\partial \mathbf{z}_1\) | \(\partial L/\partial\mathbf{h} \odot [\mathbf{z}_1 > 0]\) | \((0,\; 0.3721)\) |
| \(\partial L/\partial W_1\) | \((\partial L/\partial\mathbf{z}_1)\,\mathbf{x}^\top\) | \(\begin{pmatrix} 0 & 0 \\ 0.3721 & 0.7441 \end{pmatrix}\) |
Read the table as a story. The prediction is too low (\(p = 0.38\), target 1), so the logit gradient is negative: raise \(z_2\). Hidden unit 2 is active and has weight \(-0.6\), so the network wants its activation lower (positive gradient \(0.3721\) on \(h_2\); descent subtracts it). Hidden unit 1 is switched off (\(z = -0.2\)): the ReLU gate blocks its gradient entirely, so neither its incoming weights nor its outgoing weight learn from this example, the seed of the "dead ReLU" problem on the activations page. A centred finite difference on \(W_1[1,0]\) gives \(0.372064\), matching backprop to six digits, and one gradient step with learning rate 0.5 drops the loss from 0.9679 to 0.5292. All of this is the first snippet in Build it.
Gates: the local rules you need to remember¶
Every operation in a network is a small "gate" that knows only its own local derivative. In the backward pass it receives \(\bar{o} = \partial L/\partial o\) for its output \(o\) and returns gradients for its inputs. Five gates explain almost every gradient you will ever trace by hand:
| Gate | Forward | Backward (given \(\bar o\)) | Intuition |
|---|---|---|---|
| add | \(o = a + b\) | \(\bar a = \bar o,\; \bar b = \bar o\) | distributes the gradient unchanged |
| multiply | \(o = ab\) | \(\bar a = b\,\bar o,\; \bar b = a\,\bar o\) | swaps the inputs |
| max / ReLU | \(o = \max(a, b)\) | the larger input gets \(\bar o\), the other 0 | routes |
| copy (fan-out) | \(a\) used by \(o_1, o_2\) | \(\bar a = \bar o_1 + \bar o_2\) | gradients from every use sum |
| matmul | \(O = AB\) | \(\bar A = \bar O B^\top,\; \bar B = A^\top \bar O\) | the only arrangement whose shapes fit |
The add gate is why residual connections help: a skip path \(\mathbf{y} = \mathbf{x} + f(\mathbf{x})\) hands the gradient straight through to \(\mathbf{x}\), untouched by \(f\) (residual networks). The multiply gate is why input scale matters: the gradient on a weight is proportional to the input it multiplies, so un-normalised features with large values get large updates (feature engineering). The fan-out rule is the one people forget when they write backprop by hand: a weight shared across time steps or positions (an RNN, a convolution, a tied embedding) accumulates gradient from every place it is used.
From scalars to layers¶
Doing this one scalar at a time is how you understand it; doing it a layer at a time is how you implement it. For a layer \(\mathbf{z} = W\mathbf{h} + \mathbf{b}\) with \(W \in \mathbb{R}^{m \times n}\), write \(\boldsymbol{\delta} = \partial L/\partial\mathbf{z} \in \mathbb{R}^m\) (the "error" at that layer). Then:
and through the elementwise nonlinearity \(\mathbf{h} = \phi(\mathbf{z}')\), \(\partial L/\partial\mathbf{z}' = (\partial L/\partial\mathbf{h}) \odot \phi'(\mathbf{z}')\).
With a batch in row convention, \(Z = HW + \mathbf{b}\) with \(H \in \mathbb{R}^{B \times n}\) and \(W \in \mathbb{R}^{n \times m}\), the same equations become \(\partial L/\partial W = H^\top\Delta\), \(\partial L/\partial\mathbf{b} = \sum_{\text{rows}} \Delta\), \(\partial L/\partial H = \Delta W^\top\), where \(\Delta \in \mathbb{R}^{B \times m}\). If the loss is a batch mean, \(\Delta\) already contains the \(1/B\); the weight gradient is a sum over examples of per-example outer products, which is why bigger batches give less noisy gradients.
The shape trick
You rarely need to derive a matrix gradient. The gradient of a parameter always has the parameter's shape, and for a matmul there is exactly one way to combine the incoming gradient and the cached input that produces that shape. \(W\) is \(n \times m\), \(H\) is \(B \times n\), \(\Delta\) is \(B \times m\): the only product giving \(n \times m\) is \(H^\top\Delta\). Karpathy's "Becoming a backprop ninja" lecture drills this until it is reflex.
Why backwards? The order of a matrix product¶
Stack the layer Jacobians. For \(L(\mathbf{z}_3(\mathbf{z}_2(\mathbf{z}_1(\theta))))\) the chain rule says
Matrix multiplication is associative, so the answer is the same in any order, but the cost is not. Left to right, every intermediate is a \(1 \times (\cdot)\) row vector: each step is a vector–Jacobian product costing about as much as the layer's forward pass. Right to left, every intermediate is a \(d \times P\) matrix, which is forward-mode differentiation and costs \(P\) times more. Because the loss is a single number and the parameters are many, going from the loss backwards is the cheap order. That is the whole reason it is called backpropagation, and the autodiff page generalises it to any program.
Two consequences follow. First, you never build a Jacobian. The Jacobian of ReLU on a 4096-vector is a \(4096 \times 4096\) diagonal matrix; backprop multiplies by its diagonal elementwise instead. Second, the cost is fixed: each matmul in the forward pass becomes two matmuls of the same size in the backward pass (one for \(\bar A\), one for \(\bar B\)), so backward costs about twice the forward, and a training step about three times. With forward at about \(2\) FLOPs per parameter per example, training costs about 6 FLOPs per parameter per token, the constant behind every compute budget.
The price: memory¶
The backward pass needs the forward pass's intermediates: \(\partial L/\partial W_\ell\) needs \(\mathbf{h}_{\ell-1}\), and the ReLU gate needs \(\mathbf{z}_\ell\). So training memory grows with depth × batch size × width, and for large models the stored activations often outweigh the weights. The standard escape is gradient checkpointing (Chen et al., 2016): store activations only at every \(\sqrt{n}\)-th layer of an \(n\)-layer network and recompute the rest during the backward pass. Memory drops to \(O(\sqrt{n})\) for the price of roughly one extra forward pass. Every large-model training stack uses some form of it (distributed training).
Vanishing and exploding gradients¶
Look at the recursion \(\boldsymbol{\delta}_{\ell-1} = (W_\ell^\top\boldsymbol{\delta}_\ell) \odot \phi'(\mathbf{z}_{\ell-1})\). Through \(L\) layers the gradient at the bottom is a product of \(L\) factors, each "weight matrix times activation derivative". Products of many numbers either shrink to zero or blow up unless each factor is very close to 1 in size.
The sigmoid's derivative is at most \(\sigma'(0) = 0.25\). Ignore the weights and you get a best case of \(0.25^{10} \approx 9.5 \times 10^{-7}\) after ten layers and \(0.25^{20} \approx 9.1 \times 10^{-13}\) after twenty. The bottom layers of a deep sigmoid network barely learn at all. Sepp Hochreiter's 1991 diploma thesis analysed this, and Bengio, Simard and Frasconi (1994) showed why it makes long-range dependencies hard for recurrent networks, which are deep in time. The opposite failure, gradients that grow geometrically, makes training diverge in a single step (Pascanu, Mikolov and Bengio, 2013, for RNNs).
The cures are the subject of the next three pages of this track: non-saturating activations (ReLU and friends), weights scaled so each factor has size about 1 (initialisation), normalisation layers that re-centre the signal, and residual connections that give the gradient an additive express lane (residual networks). Gradient clipping is the blunt instrument for the exploding side (training recipe).
Checking your gradients¶
Every hand-written backward pass should be checked numerically before you trust it. Use the centred difference with \(\varepsilon \approx 10^{-5}\) in float64 and compare by relative error:
Rules of thumb from the CS231n notes: below \(10^{-7}\) is right; around \(10^{-4}\) is suspicious unless the function has kinks (ReLU, max) near the test point; above \(10^{-2}\) is a bug. The full training run in Build it checks all four parameter tensors and gets errors below \(10^{-9}\). Check with a tiny network, a few examples, and no dropout or other randomness.
Classic backprop bugs
Forgetting to sum gradients over the batch or over shared uses; forgetting the \(1/B\) of a mean loss (gradients \(B\) times too large); using the post-activation \(\mathbf{h}\) where the pre-activation \(\mathbf{z}\) is needed in \(\phi'\); not zeroing accumulated gradients between steps (PyTorch's .grad accumulates by design); and applying softmax before a loss that expects logits, which squashes the gradient and costs numerical stability.
History¶
Invented several times, popularised once
The idea of propagating derivatives backwards through a chain of computations appeared in optimal control around 1960–61 (Kelley; Bryson), in Stuart Dreyfus's 1962 work and, in general form for any computer program built from elementary operations, in Seppo Linnainmaa's 1970 master's thesis, which is reverse-mode automatic differentiation. Bert Speelpenning's 1980 thesis implemented it as a program that differentiates other programs automatically. Paul Werbos discussed neural networks briefly in his 1974 Harvard PhD thesis and described the first neural-network-specific application of efficient backpropagation in 1982. David Parker and Yann LeCun reached it independently in the mid-1980s. In 1986, David Rumelhart, Geoffrey Hinton and Ronald Williams published Learning representations by back-propagating errors in Nature; its contribution was not the algorithm's novelty but the demonstration that hidden units learn meaningful internal representations, and it launched the second neural-network boom. Andreas Griewank's essay and Jürgen Schmidhuber's survey (both in Go deeper) document the priority story; the history track tells the wider one.
First principles¶
Why the chain rule decomposes the problem. A network is a composition of functions. The derivative of a composition is the product of derivatives (in several variables, the product of Jacobians: see the multivariable chain rule). So the global gradient can be assembled from local derivatives, each of which only needs to know one small operation.
Why sharing makes it cheap. Draw the network as a graph. The partial derivative \(\partial L/\partial v\) for any node \(v\) is the sum over every path from \(v\) to \(L\) of the product of the edge derivatives along it. In a deep, densely connected network the number of paths grows exponentially with depth, so summing them naively is hopeless. But every path from \(v\) to \(L\) passes through one of \(v\)'s children \(c\), which gives the recursion
If you process nodes in reverse topological order, each \(\partial L/\partial c\) is already known when you need it. This is dynamic programming: the exponential sum over paths is factored so each edge is touched once. (The forward algorithm for hidden Markov models and the Viterbi algorithm are the same trick on a different graph.)
Why the cost is a constant factor. Each edge contributes one multiply-add in the backward pass, and each node in the forward pass did comparable work, so the backward pass costs a constant multiple of the forward pass, independent of the number of parameters. Baur and Strassen (1983) proved this "cheap gradient principle" for arithmetic circuits: all partial derivatives of a function cost at most a small constant factor more than the function itself.
Why reverse rather than forward. Forward-mode differentiation propagates \(\partial(\text{node})/\partial\theta_i\) for one input \(\theta_i\) at a time: \(P\) sweeps for \(P\) parameters. Reverse mode propagates \(\partial L/\partial(\text{node})\) for one output: one sweep, whatever \(P\) is. Neural network training has one output (the loss) and many inputs (the weights), so reverse mode wins by a factor of \(P\). If you had one input and many outputs, forward mode would win (autodiff).
What it needs from the network. Every operation must have a usable derivative almost everywhere. Step functions have zero derivative almost everywhere, which is why the perceptron's step activation had to be replaced by smooth or piecewise-linear ones before hidden layers could be trained. Non-differentiable points such as ReLU at 0 are handled by picking a subgradient (frameworks use 0); they are a set of measure zero and almost never matter.
Is the brain doing backprop?
Probably not literally. Backprop requires the backward pass to use the transpose of the forward weights (the "weight transport problem") and a separate backward phase. Lillicrap et al. (2016) showed that fixed random feedback weights still let networks learn ("feedback alignment"), reopening the question of what learning rule a brain could implement. It is an active research area; see brains and machines.
The maths¶
Setting. Layers \(\ell = 1, \dots, L\); \(\mathbf{h}_0 = \mathbf{x}\); \(\mathbf{z}_\ell = W_\ell\mathbf{h}_{\ell-1} + \mathbf{b}_\ell\) with \(W_\ell \in \mathbb{R}^{d_\ell \times d_{\ell-1}}\); \(\mathbf{h}_\ell = \phi(\mathbf{z}_\ell)\) for \(\ell < L\); loss \(\mathcal{L}(\mathbf{z}_L, y)\). Define the error \(\boldsymbol{\delta}_\ell = \partial\mathcal{L}/\partial\mathbf{z}_\ell \in \mathbb{R}^{d_\ell}\) (a column vector, the gradient, i.e. the transposed row Jacobian).
The four backpropagation equations.
Derivation of BP2 and BP4 in index notation
BP4. Component \(i\) of layer \(\ell\) is \(z_{\ell,i} = \sum_j W_{\ell,ij}\,h_{\ell-1,j} + b_{\ell,i}\). The weight \(W_{\ell,ij}\) affects the loss only through \(z_{\ell,i}\), so
which is entry \((i, j)\) of the outer product \(\boldsymbol{\delta}_\ell\mathbf{h}_{\ell-1}^\top\). BP3 is the same with \(\partial z_{\ell,i}/\partial b_{\ell,i} = 1\).
BP2. \(z_{\ell,j}\) affects the loss through \(h_{\ell,j} = \phi(z_{\ell,j})\), which in turn feeds every \(z_{\ell+1,i}\) (fan-out, so we sum):
and \(\sum_i W_{\ell+1,ij}\delta_{\ell+1,i} = (W_{\ell+1}^\top\boldsymbol{\delta}_{\ell+1})_j\).
Derivation of BP1 for softmax with cross-entropy: δ = p − e_y
With logits \(\mathbf{z} \in \mathbb{R}^K\), \(p_k = e^{z_k}/\sum_j e^{z_j}\) and \(\mathcal{L} = -\log p_y\):
So \(\boldsymbol{\delta}_L = \mathbf{p} - \mathbf{e}_y\). For the sigmoid with binary cross-entropy, \(\mathcal{L} = -y\log\sigma(z) - (1-y)\log(1 - \sigma(z))\) and \(\sigma' = \sigma(1-\sigma)\) give \(\partial\mathcal{L}/\partial z = \sigma(z) - y\). For identity output with \(\tfrac12(\hat y - y)^2\), it is \(\hat y - y\). Notice that the softmax Jacobian, a full \(K \times K\) matrix \(\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top\), never has to be formed: fusing it with the loss collapses it to a subtraction.
Batched form. Rows are examples: \(H_{\ell-1} \in \mathbb{R}^{B \times d_{\ell-1}}\), \(Z_\ell = H_{\ell-1}W_\ell^\top + \mathbf{1}\mathbf{b}_\ell^\top\), \(\Delta_\ell \in \mathbb{R}^{B \times d_\ell}\) (row \(n\) is \(\boldsymbol{\delta}_\ell\) for example \(n\), including the \(1/B\) of a mean loss). Then
(The NumPy code below stores \(W\) as \(d_{\ell-1} \times d_\ell\), so its weight gradient is \(H^\top\Delta\); same maths, transposed storage.)
Cost. Forward matmul \((B \times n)(n \times m)\): \(2Bnm\) FLOPs. Backward: \(\Delta W^\top\)-type product for the input gradient (\(2Bnm\)) and \(H^\top\Delta\) for the weight gradient (\(2Bnm\)). Elementwise terms are \(O(Bm)\). Total per step \(\approx 3 \times\) forward.
Vanishing and exploding, formally. \(\boldsymbol{\delta}_1 = \Big(\prod_{\ell=1}^{L-1} D_\ell W_{\ell+1}^\top\Big)\boldsymbol{\delta}_L\) with \(D_\ell = \operatorname{diag}(\phi'(\mathbf{z}_\ell))\). Its norm is bounded by \(\prod_\ell \lVert D_\ell\rVert\,\lVert W_{\ell+1}\rVert\). If each factor's typical gain is \(g\), the gradient scales like \(g^{L}\): stable training needs \(g \approx 1\), which is precisely what variance-preserving initialisation arranges (initialisation).
Build it¶
NumPy only. First, the worked example from Ground level, every number reproduced:
import numpy as np
np.set_printoptions(precision=4, suppress=True)
x = np.array([1.0, 2.0]); y = 1.0
W1 = np.array([[0.5, -0.3],
[0.2, 0.4]]); b1 = np.array([-0.1, -0.1])
w2 = np.array([0.7, -0.6]); b2 = 0.05
def forward(W1, b1, w2, b2):
z1 = W1 @ x + b1 # (2,) pre-activations
h = np.maximum(z1, 0) # ReLU
z2 = w2 @ h + b2 # scalar logit
p = 1 / (1 + np.exp(-z2)) # sigmoid
L = -(y*np.log(p) + (1-y)*np.log(1-p))
return z1, h, z2, p, L
z1, h, z2, p, L = forward(W1, b1, w2, b2)
print("z1", z1, " h", h, f" z2 {z2:.4f} p {p:.4f} L {L:.4f}")
# backward, one local derivative at a time
dz2 = p - y # sigmoid + BCE
dw2 = dz2 * h + 0.0; db2 = dz2 # + 0.0 prints -0.0 as 0.0
dh = dz2 * w2
dz1 = dh * (z1 > 0) + 0.0 # ReLU gate
dW1 = np.outer(dz1, x); db1 = dz1
print(f"dz2 {dz2:.4f} dw2 {dw2} dh {dh} dz1 {dz1}")
print("dW1\n", dW1)
# check one entry with a centred finite difference
eps = 1e-6; E = np.zeros_like(W1); E[1, 0] = eps
num = (forward(W1+E, b1, w2, b2)[-1] - forward(W1-E, b1, w2, b2)[-1]) / (2*eps)
print(f"dL/dW1[1,0]: backprop {dW1[1,0]:.6f} numeric {num:.6f}")
# one gradient step
lr = 0.5
L_new = forward(W1 - lr*dW1, b1 - lr*db1, w2 - lr*dw2, b2 - lr*db2)[-1]
print(f"loss before {L:.4f} after one step {L_new:.4f}")
z1 [-0.2 0.9] h [0. 0.9] z2 -0.4900 p 0.3799 L 0.9679
dz2 -0.6201 dw2 [ 0. -0.5581] dh [-0.4341 0.3721] dz1 [0. 0.3721]
dW1
[[0. 0. ]
[0.3721 0.7441]]
dL/dW1[1,0]: backprop 0.372064 numeric 0.372064
loss before 0.9679 after one step 0.5292
Now a real network: a 2–64–3 MLP on three interleaved spirals (not linearly separable), softmax cross-entropy, batched backprop, a gradient check on every parameter tensor, then full-batch gradient descent.
import numpy as np
rng = np.random.default_rng(0)
# three interleaved spirals: 300 points, 3 classes (not linearly separable)
N, K = 100, 3
X = np.zeros((N*K, 2)); y = np.repeat(np.arange(K), N)
for k in range(K):
r = np.linspace(0.05, 1, N); t = np.linspace(4*k, 4*k + 4, N) + rng.normal(0, 0.2, N)
X[k*N:(k+1)*N] = np.c_[r*np.sin(t), r*np.cos(t)]
def init(d=2, m=64, k=3):
return {"W1": rng.normal(0, np.sqrt(2/d), (d, m)), "b1": np.zeros(m),
"W2": rng.normal(0, np.sqrt(1/m), (m, k)), "b2": np.zeros(k)}
def loss_and_grads(P, X, y):
B = len(X)
Z1 = X @ P["W1"] + P["b1"] # (B, m)
H = np.maximum(Z1, 0) # (B, m)
Z2 = H @ P["W2"] + P["b2"] # (B, k) logits
Z2 = Z2 - Z2.max(1, keepdims=True) # stable softmax
Pr = np.exp(Z2); Pr /= Pr.sum(1, keepdims=True)
L = -np.log(Pr[np.arange(B), y]).mean()
dZ2 = Pr.copy(); dZ2[np.arange(B), y] -= 1; dZ2 /= B # (p - onehot)/B
dW2 = H.T @ dZ2; db2 = dZ2.sum(0)
dH = dZ2 @ P["W2"].T # (B, m)
dZ1 = dH * (Z1 > 0)
dW1 = X.T @ dZ1; db1 = dZ1.sum(0)
return L, {"W1": dW1, "b1": db1, "W2": dW2, "b2": db2}
P = init()
_, G = loss_and_grads(P, X, y)
for name in P: # gradient check, 5 random entries each
errs = []
for _ in range(5):
i = tuple(rng.integers(s) for s in P[name].shape); old = P[name][i]
P[name][i] = old + 1e-5; Lp, _ = loss_and_grads(P, X, y)
P[name][i] = old - 1e-5; Lm, _ = loss_and_grads(P, X, y)
P[name][i] = old; num = (Lp - Lm) / 2e-5
errs.append(abs(num - G[name][i]) / max(1e-12, abs(num) + abs(G[name][i])))
print(f"grad check {name}: max relative error {max(errs):.1e}")
for step in range(3001): # full-batch gradient descent
L, G = loss_and_grads(P, X, y)
if step % 1000 == 0:
acc = ((np.maximum(X @ P["W1"] + P["b1"], 0) @ P["W2"] + P["b2"]).argmax(1) == y).mean()
print(f"step {step:4d} loss {L:.3f} train accuracy {acc:.1%}")
for name in P: P[name] -= 1.0 * G[name]
grad check W1: max relative error 7.3e-10
grad check b1: max relative error 6.9e-10
grad check W2: max relative error 5.2e-10
grad check b2: max relative error 2.0e-10
step 0 loss 1.045 train accuracy 28.7%
step 1000 loss 0.018 train accuracy 100.0%
step 2000 loss 0.008 train accuracy 100.0%
step 3000 loss 0.005 train accuracy 100.0%
Training accuracy of 100% on 300 points says nothing about generalisation; hold out a test split before you believe it (evaluation).
Things to try
- Break the backward pass on purpose (drop the
/ B, useH > 0instead ofZ1 > 0, forget.sum(0)on a bias) and watch the gradient check catch each bug. - Add a second hidden layer. You only need to repeat the three lines
dW = H.T @ dZ,dH = dZ @ W.T,dZ = dH * (Z > 0). - Swap ReLU for sigmoid in both layers and stack five hidden layers. Print the norm of
dWfor each layer after one backward pass: the bottom layer's gradient is orders of magnitude smaller. - Replace full-batch descent with minibatches of 32 and compare the loss curves: noisier, but often faster per unit of compute (optimisers).
- Port the code to PyTorch (
loss.backward()) and assert thatW1.gradmatches yourdW1to 1e-6.
Check yourself¶
Why does backpropagation go from the loss to the inputs rather than the other way round?
The gradient is a product of Jacobians. The loss is a scalar, so starting from it every intermediate is a row vector and each step is a cheap vector–Jacobian product. Starting from the parameters, every intermediate is a matrix with one column per parameter, which is \(P\) times more work. Reverse order wins whenever there are few outputs and many inputs.
A weight is used in three places in the forward pass. What is its gradient?
The sum of the three gradients it would get from each use separately (the fan-out rule). This is why convolution kernels, RNN weights and tied embeddings accumulate gradient across all positions or time steps.
In the worked example, hidden unit 1 had z = −0.2. What happens to the gradients of its incoming weights, and why could that become a problem?
They are exactly zero: the ReLU gate passes no gradient when its input is negative. If a unit's pre-activation is negative for every training example (for example after a large update pushes its bias very negative), it never receives gradient again: a dead ReLU. Leaky ReLU, GELU and careful initialisation reduce the risk (activations).
Why is the gradient of softmax followed by cross-entropy simply p − y, and why should you never compute the two separately?
Writing the loss as \(-z_y + \log\sum_j e^{z_j}\) and differentiating gives \(p_k - [k=y]\) directly. Computing softmax first and then \(\log\) of a tiny probability loses precision (and \(\log 0 = -\infty\)), and backpropagating through the separate softmax Jacobian is extra work. The fused log-sum-exp form is both exact and stable.
Roughly how many FLOPs does one training step of a 1-billion-parameter model on a batch of 1 million tokens cost?
About \(6 \times 10^9 \times 10^6 = 6 \times 10^{15}\) FLOPs: 2 per parameter per token forward, 4 backward. On hardware sustaining \(4 \times 10^{14}\) FLOP/s that is 15 seconds (compute maths).
Your gradient check reports relative error 3 × 10⁻³ on a ReLU network. Bug or not?
Possibly not. Near a ReLU kink the finite difference straddles the non-differentiable point and the numeric estimate is wrong. Check which entries fail, whether the corresponding pre-activations are within \(\varepsilon\) of 0, and rerun with a different random input or smaller \(\varepsilon\). If errors of that size persist everywhere, it is a bug.
Hard: why do activations, not weights, dominate memory when training large models, and what does gradient checkpointing trade?
Weights scale with width² × depth but are stored once; activations scale with batch × sequence length × width × depth and must be kept for every example in flight until the backward pass uses them. Checkpointing keeps only a subset (e.g. every \(\sqrt{n}\)-th layer's input) and recomputes the rest during backward, trading about one extra forward pass (≈ 33% more compute) for memory that grows like \(\sqrt{n}\) instead of \(n\).
Hard: a network has only one parameter but a million outputs, and you want all their derivatives. Which mode of differentiation should you use?
Forward mode. It propagates \(\partial(\cdot)/\partial\theta\) alongside the computation and gets all one million output derivatives in one sweep; reverse mode would need one backward sweep per output. Backprop is the right tool only because training has the opposite shape.
Go deeper¶
Papers
- Learning representations by back-propagating errors — Rumelhart, Hinton and Williams, 1986. Four pages. Read it for the hidden-representation results, which are what convinced the field.
- Who invented the reverse mode of differentiation? — Andreas Griewank, 2012. A short, first-hand history from the leading AD researcher.
- Efficient BackProp — LeCun, Bottou, Orr and Müller, 1998. Practical tricks (input normalisation, initialisation, learning rates) that remain correct; sections 4 and 5.
- Learning long-term dependencies with gradient descent is difficult — Bengio, Simard and Frasconi, 1994. The vanishing-gradient problem stated for recurrent nets.
- On the difficulty of training recurrent neural networks — Pascanu, Mikolov and Bengio, 2013. Exploding gradients analysed, gradient clipping justified.
- Training deep nets with sublinear memory cost — Chen et al., 2016. Gradient checkpointing.
- Random synaptic feedback weights support error backpropagation for deep learning — Lillicrap et al., 2016. Feedback alignment and the biological-plausibility question.
Videos and lectures
- The spelled-out intro to neural networks and backpropagation: building micrograd — Andrej Karpathy. Two and a half hours that build a scalar autograd engine from nothing. The single best way to learn this page.
- Building makemore Part 4: Becoming a Backprop Ninja — Andrej Karpathy. Manual tensor-level backprop through cross-entropy, batch norm and an MLP; the shape trick in action.
- Backpropagation, intuitively and Backpropagation calculus — 3Blue1Brown, Deep Learning chapters 3–4. The picture, then the chain rule, beautifully animated.
Articles and blog posts
- Calculus on computational graphs: backpropagation — Christopher Olah, 2015. The sum-over-paths view and why reverse mode factorises it.
- Yes you should understand backprop — Andrej Karpathy, 2016. Backprop as a leaky abstraction: saturated sigmoids, dead ReLUs, exploding RNN gradients.
- CS231n: Backpropagation, intuitions — Stanford. Gates, patterns in backward flow and vectorised gradients.
- How the backpropagation algorithm works — Michael Nielsen. The four equations BP1–BP4 with proofs.
- The Matrix Calculus You Need For Deep Learning — Terence Parr and Jeremy Howard. Jacobians and vector chain rules for practitioners.
- Who invented backpropagation? — Jürgen Schmidhuber. A partisan but thoroughly referenced priority history.
Courses and books
- Deep Learning — Goodfellow, Bengio and Courville. Section 6.5, back-propagation and other differentiation algorithms, with the general graph algorithm.
Code
- karpathy/micrograd — About 150 lines of Python: the whole idea, small enough to read in a sitting. Rebuild it in the micrograd project.
Where this leads¶
- Automatic differentiation and computation graphs — backprop generalised to any program, and how PyTorch and JAX implement it.
- Activation functions — the \(\phi'\) in BP2, and why its shape decides whether deep networks train.
- Initialisation and normalisation — keeping the product of layer gains near 1.
- Optimisers — what to do with the gradient once you have it.
- Project: build micrograd — write your own engine and train a network with it.