Module contents
Lesson 7 of 22Core 100 min

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

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.

InteractiveThe gradient follows the graph
a2.00∂: pendingb−3.00∂: pendingc4.00∂: pendingu = a·bpending∂: pendingr = ReLU(a)pending∂: pendingv = u+cpending∂: pendingf = v·rpending∂: pending
Each box shows the value and accumulated gradient of f with respect to that node. The asterisk indicates a still partial sum.
f → v · local: pending · contribution: pending
f → r · local: pending · contribution: pending
v → u · local: pending · contribution: pending
v → c · local: pending · contribution: pending
r → a · local: pending · contribution: pending
u → a · local: pending · contribution: pending
u → b · local: pending · contribution: pending
Each contribution multiplies the accumulated gradient at the output node by the local derivative of the edge. At a=0a=0, ReLU has no ordinary derivative: here we use the local convention 00. For other values, its derivative is 11 if a>0a>0 and 00 if a<0a<0.
2.0
-3.0
4.0
0 / 9
StepInputs available
Step through forward and backward. Input a is used twice: its gradient sums contributions from both branches. At the ReLU kink the convention shown in the figure is used.

For u=abu=ab, v=u+cv=u+c, r=ReLU⁡(a)r=\relu(a) and f=vrf=vr, local derivatives give

∂f∂a=rb+vReLU⁡′(a),∂f∂b=ra,∂f∂c=r.\frac{\partial f}{\partial a}=rb+v\relu'(a),\qquad \frac{\partial f}{\partial b}=ra,\qquad \frac{\partial f}{\partial c}=r.

The first term of ∂f/∂a\partial f/\partial a arrives through a→u→v→fa\to u\to v\to f and the second through a→r→fa\to r\to f. In a general graph, if a variable feeds multiple nodes, sum contributions from all its uses rather than overwriting the first. At a=0a=0, 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 Z=HW+1Bb⊤\mat{Z}=\mat{H}\mat{W}+\vb{1}_B\vb{b}\T and scalar loss LL, write G=∂L/∂Z\mat{G}=\partial L/\partial\mat{Z}. The linear-layer gradients are

∂L∂W=H⊤G,∂L∂b=G⊤1B,∂L∂H=GW⊤.\frac{\partial L}{\partial\mat{W}}=\mat{H}\T\mat{G},\qquad \frac{\partial L}{\partial\vb{b}}=\mat{G}\T\vb{1}_B,\qquad \frac{\partial L}{\partial\mat{H}}=\mat{G}\mat{W}\T.

With H∈RB×din\mat{H}\in\R^{B\times d_{\mathrm{in}}} and W∈Rdin×dout\mat{W}\in\R^{d_{\mathrm{in}}\times d_{\mathrm{out}}}, 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, Zic=∑jHijWjc+bcZ_{ic}=\sum_j H_{ij}W_{jc}+b_c. Holding other arguments fixed, ∂Zic/∂Wjr=Hij1[c=r]\partial Z_{ic}/\partial W_{jr}=H_{ij}\ind[c=r]. Thus ∂L/∂Wjr=∑iGirHij\partial L/\partial W_{jr}=\sum_i G_{ir}H_{ij}: this is entry (j,r)(j,r) of H⊤GH\T G. The same bias brb_r appears in all examples, so its gradient sums GirG_{ir} over ii. Finally, ∂L/∂Hij=∑cGicWjc\partial L/\partial H_{ij}=\sum_c G_{ic}W_{jc}, entry (i,j)(i,j) of GW⊤GW\T. These sums show why weights are shared across examples and why backward accumulates their contributions.

In an MLP, H(0)=X\mat{H}^{(0)}=\mat{X} and H(ℓ)=ϕℓ(Z(ℓ))\mat{H}^{(\ell)}=\phi_\ell(\mat{Z}^{(\ell)}). The error signal δ(ℓ)=∂L/∂Z(ℓ)\mat{\delta}^{(\ell)}=\partial L/\partial\mat{Z}^{(\ell)} propagates from the output through

