Module contents
Lesson 20 of 20Research 120 min

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

Motivation: models as dynamical laws

A residual block computes zℓ+1=zℓ+g(zℓ,θℓ)\vb{z}_{\ell+1} = \vb{z}_\ell + g(\vb{z}_\ell, \theta_\ell). If we write the increment as h f(zℓ,θℓ)h\,f(\vb{z}_\ell, \theta_\ell), with step h>0h > 0, the whole network is

zℓ+1=zℓ+h f(zℓ,θℓ),ℓ=0,1,…,L−1,\vb{z}_{\ell+1} = \vb{z}_\ell + h\,f(\vb{z}_\ell, \theta_\ell), \qquad \ell = 0, 1, \dots, L - 1,

which is exactly explicit Euler applied to the differential equation z′(t)=f(z(t),θ(t))\vb{z}'(t) = f(\vb{z}(t), \theta(t)) with tℓ=ℓht_\ell = \ell h. 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 fθf_\theta 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 z′=f(z,θ,t)\vb{z}' = f(\vb{z}, \theta, t) with z(t0)=z0\vb{z}(t_0) = \vb{z}_0 has a unique solution. To train it you need its derivative: how much does z(t1)\vb{z}(t_1), or a loss LL depending on it, change when you move z0\vb{z}_0 or θ\theta? It appears in three different places.

  1. 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.
  2. Memory. Backpropagating through LL integrator steps requires saving LL intermediate states (and the activations of each field evaluation). We will see an alternative whose memory does not depend on the number of steps.
  3. 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” T=LhT = Lh. 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.

InteractiveFrom ResNet to Neural ODE
  • ResNet: outputs of 8 blocks
  • exact integral curve and endpoint
  • maximum final error
  • slope −1 (reference)
Experiment
h = 0.250
Step per block h=T/Lh = T/L0.2500
Maximum final error versus exact flow0.5959
L×L \times error (nearly constant: order 1)4.767
A residual block is an Euler step: zℓ+1=zℓ+h f(zℓ)\vb{z}_{\ell+1} = \vb{z}_\ell + h\,f(\vb{z}_\ell). With L=8L = 8 blocks, the network traverses 8 segments.
In ‘Depth’, each blue polyline is a point's path through LL residual blocks z←z+hf(z)\vb{z} \leftarrow \vb{z} + h f(\vb{z}) with h=2/Lh = 2/L; gray curves are exact integral curves of the arrow field. Increase LL and observe the graph: final error falls as 1/L1/L, with slope −1-1 on a log-log scale, because Euler is first order. In ‘Rings’, a disk and concentric ring travel with the flow of three different fields. Can any move the disk outside the ring? Look at the turns readout and the linear margin. Then enable the extra dimension.

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 z(t)∈Rn\vb{z}(t) \in \R^n, the parameters are θ∈Rp\theta \in \R^p and

z′(t)=f(z(t),θ,t),z(t0)=z0,t∈[t0,t1].\vb{z}'(t) = f(\vb{z}(t), \theta, t), \qquad \vb{z}(t_0) = \vb{z}_0, \qquad t \in [t_0, t_1].

Along a particular solution we use the two Jacobians of the field:

J(t)=∂f∂z(z(t),θ,t)∈Rn×n,B(t)=∂f∂θ(z(t),θ,t)∈Rn×p.\mat{J}(t) = \pd{f}{\vb{z}}(\vb{z}(t), \theta, t) \in \R^{n\times n}, \qquad \mat{B}(t) = \pd{f}{\theta}(\vb{z}(t), \theta, t) \in \R^{n\times p}.

The idea is to differentiate both sides of the equation. If P(t)=∂z(t)/∂θ\mat{P}(t) = \partial\vb{z}(t)/\partial\theta, the chain rule applied to f(z(t),θ,t)f(\vb{z}(t), \theta, t) gives P′=JP+B\mat{P}' = \mat{J}\mat{P} + \mat{B}, and since z(t0)=z0\vb{z}(t_0) = \vb{z}_0 does not depend on θ\theta, P(t0)=0\mat{P}(t_0) = \mat{0}. The same applies to initial conditions, without term B\mat{B} and with ∂z(t0)/∂z0=I\partial\vb{z}(t_0)/\partial\vb{z}_0 = \mat{I}. The calculation is formal: it assumes the solution is differentiable and derivatives in tt and θ\theta can be exchanged. The following theorem justifies this.

The columns of S\mat{S} and P\mat{P} 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 z\vb{z}, not afterward.

Proof

