Simple Algorithm
Deep Learning · Representation · 24 min

Backpropagation & Automatic Differentiation

Computational graphs, reverse mode and why a gradient costs only a few forward passes.

Backpropagation is not a neural-network trick. It is one instance of reverse-mode automatic differentiation, an algorithm that differentiates any program built from differentiable pieces and returns the exact gradient for a small constant multiple of the program's own cost. Here you derive it for a whole layer at once, count what it costs in time and memory, and see how PyTorch automates it.

What you’ll learn

  • Express a network as a composition of primitives with local Jacobians, and explain why reverse mode computes the gradient with vector–Jacobian products only.
  • Write backpropagation through a multilayer perceptron as matrix equations, first for a single example and then for a whole mini-batch.
  • Count the cost of a gradient (backward about twice the forward FLOPs) and its activation memory, and explain how gradient checkpointing trades recomputation for memory.
  • Compare forward mode (Jacobian–vector products) with reverse mode, and use PyTorch's autograd and a gradient check correctly.

Programs, Jacobians and the order of multiplication

A network is a computational graph of primitives: matrix products, additions, elementwise activations, a loss. Write the whole computation as a composition L=fK∘⋯∘f2∘f1(x)L = f_K\circ\cdots\circ f_2\circ f_1(\mathbf x), where fkf_k maps the value vk−1\mathbf v_{k-1} to vk\mathbf v_k and has the local Jacobian Jk=∂vk/∂vk−1J_k = \partial\mathbf v_k/\partial\mathbf v_{k-1}. The chain rule says the derivative of the composition is the product of the local Jacobians:

∂L∂x=JK JK−1⋯J2 J1,a 1×n row vector, since L is a scalar\frac{\partial L}{\partial\mathbf x} = J_K\,J_{K-1}\cdots J_2\,J_1,\qquad\text{a }1\times n\text{ row vector, since }L\text{ is a scalar}
Matrix multiplication is associative, so the product can be evaluated in any order, and the order decides the cost.

Multiplying from the right, J2J1J_2J_1 first, builds full Jacobians of intermediate values with respect to all nn inputs: matrix–matrix products, hopeless when nn is the number of weights. Multiplying from the left starts with the 1×dim⁡vK−11\times\dim\mathbf v_{K-1} row JK=∂L/∂vK−1J_K = \partial L/\partial\mathbf v_{K-1}, and every later product is a row vector times a matrix. That is reverse mode, and backpropagation is reverse mode applied to a network.

Graphs are rarely simple chains. When a value u\mathbf u is used by several primitives, its adjoint is the sum of the VJPs coming back from each use, uˉ=∑usesvˉiJi\bar{\mathbf u} = \sum_{\text{uses}}\bar{\mathbf v}_iJ_i, which is the multivariable chain rule. A reverse sweep therefore visits the nodes in reverse topological order, accumulating adjoints, so each primitive's VJP runs exactly once.

Backpropagation for a layer, in matrix form

Apply this to a multilayer perceptron with z(ℓ)=W(ℓ)h(ℓ−1)+b(ℓ)\mathbf z^{(\ell)} = W^{(\ell)}\mathbf h^{(\ell-1)} + \mathbf b^{(\ell)} and h(ℓ)=ϕ(z(ℓ))\mathbf h^{(\ell)} = \phi(\mathbf z^{(\ell)}) for ℓ=1,…,L\ell = 1,\dots,L, with h(0)=x\mathbf h^{(0)} = \mathbf x and the loss computed from z(L)\mathbf z^{(L)}. The quantity to propagate is the error signal δ(ℓ)=∂ℓ/∂z(ℓ)\boldsymbol\delta^{(\ell)} = \partial\ell/\partial\mathbf z^{(\ell)}, written as a column vector.

