Simple Algorithm
Machine Learning · Convergence · 28 min

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: n\sqrt n checkpointing, logarithmic schedules and reversible residual networks.
  • Get exact Hessian–vector products at the cost of a few gradients with Pearlmutter's R\mathcal R-operator (forward mode applied to the gradient computation), and use them to probe curvature.

Forward mode: dual numbers

DerivationWhy dual arithmetic differentiates
  1. (a+bε)k=ak+k ak−1b ε⟹p(a+bε)=p(a)+p′(a) b ε(a+b\varepsilon)^k=a^k+k\,a^{k-1}b\,\varepsilon\quad\Longrightarrow\quad p(a+b\varepsilon)=p(a)+p'(a)\,b\,\varepsilon

    For a polynomial, expand with the binomial theorem; every term with ε2\varepsilon^2 or higher vanishes, so the ε\varepsilon-coefficient is exactly the derivative:

  2. g(f(a+bε))=g(f(a)+f′(a)b ε)=g(f(a))+g′(f(a)) f′(a) b εg\big(f(a+b\varepsilon)\big)=g\big(f(a)+f'(a)b\,\varepsilon\big)=g(f(a))+g'(f(a))\,f'(a)\,b\,\varepsilon

    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:

  3. f(a+vε)=f(a)+Jf(a) v εf(\mathbf a+\mathbf v\varepsilon)=f(\mathbf a)+J_f(\mathbf a)\,\mathbf v\,\varepsilon

    With several inputs, seed every input xi=ai+viεx_i=a_i+v_i\varepsilon. One evaluation in dual arithmetic returns the value and a Jacobian–vector product (JVP), for a small constant times the cost of ff and with no stored history. A full Jacobian of f:Rn→Rmf:\R^n\to\R^m takes nn sweeps, one per basis vector v=ei\mathbf v=\mathbf e_i.

python
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.75

Forward 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.

Predict before you look

Evaluate f(x)=x3−2xf(x)=x^3-2x at the dual number 2+ε2+\varepsilon. What is the coefficient of ε\varepsilon?

Show the answer

10

(2+ε)3=8+12ε(2+\varepsilon)^3=8+12\varepsilon (the 6ε26\varepsilon^2 and ε3\varepsilon^3 terms vanish) and −2(2+ε)=−4−2ε-2(2+\varepsilon)=-4-2\varepsilon, so f(2+ε)=4+10εf(2+\varepsilon)=4+10\varepsilon: the value f(2)=4f(2)=4 and the derivative f′(2)=3⋅4−2=10f'(2)=3\cdot4-2=10, exactly, with no step size and no rounding beyond ordinary arithmetic.

Reverse mode: the transpose

Write f=fL∘⋯∘f1f=f_L\circ\cdots\circ f_1 with Jacobians JkJ_k evaluated along the computation, so Jf=JL⋯J1J_f=J_L\cdots J_1. Forward mode multiplies from the right, JL(⋯(J1v))J_L(\cdots(J_1\mathbf v)), in the same order as the evaluation. Reverse mode multiplies a row vector from the left, ((u⊤JL)JL−1)⋯J1((\mathbf u^\top J_L)J_{L-1})\cdots J_1: a vector–Jacobian product (VJP), in the opposite order. Because each JkJ_k depends on the intermediate state at step kk, reverse mode must store the forward trajectory (the "tape") or recompute it.

DerivationReverse mode is forward mode transposed
  1. v˙k=∑j∈parents(k)∂ϕk∂vj v˙j⟹y˙=Jf x˙\dot v_k=\sum_{j\in\text{parents}(k)}\frac{\partial\phi_k}{\partial v_j}\,\dot v_j\qquad\Longrightarrow\qquad\dot{\mathbf y}=J_f\,\dot{\mathbf x}

    Forward mode runs a tangent program: one linear update per elementary operation, propagating tangents v˙\dot v from parents to children.

  2. vˉj=∑k∈children(j)∂ϕk∂vj vˉk⟹xˉ=Jf⊤ yˉ\bar v_j=\sum_{k\in\text{children}(j)}\frac{\partial\phi_k}{\partial v_j}\,\bar v_k\qquad\Longrightarrow\qquad\bar{\mathbf x}=J_f^\top\,\bar{\mathbf y}

    A linear straight-line program computing y=Ax\mathbf y=A\mathbf x can be reversed into one computing A⊤yˉA^\top\bar{\mathbf y} with the same number of multiplications: run the statements backward and turn each "vkv_k += c vjc\,v_j" into "vˉj\bar v_j += c vˉkc\,\bar v_k" (the transposition principle). Applied to the tangent program, this yields the adjoint program, which is exactly the backward sweep of backpropagation:

  3. cost(Jf) ≈ min⁡(n,m)×c⋅cost(f)\text{cost}(J_f)\ \approx\ \min(n,m)\times c\cdot\text{cost}(f)

    So a JVP and a VJP each cost a small constant times one evaluation of ff. A full Jacobian costs about min⁡(n,m)\min(n,m) 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.

ModeEach sweep yieldsFull Jacobian of f:Rn→Rmf:\R^n\to\R^mExtra memoryNatural use
Forward (tangent)JvJ\mathbf v: one column, or a directional derivativenn sweepstangents alongside the current values; no historyfew inputs, many outputs; directional derivatives
Reverse (adjoint)u⊤J\mathbf u^\top J: one row; the gradient when m=1m=1mm sweepsthe forward trajectory, or recomputationmany inputs, scalar output: training
Check your understanding

An image renderer maps one lighting parameter θ\theta to 5,000 pixel intensities, f:R→R5000f:\R\to\R^{5000}, and you need ∂yi/∂θ\partial y_i/\partial\theta for every pixel. How many sweeps of which mode does that take?

  1. One reverse sweep, since reverse mode returns every derivative at once
  2. 5,000 forward sweeps, one per pixel
  3. One forward sweep, seeded with θ˙=1\dot\theta=1
  4. 5,000 reverse sweeps, still the cheaper option because backpropagation is efficient
Show the answer

C. One forward sweep, seeded with θ˙=1\dot\theta=1

The Jacobian is a single column of 5,000 entries. One forward sweep carries the tangent θ˙=1\dot\theta=1 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 min⁡(n,m)\min(n,m) sweeps by the cheaper mode: n=1n=1 here, while training has the opposite shape, m=1m=1.

The cheap-gradient theorem

DerivationWhy 3: count the adjoint operations
  1. vˉi += vˉk vj,vˉj += vˉk vi\bar v_i\ \mathrel{+}=\ \bar v_k\,v_j,\qquad\bar v_j\ \mathrel{+}=\ \bar v_k\,v_i

    Run the program forward (L(f)L(f) 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 vk=vivjv_k=v_iv_j creates two nonscalar adjoint updates:

  2. L(f)⏟forward+2 L(f)⏟adjoint=3 L(f)\underbrace{L(f)}_{\text{forward}}+\underbrace{2\,L(f)}_{\text{adjoint}}=3\,L(f)

    A division vk=vi/vjv_k=v_i/v_j also costs two, reusing the stored quotient: vˉi\bar v_i += vˉk/vj\bar v_k/v_j and vˉj\bar v_j -= (vˉk/vj) vk(\bar v_k/v_j)\,v_k, where vˉk/vj\bar v_k/v_j is computed once. So each nonscalar operation of the forward sweep generates at most two in the backward sweep, whatever nn 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, ∂det⁡X/∂Xij=det⁡X (X−1)ji\partial\det X/\partial X_{ij}=\det X\,(X^{-1})_{ji}, so the gradient of the determinant is the inverse, up to a transpose and a scalar. Any algorithm for det⁡X\det X therefore yields, by reverse mode, an algorithm for X−1X^{-1} with at most three times the nonscalar operations, plus n2n^2 divisions.

What the theorem does not say. It concerns one scalar output: a full Jacobian of mm outputs still needs mm reverse sweeps, and a full Hessian needs nn 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 nn steps (layers, or the time steps of a recurrent network or an ODE solver) needs step kk's input when it processes step kk backward. Storing all of them costs memory proportional to nn. Checkpointing stores some and recomputes the rest.

DerivationSquare-root checkpointing (Chen, Xu, Zhang & Guestrin, 2016)
  1. stored during the forward pass:  n/k states\text{stored during the forward pass: }\ n/k\ \text{states}

    Split the nn layers into n/kn/k segments of kk layers. During the forward pass keep only each segment's input: n/kn/k checkpoints.

  2. memory(k)=nk+k  ⟹  k=n,memory=2n\text{memory}(k)=\frac nk+k\ \ \Longrightarrow\ \ k=\sqrt n,\quad\text{memory}=2\sqrt n

    During the backward pass, process segments last to first: recompute one segment's kk internal states from its checkpoint, backpropagate through it, discard them. Peak memory is the checkpoints plus one segment, minimized at k=nk=\sqrt n:

  3. time ≈ F⏟forward+F⏟recompute+2F⏟backward=4Finstead of3F\text{time}\ \approx\ \underbrace{F}_{\text{forward}}+\underbrace{F}_{\text{recompute}}+\underbrace{2F}_{\text{backward}}=4F\quad\text{instead of}\quad3F

    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 3F3F to about 4F4F: roughly a third more compute for n\sqrt n instead of nn 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.

  4. recursive checkpointing: memory O(log⁡n), extra compute O(nlog⁡n)\text{recursive checkpointing: memory }\order{\log n},\ \text{extra compute }\order{n\log n}

    Applying the trick recursively inside segments trades more recomputation for less memory: Chen et al. note memory O(log⁡n)\order{\log n} at O(nlog⁡n)\order{n\log n} 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.

Predict before you look

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 k=100=10k=\sqrt{100}=10 layers give 10 checkpoints plus at most 10 recomputed states: 2n=202\sqrt n=20, a fivefold saving for one extra forward pass. At n=10,000n=10{,}000 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:

y1=x1+F(x2),y2=x2+G(y1)⟺x2=y2−G(y1),x1=y1−F(x2)\mathbf y_1=\mathbf x_1+F(\mathbf x_2),\quad\mathbf y_2=\mathbf x_2+G(\mathbf y_1)\qquad\Longleftrightarrow\qquad\mathbf x_2=\mathbf y_2-G(\mathbf y_1),\quad\mathbf x_1=\mathbf y_1-F(\mathbf x_2)
FF and GG can be any residual functions; they need not be invertible themselves. During the backward pass each block rebuilds its input from its output, so activation storage is independent of depth (non-invertible layers such as downsampling still store theirs). The price is recomputing FF and GG, and floating-point reconstruction error can accumulate over many blocks. Gomez et al. reported accuracy nearly identical to ordinary residual networks of equal size.

Hessian–vector products for the price of a gradient

The Hessian of a network with 10910^9 parameters has 101810^{18} entries and is never formed. But almost everything one wants from it (Newton-type steps, curvature along a direction, top eigenvalues) needs only products HvH\mathbf v, and those are cheap.

DerivationPearlmutter's R-operator (1994)
  1. Rv{∇L(θ)}=∂∂r∇L(θ+rv)∣r=0=Hv\mathcal R_{\mathbf v}\{\nabla L(\boldsymbol\theta)\}=\frac{\partial}{\partial r}\nabla L(\boldsymbol\theta+r\mathbf v)\Big|_{r=0}=H\mathbf v

    Define the directional derivative operator Rv{g(θ)}=∂∂rg(θ+rv)∣r=0\mathcal R_{\mathbf v}\{g(\boldsymbol\theta)\}=\frac{\partial}{\partial r}g(\boldsymbol\theta+r\mathbf v)\big|_{r=0}. Then Rv{θ}=v\mathcal R_{\mathbf v}\{\boldsymbol\theta\}=\mathbf v, and applied to the gradient it gives the Hessian–vector product:

  2. R{z}=R{W}h+WR{hin}+R{b},R{∂ℓ∂W}=R{δ} h⊤+δ R{h}⊤\mathcal R\{\mathbf z\}=\mathcal R\{W\}\mathbf h+W\mathcal R\{\mathbf h_{\text{in}}\}+\mathcal R\{\mathbf b\},\qquad\mathcal R\Big\{\frac{\partial\ell}{\partial W}\Big\}=\mathcal R\{\boldsymbol\delta\}\,\mathbf h^\top+\boldsymbol\delta\,\mathcal R\{\mathbf h\}^\top

    Apply Rv\mathcal R_{\mathbf v} to every line of the forward and backward passes, using the product and chain rules. For a layer of an MLP:

  3. cost(Hv) ≈ c⋅cost(∇L),c a small constant\text{cost}(H\mathbf v)\ \approx\ c\cdot\text{cost}\big(\nabla L\big),\quad c\ \text{a small constant}

    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 (∇L(θ+hv)−∇L(θ−hv))/(2h)(\nabla L(\boldsymbol\theta+h\mathbf v)-\nabla L(\boldsymbol\theta-h\mathbf v))/(2h) costs two gradients but carries O(h2)\order{h^2} truncation and rounding errors.

python
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 HvH\mathbf v 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 Hd=−∇LH\mathbf d=-\nabla L 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. Gv=J⊤HℓJvG\mathbf v=J^\top H_\ell J\mathbf v, with JJ the Jacobian of the outputs and HℓH_\ell 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 HvH\mathbf v (Koh & Liang, 2017).
Check your understanding

You want the largest eigenvalue of the training-loss Hessian of a network with 10810^8 parameters. What is the practical approach?

  1. Form the Hessian with 10810^8 reverse sweeps and call an eigensolver
  2. Estimate it from the loss values along a random direction
  3. Run power iteration or Lanczos using Hessian–vector products, each costing a small multiple of a gradient
  4. 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 HvH\mathbf v, costing a small constant times a gradient by forward-over-reverse. A few dozen iterations usually pin down the top eigenvalue, while forming HH would cost 10810^8 gradients and 101610^{16} numbers of memory.

Key takeaways

  • Dual numbers (ε2=0\varepsilon^2=0) compute f(a+vε)=f(a)+Jv εf(\mathbf a+\mathbf v\varepsilon)=f(\mathbf a)+J\mathbf v\,\varepsilon: 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: L(f,∇f)≤3L(f)L(f,\nabla f)\le3L(f) for scalar rational ff, 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 n\sqrt n layers cuts memory from nn to 2n2\sqrt n 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 (R\mathcal R-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.

Question 1

You evaluate f(x,y)=x2yf(x,y)=x^2y at x=2+εx=2+\varepsilon, y=3y=3 in dual arithmetic. What is the coefficient of ε\varepsilon in the result?

  1. 44
  2. 1212
  3. 66
  4. 1616
Show the answer

B. 1212

(2+ε)2⋅3=(4+4ε)⋅3=12+12ε(2+\varepsilon)^2\cdot3=(4+4\varepsilon)\cdot3=12+12\varepsilon. Seeding xx with x˙=1\dot x=1 and yy with y˙=0\dot y=0 gives the directional derivative along ex\mathbf e_x: ∂f/∂x=2xy=12\partial f/\partial x=2xy=12.

Question 2

What does the Baur–Strassen theorem guarantee?

  1. The gradient of a scalar rational function costs at most 3 times its nonscalar complexity, independent of the number of inputs
  2. The full Jacobian of any f:Rn→Rmf:\R^n\to\R^m costs at most 3 evaluations of ff
  3. Reverse mode uses at most 3 times the memory of the forward pass
  4. 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

L(f,∇f)≤3L(f)L(f,\nabla f)\le3L(f) 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.

Question 3

Why can a reversible residual network backpropagate without storing its activations?

  1. Its blocks FF and GG are invertible functions
  2. It uses forward-mode differentiation instead of reverse mode
  3. It stores only every n\sqrt n-th activation
  4. Each block's input can be computed exactly from its output, x2=y2−G(y1)\mathbf x_2=\mathbf y_2-G(\mathbf y_1), x1=y1−F(x2)\mathbf x_1=\mathbf y_1-F(\mathbf x_2), so the backward pass rebuilds activations as it goes
Show the answer

D. Each block's input can be computed exactly from its output, x2=y2−G(y1)\mathbf x_2=\mathbf y_2-G(\mathbf y_1), x1=y1−F(x2)\mathbf x_1=\mathbf y_1-F(\mathbf x_2), so the backward pass rebuilds activations as it goes

The additive coupling is invertible whatever FF and GG are, so the backward pass can reconstruct each block's input on the fly, at the price of recomputing FF and GG. Activation storage then no longer grows with depth.

Question 4

A Hessian-free optimizer solves Md=−∇LM\mathbf d=-\nabla L by conjugate gradients, using only matrix–vector products. Why is the Gauss–Newton matrix G=J⊤HℓJG=J^\top H_\ell J (with a convex loss ℓ\ell) usually preferred to the Hessian as MM?

  1. Products GvG\mathbf v are exact, while products HvH\mathbf v can only be approximated by finite differences
  2. GG equals the Hessian for neural networks, so nothing changes
  3. GG is positive semidefinite, which conjugate gradients relies on, while HH can be indefinite away from a minimum
  4. GvG\mathbf v needs no forward pass, so it is far cheaper than HvH\mathbf v
Show the answer

C. GG is positive semidefinite, which conjugate gradients relies on, while HH can be indefinite away from a minimum

Conjugate gradients assumes a positive-definite system; on an indefinite HH it can produce directions of negative curvature and break down. G=J⊤HℓJG=J^\top H_\ell J is positive semidefinite whenever ℓ\ell is convex in the outputs, and GvG\mathbf v costs one JVP and one VJP (Schraudolph, 2002), the same order as HvH\mathbf v 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).