Module contents
Lesson 16 of 26Advanced 115 min

Automatic differentiation III: higher order, iterative solvers, adjoints and checkpointing

Compose modes to obtain Hessian–vector products without forming the Hessian, choose a Jacobian strategy, write custom derivative rules, differentiate iterative solvers, decide between discrete and continuous adjoints, and control memory with binomial checkpointing. Turn the mathematical theory from m03 into algorithms with controlled cost and memory for second-order optimizers, Deep Equilibrium Models and Neural ODEs.

After this lesson you can

  • Compute Hessian–vector products by composing modes (forward over reverse) and use them in Newton-CG without forming the Hessian.
  • Choose between jacfwd, jacrev, vectorization and coloring based on Jacobian shape and sparsity.
  • Write and verify custom VJP rules for numerical stability or differentiating nondifferentiable operations.
  • Compare unrolled and implicit differentiation of an iterative solver in memory, cost and bias.
  • Implement the discrete adjoint of an integrator and compare it with the continuous adjoint.
  • Apply binomial checkpointing to reverse long simulations with logarithmic memory growth.

Before you start

Motivation: three problems autograd does not solve alone

From the previous two lessons you know how to compute a JVP in forward mode and a gradient in reverse mode for the cost of a few function evaluations. That is enough to train a network with gradient descent. It is not enough for three problems that appear when you do something a little more ambitious:

  • Curvature. Newton’s method, an analysis of a minimum’s sharpness or an influence function needs the Hessian H=∇2f\mat{H} = \hess f of a loss with n=106n = 10^6 parameters. Forming it costs nn gradients and 101210^{12} numbers: 4 TB in float32. But almost all those algorithms use only products Hv\mat{H}\vb{v}, and one product costs as much as a few gradients.
  • Layers defined as solutions of a problem. A Deep Equilibrium Model defines its layer as the fixed point z∗=g(z∗,θ)\vb{z}^* = g(\vb{z}^*, \theta); an optimization layer defines it as an energy minimum. Backpropagating through 200 solver iterations saves 200 states and gives the derivative of the truncated solver, not the solution. The implicit function theorem gives the solution derivative with one state and a linear system.
  • Long simulations. Fitting the parameters of an ODE, climate model or Neural ODE requires the gradient of something depending on thousands of integrator steps. Reverse mode saves thousands of states; the continuous adjoint method saves none but may give an unusable gradient; binomial checkpointing saves O(log⁡n)\bigO(\log n) states in exchange for recomputation.

All three have the same structure: you already saw the mathematical theory (Hessian–vector product, implicit function and continuous adjoint) in the calculus course. This lesson turns it into algorithms with controlled cost, memory and accuracy, and teaches when each gives the right number. By the end you will have an HVP on the custom engine, Newton-CG, a sparse Jacobian compressor, verified custom derivative rules, an implicit layer on the GPU and three ways to compute a simulation gradient, with their failures measured.

Mode composition: differentiating the gradient program

The gradient computed by reverse mode is itself a program: a sequence of elementary operations that takes x\vb{x} and returns ∇f(x)\nabla f(\vb{x}). Nothing prevents applying automatic differentiation to it again. Since there are two modes, there are four compositions, and the Hessian–vector product comes from any of them.

What does each cost? Call CC the cost of evaluating ff, ωF\omega_F the forward-mode factor (at most 4 in the operation model of the forward-mode lesson) and ωR\omega_R the reverse-mode factor (the constant in the cheap gradient principle).

CompositionWhat executesCost of one Hv\mat{H}\vb{v}Memory
forward over reversethe gradient program with duals≤ωF ωR C\le \omega_F\,\omega_R\,Cthe tape of ff, with each entry doubled
reverse over forwardthe tangent program’s tape, traversed backward≤ωR ωF C\le \omega_R\,\omega_F\,Cthe tangent program’s tape, larger than that of ff
reverse over reversethe backward pass’s tape, traversed backward≤ωR2 C\le \omega_R^2\,Cthe tape of ff plus that of its backward pass
forward over forwardhyperduals: u⊤Hw\vb{u}\T\mat{H}\vb{w} per passnn passes, O(n C)\bigO(n\,C)minimal
Proof

Reverse mode produces ∇f(x)\nabla f(\vb{x}) with a program of elementary operations (those of ff and their local derivatives) costing ≤ωRC\le \omega_R C. Each local derivative φ′(u)\varphi'(u) is differentiable because φ∈C2\varphi \in C^2, so that program is itself differentiable and forward mode applies the JVP theorem to it: one pass with seed v\vb{v} gives J∇f(x)v\mat{J}_{\nabla f}(\vb{x})\vb{v} at ≤ωF\le \omega_F times the program cost. Since J∇f=H\mat{J}_{\nabla f} = \mat{H}, the result is Hv\mat{H}\vb{v}. Dual arithmetic truncates nothing: the only error is operation rounding.

∎

Why does the choice matter? The first two rows cost the same in operations, but not in memory or overhead. Forward over reverse runs the backward pass only once, carrying tangents: it need not record that pass to traverse it later. Reverse over reverse does: it records the backward pass of ff and then reverses it. The JAX guide (The Autodiff Cookbook) summarizes it this way: forward mode has less overhead than reverse, so it is preferable on the outside; in its example measurement, forward over reverse took 2.76 ms, reverse over forward 8.83 ms, reverse over reverse 13.2 ms and forming the full Hessian 28.5 ms. In the PyTorch lab you will see that the difference depends heavily on implementation.

Pearlmutter’s R operator

In 1994, long before AD libraries became the usual tool for neural networks, Barak Pearlmutter showed how to compute Hv\mat{H}\vb{v} exactly, without approximations, for any network at a cost on the order of a gradient. He defined the operator

Rv{h(x)}=ddrh(x+rv)∣r=0,\mathcal{R}_{\vb{v}}\{h(\vb{x})\} = \frac{d}{dr}h(\vb{x} + r\vb{v})\Big|_{r=0},

