Backpropagation: the chain rule applied to a network
Derive reverse-mode backpropagation for computational graphs and batched layers, then count operations, estimate activation memory and check manual gradients.
After this lesson you can
- Perform forward and backward passes on a scalar computational graph, accumulating gradients at branches.
- Derive the layerwise error recursion and combine it with batched linear-layer gradients for an MLP.
- Count forward and backward FLOPs and justify the approximate six-FLOP rule per weight and example.
- Estimate activation memory as a function of batch size, width and depth.
- Implement manual MLP backpropagation in NumPy and verify it with gradient checking.
Before you start
- 15Forward propagationMultilayer perceptronLogitsOutput layer and loss pairingBatch shape conventionRectified linear unit
- 03Multivariable chain ruleJacobian matrix
- 09Reverse-mode automatic differentiationCheap gradient principleGradient checkingMemory cost of reverse mode
- 02Linear layer gradientsMatrix chain rule
One derivative per parameter
A network can have millions of parameters and a single loss. Computing one derivative per parameter by separate perturbations would repeat the forward pass millions of times. Backpropagation traverses the graph in reverse order and shares work across all those derivatives. It is reverse-mode automatic differentiation applied to network structure.
For , , and , local derivatives give
The first term of arrives through and the second through . In a general graph, if a variable feeds multiple nodes, sum contributions from all its uses rather than overwriting the first. At , ReLU has no ordinary derivative; a system may set a local convention, zero here, but that does not prove every composition containing it is necessarily nondifferentiable.
A layer as a block
For and scalar loss , write . The linear-layer gradients are
With and , all three resulting shapes match their respective arguments. This is a vector-Jacobian product: there is no need to construct the Jacobian of all inputs and outputs. The matrix chain rule gives the same formulas as summing contributions by index.
To see where each term comes from, . Holding other arguments fixed, . Thus : this is entry of . The same bias appears in all examples, so its gradient sums over . Finally, , entry of . These sums show why weights are shared across examples and why backward accumulates their contributions.
In an MLP, and . The error signal propagates from the output through
Multiplication by aggregates the effect of each unit in the next layer; applies the activation’s local derivative componentwise. The formula assumes elementwise activations; an intermediate softmax needs its full vector-Jacobian product, not an elementwise derivative. For softmax output with mean cross-entropy and one-hot labels, . Then, for each layer,
Factor is already in the output signal: applying it again at each layer would be an error. With a summed loss that factor does not appear. Ensure labels and loss reduction match those used to check the gradient.
During forward, save each layer’s input activation and enough information to differentiate its activation. During backward start from the loss derivative with respect to logits, calculate and , and pass to the preceding layer before applying its mask. Once all parameters have been used, the gradient vector can feed an update rule, but the update itself is not part of the derivation. If an activation is reused by another path, add that gradient too before continuing: a sequential list is a special case of a graph.
Cost and saved state
Consider a dense layer with examples, inputs and outputs. Counting about two FLOPs per multiply-add, the forward product costs . Weight backward computes for another ; propagating to input computes for another . If counts matrix weights, the approximate rule is for forward, for backward and total.
Backward accounting has limits: it omits biases, activations, softmax, loss, optimizer, memory operations and other components. If input-data gradients are unnecessary, can be omitted at lower cost. If parameters are frozen, not every weight product is needed either, although propagation to earlier layers may still be necessary. The rule counts approximate operations; it does not guarantee a time ratio on a particular machine.
Backward usually saves layer inputs and what is needed to differentiate activations. Storing only in float32 occupies bytes. Saving logits, preactivations or masks adds memory; gradients, temporaries, parameters and optimizer states are separate items. Implementation and tensor lifetimes determine the actual peak. Recomputing part of forward trades compute for memory, an idea that returns in distributed training.
For an MLP with , there are matrix weights. If both backward products are calculated even in the first layer, and approximate FLOPs. If input gradient is unnecessary, subtract the first-layer product; the lab calculates both counts. Saving in float32 occupies bytes, excluding logits and other storage. Do not cite these figures as measured runtime or peak framework memory.
Check before training
For parameter and step , the central difference estimates
For a sufficiently smooth function, truncation error is of order ; overly small amplifies rounding. Use float64, fix data and randomness and compare with a denominator that does not vanish near zero. Do not run gradcheck with changing dropout or ReLU preactivations near zero: a perturbation may cross the kink and the central difference is not the original graph’s local derivative. Large relative error signals investigation; review the protocol before concluding the formula is wrong.
Historically, reverse traversal of operations predates its popularization in networks. Linnainmaa described a reverse differentiation algorithm; Werbos’s thesis studied network applications; Rumelhart, Hinton and Williams popularized learning representations through error propagation in 1986. The review by Baydin and colleagues places these works in a broader history without attributing all development to one source.
Lab: manual MLP
Use two ReLU hidden layers and a softmax output. Examples are rows, cost is a mean and a cache is saved per layer. The backward function returns gradients matching each parameter’s exact shape and the input gradient.
import numpy as np
rng = np.random.default_rng(7)
X = rng.normal(size=(5, 3))
y = np.array([0, 1, 2, 1, 0])
dims = [3, 4, 3, 3]
params = [(rng.normal(scale=0.3, size=(a, b)), rng.normal(scale=0.2, size=b))
for a, b in zip(dims[:-1], dims[1:])]
def forward(X, y, params):
H = X
hs = [H]
zs = []
for i, (W, b) in enumerate(params):
Z = H @ W + b
zs.append(Z)
H = np.maximum(Z, 0) if i < len(params)-1 else Z
hs.append(H)
shifted = H-H.max(axis=1, keepdims=True)
logp = shifted-np.log(np.exp(shifted).sum(axis=1, keepdims=True))
loss = -logp[np.arange(len(y)), y].mean()
return loss, (hs, zs, np.exp(logp))
def backward(y, params, cache, bug=None):
hs, zs, P = cache
delta = P.copy()
delta[np.arange(len(y)), y] -= 1
if bug != 'sin_media': delta /= len(y)
grads = [None] * len(params)
for i in range(len(params)-1, -1, -1):
W, b = params[i]
grads[i] = (hs[i].T @ delta, delta.sum(axis=0))
dH = delta @ W.T
if i > 0:
mask = (zs[i-1] > 0) if bug != 'sin_relu' else np.ones_like(zs[i-1])
delta = dH * mask
return grads, dH
loss, cache = forward(X, y, params)
print('pérdida inicial', loss, 'mínima distancia de preactivaciones ocultas a cero',
min(np.abs(z).min() for z in cache[1][:-1]))def gradcheck(X, y, params, bug=None, eps=1e-5):
loss, cache = forward(X, y, params)
grads, _ = backward(y, params, cache, bug=bug)
largest = 0.0
for layer, (W, b) in enumerate(params):
for part, arr in enumerate((W, b)):
for index in np.ndindex(arr.shape):
original = arr[index]
arr[index] = original + eps
plus = forward(X, y, params)[0]
arr[index] = original - eps
minus = forward(X, y, params)[0]
arr[index] = original
numerical = (plus-minus)/(2*eps)
analytic = grads[layer][part][index]
relative = abs(numerical-analytic)/max(1e-8, abs(numerical)+abs(analytic))
largest = max(largest, relative)
return largest
for bug in (None, 'sin_media', 'sin_relu'):
print('variante', bug, 'error relativo máximo', gradcheck(X, y, params, bug))The two incorrect variants omit averaging and the ReLU mask respectively; output shows their errors and does not assume every error has the same signature. An incorrect transpose in a nonsquare layer usually fails on shape already: try it in the next cell. If a case is too close to a kink, change seed or example before interpreting the difference.
loss, cache = forward(X, y, params)
grads, dx = backward(y, params, cache)
try:
wrong = cache[0][0] @ np.ones((5, 4))
except ValueError as exc:
print('producto mal orientado:', type(exc).__name__)
x = np.array([[1., 2.]])
W1 = np.array([[1., -1.], [0.5, 1.]])
b1 = np.array([0., -0.5])
W2 = np.array([[1.], [-2.]])
b2 = np.array([0.5])
z1 = x @ W1 + b1
h1 = np.maximum(z1, 0)
out = h1 @ W2 + b2
d2 = out - 0.5
d1 = (d2 @ W2.T)*(z1 > 0)
print('ejemplo z1, salida, dW1, db1, dW2, db2', z1, out, x.T @ d1, d1.sum(axis=0), h1.T @ d2, d2.sum(axis=0))Lab: cost and memory
The next count adopts convention and also shows the saving from omitting input gradients. It then times small products in the browser. Pyodide runs NumPy without BLAS and on one thread: observed time ratios can differ from FLOP ratios due to shape, transposition and memory cost. A noisy measurement does not guarantee performance on another machine.
widths = [784, 1024, 1024, 10]
B = 256
for layer, (W, b) in enumerate(params, start=1):
count = 2*len(y)*W.shape[0]*W.shape[1]
print('MLP manual: capa, forward, dW, dH', layer, count, count, count)
N = sum(a*b for a, b in zip(widths[:-1], widths[1:]))
forward_flops = 2*B*N
backward_both = 4*B*N
saved_input = 2*B*widths[0]*widths[1]
activation_bytes = 4*B*sum(widths[:-1])
for layer, (a, b) in enumerate(zip(widths[:-1], widths[1:]), start=1):
one = 2*B*a*b
print('capa, forward, dW, dH', layer, one, one, one)
print('pesos, forward, backward ambos, total', N, forward_flops, backward_both, forward_flops+backward_both)
print('backward y total sin dX inicial', backward_both-saved_input, forward_flops+backward_both-saved_input)
print('bytes de H0, H1, H2', activation_bytes, 'MiB', activation_bytes/2**20)from time import perf_counter
rng = np.random.default_rng(9)
H = rng.normal(size=(64, 48))
W = rng.normal(size=(48, 64))
D = rng.normal(size=(64, 64))
repeat = 30
start = perf_counter()
for _ in range(repeat): Z = H @ W
t_forward = perf_counter()-start
start = perf_counter()
for _ in range(repeat): dW = H.T @ D
t_weight = perf_counter()-start
start = perf_counter()
for _ in range(repeat): dH = D @ W.T
t_input = perf_counter()-start
print('segundos forward / dW / dH', t_forward, t_weight, t_input)
print('cociente backward/forward observado', (t_weight+t_input)/max(t_forward, 1e-12))
print('FLOPs por producto', 2*64*48*64, 'bytes entrada guardada', H.nbytes)
for batch in (16, 32, 64, 128):
saved_h = np.empty((batch, 48), dtype=np.float32)
saved_next = np.empty((batch, 64), dtype=np.float32)
print('lote, bytes H y H siguiente', batch, saved_h.nbytes + saved_next.nbytes)The next local comparison uses small data in float64 to check both an affine layer’s backward pass and all weights and biases of the preceding MLP against autograd, without training a full model.
import numpy as np
import torch
X = np.array([[1., 2.], [-1., 0.5]])
W = np.array([[0.2, -0.3], [0.4, 0.1]])
b = np.array([0.1, -0.2])
D = np.array([[0.5, -0.7], [0.2, 0.3]])
x = torch.tensor(X, dtype=torch.float64, requires_grad=True)
w = torch.tensor(W, dtype=torch.float64, requires_grad=True)
bias = torch.tensor(b, dtype=torch.float64, requires_grad=True)
loss = ((x @ w + bias) * torch.tensor(D)).sum()
loss.backward()
print('errores dW, db, dX', np.max(np.abs(w.grad.numpy()-X.T@D)),
np.max(np.abs(bias.grad.numpy()-D.sum(axis=0))), np.max(np.abs(x.grad.numpy()[email protected])))
rng = np.random.default_rng(7)
X = rng.normal(size=(5, 3))
y = np.array([0, 1, 2, 1, 0])
dims = [3, 4, 3, 3]
params = [(rng.normal(scale=0.3, size=(a, b)), rng.normal(scale=0.2, size=b))
for a, b in zip(dims[:-1], dims[1:])]
hs, zs = [X], []
for i, (W, b) in enumerate(params):
z = hs[-1] @ W + b
zs.append(z)
hs.append(np.maximum(z, 0) if i < len(params)-1 else z)
shifted = hs[-1] - hs[-1].max(axis=1, keepdims=True)
delta = np.exp(shifted) / np.exp(shifted).sum(axis=1, keepdims=True)
delta[np.arange(len(y)), y] -= 1
delta /= len(y)
manual = [None] * len(params)
for i in range(len(params)-1, -1, -1):
manual[i] = (hs[i].T @ delta, delta.sum(axis=0))
if i > 0:
delta = (delta @ params[i][0].T) * (zs[i-1] > 0)
tw = [torch.tensor(W, dtype=torch.float64, requires_grad=True) for W, _ in params]
tb = [torch.tensor(b, dtype=torch.float64, requires_grad=True) for _, b in params]
h = torch.tensor(X, dtype=torch.float64)
for i in range(len(params)):
h = h @ tw[i] + tb[i]
if i < len(params)-1: h = torch.relu(h)
torch.nn.functional.cross_entropy(h, torch.tensor(y)).backward()
errors = [np.max(np.abs(tw[i].grad.numpy()-manual[i][0])) for i in range(len(params))]
errors += [np.max(np.abs(tb[i].grad.numpy()-manual[i][1])) for i in range(len(params))]
print('MLP: máximo error de pesos y sesgos contra autograd', max(errors))npm run lab and open the connection link.Exercises
Step 1 of 3. What gradient reaches H⁽ˡ⁾ from the next layer?
dense_backward(dZ, H_prev, W). Return dW, db and dH_prev for Z=H_prev@W+b, without dividing by batch size: dZ already includes any reduction.import numpy as np
def dense_backward(dZ, H_prev, W):
passBackpropagation applies the chain rule to the graph in reverse order and accumulates branches. In an MLP, the signal propagates through multiplication by transposed weights and a local derivative; saved activations allow parameter gradients to be formed. The approximate rule is a count under assumptions, not a universal measurement of time or peak memory.