Module contents
Lesson 15 of 26Core 120 min

Automatic differentiation II: reverse mode and general backpropagation

Reverse mode computes the full gradient of a scalar function at a cost comparable to evaluating it, making it possible to train models with billions of parameters or calibrate simulations with thousands. Build a tape-based reverse engine for arbitrary scientific programs, verify it with the dot-product test against forward mode, and apply it to a simulation gradient before comparing it with torch.autograd. The tensor engine for neural networks is built in m15.

After this lesson you can

  • Run a trace's backward pass by hand, propagating adjoints and accumulating them at nodes with multiple consumers.
  • Implement a tape-based reverse engine that differentiates programs with loops and branches.
  • Verify adjoints with the dot-product test and a gradient checker.
  • Explain the cheap gradient principle and reverse mode's memory cost.
  • Compute a simulation's gradient with respect to hundreds of parameters in one pass and compare its cost with forward mode and finite differences.

Before you start

Motivation: the gradient of something enormous

Training a model means following the gradient of a scalar loss L(θ)\Loss(\theta) with respect to all its parameters. If θ\theta has 10910^9 components, the three tools you know fail for the same reason: finite differences need one or two evaluations of L\Loss per component, and forward mode from the previous lesson, although exact, gives one directional derivative per pass. Both require on the order of 10910^9 evaluations for a single gradient. The same happens outside machine learning: calibrating a heat simulation with a different conductivity in each of 500 cells, or calculating a portfolio’s sensitivity to each point on an interest-rate curve, involves gradients of a scalar function with respect to hundreds or thousands of inputs.

Reverse mode solves the problem with a simple idea: instead of pushing a tangent from inputs to output, it pulls backward from the output its sensitivity to each intermediate variable. A single backward pass produces all partial derivatives at once, at a cost that is a small multiple of evaluating the function, regardless of the number of inputs. This is the algorithm behind loss.backward() and backpropagation in neural networks, but it is much more general: it differentiates any program, with loops, branches and integrators, and therefore works for a simulation as well as a network.

The price is memory: to traverse the computation backward you must remember what happened forward. This lesson builds the method by hand, proves why it works and what it costs, builds a tape-based engine that differentiates arbitrary scientific programs, verifies it with the dot-product test and uses it to calibrate that simulation with 500 conductivities. Finally you will compare your engine with torch.autograd, which does exactly the same thing at industrial scale. The tensor engine for networks, with matmul, broadcasting and reduction rules, is built in the tensor autograd engine.

By hand: the backward pass over a trace

Return to the function from the previous lesson, the example from Baydin et al., at (x1,x2)=(2,5)(x_1, x_2) = (2, 5):

f(x1,x2)=ln⁡x1+x1x2−sin⁡x2.f(x_1, x_2) = \ln x_1 + x_1 x_2 - \sin x_2 .

Its evaluation trace has two inputs, v−1=x1v_{-1} = x_1 and v0=x2v_0 = x_2, and five elementary instructions. The forward pass executes them in order and stores each value:

InstructionValue at (2,5)(2, 5)
v1=ln⁡v−1v_1 = \ln v_{-1}0.69310.6931
v2=v−1v0v_2 = v_{-1} v_01010
v3=sin⁡v0v_3 = \sin v_0−0.9589-0.9589
v4=v1+v2v_4 = v_1 + v_210.693110.6931
v5=v4−v3v_5 = v_4 - v_311.6521=y11.6521 = y

Now define, for each variable, its adjoint vˉi=∂y/∂vi\bar v_i = \partial y / \partial v_i: how much the output changes if you perturb viv_i and let the rest of the program run unchanged. At the output, vˉ5=∂y/∂y=1\bar v_5 = \partial y/\partial y = 1. Going backward, each instruction vk=φ(vi,vj)v_k = \varphi(v_i, v_j) distributes its adjoint among its arguments by multiplying it by the local partial derivative, vˉk ∂vk/∂vi\bar v_k \,\partial v_k/\partial v_i:

  • v5=v4−v3v_5 = v_4 - v_3 sends vˉ5⋅1=1\bar v_5 \cdot 1 = 1 to v4v_4 and vˉ5⋅(−1)=−1\bar v_5 \cdot (-1) = -1 to v3v_3.
  • v4=v1+v2v_4 = v_1 + v_2 sends 11 to v1v_1 and 11 to v2v_2.
  • v3=sin⁡v0v_3 = \sin v_0 sends vˉ3cos⁡v0=−cos⁡5=−0.2837\bar v_3 \cos v_0 = -\cos 5 = -0.2837 to v0v_0.
  • v2=v−1v0v_2 = v_{-1} v_0 sends vˉ2 v0=5\bar v_2\, v_0 = 5 to v−1v_{-1} and vˉ2 v−1=2\bar v_2\, v_{-1} = 2 to v0v_0.
  • v1=ln⁡v−1v_1 = \ln v_{-1} sends vˉ1/v−1=0.5\bar v_1 / v_{-1} = 0.5 to v−1v_{-1}.

Notice the inputs: x1x_1 is used by two instructions (v1v_1 and v2v_2), and x2x_2 by two others (v2v_2 and v3v_3). Each receives two contributions, and its adjoint is their sum: xˉ1=5+0.5=5.5\bar x_1 = 5 + 0.5 = 5.5 and xˉ2=−0.2837+2=1.7163\bar x_2 = -0.2837 + 2 = 1.7163. These are exactly ∂f/∂x1=1/x1+x2\partial f/\partial x_1 = 1/x_1 + x_2 and ∂f/∂x2=x1−cos⁡x2\partial f/\partial x_2 = x_1 - \cos x_2. One forward and one backward pass have produced the entire gradient; forward mode would have needed two passes, one per input.

InteractiveThe backward pass step by step
x₁v₋₁ ·22.000x₂v₀ ·25.000lnv₁×v₂sinv₃+v₄−v₅
Below each node, its value (blue) and adjoint (violet). “·2” marks a variable with two consumers and “(1/2)” shows how many contributions have arrived.
VariableValueAdjoint vˉ\bar v
v5=v4−v3v_{5} = v_{4} - v_{3}·vˉ5=yˉ=1\bar v_{5} = \bar y = 1·
v4=v1+v2v_{4} = v_{1} + v_{2}·vˉ4=vˉ5\bar v_{4} = \bar v_{5}·
v3=sin⁡v0v_{3} = \sin v_{0}·vˉ3=−vˉ5\bar v_{3} = -\bar v_{5}·
v2=v−1⋅v0v_{2} = v_{-1} \cdot v_{0}·vˉ2=vˉ4\bar v_{2} = \bar v_{4}·
v1=ln⁡v−1v_{1} = \ln v_{-1}·vˉ1=vˉ4\bar v_{1} = \bar v_{4}·
v0=x2v_{0} = x_25.0000vˉ0=vˉ3 (cos⁡v0)+vˉ2 v−1\bar v_{0} = \bar v_{3}\,(\cos v_{0}) + \bar v_{2}\,v_{-1}·
v−1=x1v_{-1} = x_12.0000vˉ−1=vˉ2 v0+vˉ1 (1/v−1)\bar v_{-1} = \bar v_{2}\,v_{0} + \bar v_{1}\,(1/v_{-1})·
Function and point
2.0
5.0
inputs
Phaseforward (values stored)
xˉ1=∂f/∂x1\bar x_1 = \partial f/\partial x_1…
xˉ2=∂f/∂x2\bar x_2 = \partial f/\partial x_2…
Central differences, h=10−6h = 10^{-6}5.500000, 1.716338
First the forward pass fills in the values (blue). Then the backward pass traverses the trace in reverse: each instruction sends its arguments the contribution vˉk ∂vk/∂vi\bar v_k\,\partial v_k/\partial v_i (purple arrows). The initial state is halfway through the pass: x2x_2 (v0v_0) has already received both contributions and x1x_1 (v−1v_{-1}) only one of two. Advance one step and see how it is completed. Try the shared subexpression: how many contributions does the x1x2x_1 x_2 node receive? The readouts compare the gradient with centered differences.

Two details of the procedure are key to everything that follows. Order matters: a variable can send its adjoint only when it has received it in full, that is, when all instructions that consume it have been processed. Traversing the trace backward guarantees this, because a variable’s consumers always follow it in the trace. And the forward-pass values are needed: the contribution from v3=sin⁡v0v_3 = \sin v_0 uses cos⁡v0\cos v_0, that from v2=v−1v0v_2 = v_{-1}v_0 uses v−1v_{-1} and v0v_0, and that from v1=ln⁡v−1v_1 = \ln v_{-1} uses v−1v_{-1}. This is the source of reverse mode’s memory cost.

Why it works: the chain rule backward

The informal definition “∂y/∂vi\partial y/\partial v_i letting the rest of the program execute” needs precision, because viv_i is not an input of ff: it is an intermediate value that depends on others. The clean approach is to look at the program from each point in the trace to the end.

A straight-line program (loops and branches are unfolded in the particular execution) with inputs v1−n,…,v0v_{1-n}, \dots, v_0 executes ℓ\ell instructions vi=φi(ui)v_i = \varphi_i(\vb{u}_i), i=1,…,ℓi = 1, \dots, \ell, where ui=(vj)j≺i\vb{u}_i = (v_j)_{j \prec i} are its arguments and j≺ij \prec i implies j<ij < i. The output is y=vℓy = v_\ell. For each i∈{0,…,ℓ}i \in \{0, \dots, \ell\}, call Yi(v1−n,…,vi)Y_i(v_{1-n}, \dots, v_i) the result of executing instructions i+1,…,ℓi + 1, \dots, \ell starting from arbitrary values of v1−n,…,viv_{1-n}, \dots, v_i, treated as independent variables. Thus Yℓ(v1−n,…,vℓ)=vℓY_\ell(v_{1-n}, \dots, v_\ell) = v_\ell and Y0=fY_0 = f, and executing instruction ii relates two consecutive functions:

Yi−1(v1−n,…,vi−1)=Yi(v1−n,…,vi−1,φi(ui)).Y_{i-1}(v_{1-n}, \dots, v_{i-1}) = Y_i\big(v_{1-n}, \dots, v_{i-1}, \varphi_i(\vb{u}_i)\big).
Proof

Call the accumulators wjw_j. We prove the invariant by descending induction: after processing instruction ii (or at the start, with i=ℓ+1i = \ell + 1), wj=yˉ ∂Yi−1/∂vjw_j = \bar y\,\partial Y_{i-1}/\partial v_j for every j≤i−1j \le i - 1.