δ(ℓ)=(δ(ℓ+1)W(ℓ+1)⊤)⊙ϕℓ′(Z(ℓ)).\mat{\delta}^{(\ell)}= \left(\mat{\delta}^{(\ell+1)}\mat{W}^{(\ell+1)\T}\right)\odot \phi_\ell'(\mat{Z}^{(\ell)}).

Multiplication by W(ℓ+1)⊤\mat{W}^{(\ell+1)\T} aggregates the effect of each unit in the next layer; ⊙\odot 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, δ(L)=(P−Y)/B\mat{\delta}^{(L)}=(\mat{P}-\mat{Y})/B. Then, for each layer,

∇W(ℓ)L=H(ℓ−1)⊤δ(ℓ),∇b(ℓ)L=δ(ℓ)⊤1B.\nabla_{W^{(\ell)}}L=\mat{H}^{(\ell-1)\T}\mat{\delta}^{(\ell)},\qquad \nabla_{b^{(\ell)}}L=\mat{\delta}^{(\ell)\T}\vb{1}_B.

Factor 1/B1/B 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 dWdW and dbdb, and pass dHdH 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.

InteractiveBackward through matrices
1. Output error

δ³ = (P − Y) / 4

No matrix product in this step.

Probabilities P · 4 × 2
0.8810.1190.4120.5880.4430.5570.8030.197
Labels Y · 4 × 2
1.0000.0000.0001.0000.0001.0001.0000.000
δ³ · 4 × 2
−0.0300.0300.103−0.1030.111−0.111−0.0490.049

The loss is an average over four examples; the factor 1/4 enters here once.

The example inputs, weights and biases are fixed and defined in the code; matrices are calculated by forward and backward passes. Values are rounded to three decimals. For ReLU, the derivative at the origin is taken as zero.

1 / 6
Network3 → 4 → 3 → 2
Batch4 examples
Mean cross-entropy0.3657
Trace a batch backward and follow each product's dimensions. The contracted dimension appears in both factors; correct shape is necessary, but the chain rule identifies the product.

Cost and saved state

Consider a dense layer with BB examples, mm inputs and nn outputs. Counting about two FLOPs per multiply-add, the forward product costs 2Bmn2Bmn. Weight backward computes H⊤δ\mat{H}\T\mat{\delta} for another 2Bmn2Bmn; propagating to input computes δW⊤\mat{\delta}\mat{W}\T for another 2Bmn2Bmn. If N=∑ℓdℓ−1dℓN=\sum_\ell d_{\ell-1}d_\ell counts matrix weights, the approximate rule is 2BN2BN for forward, 4BN4BN for backward and 6BN6BN total.

Backward accounting has limits: it omits biases, activations, softmax, loss, optimizer, memory operations and other components. If input-data gradients are unnecessary, δ(1)W(1)⊤\delta^{(1)}W^{(1)\T} 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 H(0),…,H(L−1)\mat{H}^{(0)},\ldots,\mat{H}^{(L-1)} in float32 occupies 4B∑ℓ=0L−1dℓ4B\sum_{\ell=0}^{L-1}d_\ell 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.

InteractiveA network ledger

Network 784 → 1024 → 1024 → 10. Bars show FLOPs per batch: a multiplication and an addition count as two. The horizontal scale is shared across layers.

  • Forward HW
  • Weight gradient
  • Layer input gradient
Layer 1: 784 × 1024Forward 411 M · dW 411 M · dH 0
Layer 2: 1024 × 1024Forward 537 M · dW 537 M · dH 537 M
Layer 3: 1024 × 10Forward 5.24 M · dW 5.24 M · dH 5.24 M
Millions of cumulative matrix FLOPs per example
  • Selected count
  • 6N reference

