Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

FFJORD on two moons

A flow that is the solution of an ODE: the log-density changes at the rate of minus the trace of the vector field's Jacobian

00 · FFJORD on two moons

Open In Colab

Every flow so far is a stack of layers, and its log-density adds up one log-determinant per layer (5). A continuous normalizing flow Chen et al., 2018 takes the limit of a stack of infinitely many, infinitely small layers: the map is the solution of an ordinary differential equation, and the sum of log-determinants becomes the time integral of a trace. FFJORD Grathwohl et al., 2019 makes the idea practical. Any network can be the vector field, because the trace needs only Jacobian-vector products, and nothing about the network has to be triangular or invertible: the ODE solver inverts the map by running time backwards.

The FFJORD example already trains this flow on two moons and shows its density, its vector field at three times and how many Hutchinson probes its log-density needs. This notebook adds what the example takes for granted: where the integral of the trace comes from, a check of it against autodiff, and what the trained flow does to the data.

Python implementation: CPython
Python version       : 3.13.12
IPython version      : 9.12.0

jax               : 0.12.1
numpy             : 2.4.3
optax             : 0.2.8
diffrax           : 0.7.2
flowjax           : 19.1.0
pipekit_train     : 0.3.4
gauss_flows_models: 0.3.1

Compiler    : Clang 21.1.4 
OS          : Linux
Release     : 6.8.0-1044-azure
Machine     : x86_64
Processor   : x86_64
CPU cores   : 16
Architecture: 64bit

The notebook runs in float32, the precision users get by default; every log-density goes through an adaptive ODE solve, which float32 keeps fast enough for a notebook.

The continuous change of variables

Take one residual layer that moves a point a small step Δt\Delta t along a vector field vθ(t,x)\vect{v}_\theta(t, \vect{x}), a neural network with weights θ\theta: xk=xk−1+Δtvθ(tk,xk−1)\vect{x}_{k} = \vect{x}_{k-1} + \Delta t \vect{v}_\theta(t_k, \vect{x}_{k-1}). Its Jacobian is I+ΔtJv\mat{I} + \Delta t \mat{J}_v, with Jv=∂vθ/∂x\mat{J}_v = \partial \vect{v}_\theta / \partial \vect{x} the Jacobian of the vector field, and its log-determinant is log⁡det⁡(I+ΔtJv)=Δttr(Jv)+O(Δt2)\log \det(\mat{I} + \Delta t \mat{J}_v) = \Delta t \mathrm{tr}(\mat{J}_v) + O(\Delta t^2). A stack of such layers with Δt→0\Delta t \to 0 is the ODE

dx(t)dt=vθ(t,x(t)),x(0)=z,x(1)=x\begin{aligned} \frac{\mathrm{d} \vect{x}(t)}{\mathrm{d} t} &= \vect{v}_\theta(t, \vect{x}(t)), \\ \vect{x}(0) &= \vect{z}, \\ \vect{x}(1) &= \vect{x} \end{aligned}

which starts at the latent z\vect{z} at time t=0t = 0 and ends at the data point x\vect{x} at t=1t = 1. The sum of the layers’ log-determinants becomes an integral of traces along the path:

log⁡∣det⁡∂x(1)∂x(0)∣=∫01tr(Jv(t,x(t)))dt\log \left\vert \det \frac{\partial \vect{x}(1)}{\partial \vect{x}(0)} \right\vert = \int_0^1 \mathrm{tr}(\mat{J}_v(t, \vect{x}(t))) \mathrm{d} t

The same statement, written for the density of a point carried along the path, is the instantaneous change of variables:

dlog⁡p(x(t))dt=−tr(Jv(t,x(t)))\frac{\mathrm{d} \log p(\vect{x}(t))}{\mathrm{d} t} = -\mathrm{tr}(\mat{J}_v(t, \vect{x}(t)))

The map from data to latent, z=f(x)\vect{z} = f(\vect{x}), runs the ODE backwards from t=1t = 1 to t=0t = 0, so its log-determinant is minus the integral, and the change of variables (4) becomes

log⁡px(x)=log⁡N(z;0,I)−∫01tr(Jv(t,x(t)))dt\log p_x(\vect{x}) = \log \mathcal{N}(\vect{z}; \vect{0}, \mat{I}) - \int_0^1 \mathrm{tr}(\mat{J}_v(t, \vect{x}(t))) \mathrm{d} t