At the start, wℓ=yˉw_\ell = \bar y and wj=0w_j = 0 for j<ℓj < \ell, which are the derivatives of yˉ Yℓ=yˉ vℓ\bar y\,Y_\ell = \bar y\,v_\ell. Suppose the invariant holds after processing i+1i + 1, that is, wj=yˉ ∂Yi/∂vjw_j = \bar y\,\partial Y_i/\partial v_j for j≤ij \le i. Differentiate the relation Yi−1(v≤i−1)=Yi(v≤i−1,φi(ui))Y_{i-1}(v_{\le i-1}) = Y_i(v_{\le i-1}, \varphi_i(\vb{u}_i)) with respect to vjv_j, j≤i−1j \le i - 1, using the chain rule: vjv_j appears directly as an argument of YiY_i and, if j≺ij \prec i, also inside φi\varphi_i, so

∂Yi−1∂vj=∂Yi∂vj+∂Yi∂vi ∂φi∂vj,\frac{\partial Y_{i-1}}{\partial v_j} = \frac{\partial Y_i}{\partial v_j} + \frac{\partial Y_i}{\partial v_i}\,\frac{\partial \varphi_i}{\partial v_j},

where the second term is zero if j⊀ij \nprec i. Multiplied by yˉ\bar y, the first term is the current value of wjw_j and the second is exactly what instruction ii adds, because wi=yˉ ∂Yi/∂viw_i = \bar y\,\partial Y_i/\partial v_i. After processing ii the invariant holds for i−1i - 1. Moreover, the instructions still to process have index smaller than ii, and their arguments have index smaller than theirs, so none touches wiw_i again: its value when processing ii was final, yˉ vˉi\bar y\,\bar v_i. At the end (i=1i = 1), wj=yˉ ∂Y0/∂vj=yˉ ∂f/∂xjw_j = \bar y\,\partial Y_0/\partial v_j = \bar y\,\partial f/\partial x_j for the inputs.

∎

The proof explains the algorithm’s two pieces. += is not an implementation detail: it is the already accumulated term ∂Yi/∂vj\partial Y_i/\partial v_j plus the new path opened by instruction ii. A variable with multiple consumers receives a contribution from each, and its derivative is the sum over all paths, as in the chain rule for multivariable functions. And reverse order ensures that wiw_i is complete when used.

The VJP as a unit and duality with the JVP

Group instructions into larger blocks, such as network layers or integrator steps: f=FL∘⋯∘F1f = F_L \circ \cdots \circ F_1 with zk=Fk(zk−1)\vb{z}_k = F_k(\vb{z}_{k-1}). By the chain rule, the Jacobian is a product of block Jacobians, J=JLJL−1⋯J1\mat{J} = \mat{J}_L \mat{J}_{L-1} \cdots \mat{J}_1 with Jk=Fk′(zk−1)\mat{J}_k = F_k'(\vb{z}_{k-1}). The two modes are the two ways to multiply that chain by a vector without ever forming a matrix:

Ju=JL(⋯(J2(J1u)))⏟forward: de derecha a izquierdayˉ⊤J=(((yˉ⊤JL)JL−1)⋯)J1⏟reverse: de izquierda a derecha.\underbrace{\mat{J}\vb{u} = \mat{J}_L\big(\cdots\big(\mat{J}_2(\mat{J}_1\vb{u})\big)\big)}_{\text{forward: de derecha a izquierda}} \qquad \underbrace{\bar{\vb{y}}\T\mat{J} = \big(\big((\bar{\vb{y}}\T\mat{J}_L)\mat{J}_{L-1}\big)\cdots\big)\mat{J}_1}_{\text{reverse: de izquierda a derecha}} .

Forward mode propagates a tangent in the same order as the computation, so it needs to remember nothing. Reverse mode starts at the end, so it needs the zk−1\vb{z}_{k-1} at which to evaluate each Jk\mat{J}_k: that is why the forward pass comes first. Each reverse-mode factor is a vector–Jacobian product (VJP), zˉk−1=Jk⊤zˉk\bar{\vb{z}}_{k-1} = \mat{J}_k\T\bar{\vb{z}}_k, the unit from which every reverse engine is built: each operation knows how to compute its output and, given the output adjoint, its input adjoints. Some rules you will use:

OperationVJP: contribution to each input
y=a+b\vb{y} = \vb{a} + \vb{b}aˉ+=yˉ\bar{\vb{a}} \mathrel{+}= \bar{\vb{y}},  bˉ+=yˉ\ \bar{\vb{b}} \mathrel{+}= \bar{\vb{y}}
y=a⊙b\vb{y} = \vb{a} \odot \vb{b} (elementwise)aˉ+=yˉ⊙b\bar{\vb{a}} \mathrel{+}= \bar{\vb{y}} \odot \vb{b},  bˉ+=yˉ⊙a\ \bar{\vb{b}} \mathrel{+}= \bar{\vb{y}} \odot \vb{a}
y=a/b\vb{y} = \vb{a} / \vb{b}aˉ+=yˉ/b\bar{\vb{a}} \mathrel{+}= \bar{\vb{y}} / \vb{b},  bˉ−=yˉ⊙y/b\ \bar{\vb{b}} \mathrel{-}= \bar{\vb{y}} \odot \vb{y} / \vb{b}
y=exp⁡a\vb{y} = \exp\vb{a}aˉ+=yˉ⊙y\bar{\vb{a}} \mathrel{+}= \bar{\vb{y}} \odot \vb{y} (save the output, not the input)
y=Ax\vb{y} = \mat{A}\vb{x}xˉ+=A⊤yˉ\bar{\vb{x}} \mathrel{+}= \mat{A}\T\bar{\vb{y}},  Aˉ+=yˉx⊤\ \bar{\mat{A}} \mathrel{+}= \bar{\vb{y}}\vb{x}\T
y=a[idx]\vb{y} = \vb{a}[\text{idx}] (read positions)aˉ[idx]+=yˉ\bar{\vb{a}}[\text{idx}] \mathrel{+}= \bar{\vb{y}} (write to those positions)
s=∑iais = \sum_i a_iaˉ+=sˉ 1\bar{\vb{a}} \mathrel{+}= \bar s\,\vb{1}

The table shows a symmetry that is no coincidence: what reads forward writes backward, and what copies or broadcasts forward sums backward. This is transposition: if a linear operation is y=Mx\vb{y} = \mat{M}\vb{x}, its VJP is M⊤\mat{M}\T, and reading a subset of positions is a matrix of zeros and ones whose transpose writes them. The relationship between the two products is the identity defining the transpose,

⟨yˉ,Ju⟩=⟨J⊤yˉ,u⟩para todos u∈Rn, yˉ∈Rm,\inner{\bar{\vb{y}}}{\mat{J}\vb{u}} = \inner{\mat{J}\T\bar{\vb{y}}}{\vb{u}} \quad \text{para todos } \vb{u} \in \R^n,\ \bar{\vb{y}} \in \R^m ,

which will be the basis of verification later.

Cost of the full Jacobian

One forward pass gives a Jacobian column (Jej\mat{J}\vb{e}_j) and one reverse pass gives a row (ei⊤J\vb{e}_i\T\mat{J}). If each pass costs cc times an evaluation of ff, the Jacobian of f:Rn→Rmf: \R^n \to \R^m costs n cn\,c evaluations in forward mode and m cm\,c in reverse. Baydin et al. give exactly these two expressions, with a constant “guaranteed c<6c < 6 and typically c∼[2,3]c \sim [2, 3]”. For a scalar loss, m=1m = 1: the full gradient costs cc evaluations, regardless of nn. The actual constants for each mode depend on implementation, but move the crossover point by a small factor, while n/mn/m varies over many orders of magnitude.

InteractiveForward or reverse?
Jacobian time (f evaluations, log scale)forward3.0·10⁹reverse3.0Memory (multiples of live memory M for f)forward2.0reverse801110³10⁶10⁹
  • forward mode
  • reverse mode
Dimensions
1.0·10⁹
1.0
Memory
800
Forward: nn passes3.0·10⁹ f evals.
Reverse: mm passes3.0 f evals.
Forward / reverse1.0·10⁹
Forward memory2 M
Reverse memory801 M
Reverse wins by a factor of 1.0·10⁹: the full gradient costs as much as a few evaluations of ff, whatever nn. In exchange, the tape occupies 800 times the live memory of ff.
Each point in the plane is a function f:Rn→Rmf: \R^n \to \R^m (logarithmic scales). In the model, the Jacobian costs 3n3n evaluations of ff in forward mode and 3m3m in reverse, and memory is twice that of ff in forward and 1+r1 + r times in reverse, where rr measures the tape's size (in the heat lab, r≈800r \approx 800). Start with a network loss and drag the point toward the square layer and the trajectory with 3 parameters: when does reverse memory stop paying off?

The figure summarizes the rule of thumb: reverse for few outputs and many inputs (losses, calibration, portfolio Greeks), forward for few inputs and many outputs (the sensitivity of an entire trajectory to three parameters, the JVP of a Newton–Krylov method), and for intermediate cases, memory or Jacobian structure decides. The next lesson, on strategies for computing Jacobians, combines the two modes and exploits sparsity.

The tape and topological order

A reverse engine needs to know which operations were executed, with which arguments and in what order. The most direct way is to record them as they happen.

Why is it topological? Because an operation can execute only when its inputs already exist: each edge j→ij \to i of the graph goes from an operation recorded earlier to one recorded later. Reverse traversal then processes each variable after all its consumers, exactly the condition required by the proof. This has three practical consequences.

  • Loops and branches for free. The tape does not see for or if: it sees the operations that executed. A Newton loop that stops when the residual is small is recorded with however many iterations it performed, and a branch is recorded on the side taken. The derivative is that of the executed program, not the mathematical function the program approximates (you will see this again with iterative solvers in the next lesson).
  • Freeing on the fly. Once an operation is processed backward, its saved values and output adjoint are no longer needed and can be freed. PyTorch does this by default: that is why a second backward() on the same graph fails unless you pass retain_graph=True.
  • No recursion. An engine that does not store the tape and knows only each node’s parents must reconstruct the order with a depth-first search. Written recursively, it overflows the stack when the computation is long; you will check this in the lab with a chain of 5000 operations.

The cheap gradient principle

Exactly how much does the backward pass cost? The answer is one of the most important results in scientific computing, and it is proved by counting.