It suffices to consider z0\vb{z}_0: parameters become state by adding equation θ′=0\theta' = \vb{0}, and then P\mat{P} is a block of the matrix S\mat{S} of augmented system (z,θ)(\vb{z}, \theta), whose variational equation is precisely P′=JP+B\mat{P}' = \mat{J}\mat{P} + \mat{B} with P(t0)=0\mat{P}(t_0) = \mat{0}.

Take a direction v\vb{v} and small η\eta, and let z(t)\vb{z}(t) and w(t)\vb{w}(t) be solutions with data z0\vb{z}_0 and z0+ηv\vb{z}_0 + \eta\vb{v}. Trajectory {z(t)}\{\vb{z}(t)\} is compact, so it has a compact neighborhood KK on which ∂f/∂z\partial f/\partial\vb{z} is bounded by MM and uniformly continuous; by continuous dependence of solutions (another consequence of Grönwall’s inequality), for small η\eta, w(t)\vb{w}(t) also exists on [t0,t1][t_0, t_1] and stays inside KK. First, the Lipschitz bound: since (w−z)′=f(w)−f(z)(\vb{w} - \vb{z})' = f(\vb{w}) - f(\vb{z}) has norm at most M∥w−z∥M\norm{\vb{w} - \vb{z}}, Grönwall gives

∥w(t)−z(t)∥≤∣η∣ ∥v∥ eM(t−t0).\norm{\vb{w}(t) - \vb{z}(t)} \le \abs{\eta}\,\norm{\vb{v}}\,e^{M(t - t_0)}.

Now define the remainder r(t)=w(t)−z(t)−η S(t)v\vb{r}(t) = \vb{w}(t) - \vb{z}(t) - \eta\,\mat{S}(t)\vb{v}, with r(t0)=0\vb{r}(t_0) = \vb{0}. Differentiating and adding and subtracting J(w−z)\mat{J}(\vb{w} - \vb{z}),

r′=f(w)−f(z)−J(t)(w−z)⏟q(t)+J(t) r.\vb{r}' = \underbrace{f(\vb{w}) - f(\vb{z}) - \mat{J}(t)(\vb{w} - \vb{z})}_{\vb{q}(t)} + \mat{J}(t)\,\vb{r}.

By the mean value inequality, ∥q(t)∥≤ω(∥w−z∥) ∥w−z∥\norm{\vb{q}(t)} \le \omega(\norm{\vb{w} - \vb{z}})\,\norm{\vb{w} - \vb{z}}, where ω(δ)=sup⁡{∥∂zf(ξ)−∂zf(ζ)∥:∥ξ−ζ∥≤δ}\omega(\delta) = \sup\{\norm{\partial_{\vb{z}} f(\vb{\xi}) - \partial_{\vb{z}} f(\vb{\zeta})} : \norm{\vb{\xi} - \vb{\zeta}} \le \delta\} tends to 0 with δ\delta by uniform continuity. With the previous bound, ∥q(t)∥≤ε(η)∣η∣\norm{\vb{q}(t)} \le \eps(\eta)\abs{\eta} with ε(η)→0\eps(\eta) \to 0. Then ∥r∥′≤M∥r∥+ε(η)∣η∣\norm{\vb{r}}' \le M\norm{\vb{r}} + \eps(\eta)\abs{\eta} and Grönwall again gives ∥r(t)∥≤ε(η)∣η∣ (t1−t0) eM(t1−t0)=o(η)\norm{\vb{r}(t)} \le \eps(\eta)\abs{\eta}\,(t_1 - t_0)\,e^{M(t_1 - t_0)} = o(\eta), uniformly in tt. This says w(t)=z(t)+η S(t)v+o(η)\vb{w}(t) = \vb{z}(t) + \eta\,\mat{S}(t)\vb{v} + o(\eta): the directional derivative exists and equals S(t)v\mat{S}(t)\vb{v}, linear in v\vb{v}. Since S\mat{S} solves a linear ODE whose coefficients depend continuously on z0\vb{z}_0, it also depends continuously on z0\vb{z}_0, and the solution is C1C^1.

∎

Three examples are worth keeping at hand.

Liouville’s formula applied to S′=JS\mat{S}' = \mat{J}\mat{S} also says

det⁡S(t)=exp⁡∫t0ttr⁡J(s)  ⁣ds>0.\det\mat{S}(t) = \exp\int_{t_0}^t \tr\mat{J}(s)\,\dd s > 0.

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 L=ℓ(z(t1))L = \ell(\vb{z}(t_1)) with respect to the pp parameters. By the chain rule,

∇θL⊤=∇ℓ(z(t1))⊤ P(t1).\grad_\theta L\T = \grad\ell(\vb{z}(t_1))\T\,\mat{P}(t_1).