In each layer, forward and dW cost 2B × input × output; dH costs the same if calculated. The 6N reference includes all three products in every layer. If the input does not need a gradient, dH for the first layer is omitted. Only matrix multiplications are counted, not biases or other operations.

Simplified model memory, float32
Stored input and hidden activations2.77 MiB
Weights and biases7.11 MiB

Store H₀ and hidden outputs H₁,…,H2: 256 × (784 + 1024 + 1024) × 4 bytes. Input data are counted even if they may exist before the forward pass. Weights and biases occupy (N + 2058) × 4 bytes. Excludes logits, loss, additional masks or preactivations, gradients, optimizer and temporaries: this is not peak memory.

Biases separately: 527 k additions when adding them in the forward pass and 525 k additions to reduce dB over the batch, assuming B−1 additions per component. These are excluded from the plot and 6N. Activation, loss and update costs are also excluded.

784
1024
2
10
256
Weights N1.86 M
Biases2058
Matrix forward per batch953 M
Matrix backward per batch1.50 B
Total matrix operations per example9.56 M
Change batch size and widths. Compare forward, both backward products and memory; disable input gradients to see the cost that can be omitted.

For an MLP 784→1024→1024→10784\to1024\to1024\to10 with B=256B=256, there are N=1,861,632N=1,861,632 matrix weights. If both backward products are calculated even in the first layer, 2BN=953,155,5842BN=953,155,584 and 6BN=2,859,466,7526BN=2,859,466,752 approximate FLOPs. If input gradient is unnecessary, subtract the first-layer product; the lab calculates both counts. Saving H(0),H(1),H(2)H^{(0)},H^{(1)},H^{(2)} in float32 occupies 2,899,9682,899,968 bytes, excluding logits and other storage. Do not cite these figures as measured runtime or peak framework memory.

Check before training

For parameter θi\theta_i and step h>0h>0, the central difference estimates

ginum=L(θi+h)−L(θi−h)2h.g_i^{\mathrm{num}}=\frac{L(\theta_i+h)-L(\theta_i-h)}{2h}.

For a sufficiently smooth function, truncation error is of order h2h^2; overly small hh 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.

[ ]Stable forward and cacheBrowser
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]))
[ ]Gradcheck and deliberate failuresBrowser
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.

[ ]An incorrect transpose and a worked exampleBrowser
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 2Bmn2Bmn 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.

[ ]Per-layer accountingBrowser
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)
[ ]Time three products in PyodideBrowser
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.

[ ]Compare with autogradLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofLayerwise recursion
Prove: Derive the error signal and gradients for one layer of a batched MLP.
0
δ⁽ˡ⁺¹⁾ = ∂L/∂Z⁽ˡ⁺¹⁾ and H⁽ˡ⁾ = φ(Z⁽ˡ⁾), with φ elementwise.

Step 1 of 3. What gradient reaches H⁽ˡ⁾ from the next layer?

NumericA gradient in the small network
For x=(1,2), W₁=[[1,−1],[0.5,1]], b₁=(0,−0.5), ReLU, W₂=(1,−2)ᵀ, b₂=0.5 and loss ½(output−0.5)², calculate the row 2, column 2 entry of ∂L/∂W₁.
NumericCount operations
For the 784-1024-1024-10 MLP and batch 256, calculate approximate total forward and backward FLOPs when both backward products are calculated in all layers; count 2 per multiply-add and omit minor operations.
NumericActivation memory
For that network and batch 256, how many bytes do H⁽⁰⁾, H⁽¹⁾ and H⁽²⁾ occupy in float32? Exclude logits and other tensors.
QuizInterpret gradcheck
With fixed data, float64 and preactivations away from zero, which maximum relative error should be investigated first: 1e−2, 1e−5 or 1e−9?
CodeDense-layer backward
Implement 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):
  pass
Shift+Enter to run
Key idea

Backpropagation 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 6BN6BN rule is a count under assumptions, not a universal measurement of time or peak memory.