This is the cheap gradient principle. The proof counts the algorithm’s operations and you will reconstruct it step by step in a guided exercise: the forward pass costs C(f)C(f); the backward pass visits each tape instruction only once and executes its VJP rule, costing at most ω ci\omega\,c_i; and additions to accumulators are already included in that cost. nn appears nowhere: the nn input adjoints are accumulators filled along the way.

What is ω\omega? With the four arithmetic operations and cost 1 per operation:

  • y=a+by = a + b: the VJP makes two accumulator additions, aˉ+=yˉ\bar a \mathrel{+}= \bar y and bˉ+=yˉ\bar b \mathrel{+}= \bar y. Cost 2.
  • y=a by = a\,b: two products (yˉ b\bar y\,b and yˉ a\bar y\,a) and two additions. Cost 4.
  • y=a/by = a / b: with t=yˉ/bt = \bar y / b, aˉ+=t\bar a \mathrel{+}= t and bˉ−=t y\bar b \mathrel{-}= t\,y. One division, one product and two additions: cost 4.

Thus ω=4\omega = 4 and the gradient costs at most 5 C(f)5\,C(f). This is the Baur–Strassen bound (1983): if an arithmetic circuit of size ss computes ff, one of size at most 5s5s exists that computes ff and all its partial derivatives. They used it for a very different purpose, proving lower bounds on algebraic complexity: since the gradient costs the same as the function up to a constant, a lower bound for computing all partials is also one for ff. Elementary functions do not change the picture: the VJP of sin⁡a\sin a needs cos⁡a\cos a, which costs the same as sine, plus a product and an addition.

Memory: what must be saved

Reverse mode has traded time for memory. The backward pass processes the last operation first, by which time the forward pass has finished: every value needed by a VJP rule must have been saved. In a computation of TT steps with a state of size ss (simulation steps, network layers), the tape stores on the order of T⋅sT\cdot s numbers, while forward mode needs only the current state’s tangent, on the order of ss.

An example gives the scale. A simulation of 10510^5 steps with a state of 10610^6 float64 numbers that saves the state at each step needs 105⋅106⋅810^5 \cdot 10^6 \cdot 8 bytes: 800 GB, when the simulation itself fits in 8 MB. In a network, the activations of each layer for each batch example are saved, and they often dominate training memory.

The classic solution is to save only some states (checkpoints) and recompute the others from the nearest checkpoint when the backward pass needs them. The figure shows this tradeoff.

InteractiveMemory over an iteration
0917time (1 = one forward layer) →0activations in memory
  • forward
  • recomputation
  • backward
  • store everything (k = 1)
The tradeoff for L=16L = 16: peak memory and cost relative to storing everything, versus kk
  • peak memory / peak with k = 1
  • cost / cost with k = 1
Network and checkpoints
16
4
start
Peak memory (activations)8 (storing all: 17)
Recomputed layers12 of 16
Iteration cost60 = 16 + 12 + 32 (+25 %)
Phase·
With checkpoints every 4 layers, peak memory falls from 17 to 8 (47 %) in exchange for recomputing 12 layers (25 % more compute). The minimum peak, 8, is reached between k=3k = 3 and k=6k = 6, around L=4.0\sqrt{L} = 4.0.
Model of an iteration of an LL-layer network: each layer costs 1 forward and 2 backward, and each activation occupies one unit. With k=1k = 1 all are saved: memory rises to L+1L + 1 and falls during backpropagation (dashed line). With checkpoints every kk layers, each segment is recomputed (orange) just before backpropagating through it. Play the iteration with k=4k = 4, then find the kk that minimizes the peak: how does it relate to L\sqrt{L}, and how much extra computation does it cost? The graph below shows the full tradeoff for each kk.

In the model, with checkpoints every kk layers about L/kL/k activations are saved during the forward pass and, when processing a segment, at most another kk. The peak is on the order of L/k+kL/k + k, minimal at k≈Lk \approx \sqrt{L}, with value on the order of 2L2\sqrt{L}, and the price is recomputing L−⌈L/k⌉L - \lceil L/k\rceil layers: less than an additional forward pass, at most 33% more over the cost 1+21 + 2 per layer. This is the result of Chen et al. (2016), Training Deep Nets with Sublinear Memory Cost: O(n)\bigO(\sqrt{n}) memory for an nn-layer network in exchange for an extra forward pass per batch; in their experiment, a 1000-layer residual network went from 48 GB to 7 GB with 30% more time. Optimal multilevel strategies, Griewank’s binomial checkpointing, are the subject of the next lesson, and their use at scale, with activation checkpointing and ZeRO sharding, belongs to distributed training systems.

Verifying adjoints: the dot-product test

A reverse engine is only as reliable as its VJP rules, and a handwritten VJP rule is easy to get wrong: a transposed factor, a sign, an index. The gradient checker from lesson 13 compares against finite differences, but only distinguishes errors larger than its own truncation error, on the order of 10−1010^{-10} in the best case and 10−610^{-6} as a reasonable threshold. There is a much finer test that does not use finite differences and reaches rounding level.

Why do random vectors suffice? Because a−b=yˉ⊤(J−B⊤)ua - b = \bar{\vb{y}}\T(\mat{J} - \mat{B}\T)\vb{u} is a bilinear form in (u,yˉ)(\vb{u}, \bar{\vb{y}}). If B≠J⊤\mat{B} \ne \mat{J}\T, the matrix D=J−B⊤\mat{D} = \mat{J} - \mat{B}\T is nonzero and the polynomial yˉ⊤Du\bar{\vb{y}}\T\mat{D}\vb{u} is not identically zero; its zero set is a proper algebraic subset of Rm×Rn\R^{m} \times \R^{n}, which has Lebesgue measure zero. With Gaussian u\vb{u} and yˉ\bar{\vb{y}}, an error in the VJP produces a≠ba \ne b with probability 1. The discrepancy’s size is informative: a factor-of-2 error gives b=2ab = 2a in every trial; a sign, b=−ab = -a; a transpose, a cloud unrelated to the diagonal.

InteractiveThe dot-product test bench
Relative discrepancy |a − b| / max(|a|, |b|) for each trial (log scale)
roundingu = 2⁻⁵³10⁻¹⁶10⁻¹²10⁻⁸10⁻⁴1
  • trial: (a,b)=(⟨yˉ,Ju⟩, ⟨VJP(yˉ),u⟩)(a, b) = (\langle\bar{\vb{y}}, \mat{J}\vb{u}\rangle,\ \langle \text{VJP}(\bar{\vb{y}}), \vb{u}\rangle)
  • diagonal b=ab = a
Trials
20
Maximum relative discrepancy1.824
Slope of bb versus aa0.1827
Correlation0.1977
A cloud with no clear relationship to the diagonal (correlation 0.20): the VJP implements another linear map, not J⊤\mat{J}\T.
Choose an operation and break its VJP with a typical error. Each point is a trial with Gaussian vectors: its horizontal coordinate is ⟨yˉ,Ju⟩\inner{\bar{\vb{y}}}{\mat{J}\vb{u}}, computed with the JVP, and its vertical coordinate is ⟨VJP(yˉ),u⟩\inner{\text{VJP}(\bar{\vb{y}})}{\vb{u}}. Below is each trial's relative discrepancy on a logarithmic scale, with unit roundoff. The initial state has a forgotten transpose in multiplication by a matrix: look at the cloud, then choose the correct VJP. Also try the RK4 step using the first stage's Jacobian in all four and reduce the step hh: why does that error become small but never drop to 10−1610^{-16}?

The RK4 step deserves a closer look. A step zn+1=zn+h6(k1+2k2+2k3+k4)\vb{z}_{n+1} = \vb{z}_n + \tfrac{h}{6}(\vb{k}_1 + 2\vb{k}_2 + 2\vb{k}_3 + \vb{k}_4) of a Runge–Kutta method is a small trace: k1=f(zn)\vb{k}_1 = f(\vb{z}_n), k2=f(zn+h2k1)\vb{k}_2 = f(\vb{z}_n + \tfrac{h}{2}\vb{k}_1), and so on. Its VJP traverses the stages backward: it starts with kˉ1=kˉ4=h6zˉn+1\bar{\vb{k}}_1 = \bar{\vb{k}}_4 = \tfrac{h}{6}\bar{\vb{z}}_{n+1} and kˉ2=kˉ3=h3zˉn+1\bar{\vb{k}}_2 = \bar{\vb{k}}_3 = \tfrac{h}{3}\bar{\vb{z}}_{n+1}, and each stage ks=f(ys)\vb{k}_s = f(\vb{y}_s) applies f′(ys)⊤f'(\vb{y}_s)\T to its adjoint and distributes it between zˉn\bar{\vb{z}}_n and the previous stage’s adjoint, with the same weight with which the previous stage entered ys\vb{y}_s. Using f′(zn)f'(\vb{z}_n) in all four stages instead of f′(ys)f'(\vb{y}_s) is an error that hides well: the difference between Jacobians is of order hh, so the resulting discrepancy decreases when reducing the step (check it on the bench by moving hh), but stays many orders of magnitude above rounding. A gradient with that error “looks like” the correct one and an optimization may even converge with it; the dot-product test distinguishes it unambiguously.

Lab 1: a tape-based reverse engine

The engine has four pieces: a class Var that wraps a value (a float or NumPy array, elementwise) and its adjoint; an active Cinta on which each operation records itself when executed; each operation’s VJP rules, which receive the output adjoint and saved values and return a contribution per input; and retropropaga, which traverses the tape backward accumulating. Each operation explicitly declares what it saves (guardado), so you can measure tape memory and free it when processing each record.

[ ]A tape-based reverse engineBrowser
import numpy as np

class Cinta:
    """Lista de Wengert: cada operación sobre Var se apunta aquí en orden de ejecución."""
    activa = None

    def __init__(self):
        self.registros = []

    def __enter__(self):
        Cinta.activa = self
        return self

    def __exit__(self, *exc):
        Cinta.activa = None

    def bytes_guardados(self):
        return sum(np.asarray(g).nbytes for r in self.registros if r.guardado for g in r.guardado)


class Registro:
    __slots__ = ("salida", "entradas", "vjp", "guardado")

    def __init__(self, salida, entradas, vjp, guardado):
        self.salida, self.entradas, self.vjp, self.guardado = salida, entradas, vjp, guardado