There are two ways to evaluate this product, just as in the chain rule lesson.

  • Forward. Integrate P\mat{P} together with z\vb{z}: a system of n+npn + np equations. Each column of P\mat{P}, or each combination Pv\mat{P}\vb{v}, is a JVP propagated through time: (Pv)′=J(Pv)+Bv(\mat{P}\vb{v})' = \mat{J}(\mat{P}\vb{v}) + \mat{B}\vb{v}. Cost grows linearly with the number of inputs pp, and nothing must be stored.
  • Backward. Propagate covector ∇ℓ(z(t1))⊤\grad\ell(\vb{z}(t_1))\T from end to beginning, like a VJP. Cost no longer depends on pp but on the number of scalar outputs (one for a loss), at the price of traveling backward in time.

With pp in the millions, as in a network, the first option is impractical. The second is the adjoint method.

MethodWhat it integratesScalars at onceMemoryAccuracy
Finite differences2p2p solutions of z\vb{z}nnO(n)\bigO(n)≈εmaˊq2/3\approx\eps_{\text{máq}}^{2/3} with centered differences, depends on step
Forward sensitivities(z,P)(\vb{z}, \mat{P})n(1+p)n(1 + p)O(np)\bigO(np)exact gradient of the integrator
Backprop through integratorz\vb{z}, then chain of VJPsnnO(Nn)\bigO(Nn) with NN stepsexact gradient of the integrator
Adjoint methodz\vb{z}, then (z,a,g)(\vb{z}, \vb{a}, \vb{g}) backward2n+p2n + pO(n+p)\bigO(n + p)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 LL change if I perturbed the state at an intermediate time tt? Since the future depends on the state at tt 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 t1t_1.

Proof

Let a\vb{a} 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,

ddt(a⊤P)=a′TP+a⊤P′=−a⊤JP+a⊤(JP+B)=a⊤B,\frac{d}{dt}\big(\vb{a}\T\mat{P}\big) = \vb{a}'^{\mathsf{T}}\mat{P} + \vb{a}\T\mat{P}' = -\vb{a}\T\mat{J}\mat{P} + \vb{a}\T(\mat{J}\mat{P} + \mat{B}) = \vb{a}\T\mat{B},

and similarly ddt(a⊤S)=−a⊤JS+a⊤JS=0⊤\frac{d}{dt}(\vb{a}\T\mat{S}) = -\vb{a}\T\mat{J}\mat{S} + \vb{a}\T\mat{J}\mat{S} = \vb{0}\T. Integrating between t0t_0 and t1t_1 with P(t0)=0\mat{P}(t_0) = \mat{0} and S(t0)=I\mat{S}(t_0) = \mat{I}:

∇θL⊤=a(t1)⊤P(t1)=∫t0t1a⊤B  ⁣dt,∇z0L⊤=a(t1)⊤S(t1)=a(t0)⊤.\grad_\theta L\T = \vb{a}(t_1)\T\mat{P}(t_1) = \int_{t_0}^{t_1}\vb{a}\T\mat{B}\,\dd t, \qquad \grad_{\vb{z}_0} L\T = \vb{a}(t_1)\T\mat{S}(t_1) = \vb{a}(t_0)\T.

Repeating the argument with tt instead of t0t_0 as initial time (the sensitivity of z(t1)\vb{z}(t_1) with respect to z(t)\vb{z}(t) also solves the variational equation) yields a(t)=∇z(t)L\vb{a}(t) = \grad_{\vb{z}(t)} L for every tt: the adjoint equation’s solution is the adjoint state in the definition.

∎

The proof shows the structure: the adjoint is designed so a⊤S\vb{a}\T\mat{S} is constant. What forward mode computes by carrying S\mat{S} forward, reverse mode computes by carrying a\vb{a} 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, zk+1=zk+hf(zk,θ)\vb{z}_{k+1} = \vb{z}_k + h f(\vb{z}_k, \theta), and backpropagate by hand. Write aˉk=∇zkL\bar{\vb{a}}_k = \grad_{\vb{z}_k} L, Jk=∂f/∂z(zk)\mat{J}_k = \partial f/\partial\vb{z}(\vb{z}_k) and Bk=∂f/∂θ(zk)\mat{B}_k = \partial f/\partial\theta(\vb{z}_k).

aˉk=(I+hJk)⊤ aˉk+1\bar{\vb{a}}_k = (\mat{I} + h\mat{J}_k)\T\,\bar{\vb{a}}_{k+1}
One-step VJP: the Jacobian of a residual block, ∂z_{k+1}/∂z_k, is the identity plus h times the field Jacobian.
1/5

