Backpropagation

Dive into Deep Learning · §4.3

Backpropagation & Computational Graphs in MLPs
reverse-mode DAGs · local matrix rules · 5-line MLP backward pass · activation memory & FLOP cost

Why One Backward Pass Computes All 203,530 Gradients

Opening the Black Box

  • Finite differences vs. reverse mode: Perturbing each scalar weight w \pm \epsilon would require 203{,}530 forward passes per step; reverse-mode differentiation computes all parameter gradients in at most \sim 2\times the FLOPs of one forward pass.
  • Shared intermediate layer errors: Backpropagation computes each layer’s upstream sensitivity \partial J / \partial \mathbf{Z}^{(k)} once from top to bottom and reads off \partial J / \partial \mathbf{W}^{(k)} with a single matrix product.
  • The memory price of training: Forming \mathbf{H}^{(k-1)\top}\mathbf{G}_{\mathbf{Z}^{(k)}} requires caching every hidden layer’s forward activation in O(nKh) GPU RAM.

A Three-Node Computational Graph: Forward & Reverse

Computational Graphs · Scalar Anatomy

To see reverse-mode differentiation in its barest form, trace e = (a + b)\,c at a = 2, b = 1, c = -3:

  • Forward pass (left to right): Evaluates and caches intermediate values: u = a + b = 3, then e = u\,c = -9.
  • Backward pass (right to left): Seeds \partial e / \partial e = 1 and applies one local derivative per node in reverse topological order:
    • Multiply node (e = u\,c): Swaps and scales by the other cached input: \partial e / \partial u = c = -3 and \partial e / \partial c = u = 3.
    • Add node (u = a + b): Routes its incoming gradient unchanged to both branches: \partial e / \partial a = \partial e / \partial b = -3.

Computational Graph of a Regularized MLP

Computational Graphs · Matrix DAG

For a minibatch \mathbf{X} \in \mathbb{R}^{n \times d}, our one-hidden-layer MLP with \ell_2 weight decay s = \frac{\lambda}{2}(\|\mathbf{W}^{(1)}\|_{\textrm{F}}^2 + \|\mathbf{W}^{(2)}\|_{\textrm{F}}^2) forms a directed acyclic graph:

  • Forward pass chain: \mathbf{Z} = \mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)} \to \mathbf{H} = \phi(\mathbf{Z}) \to \mathbf{O} = \mathbf{H}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}: J = L(\mathbf{O}, \mathbf{Y}) + s
  • Branching parameter nodes (shaded): Each weight matrix \mathbf{W}^{(k)} feeds two children—its affine layer and the Frobenius penalty s.
  • Multivariate chain rule at branches: Whenever a node feeds multiple downstream paths, its backward gradient is the sum (+=) of the gradients returning along all outgoing edges.

Local Rule 1: Matrix Multiplication A = XW

Local Matrix Calculus

\begin{aligned}\frac{\partial J}{\partial \mathbf{W}} &= \mathbf{X}^\top\mathbf{G} \in \mathbb{R}^{d \times h}, \\ \frac{\partial J}{\partial \mathbf{X}} &= \mathbf{G}\mathbf{W}^\top \in \mathbb{R}^{n \times d}\end{aligned}

  • Coordinate expansion: Entry w_{rj} influences every example i in column j (\sum_i x_{ir} g_{ij}), while entry x_{ir} influences every output unit j in row i (\sum_j g_{ij} w_{rj}).
  • Shape-lock check: \mathbf{X}^\top\mathbf{G} is the only way to multiply (n \times d) and (n \times h) into (d \times h)—requiring the cached forward input \mathbf{X}.

Local Rules 2 & 3: Broadcasted Biases and Activations

Local Matrix Calculus

\begin{aligned}\frac{\partial J}{\partial \mathbf{b}} &= \mathbf{G}^\top\mathbf{1}_n, \\ \frac{\partial J}{\partial \mathbf{Z}} &= \frac{\partial J}{\partial \mathbf{H}} \odot \phi'(\mathbf{Z})\end{aligned}

  • Broadcasted bias (\mathbf{Z} = \mathbf{A} + \mathbf{b}): Copies \mathbf{G} unchanged to \mathbf{A} and sums across the batch axis (G.sum(axis=0)).
  • Elementwise activation (\mathbf{H} = \phi(\mathbf{Z})): Gates the upstream gradient entry-by-entry (Hadamard product \odot) by the local slope \phi'(z_{ij}).

