26.3 Neural ODEs, Adjoints, and Continuous Flows

A residual block adds a correction to its input, and so does a step of Euler's method (Section 26.2). If a residual network (Section 7.4) is a numerical solution of a differential equation, what do we gain by taking the equation itself as the model, and what does it cost?

Generative modelling gives one answer. Maximum likelihood needs the density of what a model produces. A normalizing flow is a network that can be inverted, so that this density follows from the change-of-variables formula. The formula asks for the determinant of the network's Jacobian at every sample, a matrix with 30723072 rows for a colour image of 32×3232\times32 pixels. In continuous time the determinant turns into a trace, and the trace can be estimated with one backward pass.

A Neural ODE (Chen et al., 2018) takes the equation itself as the model: a differential equation x˙=fθ(x,t)\dot{\mathbf{x}}=\mathbf{f}_{\boldsymbol\theta}(\mathbf{x},t) whose field is a network and whose solution at a final time is the output. Training it and computing its density each come down to integrating one more equation beside the state. For training it is the adjoint equation, which optimal control developed in the 1950s to ask how the cost of a trajectory changes with its controls (Pontryagin et al., 1962). For the density it is an integral of the Jacobian's trace.

Compared with a residual stack, the model gains an invertible map, a step count that is no longer part of the model, a gradient that needs no stored activations, and a computable density. Each gain has a catch, and this section measures all four: a flow on the line cannot swap two points, a trained field is tied to its solver, the gradient computed without stored states drifts, and the cheap trace is noisy.

We train such a model through a solver, derive the adjoint, and follow a density along the flow. The results to carry away are the adjoint equations and the trace rule (26.3.8), on which the likelihoods of diffusion models rest; a reader who wants only the second can begin at Section 26.3.3. Nothing later builds on the subsection on memory and drift.

The cells below train through the Euler and RK4 steps of Section 26.2: the loop solve takes NN of them, of size T/NT/N, and a negative TT runs the field backward. The check of the adjoint, further down, uses the spiral A\mathbf A, its start x0\mathbf{x}_0 and the matrix exponential eCs=VeΛsV−1e^{\mathbf Cs}=\mathbf Ve^{\boldsymbol\Lambda s}\mathbf V^{-1} of Section 26.1.

rng = np.random.default_rng()
A = np.array([[-0.5, -1.0], [1.0, -0.5]])      # spiral sink: eigenvalues -0.5 +- i
x0 = np.array([2.0, 0.0])

def expm_eig(C, s):
    """e^{Cs} via the eigendecomposition C = V diag(mu) V^{-1}."""
    mu, V = np.linalg.eig(C)
    return (V @ np.diag(np.exp(mu * s)) @ np.linalg.inv(V)).real

def euler_step(f, x, h):
    """One forward-Euler step of size h for dx/dt = f(x)."""
    return x + h * f(x)

def rk4_step(f, x, h):
    """One classical Runge-Kutta step of size h for dx/dt = f(x)."""
    k1 = f(x)
    k2 = f(x + h / 2 * k1)
    k3 = f(x + h / 2 * k2)
    k4 = f(x + h * k3)
    return x + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)

def solve(step, f, x, T, N):
    """N steps of size T/N from time 0 to time T; T < 0 runs the field backward."""
    for _ in range(N):
        x = step(f, x, T / N)
    return x

26.3.1 Neural ODEs#

A Neural ODE is what a residual network becomes when its depth turns into time.

26.3.1.1 From Residual Blocks to a Continuous Model#

Set a residual block (He et al., 2016) beside a forward-Euler step of the ODE x˙=f(x,t)\dot{\mathbf{x}}=\mathbf{f}(\mathbf{x},t):

xl+1=xl+fθl(xl)andxn+1=xn+h f(xn,tn).(26.3.1)\mathbf{x}_{l+1}=\mathbf{x}_l+\mathbf{f}_{\boldsymbol\theta_l}(\mathbf{x}_l) \qquad\textrm{and}\qquad \mathbf{x}_{n+1}=\mathbf{x}_n+h\,\mathbf{f}(\mathbf{x}_n,t_n). \tag{26.3.1}

With h=1h=1 and f(⋅,tl)=fθl\mathbf{f}(\cdot,t_l)=\mathbf{f}_{\boldsymbol\theta_l} the two updates are the same formula. A ResNet whose blocks have different weights is therefore a time-dependent field sampled at the layer times and integrated by Euler's method with unit steps (Figure 26.3.1 draws the case in which all blocks share one field). Its horizon is its depth: ten blocks integrate the field to time 1010.

Figure 26.3.1:

Left: a stack of residual blocks that share one field, each adding the learned branch to an identity skip. Right: the same updates read as forward-Euler steps of size h=1h=1, beside the exact flow of the same field, from which they drift.

To take the limit, fix the horizon TT, keep one parameter vector θ\boldsymbol\theta for all times, and let the steps shrink. In the language of layers, the network grows deeper while each layer corrects less. (The field may still depend on tt: the network takes tt as an input, and that is how one parameter vector serves blocks that differ.) With NN steps of size h=T/Nh=T/N at the times tn=nht_n=nh,

xn+1=xn+h fθ(xn,tn),xN  →  N→∞    x(T)=x0+∫0Tfθ(x(t),t) dt.(26.3.2)\mathbf{x}_{n+1}=\mathbf{x}_n+h\,\mathbf{f}_{\boldsymbol\theta}(\mathbf{x}_n,t_n), \qquad \mathbf{x}_N\;\xrightarrow{\;N\to\infty\;}\; \mathbf{x}(T)=\mathbf{x}_0+\int_0^T\mathbf{f}_{\boldsymbol\theta}(\mathbf{x}(t),t)\,dt . \tag{26.3.2}

The convergence is Euler's error bound from Section 26.2: for a smooth field that is Lipschitz in x\mathbf{x}, the Euler iterate after NN steps is within O(h)O(h) of the exact solution. The Neural ODE is the limit object: the model whose output is the solution x(T)\mathbf{x}(T) of x˙=fθ(x,t)\dot{\mathbf{x}}=\mathbf{f}_{\boldsymbol\theta}(\mathbf{x},t) with x(0)=x0\mathbf{x}(0)=\mathbf{x}_0. The parameters define the field. The solver (Euler, RK4, an adaptive method) is a choice made afterwards, which changes the computed map, its cost and its error, but not the model.

The exact map and the computed map can differ in kind, not only in accuracy. The field x˙=−x\dot{x}=-x has the exact flow Φt(x)=e−tx\Phi_t(x)=e^{-t}x, a bijection of R\mathbb{R} for every tt. One Euler step with h=1h=1 computes x+1⋅(−x)=0x+1\cdot(-x)=0 and maps every input to zero. The exact map, by contrast, is a bijection whenever the field is continuous in tt and globally Lipschitz in x\mathbf{x}: running the field backward from x(T)\mathbf{x}(T) is again a problem with exactly one solution, and that solution leads back to the start (Section 26.1.1.3).

26.3.1.2 Order Preservation on the Line#

Invertibility is a gain, but it is also a constraint. Is a Neural ODE at least as expressive as the residual stack it came from? On the real line it is not, and a picture shows why. In the (t,x)(t,x) plane, trajectories of a Lipschitz field never cross. Two trajectories that swapped −1-1 and 11 would have to meet on the way (panel (a) of Figure 26.3.2).

Figure 26.3.2:

(a) On the line, trajectories of a Lipschitz field never cross (here x˙=−x\dot x=-x), so the time-TT map preserves order; the dashed pair that swaps −1-1 and 11 would need two solutions through one point. (b) The residual step x+f(x)x+f(x) with f(x)=−2xf(x)=-2x swaps the points in one step: it is an Euler step with hL=2hL=2, not a flow. (c) One extra dimension removes the obstruction: the rotation by π\pi carries (x,0)(x,0) to (−x,0)(-x,0) along half circles that pass without meeting (colours as in (b)).

Proposition (flows on R\mathbb{R} preserve order). Let f(x,t)f(x,t) be continuous in tt and globally Lipschitz in xx, and write Φt(x)\Phi_t(x) for the solution at time tt started from xx at time 00. Then for every T>0T>0 the map ΦT\Phi_T is strictly increasing.

Proof. Let x<yx\lt y and suppose ΦT(x)≥ΦT(y)\Phi_T(x)\ge\Phi_T(y). The function g(t)=Φt(y)−Φt(x)g(t)=\Phi_t(y)-\Phi_t(x) is continuous with g(0)>0g(0)>0 and g(T)≤0g(T)\le0, so by the intermediate value theorem g(s)=0g(s)=0 for some s∈(0,T]s\in(0,T]: the two trajectories meet at time ss at a point zz. Now run time backward from ss. Both reversed trajectories τ↦Φs−τ(x)\tau\mapsto\Phi_{s-\tau}(x) and τ↦Φs−τ(y)\tau\mapsto\Phi_{s-\tau}(y) solve the same initial-value problem w˙=−f(w,s−τ)\dot{w}=-f(w,s-\tau), w(0)=zw(0)=z, whose field is again Lipschitz. By Picard--Lindelöf that problem has only one solution, so the two reversed trajectories coincide, and at τ=s\tau=s this says x=yx=y, a contradiction. ■\blacksquare

The proof has one idea, to apply uniqueness backward from the meeting time. As a consequence, no Neural ODE on R\mathbb{R} realizes x↦−xx\mapsto-x: that map sends −1-1 to 11 and 11 to −1-1, which reverses their order.

The residual block x+f(x)x+f(x) with f(x)=−2xf(x)=-2x does realize it, in one step (panel (b) of Figure 26.3.2). That block is the Euler step with h=1h=1 of x˙=−2x\dot{x}=-2x, whose exact flow e−2txe^{-2t}x never reverses order. The two statements agree because one Euler step x+hf(x)x+hf(x) of a field with Lipschitz constant LL is guaranteed to be increasing when hL<1hL\lt 1: for x>yx>y,

(x+hf(x))−(y+hf(y))  ≥  (x−y)−hL (x−y)  =  (1−hL)(x−y),\big(x+hf(x)\big)-\big(y+hf(y)\big)\;\ge\;(x-y)-hL\,(x-y)\;=\;(1-hL)(x-y),

which is positive when hL<1hL\lt 1. Here hL=2hL=2, so the step may reverse order. A finite step is not a flow, and the proposition does not constrain it.