Nothing here asks vθ\vect{v}_\theta to be invertible or its Jacobian to be triangular: the ODE’s solution is invertible for any smooth vector field, and the trace needs only the DxD_x diagonal entries of Jv\mat{J}_v, which DxD_x Jacobian-vector products give exactly.

1. A FFJORD bijection, checked against autodiff

FFJORD solves (1) together with the running integral of (2), with diffrax. Its transform runs time forwards, from the latent to the data (the sampling direction of FlowJax), and its inverse runs it backwards, from the data to the latent (the density direction). With divergence_mode="exact" the trace is gaussx.trace of the Jacobian operator of vθ\vect{v}_\theta, which costs DxD_x Jacobian-vector products per solver step: two in 2-D, so there is no reason to estimate it. Notebook 01 is about the estimate that larger DxD_x needs.

The vector field is a DiffeqMLP, an MLP with two hidden layers of 64 tanh units that reads the time and the point. Its last layer has random weights, unlike the zero readout of a fresh coupling (Part 5), so a fresh FFJORD is not the identity.

To check (2) we need the Jacobian of the solved map z↦x(1)\vect{z} \mapsto \vect{x}(1), which jax.jacfwd builds by differentiating through the solver. The default adjoint of FFJORD ("recursive_checkpoint", reverse mode for training) does not support forward-mode autodiff, so we solve the same vector field again with the "direct" adjoint, which does, and with a tolerance of 10-6 so that the solver’s error stays below what we compare.

distance moved, ||x(1) - z||: [0.044 0.186 0.096 0.119 0.137]
integrated trace           : [ 0.012  0.01   0.024 -0.002  0.001]
log |det| from autodiff    : [ 0.012  0.01   0.024 -0.002  0.001]
largest difference         : 1.1e-07

The fresh field moves these points by 0.04 to 0.19 and changes their log-volume by at most 0.024: a random field of this size is close to the identity, but not the identity. The integrated trace agrees with the log-determinant of the autodiff Jacobian to 1.1×10−71.1 \times 10^{-7}, float32 rounding. Section 4 repeats the check on the trained field, which moves points much further.

2. Two moons

The data are N=1500N = 1500 points of two moons with noise of standard deviation 0.06, standardised per coordinate and split into Nt=1200N_t = 1200 training rows and Nv=300N_v = 300 held-out rows. We keep the moon each point came from, to colour the paths in section 6.

3. Training with pipekit-train

The flow is FlowJax’s Transformed with a standard-normal base, so log_prob is (4), and the loss is the negative log-likelihood (1) through negative_log_likelihood, as in Part 4. The base is FlowJax’s StandardNormal, which has no parameters, so only θ\theta trains.

Every step solves the ODE for each of its 256 points, so FFJORD trains far more slowly than the closed-form flows of Parts 4 and 5. We keep the run to 1,500 steps of Adam with a one-cycle cosine learning rate that peaks at 5×10−35 \times 10^{-3} and the gradient clipped to a global norm of 1, which takes three to four minutes on the 16 CPU cores this notebook was run on. A longer run fits the moons more tightly.

training took 3.2 min
held-out NLL: 2.773 before training, 1.393 after; training rows 1.326
<Figure size 700x350 with 1 Axes>

Figure 1:Training loss of each logged step (light) and held-out loss after each epoch (dark), in nats per point.

The held-out NLL falls from 2.773 to 1.393 nats in 3.2 minutes, with the training rows at 1.326. Most of the fall comes in the first 400 steps, and the held-out loss is flat over the last third of the run.

4. The learned density

Training solved the ODE to 10-4. For the plots we put the trained vector field into a FFJORD that solves to 10-6 with the "direct" adjoint, as in section 1, and evaluate everything below with it.

First the check of section 1 again, now on the trained field, which moves points much further.

distance moved, ||x(1) - z||: [1.042 2.102 1.245 0.919 1.856]
integrated trace           : [-2.2   -1.601 -1.25  -1.589 -1.423]
largest difference         : 3.8e-06