The Complete Five-Line Backward Pass of an MLP

Assembling the Backward Sweep

  • Top-down credit assignment: Seeds \mathbf{G}_{\mathbf{O}} = \frac{1}{n}(\hat{\mathbf{Y}} - \mathbf{Y}) at the softmax logits and reads off \nabla\mathbf{W}^{(2)} = \mathbf{H}^\top\mathbf{G}_{\mathbf{O}} + \lambda\mathbf{W}^{(2)}.
  • Hidden error routing: Projects \mathbf{G}_{\mathbf{O}}\mathbf{W}^{(2)\top} back to hidden units, gates by \odot\,\phi'(\mathbf{Z}), and forms \nabla\mathbf{W}^{(1)} = \mathbf{X}^\top\mathbf{G}_{\mathbf{Z}} + \lambda\mathbf{W}^{(1)}.

Generalizing to K Layers: The Backward Recurrence

Deep MLP Recurrence

\frac{\partial J}{\partial \mathbf{Z}^{(k)}} = \Bigl(\frac{\partial J}{\partial \mathbf{Z}^{(k+1)}}\, \mathbf{W}^{(k+1)\top}\Bigr) \odot \phi'\bigl(\mathbf{Z}^{(k)}\bigr)

  • Two-step layer module: Every hidden layer k = K - 1, \ldots, 1 projects upstream errors through \mathbf{W}^{(k+1)\top}, gates by \odot\,\phi'(\mathbf{Z}^{(k)}), and reads off \mathbf{H}^{(k-1)\top}\mathbf{G}_{\mathbf{Z}^{(k)}}.
  • Product chain across depth: Repeatedly multiplying by \mathbf{W}^{(k)\top} and \phi'(\mathbf{Z}^{(k)}) explains why gradients vanish or explode in deep networks.

Worked Numerical Example: Forward & Backward by Hand

Worked Example · Numbers

  • Setup (2 \to 2 \to 1 ReLU): \mathbf{X} = [1, 2], \mathbf{W}^{(1)} = \begin{bmatrix} 1 & 0 \\ -1 & 1 \end{bmatrix}, \mathbf{W}^{(2)} = [2, -1]^\top, y = 0, L = \frac{1}{2}(o - y)^2.
  • Forward: \mathbf{Z} = [-1, 2] \to \mathbf{H} = [0, 2] \to o = -2 \to L = 2.
  • Backward: \partial L/\partial o = -2 \implies \nabla\mathbf{H} = [-4, 2] \implies \nabla\mathbf{Z} = [-4, 2] \odot [0, 1] = [0, 2], zeroing out column 1 of \nabla\mathbf{W}^{(1)}.

Visualizing the Dead ReLU Gate in the Backward Graph

Worked Example · Graph

Inspecting the forward values (black) and reverse-mode derivatives (red) on the computational graph explains mechanically how a dead ReLU unit freezes learning:

  • Zeroed incoming column: Even though unit 1 has a large upstream sensitivity \partial L / \partial h_1 = -4, its negative pre-activation z_1 = -1 < 0 sets the ReLU slope to \phi'(z_1) = 0.
  • Permanent stall if inactive across dataset: Gating \partial L / \partial z_1 = 0 zeroes out the entire first column of \partial L / \partial \mathbf{W}^{(1)} (\begin{bmatrix} 0 & 0 \end{bmatrix}^\top), so column 1 of \mathbf{W}^{(1)} never updates.

Implementing the Five-Line Backward Pass in Code

Verifying Backprop Against Autograd

We translate our five matrix equations directly into mlp_backward(X, Y, W1, b1, W2, b2, lambd):

