concept / backpropagation
Next task →
University/Deep Learning/Training mechanics/Backpropagation and Computational Graphs
Deep Learning · Training mechanics · Gradient computation

Backpropagation and Computational Graphs

Backpropagation is reverse-mode automatic differentiation: it composes local derivatives in reverse topological order of a computational graph, obtaining the gradient of one scalar loss with respect to every parameter at roughly the cost of one forward pass.

39 sectionsintermediate200 minhand-authored · structural 73/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Backpropagation ("backprop") is an algorithm for computing derivatives through a computational graph. A computation such as y^=σ(W2 ReLU(W1x+b1)+b2)\hat y=\sigma(W_2\,\mathrm{ReLU}(W_1x+b_1)+b_2) is represented as a directed acyclic graph (DAG) whose nodes are elementary operations (matrix multiply, bias add, ReLU, sigmoid, loss) and whose edges carry intermediate values.

The algorithm has two phases:

  1. Forward pass: evaluate every node in topological order, storing its value.
  2. Backward pass: starting from the scalar loss LL with adjoint Lˉ=1\bar L=1, visit nodes in reverse topological order and push derivatives backward using the multivariable chain rule.

For each node viv_i we store the adjoint vˉi=∂L/∂vi\bar v_i=\partial L/\partial v_i. The recurrence is

vˉi=∑j∈children(i)vˉj ∂vj∂vi∣forward values,\bar v_i=\sum_{j\in\mathrm{children}(i)}\bar v_j\,\frac{\partial v_j}{\partial v_i}\Big|_{\text{forward values}},

i.e. sum the "sensitivity coming from downstream" weighted by each local derivative. Because a scalar output has one adjoint seed, reverse mode obtains all dd partial derivatives in one sweep — the reason deep networks with billions of parameters are trainable.

2. Why this concept exists

Three ways to get derivatives were available before reverse-mode AD became standard:

  • Finite differences: gi≈(f(θ+hei)−f(θ−hei))/(2h)g_i\approx(f(\theta+he_i)-f(\theta-he_i))/(2h) costs 2d2d forward evaluations. For d=109d=10^9 parameters this is physically impossible, and it is inaccurate (hh trades truncation against roundoff; best relative error is about ϵmach≈10−8\sqrt{\epsilon_{\text{mach}}}\approx10^{-8} in double precision, far worse in fp16).
  • Symbolic differentiation: expand the derivative expression algebraically. It produces exponentially large expressions and cannot handle control flow or data-dependent graphs.
  • Forward-mode AD: propagate tangents v˙i=∂vi/∂θ1\dot v_i=\partial v_i/\partial\theta_1 alongside values. One pass gives derivatives with respect to one input direction; a full gradient needs dd passes, i.e. O(dC)O(dC) work.

Reverse mode flips this: because neural-network losses are scalar functions of a huge parameter vector, one forward + one backward sweep yields the whole gradient in O(C)O(C), where CC is the forward cost. That single asymmetry is why backpropagation, not forward mode, powers deep learning.

3. Historical background

The mathematical core predates neural networks. Seppo Linnainmaa (1970) published the reverse mode of automatic differentiation (he called it "the representation of the computed result as a Taylor expansion" and described the reverse accumulation of derivatives); his master's thesis is often cited as the first published reverse-mode AD algorithm. Paul Werbos (1974) described applying such a procedure to neural networks in his Harvard PhD thesis. David Parker (1985) independently derived it for connectionist models. Rumelhart, Hinton and Williams (1986) popularized the method in the seminal Nature paper "Learning representations by back-propagating errors", combining it with gradient descent and demonstrating hidden-layer representations. Schmidhuber (2015) provides a historical survey; Baydin, Pearlmutter, Radul and Siskind (2018) give the modern AD survey that unifies backprop with reverse-mode AD. Today frameworks (PyTorch, JAX, TensorFlow) treat backprop as a special case of differentiable programming.

4. Fundamental problem

Given a scalar objective L=f(x;θ)L=f(x;\theta) built from elementary differentiable operations, compute ∇θL∈Rd\nabla_\theta L\in\mathbb{R}^d exactly (to floating-point precision) and efficiently (a small constant multiple of the cost of evaluating LL), without forming the full Jacobian of any intermediate layer.

Two structural facts make this possible:

  1. The composition is a DAG, so a topological order exists and local derivatives can be composed without cycles.
  2. The output is scalar, so the adjoint at the output is the scalar 11 and reverse accumulation is well-defined with a single seed.