def _ajusta(g, forma):
    """Deshace el broadcasting: suma g sobre los ejes que la operación estiró."""
    g = np.asarray(g)
    while g.ndim > len(forma):
        g = g.sum(axis=0)
    for i, n in enumerate(forma):
        if n == 1 and g.shape[i] != 1:
            g = g.sum(axis=i, keepdims=True)
    return g


class Var:
    """Valor (escalar o array) que apunta en la cinta activa las operaciones que lo usan."""
    __array_priority__ = 1000          # para que ndarray * Var llame a Var.__rmul__

    def __init__(self, valor):
        self.valor = valor if isinstance(valor, np.ndarray) else float(valor)
        self.adj = None                # adjunto: ∂(salida)/∂(esta variable), se rellena hacia atrás

    @property
    def forma(self):
        return np.shape(self.valor)

    def __repr__(self):
        return f"Var({self.valor})"


def _v(x):
    return x if isinstance(x, Var) else Var(x)


def _op(valor, entradas, vjp, guardado=()):
    """Crea la salida de una operación y la apunta en la cinta (si hay una activa)."""
    out = Var(valor)
    if Cinta.activa is not None:
        Cinta.activa.registros.append(Registro(out, entradas, vjp, guardado))
    return out


# --- reglas VJP: reciben el adjunto de la salida g y lo guardado; devuelven una contribución por entrada ---
def suma(a, b):
    a, b = _v(a), _v(b)
    fa, fb = a.forma, b.forma
    return _op(a.valor + b.valor, (a, b), lambda g: (_ajusta(g, fa), _ajusta(g, fb)))

def resta(a, b):
    a, b = _v(a), _v(b)
    fa, fb = a.forma, b.forma
    return _op(a.valor - b.valor, (a, b), lambda g: (_ajusta(g, fa), _ajusta(-g, fb)))

def producto(a, b):
    a, b = _v(a), _v(b)
    fa, fb = a.forma, b.forma
    return _op(a.valor * b.valor, (a, b),
               lambda g, av, bv: (_ajusta(g * bv, fa), _ajusta(g * av, fb)), (a.valor, b.valor))

def cociente(a, b):
    a, b = _v(a), _v(b)
    fa, fb = a.forma, b.forma
    y = a.valor / b.valor
    return _op(y, (a, b), lambda g, bv, yv: (_ajusta(g / bv, fa), _ajusta(-g * yv / bv, fb)), (b.valor, y))

def potencia(a, p):                          # exponente constante
    return _op(a.valor ** p, (a,), lambda g, av: (g * p * av ** (p - 1),), (a.valor,))

def _unaria(f, df_de):
    """df_de(x, y) da f'(x) a partir de la entrada x y la salida y = f(x)."""
    def op(a):
        if not isinstance(a, Var):
            return f(a)
        y = f(a.valor)
        return _op(y, (a,), lambda g, av, yv: (g * df_de(av, yv),), (a.valor, y))
    return op

exp = _unaria(np.exp, lambda x, y: y)
log = _unaria(np.log, lambda x, y: 1 / x)
sin = _unaria(np.sin, lambda x, y: np.cos(x))
cos = _unaria(np.cos, lambda x, y: -np.sin(x))
tanh = _unaria(np.tanh, lambda x, y: 1 - y * y)
sqrt = _unaria(np.sqrt, lambda x, y: 0.5 / y)

def recorta(a, idx):                         # a[idx]: lineal, su VJP reparte g en las posiciones leídas
    forma = a.forma
    def vjp(g):
        z = np.zeros(forma)
        np.add.at(z, idx, g)
        return (z,)
    return _op(a.valor[idx], (a,), vjp)

def concatena(partes):
    partes = [_v(p) for p in partes]
    cortes = np.cumsum([np.size(p.valor) for p in partes])[:-1]
    return _op(np.concatenate([np.atleast_1d(p.valor) for p in partes]), tuple(partes),
               lambda g: tuple(s.reshape(p.forma) for s, p in zip(np.split(g, cortes), partes)))

def total(a):                                 # suma de todas las componentes
    forma = a.forma
    return _op(np.sum(a.valor), (a,), lambda g: (np.broadcast_to(g, forma).copy(),))

Var.__add__ = lambda a, b: suma(a, b)
Var.__radd__ = lambda a, b: suma(b, a)
Var.__sub__ = lambda a, b: resta(a, b)
Var.__rsub__ = lambda a, b: resta(b, a)
Var.__mul__ = lambda a, b: producto(a, b)
Var.__rmul__ = lambda a, b: producto(b, a)
Var.__truediv__ = lambda a, b: cociente(a, b)
Var.__rtruediv__ = lambda a, b: cociente(b, a)
Var.__neg__ = lambda a: producto(a, -1.0)
Var.__pow__ = lambda a, p: potencia(a, p)
Var.__getitem__ = lambda a, idx: recorta(a, idx)


def retropropaga(cinta, salidas, semillas=None, liberar=True):
    """Pasada hacia atrás: recorre la cinta al revés (orden topológico inverso) acumulando adjuntos."""
    salidas = salidas if isinstance(salidas, (list, tuple)) else [salidas]
    semillas = semillas if semillas is not None else [np.ones_like(s.valor) for s in salidas]
    for s, sb in zip(salidas, semillas):
        s.adj = sb if s.adj is None else s.adj + sb
    for r in reversed(cinta.registros):
        if r.salida.adj is None:           # esta operación no influye en las salidas
            continue
        contribuciones = r.vjp(r.salida.adj, *r.guardado)
        for x, c in zip(r.entradas, contribuciones):
            x.adj = c if x.adj is None else x.adj + c       # acumulación: x puede tener varios consumidores
        if liberar:
            r.vjp, r.guardado = None, ()   # lo que guardaba este nodo ya no hace falta
            if r.salida not in salidas:
                r.salida.adj = None


def grad(f):
    """grad(f)(*args): gradiente de una f escalar respecto a cada argumento, con una pasada reverse."""
    def g(*args):
        xs = [Var(np.array(a, dtype=float) if np.ndim(a) else float(a)) for a in args]
        with Cinta() as cinta:
            y = f(*xs)
        retropropaga(cinta, y)
        return [x.adj if x.adj is not None else np.zeros_like(x.valor) for x in xs]
    return g


# --- la traza de la lección 14, a mano y con el motor ---
x1, x2 = Var(2.0), Var(5.0)
with Cinta() as cinta:
    y = log(x1) + x1 * x2 - sin(x2)
retropropaga(cinta, y)
print(f"f(2, 5) = {y.valor:.6f}   registros en la cinta: {len(cinta.registros)}")
print(f"∂f/∂x1 = {x1.adj:.6f}   (exacta: 1/x1 + x2 = 5.5)")
print(f"∂f/∂x2 = {x2.adj:.6f}   (exacta: x1 - cos x2 = {2 - np.cos(5):.6f})")

The tape has five records, one per trace instruction, and both adjoints match the exact derivatives. Notice three code decisions. Accumulation x.adj = c if x.adj is None else x.adj + c creates a new array instead of adding in place: adding in place could modify an array saved by another operation. _ajusta undoes broadcasting by summing over stretched axes, the table’s “what broadcasts forward sums backward” rule. And the rules for exp, tanh and sqrt use the saved output instead of recomputing the function.

The dot-product test needs an independent JVP. The next cell rebuilds lesson 14’s forward mode in compact form (a class Dual with scalar or vector tangents) and makes functions exp, sin, concatena, total, etc., accept floats, Var and Dual interchangeably, so that the same code of a program can be evaluated, differentiated forward and differentiated backward.

[ ]The lesson 14 forward engine, compactlyBrowser
import numpy as np

class Dual:
    """Modo forward de la lección 14, compacto: valor y tangente (escalares o arrays)."""
    __array_priority__ = 1000

    def __init__(self, valor, tan):
        self.valor, self.tan = valor, tan

    def __add__(a, b):
        b = b if isinstance(b, Dual) else Dual(b, 0.0)
        return Dual(a.valor + b.valor, a.tan + b.tan)
    __radd__ = __add__

    def __sub__(a, b):
        b = b if isinstance(b, Dual) else Dual(b, 0.0)
        return Dual(a.valor - b.valor, a.tan - b.tan)

    def __rsub__(a, b):
        return Dual(b - a.valor, -a.tan)

    def __mul__(a, b):
        b = b if isinstance(b, Dual) else Dual(b, 0.0)
        return Dual(a.valor * b.valor, a.tan * b.valor + a.valor * b.tan)
    __rmul__ = __mul__

    def __truediv__(a, b):
        b = b if isinstance(b, Dual) else Dual(b, 0.0)
        y = a.valor / b.valor
        return Dual(y, (a.tan - y * b.tan) / b.valor)

    def __rtruediv__(a, b):
        y = b / a.valor
        return Dual(y, -y * a.tan / a.valor)

    def __neg__(a):
        return Dual(-a.valor, -a.tan)

    def __pow__(a, p):
        return Dual(a.valor ** p, p * a.valor ** (p - 1) * a.tan)

    def __getitem__(a, idx):
        return Dual(a.valor[idx], a.tan[idx])


def _despacha(fv, dfv, nombre):
    """Una misma función para floats, Var (reverse) y Dual (forward)."""
    rev = globals()[nombre]                  # la versión reverse definida en la celda anterior
    def f(x):
        if isinstance(x, Dual):
            return Dual(fv(x.valor), dfv(x.valor) * x.tan)
        return rev(x)
    return f

exp = _despacha(np.exp, np.exp, "exp")
log = _despacha(np.log, lambda x: 1 / x, "log")
sin = _despacha(np.sin, np.cos, "sin")
cos = _despacha(np.cos, lambda x: -np.sin(x), "cos")
tanh = _despacha(np.tanh, lambda x: 1 - np.tanh(x) ** 2, "tanh")
sqrt = _despacha(np.sqrt, lambda x: 0.5 / np.sqrt(x), "sqrt")
_concatena_rev, _total_rev = concatena, total

def concatena(partes):
    if any(isinstance(p, Dual) for p in partes):
        ps = [p if isinstance(p, Dual) else Dual(p, np.zeros(np.shape(p))) for p in partes]
        return Dual(np.concatenate([np.atleast_1d(p.valor) for p in ps]),
                    np.concatenate([np.atleast_1d(p.tan) for p in ps]))
    if any(isinstance(p, Var) for p in partes):
        return _concatena_rev(partes)
    return np.concatenate(partes)