If each block had its own parameters θk\theta_k, as in a ResNet, the gradient with respect to θk\theta_k would be term h Bk⊤aˉk+1h\,\mat{B}_k\T\bar{\vb{a}}_{k+1} 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: J(t)\mat{J}(t) and B(t)\mat{B}(t) are evaluated at z(t)\vb{z}(t), and the adjoint is integrated from t1t_1 to t0t_0. If the trajectory has not been saved, it must be reconstructed by integrating the ODE itself backward from z(t1)\vb{z}(t_1). The three are integrated together in the augmented system

ddt[zag]=[f(z,θ,t)−J⊤a−B⊤a],[zag](t1)=[z(t1)∇ℓ(z(t1))0],\frac{d}{dt}\begin{bmatrix}\vb{z} \\ \vb{a} \\ \vb{g}\end{bmatrix} = \begin{bmatrix} f(\vb{z}, \theta, t) \\ -\mat{J}\T\vb{a} \\ -\mat{B}\T\vb{a}\end{bmatrix}, \qquad \begin{bmatrix}\vb{z} \\ \vb{a} \\ \vb{g}\end{bmatrix}(t_1) = \begin{bmatrix}\vb{z}(t_1) \\ \grad\ell(\vb{z}(t_1)) \\ \vb{0}\end{bmatrix},

where g(t)=∫tt1B⊤a  ⁣ds\vb{g}(t) = \int_t^{t_1}\mat{B}\T\vb{a}\,\dd s accumulates the gradient, so g(t0)=∇θL\vb{g}(t_0) = \grad_\theta L. Three observations turn this into a practical algorithm:

  • No Jacobians are needed. What appears are products a⊤J\vb{a}\T\mat{J} and a⊤B\vb{a}\T\mat{B}, both obtained from a single VJP of function (z,θ)↦f(z,θ,t)(\vb{z}, \theta) \mapsto f(\vb{z}, \theta, t) with covector a\vb{a}. With autograd, each evaluation of the right-hand side costs a small multiple of evaluating ff.
  • Memory does not depend on the number of steps. The forward pass only outputs z(t1)\vb{z}(t_1), and the backward pass needs only the current augmented-system state: 2n+p2n + p numbers. Backpropagating through the integrator, in contrast, stores every state and internal activation of each ff evaluation (you will quantify this on the GPU below, using PyTorch memory profiling).
  • Losses at multiple times. If L=∑iℓi(z(ti))L = \sum_i \ell_i(\vb{z}(t_i)), the adjoint jumps at each observation: when passing tit_i backward, add ∇ℓi(z(ti))\grad\ell_i(\vb{z}(t_i)). With running cost ∫r(z)  ⁣dt\int r(\vb{z})\,\dd t, the adjoint equation gains a source term, a′=−J⊤a−∇r\vb{a}' = -\mat{J}\T\vb{a} - \grad r.
InteractiveThe adjoint backward pass
cz*z(0)
  • z(t) forward
  • z reconstructed backward
  • adjoint a(t), direction
  • target z*
States stored for the gradient (of 61 possible)
Backprop through integrator61
Adjoint method1
  • g(t) = ∫ₜᵀ aᵀ ∂f/∂θ
  • exact integrator gradient
backward: t = 0.00
1.0
2.00
h = 0.050
Precision
Memory: backprop through integrator61 states
Memory: adjoint method1 state
Reconstruction error ∥z~(t)−z(t)∥\|\tilde{\vb{z}}(t) - \vb{z}(t)\|2.4e−6
∂L/∂θ\partial L/\partial\theta, adjoint0.0892
∂L/∂θ\partial L/\partial\theta, backprop through RK40.0892
∂L/∂θ\partial L/\partial\theta, exact ODE0.0892
Adjoint relative error3.3e−6
Backward amplification ekTe^{kT}20.086
Reliable reconstruction (error at t=0t = 0: 2e−6). The adjoint agrees with backprop up to RK4 discretization error, without storing the trajectory.
Model z′=A(θ)(z−c)\vb{z}' = \mat{A}(\theta)(\vb{z} - \vb{c}) with A=[−k−θθ−k]\mat{A} = \begin{bmatrix} -k & -\theta \\ \theta & -k\end{bmatrix}: a spiral falling toward c\vb{c}. The loss is L=12∥z(T)−z∗∥2L = \tfrac12\norm{\vb{z}(T) - \vb{z}^*}^2. Play: in the first half RK4 advances and the blue bar counts the states backprop would save; in the second the augmented system travels backward, reconstructs z\vb{z} (dashed), carries adjoint a(t)\vb{a}(t) (arrow) and accumulates gradient g(t)\vb{g}(t), ending at the backprop value. Now increase contraction kk: forward, the spiral is crushed against c\vb{c}; backward, every error is amplified by ekTe^{kT}. At what kk does reconstruction break in float32? And in float64?