The hard part is bookkeeping: you must retain the forward values needed to evaluate local derivatives (e.g. σ′(a)\sigma'(a) needs aa) and you must sum contributions from every downstream consumer before a node's adjoint is final.

5. First-principles explanation

Start from the multivariable chain rule. Suppose node viv_i feeds nodes vj1,…,vjkv_{j_1},\dots,v_{j_k}, and LL depends on viv_i only through them. Then

∂L∂vi=∑m=1k∂L∂vjm∂vjm∂vi.\frac{\partial L}{\partial v_i}=\sum_{m=1}^{k}\frac{\partial L}{\partial v_{j_m}}\frac{\partial v_{j_m}}{\partial v_i}.

Written with adjoints, vˉi=∑mvˉjm ∂vjm/∂vi\bar v_i=\sum_m \bar v_{j_m}\,\partial v_{j_m}/\partial v_i. This is recursive: to know vˉi\bar v_i you need adjoints of consumers, which are later in the graph. Hence process nodes in reverse topological order — consumers before producers.

Local rules for common nodes (evaluated at forward values):

  • Add: v_i=a+b\Rightarrow \bar a\)+=\bar v_i,, \bar b+=+=\bar v_i$.
  • Multiply: vi=ab⇒aˉv_i=ab\Rightarrow \bar a+=vˉib\bar v_i b, bˉ\bar b+=vˉia\bar v_i a.
  • Matrix multiply: Vi=AB⇒AˉV_i=AB\Rightarrow \bar A+=VˉiB⊤\bar V_i B^\top, Bˉ\bar B+=A⊤VˉiA^\top\bar V_i.
  • Unary ϕ\phi: vi=ϕ(a)⇒aˉv_i=\phi(a)\Rightarrow \bar a+=vˉi ϕ′(a)\bar v_i\,\phi'(a).

Each rule is just the chain rule applied to one elementary op. "Backpropagation" is nothing more than these rules executed in the right order.

6. Prerequisite concepts

Required background: (a) partial derivatives and the gradient as a vector; (b) the multivariable chain rule, including the Jacobian matrix Jij=∂vi/∂xjJ_{ij}=\partial v_i/\partial x_j; (c) matrix calculus identities such as ∂(AB)/∂A\partial(A B)/\partial A and the transpose pattern in VJPs; (d) directed acyclic graphs and topological sorting; (e) gradient descent, since backprop supplies the gradient it consumes; (f) basic numerical precision concepts to understand gradient checking. See the linked concepts for each.

7. Complete mathematical formulation

Graph. Let G=(V,E)G=(V,E) with nodes v1,…,vnv_1,\dots,v_n in topological order and vn=L∈Rv_n=L\in\mathbb{R}. Each node is vi=ϕi((vp)p∈pa(i))v_i=\phi_i\big((v_p)_{p\in\mathrm{pa}(i)}\big) for elementary ϕi\phi_i.

Forward pass. For i=1,…,ni=1,\dots,n: compute and cache viv_i and any quantities needed for ϕi′\phi_i' (e.g. the pre-activation of a sigmoid).

Backward pass. Initialize vˉn=1\bar v_n=1 and vˉi=0\bar v_i=0 for i<ni<n. For i=n−1,…,1i=n-1,\dots,1:

vˉi=∑j: i→j(Jϕj∣v)⊤vˉj,\bar v_i=\sum_{j:\,i\to j}\big(J_{\phi_j}\big|_{v}\big)^\top\bar v_j ,

where Jϕj∣vJ_{\phi_j}|_{v} is the Jacobian of node jj with respect to its input viv_i, evaluated at cached forward values. The operation v↦J⊤vv\mapsto J^\top v is a vector-Jacobian product (VJP).

Parameter gradients. If θ\theta are leaf nodes (inputs to the graph), ∇θL=θˉ\nabla_\theta L=\bar\theta after the sweep.

Key identity (pathwise form). Unrolling the recurrence gives

∂L∂vi=∑paths i→n∏e∈path∂vhead(e)∂vtail(e),\frac{\partial L}{\partial v_i}=\sum_{\text{paths }i\to n}\prod_{e\in\text{path}}\frac{\partial v_{\text{head}(e)}}{\partial v_{\text{tail}(e)}},

so backprop efficiently sums sensitivity over all paths from a node to the loss without enumerating them.

8. Notation dictionary