def total(a):
    if isinstance(a, Dual):
        return Dual(np.sum(a.valor), np.sum(a.tan))
    return _total_rev(a) if isinstance(a, Var) else np.sum(a)

def valor(x):
    return x.valor if isinstance(x, (Var, Dual)) else x

Now, programs with control flow. The first computes a\sqrt{a} by Newton’s method, with a loop whose length depends on the input and a stopping condition evaluated with values, not Var. The second integrates the Lotka–Volterra predator–prey model with 200 RK4 steps and measures the trajectory’s mismatch with observations, as a function of the four parameters and initial state.

[ ]Differentiating programs with loops and branchesBrowser
# --- programa 1: una raíz cuadrada por Newton, con un bucle cuya longitud depende del dato ---
def raiz_newton(a, tol=1e-15):
    x = a                                 # punto inicial que depende de a
    iteraciones = 0
    while abs(valor(x) * valor(x) - valor(a)) > tol * valor(a):   # rama: decide con valores, no con Var
        x = 0.5 * (x + a / x)
        iteraciones += 1
    return x, iteraciones

for a in [2.0, 1e4]:
    da, = grad(lambda a: raiz_newton(a)[0])(a)
    _, it = raiz_newton(a)
    print(f"a = {a:g}: {it} iteraciones de Newton;  d sqrt(a)/da por reverse = {da:.16f}   exacta = {0.5 / np.sqrt(a):.16f}")


# --- programa 2: RK4 sobre Lotka-Volterra; pérdida respecto a parámetros y estado inicial ---
def lotka_volterra(z, th):
    x, y = z
    a, b, c, d = th
    return [a * x - b * x * y, d * x * y - c * y]

def rk4(f, z, th, h, pasos):
    tray = [z]
    for _ in range(pasos):
        k1 = f(z, th)
        k2 = f([zi + 0.5 * h * ki for zi, ki in zip(z, k1)], th)
        k3 = f([zi + 0.5 * h * ki for zi, ki in zip(z, k2)], th)
        k4 = f([zi + h * ki for zi, ki in zip(z, k3)], th)
        z = [zi + h / 6 * (a + 2 * b + 2 * c + d) for zi, a, b, c, d in zip(z, k1, k2, k3, k4)]
        tray.append(z)
    return tray

th_ref = [1.0, 0.4, 1.0, 0.1]                      # alfa, beta, gamma, delta
z_obs = rk4(lotka_volterra, [10.0, 5.0], th_ref, 0.05, 200)
obs = np.array([[valor(v) for v in z] for z in z_obs])

def perdida_lv(p):                                 # p = (alfa, beta, gamma, delta, x0, y0)
    tray = rk4(lotka_volterra, [p[4], p[5]], p[:4], 0.05, 200)
    L = 0.0
    for z, o in zip(tray, obs):
        L = L + (z[0] - o[0]) ** 2 + (z[1] - o[1]) ** 2
    return 0.5 * L

p0 = np.array([1.1, 0.38, 0.95, 0.11, 9.5, 5.3])
P = [Var(v) for v in p0]
with Cinta() as cinta:
    L = perdida_lv(P)
n_reg = len(cinta.registros)
retropropaga(cinta, L)
g_lv = np.array([v.adj for v in P])
print(f"\nRK4, 200 pasos: {n_reg} operaciones en la cinta;  L = {L.valor:.6f}")
print("gradiente reverse:", np.array2string(g_lv, precision=6))

def grad_check(f, g, x):
    """Verificador de la lección 13: máximo error relativo frente a diferencias centradas."""
    eps = (3 * 2.0**-53) ** (1 / 3)
    peor = 0.0
    for j in range(x.size):
        hj = eps * max(1.0, abs(x[j]))
        xp, xm = x.copy(), x.copy()
        xp[j] += hj
        xm[j] -= hj
        num = (f(xp) - f(xm)) / (xp[j] - xm[j])
        den = max(abs(g[j]), abs(num))
        peor = max(peor, 0.0 if den == 0 else abs(g[j] - num) / den)
    return peor

print(f"verificador de gradientes (diferencias centradas): error relativo máximo {grad_check(lambda p: perdida_lv(list(p)), g_lv, p0):.1e}")

The output deserves attention. Newton performs a different number of iterations for each aa, and the tape records exactly those executed; even so, the algorithm’s derivative agrees with 1/(2a)1/(2\sqrt{a}) to every printed digit. This is no coincidence: the derivative of the iterate, xk+1′=12(1−a/xk2)xk′+1/(2xk)x_{k+1}' = \tfrac{1}{2}\big(1 - a/x_k^2\big)x_k' + 1/(2x_k), converges to the solution’s derivative because the factor 1−a/xk21 - a/x_k^2 tends to zero as fast as Newton itself. Differentiating an iterative solver through its trace works, but costs memory proportional to the number of iterations; the next lesson studies when it is worthwhile and when it is better to differentiate the equation it solves. For RK4, the tape has on the order of 10410^4 scalar operations and the gradient checker confirms all six derivatives with relative error on the order of 10−810^{-8}, typical of centered differences.

Now the dot-product test on the map R6→R2\R^6 \to \R^2 taking the parameters and initial state to the Lotka–Volterra state after 20 RK4 steps, using the forward engine’s JVP and the reverse engine’s VJP. Then a deliberately broken rule: the product rule with factors swapped (aˉ+=yˉ a\bar a \mathrel{+}= \bar y\,a instead of yˉ b\bar y\,b), a transpose error in miniature.

[ ]The dot-product test against forward modeBrowser
def jvp(F, x, u):
    """J u con el modo forward: una pasada con tangentes u."""
    return np.array([s.tan for s in F([Dual(xi, ui) for xi, ui in zip(x, u)])])

def vjp(F, x, ybar):
    """Jᵀ ȳ con el modo reverse: una pasada hacia atrás sembrada con ȳ."""
    X = [Var(xi) for xi in x]
    with Cinta() as cinta:
        S = F(X)
    retropropaga(cinta, S, list(ybar))
    return np.array([xi.adj if xi.adj is not None else 0.0 for xi in X])

def prueba_producto_escalar(F, x, m, ensayos=20, semilla=0):
    """Máxima discrepancia relativa entre ⟨ȳ, J u⟩ y ⟨Jᵀ ȳ, u⟩ con u, ȳ gaussianos."""
    rng = np.random.default_rng(semilla)
    peor = 0.0
    for _ in range(ensayos):
        u, ybar = rng.normal(size=len(x)), rng.normal(size=m)
        a = ybar @ jvp(F, x, u)
        b = vjp(F, x, ybar) @ u
        r = abs(a - b) / max(abs(a), abs(b), 1e-300)
        if not np.isfinite(r):
            return np.inf                      # un NaN es un fallo; max() lo ignoraría
        peor = max(peor, r)
    return peor

def estado_final(p, pasos=20):                 # R^6 -> R^2: estado de Lotka-Volterra tras 20 pasos de RK4
    return rk4(lotka_volterra, [p[4], p[5]], p[:4], 0.05, pasos)[-1]

print(f"RK4 (R^6 -> R^2):   discrepancia máxima en 20 ensayos = {prueba_producto_escalar(estado_final, p0, 2):.1e}")
print(f"unidad de redondeo u = 2^-53 = {2.0**-53:.1e}")

# rompemos a propósito la regla del producto: intercambiar los factores (el error de «transposición» más común)
producto_bueno = producto
def producto_roto(a, b):
    a, b = _v(a), _v(b)
    fa, fb = a.forma, b.forma
    return _op(a.valor * b.valor, (a, b),
               lambda g, av, bv: (_ajusta(g * av, fa), _ajusta(g * bv, fb)), (a.valor, b.valor))

Var.__mul__ = lambda a, b: producto_roto(a, b)
Var.__rmul__ = lambda a, b: producto_roto(b, a)
print(f"con la regla del producto rota: discrepancia máxima = {prueba_producto_escalar(estado_final, p0, 2):.1e}")
with np.errstate(over="ignore", invalid="ignore"):     # con 200 pasos, la regla rota desborda
    b200 = vjp(lambda p: estado_final(p, 200), p0, np.ones(2))
print(f"200 pasos con la regla rota: VJP = {b200};   max(0.0, nan) = {max(0.0, float('nan'))}")
Var.__mul__ = lambda a, b: producto_bueno(a, b)
Var.__rmul__ = lambda a, b: producto_bueno(b, a)
print(f"restaurada:                     discrepancia máxima = {prueba_producto_escalar(estado_final, p0, 2):.1e}")

With correct rules, the maximum discrepancy in 20 trials is 5.6×10−155.6\times 10^{-15}, about fifty units of rounding accumulated over 20 steps. With the broken rule, the discrepancy is order 1. A detail in prueba_producto_escalar is not cosmetic: if the broken VJP overflows and produces NaN, max(peor, nan) returns peor in Python, because every comparison with NaN is false, and the test would silently pass. The penultimate line shows it: with 200 steps instead of 20, the broken rule grows adjoints until overflow, the VJP comes out as nan and max(0.0, nan) returns 0.0. Without the np.isfinite check, the test would accept the broken engine.

Finally, why the engine uses a tape rather than a graph search. An engine that stores only references to each node’s parents (like the simplest version of the m15 scalar engine) must order the graph before traversing it, and the most natural way to do so is recursive.

[ ]Topological order: recursion versus a stackBrowser
import sys

class Nodo:
    """Un grafo sin cinta, como el de un motor escalar mínimo: cada nodo solo conoce a sus padres."""
    def __init__(self, valor, padres=()):
        self.valor, self.padres = valor, padres

def cadena(n):                                  # un bucle largo: n operaciones encadenadas
    x = Nodo(1.0)
    for _ in range(n):
        x = Nodo(x.valor * 1.0001, (x,))
    return x

def topo_recursivo(raiz):
    orden, vistos = [], set()
    def visita(v):
        if id(v) in vistos:
            return
        vistos.add(id(v))
        for p in v.padres:
            visita(p)
        orden.append(v)                         # postorden: después de todos sus padres
    visita(raiz)
    return orden

def topo_iterativo(raiz):
    orden, vistos, pila = [], set(), [(raiz, False)]
    while pila:
        v, expandido = pila.pop()
        if expandido:
            orden.append(v)
            continue
        if id(v) in vistos:
            continue
        vistos.add(id(v))
        pila.append((v, True))                  # se emitirá cuando terminen sus padres
        pila.extend((p, False) for p in v.padres if id(p) not in vistos)
    return orden

