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 10810^8 parameters that outputs a single scalar loss ℓ\ell. Every training step needs the derivative of ℓ\ell with respect to all 10810^8 parameters. The direct finite-difference approach nudges one parameter at a time, reruns the network, and divides the change in ℓ\ell by the nudge. That requires 10810^8 runs per step. At 10 ms per run, computing a single gradient would take 10610^6 s, nearly twelve days, and the choice of step size would still introduce truncation and rounding errors. Backpropagation returns all 10810^8 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 10810^8 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 10810^8 inputs demand 10810^8 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 ℓ(x)=log⁡∑jexj\ell(\mathbf x)=\log\sum_j e^{x_j}, whose gradient is the softmax; the plane map f(x,y)=(x+sin⁡y, y+x2/2)\mathbf f(x,y)=(x+\sin y,\ y+x^2/2) from the previous section; and the polynomial expression y=(uv+u)2y=(uv+u)^2, which is small enough to trace completely by hand.

We use the following imports throughout this section.

import numpy as np
import torch

22.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 f′f' written down in advance. The trick is a remarkably small extension of the real numbers. We adjoin a new symbol ε\varepsilon that is nonzero, yet whose square vanishes:

ε2=0,ε≠0.(22.5.1)\varepsilon^2 = 0, \qquad \varepsilon\neq0. \tag{22.5.1}

With this single rule in place, we compute with expressions of the form a+bεa+b\varepsilon, called dual numbers, using the ordinary rules of algebra. Every differentiation rule in Section 22.1 works by discarding second-order terms, and setting ε2=0\varepsilon^2=0 builds that discard directly into the arithmetic.

Let us see what happens when we apply this rule to 3+ε3+\varepsilon. Squaring and cubing it yields

(3+ε)2=9+6ε+ε2=9+6ε,(3+ε)3=(9+6ε)(3+ε)=27+27ε.(3+\varepsilon)^2=9+6\varepsilon+\varepsilon^2=9+6\varepsilon, \qquad (3+\varepsilon)^3=(9+6\varepsilon)(3+\varepsilon)=27+27\varepsilon .

Look at the coefficients of ε\varepsilon: 66 and 2727 are the derivatives of x2x^2 and x3x^3 at x=3x=3. 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 ε2\varepsilon^2 term gives

(a+bε)(c+dε)=ac+(ad+bc) ε.(22.5.2)(a+b\varepsilon)(c+d\varepsilon) = ac + (ad+bc)\,\varepsilon. \tag{22.5.2}

If bb and dd are the derivatives of two quantities whose values are aa and cc, then ad+bcad+bc 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 ε=(0100)\varepsilon=\left(\begin{smallmatrix}0&1\\0&0\end{smallmatrix}\right). Then ε2=0\varepsilon^2=\mathbf 0, the dual number a+bεa+b\varepsilon becomes the 2×22\times2 matrix (ab0a)\left(\begin{smallmatrix}a&b\\0&a\end{smallmatrix}\right), and ordinary matrix multiplication (ab0a)(cd0c)=(acad+bc0ac)\left(\begin{smallmatrix}a&b\\0&a\end{smallmatrix}\right)\left(\begin{smallmatrix}c&d\\0&c\end{smallmatrix}\right)=\left(\begin{smallmatrix}ac&ad+bc\\0&ac\end{smallmatrix}\right) reproduces (22.5.2). Dual numbers are just as concrete as 2×22\times2 matrices, much as complex numbers are as concrete as rotations and scalings of the plane.

Real programs also call elementary functions such as sin⁡\sin, exp⁡\exp, and log⁡\log. For a function φ\varphi given by its Taylor series around aa, substituting a+bεa+b\varepsilon into the series kills every term from (bε)2(b\varepsilon)^2 onward, leaving only the linear approximation:

φ(a+bε)=φ(a)+φ′(a) b ε.\varphi(a+b\varepsilon)=\varphi(a)+\varphi'(a)\,b\,\varepsilon .

Thus ea+bε=ea+eab εe^{a+b\varepsilon}=e^a+e^a b\,\varepsilon and sin⁡(a+bε)=sin⁡a+(cos⁡a) b ε\sin(a+b\varepsilon)=\sin a+(\cos a)\,b\,\varepsilon are forced by the algebra itself. For a primitive that is merely differentiable at aa rather than analytic, we adopt the formula above as the definition of its action on dual numbers. In either case, the ε\varepsilon-part obeys the chain rule: the incoming derivative bb of the argument is multiplied by the local derivative φ′(a)\varphi'(a).

Proposition (dual numbers compute derivatives). Let ff be an expression built from constants, the identity, sums, products, and primitives φ\varphi (such as sin⁡\sin, exp⁡\exp, log⁡\log). Suppose each primitive is differentiable at the argument it receives when ff is evaluated at xx (for log⁡\log, a positive argument). Then evaluating the same expression on the dual number x+εx+\varepsilon gives

f(x+ε)=f(x)+f′(x) ε.(22.5.3)f(x + \varepsilon) = f(x) + f'(x)\,\varepsilon. \tag{22.5.3}