| Symbol | Meaning | Type | |---|---|---| | G=(V,E)G=(V,E) | computational graph of elementary ops | DAG | | viv_i | value of node ii (cached in forward pass) | tensor | | vˉi=∂L/∂vi\bar v_i=\partial L/\partial v_i | adjoint / cotangent of node ii | tensor, same shape as viv_i | | pa(i)\mathrm{pa}(i), children(i)\mathrm{children}(i) | parents and consumers of node ii | index sets | | ϕi\phi_i | elementary function computed at node ii | differentiable map | | JϕiJ_{\phi_i} | Jacobian of node ii w.r.t. its inputs | matrix / linear operator | | vˉi=J⊤uˉ\bar v_i = J^\top \bar u | vector-Jacobian product (VJP) | linear map application | | θ\theta | leaf/parameter nodes | tensors | | LL | scalar loss, root of the graph | scalar | | CC | cost of one forward evaluation | flops | | ϵmach\epsilon_{\text{mach}} | machine precision (~10−1610^{-16} fp64) | scalar |

9. Step-by-step derivation

Step 1 — set up a concrete graph. Consider the scalar network a=wx+b,z=σ(a)=11+e−a,L=(z−y)2.a=wx+b,\qquad z=\sigma(a)=\frac{1}{1+e^{-a}},\qquad L=(z-y)^2 . Nodes in order: v1=w, v2=x, v3=b, v4=a, v5=z, v6=e=z−y, v7=L=e2v_1=w,\ v_2=x,\ v_3=b,\ v_4=a,\ v_5=z,\ v_6=e=z-y,\ v_7=L=e^2.