With k=1k = 1, the adjoint reproduces the backprop gradient to about five digits: the difference is RK4 discretization error, discussed shortly. With k=5k = 5 in float32, relative error is already 11%. From k≈6k \approx 6, z(T)−c\vb{z}(T) - \vb{c} measures about 1.8 e−18≈3⋅10−81.8\,e^{-18} \approx 3\cdot 10^{-8}, of the order of float32 spacing near c\vb{c}, and each backward-step increment, h A(z−c)h\,\mat{A}(\vb{z} - \vb{c}), falls below that resolution and is lost when added: reconstruction does not move away from the vicinity of c\vb{c}, information about z(0)\vb{z}(0) has disappeared, and the gradient means nothing. In float64 the threshold is much farther away, because ekTe^{kT} must offset 10−1610^{-16} instead of 10−710^{-7}; before reaching it, RK4 truncation error already appears, amplified in the same way (0.7% with k=10k = 10), and with k=12k = 12, where ekT≈4⋅1015e^{kT} \approx 4\cdot 10^{15}, 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 aˉk=aˉk+1+h J(zk)⊤aˉk+1\bar{\vb{a}}_k = \bar{\vb{a}}_{k+1} + h\,\mat{J}(\vb{z}_k)\T\bar{\vb{a}}_{k+1}. Euler applied to the adjoint equation backward from tk+1t_{k+1} gives ak=ak+1+h J(z~k+1)⊤ak+1\vb{a}_k = \vb{a}_{k+1} + h\,\mat{J}(\tilde{\vb{z}}_{k+1})\T\vb{a}_{k+1} instead: the Jacobian is evaluated at the other end of the step and moreover at a reconstructed state z~k+1\tilde{\vb{z}}_{k+1} rather than the saved one. The recurrences differ by O(h2)\bigO(h^2) per step and O(h)\bigO(h) 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 t1t_1 to t0t_0 returns the initial condition, by uniqueness. Differentiability follows from the previous section’s theorem and the determinant’s sign from Liouville’s formula: det⁡S(t1)=exp⁡∫tr⁡J>0\det\mat{S}(t_1) = \exp\int\tr\mat{J} > 0. 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 CC surrounding disk DD. Since φ\varphi is a homeomorphism, φ(C)\varphi(C) is a simple closed curve, and the bounded component of R2∖C\R^2 \setminus C containing DD maps to the bounded component of R2∖φ(C)\R^2 \setminus \varphi(C). If a half-plane HH contained φ(D)\varphi(D) without touching φ(C)\varphi(C), take a point p∈φ(D)\vb{p} \in \varphi(D) and the half-line from p\vb{p} normal to the boundary of HH, directed inward: it never leaves HH, and every half-line from a point inside a Jordan curve intersects it. Contradiction. No Neural ODE in R2\R^2 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 qq zero coordinates, z(t0)=(x,0)∈Rn+q\vb{z}(t_0) = (\vb{x}, \vb{0}) \in \R^{n + q}, and let the flow work in the larger space (Augmented Neural ODEs). In R3\R^3 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 z↦z+hf(z)\vb{z} \mapsto \vb{z} + h f(\vb{z}) need not be injective if hh times the Lipschitz constant of ff reaches 1; invertible ResNets impose precisely h Lip(f)<1h\,\mathrm{Lip}(f) < 1 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: z(t0)∼p0\vb{z}(t_0) \sim p_0. Each particle follows the field and the distribution of z(t)\vb{z}(t) has density ptp_t. 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 pt(φt(z0)) det⁡Dφt(z0)=p0(z0)p_t(\varphi_t(\vb{z}_0))\,\det D\varphi_t(\vb{z}_0) = p_0(\vb{z}_0), 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 ∂tp+∇⋅(pf)=0\partial_t p + \nabla\cdot(p f) = 0. Expanding the divergence of a product and using the chain rule along the trajectory,

ddtpt(z(t))=∂tp+f⋅∇p=−p ∇⋅f,\frac{d}{dt}p_t(\vb{z}(t)) = \partial_t p + f\cdot\grad p = -p\,\nabla\cdot f,

and ∇⋅f=tr⁡(∂f/∂z)\nabla\cdot f = \tr(\partial f/\partial\vb{z}). A particle’s density falls where the flow diverges and rises where it converges.

InteractiveFlowing density
  • density ptp_t
  • particle z(t)\vb{z}(t)
  • ℓ(t) = −∫ tr ∂f/∂z
  • −log|det J| (finite differences)