y = cadena(5000)
print("límite de recursión de Python:", sys.getrecursionlimit())
try:
    topo_recursivo(y)
except RecursionError as e:
    print("recursivo -> RecursionError:", e)
orden = topo_iterativo(y)
pos = {id(v): i for i, v in enumerate(orden)}
print(f"iterativo -> {len(orden)} nodos; ¿todo padre antes que su hijo? {all(pos[id(p)] < pos[id(v)] for v in orden for p in v.padres)}")

A chain of 5000 operations, produced by a short simulation loop, exceeds Python’s recursion limit. The version with an explicit stack produces a correct topological order of any length. The tape avoids the problem at its root: the order is already written.

Lab 2: the gradient of a simulation with 500 parameters

The problem: a rod of length 1 with temperature u(x,t)u(x, t) obeying the heat equation with variable conductivity, ut=(k(x) ux)xu_t = (k(x)\,u_x)_x, with u=0u = 0 at the ends. The conductivity is unknown; you know the initial temperature and observe the temperature throughout the rod at eight times, with a little noise. You want to recover kk in each of 500 cells.

The discretization is the simplest finite-volume one. With N=500N = 500 cells of width hx=1/Nh_x = 1/N, the flux through the face between cells ii and i+1i + 1 is ki+1/2(ui+1−ui)/hxk_{i+1/2}(u_{i+1} - u_i)/h_x, with ki+1/2=(ki+ki+1)/2k_{i+1/2} = (k_i + k_{i+1})/2, and at the boundaries the face is hx/2h_x/2 from the wall, giving 2ki2k_i. Explicit Euler advances ui←ui+Δthx(flujoi+1/2−flujoi−1/2)u_i \leftarrow u_i + \tfrac{\Delta t}{h_x}\big(\text{flujo}_{i+1/2} - \text{flujo}_{i-1/2}\big). Each new uiu_i is a convex combination of ui−1,ui,ui+1u_{i-1}, u_i, u_{i+1} (and the scheme amplifies nothing) if Δthx2(ki−1/2+ki+1/2)≤1\tfrac{\Delta t}{h_x^2}\big(k_{i-1/2} + k_{i+1/2}\big) \le 1 in every cell; with Δt=0.2 hx2\Delta t = 0.2\,h_x^2 and boundary face 2k2k, k≤2k \le 2 suffices, and calibration is restricted to [0.2,2][0.2, 2]. The mismatch is

J(k)=12∑t∈obs∥ut(k)−dt∥22,k∈R500,J(\vb{k}) = \frac{1}{2}\sum_{t \in \text{obs}} \norm{\vb{u}_t(\vb{k}) - \vb{d}_t}_2^2, \qquad \vb{k} \in \R^{500},

a scalar function of 500 inputs defined by a program with 400 steps. This is the case for which reverse mode exists.

[ ]Heat simulation and its gradient in one passBrowser
import time

N, PASOS = 500, 400                                  # celdas y pasos de tiempo
hx = 1.0 / N
xc = (np.arange(N) + 0.5) * hx                       # centros de las celdas
k_real = 1.0 + 0.4 * np.sin(2 * np.pi * xc) + 0.5 * np.exp(-((xc - 0.7) / 0.06) ** 2)
u0 = np.sin(np.pi * xc) + 0.5 * np.sin(9 * np.pi * xc) + 0.3 * np.sin(31 * np.pi * xc)
dt = 0.2 * hx**2                                     # estable si (dt/hx^2)(k_cara_izq + k_cara_der) <= 1: basta k <= 2
OBS_CADA = 50

def caras(k):
    """Conductividad en las N + 1 caras: media aritmética dentro y k de la celda en los bordes (u = 0 fuera)."""
    dentro = 0.5 * (k[:-1] + k[1:])
    return concatena([2.0 * k[:1], dentro, 2.0 * k[-1:]]) if isinstance(k, (Var, Dual)) else \
        np.concatenate([2.0 * k[:1], dentro, 2.0 * k[-1:]])

def simula(k):
    """Esquema explícito de volúmenes finitos para u_t = (k u_x)_x; devuelve los estados observados."""
    c = (dt / hx**2) * caras(k)
    u, obs = u0, []
    cero = np.zeros(1)
    for n in range(1, PASOS + 1):
        ue = concatena([cero, u, cero])
        flujo = c * (ue[1:] - ue[:-1])                # flujo por cada cara (sin el signo)
        u = u + (flujo[1:] - flujo[:-1])
        if n % OBS_CADA == 0:
            obs.append(u)
    return obs

rng = np.random.default_rng(1)
datos = [o + 0.002 * rng.normal(size=N) for o in simula(k_real)]   # observaciones con un poco de ruido

def desajuste(k):
    J = 0.0
    for u, d in zip(simula(k), datos):
        r = u - d
        J = J + 0.5 * total(r * r)
    return J

k_ini = np.full(N, 1.2)

t0 = time.perf_counter(); J0 = desajuste(k_ini); t_f = time.perf_counter() - t0
K = Var(k_ini.copy())
t0 = time.perf_counter()
with Cinta() as cinta:
    J = desajuste(K)
t_grab = time.perf_counter() - t0
n_reg, mem = len(cinta.registros), cinta.bytes_guardados()
t0 = time.perf_counter(); retropropaga(cinta, J); t_back = time.perf_counter() - t0
g_calor = K.adj
print(f"una evaluación de J sin cinta: {1e3 * t_f:.0f} ms")
print(f"reverse: grabar {1e3 * t_grab:.0f} ms + hacia atrás {1e3 * t_back:.0f} ms = {(t_grab + t_back) / t_f:.1f} evaluaciones de J")
print(f"cinta: {n_reg} operaciones, {mem / 2**20:.1f} MiB guardados  (el estado ocupa {u0.nbytes / 2**10:.1f} KiB)")
print(f"tras la pasada hacia atrás (liberar=True) la cinta guarda {cinta.bytes_guardados()} bytes")

The tape has about 3650 array operations and stores on the order of 3 MiB: about 800 times the state size. This is reverse-mode memory in action, Θ(Ts)\Theta(T s) with T=400T = 400 steps, and it is all freed at the end of the backward pass. The cost of the gradient relative to one evaluation of JJ depends on the comparison, and the next cell separates it: pure NumPy evaluation creates no objects and records nothing, while the engine, written in Python, pays per-operation overhead unrelated to the cheap gradient principle.

[ ]Reverse, forward and finite differencesBrowser
# el mismo programa con objetos Var pero sin cinta: mide la sobrecarga del motor sin la pasada hacia atrás
t0 = time.perf_counter(); desajuste(Var(k_ini.copy())); t_var = time.perf_counter() - t0
print(f"misma evaluación con objetos Var y sin cinta: {1e3 * t_var:.0f} ms  ->  gradiente = {(t_grab + t_back) / t_var:.1f} evaluaciones de ese programa")

# modo forward: una pasada por conductividad; medimos 10 de las 500
cols = rng.choice(N, size=10, replace=False)
t0 = time.perf_counter()
g_fwd = np.array([desajuste(Dual(k_ini.copy(), np.eye(N)[j])).tan for j in cols])
t_fwd = (time.perf_counter() - t0) / len(cols)
print(f"\nforward: {1e3 * t_fwd:.0f} ms por pasada  ->  las 500 pasadas, unos {N * t_fwd:.1f} s ({N * t_fwd / (t_grab + t_back):.0f} veces el reverse)")
print(f"forward frente a reverse en esas 10 componentes: diferencia relativa máxima {np.max(np.abs(g_fwd - g_calor[cols]) / np.abs(g_calor[cols])):.1e}")

# diferencias centradas: 2 evaluaciones por componente, con el paso de la lección 13
h_fd = (3 * 2.0**-53) ** (1 / 3) * 1.2
t0 = time.perf_counter()
g_fd = []
for j in cols:
    e = np.zeros(N); e[j] = h_fd
    g_fd.append((desajuste(k_ini + e) - desajuste(k_ini - e)) / (2 * h_fd))
t_fd = (time.perf_counter() - t0) / len(cols)
g_fd = np.array(g_fd)
print(f"centradas: {1e3 * t_fd:.0f} ms por componente  ->  las 500, unos {N * t_fd:.1f} s")
print(f"centradas frente a reverse: diferencia relativa máxima {np.max(np.abs(g_fd - g_calor[cols]) / np.abs(g_calor[cols])):.1e}")
print(f"memoria extra: forward, la tangente del estado ({u0.nbytes / 2**10:.1f} KiB por array vivo); reverse, {mem / 2**20:.1f} MiB de cinta")

Read the ratios, not the milliseconds, which depend on the machine (in the browser everything runs several times slower than native Python). Reverse: the full gradient costs about 4 evaluations of the same program with Var objects, in line with Baydin’s c∼[2,3]c \sim [2, 3] plus recording overhead; against pure NumPy evaluation the ratio rises to about 19, and that difference is interpreter overhead, not arithmetic. Forward: each pass costs roughly one evaluation with objects, but 500 are needed; extrapolating the 10 measurements, forward mode needs about 70 times more time than reverse, and agrees with it to a relative difference of 10−1310^{-13}, accumulated rounding, because both are exact. Centered differences: 1000 evaluations of JJ, each cheaper because it does not use the engine, and a relative difference of 3×10−63\times 10^{-6}: five or six correct digits, as the V curve of lesson 13 predicts. Memory goes in the other direction: reverse stores 3.1 MiB of tape and forward only one tangent per live array, 3.9 KiB.

With the 500-component gradient in hand, calibration is optimization. The problem is ill-conditioned: the mismatch is very sensitive to kk where temperature varies rapidly and almost insensitive where it is flat, so a smoothness penalty λ2∑i(ki+1−ki)2\tfrac{\lambda}{2}\sum_i (k_{i+1} - k_i)^2 with λ=10−2\lambda = 10^{-2} is added and, like every part of the program, its gradient comes from the same tape.

[ ]Calibration by gradient descentBrowser
def objetivo(k, lam=1e-2):
    """Desajuste más una penalización de suavidad (lam/2) Σ (k_{i+1} - k_i)^2, y su gradiente por reverse."""
    K = Var(np.array(k, dtype=float))
    with Cinta() as cinta:
        dk = K[1:] - K[:-1]
        J = desajuste(K) + (0.5 * lam) * total(dk * dk)
    retropropaga(cinta, J)
    return J.valor, K.adj