Proof. We proceed by structural induction on the expression. A constant cc is represented as c+0εc+0\varepsilon and the identity as x+1εx+1\varepsilon, so their ε\varepsilon-parts are their derivatives, 00 and 11. Now suppose two subexpressions satisfy g(x+ε)=g(x)+g′(x)εg(x+\varepsilon)=g(x)+g'(x)\varepsilon and h(x+ε)=h(x)+h′(x)εh(x+\varepsilon)=h(x)+h'(x)\varepsilon. Their sum has ε\varepsilon-part g′+h′=(g+h)′g'+h'=(g+h)'. By (22.5.2), their product has ε\varepsilon-part g′h+gh′=(gh)′g'h+gh'=(gh)'. Finally, applying a primitive φ\varphi to gg produces, by the rule above with a=g(x)a=g(x) and b=g′(x)b=g'(x), the ε\varepsilon-part φ′(g(x)) g′(x)=(φ∘g)′(x)\varphi'(g(x))\,g'(x)=(\varphi\circ g)'(x). Every way of combining subexpressions preserves the property, so the full expression satisfies (22.5.3). ■\blacksquare

To differentiate a program, we therefore run it on x+εx+\varepsilon and read off the ε\varepsilon-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 f′(x)f'(x) 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 x=0x=0 it executes the constant branch, and the dual-number run reports slope 00. This is the failure we met with ReLU(x)−ReLU(−x)\mathrm{ReLU}(x)-\mathrm{ReLU}(-x) in Section 22.1.6.3. The input's ε\varepsilon-part, here 11, is called the seed. No symbolic expression for f′f' 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 aa together with its derivative part bb, which we call the tangent and write as v˙\dot v for a quantity vv. 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 f(x)=sin⁡(x2)+exf(x)=\sin(x^2)+e^x at x=1.3x=1.3 by passing in 1.3+ε1.3+\varepsilon, and compare its ε\varepsilon-part against the hand-derived derivative f′(x)=2xcos⁡(x2)+exf'(x)=2x\cos(x^2)+e^x:

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 4.66224.6622 and the derivative 3.3601013.360101, 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 x=(1,−0.5,2)\mathbf x=(1,-0.5,2), whose gradient is the softmax ∂ℓ/∂xj=exj/∑kexk=pj\partial\ell/\partial x_j=e^{x_j}/\sum_k e^{x_k}=p_j. How many passes does forward mode need to obtain this full gradient? Seeding input jj with 11 and all other inputs with 00 yields the single partial derivative ∂ℓ/∂xj\partial\ell/\partial x_j in the output's ε\varepsilon-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 2.3715392.371539 and recovers just one softmax entry: 0.2537160.253716, 0.0566120.056612, or 0.6896720.689672. More generally, a gradient over nn inputs requires nn passes. For the 10810^8-parameter network from the opening, that puts us right back at 10810^8 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 f:Rn→Rm\mathbf f:\mathbb R^n\to\mathbb R^m with m×nm\times n Jacobian J\mathbf J. What does a single forward pass compute? Suppose we seed the inputs with an arbitrary direction v\mathbf v, setting input jj to xj+vjεx_j+v_j\varepsilon. Applying our proposition to the one-dimensional slice t↦fi(x+tv)t\mapsto f_i(\mathbf x+t\mathbf v) shows that output ii emerges as fi(x)+(∇fi⋅v) εf_i(\mathbf x)+(\nabla f_i\cdot\mathbf v)\,\varepsilon. Collecting the ε\varepsilon-parts across all mm outputs therefore produces the vector Jv\mathbf J\mathbf v, known as the Jacobian--vector product (JVP). When v\mathbf v is the jj-th standard basis vector ej\mathbf e_j, the JVP picks out column jj of J\mathbf J. One forward pass carries one input direction through the entire map.

Let us verify this on the plane map f(x,y)=(x+sin⁡y, y+x2/2)\mathbf f(x,y)=(x+\sin y,\ y+x^2/2) at (0.5,0.5)(0.5,0.5). Its Jacobian, whose row ii holds the partial derivatives of output ii, is

J=(1cos⁡yx1)=(10.8775830.51).\mathbf J=\begin{pmatrix}1&\cos y\\ x&1\end{pmatrix} =\begin{pmatrix}1&0.877583\\0.5&1\end{pmatrix}.

Two forward passes, seeded first with e1\mathbf e_1 and then with e2\mathbf e_2, 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 xx the vector tangent (1,0)(1,0) and yy the vector tangent (0,1)(0,1), every operation propagates both input directions simultaneously, and the tangent of output ii becomes row ii of J\mathbf J. 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 nn, so that single pass performs roughly nn 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 10810^8 inputs, forward mode demands either 10810^8 scalar passes or one pass carrying tangents of length 10810^8. Either way, its total work scales with nn 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 nn, we must multiply the chain of derivatives in the opposite order. In Section 22.4, we saw that the Jacobian of a KK-step program f=fK∘⋯∘f1\mathbf f=\mathbf f_K\circ\cdots\circ\mathbf f_1 is the product of the step Jacobians,

J=JK JK−1⋯J1,(22.5.4)\mathbf J = \mathbf J_K\,\mathbf J_{K-1}\cdots\mathbf J_1, \tag{22.5.4}

