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
- 09Reverse-mode automatic differentiationDot-product (adjoint) testMemory cost of reverse modeForward-mode automatic differentiationNested forward mode and perturbation confusionDual numbersConjugate gradientGeneralized minimal residual methodMatrix-free operatorsPower iterationNewton's method for nonlinear systemsFixed-point iterationRunge-Kutta methods
- 03Hessian-vector productImplicit function theoremImplicit differentiationVariational equation and sensitivitiesAdjoint sensitivity method
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 of a loss with parameters. Forming it costs gradients and numbers: 4 TB in float32. But almost all those algorithms use only products , 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 ; 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 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 and returns . 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 the cost of evaluating , the forward-mode factor (at most 4 in the operation model of the forward-mode lesson) and the reverse-mode factor (the constant in the cheap gradient principle).
| Composition | What executes | Cost of one | Memory |
|---|---|---|---|
| forward over reverse | the gradient program with duals | the tape of , with each entry doubled | |
| reverse over forward | the tangent program’s tape, traversed backward | the tangent program’s tape, larger than that of | |
| reverse over reverse | the backward pass’s tape, traversed backward | the tape of plus that of its backward pass | |
| forward over forward | hyperduals: per pass | passes, | minimal |
Proof
Reverse mode produces with a program of elementary operations (those of and their local derivatives) costing . Each local derivative is differentiable because , so that program is itself differentiable and forward mode applies the JVP theorem to it: one pass with seed gives at times the program cost. Since , the result is . 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 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 exactly, without approximations, for any network at a cost on the order of a gradient. He defined the operator
which obeys derivative rules (, , linearity, product and ), and applied it to every equation of the forward pass and backpropagation. For a layer , , with backpropagation and , and a direction for each weight matrix:
The last quantities together are . Look at what this is: a forward pass propagating alongside values and a backward pass propagating alongside . It is exactly forward over reverse written by hand: is the 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.
In the initial state, in the curved valley with , and , the exact HVP is , but the gradient difference is : the magenta arrow does not close the triangle, because in such a curved valley the Hessian changes greatly over units. With the difference is already and with , : it approaches with error , that of a forward difference. The AD HVP has no such error because there is no . At that same point the Hessian is indefinite, with eigenvalues and , although curvature along is positive (). Power iteration aligns with the eigenvector of in a few steps because the ratio of magnitudes is ; 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 , not the greatest .
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 inputs, the backward pass operates on duals without knowing it and each gradient component comes out with its directional derivative in the part: forward over reverse in one line.
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 (). The centered difference of gradients, by contrast, has the two errors of step-size selection: with (truncation), with (near optimal, on the order of ) and with (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 , while forming the Hessian costs times that. Notice that the ratio is less than : 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 . Conjugate gradient solves that system touching only through products , 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 with , local convergence is superlinear, and quadratic if . The usual choice, from algorithm 7.1 of Nocedal and Wright, is .
- Negative curvature. CG assumes is positive definite. If at an iteration , the quadratic model has no minimum in that direction: stop and return the last iterate (or on the first iteration), which is still a descent direction. It is the same number shown in red by the curvature probe.
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 . Newton-CG reaches the minimum 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 . On a quadratic problem with that conditioning, gradient descent with the optimal step reduces error by a factor per iteration: about 480 iterations to gain the 13 orders of magnitude Newton gains in 7.
- Spectrum. With , power iteration converges in very few HVPs, and Lanczos (
eigshon anLinearOperatorthat only knows how to do HVPs) gives both ends of the spectrum without forming . With 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 , each forward pass gives a column and each reverse pass a row . Strategies for computing Jacobians choose how many passes, of what kind and with which seeds:
| Strategy | Passes | Approximate cost | When |
|---|---|---|---|
jacfwd | JVPs (vectorized) | : few inputs, many outputs | |
jacrev | VJPs (vectorized) | , plus the tape | : few outputs |
| column coloring | JVPs, = number of colors | sparse with short rows | |
| row coloring | VJPs | sparse with short columns | |
| bidirectional | JVPs + VJPs | few dense rows or columns |
vmap does not change the number of passes: it executes them together, turning matrix–vector products into a matrix–matrix product. On the GPU that is the difference between launching 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, . If the coloring is valid, that sum has at most one nonzero term, so . (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 neighbors, it never needs more than . (3): in a band, columns and share a row if and only if ; with , two columns of the same color are at least apart. And an interior row has nonzeros, so by (1) fewer cannot suffice.
∎A dense row ruins column coloring: all columns share that row and 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 ; the reference paper is What color is your Jacobian? by Gebremedhin, Manne and Pothen (2005).
In the pentadiagonal, two colors are not enough because columns and share row : 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 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.
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 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 and , , where is computed independently (in forward mode on the implementation without the rule, or with finite differences as in the gradient checker) and with the rule.
Logsumexp. overflows as soon as any exceeds 709 in float64. The stable form , with , does not overflow, and AD differentiates it correctly ( disappears from the gradient because ). But it records nodes and, in the backward pass, reconstructs the gradient by adding contributions that cancel. The custom rule saves and and directly returns .
Gradient clipping. A primitive that is the identity forward and clips the adjoint backward, . 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.
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, , with 14 nodes; the custom rule gives the same numbers with 4 (the three inputs and output). With inputs the difference is 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 , from one that forgets to multiply by , a real mistake that with (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 to a region where it rounds to 3, the integer nearest target , 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
where is a contraction in : , the convergence condition for fixed-point iteration. A loss depends on through the solution. There are two ways to obtain , and choosing between them is what we call differentiating through iterative solvers.
Unroll. Execute iterations while recording them and backpropagate through all of them, as through a network of layers with shared weights. It gives the exact derivative of what you ran, , and costs states of memory.
Differentiate the fixed point. Differentiate the identity , as in implicit differentiation: , that is,
The matrix is invertible because the eigenvalues of have magnitude less than 1. The second form is what is implemented: a single adjoint system of size , solved by touching only through VJPs of . Only 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 (here, ; for a minimum, ) and the library applies the same formula, .
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, with , and error contracts by at each step but simultaneously receives a source of size , because has not yet reached . Summing sources of size gives factor . If is affine in , and the source comes only from .
In the initial state, with and , all three curves descend as straight lines on a logarithmic scale with the slope of the observed rate (, smaller than because ), but red gradually separates from gray: the ratio between unrolled and state errors is at , at and at , a line in , which is the theorem’s factor . Aquamarine instead follows gray at a constant distance (ratio for every ): the implicit gradient evaluated at an unconverged has error on the order of , no more and no less. With the adjoint solved by fixed-point iterations, a third error appears that decreases with at the same rate as the state with : the adjoint iteration, , 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 . He proposed reusing the graph of 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 , with the same spectral radius as . The bounds turning this into stopping criteria come from contraction. If is the forward residual,
because and the last term is at most . And if the adjoint system is solved with residual , that is, , the gradient error is . 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 is a fixed point: evaluated at 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 and does not disappear by averaging: every optimizer step carries it in the same direction. And if stops being contractive during training (the spectral radius of 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.
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 , exactly the spectral radius of at (the bound is pessimistic because ). The unrolled error is always above it, and their ratio grows almost linearly: , , , and for , about times (at the state is already at and the ratio begins to mix with rounding). The implicit gradient evaluated at has error on the order of the state’s, around 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 , and with 25, 50 and 100 iterations), and GMRES, which depends on eigenvalue distribution rather than spectral radius, solves it in 23 products. When is symmetric positive definite, for example if 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 on with and a loss . The continuous adjoint method, which you saw alongside ODE sensitivity, defines and gives
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 steps, and apply reverse mode to the resulting program. You obtain the exact gradient of the loss you computed, , 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 . You obtain an approximation of the exact loss gradient, with discretization error of the integrator’s order. And you need at every time the integrator evaluates .
Where does that come from? There are three options: save the trajectory (memory , 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 . The third was proposed by Chen, Rubanova, Bettencourt and Duvenaud (2018) for Neural ODEs: an augmented system integrated from 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, , whose linearization eigenvalues are those of with signs reversed. A mode damped forward as grows backward as . In a stiff or dissipative system, any difference between reconstructed and true (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 , 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.
The stiff system in the figure is , : a slow variable and a fast one that relaxes toward with time constant . Forward, RK4 with is stable and accurate. Backward, the fast mode grows as and at that is : 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 reconstruction is already lost.
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 ) 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 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 fails in the stiff system, with relative error on the order of and a reconstructed state at 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 decreases in the gradient direction; with the continuous adjoint, the gradient belongs to another function (exact ) 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 in reverse order. Saving them all costs states; saving none forces recomputation from for each step, 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 , . There are memory slots for states (checkpoints, one initially occupied by ), in addition to the working state. An advance computes from without recording and costs 1. Reversing step requires : 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 , there is only one checkpoint, for : reversing step requires advancing from to , and step 1 is advanced times, so . If , advance steps from , save in a new checkpoint and first reverse segment , which has checkpoints available (the one for remains occupied) and all repetition . Then free and reverse segment with checkpoints; its steps were already advanced once to reach , so within the segment they may only be advanced more times. Choosing reverses
steps, which is Pascal’s relation, and with its solution is . 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 .
∎The consequence is in the title of Griewank’s paper: logarithmic growth. If you take , , so with checkpoints each step is recomputed about 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).
With and , repetition is (because ) and the schedule makes 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 the staircase becomes a triangle (190 advances), and with recomputation nearly disappears.
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 , with 10 checkpoints the cost is times the forward pass, and with 20, 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,
which is also the fixed point of gradient step . Its optimality condition is , Hessian is symmetric positive definite, and the implicit formula gives with : a system CG solves using only HVPs of , which here are JVPs of .
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()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 , jacfwd (8000 vectorized JVPs) was 25 to 63 times slower than jacrev (4 VJPs) in three check runs, and for , 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 , float32 rounding), agreeing with the centered gradient difference computed in float64 to , 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 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 ( 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.
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}")npm run lab and open the connection link.In Lotka–Volterra, the discrete adjoint matches the program’s differences with relative error and saves about 113 KiB of tensors for the backward pass, growing in proportion to . The continuous adjoint has error (discretization error, because the system is not dissipative and reconstruction returns to with error ) and uses constant memory. Binomial checkpointing reproduces the autograd gradient to 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 .
With the discrete-adjoint gradient, L-BFGS-B recovers the parameters used to generate the data, , with error of one or two hundredths, in about 25 iterations, and the final loss reaches the level corresponding to observation noise (). 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 with to with and with . At the two finite differences no longer agree with each other (with the result is ten times larger than with , 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 (error almost 8% and reconstructed state units from the true one) and from overflows to nan: the volume contraction , reversed.
Common mistakes
Exercises
More than one answer may be correct.
odeint_adjoint). The learned dynamics are highly dissipative and gradients are erratic even though the forward pass is accurate. What change addresses the cause?Step 1 of 4. What equations do and satisfy?
Dual) and a tape (Var) whose values and local partials can be floats or duals. Implement grad(f, x), returning the list of derivatives 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 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))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
- Mode composition. is the JVP of the gradient program (forward over reverse), exact and costing , independent of . 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 .
- Jacobians.
jacfwdcosts one pass per input andjacrevone per output. If 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 , 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 checkpoints and repetition , steps are reversed; memory and recomputation grow as , and Revolve gives the optimal schedule.