error_k = lambda k: np.sqrt(np.mean((k - k_real) ** 2))
J_ruido = 0.5 * sum(np.sum((d - o) ** 2) for d, o in zip(datos, simula(k_real)))
print(f"desajuste inicial {objetivo(k_ini)[0]:.3e};  con la k verdadera (solo ruido) {J_ruido:.3e}")

k, eta = k_ini.copy(), 2.0
for it in range(1, 11):
    Jk, gk = objetivo(k)
    k = np.clip(k - eta * gk, 0.2, 2.0)
    if it in (1, 5, 10):
        print(f"descenso de gradiente, iteración {it:2d}: J = {Jk:.3e}   error RMS en k = {error_k(k):.3f}")

Fixed-step gradient descent advances slowly: at the tenth iteration the mismatch is 0.120.12, a factor of 8 smaller than at the start, but the mean squared error in kk has only fallen from 0.280.28 to 0.190.19. The gradient is large in cells where uxu_x is large and almost zero elsewhere, so descent corrects those cells first, like descent in a very elongated valley (conditioning again). A quasi-Newton method like L-BFGS builds an approximation of curvature from previous gradients and needs nothing beyond what the engine already computes: value and gradient.

[ ]Calibration with L-BFGSBrowser
from scipy.optimize import minimize
import matplotlib.pyplot as plt

hist, vistos = [], {}

def objetivo_anotado(k):                   # guarda J de cada punto para no recalcularlo en el callback
    J, g = objetivo(k)
    vistos[k.tobytes()] = J
    return J, g

res = minimize(objetivo_anotado, k_ini, jac=True, method="L-BFGS-B", bounds=[(0.2, 2.0)] * N,
               options=dict(maxiter=15), callback=lambda kk: hist.append(vistos.get(kk.tobytes(), np.nan)))
print(f"L-BFGS: {res.nit} iteraciones, {res.nfev} gradientes;  J = {res.fun:.3e}   error RMS en k = {error_k(res.x):.3f} (al principio {error_k(k_ini):.3f})")

fig, ax = plt.subplots(1, 2, figsize=(10, 3.4))
ax[0].plot(xc, k_real, color="gray", lw=2, label="k verdadera")
ax[0].plot(xc, k, label="descenso de gradiente (10 it.)")
ax[0].plot(xc, res.x, label="L-BFGS (15 it.)")
ax[0].set_xlabel("x"); ax[0].set_ylabel("conductividad k(x)"); ax[0].legend()
ax[1].semilogy(range(1, len(hist) + 1), hist, marker="o", ms=3)
ax[1].axhline(J_ruido, color="gray", ls="--", label="nivel del ruido")
ax[1].set_xlabel("iteración de L-BFGS"); ax[1].set_ylabel("J"); ax[1].legend()
plt.show()

With 15 L-BFGS iterations the mismatch falls from 0.940.94 to 9.4×10−39.4\times 10^{-3}, near the noise level (8.1×10−38.1\times 10^{-3}, what the true conductivity would give), and mean squared error in kk goes from 0.280.28 to 0.040.04. The figure on the left shows where the error remains: in the region from x≈0.6x \approx 0.6 to 0.80.8, where conductivity has its finest structure. Each iteration cost one 500-component gradient in one pass; with finite differences, each would have cost 1000 simulations.

Beyond networks: simulations and finance

The lab is a small example of a general situation: a physical model with many unknown parameters and a scalar mismatch measure. In inverse problems with partial differential equations (seismic tomography, weather data assimilation, aerodynamic design), the gradient is obtained with the adjoint method, reverse mode applied to the solver; you will study it as the adjoint gradient for PDE problems. The next lesson distinguishes differentiating the discretized program, as you have done here, from discretizing the continuous adjoint equation: the discrete versus continuous adjoint.

In quantitative finance the same idea is called adjoint algorithmic differentiation (AAD). A bank needs sensitivities (the “Greeks”) of its portfolio value to hundreds or thousands of market inputs: each point on the rate curve, each volatility. A portfolio’s value is one scalar output, or a few, of a program with many inputs, usually a Monte Carlo simulation. Giles and Glasserman, in “Smoking adjoints: fast Monte Carlo Greeks” (Risk, 2006), applied reverse mode along each simulated path to compute pathwise Greeks in the LIBOR market model. According to their abstract, the adjoint method outperforms the forward implementation when seeking sensitivities of few outputs to many inputs, and its computational advantage grows in proportion to the number of initial forward rates, that is, the number of inputs, as this lesson’s cost analysis predicts.

In libraries: torch.autograd

PyTorch implements exactly the lab engine, with tensors and rules written in C++. Every tensor created by an operation on tensors with requires_grad=True carries an attribute grad_fn: the record of the operation that produced it, with the VJP rule and references to its inputs’ records in next_functions. loss.backward() seeds yˉ=1\bar y = 1 and traverses that graph in reverse topological order, and leaf adjoints are added into their .grad attribute. torch.autograd.grad(y, x) returns adjoints instead of accumulating them, and torch.func.vjp(f, x) returns the output and a function applying J⊤\mat{J}\T to any yˉ\bar{\vb{y}}, the piece needed by the dot-product test.

The local lab rewrites the previous programs with tensors and compares them with your engine. Because local cells run in another process, a hidden cell defines the engine and programs above there again, with the same code.

[ ]Comparison with torch.autogradLocal GPU
import time
import numpy as np
import torch
from torch.func import jvp as t_jvp, vjp as t_vjp

torch.set_default_dtype(torch.float64)

# 1. Newton: el mismo bucle con parada dependiente del dato; PyTorch graba lo que se ejecuta
a = torch.tensor(2.0, requires_grad=True)
x = a
while abs(x.item() ** 2 - a.item()) > 1e-15 * a.item():
    x = 0.5 * (x + a / x)
x.backward()
print(f"Newton: d sqrt(a)/da = {a.grad.item():.16f}   exacta {0.5 / np.sqrt(2):.16f}")

# la cadena de grad_fn: el grafo que PyTorch construyó, recorrido desde la salida
nodo, cadena = x.grad_fn, []
while nodo is not None and len(cadena) < 6:
    cadena.append(type(nodo).__name__)
    hijos = [f for f, _ in nodo.next_functions if f is not None]
    nodo = hijos[0] if hijos else None
print("grad_fn desde la salida:", " <- ".join(cadena), "...")

# 2. Lotka-Volterra con RK4: mismo programa, tensores en lugar de Var
def rk4_t(p, pasos=200, h=0.05):
    a_, b_, c_, d_, x0, y0 = p
    f = lambda x, y: (a_ * x - b_ * x * y, d_ * x * y - c_ * y)
    x, y, tray = x0, y0, [(x0, y0)]
    for _ in range(pasos):
        k1 = f(x, y)
        k2 = f(x + 0.5 * h * k1[0], y + 0.5 * h * k1[1])
        k3 = f(x + 0.5 * h * k2[0], y + 0.5 * h * k2[1])
        k4 = f(x + h * k3[0], y + h * k3[1])
        x = x + h / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0])
        y = y + h / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1])
        tray.append((x, y))
    return tray

obs_t = torch.tensor(obs)
p = torch.tensor(p0, requires_grad=True)
tray = rk4_t(p)
L = 0.5 * sum((z[0] - o[0]) ** 2 + (z[1] - o[1]) ** 2 for z, o in zip(tray, obs_t))
L.backward()
print(f"\nRK4: L = {L.item():.6f};  diferencia relativa máxima con el motor propio: {np.max(np.abs(p.grad.numpy() - g_lv) / np.abs(g_lv)):.1e}")

# 3. Calor: el gradiente respecto a las 500 conductividades
def simula_t(k, u0, pasos, dt, hx):
    c = (dt / hx**2) * torch.cat([2 * k[:1], 0.5 * (k[:-1] + k[1:]), 2 * k[-1:]])
    u, cero, salidas = u0, torch.zeros(1, device=k.device), []
    for n in range(1, pasos + 1):
        ue = torch.cat([cero, u, cero])
        flujo = c * (ue[1:] - ue[:-1])
        u = u + (flujo[1:] - flujo[:-1])
        if n % OBS_CADA == 0:
            salidas.append(u)
    return salidas

u0_t, datos_t = torch.tensor(u0), [torch.tensor(d) for d in datos]
k = torch.tensor(k_ini, requires_grad=True)
J = sum(0.5 * ((u - d) ** 2).sum() for u, d in zip(simula_t(k, u0_t, PASOS, dt, hx), datos_t))
J.backward()
print(f"calor: diferencia relativa máxima con el motor propio en las 500 componentes: {np.max(np.abs(k.grad.numpy() - g_calor) / np.abs(g_calor)):.1e}")

# 4. Prueba del producto escalar con torch.func: F(k) = estado final, de R^500 en R^500
F = lambda k: simula_t(k, u0_t, PASOS, dt, hx)[-1]
gen = torch.Generator().manual_seed(0)
kk = torch.tensor(k_ini)
peor = 0.0
for _ in range(5):
    v = torch.randn(N, generator=gen)
    ybar = torch.randn(N, generator=gen)
    _, Jv = t_jvp(F, (kk,), (v,))
    _, f_vjp = t_vjp(F, kk)
    (JTy,) = f_vjp(ybar)
    a_, b_ = (ybar @ Jv).item(), (JTy @ v).item()
    peor = max(peor, abs(a_ - b_) / max(abs(a_), abs(b_)))
print(f"prueba del producto escalar con torch.func (5 ensayos): {peor:.1e}")

# 5. Los gradientes se acumulan y el grafo se libera
k = torch.tensor(k_ini, requires_grad=True)
J = sum(0.5 * ((u - d) ** 2).sum() for u, d in zip(simula_t(k, u0_t, PASOS, dt, hx), datos_t))
J.backward(retain_graph=True)
g1 = k.grad.clone()
J.backward()                                   # segunda pasada sobre el mismo grafo: suma, no sustituye
print(f"\ntras dos backward: k.grad / gradiente = {(k.grad / g1).mean().item():.3f}")
try:
    J.backward()
except RuntimeError as e:
    print("tercera llamada sin retain_graph:", str(e).split(".")[0])
k.grad = None                                  # lo que hace optimizer.zero_grad() por defecto

# 6. Modificar in situ algo que la pasada hacia atrás necesita
z = torch.tensor([1.0, 2.0], requires_grad=True)
e = z.exp()                                    # exp guarda su salida para el VJP
e.add_(1.0)                                    # ... y la cambiamos en el sitio
try:
    e.sum().backward()