def mlp_backward(X, Y, W1, b1, W2, b2, lambd):
    """Gradients of J = cross-entropy + weight decay, by backprop."""
    Z = X @ W1 + b1  # forward pass, keeping X, Z, H, and Y_hat
    H = torch.relu(Z)
    Y_hat = torch.softmax(H @ W2 + b2, dim=1)
    G_O = (Y_hat - Y) / X.shape[0]  # dJ/dO
    dW2, db2 = H.T @ G_O + lambd * W2, G_O.sum(dim=0)
    G_Z = (G_O @ W2.T) * (Z > 0)  # dJ/dH, then dJ/dZ
    dW1, db1 = X.T @ G_Z + lambd * W1, G_Z.sum(dim=0)
    return dW1, db1, dW2, db2

Notice that for ReLU, storing \mathbf{H} (or \mathbf{Z}) suffices to evaluate the binary mask (Z > 0) in line G_Z = (G_O @ W2.T) * (Z > 0).

Float64 Gradient Check: Matching Autograd to 10⁻¹⁵

Verifying Backprop Against Autograd

Running both mlp_backward and framework autograd in 64-bit floating point (float64, machine epsilon \approx 2.2 \times 10^{-16}) on a random 256 \times 784 minibatch verifies our derivation to within 10^{-15} relative error:

W1: relative difference 4.4e-16
b1: relative difference 2.9e-16
W2: relative difference 3.8e-16
b2: relative difference 2.1e-16

Why Training Uses More Memory Than Inference

Systems Cost · Activation Memory

  • Inference (O(nh) RAM): Overwrites each layer’s activation buffer as soon as the next layer finishes.
  • Training (O(nKh) RAM): Must cache \mathbf{X} (0.80\textrm{ MB}), \mathbf{H} (0.26\textrm{ MB}), and \hat{\mathbf{Y}} (0.01\textrm{ MB}) until the backward pass forms \mathbf{H}^{(k-1)\top}\mathbf{G}_{\mathbf{Z}^{(k)}}.
  • Batch scaling: Even for a 1-hidden-layer MLP at n = 256, cached activations (1.08\textrm{ MB}) exceed model parameters (0.81\textrm{ MB}).

Arithmetic Cost: Why Backward Costs ~2× Forward

Systems Cost · FLOPs

  • Forward pass (203{,}264 MACs / image): Computes one matrix product per layer (\mathbf{X}\mathbf{W}^{(1)} and \mathbf{H}\mathbf{W}^{(2)}).
  • Backward pass (205{,}824 MACs / image): Every interior forward matmul \mathbf{H}^{(k-1)}\mathbf{W}^{(k)} spawns two backward matmuls of identical FLOP count (\mathbf{H}^{(k-1)\top}\mathbf{G} and \mathbf{G}\mathbf{W}^{(k)\top}).
  • 3× rule of thumb: Backward costs \approx 2\times forward FLOPs, so a full training step costs \approx 3\times inference FLOPs.

Reverse Mode vs. Forward Mode & Finite Differences

Systems Cost · Algorithmic Comparison

Why does deep learning rely on reverse-mode backpropagation rather than forward-mode differentiation or numerical finite differences for a scalar loss J: \mathbb{R}^P \to \mathbb{R} (P = 203{,}530)?

Differentiation Method What One Sweep Computes Sweeps Needed for \nabla J \in \mathbb{R}^P Activation Memory Total FLOPs / Step (P = 203{,}530)
Finite Differences \frac{J(w+\epsilon)-J(w-\epsilon)}{2\epsilon} 1 scalar directional derivative P (or 2P central) O(nh) (no cache) \sim 203{,}530 \times forward (\sim 4 \times 10^{10})
Forward Mode (seed \dot{w}_i = 1) Tangents \partial (\cdot) / \partial w_i for 1 weight P forward sweeps O(nh) (no cache) \sim 203{,}530 \times forward
Reverse Mode (Backprop) (seed \bar{J} = 1) Adjoints \partial J / \partial (\cdot) for all weights 1 backward sweep O(nKh) cached \sim 3 \times forward (\sim 6 \times 10^5)