Step 2 — forward pass with numbers. Take w=2w=2, x=1x=1, b=0b=0, y=0.8y=0.8. Then a=2a=2, z=σ(2)=0.880797z=\sigma(2)=0.880797, e=0.080797e=0.080797, L=0.0065282L=0.0065282. Cache aa (needed for σ′\sigma') and ee.

Step 3 — seed the adjoint. LL is the output, so Lˉ=∂L/∂L=1\bar L=\partial L/\partial L=1.

Step 4 — walk backward through each node.

  • Square: L=e2⇒eˉ=Lˉ⋅2e=1⋅0.161594=0.161594L=e^2\Rightarrow \bar e=\bar L\cdot 2e=1\cdot0.161594=0.161594.
  • Subtract: e=z−y⇒zˉ=eˉ=0.161594e=z-y\Rightarrow \bar z=\bar e=0.161594 (and yˉ=−eˉ\bar y=-\bar e, ignored since yy is data).
  • Sigmoid: z=σ(a)z=\sigma(a), σ′(a)=σ(a)(1−σ(a))=0.880797×0.119203=0.104994\sigma'(a)=\sigma(a)(1-\sigma(a))=0.880797\times0.119203=0.104994, so aˉ=zˉ σ′(a)=0.161594×0.104994=0.016966\bar a=\bar z\,\sigma'(a)=0.161594\times0.104994=0.016966.
  • Affine: a=wx+b⇒wˉ=aˉ x=0.016966a=wx+b\Rightarrow \bar w=\bar a\,x=0.016966, bˉ=aˉ=0.016966\bar b=\bar a=0.016966, xˉ=aˉ w=0.033932\bar x=\bar a\,w=0.033932.

Step 5 — verify. Central difference with h=10−3h=10^{-3}: (L(2.001)−L(1.999))/(2h)≈0.01697(L(2.001)-L(1.999))/(2h)\approx0.01697, matching wˉ=0.016966\bar w=0.016966 to about 4 digits (difference limited by the finite-difference truncation error). This is the standard gradient check.

Step 6 — generalise. For vector/matrix nodes, replace scalar multiplications by VJPs: Aˉ\bar A+=VˉB⊤\bar V B^\top and Bˉ\bar B+=A⊤VˉA^\top\bar V for V=ABV=AB. Nothing else changes.

10. Proofs and proof intuition

Lemma 1 (correctness of reverse accumulation). After the backward sweep, vˉi=∂L/∂vi\bar v_i=\partial L/\partial v_i for every node ii.

Proof (backward induction on topological position). For the root vn=Lv_n=L, vˉn=1=∂L/∂L\bar v_n=1=\partial L/\partial L. Assume the claim holds for all consumers jj of node ii (they are later in topological order and hence already processed). By the multivariable chain rule, ∂L/∂vi=∑j:i→j(∂L/∂vj)(∂vj/∂vi)=∑j:i→jvˉjJji\partial L/\partial v_i=\sum_{j:i\to j}(\partial L/\partial v_j)(\partial v_j/\partial v_i)=\sum_{j:i\to j}\bar v_j J_{ji}, which is exactly the update the algorithm performs. □\square

Lemma 2 (cost). Reverse mode evaluates the gradient of a scalar output in at most cc times the forward cost, for a small constant cc (typically 2≤c≤42\le c\le4).

Proof sketch. Each elementary forward op of cost cic_i has a VJP of cost O(ci)O(c_i) (matrix multiply's VJP is two matrix multiplies; elementwise ops' VJPs are elementwise). Summing over nodes gives backward work O(∑ici)=O(C)O(\sum_i c_i)=O(C); together with the forward pass, total work is O(C)O(C) and empirically about 3C3C. □\square

Lemma 3 (path-sum identity). ∂L/∂vi=∑paths p:i→n∏e∈p∂vhead(e)/∂vtail(e)\partial L/\partial v_i=\sum_{\text{paths }p:i\to n}\prod_{e\in p}\partial v_{\text{head}(e)}/\partial v_{\text{tail}(e)} for a DAG with scalar output.

Proof. Expand the recursive chain rule; each consumer contributes products over paths through it, and because the graph is acyclic the recursion terminates at the root with no repeated paths. □\square

Proof intuition. Backprop is dynamic programming over the DAG: the adjoint at a node is a cached "influence on the loss", so an exponential number of paths is summed with linear work.

11. Geometric interpretation

Think of the forward pass as pushing a tangent vector forward through linear maps (forward mode): a perturbation δx\delta x becomes δv=J δx\delta v = J\,\delta x. The backward pass pulls a cotangent vector back: a sensitivity Lˉ\bar L on the output becomes xˉ=J⊤Lˉ\bar x=J^\top\bar L on the input. Cotangents live in the dual space; the adjoint is the gradient expressed in the primal space via the Euclidean inner product.

Geometrically, each layer's Jacobian maps "how inputs move" to "how outputs move"; its transpose maps "how much the output matters" back to "how much the input matters". Backprop composes these transpose maps from the loss backward to the parameters. The resulting gradient is the direction of steepest increase in weight space, so gradient descent moves opposite it.

12. Visual explanation

Draw the small graph w,x oa oz oe oLw,x\ o a\ o z\ o e\ o L (with b oab\ o a, y oey\ o e) as boxes with forward arrows left-to-right. Annotate each forward arrow with its value (a=2a=2, z=0.8808z=0.8808, e=0.0808e=0.0808, L=0.0065282L=0.0065282). Then draw backward arrows right-to-left, labelled with adjoints (\arL=1\ar L=1, \are=0.1616\ar e=0.1616, \arz=0.1616\ar z=0.1616, \ara=0.01697\ar a=0.01697, \arw=\arb=0.01697\ar w=\ar b=0.01697, \arx=0.03393\ar x=0.03393). The backward arrows fan out at "add" and "multiply" nodes (multiple contributions summed) and shrink or grow at nonlinear nodes depending on the local derivative magnitude. Use the interactive Computational Graph Playground to hover a node and see both its value and adjoint, and to compare with a finite-difference perturbation of that node.

13. Numerical worked example

Use the graph above with w=2,x=1,b=0,y=0.8w=2,x=1,b=0,y=0.8:

| Node | Forward value | Adjoint (backward) | |---|---|---| | ww | 2 | 0.016966 | | xx | 1 | 0.033932 | | bb | 0 | 0.016966 | | a=wx+ba=wx+b | 2 | 0.016966 | | z=σ(a)z=\sigma(a) | 0.880797 | 0.161594 | | e=z−ye=z-y | 0.080797 | 0.161594 | | L=e2L=e^2 | 0.0065282 | 1 |

Check ∂L/∂a=∂L/∂z⋅σ′(a)=0.161594×0.104994=0.016966\partial L/\partial a=\partial L/\partial z\cdot\sigma'(a)=0.161594\times0.104994=0.016966; and ∂L/∂w=∂L/∂a⋅x=0.016966×1=0.016966\partial L/\partial w=\partial L/\partial a\cdot x=0.016966\times1=0.016966, while ∂L/∂x=∂L/∂a⋅w=0.016966×2=0.033932\partial L/\partial x=\partial L/\partial a\cdot w=0.016966\times2=0.033932 — the parameter and the input differ by the factor ww because the same sensitivity is multiplied by different local derivatives. Finite differences agree to four significant figures, confirming the sweep.

14. Real-world analogy

Imagine a factory supply chain. The forward pass turns raw materials (parameters and inputs) into a finished product (the loss), recording how much of each intermediate was used. Now ask: "if the final customer value changes by one dollar, how much does each supplier's contribution matter?" The answer propagates backward along the chain: each station distributes blame/credit to its suppliers in proportion to its local recipe derivative, and stations with multiple outgoing products sum their contributions. No supplier is consulted directly — only local recipes and recorded quantities are needed. That is backpropagation.

15. Algorithm pseudocode

algorithm Backpropagate(G, values, loss_node, parameters):
    # G in topological order v[1..n]; values[i] cached from forward pass
    for i = 1 .. n: adjoint[i] <- 0
    adjoint[loss_node] <- 1
    for i = n-1 downto 1:                 # reverse topological order
        acc <- 0
        for each edge (v[i] -> v[j]):
            J_local <- local_derivative(op[j], values)  # d v[j] / d v[i]
            acc <- acc + J_local^T @ adjoint[j]         # VJP
        adjoint[i] <- adjoint[i] + acc
    return [adjoint[p] for p in parameters]            # the gradient
# Memory optimisation: release values[i] once all its consumers are processed.

16. Implementation from scratch

import math

class Value:
    """Minimal reverse-mode AD node (scalar)."""
    def __init__(self, data, parents=(), op=""):
        self.data, self.parents, self.op = data, parents, op
        self.grad = 0.0
        self._backward = lambda: None

    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, (self, other), "+")
        def _backward():
            self.grad  += out.grad
            other.grad += out.grad
        out._backward = _backward
        return out

    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, (self, other), "*")
        def _backward():
            self.grad  += out.grad * other.data
            other.grad += out.grad * self.data
        out._backward = _backward
        return out

    def __sub__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data - other.data, (self, other), "-")
        def _backward():
            self.grad += out.grad
            other.grad -= out.grad
        out._backward = _backward
        return out

    def __rsub__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        return other - self

    def sigmoid(self):
        s = 1 / (1 + math.exp(-self.data))
        out = Value(s, (self,), "sigmoid")
        out._backward = lambda: setattr(self, "grad", self.grad + out.grad * s * (1 - s))
        return out

    def backward(self):
        topo, seen = [], set()
        def build(v):
            if id(v) in seen: return
            seen.add(id(v))
            for p in v.parents: build(p)
            topo.append(v)
        build(self)
        self.grad = 1.0
        for v in reversed(topo): v._backward()

