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.
1. Concept overview
Backpropagation ("backprop") is an algorithm for computing derivatives through a computational graph. A computation such as 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:
- Forward pass: evaluate every node in topological order, storing its value.
- Backward pass: starting from the scalar loss with adjoint , visit nodes in reverse topological order and push derivatives backward using the multivariable chain rule.
For each node we store the adjoint . The recurrence is
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 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: costs forward evaluations. For parameters this is physically impossible, and it is inaccurate ( trades truncation against roundoff; best relative error is about 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 alongside values. One pass gives derivatives with respect to one input direction; a full gradient needs passes, i.e. 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 , where 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 built from elementary differentiable operations, compute exactly (to floating-point precision) and efficiently (a small constant multiple of the cost of evaluating ), without forming the full Jacobian of any intermediate layer.
Two structural facts make this possible:
- The composition is a DAG, so a topological order exists and local derivatives can be composed without cycles.
- The output is scalar, so the adjoint at the output is the scalar 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. needs ) 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 feeds nodes , and depends on only through them. Then
Written with adjoints, . This is recursive: to know 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: +=, +=.
- Matrix multiply: +=, +=.
- Unary : +=.
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 ; (c) matrix calculus identities such as 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 with nodes in topological order and . Each node is for elementary .
Forward pass. For : compute and cache and any quantities needed for (e.g. the pre-activation of a sigmoid).
Backward pass. Initialize and for . For :
where is the Jacobian of node with respect to its input , evaluated at cached forward values. The operation is a vector-Jacobian product (VJP).
Parameter gradients. If are leaf nodes (inputs to the graph), after the sweep.
Key identity (pathwise form). Unrolling the recurrence gives
so backprop efficiently sums sensitivity over all paths from a node to the loss without enumerating them.
8. Notation dictionary
| Symbol | Meaning | Type | |---|---|---| | | computational graph of elementary ops | DAG | | | value of node (cached in forward pass) | tensor | | | adjoint / cotangent of node | tensor, same shape as | | , | parents and consumers of node | index sets | | | elementary function computed at node | differentiable map | | | Jacobian of node w.r.t. its inputs | matrix / linear operator | | | vector-Jacobian product (VJP) | linear map application | | | leaf/parameter nodes | tensors | | | scalar loss, root of the graph | scalar | | | cost of one forward evaluation | flops | | | machine precision (~ fp64) | scalar |
9. Step-by-step derivation
Step 1 — set up a concrete graph. Consider the scalar network Nodes in order: .
Step 2 — forward pass with numbers. Take , , , . Then , , , . Cache (needed for ) and .
Step 3 — seed the adjoint. is the output, so .
Step 4 — walk backward through each node.
- Square: .
- Subtract: (and , ignored since is data).
- Sigmoid: , , so .
- Affine: , , .
Step 5 — verify. Central difference with : , matching 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: += and += for . Nothing else changes.
10. Proofs and proof intuition
Lemma 1 (correctness of reverse accumulation). After the backward sweep, for every node .
Proof (backward induction on topological position). For the root , . Assume the claim holds for all consumers of node (they are later in topological order and hence already processed). By the multivariable chain rule, , which is exactly the update the algorithm performs.
Lemma 2 (cost). Reverse mode evaluates the gradient of a scalar output in at most times the forward cost, for a small constant (typically ).
Proof sketch. Each elementary forward op of cost has a VJP of cost (matrix multiply's VJP is two matrix multiplies; elementwise ops' VJPs are elementwise). Summing over nodes gives backward work ; together with the forward pass, total work is and empirically about .
Lemma 3 (path-sum identity). 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.
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 becomes . The backward pass pulls a cotangent vector back: a sensitivity on the output becomes 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 (with , ) as boxes with forward arrows left-to-right. Annotate each forward arrow with its value (, , , ). Then draw backward arrows right-to-left, labelled with adjoints (, , , , , ). 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 :
| Node | Forward value | Adjoint (backward) | |---|---|---| | | 2 | 0.016966 | | | 1 | 0.033932 | | | 0 | 0.016966 | | | 2 | 0.016966 | | | 0.880797 | 0.161594 | | | 0.080797 | 0.161594 | | | 0.0065282 | 1 |
Check ; and , while — the parameter and the input differ by the factor 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 layers of width and batch size in fp32 (4 bytes):
- activations to cache: bytes for one pre-activation per layer (more for attention, which stores of shape );
- adjoints: another bytes, though many frameworks free activations as soon as their consumers are done;
- parameters and gradients: and bytes.
Example: , , gives MB of cached activations — modest for MLPs but attention's scores dominate at long context. Gradient checkpointing stores only every -th activation and recomputes the rest during backward, reducing activation memory from to at the cost of one extra forward pass (about 33% more compute).
20. Time complexity
Forward cost ; backward cost is because each VJP costs the same order as its forward op (concretely about for typical nets), so one gradient costs about . Compare: finite differences , forward-mode AD , 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, and the backward has the same asymptotic cost.
21. Space complexity
Naive reverse mode stores all intermediate values: for a plain stack, 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 times per-layer size while compute rises to about . 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 , compare w.grad to for ; expect agreement improving to ~ relative error then degrading from roundoff for too-small . (2) Timing: build a chain of multiplies for and measure forward vs backward time; the ratio should stay near a small constant (~2), confirming . (3) Compare with a hand-written forward-mode tangent propagation on the same graph: it needs one pass per input and should be slower for many inputs.
23. Benchmark results
On the scalar example, backprop gives while the best finite-difference estimate gives — a relative error near in double precision, versus machine-precision accuracy for backprop. For a 3-layer MLP with and , 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
- Exploding gradients: in an -layer chain with Jacobian singular values , gradients grow like ; clip the global norm.
- Vanishing gradients: makes gradients decay exponentially; use residual connections, normalization and appropriate activations.
- Forgotten
zero_grad(): gradients accumulate across iterations, so the effective update is a sum of stale gradients — training diverges or plateaus. - Detached tensors: converting to Python (
.item()) or calling.detach()cuts the graph; downstream gradients are zero or nonexistent. - In-place overwrite: editing a tensor saved for backward raises a version-counter error in PyTorch or yields wrong derivatives in custom code.
- NaN propagation: a single NaN in a local derivative contaminates every adjoint upstream; use anomaly detection to locate the source.
- Assuming independence: treating a node with multiple consumers as if only one path exists omits terms in — 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 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, 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.vjpandjax.jvp: docs.jax.dev. - PyTorch autograd mechanics: docs.pytorch.org/docs/stable/notes/autograd.html.
32. Practical exercises
- Implement the scalar
Valueclass from memory, including+,*, sigmoid andbackward(); reproduce the printed numbers for . - Add
-,/,tanhandexpnodes with correct local derivatives; gradient-check each against finite differences. - Build a two-layer MLP with your engine on a toy classification dataset and train it for 100 steps; verify the loss decreases.
- Write the VJP rules for
A @ Band for softmax, and confirm shapes by printing adjoint shapes in PyTorch. - Use
torch.autograd.gradto compute a Hessian-vector product of and compare with the analytic . - Measure forward/backward time for chain lengths and confirm the ratio is roughly constant.
33. Debugging challenges
- Gradient is
Nonein PyTorch: the tensor is not connected to the loss (missingrequires_grador 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 are cached; enable checkpointing or a memory-efficient attention kernel.
34. Advanced exercises
- Prove Lemma 3 (path-sum identity) formally by induction on DAG topological order.
- Implement forward-over-reverse AD to compute Hessian-vector products and verify on a nonconvex function.
- Derive and implement the VJP of the softmax function: where .
- Implement gradient checkpointing on a 10-layer MLP and measure the memory/compute trade-off against full caching.
- Build a custom
torch.autograd.Functionwith a correctbackwardand gradient-check it at double precision. - Compare eager PyTorch,
torch.compileand JAXjitgradient 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 vs 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 ; (4) state and justify the 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 ), experiments.ipynb (toy MLP training, timing table for , 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.`