One more dimension removes the obstruction. The rotation field x˙=Kx\dot{\mathbf{x}}=\mathbf K\mathbf{x} of Section 26.1, with K=(0−110)\mathbf K=\left(\begin{smallmatrix}0&-1\\1&0\end{smallmatrix}\right), has the flow esK=cos⁡s I+sin⁡s Ke^{s\mathbf K}=\cos s\,\mathbf{I}+\sin s\,\mathbf K, which turns the plane by the angle ss. Run π\pi times as fast, as x˙=πKx\dot{\mathbf{x}}=\pi \mathbf K\mathbf{x}, it has the time-one map

Φ1=eπK=cos⁡π I+sin⁡π K=−I.\Phi_1=e^{\pi \mathbf K}=\cos\pi\,\mathbf{I}+\sin\pi\,\mathbf K=-\mathbf{I}.

It carries (x,0)(x,0) to (−x,0)(-x,0) along half circles, and trajectories pass each other in the plane without meeting (panel (c) of Figure 26.3.2). Adding dimensions in this way is called augmentation (Dupont et al., 2019): the input xx is embedded as (x,0)(x,0), the flow runs in the plane, and the first coordinate is read out. A flow is a continuous rearrangement of space, and on a line there is no room for two points to pass.

26.3.1.3 Training Through the Solver#

The forward pass of a Neural ODE is a loop of NN solver steps. The direct way to train it is to discretize, then differentiate: write the solver into the computation graph, compute the loss on xN\mathbf{x}_N, and backpropagate through the unrolled steps. With Euler as the solver the program is a ResNet of NN blocks that share one set of weights, so ordinary automatic differentiation trains it.

Let us try this on a task that is deliberately easy: carry 6464 points of the unit circle to the matching points of the ellipse centred at (1.5,0)(1.5,0) with semi-axes 1.21.2 and 0.40.4, a stretch and a shift. The exact flow of the affine field x˙=diag(ln⁡1.2,ln⁡0.4) x+c\dot{\mathbf{x}}=\mathrm{diag}(\ln1.2,\ln0.4)\,\mathbf{x}+\mathbf{c} does this without error for a suitable c\mathbf{c}, so whatever error we find will not be for want of a solution. Will the trained field still reach the targets when it is integrated accurately, or only with the ten steps it was trained with? In the first case training has found a flow, in the second only a ten-step program.

The field has one hidden layer of 3232 tanh units, the loss is the mean squared error at the endpoints, and Adam (Section 23.5) runs full-batch iterations 00 to 400400 at learning rate 0.050.05, lowered to 0.0050.005 for the last hundred. We train twice from the same initial weights: once through N=10N=10 Euler steps of size h=0.1h=0.1, and once through ten steps of RK4, which evaluates the field four times per step.

angle = np.linspace(0, 2 * np.pi, 64, endpoint=False)
X0_ring = np.stack([np.cos(angle), np.sin(angle)], axis=1)            # circle
X1_ring = np.stack([1.5 + 1.2 * np.cos(angle), 0.4 * np.sin(angle)], axis=1)
solvers = {'Euler': euler_step, 'RK4': rk4_step}
seed = int(rng.integers(2**31))                # one initialization for both solvers

With the source circle X0_ring, target ellipse X1_ring, and shared initialization seed fixed, train fits the two-layer tanh vector field net by backpropagating through 10 steps of solve(step, net, X, 1.0, 10) for each solver in solvers:

X, Y = torch.tensor(X0_ring).float(), torch.tensor(X1_ring).float()