except RuntimeError as err:
    print("in situ:", str(err).split(";")[0][:120])

# 7. Tiempos: CPU frente a GPU, con el problema pequeño y con uno grande
def mide(n, pasos, dispositivo, rep=3):
    hx_ = 1.0 / n
    dt_ = 0.4 * hx_**2 / 2.0
    xc_ = (torch.arange(n, device=dispositivo) + 0.5) * hx_
    u0_ = torch.sin(torch.pi * xc_)
    mejores = []
    for _ in range(rep):
        k = torch.full((n,), 1.2, device=dispositivo, requires_grad=True)
        if dispositivo == "cuda":
            torch.cuda.synchronize()
        t0 = time.perf_counter()
        J = (simula_t(k, u0_, pasos, dt_, hx_)[-1] ** 2).sum()
        J.backward()
        if dispositivo == "cuda":
            torch.cuda.synchronize()
        mejores.append(time.perf_counter() - t0)
    return min(mejores)

hay_gpu = torch.cuda.is_available()
for n in (500, 2**16):
    t_cpu = mide(n, 200, "cpu")
    linea = f"N = {n:6d}, 200 pasos, valor + gradiente: CPU {1e3 * t_cpu:7.1f} ms"
    if hay_gpu:
        mide(n, 50, "cuda", rep=1)             # calentamiento
        t_gpu = mide(n, 200, "cuda")
        linea += f"   GPU {1e3 * t_gpu:7.1f} ms   CPU/GPU = {t_cpu / t_gpu:.2f}"
    print(linea)
if hay_gpu:
    torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What the output shows:

  • Newton and grad_fn. PyTorch records the loop just like your tape, and the chain of grad_fn from the output is the operations list in reverse. Always following the first argument gives MulBackward0 <- AddBackward0 <- MulBackward0 <- ...: each Newton iteration is a product by 0.50.5 of a sum, and the quotient a/xa/x hangs off the other argument of each sum.
  • Same gradients. In Lotka–Volterra RK4 and all 500 components of the heat gradient, the relative difference from your engine is exactly 0: both implementations perform the same float64 operations in the same order.
  • The dot-product test with torch.func, with jvp and vjp on the R500\R^{500} map at R500\R^{500} that takes kk to the final state, gives discrepancies on the order of 10−1510^{-15}.
  • Accumulation. Two backward() calls on the same graph (the first with retain_graph=True) leave exactly twice the gradient in k.grad; a third fails because the graph has already been freed.
  • Modifying in place a tensor needed by a VJP rule (here, the output of exp) is detected by PyTorch’s version counter, which raises an error during backpropagation instead of giving a false gradient.
  • CPU versus GPU. With 500 cells, the GPU is slower than the CPU: each step launches a few tiny operations and time is dominated by kernel launch latency, not computation. With 2162^{16} cells and the same number of steps, GPU time barely changes and it is now faster than the CPU. Exact times vary with machine load; the direction of the comparison does not.

Common mistakes

Exercises

NumericA node with two consumers
Let v=x1x2v = x_1 x_2 and y=v+evy = v + e^{v}. Run the backward pass by hand at (x1,x2)=(1,2)(x_1, x_2) = (1, 2) and give ∂y/∂x1\partial y/\partial x_1 to four decimal places.
QuizWhy += and what happens without zero_grad
In the backward pass adjoints accumulate with +=. Why, and what happens in PyTorch if you do not zero gradients between iterations?
NumericPasses for a wide Jacobian
How many reverse passes are needed at minimum, without exploiting structure, to obtain the full Jacobian of f:R1000→R3f: \R^{1000} \to \R^{3}?
NumericMemory for a long simulation
A simulation of 10510^5 steps with a state of 10610^6 float64 values is differentiated in reverse mode, saving the state at each step. How many GB (10910^9 bytes) are needed to save those states?
QuizWhich mode would you use?
For which of these tasks is reverse mode preferable? (There may be several.)

More than one answer may be correct.

QuizWhat the dot-product test cannot detect
You add a new operation to your engine and write both its JVP and VJP rules, mistakenly using the same wrong local derivative in both. Does the dot-product test between that JVP and VJP detect the error?
ProofThe cheap gradient principle
Prove: If each instruction ii of a straight-line program has cost ci≥1c_i \ge 1 and a VJP rule (multiplications by local partials and additions to accumulators) costing at most ω ci\omega\,c_i, reverse mode computes ff and ∇f\grad f with arithmetic cost at most (1+ω) C(f)(1 + \omega)\,C(f), where C(f)=∑iciC(f) = \sum_i c_i.
0
Count separately the forward pass, which executes the program and saves values, and the backward pass.

Step 1 of 4. How many times is each instruction's VJP rule executed during the backward pass?

CodeThe dot-product test
Implement dot_test(jvp, vjp, x, trials=10, seed=0), where jvp(x, u) returns Ju\mat{J}\vb{u} and vjp(x, ybar) returns what should be J⊤yˉ\mat{J}\T\bar{\vb{y}}, for f:Rn→Rmf: \R^n \to \R^m at point x. Generate trials Gaussian pairs (u,yˉ)(\vb{u}, \bar{\vb{y}}) with np.random.default_rng(seed) (obtain mm from the size of jvp(x, u)) and return the maximum relative discrepancy ∣a−b∣/max⁡(∣a∣,∣b∣)\abs{a - b}/\max(\abs{a}, \abs{b}) with a=⟨yˉ,Ju⟩a = \inner{\bar{\vb{y}}}{\mat{J}\vb{u}} and b=⟨vjp(yˉ),u⟩b = \inner{\text{vjp}(\bar{\vb{y}})}{\vb{u}}. If any trial gives a nonfinite discrepancy, return np.inf. Do not modify x.
import numpy as np

def dot_test(jvp, vjp, x, trials=10, seed=0):
  """Máxima discrepancia relativa entre <ybar, J u> y <vjp(ybar), u> en 'trials' ensayos gaussianos."""
  x = np.asarray(x, dtype=float)
  rng = np.random.default_rng(seed)
  peor = 0.0
  # tu código
  return peor
Shift+Enter to run
CodeA new operation: stable softplus
The minimal engine below is a reduced version of the lab engine. Add softplus(a) to compute log⁡(1+ex)\log(1 + e^{x}) elementwise without overflow for large ∣x∣\abs{x} and record its also stable VJP rule, xˉ=yˉ⊙σ(x)\bar{\vb{x}} = \bar{\vb{y}} \odot \sigma(\vb{x}), on the tape. The tests evaluate values and gradients at x=±800x = \pm 800 and ±30\pm 30, compare with centered differences and apply the dot-product test against an independent JVP. Conceptual hint: the naive form np.log(1 + np.exp(x)) gives inf at x=800x = 800, and its derivative exp(x) / (1 + exp(x)) gives nan.
import numpy as np

# motor mínimo (el del laboratorio, recortado): no hace falta tocarlo
class Var:
  def __init__(self, valor):
      self.valor, self.adj = np.asarray(valor, dtype=float), None

class Cinta:
  activa = None
  def __init__(self):
      self.registros = []
  def __enter__(self):
      Cinta.activa = self
      return self
  def __exit__(self, *exc):
      Cinta.activa = None

def _op(valor, entradas, vjp, guardado=()):
  out = Var(valor)
  if Cinta.activa is not None:
      Cinta.activa.registros.append((out, entradas, vjp, guardado))
  return out

def retropropaga(cinta, y, semilla=None):
  y.adj = np.ones_like(y.valor) if semilla is None else np.asarray(semilla, dtype=float)
  for out, entradas, vjp, guardado in reversed(cinta.registros):
      if out.adj is None:
          continue
      for x, c in zip(entradas, vjp(out.adj, *guardado)):
          x.adj = c if x.adj is None else x.adj + c

def softplus(a):
  """log(1 + e^x) elemento a elemento, sin desbordar, con su regla VJP registrada en la cinta."""
  # tu código: calcula el valor de forma estable y llama a _op(valor, (a,), vjp, guardado)
  raise NotImplementedError
Shift+Enter to run

Connections and reading

For further reading: chapters 3 and 4 of Griewank and Walther are the complete reverse-mode reference, with its cost and memory analysis; section 3 of Baydin et al. (2018) is the clearest introduction and the source of this lesson’s example; Baur and Strassen (1983) is the original complexity result; Paszke et al. (2019) describe PyTorch’s autograd design; and Giles and Glasserman (2006) are the starting point for AAD in finance.

Summary

Key idea
Reverse mode traverses the trace backward and accumulates the output sensitivity at each variable, vˉj+=vˉi ∂vi/∂vj\bar v_j \mathrel{+}= \bar v_i\,\partial v_i/\partial v_j: one pass gives the whole gradient at the cost of a few evaluations of ff, regardless of the number of inputs, in exchange for saving what the forward pass computed.
  • Adjoint vˉi=∂Yi/∂vi\bar v_i = \partial Y_i/\partial v_i is the derivative of the output with respect to viv_i as the rest of the program executes. The chain rule gives the backward recursion, and += sums the paths of a variable with multiple consumers.
  • Each operation contributes a VJP, xˉ=J⊤yˉ\bar{\vb{x}} = \mat{J}\T\bar{\vb{y}}: what reads forward writes backward, and what broadcasts forward sums backward. The full Jacobian costs on the order of nn forward passes or mm reverse passes.
  • The tape records operations in execution order, a topological order; traversing it backward differentiates loops and branches along the executed path, allows memory to be freed on the fly and avoids recursion.
  • Cheap gradient principle: if each VJP costs at most ω\omega times its operation, the gradient costs at most (1+ω) C(f)(1 + \omega)\,C(f); with arithmetic, 5 C(f)5\,C(f), the Baur–Strassen bound.
  • Memory grows with computation length, Θ(Ts)\Theta(T s); checkpoints reduce it in exchange for recomputation, with a peak of order L\sqrt{L} for an extra pass.
  • The dot-product test, ⟨yˉ,Ju⟩=⟨J⊤yˉ,u⟩\inner{\bar{\vb{y}}}{\mat{J}\vb{u}} = \inner{\mat{J}\T\bar{\vb{y}}}{\vb{u}} with random vectors, verifies a VJP at rounding level against an independent JVP; treat NaN as failure and complement it with the gradient checker.
  • In the lab, one reverse pass gave all 500 components of a heat simulation gradient and enabled conductivity calibration, while forward mode would have needed tens of times more time and finite differences gave only five or six digits.