DerivationThe backpropagation equations
  1. ∂ℓ∂hj(ℓ)=∑iδi(ℓ+1) Wij(ℓ+1)⟹∂ℓ∂h(ℓ)=W(ℓ+1)⊤δ(ℓ+1)\frac{\partial\ell}{\partial h^{(\ell)}_j} = \sum_i\delta^{(\ell+1)}_i\,W^{(\ell+1)}_{ij}\quad\Longrightarrow\quad\frac{\partial\ell}{\partial\mathbf h^{(\ell)}} = W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}

    Unit jj of layer ℓ\ell feeds every unit of layer ℓ+1\ell+1, with ∂zi(ℓ+1)/∂hj(ℓ)=Wij(ℓ+1)\partial z^{(\ell+1)}_i/\partial h^{(\ell)}_j = W^{(\ell+1)}_{ij}. Sum over those paths:

  2. δ(ℓ)=(W(ℓ+1)⊤δ(ℓ+1))⊙ϕ′(z(ℓ))\boldsymbol\delta^{(\ell)} = \big(W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}\big)\odot\phi'(\mathbf z^{(\ell)})

    The activation acts elementwise, so its Jacobian is diagonal, diag⁡(ϕ′(z(ℓ)))\diag(\phi'(\mathbf z^{(\ell)})), and its VJP is an elementwise product:

  3. ∂ℓ∂W(ℓ)=δ(ℓ) h(ℓ−1)⊤,∂ℓ∂b(ℓ)=δ(ℓ)\frac{\partial\ell}{\partial W^{(\ell)}} = \boldsymbol\delta^{(\ell)}\,\mathbf h^{(\ell-1)\top},\qquad\frac{\partial\ell}{\partial\mathbf b^{(\ell)}} = \boldsymbol\delta^{(\ell)}

    Weight Wij(ℓ)W^{(\ell)}_{ij} enters only zi(ℓ)z^{(\ell)}_i, with ∂zi(ℓ)/∂Wij(ℓ)=hj(ℓ−1)\partial z^{(\ell)}_i/\partial W^{(\ell)}_{ij} = h^{(\ell-1)}_j. So each weight's gradient is the error at its output unit times the activation at its input unit, an outer product:

  4. ∂L∂W(ℓ)=Δ(ℓ)⊤H(ℓ−1),∂L∂b(ℓ)=Δ(ℓ)⊤1,Δ(ℓ−1)=(Δ(ℓ)W(ℓ))⊙ϕ′(Z(ℓ−1))\frac{\partial\loss}{\partial W^{(\ell)}} = \Delta^{(\ell)\top}H^{(\ell-1)},\qquad\frac{\partial\loss}{\partial\mathbf b^{(\ell)}} = \Delta^{(\ell)\top}\mathbf 1,\qquad\Delta^{(\ell-1)} = \big(\Delta^{(\ell)}W^{(\ell)}\big)\odot\phi'(Z^{(\ell-1)})

    For a mini-batch, stack the BB examples as rows: Z(ℓ)=H(ℓ−1)W(ℓ)⊤+1b(ℓ)⊤Z^{(\ell)} = H^{(\ell-1)}W^{(\ell)\top} + \mathbf 1\mathbf b^{(\ell)\top}, and Δ(ℓ)=∂L/∂Z(ℓ)\Delta^{(\ell)} = \partial\loss/\partial Z^{(\ell)} has row ii equal to δi(ℓ)⊤/B\boldsymbol\delta_i^{(\ell)\top}/B for the batch-mean loss. The per-example outer products sum into one matrix product:

text
BACKPROP-MLP(X, Y)                        // rows of X: B examples; Y: one-hot labels
  H⁽⁰⁾ ← X
  for ℓ = 1 … L:                           // forward pass, keeping Z⁽ℓ⁾ and H⁽ℓ⁾
      Z⁽ℓ⁾ ← H⁽ℓ⁻¹⁾ W⁽ℓ⁾ᵀ + 1 b⁽ℓ⁾ᵀ
      H⁽ℓ⁾ ← φ(Z⁽ℓ⁾)                       // no activation at the output layer
  Δ ← (softmax(Z⁽ᴸ⁾) − Y) / B               // ∂ℒ/∂Z⁽ᴸ⁾ for the mean cross-entropy
  for ℓ = L … 1:                           // backward pass
      ∂W⁽ℓ⁾ ← Δᵀ H⁽ℓ⁻¹⁾ ;  ∂b⁽ℓ⁾ ← Δᵀ 1
      if ℓ > 1:  Δ ← (Δ W⁽ℓ⁾) ⊙ φ′(Z⁽ℓ⁻¹⁾)
  return all ∂W⁽ℓ⁾, ∂b⁽ℓ⁾

The starting signal softmax⁡(z)−y\operatorname{softmax}(\mathbf z) - \mathbf y is the gradient of softmax followed by cross-entropy, derived in Deriving Backward Passes. Everything else is the derivation above, one layer at a time.

Check your understanding

Layer ℓ\ell has W(ℓ)∈R256×512W^{(\ell)}\in\R^{256\times512} and the batch has B=64B = 64 examples. What is the shape of Δ(ℓ)⊤H(ℓ−1)\Delta^{(\ell)\top}H^{(\ell-1)}?

  1. 64×6464\times64
  2. 512×256512\times256
  3. 256×512256\times512, the shape of W(ℓ)W^{(\ell)}
  4. 64×25664\times256
Show the answer

C. 256×512256\times512, the shape of W(ℓ)W^{(\ell)}

Δ(ℓ)\Delta^{(\ell)} is 64×25664\times256 (one error per example and output unit) and H(ℓ−1)H^{(\ell-1)} is 64×51264\times512, so Δ(ℓ)⊤H(ℓ−1)\Delta^{(\ell)\top}H^{(\ell-1)} is 256×512256\times512. A gradient always has the shape of the thing it differentiates, a quick test for transposition bugs.

What a gradient costs: time and memory

Time. Count FLOPs for one dense layer with ninn_{\text{in}} inputs, noutn_{\text{out}} outputs and a batch of BB, taking a multiply–add as 2 FLOPs. The forward product HW⊤H W^\top costs 2Bninnout2Bn_{\text{in}}n_{\text{out}}. The backward pass needs two products of the same size: ΔW\Delta W to pass the error down, and Δ⊤H\Delta^\top H for the weight gradient. So the backward pass costs about twice the forward pass, and a training step about three times, or 66 FLOPs per weight per example. This is where the estimate C≈6NDC\approx6ND for training a model with NN parameters on DD tokens comes from (Kaplan et al., 2020). Elementwise work (activations, their derivatives, biases) adds only O(Bn)\order{Bn} per layer.

Beyond networks, the cheap gradient principle (Baur & Strassen, 1983, for arithmetic circuits; Griewank & Walther, 2008, for programs) guarantees that reverse mode returns the full gradient of a scalar function for a small constant multiple of the function's own operation count, independent of the number of inputs. The constant depends on the cost model; memory is the part that is not cheap.

Memory. The derivation needs H(ℓ−1)H^{(\ell-1)} and ϕ′(Z(ℓ−1))\phi'(Z^{(\ell-1)}) for every layer, and they are produced in the forward pass but consumed in reverse order. So all of them are stored at once: activation memory grows like depth × batch × width (× sequence length for transformers), while the weights grow like depth × width². For large batches and long sequences the activations, not the weights, fill the accelerator. Inference needs none of this, because each layer's input can be discarded once the next layer has it.

Gradient checkpointing trades compute for memory. Keep the activations only at every kk-th layer (the checkpoints) and discard the rest. During the backward pass, rerun the forward pass of one segment at a time from its checkpoint to regenerate its activations. Peak memory is about L/kL/k checkpoints plus one live segment of kk layers, minimized at k≈Lk\approx\sqrt L, for one extra forward pass in total. Chen, Xu, Zhang and Guestrin (2016) brought this O(L)\order{\sqrt L} scheme to deep networks and noted that applying it recursively cuts memory to O(log⁡L)\order{\log L} at O(Llog⁡L)\order{L\log L} extra forward computation. Checkpointing is older in automatic differentiation, where optimal ("binomial") schedules are known (Griewank & Walther, 2008).

Predict before you look

A 100-layer network is checkpointed every kk layers, so peak memory is about 100/k+k100/k + k layers' worth of activations. With the best kk, how many layers' worth is that (against 100 without checkpointing)?

Show the answer

20 layers

100/k+k100/k + k is smallest at k=100=10k = \sqrt{100} = 10, giving 10+10=2010 + 10 = 20: five times less memory, paid for with one extra forward pass, which raises the step's cost from about three forward passes to about four.

python
import torch
from torch.utils.checkpoint import checkpoint

class Deep(torch.nn.Module):
    def __init__(self, width=1024, depth=48):
        super().__init__()
        self.blocks = torch.nn.ModuleList(
            torch.nn.Sequential(torch.nn.Linear(width, width), torch.nn.GELU())
            for _ in range(depth))

    def forward(self, x):
        for block in self.blocks:
            # keep only the block's input; recompute its insides during backward
            x = checkpoint(block, x, use_reentrant=False)
        return x

Checkpointing every block, as here, stores one tensor per block instead of all the internals. PyTorch's documentation asks for use_reentrant to be passed explicitly and recommends False.

Forward mode versus reverse mode

Forward mode carries a tangent v˙\dot{\mathbf v} alongside every value, applying each primitive's JVP as the program runs. One forward-mode pass costs a small multiple of one evaluation and yields Jx˙J\dot{\mathbf x}: the derivative of every output along one input direction. One reverse-mode pass yields yˉJ\bar{\mathbf y}J: the derivative of one output combination with respect to every input. The shape of the function decides which is cheaper:

For f:Rn→Rmf:\R^n\to\R^mForward mode (JVP)Reverse mode (VJP)
One pass givesJvJ\mathbf v: one column combinationu⊤J\mathbf u^\top J: one row combination
Full Jacobiannn passesmm passes
Gradient of a loss (m=1m = 1)nn passes: one per weight1 pass
Extra memorynone beyond the current valuesevery intermediate needed by a VJP, until the sweep reaches it
Typical usefew inputs, many outputs; sensitivities; the outer pass of Hessian–vector productstraining: millions of inputs, one loss
A Hessian–vector product HvH\mathbf v costs a few gradients: run forward mode over the reverse-mode gradient ("forward-over-reverse"), without ever forming HH. The influence-function lesson uses exactly this.
python
import torch
from torch.func import jvp, vjp

A = torch.randn(1000, 3)
f = lambda x: torch.tanh(A @ x)              # f: R^3 -> R^1000
x = torch.randn(3)

y, Jv = jvp(f, (x,), (torch.ones(3),))      # forward mode: J v, one pass
y, pullback = vjp(f, x)                      # reverse mode: returns a function
uJ, = pullback(torch.ones(1000))             # u^T J, one pass
J = torch.stack([jvp(f, (x,), (e,))[1] for e in torch.eye(3)], dim=1)  # 3 passes

With 3 inputs and 1,000 outputs, the full Jacobian takes 3 forward-mode passes but 1,000 reverse-mode ones. Training is the opposite shape.

Check your understanding

A simulator maps 4 physical parameters to a 10,000-pixel image. You need the full Jacobian of the image with respect to the parameters. Which mode, and how many passes?

  1. Reverse mode, 1 pass, as for any gradient
  2. Forward mode, 4 passes
  3. Reverse mode, 4 passes
  4. Forward mode, 10,000 passes
Show the answer

B. Forward mode, 4 passes

Forward mode gives one column JeiJ\mathbf e_i per pass, so 4 passes cover all 4 parameters. Reverse mode gives one row per pass and would need 10,000. The rule: forward mode when inputs are few, reverse mode when outputs are few.

Autograd in PyTorch, and checking it

PyTorch builds the graph as your code runs (define-by-run): every operation on a tensor with requires_grad=True records a node holding its VJP and whatever it saved for it. Ordinary Python control flow just works: the graph records whichever operations actually ran, so a loop or a data-dependent branch can differ from one batch to the next. loss.backward() runs the reverse sweep from a scalar and adds each leaf's gradient into its .grad, then frees the graph. Four habits follow:

  • Zero (or set to None) the gradients before each backward pass, since .grad accumulates. Accumulation is a feature: summing gradients over several small batches simulates one big batch.
  • Wrap evaluation and parameter updates in torch.no_grad(), so nothing is recorded and no activations are kept.
  • Use .detach() to get the same values cut off from the graph, for logging or for a stop-gradient.
  • Use torch.autograd.grad(out, inputs) to get gradients as return values instead of in .grad; with create_graph=True the result is itself differentiable, which gives higher derivatives.
python
import torch
import torch.nn.functional as F

torch.manual_seed(0)
X, y = torch.randn(64, 10), torch.randint(0, 3, (64,))   # a batch: inputs, labels
W1 = (0.3 * torch.randn(32, 10)).requires_grad_()        # leaf tensors to train
W2 = (0.2 * torch.randn(3, 32)).requires_grad_()

for step in range(100):
    H = torch.tanh(X @ W1.T)               # the graph is recorded as this runs
    loss = F.cross_entropy(H @ W2.T, y)    # mean over the batch
    loss.backward()                        # reverse sweep: fills W1.grad, W2.grad
    with torch.no_grad():                  # the update itself is not recorded
        for W in (W1, W2):
            W -= 0.5 * W.grad
            W.grad = None                  # else the next backward() adds to it

features = H.detach()                      # same values, no graph attached

In real code torch.nn.Linear and torch.optim.SGD do this bookkeeping, and optimizer.zero_grad() resets the gradients.

A hand-written backward pass is easy to get subtly wrong, so test it. A gradient check compares it with central differences, (f(x+hei)−f(x−hei))/2h\big(f(\mathbf x + h\mathbf e_i) - f(\mathbf x - h\mathbf e_i)\big)/2h, whose truncation error is O(h2)\order{h^2} while rounding error grows like ϵmach/h\epsilon_{\text{mach}}/h. Use double precision, a step around 10−610^{-6}, a few random coordinates and the relative error. In double precision a correct gradient typically agrees to many digits, while a bug usually shows up as a disagreement in the first or second digit; kinks such as ReLU's at 00 can cause rare false alarms.

python
def max_rel_error(f, x, h=1e-6, k=5):
    """Autograd vs central differences on k random coordinates, in float64."""
    x = x.detach().double().requires_grad_()
    g = torch.autograd.grad(f(x), x)[0].reshape(-1)
    worst = 0.0
    for i in torch.randint(0, x.numel(), (k,)).tolist():
        e = torch.zeros(x.numel(), dtype=x.dtype)
        e[i] = h
        e = e.reshape(x.shape)
        with torch.no_grad():
            fd = (f(x + e) - f(x - e)).item() / (2 * h)
        worst = max(worst, abs(fd - g[i].item()) / max(abs(fd), abs(g[i].item()), 1e-12))
    return worst

# built in: checks every entry of the Jacobian; its defaults assume float64 inputs
torch.autograd.gradcheck(torch.tanh, (torch.randn(4, dtype=torch.double, requires_grad=True),))

f must return a scalar. torch.autograd.gradcheck raises an error on a mismatch; its documentation warns that it will likely fail on single-precision inputs.

Key takeaways

  • Backpropagation is reverse-mode automatic differentiation: the chain rule evaluated from the loss backward as a sequence of vector–Jacobian products, with adjoints summed where a value is used more than once.
  • For an MLP, δ(ℓ)=(W(ℓ+1)⊤δ(ℓ+1))⊙ϕ′(z(ℓ))\boldsymbol\delta^{(\ell)} = (W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)})\odot\phi'(\mathbf z^{(\ell)}) and ∂ℓ/∂W(ℓ)=δ(ℓ)h(ℓ−1)⊤\partial\ell/\partial W^{(\ell)} = \boldsymbol\delta^{(\ell)}\mathbf h^{(\ell-1)\top}; over a batch these become the matrix products Δ⊤H\Delta^\top H and ΔW\Delta W.
  • The backward pass costs about twice the forward FLOPs (6 FLOPs per weight per example in total), and it needs every stored activation, so memory grows with depth × batch; checkpointing every L\sqrt L layers cuts it to O(L)\order{\sqrt L} for one extra forward pass.
  • Forward mode (JVPs) costs one pass per input and reverse mode (VJPs) one pass per output: reverse for training, forward for few-input sensitivities and Hessian–vector products.
  • PyTorch records the graph as code runs and accumulates into .grad; use no_grad, detach and gradient checks in double precision.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