def train(name, step, seed):
    """Fit the field through 10 steps of one solver, from the given seed."""
    torch.manual_seed(seed)
    net = nn.Sequential(nn.Linear(2, 32), nn.Tanh(), nn.Linear(32, 2))
    for layer in net[::2]:                     # Glorot-uniform weights, zero biases
        nn.init.xavier_uniform_(layer.weight)
        nn.init.zeros_(layer.bias)
    opt = torch.optim.Adam(net.parameters(), lr=0.05)
    sched = torch.optim.lr_scheduler.MultiStepLR(opt, [300], 0.1)  # 0.005 from 300
    losses = []
    for it in range(401):
        loss = ((solve(step, net, X, 1.0, 10) - Y) ** 2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
        sched.step()
        if it % 200 == 0:
            losses.append(loss.item())
    print(f'{name}-trained: loss', ', '.join(f'{l:.1e}' for l in losses),
          'at iterations 0, 200, 400')
    return net

trained = {name: train(name, step, seed) for name, step in solvers.items()}
Euler-trained: loss 1.5e+00, 3.1e-06, 5.2e-07 at iterations 0, 200, 400
RK4-trained: loss 1.5e+00, 4.3e-06, 5.8e-07 at iterations 0, 200, 400

Both losses fall from order one to below 10−510^{-5}. Judged by the loss they were trained on, the two fields are equally good.

Two tests follow. The first puts our question directly: integrate each trained field with its own solver at N=100N=100 and N=1000N=1000 steps (Nh=1Nh=1 throughout). The larger NN, the closer the computed map is to the exact time-one flow of the field. Before running the cell, guess what this does to the two endpoint errors. The second test is about invertibility, the first gain on our list. Take the Euler-trained field forward NN steps and then backward NN steps, and measure how far the round trip lands from where it started. An exact flow would return every point to its start.

dist = lambda P, Q: torch.linalg.vector_norm(P - Q, dim=1).mean().item()
print('   N   Euler-trained   RK4-trained   Euler round trip')
with torch.inference_mode():
    for N in (10, 100, 1000):
        err = [dist(solve(solvers[k], trained[k], X, 1.0, N), Y) for k in solvers]
        fwd = solve(euler_step, trained['Euler'], X, 1.0, N)
        back = solve(euler_step, trained['Euler'], fwd, -1.0, N)
        print(f'{N:4d}   {err[0]:13.1e}   {err[1]:11.1e}   {dist(back, X):16.1e}')
   N   Euler-trained   RK4-trained   Euler round trip
  10         9.0e-04       9.8e-04            5.4e-02
 100         1.7e-02       9.8e-04            5.5e-03
1000         1.9e-02       9.8e-04            5.5e-04

Take the round trip first, in the last column. It misses its start by about 0.0550.055 at N=10N=10, 0.00550.0055 at N=100N=100 and 0.000550.00055 at N=1000N=1000, tenfold less per tenfold more steps. Each pair of a forward and a backward Euler step leaves a residual of order h2h^2, and NN of them add up to O(h)O(h), Euler's order. Running the field backward undoes the exact flow. It undoes the Euler program only in the limit h→0h\to0. An Euler program with hL<1hL\lt 1 does have an inverse, since each of its steps is then a bijection (Exercise 4). But that inverse is made of implicit steps, not of Euler steps with −h-h.

Now the endpoint errors. At the training step count both fields land within a few thousandths of their targets. Surprisingly, finer steps make the Euler-trained field worse: its error rises to about 0.020.02 and then stops changing. Training fitted the ten-step program. The exact time-one flow of that field, which N=1000N=1000 approximates, lands 0.020.02 from the targets, under 2%2\% of the ellipse's long semi-axis: the field defines a flow close to its ten-step program, not equal to it.

The RK4-trained field prints the same error at ten, a hundred and a thousand steps. Ten RK4 steps already compute the flow of so smooth a field to the digits shown, so fitting the program fitted the flow, and the step count is free after training. A field trained through a crude solver is a program; a field trained through an accurate one is a flow.

The accuracy has to be supplied in every iteration, however. Training through RK4 evaluates the field forty times per iteration and backpropagates through all forty evaluations; training through Euler, ten times. A hundred Euler steps or a second-order solver would change the count and nothing else. The alternative is to take the solver out of training altogether: fit the field by regression onto targets that are known in closed form, at one field evaluation per example, so that what is fitted is a flow from the start. This is how Section 26.6 and Section 26.7 learn their fields.

26.3.2 The Adjoint Method#

Training gave us the gradient of the ten-step program, and the program and the flow turned out to be different maps. Are their gradients different too? And can the gradient of the flow be computed at all, when no finite program computes the flow?

It can, by an idea that reverse-mode differentiation already contains. Reverse mode carries the derivative of the loss with respect to a layer's activations backward from layer to layer; Section 22.3.2 called it the adjoint of a node. The adjoint method carries the same quantity backward through time, with one node x(t)\mathbf{x}(t) for every instant. Its central object is the adjoint state a(t)=∂L/∂x(t)\mathbf{a}(t)=\partial\mathcal{L}/\partial\mathbf{x}(t), the gradient of the loss with respect to the state at time tt, and it turns out to obey a linear differential equation of its own.

26.3.2.1 The Scalar Case#

Before the general statement we work one example to the end, an example in which every quantity has a closed form. Take x˙=θx\dot{x}=\theta x with x(0)=x0x(0)=x_0 and the loss L=12x(T)2\mathcal{L}=\tfrac12x(T)^2 on the endpoint. Directly, x(T)=eθTx0x(T)=e^{\theta T}x_0, so ∂x(T)/∂θ=T x(T)\partial x(T)/\partial\theta=T\,x(T) and

∂L∂θ=x(T) ∂x(T)∂θ=T x(T)2.\frac{\partial\mathcal{L}}{\partial\theta}=x(T)\,\frac{\partial x(T)}{\partial\theta}=T\,x(T)^2 .

With θ=T=x0=1\theta=T=x_0=1 this is e2=7.389e^2=7.389.

The adjoint reaches the same number by another route. A nudge δ\delta to the state at time tt grows to eθ(T−t)δe^{\theta(T-t)}\delta by time TT and changes the loss by x(T) eθ(T−t)δx(T)\,e^{\theta(T-t)}\delta, so a(t)=eθ(T−t)x(T)a(t)=e^{\theta(T-t)}x(T). This adjoint solves the ODE a˙=−θa\dot{a}=-\theta a backward from the final value a(T)=x(T)a(T)=x(T), which is the derivative of the loss ℓ(x)=12x2\ell(x)=\tfrac12x^2 at x(T)x(T). A change δθ\delta\theta of the parameter alters the velocity by x(t) δθx(t)\,\delta\theta at every instant, since ∂f/∂θ=x\partial f/\partial\theta=x, and the adjoint converts each of these nudges into a change of the loss. Summing over time,

∫0Ta(t) ∂f∂θ dt=∫0Teθ(T−t)x(T)  eθtx0 dt=∫0Tx(T)2 dt=T x(T)2.(26.3.3)\int_0^T a(t)\,\frac{\partial f}{\partial\theta}\,dt =\int_0^T e^{\theta(T-t)}x(T)\;e^{\theta t}x_0\,dt =\int_0^T x(T)^2\,dt =T\,x(T)^2 . \tag{26.3.3}

The integrand is constant: xx grows forward, aa shrinks by the same factor when read forward, and their product stays at x(T)2x(T)^2 (Figure 26.3.3). The gradient is the area under it.

Figure 26.3.3:

The scalar adjoint for x˙=θx\dot x=\theta x at θ=1\theta=1, x0=1x_0=1, T=1T=1: the state grows forward, the adjoint is integrated backward from the loss gradient a(1)=x(1)a(1)=x(1), and their product is constant; the parameter gradient is the shaded area, Tx(T)2=e2Tx(T)^2=e^2.

26.3.2.2 The Adjoint Equations#

The general case keeps the shape of the scalar one: an adjoint that runs backward from the gradient of the loss, and a parameter gradient that integrates the adjoint against ∂f/∂θ\partial\mathbf{f}/\partial\boldsymbol\theta.

Proposition (the adjoint equations). Let f\mathbf{f} be continuously differentiable in x\mathbf{x} and θ\boldsymbol\theta, let x(t)\mathbf{x}(t) solve x˙=f(x,θ,t)\dot{\mathbf{x}}=\mathbf{f}(\mathbf{x},\boldsymbol\theta,t) (the field fθ\mathbf{f}_{\boldsymbol\theta}, with its parameters written as an argument) on [0,T][0,T] from a fixed x(0)\mathbf{x}(0), and let L=ℓ(x(T))\mathcal{L}=\ell(\mathbf{x}(T)) for a differentiable ℓ\ell. Then the adjoint state satisfies the linear ODE

a˙(t)=−(∂f∂x) ⁣⊤ ⁣a(t),a(T)=∇ℓ(x(T)),(26.3.4)\dot{\mathbf{a}}(t) = -\left(\frac{\partial \mathbf{f}}{\partial \mathbf{x}}\right)^{\!\top}\! \mathbf{a}(t), \qquad \mathbf{a}(T) = \nabla \ell(\mathbf{x}(T)), \tag{26.3.4}

integrated backward from TT, and the parameter gradient is the integral

∂L∂θ=∫0T(∂f∂θ) ⁣⊤ ⁣a(t) dt,(26.3.5)\frac{\partial \mathcal{L}}{\partial \boldsymbol\theta} = \int_0^T \left(\frac{\partial \mathbf{f}}{\partial \boldsymbol\theta}\right)^{\!\top}\! \mathbf{a}(t)\, dt, \tag{26.3.5}

with both partial derivatives evaluated along the trajectory (x(t),θ,t)(\mathbf{x}(t),\boldsymbol\theta,t) (Chen et al., 2018).

Proof (variational). Perturb the parameters by an infinitesimal δθ\delta\boldsymbol\theta. Because f\mathbf{f} is C1C^1, the solution is differentiable in θ\boldsymbol\theta, and the first-order perturbation δx(t)\delta\mathbf{x}(t) of the trajectory obeys the linearization of the dynamics (differentiate the ODE in θ\boldsymbol\theta and use the chain rule):

δx˙=∂f∂x δx+∂f∂θ δθ,δx(0)=0.\delta\dot{\mathbf{x}} = \frac{\partial \mathbf{f}}{\partial \mathbf{x}}\,\delta\mathbf{x} + \frac{\partial \mathbf{f}}{\partial \boldsymbol\theta}\,\delta\boldsymbol\theta, \qquad \delta\mathbf{x}(0) = \mathbf{0}.

Define a(t)\mathbf{a}(t) by the backward ODE (26.3.4) and differentiate the pairing a⊤δx\mathbf{a}^\top\delta\mathbf{x}:

ddt(a⊤δx)=a˙⊤δx+a⊤δx˙=−a⊤∂f∂x δx+a⊤∂f∂x δx+a⊤∂f∂θ δθ=a⊤∂f∂θ δθ.\begin{aligned} \frac{d}{dt}\left(\mathbf{a}^\top \delta\mathbf{x}\right) &= \dot{\mathbf{a}}^\top \delta\mathbf{x} + \mathbf{a}^\top \delta\dot{\mathbf{x}} \\ &= -\mathbf{a}^\top \frac{\partial \mathbf{f}}{\partial \mathbf{x}}\,\delta\mathbf{x} + \mathbf{a}^\top \frac{\partial \mathbf{f}}{\partial \mathbf{x}}\,\delta\mathbf{x} + \mathbf{a}^\top \frac{\partial \mathbf{f}}{\partial \boldsymbol\theta}\,\delta\boldsymbol\theta = \mathbf{a}^\top \frac{\partial \mathbf{f}}{\partial \boldsymbol\theta}\,\delta\boldsymbol\theta . \end{aligned}

The state-coupling terms cancel, and the adjoint ODE was defined so that they would. Integrate from 00 to TT, using δx(0)=0\delta\mathbf{x}(0)=\mathbf{0} at the left endpoint:

a(T)⊤δx(T)=∫0Ta(t)⊤∂f∂θ dt  δθ.\mathbf{a}(T)^\top \delta\mathbf{x}(T) = \int_0^T \mathbf{a}(t)^\top \frac{\partial \mathbf{f}}{\partial \boldsymbol\theta}\, dt \;\delta\boldsymbol\theta .

The left side is ∇ℓ(x(T))⊤δx(T)=δL\nabla\ell(\mathbf{x}(T))^\top\delta\mathbf{x}(T)=\delta\mathcal{L}, the first-order change of the loss; the right side is linear in δθ\delta\boldsymbol\theta with coefficient (26.3.5). It remains to identify a\mathbf{a} with the adjoint state. Run the same argument with δθ=0\delta\boldsymbol\theta=\mathbf{0} and a nudge δx(s)\delta\mathbf{x}(s) injected at time ss: the pairing a⊤δx\mathbf{a}^\top\delta\mathbf{x} is then constant on [s,T][s,T], so δL=a(T)⊤δx(T)=a(s)⊤δx(s)\delta\mathcal{L}=\mathbf{a}(T)^\top\delta\mathbf{x}(T)=\mathbf{a}(s)^\top\delta\mathbf{x}(s), and the solution of (26.3.4) is ∂L/∂x(s)\partial\mathcal{L}/\partial\mathbf{x}(s). ■\blacksquare

The backward ODE is linear in a\mathbf{a}, with the transposed Jacobian as its matrix. Each of its steps computes a⊤∂f/∂x\mathbf{a}^\top\partial\mathbf{f}/\partial\mathbf{x}, one vector--Jacobian product, which costs one reverse-mode pass through f\mathbf{f} (Section 22.5). The same pass returns (∂f/∂θ)⊤a(\partial\mathbf{f}/\partial\boldsymbol\theta)^\top\mathbf{a}, the integrand of the parameter gradient, however many parameters there are. (A ReLU field is only piecewise C1C^1, so the proposition does not cover it, although automatic differentiation still differentiates the unrolled solver piece by piece. Smooth activations such as tanh or GELU satisfy the hypothesis.)

26.3.2.3 Backpropagation as the Discrete Adjoint#

Backpropagation through the Euler program can now be set beside the adjoint ODE, line by line. To keep the formulas short, let the field be autonomous and write J=∂f/∂x\mathbf J=\partial\mathbf{f}/\partial\mathbf{x} for its Jacobian. Differentiate the program xn+1=xn+h f(xn,θ)\mathbf{x}_{n+1}=\mathbf{x}_n+h\,\mathbf{f}(\mathbf{x}_n,\boldsymbol\theta) by the chain rule, with an=∂L/∂xn\mathbf{a}_n=\partial\mathcal{L}/\partial\mathbf{x}_n. The Jacobian of one step is I+hJ(xn)\mathbf{I}+h\mathbf J(\mathbf{x}_n), so

an=(I+hJ(xn)) ⁣⊤an+1,aN=∇ℓ(xN),∂L∂θ=∑n=0N−1h(∂f∂θ(xn)) ⁣⊤an+1.(26.3.6)\begin{aligned} \mathbf{a}_n &= \big(\mathbf{I}+h\mathbf J(\mathbf{x}_n)\big)^{\!\top}\mathbf{a}_{n+1}, \qquad \mathbf{a}_N = \nabla\ell(\mathbf{x}_N), \\ \frac{\partial\mathcal{L}}{\partial\boldsymbol\theta} &= \sum_{n=0}^{N-1}h\left(\frac{\partial\mathbf{f}}{\partial\boldsymbol\theta}(\mathbf{x}_n)\right)^{\!\top}\mathbf{a}_{n+1}. \end{aligned} \tag{26.3.6}

Compare this with one explicit Euler step of the adjoint ODE (26.3.4) from tn+1t_{n+1} back to tnt_n:

an=an+1+h J(xn+1)⊤an+1.\mathbf{a}_n=\mathbf{a}_{n+1}+h\,\mathbf J(\mathbf{x}_{n+1})^\top\mathbf{a}_{n+1}.

The two updates differ only in where the Jacobian is evaluated: at the start xn\mathbf{x}_n of the forward step or at its end xn+1\mathbf{x}_{n+1}. The sum in (26.3.6) is a rectangle rule for the integral (26.3.5). So backpropagation through a solver is a discrete adjoint, and a solver applied to the adjoint ODE is the continuous adjoint, discretized. The literature calls the two routes discretize-then-optimize, which is the "discretize, then differentiate" of our training run, and optimize-then-discretize (Kidger, 2022). The first is the exact gradient of the program, the second approximates the gradient of the flow, and for Euler the two gradients differ at first order in hh. Of everything in this subsection, this is the statement to keep.

The scalar example shows both gradients at once. For x˙=θx\dot{x}=\theta x the Euler program is xN=(1+hθ)Nx0x_N=(1+h\theta)^Nx_0, so ∂xN/∂θ=Nh(1+hθ)N−1x0=T xN/(1+hθ)\partial x_N/\partial\theta=Nh(1+h\theta)^{N-1}x_0=T\,x_N/(1+h\theta) and the discrete adjoint gives ∂L/∂θ=T xN2/(1+hθ)\partial\mathcal{L}/\partial\theta=T\,x_N^2/(1+h\theta). With θ=T=x0=1\theta=T=x_0=1 this is 6.1166.116 at N=10N=10, 7.2447.244 at N=100N=100 and 7.3747.374 at N=1000N=1000, against the exact e2=7.389e^2=7.389. The gaps 1.271.27, 0.1450.145 and 0.01480.0148 shrink tenfold per tenfold NN.

The spiral field of Section 26.1, x˙=Ax\dot{\mathbf{x}}=\mathbf A\mathbf{x} with A=(−0.5−11−0.5)\mathbf A=\left(\begin{smallmatrix}-0.5&-1\\1&-0.5\end{smallmatrix}\right), gives the same check in two dimensions with every ingredient in closed form. For a linear field the Jacobian is A\mathbf A at every point, so the two recursions displayed above are one and the same. What is left to measure is the error that both have against the flow, where the states, the adjoint and the sum are all Euler's.

Take θ\boldsymbol\theta to be the entries of A\mathbf A and L=12∥x(T)∥2\mathcal{L}=\tfrac12\|\mathbf{x}(T)\|^2. The trajectory is eAtx0e^{\mathbf At}\mathbf{x}_0, the adjoint is a(t)=eA⊤(T−t)x(T)\mathbf{a}(t)=e^{\mathbf A^\top(T-t)}\mathbf{x}(T) (the solution of a˙=−A⊤a\dot{\mathbf{a}}=-\mathbf A^\top\mathbf{a}), and since ∂f/∂Aij=xjei\partial\mathbf{f}/\partial A_{ij}=x_j\mathbf{e}_i, the gradient (26.3.5) becomes ∂L/∂A=∫0Ta(t) x(t)⊤dt\partial\mathcal{L}/\partial \mathbf A=\int_0^T\mathbf{a}(t)\,\mathbf{x}(t)^\top dt.

The cell writes the backward sweep (26.3.6) by hand, for T=2T=2. Its first line of output tests the sweep against central finite differences of the same program at N=1000N=1000 steps, which tells us only that the sweep is coded correctly. The distance that matters is the one to the gradient of the exact flow. For it the cell evaluates the continuous adjoint integral by the trapezoid rule on 20002000 intervals, with a\mathbf{a} and x\mathbf{x} from the matrix exponential, and compares it with the discrete adjoint at three step counts.

def loss_and_grad_unrolled(A, x0, T, N):
    """L = ||x_N||^2 / 2 through N unrolled Euler steps; dL/dA by hand-written
    reverse mode, the discrete adjoint."""
    h, xs = T / N, [x0]
    for _ in range(N):
        xs.append(xs[-1] + h * (A @ xs[-1]))   # forward sweep, tape the states
    a, gA = xs[-1].copy(), np.zeros_like(A)    # a_N = dL/dx_N = x_N
    for n in range(N - 1, -1, -1):             # backward sweep: one VJP per step
        gA += h * np.outer(a, xs[n])           # dL/dA += h a_{n+1} x_n^T
        a = a + h * (A.T @ a)                  # a_n = (I + hA)^T a_{n+1}
    return 0.5 * xs[-1] @ xs[-1], gA

T = 2.0
loss = lambda A: loss_and_grad_unrolled(A, x0, T, 1000)[0]
g_fd = np.array([(loss(A + 1e-5 * E) - loss(A - 1e-5 * E)) / 2e-5
                 for E in np.eye(4).reshape(4, 2, 2)]).reshape(2, 2)
gap_fd = np.abs(loss_and_grad_unrolled(A, x0, T, 1000)[1] - g_fd).max()
print(f'N =  1000: |backward sweep - central differences| = {gap_fd:.1e}')
n_quad = 2000                                  # continuous adjoint, trapezoid rule
ts = np.linspace(0.0, T, n_quad + 1)
xT = expm_eig(A, T) @ x0
AX = np.stack([np.outer(expm_eig(A.T, T - s) @ xT, expm_eig(A, s) @ x0)
               for s in ts])                   # a(s) x(s)^T
g_cont = (T / n_quad) * (AX[1:-1].sum(axis=0) + 0.5 * (AX[0] + AX[-1]))
for N in (100, 1000, 10000):
    gap = np.abs(loss_and_grad_unrolled(A, x0, T, N)[1] - g_cont).max()
    print(f'N = {N:5d}: |discrete - continuous adjoint|     = {gap:.1e}')
N =  1000: |backward sweep - central differences| = 1.2e-10
N =   100: |discrete - continuous adjoint|     = 2.9e-02
N =  1000: |discrete - continuous adjoint|     = 2.8e-03
N = 10000: |discrete - continuous adjoint|     = 2.8e-04

The sweep matches the finite differences to about 10−1010^{-10}, the accuracy of the differences themselves. Its gap to the gradient of the flow falls from 2.9×10−22.9\times10^{-2} to 2.8×10−32.8\times10^{-3} to 2.8×10−42.8\times10^{-4}, tenfold per tenfold NN, as in the scalar case.

26.3.2.4 Memory and Drift#

The adjoint ODE needs x(t)\mathbf{x}(t) at every backward step, because the Jacobian is evaluated there. There are two ways to supply it. Store the forward states, as backpropagation does, which costs memory proportional to NN. Or re-integrate x˙=f\dot{\mathbf{x}}=\mathbf{f} backward from x(T)\mathbf{x}(T) alongside a\mathbf{a}, which keeps the memory constant in NN at the cost of one more field evaluation per step. The second option sounds too good, and the smallest case shows why: it amplifies errors.

For x˙=−λx\dot{x}=-\lambda x with λ>0\lambda>0, the backward integration solves x˙=+λx\dot{x}=+\lambda x. An absolute error δ\delta in the stored x(T)x(T) therefore becomes eλTδe^{\lambda T}\delta by the time it reaches t=0t=0.

How large is δ\delta? Picture a state with two modes. One decays at the rate λ=50\lambda=50, the fast rate of the stiff example of Section 26.2.3, and the other hardly moves. Let the fast mode point along a diagonal, so that every coordinate contains some of it. By time TT the fast mode has died out, the coordinates that are stored are of size one, and double precision rounds each of them at about 10−1610^{-16}. Rounding knows nothing of modes: part of the error lies along the fast direction, so δ≈10−16\delta\approx10^{-16}. The reconstructed start is then off by 2.7×10−112.7\times10^{-11} at T=0.25T=0.25, by 7×10−67\times10^{-6} at T=0.5T=0.5 and by 5×1055\times10^{5} at T=1T=1, larger than the state itself. A double carries about sixteen digits, and a factor of e50≈5×1021e^{50}\approx5\times10^{21} is five digits more than it has. Exercise 3 measures this growth.

For the spiral, whose eigenvalues have real part −0.5-0.5, the factor over T=2T=2 is only ee. A strongly contracting forward flow is a strongly expanding backward one, so re-integration saves memory at the cost of drift. For stiff fields checkpointing (Section 22.5.2.5) is the sturdier choice. It stores the state only at a few checkpoints and recomputes the states in between forward from the checkpoint before them, so nothing is ever integrated against the flow. With a checkpoint every N\sqrt N steps the backward sweep holds about 2N2\sqrt N states, 6363 instead of 10001000 for N=1000N=1000, at the cost of one extra forward pass.

That makes three routes to a gradient. Which would we use? Backpropagation through the solver, with checkpoints when memory is short: it returns the exact gradient of the program that is actually run. The continuous adjoint is what that gradient converges to, and the formula to reason with. Re-integrating the state is a last resort, for fields that are not stiff.

26.3.3 Continuous Normalizing Flows#

A Neural ODE moves points. A generative model trained by maximum likelihood must also say how probable each of its outputs is, so we now follow a density along the flow.

26.3.3.1 Density Along a Flow#

Pushing samples through a flow turns it into a generator: draw x(0)\mathbf{x}(0) from a simple density p0p_0 and integrate. Training such a generator by maximum likelihood needs the density of what comes out. A normalizing flow is an invertible network trained in this way, and its density follows from the change-of-variables formula of Section 24.2: for an invertible differentiable map g\mathbf{g} with Jacobian Jg\mathbf J_{\mathbf{g}},

log⁡pout(g(x))=log⁡pin(x)−log⁡∣det⁡Jg(x)∣.(26.3.7)\log p_{\textrm{out}}(\mathbf{g}(\mathbf{x})) = \log p_{\textrm{in}}(\mathbf{x}) - \log \left|\det \mathbf J_{\mathbf{g}}(\mathbf{x})\right| . \tag{26.3.7}

The log-density drops by the logarithm of the factor by which g\mathbf{g} stretches volume near x\mathbf{x}. A normalizing flow built from many layers needs one log-determinant per layer and sample. A general determinant costs O(d3)O(d^3) operations, about 2×10102\times10^{10} for the d=3072d=3072 of a 32×3232\times32 colour image. Discrete flows therefore restrict their layers to triangular Jacobians, whose determinant is the product of the diagonal, or to identity-plus-low-rank Jacobians, such as det⁡(I+uv⊤)=1+v⊤u\det(\mathbf{I}+\mathbf{u}\mathbf{v}^\top)=1+\mathbf{v}^\top\mathbf{u}. Both determinants cost O(d)O(d).

In continuous time the formula simplifies. Start with one dimension. The field x˙=θx\dot{x}=\theta x on R\mathbb{R} has the flow Φt(x)=eθtx\Phi_t(x)=e^{\theta t}x, which stretches every interval by eθte^{\theta t}. A density carried along is divided by the stretch, so log⁡pt(x(t))=log⁡p0(x0)−θt\log p_t(x(t))=\log p_0(x_0)-\theta t and ddtlog⁡pt(x(t))=−θ\tfrac{d}{dt}\log p_t(x(t))=-\theta. The number θ\theta is the 1×11\times1 Jacobian of the field, and therefore also its trace.

The spiral is the running example in two dimensions. Its flow eAt=e−t/2etKe^{\mathbf At}=e^{-t/2}e^{t\mathbf K} is a rotation followed by a shrink by e−t/2e^{-t/2} (Section 26.1). A disc is carried to a disc of e−t/2e^{-t/2} times its radius, so its area is multiplied by e−te^{-t}, and the density along each trajectory rises by ete^{t}. Here tr⁡A=−1\operatorname{tr}\mathbf A=-1, so the rate of change of the log-density is again minus the trace. Figure 26.3.4 draws this beside a field that preserves area and one that expands it: the darkest disc of the spiral, at t=1.2t=1.2, has e−1.2≈0.30e^{-1.2}\approx0.30 of the area of the lightest.

Figure 26.3.4:

A disc of samples carried by the exact flows of three linear fields, shown at t=0t=0, 0.60.6 and 1.21.2 (darker is later); the dotted line is the path of the centre. The density along a trajectory changes by the factor e−ttr⁡Ae^{-t\operatorname{tr}\mathbf A}: it rises where the flow contracts (left, the spiral), stays constant under the area-preserving saddle although the shape changes (middle), and falls where the flow expands (right).

26.3.3.2 The Instantaneous Change of Variables#

Both examples were linear, and in both the log-density changed at the rate minus the trace. The general case needs one fact about determinants: over a short step the flow map is close to the identity, and the determinant of a matrix close to the identity is governed by its trace.

Lemma. For any square matrix J\mathbf J, det⁡(I+hJ)=1+htr⁡J+O(h2)\det(\mathbf{I}+h\mathbf J)=1+h\operatorname{tr}\mathbf J+O(h^2).

Proof. The permutation formula (Section 21.2.3.2) writes the determinant as a signed sum, over all permutations, of products with one entry from every row and every column. Any permutation other than the identity picks at least two off-diagonal entries, each of size O(h)O(h), so it contributes O(h2)O(h^2). The identity permutation contributes ∏i(1+hJii)=1+h∑iJii+O(h2)\prod_i(1+hJ_{ii})=1+h\sum_iJ_{ii}+O(h^2). ■\blacksquare

Proposition (instantaneous change of variables). Let x˙=f(x,t)\dot{\mathbf{x}}=\mathbf{f}(\mathbf{x},t) with f\mathbf{f} continuously differentiable in (x,t)(\mathbf{x},t) and globally Lipschitz in x\mathbf{x}, so that each flow map Φt\Phi_t is a C1C^1 bijection with a C1C^1 inverse (the solution of a C1C^1 field is C1C^1 in its initial value (Hairer et al., 1993), and the inverse runs the field backward). Let x(0)∼p0\mathbf{x}(0)\sim p_0 for a positive differentiable density p0p_0. Then the density ptp_t of x(t)\mathbf{x}(t) exists and is positive, and along each trajectory (Chen et al., 2018)

ddtlog⁡pt(x(t))=−tr⁡ ⁣(∂f∂x) ⁣(x(t),t).(26.3.8)\frac{d}{dt} \log p_t(\mathbf{x}(t)) = -\operatorname{tr}\!\left(\frac{\partial \mathbf{f}}{\partial \mathbf{x}}\right)\!(\mathbf{x}(t), t). \tag{26.3.8}

Proof. The density exists by (26.3.7) applied to the bijection Φt\Phi_t, and it is positive because p0p_0 is and the Jacobian of a map with a differentiable inverse is nonsingular. Over a short interval the flow advances by the map Φt→t+h(x)=x+∫tt+hf(x(s),s) ds\Phi_{t\to t+h}(\mathbf{x})=\mathbf{x}+\int_t^{t+h}\mathbf{f}(\mathbf{x}(s),s)\,ds. Differentiating in x\mathbf{x} and using the continuity of J\mathbf J, its Jacobian is I+hJ+o(h)\mathbf{I}+h\mathbf J+o(h), where J=∂f/∂x\mathbf J=\partial\mathbf{f}/\partial\mathbf{x} is evaluated at (x(t),t)(\mathbf{x}(t),t) and o(h)o(h) stands for terms that vanish faster than hh. Apply (26.3.7) to this one map and expand with the Lemma, which tolerates the perturbation: replacing hJh\mathbf J by hJ+o(h)h\mathbf J+o(h) changes the determinant only by o(h)o(h). For small hh the determinant is close to 11, hence positive, so the absolute value can be dropped:

log⁡pt+h(x(t+h))=log⁡pt(x(t))−log⁡det⁡ ⁣(I+hJ+o(h))=log⁡pt(x(t))−htr⁡J+o(h),\begin{aligned} \log p_{t+h}(\mathbf{x}(t+h)) &= \log p_t(\mathbf{x}(t)) - \log\det\!\big(\mathbf{I} + h\mathbf J + o(h)\big) \\ &= \log p_t(\mathbf{x}(t)) - h \operatorname{tr} \mathbf J + o(h), \end{aligned}

using log⁡(1+u)=u+O(u2)\log(1+u)=u+O(u^2). Subtract log⁡pt(x(t))\log p_t(\mathbf{x}(t)), divide by hh, and let h→0h\to0. ■\blacksquare

The hypotheses look heavier than they are. They ask only that every flow map be a smooth bijection, which a field with smooth Lipschitz activations such as tanh provides. The content of the proposition is the one line with the trace.

The trace of the Jacobian is the divergence ∇⋅f\nabla\cdot\mathbf{f} of the field, the local rate at which the flow expands volume. Where the field spreads samples apart (tr⁡J>0\operatorname{tr}\mathbf J>0) the log-density along each trajectory falls, and where it compresses them, it rises. Integrating (26.3.8) along a trajectory gives

log⁡pT(x(T))=log⁡p0(x(0))−∫0Ttr⁡ ⁣(∂f∂x)dt.(26.3.9)\log p_T(\mathbf{x}(T)) = \log p_0(\mathbf{x}(0)) - \int_0^T \operatorname{tr}\!\left(\frac{\partial \mathbf{f}}{\partial \mathbf{x}}\right) dt . \tag{26.3.9}

The per-layer sum of log-determinants of a discrete flow has become an integral of traces. A model that computes it, by integrating the pair (x,log⁡p)(\mathbf{x},\log p) with any ODE solver, is a continuous normalizing flow (CNF) (Chen et al., 2018). It needs no restriction on the architecture of f\mathbf{f}. To evaluate the density of a given point x(T)\mathbf{x}(T), integrate the field backward from it to x(0)\mathbf{x}(0), accumulate the trace on the way, and read off p0p_0 there. Likelihoods of diffusion models are computed in this way (Section 17.6). Nothing in the formula prefers a direction of time: the generators of Section 26.6 and Section 26.7 put the noise at the final time and the data at t=0t=0, and the same formula serves them.

For a linear field the trace integral is ttr⁡At\operatorname{tr}\mathbf A, and (26.3.9) compared with (26.3.7) for the map eAte^{\mathbf At} says log⁡det⁡eAt=ttr⁡A\log\det e^{\mathbf At}=t\operatorname{tr}\mathbf A. For a diagonalizable A=VΛV−1\mathbf A=\mathbf V\boldsymbol\Lambda \mathbf V^{-1} the identity also follows in one line from the eigenvalues,

det⁡eAt=det⁡(VeΛtV−1)=∏jeΛjjt=ettr⁡A,(26.3.10)\det e^{\mathbf At}=\det\big(\mathbf Ve^{\boldsymbol\Lambda t}\mathbf V^{-1}\big)=\prod_je^{\Lambda_{jj}t}=e^{t\operatorname{tr}\mathbf A}, \tag{26.3.10}

and the comparison of the two formulas gives it for every A\mathbf A.

The proposition follows one trajectory at a time. Stated for the whole density at once, the same law is the continuity equation of fluid mechanics, which Section 26.5 derives together with the term that noise adds.

26.3.3.3 Checking the Trace Integral#

A linear field is a weak test of the proposition: its trace is constant, and the integral is just ttr⁡At\operatorname{tr}\mathbf A. A nonlinear field is a real one, because its trace changes along the path. Take the planar field f(x)=W2tanh⁡(W1x+b1)\mathbf{f}(\mathbf{x})=\mathbf W_2\tanh(\mathbf W_1\mathbf{x}+\mathbf{b}_1) with 88 hidden units and random weights. Its Jacobian and trace are explicit:

J=W2 diag(s) W1,s=1−tanh⁡2(W1x+b1),tr⁡J=∑isi (W1W2)ii,\mathbf J=\mathbf W_2\,\mathrm{diag}(\mathbf{s})\,\mathbf W_1, \qquad \mathbf{s}=1-\tanh^2(\mathbf W_1\mathbf{x}+\mathbf{b}_1), \qquad \operatorname{tr}\mathbf J=\sum_is_i\,(\mathbf W_1\mathbf W_2)_{ii},

using the cyclic property tr⁡(W2 diag(s) W1)=tr⁡(diag(s) W1W2)\operatorname{tr}\big(\mathbf W_2\,\mathrm{diag}(\mathbf{s})\,\mathbf W_1\big)=\operatorname{tr}\big(\mathrm{diag}(\mathbf{s})\,\mathbf W_1\mathbf W_2\big). The cell integrates the pair (x,∫tr⁡J dt)(\mathbf{x},\int\operatorname{tr}\mathbf J\,dt) with RK4 to T=1T=1 and keeps the path. It prints the smallest and the largest trace met on the way, and then compares the integral with log⁡∣det⁡DΦT∣\log|\det D\Phi_T|, where the Jacobian DΦTD\Phi_T of the flow map is computed from central finite differences of the flow map itself.

n_hidden = 8
W1, b1 = rng.standard_normal((n_hidden, 2)), rng.standard_normal(n_hidden)
W2 = rng.standard_normal((2, n_hidden)) / np.sqrt(n_hidden)
field = lambda x: W2 @ np.tanh(W1 @ x + b1)
trJ = lambda x: np.sum((1 - np.tanh(W1 @ x + b1) ** 2)
                       * np.einsum('ij,ji->i', W1, W2))
aug = lambda z: np.append(field(z[:2]), trJ(z[:2]))  # d/dt (x, int tr J)
xa, N = rng.standard_normal(2), 200
zs = [np.append(xa, 0.0)]                      # RK4 path of (x, int tr J)
for _ in range(N):
    zs.append(rk4_step(aug, zs[-1], 1.0 / N))
zT, tr_path = zs[-1], [trJ(z[:2]) for z in zs]
D = np.zeros((2, 2))                           # D Phi_1 by central differences
for j in range(2):
    e = np.zeros(2); e[j] = 1e-5
    D[:, j] = (solve(rk4_step, field, xa + e, 1.0, N)
               - solve(rk4_step, field, xa - e, 1.0, N)) / 2e-5
logdet = np.log(abs(np.linalg.det(D)))
print(f'tr J along the path: from {min(tr_path):+.3f} to {max(tr_path):+.3f}')
print(f'trace integral {zT[2]:+.6f}  log|det D Phi| {logdet:+.6f}  '
      f'gap {abs(zT[2] - logdet):.1e}')
tr J along the path: from +0.889 to +1.013
trace integral +0.970187  log|det D Phi| +0.970187  gap 8.3e-11

The trace does move: the first line gives the interval that it covers along the path. How wide the interval is depends on the draw of the weights. A tenth or more is typical, and in some draws the interval contains zero, so that the flow expands area on one stretch of the path and compresses it on another. Yet the integral and the log-determinant agree to eight digits or better, the accuracy of the solver and of the finite differences. Nothing in the proposition used linearity.

26.3.3.4 The Hutchinson Trace Estimator#

The formula for tr⁡J\operatorname{tr}\mathbf J above used the structure of a one-layer field. For a general network the trace needs the dd diagonal entries of J\mathbf J, which cost dd reverse-mode passes, one per coordinate. The trace has already replaced an O(d3)O(d^3) determinant by dd passes. A random projection replaces the dd passes by one, and returns an unbiased but noisy estimate (Hutchinson, 1989).

Proposition (Hutchinson estimator). For any matrix M∈Rd×d\mathbf M\in\mathbb{R}^{d\times d} and any random vector ϵ∈Rd\boldsymbol\epsilon\in\mathbb{R}^d with E[ϵϵ⊤]=I\mathbb{E}[\boldsymbol\epsilon\boldsymbol\epsilon^\top]=\mathbf{I}, such as a standard Gaussian or a Rademacher vector with independent entries ±1\pm1 of equal probability,

tr⁡(M)=E ⁣[ϵ⊤Mϵ].(26.3.11)\operatorname{tr}(\mathbf M) = \mathbb{E}\!\left[\boldsymbol{\epsilon}^\top \mathbf M \boldsymbol{\epsilon}\right]. \tag{26.3.11}

Proof. E[ϵ⊤Mϵ]=E[tr⁡(Mϵϵ⊤)]=tr⁡(M E[ϵϵ⊤])=tr⁡(M)\mathbb{E}[\boldsymbol\epsilon^\top \mathbf M\boldsymbol\epsilon] =\mathbb{E}[\operatorname{tr}(\mathbf M\boldsymbol\epsilon\boldsymbol\epsilon^\top)] =\operatorname{tr}(\mathbf M\,\mathbb{E}[\boldsymbol\epsilon\boldsymbol\epsilon^\top]) =\operatorname{tr}(\mathbf M), by the cyclic property of the trace and its linearity, which lets it commute with the expectation. ■\blacksquare

The estimator touches J\mathbf J only through ϵ⊤J\boldsymbol\epsilon^\top \mathbf J, one vector--Jacobian product, which is one reverse-mode pass through f\mathbf{f} with ϵ\boldsymbol\epsilon as the seed; no Jacobian is formed. For the one-hidden-layer field the product is explicit,

ϵ⊤J=((ϵ⊤W2)⊙s) W1,\boldsymbol\epsilon^\top \mathbf J=\big((\boldsymbol\epsilon^\top \mathbf W_2)\odot\mathbf{s}\big)\,\mathbf W_1,

and it costs about as much as evaluating f\mathbf{f}. A CNF evaluates one such product with every evaluation of the field, so the likelihood costs one additional backward pass per field evaluation. This is the method that Grathwohl et al. (2019) named FFJORD.

The proposition says that the average over probes converges to the trace. It does not say how fast, and for a single probe that is the whole question. With S=(J+J⊤)/2\mathbf S=(\mathbf J+\mathbf J^\top)/2, one Rademacher probe has variance 2∑i≠jSij22\sum_{i\ne j}S_{ij}^2 and one Gaussian probe 2∑i,jSij22\sum_{i,j}S_{ij}^2, the same sum with the diagonal included (Exercise 5). The trace sees only the diagonal of J\mathbf J, and the noise of a Rademacher probe only what lies off it.

Let us try the estimator on a field in d=50d=50 whose trace we can predict: a random one-hidden-layer part with 6464 tanh units and a pull toward the origin, f(x)=W2tanh⁡(W1x+b1)−x\mathbf{f}(\mathbf{x})=\mathbf W_2\tanh(\mathbf W_1\mathbf{x}+\mathbf{b}_1)-\mathbf{x}. Its Jacobian is W2 diag(s) W1−I\mathbf W_2\,\mathrm{diag}(\mathbf{s})\,\mathbf W_1-\mathbf{I}, so the pull contributes −50-50 to the trace and the random part a number of order one. The pull also adds −ϵ⊤ϵ-\boldsymbol\epsilon^\top\boldsymbol\epsilon to every estimate. For a Rademacher probe this is −50-50 exactly, and all the noise comes from the random part. For a Gaussian probe ϵ⊤ϵ\boldsymbol\epsilon^\top\boldsymbol\epsilon is itself random, and the two variance formulas say what that costs. They differ by the diagonal term 2∑iSii22\sum_iS_{ii}^2, and here every Sii=JiiS_{ii}=J_{ii} is close to −1-1, so the variance of a Gaussian probe should exceed that of a Rademacher probe by about 2⋅50=1002\cdot50=100. The cell draws m=1000m=1000 probes of each kind and computes each ϵ⊤J\boldsymbol\epsilon^\top\mathbf J by reverse mode.

d, n_hidden, m = 50, 64, 1000
W1 = rng.standard_normal((n_hidden, d)) / np.sqrt(d)
b1 = 0.1 * rng.standard_normal(n_hidden)
W2 = rng.standard_normal((d, n_hidden)) / np.sqrt(n_hidden)
x = rng.standard_normal(d)
s = 1 - np.tanh(W1 @ x + b1) ** 2
tr_tanh = np.sum(s * np.einsum('ij,ji->i', W1, W2))  # trace of W2 diag(s) W1
E = rng.choice([-1.0, 1.0], size=(m, d))         # Rademacher probes, one per row
E_gauss = rng.standard_normal((m, d))            # Gaussian probes, one per row

We now evaluate the reverse-mode vector–Jacobian product ϵk⊤J\boldsymbol\epsilon_k^\top \mathbf{J} at x for all m=1000m = 1000 Rademacher (E) and Gaussian (E_gauss) probes and compare the resulting trace estimates ϵk⊤Jϵk\boldsymbol\epsilon_k^\top \mathbf{J}\boldsymbol\epsilon_k and their single-probe standard deviations against the exact trace tr_tanh - d:

W1t, b1t, W2t = (torch.tensor(w) for w in (W1, b1, W2))
field = lambda x: W2t @ torch.tanh(W1t @ x + b1t) - x
_, vjp = torch.func.vjp(field, torch.tensor(x))      # reverse mode at x
for name, P in (('Rademacher', E), ('Gaussian', E_gauss)):
    P = torch.tensor(P)
    rows = torch.func.vmap(vjp)(P)[0]                # row k: eps_k^T J
    est = (rows * P).sum(dim=1)                      # eps_k^T J eps_k
    sd = est.std(correction=0)
    print(f'{name:10s}: exact {tr_tanh - d:+6.2f}, mean of {m} probes '
          f'{est.mean():+6.2f} +- {sd / m ** 0.5:.2f}, one probe sd {sd:.2f}')
Rademacher: exact -51.30, mean of 1000 probes -51.23 +- 0.16, one probe sd 4.99
Gaussian  : exact -51.30, mean of 1000 probes -51.16 +- 0.37, one probe sd 11.62

Both averages lie within a few of their standard errors of the exact trace, as unbiased estimates should. One Rademacher probe has a standard deviation of about 55, a tenth of the trace: a single backward pass locates the trace to ten percent, where the exact value takes 5050 passes. One Gaussian probe has a standard deviation of about 1111, and 112−52=9611^2-5^2=96, close to the predicted 100100. Rademacher probes are never the noisier kind, and here they are much the quieter.

The ten percent belongs to this field, not to the estimator. Without the pull every Rademacher estimate would shift by exactly +50+50: the standard deviation would still be 55, the trace would be of order one, and a single probe would say next to nothing about it. Which of the two cases a model in high dimension resembles is the subject of Exercise 5.

A likelihood needs more than one trace. It needs the integral ∫0Ttr⁡J dt\int_0^T\operatorname{tr}\mathbf J\,dt along a trajectory, one estimate per solver step, and the probes can be supplied in two ways: one probe held for the whole solve, or a fresh one at every step. What should we expect? A held probe sees the sum ∑nh J(xn)\sum_nh\,\mathbf J(\mathbf x_n) as one matrix and estimates its trace once, so its noise is that of a single estimate whatever NN is. Fresh probes make independent errors, each weighted by h=1/Nh=1/N, so the noise of their sum falls like 1/N1/\sqrt N. The next cell follows one Euler trajectory of the same field to T=1T=1 with N=10N=10, 100100 and 10001000 steps and repeats each policy 200200 times with Rademacher probes, taking ϵ⊤J\boldsymbol\epsilon^\top\mathbf J from the explicit product above.

field = lambda x: W2 @ np.tanh(W1 @ x + b1) - x
diag_W1W2 = np.einsum('ij,ji->i', W1, W2)
for N in (10, 100, 1000):
    h, xs = 1 / N, [x]
    for _ in range(N - 1):                     # Euler trajectory x_0, ..., x_{N-1}
        xs.append(xs[-1] + h * field(xs[-1]))
    S = 1 - np.tanh(np.array(xs) @ W1.T + b1) ** 2  # s at every step, (N, n_hidden)
    exact = h * (S @ diag_W1W2).sum() - d      # h * sum_n tr J(x_n)
    held = np.broadcast_to(rng.choice([-1.0, 1.0], (200, 1, d)), (200, N, d))
    fresh = rng.choice([-1.0, 1.0], (200, N, d))
    row = f'N = {N:4d}: exact {exact:+.2f}'
    for name, P in (('held probe', held), ('fresh probes', fresh)):
        est = h * np.einsum('rnh,nh,rnh->r', P @ W2, S, P @ W1.T) - d  # eps^T eps = d
        row += f' | {name} {est.mean():+.2f}, sd {est.std():.2f}'
    print(row)
N =   10: exact -51.90 | held probe -52.11, sd 5.69 | fresh probes -51.73, sd 1.71
N =  100: exact -51.93 | held probe -51.35, sd 5.98 | fresh probes -51.94, sd 0.63
N = 1000: exact -51.93 | held probe -51.28, sd 5.88 | fresh probes -51.92, sd 0.19

The exact integral is again close to −50-50, and the means of both policies agree with it to within sampling error: the estimate is unbiased either way. The spreads are as predicted. A held probe has a standard deviation of about 55 to 66 at every NN. Fresh probes come to between 1.51.5 and 1.81.8 at N=10N=10, about 0.50.5 to 0.60.6 at N=100N=100 and just under 0.20.2 at N=1000N=1000: in each row, the held value divided by N\sqrt N.

Fresh probes are about thirty times quieter at N=1000N=1000 and cost the same. Why would anyone hold the probe? Because a held probe leaves the solver an ordinary differential equation. With ϵ\boldsymbol\epsilon fixed, the estimate ϵ⊤J(x)ϵ\boldsymbol\epsilon^\top\mathbf J(\mathbf{x})\boldsymbol\epsilon is a deterministic function of the state, so any solver applies, an adaptive one can control its error, and the adjoint equations give the gradient. With a fresh probe at every evaluation the right-hand side is noise, and a solver that compares two evaluations to judge its step would be comparing two random draws. Our cell could use fresh probes because its Euler steps were fixed in advance. FFJORD holds the probe, and keeps the noise.

Training can live with that noise, because training never needs an accurate likelihood, only an unbiased one. The estimate enters the log-likelihood linearly, so the estimated log-likelihood and its gradient are unbiased too, and a stochastic gradient asks for nothing more (Section 23.4). The noise of the probes is averaged over the minibatch and over iterations, as the noise of the minibatch itself is. What one held probe cannot give is the likelihood of a single point. An error of 55 in a log-likelihood is a factor of e5≈150e^5\approx150 in the density, so for that one averages many probes, draws fresh ones along a fixed grid of steps, or computes the exact trace.

The only noise in this section sat in our probes. The trajectories themselves were deterministic. A diffusion model adds fresh noise to the state at every step, and increments that scale like h\sqrt{h} break the Taylor expansions this section relied on. Integrating such an equation takes a calculus of its own (Section 26.4).

26.3.4 Summary#

A residual block is an Euler step, and one field with shrinking steps gives a Neural ODE, whose exact flow is invertible and whose step count is left to a solver. Both gains have limits: on R\mathbb{R} a flow preserves order, so x↦−xx\mapsto-x needs a second dimension, and a field trained through ten Euler steps fits the ten-step program, where one trained through RK4 fits the flow at four times the field evaluations. The gradient of a loss on x(T)\mathbf{x}(T) is the integral of (∂f/∂θ)⊤a(\partial\mathbf{f}/\partial\boldsymbol\theta)^\top\mathbf{a} along the trajectory, where the adjoint a\mathbf{a} solves a linear ODE backward from ∇ℓ(x(T))\nabla\ell(\mathbf{x}(T)); backpropagation through Euler is exact for the program and within O(h)O(h) of this gradient. Re-integrating the state backward saves memory but amplifies a stored error by eλTe^{\lambda T} for a mode that decays at rate λ\lambda. Along a trajectory ddtlog⁡pt=−tr⁡J\tfrac{d}{dt}\log p_t=-\operatorname{tr}\mathbf J, a trace where a discrete flow needs a determinant. Hutchinson's estimator obtains the trace from one vector--Jacobian product per probe, without bias but with noise that training averages out and a single likelihood does not.

26.3.5 Exercises#

  1. [code] What a flow cannot represent. ● Two trajectories of a field with Lipschitz constant LL satisfy e−Lt∥x−y∥≤∥Φt(x)−Φt(y)∥≤eLt∥x−y∥e^{-Lt}\|\mathbf{x}-\mathbf{y}\|\le\|\Phi_t(\mathbf{x})-\Phi_t(\mathbf{y})\|\le e^{Lt}\|\mathbf{x}-\mathbf{y}\| (Exercise 2 of Section 26.1), and Section 26.3.1.2 showed that no flow on R\mathbb{R} reverses order (Dupont et al., 2019).

    1. Let d=1d=1. Use the lower bound to give a second proof that ΦT\Phi_T is strictly increasing, and show that ΦT(1)−ΦT(−1)≥2e−LT\Phi_T(1)-\Phi_T(-1)\ge2e^{-LT}. Which of the two statements, order or distance, does the proposition of the text give, and which needs the bound?
    2. The training example carries the circle points (0,±1)(0,\pm1), which are 22 apart, to (1.5,±0.4)(1.5,\pm0.4), which are 0.80.8 apart. Show that the exact time-TT flow of a field with Lipschitz constant LL can do this only if LT≥ln⁡2.5≈0.92LT\ge\ln2.5\approx0.92, whereas the long axis, stretched from 22 to 2.42.4, gives only LT≥ln⁡1.2LT\ge\ln1.2. A one-hidden-layer tanh field has L≤∥W2∥2∥W1∥2L\le\|\mathbf W_2\|_2\|\mathbf W_1\|_2 because tanh⁡\tanh is 11-Lipschitz. Compute this bound for the RK4-trained field and check the inequality.
    3. Embed R\mathbb{R} in R2\mathbb{R}^2 as x↦(x,0)x\mapsto(x,0). Show that every linear field x˙=Cx\dot{\mathbf{x}}=\mathbf C\mathbf{x} whose time-one map sends (x,0)(x,0) to (−x,0)(-x,0) for every xx has eC=−Ie^{\mathbf C}=-\mathbf{I}. Hint: an eigenvalue −1-1 of eCe^{\mathbf C} comes from an eigenvalue μ\mu of C\mathbf C with eμ=−1e^{\mu}=-1, which is not real. Find such a field whose trajectories are ellipses rather than circles.
    4. Change the training cell to fit the map x↦−xx\mapsto-x on 6464 evenly spaced points of [−1,1][-1,1] with a field of input and output dimension 11 and N=10N=10 Euler steps. What does the trained model output, and why does the loss settle at a value you can predict before training? Repeat with a field of dimension 22, inputs (x,0)(x,0), and the loss on the first coordinate.
    5. Train the one-dimensional model once more with N=1N=1 and h=1h=1, and evaluate it with N=1N=1 and with N=100N=100 steps of size h=0.01h=0.01. Relate the two results to the proposition and to the condition hL<1hL\lt 1.
  2. Adjoint with a running loss. ● The adjoint equations (26.3.4) and (26.3.5) treat a loss on the endpoint. Regularizers such as the kinetic energy ∫0T∥f(x(t),θ,t)∥2 dt\int_0^T\|\mathbf{f}(\mathbf{x}(t),\boldsymbol\theta,t)\|^2\,dt of Finlay et al. (2020) accumulate a cost along the trajectory. Let

L=ℓT(x(T))+∫0Tℓ(x(t),θ,t) dt.\mathcal{L} = \ell_T(\mathbf{x}(T)) + \int_0^T \ell(\mathbf{x}(t), \boldsymbol\theta, t)\,dt .
  1. Extend the variational proof of (26.3.4) to show that the adjoint acquires a source term, a˙=−(∂f/∂x)⊤a−∇xℓ\dot{\mathbf{a}} = -(\partial\mathbf{f}/\partial\mathbf{x})^\top\mathbf{a} - \nabla_{\mathbf{x}}\ell with a(T)=∇ℓT(x(T))\mathbf{a}(T) = \nabla\ell_T(\mathbf{x}(T)), and that ∂L/∂θ=∫0T((∂f/∂θ)⊤a+∇θℓ) dt\partial\mathcal{L}/\partial\boldsymbol\theta = \int_0^T \big((\partial\mathbf{f}/\partial\boldsymbol\theta)^\top\mathbf{a} + \nabla_{\boldsymbol\theta}\ell\big)\,dt.
  2. Finlay et al. (2020) instead append a coordinate EE with E˙=ℓ\dot{E} = \ell and E(0)=0E(0) = 0 to the state, and add E(T)E(T) to the endpoint loss. Apply (26.3.4) to the extended state (x,E)(\mathbf{x},E) and show that it reproduces (a).
  3. For the kinetic energy, ℓ=∥f∥2\ell = \|\mathbf{f}\|^2. Write ∇xℓ\nabla_{\mathbf{x}}\ell as a vector--Jacobian product. How many reverse-mode passes through f\mathbf{f} does one step of the adjoint ODE then require?
  1. [code] Reconstructing the trajectory backward. ● The continuous adjoint can avoid storing the forward states by integrating x(t)\mathbf{x}(t) backward from x(T)\mathbf{x}(T) alongside a(t)\mathbf{a}(t). Section 26.3.2 found that a mode which decays at the rate λ\lambda then amplifies an error δ\delta in the stored x(T)\mathbf{x}(T) to eλTδe^{\lambda T}\delta.

    1. Let R\mathbf R be the rotation by 0.60.6 radians and C=R diag(−50,−1) R⊤\mathbf C=\mathbf R\,\mathrm{diag}(-50,-1)\,\mathbf R^\top. Integrate x˙=Cx\dot{\mathbf{x}}=\mathbf C\mathbf{x} from (1,1)(1,1) to time TT with 20002000 RK4 steps (solve with rk4_step), then integrate backward from the result for the same time, with a negative horizon. Report the reconstruction error for T=0.25T=0.25, 0.50.5, 11 and 22, and compare its growth with e50Tδe^{50T}\delta. Which δ\delta fits? Why is it nearer 10−1710^{-17} than the 10−1610^{-16} of the text? Hint: how large are the coordinates of x(T)\mathbf{x}(T)?
    2. Repeat with diag(−50,−1)\mathrm{diag}(-50,-1) itself. From T=0.5T=0.5 on it reconstructs the start far more accurately than C\mathbf C does. Why?
    3. Activation checkpointing (Section 5.7.3.3) stores the state at the start of each segment of the trajectory. A hybrid scheme reconstructs the states within a segment by integrating backward from the checkpoint at its end. For the matrix C\mathbf C of (a), what is the longest segment duration for which the drift e50Tδe^{50T}\delta with δ=10−16\delta=10^{-16} stays below 10−810^{-8}?
  2. Log-determinant of a residual step. ●● The instantaneous change of variables (26.3.8) is a limit of infinitesimal steps. A finite residual step F(x)=x+g(x)F(\mathbf{x})=\mathbf{x}+\mathbf{g}(\mathbf{x}) needs its exact log-determinant, as in the invertible residual networks of Behrmann et al. (2019).

    1. Let g\mathbf{g} be Lipschitz with constant c<1c\lt 1. For d=1d=1 the one-line argument of Section 26.3.1.2 (an Euler step is increasing when hL<1hL\lt 1) shows that FF is strictly increasing, hence injective. For general dd, write F(x)=yF(\mathbf{x})=\mathbf{y} as a fixed-point equation for x\mathbf{x} and use the Banach fixed-point theorem, as in the proof of Picard--Lindelöf, to show that FF is a bijection of Rd\mathbb{R}^d. How fast does the fixed-point iteration converge?
    2. Show that ∥Jg∥≤c\|\mathbf J_{\mathbf{g}}\|\le c, where Jg\mathbf J_{\mathbf{g}} is the Jacobian of g\mathbf{g}, and use the eigenvalues of Jg\mathbf J_{\mathbf{g}} to show that
log⁡det⁡(I+Jg)=∑k=1∞(−1)k+1ktr⁡(Jgk).\log\det(\mathbf{I} + \mathbf J_{\mathbf{g}}) = \sum_{k=1}^\infty \frac{(-1)^{k+1}}{k}\operatorname{tr}\big(\mathbf J_{\mathbf{g}}^k\big).
  1. An Euler step has g=hf\mathbf{g}=h\mathbf{f} and Jg=hJ\mathbf J_{\mathbf{g}}=h\mathbf J. Compare log⁡det⁡(I+hJ)\log\det(\mathbf{I}+h\mathbf J) with the term htr⁡Jh\operatorname{tr}\mathbf J that (26.3.9) accumulates per step. How large is the difference per step, and how large is it in total over T/hT/h steps?
  2. The Hutchinson estimator (26.3.11) estimates tr⁡(Jgk)\operatorname{tr}(\mathbf J_{\mathbf{g}}^k) by ϵ⊤Jgkϵ\boldsymbol{\epsilon}^\top \mathbf J_{\mathbf{g}}^k\boldsymbol{\epsilon}. How many vector--Jacobian products per probe does the series truncated after KK terms cost?
  1. [code] Variance of the Hutchinson estimator. ● The estimator (26.3.11) estimates tr⁡M\operatorname{tr}\mathbf M by ϵ⊤Mϵ\boldsymbol{\epsilon}^\top \mathbf M\boldsymbol{\epsilon} for a single probe ϵ\boldsymbol{\epsilon}. Let S=(M+M⊤)/2\mathbf S=(\mathbf M+\mathbf M^\top)/2, so that ϵ⊤Mϵ=ϵ⊤Sϵ\boldsymbol{\epsilon}^\top \mathbf M\boldsymbol{\epsilon}=\boldsymbol{\epsilon}^\top \mathbf S\boldsymbol{\epsilon}.

    1. Show that the variance of ϵ⊤Mϵ\boldsymbol{\epsilon}^\top \mathbf M\boldsymbol{\epsilon} is 2∥S∥F22\|\mathbf S\|_F^2 for Gaussian probes and 2∑i≠jSij22\sum_{i\neq j}S_{ij}^2 for Rademacher probes. For which matrices is a single Rademacher probe exact?
    2. Form the Jacobian J=W2 diag(s) W1−I\mathbf J=\mathbf W_2\,\mathrm{diag}(\mathbf{s})\,\mathbf W_1-\mathbf{I} of the field with the pull explicitly, from the weights and the point of the Hutchinson experiment (it is 50×5050\times50). Evaluate both variances and compare their square roots with the two one-probe standard deviations that the experiment printed. How many probes does each distribution need for a standard error of 0.010.01?
    3. In a CNF, M\mathbf M is the Jacobian ∂f/∂x\partial\mathbf{f}/\partial\mathbf{x} in dimension dd. Suppose that all entries have comparable magnitude. How does the relative standard error Var/∣tr⁡M∣\sqrt{\textrm{Var}}/|\operatorname{tr}\mathbf M| of one probe scale with dd when the diagonal entries share one sign, and when their signs are random?
    4. In training, each of the BB points of a minibatch has its own trajectory and its own held probe. How does the noise of the average log-likelihood depend on BB? For which BB does it match the noise that one point has with fresh probes at N=100N=100 steps?
  2. [code] Discrete and continuous adjoints. ●● Backpropagation through a solver differentiates the executed program, whereas a solver applied to the adjoint ODE (26.3.4) approximates the gradient of the exact flow (Kidger, 2022). Compare the two recursions step by step for an autonomous field with Jacobian J(x)=∂f/∂x\mathbf J(\mathbf{x})=\partial\mathbf{f}/\partial\mathbf{x} and forward states xn\mathbf{x}_n.

    1. For forward Euler, the discrete adjoint (26.3.6) computes an=(I+hJ(xn))⊤an+1\mathbf{a}_n=(\mathbf{I}+h\mathbf J(\mathbf{x}_n))^\top\mathbf{a}_{n+1}, whereas an explicit Euler step of the adjoint ODE from tn+1t_{n+1} back to tnt_n computes an=an+1+hJ(xn+1)⊤an+1\mathbf{a}_n=\mathbf{a}_{n+1}+h\mathbf J(\mathbf{x}_{n+1})^\top\mathbf{a}_{n+1}. Bound the difference of the two updates for a smooth f\mathbf{f}. For a linear field the two coincide, and the text said that the gap to the gradient of the flow is then Euler's own error. Make this precise for the scalar program xN=(1+hθ)Nx0x_N=(1+h\theta)^Nx_0: show that the recursion computes the gradient T xN2/(1+hθ)T\,x_N^2/(1+h\theta) that the text found, and that this equals T x(T)2(1−hθ(1+θT))+O(h2)T\,x(T)^2\big(1-h\theta(1+\theta T)\big)+O(h^2).
    2. Differentiate one Heun step xn+1=xn+h2[f(xn)+f(un)]\mathbf{x}_{n+1}=\mathbf{x}_n+\tfrac{h}{2}\big[\mathbf{f}(\mathbf{x}_n)+\mathbf{f}(\mathbf{u}_n)\big] with un=xn+hf(xn)\mathbf{u}_n=\mathbf{x}_n+h\mathbf{f}(\mathbf{x}_n) to obtain its discrete adjoint recursion. Show that this recursion is a Heun step of the adjoint ODE from tn+1t_{n+1} to tnt_n in which J(xn+1)\mathbf J(\mathbf{x}_{n+1}) is replaced by J(un)\mathbf J(\mathbf{u}_n). At which order in hh do the two updates differ?
    3. For a linear field f(x)=Ax\mathbf{f}(\mathbf{x})=\mathbf A\mathbf{x}, one RK4 step multiplies the state by R(hA)R(h\mathbf A), where R(z)=1+z+z2/2+z3/6+z4/24R(z)=1+z+z^2/2+z^3/6+z^4/24 is the stability function of RK4 (Section 26.2; Exercise 2 there studies it on the imaginary axis). Show that the discrete adjoint of RK4 is an RK4 step of the adjoint ODE.
    4. Replace the Euler step of loss_and_grad_unrolled by an RK4 step, and compute the gradient of the unrolled loss by central finite differences instead of a hand-written backward sweep. Measure its gap to the continuous-adjoint gradient g_cont for N=5N=5, 1010, 2020, 4040 and 8080 steps. The trapezoid rule that computes g_cont uses n_quad = 2000 intervals and is accurate only to about 10−710^{-7}, so refine it first. Which slope do you measure? Which order does the gradient computed through a solver of order pp inherit?
  3. [code] Liouville's formula. ●● The instantaneous change of variables followed a density along a trajectory. This exercise proves it a second way, through the Jacobian M(t)=DΦt(x0)\mathbf M(t)=D\Phi_t(\mathbf{x}_0) of the flow map itself.

    1. Differentiate ddtΦt(x0)=f(Φt(x0),t)\tfrac{d}{dt}\Phi_t(\mathbf{x}_0)=\mathbf{f}(\Phi_t(\mathbf{x}_0),t) with respect to x0\mathbf{x}_0 to obtain the variational equation M˙=J(x(t),t) M\dot{\mathbf M}=\mathbf J(\mathbf{x}(t),t)\,\mathbf M with M(0)=I\mathbf M(0)=\mathbf{I}.
    2. Prove Jacobi's formula ddtdet⁡M=tr⁡(M−1M˙)det⁡M\tfrac{d}{dt}\det \mathbf M=\operatorname{tr}(\mathbf M^{-1}\dot{\mathbf M})\det \mathbf M for invertible M(t)\mathbf M(t). Hint: write det⁡M(t+h)=det⁡M(t) det⁡(I+hM−1M˙+O(h2))\det \mathbf M(t+h)=\det \mathbf M(t)\,\det\big(\mathbf{I}+h\mathbf M^{-1}\dot{\mathbf M}+O(h^2)\big) and use the Lemma.
    3. Conclude that log⁡∣det⁡DΦT(x0)∣=∫0Ttr⁡J(x(t),t) dt\log|\det D\Phi_T(\mathbf{x}_0)|=\int_0^T\operatorname{tr}\mathbf J(\mathbf{x}(t),t)\,dt, and derive (26.3.9) from the discrete change of variables (26.3.7) applied to the bijection ΦT\Phi_T. For a linear field the result is the formula (26.3.10).
    4. Integrate M˙=JM\dot{\mathbf M}=\mathbf J\mathbf M with RK4 alongside the 88-unit tanh field of Section 26.3.3, in the cell that checks the trace integral (before the Hutchinson experiment reuses the names of its weights), and compare log⁡∣det⁡M(1)∣\log|\det \mathbf M(1)| with the trace integral and the log-determinant that cell prints.

Discussions