w, x, b, y = Value(2.0), Value(1.0), Value(0.0), Value(0.8)
a = w * x + b
z = a.sigmoid()
L = (z - y) * (z - y)
L.backward()
print(L.data, w.grad, b.grad, x.grad)   # ~0.0065282, ~0.016966, ~0.016966, ~0.033932

17. Professional library implementation

import torch

x = torch.tensor([1.0])
w = torch.tensor([2.0], requires_grad=True)
b = torch.tensor([0.0], requires_grad=True)
y = torch.tensor([0.8])

a = w * x + b
z = torch.sigmoid(a)
L = (z - y) ** 2
print(L.item(), z.grad_fn)     # grad_fn records the backward recipe
L.backward()                   # reverse-mode sweep; fills .grad
print(w.grad, b.grad)          # tensor([0.0170]), tensor([0.0170])

# Vector-Jacobian products without materialising a Jacobian:
v = torch.tensor([1.0])
grad = torch.autograd.grad(z, a, grad_outputs=v, retain_graph=True)[0]
# Hessian-vector product = reverse-on-reverse:
hvp = torch.autograd.grad(grad, w, grad_outputs=torch.ones_like(grad))[0]

For production training use loss.backward() followed by optimizer.step(); wrap the backward in torch.cuda.amp.autocast / GradScaler for mixed precision.

18. Code walkthrough

Scratch engine. Each Value stores its forward data, a closure _backward implementing the local rule, and an accumulated grad. backward() first builds a topological order by depth-first search (parents before children) and then traverses it in reverse, seeding the root with grad=1. The "+=" in every local rule is essential: a node can feed multiple consumers and must sum all contributions.

PyTorch version. Every operation on a requires_grad=True tensor creates a grad_fn node that knows its VJP, forming a dynamic graph. backward() performs the same reverse topological sweep in C++. torch.autograd.grad exposes arbitrary VJPs; applying reverse mode twice yields Hessian-vector products, which is how second-order methods avoid building the full Hessian. Note that gradients accumulate by default, so optimizer.zero_grad() must be called each iteration.

19. Tensor and memory analysis

