Autodiff in Depth
Forward and reverse mode, cost, memory and checkpointing.
Automatic differentiation computes exact derivatives of programs built from differentiable operations, at a cost provably a small multiple of running the program. This lesson builds both of its modes from first principles, as dual numbers that push tangents forward and as transposed linear maps that pull adjoints back; proves the cheap-gradient theorem and one surprising consequence of it; derives the square-root memory trick and reversible networks; and obtains second-order information, Hessian–vector products, for the price of a gradient.
What you’ll learn
- Implement forward mode with dual numbers and prove that one sweep computes a Jacobian–vector product; derive reverse mode as its transpose, computing vector–Jacobian products.
- State the Baur–Strassen theorem, explain why gradients cost a constant number of function evaluations while full Jacobians and Hessians do not, and use it to show that inverting a matrix is no harder than computing its determinant.
- Derive the memory–compute trade-offs of reverse mode: checkpointing, logarithmic schedules and reversible residual networks.
- Get exact Hessian–vector products at the cost of a few gradients with Pearlmutter's -operator (forward mode applied to the gradient computation), and use them to probe curvature.
Forward mode: dual numbers
For a polynomial, expand with the binomial theorem; every term with or higher vanishes, so the -coefficient is exactly the derivative:
The extension is closed under composition, and the chain rule falls out of the arithmetic, so any program built from such operations propagates the derivative correctly:
With several inputs, seed every input . One evaluation in dual arithmetic returns the value and a Jacobian–vector product (JVP), for a small constant times the cost of and with no stored history. A full Jacobian of takes sweeps, one per basis vector .
class Dual:
"""a + b*eps with eps**2 = 0: b carries the derivative along."""
def __init__(self, a, b=0.0):
self.a, self.b = a, b
def __add__(self, o):
o = o if isinstance(o, Dual) else Dual(o)
return Dual(self.a + o.a, self.b + o.b)
__radd__ = __add__
def __mul__(self, o):
o = o if isinstance(o, Dual) else Dual(o)
return Dual(self.a * o.a, self.a * o.b + self.b * o.a)
__rmul__ = __mul__
def __truediv__(self, o):
o = o if isinstance(o, Dual) else Dual(o)
return Dual(self.a / o.a, (self.b * o.a - self.a * o.b) / o.a ** 2)
x = Dual(1.0, 1.0) # seed: dx/dx = 1
y = x * x / (x + 1) # f(x) = x^2 / (x + 1)
print(y.a, y.b) # 0.5 0.75Forward mode in fifteen lines: overload the arithmetic and the derivative rides along. Production systems (JAX's jvp, PyTorch's forward-mode AD) work the same way on tensors.
Evaluate at the dual number . What is the coefficient of ?
Show the answer
10
(the and terms vanish) and , so : the value and the derivative , exactly, with no step size and no rounding beyond ordinary arithmetic.
Reverse mode: the transpose
Write with Jacobians evaluated along the computation, so . Forward mode multiplies from the right, , in the same order as the evaluation. Reverse mode multiplies a row vector from the left, : a vector–Jacobian product (VJP), in the opposite order. Because each depends on the intermediate state at step , reverse mode must store the forward trajectory (the "tape") or recompute it.
Forward mode runs a tangent program: one linear update per elementary operation, propagating tangents from parents to children.
A linear straight-line program computing can be reversed into one computing with the same number of multiplications: run the statements backward and turn each " += " into " += " (the transposition principle). Applied to the tangent program, this yields the adjoint program, which is exactly the backward sweep of backpropagation:
So a JVP and a VJP each cost a small constant times one evaluation of . A full Jacobian costs about sweeps, by the cheaper mode. Mixing modes along the graph can do better, but finding the cheapest elimination order is hard in general: Naumann (2008) proved that optimal Jacobian accumulation is NP-complete.
| Mode | Each sweep yields | Full Jacobian of | Extra memory | Natural use |
|---|---|---|---|---|
| Forward (tangent) | : one column, or a directional derivative | sweeps | tangents alongside the current values; no history | few inputs, many outputs; directional derivatives |
| Reverse (adjoint) | : one row; the gradient when | sweeps | the forward trajectory, or recomputation | many inputs, scalar output: training |
An image renderer maps one lighting parameter to 5,000 pixel intensities, , and you need for every pixel. How many sweeps of which mode does that take?
- One reverse sweep, since reverse mode returns every derivative at once
- 5,000 forward sweeps, one per pixel
- One forward sweep, seeded with
- 5,000 reverse sweeps, still the cheaper option because backpropagation is efficient
Show the answer
C. One forward sweep, seeded with
The Jacobian is a single column of 5,000 entries. One forward sweep carries the tangent to every pixel at once, for a small constant times one rendering. A reverse sweep returns one row, here the derivative of a single pixel (or of one weighted sum of pixels), so reverse mode needs 5,000 sweeps. The rule is sweeps by the cheaper mode: here, while training has the opposite shape, .
The cheap-gradient theorem
Run the program forward ( nonscalar operations), then the adjoint program. An addition or a multiplication by a constant has a linear adjoint, which is free in this cost model. A multiplication creates two nonscalar adjoint updates:
A division also costs two, reusing the stored quotient: += and -= , where is computed once. So each nonscalar operation of the forward sweep generates at most two in the backward sweep, whatever is:
A surprising consequence, already in Baur and Strassen's paper: inverting a matrix is no harder than computing its determinant. By Jacobi's formula, , so the gradient of the determinant is the inverse, up to a transpose and a scalar. Any algorithm for therefore yields, by reverse mode, an algorithm for with at most three times the nonscalar operations, plus divisions.
What the theorem does not say. It concerns one scalar output: a full Jacobian of outputs still needs reverse sweeps, and a full Hessian needs Hessian–vector products. It counts arithmetic, not memory traffic; reverse mode must keep or recompute intermediate values, so wall-clock ratios in practice are larger than 3 (backpropagation's "about 3 forward passes" counts matrix-multiply flops). Griewank & Walther (2008) prove bounds of the same kind, with small constants, for general programs and cost models that include memory access.
Memory: checkpointing and reversible networks
Reverse mode through a chain of steps (layers, or the time steps of a recurrent network or an ODE solver) needs step 's input when it processes step backward. Storing all of them costs memory proportional to . Checkpointing stores some and recomputes the rest.
Split the layers into segments of layers. During the forward pass keep only each segment's input: checkpoints.
During the backward pass, process segments last to first: recompute one segment's internal states from its checkpoint, backpropagate through it, discard them. Peak memory is the checkpoints plus one segment, minimized at :
Each layer is recomputed exactly once, so the price is one extra forward pass. With a backward pass costing about two forward passes, the gradient goes from about to about : roughly a third more compute for instead of memory. Chen et al. reported a 1,000-layer residual network going from 48 GB to 7 GB of memory for about 30% more running time.
Applying the trick recursively inside segments trades more recomputation for less memory: Chen et al. note memory at extra forward computation. Griewank (1992) had shown that, with checkpoints placed recursively, the memory and the number of times each step is recomputed can both grow only logarithmically in the length of the chain; his binomial schedules, implemented as revolve (Griewank & Walther, 2000), are standard in scientific computing.
A 100-layer network is trained with square-root checkpointing. About how many layer states must be held in memory at peak, instead of 100?
Show the answer
20 states
Segments of layers give 10 checkpoints plus at most 10 recomputed states: , a fivefold saving for one extra forward pass. At the saving would be fiftyfold.
Reversible networks avoid storing activations altogether. A reversible residual block (Gomez, Ren, Urtasun & Grosse, 2017) splits its channels into two halves and updates each with a function of the other, so its input can be reconstructed exactly from its output:
Hessian–vector products for the price of a gradient
The Hessian of a network with parameters has entries and is never formed. But almost everything one wants from it (Newton-type steps, curvature along a direction, top eigenvalues) needs only products , and those are cheap.
Define the directional derivative operator . Then , and applied to the gradient it gives the Hessian–vector product:
Apply to every line of the forward and backward passes, using the product and chain rules. For a layer of an MLP:
This is forward-mode differentiation of the reverse-mode gradient program: forward-over-reverse. It is exact (no step size), numerically stable, and costs a small constant times one gradient, in time and in memory. The finite-difference alternative costs two gradients but carries truncation and rounding errors.
import jax
def hvp(f, theta, v):
"""Hessian-vector product: differentiate grad(f) along v (forward-over-reverse)."""
return jax.jvp(jax.grad(f), (theta,), (v,))[1]One line in a library with both modes. Reverse-over-reverse also works but stores more; forward-over-reverse is usually the cheapest.
What Hessian–vector products buy:
- Curvature along the path. Power iteration or the Lanczos method with products gives the top Hessian eigenvalue, the sharpness tracked in Training Dynamics & the Edge of Stability, at the cost of a few dozen gradients.
- Newton-type steps without the Hessian. Conjugate gradients solve using only products, the basis of "Hessian-free" optimization (which in practice multiplies by the Gauss–Newton matrix below, because conjugate gradients needs a positive-definite system).
- Gauss–Newton products. , with the Jacobian of the outputs and the Hessian of the loss in the outputs, takes one JVP and one VJP and is always positive semidefinite for convex losses (Schraudolph, 2002).
- Influence of training points. Influence functions need inverse-Hessian–vector products, computed iteratively from (Koh & Liang, 2017).
You want the largest eigenvalue of the training-loss Hessian of a network with parameters. What is the practical approach?
- Form the Hessian with reverse sweeps and call an eigensolver
- Estimate it from the loss values along a random direction
- Run power iteration or Lanczos using Hessian–vector products, each costing a small multiple of a gradient
- It cannot be computed for networks this large
Show the answer
C. Run power iteration or Lanczos using Hessian–vector products, each costing a small multiple of a gradient
Each iteration needs one , costing a small constant times a gradient by forward-over-reverse. A few dozen iterations usually pin down the top eigenvalue, while forming would cost gradients and numbers of memory.
Key takeaways
- Dual numbers () compute : forward mode gives a Jacobian–vector product per sweep. Reverse mode, its transpose, gives a vector–Jacobian product per sweep, but needs the forward trajectory.
- Baur–Strassen: for scalar rational , whatever the number of inputs; one corollary is that matrix inversion is no harder than the determinant. Jacobians of vector functions and full Hessians remain expensive, and optimal Jacobian accumulation is NP-complete.
- Checkpointing every layers cuts memory from to for one extra forward pass; recursive schemes reach logarithmic memory; reversible residual blocks rebuild inputs from outputs and make activation storage independent of depth.
- Hessian–vector products cost a small multiple of a gradient by forward-over-reverse (-operator); they power sharpness estimates, Hessian-free Newton steps, Gauss–Newton products and influence functions.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You evaluate at , in dual arithmetic. What is the coefficient of in the result?
Show the answer
B.
. Seeding with and with gives the directional derivative along : .
What does the Baur–Strassen theorem guarantee?
- The gradient of a scalar rational function costs at most 3 times its nonscalar complexity, independent of the number of inputs
- The full Jacobian of any costs at most 3 evaluations of
- Reverse mode uses at most 3 times the memory of the forward pass
- The Hessian costs at most 3 times as much as the gradient
Show the answer
A. The gradient of a scalar rational function costs at most 3 times its nonscalar complexity, independent of the number of inputs
for a single output: every forward multiplication or division creates at most two in the adjoint sweep. Jacobians of vector functions and full Hessians are not cheap in this sense, and memory is a separate matter.
Why can a reversible residual network backpropagate without storing its activations?
- Its blocks and are invertible functions
- It uses forward-mode differentiation instead of reverse mode
- It stores only every -th activation
- Each block's input can be computed exactly from its output, , , so the backward pass rebuilds activations as it goes
Show the answer
D. Each block's input can be computed exactly from its output, , , so the backward pass rebuilds activations as it goes
The additive coupling is invertible whatever and are, so the backward pass can reconstruct each block's input on the fly, at the price of recomputing and . Activation storage then no longer grows with depth.
A Hessian-free optimizer solves by conjugate gradients, using only matrix–vector products. Why is the Gauss–Newton matrix (with a convex loss ) usually preferred to the Hessian as ?
- Products are exact, while products can only be approximated by finite differences
- equals the Hessian for neural networks, so nothing changes
- is positive semidefinite, which conjugate gradients relies on, while can be indefinite away from a minimum
- needs no forward pass, so it is far cheaper than
Show the answer
C. is positive semidefinite, which conjugate gradients relies on, while can be indefinite away from a minimum
Conjugate gradients assumes a positive-definite system; on an indefinite it can produce directions of negative curvature and break down. is positive semidefinite whenever is convex in the outputs, and costs one JVP and one VJP (Schraudolph, 2002), the same order as by forward-over-reverse.
Further reading
- A. Griewank & A. Walther, Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation, 2nd ed. (SIAM, 2008).
- W. Baur & V. Strassen, "The complexity of partial derivatives," Theoretical Computer Science 22(3), 317–330 (1983).
- B. A. Pearlmutter, "Fast exact multiplication by the Hessian," Neural Computation 6(1), 147–160 (1994).
- T. Chen, B. Xu, C. Zhang & C. Guestrin, "Training deep nets with sublinear memory cost," arXiv:1604.06174 (2016).
- A. N. Gomez, M. Ren, R. Urtasun & R. B. Grosse, "The reversible residual network: backpropagation without storing activations," Advances in Neural Information Processing Systems 30 (2017).