Automatic differentiation and computation graphs¶
Automatic differentiation turns any program built from differentiable primitives into a program that also computes exact derivatives. Forward mode pushes tangents along with the values; reverse mode records the computation and pulls gradients back. Backpropagation is reverse mode applied to a neural network, and every deep learning framework is, at its core, an autodiff engine.
10,000 ft
Deep learning frameworks exist mainly to do two things: run tensor operations fast on accelerators, and differentiate them automatically. PyTorch's autograd, JAX's grad, TensorFlow's GradientTape and MLX's mx.grad are all implementations of the same idea, worked out in numerical analysis decades before neural networks needed it. Autodiff is why you can invent a new layer, loss or architecture and train it the same afternoon without deriving a single gradient by hand, and it has spread far beyond neural networks into physics simulation, robotics, finance and probabilistic programming under the name differentiable programming. This page assumes you know backpropagation and generalises it.
2,000 ft
Any numerical program, however tangled, executes as a sequence of primitive operations (add, multiply, exp, matmul…) whose derivatives are known. Record that sequence as a graph. Then apply the chain rule mechanically, in one of two orders.
- Trace: run the program and record each primitive and its inputs (a tape or graph).
- Local rules: every primitive ships with its derivative rule (a JVP, a VJP, or both).
- Forward mode: carry a tangent alongside each value; one pass gives \(J\mathbf{v}\), a directional derivative.
- Reverse mode: after the forward pass, walk the tape backwards carrying adjoints; one pass gives \(\mathbf{u}^\top J\), so a full gradient of a scalar.
- Pick the mode by shape: few inputs → forward; few outputs (a loss) → reverse.
Ground level¶
Three ways to get a derivative¶
| Method | How | Accuracy | Cost for \(\nabla f\), \(f:\mathbb{R}^n\to\mathbb{R}\) | Main problem |
|---|---|---|---|---|
| Numerical (finite differences) | evaluate \(f\) at nearby points | approximate | \(n+1\) or \(2n\) evaluations | truncation vs rounding error; slow |
| Symbolic | manipulate the formula | exact | can explode in size | expression swell; needs closed-form code |
| Automatic | apply the chain rule to the executed operations | exact to machine precision | a small constant × one evaluation (reverse mode) | memory for the tape |
Numerical differentiation has a built-in tension. The forward difference \((f(x+h) - f(x))/h\) has truncation error \(\tfrac{h}{2}f''(x)\), so you want \(h\) small; but subtracting two nearly equal floats loses about \(\epsilon_{\text{mach}}/h\) in relative precision, so you want \(h\) large. The best you can do is \(h \approx \sqrt{\epsilon_{\text{mach}}} \approx 10^{-8}\) for an error around \(10^{-8}\); the central difference does better (\(h \approx \epsilon^{1/3}\), error around \(10^{-11}\)). Measured for \(\frac{d}{dx}e^x\) at \(x=1\):
Symbolic differentiation is exact but works on expressions, not programs. Differentiate a product of \(k\) factors and the product rule gives \(k\) terms each with \(k-1\) factors; nest such expressions and the derivative's size can grow exponentially even when the original is small, because symbolic tools lose track of shared sub-expressions. It also cannot see through loops, branches or recursion.
Automatic differentiation sits between them. Like the symbolic approach it is exact; like the numerical approach it works on the values of an actual execution, so loops, branches, recursion and library calls are no problem. The trick is that it never builds a formula for the derivative: it applies the chain rule numerically, one primitive at a time, reusing every intermediate value.
Programs are compositions of primitives¶
Take the classic example from the Baydin et al. survey,
Executed, it is a straight-line sequence of primitives, an evaluation trace (also called a Wengert list, after Wengert's 1964 paper):
| Node | Operation | Value |
|---|---|---|
| \(v_{-1}\) | \(x_1\) | 2 |
| \(v_0\) | \(x_2\) | 5 |
| \(v_1\) | \(\ln v_{-1}\) | 0.6931 |
| \(v_2\) | \(v_{-1} \times v_0\) | 10 |
| \(v_3\) | \(\sin v_0\) | −0.9589 |
| \(v_4\) | \(v_1 + v_2\) | 10.6931 |
| \(v_5\) | \(v_4 - v_3\) | 11.6521 |
Both \(x_1\) and \(x_2\) fan out to two uses each. Hold that thought: the fan-out is where forward and reverse mode differ.
Forward mode: carry the derivative along¶
Pick an input direction and give every node a second number, its tangent \(\dot v_i = \partial v_i/\partial(\text{that direction})\). Seed \(\dot x_1 = 1, \dot x_2 = 0\) to differentiate with respect to \(x_1\), and update tangents with each primitive's local derivative as you go:
| Node | Value | Tangent rule | \(\dot v\) for \(\partial/\partial x_1\) |
|---|---|---|---|
| \(v_{-1} = x_1\) | 2 | seed | 1 |
| \(v_0 = x_2\) | 5 | seed | 0 |
| \(v_1 = \ln v_{-1}\) | 0.6931 | \(\dot v_{-1}/v_{-1}\) | 0.5 |
| \(v_2 = v_{-1}v_0\) | 10 | \(\dot v_{-1}v_0 + v_{-1}\dot v_0\) | 5 |
| \(v_3 = \sin v_0\) | −0.9589 | \(\cos(v_0)\,\dot v_0\) | 0 |
| \(v_4 = v_1 + v_2\) | 10.6931 | \(\dot v_1 + \dot v_2\) | 5.5 |
| \(v_5 = v_4 - v_3\) | 11.6521 | \(\dot v_4 - \dot v_3\) | 5.5 |
So \(\partial f/\partial x_1 = 5.5\) (check: \(1/x_1 + x_2 = 0.5 + 5\)). To get \(\partial f/\partial x_2\) you need a second pass seeded with \((0, 1)\), which gives \(x_1 - \cos x_2 = 1.7163\). Forward mode delivers one directional derivative \(J\mathbf{v}\) (a Jacobian–vector product, JVP) per pass; a full gradient of \(n\) inputs takes \(n\) passes.
There is a beautiful algebraic way to see this. Extend the real numbers with a symbol \(\varepsilon\) where \(\varepsilon^2 = 0\) (dual numbers, Clifford 1873). Taylor's theorem then gives, exactly,
because every higher term carries \(\varepsilon^2 = 0\). Overload +, *, ln, sin on pairs \((a, b)\) and every program computes its own derivative in the \(\varepsilon\) slot. That is forward-mode autodiff in about twenty lines (Build it).
Reverse mode: record, then pull back¶
Reverse mode runs the program forward once, keeping the trace, then assigns every node an adjoint \(\bar v_i = \partial y/\partial v_i\) and fills them in from the output backwards. Seed \(\bar v_5 = 1\). Each node pushes its adjoint to its inputs, multiplied by the local derivative, and inputs used more than once sum what they receive:
| Adjoint | Rule | Value |
|---|---|---|
| \(\bar v_5\) | seed | 1 |
| \(\bar v_4\) | \(\bar v_5 \cdot 1\) | 1 |
| \(\bar v_3\) | \(\bar v_5 \cdot (-1)\) | −1 |
| \(\bar v_2\) | \(\bar v_4 \cdot 1\) | 1 |
| \(\bar v_1\) | \(\bar v_4 \cdot 1\) | 1 |
| \(\bar v_0 = \bar x_2\) | \(\bar v_2 \cdot v_{-1} + \bar v_3 \cos v_0\) | $2 - \cos 5 = $ 1.7163 |
| \(\bar v_{-1} = \bar x_1\) | \(\bar v_2 \cdot v_0 + \bar v_1 / v_{-1}\) | $5 + 0.5 = $ 5.5 |
One backward pass gave both partial derivatives. In general it gives \(\mathbf{u}^\top J\), a vector–Jacobian product (VJP); with a scalar output and \(u = 1\) that is the whole gradient, whatever the number of inputs. Note what the backward pass needed: \(v_{-1}\), \(v_0\) and \(\cos v_0\) from the forward pass. Reverse mode must store (or recompute) forward values, which is its memory cost.
Which mode when¶
For \(f: \mathbb{R}^n \to \mathbb{R}^m\), the full Jacobian costs \(n\) forward passes or \(m\) reverse passes.
| Shape | Example | Best mode |
|---|---|---|
| \(n \gg m = 1\) | a training loss over \(10^9\) parameters | reverse (backprop) |
| \(n = 1 \ll m\) | the trajectory of an ODE as a function of one physical constant | forward |
| \(n \approx m\) | a Jacobian of a small layer for analysis | either; forward needs no tape |
| Hessian–vector product | curvature along one direction | forward-over-reverse |
The snippet in Build it builds the \(3 \times 5\) Jacobian of \(\tanh(W\mathbf{x})\) both ways: five JVPs (columns) or three VJPs (rows), identical results.
How PyTorch does it: define-by-run¶
PyTorch builds the graph as your Python code runs. Every tensor created by an operation on a tensor with requires_grad=True gets a grad_fn, a node such as MulBackward0 that remembers its inputs (or whatever it needs from them) and knows its VJP. Calling loss.backward() walks those nodes in reverse topological order, from the loss to the leaves, and accumulates into each leaf's .grad. Consequences worth knowing by heart:
- The graph is rebuilt every iteration. Python
if,forand recursion just work, because only the path actually executed is recorded. This "define-by-run" style came from Chainer (2015) and is described in the PyTorch paper (Paszke et al., 2019). - Gradients accumulate. That is how fan-out sums are implemented, and why you call
optimizer.zero_grad()every step. It is also how gradient accumulation over micro-batches works on purpose. - The graph is freed after
backward()to save memory; passretain_graph=Trueto backpropagate twice. - Saved tensors are version-checked. If an in-place operation overwrites a value that a backward node saved, you get "one of the variables needed for gradient computation has been modified by an inplace operation".
torch.no_grad()/torch.inference_mode()stop recording, which saves memory at evaluation time.- Custom rules come from subclassing
torch.autograd.Functionwith aforwardthat callsctx.save_for_backward(...)and abackwardthat returns one gradient per input.torch.funcadds JAX-stylegrad,vjp,jvp,jacrev,jacfwdandvmap.
How JAX does it: transformations of pure functions¶
JAX takes a different route. You write a pure function; jax.grad(f) returns a new function that computes the gradient. Internally, JAX traces your Python into an intermediate representation (a jaxpr) and applies transformations to it: jvp (forward mode), vjp and grad (reverse mode), vmap (vectorisation), jit (compilation through XLA). They compose: jax.hessian is jacfwd(jacrev(f)), and vmap(grad(f)) gives per-example gradients in one call.
A design insight from JAX is that reverse mode need not be implemented separately. Any program's JVP is linear in the tangent; JAX linearises the program (forward mode plus partial evaluation) and then transposes the linear part to get the VJP. Each primitive therefore needs a JVP rule and, for its linear pieces, a transpose rule. Radul et al. (2022), You Only Linearize Once, formalise this; JAX's "Autodidax" tutorial builds it from scratch. MLX on Apple silicon follows the same functional style (mx.grad, mx.vjp, mx.jvp, mx.vmap; see on-device AI).
Two mental models of one idea
PyTorch: a tape recorded during execution, played backwards. JAX: a function transformer that rewrites \(f\) into \(\nabla f\). Both apply the same local VJP rules in the same reverse order; they differ in when the graph is captured and what you are allowed to write (JAX wants pure functions; PyTorch allows mutation and checks it).
Higher-order derivatives, cheaply¶
Because a gradient computation is itself a program made of primitives, you can differentiate it again. The most useful second-order object is not the Hessian \(H\) (a \(P \times P\) matrix, \(10^{18}\) entries for a billion-parameter model) but the Hessian–vector product \(H\mathbf{v}\). Pearlmutter (1994) showed it costs only a small constant times a gradient:
HVPs power Newton–conjugate-gradient methods, the top Hessian eigenvalue that measures sharpness of a minimum, influence functions for tracing a prediction back to training examples, and some meta-learning. In JAX, forward-over-reverse is jax.jvp(jax.grad(f), (x,), (v,)).
Gotchas: kinks, NaNs and things that are not differentiable¶
- Control flow is fine, discontinuities are not. Autodiff differentiates the branch that ran. For
abs(x)at \(x = 0\), or ReLU at 0, frameworks pick one subgradient (PyTorch returns 0 for ReLU at 0). If a function is a step (round,argmax, sampling a discrete token), its derivative is zero almost everywhere and autodiff will dutifully report 0. Workarounds are modelling choices: the straight-through estimator (pretend the step was the identity in the backward pass, used in quantisation-aware training), the Gumbel-softmax relaxation, or the score-function estimator of policy gradients. - The
whereNaN trap.where(x > 0, sqrt(x), 0)looks safe at \(x = -1\), but autodiff differentiates both branches and multiplies the unused one by zero: \(\text{NaN} \times 0 = \text{NaN}\). Fix it by making the unused branch safe too (sqrt(where(x > 0, x, 1))). The JAX FAQ calls this the "double where" trick. - Exact derivative of an approximate function. If your code computes \(\log(1 + x)\) as
log(1 + x)for tiny \(x\), autodiff gives the exact derivative of that inaccurate computation. Use stable primitives (log1p,logsumexp) and the derivatives inherit the stability (numerical computing). - Iterative solvers. Differentiating through 1,000 iterations of an optimiser stores 1,000 tapes. When the iteration converges to a fixed point, implicit differentiation computes the gradient from the fixed-point condition alone, with constant memory; this is how deep equilibrium models and differentiable optimisation layers work.
History¶
Older than neural networks
1964: R. E. Wengert publishes a simple program for automatic derivative evaluation, forward mode on an evaluation trace. 1970: Seppo Linnainmaa's master's thesis describes reverse accumulation for general programs (to estimate rounding-error propagation). 1980: Bert Speelpenning's thesis compiles programs into their reverse-mode derivative programs. 1983: Baur and Strassen prove that all partial derivatives cost at most a constant factor more than the function. 1994: Pearlmutter's fast exact Hessian–vector products. 2000s: Griewank and Walther's Evaluating Derivatives becomes the field's reference. Machine learning adopted AD in waves: Theano (around 2010) and TensorFlow (2015) with static graphs, HIPS Autograd (2015) and Chainer (2015) with define-by-run, PyTorch (released 2017), and JAX (2018) with composable transformations. The machine-learning community spent years re-deriving gradients by hand that the AD community could have generated automatically, which is the point of the Baydin et al. survey.
First principles¶
The derivative is a linear map. At a point \(\mathbf{x}\), the derivative of \(f:\mathbb{R}^n \to \mathbb{R}^m\) is the linear map \(Df(\mathbf{x}): \mathbb{R}^n \to \mathbb{R}^m\) that best approximates \(f\) nearby: \(f(\mathbf{x} + \mathbf{v}) = f(\mathbf{x}) + Df(\mathbf{x})\mathbf{v} + o(\lVert\mathbf{v}\rVert)\). Its matrix is the Jacobian \(J\). The chain rule says the derivative of a composition is the composition of derivatives: \(D(g \circ f)(\mathbf{x}) = Dg(f(\mathbf{x})) \circ Df(\mathbf{x})\).
Forward mode is applying those linear maps to a vector, in program order. A tangent \(\mathbf{v}\) is pushed through \(Df_1\), then \(Df_2\), and so on: \(J\mathbf{v} = J_k(\cdots(J_2(J_1\mathbf{v})))\). It needs only the current values, so it runs in lockstep with the program and needs no storage. In differential-geometry language it computes the pushforward of a tangent vector.
Reverse mode is applying the transposes, in reverse order. A cotangent (a row vector, a "sensitivity") \(\mathbf{u}^\top\) is pulled back: \(\mathbf{u}^\top J = (((\mathbf{u}^\top J_k)J_{k-1})\cdots)J_1\). Because \(J_1\) is needed last but depends on values computed first, the forward values must be kept. This is the pullback, and the adjoint state methods of optimal control and the adjoint equations in weather forecasting and aerodynamic design are the same idea.
Why it is exact. Each primitive's local derivative is evaluated exactly (up to floating-point rounding of that primitive), and the chain rule is an identity, not an approximation. Nothing is truncated.
Why it is cheap. Each primitive contributes a bounded amount of extra work (its JVP or VJP rule), so the derivative program is a constant factor larger than the original: the cheap gradient principle. The constant is small in practice: a matmul's VJP is two matmuls, so backpropagation costs about twice the forward pass.
What it cannot do. It differentiates the program you wrote, not the mathematical function you meant. If the program is piecewise constant, the derivative is zero; if it is numerically unstable, so is its derivative; if it branches on a value, the derivative ignores what would have happened on the other branch.
The maths¶
Definitions. For \(f:\mathbb{R}^n\to\mathbb{R}^m\) with Jacobian \(J = \partial f/\partial\mathbf{x} \in \mathbb{R}^{m \times n}\) at \(\mathbf{x}\):
For a composition \(f = f_k \circ \dots \circ f_1\) with intermediate values \(\mathbf{x}_i = f_i(\mathbf{x}_{i-1})\) and Jacobians \(J_i\) evaluated at \(\mathbf{x}_{i-1}\):
General reverse-mode recurrence. On a graph, with \(\bar v_i = \partial y/\partial v_i\):
VJP rules for the primitives that matter (\(\bar{O}\) is the incoming adjoint, shapes match the variables):
| Primitive | Forward | VJP |
|---|---|---|
| add | \(O = A + B\) | \(\bar A = \bar O\), \(\bar B = \bar O\) |
| elementwise mul | \(O = A \odot B\) | \(\bar A = \bar O \odot B\), \(\bar B = \bar O \odot A\) |
| elementwise \(g\) | \(O = g(A)\) | \(\bar A = \bar O \odot g'(A)\) |
| matmul | \(O = AB\) | \(\bar A = \bar O B^\top\), \(\bar B = A^\top\bar O\) |
| sum over axis | \(o = \sum_i a_i\) | \(\bar a_i = \bar o\) (broadcast back) |
| broadcast | \(O = \mathbf{a}\) copied along an axis | \(\bar{\mathbf{a}} = \sum_{\text{axis}} \bar O\) (sum back) |
| transpose / reshape | \(O = A^\top\) | \(\bar A = \bar O^\top\) (undo the reshuffle) |
| log-sum-exp | \(o = \log\sum_i e^{a_i}\) | \(\bar a_i = \bar o\,\operatorname{softmax}(\mathbf{a})_i\) |
Sum and broadcast are each other's VJPs; that pairing is why a bias added to every row of a batch receives the sum of the row gradients.
Derivation of the matmul VJP with differentials
Let \(L\) be a scalar and \(O = AB\) with \(A \in \mathbb{R}^{p\times q}\), \(B \in \mathbb{R}^{q \times r}\). The differential of \(L\) is \(dL = \operatorname{tr}(\bar O^\top dO)\) (the Frobenius inner product \(\langle \bar O, dO\rangle\)). With \(dO = dA\,B + A\,dB\):
using the cyclic property of the trace. Reading off the coefficients of \(dA\) and \(dB\): \(\bar A = \bar O B^\top \in \mathbb{R}^{p \times q}\) and \(\bar B = A^\top\bar O \in \mathbb{R}^{q\times r}\). The same three-line method derives the VJP of any primitive.
Dual numbers compute derivatives exactly
Let \(\mathbb{D} = \{a + b\varepsilon : a, b \in \mathbb{R}\}\) with \(\varepsilon^2 = 0\). Then \((a + b\varepsilon)(c + d\varepsilon) = ac + (ad + bc)\varepsilon\), which is the product rule in the \(\varepsilon\) slot. For a polynomial \(p\), expanding \(p(a + b\varepsilon)\) and discarding \(\varepsilon^2\) terms gives \(p(a) + p'(a)b\varepsilon\); extending each analytic primitive by \(g(a + b\varepsilon) := g(a) + g'(a)b\varepsilon\) keeps this true under composition, because
which is the chain rule. Multivariate forward mode seeds a vector of \(\varepsilon\) coefficients (the tangent \(\mathbf{v}\)) and returns \(J\mathbf{v}\).
Costs. Let \(\text{ops}(f)\) be the cost of evaluating \(f\). Then \(\text{ops}(J\mathbf{v}) \le c_F\,\text{ops}(f)\) and \(\text{ops}(J^\top\mathbf{u}) \le c_R\,\text{ops}(f)\) for small constants (Griewank and Walther derive explicit bounds), while reverse mode's memory is proportional to the number of stored intermediates unless you checkpoint. A full Jacobian costs \(\min(n, m)\) passes of the appropriate mode, or fewer if the Jacobian is sparse and you colour its columns.
Hessian–vector product. With \(g(\theta) = \nabla L(\theta)\), \(H\mathbf{v} = Dg(\theta)\mathbf{v} = \operatorname{jvp}(\nabla L, \theta, \mathbf{v})\): forward mode over reverse mode, cost a constant multiple of one gradient.
Build it¶
First, why not finite differences: the error of the forward and central difference for \(\frac{d}{dx}e^x\) at \(x = 1\) as \(h\) shrinks.
import numpy as np
# finite differences: truncation error vs rounding error, d/dx exp(x) at x = 1
f, x, exact = np.exp, 1.0, np.exp(1.0)
print(" h forward diff central diff")
for h in [1e-1, 1e-3, 1e-5, 1e-7, 1e-9, 1e-11]:
fwd = (f(x + h) - f(x)) / h
ctr = (f(x + h) - f(x - h)) / (2 * h)
print(f"{h:8.0e} {abs(fwd - exact):.1e} {abs(ctr - exact):.1e}")
h forward diff central diff
1e-01 1.4e-01 4.5e-03
1e-03 1.4e-03 4.5e-07
1e-05 1.4e-05 5.9e-11
1e-07 1.4e-07 5.9e-11
1e-09 2.2e-07 6.6e-09
1e-11 3.3e-05 1.0e-05
Forward mode with dual numbers, on the example function. One pass per input:
import math
class Dual:
"""a + b·ε with ε² = 0. `val` is the value, `dot` the tangent."""
def __init__(self, val, dot=0.0): self.val, self.dot = val, dot
def __add__(self, o): o = lift(o); return Dual(self.val + o.val, self.dot + o.dot)
def __sub__(self, o): o = lift(o); return Dual(self.val - o.val, self.dot - o.dot)
def __mul__(self, o):
o = lift(o); return Dual(self.val * o.val, self.val * o.dot + self.dot * o.val)
__radd__, __rmul__ = __add__, __mul__
def lift(o): return o if isinstance(o, Dual) else Dual(o)
def log(d): return Dual(math.log(d.val), d.dot / d.val)
def sin(d): return Dual(math.sin(d.val), math.cos(d.val) * d.dot)
def f(x1, x2): return log(x1) + x1 * x2 - sin(x2)
# one forward pass per input direction: seed the tangent of that input with 1
print("f =", round(f(Dual(2.0), Dual(5.0)).val, 4))
print("df/dx1 =", round(f(Dual(2.0, 1.0), Dual(5.0, 0.0)).dot, 4))
print("df/dx2 =", round(f(Dual(2.0, 0.0), Dual(5.0, 1.0)).dot, 4))
print("exact :", 1/2 + 5, ",", round(2 - math.cos(5.0), 4))
Reverse mode with a tape: each node remembers its parents and the local derivative to each; backward sorts the graph topologically and accumulates adjoints. One pass gives every partial derivative.
import math
class Var:
"""A scalar node in a reverse-mode tape (micrograd-style)."""
def __init__(self, val, parents=()):
self.val, self.grad, self.parents = val, 0.0, parents # parents: (node, local_grad)
def __add__(self, o):
o = o if isinstance(o, Var) else Var(o)
return Var(self.val + o.val, ((self, 1.0), (o, 1.0)))
def __sub__(self, o):
o = o if isinstance(o, Var) else Var(o)
return Var(self.val - o.val, ((self, 1.0), (o, -1.0)))
def __mul__(self, o):
o = o if isinstance(o, Var) else Var(o)
return Var(self.val * o.val, ((self, o.val), (o, self.val)))
def backward(self):
order, seen = [], set()
def visit(v): # topological order: parents before children
if id(v) in seen: return
seen.add(id(v))
for p, _ in v.parents: visit(p)
order.append(v)
visit(self)
self.grad = 1.0 # seed: dL/dL = 1
for v in reversed(order): # children before parents
for p, local in v.parents:
p.grad += local * v.grad # += : fan-out gradients sum
def log(v): return Var(math.log(v.val), ((v, 1.0 / v.val),))
def sin(v): return Var(math.sin(v.val), ((v, math.cos(v.val)),))
x1, x2 = Var(2.0), Var(5.0)
y = log(x1) + x1 * x2 - sin(x2)
y.backward() # ONE backward pass gives both partials
print(f"f = {y.val:.4f} df/dx1 = {x1.grad:.4f} df/dx2 = {x2.grad:.4f}")
a = Var(3.0)
b = a * a + a # a is used three times
b.backward()
print(f"d(a^2 + a)/da at a=3: {a.grad} (exact 2a + 1 = 7)")
Finally, vector JVPs and VJPs, and the cost asymmetry: building the Jacobian of \(\tanh(W\mathbf{x})\), \(\mathbb{R}^5 \to \mathbb{R}^3\), column by column and row by row.
import numpy as np
rng = np.random.default_rng(0)
n, m = 5, 3 # f: R^5 -> R^3
W = rng.normal(size=(m, n)); x = rng.normal(size=n)
s = 1 - np.tanh(W @ x) ** 2 # tanh'(Wx), shape (m,)
jvp = lambda v: s * (W @ v) # J v : push a tangent forward
vjp = lambda u: W.T @ (s * u) # u^T J : pull a cotangent back
J_fwd = np.stack([jvp(e) for e in np.eye(n)], axis=1) # n = 5 passes, one column each
J_rev = np.stack([vjp(e) for e in np.eye(m)], axis=0) # m = 3 passes, one row each
print("Jacobian shape", J_fwd.shape, "| forward passes:", n, "| reverse passes:", m)
print("both modes agree:", np.allclose(J_fwd, J_rev))
print("explicit formula agrees:", np.allclose(J_rev, s[:, None] * W))
Jacobian shape (3, 5) | forward passes: 5 | reverse passes: 3
both modes agree: True
explicit formula agrees: True
The same thing in the two big frameworks (standard APIs; not run here, since this site's code runs in NumPy):
# PyTorch
import torch
x1 = torch.tensor(2.0, requires_grad=True); x2 = torch.tensor(5.0, requires_grad=True)
y = torch.log(x1) + x1 * x2 - torch.sin(x2)
y.backward()
print(x1.grad, x2.grad) # tensor(5.5000) tensor(1.7163)
# JAX
import jax, jax.numpy as jnp
f = lambda x: jnp.log(x[0]) + x[0] * x[1] - jnp.sin(x[1])
print(jax.grad(f)(jnp.array([2.0, 5.0]))) # ≈ [5.5, 1.7163]
Things to try
- Add
__truediv__,expandtanhto bothDualandVar, then train a single tanh neuron withVaron four points. You have rebuilt the heart of micrograd. - Nest the two engines to get a Hessian–vector product (forward-over-reverse): run the
Varengine onDualvalues instead of floats. You will needlog,sinandcosrules that accept either type. Check \(H\mathbf{v}\) for \(f(x_1, x_2)\) against the analytic Hessian \(\begin{pmatrix} -1/x_1^2 & 1 \\ 1 & \sin x_2 \end{pmatrix}\). - Implement the
wheretrap: withVar, writerelu_sqrt(x) = sqrt(x) if x > 0 else 0as a Python branch (safe) and as a "compute both, multiply by a mask" expression (NaN at \(x = -1\)). Explain the difference. - Time
jvpandvjpbuilding Jacobians for \(n = 1000, m = 10\) and for \(n = 10, m = 1000\). - Remove the topological sort from
backwardand process parents depth-first instead. Find a graph where that gives the wrong answer (hint: a node whose adjoint is not complete when it is first visited).
Check yourself¶
What is the difference between autodiff and symbolic differentiation, given that both are exact?
Symbolic differentiation transforms an expression into another expression, which can swell exponentially and cannot handle loops or branches. Autodiff transforms an execution: it evaluates local derivatives numerically at the current point and combines them with the chain rule, reusing shared intermediates, so its cost is a constant multiple of the original program and it works for any code that runs.
Why does forward mode need no extra memory while reverse mode does?
Forward mode computes each tangent from the current values in program order, so it can discard values as it goes. Reverse mode processes the program backwards, and each local VJP needs values from the forward pass (inputs to multiplies, pre-activations of nonlinearities), so those must be stored or recomputed.
A bias vector b of shape (m,) is broadcast-added to a (B, m) matrix. What is its gradient?
The sum over the batch axis of the incoming (B, m) gradient. Broadcasting copies \(\mathbf{b}\) to every row (a fan-out), and fan-out gradients sum.
You need the full Jacobian of a function from ℝ¹⁰ to ℝ¹⁰⁰⁰⁰. Which mode, and how many passes?
Forward mode, 10 passes (one per input column). Reverse mode would need 10,000 passes. In JAX that is jax.jacfwd.
Why is a Hessian–vector product affordable for a billion-parameter model when the Hessian is not?
The Hessian has \(10^{18}\) entries; nobody can store it. But \(H\mathbf{v}\) is the directional derivative of the gradient along \(\mathbf{v}\), which forward-over-reverse autodiff computes for a constant multiple of the cost of one gradient (Pearlmutter's trick), with memory linear in the number of parameters.
In PyTorch, you call loss.backward() twice in a row on the same graph. What happens, and what if you also forgot zero_grad?
The second call raises an error because the graph's saved tensors were freed after the first backward (unless retain_graph=True). With retain_graph=True and no zero_grad, the second call adds the same gradient again, so every .grad is doubled.
Hard: how can JAX get reverse mode 'for free' from forward mode?
A JVP \(\mathbf{v} \mapsto J\mathbf{v}\) is linear in the tangent. JAX linearises the program: it runs forward mode, evaluating everything that does not depend on the tangent (partial evaluation), leaving a purely linear program in \(\mathbf{v}\). Every linear primitive has a known transpose (the transpose of "multiply by \(W\)" is "multiply by \(W^\top\)", of "broadcast" is "sum"), so reversing the linear program and transposing each step gives \(\mathbf{u} \mapsto J^\top\mathbf{u}\), the VJP. Only JVP and transpose rules need to be written per primitive.
Hard: your loss uses torch.round on an intermediate value and the parameters before it never change. Why, and what are your options?
round is piecewise constant, so its derivative is zero almost everywhere and autodiff correctly propagates zero gradient to everything upstream. Options: replace it with a smooth surrogate during training; use the straight-through estimator (treat round as identity in the backward pass, x + (x.round() - x).detach()); or move the discrete choice into a stochastic node and use a score-function or reparameterised estimator.
Go deeper¶
Papers
- Automatic differentiation in machine learning: a survey — Baydin, Pearlmutter, Radul and Siskind, JMLR 2018 (arXiv). The reference introduction; the worked example on this page is theirs. Sections 2–3 are essential.
- A simple automatic derivative evaluation program — Wengert, 1964. Forward mode on an evaluation trace, two pages.
- Who invented the reverse mode of differentiation? — Griewank, 2012. Linnainmaa, Speelpenning and the rest of the story.
- The complexity of partial derivatives — Baur and Strassen, 1983. The cheap gradient principle, proved.
- Fast exact multiplication by the Hessian — Pearlmutter, 1994. Hessian–vector products at the cost of a gradient.
- PyTorch: an imperative style, high-performance deep learning library — Paszke et al., 2019. Design of define-by-run autograd; section 5 on the implementation.
- You Only Linearize Once: tangents transpose to gradients — Radul et al., 2022. Reverse mode as linearise-then-transpose, the JAX design.
- Training deep nets with sublinear memory cost — Chen et al., 2016. Checkpointing: trade recomputation for tape memory.
Videos and lectures
- The spelled-out intro to neural networks and backpropagation: building micrograd — Andrej Karpathy. Builds the
Varclass above at length, then a neural network on top.
Articles and documentation
- The Autodiff Cookbook — JAX docs. JVPs, VJPs, Hessian–vector products and Jacobians, with the forward/reverse cost argument.
- Autodidax: JAX core from scratch — JAX docs. Builds tracing, JVP, partial evaluation and transposition in plain Python. Advanced, superb.
- Autograd mechanics — PyTorch docs. Saved tensors, in-place correctness checks, gradients for complex numbers.
- Overview of PyTorch Autograd Engine — PyTorch blog. How the graph of
grad_fnnodes is built and executed. - JAX FAQ: gradients contain NaN where using where — The double-where trick, explained.
Courses and books
- Evaluating Derivatives — Griewank and Walther, SIAM, 2nd ed. 2008. The textbook of algorithmic differentiation: complexity bounds, checkpointing, sparsity.
- The Elements of Differentiable Programming — Blondel and Roulet, 2024. A modern book-length treatment linking autodiff, optimisation and probabilistic modelling.
Code
- karpathy/micrograd — Scalar reverse mode in about 100 lines.
- HIPS/autograd — Differentiates plain NumPy code; JAX's direct ancestor and very readable.
Where this leads¶
- Activation functions — the \(g'\) in every elementwise VJP, and what its shape does to training.
- Initialisation and normalisation — controlling the size of the products autodiff multiplies together.
- Project: build micrograd — extend the
Varclass into a working neural-network library. - Mixed precision — what happens to these gradients in BF16 and FP8, and why loss scaling exists.
- Kernels: CUDA and Triton — writing fused forward and backward kernels by hand when autodiff's generic ones are too slow.