For a network with LL layers of width dd and batch size BB in fp32 (4 bytes):

  • activations to cache: 4BdL4BdL bytes for one pre-activation per layer (more for attention, which stores QK⊤QK^\top of shape B×h×n×nB\times h\times n\times n);
  • adjoints: another 4BdL4BdL bytes, though many frameworks free activations as soon as their consumers are done;
  • parameters and gradients: 4dparam4d_{\text{param}} and 4dparam4d_{\text{param}} bytes.

Example: B=32B=32, d=4096d=4096, L=48L=48 gives 4⋅32⋅4096⋅48≈254\cdot32\cdot4096\cdot48\approx25 MB of cached activations — modest for MLPs but attention's O(n2)O(n^2) scores dominate at long context. Gradient checkpointing stores only every L\sqrt L-th activation and recomputes the rest during backward, reducing activation memory from O(L)O(L) to O(L)O(\sqrt L) at the cost of one extra forward pass (about 33% more compute).

20. Time complexity

Forward cost C=∑iciC=\sum_i c_i; backward cost is O(C)O(C) because each VJP costs the same order as its forward op (concretely about 2C2C for typical nets), so one gradient costs about 3C3C. Compare: finite differences O(dC)O(dC), forward-mode AD O(dC)O(dC), symbolic differentiation potentially exponential. Backprop therefore scales independently of the number of parameters — it scales with the cost of one forward evaluation. For a transformer, C∼O(Bnd2+Bn2d)C\sim O(B n d^2 + B n^2 d) and the backward has the same asymptotic cost.

21. Space complexity

Naive reverse mode stores all intermediate values: O(B∑ldl)O(B\sum_l d_l) for a plain stack, O(Bhn2L)O(B h n^2 L) if attention scores are retained. Adjoints are the same size as their values, so peak memory is roughly twice the forward activation memory plus parameters. With checkpointing, activation memory drops to O(L)O(\sqrt L) times per-layer size while compute rises to about 4C4C. In-place operations can reduce memory but break the cache if a needed value is overwritten — a classic source of autodiff errors.

22. Experimental demonstration

Implement the scalar engine above and run three checks. (1) Gradient check: for the graph with w=2,x=1,b=0,y=0.8w=2,x=1,b=0,y=0.8, compare w.grad to (L(w+h)−L(w−h))/(2h)(L(w+h)-L(w-h))/(2h) for h∈{10−2,10−3,10−4,10−5}h\in\{10^{-2},10^{-3},10^{-4},10^{-5}\}; expect agreement improving to ~10−710^{-7} relative error then degrading from roundoff for too-small hh. (2) Timing: build a chain of kk multiplies for k=10,102,103,104k=10,10^2,10^3,10^4 and measure forward vs backward time; the ratio should stay near a small constant (~2), confirming O(C)O(C). (3) Compare with a hand-written forward-mode tangent propagation on the same graph: it needs one pass per input and should be O(d)O(d) slower for many inputs.

23. Benchmark results

On the scalar example, backprop gives wˉ=0.016966\bar w=0.016966 while the best finite-difference estimate gives 0.01696630.0169663 — a relative error near 10−610^{-6} in double precision, versus machine-precision accuracy for backprop. For a 3-layer MLP with d=512d=512 and B=64B=64, one forward+backward is typically ~3x the forward time in PyTorch. In JAX, reverse mode of a scalar loss is likewise ~2.5–3x forward. These ratios are architectural constants, not universal laws: memory-bound ops (softmax, layernorm) can make the backward relatively cheaper, while recomputation or eager graph construction makes it more expensive.

24. Limitations

  • Requires every operation to be differentiable (or to have a defined subgradient); argmax, sampling and control flow need straight-through estimators or reparameterisations.
  • Must cache forward activations, so memory grows with depth and batch size.
  • The reverse sweep is sequential along the graph; it cannot begin until the forward pass finishes, limiting pipeline parallelism.
  • Eager frameworks pay graph-construction overhead; compiled frameworks trade flexibility for speed.
  • Higher-order derivatives need additional machinery (double backward, forward-over-reverse).
  • In-place mutation of cached values silently corrupts gradients.
  • Non-smooth points (ReLU at 0) require a subgradient convention; frameworks pick one arbitrarily.