which obeys derivative rules (R{x}=v\mathcal{R}\{\vb{x}\} = \vb{v}, R{c}=0\mathcal{R}\{c\} = 0, linearity, product and R{φ(a)}=φ′(a)R{a}\mathcal{R}\{\varphi(a)\} = \varphi'(a)\mathcal{R}\{a\}), and applied it to every equation of the forward pass and backpropagation. For a layer aℓ=Wℓhℓ−1\vb{a}_\ell = \mat{W}_\ell\vb{h}_{\ell-1}, hℓ=σ(aℓ)\vb{h}_\ell = \sigma(\vb{a}_\ell), with backpropagation δℓ=σ′(aℓ)⊙(Wℓ+1⊤δℓ+1)\vb{\delta}_\ell = \sigma'(\vb{a}_\ell)\odot(\mat{W}_{\ell+1}\T\vb{\delta}_{\ell+1}) and ∂L/∂Wℓ=δℓhℓ−1⊤\partial L/\partial\mat{W}_\ell = \vb{\delta}_\ell\vb{h}_{\ell-1}\T, and a direction Vℓ\mat{V}_\ell for each weight matrix:

R{aℓ}=Vℓhℓ−1+Wℓ R{hℓ−1},R{hℓ}=σ′(aℓ)⊙R{aℓ},R{δℓ}=σ′′(aℓ)⊙R{aℓ}⊙(Wℓ+1⊤δℓ+1)+σ′(aℓ)⊙(Vℓ+1⊤δℓ+1+Wℓ+1⊤R{δℓ+1}),R{∂L∂Wℓ}=R{δℓ} hℓ−1⊤+δℓ R{hℓ−1}⊤.\begin{aligned} \mathcal{R}\{\vb{a}_\ell\} &= \mat{V}_\ell\vb{h}_{\ell-1} + \mat{W}_\ell\,\mathcal{R}\{\vb{h}_{\ell-1}\}, \qquad \mathcal{R}\{\vb{h}_\ell\} = \sigma'(\vb{a}_\ell)\odot\mathcal{R}\{\vb{a}_\ell\},\\ \mathcal{R}\{\vb{\delta}_\ell\} &= \sigma''(\vb{a}_\ell)\odot\mathcal{R}\{\vb{a}_\ell\}\odot(\mat{W}_{\ell+1}\T\vb{\delta}_{\ell+1}) + \sigma'(\vb{a}_\ell)\odot\big(\mat{V}_{\ell+1}\T\vb{\delta}_{\ell+1} + \mat{W}_{\ell+1}\T\mathcal{R}\{\vb{\delta}_{\ell+1}\}\big),\\ \mathcal{R}\Big\{\frac{\partial L}{\partial\mat{W}_\ell}\Big\} &= \mathcal{R}\{\vb{\delta}_\ell\}\,\vb{h}_{\ell-1}\T + \vb{\delta}_\ell\,\mathcal{R}\{\vb{h}_{\ell-1}\}\T. \end{aligned}

The last quantities together are Hv\mat{H}\vb{v}. Look at what this is: a forward pass propagating R{⋅}\mathcal{R}\{\cdot\} alongside values and a backward pass propagating R{δ}\mathcal{R}\{\vb{\delta}\} alongside δ\vb{\delta}. It is exactly forward over reverse written by hand: R{⋅}\mathcal{R}\{\cdot\} is the ε\eps part of a dual number. Today it is not written by hand, but the R operator remains a way to read what the composition does.

InteractiveCurvature probe with HVP
Contours, ∇f\nabla f at p\vb{p} and p+δv\vb{p} + \delta\vb{v}, and δ Hv\delta\,\mat{H}\vb{v}
Slice φ(t)=f(p+tv)\varphi(t) = f(\vb{p} + t\vb{v}) and its local parabola
  • direction v\vb{v} (unit length)
  • ∇f\nabla f at p\vb{p} (strong) and p+δv\vb{p} + \delta\vb{v} (faint)
  • δ Hv\delta\,\mat{H}\vb{v} from the tip of ∇f(p)\nabla f(\vb{p})
  • slice φ(t)\varphi(t)
  • parabola φ(0)+t ∇f⋅v+12t2 v⊤Hv\varphi(0) + t\,\nabla f\cdot\vb{v} + \tfrac12 t^2\,\vb{v}\T\mat{H}\vb{v}
Function
Difference of gradients
0.30
Power iteration with HVPs
f(x,y)=(1−x)2+4 (y−x2)2f(x, y) = (1 - x)^2 + 4\,(y - x^2)^2
Slope ∇f⋅v\nabla f\cdot\vb{v}1.984
Curvature v⊤Hv\vb{v}\T\mat{H}\vb{v}4.880
Hv\mat{H}\vb{v} (hyperduals)(4.880, 9.600)
(∇f(p+δv)−∇f(p))/δ(\nabla f(\vb{p} + \delta\vb{v}) - \nabla f(\vb{p}))/\delta(−2.320, 7.200)
Power steps0
Angle between v\vb{v} and eigenvector with largest ∣λ∣\abs{\lambda}49.6°
Drag the point p\vb{p} and the tip of the unit direction v\vb{v}. The strong orange arrow is ∇f(p)\nabla f(\vb{p}); the faint one, ∇f(p+δv)\nabla f(\vb{p} + \delta\vb{v}); the magenta one, δ Hv\delta\,\mat{H}\vb{v} placed at the tip of the first: for small δ\delta, the HVP is what the gradient at p\vb{p} lacks to become the one at p+δv\vb{p} + \delta\vb{v}. Lower δ\delta and compare the two colored readouts. On the right, the slice φ(t)=f(p+tv)\varphi(t) = f(\vb{p} + t\vb{v}) and the parabola whose curvature is v⊤Hv\vb{v}\T\mat{H}\vb{v}. Press “Iterate”: each step performs v←Hv/∥Hv∥\vb{v} \leftarrow \mat{H}\vb{v}/\norm{\mat{H}\vb{v}} and the direction rotates toward the greatest curvature in absolute value. Try the saddle: when does curvature become negative? Everything is computed with hyperdual numbers, without finite differences.

In the initial state, in the curved valley with p=(−0.6,0.9)\vb{p} = (-0.6, 0.9), v=e1\vb{v} = \vb{e}_1 and δ=0.3\delta = 0.3, the exact HVP is Hv=(4.88,9.6)\mat{H}\vb{v} = (4.88, 9.6), but the gradient difference (∇f(p+δv)−∇f(p))/δ(\nabla f(\vb{p} + \delta\vb{v}) - \nabla f(\vb{p}))/\delta is (−2.32,7.2)(-2.32, 7.2): the magenta arrow does not close the triangle, because in such a curved valley the Hessian changes greatly over 0.30.3 units. With δ=0.05\delta = 0.05 the difference is already (3.48,9.2)(3.48, 9.2) and with 0.020.02, (4.31,9.44)(4.31, 9.44): it approaches Hv\mat{H}\vb{v} with error O(δ)\bigO(\delta), that of a forward difference. The AD HVP has no such error because there is no δ\delta. At that same point the Hessian is indefinite, with eigenvalues 16.1716.17 and −3.29-3.29, although curvature along e1\vb{e}_1 is positive (4.884.88). Power iteration aligns v\vb{v} with the eigenvector of 16.1716.17 in a few steps because the ratio of magnitudes is 0.20.2; the closer that ratio is to 1, the more steps it needs. At the saddle the largest-magnitude eigenvalue may be negative, and the iteration converges to it anyway: power iteration seeks the greatest ∣λ∣\abs{\lambda}, not the greatest λ\lambda.

Lab 1: HVP and Newton-CG with the custom engine

This cell’s engine combines the previous two lessons’ engines in minimal form: an Dual (from the dual-number lesson) and a reverse-mode tape Var traversed in topological order. The only design decision that matters is that the tape is generic: it stores whatever it is given, floats or duals, in val and local derivatives, and elementary functions dispatch by type. If you call grad with xi+viεx_i + v_i\eps inputs, the backward pass operates on duals without knowing it and each gradient component comes out with its directional derivative in the ε\eps part: forward over reverse in one line.

[ ]Forward over reverse: an HVP with the custom engineBrowser
import math, time
import numpy as np

# ---------- modo forward: duales mínimos (los de la lección 14) ----------
class Dual:
    __slots__ = ("val", "tan")
    def __init__(self, val, tan=0.0):
        self.val, self.tan = val, tan
    def __add__(self, o):
        return Dual(self.val + o.val, self.tan + o.tan) if isinstance(o, Dual) else Dual(self.val + o, self.tan)
    __radd__ = __add__
    def __sub__(self, o):
        return Dual(self.val - o.val, self.tan - o.tan) if isinstance(o, Dual) else Dual(self.val - o, self.tan)
    def __rsub__(self, o):
        return Dual(o - self.val, -self.tan)
    def __neg__(self):
        return Dual(-self.val, -self.tan)
    def __mul__(self, o):
        if isinstance(o, Dual):
            return Dual(self.val * o.val, self.tan * o.val + self.val * o.tan)
        return Dual(self.val * o, self.tan * o)
    __rmul__ = __mul__
    def __truediv__(self, o):
        if isinstance(o, Dual):
            w = self.val / o.val
            return Dual(w, (self.tan - w * o.tan) / o.val)
        return Dual(self.val / o, self.tan / o)
    def __rtruediv__(self, o):
        w = o / self.val
        return Dual(w, -w * self.tan / self.val)
    def __pow__(self, p):
        return Dual(self.val ** p, p * self.val ** (p - 1) * self.tan)
    def __lt__(self, o): return self.val < (o.val if isinstance(o, Dual) else o)
    def __gt__(self, o): return self.val > (o.val if isinstance(o, Dual) else o)
    def __repr__(self): return f"Dual({self.val!r}, {self.tan!r})"

# ---------- modo reverse: una cinta cuyos valores pueden ser floats o duales ----------
class Var:
    """Nodo de la cinta. val y las parciales locales usan aritmética genérica: si son duales, la pasada
    hacia atrás arrastra tangentes y el gradiente sale con su derivada direccional (forward sobre reverse)."""
    __slots__ = ("val", "padres")
    def __init__(self, val, padres=()):
        self.val, self.padres = val, padres
    def __add__(self, o):
        if isinstance(o, Var):
            return Var(self.val + o.val, ((self, 1.0), (o, 1.0)))
        return Var(self.val + o, ((self, 1.0),))
    __radd__ = __add__
    def __sub__(self, o):
        if isinstance(o, Var):
            return Var(self.val - o.val, ((self, 1.0), (o, -1.0)))
        return Var(self.val - o, ((self, 1.0),))
    def __rsub__(self, o):
        return Var(o - self.val, ((self, -1.0),))
    def __neg__(self):
        return Var(-self.val, ((self, -1.0),))
    def __mul__(self, o):
        if isinstance(o, Var):
            return Var(self.val * o.val, ((self, o.val), (o, self.val)))
        return Var(self.val * o, ((self, o),))
    __rmul__ = __mul__
    def __truediv__(self, o):
        if isinstance(o, Var):
            w = self.val / o.val
            return Var(w, ((self, 1.0 / o.val), (o, -1.0 * w / o.val)))
        return Var(self.val / o, ((self, 1.0 / o),))
    def __pow__(self, p):
        return Var(self.val ** p, ((self, p * self.val ** (p - 1)),))

def _elemental(f, df):
    """f sobre floats; df(u) escrita con las propias funciones genéricas, para que valga con duales."""
    def g(x):
        if isinstance(x, Var):
            return Var(g(x.val), ((x, df(x.val)),))
        if isinstance(x, Dual):
            return Dual(f(x.val), df(x.val) * x.tan)
        if isinstance(x, np.ndarray):
            return np.array([g(xi) for xi in x], dtype=object)
        if hasattr(x, "_elemental"):          # otros tipos (el trazador de dispersión) la interceptan
            return x._elemental()
        return f(x)
    return g

exp = _elemental(math.exp, lambda u: exp(u))
log = _elemental(math.log, lambda u: 1.0 / u)
sin = _elemental(math.sin, lambda u: cos(u))
cos = _elemental(math.cos, lambda u: -sin(u))
tanh = _elemental(math.tanh, lambda u: 1.0 - tanh(u) ** 2)

def _orden(y):
    """Orden topológico de la cinta (DFS iterativo)."""
    orden, visto, pila = [], set(), [(y, False)]
    while pila:
        nodo, hecho = pila.pop()
        if hecho:
            orden.append(nodo); continue
        if id(nodo) in visto:
            continue
        visto.add(id(nodo))
        pila.append((nodo, True))
        for p, _ in nodo.padres:
            if id(p) not in visto:
                pila.append((p, False))
    return orden

def grad(f, x):
    """Valor y gradiente de f: R^n -> R en modo reverse. Las entradas pueden ser floats o duales.
    Una parcial local puede ser una función del adjunto (para las reglas propias de más abajo)."""
    xs = np.array([Var(xi) for xi in x], dtype=object)
    y = f(xs)
    adj = {id(y): 1.0}
    for nodo in reversed(_orden(y)):
        a = adj.get(id(nodo))
        if a is None:
            continue
        for p, d in nodo.padres:
            adj[id(p)] = adj.get(id(p), 0.0) + (d(a) if callable(d) else a * d)
    return y.val, [adj.get(id(xi), 0.0) for xi in xs]

def hvp(f, x, v):
    """Forward sobre reverse: el gradiente calculado con entradas x + v·ε. Su parte ε es H v."""
    _, g = grad(f, [Dual(float(xi), float(vi)) for xi, vi in zip(x, v)])
    return np.array([gi.tan if isinstance(gi, Dual) else 0.0 for gi in g])

def gradiente(f, x):
    val, g = grad(f, [float(xi) for xi in x])
    return val, np.array(g, dtype=float)

# --- validación 1: cuadrática, cuyo hessiano exacto es (A + A^T)/2 ---
rng = np.random.default_rng(0)
n = 6
A = rng.normal(size=(n, n)); b = rng.normal(size=n)
cuad = lambda x: 0.5 * (x @ (A @ x)) + b @ x
x0, v = rng.normal(size=n), rng.normal(size=n)
print("cuadrática: |Hv - (A+A^T)v/2| =", np.max(np.abs(hvp(cuad, x0, v) - 0.5 * (A + A.T) @ v)))

# --- validación 2: Rosenbrock en R^10 frente al hessiano analítico y a diferencias de gradientes ---
def rosen(x):
    return sum(100.0 * (x[i + 1] - x[i] ** 2) ** 2 + (1.0 - x[i]) ** 2 for i in range(len(x) - 1))

def rosen_hess(x):
    n = len(x); H = np.zeros((n, n))
    for i in range(n - 1):
        H[i, i] += 1200 * x[i] ** 2 - 400 * x[i + 1] + 2
        H[i + 1, i + 1] += 200
        H[i, i + 1] += -400 * x[i]; H[i + 1, i] += -400 * x[i]
    return H

x = rng.normal(size=10); v = rng.normal(size=10)
Hv = hvp(rosen, x, v)
print("Rosenbrock: error relativo frente al hessiano analítico =", np.linalg.norm(Hv - rosen_hess(x) @ v) / np.linalg.norm(Hv))
for h in (1e-3, 1e-5, 1e-7):
    dif = (gradiente(rosen, x + h * v)[1] - gradiente(rosen, x - h * v)[1]) / (2 * h)
    print(f"  diferencia central de gradientes, h = {h:.0e}: error relativo {np.linalg.norm(dif - Hv) / np.linalg.norm(Hv):.1e}")

# --- coste: un HVP frente a un gradiente y frente a formar el hessiano con n HVPs ---
def cronometra(fn, rep):
    t = time.perf_counter()
    for _ in range(rep):
        fn()
    return (time.perf_counter() - t) / rep
for n in (20, 80):
    x = rng.normal(size=n); v = rng.normal(size=n)
    tg = cronometra(lambda: gradiente(rosen, x), 5)
    th = cronometra(lambda: hvp(rosen, x, v), 5)
    print(f"n = {n:3d}: HVP / gradiente = {th / tg:.1f}   hessiano completo (n HVPs) / gradiente ≈ {n * th / tg:.0f}")

The engine’s HVP agrees with the quadratic’s exact Hessian and Rosenbrock’s analytic one up to rounding (10−1610^{-16}). The centered difference of gradients, by contrast, has the two errors of step-size selection: 8.5×10−78.5\times 10^{-7} with h=10−3h = 10^{-3} (truncation), 8.8×10−118.8\times 10^{-11} with h=10−5h = 10^{-5} (near optimal, on the order of u2/3u^{2/3}) and 5.9×10−105.9\times 10^{-10} with h=10−7h = 10^{-7} (rounding). In cost, the HVP takes about two gradients in this engine (the ratio varies between runs; in checks it was between 1.5 and 2), independently of nn, while forming the Hessian costs nn times that. Notice that the ratio is less than ωF\omega_F: in an interpreted engine much of the cost is the interpreter itself, paid once per node with either floats or duals.

Newton-CG: Newton without a Hessian

The Newton step solves Hkp=−∇fk\mat{H}_k\vb{p} = -\nabla f_k. Conjugate gradient solves that system touching Hk\mat{H}_k only through products Hkd\mat{H}_k\vb{d}, that is, as a matrix-free operator. With an HVP each CG iteration costs a couple of gradients and memory is that of a few vectors. Two details turn this idea into Newton-CG (also called truncated Newton):

  • Solve only as much as needed. Far from the minimum it is not worthwhile to solve the system accurately. The theory of inexact Newton methods (Dembo, Eisenstat and Steihaug, 1982) says that if the residual satisfies ∥Hkpk+∇fk∥≤ηk∥∇fk∥\norm{\mat{H}_k\vb{p}_k + \nabla f_k} \le \eta_k\norm{\nabla f_k} with ηk→0\eta_k \to 0, local convergence is superlinear, and quadratic if ηk=O(∥∇fk∥)\eta_k = \bigO(\norm{\nabla f_k}). The usual choice, from algorithm 7.1 of Nocedal and Wright, is ηk=min⁡(0.5,∥∇fk∥)\eta_k = \min(0.5, \sqrt{\norm{\nabla f_k}}).
  • Negative curvature. CG assumes H\mat{H} is positive definite. If at an iteration d⊤Hd≤0\vb{d}\T\mat{H}\vb{d} \le 0, the quadratic model has no minimum in that direction: stop and return the last iterate (or −∇f-\nabla f on the first iteration), which is still a descent direction. It is the same number shown in red by the curvature probe.
[ ]Newton-CG, Lanczos and power iteration with HVPsBrowser
import numpy as np
from scipy.optimize import minimize
from scipy.sparse.linalg import LinearOperator, eigsh

def cg_truncado(Hv, g, tol, maxit):
    """CG de la lección 7 sobre H p = -g, parando si encuentra curvatura no positiva (Newton-CG truncado)."""
    p = np.zeros_like(g); r = -g.copy(); d = r.copy(); rr = r @ r; usados = 0
    for _ in range(maxit):
        Hd = Hv(d); usados += 1
        dHd = d @ Hd
        if dHd <= 1e-12 * (d @ d):              # curvatura negativa o nula: H no es definida positiva aquí
            return (p if p.any() else -g), usados, True
        a = rr / dHd
        p = p + a * d; r = r - a * Hd
        rr_nuevo = r @ r
        if np.sqrt(rr_nuevo) <= tol:
            break
        d = r + (rr_nuevo / rr) * d; rr = rr_nuevo
    return p, usados, False

def newton_cg(f, x0, tol=1e-8, maxit=200):
    x = np.array(x0, dtype=float); total_hvp = 0; negativas = 0; normas = []
    for k in range(maxit):
        fx, g = gradiente(f, x)
        ng = np.linalg.norm(g); normas.append(ng)
        if ng < tol:
            break
        eta = min(0.5, np.sqrt(ng)) * ng                  # forzado de Nocedal y Wright, algoritmo 7.1
        p, usados, neg = cg_truncado(lambda d: hvp(f, x, d), g, eta, 2 * len(x))
        total_hvp += usados; negativas += neg
        t = 1.0                                            # búsqueda lineal de Armijo con retroceso
        while f(x + t * p) > fx + 1e-4 * t * (g @ p):
            t *= 0.5
        x = x + t * p
    return x, k, total_hvp, negativas, normas

x0 = np.zeros(10)
x, it, nh, neg, normas = newton_cg(rosen, x0)
print(f"Rosenbrock n = 10: {it} iteraciones de Newton, {nh} HVPs, {neg} con curvatura negativa, error final {np.max(np.abs(x - 1)):.1e}")
print("  |grad| en las últimas iteraciones:", " ".join(f"{g:.1e}" for g in normas[-5:]))
for metodo, extra in (("Newton-CG", dict(hessp=lambda x, p: hvp(rosen, x, p))), ("BFGS", {})):
    r = minimize(lambda x: gradiente(rosen, x)[0], x0, jac=lambda x: gradiente(rosen, x)[1], method=metodo, **extra)
    print(f"scipy {metodo:9s}: {r.nit} iteraciones, {r.njev} gradientes, {getattr(r, 'nhev', 0)} HVPs, error {np.max(np.abs(r.x - 1)):.1e}")

# regresión logística con regularización L2 y características de escalas muy distintas
rng = np.random.default_rng(1)
N, d, lam = 80, 4, 1e-2
X = rng.normal(size=(N, d)) * np.array([3.0, 1.0, 0.3, 0.1])
w_real = np.array([1.0, -2.0, 3.0, 0.5])
y = np.where(rng.random(N) < 1 / (1 + np.exp(-X @ w_real)), 1.0, -1.0)

def logistica(w):
    z = X @ w
    return sum(log(1.0 + exp(-yi * zi)) for yi, zi in zip(y, z)) / N + 0.5 * lam * (w @ w)

def logistica_hess(w):
    s = 1 / (1 + np.exp(-X @ w))
    return X.T @ (X * (s * (1 - s))[:, None]) / N + lam * np.eye(d)

v = rng.normal(size=d)
print("\nlogística: |HVP - H v| =", np.max(np.abs(hvp(logistica, np.full(d, 0.3), v) - logistica_hess(np.full(d, 0.3)) @ v)))
w, it, nh, neg, normas = newton_cg(logistica, np.zeros(d), tol=1e-10)
print(f"logística: {it} iteraciones de Newton, {nh} HVPs; |grad| por iteración:", " ".join(f"{g:.0e}" for g in normas))

# espectro del hessiano en el óptimo sin formarlo: potencia y Lanczos
ev = np.linalg.eigvalsh(logistica_hess(w))
q = np.ones(d) / 2
for k in range(1, 9):
    Hq = hvp(logistica, w, q); rayleigh = q @ Hq; q = Hq / np.linalg.norm(Hq)
    if k in (1, 2, 4, 8):
        print(f"potencia, {k} HVPs: error relativo de λ_max {abs(rayleigh - ev[-1]) / ev[-1]:.1e}")
Hop = LinearOperator((d, d), matvec=lambda u: hvp(logistica, w, np.ravel(u)), dtype=float)
print("Lanczos (eigsh), extremos:", np.round(eigsh(Hop, k=2, which="BE", return_eigenvectors=False), 6))
print("eigvalsh de H formada:   ", np.round(ev, 6), f"  condición {ev[-1] / ev[0]:.1f},  λ2/λ1 = {ev[-2] / ev[-1]:.3f}")

Read the results carefully, because they say different things for each problem.

  • Rosenbrock at R10\R^{10}. Newton-CG reaches the minimum (1,…,1)(1, \dots, 1) with a gradient norm that, in the last iterations, falls faster than linearly: the theory’s superlinear convergence. But it needs 56 iterations and 215 HVPs, and in 7 CG finds negative curvature: the valley is narrow and curved, the quadratic model is valid only nearby and line search shortens the steps. BFGS, without a single HVP, needs a similar number of iterations. Newton is not magic far from the minimum; its advantage is local convergence and independence from conditioning.
  • Logistic regression. The problem is convex and smooth, and Newton-CG solves it in a few iterations with a handful of HVPs, with gradient norm falling quadratically at the end. The Hessian at the optimum has condition number κ=32.3\kappa = 32.3. On a quadratic problem with that conditioning, gradient descent with the optimal step reduces error by a factor (κ−1)/(κ+1)≈0.94(\kappa - 1)/(\kappa + 1) \approx 0.94 per iteration: about 480 iterations to gain the 13 orders of magnitude Newton gains in 7.
  • Spectrum. With λ2/λ1=0.15\lambda_2/\lambda_1 = 0.15, power iteration converges in very few HVPs, and Lanczos (eigsh on an LinearOperator that only knows how to do HVPs) gives both ends of the spectrum without forming H\mat{H}. With n=107n = 10^7 parameters, this is the only way to inspect a network’s curvature: this is what Hessian spectrum analysis tools do in real networks.

Strategies for computing Jacobians

For F:Rn→RmF: \R^n \to \R^m, each forward pass gives a column Jej\mat{J}\vb{e}_j and each reverse pass a row ei⊤J\vb{e}_i\T\mat{J}. Strategies for computing Jacobians choose how many passes, of what kind and with which seeds:

StrategyPassesApproximate costWhen
jacfwdnn JVPs (vectorized)n ωF Cn\,\omega_F\,Cn≪mn \ll m: few inputs, many outputs
jacrevmm VJPs (vectorized)m ωR Cm\,\omega_R\,C, plus the tapem≪nm \ll n: few outputs
column coloringpp JVPs, pp = number of colorsp ωF Cp\,\omega_F\,Csparse J\mat{J} with short rows
row coloringqq VJPsq ωR Cq\,\omega_R\,Csparse J\mat{J} with short columns
bidirectionalpp JVPs + qq VJPsfew dense rows or columns

vmap does not change the number of passes: it executes them together, turning nn matrix–vector products into a matrix–matrix product. On the GPU that is the difference between launching nn small kernels and one large one, and you will measure it in the PyTorch lab.

Sparse Jacobian compression

The forward-mode lesson already showed that a tridiagonal Jacobian is obtained with three seeds. Here is the full theory, by Curtis, Powell and Reid (1974), in the graph language formalized by Coleman and Moré (1983).

Proof

By definition, Bic=∑j: c(j)=cJijB_{ic} = \sum_{j:\,c(j) = c} J_{ij}. If the coloring is valid, that sum has at most one nonzero term, so Bi,c(j)=JijB_{i,c(j)} = J_{ij}. (1): nonzeros in the same row are in columns that share that row, so they must have different colors. (2): “share a row” is exactly adjacency, and a valid coloring assigns colors with no adjacent vertices of the same color. Greedy assigns each vertex the smallest color unused by an already colored neighbor; since it has at most Δ\Delta neighbors, it never needs more than Δ+1\Delta + 1. (3): in a band, columns jj and kk share a row if and only if ∣j−k∣≤bℓ+bu\abs{j - k} \le b_\ell + b_u; with c(j)=j mod (bℓ+bu+1)c(j) = j \bmod (b_\ell + b_u + 1), two columns of the same color are at least bℓ+bu+1b_\ell + b_u + 1 apart. And an interior row has bℓ+bu+1b_\ell + b_u + 1 nonzeros, so by (1) fewer cannot suffice.

∎

A dense row ruins column coloring: all columns share that row and nn colors are needed. The solution is bidirectional coloring (Coleman and Verma, 1998): that row is obtained with a reverse-mode VJP and the remainder colored without it. For symmetric Hessians, finer colorings exist (star coloring) that exploit Hij=HjiH_{ij} = H_{ji}; the reference paper is What color is your Jacobian? by Gebremedhin, Manne and Pothen (2005).

InteractiveColoring a sparse Jacobian
121212121212123456789101112B = J S2223223322332233223222J (12×12), colored columns12×2
Pattern
Brush
Strategy
Colors = JVPs2
Total passes2
Lower bound: max. nonzeros per row5
Greedy in natural order5 colors
Conflicting rows12 of 12
In red rows, two columns of the same color have nonzero entries: the compressed JVP gives their sum, so they cannot be separated.
Choose a brush color and click columns to paint them. Columns of the same color are summed in one seed and cost one JVP. A red row has two nonzeros of the same color: in the compressed matrix B=JS\mat{B} = \mat{J}\mat{S} on the right those entries are summed (the red cell says how many) and cannot be separated. The initial state alternates two colors on a pentadiagonal: why does it fail? Find the fewest colors without conflicts and compare with the lower bound and greedy. Then try the arrow, first alone and then extracting the dense row into a VJP.

In the pentadiagonal, two colors are not enough because columns jj and j+2j + 2 share row j+1j + 1: conflicts appear in every interior row. Each interior row has 5 nonzeros, so the lower bound is 5, and greedy reaches it. In the arrow, the last row touches every column: greedy needs 12 colors, as many as columns, and compression does nothing. Extracting that row into a VJP leaves the diagonal plus the last column: the first eleven columns no longer share any row and use one color, and the last, which touches every row, another. That is 3 total passes instead of 12, and for any nn it would still be 3. In the random pattern, greedy in natural order uses 4 colors and the lower bound is 3: the bound is not always attained, column order changes the greedy result, and finding the minimum is generally NP-hard.

[ ]Pattern, coloring and compression with the custom engineBrowser
import numpy as np

def jvp(F, x, v):
    """J v con una pasada de modo forward (duales escalares)."""
    y = F(np.array([Dual(float(a), float(b)) for a, b in zip(x, v)], dtype=object))
    return np.array([yi.tan if isinstance(yi, Dual) else 0.0 for yi in y])

def vjp(F, x, w):
    """w^T J con una pasada de modo reverse: el gradiente de x -> w · F(x)."""
    return gradiente(lambda u: sum(wi * Fi for wi, Fi in zip(w, F(u)) if wi != 0), x)[1]

class Dep:
    """Trazador de dispersión: en lugar de un valor, el conjunto de entradas de las que depende."""
    __slots__ = ("s",)
    def __init__(self, s): self.s = s
    def _op(self, o): return Dep(self.s | o.s) if isinstance(o, Dep) else Dep(self.s)
    __add__ = __radd__ = __sub__ = __rsub__ = __mul__ = __rmul__ = __truediv__ = __rtruediv__ = _op
    def __pow__(self, p): return Dep(self.s)
    def __neg__(self): return Dep(self.s)
    def _elemental(self): return Dep(self.s)

def patron(F, n):
    """Patrón de dispersión del jacobiano con una sola evaluación de F sobre conjuntos de dependencias."""
    y = F(np.array([Dep({j}) for j in range(n)], dtype=object))
    P = np.zeros((len(y), n), dtype=bool)
    for i, yi in enumerate(y):
        if isinstance(yi, Dep):
            P[i, list(yi.s)] = True
    return P

def colorear(P):
    """Coloreado voraz de columnas: dos columnas comparten color solo si no comparten ninguna fila."""
    n = P.shape[1]; color = -np.ones(n, dtype=int)
    for j in range(n):
        prohibidos = {color[k] for k in range(n) if color[k] >= 0 and np.any(P[:, j] & P[:, k])}
        c = 0
        while c in prohibidos:
            c += 1
        color[j] = c
    return color

def jacobiano_comprimido(F, x, P, color):
    """Un JVP por color con semilla = suma de las columnas de ese color; cada entrada se lee sin ambigüedad."""
    J = np.zeros(P.shape)
    for c in range(color.max() + 1):
        Jd = jvp(F, x, (color == c).astype(float))
        for j in np.flatnonzero(color == c):
            J[P[:, j], j] = Jd[P[:, j]]
    return J

n, h = 30, 1 / 31
def banda(u):                       # pentadiagonal: cada ecuación mira dos vecinos a cada lado
    up = np.concatenate([[0.0, 0.0], u, [0.0, 0.0]])
    return (up[:-4] - 4 * up[1:-3] + 6 * up[2:-2] - 4 * up[3:-1] + up[4:]) / h**4 + exp(u)
def flecha(u):                      # flecha: diagonal + una última fila densa + una última columna densa
    out = [u[i] ** 2 + 0.5 * u[-1] for i in range(n - 1)]
    out.append(sum(u[i] for i in range(n)) ** 2)
    return np.array(out, dtype=object)

u = np.random.default_rng(2).normal(size=n) * 0.1
for nombre, F in (("pentadiagonal", banda), ("flecha", flecha)):
    P = patron(F, n)
    col = colorear(P)
    J_ref = np.column_stack([jvp(F, u, np.eye(n)[j]) for j in range(n)])
    J = jacobiano_comprimido(F, u, P, col)
    print(f"{nombre:13s}: {P.sum()} no nulos, máx. por fila {P.sum(1).max()}, colores (JVPs) = {col.max() + 1},"
          f" error = {np.max(np.abs(J - J_ref)):.1e}")

# la flecha en dos direcciones: la fila densa con un VJP y el resto por columnas
P = patron(flecha, n)
P_sin_fila = P.copy(); P_sin_fila[-1] = False
col = colorear(P_sin_fila)
J = jacobiano_comprimido(flecha, u, P_sin_fila, col)
J[-1] = vjp(flecha, u, np.eye(n)[-1])
J_ref = np.column_stack([jvp(flecha, u, np.eye(n)[j]) for j in range(n)])
print(f"flecha bidireccional: {col.max() + 1} JVPs + 1 VJP, error = {np.max(np.abs(J - J_ref)):.1e}")

Two things are new compared with lesson 14. First, the pattern is computed, not written: tracer Dep evaluates FF once on sets of indices instead of numbers, using the rule “the result depends on the union of what the operands depend on”. This is the idea behind library sparsity-detection tools (in Julia, for example, SparseConnectivityTracer.jl), and it costs one evaluation. Since it only examines program structure, it may mark as nonzero an entry that is zero through cancellation, never the reverse. Second, the result: the 30-column pentadiagonal takes 5 JVPs instead of 30, and the arrow goes from 30 colors to 2 JVPs and 1 VJP, both with error 0 because each entry is read from a sum with one term.

Custom derivative rules

Sometimes you do not want AD to differentiate what you wrote. There are three reasons: the automatic derivative is numerically poor even though the function is good, the function contains a solver or external call you do not want or cannot record, or the function is nondifferentiable and you need a useful pseudoderivative. In all three cases you declare a new primitive with its own rule.

AD cannot check consistency for you: the rule replaces the derivative and any error propagates silently through the entire gradient. That is why each custom rule is verified with the previous lesson’s dot-product test: for random vectors v\vb{v} and w\vb{w}, w⊤(Jv)=(J⊤w)⊤v\vb{w}\T(\mat{J}\vb{v}) = (\mat{J}\T\vb{w})\T\vb{v}, where Jv\mat{J}\vb{v} is computed independently (in forward mode on the implementation without the rule, or with finite differences as in the gradient checker) and J⊤w\mat{J}\T\vb{w} with the rule.

Logsumexp. lse⁡(x)=log⁡∑iexi\operatorname{lse}(\vb{x}) = \log\sum_i e^{x_i} overflows as soon as any xix_i exceeds 709 in float64. The stable form m+log⁡∑iexi−mm + \log\sum_i e^{x_i - m}, with m=max⁡ixim = \max_i x_i, does not overflow, and AD differentiates it correctly (mm disappears from the gradient because 1−∑isoftmax⁡i=01 - \sum_i \operatorname{softmax}_i = 0). But it records 3n3n nodes and, in the backward pass, reconstructs the gradient by adding contributions that cancel. The custom rule saves x\vb{x} and yy and directly returns xˉ=yˉ ex−y=yˉ softmax⁡(x)\bar{\vb{x}} = \bar y\,e^{\vb{x} - y} = \bar y\,\softmax(\vb{x}).

Gradient clipping. A primitive that is the identity forward and clips the adjoint backward, xˉ=clip⁡(yˉ,−c,c)\bar x = \operatorname{clip}(\bar y, -c, c). It is not the derivative of anything: the rule is intentionally inconsistent, and the dot-product test must fail.

Straight-through estimator. Rounding has zero derivative almost everywhere, so a quantized parameter receives no gradient. The straight-through estimator (Bengio, Léonard and Courville, 2013) rounds forward and uses the identity backward. It is not a derivative either: it is a biased estimator that works in practice and is used to train with discrete or quantized variables.

[ ]Custom rules on the tape and their verificationBrowser
import math
import numpy as np

def regla_propia(f, vjp_regla):
    """Declara una primitiva con su VJP: hacia delante, f sobre floats sin grabar nada; en la cinta, un solo nodo
    cuyo padre j recibe vjp_regla(x, y, ā)[j] en la pasada hacia atrás."""
    def g(*xs):
        vals = [x.val if isinstance(x, Var) else x for x in xs]
        y = f(*vals)
        if not any(isinstance(x, Var) for x in xs):
            return y
        padres = tuple((x, (lambda a, j=j: vjp_regla(vals, y, a)[j])) for j, x in enumerate(xs) if isinstance(x, Var))
        return Var(y, padres)
    return g

# 1) logsumexp: ingenua, estable derivada por la cinta y estable con regla propia
def lse_ingenua(*x):
    return log(sum(exp(xi) for xi in x))
def lse_estable_cinta(*x):
    m = max(xi.val if isinstance(xi, Var) else xi for xi in x)       # constante para la cinta
    return m + log(sum(exp(xi - m) for xi in x))
def _lse(*x):
    m = max(x)
    return m + math.log(sum(math.exp(xi - m) for xi in x))
lse = regla_propia(_lse, lambda x, y, a: [a * math.exp(xi - y) for xi in x])   # VJP: ā · softmax(x)

x = [1000.0, 999.0, 998.0]
try:
    gradiente(lambda v: lse_ingenua(*v), x)
except OverflowError as e:
    print("ingenua:", type(e).__name__, e)
for nombre, f in (("estable por la cinta", lse_estable_cinta), ("regla propia", lse)):
    val, g = gradiente(lambda v: f(*v), x)
    nodos = len(_orden(f(*np.array([Var(xi) for xi in x], dtype=object))))
    print(f"{nombre:20s}: lse = {val:.6f}, gradiente = {np.round(g, 6)}, nodos en la cinta = {nodos}")

# 2) la prueba del producto escalar: w·(J v) con un JVP independiente frente a (J^T w)·v con la regla
def prueba_producto_escalar(f_dual, f_regla, x, pruebas=5, seed=0):
    r = np.random.default_rng(seed); peor = 0.0
    for _ in range(pruebas):
        v, w = r.normal(size=len(x)), r.normal()
        Jv = f_dual(*[Dual(xi, vi) for xi, vi in zip(x, v)]).tan
        JTw = np.array(gradiente(lambda u: w * f_regla(*u), x)[1])
        peor = max(peor, abs(w * Jv - JTw @ v) / max(abs(w * Jv), 1e-300))
    return peor
def lse_dual(*x):                                     # la versión estable sobre duales da el JVP de referencia
    m = max(xi.val for xi in x)
    return m + log(sum(exp(xi - m) for xi in x))
x = np.random.default_rng(3).normal(size=6) * 3
olvida_a = regla_propia(_lse, lambda x, y, a: [math.exp(xi - y) for xi in x])       # error típico: no multiplica por ā
print(f"\nproducto escalar, regla correcta:        discrepancia relativa {prueba_producto_escalar(lse_dual, lse, x):.1e}")
print(f"producto escalar, regla que olvida ā:   discrepancia relativa {prueba_producto_escalar(lse_dual, olvida_a, x):.1e}")

# 3) reglas que cambian el gradiente a propósito
recorte = regla_propia(lambda x: x, lambda x, y, a: [max(-1.0, min(1.0, a))])   # identidad; recorta ā en [-1, 1]
redondeo_ste = regla_propia(lambda x: float(round(x)), lambda x, y, a: [a])        # straight-through
print("\nrecorte: d/dx de 5·x en x = 2 ->", gradiente(lambda v: 5.0 * recorte(v[0]), [2.0])[1][0], "(sin recorte, 5)")
print(f"producto escalar del recorte: {prueba_producto_escalar(lambda x: x, recorte, [2.0]):.2f} (falla por diseño)")
w, objetivo = 0.2, 3.4
for paso in range(8):
    val, g = gradiente(lambda v: (redondeo_ste(v[0]) - objetivo) ** 2, [w])
    w -= 0.3 * g[0]
print(f"STE: tras 8 pasos w = {w:.3f}, round(w) = {round(w)}; la derivada verdadera de round es 0 casi en todo punto")

The naive version does not even reach the backward pass: math.exp(1000) raises OverflowError (NumPy or PyTorch would give inf and a gradient nan). The stable version through the tape gives the correct gradient, (0.665,0.245,0.090)(0.665, 0.245, 0.090), with 14 nodes; the custom rule gives the same numbers with 4 (the three inputs and output). With nn inputs the difference is O(n)\bigO(n) nodes versus one, which matters for a large network’s memory. The dot-product test unambiguously separates the correct rule, with discrepancy on the order of 10−1610^{-16}, from one that forgets to multiply by yˉ\bar y, a real mistake that with yˉ=1\bar y = 1 (a single scalar loss) would go unnoticed. Clipping gives 1 where the derivative is 5 and the test flags it: that is intended, but should be documented as an estimator, not a derivative. Straight-through moves the parameter from 0.20.2 to a region where it rounds to 3, the integer nearest target 3.43.4, even though the true derivative of rounding is zero.

Differentiating through iterative solvers

Many layers and models are defined as the solution to a problem: the fixed point of an iteration, the minimum of an energy, the root of a system. Write the general case as an iteration

zk+1=g(zk,θ),z∗(θ)=g(z∗(θ),θ),\vb{z}_{k+1} = g(\vb{z}_k, \theta), \qquad \vb{z}^*(\theta) = g(\vb{z}^*(\theta), \theta),

where gg is a contraction in z\vb{z}: ∥∂zg∥≤ρ<1\norm{\partial_{\vb{z}}g} \le \rho < 1, the convergence condition for fixed-point iteration. A loss L(z∗)L(\vb{z}^*) depends on θ\theta through the solution. There are two ways to obtain dL/dθdL/d\theta, and choosing between them is what we call differentiating through iterative solvers.

Unroll. Execute kk iterations while recording them and backpropagate through all of them, as through a network of kk layers with shared weights. It gives the exact derivative of what you ran, dL(zk)/dθdL(\vb{z}_k)/d\theta, and costs kk states of memory.

Differentiate the fixed point. Differentiate the identity z∗=g(z∗,θ)\vb{z}^* = g(\vb{z}^*, \theta), as in implicit differentiation: dz∗dθ=∂zg dz∗dθ+∂θg\frac{d\vb{z}^*}{d\theta} = \partial_{\vb{z}}g\,\frac{d\vb{z}^*}{d\theta} + \partial_\theta g, that is,

dz∗dθ=(I−∂zg)−1 ∂θg,dLdθ=u⊤∂θgcon(I−∂zg)⊤u=∇L(z∗).\frac{d\vb{z}^*}{d\theta} = (\mat{I} - \partial_{\vb{z}}g)^{-1}\,\partial_\theta g, \qquad \frac{dL}{d\theta} = \vb{u}\T\partial_\theta g \quad\text{con}\quad (\mat{I} - \partial_{\vb{z}}g)\T\vb{u} = \nabla L(\vb{z}^*).

The matrix I−∂zg\mat{I} - \partial_{\vb{z}}g is invertible because the eigenvalues of ∂zg\partial_{\vb{z}}g have magnitude less than 1. The second form is what is implemented: a single adjoint system of size dim⁡z\dim\vb{z}, solved by touching ∂zg⊤\partial_{\vb{z}}g\T only through VJPs of gg. Only z∗\vb{z}^* must be saved, regardless of the number of forward iterations: that is the constant memory of Bai, Kolter and Koltun’s Deep Equilibrium Models (2019), whose paper reports up to 88% less memory in their experiments. Blondel and collaborators (2022) generalized it: simply provide the optimality condition F(z,θ)=0F(\vb{z}, \theta) = \vb{0} (here, F=z−gF = \vb{z} - g; for a minimum, F=∇zEF = \nabla_{\vb{z}}E) and the library applies the same formula, dz∗/dθ=−(∂zF)−1∂θFd\vb{z}^*/d\theta = -(\partial_{\vb{z}}F)^{-1}\partial_\theta F.

Does the unrolled derivative converge to the implicit one? Yes, but late. This is a result of Gilbert (1992), and its quantitative form is as follows.

The proof is the guided exercise at the end. The idea fits in one line: differentiating the iteration, Zk+1=AkZk+Bk\mat{Z}_{k+1} = \mat{A}_k\mat{Z}_k + \mat{B}_k with Ak=∂zg(zk,θ)\mat{A}_k = \partial_{\vb{z}}g(\vb{z}_k, \theta), and error Ek=Zk−Z∗\mat{E}_k = \mat{Z}_k - \mat{Z}^* contracts by ρ\rho at each step but simultaneously receives a source (Ak−A∗)Z∗+(Bk−B∗)(\mat{A}_k - \mat{A}^*)\mat{Z}^* + (\mat{B}_k - \mat{B}^*) of size O(ρk)\bigO(\rho^k), because zk\vb{z}_k has not yet reached z∗\vb{z}^*. Summing kk sources of size ρk\rho^k gives factor kk. If gg is affine in z\vb{z}, Ak=A∗\mat{A}_k = \mat{A}^* and the source comes only from Bk\mat{B}_k.

InteractiveImplicit versus unrolled
The layer
0.90
20
The adjoint system
10
dL/dθdL/d\theta at z∗\vb{z}^* (reference)0.97608362
unrolled, k=20k = 200.97634562
implicit at z20\vb{z}_{20}0.97602063
unrolled error / ∥zk−z∗∥\norm{\vb{z}_k - \vb{z}^*}1.87
implicit error / ∥zk−z∗∥\norm{\vb{z}_k - \vb{z}^*}0.45
observed rate of ∥zk−z∗∥\norm{\vb{z}_k - \vb{z}^*}0.694
Unrolled memory: 20 states
Implicit memory: z* and u
A fixed-point layer z=tanh⁡(Wz+θx+b)\vb{z} = \tanh(\mat{W}\vb{z} + \theta\vb{x} + \vb{b}) with n=8n = 8 and symmetric W\mat{W} of norm ρ\rho, iterated from z0=0\vb{z}_0 = \vb{0}, and loss L=12∥z−y∥2L = \tfrac12\norm{\vb{z} - \vb{y}}^2. The three curves, on a logarithmic scale, are the iterate's distance to the fixed point (gray), the unrolled gradient error dL(zk)/dθdL(\vb{z}_k)/d\theta (red), and the error of the implicit formula evaluated at zk\vb{z}_k (aquamarine). Move kk: after the first iterations, the red curve is above the gray, and the ratio of readouts grows with kk. The curves meet at 10−1410^{-14}, where only rounding remains. Raise ρ\rho toward 1. Then disable the exact adjoint and solve it with mm fixed-point iterations: how many are needed so its error does not dominate? The bars compare memory: kk states versus two vectors.

In the initial state, with ρ=0.9\rho = 0.9 and k=20k = 20, all three curves descend as straight lines on a logarithmic scale with the slope of the observed rate (0.6940.694, smaller than ρ\rho because tanh⁡′<1\tanh' < 1), but red gradually separates from gray: the ratio between unrolled and state errors is 1.91.9 at k=20k = 20, 6.16.1 at k=40k = 40 and 14.614.6 at k=80k = 80, a line in kk, which is the theorem’s factor kk. Aquamarine instead follows gray at a constant distance (ratio 0.450.45 for every kk): the implicit gradient evaluated at an unconverged zk\vb{z}_k has error on the order of ∥zk−z∗∥\norm{\vb{z}_k - \vb{z}^*}, no more and no less. With the adjoint solved by mm fixed-point iterations, a third error appears that decreases with mm at the same rate as the state with kk: the adjoint iteration, u←∂zg⊤u+∇L\vb{u} \leftarrow \partial_{\vb{z}}g\T\vb{u} + \nabla L, has the same iteration matrix transposed and therefore the same spectral radius.

Stopping criteria and bias

Christianson (1994) studied exactly this situation: reverse accumulation through a convergent iteration y←Φ(y,u)\vb{y} \leftarrow \Phi(\vb{y}, \vb{u}). He proposed reusing the graph of Φ\Phi to iterate the adjoint with explicit stopping criteria set according to desired gradient accuracy, and showed that the gradient then reaches the same order of accuracy as the function value, at cost of the same order. That the adjoint iteration converges at the same rate as the original follows from the formula itself: its iteration matrix is ∂zg⊤\partial_{\vb{z}}g\T, with the same spectral radius as ∂zg\partial_{\vb{z}}g. The bounds turning this into stopping criteria come from contraction. If rk=zk−g(zk,θ)\vb{r}_k = \vb{z}_k - g(\vb{z}_k, \theta) is the forward residual,

∥zk−z∗∥≤∥rk∥1−ρ,\norm{\vb{z}_k - \vb{z}^*} \le \frac{\norm{\vb{r}_k}}{1 - \rho},

because zk−z∗=rk+g(zk)−g(z∗)\vb{z}_k - \vb{z}^* = \vb{r}_k + g(\vb{z}_k) - g(\vb{z}^*) and the last term is at most ρ∥zk−z∗∥\rho\norm{\vb{z}_k - \vb{z}^*}. And if the adjoint system is solved with residual s\vb{s}, that is, (I−∂zg)⊤u^=∇L+s(\mat{I} - \partial_{\vb{z}}g)\T\hat{\vb{u}} = \nabla L + \vb{s}, the gradient error is ∣(u^−u)⊤∂θg∣≤∥s∥ ∥∂θg∥/(1−ρ)\abs{(\hat{\vb{u}} - \vb{u})\T\partial_\theta g} \le \norm{\vb{s}}\,\norm{\partial_\theta g}/(1 - \rho). Two measurable residuals, two tolerances that can be set.

Bias appears when the forward iteration does not converge and the implicit formula is applied anyway. The formula assumes z\vb{z} is a fixed point: evaluated at zk\vb{z}_k with a large residual, it gives the gradient of another problem, neither the program you executed (that would be the unrolled one) nor the solution. The error is proportional to ∥rk∥/(1−ρ)\norm{\vb{r}_k}/(1 - \rho) and does not disappear by averaging: every optimizer step carries it in the same direction. And if gg stops being contractive during training (the spectral radius of ∂zg\partial_{\vb{z}}g crosses 1), the adjoint iteration diverges, and if the crossing eigenvalue passes through 1, the adjoint system becomes singular or nearly so and its solution enormous.

[ ]Unrolled, implicit and the adjoint iterationBrowser
import numpy as np
from scipy.sparse.linalg import gmres, LinearOperator

rng = np.random.default_rng(4)
n = 40
W0 = rng.normal(size=(n, n)); W0 = W0 + W0.T                 # simétrica: radio espectral = norma
W = 0.95 * W0 / np.linalg.norm(W0, 2)          # ||W||_2 = 0.95 y tanh' <= 1: g es una contracción con rho <= 0.95
x, b, y = rng.normal(size=n), 0.1 * rng.normal(size=n), rng.normal(size=n) * 0.5
theta = 0.7
g = lambda z, th: np.tanh(W @ z + th * x + b)

def desenrollado(k, th=theta):
    """k iteraciones desde z0 = 0 y la derivada exacta de L(z_k) respecto a theta (lo que da retropropagar por ellas)."""
    z, dz = np.zeros(n), np.zeros(n)
    for _ in range(k):
        D = 1 - np.tanh(W @ z + th * x + b) ** 2
        z, dz = g(z, th), D * (W @ dz + x)
    return z, (z - y) @ dz

def implicito(z, th=theta, iters=None):
    """Gradiente implícito evaluado en z: resuelve (I - J_z)^T u = dL/dz y devuelve u · dg/dtheta."""
    D = 1 - np.tanh(W @ z + th * x + b) ** 2
    Jz = D[:, None] * W
    gL = z - y
    if iters is None:                                   # resolución exacta (densa, n pequeño)
        u = np.linalg.solve((np.eye(n) - Jz).T, gL)
    else:                                               # iteración de punto fijo del adjunto: u <- J_z^T u + dL/dz
        u = np.zeros(n)
        for _ in range(iters):
            u = Jz.T @ u + gL
    return u @ (D * x)

z_ref, _ = desenrollado(3000)
G_ref = implicito(z_ref)
print(f"gradiente de referencia dL/dθ = {G_ref:.12f}")
print(" k   |z_k - z*|    error desenrollado   cociente    error implícito en z_k")
for k in (10, 25, 50, 75, 100, 125):
    zk, Gk = desenrollado(k)
    ez = np.linalg.norm(zk - z_ref)
    print(f"{k:3d}   {ez:.2e}      {abs(Gk - G_ref):.2e}         {abs(Gk - G_ref) / ez:7.1f}     {abs(implicito(zk) - G_ref):.2e}")

zs = [np.zeros(n)]
for _ in range(100):
    zs.append(g(zs[-1], theta))
e = [np.linalg.norm(z - z_ref) for z in zs]
D = 1 - np.tanh(W @ z_ref + theta * x + b) ** 2
print(f"tasa observada ≈ {np.exp(np.polyfit(np.arange(20, 100), np.log(e[20:100]), 1)[0]):.3f}"
      f"   (cota rho = 0.95;  radio espectral de J_z en z*: {np.max(np.abs(np.linalg.eigvals(D[:, None] * W))):.3f})")

# el adjunto: iteración de punto fijo frente a GMRES, cada producto es un VJP de g
A = LinearOperator((n, n), matvec=lambda u: u - W.T @ (D * u), dtype=float)   # (I - J_z)^T u
for m in (25, 50, 100):
    print(f"adjunto por punto fijo, {m:3d} iteraciones: error del gradiente {abs(implicito(z_ref, iters=m) - G_ref):.1e}")
cuenta = []
u, info = gmres(A, z_ref - y, rtol=1e-10, restart=n, callback=lambda r: cuenta.append(r), callback_type="pr_norm")
print(f"GMRES: {len(cuenta)} productos, error del gradiente {abs(u @ (D * x) - G_ref):.1e}")

The table confirms the theorem on a problem of size 40. The state converges at rate 0.7750.775, exactly the spectral radius of ∂zg\partial_{\vb{z}}g at z∗\vb{z}^* (the bound ρ=0.95\rho = 0.95 is pessimistic because tanh⁡′<1\tanh' < 1). The unrolled error is always above it, and their ratio grows almost linearly: 3.93.9, 9.09.0, 17.317.3, 25.625.6 and 33.933.9 for k=10,25,50,75,100k = 10, 25, 50, 75, 100, about k/3k/3 times (at k=125k = 125 the state is already at 10−1410^{-14} and the ratio begins to mix with rounding). The implicit gradient evaluated at zk\vb{z}_k has error on the order of the state’s, around 1.31.3 times. To obtain 10 gradient digits, unrolling needs about 100 iterations and 100 saved states; implicit differentiation needs the same number of forward iterations (not saved) and one adjoint system. That system converges at the same rate by fixed-point iteration (error 3.2×10−43.2\times 10^{-4}, 5.5×10−75.5\times 10^{-7} and 1.6×10−121.6\times 10^{-12} with 25, 50 and 100 iterations), and GMRES, which depends on eigenvalue distribution rather than spectral radius, solves it in 23 products. When I−∂zg\mat{I} - \partial_{\vb{z}}g is symmetric positive definite, for example if gg is a gradient step on a convex energy, the natural solver is CG: you will use it on the GPU.

ODE adjoints: discretize then differentiate, or differentiate then discretize

Let z′=f(z,θ)\vb{z}' = f(\vb{z}, \theta) on [0,T][0, T] with z(0)=z0\vb{z}(0) = \vb{z}_0 and a loss L=ℓ(z(T))L = \ell(\vb{z}(T)). The continuous adjoint method, which you saw alongside ODE sensitivity, defines a(t)=∂L/∂z(t)\vb{a}(t) = \partial L/\partial\vb{z}(t) and gives

a′=−(∂f∂z)⊤a,a(T)=∇ℓ(z(T)),dLdθ=∫0Ta(t)⊤∂f∂θ(z(t),θ) dt.\vb{a}' = -\Big(\frac{\partial f}{\partial\vb{z}}\Big)\T\vb{a}, \quad \vb{a}(T) = \nabla\ell(\vb{z}(T)), \qquad \frac{dL}{d\theta} = \int_0^T \vb{a}(t)\T\frac{\partial f}{\partial\theta}(\vb{z}(t), \theta)\,dt.

On a computer something must be discretized, and order matters. This is the distinction between discrete and continuous adjoints:

  • Discretize then differentiate (discrete adjoint). Integrate with a specific method, for example RK4 with NN steps, and apply reverse mode to the resulting program. You obtain the exact gradient of the loss you computed, Lh(θ)L_h(\theta), up to rounding. It needs the states of each step (and stage) in the backward pass.
  • Differentiate then discretize (continuous adjoint). Numerically integrate the adjoint equation backward, along with the integral of dL/dθdL/d\theta. You obtain an approximation of the exact loss gradient, with discretization error of the integrator’s order. And you need z(t)\vb{z}(t) at every time the integrator evaluates ∂f/∂z\partial f/\partial\vb{z}.

Where does that z(t)\vb{z}(t) come from? There are three options: save the trajectory (memory O(N)\bigO(N), like the discrete adjoint), recompute it from checkpoints (see the next section), or reconstruct it by integrating the ODE backward alongside the adjoint, from the final z(T)\vb{z}(T). The third was proposed by Chen, Rubanova, Bettencourt and Duvenaud (2018) for Neural ODEs: an augmented system (z,a,g)(\vb{z}, \vb{a}, \vb{g}) integrated from TT to 0 with constant memory; their paper’s abstract specifically highlights that these continuous-depth models have constant memory cost.

The catch is that integrating backward means integrating another dynamical system, z′=−f\vb{z}' = -f, whose linearization eigenvalues are those of ff with signs reversed. A mode damped forward as e−κte^{-\kappa t} grows backward as eκte^{\kappa t}. In a stiff or dissipative system, any difference between reconstructed and true z\vb{z} (rounding, or simply that a backward RK4 step is not the exact inverse of the forward step) is exponentially amplified, and the adjoint is evaluated at states unrelated to the trajectory. In a chaotic system the same happens with the attractor’s contractive part: in Lorenz, phase-space volumes contract as e−(σ+1+β)t=e−13.67te^{-(\sigma + 1 + \beta)t} = e^{-13.67t}, so backward they expand equally fast. Gholami, Keutzer and Biros (2019) identified this problem in Neural ODEs and proposed returning to the discrete adjoint with checkpointing.

InteractiveThe adjoint travels backward
State: forward trajectory (solid) and backward reconstructed state (dashed)
Adjoint a(t)=∂L/∂z(t)a(t) = \partial L/\partial z(t) of the selected mode (color) and discrete adjoint (grey)
  • component z1z_1
  • component z2z_2
  • backward reconstruction
  • discrete adjoint (reference)
System
50
Gradient
t = 0.00
z1′=−θz1+z2,  z2′=10 (z12−z2)z_1' = -\theta z_1 + z_2,\ \ z_2' = 10\,(z_1^2 - z_2)
θ=2\theta = 2
the parameter being differentiated with respect to
dL/dθdL/d\theta discrete adjoint−0.003684
central difference of the program−0.003684 (rel. error 4.4e-12)
continuous, stored zz−0.003684 (4.4e-7)
continuous, reconstructed zz−0.002396 (3.5e-1)
max⁡∥zrec−z∥\max\norm{z_{\mathrm{rec}} - z} on [0.00,T][0.00, T]4.1e+1
Backward reconstruction diverges from the trajectory: modes that decay forward grow exponentially backward, so the adjoint is evaluated at incorrect states.
Above, the trajectory computed forward with RK4 (solid line) and, in “reconstructed z” mode, the state the continuous adjoint obtains by integrating the ODE backward (dashed). Below, the chosen mode's adjoint a(t)\vb{a}(t) and, in gray, the discrete adjoint. Play the pass from TT to 0. In the stiff system, reconstruction diverges almost immediately and the gradient is wrong even though the forward trajectory is perfect. Switch to Lotka–Volterra: reconstruction holds. In Lorenz, increase the horizon TT. Always compare the readouts: the discrete adjoint matches the program's own centered difference; the continuous ones only up to discretization error, and reconstruction only while it stays close.

The stiff system in the figure is z1′=−θz1+z2z_1' = -\theta z_1 + z_2, z2′=10(z12−z2)z_2' = 10(z_1^2 - z_2): a slow variable and a fast one that relaxes toward z12z_1^2 with time constant 0.10.1. Forward, RK4 with h=0.04h = 0.04 is stable and accurate. Backward, the fast mode grows as e10te^{10t} and at T=2T = 2 that is e20≈5×108e^{20} \approx 5\times 10^8: reconstruction blows up, the adjoint is evaluated where it should not be, and the gradient has relative error of tens of percent. The continuous adjoint with stored trajectory and the discrete adjoint agree up to discretization error. In Lotka–Volterra, which conserves a quantity and has no dissipative modes, all three options agree. And in Lorenz, with T=1.5T = 1.5 reconstruction is already lost.

[ ]Discrete RK4 adjoint versus continuous adjointBrowser
import numpy as np

def rk4_paso(f, z, th, h):
    k1 = f(z, th); k2 = f(z + h / 2 * k1, th); k3 = f(z + h / 2 * k2, th); k4 = f(z + h * k3, th)
    return z + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4), (k1, k2, k3)

def adjunto_discreto(f, fz, fth, z0, th, T, N, dLdz):
    """Gradiente exacto del programa RK4: pasada hacia delante guardando estados y VJP de cada paso al revés."""
    h = T / N; zs = [z0]
    for _ in range(N):
        zs.append(rk4_paso(f, zs[-1], th, h)[0])
    a, gth = dLdz(zs[-1]), 0.0
    for z in reversed(zs[:-1]):
        _, (k1, k2, k3) = rk4_paso(f, z, th, h)
        y1, y2, y3, y4 = z, z + h / 2 * k1, z + h / 2 * k2, z + h * k3     # puntos donde se evaluó f
        kb4, kb3, kb2, kb1 = h / 6 * a, h / 3 * a, h / 3 * a, h / 6 * a  # adjuntos de las etapas k_i
        nuevo = a.copy()
        r = fz(y4, th).T @ kb4; nuevo += r; kb3 = kb3 + h * r;     gth += fth(y4, th) @ kb4
        r = fz(y3, th).T @ kb3; nuevo += r; kb2 = kb2 + h / 2 * r; gth += fth(y3, th) @ kb3
        r = fz(y2, th).T @ kb2; nuevo += r; kb1 = kb1 + h / 2 * r; gth += fth(y2, th) @ kb2
        nuevo += fz(y1, th).T @ kb1;                               gth += fth(y1, th) @ kb1
        a = nuevo
    return zs, gth

def adjunto_continuo(f, fz, fth, zT, th, T, N, dLdz, z_guardada=None):
    """Integra hacia atrás con RK4 el sistema aumentado (z, a, g): z' = f, a' = -f_z^T a, g' = -f_th^T a.
    Si z_guardada (estados en la rejilla de paso h/2) no es None, usa la trayectoria guardada en vez de reconstruirla."""
    h = T / N; d = len(zT)
    def F(s, zz=None):
        z = s[:d] if zz is None else zz
        a = s[d:2 * d]
        return np.concatenate([f(z, th), -fz(z, th).T @ a, [-(fth(z, th) @ a)]])
    s = np.concatenate([zT, dLdz(zT), [0.0]])
    rec = [zT]
    for i in range(N, 0, -1):
        if z_guardada is None:
            k1 = F(s); k2 = F(s - h / 2 * k1); k3 = F(s - h / 2 * k2); k4 = F(s - h * k3)
        else:
            zi, zm, zp = z_guardada[2 * i], z_guardada[2 * i - 1], z_guardada[2 * i - 2]
            k1 = F(s, zi); k2 = F(s - h / 2 * k1, zm); k3 = F(s - h / 2 * k2, zm); k4 = F(s - h * k3, zp)
        s = s - h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
        rec.append(s[:d].copy())
    return np.array(rec[::-1]), s[-1]

def comparar(nombre, f, fz, fth, z0, th, T, N, objetivo):
    dLdz = lambda z: z - objetivo
    L = lambda zz: 0.5 * np.sum((zz - objetivo) ** 2)
    zs, g_disc = adjunto_discreto(f, fz, fth, z0, th, T, N, dLdz)
    final = lambda t: adjunto_discreto(f, fz, fth, z0, t, T, N, dLdz)[0][-1]
    eps = 1e-6
    g_fd = (L(final(th + eps)) - L(final(th - eps))) / (2 * eps)
    rec, g_rec = adjunto_continuo(f, fz, fth, zs[-1], th, T, N, dLdz)
    zf = [z0]
    for _ in range(2 * N):
        zf.append(rk4_paso(f, zf[-1], th, T / (2 * N))[0])
    _, g_guard = adjunto_continuo(f, fz, fth, zs[-1], th, T, N, dLdz, z_guardada=zf)
    _, g_fino = adjunto_discreto(f, fz, fth, z0, th, T, 20 * N, dLdz)   # referencia del gradiente de la EDO
    print(f"{nombre}  (h = {T / N:g})")
    print(f"  discreto                  {g_disc: .10e}   frente a la diferencia central del programa: {abs(g_disc - g_fd) / abs(g_fd):.1e}")
    print(f"  errores relativos frente al gradiente de la EDO (h/20):  discreto {abs(g_disc - g_fino) / abs(g_fino):.1e},"
          f"  continuo con z guardada {abs(g_guard - g_fino) / abs(g_fino):.1e},  continuo reconstruyendo z {abs(g_rec - g_fino) / abs(g_fino):.1e}")
    print(f"  |z reconstruida(0) - z(0)| = {np.linalg.norm(rec[0] - z0):.1e}")

# rígido: z1 lenta, z2 rápida (constante de tiempo 0.1) acoplada de forma no lineal
f = lambda z, th: np.array([-th * z[0] + z[1], 10 * (z[0] ** 2 - z[1])])
fz = lambda z, th: np.array([[-th, 1.0], [20 * z[0], -10.0]])
fth = lambda z, th: np.array([-z[0], 0.0])
comparar("rígido", f, fz, fth, np.array([1.0, 0.0]), 2.0, 2.0, 50, np.array([0.0, 0.0]))

# Lotka-Volterra, theta = alfa (tasa de crecimiento de las presas)
f = lambda z, th: np.array([th * z[0] - 0.4 * z[0] * z[1], 0.1 * z[0] * z[1] - 0.4 * z[1]])
fz = lambda z, th: np.array([[th - 0.4 * z[1], -0.4 * z[0]], [0.1 * z[1], 0.1 * z[0] - 0.4]])
fth = lambda z, th: np.array([z[0], 0.0])
comparar("Lotka-Volterra", f, fz, fth, np.array([10.0, 5.0]), 1.1, 15.0, 300, np.array([5.0, 5.0]))

Three results should be separated. The discrete adjoint agrees with the program’s own centered difference up to its error (on the order of 10−1010^{-10}) in both systems: it is the gradient of what you computed. Relative to the ODE gradient (approximated with a step 20 times smaller, whose RK4 error is about 204=160 00020^4 = 160\,000 times smaller), the discrete adjoint and the continuous one with stored trajectory have comparable errors, those of RK4 at that step: neither is “the right one”; each approximates something different. And the continuous one reconstructing z\vb{z} fails in the stiff system, with relative error on the order of 0.350.35 and a reconstructed state at t=0t = 0 tens of units from the true one, while in Lotka–Volterra it agrees with the others.

There is another reason to prefer the discrete adjoint when the gradient feeds an optimizer: it is consistent with the computed objective function. A line search checks that LhL_h decreases in the gradient direction; with the continuous adjoint, the gradient belongs to another function (exact LL) and the search can fail near the optimum, where discretization errors dominate. For Runge–Kutta methods the discrete adjoint is also known to be a (partitioned) Runge–Kutta method applied to the adjoint equation; Hager (2000) gave conditions for it to retain the method’s order, and Sanz-Serna (2016) explains the relation to symplectic integrators.

Checkpointing binomial

The discrete adjoint needs states x0,…,xn−1\vb{x}_0, \dots, \vb{x}_{n-1} in reverse order. Saving them all costs nn states; saving none forces recomputation from x0\vb{x}_0 for each step, n(n−1)/2n(n - 1)/2 advances. Checkpointing is in between: save a few states (checkpoints) and recompute the rest when needed. It addresses the previous lesson’s reverse-mode memory cost.

The model. A chain xi=Fi(xi−1)\vb{x}_i = F_i(\vb{x}_{i-1}), i=1,…,ni = 1, \dots, n. There are ss memory slots for states (checkpoints, one initially occupied by x0\vb{x}_0), in addition to the working state. An advance computes xi\vb{x}_i from xi−1\vb{x}_{i-1} without recording and costs 1. Reversing step ii requires xi−1\vb{x}_{i-1}: it records and backpropagates it, and its cost (the same for any schedule) is not counted. A schedule’s repetition is the maximum number of times any one step is advanced.

Proof

Sketch of the constructive part, the Revolve recursion. If s=1s = 1, there is only one checkpoint, for x0\vb{x}_0: reversing step jj requires advancing from x0\vb{x}_0 to xj−1\vb{x}_{j-1}, and step 1 is advanced n−1n - 1 times, so β(1,r)=r+1\beta(1, r) = r + 1. If s≥2s \ge 2, advance mm steps from x0\vb{x}_0, save xm\vb{x}_m in a new checkpoint and first reverse segment m+1,…,nm + 1, \dots, n, which has s−1s - 1 checkpoints available (the one for x0\vb{x}_0 remains occupied) and all repetition rr. Then free xm\vb{x}_m and reverse segment 1,…,m1, \dots, m with ss checkpoints; its steps were already advanced once to reach xm\vb{x}_m, so within the segment they may only be advanced r−1r - 1 more times. Choosing m=β(s,r−1)m = \beta(s, r - 1) reverses

β(s,r)=β(s,r−1)+β(s−1,r)\beta(s, r) = \beta(s, r - 1) + \beta(s - 1, r)

steps, which is Pascal’s relation, and with β(s,0)=β(0,r)=1\beta(s, 0) = \beta(0, r) = 1 its solution is (s+rs)\binom{s + r}{s}. That no schedule does better, and the minimum-cost formula, are Griewank’s theorem (1992); the next cell checks them by exhaustive search over all recursive schedules for n≤120n \le 120.

∎

The consequence is in the title of Griewank’s paper: logarithmic growth. If you take s=rs = r, (2rr)≈4r/πr\binom{2r}{r} \approx 4^r/\sqrt{\pi r}, so with s≈log⁡4ns \approx \log_4 n checkpoints each step is recomputed about log⁡4n\log_4 n times. By the theorem’s formula, one million steps are reversed with 12 checkpoints and 9.9 times the forward-pass cost, instead of a million states. This is binomial checkpointing. Revolve (Griewank and Walther, 2000) is the reference implementation: it generates the optimal schedule as a sequence of actions (advance, save, restore, reverse).

InteractiveThe checkpointing schedule
02468101214161820time (steps executed) →forward steps
  • forward step without recording
  • reverse one step (record and backpropagate)
  • live checkpoint
  • advances per step, at right (magenta reaches r)
Problem
20
3
action 85 of 85
Live checkpoints now / peak0 / 3
Forward steps completed45 of 45
Steps reversed20 of 20
Maximum advances of any step3 (r = 3)
Store everything20 states, 19 forward steps
Equally spaced, 3 segments9 states, 36 forward steps
Binomial3 states, 45 forward steps
With s=3s = 3 and repetition r=3r = 3, up to (s+rs)=20\binom{s + r}{s} = 20 steps can be reversed. Minimum cost: r n−(s+rs+1)=45r\,n - \binom{s + r}{s + 1} = 45 forward steps.
Time advances to the right and state index upward. A rising blue stroke is an advance without recording; a falling magenta stroke reverses a step. Orange bars are checkpoints while alive: their number at each instant is memory. On the right is how many times each step was advanced; magenta bars reach repetition rr. Play the schedule and watch the staircase: the first segment is reversed with one fewer checkpoint and, when finished, its checkpoint is freed and reused by the segment to the left. Lower ss to 1 (quadratic) and raise it to 8; compare the readouts with saving everything and with the equally spaced schedule.

With n=20n = 20 and s=3s = 3, repetition is r=3r = 3 (because (53)=10<20≤(63)=20\binom{5}{3} = 10 < 20 \le \binom{6}{3} = 20) and the schedule makes 3⋅20−(64)=453\cdot 20 - \binom{6}{4} = 45 advances with 3 states in memory, versus 19 advances and 20 states when saving everything. The equally spaced schedule with 3 segments, what torch.utils.checkpoint_sequential does, saves the 3 segment starts and, when reversing each segment, all its states: 9 states and 36 advances. With s=1s = 1 the staircase becomes a triangle (190 advances), and with s=8s = 8 recomputation nearly disappears.

[ ]The binomial formula, checked by exhaustive searchBrowser
from functools import lru_cache
from math import comb

@lru_cache(maxsize=None)
def T(l, s):
    """Mínimo de avances para invertir l pasos con s puntos de control, uno de ellos ocupado por el inicio del tramo."""
    if l == 1:
        return 0
    if s == 1:
        return l * (l - 1) // 2               # sin más memoria: rehacer desde el principio para cada paso
    return min(m + T(l - m, s - 1) + T(m, s) for m in range(1, l))

@lru_cache(maxsize=None)
def R(l, s):
    """Mínimo, entre todos los esquemas recursivos, del número máximo de veces que se avanza un mismo paso."""
    if l == 1:
        return 0
    if s == 1:
        return l - 1
    return min(max(1 + R(m, s), R(l - m, s - 1)) for m in range(1, l))

beta = lambda s, r: comb(s + r, s)

ok = all(max(l for l in range(1, 130) if R(l, s) <= r) == beta(s, r) for s in range(1, 6) for r in range(1, 5) if beta(s, r) < 130)
print("pasos invertibles con s puntos de control y repetición r = C(s + r, s):", ok)
print("tabla de C(s + r, s):")
print("      " + "".join(f"r={r:<6d}" for r in range(1, 6)))
for s in range(1, 5):
    print(f"s = {s} " + "".join(f"{beta(s, r):<8d}" for r in range(1, 6)))

def t_griewank(l, s):
    r = next(r for r in range(0, l + 1) if beta(s, r) >= l)
    return r * l - comb(s + r, s + 1)
print("coste mínimo = r·n − C(s + r, s + 1) en todos los casos n ≤ 120, s ≤ 6:",
      all(T(l, s) == t_griewank(l, s) for l in range(1, 121) for s in range(1, 7)))

l = 1000
print(f"\nn = {l}: guardarlo todo usa {l} estados y {l - 1} avances")
for s in (2, 3, 5, 10, 20):
    t = t_griewank(l, s)
    r = next(r for r in range(l + 1) if beta(s, r) >= l)
    print(f"  s = {s:2d} puntos de control: {t:6d} avances  ({t / (l - 1):.2f} veces la pasada hacia delante), r = {r}")

The exhaustive search confirms both formulas. For n=1000n = 1000, with 10 checkpoints the cost is 3.643.64 times the forward pass, and with 20, 2.752.75 times; with 2, by contrast, almost 29 times. The curve is very flat beyond a few checkpoints: doubling memory from 10 to 20 saves only a third of recomputation.

Lab 2: torch.func, custom rules and an implicit layer on the GPU

PyTorch exposes composable transformations in torch.func: grad, jvp, vjp, jacrev, jacfwd, hessian (which is jacfwd(jacrev(f)), forward over reverse for the full Hessian) and vmap, in JAX’s style. In JAX, the reference for this style, the same ideas are written:

import jax, jax.numpy as jnp

hvp = lambda f, x, v: jax.jvp(jax.grad(f), (x,), (v,))[1]      # forward sobre reverse

@jax.custom_vjp
def lse(x):
    return jax.nn.logsumexp(x)
def lse_fwd(x):
    y = jax.nn.logsumexp(x)
    return y, (x, y)                                                # fwd: salida y residuos
lse.defvjp(lse_fwd,
           lambda res, g: (g * jnp.exp(res[0] - res[1]),))         # bwd: ȳ · softmax(x)

paso_sin_guardar = jax.checkpoint(lambda z: z + 0.1 * jnp.tanh(z))  # se recalcula en la pasada hacia atrás

The next cell, which runs locally on the GPU, compares Jacobian strategies in time, measures the three compositions for the HVP of an MLP with about 200,000 parameters, writes the logsumexp rule as torch.autograd.Function and builds a fixed-point layer differentiated implicitly with CG.

The layer is the minimum of a convex energy,

z∗(x,U)=arg min⁡z 12∥z∥2+λ∑ilog⁡cosh⁡zi−(Ux)⊤z,\vb{z}^*(\vb{x}, \mat{U}) = \argmin_{\vb{z}}\ \tfrac12\norm{\vb{z}}^2 + \lambda\sum_i\log\cosh z_i - (\mat{U}\vb{x})\T\vb{z},

which is also the fixed point of gradient step z←z−α∇zE\vb{z} \leftarrow \vb{z} - \alpha\nabla_{\vb{z}}E. Its optimality condition is F=∇zE=0F = \nabla_{\vb{z}}E = \vb{0}, Hessian H=I+λdiag⁡(sech⁡2zi)\mat{H} = \mat{I} + \lambda\diag(\operatorname{sech}^2 z_i) is symmetric positive definite, and the implicit formula gives Uˉ=−(∂UF)⊤u\bar{\mat{U}} = -(\partial_{\mat{U}}F)\T\vb{u} with Hu=zˉ\mat{H}\vb{u} = \bar{\vb{z}}: a system CG solves using only HVPs of EE, which here are JVPs of ∇zE\nabla_{\vb{z}}E.

[ ]torch.func, custom rules and an implicit layer on the GPULocal GPU
import time
import torch
from torch.func import jacrev, jacfwd, vmap, vjp, jvp, grad

dev = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(0)

def cronometra(fn, rep=10):
    fn()                                                   # calentamiento (compilación de núcleos, cachés)
    if dev == "cuda": torch.cuda.synchronize()
    t = time.perf_counter()
    for _ in range(rep):
        fn()
    if dev == "cuda": torch.cuda.synchronize()
    return (time.perf_counter() - t) / rep

# 1) jacrev frente a jacfwd según la forma del jacobiano
n_grande, oculta = 8000, 2048
A = torch.randn(oculta, n_grande, device=dev) / n_grande**0.5
B = torch.randn(4, oculta, device=dev) / oculta**0.5
ancha = lambda x: B @ torch.tanh(A @ x)                    # R^8000 -> R^4: pocas salidas
alta = lambda x: torch.tanh(A.T @ torch.tanh(B.T @ x))     # R^4 -> R^8000: pocas entradas
x_ancha, x_alta = torch.randn(n_grande, device=dev), torch.randn(4, device=dev)
for nombre, f, x in (("R^8000 -> R^4", ancha, x_ancha), ("R^4 -> R^8000", alta, x_alta)):
    tr, tf = cronometra(lambda: jacrev(f)(x)), cronometra(lambda: jacfwd(f)(x))
    err = (jacrev(f)(x) - jacfwd(f)(x)).abs().max().item()
    print(f"{nombre}: jacfwd / jacrev = {tf / tr:7.2f}   jacrev / jacfwd = {tr / tf:7.2f}   (|diferencia| = {err:.1e})")

# vmap frente a un bucle de Python de VJPs (las filas del jacobiano de la función ancha)
_, f_vjp = vjp(ancha, x_ancha)
I4 = torch.eye(4, device=dev)
t_bucle = cronometra(lambda: torch.stack([f_vjp(I4[i])[0] for i in range(4)]))
t_vmap = cronometra(lambda: vmap(f_vjp)(I4)[0])
print(f"4 VJPs: bucle / vmap = {t_bucle / t_vmap:.1f}")

# 2) HVP de la pérdida de un MLP de unos 200 000 parámetros, sin formar el hessiano
X = torch.randn(4096, 784, device=dev); y = torch.randint(0, 10, (4096,), device=dev)
formas = [(256, 784), (256,), (10, 256), (10,)]
tam = [torch.Size(s).numel() for s in formas]
def perdida(theta):
    W1, b1, W2, b2 = [t.view(s) for t, s in zip(torch.split(theta, tam), formas)]
    return torch.nn.functional.cross_entropy(torch.tanh(X.to(theta.dtype) @ W1.T + b1) @ W2.T + b2, y)
p = sum(tam)
theta = torch.randn(p, device=dev) * 0.05
v = torch.randn(p, device=dev)
print(f"\nMLP: {p} parámetros; el hessiano en float32 ocuparía {p * p * 4 / 1e9:.0f} GB")

fwd_sobre_rev = lambda: jvp(grad(perdida), (theta,), (v,))[1]
rev_sobre_rev = lambda: grad(lambda t: grad(perdida)(t) @ v)(theta)
rev_sobre_fwd = lambda: grad(lambda t: jvp(perdida, (t,), (v,))[1])(theta)
ref = fwd_sobre_rev()
t_grad = cronometra(lambda: grad(perdida)(theta))
for nombre, fn in (("forward sobre reverse", fwd_sobre_rev), ("reverse sobre reverse", rev_sobre_rev), ("reverse sobre forward", rev_sobre_fwd)):
    if dev == "cuda":
        torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
        base = torch.cuda.memory_allocated()
    r = fn()
    pico = (torch.cuda.max_memory_allocated() - base) / 2**20 if dev == "cuda" else float("nan")
    print(f"{nombre}: tiempo / gradiente = {cronometra(fn) / t_grad:4.1f}   memoria pico extra = {pico:6.1f} MiB"
          f"   |diferencia| relativa = {((r - ref).norm() / ref.norm()).item():.1e}")
eps = 1e-6                                                  # diferencia central de gradientes en float64
g64 = grad(perdida)
vd = v.double()
dif = (g64(theta.double() + eps * vd) - g64(theta.double() - eps * vd)) / (2 * eps)
print(f"diferencia central de gradientes (float64) frente al HVP (float32): error relativo {((dif.float() - ref).norm() / ref.norm()).item():.1e}")

# 3) logsumexp con regla propia
class LogSumExp(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x):
        m = x.max(dim=-1, keepdim=True).values
        y = m.squeeze(-1) + torch.log(torch.exp(x - m).sum(-1))
        ctx.save_for_backward(x, y)                        # se guardan x e y, no los exponenciales intermedios
        return y
    @staticmethod
    def backward(ctx, ybar):
        x, y = ctx.saved_tensors
        return ybar.unsqueeze(-1) * torch.exp(x - y.unsqueeze(-1))   # ȳ · softmax(x)

x = torch.tensor([[1000.0, 999.0, 998.0]], dtype=torch.float64, requires_grad=True)
ingenua = torch.log(torch.exp(x).sum(-1))
ingenua.backward()
print(f"\nlogsumexp ingenua: valor {ingenua.item()}, gradiente {x.grad.tolist()}")
x.grad = None
LogSumExp.apply(x).backward()
print(f"logsumexp con regla propia: gradiente {[round(g, 6) for g in x.grad[0].tolist()]}")
xg = (torch.randn(5, 7, dtype=torch.float64) * 30).requires_grad_()
print("gradcheck de la regla:", torch.autograd.gradcheck(LogSumExp.apply, (xg,)))

# 4) una capa de punto fijo diferenciada implícitamente con CG
lam, alfa = 4.0, 0.15

def grad_E(z, x, U):
    return z + lam * torch.tanh(z) - x @ U.T

def resolver(x, U, iters):
    z = torch.zeros(x.shape[0], U.shape[0], device=x.device)
    for _ in range(iters):
        z = z - alfa * grad_E(z, x, U)                     # contracción: H tiene autovalores en [1, 1 + lam]
    return z

def cg(Hmul, b, tol=1e-6, maxit=100):
    u = torch.zeros_like(b); r = b.clone(); d = r.clone(); rr = (r * r).sum()
    for k in range(maxit):
        Hd = Hmul(d); a = rr / (d * Hd).sum()
        u = u + a * d; r = r - a * Hd; rr_n = (r * r).sum()
        if rr_n.sqrt() < tol * b.norm():
            break
        d = r + rr_n / rr * d; rr = rr_n
    return u, k + 1

class CapaImplicita(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, U, iters):
        with torch.no_grad():
            z = resolver(x, U, iters)                       # no se graba ninguna iteración
        ctx.save_for_backward(z, x, U)
        return z
    @staticmethod
    def backward(ctx, zbar):
        z, x, U = ctx.saved_tensors
        Hmul = lambda u: jvp(lambda zz: grad_E(zz, x, U), (z,), (u,))[1]     # HVP de E: un JVP de grad_E
        u, its = cg(Hmul, zbar)
        CapaImplicita.its = its
        _, vjp_U = vjp(lambda UU: grad_E(z, x, UU), U)                       # Ū = -(dF/dU)^T u
        return None, -vjp_U(u)[0], None

Bsz, din, dz, K = 512, 512, 1024, 200
x = torch.randn(Bsz, din, device=dev)
U = (torch.randn(dz, din, device=dev) / din**0.5).requires_grad_()
objetivo = torch.randn(Bsz, dz, device=dev) * 0.1
for nombre, capa in (("desenrollada", lambda: resolver(x, U, K)), ("implícita + CG", lambda: CapaImplicita.apply(x, U, K))):
    U.grad = None
    if dev == "cuda":
        torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats(); base = torch.cuda.memory_allocated()
    z = capa()
    L = ((z - objetivo) ** 2).mean()
    L.backward()
    pico = (torch.cuda.max_memory_allocated() - base) / 2**20 if dev == "cuda" else float("nan")
    if nombre == "desenrollada":
        g_des = U.grad.clone()
        print(f"\ncapa {nombre}: {K} iteraciones, memoria pico {pico:7.1f} MiB")
    else:
        print(f"capa {nombre}: {CapaImplicita.its} productos H·u en CG, memoria pico {pico:7.1f} MiB,"
              f" diferencia relativa con el desenrollado {((U.grad - g_des).norm() / g_des.norm()).item():.1e}")
with torch.no_grad():
    zK = resolver(x, U, K)
    print(f"residuo relativo del punto fijo tras {K} iteraciones: {grad_E(zK, x, U).norm().item() / zK.norm().item():.1e}")
    for k in (10, 20, 40):
        print(f"  con {k:2d} iteraciones: {grad_E(resolver(x, U, k), x, U).norm().item() / zK.norm().item():.1e}")
del x, U, objetivo, zK, A, B, X
if dev == "cuda":
    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.

On the RTX 4060, the two extreme Jacobian shapes reverse the winner as the table predicts: for R8000→R4\R^{8000} \to \R^4, jacfwd (8000 vectorized JVPs) was 25 to 63 times slower than jacrev (4 VJPs) in three check runs, and for R4→R8000\R^4 \to \R^{8000}, jacrev was 18 to 29 times slower than jacfwd. Exact ratios depend on GPU load; the order of magnitude does not. vmap over the 4 VJPs was about 3 times faster than the Python loop. All three compositions give the same HVP (relative differences of 10−710^{-7}, float32 rounding), agreeing with the centered gradient difference computed in float64 to 5×10−75\times 10^{-7}, for between 1.5 and 4 gradients each depending on the run; in this PyTorch MLP, unlike the JAX guide measurement, reverse over reverse was not more expensive in time or memory: the weight of recording the backward pass depends on how the library implements the second derivative. What does not depend on that is the Hessian: 166 GB in float32 for a small MLP. The logsumexp rule gives softmax where the naive version gives inf and nan, and gradcheck accepts it.

The implicit layer is the central result: with 200 forward iterations, unrolling peaked at about 410 MiB and the implicit version at about 21 MiB, roughly 20 times less, with a gradient matching the unrolled one to 6.5×10−76.5\times 10^{-7} in relative norm (what float32 permits after 200 iterations) and obtained by CG in 10 products. The residual shows why so many forward iterations are needed: with 10 iterations the fixed point is far away (10−310^{-3} relative) and the implicit formula applied there would be biased.

Lab 3: discrete adjoint, continuous adjoint and checkpointing

The final lab brings the pieces together on a calibration problem: fit the four parameters of a Lotka–Volterra model to 30 noisy observations of both populations. The gradient is computed three ways: (a) backpropagating with PyTorch through 300 RK4 steps, the discrete adjoint; (b) with a handwritten continuous adjoint, with adjoint jumps at each observation and the state reconstructed backward; and (c) with custom binomial checkpointing over RK4, using the previous cell’s dynamic programming to decide where to save. Then parameters are fitted with L-BFGS-B and the comparison is repeated in the Lorenz system’s chaotic regime.

[ ]Lotka–Volterra: three gradients, custom checkpointing and LorenzLocal GPU
import time
import torch
from torch.func import vjp
from functools import lru_cache

torch.set_default_dtype(torch.float64)

# ---------------- el modelo y los datos ----------------
def lv(z, th):
    a, b, d, g = th
    x, y = z[0], z[1]
    return torch.stack([a * x - b * x * y, d * x * y - g * y])

def paso_rk4(f, z, th, h):
    k1 = f(z, th); k2 = f(z + h / 2 * k1, th); k3 = f(z + h / 2 * k2, th); k4 = f(z + h * k3, th)
    return z + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

T, N = 15.0, 300
h = T / N
z0 = torch.tensor([10.0, 5.0])
th_real = torch.tensor([1.1, 0.4, 0.1, 0.4])
obs_cada = 10                                      # una observación cada 10 pasos (cada 0.5 unidades de tiempo)
gen = torch.Generator().manual_seed(0)
with torch.no_grad():
    z, datos = z0.clone(), {}
    for j in range(1, N + 1):
        z = paso_rk4(lv, z, th_real, h)
        if j % obs_cada == 0:
            datos[j] = z + 0.3 * torch.randn(2, generator=gen)
n_obs = len(datos)
termino = lambda j, z: 0.5 * ((z - datos[j]) ** 2).sum() / n_obs if j in datos else z.new_zeros(())

# ---------------- (a) adjunto discreto: retropropagar por el RK4 ----------------
def perdida_rk4(th):
    z, L = z0, 0.0
    for j in range(1, N + 1):
        z = paso_rk4(lv, z, th, h)
        L = L + termino(j, z)
    return L

def con_bytes_guardados(fn):
    """Ejecuta fn y suma los bytes de los tensores que autograd guarda para la pasada hacia atrás."""
    total = [0]
    def empaqueta(t):
        total[0] += t.numel() * t.element_size()
        return t
    with torch.autograd.graph.saved_tensors_hooks(empaqueta, lambda t: t):
        out = fn()
    return out, total[0]

th0 = torch.tensor([0.8, 0.3, 0.15, 0.5])
def grad_discreto(th):
    th = th.clone().requires_grad_()
    L, bytes_ = con_bytes_guardados(lambda: perdida_rk4(th))
    L.backward()
    return L.item(), th.grad.clone(), bytes_

# ---------------- (b) adjunto continuo a mano, reconstruyendo z hacia atrás ----------------
def grad_continuo(th):
    with torch.no_grad():
        z = z0.clone()
        for j in range(1, N + 1):
            z = paso_rk4(lv, z, th, h)
    def aumentado(s, th):                                   # s = (z, a, g): z' = f, a' = -f_z^T a, g' = -f_th^T a
        zz, a = s[:2], s[2:4]
        fz, f_vjp = vjp(lambda zz_, th_: lv(zz_, th_), zz, th)
        az, ath = f_vjp(a)
        return torch.cat([fz, -az, -ath])
    a = torch.autograd.grad(termino(N, z.requires_grad_()), z)[0]
    s = torch.cat([z.detach(), a, torch.zeros(4)])
    for j in range(N, 0, -1):
        s = paso_rk4(aumentado, s, th, -h)                  # un paso hacia atrás en el tiempo
        if j - 1 in datos:                                  # salto del adjunto en cada observación
            zj = s[:2].clone().requires_grad_()
            s = s.clone(); s[2:4] += torch.autograd.grad(termino(j - 1, zj), zj)[0]
    return s[4:], torch.linalg.norm(s[:2] - z0).item()

# ---------------- (c) checkpointing binomial propio sobre el RK4 ----------------
@lru_cache(maxsize=None)
def coste(l, s):
    """(mínimo de avances, división óptima m) para invertir l pasos con s puntos de control."""
    if l == 1: return 0, 0
    if s == 1: return l * (l - 1) // 2, 0
    return min((m + coste(l - m, s - 1)[0] + coste(m, s)[0], m) for m in range(1, l))

class Revolve:
    def __init__(self, th, s):
        self.th, self.s = th, s
        self.avances, self.vivos, self.pico, self.g = 0, 1, 1, torch.zeros(4)   # z0 ocupa el primero
    def avanzar(self, z, k):
        with torch.no_grad():
            for _ in range(k):
                z = paso_rk4(lv, z, self.th, h); self.avances += 1
        return z
    def invertir_paso(self, j, z, abar):                      # paso j: de z_(j-1) a z_j, grabado y retropropagado
        z = z.clone().requires_grad_(); th = self.th.clone().requires_grad_()
        y = paso_rk4(lv, z, th, h)
        gz, gth = torch.autograd.grad((y * abar).sum() + termino(j, y), (z, th))
        self.g += gth
        return gz
    def invertir(self, i, l, s, zi, abar):                    # invierte los pasos i+1..i+l; zi ocupa un punto de control
        if l == 1:
            abar = self.invertir_paso(i + 1, zi, abar)
        elif s == 1:
            for j in range(l, 0, -1):
                abar = self.invertir_paso(i + j, self.avanzar(zi, j - 1), abar)
        else:
            m = coste(l, s)[1]
            zm = self.avanzar(zi, m)
            self.vivos += 1; self.pico = max(self.pico, self.vivos)     # z_(i+m) ocupa un punto de control nuevo
            abar = self.invertir(i + m, l - m, s - 1, zm, abar)
            self.vivos -= 1                                             # se libera y lo reutiliza el tramo izquierdo
            abar = self.invertir(i, m, s, zi, abar)
        return abar

def grad_revolve(th, s):
    r = Revolve(th, s)
    r.invertir(0, N, s, z0, torch.zeros(2))
    return r.g, r.avances, r.pico

# ---------------- comparación ----------------
def dif_finitas(th, eps=1e-6):
    g = torch.zeros(4)
    with torch.no_grad():
        for k in range(4):
            e = torch.zeros(4); e[k] = eps
            g[k] = (perdida_rk4(th + e) - perdida_rk4(th - e)) / (2 * eps)
    return g

def mide(fn, rep=3):
    t = time.perf_counter()
    for _ in range(rep): out = fn()
    return out, (time.perf_counter() - t) / rep

g_fd = dif_finitas(th0)
(L0, g_a, bytes_a), t_a = mide(lambda: grad_discreto(th0))
(g_b, rec_err), t_b = mide(lambda: grad_continuo(th0))
rel = lambda g: ((g - g_fd).norm() / g_fd.norm()).item()
print(f"Lotka-Volterra, N = {N} pasos de RK4, {n_obs} observaciones, pérdida inicial {L0:.4f}")
print(f"gradiente por diferencias del programa: {[round(v, 6) for v in g_fd.tolist()]}")
print(f"(a) adjunto discreto (autograd): error relativo {rel(g_a):.1e}, tensores guardados {bytes_a / 1024:.0f} KiB, tiempo 1.00")
print(f"(b) adjunto continuo:            error relativo {rel(g_b):.1e}, estado de tamaño fijo, tiempo {t_b / t_a:.2f},"
      f" |z reconstruida(0) - z0| = {rec_err:.1e}")
for s in (3, 6, 12):
    (g_c, avances, pico), t_c = mide(lambda: grad_revolve(th0, s), rep=1)
    print(f"(c) binomial con s = {s:2d}: |g - g_autograd| = {(g_c - g_a).abs().max().item():.1e}, {pico} estados a la vez,"
          f" {avances} avances (óptimo {coste(N, s)[0]}), tiempo {t_c / t_a:.2f}")

# ajuste de los parámetros con L-BFGS-B y el gradiente del adjunto discreto. Las cotas impiden que la búsqueda
# lineal pruebe parámetros con los que la EDO explota (sin ellas, un paso largo da inf y la búsqueda se pierde)
import numpy as np
from scipy.optimize import minimize
evals = [0]
def valor_y_grad(p):
    th = torch.tensor(p).requires_grad_()
    L = perdida_rk4(th); L.backward(); evals[0] += 1
    return L.item(), th.grad.numpy().copy()
r = minimize(valor_y_grad, th0.numpy(), jac=True, method="L-BFGS-B", bounds=[(0.05, 3.0)] * 4)
print(f"L-BFGS-B: {r.nit} iteraciones, {evals[0]} gradientes, pérdida final {r.fun:.4f}, theta = {np.round(r.x, 3).tolist()}")
print("parámetros con los que se generaron los datos:", th_real.tolist(), " pérdida esperada del ruido ≈ 0.3² = 0.09")

# ---------------- Lorenz: el régimen caótico ----------------
def lorenz(z, th):
    rho = th[0]
    return torch.stack([10.0 * (z[1] - z[0]), z[0] * (rho - z[2]) - z[1], z[0] * z[1] - 8.0 / 3.0 * z[2]])

print("\nLorenz, theta = rho = 28, L = |z(T)|^2 / 2, RK4 con h = 0.01")
zL0 = torch.tensor([1.0, 1.0, 20.0])
for TL in (0.5, 1.0, 2.0, 5.0, 10.0, 20.0):
    NL, hL = int(round(TL / 0.01)), 0.01
    def LL(th):
        z = zL0
        for _ in range(NL): z = paso_rk4(lorenz, z, th, hL)
        return 0.5 * (z ** 2).sum(), z
    th = torch.tensor([28.0], requires_grad=True)
    (L, zT) = LL(th); L.backward(); g_disc = th.grad.item()
    def aumentado(s, th_):
        zz, a = s[:3], s[3:6]
        fz, f_vjp = vjp(lambda zz_, t_: lorenz(zz_, t_), zz, th_)
        az, ath = f_vjp(a)
        return torch.cat([fz, -az, -ath])
    s = torch.cat([zT.detach(), zT.detach(), torch.zeros(1)])
    th_d = torch.tensor([28.0])
    for _ in range(NL): s = paso_rk4(aumentado, s, th_d, -hL)
    with torch.no_grad():
        fd = lambda eps: ((LL(torch.tensor([28.0 + eps]))[0] - LL(torch.tensor([28.0 - eps]))[0]) / (2 * eps)).item()
        g_fd, g_fd2 = fd(1e-7), fd(1e-9)
    print(f"T = {TL:4.1f}: dL/drho discreto {g_disc: .3e}, diferencias (1e-7 y 1e-9) {g_fd: .3e} {g_fd2: .3e},"
          f" continuo reconstruido {s[6].item(): .3e}, |z reconstruida(0) - z0| = {torch.linalg.norm(s[:3] - zL0).item():.1e}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In Lotka–Volterra, the discrete adjoint matches the program’s differences with relative error 10−1010^{-10} and saves about 113 KiB of tensors for the backward pass, growing in proportion to NN. The continuous adjoint has error 6×10−76\times 10^{-7} (discretization error, because the system is not dissipative and reconstruction returns to z0\vb{z}_0 with error 3×10−73\times 10^{-7}) and uses constant memory. Binomial checkpointing reproduces the autograd gradient to 3×10−133\times 10^{-13} with 3, 6 or 12 states in memory, and the number of advances measured by the class exactly matches the dynamic-programming optimum: 2299, 1170 and 795 versus 299 for one pass. The cell also prints relative times, but do not take them as a cost measure: each step of this system is tiny, the Python interpreter dominates (step-by-step calls to torch.autograd.grad, VJPs of the augmented system), and in two check runs ratios changed by almost an order of magnitude. With expensive steps (a network block, a step of a large simulation), recomputation matters, and checkpointing cost approaches the number of advances divided by NN.

With the discrete-adjoint gradient, L-BFGS-B recovers the parameters used to generate the data, (1.1,0.4,0.1,0.4)(1.1, 0.4, 0.1, 0.4), with error of one or two hundredths, in about 25 iterations, and the final loss reaches the level corresponding to observation noise (≈0.09\approx 0.09). Bounds are not a detail: without them, line search tries a long step that makes the ODE blow up, the loss becomes inf and the optimizer gets lost.

In Lorenz the picture differs. The discrete adjoint and differences agree at every horizon where differences are reliable, and the gradient grows exponentially: from about 10210^2 with T=0.5T = 0.5 to 5.6×1045.6\times 10^4 with T=10T = 10 and 7.3×1077.3\times 10^7 with T=20T = 20. At T=20T = 20 the two finite differences no longer agree with each other (with ε=10−7\eps = 10^{-7} the result is ten times larger than with 10−910^{-9}, which does approach the discrete adjoint): the function is so rough at that scale that the difference is reliable only with tiny steps. The continuous adjoint with reconstruction already deviates at T=1T = 1 (error almost 8% and reconstructed state 1.71.7 units from the true one) and from T=2T = 2 overflows to nan: the volume contraction e−13.67te^{-13.67t}, reversed.

Common mistakes

Exercises

NumericPasses for a tridiagonal Jacobian
F:R1000→R1000F: \R^{1000} \to \R^{1000} has a tridiagonal Jacobian (each output FiF_i depends on xi−1x_{i-1}, xix_i and xi+1x_{i+1}). How many JVPs suffice to obtain it entirely with column coloring?
NumericThe arrow in two directions
J∈R1000×1000\mat{J} \in \R^{1000\times 1000} has nonzeros on the diagonal, throughout the last row and throughout the last column. What is the smallest total number of passes (JVPs plus VJPs) needed to obtain it if you can combine column and row coloring?
NumericHow many steps can be reversed?
With s=10s = 10 checkpoints and allowing each step to be advanced at most r=2r = 2 times, what is the largest number of steps reversible with the binomial schedule?
NumericThe minimum reversal cost
You must reverse n=100n = 100 steps with s=4s = 4 checkpoints. What is the minimum total number of advances (not counting recording each step when reversing it)?
QuizWhy forward over reverse?
To compute Hv\mat{H}\vb{v} of a neural network loss, why is forward over reverse often preferred to reverse over reverse?
QuizA poorly training DEQ
You train a Deep Equilibrium Model with an implicit gradient. When the forward solver fails to converge (stopping at the iteration limit with a large residual), training degrades. Why?
QuizThe lag in the affine case
If the iteration is affine in z\vb{z}, g(z,θ)=Az+b(θ)g(\vb{z}, \theta) = \mat{A}\vb{z} + \vb{b}(\theta) with ∥A∥≤ρ<1\norm{\mat{A}} \le \rho < 1, and z0=0\vb{z}_0 = \vb{0}, how does the unrolled derivative error ∥dzk/dθ−dz∗/dθ∥\norm{d\vb{z}_k/d\theta - d\vb{z}^*/d\theta} behave?
QuizWhich rules pass the test?
Which of these custom VJP rules pass the dot-product test (that is, return J⊤yˉ\mat{J}\T\bar{\vb{y}} of the function they compute forward)?

More than one answer may be correct.

QuizFixing a Neural ODE gradient
You train a Neural ODE with a continuous adjoint that reconstructs the state by integrating backward (like torchdiffeq's odeint_adjoint). The learned dynamics are highly dissipative and gradients are erratic even though the forward pass is accurate. What change addresses the cause?
ProofUnrolled derivatives lag behind
Prove: Let zk+1=g(zk,θ)\vb{z}_{k+1} = g(\vb{z}_k, \theta) with gg of class C1C^1 on a convex set containing the iterates, ∥∂zg∥≤ρ<1\norm{\partial_{\vb{z}}g} \le \rho < 1, ∂zg\partial_{\vb{z}}g and ∂θg\partial_\theta g Lipschitz in z\vb{z} with constants LAL_A and LBL_B, and z0\vb{z}_0 independent of θ\theta. Then Zk=dzk/dθ\mat{Z}_k = d\vb{z}_k/d\theta satisfies ∥Zk−Z∗∥≤ρk∥Z∗∥+c k ρk−1\norm{\mat{Z}_k - \mat{Z}^*} \le \rho^k\norm{\mat{Z}^*} + c\,k\,\rho^{k-1}, with c=(LA∥Z∗∥+LB)∥z0−z∗∥c = (L_A\norm{\mat{Z}^*} + L_B)\norm{\vb{z}_0 - \vb{z}^*}.
0
Call Ak=∂zg(zk,θ)\mat{A}_k = \partial_{\vb{z}}g(\vb{z}_k, \theta), Bk=∂θg(zk,θ)\mat{B}_k = \partial_\theta g(\vb{z}_k, \theta), and A∗\mat{A}^*, B∗\mat{B}^* the same Jacobians at z∗\vb{z}^*. Let Ek=Zk−Z∗\mat{E}_k = \mat{Z}_k - \mat{Z}^*.

Step 1 of 4. What equations do Zk\mat{Z}_k and Z∗\mat{Z}^* satisfy?

CodeAn HVP with forward over reverse
The starter code provides duals (Dual) and a tape (Var) whose values and local partials can be floats or duals. Implement grad(f, x), returning the list of derivatives ∂f/∂xi\partial f/\partial x_i by traversing the tape in reverse topological order and accumulating adjoints (they must work with floats and duals: do not convert anything to float), and hvp(f, x, v), returning H(x)v\mat{H}(\vb{x})\vb{v} as a NumPy array using forward over reverse. A variable can be used several times: its adjoint is the sum of all contributions.
import math
import numpy as np

class Dual:
  __slots__ = ("val", "tan")
  def __init__(self, val, tan=0.0): self.val, self.tan = val, tan
  def _d(o): return o if isinstance(o, Dual) else Dual(o, 0.0)
  def __add__(s, o): o = Dual._d(o); return Dual(s.val + o.val, s.tan + o.tan)
  __radd__ = __add__
  def __sub__(s, o): o = Dual._d(o); return Dual(s.val - o.val, s.tan - o.tan)
  def __rsub__(s, o): return Dual._d(o) - s
  def __mul__(s, o): o = Dual._d(o); return Dual(s.val * o.val, s.tan * o.val + s.val * o.tan)
  __rmul__ = __mul__
  def __truediv__(s, o): o = Dual._d(o); w = s.val / o.val; return Dual(w, (s.tan - w * o.tan) / o.val)
  def __neg__(s): return Dual(-s.val, -s.tan)

class Var:
  """Nodo de la cinta: val y las parciales de padres pueden ser floats o duales."""
  def __init__(self, val, padres=()): self.val, self.padres = val, padres
  def _v(o): return o if isinstance(o, Var) else Var(o)
  def __add__(s, o): o = Var._v(o); return Var(s.val + o.val, ((s, 1.0), (o, 1.0)))
  __radd__ = __add__
  def __sub__(s, o): o = Var._v(o); return Var(s.val - o.val, ((s, 1.0), (o, -1.0)))
  def __rsub__(s, o): return Var._v(o) - s
  def __mul__(s, o): o = Var._v(o); return Var(s.val * o.val, ((s, o.val), (o, s.val)))
  __rmul__ = __mul__
  def __neg__(s): return Var(-s.val, ((s, -1.0),))

def sin(x):
  if isinstance(x, Var): return Var(sin(x.val), ((x, cos(x.val)),))
  if isinstance(x, Dual): return Dual(math.sin(x.val), math.cos(x.val) * x.tan)
  return math.sin(x)

def cos(x):
  if isinstance(x, Var): return Var(cos(x.val), ((x, -1.0 * sin(x.val)),))
  if isinstance(x, Dual): return Dual(math.cos(x.val), -math.sin(x.val) * x.tan)
  return math.cos(x)

def grad(f, x):
  """Gradiente de f en x por modo reverse. x: lista de floats o de duales."""
  xs = [Var(xi) for xi in x]
  y = f(xs)
  # tu código: orden topológico de los nodos que llevan a y, y acumulación de adjuntos al revés
  return [0.0 for _ in xs]

def hvp(f, x, v):
  """H(x) v con forward sobre reverse."""
  # tu código
  return np.zeros(len(x))
Shift+Enter to run

Connections and reading

  • Optimization. Newton-CG, quasi-Newton methods and curvature analysis use HVPs; Martens’s Hessian-free method (2010) combines them with Gauss–Newton products for deep networks.
  • Generative and dynamical models. Neural ODEs and continuous flows are trained with the adjoint method, with this lesson’s precautions.
  • Interpretability. Influence functions need products with the inverse Hessian, computed with CG or LiSSA over HVPs.
  • Inverse problems. Physical model calibration and data assimilation use discrete or continuous adjoints over simulations with millions of variables, with adjoint PDE gradients.
  • Large models. Gradient checkpointing in transformer training is the memory–recomputation tradeoff of the last section.

Reading: Pearlmutter’s paper (1994) is short and remains the best explanation of the R operator; JAX’s The Autodiff Cookbook shows mode composition in code; Blondel and collaborators (2022) explain modular implicit differentiation; Griewank and Walther, Evaluating Derivatives (2nd ed., SIAM, 2008), is the reference for everything in this lesson, from checkpointing to adjoints of iterations.

Summary

Key idea
A gradient is a program, and automatic differentiation can be applied again: composing modes obtains the HVP for the price of a few gradients, and differentiating the condition defining a solution instead of the steps computing it obtains derivatives of solvers and simulations with constant or logarithmic memory, as long as you watch which function is actually being differentiated.
  • Mode composition. Hv\mat{H}\vb{v} is the JVP of the gradient program (forward over reverse), exact and costing ≤ωFωRC\le \omega_F\omega_R C, independent of nn. Pearlmutter’s R operator is the same idea written by hand. With HVPs, CG solves the Newton step and Lanczos gives the spectrum without forming H\mat{H}.
  • Jacobians. jacfwd costs one pass per input and jacrev one per output. If J\mat{J} is sparse, column coloring (Curtis, Powell and Reid) reduces passes to the intersection graph’s chromatic number, at least the longest row length; bidirectional coloring handles dense rows with VJPs.
  • Custom rules. They replace the derivative: they provide stability (logsumexp) or pseudoderivatives (straight-through, clipping). They are verified with the dot-product test or gradcheck, and deliberate estimators fail it.
  • Iterative solvers. The unrolled derivative converges to the implicit one as O(kρk)\bigO(k\rho^k), behind the state; the implicit one solves an adjoint system with VJPs (fixed point, CG or GMRES) and saves one state, but is biased if the fixed point has not converged.
  • ODE adjoints. The discrete adjoint gives the program’s exact gradient; the continuous one, an approximation with discretization error, and if it reconstructs the state backward it fails in stiff, dissipative or chaotic systems.
  • Binomial checkpointing. With ss checkpoints and repetition rr, (s+rs)\binom{s + r}{s} steps are reversed; memory and recomputation grow as log⁡n\log n, and Revolve gives the optimal schedule.