Continuous dynamics in deep learning: sensitivities, the adjoint method and Neural ODEs
How to differentiate an ODE solution with respect to initial conditions and parameters, and how to do so with constant memory using the adjoint method, the continuous analog of reverse mode. This lets us interpret a ResNet as an Euler discretization, construct Neural ODEs and derive the instantaneous change-of-variables formula for continuous flows. The lesson closes the module by bringing together the chain rule, VJPs, linear systems and the continuity equation.
After this lesson you can
- Derive the variational equation (forward sensitivities) of an ODE with respect to initial conditions and parameters.
- Derive the adjoint equation and the parameter-gradient formula using a Lagrangian or as a limit of VJPs.
- Explain ResNets as Euler discretizations and the topological limitations of Neural ODEs.
- Prove the instantaneous change-of-variables formula d log p/dt = -tr(∂f/∂z) from Liouville's formula.
- Implement forward sensitivities, the adjoint method and a Neural ODE trained on a GPU, comparing memory and accuracy.
Before you start
- 03Picard-Lindelöf theoremGrönwall inequalityLinear ODE systemsLiouville's formulaVector-Jacobian productJacobian-vector productMultivariable chain ruleChange of variables formulaDivergenceTransport and continuity equationsStability of the explicit Euler step
- 00Custom autograd functions and gradcheckMemory profiling
Motivation: models as dynamical laws
A residual block computes . If we write the increment as , with step , the whole network is
which is exactly explicit Euler applied to the differential equation with . This interpretation, proposed simultaneously by Weinan E (2017) and Haber and Ruthotto (2017), reversed the reasoning in Chen, Rubanova, Bettencourt and Duvenaud (2018): instead of a stack of layers, the model is the solution of an ODE whose field is a neural network, and any numerical integrator can evaluate it. It was one of the best papers at NeurIPS 2018 and opened an entire field, well summarized in Kidger’s thesis (2022).
The mathematical question behind it is not exotic. You already know from the Picard–Lindelöf theorem that with has a unique solution. To train it you need its derivative: how much does , or a loss depending on it, change when you move or ? It appears in three different places.
- Fitting dynamical laws to data. A predator–prey, pharmacokinetic or epidemiological model has a few physical parameters calibrated by minimizing error between simulated trajectory and observations (you will see this as ODE model calibration). Weather forecasting does the same with millions of state variables: 4D-Var assimilation is an adjoint method.
- Memory. Backpropagating through integrator steps requires saving intermediate states (and the activations of each field evaluation). We will see an alternative whose memory does not depend on the number of steps.
- Flowing densities. If a field transports a distribution, each particle’s log density changes according to the trace of a Jacobian, not its determinant. This is the basis of continuous normalizing flows and flow matching.
All three are solved with the same tools from the module: the chain rule, JVPs and VJPs, linear ODE systems and Liouville’s formula. This lesson brings them together and closes the module.
From ResNet to ODE
Before deriving anything, see what happens when depth grows with fixed total “time” . Each block advances one Euler step; the more blocks, the shorter the steps and the closer layer trajectories come to integral curves of the field.
Two lessons emerge from the figure. First, a deep ResNet with smooth, small blocks is effectively an ODE integrator: depth becomes a continuous variable. Second, this continuous limit has restrictions the discrete network did not: no planar field can separate the disk from the ring. We will return to both with proofs; first, the derivative.
The variational equation
We fix notation for the entire lesson. The state is , the parameters are and
Along a particular solution we use the two Jacobians of the field:
The idea is to differentiate both sides of the equation. If , the chain rule applied to gives , and since does not depend on , . The same applies to initial conditions, without term and with . The calculation is formal: it assumes the solution is differentiable and derivatives in and can be exchanged. The following theorem justifies this.
The columns of and are the ODE sensitivities: each tells how the entire trajectory moves when an initial condition or parameter is perturbed. Note that the variational equation is a linear system with coefficients depending on time through the trajectory: it must be solved together with , not afterward.
Proof
It suffices to consider : parameters become state by adding equation , and then is a block of the matrix of augmented system , whose variational equation is precisely with .
Take a direction and small , and let and be solutions with data and . Trajectory is compact, so it has a compact neighborhood on which is bounded by and uniformly continuous; by continuous dependence of solutions (another consequence of Grönwall’s inequality), for small , also exists on and stays inside . First, the Lipschitz bound: since has norm at most , Grönwall gives
Now define the remainder , with . Differentiating and adding and subtracting ,
By the mean value inequality, , where tends to 0 with by uniform continuity. With the previous bound, with . Then and Grönwall again gives , uniformly in . This says : the directional derivative exists and equals , linear in . Since solves a linear ODE whose coefficients depend continuously on , it also depends continuously on , and the solution is .
∎Three examples are worth keeping at hand.
Liouville’s formula applied to also says
Infinitesimal volume around the trajectory expands according to the Jacobian trace, that is, the field’s divergence. Remember this: it is half the proof of instantaneous change of variables.
Cost: forward or backward
Suppose we now want the gradient of a scalar loss with respect to the parameters. By the chain rule,
There are two ways to evaluate this product, just as in the chain rule lesson.
- Forward. Integrate together with : a system of equations. Each column of , or each combination , is a JVP propagated through time: . Cost grows linearly with the number of inputs , and nothing must be stored.
- Backward. Propagate covector from end to beginning, like a VJP. Cost no longer depends on but on the number of scalar outputs (one for a loss), at the price of traveling backward in time.
With in the millions, as in a network, the first option is impractical. The second is the adjoint method.
| Method | What it integrates | Scalars at once | Memory | Accuracy |
|---|---|---|---|---|
| Finite differences | solutions of | with centered differences, depends on step | ||
| Forward sensitivities | exact gradient of the integrator | |||
| Backprop through integrator | , then chain of VJPs | with steps | exact gradient of the integrator | |
| Adjoint method | , then backward | discretized gradient of the ODE |
The last column hides the lesson’s most important subtlety; we will examine it carefully.
The adjoint method
The question reverse mode asks is: how much would change if I perturbed the state at an intermediate time ? Since the future depends on the state at through the flow, that sensitivity is a function of time.
This is the adjoint method. The adjoint equation is linear, like the variational equation, but transposed and with opposite sign, and is integrated backward, from the final condition at .
Proof
Let solve the adjoint equation (it exists and is unique: it is linear with continuous coefficients). The key is that the product of an adjoint and a sensitivity changes very simply. With the variational equation,
and similarly . Integrating between and with and :
Repeating the argument with instead of as initial time (the sensitivity of with respect to also solves the variational equation) yields for every : the adjoint equation’s solution is the adjoint state in the definition.
∎The proof shows the structure: the adjoint is designed so is constant. What forward mode computes by carrying forward, reverse mode computes by carrying backward, and they meet in the product. Two other derivations are worth knowing: the Lagrangian one, which you will do in a guided exercise and which generalizes to the Pontryagin maximum principle, and the limit of a chain of VJPs, connecting with backpropagation.
As a limit of VJPs
Discretize the ODE with Euler, , and backpropagate by hand. Write , and .
If each block had its own parameters , as in a ResNet, the gradient with respect to would be term of the sum: the integrand of the adjoint method is literally the contribution of each “layer”. In this sense the adjoint method is the continuous version of reverse-mode automatic differentiation.
The augmented system and constant memory
One piece remains: and are evaluated at , and the adjoint is integrated from to . If the trajectory has not been saved, it must be reconstructed by integrating the ODE itself backward from . The three are integrated together in the augmented system
where accumulates the gradient, so . Three observations turn this into a practical algorithm:
- No Jacobians are needed. What appears are products and , both obtained from a single VJP of function with covector . With autograd, each evaluation of the right-hand side costs a small multiple of evaluating .
- Memory does not depend on the number of steps. The forward pass only outputs , and the backward pass needs only the current augmented-system state: numbers. Backpropagating through the integrator, in contrast, stores every state and internal activation of each evaluation (you will quantify this on the GPU below, using PyTorch memory profiling).
- Losses at multiple times. If , the adjoint jumps at each observation: when passing backward, add . With running cost , the adjoint equation gains a source term, .
With , the adjoint reproduces the backprop gradient to about five digits: the difference is RK4 discretization error, discussed shortly. With in float32, relative error is already 11%. From , measures about , of the order of float32 spacing near , and each backward-step increment, , falls below that resolution and is lost when added: reconstruction does not move away from the vicinity of , information about has disappeared, and the gradient means nothing. In float64 the threshold is much farther away, because must offset instead of ; before reaching it, RK4 truncation error already appears, amplified in the same way (0.7% with ), and with , where , the error is again 11%.
Optimization and discretization do not commute
In practice no one integrates exactly. There are two paths to a gradient, and they differ:
- Discretize then optimize. Fix the integrator (method, steps) and differentiate the resulting program exactly: this is backpropagation through the integrator, or equivalently its discrete adjoint. The result is the exact gradient of the function the optimizer actually minimizes.
- Optimize then discretize. Derive the continuous adjoint, then integrate it by some method. The result approximates the exact ODE’s gradient, which is not the function evaluated.
With Euler the difference is plain. The discrete adjoint is . Euler applied to the adjoint equation backward from gives instead: the Jacobian is evaluated at the other end of the step and moreover at a reconstructed state rather than the saved one. The recurrences differ by per step and overall. Both converge to the true ODE gradient, but only the first is the derivative of the loss your code computes.
Does it matter? Yes, in three situations. A finite-difference gradient check against the continuous adjoint fails even if everything is programmed correctly. Optimizers combining gradients and function values (line searches, L-BFGS) can find directions that are not descent directions for the actual function. And with adaptive integrators, the backward pass chooses its own steps, different from those of the forward pass.
ResNets and Neural ODEs
Compared with a ResNet you gain three things: parameters are shared along “depth”, cost adapts to each input’s difficulty (the integrator decides how many field evaluations, NFE, it needs), and the model is invertible by construction, because the backward flow undoes the forward one. But invertibility has a price.
The inverse is immediate: integrating from to returns the initial condition, by uniqueness. Differentiability follows from the previous section’s theorem and the determinant’s sign from Liouville’s formula: . Two solutions never pass through the same point at the same time (in an autonomous field, not even at different times: their orbits do not cross), so the flow cannot “turn space inside out”.
This is the topological limitation that Dupont, Doucet and Teh (2019) pointed out with the figure’s example. The ring’s inner boundary is a circle surrounding disk . Since is a homeomorphism, is a simple closed curve, and the bounded component of containing maps to the bounded component of . If a half-plane contained without touching , take a point and the half-line from normal to the boundary of , directed inward: it never leaves , and every half-line from a point inside a Jordan curve intersects it. Contradiction. No Neural ODE in followed by a linear layer separates the disk from the ring; in the figure you saw this in the winding number, always 1.
Their solution is simple: augment the state with zero coordinates, , and let the flow work in the larger space (Augmented Neural ODEs). In the disk can rise while the ring falls, as in the figure, and in general extra space gives trajectories room to avoid one another. Note what does not have this limitation: a ResNet with finite steps. Map need not be injective if times the Lipschitz constant of reaches 1; invertible ResNets impose precisely to recover invertibility, inheriting Neural ODE topology. The relationship is developed in residual blocks and topological limits of flows.
Instantaneous change of variables
Now let the initial condition be random: . Each particle follows the field and the distribution of has density . How does density change along a particle?
This is the instantaneous change-of-variables formula, introduced by Chen et al. (2018) to construct continuous normalizing flows. You will prove it from Liouville in a guided exercise; the one-line idea is that change of variables says , and Liouville turns that determinant into the exponential of an integral of traces.
There is a second, more physical proof using the continuity equation. Mass is conserved, so . Expanding the divergence of a product and using the chain rule along the trajectory,
and . A particle’s density falls where the flow diverges and rises where it converges.
A discrete normalizing flow costs a determinant, generally , so these architectures are designed with triangular Jacobians. The continuous version only needs the trace, but the exact trace is not free either: costs VJPs (or JVPs). FFJORD (Grathwohl et al., 2019) replaces it with the Hutchinson estimator: if is a random vector with ,
and each sample costs a single VJP, . It is unbiased, so the stochastic gradient of log likelihood remains unbiased; its variance, which you will calculate below, is the price (you will study it in depth as randomized trace estimation). With log likelihood available, a continuous flow is trained by maximum likelihood: integrate backward to the base together with , and . Flow matching, in its lesson, trains the same kind of model without integration during training.
Practical problems
Backward reconstruction. The adjoint reconstructs by integrating the ODE backward, and dynamics contracting forward expand backward: if eigenvalues of have real part , errors in are amplified as . Classifiers tend to learn exactly that, fields carrying different inputs toward a few regions. Gholami, Keutzer and Biros (2019) showed that this produces incorrect gradients in real Neural ODEs and proposed saving checkpoints: a few forward-pass states from which each segment is reintegrated forward during the backward pass. This is familiar gradient checkpointing, with its memory–recomputation tradeoff (optimal in the sense of binomial checkpointing).
Stiffness and number of evaluations. With an adaptive integrator, tolerance decides NFE, not you. During training, learned dynamics can become stiff (very negative, disparate eigenvalues of ), and an explicit method then needs steps for stability alone, not accuracy: cost per iteration rises without model improvement. Chen et al. already observed NFE increasing with training; Finlay et al. (2020) tackle it by regularizing kinetic energy and the Jacobian’s Frobenius norm, favoring straight trajectories and smooth fields. The classical alternative is implicit methods.
Exact trace. In large dimension , VJPs per field evaluation multiply cost by . Hutchinson reduces it to one, with variance.
Implementation from scratch
We begin with a meaningful system: the Lotka–Volterra model of prey and predators ,
We simulate data with observed every time units with noise, and calculate the gradient of at another point in three ways: centered finite differences, forward sensitivities (a system of equations), and the adjoint method (a backward pass of , with jumps at observations). All use the same fixed-step RK4.
import numpy as np
import time
def f(z, th):
x, y = z
a, b, d, g = th
return np.array([a * x - b * x * y, d * x * y - g * y])
def f_z(z, th): # jacobiano respecto del estado, 2x2
x, y = z
a, b, d, g = th
return np.array([[a - b * y, -b * x], [d * y, d * x - g]])
def f_th(z, th): # jacobiano respecto de los parámetros, 2x4
x, y = z
return np.array([[x, -x * y, 0.0, 0.0], [0.0, 0.0, x * y, -y]])
def rk4_step(F, u, h):
k1 = F(u)
k2 = F(u + 0.5 * h * k1)
k3 = F(u + 0.5 * h * k2)
k4 = F(u + h * k3)
return u + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
th_true = np.array([1.0, 0.5, 0.5, 1.0])
z0 = np.array([1.0, 1.0])
t_obs = np.arange(1, 21) * 0.5 # 20 observaciones en (0, 10]
m = 20 # pasos de RK4 entre observaciones
h = 0.5 / m
def trayectoria(th):
z, out = z0.copy(), []
for _ in t_obs:
for _ in range(m):
z = rk4_step(lambda u: f(u, th), z, h)
out.append(z)
return np.array(out)
rng = np.random.default_rng(0)
datos = trayectoria(th_true) + 0.05 * rng.normal(size=(len(t_obs), 2))
def loss(th):
return 0.5 * np.sum((trayectoria(th) - datos) ** 2)
def grad_fd(th, eps=1e-6):
return np.array([(loss(th + eps * e) - loss(th - eps * e)) / (2 * eps) for e in np.eye(len(th))])
def grad_sensibilidades(th):
n, p = 2, len(th)
def F(u): # u = (z, P) con P de 2x4 aplanada
z, P = u[:n], u[n:].reshape(n, p)
return np.concatenate([f(z, th), (f_z(z, th) @ P + f_th(z, th)).ravel()])
u = np.concatenate([z0, np.zeros(n * p)])
g = np.zeros(p)
for i in range(len(t_obs)):
for _ in range(m):
u = rk4_step(F, u, h)
z, P = u[:n], u[n:].reshape(n, p)
g += (z - datos[i]) @ P # regla de la cadena en cada observación
return g
def grad_adjunto(th):
n, p = 2, len(th)
z = z0.copy() # pase hacia delante: solo se conserva z(t1)
for _ in range(len(t_obs) * m):
z = rk4_step(lambda u: f(u, th), z, h)
def G(u): # sistema aumentado (z, a, g)
z, a = u[:n], u[n:2 * n]
return np.concatenate([f(z, th), -f_z(z, th).T @ a, -f_th(z, th).T @ a])
u = np.concatenate([z, np.zeros(n), np.zeros(p)])
for i in reversed(range(len(t_obs))):
u[n:2 * n] += u[:n] - datos[i] # salto del adjunto en la observación t_i
for _ in range(m):
u = rk4_step(G, u, -h) # hacia atrás en el tiempo
return u[2 * n:], u[n:2 * n] # gradiente respecto de theta y de z0
th = np.array([0.8, 0.4, 0.6, 1.1])
for nombre, fn in [("diferencias finitas", grad_fd), ("sensibilidades", grad_sensibilidades),
("adjunto", lambda t: grad_adjunto(t)[0])]:
t0 = time.perf_counter()
g = fn(th)
print(f"{nombre:20s} {np.array2string(g, precision=6)} {1e3 * (time.perf_counter() - t0):6.0f} ms")
gF, gA, gD = grad_sensibilidades(th), grad_adjunto(th)[0], grad_fd(th)
print(f"\nmax |sensibilidades - dif. finitas| = {np.abs(gF - gD).max():.1e}")
print(f"max |sensibilidades - adjunto| = {np.abs(gF - gA).max():.1e}")The three agree to seven or eight significant digits, but not in the same way. Sensitivities and finite differences differ by , the inherent noise of finite differences: both measure the derivative of the discrete function computed by trayectoria, as the Runge–Kutta note predicted. The adjoint differs slightly more, on the order of : it is the exact ODE gradient discretized with RK4, and the difference is its truncation error. With four parameters, all three cost the same. See how they scale as grows: a field with , that is, parameters.
def coste(n, N=40):
r = np.random.default_rng(1)
W = r.normal(size=(n, n)) / np.sqrt(n)
z0 = r.normal(size=n)
hh, idx = 1.0 / N, np.arange(n)
# sensibilidades hacia delante: P tiene n x n^2 entradas
def F(u):
z, P = u[:n], u[n:].reshape(n, n * n)
s = 1 - np.tanh(W @ z) ** 2
dP = ((s[:, None] * W) @ P).reshape(n, n, n)
dP[idx, idx, :] += s[:, None] * z[None, :] # término B: d tanh(Wz)_i / dW_il = s_i z_l
return np.concatenate([np.tanh(W @ z), dP.ravel()])
t0 = time.perf_counter()
u = np.concatenate([z0, np.zeros(n ** 3)])
for _ in range(N):
u = rk4_step(F, u, hh)
gF = u[:n] @ u[n:].reshape(n, n * n) # L = |z(1)|^2 / 2
tF = time.perf_counter() - t0
# adjunto: z hacia delante, (z, a, g) hacia atrás
t0 = time.perf_counter()
z = z0.copy()
for _ in range(N):
z = rk4_step(lambda v: np.tanh(W @ v), z, hh)
def G(u):
z, a = u[:n], u[n:2 * n]
sa = (1 - np.tanh(W @ z) ** 2) * a # un VJP del campo da los dos productos
return np.concatenate([np.tanh(W @ z), -W.T @ sa, -np.outer(sa, z).ravel()])
u = np.concatenate([z, z, np.zeros(n * n)])
for _ in range(N):
u = rk4_step(G, u, -hh)
tA = time.perf_counter() - t0
return tF, tA, np.abs(gF - u[2 * n:]).max() / np.abs(gF).max()
print(" n p escalares (sens.) escalares (adj.) t sens. (ms) t adj. (ms) dif. relativa")
for n in [4, 8, 16, 32]:
tF, tA, err = coste(n)
print(f"{n:2d} {n*n:6d} {n + n**3:19d} {2*n + n*n:18d} {1e3*tF:14.1f} {1e3*tA:13.1f} {err:15.1e}")The scalar column says it all: with , sensitivities integrate numbers at once and the adjoint . For small , interpreter time dominates and both methods take milliseconds; as grows, sensitivity work grows as per step (product of by ), and adjoint work as , and with the adjoint is already about twenty times faster. Both gradients agree to .
With the adjoint gradient, fitting parameters is a call to scipy.optimize.minimize:
from scipy.optimize import minimize
t0 = time.perf_counter()
res = minimize(loss, th, jac=lambda t: grad_adjunto(t)[0], method="L-BFGS-B", bounds=[(1e-3, None)] * 4)
print(f"iteraciones: {res.nit} evaluaciones: {res.nfev} tiempo: {time.perf_counter() - t0:.2f} s")
print("theta estimado:", np.round(res.x, 4), " verdadero:", th_true)
print(f"pérdida final: {res.fun:.5f} (ruido esperado: 0.5 * 40 * 0.05^2 = {0.5 * 40 * 0.05**2:.3f})")L-BFGS converges in about fifteen iterations to parameters differing from the true values by less than 1%, and the final loss, , is of the order noise alone would produce ( in expectation): no unexplained structure remains. Now the experiment separating the two gradients. With Euler, the difference between discrete adjoint (exact for the code) and discretized continuous adjoint is much more visible than with RK4:
def euler_traj(th, N):
hE = t_obs[-1] / N
zs = [z0]
for _ in range(N):
zs.append(zs[-1] + hE * f(zs[-1], th))
return np.array(zs), hE
def loss_euler(th, N):
zs, hE = euler_traj(th, N)
return 0.5 * np.sum((zs[np.rint(t_obs / hE).astype(int)] - datos) ** 2)
def grad_discreto(th, N): # retropropagar a mano a través de Euler
zs, hE = euler_traj(th, N)
obs = {int(round(t / hE)): i for i, t in enumerate(t_obs)}
a, g = np.zeros(2), np.zeros(4)
for k in range(N, 0, -1):
if k in obs:
a = a + zs[k] - datos[obs[k]]
g = g + hE * f_th(zs[k - 1], th).T @ a # jacobianos en z_{k-1}, el inicio del paso
a = a + hE * f_z(zs[k - 1], th).T @ a
return g
def grad_continuo(th, N): # adjunto continuo integrado con Euler hacia atrás
zs, hE = euler_traj(th, N)
obs = {int(round(t / hE)): i for i, t in enumerate(t_obs)}
z, a, g = zs[-1], np.zeros(2), np.zeros(4)
for k in range(N, 0, -1):
if k in obs:
a = a + z - datos[obs[k]]
z, a, g = z - hE * f(z, th), a + hE * f_z(z, th).T @ a, g + hE * f_th(z, th).T @ a
return g
g_exacto = grad_sensibilidades(th) # RK4 fino: el gradiente de la EDO, casi exacto
print(" N |discreto - dif.fin.| |continuo - discreto|/|g| |discreto - EDO|/|g|")
for N in [200, 400, 800, 1600]:
gd, gc = grad_discreto(th, N), grad_continuo(th, N)
gfd = np.array([(loss_euler(th + 1e-6 * e, N) - loss_euler(th - 1e-6 * e, N)) / 2e-6 for e in np.eye(4)])
nrm = np.abs(gd).max()
print(f"{N:5d} {np.abs(gd - gfd).max():17.1e} {np.abs(gc - gd).max() / nrm:23.3f} {np.abs(gd - g_exacto).max() / nrm:22.3f}")The first column confirms the discrete gradient is the exact derivative of the program (finite differences agree up to their own noise). The second and third are approximately halved each time doubles: both approximations to the ODE gradient have error . But with the continuous adjoint differs by 68% from the gradient of the function actually evaluated. A gradient check would flag it as a programming error.
Finally, instantaneous change of variables and Hutchinson’s estimator. For the figure’s “Two modes” field, we integrate the trajectory together with the variational equation and ; then we compare predicted density with a Monte Carlo count of transported particles.
def campo(z):
x, y = z
return np.array([1.6 * np.tanh(2.5 * x) - 0.45 * x, -0.35 * y + 0.25 * x])
def jac(z):
x, y = z
return np.array([[4 / np.cosh(2.5 * x) ** 2 - 0.45, 0.0], [0.25, -0.35]])
def F(u): # u = (z, S, ell)
z, S = u[:2], u[2:6].reshape(2, 2)
J = jac(z)
return np.concatenate([campo(z), (J @ S).ravel(), [-np.trace(J)]])
zi, T, n = np.array([0.25, 0.6]), 2.0, 200
u = np.concatenate([zi, np.eye(2).ravel(), [0.0]])
for _ in range(n):
u = rk4_step(F, u, T / n)
zT, S, ell = u[:2], u[2:6].reshape(2, 2), u[6]
print(f"ell(T) = -∫ tr J = {ell:.8f} -log det S(T) = {-np.log(np.linalg.det(S)):.8f}")
logp0 = lambda z: -np.log(2 * np.pi) - 0.5 * np.sum(z ** 2, axis=0)
p_pred = np.exp(logp0(zi) + ell)
rng = np.random.default_rng(0)
Z = rng.normal(size=(2, 50_000))
for _ in range(40):
Z = rk4_step(campo, Z, T / 40) # las 50 000 partículas a la vez
lado = 0.2
cuenta = np.all(np.abs(Z - zT[:, None]) < lado / 2, axis=0).sum()
print(f"densidad en z(T): predicha {p_pred:.3f} Monte Carlo {cuenta / 50_000 / lado**2:.3f} ({cuenta} partículas en la caja)")
# Hutchinson en dimensión 200: J = diag(s) W, el jacobiano de tanh(Wz + b)
d = 200
W = rng.normal(size=(d, d)) / np.sqrt(d)
b, z = rng.normal(size=d), rng.normal(size=d)
s = 1 - np.tanh(W @ z + b) ** 2
J = s[:, None] * W
vjp = lambda v: (v * s) @ W # v^T J sin formar J (un VJP)
K = 2000
gauss = np.array([e @ vjp(e) for e in rng.normal(size=(K, d))])
rade = np.array([e @ vjp(e) for e in rng.choice([-1.0, 1.0], size=(K, d))])
Js = (J + J.T) / 2
print(f"\ntraza exacta (d = {d} VJP): {np.trace(J):.4f}")
print(f"Gauss: media {gauss.mean():.4f} desv. por muestra {gauss.std():.3f} teoría {np.sqrt(2 * np.sum(Js**2)):.3f}")
print(f"Rademacher: media {rade.mean():.4f} desv. por muestra {rade.std():.3f} teoría {np.sqrt(2 * (np.sum(Js**2) - np.sum(np.diag(J)**2))):.3f}")The integral of the trace and log determinant of the variational equation agree to eight digits, and predicted density lies within the Monte Carlo count’s error. Note that it is twice the maximum of the initial Gaussian: the flow has concentrated mass in one mode. The Hutchinson part is humbling: the trace is and the standard deviation of each sample is . The estimator is unbiased and cheap, but many samples must be averaged or very noisy gradients accepted. Measured deviations agree with formulas for Gaussian vectors and for Rademacher, with : Rademacher removes the diagonal contribution and is therefore never worse.
Neural ODE from scratch in PyTorch
Now on the GPU, with a neural field. We reproduce Chen et al.’s toy example: a spiral generated by , with componentwise cube, and a network that must learn the dynamics from short trajectory segments. First, by backpropagating through a handwritten RK4.
import time
import torch
import torch.nn as nn
torch.manual_seed(0)
dev = "cuda" if torch.cuda.is_available() else "cpu"
print("dispositivo:", torch.cuda.get_device_name(0) if dev == "cuda" else "cpu")
A_true = torch.tensor([[-0.1, 2.0], [-2.0, -0.1]], device=dev)
f_true = lambda z: (z ** 3) @ A_true
def rk4(f, z0, t, substeps=1):
"""z' = f(z) con RK4 de paso fijo; devuelve z en todos los instantes de t, forma (len(t), ..., dim)."""
zs, z = [z0], z0
for i in range(len(t) - 1):
h = (t[i + 1] - t[i]) / substeps
for _ in range(substeps):
k1 = f(z); k2 = f(z + 0.5 * h * k1); k3 = f(z + 0.5 * h * k2); k4 = f(z + h * k3)
z = z + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
zs.append(z)
return torch.stack(zs)
t_all = torch.linspace(0.0, 25.0, 1000, device=dev)
with torch.no_grad():
z_true = rk4(f_true, torch.tensor([[2.0, 0.0]], device=dev), t_all, substeps=2)[:, 0]
class Campo(nn.Module):
def __init__(self, hidden=64):
super().__init__()
self.net = nn.Sequential(nn.Linear(2, hidden), nn.Tanh(), nn.Linear(hidden, 2))
def forward(self, z):
return self.net(z ** 3)
campo = Campo().to(dev)
iters = 800
opt = torch.optim.Adam(campo.parameters(), lr=5e-3)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, iters)
B, Lseg = 32, 20 # 32 tramos de 20 instantes
t_seg = t_all[:Lseg] - t_all[0]
t0 = time.perf_counter()
for it in range(1, iters + 1):
s = torch.randint(0, len(t_all) - Lseg, (B,), device=dev)
objetivo = torch.stack([z_true[s + i] for i in range(Lseg)])
pred = rk4(campo, z_true[s], t_seg) # backprop a través de los 19 pasos
loss = (pred - objetivo).abs().mean()
opt.zero_grad(); loss.backward(); opt.step(); sched.step()
if it % 200 == 0:
with torch.no_grad():
err = (rk4(campo, z_true[:1], t_all)[:, 0] - z_true).abs().mean().item()
print(f"iteración {it:4d} pérdida del lote {loss.item():.4f} error medio en la espiral completa {err:.3f}")
print(f"tiempo de entrenamiento: {time.perf_counter() - t0:.0f} s")npm run lab and open the connection link.The model sees segments of 20 time points (half a time unit) and ultimately reproduces the entire 25-unit spiral by integrating from a single point, with mean error of a few tenths on a spiral of radius 2: the learned field generalizes beyond training segments because it learns the law, not the trajectory. Now the adjoint method as a custom autograd function: forward integrates without a graph and saves only the states it returns; backward integrates the augmented system backward and obtains and with one torch.autograd.grad per evaluation.
class ODEAdjunta(torch.autograd.Function):
@staticmethod
def forward(ctx, z0, t, n_sub, f, *params):
with torch.no_grad(): # sin grafo: no se guarda ningún paso
zs = rk4(f, z0, t, n_sub)
ctx.f, ctx.n_sub = f, n_sub
ctx.save_for_backward(t, zs[-1], *params)
return zs
@staticmethod
def backward(ctx, gzs):
t, zT, *params = ctx.saved_tensors
f, n_sub = ctx.f, ctx.n_sub
def lado_derecho(z, a): # (f, -a^T J, -a^T B) con un solo VJP
with torch.enable_grad():
z = z.detach().requires_grad_(True)
fz = f(z)
vjp = torch.autograd.grad(fz, (z, *params), a, allow_unused=True)
return fz.detach(), [-v if v is not None else torch.zeros_like(p) for v, p in zip(vjp, (z, *params))]
z, a = zT, gzs[-1].clone()
g = [torch.zeros_like(p) for p in params]
for i in range(len(t) - 1, 0, -1):
h = -(t[i] - t[i - 1]) / n_sub
for _ in range(n_sub): # RK4 hacia atrás sobre (z, a, g)
f1, d1 = lado_derecho(z, a)
f2, d2 = lado_derecho(z + 0.5 * h * f1, a + 0.5 * h * d1[0])
f3, d3 = lado_derecho(z + 0.5 * h * f2, a + 0.5 * h * d2[0])
f4, d4 = lado_derecho(z + h * f3, a + h * d3[0])
z = z + (h / 6) * (f1 + 2 * f2 + 2 * f3 + f4)
a = a + (h / 6) * (d1[0] + 2 * d2[0] + 2 * d3[0] + d4[0])
g = [gi + (h / 6) * (u1 + 2 * u2 + 2 * u3 + u4) for gi, u1, u2, u3, u4 in zip(g, d1[1:], d2[1:], d3[1:], d4[1:])]
a = a + gzs[i - 1] # salto del adjunto en la observación t_{i-1}
return (a, None, None, None, *g)
def odeint_adjunto(f, z0, t, n_sub=1):
return ODEAdjunta.apply(z0, t, n_sub, f, *f.parameters())
# 1) mismos gradientes, en float64 para ver la diferencia de discretización y no el redondeo
campo64 = Campo().double().to(dev)
campo64.load_state_dict({k: v.double() for k, v in campo.state_dict().items()})
z0b = z_true[torch.arange(0, 800, 50)].double()
tt = torch.linspace(0, 1.0, 11, device=dev, dtype=torch.float64)
def gradientes(adjunto, n_sub):
campo64.zero_grad()
out = odeint_adjunto(campo64, z0b, tt, n_sub) if adjunto else rk4(campo64, z0b, tt, n_sub)
(out ** 2).sum().backward()
return torch.cat([p.grad.flatten() for p in campo64.parameters()])
for n_sub in [1, 2, 4, 8]:
g_bp, g_adj = gradientes(False, n_sub), gradientes(True, n_sub)
print(f"subpasos {n_sub}: |adjunto - backprop| / |backprop| = {((g_adj - g_bp).norm() / g_bp.norm()).item():.1e}")
# 2) memoria pico en la GPU al crecer el número de pasos
def memoria(adjunto, pasos, batch=512, hidden=128):
net = Campo(hidden).to(dev)
z0 = torch.randn(batch, 2, device=dev) * 0.5
t2 = torch.linspace(0, 1.0, 2, device=dev)
torch.cuda.synchronize(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
t0 = time.perf_counter()
out = odeint_adjunto(net, z0, t2, pasos) if adjunto else rk4(net, z0, t2, pasos)
(out[-1] ** 2).sum().backward()
torch.cuda.synchronize()
return (torch.cuda.max_memory_allocated() - base) / 2**20, 1e3 * (time.perf_counter() - t0)
if dev == "cuda":
print("\npasos backprop: MiB ms | adjunto: MiB ms")
for pasos in [50, 100, 200, 400]:
mb, tb = memoria(False, pasos)
ma, ta = memoria(True, pasos)
print(f"{pasos:5d} {mb:16.1f} {tb:6.0f} | {ma:13.1f} {ta:6.0f}")
try:
from torchdiffeq import odeint_adjoint
class ConTiempo(nn.Module): # torchdiffeq llama a f(t, z)
def __init__(self, f):
super().__init__()
self.f = f
def forward(self, t, z):
return self.f(z)
campo64.zero_grad()
out = odeint_adjoint(ConTiempo(campo64), z0b, tt, method="rk4", options={"step_size": 0.025})
(out ** 2).sum().backward()
g_lib = torch.cat([p.grad.flatten() for p in campo64.parameters()])
g_bp = gradientes(False, 4) # backprop por el RK4 propio con el mismo paso, h = 0.025
print("\ntorchdiffeq disponible:")
print(f" max |z(1) torchdiffeq - z(1) propio| = {(out[-1] - rk4(campo64, z0b, tt, 4)[-1]).abs().max().item():.1e}")
print(f" |adjunto torchdiffeq - backprop| / |backprop| = {((g_lib - g_bp).norm() / g_bp.norm()).item():.1e}")
except ImportError:
print("\ntorchdiffeq no está instalado: la comparación con la librería se omite (pip install torchdiffeq).")npm run lab and open the connection link.Three results. Adjoint and backprop gradients differ by about four parts per thousand with one substep (), and the difference falls by between 16 and 40 times whenever substeps double, to with eight: this is RK4’s error (factor 16 in the asymptotic regime), again the gap between optimizing then discretizing and the reverse. Backprop memory grows linearly with steps (about 52 MiB per 50 steps for this batch and network), while adjoint memory stays below 1 MiB regardless of steps. And the adjoint is slower, in our runs between 40% longer and a little over twice as long depending on GPU load, because in the backward pass it reevaluates the field to reconstruct and performs a VJP at each stage: memory is traded for computation. Training takes around one or two minutes depending on GPU load, because each iteration launches hundreds of tiny operations. If torchdiffeq is installed, the cell’s final part compares its odeint_adjoint with ours: the trajectory should agree within RK4 error with (its "rk4" method is the 3/8-rule variant, also fourth order), and its adjoint gradient should differ from backprop on the same scale as ours at that step size.
With libraries
Outside a course, nobody maintains their own adjoint integrator. Three common references:
- torchdiffeq (PyTorch, from the Neural ODE authors):
odeint(f, z0, t, method="dopri5", rtol=..., atol=...)backpropagates through the integrator, whileodeint_adjointwith the same signature uses the continuous adjoint;fmust be annn.Moduleto find parameters, and theadjoint_paramsargument allows them to be specified manually. - Diffrax (JAX, by P. Kidger): the gradient choice is explicit; its default,
RecursiveCheckpointAdjoint, differentiates the discrete integrator with checkpointing, i.e. discretize then optimize with bounded memory, whileBacksolveAdjointis this lesson’s continuous adjoint. - SUNDIALS (CVODES, IDAS), in C with interfaces in many languages: forward and adjoint sensitivities with implicit integrators for stiff problems, the engineering and science standard.
import torch
from torchdiffeq import odeint, odeint_adjoint
class Campo(torch.nn.Module):
def __init__(self):
super().__init__()
self.net = torch.nn.Sequential(torch.nn.Linear(2, 64), torch.nn.Tanh(), torch.nn.Linear(64, 2))
def forward(self, t, z): # torchdiffeq espera f(t, z)
return self.net(z)
f = Campo()
z0, t = torch.randn(128, 2), torch.linspace(0, 1, 10)
z = odeint_adjoint(f, z0, t, method="dopri5", rtol=1e-5, atol=1e-7) # forma (10, 128, 2)
z[-1].pow(2).sum().backward() # memoria constante en el número de pasos
The practical rule from this lesson: if memory permits, backpropagate through the integrator (or use checkpointing) and get the exact gradient of what you calculate; use the continuous adjoint when memory is the bottleneck, with tight tolerances and monitoring backward reconstruction.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What does differentiating this expression with respect to give?
Step 1 of 4. What relation does change of variables give between and ?
forward_sensitivity(theta, x0, T, n=1000) for , . It must use RK4 with steps to integrate the augmented system formed by and its sensitivity (write the equation for yourself), and return the tuple (x_T, s_T). Tests compare against and for several and .import numpy as np
def forward_sensitivity(theta, x0, T, n=1000):
"""Integra (x, s) con RK4 y devuelve (x(T), s(T)), con s = dx/dtheta."""
h = T / n
u = np.array([x0, 0.0])
# tu código: el campo del sistema aumentado y los n pasos de RK4
return u[0], u[1]Summary
- Sensitivities and solve , ; Grönwall justifies exchanging derivatives and bounds their growth.
- Adjoint solves backward, and . It is the limit of backpropagation through Euler steps; its cost does not depend on and its memory does not depend on the number of steps.
- The discretized continuous adjoint is not the discretized model’s gradient (optimization and discretization do not commute), and backward state reconstruction is unstable if the dynamics contract.
- A ResNet is an Euler integrator; its limit, the Neural ODE, is an orientation-preserving diffeomorphism with topological limitations resolved by increasing dimension.
- Along a trajectory, , a consequence of Liouville; in high dimensions the trace is estimated by Hutchinson, unbiased but noisy.