import math
from collections import namedtuple
# Line k of the trace: a pattern for printing the operation, the value
# v_k, and one pair (i, d_ki) for each argument v_i.
Line = namedtuple("Line", "op value partials")
class Tape:
"""An evaluation trace, recorded one line at a time."""
recording = None # the tape that operations on variables write to
def __init__(self):
self.lines = [None] # line k is self.lines[k]; entry 0 is unused
def __enter__(self):
if Tape.recording is not None:
raise RuntimeError("another tape is recording")
Tape.recording = self
return self
def __exit__(self, *exc_info):
Tape.recording = None
def input(self, value, name="input"):
"""Record an input line holding value, and return its variable."""
return record(name, float(value))
class Var:
"""Variable v_k of the trace being recorded."""
def __init__(self, k, value):
self.k = k # its line number on the tape
self.value = value # the number v_k
def __pow__(self, c):
"""v ** c for a constant exponent c."""
t = self.value
return record(f"{{}} ** {c:g}", t**c, (self.k, c * t ** (c - 1)))
def __neg__(self):
return -1.0 * self
def record(op, value, *partials):
"""Append a line to the recording tape, and return its variable."""
tape = Tape.recording
if tape is None:
raise RuntimeError("no tape is recording; use `with Tape():`")
tape.lines.append(Line(op, value, partials))
return Var(len(tape.lines) - 1, value)
def binary(symbol, g, d1, d2):
"""Two methods of Var for g(s, t), written s symbol t, partials d1, d2.
Python calls the first for u symbol w with u a Var, and the second
for c symbol u with c a number.
"""
def var_first(u, w):
if isinstance(w, Var):
s, t = u.value, w.value
return record(f"{{}} {symbol} {{}}", g(s, t),
(u.k, d1(s, t)), (w.k, d2(s, t)))
s = u.value
return record(f"{{}} {symbol} {w:g}", g(s, w), (u.k, d1(s, w)))
def number_first(u, c):
t = u.value
return record(f"{c:g} {symbol} {{}}", g(c, t), (u.k, d2(c, t)))
return var_first, number_first
Var.__add__, Var.__radd__ = binary(
"+", lambda s, t: s + t, lambda s, t: 1.0, lambda s, t: 1.0)
Var.__sub__, Var.__rsub__ = binary(
"-", lambda s, t: s - t, lambda s, t: 1.0, lambda s, t: -1.0)
Var.__mul__, Var.__rmul__ = binary(
"*", lambda s, t: s * t, lambda s, t: t, lambda s, t: s)
Var.__truediv__, Var.__rtruediv__ = binary(
"/", lambda s, t: s / t, lambda s, t: 1 / t, lambda s, t: -s / t**2)
def elementary(name, g, dg):
"""The operation t -> g(t), with derivative dg, on a variable."""
def apply(u):
return record(f"{name} {{}}", g(u.value), (u.k, dg(u.value)))
return apply
exp = elementary("exp", math.exp, math.exp)
log = elementary("log", math.log, lambda t: 1 / t)
sin = elementary("sin", math.sin, math.cos)
cos = elementary("cos", math.cos, lambda t: -math.sin(t))
relu = elementary("relu", lambda t: max(t, 0.0),
lambda t: 1.0 if t > 0 else 0.0)4 Reverse mode and backpropagation
Training a model means computing the gradient of one number, the loss, with respect to every parameter, thousands of times over. Forward mode (Chapter 3) gets one directional derivative per pass, so a gradient with respect to \(n\) parameters costs \(n\) passes. This chapter runs the chain rule the other way. After one ordinary evaluation of the function, a single sweep backwards through the evaluation trace computes the derivative of the output with respect to every variable in it, inputs included. The cost of the whole gradient is then a constant multiple of the cost of evaluating the function, whatever \(n\) is.
This is reverse mode, and applied to a neural network it goes by the name backpropagation. The chapter proves that it is correct on any acyclic computational graph and bounds its cost. It then builds a small reverse-mode engine in Python that records the evaluation trace as a table, line by line, and compares it with the design of linked nodes that the program behind the model of Chapter 11 uses.
4.1 Adjoints
Until Section 4.5, an evaluation trace \(v_1, \dots, v_N\) (Definition 3.1) with inputs \(v_1, \dots, v_n\) computes a function \(f\colon D \to \mathbb{R}\) with a single output, and the output is the last variable, \(L = v_N\). We fix \(\mathbf{a}\) in \(D\) and write \(v_k\) also for the value of variable \(k\) when \(\mathbf{x} = \mathbf{a}\). As in Chapter 3, \(d_{ki} = \partial\varphi_k/\partial v_i\) is the local partial derivative of line \(k\) with respect to its argument \(v_i\), evaluated at these values.
Forward mode asks how every variable responds to an increment of the inputs. Reverse mode asks the opposite question: how does the output respond to a perturbation of one variable? Take \(L = ab + a\) at \(a = 2\), \(b = 3\), with the trace \[ v_1 = a,\quad v_2 = b,\quad v_3 = v_1v_2,\quad v_4 = v_3 + v_1 = L, \] whose values are \(2, 3, 6, 8\). Perturb one variable at a time by a small amount \(t\), keeping the variables before it fixed and recomputing those after it.
- Perturbing \(v_4\) changes \(L\) by \(t\): rate \(1\).
- Perturbing \(v_3\) to \(6 + t\) gives \(L = (6 + t) + 2\): rate \(1\).
- Perturbing \(v_2\) to \(3 + t\) gives \(v_3 = 2(3 + t)\) and \(L = 8 + 2t\): rate \(2\).
- Perturbing \(v_1\) to \(2 + t\) gives \(v_3 = 3(2 + t)\) and \(L = 3(2 + t) + (2 + t) = 8 + 4t\): rate \(4\).
The variable \(a\) reaches \(L\) by two routes, through \(v_3\) and directly, and its rate \(4\) is the sum \(3 + 1\) of the two contributions: the local partial derivative \(d_{31} = v_2 = 3\) times the rate \(1\) of \(v_3\), plus \(d_{41} = 1\) times the rate \(1\) of \(v_4\). In general the rate for a variable is built from the rates of the later variables that use it, so the rates can be computed from the output backwards.
The obvious candidate for “the derivative of \(L\) with respect to \(v_1\)” is the partial derivative of the last line, \(\partial(v_3 + v_1)/\partial v_1 = 1\). It holds \(v_3\) fixed, and so misses the route through \(v_3\). The right notion recomputes every later variable, and holds only the earlier ones fixed.
Definition 4.1 (Adjoint) For \(n \le k \le N\), let \(L_k(w_1, \dots, w_k)\) be the value of \(v_N\) obtained by setting \(v_i = w_i\) for \(i \le k\) and then running lines \(k+1, \dots, N\) of the trace. So \(L_N(w_1, \dots, w_N) = w_N\) and \(L_n = f\). The adjoint of the variable \(v_k\) is \[ \bar v_k = \frac{\partial L_k}{\partial w_k}(v_1, \dots, v_k) \quad (k > n), \qquad \bar v_k = \frac{\partial f}{\partial x_k}(\mathbf{a}) \quad (k \le n), \] and we also write \(\bar v_k = \partial L/\partial v_k\).
In words, \(\bar v_k\) is the rate at which the output changes when \(v_k\) alone is perturbed, with every earlier variable held fixed and every later variable recomputed. In the example, \(L_3(w_1, w_2, w_3) = w_3 + w_1\) and \(L_2 = f\), and the adjoints are \((\bar v_1, \bar v_2, \bar v_3, \bar v_4) = (4, 2, 1, 1)\). The adjoints of the inputs form the gradient \(\nabla f(\mathbf{a})\), and \(\bar v_N = 1\). Theorem 4.1 shows that each partial derivative in the definition exists.
For \(n \le k < N\), lines \(k+1, \dots, N\) with \(v_1, \dots, v_k\) as inputs form a system of intermediate variables (Definition 2.1) with the same parent sets and the same local partial derivatives, and \(L_k\) is its last variable as a function of those inputs. This is what lets Theorem 2.2 describe the adjoints.
4.2 The reverse sweep
In the example, the adjoint of \(v_1\) was assembled from one contribution for each line that uses \(v_1\): line \(3\) contributed \(d_{31}\bar v_3\) and line \(4\) contributed \(d_{41}\bar v_4\). Each contribution needs the adjoint of a later variable. So we process the lines from the last to the first, and let line \(k\) hand its contribution \(d_{ki}\bar v_k\) to each of its arguments \(v_i\). Every line that uses \(v_k\) has a number larger than \(k\), so by the time the process reaches line \(k\), all of them have handed over their contributions, and the adjoint of \(v_k\) is complete and ready to pass on. A variable may receive contributions from several lines, so the method keeps a running total for each variable, called its accumulator, and adds each contribution to it. This is the reverse sweep.
Definition 4.2 (Reverse sweep)
- Forward pass. Evaluate the trace at \(\mathbf{a}\) and store every value \(v_1, \dots, v_N\).
- Set the accumulator of \(v_N\) to \(1\) and every other accumulator to \(0\).
- For \(k = N, N-1, \dots, n+1\), and for each \(i \in P(k)\), add \((\text{accumulator of } v_k)\cdot d_{ki}\) to the accumulator of \(v_i\), with \(d_{ki}\) evaluated at the stored arguments of line \(k\).
- Return the accumulators of \(v_1, \dots, v_n\).
The next example runs the sweep on \(L = ab + a\), and shows that step 3 must add to the accumulators rather than overwrite them.
Example 4.1 Run the sweep on \(L = ab + a\) at \(a = 2\), \(b = 3\). It starts with accumulators \((0, 0, 0, 1)\).
- Line \(4\), \(v_4 = v_3 + v_1\), has \(d_{43} = d_{41} = 1\). It adds \(1\cdot 1\) to the accumulators of \(v_3\) and \(v_1\), giving \((1, 0, 1, 1)\).
- Line \(3\), \(v_3 = v_1v_2\), has \(d_{31} = v_2 = 3\) and \(d_{32} = v_1 = 2\). It adds \(1\cdot3\) to the accumulator of \(v_1\) and \(1\cdot2\) to that of \(v_2\), giving \((4, 2, 1, 1)\).
The final accumulators are the adjoints found by perturbation above, and \(\nabla L(2, 3) = (4, 2)\) agrees with \(\partial L/\partial a = b + 1\) and \(\partial L/\partial b = a\). A sweep that overwrote the accumulator of \(v_1\) instead of adding to it would end with \(3\), the contribution through the product alone.
Theorem 4.1 (Reverse accumulation computes the gradient) Let an evaluation trace \(v_1, \dots, v_N\) with inputs \(v_1, \dots, v_n\) compute \(f\colon D \to \mathbb{R}\) with output \(v_N\), and let \(\mathbf{a} \in D\). Then every function \(L_k\) of Definition 4.1 is differentiable at \((v_1, \dots, v_k)\), so every adjoint exists, and:
each adjoint \(\bar v_k\) is the sum, over all paths from \(k\) to \(N\), of the product of the local partial derivatives along the path;
the adjoints satisfy \(\bar v_N = 1\) and \[ \bar v_i = \sum_{k\,:\,i \in P(k)} \bar v_k\,d_{ki} \qquad (i = 1, \dots, N-1); \tag{4.1}\]
when the reverse sweep of Definition 4.2 processes line \(k\), the accumulator of \(v_k\) holds \(\bar v_k\), and when the sweep finishes the accumulator of every variable holds its adjoint. In particular the sweep returns \(\nabla f(\mathbf{a})\).
In words, Equation 4.1 says that the adjoint of a variable is the sum, over the lines that use it, of the adjoint of that line’s result times the local partial derivative.
Proof.
For \(k = N\), \(L_N(\mathbf{w}) = w_N\) is linear, \(\bar v_N = 1\), and the only path from \(N\) to \(N\) is the empty path, with product \(1\). For \(k < N\), let \(m = \max(k, n)\), so \(m < N\). Lines \(m+1, \dots, N\) with \(v_1, \dots, v_m\) as inputs form a system of intermediate variables, and \(L_m\) is its last variable as a function of the inputs. The argument of Lemma 3.2 shows that the set on which \(L_m\) is defined is open, and each elementary operation is differentiable at its arguments. By Theorem 2.2, \(L_m\) is differentiable at \((v_1, \dots, v_m)\), and \(\partial L_m/\partial w_k\) is the sum over paths from \(k\) to \(N\) of the products of the local partial derivatives. This partial derivative is \(\bar v_k\) in both cases of Definition 4.1.
The only path from \(N\) to \(N\) is the empty path, with product \(1\), so \(\bar v_N = 1\). For \(i < N\), every path from \(i\) to \(N\) starts with an arrow \(i \to k\), which means \(i \in P(k)\), followed by a path from \(k\) to \(N\). Grouping the paths by their first arrow and applying (a) to each \(k\), the sum over paths from \(i\) is \(\sum_{k : i \in P(k)} d_{ki}\,\bar v_k\).
Line \(k\) changes only the accumulators of its arguments, whose numbers are less than \(k\). So once the sweep has reached line \(k\), no later step changes the accumulator of \(v_k\), and its value from then on is its starting value plus one contribution from each line \(k'\) with \(k \in P(k')\): the accumulator of \(v_{k'}\) when line \(k'\) was processed, times \(d_{k'k}\). We show by induction downwards from \(N\) that this value is \(\bar v_k\). For \(k = N\) no line uses \(v_N\), and the starting value is \(1 = \bar v_N\). For \(k < N\) the starting value is \(0\), and every \(k'\) with \(k \in P(k')\) is larger than \(k\), so by the induction hypothesis the accumulator of \(v_{k'}\) held \(\bar v_{k'}\) when line \(k'\) was processed. So the accumulator of \(v_k\) holds \(\sum_{k' : k \in P(k')} \bar v_{k'}\,d_{k'k} = \bar v_k\), by Equation 4.1. For an input \(k \le n\) this is the value when the sweep finishes, which is \(\partial f/\partial x_k(\mathbf{a})\).
The theorem applies to any acyclic computational graph with one output. By Theorem 3.1 the graph has a topological order with the inputs first. Nodes from which no path leads to the output do not affect it; remove them, and the output has no children left, so some topological order numbers it last. (The removed inputs have adjoint \(0\), which is what the sweep’s starting accumulators say.)
In Example 4.1 there are two paths from \(a\) to \(L\): \(1 \to 3 \to 4\) with product \(d_{31}d_{43} = 3\cdot1\), and \(1 \to 4\) with product \(d_{41} = 1\), which add to \(\bar v_1 = 4\). The number of paths can grow exponentially with the size of the graph (Exercise 2.4, Exercise 4.8), while the sweep handles each arrow once. It computes the path sums of part (a) by sharing work: the sum over all paths from \(v_k\) to the output is computed once, as \(\bar v_k\), and reused by every argument of line \(k\).
4.3 Forward and reverse mode compute the same numbers
Forward mode with seed \(\mathbf{e}_i\) and reverse mode both produce \(\partial f/\partial x_i(\mathbf{a})\), by recurrences that run in opposite directions. In Example 4.1, forward mode with seed \(\mathbf{e}_1\) gives the tangents \(\dot v_1 = 1\), \(\dot v_2 = 0\), \(\dot v_3 = d_{31}\dot v_1 + d_{32}\dot v_2 = 3\) and \(\dot v_4 = d_{43}\dot v_3 + d_{41}\dot v_1 = 4\), while reverse mode gives \(\bar v_1 = 4\). One identity explains the agreement. Collect the local partial derivatives in the \(N\times N\) matrix \(C\) whose entry in row \(i\) and column \(k\) is \[ c_{ik} = d_{ki}\ \text{ if } i \in P(k), \qquad c_{ik} = 0 \ \text{ otherwise}. \] Column \(k\) of \(C\) holds the local partial derivatives of line \(k\) with respect to its arguments, and row \(i\) holds the local partial derivatives of the lines that use \(v_i\). Since \(i \in P(k)\) only when \(i < k\), the matrix is strictly upper triangular: every entry on or below the diagonal is \(0\). For Example 4.1, \[ C = \begin{pmatrix} 0 & 0 & 3 & 1\\ 0 & 0 & 2 & 0\\ 0 & 0 & 0 & 1\\ 0 & 0 & 0 & 0 \end{pmatrix}. \] Column \(3\) holds \(d_{31} = 3\) and \(d_{32} = 2\), the local partial derivatives of \(v_3 = v_1v_2\), and column \(4\) holds \(d_{41} = 1\) and \(d_{43} = 1\), those of \(v_4 = v_3 + v_1\). Row \(1\) says that \(v_1\) is used by lines \(3\) and \(4\). Columns \(1\) and \(2\) are zero because the inputs have no arguments, and row \(4\) is zero because no line uses the output.
The tangent recurrence Equation 3.1 with seed \(\mathbf{u}\) says \(\dot{\mathbf{v}} = \mathbf{s} + C^\top\dot{\mathbf{v}}\) with \(\mathbf{s} = (u_1, \dots, u_n, 0, \dots, 0)\), because entry \(k\) of \(C^\top\dot{\mathbf{v}}\) is \(\sum_{i\in P(k)} d_{ki}\dot v_i\) and the inputs have no arguments. The adjoint equations Equation 4.1 say \(\bar{\mathbf{v}} = \mathbf{e}_N + C\bar{\mathbf{v}}\), because entry \(i\) of \(C\bar{\mathbf{v}}\) is \(\sum_{k : i\in P(k)} d_{ki}\bar v_k\). So forward mode multiplies by \(C^\top\), running down the columns of \(C\), and reverse mode multiplies by \(C\), running along its rows. In the example, \(\bar{\mathbf{v}} = (4, 2, 1, 1)\) and \(C\bar{\mathbf{v}} = (3 + 1,\; 2,\; 1,\; 0)\), so \(\mathbf{e}_4 + C\bar{\mathbf{v}} = \bar{\mathbf{v}}\). The next theorem shows that two such equations, one with \(C^\top\) and one with \(C\), always produce matching numbers.
Theorem 4.2 (Transposition) Let \(C\) be any \(N\times N\) matrix and \(\mathbf{s}\), \(\mathbf{w}\) any vectors in \(\mathbb{R}^N\). If \(\mathbf{t} \in \mathbb{R}^N\) satisfies \(\mathbf{t} = \mathbf{s} + C^\top \mathbf{t}\) and \(\bar{\mathbf{v}} \in \mathbb{R}^N\) satisfies \(\bar{\mathbf{v}} = \mathbf{w} + C\bar{\mathbf{v}}\), then \(\mathbf{w}\cdot\mathbf{t} = \bar{\mathbf{v}}\cdot\mathbf{s}\).
Proof. Using \(\mathbf{w} = \bar{\mathbf{v}} - C\bar{\mathbf{v}}\) and \((C\bar{\mathbf{v}})\cdot\mathbf{t} = \bar{\mathbf{v}}^\top C^\top \mathbf{t} = \bar{\mathbf{v}}\cdot(C^\top\mathbf{t})\), \[ \mathbf{w}\cdot\mathbf{t} = \bar{\mathbf{v}}\cdot\mathbf{t} - \bar{\mathbf{v}}\cdot(C^\top\mathbf{t}) = \bar{\mathbf{v}}\cdot(\mathbf{t} - C^\top\mathbf{t}) = \bar{\mathbf{v}}\cdot\mathbf{s} . \]
With \(\mathbf{w} = \mathbf{e}_N\) and the seed \(\mathbf{u} =
\mathbf{e}_i\), the left side is the tangent of the output, which is \(\partial f/\partial x_i(\mathbf{a})\) by Theorem 3.2, and the right side is \(\bar v_i\). This gives a second proof that the sweep returns the gradient: \(n\) forward passes and one reverse sweep fill in the same vector. The file lean/AutodiffBook/Ch04.lean checks the identity by machine.
4.4 The cost of a gradient
How much more does the gradient cost than the function? Count the work for Example 4.1, charging one unit for each arithmetic operation and one for each number read or set. Evaluating \(L = ab + a\) costs \(4\) units: \(2\) for reading the inputs and \(2\) for the operations. The sweep sets \(4\) accumulators, at \(4\) units. The local partial derivatives cost \(2\) units: those of \(v_3 + v_1\) are the constant \(1\), set twice, and those of \(v_1v_2\) are the stored arguments. Each of the \(4\) arrows needs one multiplication and one addition, \(8\) units in all. Forward pass and sweep together cost \(4 + 4 + 2 + 8 = 18\) units, \(4.5\) times the cost of \(f\). The same count for any trace gives a bound that does not depend on the number of inputs.
Definition 4.3 (Cost model) Let a trace with inputs \(v_1, \dots, v_n\) compute \(f\). Give each line \(k\) a cost \(c_k \ge 1\): reading an input costs \(c_k = 1\), and for \(k > n\), \(c_k\) is the cost of evaluating \(\varphi_k\). The cost of evaluating \(f\) is \(\operatorname{cost}(f) = c_1 + \dots + c_N\). The cost model consists of three assumptions:
every operation has at most \(r\) arguments;
for each \(k > n\), the local partial derivatives \(d_{ki}\), \(i \in P(k)\), can be computed from the arguments and the value of line \(k\) at cost at most \(\alpha\,c_k\), for a constant \(\alpha\);
each addition or multiplication costs \(1\), and so does setting a number to a constant.
For the elementary operations of Chapter 3, \(r = 2\). With every arithmetic operation and every evaluation of \(\exp\), \(\log\), \(\sin\), \(\cos\) or a power costing \(1\), we can take \(\alpha = 3\): the partial derivatives of \(t_1 + t_2\) and \(t_1 t_2\) are constants or arguments; the derivative of \(e^t\) is the value already computed; those of \(\log t\) and \(\sin t\) take one operation each, and that of \(\cos t\), which is \(-\sin t\), takes two; that of \(t^c\) is \(c\,t^c/t\), two operations; and those of \(t_1/t_2\) are \(1/t_2\) and \(-(t_1/t_2)/t_2\), three operations.
Theorem 4.3 (The cheap gradient principle) Let a trace with inputs \(v_1, \dots, v_n\) compute \(f\colon D \to \mathbb{R}\), with line costs \(c_k \ge 1\) and \(\operatorname{cost}(f) = c_1 + \dots + c_N\). Suppose every operation has at most \(r\) arguments, the local partial derivatives of line \(k\) can be computed at cost at most \(\alpha c_k\), and each addition, multiplication and assignment of a constant costs \(1\). Then the forward pass and the reverse sweep together compute \(f(\mathbf{a})\) and \(\nabla f(\mathbf{a})\) at cost at most \[ (2 + \alpha + 2r)\operatorname{cost}(f), \] whatever the number of inputs \(n\).
Proof. Add up the steps of Definition 4.2. The forward pass costs \(\operatorname{cost}(f)\). Setting the \(N\) accumulators costs \(N\), and \(N \le \operatorname{cost}(f)\) because every \(c_k \ge 1\). Computing the local partial derivatives of every line costs at most \(\sum_{k>n}\alpha c_k \le \alpha\operatorname{cost}(f)\). In step 3, each pair \((k, i)\) with \(i \in P(k)\) costs one multiplication and one addition, and there are \(\sum_{k > n}|P(k)| \le r\sum_{k>n} 1 \le r\operatorname{cost}(f)\) such pairs. The total is at most \((1 + 1 + \alpha + 2r)\operatorname{cost}(f)\).
With \(\alpha = 3\) and \(r = 2\) the bound is \(9\operatorname{cost}(f)\), comfortably above the factor \(4.5\) of the example. Forward mode needs \(n\) passes for the same gradient, each costing a constant multiple of \(\operatorname{cost}(f)\). The constant \(9\) comes from a coarse count. Griewank and Walther (2008) analyse the cost of reverse mode in detail, and Baydin et al. (2018, sec. 3.2), citing that analysis, give the constant as less than \(6\) and typically between \(2\) and \(3\).
4.5 Vector–Jacobian products and the shape of the Jacobian
Reverse mode works for functions with several outputs too. In Example 4.1, treat both \(y_1 = v_3 = ab\) and \(y_2 = v_4 = ab + a\) as outputs, so \(f(a, b) = (ab,\; ab + a)\) with \[ J_f(2, 3) = \begin{pmatrix} 3 & 2 \\ 4 & 2 \end{pmatrix}, \] whose rows are the gradients of the two outputs. Run the sweep with the accumulators of \(v_3\) and \(v_4\) starting at chosen numbers \(w_1\) and \(w_2\) instead of \(0\) and \(1\). Starting from \((w_1, w_2) = (0, 1)\) is the sweep of Example 4.1, which returns \((4, 2)\), the second row. Starting from \((1, 0)\), line \(4\) contributes nothing and line \(3\) returns \((3, 2)\), the first row. Starting from \((1, 1)\), line \(4\) raises the accumulator of \(v_3\) to \(2\) and adds \(1\) to that of \(v_1\), and line \(3\) then adds \(2\cdot3\) and \(2\cdot2\), returning \((7, 4)\), the sum of the rows. In each case the sweep returns \(\mathbf{w}^\top J_f(2, 3)\), the combination of the rows with weights \(w_1\), \(w_2\).
Theorem 4.4 (Reverse mode computes vector–Jacobian products) Let an evaluation trace with inputs \(v_1, \dots, v_n\) compute \(f\colon D \to \mathbb{R}^m\), with outputs \(y_1, \dots, y_m\) at distinct variables, let \(\mathbf{a} \in D\) and let \(\mathbf{w} \in \mathbb{R}^m\). Run the reverse sweep of Definition 4.2 with the accumulator of output \(y_l\) starting at \(w_l\), every other accumulator starting at \(0\), and every line from \(N\) down to \(n+1\) processed. Then the sweep returns \(J_f(\mathbf{a})^\top\mathbf{w}\), whose transpose is the vector–Jacobian product \(\mathbf{w}^\top J_f(\mathbf{a})\).
Proof. Let \(\tilde{\mathbf{w}} \in \mathbb{R}^N\) hold \(w_l\) in the position of output \(y_l\) and \(0\) elsewhere, and let \(\bar{\mathbf{v}}\) be the final accumulators. As in the proof of Theorem 4.1 (c), the accumulator of \(v_k\) does not change after line \(k\) is processed. So the accumulator of \(v_i\) ends as its starting value plus one contribution from each line \(k\) that uses \(v_i\), namely \(\tilde w_i + \sum_{k : i \in P(k)} d_{ki}\bar v_k\), and \(\bar{\mathbf{v}} = \tilde{\mathbf{w}} + C\bar{\mathbf{v}}\) with the matrix \(C\) of Section 4.3. Run forward mode with seed \(\mathbf{e}_j\), giving tangents \(\mathbf{t}\) with \(\mathbf{t} = \mathbf{e}_j + C^\top\mathbf{t}\). By Theorem 4.2 and Theorem 3.2, \[ \bar v_j = \tilde{\mathbf{w}}\cdot\mathbf{t} = \sum_{l=1}^m w_l\,\bigl(J_f(\mathbf{a})\mathbf{e}_j\bigr)_l = \bigl(J_f(\mathbf{a})^\top\mathbf{w}\bigr)_j . \]
With \(\mathbf{w} = \mathbf{e}_l\), one sweep gives row \(l\) of the Jacobian, the gradient of output \(l\). So for \(f\colon\mathbb{R}^n \to \mathbb{R}^m\), forward mode gets the Jacobian a column at a time, in \(n\) passes, and reverse mode gets it a row at a time, in \(m\) sweeps. Each pass or sweep costs a constant multiple of evaluating \(f\), so forward mode is the cheaper choice when \(n < m\), and reverse mode when \(m < n\). A loss function has \(m = 1\) and \(n\) in the thousands or more, which is why training uses reverse mode. A curve \(\gamma\colon\mathbb{R}\to\mathbb{R}^3\) has \(n = 1\), and one forward pass gives its velocity. For a product of Jacobians, choosing the order of the matrix multiplications is the same choice (Exercise 4.6).
4.6 Memory and checkpointing
Reverse mode pays for its speed in memory, by which we mean the number of values a method must store at the same time. Line \(k\) of the sweep needs the arguments of line \(k\), so the forward pass must keep every value until the sweep reaches it: memory in proportion to \(N\), the length of the computation. Forward mode, by contrast, can discard each value once the lines that use it have run.
Take a computation that is a chain of \(T\) steps, \(\mathbf{s}_t = \Phi_t(\mathbf{s}_{t-1})\) for \(t = 1, \dots, T\), such as the layers of a deep network, where each state \(\mathbf{s}_t\) is a vector. Sweeping back through step \(t\) needs its argument \(\mathbf{s}_{t-1}\), so the plain sweep stores all the states. With \(T = 100\) there is a cheaper way. Keep only the ten states \(\mathbf{s}_0, \mathbf{s}_{10}, \dots, \mathbf{s}_{90}\) during the forward pass. To sweep back through steps \(100, \dots, 91\), recompute \(\mathbf{s}_{91}, \dots, \mathbf{s}_{99}\) from \(\mathbf{s}_{90}\); once the sweep has passed step \(91\), discard them, recompute \(\mathbf{s}_{81}, \dots, \mathbf{s}_{89}\) from \(\mathbf{s}_{80}\), and so on. At most \(20\) states are stored at any moment, against \(100\), and each \(\Phi_t\) is evaluated at most twice.
Checkpointing trades recomputation for memory in this way. During the forward pass, keep only every \(K\)th state \(\mathbf{s}_0, \mathbf{s}_K, \mathbf{s}_{2K}, \dots\), about \(T/K\) of them. During the sweep, take the segments in reverse order: recompute the states of a segment from its stored first state, keep these \(K\) states, sweep back through the segment, and discard them. At any moment the method stores at most about \(T/K + K\) states, and the recomputation adds at most one more forward pass. Since \[ \frac TK + K - 2\sqrt T = \Bigl(\sqrt{T/K} - \sqrt K\Bigr)^2 \ge 0 , \] the memory is smallest, about \(2\sqrt T\), when \(K = \sqrt T\). For \(T = 10^6\) steps that is \(2000\) stored states instead of a million.
Chen et al. (2016) use this scheme for deep networks, with memory proportional to \(\sqrt n\) for an \(n\)-layer network at the price of one extra forward pass. Applying the idea recursively inside each segment reduces memory further (Exercise 4.9). Griewank (1992) showed that checkpointing applied recursively makes both the memory and the extra computation grow only logarithmically with the length of the computation, relative to a single evaluation, and Griewank and Walther (2000) give schedules that are optimal for this trade-off.
4.7 A reverse-mode engine on a tape
The reverse sweep of Definition 4.2 reads three things from the forward pass: the order of the lines, the arguments of each line, and the local partial derivatives \(d_{ki}\) at the values of the forward pass. A program can collect all three while it evaluates the function. Each time it applies an elementary operation, it computes the result together with the local partial derivatives of the operation, and writes one line into a list: the operation, the value, and a pair \((i, d_{ki})\) for each argument \(v_i\). We call such a list a tape. For \(L = ab + a\) at \(a = 2\), \(b = 3\) the tape is Table 4.1.
| line | operation | value | pairs \((i, d_{ki})\) |
|---|---|---|---|
| \(v_1\) | \(a\) | \(2\) | |
| \(v_2\) | \(b\) | \(3\) | |
| \(v_3\) | \(v_1 v_2\) | \(6\) | \((1, 3)\), \((2, 2)\) |
| \(v_4\) | \(v_3 + v_1\) | \(8\) | \((3, 1)\), \((1, 1)\) |
The first three columns are the evaluation trace as we wrote it by hand in Section 4.1. The last column holds the non-zero entries of the matrix \(C\) of Section 4.3, one column of \(C\) per line. The sweep of Example 4.1 reads only this column, from the bottom row up: row \(4\) adds \(1\cdot1\) to the accumulators of \(v_3\) and \(v_1\), and row \(3\) then adds \(1\cdot3\) to that of \(v_1\) and \(1\cdot2\) to that of \(v_2\).
A tape needs no sorting before the sweep. A program can apply an operation only to values that already exist, so every argument of a line was recorded on an earlier line, and \(P(k) \subseteq \{1, \dots, k-1\}\) as Definition 3.1 requires. The order of recording is therefore a topological order of the computational graph, and the sweep can take the lines in reverse order of recording. The proof of Theorem 4.1 (c) is an induction downwards over the line numbers and uses nothing else about the order, so it applies to the tape as recorded.
The engine below rests on three decisions. The first is what a number of the computation is: a variable, an object that holds a line number \(k\) and the value \(v_k\). Python lets a class say what +, * and the other operators mean for its objects (operator overloading, as in Section 3.5). The operators of a variable compute the result and the local partial derivatives, and append the line to the tape. Ordinary arithmetic on variables then writes the trace as a side effect.
The second is how the operators know which tape to write to. The program starts a tape before it evaluates the function and stops it afterwards, and only a tape that has been started and not yet stopped, the recording tape, receives lines. Python’s with statement does both: with Tape() as tape: starts a new tape, runs the indented block below it, and stops the tape when the block ends, even if the block fails with an error. Arithmetic outside the block, such as the update of the parameters after a step of gradient descent, then stays off the tape: it is not part of the function being differentiated.
The third is how long a tape lives: each evaluation gets a new tape, which the program discards after the sweep. A tape keeps every line it receives, so its memory grows with the length of the computation, as Section 4.6 explains. A training loop that recorded every step on one tape would keep the lines of all earlier steps, and every sweep would pass through all of them. The line number held by a variable refers to the tape that recorded it, so a variable belongs to one evaluation. A model’s parameters therefore live between steps as ordinary numbers, and each step records them afresh as inputs of its own tape.
The class Tape holds the list lines, with line \(k\) in entry \(k\). Python numbers the entries of a list from \(0\), and entry \(0\) stays empty so that the numbering matches the book’s. The class attribute Tape.recording names the recording tape, or is None when no tape records. The methods __enter__ and __exit__ are the ones that the with statement calls at the start and the end of its block: the first makes the new tape the recording one, refusing if another tape is already recording, and the second stops it. Each line is a Line with three fields: op, a pattern for printing the operation in which {} stands for each argument; value, the value \(v_k\); and partials, the pairs \((i, d_{ki})\). The function record appends a line to the recording tape and returns a Var holding the new line number and the value. The method tape.input records an input line, which has no pairs.
The operators come from the function binary. It turns an operation \(g(s, t)\) of two numbers and its partial derivatives \(\partial g/\partial s\) and \(\partial g/\partial t\) into two methods. The first handles u + w with u a variable. If w is also a variable, the line has two arguments. If w is a number, the line has one, because constants live inside the operations: \(t + 2\) is an operation of one variable (Section 3.1). The second method handles 2 + u, with a number on the left, which Python passes to the method __radd__ of u. The function elementary does the same for an operation \(g(t)\) of one variable with derivative \(g'\), as extend does for dual numbers in Section 3.5.
The primitive operations, the ones with a derivative rule of their own, are the elementary operations of Section 3.1: addition, subtraction, multiplication and division of two numbers or of a number and a constant, powers with a constant exponent, and \(\exp\), \(\log\), \(\sin\) and \(\cos\). To these the engine adds the ReLU, \(\max(t, 0)\). Each primitive records one line, so the tape of a formula is the trace a reader would write for it by hand, as in Table 4.1. The other operations are derived: negation records -1.0 * u, a multiplication by a constant, and a square root is written u ** 0.5. A derived operation needs no derivative rule, because the tape records the primitive lines it is made of and the sweep differentiates those. Division could be derived in the same way, as u * w ** -1, at the price of a second line for every quotient; as a primitive it keeps the tape equal to the trace of Chapter 3.
The ReLU has no derivative at \(0\), and the engine uses \(0\) there, a choice Chapter 7 discusses. At points where no ReLU receives exactly \(0\), each ReLU agrees with \(0\) or with \(t\) on an interval around its argument, so it is differentiable there and Theorem 4.1 applies.
def backward(tape, out):
"""Return bar, where bar[k] is the adjoint of line k for output out."""
N = len(tape.lines) - 1
bar = [0.0] * (N + 1)
bar[out] = 1.0
for k in range(N, 0, -1):
for i, d in tape.lines[k].partials:
bar[i] += bar[k] * d
return bar
def gradient(f, a):
"""Return f(a) and the gradient of f at a, by one tape and one sweep."""
with Tape() as tape:
x = [tape.input(aj) for aj in a]
out = f(*x)
bar = backward(tape, out.k)
return out.value, [bar[xj.k] for xj in x]
def print_tape(tape):
"""Print the tape as a table of lines, values and pairs (i, d_ki)."""
print(f"{'line':<6}{'operation':<14}{'value':>9} pairs (i, d_ki)")
for k in range(1, len(tape.lines)):
op, value, partials = tape.lines[k]
formula = op.format(*(f"v{i}" for i, _ in partials))
pairs = ", ".join(f"({i}, {d:.6g})" for i, d in partials)
print(f"v{k:<5}{formula:<14}{value:>9.6g} {pairs}".rstrip())The function backward takes a tape and the line number out of the output. It makes a list bar of adjoints indexed by line number, with every entry \(0\) except bar[out], which is \(1\). It then runs through the lines from the last, \(N\), down to \(1\), and for each pair \((i, d)\) of line \(k\) adds bar[k] * d to bar[i]. This is step 3 of Definition 4.2, with bar as the list of accumulators. Input lines have no pairs and add nothing. The function returns the whole list, so the adjoint of every line is available, inputs included.
The function gradient runs the whole cycle for a function of \(n\) numbers: it starts a tape, records the inputs, evaluates \(f\) on them, stops the tape, sweeps, and returns \(f(\mathbf{a})\) together with the adjoints of the inputs. It plays the part of the forward-mode gradient of Section 3.5, with one sweep in place of \(n\) passes. The function print_tape prints one row for each line: the line, the operation with each argument written as \(v_i\), the value, and the pairs.
Running the engine on Example 4.1 prints the tape and the adjoints:
with Tape() as tape:
a = tape.input(2.0, "a")
b = tape.input(3.0, "b")
L = a * b + a
print_tape(tape)
bar = backward(tape, L.k)
print("adjoints:", bar[1:])
print("gradient:", (bar[a.k], bar[b.k]))line operation value pairs (i, d_ki)
v1 a 2
v2 b 3
v3 v1 * v2 6 (1, 3), (2, 2)
v4 v3 + v1 8 (3, 1), (1, 1)
adjoints: [4.0, 2.0, 1.0, 1.0]
gradient: (4.0, 2.0)
The printed tape is Table 4.1, row for row. The sweep gives the adjoints \((4, 2, 1, 1)\) of Example 4.1, and the gradient \(\nabla L(2, 3) = (4, 2)\).
A product x * x records one line whose two pairs both name the line of x, each with \(d = x\), and the += in backward adds the two contributions to give \(2x\). This is Equation 4.1 for the operation \(t \mapsto t^2\), whose derivative is the sum of the partial derivatives of \(t_1t_2\) at \(t_1 = t_2 = t\). The sweep runs over every line, including lines that the output does not depend on. Their adjoints stay \(0\), so their pairs add nothing (Exercise 4.3).
A small two-layer network, of the kind Chapter 7 studies, shows the engine on the kind of expression the rest of the book trains. From the inputs \(x_1 = 0.5\) and \(x_2 = -1.5\), a \(2\times 2\) matrix \(W\) of weights and weights \(c_1\), \(c_2\), it computes \[ h_i = \max(w_{i1}x_1 + w_{i2}x_2,\; 0) \quad (i = 1, 2), \qquad y = c_1h_1 + c_2h_2, \qquad \text{loss} = (y - 1)^2 , \] the squared distance of \(y\) from a target of \(1\). The code records the inputs and the six weights as the first eight lines, evaluates the loss, and sweeps once for the derivative of the loss with respect to each weight.
with Tape() as tape:
x = [tape.input(0.5), tape.input(-1.5)]
W = [[tape.input(0.3), tape.input(-0.8)],
[tape.input(1.1), tape.input(0.4)]]
c = [tape.input(0.7), tape.input(-1.2)]
h = [relu(W[i][0] * x[0] + W[i][1] * x[1]) for i in range(2)]
y = c[0] * h[0] + c[1] * h[1]
loss = (y - 1.0) ** 2
bar = backward(tape, loss.k)
print(f"loss = {loss.value:.6f}, lines on the tape: {len(tape.lines) - 1}")
print("dloss/dW =", [[round(bar[w.k], 6) for w in row] for row in W])
print("dloss/dc =", [round(bar[ci.k], 6) for ci in c])loss = 0.003025, lines on the tape: 21
dloss/dW = [[-0.0385, 0.1155], [0.0, 0.0]]
dloss/dc = [-0.1485, 0.0]
For \(h_2\) the argument of the maximum is \(1.1 \cdot 0.5 + 0.4 \cdot (-1.5) = -0.05\), so \(h_2 = 0\), the ReLU line has \(d = 0\) and passes back adjoint \(0\), and the weights \(w_{21}\), \(w_{22}\) and \(c_2\) get zero derivative at this point. For \(h_1\) it is \(1.35\), so \(y = 0.7 \cdot 1.35 = 0.945\) and the loss is \(0.055^2 = 0.003025\). The tape has \(21\) lines: \(8\) inputs, \(4\) for each \(h_i\) (two products, a sum and a ReLU), \(3\) for \(y\), and \(2\) for the loss (a subtraction of a constant and a square).
The source of this book checks every gradient this engine produces against SymPy and against central differences, and on a chain of \(1000\) lines against the forward mode of Section 3.5. The engine is slow, since every scalar operation creates a Python object and a line, but its operations suffice for the model of Chapter 11: the program behind that model differentiates with the same operations, kept as linked nodes (Section 4.8) instead of a tape (Karpathy 2026). Real systems apply the same sweep to arrays, with one line per matrix operation instead of one per number, which is the subject of Theorem 7.1.
4.8 Linked nodes and depth-first search
A tape is one way to keep the trace. Another keeps no list at all: each result holds references to its arguments and the local partial derivatives with respect to them, and nothing else records the computation. Call these objects nodes. Each node holds its value and links to its parents, the arguments of the operation that produced it, so the nodes and links form the computational graph of Definition 3.2. In Example 4.1 the node of \(L\) links to the nodes of \(v_3\) and \(a\), and the node of \(v_3\) links to those of \(a\) and \(b\). No table of lines exists in memory, and no node records when it was made.
To run the sweep, such an engine needs the nodes on which the output depends, listed so that every node comes after its parents; reading the list backwards then processes every node before its arguments. It must build the list from the links, starting at the output. In Example 4.1, start at \(L = v_4\). Before listing \(v_4\), list its parents, \(v_3\) and \(v_1\). Before listing \(v_3\), list its parents \(v_1\) and \(v_2\), which have no parents and are listed at once. So the list begins \(v_1, v_2, v_3\). The other parent of \(v_4\) is \(v_1\), which is already listed, and finally \(v_4\) is listed: the result is \(v_1, v_2, v_3, v_4\).
Definition 4.4 (Depth-first topological sort) Start with an empty list and no node marked. To visit a node \(u\): if \(u\) is marked, do nothing; otherwise mark \(u\), visit each parent of \(u\) in turn, and then append \(u\) to the list. The depth-first order from a node \(o\) is the list obtained by visiting \(o\).
A node \(u\) is an ancestor of \(o\) if there is a path from \(u\) to \(o\) (possibly the empty path, so \(o\) is an ancestor of itself).
Theorem 4.5 (Depth-first search gives a topological order) Let \(o\) be a node of a DAG. The depth-first order from \(o\) contains every ancestor of \(o\) exactly once and no other node, and each node in it comes after all of its parents.
Proof. A node is marked before its visit appends it, and a visit to a marked node does nothing, so each node is appended at most once. Each visit to an unmarked node marks it, so at most as many visits do any work as there are nodes, and the search ends. Visits happen only to \(o\) and, from inside the visit of a node, to that node’s parents, so by induction every visited node is an ancestor of \(o\). Conversely, if \(u_0 \to u_1 \to \dots \to u_r = o\) is a path, then by induction downwards from \(o\) each \(u_i\) is visited, since every visit to an unmarked node visits all its parents, and a marked node has already been visited. Every visited node is marked, and is appended when its first visit ends.
Now let \(p\) be a parent of \(u\), with \(u\) in the list. During the first visit to \(u\), the search visits \(p\). If \(p\) is unmarked at that moment, the visit to \(p\) finishes, and appends \(p\), before the visit to \(u\) appends \(u\). If \(p\) is already marked, its first visit began earlier. If that visit has already finished, \(p\) is already in the list. Otherwise the visit to \(p\) is still in progress, so the visit to \(u\) was started, directly or through a chain of visits, from inside it. Each visit in that chain is to a parent of the node before it, so there is a path from \(u\) to \(p\). Together with the edge \(p \to u\) it forms a cycle, which is impossible in a DAG.
Each node is marked once and each edge is followed once, so the search does work proportional to the number of nodes plus the number of edges of the part of the graph above \(o\). Tarjan (1972) showed how depth-first search leads to efficient graph algorithms.
The most direct translation of Definition 4.4 into Python is a function visit that calls itself once for each parent. But a call that has started and not yet finished occupies space until it returns, and Python allows only about a thousand such calls at once, so a chain of a thousand operations would exceed the limit. The function topological_order below therefore keeps its own list of the visits in progress. It adds and removes entries only at the end of that list, which programmers call a stack. The last entry is the visit being carried out, together with the parents it has yet to visit. At each step that visit takes its next parent and, if the parent is unmarked, marks it and starts a visit to it by adding an entry. When a visit has no parents left, its entry is removed and its node is appended to the order, as Definition 4.4 prescribes. The set visited holds the marked nodes. The function works on any objects that have an attribute parents; the small class Node, which holds a name and the parents and nothing else, is enough to try it on the graph of Example 4.1.
def topological_order(root):
"""Every node that root depends on, each after all of its parents."""
order, visited = [], {root}
stack = [(root, iter(root.parents))] # the visits in progress
while stack:
node, parents = stack[-1]
parent = next(parents, None)
if parent is None: # every parent of node is done
stack.pop()
order.append(node)
elif parent not in visited: # start a visit to parent
visited.add(parent)
stack.append((parent, iter(parent.parents)))
return order
class Node:
"""A node of a computational graph: a name and the parents."""
def __init__(self, name, *parents):
self.name, self.parents = name, parentsv1, v2 = Node("v1"), Node("v2")
v3 = Node("v3", v1, v2)
v4 = Node("v4", v3, v1)
print([u.name for u in topological_order(v4)])['v1', 'v2', 'v3', 'v4']
With this list in hand, the sweep is Definition 4.2 with the positions in the list in place of line numbers. The engine takes the nodes from the last to the first, and each node adds its adjoint times each stored local partial derivative to the accumulator of the corresponding parent. The accumulators can be kept in the nodes themselves or in a table indexed by node.
This is the design of systems that build a graph of linked nodes as the program runs. PyTorch records with each result the function that produced it, an entry point into a graph of such functions that it builds afresh at every evaluation (PyTorch Contributors 2026). Two small examples in plain Python are micrograd (Karpathy 2020) and the program behind the model of Chapter 11. Each wraps every number in an object that holds its accumulator and links to its arguments, and each sorts the nodes by the recursive form of Definition 4.4 before the sweep.
The two designs differ in four ways, summarised in Table 4.2.
| tape | linked nodes | |
|---|---|---|
| order for the sweep | the order of recording, free | rebuilt by depth-first search at every sweep |
| lines swept | every line on the tape | only the ancestors of the output |
| lifetime of the record | from start to discard, set by the program | as long as some node refers to it |
| several computations | one tape per computation, one recording at a time | separate graphs side by side, sharing nodes freely |
The tape gets its order for nothing, but sweeps every line, including lines that the output does not depend on. Depth-first search costs work in proportion to the size of the graph above the output, about as much as the sweep itself, and in return skips every node that does not lead to the output. A tape lives until the program discards it, which is why the program must start and stop it; linked nodes live as long as something refers to them, so a node that leads nowhere disappears as soon as the program drops it, and the rest of the graph goes when the program drops the output. And because nodes carry their own links, two computations can build their graphs at the same time and share nodes, such as the parameters of a model, while the tape of this chapter records one computation at a time and keeps parameters as ordinary numbers between evaluations.
4.9 History
Wengert (1964) described forward mode as a program in 1964. For reverse mode, Linnainmaa (1976) expanded the rounding error accumulated by an algorithm in terms of the local rounding errors of its steps, a calculation of first-order sensitivities of the final result to each intermediate quantity; Baydin et al. (2018, sec. 3.3) note that this work is often cited as the first published description of reverse mode. Rumelhart et al. (1986) applied the method, under the name back-propagation, to training layered neural networks, and their paper brought it to wide attention. Researchers in several fields found the idea independently, and Baydin et al. (2018, sec. 3.3) trace its history through optimal control and the automatic differentiation community.
4.10 Notes and further reading
Griewank and Walther (2008) develop reverse mode in full, including its cost and the checkpointing methods that reduce its memory use. Baydin et al. (2018) survey automatic differentiation for machine learning, with worked forward and reverse sweeps on a small example and a review of implementations. Topological sorting goes back to Kahn (1962), and the method of Theorem 4.5 uses the depth-first search studied by Tarjan (1972).
4.11 Exercises
Exercise 4.1 Run the reverse sweep by hand on the trace of Table 3.1 at \((2, 0.5)\), listing the adjoint of every variable, and compare the result with Example 3.1.
Exercise 4.2 On a tape whose first line is an input x, the statement y = x * x records line \(2\) with the pairs \((1, x)\) and \((1, x)\).
Show that
backward(tape, y.k)setsbar[1]to \(2x\).What would it set
bar[1]to ifbackwardused=instead of+=? What would it give for Example 4.1?
Exercise 4.3 Record, with \(a = 2\) and \(b = 3\),
with Tape() as tape:
a = tape.input(2.0, "a")
b = tape.input(3.0, "b")
u = a * b
w = exp(b)
L = u + aWrite out the tape as in Table 4.1, and run
backward(tape, L.k)by hand. Show that the sweep processes line \(4\) but that the line adds nothing, and that the gradient is still \((4, 2)\).Run
backward(tape, u.k), with the output \(u = ab\) on line \(3\). Which lines have adjoint \(0\), and which of them does the sweep still process? Compare the result with the first row of the Jacobian in Section 4.5.The depth-first search of Section 4.8 starts from the node of the output. Which nodes does it visit for \(L\), and for \(u\)?
Exercise 4.4 Build the graph of Table 3.1 from the nodes of Section 4.8 as v3 = Node("v3", v1), v4 = Node("v4", v3, v2), v5 = Node("v5", v1, v2), v6 = Node("v6", v5) and v7 = Node("v7", v4, v6), with v1 = Node("v1") and v2 = Node("v2"). Find the list that topological_order(v7) returns, and check that it is a topological order.
Exercise 4.5 Let \(f(x, y) = (xy,\; x + y,\; x^2)\) and \(\mathbf{w} = (1, -1, 2)\). Compute \(\mathbf{w}^\top J_f(1, 2)\) from the Jacobian, and again by a reverse sweep on a trace of \(f\) with the outputs seeded by \(\mathbf{w}\).
Exercise 4.6 Let \(f = f_3 \circ f_2 \circ f_1\) with \(f_1\colon\mathbb{R}^n \to \mathbb{R}^p\), \(f_2\colon\mathbb{R}^p\to\mathbb{R}^p\) and \(f_3\colon\mathbb{R}^p\to\mathbb{R}\), so that \(J_f = J_3J_2J_1\) by Theorem 2.1. Multiplying an \(a\times b\) matrix by a \(b\times c\) matrix takes \(abc\) multiplications. Count the multiplications needed to form \(J_f\) as \(J_3(J_2J_1)\) and as \((J_3J_2)J_1\), and evaluate both for \(n = p = 1000\). Which order corresponds to forward mode, and which to reverse mode?
Exercise 4.7 Let \(f(\mathbf{x}) = x_1x_2\cdots x_n\), computed by the trace \(p_2 = x_1x_2\), \(p_k = p_{k-1}x_k\) for \(k = 3, \dots, n\).
Write out the reverse sweep and show that it computes \(\nabla f(\mathbf{x})\) with \(2(n-1)\) multiplications.
How many multiplications does it take to compute each partial derivative \(\prod_{j\ne i}x_j\) separately, and how many does forward mode take?
Exercise 4.8 Let \(u_0 = 2x\), \(w_0 = 3x\), and for \(i = 1, \dots, k\) let \(u_i = u_{i-1}w_{i-1}\) and \(w_i = u_{i-1} + w_{i-1}\). Let \(L = u_k + w_k\).
Show that the computational graph has \(2^{k+1}\) paths from \(x\) to \(L\).
Show that step 3 of the reverse sweep updates an accumulator \(4k + 4\) times, once for each edge of the graph.
Exercise 4.9 Reverse mode differentiates a chain of \(T\) steps with checkpoints every \(K\) steps, as in Section 4.6.
For \(T = 10\,000\), find the \(K\) that minimises \(T/K + K\) and the number of states stored.
Inside each segment of length \(K_1\), store every \(K_2\)th state during the recomputation, and recompute the sub-segments from these. Show that the method stores at most about \(T/K_1 + K_1/K_2 + K_2\) states at once, that the recomputation adds at most two forward passes, and that \(K_1 = T^{2/3}\), \(K_2 = T^{1/3}\) give about \(3T^{1/3}\) states.
Exercise 4.10 Add a primitive operation tanh to the engine of Section 4.7, using \(\frac{d}{dt}\tanh t = 1 - \tanh^2 t\). Prove this formula from \(\tanh t = (e^t - e^{-t})/(e^t + e^{-t})\), and use the engine to find the gradient of \(\tanh(xy)\) at \((0.5, -1)\). How many lines would the tape of \(\tanh(xy)\) have if tanh were derived from exp by the formula above instead, with \(e^t\) and \(e^{-t}\) each computed once?