Reverse mode is O(1) sweeps for scalar outputs with many inputs (P \gg 1), whereas forward mode is preferable only when outputs outnumber inputs (q \gg P).

Concept Check: Shapes, Memory Scaling, and Jacobians

Check

Test your grasp of backpropagation mechanics and systems scaling:

  1. Outer-product sum: In our Fashion-MNIST MLP with batch size n = 256, \mathbf{X}^\top\mathbf{G}_{\mathbf{Z}} has shape (784, 256) \times (256, 256) = (784, 256). Written as a sum over examples i = 1, \ldots, 256, what rank-1 matrix does each example contribute?
  2. 10-layer activation memory: If we deepen our MLP to 10 hidden layers of width 256 (n = 256), how many megabytes of float32 activations must training cache per minibatch vs. parameter memory?
  3. Why not form the full Jacobian? How much float32 memory would the full 4D tensor \partial \mathbf{O} / \partial \mathbf{W}^{(2)} of shape (n, q, h, q) = (256, 10, 256, 10) occupy if materialized explicitly?

Answers:

  1. Sum of outer products: \mathbf{X}^\top\mathbf{G}_{\mathbf{Z}} = \sum_{i=1}^{256} \mathbf{x}_i \mathbf{g}_{\mathbf{z}, i}^\top, where \mathbf{x}_i \in \mathbb{R}^{784} is example i’s input and \mathbf{g}_{\mathbf{z}, i} \in \mathbb{R}^{256} is its pre-activation gradient.
  2. Memory at depth 10: \mathbf{X} (200{,}704) + 10 \times \mathbf{H}^{(k)} (10 \times 65{,}536) + \hat{\mathbf{Y}} (2{,}560) = 858{,}624 floats \approx 3.43\textrm{ MB} (exceeding the 795{,}658 parameters \approx 3.18\textrm{ MB}).
  3. Full Jacobian explosion: 256 \times 10 \times 256 \times 10 \times 4\textrm{ B} \approx 26.2\textrm{ MB} for just the small output layer. Vector-Jacobian products contract \mathbf{H}^\top\mathbf{G}_{\mathbf{O}} directly into 256 \times 10 (10\textrm{ KB}).

Summary: Backpropagation in Multilayer Perceptrons

Key Takeaways

Forward Operation Cached Tensor(s) Backward Parameter Gradient Backward Input Gradient FLOP / Memory Scaling
Linear \mathbf{A} = \mathbf{X}\mathbf{W} \mathbf{X} \in \mathbb{R}^{n \times d}, \mathbf{W} \in \mathbb{R}^{d \times h} \frac{\partial J}{\partial \mathbf{W}} = \mathbf{X}^\top\mathbf{G} \frac{\partial J}{\partial \mathbf{X}} = \mathbf{G}\mathbf{W}^\top 2 \times n d h backward multiply-adds
Broadcast Bias \mathbf{Z} = \mathbf{A} + \mathbf{b} None \frac{\partial J}{\partial \mathbf{b}} = \mathbf{G}^\top\mathbf{1}_n (row sum) \frac{\partial J}{\partial \mathbf{A}} = \mathbf{G} O(nh) sum; no extra cache
Activation \mathbf{H} = \phi(\mathbf{Z}) \mathbf{Z} (or \mathbf{H} for ReLU) None \frac{\partial J}{\partial \mathbf{Z}} = \mathbf{G} \odot \phi'(\mathbf{Z}) O(nh) elementwise; dead if \phi' = 0
Weight Decay s = \frac{\lambda}{2}\|\mathbf{W}\|_{\textrm{F}}^2 \mathbf{W} Adds +\lambda\mathbf{W} to \frac{\partial J}{\partial \mathbf{W}} — Branch in DAG sums incoming grads
Full K-Layer MLP Sweep \mathbf{X}, \mathbf{H}^{(1 \dots K-1)}, \hat{\mathbf{Y}} All \mathbf{W}^{(k)}, \mathbf{b}^{(k)} in 1 reverse pass Propagates \mathbf{G}\mathbf{W}^{(k)\top} \odot \phi' \sim 2\times forward FLOPs; O(nKh) RAM