With z(ℓ+1)=W(ℓ+1)h(ℓ)+b(ℓ+1)\mathbf z^{(\ell+1)} = W^{(\ell+1)}\mathbf h^{(\ell)} + \mathbf b^{(\ell+1)} and h(ℓ)=ϕ(z(ℓ))\mathbf h^{(\ell)} = \phi(\mathbf z^{(\ell)}), which is the error signal δ(ℓ)=∂ℓ/∂z(ℓ)\boldsymbol\delta^{(\ell)} = \partial\ell/\partial\mathbf z^{(\ell)}?

  1. (W(ℓ+1)δ(ℓ+1))⊙ϕ′(z(ℓ))\big(W^{(\ell+1)}\boldsymbol\delta^{(\ell+1)}\big)\odot\phi'(\mathbf z^{(\ell)})
  2. (W(ℓ+1)⊤δ(ℓ+1))⊙ϕ′(z(ℓ+1))\big(W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}\big)\odot\phi'(\mathbf z^{(\ell+1)})
  3. (W(ℓ+1)⊤δ(ℓ+1))⊙ϕ′(z(ℓ))\big(W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}\big)\odot\phi'(\mathbf z^{(\ell)})
  4. W(ℓ+1)⊤δ(ℓ+1)W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}, with no activation term