Field ff
t = 2.0
ℓ(t)=−∫0ttr⁡∂f∂z ds\ell(t) = -\int_0^t \operatorname{tr}\frac{\partial f}{\partial \vb{z}}\,\mathrm{d}s0.89601
−log⁡∣det⁡Jt∣-\log|\det \mat{J}_t| (finite differences)0.89601
Difference1.7e−7
p0(z0)p_0(\vb{z}_0) and pt(z(t))p_t(\vb{z}(t))0.1288 → 0.3157
Where divergence is positive (near x=0x = 0) the flow spreads and density drops; elsewhere it accumulates in two modes.
The field transports the standard Gaussian. Color is ptp_t, calculated by integrating each pixel backward to t=0t = 0. Drag particle z0\vb{z}_0: the orange curve is ℓ(t)=−∫0ttr⁡ ∂f/∂z ds\ell(t) = -\int_0^t \operatorname{tr}\,\partial f/\partial\vb{z}\,\mathrm{d}s, accumulated along its trajectory; the dashed line is −log⁡∣det⁡Jt∣-\log\abs{\det\mat{J}_t} of the flow map calculated with finite differences. They agree to six digits. Compare the three fields: where does density fall in ‘Two modes’? Why does nothing change in the swirl? What is ℓ(2)\ell(2) in the spiral?

A discrete normalizing flow costs a determinant, generally O(n3)\bigO(n^3), so these architectures are designed with triangular Jacobians. The continuous version only needs the trace, but the exact trace is not free either: tr⁡J=∑iei⊤Jei\tr\mat{J} = \sum_i \vb{e}_i\T\mat{J}\vb{e}_i costs nn VJPs (or JVPs). FFJORD (Grathwohl et al., 2019) replaces it with the Hutchinson estimator: if ε\vb{\eps} is a random vector with E[εε⊤]=I\E[\vb{\eps}\vb{\eps}\T] = \mat{I},

E[ε⊤Jε]=E[tr⁡(Jεε⊤)]=tr⁡(J E[εε⊤])=tr⁡J,\E\big[\vb{\eps}\T\mat{J}\vb{\eps}\big] = \E\big[\tr(\mat{J}\vb{\eps}\vb{\eps}\T)\big] = \tr\big(\mat{J}\,\E[\vb{\eps}\vb{\eps}\T]\big) = \tr\mat{J},

and each sample costs a single VJP, ε⊤J\vb{\eps}\T\mat{J}. 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 x\vb{x} backward to the base together with ℓ\ell, and log⁡pmodelo(x)=log⁡p0(z(t0))−∫t0t1tr⁡J  ⁣dt\log p_{\text{modelo}}(\vb{x}) = \log p_0(\vb{z}(t_0)) - \int_{t_0}^{t_1}\tr\mat{J}\,\dd t. Flow matching, in its lesson, trains the same kind of model without integration during training.

Practical problems

Backward reconstruction. The adjoint reconstructs z(t)\vb{z}(t) by integrating the ODE backward, and dynamics contracting forward expand backward: if eigenvalues of J\mat{J} have real part ≤−k\le -k, errors in z(t1)\vb{z}(t_1) are amplified as ek(t1−t0)e^{k(t_1 - t_0)}. 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 J\mat{J}), and an explicit method then needs steps h≲2/∣λ∣h \lesssim 2/\abs{\lambda} 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 ∫∥f∥2\int\norm{f}^2 and the Jacobian’s Frobenius norm, favoring straight trajectories and smooth fields. The classical alternative is implicit methods.

Exact trace. In large dimension nn, nn VJPs per field evaluation multiply cost by nn. Hutchinson reduces it to one, with variance.

Implementation from scratch

We begin with a meaningful system: the Lotka–Volterra model of prey xx and predators yy,

x′=αx−βxy,y′=δxy−γy,θ=(α,β,δ,γ).x' = \alpha x - \beta xy, \qquad y' = \delta xy - \gamma y, \qquad \theta = (\alpha, \beta, \delta, \gamma).

We simulate data with θ=(1,0.5,0.5,1)\theta = (1, 0.5, 0.5, 1) observed every 0.50.5 time units with noise, and calculate the gradient of L(θ)=12∑i∥z(ti)−yi∥2L(\theta) = \tfrac12\sum_i\norm{\vb{z}(t_i) - \vb{y}_i}^2 at another point in three ways: centered finite differences, forward sensitivities (a system of 2+2⋅4=102 + 2\cdot 4 = 10 equations), and the adjoint method (a backward pass of 2+2+4=82 + 2 + 4 = 8, with jumps at observations). All use the same fixed-step RK4.

[ ]Lotka–Volterra sensitivities in three waysBrowser
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 10−810^{-8}, 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 10−610^{-6}: it is the exact ODE gradient discretized with RK4, and the difference is its O(h4)\bigO(h^4) truncation error. With four parameters, all three cost the same. See how they scale as pp grows: a field z′=tanh⁡(Wz)\vb{z}' = \tanh(\mat{W}\vb{z}) with W∈Rn×n\mat{W} \in \R^{n\times n}, that is, p=n2p = n^2 parameters.

