22.5 Automatic Differentiation
Throughout the Basics part of this book, every gradient came from a single call to the framework's automatic differentiation engine. The previous section showed what that call computes mathematically: the derivative of a network is a product of Jacobians, one per layer, and the order in which we multiply those matrices determines the cost. A real program, however, is not a neat list of matrices; it is a sequence of additions, multiplications, and function calls. How does a framework extract those factors from ordinary code, and how does it multiply them in the cheap order?
How much the cheap order saves becomes unmistakable on a modern network. Consider a model with parameters that outputs a single scalar loss . Every training step needs the derivative of with respect to all parameters. The direct finite-difference approach nudges one parameter at a time, reruns the network, and divides the change in by the nudge. That requires runs per step. At 10 ms per run, computing a single gradient would take s, nearly twelve days, and the choice of step size would still introduce truncation and rounding errors. Backpropagation returns all derivatives, exact up to floating-point rounding, for roughly the cost of three forward runs, about 30 ms. This section explains where that factor of goes.
The core idea is surprisingly simple: a product of Jacobians can be evaluated from either end. Starting from the input end, each pass propagates one input direction forward, so inputs demand passes. Starting from the loss end, each pass propagates one output direction backward, and a scalar loss has only a single output.
In Section 1.5, we saw how to invoke both modes in a deep learning framework. Here we open the hood. We will build forward mode and reverse mode from scratch in a few dozen lines of Python, prove that they return true derivatives, trace a backward pass by hand, and measure the cost of each mode. We will then compose the two modes to compute second-order curvature along a direction and to differentiate the solution of an equation without differentiating through the solver itself. Two takeaways stand above the rest: evaluating a program on dual numbers yields derivatives automatically (the section's one proposition), and every sweep costs only a small multiple of one program evaluation, with forward mode needing one sweep per input direction and reverse mode one per output direction. Readers on a first pass may save Section 22.5.3 for a second reading.
Three small running examples will anchor the discussion: the chapter's log-sum-exp , whose gradient is the softmax; the plane map from the previous section; and the polynomial expression , which is small enough to trace completely by hand.
We use the following imports throughout this section.
import numpy as np
import torch22.5.1 Forward Mode and Dual Numbers#
22.5.1.1 Dual Numbers#
We want both the value of a program and its derivative from a single run, with no step size to tune and no symbolic formula for written down in advance. The trick is a remarkably small extension of the real numbers. We adjoin a new symbol that is nonzero, yet whose square vanishes:
With this single rule in place, we compute with expressions of the form , called dual numbers, using the ordinary rules of algebra. Every differentiation rule in Section 22.1 works by discarding second-order terms, and setting builds that discard directly into the arithmetic.
Let us see what happens when we apply this rule to . Squaring and cubing it yields
Look at the coefficients of : and are the derivatives of and at . We did not invoke any differentiation rule; the derivatives fell straight out of multiplication. The same holds for any product. Multiplying two dual numbers and dropping the term gives
If and are the derivatives of two quantities whose values are and , then is the derivative of their product. Multiplication of dual numbers simply is the product rule.
A skeptical reader may object that no number can be nonzero and still have a zero square. No real number can, of course, but a matrix easily can. Take . Then , the dual number becomes the matrix , and ordinary matrix multiplication reproduces (22.5.2). Dual numbers are just as concrete as matrices, much as complex numbers are as concrete as rotations and scalings of the plane.
Real programs also call elementary functions such as , , and . For a function given by its Taylor series around , substituting into the series kills every term from onward, leaving only the linear approximation:
Thus and are forced by the algebra itself. For a primitive that is merely differentiable at rather than analytic, we adopt the formula above as the definition of its action on dual numbers. In either case, the -part obeys the chain rule: the incoming derivative of the argument is multiplied by the local derivative .
Proposition (dual numbers compute derivatives). Let be an expression built from constants, the identity, sums, products, and primitives (such as , , ). Suppose each primitive is differentiable at the argument it receives when is evaluated at (for , a positive argument). Then evaluating the same expression on the dual number gives
Proof. We proceed by structural induction on the expression. A constant is represented as and the identity as , so their -parts are their derivatives, and . Now suppose two subexpressions satisfy and . Their sum has -part . By (22.5.2), their product has -part . Finally, applying a primitive to produces, by the rule above with and , the -part . Every way of combining subexpressions preserves the property, so the full expression satisfies (22.5.3).
To differentiate a program, we therefore run it on and read off
the -part of the output. Programs with loops and branches are
handled automatically as well: for any fixed input, the program executes a
single concrete sequence of elementary operations, which is an expression of
this exact form, and the dual-number run differentiates that execution path
(Section 1.5.3.1 demonstrates this in the frameworks).
Note, however, that the result is the derivative of the executed path, which
equals only if all nearby inputs take the same branches. A program that
returns x if x != 0 and 0.0 otherwise computes the identity, yet at
it executes the constant branch, and the dual-number run reports slope .
This is the failure we met with in
Section 22.1.6.3.
The input's -part, here , is called the seed. No symbolic
expression for is ever constructed and no step size is chosen; the only
error is floating-point rounding.
22.5.1.2 A Forward-Mode Engine#
Operator overloading turns this algebra directly into code. The Dual class
below stores a value together with its derivative part , which we call
the tangent and write as for a quantity . It implements
(22.5.2) for * and equips sin, exp, and log with the
primitive rule. A class counter ops tallies how many primitive operations have
executed, which we will use to measure cost in
Section 22.5.2.4.
class Dual:
"""A dual number a + b*eps with eps^2 = 0; b carries the derivative."""
ops = 0 # primitive operations run
def __init__(self, a, b=0.0):
self.a, self.b = a, b # value, tangent
def __add__(self, o):
o = o if isinstance(o, Dual) else Dual(o)
Dual.ops += 1
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)
Dual.ops += 1
return Dual(self.a * o.a, self.a * o.b + self.b * o.a) # product rule
__rmul__ = __mul__
def sin(self):
Dual.ops += 1
return Dual(np.sin(self.a), np.cos(self.a) * self.b) # chain rule
def exp(self):
Dual.ops += 1
return Dual(np.exp(self.a), np.exp(self.a) * self.b)
def log(self):
Dual.ops += 1
return Dual(np.log(self.a), self.b / self.a)
def __repr__(self):
return f'{np.round(self.a, 6)} + {np.round(self.b, 6)} eps'
Let us test Dual on at by passing in
, and compare its -part against the hand-derived
derivative :
def f(x):
return (x * x).sin() + x.exp() # sin(x^2) + e^x, in dual algebra
x0 = 1.3
out = f(Dual(x0, 1.0)) # seed the derivative with 1
exact = 2 * x0 * np.cos(x0**2) + np.exp(x0) # f'(x) by hand
print('dual result :', out)
print('value f(x) :', np.sin(x0**2) + np.exp(x0))
print("derivative : dual %.6f vs exact %.6f" % (out.b, exact))
dual result : 4.6622 + 3.360101 eps
value f(x) : 4.662200318713363
derivative : dual 3.360101 vs exact 3.360101
A single run returns both the function value and the derivative , matching the analytic formula to every printed digit.
A single-variable example, however, hides the main limitation of forward mode. Consider log-sum-exp at the three-dimensional input , whose gradient is the softmax . How many passes does forward mode need to obtain this full gradient? Seeding input with and all other inputs with yields the single partial derivative in the output's -part, and nothing else.
def lse_dual(xs): # log-sum-exp, in dual algebra
total = 0.0
for x in xs:
total = total + x.exp()
return total.log()
x_lse = [1.0, -0.5, 2.0]
p = np.exp(x_lse) / np.exp(x_lse).sum() # softmax, the known gradient
for j in range(3): # one pass per input direction
out = lse_dual([Dual(x, 1.0 if k == j else 0.0) for k, x in enumerate(x_lse)])
print(f'seed e{j + 1}: value {out.a:.6f}, partial {out.b:.6f}, '
f'softmax {p[j]:.6f}')
seed e1: value 2.371539, partial 0.253716, softmax 0.253716
seed e2: value 2.371539, partial 0.056612, softmax 0.056612
seed e3: value 2.371539, partial 0.689672, softmax 0.689672
It takes three passes. Each pass recomputes the same value and recovers just one softmax entry: , , or . More generally, a gradient over inputs requires passes. For the -parameter network from the opening, that puts us right back at runs of the program. Forward mode eliminates the finite-difference step size, but not the number of runs.
22.5.1.3 Vector Tangents and Jacobian Columns#
Now consider a vector-valued map with Jacobian . What does a single forward pass compute? Suppose we seed the inputs with an arbitrary direction , setting input to . Applying our proposition to the one-dimensional slice shows that output emerges as . Collecting the -parts across all outputs therefore produces the vector , known as the Jacobian--vector product (JVP). When is the -th standard basis vector , the JVP picks out column of . One forward pass carries one input direction through the entire map.
Let us verify this on the plane map at . Its Jacobian, whose row holds the partial derivatives of output , is
Two forward passes, seeded first with and then with , recover its two columns.
def plane_dual(x, y):
return [x + y.sin(), y + 0.5 * (x * x)] # (x + sin y, y + x^2/2)
z0 = (0.5, 0.5)
cols = []
for seed in ((1.0, 0.0), (0.0, 1.0)): # e1, then e2
out = plane_dual(Dual(z0[0], seed[0]), Dual(z0[1], seed[1]))
cols.append([out[0].b, out[1].b]) # tangent = J @ seed, a column
J_fwd = np.array(cols).T # columns side by side
J_exact = np.array([[1.0, np.cos(0.5)], [0.5, 1.0]])
print('forward-mode J:\n', J_fwd.round(6))
print('matches the analytic Jacobian:', np.allclose(J_fwd, J_exact))
forward-mode J:
[[1. 0.877583]
[0.5 1. ]]
matches the analytic Jacobian: True
Notice that nothing in Dual forces the tangent to be a scalar. If we give
the vector tangent and the vector tangent , every operation
propagates both input directions simultaneously, and the tangent of output
becomes row of . Can a single pass recover the entire matrix?
out = plane_dual(Dual(z0[0], np.array([1.0, 0.0])), # identity seed:
Dual(z0[1], np.array([0.0, 1.0]))) # both directions at once
J_one = np.array([out[0].b, out[1].b]) # row i = tangent of f_i
print('one-pass J:\n', J_one.round(6))
print('matches the analytic Jacobian:', np.allclose(J_one, J_exact))
one-pass J:
[[1. 0.877583]
[0.5 1. ]]
matches the analytic Jacobian: True
It can, though the savings are illusory. Every tangent operation now acts on arrays of length , so that single pass performs roughly times as much arithmetic as a scalar pass. Counting passes and counting arithmetic are not the same thing, and we will measure arithmetic directly in Section 22.5.2.4. For a scalar loss with inputs, forward mode demands either scalar passes or one pass carrying tangents of length . Either way, its total work scales with runs of the program.
22.5.2 Reverse Mode and the Tape#
22.5.2.1 Two Orders of One Product#
To eliminate the factor of , we must multiply the chain of derivatives in the opposite order. In Section 22.4, we saw that the Jacobian of a -step program is the product of the step Jacobians,
and that the parenthesization of this product governs its cost: for three layers of width multiplied by a row vector on the left, associating from the left takes multiplications, whereas associating from the right takes (Figure 22.4.3). An automatic differentiation engine never materializes these Jacobian matrices explicitly. Instead, it propagates a seed vector through one step after another. Forward mode multiplies a column direction in from the right; reverse mode multiplies a row vector in from the left:
Because a seed vector is present from the start, every step is a matrix--vector product and never a matrix--matrix product. On the left, an input direction travels forward to produce the JVP . On the right, an output direction travels backward to produce the vector--Jacobian product (VJP) , a linear combination of the rows of weighted by . Setting extracts row of .
From this symmetry comes the fundamental cost rule of automatic differentiation. Forward mode requires one sweep per input direction, while reverse mode requires one sweep per output direction, and each sweep costs only a small constant multiple of evaluating the program once. For programs built from , Baur and Strassen proved that computing all partial derivatives together takes at most a fixed multiple of the program's own operation count, between three and five depending on which operations are counted (Baur and Strassen, 1983). A scalar loss has a Jacobian, a single row, so one reverse sweep seeded with returns the entire gradient at once. Figure 22.5.1 illustrates this rule in terms of matrix shapes.
The shape of the Jacobian decides the cheaper mode. A scalar loss has a Jacobian: one row, one VJP, one backward pass. A map with one input has an Jacobian: one column, one JVP, one forward pass. A full Jacobian costs passes with the cheaper mode.
The two modes evaluate the exact same matrix product from opposite ends. Which end wins depends solely on the shape of : the cheaper mode is the one whose number of seeds matches the shorter side. A neural network loss, with one scalar output and millions or billions of parameters, has the most lopsided Jacobian imaginable.
22.5.2.2 The Tape#
Forward mode and reverse mode propagate fundamentally different quantities. In a program taking input to output , the tangent of an intermediate variable measures how fast changes when the input moves in the direction . By contrast, the adjoint introduced in Section 22.3 is the total derivative of the final output with respect to , summed over all paths from to . A tangent depends only on the steps before , whereas an adjoint depends on the steps after . In with , for example, we have coming from below and coming from above.
This asymmetry dictates how each mode executes
(Figure 22.5.2). Because tangents move in the same direction
as the values, forward mode finishes in a single pass alongside the program
itself; Dual never needs to remember past intermediates. Adjoints, however,
travel against the flow of execution: computing the adjoint of a node requires
the adjoints of every node that consumes it, and those exist only after the
program has reached its output. Reverse mode therefore runs in two phases. First
it executes the program forward while recording every elementary operation; then
it replays that record in reverse. The record is called the tape, or Wengert
list, after the list of elementary operations that Wengert (1964)
introduced for forward mode; reversing the list yields reverse mode, introduced
by Linnainmaa (1970).
Forward and reverse mode on a chain . Both evaluate the chain from left to right (gray). Forward mode (top) carries the tangents along with the values, one input direction per sweep. Reverse mode (bottom) runs the chain first and then carries the adjoints , the total derivatives of with respect to , back from the seed , one output direction per sweep, which for a scalar loss is the whole gradient.
We can build a working reverse-mode engine in about forty lines of Python. Each
node on the tape stores its forward value, its parent nodes, and a small
backward closure. Given the node's own adjoint , that closure adds the
node's contribution to each parent's adjoint: for it adds to both
parents, while for it adds to and to .
The function backprop topologically sorts the graph so that every node appears
after its parents, seeds the output adjoint with , and invokes the closures
in reverse order. Just like Dual, the class maintains an ops counter across
both forward and backward steps.
class Var:
"""A scalar node on the autodiff tape; .grad accumulates the adjoint."""
ops = 0 # recorded ops + backward steps
def __init__(self, value, parents=(), backward=lambda g: None):
self.value = value
self.grad = 0.0
self._parents = parents # nodes this one depends on
self._backward = backward # pushes adjoint to parents
def __add__(self, o):
o = o if isinstance(o, Var) else Var(o)
Var.ops += 1
out = Var(self.value + o.value, (self, o))
def back(g): # d(a+b) = 1*g to each parent
Var.ops += 1
self.grad += g; o.grad += g
out._backward = back
return out
__radd__ = __add__
def __mul__(self, o):
o = o if isinstance(o, Var) else Var(o)
Var.ops += 1
out = Var(self.value * o.value, (self, o))
def back(g): # product rule, reversed
Var.ops += 1
self.grad += o.value * g; o.grad += self.value * g
out._backward = back
return out
__rmul__ = __mul__
def backprop(node):
"""Topologically sort the tape and replay it backward from `node`."""
order, seen = [], set()
def visit(v):
if v not in seen:
seen.add(v)
for p in v._parents:
visit(p)
order.append(v)
visit(node)
node.grad = 1.0 # seed the output adjoint
for v in reversed(order):
v._backward(v.grad)
Although Var implements only + and *, that is already enough for our
third running example, . Before running the code, let us trace the
entire backward sweep by hand at , . The forward pass records three
elementary operations: , then , and finally
. The backward sweep visits nodes in a reverse topological order
such as , ensuring that every node is processed only after all nodes
that depend on it (backprop happens to visit before , which is equally
valid). Each adjoint is the sum of contributions arriving along its outgoing
edges, where each contribution multiplies the consumer's adjoint by the local
derivative:
| node | outgoing edges and their contributions | adjoint |
|---|---|---|
| none: the seed | ||
| both arguments of : | ||
| : | ||
| and : | ||
| : |
Direct differentiation of confirms both answers:
and
. Notice how crucial
accumulation is at two places in the graph: feeds both arguments of the
final product, and feeds both and (Figure 22.5.3).
Overwriting instead of adding would leave , and even with
fixed it would leave as either or , depending on which
closure happened to run last. Because an adjoint sums over all outgoing edges
(the chain rule's sum over paths), every backward closure must accumulate with
+=.
The tape of at , . Each box shows the forward value of its node; the orange label shows its adjoint, the derivative of with respect to that node. The graph is a diamond, not a chain: feeds both and , and feeds both arguments of , so the adjoints of and are sums of two contributions.
Recording the same expression with Var and running a single backward sweep
gives:
u, v = Var(2.0), Var(-3.0)
r = u * v + u # t = uv, then r = t + u
y = r * r # r feeds both arguments
backprop(y)
print('our tape : dy/du = %.4f dy/dv = %.4f' % (u.grad, v.grad))
our tape : dy/du = 16.0000 dy/dv = -16.0000
These match and from our hand trace. A production deep learning framework runs the exact same algorithm at tensor scale and produces the same two derivatives:
ut = torch.tensor(2.0, requires_grad=True)
vt = torch.tensor(-3.0, requires_grad=True)
rt = ut * vt + ut
(rt * rt).backward() # framework autograd
print('torch : dy/du = %.4f dy/dv = %.4f' % (ut.grad, vt.grad))torch : dy/du = 16.0000 dy/dv = -16.0000
A production framework differs from our toy Var engine in three practical
respects, none of which alters the underlying algorithm. First, its nodes hold
entire tensors rather than scalars, so each backward closure implements the VJP
of a whole tensor operation, such as and (Section 22.4.3.2) for matrix
multiplication. Second, its library of primitives is much larger, each paired
with a hand-tuned VJP rule. Third, frameworks construct the computation graph in
one of two ways. An eager tape records operations dynamically as the program
executes, just as Var does. A tracer, by contrast, runs the program once on
abstract placeholder inputs to capture its sequence of operations, builds the
linearized forward-mode rule for each step, and then transposes and reverses the
sequence. Both routes produce the exact same backward sweep. Applied to a neural
network, this reverse-mode sweep is what deep learning calls backpropagation
(Rumelhart et al., 1986).
PyTorch records eagerly: every operation on a tensor with
requires_grad=True appends a node to the graph, and backward() replays
those nodes in reverse.
The frameworks also inherit the hypothesis of the dual-number proposition: each
primitive must be differentiable at the argument it receives. Masking is where
this hypothesis fails most often in practice. Suppose that we sum
over the real entries of a padded vector, and that a where sets the padded
entries to zero. A where chooses between two values that have both been
computed, so still runs on the padding, here . The forward pass
is unharmed: the is discarded and the loss is .
On the backward sweep, however, where sends the adjoint into the
discarded branch, and the VJP of multiplies it by the local derivative
. In floating-point arithmetic is not but NaN.
x = torch.tensor([2.0, 0.0], requires_grad=True) # x[1] is padding
mask = torch.tensor([True, False])
loss = torch.where(mask, torch.log(x), 0.0).sum() # sum of log x, real entries
loss.backward()
print('one where : loss = %.4f, grad =' % loss.item(), x.grad.numpy())
x.grad = None
safe = torch.where(mask, x, 1.0) # padding never reaches log
loss = torch.where(mask, torch.log(safe), 0.0).sum()
loss.backward()
print('double where: loss = %.4f, grad =' % loss.item(), x.grad.numpy())one where : loss = 0.6931, grad = [0.5 nan]
double where: loss = 0.6931, grad = [0.5 0. ]
The first line reports the gradient , although the loss
does not depend on the padded entry at all and the true derivative there is
. A single NaN is not a local blemish: every parameter upstream of
receives it. The second line shows the standard remedy, the double where. An
inner where replaces the masked entries by a harmless value, here , before
the primitive sees them, so that no infinite local derivative is ever formed
and the gradient is . Clamping the argument away from the edge of the
domain serves the same purpose. The same trap awaits at , and
with it a norm computed as at .
22.5.2.3 Parameter Gradients#
So far, the Jacobian product (22.5.4) has tracked derivatives with respect to the network's input, whereas training needs derivatives with respect to its weights. Fortunately, the weight gradients drop out of the very same backward sweep via the layer VJP rule (Section 22.4.3.2). For a linear layer with weight matrix of shape , that rule reads
the outer product of the adjoint arriving from above and the activation stored from below. Intuitively, a weight matters in proportion to both how strongly its output affects the loss and how large its input activation was. What matters for our cost analysis is how much arithmetic this rule takes.
Forming the outer product takes multiplications, the same count as the forward matrix--vector product . Passing the adjoint down to the previous layer, , takes another multiplications. Measured in multiplications, the backward sweep therefore costs roughly twice a forward pass, so a forward pass plus a backward sweep costs about three forward passes, matching the 30 ms figure from the opening. Forward mode, by contrast, would have to treat every individual weight as its own input direction, requiring passes for a single layer alone. That is why no framework trains neural networks in forward mode.
22.5.2.4 Cost of the Two Modes#
Because we built both engines ourselves, we can measure their operation counts
directly instead of relying on asymptotic arguments. Take
on inputs for
. We choose a polynomial built solely from and so
that Var can record it without adding exp and log closures (which would
mirror the methods of Dual). Its gradient is
, and one plain evaluation runs
primitive operations: squares, additions, and one final
square. Forward mode will clearly need passes of operations each.
Before reading the output below, pause and guess how many operations reverse
mode will take.
n = 200
def f(xs): # f: R^n -> R, from + and * alone
total = 0.0
for x in xs:
total = total + x * x
return total * total # (sum of squares)^2
xs0 = [0.01 * (j + 1) for j in range(n)]
Dual.ops = 0
grad_fwd = [f([Dual(x, 1.0 if k == j else 0.0) for k, x in enumerate(xs0)]).b
for j in range(n)] # forward mode: one pass per input direction
Var.ops = 0
xs = [Var(x) for x in xs0] # reverse mode: one recorded pass...
backprop(f(xs)) # ...and one backward sweep for all n partials
grad_rev = [x.grad for x in xs]
gap = max(abs(a - b) for a, b in zip(grad_fwd, grad_rev))
print(f'forward mode: {Dual.ops:,} operations ({n} passes of {2 * n + 1})')
print(f'reverse mode: {Var.ops:,} operations (one recorded pass, one sweep)')
print(f'ratio {Dual.ops / Var.ops:.1f}, largest gradient difference {gap:.1e}')
forward mode: 80,200 operations (200 passes of 401)
reverse mode: 802 operations (one recorded pass, one sweep)
ratio 100.0, largest gradient difference 0.0e+00
Forward mode executed operations, whereas reverse mode executed only : recorded during the forward pass and backward closures during the sweep. The ratio is , and the two gradients agree to every printed digit. For these engines, pass counts differ by a factor of and operation counts by ; at , that recovers the factor from the opening up to the same small constant.
At first glance, the measured factor of two might seem to contradict the factor
of three we quoted earlier. It does not: Var.ops counts each backward closure
as a single operation, even though the closure for multiplication performs two
multiplications of its own. Counting scalar multiplications directly gives
on the backward sweep against on the forward pass, so computing the value
and gradient together costs three times the value alone, just as it did for the
linear layer. Including the additions that accumulate adjoints brings the
backward sweep to operations and the total factor to four, still well
within the Baur--Strassen bound.
Reverse mode trades memory for this speed. The tape must retain all recorded intermediate values until the backward sweep consumes them, whereas forward mode, like the original program, holds only the current values alongside their tangents.
22.5.2.5 Gradient Checkpointing#
A computation of recorded steps keeps intermediate values alive in memory until the backward sweep reaches them. In a deep neural network, those values are the activations of every layer for every example in the batch, and activation memory, rather than arithmetic, is often what caps the batch size or depth.
The simplest remedy divides the tape into segments of steps. During the forward pass, we save only every -th value, the checkpoints, and discard everything in between. When the backward sweep arrives at a segment, it recomputes that segment's steps from its saved checkpoint onto a temporary tape, sweeps that short tape backward, and immediately frees it. At any instant, memory holds only the checkpoints plus one active segment of length . Choosing to balance these two terms minimizes peak memory:
The minimum follows either from setting or directly from the AM--GM inequality . Peak memory now grows only as the square root of the computation length rather than linearly. Because each step is recomputed once, the extra compute is just one additional forward pass. For , segment lengths yield peak memory , with the minimum at . At , segments of length store just values instead of (Chen et al., 2016). Figure 22.5.4 illustrates this schedule.
Gradient checkpointing on a tape of steps. Plain reverse mode (top) keeps all values until the backward sweep uses them. Checkpointing (bottom) keeps every -th value; when the backward sweep reaches a segment, the segment is recomputed from its checkpoint and then swept. The memory is , which is at , for one extra forward pass.
Importantly, checkpointing alters time and memory without changing the gradient at all, provided the recomputation is deterministic: the recomputed intermediates are then identical, so the resulting derivatives match plain reverse mode bit for bit. Deep learning frameworks expose this trade-off at the level of network blocks, storing only a checkpointed block's input and rerunning the block during backpropagation. There the proviso needs care. A rerun block draws a fresh dropout mask unless the state of the random number generator is restored, batch normalization updates its running statistics a second time, and nondeterministic GPU kernels need not reproduce the first run's bits. Applying the same idea recursively inside each segment pushes memory all the way down to at the cost of recomputation.
22.5.3 Composing Jacobian Products#
Automatic differentiation offers both linear operators our toy engines just built: the forward-mode JVP and the reverse-mode VJP . Once both are available as composable primitives, we can compute directional curvature, differentiate through numerical solvers, or assemble full Jacobians when needed.
22.5.3.1 Jacobian--Vector and Vector--Jacobian Products#
In Section 1.5.4, we met the framework APIs for both
products. Let us evaluate them on the plane map at with
. Using the Jacobian we computed earlier with Dual,
we expect and
, and the
framework calls match these values directly.
def plane(z): # (x + sin y, y + x^2/2)
return torch.stack([z[0] + torch.sin(z[1]), z[1] + 0.5 * z[0]**2])
z0 = torch.tensor([0.5, 0.5])
v, u = torch.tensor([1.0, 2.0]), torch.tensor([1.0, 2.0])
_, Jv = torch.func.jvp(plane, (z0,), (v,)) # forward mode: J v
_, vjp_fn = torch.func.vjp(plane, z0) # reverse mode: records once,
uJ, = vjp_fn(u) # then u^T J per seed
J = torch.func.jacrev(plane)(z0) # one VJP per row
print('J v =', Jv.numpy().round(4))
print('u^T J =', uJ.numpy().round(4))
print('J =', J.numpy().astype(float).round(4).tolist())J v = [2.7552 2.5 ]
u^T J = [2. 2.8776]
J = [[1.0, 0.8776], [0.5, 1.0]]
Both a JVP and a VJP cost a single sweep and propagate only a vector of derivative information, though the VJP must also hold the forward intermediates on its tape. Assembling a dense Jacobian takes sweeps in the cheaper mode plus numbers of storage. Materializing the full matrix is the right choice when is small, as in this example, or when an algorithm needs its determinant, as in normalizing flows that transform probability densities by .
22.5.3.2 Hessian--Vector Products#
For a model with parameters, the Hessian has entries, which would occupy 4 TB in float32. Yet second-order optimization methods rarely need the matrix itself. Newton's method uses the Hessian only to solve for the update step , and Newton--CG (or truncated Newton) solves that linear system by conjugate gradients, an iterative solver that accesses solely through matrix--vector products (Nocedal and Wright, 2006; Martens, 2010). Can we compute without ever forming ?
We can, by composing reverse mode and forward mode. Because the Hessian is the Jacobian of the gradient map , the product is simply a JVP of the gradient, measuring how fast the gradient changes along :
A reverse sweep evaluates , and a forward-mode pass through that gradient computation, seeded with tangent , differentiates it along . This composition is called forward over reverse (Pearlmutter, 1994). Regardless of the dimension , its cost is only a small constant multiple of computing a single gradient.
Log-sum-exp gives us a clean test with a closed-form answer. Its gradient is the softmax , so its Hessian is the softmax Jacobian (Section 22.4, equivalently the covariance matrix of a one-hot vector with drawn from ). Therefore,
where denotes entrywise multiplication. Evaluating the right-hand side requires just multiplications and never builds an matrix. At and , we have and , which gives
Notice that this is a genuine check, unlike testing on a quadratic . For a quadratic, the gradient at happens to equal , so a buggy implementation could still pass; for log-sum-exp, varies with , and the gradient at , , is nowhere near .
With both modes available, forward over reverse takes a single line of code.
x = torch.tensor([1.0, -0.5, 2.0])
v = torch.tensor([1.0, 0.5, -1.0])
lse = lambda x: torch.logsumexp(x, 0)
_, Hv = torch.func.jvp(torch.func.grad(lse), (x,), (v,)) # forward over reverse
p = torch.softmax(x, 0)
print('forward over reverse :', Hv.numpy().round(4))
print('p*v - p (p.v) :', (p * v - p * (p @ v)).numpy().round(4))forward over reverse : [ 0.3571 0.0514 -0.4085]
p*v - p (p.v) : [ 0.3571 0.0514 -0.4085]
The computed products match (22.5.9) to full printed
precision, without ever forming the Hessian matrix. In
Exercise 3, you
will build the same product directly from our Dual and Var classes and
compare forward-over-reverse with reverse-over-reverse.
22.5.3.3 Implicit Differentiation#
Not every quantity of interest comes from an explicit formula. Many are defined implicitly as the solution to an equation and computed by an iterative solver: the fixed point of a recurrence, the equilibrium of a physical system, or the minimizer of an inner optimization problem. Recording twenty Newton iterations on a tape and backpropagating through all of them does work, but it stores every intermediate iterate and differentiates the particular trajectory the solver happened to follow. Can we obtain the derivative from the defining equation alone?
Start with the simplest possible case: a single equation in one unknown, , whose solution is . Instead of differentiating the closed form, differentiate the identity directly with respect to . That gives , and solving for the derivative yields
which is indeed the derivative of (equal to at ). Crucially, we never used an explicit formula for , only the equation and the value of the solution itself.
The general result is the implicit function theorem (Rudin, 1976), which we state without proof. Let map to , suppose is continuously differentiable near a solution of , and suppose the Jacobian is invertible there. Then, in a neighborhood of , the solution is a differentiable function . Applying the chain rule to the identity gives , and therefore
Both Jacobians on the right are evaluated solely at the solution . Computing the full derivative matrix costs one linear solve with per parameter, regardless of how many iterations the solver took. Even better, in VJP form it takes just a single linear solve for all parameters combined: , where the adjoint vector solves .
This same principle powers several major techniques in machine learning: the adjoint method for differentiating through ODE solvers (Section 26.3.2), deep equilibrium models (Bai et al., 2019) that define an entire layer as a fixed point and train it via (22.5.10), and gradient-based hyperparameter tuning through an inner minimization.
Let us test (22.5.10) on a nonlinear system, and , solved with twenty Newton steps, and check the implicit gradient against a central difference of the solver's output.
# Implicit gradient dx*/dtheta = -(dg/dx)^{-1} dg/dtheta on a 2x2 system,
# checked against a finite difference of the solver output
def g(x, th): # g(x, theta) = 0 defines x*(theta)
return np.array([x[0]**2 + th * x[1] - 2, x[0] * x[1] + th - 1])
def dg_dx(x, th): # Jacobian in x, evaluated at (x, th)
return np.array([[2 * x[0], th], [x[1], x[0]]])
def solve(th): # Newton iteration, from a fixed start
x = np.array([1.0, 1.0])
for _ in range(20):
x = x - np.linalg.solve(dg_dx(x, th), g(x, th))
return x
th, h = 0.3, 1e-6
xs = solve(th)
dg_dth = np.array([xs[1], 1.0]) # dg/dtheta at the solution
implicit = -np.linalg.solve(dg_dx(xs, th), dg_dth)
fd = (solve(th + h) - solve(th - h)) / (2 * h)
print('implicit-function gradient:', implicit.round(8))
print('finite-difference check :', fd.round(8))
implicit-function gradient: [-0.11311451 -0.69322129]
finite-difference check : [-0.11311451 -0.69322129]
The two vectors agree to the full precision of the finite difference, and none of the twenty Newton iterations ever appeared in the implicit formula. Because the derivative depends only on and the solution , any solver that converges to the same root produces the same gradient.
Like any theorem, the implicit function theorem has two clear boundaries, and both are easy to observe in practice. First, must be invertible at the solution. In our scalar example , at we have , so the formula divides by zero, reflecting the vertical tangent of at the origin. Second, the formula assumes the solver has actually converged. To see what goes wrong when it has not, let us run Newton's method on starting from and stop early after steps, comparing the implicit formula evaluated at the unconverged iterate with the derivative of the -step unrolled solver itself (estimated by a central difference in ).
def newton(theta, k, x=1.0): # k Newton steps on x^2 = theta
for _ in range(k):
x = x - (x * x - theta) / (2 * x)
return x
theta, h = 4.0, 1e-6
for k in (1, 2, 3):
x_k = newton(theta, k)
unrolled = (newton(theta + h, k) - newton(theta - h, k)) / (2 * h)
print(f'k={k}: x = {x_k:.5f}, formula {1 / (2 * x_k):.4f}, '
f'unrolled {unrolled:.4f}, exact 0.25')
k=1: x = 2.50000, formula 0.2000, unrolled 0.5000, exact 0.25
k=2: x = 2.05000, formula 0.2439, unrolled 0.2900, exact 0.25
k=3: x = 2.00061, formula 0.2499, unrolled 0.2509, exact 0.25
After one, two, and three steps, Newton's method reaches , , and . Against the true derivative , the implicit formula returns , , and , while the unrolled derivative gives , , and . Both are inaccurate before convergence: the implicit formula inherits the solver's residual error, and the unrolled derivative, which differentiates the truncated iteration path, is even further off here. The remedy is straightforward: let the solver converge first.
One fundamental problem remains open. Automatic differentiation computes the product accurately up to floating-point rounding, but it cannot alter the value of that product. Across many layers, a long product of Jacobians can still shrink or explode geometrically (Section 22.4), and an exact gradient of is no more useful for training than zero. Controlling vanishing and exploding gradients requires careful initialization and architectural choices, which we take up starting in Section 4.4.
22.5.4 Summary#
The derivative of a program is the product of the Jacobians of its elementary steps, and automatic differentiation evaluates that product against a seed vector so that every step is a matrix--vector product rather than a matrix--matrix product. Forward mode runs the program on dual numbers to compute one Jacobian--vector product (one input direction) per pass; reverse mode records a tape during the forward pass and replays it backward to compute one vector--Jacobian product (one output direction) per pass. The shape of the Jacobian determines which mode is cheaper. Because a scalar loss has a single output, one reverse sweep yields all parameter gradients at roughly three times the cost of evaluating the loss. On with inputs, reverse mode took operations against for forward mode. The tape's memory grows linearly with the computation length , and gradient checkpointing lowers peak memory to for one extra forward pass. Finally, composing forward mode over reverse mode computes Hessian--vector products at a small constant multiple of one gradient evaluation, and the implicit function theorem differentiates a solver's output with a single linear solve at the converged solution.
22.5.5 Exercises#
-
[code] Dual and complex steps. Take at and the second column of its Jacobian. The central difference has an error of order from truncation plus an error of order from rounding, where is the float64 unit roundoff.
- Predict the best step and the smallest error, then check the prediction
for (you should find about
near ). Compare with one pass of
Dualseeded with . Why does no step size enter the dual computation? - Repeat (a) for the first column , and explain why the central difference is exact there for every , up to rounding. (Hint: is a polynomial of degree two in .)
- Replacing by the imaginary unit gives the complex-step estimate (Squire and Trapp, 1998), valid for an that extends analytically to complex arguments, as this one does. Expand to third order in and show that the error of the estimate is . Why does the estimate subtract no nearly equal numbers?
- Evaluate the complex-step estimate with NumPy's complex arithmetic for and compare its errors with those of (a). Which difference between and causes the error of the complex step?
- Predict the best step and the smallest error, then check the prediction
for (you should find about
near ). Compare with one pass of
-
[code] Hyperparameter gradient. Ridge regression with one penalty per feature fits
on training data , and its validation loss on data is .
- Show that solves , and use (22.5.10) to derive .
- Show that , where solves one linear system with the matrix , and give its right-hand side. How many linear solves does the forward route through need for penalties, and how many does this adjoint route need?
- Implement and the adjoint gradient in NumPy for random data with training examples, validation examples, and features. Check the gradient against central differences of .
Adapted from Alan Edelman and Steven G. Johnson, Matrix Calculus for Machine Learning and Beyond, problem set 2, MIT 18.S096, IAP 2023, Problem 1.
-
[code] Hessian--vector product. ● The function of Section 22.5.2.4, evaluated at the inputs
xs0with , is built from addition and multiplication alone, so bothDualandVarcan evaluate it.- Derive and the Hessian of , and write in a form that never builds .
- Draw a random direction , wrap each input as
Var(Dual(x_j, v_j)), and runbackprop. Show that the value parts of the resulting adjoints form and that their -parts form , and compare both with (a) and with the Hessian--vector product of Section 22.5.3.2 applied to the same . Which operations of the backward closures run in dual arithmetic, and why does this make the computation forward over reverse in the sense of (22.5.8)? - Nest the tape in itself instead. Wrap each input as
Var(Var(x_j))and runbackprop; the adjoints are nowVarobjects. Form from them and runbackpropon it to obtain by reverse over reverse. Count theVarobjects that each method creates, for example with a counter inVar.__init__, and compare both counts with that of one plain gradient. Which method records the backward pass, and what does that cost in memory?
-
[code] Checkpointing on the tape. ● Let for with and , and differentiate with respect to .
Varhas no subtraction, so record each step asx + (-0.01) * x * x.- Record the chain on the tape with plain
backpropand count the nodes that the tape holds when the backward sweep starts. backpropseeds the output adjoint with . Generalize it to accept any seed. Show that recording a segment from a fresh leaf for and running the generalizedbackpropfrom with the seed returns in the adjoint of the leaf.- Implement the schedule of Figure 22.5.4 with segments of steps: a forward pass in plain floats that stores , followed by a backward pass that re-records one segment at a time, from the last to the first, and applies (b). Check that the result equals the gradient of (a).
- For , report the number of stored
checkpoints, the largest tape in steps, and the number of evaluations of the
step , the first forward pass included. Confirm
the memory of (22.5.7), that is
, and its minimizer . Repeat the
sweep for and over the divisors of (a
single segment of steps exceeds Python's default recursion
limit in
backprop). How does the minimizing scale with , and how many step evaluations does the best schedule need?
- Record the chain on the tape with plain
-
[extended] Equilibrium layer. ●● A deep equilibrium layer (Bai et al., 2019) outputs the fixed point
where depends on the layer's input. Let the loss be , and write for the derivative of at the fixed point.
-
Show that the map is a contraction when , so that the fixed point exists and is unique, and that is then invertible. Use (22.5.10) to derive , and show that it equals for the adjoint that solves .
-
Take , a standard normal , , and for , and draw the entries of and independently from . In NumPy, compute by fixed-point iteration and the gradient of (a) with one linear solve. Check a few of its entries against central differences of .
-
Unrolled differentiation runs iterations from and backpropagates through all of them. Implement this backward sweep by hand, one VJP per iteration. Plot against the error of the unrolled gradient relative to the gradient of (b), together with the forward error . Compare the decay rate of both errors with the spectral radius of . How does the ratio of the two errors behave as grows, and why? How does the memory of each gradient scale with ?
-
Replace the linear solve by steps of the iteration from , a truncated Neumann series that Geng et al. (2021) use as a phantom gradient. Show that this truncated adjoint gives the same gradient as backpropagation through iterations started at . Plot the cosine between the truncated and the exact gradient against for each . The gradient for needs no linear solve and is the Jacobian-free backpropagation of Wu Fung et al. (2022). Is it still a descent direction for ?
-
[code] Second derivatives in one forward pass. Adjoin with (but ), and write as a triple .
- Derive the product , and show that for an analytic , .
- Implement
Dual2with__add__,__mul__,sin, andexp, and evaluate on . Show that the result is , and check against the hand formula . - For with inputs seeded by a direction , what does the -part return? (Answer: , a number.) How many such passes give the vector by polarization, against one forward-over-reverse pass?
- Write as a matrix with and verify the product of (a) by matrix multiplication.