25. Failure scenarios

  1. Exploding gradients: in an LL-layer chain with Jacobian singular values s>1s>1, gradients grow like sLs^L; clip the global norm.
  2. Vanishing gradients: s<1s<1 makes gradients decay exponentially; use residual connections, normalization and appropriate activations.
  3. Forgotten zero_grad(): gradients accumulate across iterations, so the effective update is a sum of stale gradients — training diverges or plateaus.
  4. Detached tensors: converting to Python (.item()) or calling .detach() cuts the graph; downstream gradients are zero or nonexistent.
  5. In-place overwrite: editing a tensor saved for backward raises a version-counter error in PyTorch or yields wrong derivatives in custom code.
  6. NaN propagation: a single NaN in a local derivative contaminates every adjoint upstream; use anomaly detection to locate the source.
  7. Assuming independence: treating a node with multiple consumers as if only one path exists omits terms in vˉi\bar v_i — the most common bug in hand-written backward functions.

26. Common misconceptions

  • "Backpropagation is a learning algorithm." It only computes derivatives; gradient descent (or AdamW) performs the learning update.
  • "Backprop stores a gradient for every weight." It stores one adjoint per graph node; weight gradients are just the adjoints of leaf nodes.
  • "Backprop is how the brain learns." It is a computational technique; biological plausibility is debated and not assumed.
  • "Forward and reverse mode are equally efficient." Reverse mode wins by a factor of dd for scalar outputs; forward mode wins for many outputs with few inputs.
  • "Automatic differentiation is symbolic differentiation." AD evaluates local derivatives numerically at cached values and never expands expressions symbolically.
  • "More gradient checks are always better." Checking every parameter on a huge model is expensive; check a random subset with double precision.

27. Alternative approaches

  • Finite differences: trivial to implement, O(d)O(d) cost, useful only as a correctness check.
  • Forward-mode AD: propagates tangents; efficient for few inputs / many outputs, e.g. curvature or sensitivity analysis.
  • Manual derivatives: hand-coded gradient kernels can be faster but are error-prone and brittle to architecture changes.
  • Symbolic differentiation: useful for compact expressions via SymPy; explodes on deep compositions.
  • Gradient checkpointing / recomputation: trades compute for activation memory; not a different derivative algorithm.
  • Second-order methods: use Hessian-vector products (reverse-on-reverse) or K-FAC approximations for curvature-aware updates.

29. Research applications

  • Deep learning training: every gradient-based update in vision, language and speech models.
  • Scientific machine learning: physics-informed neural networks where PDE residuals differentiate through solver steps.
  • Differentiable rendering / simulation: gradients through rasterizers and physics engines for inverse problems.
  • Meta-learning and hyperparameter optimisation: differentiating through the training loop (reverse-on-reverse).
  • Neural ODEs: adjoint sensitivities for continuous-depth models.
  • Probabilistic programming: variational inference via the reparameterisation trick and autodiff.

