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 rows for a colour image of 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 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 of them, of
size , and a negative runs the field backward. The check of the
adjoint, further down, uses the spiral , its start
and the matrix exponential
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 :
With and 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 .
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 , beside the exact flow of the same field, from which they drift.
To take the limit, fix the horizon , keep one parameter vector 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 : the network takes as an input, and that is how one parameter vector serves blocks that differ.) With steps of size at the times ,
The convergence is Euler's error bound from Section 26.2: for a smooth field that is Lipschitz in , the Euler iterate after steps is within of the exact solution. The Neural ODE is the limit object: the model whose output is the solution of with . 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 has the exact flow , a bijection of for every . One Euler step with computes and maps every input to zero. The exact map, by contrast, is a bijection whenever the field is continuous in and globally Lipschitz in : running the field backward from 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 plane, trajectories of a Lipschitz field never cross. Two trajectories that swapped and would have to meet on the way (panel (a) of Figure 26.3.2).
(a) On the line, trajectories of a Lipschitz field never cross (here ), so the time- map preserves order; the dashed pair that swaps and would need two solutions through one point. (b) The residual step with swaps the points in one step: it is an Euler step with , not a flow. (c) One extra dimension removes the obstruction: the rotation by carries to along half circles that pass without meeting (colours as in (b)).
Proposition (flows on preserve order). Let be continuous in and globally Lipschitz in , and write for the solution at time started from at time . Then for every the map is strictly increasing.
Proof. Let and suppose . The function is continuous with and , so by the intermediate value theorem for some : the two trajectories meet at time at a point . Now run time backward from . Both reversed trajectories and solve the same initial-value problem , , whose field is again Lipschitz. By Picard--Lindelöf that problem has only one solution, so the two reversed trajectories coincide, and at this says , a contradiction.
The proof has one idea, to apply uniqueness backward from the meeting time. As a consequence, no Neural ODE on realizes : that map sends to and to , which reverses their order.
The residual block with does realize it, in one step (panel (b) of Figure 26.3.2). That block is the Euler step with of , whose exact flow never reverses order. The two statements agree because one Euler step of a field with Lipschitz constant is guaranteed to be increasing when : for ,
which is positive when . Here , 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 of Section 26.1, with , has the flow , which turns the plane by the angle . Run times as fast, as , it has the time-one map
It carries to 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 is embedded as , 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 solver steps. The direct way to train it is to discretize, then differentiate: write the solver into the computation graph, compute the loss on , and backpropagate through the unrolled steps. With Euler as the solver the program is a ResNet of 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 points of the unit circle to the matching points of the ellipse centred at with semi-axes and , a stretch and a shift. The exact flow of the affine field does this without error for a suitable , 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 tanh units, the loss is the mean squared error at the endpoints, and Adam (Section 23.5) runs full-batch iterations to at learning rate , lowered to for the last hundred. We train twice from the same initial weights: once through Euler steps of size , 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 . 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 and steps ( throughout). The larger , 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 steps and then backward 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 at , at and at , tenfold less per tenfold more steps. Each pair of a forward and a backward Euler step leaves a residual of order , and of them add up to , Euler's order. Running the field backward undoes the exact flow. It undoes the Euler program only in the limit . An Euler program with 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 .
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 and then stops changing. Training fitted the ten-step program. The exact time-one flow of that field, which approximates, lands from the targets, under 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 for every instant. Its central object is the adjoint state , the gradient of the loss with respect to the state at time , 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 with and the loss on the endpoint. Directly, , so and
With this is .
The adjoint reaches the same number by another route. A nudge to the state at time grows to by time and changes the loss by , so . This adjoint solves the ODE backward from the final value , which is the derivative of the loss at . A change of the parameter alters the velocity by at every instant, since , and the adjoint converts each of these nudges into a change of the loss. Summing over time,
The integrand is constant: grows forward, shrinks by the same factor when read forward, and their product stays at (Figure 26.3.3). The gradient is the area under it.
The scalar adjoint for at , , : the state grows forward, the adjoint is integrated backward from the loss gradient , and their product is constant; the parameter gradient is the shaded area, .
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 .
Proposition (the adjoint equations). Let be continuously differentiable in and , let solve (the field , with its parameters written as an argument) on from a fixed , and let for a differentiable . Then the adjoint state satisfies the linear ODE
integrated backward from , and the parameter gradient is the integral
with both partial derivatives evaluated along the trajectory (Chen et al., 2018).
Proof (variational). Perturb the parameters by an infinitesimal . Because is , the solution is differentiable in , and the first-order perturbation of the trajectory obeys the linearization of the dynamics (differentiate the ODE in and use the chain rule):
Define by the backward ODE (26.3.4) and differentiate the pairing :
The state-coupling terms cancel, and the adjoint ODE was defined so that they would. Integrate from to , using at the left endpoint:
The left side is , the first-order change of the loss; the right side is linear in with coefficient (26.3.5). It remains to identify with the adjoint state. Run the same argument with and a nudge injected at time : the pairing is then constant on , so , and the solution of (26.3.4) is .
The backward ODE is linear in , with the transposed Jacobian as its matrix. Each of its steps computes , one vector--Jacobian product, which costs one reverse-mode pass through (Section 22.5). The same pass returns , the integrand of the parameter gradient, however many parameters there are. (A ReLU field is only piecewise , 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 for its Jacobian. Differentiate the program by the chain rule, with . The Jacobian of one step is , so
Compare this with one explicit Euler step of the adjoint ODE (26.3.4) from back to :
The two updates differ only in where the Jacobian is evaluated: at the start of the forward step or at its end . 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 . Of everything in this subsection, this is the statement to keep.
The scalar example shows both gradients at once. For the Euler program is , so and the discrete adjoint gives . With this is at , at and at , against the exact . The gaps , and shrink tenfold per tenfold .
The spiral field of Section 26.1, with , gives the same check in two dimensions with every ingredient in closed form. For a linear field the Jacobian is 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 to be the entries of and . The trajectory is , the adjoint is (the solution of ), and since , the gradient (26.3.5) becomes .
The cell writes the backward sweep (26.3.6) by hand, for . Its first line of output tests the sweep against central finite differences of the same program at 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 intervals, with and 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 , the accuracy of the differences themselves. Its gap to the gradient of the flow falls from to to , tenfold per tenfold , as in the scalar case.
26.3.2.4 Memory and Drift#
The adjoint ODE needs 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 . Or re-integrate backward from alongside , which keeps the memory constant in 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 with , the backward integration solves . An absolute error in the stored therefore becomes by the time it reaches .
How large is ? Picture a state with two modes. One decays at the rate , 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 the fast mode has died out, the coordinates that are stored are of size one, and double precision rounds each of them at about . Rounding knows nothing of modes: part of the error lies along the fast direction, so . The reconstructed start is then off by at , by at and by at , larger than the state itself. A double carries about sixteen digits, and a factor of is five digits more than it has. Exercise 3 measures this growth.
For the spiral, whose eigenvalues have real part , the factor over is only . 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 steps the backward sweep holds about states, instead of for , 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 from a simple density 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 with Jacobian ,
The log-density drops by the logarithm of the factor by which stretches volume near . A normalizing flow built from many layers needs one log-determinant per layer and sample. A general determinant costs operations, about for the of a 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 . Both determinants cost .
In continuous time the formula simplifies. Start with one dimension. The field on has the flow , which stretches every interval by . A density carried along is divided by the stretch, so and . The number is the Jacobian of the field, and therefore also its trace.
The spiral is the running example in two dimensions. Its flow is a rotation followed by a shrink by (Section 26.1). A disc is carried to a disc of times its radius, so its area is multiplied by , and the density along each trajectory rises by . Here , 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 , has of the area of the lightest.
A disc of samples carried by the exact flows of three linear fields, shown at , and (darker is later); the dotted line is the path of the centre. The density along a trajectory changes by the factor : 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 , .
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 , so it contributes . The identity permutation contributes .
Proposition (instantaneous change of variables). Let with continuously differentiable in and globally Lipschitz in , so that each flow map is a bijection with a inverse (the solution of a field is in its initial value (Hairer et al., 1993), and the inverse runs the field backward). Let for a positive differentiable density . Then the density of exists and is positive, and along each trajectory (Chen et al., 2018)
Proof. The density exists by (26.3.7) applied to the bijection , and it is positive because is and the Jacobian of a map with a differentiable inverse is nonsingular. Over a short interval the flow advances by the map . Differentiating in and using the continuity of , its Jacobian is , where is evaluated at and stands for terms that vanish faster than . Apply (26.3.7) to this one map and expand with the Lemma, which tolerates the perturbation: replacing by changes the determinant only by . For small the determinant is close to , hence positive, so the absolute value can be dropped:
using . Subtract , divide by , and let .
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 of the field, the local rate at which the flow expands volume. Where the field spreads samples apart () the log-density along each trajectory falls, and where it compresses them, it rises. Integrating (26.3.8) along a trajectory gives
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 with any ODE solver, is a continuous normalizing flow (CNF) (Chen et al., 2018). It needs no restriction on the architecture of . To evaluate the density of a given point , integrate the field backward from it to , accumulate the trace on the way, and read off 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 , and the same formula serves them.
For a linear field the trace integral is , and (26.3.9) compared with (26.3.7) for the map says . For a diagonalizable the identity also follows in one line from the eigenvalues,
and the comparison of the two formulas gives it for every .
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 . A nonlinear field is a real one, because its trace changes along the path. Take the planar field with hidden units and random weights. Its Jacobian and trace are explicit:
using the cyclic property . The cell integrates the pair with RK4 to and keeps the path. It prints the smallest and the largest trace met on the way, and then compares the integral with , where the Jacobian 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 above used the structure of a one-layer field. For a general network the trace needs the diagonal entries of , which cost reverse-mode passes, one per coordinate. The trace has already replaced an determinant by passes. A random projection replaces the passes by one, and returns an unbiased but noisy estimate (Hutchinson, 1989).
Proposition (Hutchinson estimator). For any matrix and any random vector with , such as a standard Gaussian or a Rademacher vector with independent entries of equal probability,
Proof. , by the cyclic property of the trace and its linearity, which lets it commute with the expectation.
The estimator touches only through , one vector--Jacobian product, which is one reverse-mode pass through with as the seed; no Jacobian is formed. For the one-hidden-layer field the product is explicit,
and it costs about as much as evaluating . 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 , one Rademacher probe has variance and one Gaussian probe , the same sum with the diagonal included (Exercise 5). The trace sees only the diagonal of , and the noise of a Rademacher probe only what lies off it.
Let us try the estimator on a field in whose trace we can predict: a random one-hidden-layer part with tanh units and a pull toward the origin, . Its Jacobian is , so the pull contributes to the trace and the random part a number of order one. The pull also adds to every estimate. For a Rademacher probe this is exactly, and all the noise comes from the random part. For a Gaussian probe is itself random, and the two variance formulas say what that costs. They differ by the diagonal term , and here every is close to , so the variance of a Gaussian probe should exceed that of a Rademacher probe by about . The cell draws probes of each kind and computes each 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
at x for all Rademacher
(E) and Gaussian (E_gauss) probes and compare the resulting trace estimates
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 , a tenth of the trace: a single backward pass locates the trace to ten percent, where the exact value takes passes. One Gaussian probe has a standard deviation of about , and , close to the predicted . 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 : the standard deviation would still be , 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 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 as one matrix and estimates its trace once, so its noise is that of a single estimate whatever is. Fresh probes make independent errors, each weighted by , so the noise of their sum falls like . The next cell follows one Euler trajectory of the same field to with , and steps and repeats each policy times with Rademacher probes, taking 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 , 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 to at every . Fresh probes come to between and at , about to at and just under at : in each row, the held value divided by .
Fresh probes are about thirty times quieter at and cost the same. Why would anyone hold the probe? Because a held probe leaves the solver an ordinary differential equation. With fixed, the estimate 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 in a log-likelihood is a factor of 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 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 a flow preserves order, so 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 is the integral of along the trajectory, where the adjoint solves a linear ODE backward from ; backpropagation through Euler is exact for the program and within of this gradient. Re-integrating the state backward saves memory but amplifies a stored error by for a mode that decays at rate . Along a trajectory , 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#
-
[code] What a flow cannot represent. ● Two trajectories of a field with Lipschitz constant satisfy (Exercise 2 of Section 26.1), and Section 26.3.1.2 showed that no flow on reverses order (Dupont et al., 2019).
- Let . Use the lower bound to give a second proof that is strictly increasing, and show that . Which of the two statements, order or distance, does the proposition of the text give, and which needs the bound?
- The training example carries the circle points , which are apart, to , which are apart. Show that the exact time- flow of a field with Lipschitz constant can do this only if , whereas the long axis, stretched from to , gives only . A one-hidden-layer tanh field has because is -Lipschitz. Compute this bound for the RK4-trained field and check the inequality.
- Embed in as . Show that every linear field whose time-one map sends to for every has . Hint: an eigenvalue of comes from an eigenvalue of with , which is not real. Find such a field whose trajectories are ellipses rather than circles.
- Change the training cell to fit the map on evenly spaced points of with a field of input and output dimension and 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 , inputs , and the loss on the first coordinate.
- Train the one-dimensional model once more with and , and evaluate it with and with steps of size . Relate the two results to the proposition and to the condition .
-
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 of Finlay et al. (2020) accumulate a cost along the trajectory. Let
- Extend the variational proof of (26.3.4) to show that the adjoint acquires a source term, with , and that .
- Finlay et al. (2020) instead append a coordinate with and to the state, and add to the endpoint loss. Apply (26.3.4) to the extended state and show that it reproduces (a).
- For the kinetic energy, . Write as a vector--Jacobian product. How many reverse-mode passes through does one step of the adjoint ODE then require?
-
[code] Reconstructing the trajectory backward. ● The continuous adjoint can avoid storing the forward states by integrating backward from alongside . Section 26.3.2 found that a mode which decays at the rate then amplifies an error in the stored to .
- Let be the rotation by radians and
. Integrate
from to time with
RK4 steps (
solvewithrk4_step), then integrate backward from the result for the same time, with a negative horizon. Report the reconstruction error for , , and , and compare its growth with . Which fits? Why is it nearer than the of the text? Hint: how large are the coordinates of ? - Repeat with itself. From on it reconstructs the start far more accurately than does. Why?
- 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 of (a), what is the longest segment duration for which the drift with stays below ?
- Let be the rotation by radians and
. Integrate
from to time with
RK4 steps (
-
Log-determinant of a residual step. ●● The instantaneous change of variables (26.3.8) is a limit of infinitesimal steps. A finite residual step needs its exact log-determinant, as in the invertible residual networks of Behrmann et al. (2019).
- Let be Lipschitz with constant . For the one-line argument of Section 26.3.1.2 (an Euler step is increasing when ) shows that is strictly increasing, hence injective. For general , write as a fixed-point equation for and use the Banach fixed-point theorem, as in the proof of Picard--Lindelöf, to show that is a bijection of . How fast does the fixed-point iteration converge?
- Show that , where is the Jacobian of , and use the eigenvalues of to show that
- An Euler step has and . Compare with the term that (26.3.9) accumulates per step. How large is the difference per step, and how large is it in total over steps?
- The Hutchinson estimator (26.3.11) estimates by . How many vector--Jacobian products per probe does the series truncated after terms cost?
-
[code] Variance of the Hutchinson estimator. ● The estimator (26.3.11) estimates by for a single probe . Let , so that .
- Show that the variance of is for Gaussian probes and for Rademacher probes. For which matrices is a single Rademacher probe exact?
- Form the Jacobian of the field with the pull explicitly, from the weights and the point of the Hutchinson experiment (it is ). 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 ?
- In a CNF, is the Jacobian in dimension . Suppose that all entries have comparable magnitude. How does the relative standard error of one probe scale with when the diagonal entries share one sign, and when their signs are random?
- In training, each of the points of a minibatch has its own trajectory and its own held probe. How does the noise of the average log-likelihood depend on ? For which does it match the noise that one point has with fresh probes at steps?
-
[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 and forward states .
- For forward Euler, the discrete adjoint (26.3.6) computes , whereas an explicit Euler step of the adjoint ODE from back to computes . Bound the difference of the two updates for a smooth . 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 : show that the recursion computes the gradient that the text found, and that this equals .
- Differentiate one Heun step with to obtain its discrete adjoint recursion. Show that this recursion is a Heun step of the adjoint ODE from to in which is replaced by . At which order in do the two updates differ?
- For a linear field , one RK4 step multiplies the state by , where 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.
- Replace the Euler step of
loss_and_grad_unrolledby 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 gradientg_contfor , , , and steps. The trapezoid rule that computesg_contusesn_quad = 2000intervals and is accurate only to about , so refine it first. Which slope do you measure? Which order does the gradient computed through a solver of order inherit?
-
[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 of the flow map itself.
- Differentiate with respect to to obtain the variational equation with .
- Prove Jacobi's formula for invertible . Hint: write and use the Lemma.
- Conclude that , and derive (26.3.9) from the discrete change of variables (26.3.7) applied to the bijection . For a linear field the result is the formula (26.3.10).
- Integrate with RK4 alongside the -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 with the trace integral and the log-determinant that cell prints.