[ ]How cost scales with parameter countBrowser
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 n=32n = 32, sensitivities integrate 32 80032\,800 numbers at once and the adjoint 1 0881\,088. For small nn, interpreter time dominates and both methods take milliseconds; as nn grows, sensitivity work grows as n4n^4 per step (product JP\mat{J}\mat{P} of n×nn\times n by n×n2n\times n^2), and adjoint work as n2n^2, and with n=32n = 32 the adjoint is already about twenty times faster. Both gradients agree to 10−910^{-9}.

With the adjoint gradient, fitting parameters is a call to scipy.optimize.minimize:

[ ]Fitting Lotka–Volterra to dataBrowser
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, 0.0270.027, is of the order noise alone would produce (0.050.05 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:

[ ]Discretize then optimize versus optimize then discretizeBrowser
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 NN doubles: both approximations to the ODE gradient have error O(h)\bigO(h). But with N=200N = 200 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 ℓ′=−tr⁡J\ell' = -\tr\mat{J}; then we compare predicted density with a Monte Carlo count of 50 00050\,000 transported particles.

[ ]Instantaneous change of variables and Hutchinson traceBrowser
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 0.3160.316 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 0.530.53 and the standard deviation of each sample is 8.48.4. The estimator is unbiased and cheap, but many samples must be averaged or very noisy gradients accepted. Measured deviations agree with formulas Var⁡=2∥Js∥F2\Var = 2\norm{\mat{J}_s}_F^2 for Gaussian vectors and Var⁡=2(∥Js∥F2−∑iJii2)\Var = 2(\norm{\mat{J}_s}_F^2 - \sum_i J_{ii}^2) for Rademacher, with Js=(J+J⊤)/2\mat{J}_s = (\mat{J} + \mat{J}\T)/2: 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 z′=(z3)A\vb{z}' = (\vb{z}^{3})\mat{A}, with componentwise cube, and a network fθ(z)=MLP(z3)f_\theta(\vb{z}) = \mathrm{MLP}(\vb{z}^{3}) that must learn the dynamics from short trajectory segments. First, by backpropagating through a handwritten RK4.

[ ]Training a Neural ODE by backpropagation through RK4Local GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 a⊤J\vb{a}\T\mat{J} and a⊤B\vb{a}\T\mat{B} with one torch.autograd.grad per evaluation.

[ ]The adjoint method as torch.autograd.FunctionLocal GPU
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).")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Three results. Adjoint and backprop gradients differ by about four parts per thousand with one substep (h=0.1h = 0.1), and the difference falls by between 16 and 40 times whenever substeps double, to 3×10−73\times 10^{-7} with eight: this is RK4’s O(h4)\bigO(h^4) 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 z\vb{z} 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 h=0.025h = 0.025 (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, while odeint_adjoint with the same signature uses the continuous adjoint; f must be an nn.Module to find parameters, and the adjoint_params argument 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, while BacksolveAdjoint is 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

NumericDensity in a contracting spiral
Let z′=Az\vb{z}' = \mat{A}\vb{z} with tr⁡A=−0.5\tr\mat{A} = -0.5 and random z(0)\vb{z}(0) with density p0p_0. How much does log⁡pt(z(t))\log p_t(\vb{z}(t)) change between t=0t = 0 and t=2t = 2 along a trajectory?
NumericAn adjoint by hand
For z′=θzz' = \theta z with z(0)=z0z(0) = z_0 and loss L=z(T)L = z(T), solve the adjoint equation and calculate ∂L/∂θ=∫0Ta(t) B(t) dt\partial L/\partial\theta = \int_0^T a(t)\,B(t)\,\mathrm{d}t with θ=−1\theta = -1, z0=2z_0 = 2 and T=1.5T = 1.5.
NumericHow many numbers must be integrated
A model has state dimension n=100n = 100 and p=105p = 10^5 parameters. For a scalar loss gradient, how many times more scalars does the forward-sensitivity system (z,P)(\vb{z}, \mat{P}) integrate at once than the augmented adjoint system (z,a,g)(\vb{z}, \vb{a}, \vb{g})?
QuizA Neural ODE cannot turn the line around
Why can no Neural ODE in R\R (with field C1C^1) represent the map x↦−xx \mapsto -x, and how does increasing the dimension solve it?
QuizWhich gradient does the gradient check test?
You implement a Neural ODE with 50 Euler steps and calculate its gradient in two ways: backpropagating through all 50 steps (A), and with the continuous adjoint also integrated backward using Euler (B). You compare against centered finite differences of your loss function. What do you expect?
QuizWhen does reconstruction fail?
You train with the continuous adjoint method and no checkpoints. In which dynamics is the gradient most likely to be wrong due to reconstructing z\vb{z} backward?
QuizVectors for Hutchinson
For which of these distributions of ε\vb{\varepsilon} is estimator ε⊤Jε\vb{\varepsilon}\T\mat{J}\vb{\varepsilon} of tr⁡J\tr\mat{J}, with arbitrary J∈Rn×n\mat{J} \in \R^{n\times n}, unbiased?