Show the answer

C. (W(ℓ+1)⊤δ(ℓ+1))⊙ϕ′(z(ℓ))\big(W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}\big)\odot\phi'(\mathbf z^{(\ell)})

The VJP of h↦Wh\mathbf h\mapsto W\mathbf h multiplies by W⊤W^\top, and the VJP of the elementwise activation multiplies by ϕ′\phi' at the layer's own pre-activation z(ℓ)\mathbf z^{(\ell)}.

Question 2

About how many FLOPs does one training step (forward plus backward) spend per weight of a dense layer, per example?

  1. 66
  2. 22
  3. 44
  4. 33
Show the answer

A. 66

Forward: one multiply–add per weight per example, 22 FLOPs. Backward: two products of the same size, ΔW\Delta W and Δ⊤H\Delta^\top H, another 44. Total 66, hence C≈6NDC\approx6ND.

Question 3

Why do deep learning libraries train with reverse mode rather than forward mode?

  1. Forward mode gives only approximate derivatives
  2. Reverse mode needs less memory
  3. Forward mode cannot handle nonlinear activations
  4. The loss is one number depending on millions of weights, and reverse mode gets all of their derivatives in one pass instead of one pass per weight
Show the answer

D. The loss is one number depending on millions of weights, and reverse mode gets all of their derivatives in one pass instead of one pass per weight