and that the parenthesization of this product governs its cost: for three layers of width 10001000 multiplied by a row vector on the left, associating from the left takes 3×1063\times10^6 multiplications, whereas associating from the right takes 2×1092\times10^9 (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 v\mathbf v in from the right; reverse mode multiplies a row vector u⊤\mathbf u^\top in from the left:

Jv=JK(⋯(J2(J1v))),u⊤J=(((u⊤JK)JK−1)⋯ )J1.(22.5.5)\mathbf J\mathbf v=\mathbf J_K\Bigl(\cdots\bigl(\mathbf J_2(\mathbf J_1\mathbf v)\bigr)\Bigr), \qquad \mathbf u^\top\mathbf J=\Bigl(\bigl((\mathbf u^\top\mathbf J_K)\mathbf J_{K-1}\bigr)\cdots\Bigr)\mathbf J_1. \tag{22.5.5}

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 Jv\mathbf J\mathbf v. On the right, an output direction travels backward to produce the vector--Jacobian product (VJP) u⊤J\mathbf u^\top\mathbf J, a linear combination of the rows of J\mathbf J weighted by u\mathbf u. Setting u=ei\mathbf u=\mathbf e_i extracts row ii of J\mathbf J.

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 +,−,×,÷+,-,\times,\div, 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 1×n1\times n Jacobian, a single row, so one reverse sweep seeded with 11 returns the entire gradient at once. Figure 22.5.1 illustrates this rule in terms of matrix shapes.

Figure 22.5.1:

The shape of the Jacobian decides the cheaper mode. A scalar loss has a 1×n1\times n Jacobian: one row, one VJP, one backward pass. A map with one input has an m×1m\times 1 Jacobian: one column, one JVP, one forward pass. A full m×nm\times n Jacobian costs min⁡(m,n)\min(m,n) 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 J\mathbf J: 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 xx to output yy, the tangent v˙\dot v of an intermediate variable vv measures how fast vv changes when the input moves in the direction x˙\dot x. By contrast, the adjoint vˉ\bar v introduced in Section 22.3 is the total derivative of the final output yy with respect to vv, summed over all paths from vv to yy. A tangent depends only on the steps before vv, whereas an adjoint depends on the steps after vv. In y=v2y=v^2 with v=3xv=3x, for example, we have v˙=3x˙\dot v=3\dot x coming from below and vˉ=2v\bar v=2v 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).

Figure 22.5.2:

Forward and reverse mode on a chain x→a→b→ℓx\to a\to b\to\ell. Both evaluate the chain from left to right (gray). Forward mode (top) carries the tangents v˙\dot v along with the values, one input direction per sweep. Reverse mode (bottom) runs the chain first and then carries the adjoints vˉ\bar v, the total derivatives of ℓ\ell with respect to vv, back from the seed ℓˉ=1\bar\ell=1, 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 gg, that closure adds the node's contribution to each parent's adjoint: for c=a+bc=a+b it adds gg to both parents, while for c=abc=ab it adds b gb\,g to aˉ\bar a and a ga\,g to bˉ\bar b. The function backprop topologically sorts the graph so that every node appears after its parents, seeds the output adjoint with 11, 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, y=(uv+u)2y=(uv+u)^2. Before running the code, let us trace the entire backward sweep by hand at u=2u=2, v=−3v=-3. The forward pass records three elementary operations: t=uv=−6t=uv=-6, then r=t+u=−4r=t+u=-4, and finally y=r⋅r=16y=r\cdot r=16. The backward sweep visits nodes in a reverse topological order such as y,r,t,u,vy,r,t,u,v, ensuring that every node is processed only after all nodes that depend on it (backprop happens to visit vv before uu, 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:

nodeoutgoing edges and their contributionsadjoint
yynone: the seedyˉ=1\bar y=1
rrboth arguments of y=r⋅ry=r\cdot r: yˉ r+yˉ r\bar y\,r+\bar y\,rrˉ=−8\bar r=-8
ttr=t+ur=t+u: rˉ⋅1\bar r\cdot1tˉ=−8\bar t=-8
uur=t+ur=t+u and t=uvt=uv: rˉ⋅1+tˉ⋅v\bar r\cdot1+\bar t\cdot vuˉ=−8+24=16\bar u=-8+24=16
vvt=uvt=uv: tˉ⋅u\bar t\cdot uvˉ=−16\bar v=-16

Direct differentiation of y=(uv+u)2y=(uv+u)^2 confirms both answers: ∂y/∂u=2(uv+u)(v+1)=2(−4)(−2)=16\partial y/\partial u=2(uv+u)(v+1)=2(-4)(-2)=16 and ∂y/∂v=2(uv+u) u=2(−4)(2)=−16\partial y/\partial v=2(uv+u)\,u=2(-4)(2)=-16. Notice how crucial accumulation is at two places in the graph: rr feeds both arguments of the final product, and uu feeds both tt and rr (Figure 22.5.3). Overwriting instead of adding would leave rˉ=−4\bar r=-4, and even with rˉ\bar r fixed it would leave uˉ\bar u as either −8-8 or 2424, 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 +=.

Figure 22.5.3:

The tape of y=(uv+u)2y=(uv+u)^2 at u=2u=2, v=−3v=-3. Each box shows the forward value of its node; the orange label shows its adjoint, the derivative of yy with respect to that node. The graph is a diamond, not a chain: uu feeds both t=uvt=uv and r=t+ur=t+u, and rr feeds both arguments of y=r⋅ry=r\cdot r, so the adjoints of rr and uu 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 uˉ\bar u and vˉ\bar v 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 Xˉ=YˉW⊤\bar{\mathbf X}=\bar{\mathbf Y}\mathbf W^\top and Wˉ=X⊤Yˉ\bar{\mathbf W}=\mathbf X^\top\bar{\mathbf Y} (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 log⁡xi\log x_i 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 log⁡\log still runs on the padding, here x2=0x_2=0. The forward pass is unharmed: the −∞-\infty is discarded and the loss is log⁡2≈0.6931\log 2\approx0.6931. On the backward sweep, however, where sends the adjoint 00 into the discarded branch, and the VJP of log⁡\log multiplies it by the local derivative 1/0=∞1/0=\infty. In floating-point arithmetic 0⋅∞0\cdot\infty is not 00 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 (0.5,NaN)(0.5, \textrm{NaN}), although the loss does not depend on the padded entry at all and the true derivative there is 00. A single NaN is not a local blemish: every parameter upstream of x2x_2 receives it. The second line shows the standard remedy, the double where. An inner where replaces the masked entries by a harmless value, here 11, before the primitive sees them, so that no infinite local derivative is ever formed and the gradient is (0.5,0)(0.5, 0). Clamping the argument away from the edge of the domain serves the same purpose. The same trap awaits x\sqrt{x} at 00, and with it a norm computed as ∑ixi2\sqrt{\sum_i x_i^2} at x=0\mathbf x=\mathbf 0.

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 hk=Wkhk−1\mathbf h_k=\mathbf W_k\mathbf h_{k-1} with weight matrix Wk\mathbf W_k of shape dk×dk−1d_k\times d_{k-1}, that rule reads

∇Wkℓ=hˉk hk−1⊤,(22.5.6)\nabla_{\mathbf W_k}\ell=\bar{\mathbf h}_k\,\mathbf h_{k-1}^\top, \tag{22.5.6}

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 hˉk hk−1⊤\bar{\mathbf h}_k\,\mathbf h_{k-1}^\top takes dkdk−1d_kd_{k-1} multiplications, the same count as the forward matrix--vector product Wkhk−1\mathbf W_k\mathbf h_{k-1}. Passing the adjoint down to the previous layer, hˉk−1⊤=hˉk⊤Wk\bar{\mathbf h}_{k-1}^\top=\bar{\mathbf h}_k^\top\mathbf W_k, takes another dkdk−1d_kd_{k-1} 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 dkdk−1d_kd_{k-1} 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 f(x)=(∑jxj2)2f(\mathbf x)=(\sum_j x_j^2)^2 on n=200n=200 inputs xj=0.01 jx_j=0.01\,j for j=1,…,200j=1,\ldots,200. We choose a polynomial built solely from ++ and ×\times so that Var can record it without adding exp and log closures (which would mirror the methods of Dual). Its gradient is ∇f=4(∑jxj2)x\nabla f=4\bigl(\sum_jx_j^2\bigr)\mathbf x, and one plain evaluation runs 2n+1=4012n+1=401 primitive operations: nn squares, nn additions, and one final square. Forward mode will clearly need 200200 passes of 401401 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 80,200=n(2n+1)80{,}200=n(2n+1) operations, whereas reverse mode executed only 802=2(2n+1)802=2(2n+1): 401401 recorded during the forward pass and 401401 backward closures during the sweep. The ratio is 100=n/2100=n/2, and the two gradients agree to every printed digit. For these engines, pass counts differ by a factor of nn and operation counts by n/2n/2; at n=108n=10^8, 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 402402 on the backward sweep against 201201 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 12041204 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 401401 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 TT recorded steps keeps TT 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 ss steps. During the forward pass, we save only every ss-th value, the T/sT/s checkpoints, and discard everything in between. When the backward sweep arrives at a segment, it recomputes that segment's ss 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 T/sT/s checkpoints plus one active segment of length ss. Choosing ss to balance these two terms minimizes peak memory:

M(s)=Ts+s,min⁡sM(s)=M(T)=2T.(22.5.7)M(s)=\frac{T}{s}+s, \qquad \min_s M(s)=M(\sqrt T)=2\sqrt T. \tag{22.5.7}

The minimum follows either from setting M′(s)=1−T/s2=0M'(s)=1-T/s^2=0 or directly from the AM--GM inequality T/s+s≥2TT/s+s\ge2\sqrt T. 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 T=400T=400, segment lengths s=1,5,10,20,100,400s=1,5,10,20,100,400 yield peak memory M=401,85,50,40,104,401M=401,85,50,40,104,401, with the minimum at s=20=400s=20=\sqrt{400}. At T=104T=10^4, segments of length s=100s=100 store just 200200 values instead of 10,00010{,}000 (Chen et al., 2016). Figure 22.5.4 illustrates this schedule.

Figure 22.5.4:

Gradient checkpointing on a tape of TT steps. Plain reverse mode (top) keeps all TT values until the backward sweep uses them. Checkpointing (bottom) keeps every ss-th value; when the backward sweep reaches a segment, the segment is recomputed from its checkpoint and then swept. The memory is T/s+sT/s+s, which is 2T2\sqrt T at s=Ts=\sqrt T, 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 O(log⁡T)O(\log T) at the cost of O(Tlog⁡T)O(T\log T) recomputation.

22.5.3 Composing Jacobian Products#

Automatic differentiation offers both linear operators our toy engines just built: the forward-mode JVP Jv\mathbf J\mathbf v and the reverse-mode VJP u⊤J\mathbf u^\top\mathbf J. 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 (0.5,0.5)(0.5,0.5) with v=u=(1,2)\mathbf v=\mathbf u=(1,2). Using the Jacobian we computed earlier with Dual, we expect Jv=(1+2⋅0.8776, 0.5+2)=(2.7552, 2.5)\mathbf J\mathbf v=(1+2\cdot0.8776,\ 0.5+2)=(2.7552,\ 2.5) and u⊤J=(1+2⋅0.5, 0.8776+2)=(2, 2.8776)\mathbf u^\top\mathbf J=(1+2\cdot0.5,\ 0.8776+2)=(2,\ 2.8776), 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 m×nm\times n Jacobian takes min⁡(m,n)\min(m,n) sweeps in the cheaper mode plus mnmn numbers of storage. Materializing the full matrix is the right choice when nn is small, as in this 2×22\times2 example, or when an algorithm needs its determinant, as in normalizing flows that transform probability densities by ∣det⁡J∣|\det\mathbf J|.

22.5.3.2 Hessian--Vector Products#

For a model with n=106n=10^6 parameters, the Hessian has 101210^{12} 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 Hd=−∇ℓ\mathbf H\mathbf d=-\nabla\ell for the update step d\mathbf d, and Newton--CG (or truncated Newton) solves that linear system by conjugate gradients, an iterative solver that accesses H\mathbf H solely through matrix--vector products Hv\mathbf H\mathbf v (Nocedal and Wright, 2006; Martens, 2010). Can we compute Hv\mathbf H\mathbf v without ever forming H\mathbf H?

We can, by composing reverse mode and forward mode. Because the Hessian is the Jacobian of the gradient map ∇ℓ\nabla\ell, the product Hv\mathbf H\mathbf v is simply a JVP of the gradient, measuring how fast the gradient changes along v\mathbf v:

Hv=J∇ℓ v=ddt∣t=0∇ℓ(x+tv).(22.5.8)\mathbf H\mathbf v = \mathbf J_{\nabla \ell}\,\mathbf v = \left.\frac{d}{dt}\right|_{t=0}\nabla \ell(\mathbf x + t\mathbf v). \tag{22.5.8}

A reverse sweep evaluates ∇ℓ\nabla\ell, and a forward-mode pass through that gradient computation, seeded with tangent v\mathbf v, differentiates it along v\mathbf v. This composition is called forward over reverse (Pearlmutter, 1994). Regardless of the dimension nn, 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 p\mathbf p, so its Hessian is the softmax Jacobian (Section 22.4, equivalently the covariance matrix of a one-hot vector eJ\mathbf e_J with JJ drawn from p\mathbf p). Therefore,

H=diag⁡(p)−pp⊤,Hv=p⊙v−p (p⊤v),(22.5.9)\mathbf H=\operatorname{diag}(\mathbf p)-\mathbf p\mathbf p^\top, \qquad \mathbf H\mathbf v=\mathbf p\odot\mathbf v-\mathbf p\,(\mathbf p^\top\mathbf v), \tag{22.5.9}

where ⊙\odot denotes entrywise multiplication. Evaluating the right-hand side requires just 3n3n multiplications and never builds an n×nn\times n matrix. At x=(1,−0.5,2)\mathbf x=(1,-0.5,2) and v=(1,0.5,−1)\mathbf v=(1,0.5,-1), we have p=(0.2537,0.0566,0.6897)\mathbf p=(0.2537,0.0566,0.6897) and p⊤v=−0.4077\mathbf p^\top\mathbf v=-0.4077, which gives

Hv=(0.3571, 0.0514, −0.4085).\mathbf H\mathbf v=(0.3571,\ 0.0514,\ -0.4085).

Notice that this is a genuine check, unlike testing on a quadratic 12x⊤Ax\tfrac12\mathbf x^\top\mathbf A\mathbf x. For a quadratic, the gradient at v\mathbf v happens to equal Hv\mathbf H\mathbf v, so a buggy implementation could still pass; for log-sum-exp, H\mathbf H varies with x\mathbf x, and the gradient at v\mathbf v, softmax⁡(v)=(0.574,0.348,0.078)\operatorname{softmax}(\mathbf v)=(0.574,0.348,0.078), is nowhere near Hv\mathbf H\mathbf v.

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 3×33\times3 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, g(x,θ)=x2−θ=0g(x,\theta)=x^2-\theta=0, whose solution is x⋆=θx^\star=\sqrt\theta. Instead of differentiating the closed form, differentiate the identity x⋆(θ)2−θ≡0x^\star(\theta)^2-\theta\equiv0 directly with respect to θ\theta. That gives 2x⋆ dx⋆/dθ−1=02x^\star\,dx^\star/d\theta-1=0, and solving for the derivative yields

dx⋆dθ=12x⋆=12θ,\frac{dx^\star}{d\theta}=\frac{1}{2x^\star}=\frac{1}{2\sqrt\theta},

which is indeed the derivative of θ\sqrt\theta (equal to 0.250.25 at θ=4\theta=4). Crucially, we never used an explicit formula for x⋆x^\star, only the equation g(x,θ)=0g(x,\theta)=0 and the value of the solution itself.

The general result is the implicit function theorem (Rudin, 1976), which we state without proof. Let g(x,θ)\mathbf g(\mathbf x,\boldsymbol\theta) map Rd×Rp\mathbb R^d\times\mathbb R^p to Rd\mathbb R^d, suppose g\mathbf g is continuously differentiable near a solution (x⋆,θ)(\mathbf x^\star,\boldsymbol\theta) of g=0\mathbf g=\mathbf 0, and suppose the Jacobian ∂g/∂x\partial\mathbf g/\partial\mathbf x is invertible there. Then, in a neighborhood of θ\boldsymbol\theta, the solution is a differentiable function x⋆(θ)\mathbf x^\star(\boldsymbol\theta). Applying the chain rule to the identity g(x⋆(θ),θ)≡0\mathbf g(\mathbf x^\star(\boldsymbol\theta),\boldsymbol\theta)\equiv\mathbf 0 gives ∂g∂x∂x⋆∂θ+∂g∂θ=0\frac{\partial\mathbf g}{\partial\mathbf x}\frac{\partial\mathbf x^\star}{\partial\boldsymbol\theta} +\frac{\partial\mathbf g}{\partial\boldsymbol\theta}=\mathbf 0, and therefore

∂x⋆∂θ=−(∂g∂x) ⁣−1∂g∂θ.(22.5.10)\frac{\partial\mathbf x^\star}{\partial\boldsymbol\theta} = -\Bigl(\frac{\partial\mathbf g}{\partial\mathbf x}\Bigr)^{\!-1} \frac{\partial\mathbf g}{\partial\boldsymbol\theta}. \tag{22.5.10}

Both Jacobians on the right are evaluated solely at the solution (x⋆,θ)(\mathbf x^\star,\boldsymbol\theta). Computing the full derivative matrix costs one linear solve with ∂g/∂x\partial\mathbf g/\partial\mathbf x 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: u⊤∂x⋆/∂θ=−a⊤∂g/∂θ\mathbf u^\top\partial\mathbf x^\star/\partial\boldsymbol\theta =-\mathbf a^\top\partial\mathbf g/\partial\boldsymbol\theta, where the adjoint vector a\mathbf a solves (∂g/∂x)⊤a=u(\partial\mathbf g/\partial\mathbf x)^\top\mathbf a=\mathbf u.

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 z⋆=f(z⋆,θ)\mathbf z^\star=\mathbf f(\mathbf z^\star,\boldsymbol\theta) 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 2×22\times2 system, g1=x12+θx2−2=0g_1=x_1^2+\theta x_2-2=0 and g2=x1x2+θ−1=0g_2=x_1x_2+\theta-1=0, 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 g\mathbf g and the solution x⋆\mathbf x^\star, 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, ∂g/∂x\partial\mathbf g/\partial\mathbf x must be invertible at the solution. In our scalar example x2=θx^2=\theta, at θ=0\theta=0 we have ∂g/∂x=2x⋆=0\partial g/\partial x=2x^\star=0, so the formula divides by zero, reflecting the vertical tangent of θ\sqrt\theta 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 x2=4x^2=4 starting from x=1x=1 and stop early after k=1,2,3k=1,2,3 steps, comparing the implicit formula 1/(2x~k)1/(2\tilde x_k) evaluated at the unconverged iterate x~k\tilde x_k with the derivative of the kk-step unrolled solver itself (estimated by a central difference in θ\theta).

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 2.52.5, 2.052.05, and 2.000612.00061. Against the true derivative 0.250.25, the implicit formula returns 0.20000.2000, 0.24390.2439, and 0.24990.2499, while the unrolled derivative gives 0.50000.5000, 0.29000.2900, and 0.25090.2509. 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 JK⋯J1\mathbf J_K\cdots\mathbf J_1 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 10−2010^{-20} 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 (∑jxj2)2(\sum_j x_j^2)^2 with n=200n=200 inputs, reverse mode took 802802 operations against 80,20080{,}200 for forward mode. The tape's memory grows linearly with the computation length TT, and gradient checkpointing lowers peak memory to 2T2\sqrt T 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#

  1. [code] Dual and complex steps. Take f(x,y)=(x+sin⁡y, y+x2/2)\mathbf f(x,y)=(x+\sin y,\ y+x^2/2) at x0=(0.5,0.5)\mathbf x_0=(0.5,0.5) and the second column Je2=(cos⁡0.5, 1)\mathbf J\mathbf e_2=(\cos0.5,\ 1) of its Jacobian. The central difference (f(x0+te2)−f(x0−te2))/(2t)(\mathbf f(\mathbf x_0+t\mathbf e_2)-\mathbf f(\mathbf x_0-t\mathbf e_2))/(2t) has an error of order t2t^2 from truncation plus an error of order u/tu/t from rounding, where u≈10−16u\approx10^{-16} is the float64 unit roundoff.

    1. Predict the best step and the smallest error, then check the prediction for t=10−1,10−2,…,10−12t=10^{-1},10^{-2},\ldots,10^{-12} (you should find about 2×10−112\times10^{-11} near t=10−5t=10^{-5}). Compare with one pass of Dual seeded with e2\mathbf e_2. Why does no step size enter the dual computation?
    2. Repeat (a) for the first column Je1\mathbf J\mathbf e_1, and explain why the central difference is exact there for every tt, up to rounding. (Hint: f\mathbf f is a polynomial of degree two in xx.)
    3. Replacing ε\varepsilon by the imaginary unit ii gives the complex-step estimate Im⁡f(x0+ite2)/t\operatorname{Im}\mathbf f(\mathbf x_0+it\mathbf e_2)/t (Squire and Trapp, 1998), valid for an f\mathbf f that extends analytically to complex arguments, as this one does. Expand f(x0+ite2)\mathbf f(\mathbf x_0+it\mathbf e_2) to third order in tt and show that the error of the estimate is O(t2)O(t^2). Why does the estimate subtract no nearly equal numbers?
    4. Evaluate the complex-step estimate with NumPy's complex arithmetic for t=10−1,10−2,…,10−20t=10^{-1},10^{-2},\ldots,10^{-20} and compare its errors with those of (a). Which difference between ε2=0\varepsilon^2=0 and i2=−1i^2=-1 causes the O(t2)O(t^2) error of the complex step?
  2. [code] Hyperparameter gradient. Ridge regression with one penalty λj>0\lambda_j>0 per feature fits

w⋆(λ)=argmin⁡w ∥Xw−y∥2+∑j=1dλjwj2\mathbf w^\star(\boldsymbol\lambda)=\operatorname*{argmin}_{\mathbf w}\ \|\mathbf X\mathbf w-\mathbf y\|^2+\sum_{j=1}^d\lambda_jw_j^2

on training data (X,y)(\mathbf X,\mathbf y), and its validation loss on data (Xv,yv)(\mathbf X_{\text{v}},\mathbf y_{\text{v}}) is V(λ)=∥Xvw⋆(λ)−yv∥2V(\boldsymbol\lambda)=\|\mathbf X_{\text{v}}\mathbf w^\star(\boldsymbol\lambda)-\mathbf y_{\text{v}}\|^2.

  1. Show that w⋆\mathbf w^\star solves g(w,λ)=(X⊤X+diag⁡(λ)) w−X⊤y=0\mathbf g(\mathbf w,\boldsymbol\lambda)=(\mathbf X^\top\mathbf X+\operatorname{diag}(\boldsymbol\lambda))\,\mathbf w-\mathbf X^\top\mathbf y=\mathbf 0, and use (22.5.10) to derive ∂w⋆/∂λ\partial\mathbf w^\star/\partial\boldsymbol\lambda.
  2. Show that ∇λV=−a⊙w⋆\nabla_{\boldsymbol\lambda}V=-\mathbf a\odot\mathbf w^\star, where a\mathbf a solves one linear system with the matrix X⊤X+diag⁡(λ)\mathbf X^\top\mathbf X+\operatorname{diag}(\boldsymbol\lambda), and give its right-hand side. How many linear solves does the forward route through ∂w⋆/∂λ\partial\mathbf w^\star/\partial\boldsymbol\lambda need for dd penalties, and how many does this adjoint route need?
  3. Implement VV and the adjoint gradient in NumPy for random data with 5050 training examples, 5050 validation examples, and d=10d=10 features. Check the gradient against central differences of VV.

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.

  1. [code] Hessian--vector product. ● The function f(x)=(∑jxj2)2f(\mathbf x)=\bigl(\sum_j x_j^2\bigr)^2 of Section 22.5.2.4, evaluated at the inputs xs0 with n=200n=200, is built from addition and multiplication alone, so both Dual and Var can evaluate it.

    1. Derive ∇f\nabla f and the Hessian H\mathbf H of ff, and write Hv\mathbf H\mathbf v in a form that never builds H\mathbf H.
    2. Draw a random direction v\mathbf v, wrap each input xjx_j as Var(Dual(x_j, v_j)), and run backprop. Show that the value parts of the resulting adjoints form ∇f\nabla f and that their ε\varepsilon-parts form Hv\mathbf H\mathbf v, and compare both with (a) and with the Hessian--vector product of Section 22.5.3.2 applied to the same ff. 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)?
    3. Nest the tape in itself instead. Wrap each input as Var(Var(x_j)) and run backprop; the adjoints are now Var objects. Form ∑j(∇f)jvj\sum_j(\nabla f)_jv_j from them and run backprop on it to obtain Hv\mathbf H\mathbf v by reverse over reverse. Count the Var objects that each method creates, for example with a counter in Var.__init__, and compare both counts with that of one plain gradient. Which method records the backward pass, and what does that cost in memory?
  2. [code] Checkpointing on the tape. ● Let xk=xk−1−0.01 xk−12x_k=x_{k-1}-0.01\,x_{k-1}^2 for k=1,…,Tk=1,\ldots,T with T=400T=400 and x0=1x_0=1, and differentiate xTx_T with respect to x0x_0. Var has no subtraction, so record each step as x + (-0.01) * x * x.

    1. Record the chain on the tape with plain backprop and count the nodes that the tape holds when the backward sweep starts.
    2. backprop seeds the output adjoint with 11. Generalize it to accept any seed. Show that recording a segment xi↦xjx_i\mapsto x_j from a fresh leaf for xix_i and running the generalized backprop from xjx_j with the seed ∂xT/∂xj\partial x_T/\partial x_j returns ∂xT/∂xi\partial x_T/\partial x_i in the adjoint of the leaf.
    3. Implement the schedule of Figure 22.5.4 with segments of ss steps: a forward pass in plain floats that stores x0,xs,x2s,…x_0,x_s,x_{2s},\ldots, 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).
    4. For s∈{1,5,10,20,100,400}s\in\{1,5,10,20,100,400\}, report the number of stored checkpoints, the largest tape in steps, and the number of evaluations of the step x↦x−0.01x2x\mapsto x-0.01x^2, the first forward pass included. Confirm the memory T/s+sT/s+s of (22.5.7), that is 401,85,50,40,104,401401,85,50,40,104,401, and its minimizer s=T=20s=\sqrt T=20. Repeat the sweep for T=100T=100 and T=1600T=1600 over the divisors s≤800s\le800 of TT (a single segment of 16001600 steps exceeds Python's default recursion limit in backprop). How does the minimizing ss scale with TT, and how many step evaluations does the best schedule need?
  3. [extended] Equilibrium layer. ●● A deep equilibrium layer (Bai et al., 2019) outputs the fixed point

z⋆=tanh⁡(Wz⋆+c),(22.5.11)\mathbf z^\star=\tanh(\mathbf W\mathbf z^\star+\mathbf c), \tag{22.5.11}

where c\mathbf c depends on the layer's input. Let the loss be ℓ=12∥z⋆−y∥2\ell=\tfrac12\|\mathbf z^\star-\mathbf y\|^2, and write D=diag⁡(1−(z1⋆)2,…,1−(zd⋆)2)\mathbf D=\operatorname{diag}\bigl(1-(z^\star_1)^2,\ldots,1-(z^\star_d)^2\bigr) for the derivative of tanh⁡\tanh at the fixed point.

  1. Show that the map z↦tanh⁡(Wz+c)\mathbf z\mapsto\tanh(\mathbf W\mathbf z+\mathbf c) is a contraction when ∥W∥2<1\|\mathbf W\|_2\lt 1, so that the fixed point exists and is unique, and that I−DW\mathbf I-\mathbf D\mathbf W is then invertible. Use (22.5.10) to derive ∇Wℓ\nabla_{\mathbf W}\ell, and show that it equals (Da)(z⋆)⊤(\mathbf D\mathbf a)(\mathbf z^\star)^\top for the adjoint a\mathbf a that solves (I−DW)⊤a=z⋆−y(\mathbf I-\mathbf D\mathbf W)^\top\mathbf a=\mathbf z^\star-\mathbf y.

  2. Take d=20d=20, a standard normal G∈Rd×d\mathbf G\in\mathbb R^{d\times d}, S=G+G⊤\mathbf S=\mathbf G+\mathbf G^\top, and W=ρ S/∥S∥2\mathbf W=\rho\,\mathbf S/\|\mathbf S\|_2 for ρ∈{0.5,0.9,0.99}\rho\in\{0.5,0.9,0.99\}, and draw the entries of c\mathbf c and y\mathbf y independently from N(0,0.12)\mathcal N(0,0.1^2). In NumPy, compute z⋆\mathbf z^\star by fixed-point iteration and the gradient of (a) with one linear solve. Check a few of its entries against central differences of ℓ\ell.

  3. Unrolled differentiation runs KK iterations from z0=0\mathbf z_0=\mathbf 0 and backpropagates through all of them. Implement this backward sweep by hand, one VJP per iteration. Plot against KK the error of the unrolled gradient relative to the gradient of (b), together with the forward error ∥zK−z⋆∥\|\mathbf z_K-\mathbf z^\star\|. Compare the decay rate of both errors with the spectral radius of DW\mathbf D\mathbf W. How does the ratio of the two errors behave as KK grows, and why? How does the memory of each gradient scale with KK?

  4. Replace the linear solve by mm steps of the iteration a←(z⋆−y)+(DW)⊤a\mathbf a\leftarrow(\mathbf z^\star-\mathbf y)+(\mathbf D\mathbf W)^\top\mathbf a from a=0\mathbf a=\mathbf 0, 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 mm iterations started at z⋆\mathbf z^\star. Plot the cosine between the truncated and the exact gradient against mm for each ρ\rho. The gradient for m=1m=1 needs no linear solve and is the Jacobian-free backpropagation of Wu Fung et al. (2022). Is it still a descent direction for ℓ\ell?

  5. [code] Second derivatives in one forward pass. Adjoin ε\varepsilon with ε3=0\varepsilon^3=0 (but ε2≠0\varepsilon^2\neq0), and write a+bε+cε2a+b\varepsilon+c\varepsilon^2 as a triple (a,b,c)(a,b,c).

    1. Derive the product (a,b,c)(a′,b′,c′)=(aa′, ab′+ba′, ac′+bb′+ca′)(a,b,c)(a',b',c')=(aa',\ ab'+ba',\ ac'+bb'+ca'), and show that for an analytic φ\varphi, φ(a+bε+cε2)=φ(a)+φ′(a) b ε+(φ′(a) c+12φ′′(a) b2)ε2\varphi(a+b\varepsilon+c\varepsilon^2)=\varphi(a)+\varphi'(a)\,b\,\varepsilon+\bigl(\varphi'(a)\,c+\tfrac12\varphi''(a)\,b^2\bigr)\varepsilon^2.
    2. Implement Dual2 with __add__, __mul__, sin, and exp, and evaluate f(x)=sin⁡(x2)+exf(x)=\sin(x^2)+e^x on (1.3,1,0)(1.3,1,0). Show that the result is (f(1.3), f′(1.3), 12f′′(1.3))(f(1.3),\ f'(1.3),\ \tfrac12f''(1.3)), and check f′′(1.3)≈−3.2806f''(1.3)\approx-3.2806 against the hand formula f′′(x)=2cos⁡x2−4x2sin⁡x2+exf''(x)=2\cos x^2-4x^2\sin x^2+e^x.
    3. For ℓ:Rn→R\ell:\mathbb R^n\to\mathbb R with inputs seeded by a direction v\mathbf v, what does the ε2\varepsilon^2-part return? (Answer: 12v⊤Hv\tfrac12\mathbf v^\top\mathbf H\mathbf v, a number.) How many such passes give the vector Hv\mathbf H\mathbf v by polarization, against one forward-over-reverse pass?
    4. Write ε\varepsilon as a 3×33\times3 matrix with ε3=0\varepsilon^3=\mathbf 0 and verify the product of (a) by matrix multiplication.

Discussions