More than one answer may be correct.

ProofThe adjoint equation using a Lagrangian
Prove: For z′=f(z,θ,t)\vb{z}' = f(\vb{z}, \theta, t), z(t0)=z0\vb{z}(t_0) = \vb{z}_0 and L=ℓ(z(t1))L = \ell(\vb{z}(t_1)), the gradient is ∇θL=∫t0t1B⊤a dt\grad_\theta L = \int_{t_0}^{t_1}\mat{B}\T\vb{a}\,\mathrm{d}t, where a′=−J⊤a\vb{a}' = -\mat{J}\T\vb{a} and a(t1)=∇ℓ(z(t1))\vb{a}(t_1) = \grad\ell(\vb{z}(t_1)).
0
For any function λ:[t0,t1]→Rn\vb{\lambda}: [t_0, t_1] \to \R^n of class C1C^1 independent of θ\theta, since z′−f=0\vb{z}' - f = \vb{0} along the solution, L=ℓ(z(t1))−∫t0t1λ⊤(z′−f(z,θ,t)) dtL = \ell(\vb{z}(t_1)) - \int_{t_0}^{t_1}\vb{\lambda}\T(\vb{z}' - f(\vb{z}, \theta, t))\,\mathrm{d}t. Write P=∂z/∂θ\mat{P} = \partial\vb{z}/\partial\theta.

Step 1 of 4. What does differentiating this expression with respect to θ\theta give?

ProofInstantaneous change of variables from Liouville
Prove: If z′=f(z,t)\vb{z}' = f(\vb{z}, t) with ff of class C1C^1 and global flow, and z(t0)\vb{z}(t_0) has density p0p_0, then ddtlog⁡pt(z(t))=−tr⁡∂f∂z(z(t),t)\frac{d}{dt}\log p_t(\vb{z}(t)) = -\tr\frac{\partial f}{\partial\vb{z}}(\vb{z}(t), t).
0
Let φt\varphi_t be the flow map from t0t_0 to tt, a diffeomorphism, and z(t)=φt(z0)\vb{z}(t) = \varphi_t(\vb{z}_0).

Step 1 of 4. What relation does change of variables give between ptp_t and p0p_0?

CodeForward sensitivity of exponential growth
Implement forward_sensitivity(theta, x0, T, n=1000) for x′=θxx' = \theta x, x(0)=x0x(0) = x_0. It must use RK4 with nn steps to integrate the augmented system formed by xx and its sensitivity s=∂x/∂θs = \partial x/\partial\theta (write the equation for ss yourself), and return the tuple (x_T, s_T). Tests compare against x(T)=x0eθTx(T) = x_0e^{\theta T} and s(T)=Tx0eθTs(T) = T x_0 e^{\theta T} for several θ\theta and TT.
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]
Shift+Enter to run

Summary

Key idea
Differentiating an ODE solution means solving another linear ODE along the trajectory: forward with the variational equation, which pushes perturbations (JVP), or backward with the adjoint equation, which brings gradients (VJP) using constant memory. The trace of that same Jacobian governs how a particle’s density changes.
  • Sensitivities S=∂z/∂z0\mat{S} = \partial\vb{z}/\partial\vb{z}_0 and P=∂z/∂θ\mat{P} = \partial\vb{z}/\partial\theta solve S′=JS\mat{S}' = \mat{J}\mat{S}, P′=JP+B\mat{P}' = \mat{J}\mat{P} + \mat{B}; Grönwall justifies exchanging derivatives and bounds their growth.
  • Adjoint a(t)=∇z(t)L\vb{a}(t) = \grad_{\vb{z}(t)}L solves a′=−J⊤a\vb{a}' = -\mat{J}\T\vb{a} backward, and ∇θL=∫B⊤a  ⁣dt\grad_\theta L = \int\mat{B}\T\vb{a}\,\dd t. It is the limit of backpropagation through Euler steps; its cost does not depend on pp 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, ddtlog⁡pt=−tr⁡ ∂f/∂z\frac{d}{dt}\log p_t = -\tr\,\partial f/\partial\vb{z}, a consequence of Liouville; in high dimensions the trace is estimated by Hutchinson, unbiased but noisy.