The trained field moves the same latents by 0.9 to 2.1, and the integrated traces, from −2.2 to −1.25, still agree with autodiff to 3.8×10−63.8 \times 10^{-6}. They are negative: going from the latent to the data the flow shrinks volume, which is how it piles the probability onto two thin moons.

The density is (4) on a grid. A density must integrate to one, so we also sum it over the grid, which covers the moons with room to spare.

density summed over the grid: 0.9999
<Figure size 1000x460 with 3 Axes>

Figure 2:Left: the density of the trained FFJORD on a grid, solved to 10⁻⁶. Right: the data (blue) and as many samples from the flow (orange).

The density sums to 0.9999 over the grid, so the integrated trace gives a properly normalised density. It follows both moons, and the samples, drawn by solving forwards from the base, cover them. A few samples fall between the moons, where the density keeps a faint bridge: the flow is a continuous invertible map of a Gaussian, so it cannot tear the mass into two separate pieces, and it stretches a thin band between them instead.

5. Is the latent Gaussian?

The flow is trained so that z=f(x)\vect{z} = f(\vect{x}) is standard normal. We run the held-out rows backwards through the ODE and look at their latents the way Part 0 did: a scatter against the circles of radius one, two and three, a quantile-quantile plot of each coordinate against N(0,1)\mathcal{N}(0, 1), and the first four moments.

mean [-0.025  0.015], std [0.983 0.983], skewness [-0.083  0.087], excess kurtosis [ 0.043 -0.166]
<Figure size 1300x420 with 3 Axes>

Figure 3:The held-out rows mapped to the latent. Left: the latents with the circles of radius 1, 2 and 3 of the standard normal. Middle and right: quantile-quantile plots of each latent coordinate against N(0, 1), with the identity line dashed.

The latent means are within 0.03 of zero, the standard deviations are 0.98, the skewness is within ±0.09 and the excess kurtosis between −0.17 and 0.04. With 300 rows the standard error of a skewness is about 0.14 and that of an excess kurtosis about 0.28, so none of these departures stands out from sampling noise, and the quantile-quantile plots follow the identity line except for a slightly light lower tail of z1z_1.

6. The paths from data to latent

The ODE gives more than the endpoints: every time tt between 0 and 1 has its own state x(t)\vect{x}(t). A FFJORD with the time span (s,1)(s, 1) and the trained vector field runs the backward solve only down to t=st = s, so its inverse returns x(s)\vect{x}(s), with the public API and nothing else. We take five times and colour each held-out row by its moon.

<Figure size 1700x380 with 5 Axes>

Figure 4:The held-out rows at five times of the backward solve, from the data at t = 1 to the latent at t = 0, coloured by the moon each came from.

Going back in time, the moons first thicken (t=0.75t = 0.75), then open up and move apart (t=0.5t = 0.5 and 0.25), and at t=0t = 0 they fill the two halves of a round cloud, split along a diagonal. The paths of an ODE cannot cross, so the moons never pass through each other: each ends on its own side of the Gaussian.

Recap

PieceEquationIn code
a flow that is the solution of an ODE(1)FFJORD(key, shape, vector_field=DiffeqMLP(...))
its log-determinant, an integral of traces(2)transform_and_log_det, checked against jax.jacfwd with adjoint="direct"
the instantaneous change of variables(3)the augmented state that diffrax solves
the log-density of a data point(4)Transformed(StandardNormal((2,)), ffjord).log_prob
the exact trace, DxD_x JVPs per stepdivergence_mode="exact", gaussx.trace of the Jacobian operator
the state at an intermediate timeFFJORD(..., t_span=(s, 1.0)).inverse

Next. The exact trace costs DxD_x Jacobian-vector products per solver step, cheap in 2-D and prohibitive for an image. Notebook 01 replaces it with Hutchinson’s estimator, which costs one product per probe whatever DxD_x is.

References
  1. Chen, R. T. Q., Rubanova, Y., Bettencourt, J., & Duvenaud, D. (2018). Neural Ordinary Differential Equations. Advances in Neural Information Processing Systems (NeurIPS).
  2. Grathwohl, W., Chen, R. T. Q., Bettencourt, J., Sutskever, I., & Duvenaud, D. (2019). FFJORD: Free-Form Continuous Dynamics for Scalable Reversible Generative Models. International Conference on Learning Representations (ICLR).