30. Important research papers

  • Linnainmaa S. (1970), The representation of the computed result as a Taylor expansion (Master's thesis) — first published reverse-mode AD.
  • Werbos P. J. (1974), Beyond Regression: New Tools for Prediction and Analysis in the Behavioral Sciences, PhD thesis, Harvard — backprop for neural networks.
  • Rumelhart D. E., Hinton G. E., Williams R. J. (1986), Learning representations by back-propagating errors, Nature 323:533–536.
  • Parker D. B. (1985), Learning Logic, Technical Report MIT-TR-247 — independent rediscovery.
  • Baydin A. G., Pearlmutter B. A., Radul A. A., Siskind J. M. (2018), Automatic differentiation in machine learning: a survey, JMLR 18(153).
  • Schmidhuber J. (2015), Deep learning in neural networks: an overview, Neural Networks 61:85–117 — historical survey.

31. Further reading

  • Baydin et al. (2018), JMLR 18:1–43 — the definitive AD survey.
  • Goodfellow, Bengio & Courville, Deep Learning (2016), chapter 6.5 — backprop derivation.
  • Stanford CS231n notes on backpropagation: cs231n.github.io/optimization-2/.
  • JAX documentation on jax.grad, jax.vjp and jax.jvp: docs.jax.dev.
  • PyTorch autograd mechanics: docs.pytorch.org/docs/stable/notes/autograd.html.

32. Practical exercises

  1. Implement the scalar Value class from memory, including +, *, sigmoid and backward(); reproduce the printed numbers for w=2,x=1,b=0,y=0.8w=2,x=1,b=0,y=0.8.
  2. Add -, /, tanh and exp nodes with correct local derivatives; gradient-check each against finite differences.
  3. Build a two-layer MLP with your engine on a toy classification dataset and train it for 100 steps; verify the loss decreases.
  4. Write the VJP rules for A @ B and for softmax, and confirm shapes by printing adjoint shapes in PyTorch.
  5. Use torch.autograd.grad to compute a Hessian-vector product of L(w)=∑iwi4L(w)=\sum_i w_i^4 and compare with the analytic Hij=12wi2δijH_{ij}=12 w_i^2\delta_{ij}.
  6. Measure forward/backward time for chain lengths 10,102,103,10410,10^2,10^3,10^4 and confirm the ratio is roughly constant.

33. Debugging challenges

  • Gradient is None in PyTorch: the tensor is not connected to the loss (missing requires_grad or a .detach() somewhere).
  • Gradients are twice as large as expected: you forgot zero_grad() and the values accumulated over two iterations.
  • Custom backward passes a gradient check only for some nodes: check the "+=" accumulation — a node with two consumers was overwritten instead of summed.
  • NaN gradients appear after a few steps: locate the op with PyTorch's torch.autograd.set_detect_anomaly(True) and inspect its inputs.
  • Gradient check fails only in fp16: finite differences are inaccurate at low precision; switch the check to fp64.
  • Memory explodes at long sequence length: attention scores of shape Bhn2B h n^2 are cached; enable checkpointing or a memory-efficient attention kernel.

34. Advanced exercises

  1. Prove Lemma 3 (path-sum identity) formally by induction on DAG topological order.
  2. Implement forward-over-reverse AD to compute Hessian-vector products and verify on a nonconvex function.
  3. Derive and implement the VJP of the softmax function: xˉi=yi(yˉi−∑jyjyˉj)\bar x_i = y_i(\bar y_i - \sum_j y_j\bar y_j) where y=softmax(x)y=\mathrm{softmax}(x).
  4. Implement gradient checkpointing on a 10-layer MLP and measure the memory/compute trade-off against full caching.
  5. Build a custom torch.autograd.Function with a correct backward and gradient-check it at double precision.
  6. Compare eager PyTorch, torch.compile and JAX jit gradient timings on the same network; explain the differences by graph-rewrite overhead.

35. Interview questions

  • State the multivariable chain rule and show why nodes must be processed in reverse topological order.
  • Why is reverse mode much cheaper than forward mode for training neural networks? Give the O(C)O(C) vs O(dC)O(dC) argument.
  • What is a VJP and how does it avoid materialising a Jacobian?
  • Derive the backward rules for addition, multiplication, matrix multiply and sigmoid.
  • How would you compute a Hessian-vector product using only backprop?
  • What breaks if you reuse a cached activation after an in-place modification?
  • Explain why forgetting zero_grad() changes the update, mathematically.
  • When would you choose checkpointing, and what does it cost?

36. Research questions

  • Can automatic differentiation be made memory-optimal without recomputation, e.g. via optimal checkpoint schedules for heterogeneous graphs?
  • How do non-smooth operations (ReLU, argmax, clipping) affect the validity of gradients used in practice?
  • What is the overhead of dynamic graphs versus static graphs for sparse or data-dependent architectures?
  • Can higher-order derivatives be computed stably in low precision, and what are the error bounds?
  • How should autodiff systems handle stochastic nodes (sampling) to give unbiased gradients?
  • What role does reverse-mode AD play in differentiable science, and where does it fail for chaotic dynamics?

37. Mastery assessment

To pass: (1) derive the adjoint recurrence from the multivariable chain rule without notes; (2) hand-compute a small graph's forward values and adjoints with correct numbers; (3) implement a scalar reverse-mode engine passing a finite-difference gradient check to 10−610^{-6}; (4) state and justify the O(C)O(C) cost claim and contrast with forward mode; (5) diagnose at least three failure scenarios (exploding gradients, missing zero_grad, detached tensors). Complete the linked assessment, which mixes derivation, numerical and debugging items. Having merely read this page is not mastery.

38. Implementation submission

Push a repository containing: micrograd.py (scalar reverse-mode engine with at least five operations), tests/test_gradcheck.py (finite-difference checks at double precision to 10−610^{-6}), experiments.ipynb (toy MLP training, timing table for k=10,102,103,104k=10,10^2,10^3,10^4, and a Hessian-vector product), plus a README.md with the chain-rule derivation and observed forward/backward time ratios. Include the exact command to reproduce every number and a note on any discrepancy between analytic and finite-difference gradients.

39. Completion criteria

All of: the adjoint recurrence derived and the worked example reproduced on paper; scratch engine passing gradient checks; a toy network trained successfully with it; timing experiment showing near-constant forward/backward ratio; three failure scenarios reproduced and explained; assessment score at least 80%; one research question answered in a one-page note citing at least one paper. Only then mark the concept mastered in the task system.`

Research papers linked to this concept