For f:Rn→Rf:\R^n\to\R reverse mode costs one sweep for the whole gradient; forward mode costs nn sweeps. Reverse mode pays for it in memory, since it must store intermediates.

Question 4

A training loop calls loss.backward() and steps the optimizer, but never zeroes the gradients. What happens?

  1. Nothing: backward() overwrites .grad each time
  2. Each .grad holds the sum of all gradients so far, so the steps keep growing and point in a stale direction
  3. PyTorch raises an error on the second call
  4. The gradients are averaged over steps, which acts like momentum
Show the answer

B. Each .grad holds the sum of all gradients so far, so the steps keep growing and point in a stale direction

backward() adds into .grad. Without zeroing, step tt uses the sum of tt gradients. Deliberate accumulation over a few micro-batches, followed by one step and a reset, is how large batches are simulated.

Go deeper

Further reading

  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, §6.5 "Back-Propagation and Other Differentiation Algorithms" (MIT Press, 2016).
  • A. G. Baydin, B. A. Pearlmutter, A. A. Radul & J. M. Siskind, "Automatic differentiation in machine learning: a survey," Journal of Machine Learning Research 18(153) (2018).
  • A. Griewank & A. Walther, Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation (2nd ed., SIAM, 2008).
  • T. Chen, B. Xu, C. Zhang & C. Guestrin, "Training deep nets with sublinear memory cost," arXiv:1604.06174 (2016).