Backpropagation
How neural networks compute gradients — computational graphs, the chain rule applied backwards, a worked numeric example, vectorised backprop for layers, automatic differentiation (reverse mode) in PyTorch, a tiny autograd engine, and vanishing/exploding gradients.
To train with gradient descent, we need the gradient of the loss with respect to every weight — millions or billions of them. Computing each separately would be hopeless. Backpropagation computes all of them in one backward pass, at roughly the cost of a forward pass, by applying the chain rule systematically from the output back to the inputs.
Computational graphs
Any computation can be written as a graph of simple operations. For :
Forward pass: compute values left to right: u = wx = 6, z = u + b = 7, e = z − y = −3, L = e² = 9.
The backward pass
Start at the output with and move right to left. At each node, multiply the incoming gradient (the upstream gradient) by the node's local derivative — the chain rule:
| Node | Local derivative | Gradient of L |
|---|---|---|
| L = e² | ∂L/∂e = 2e = −6 | ∂L/∂e = −6 |
| e = z − y | ∂e/∂z = 1 | ∂L/∂z = −6 × 1 = −6 |
| z = u + b | ∂z/∂u = 1, ∂z/∂b = 1 | ∂L/∂u = −6, ∂L/∂b = −6 |
| u = w·x | ∂u/∂w = x = 3, ∂u/∂x = w = 2 | ∂L/∂w = −6 × 3 = −18, ∂L/∂x = −12 |
The gradient says: increasing w increases L at rate −18 — i.e. increasing w decreases the loss. A gradient step with η = 0.01 gives w = 2 + 0.18 = 2.18, moving the prediction from 7 toward the target 10.
Patterns worth remembering:
- Addition distributes the upstream gradient unchanged to all inputs.
- Multiplication sends each input the upstream gradient times the other input.
- When a value feeds several nodes, its gradients from each path are summed.
Why "reverse mode" is efficient
The network has one scalar output (the loss) and many inputs (parameters). Going backwards from that single output, one pass yields the gradient for all parameters simultaneously, reusing intermediate results — dynamic programming over the graph. (Forward-mode differentiation would need one pass per parameter.) The cost: forward activations must be stored for the backward pass, which is why training needs much more memory than inference.
Backprop through a layer
For a dense layer , , given the upstream gradient :
The last term becomes the upstream gradient for the previous layer. Backprop is just these matrix multiplications, layer after layer — the same GPU-friendly operations as the forward pass.
import numpy as np
def relu(z): return np.maximum(0, z)
# Two-layer network, one batch: X (n×d), y (n×1)
def train_step(X, y, W1, b1, W2, b2, lr=1e-2):
# forward
z1 = X @ W1 + b1; a1 = relu(z1)
pred = a1 @ W2 + b2
loss = ((pred - y) ** 2).mean()
# backward
n = len(X)
d_pred = 2 * (pred - y) / n # ∂L/∂pred
dW2 = a1.T @ d_pred; db2 = d_pred.sum(0)
d_a1 = d_pred @ W2.T # pass gradient to the previous layer
d_z1 = d_a1 * (z1 > 0) # ReLU derivative
dW1 = X.T @ d_z1; db1 = d_z1.sum(0)
# update
for p, g in ((W1, dW1), (b1, db1), (W2, dW2), (b2, db2)):
p -= lr * g
return lossAutomatic differentiation
Nobody writes backward passes by hand any more. Frameworks — PyTorch, JAX, TensorFlow — record the operations of the forward pass into a graph and apply each operation's known derivative in reverse:
import torch
w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)
x, y = torch.tensor(3.0), torch.tensor(10.0)
L = (w * x + b - y) ** 2
L.backward() # reverse-mode autodiff through the recorded graph
print(w.grad, b.grad) # tensor(-18.) tensor(-6.) — matches the table aboveA tiny autograd engine
The core idea fits in a few dozen lines (in the spirit of Karpathy's micrograd):
class Value:
def __init__(self, data, parents=(), backward=lambda: None):
self.data, self.grad = data, 0.0
self._parents, self._backward = parents, backward
def __add__(self, other):
out = Value(self.data + other.data, (self, other))
def backward():
self.grad += out.grad # addition passes the gradient through
other.grad += out.grad
out._backward = backward
return out
def __mul__(self, other):
out = Value(self.data * other.data, (self, other))
def backward():
self.grad += other.data * out.grad # times the other input
other.grad += self.data * out.grad
out._backward = backward
return out
def backward(self):
order, seen = [], set()
def visit(v): # topological sort
if v not in seen:
seen.add(v)
for p in v._parents: visit(p)
order.append(v)
visit(self)
self.grad = 1.0
for v in reversed(order): # apply the chain rule in reverse order
v._backward()Vanishing and exploding gradients
Backprop multiplies many local derivatives together. In deep networks:
- If they're mostly < 1 (e.g. sigmoid's derivative is at most 0.25), gradients shrink exponentially toward the early layers — vanishing gradients: early layers barely learn.
- If they're mostly > 1, gradients grow exponentially — exploding gradients: unstable updates, NaN losses.
This plagued early deep networks and plain RNNs (RNNs). The fixes are now standard:
| Fix | How it helps |
|---|---|
| ReLU-family activations | Derivative 1 for positive inputs — no shrinking |
| He / Xavier initialisation | Keeps signal variance roughly constant across layers |
| Normalisation layers | Keep activations in a healthy range |
| Residual connections | The identity path passes gradients through unchanged |
| LSTM/GRU gating | Additive memory paths for sequences |
| Gradient clipping | Caps exploding gradient norms |
Memory and compute tricks
- Gradient checkpointing: store only some activations and recompute the rest during the backward pass — trades compute for memory.
- Mixed precision (bf16/fp16 with fp32 master weights): halves memory and speeds up GPU math.
- Gradient accumulation: sum gradients over several small batches before an update to simulate a larger batch.
- Backpropagation is the chain rule applied backwards through a computational graph.
- One backward pass gives the gradient for every parameter at roughly the cost of the forward pass (reverse-mode autodiff).
- Add nodes pass gradients through; multiply nodes scale by the other input; branches sum.
- For dense layers, backprop is matrix multiplications: dW = δ xᵀ, dx = Wᵀ δ.
- Frameworks record the forward graph and differentiate automatically.
- Deep products of derivatives cause vanishing or exploding gradients; ReLU, good initialisation, normalisation, residuals and clipping fix them.
QExplain backpropagation in simple terms.medium
The network computes a loss through a chain of simple operations. Backpropagation walks that chain in reverse: starting from the loss, it uses each operation's local derivative and the chain rule to work out how much each intermediate value — and ultimately each weight — contributed to the error. Because intermediate results are reused, one backward pass gives gradients for all weights at about the cost of a forward pass; the optimiser then nudges every weight in the direction that reduces the loss.