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 the two-moons density

This notebook trains a FFJORD continuous normalizing flow on the canonical two-moons toy. FFJORD parameterises the density transform as the solution of an ODE,

dxdt=fθ(t,x),dlog⁡ ∣det⁡J∣dt=tr(∂fθ/∂x),\frac{dx}{dt} = f_\theta(t, x), \qquad \frac{d\log\,|\det J|}{dt} = \mathrm{tr}(\partial f_\theta/\partial x),

integrated over [t0,t1][t_0, t_1] with diffrax. The trace can be computed exactly with jax.jacfwd (cost O(dim⁡)O(\dim) per ODE step) or stochastically with Hutchinson’s identity via matfree (cost O(n_samples)O(\text{n\_samples}) per step). The Hutchinson probes in gauss_flows’s FFJORD are fixed per instance — see the docstring — so the log-determinant is a deterministic function of parameters, which stabilises gradient training.

We follow the standard recipe: train with cheap Hutchinson divergence, evaluate with the exact trace by re-instantiating with the same trained vector field.

/home/azureuser/localfiles/geo_repos/geo_ml/gauss_flows-fit/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm

1. Dataset

A standardised two-moons sample. Standardisation matters because the FFJORD base distribution is a unit-variance Normal — without it, training has to absorb the scale through the vector field.

findfont: Failed to find font weight semibold for DejaVu Sans, now using 700.
<Figure size 605x550 with 1 Axes>

2. Build a FFJORD bijection

The vector field is a small DiffeqMLP that takes the ODE time and state and returns dx/dtdx/dt. The bijection is unconditional (control_dim=0), so no packed condition is required at call time and bij.cond_shape is None.

For a 2D problem, exact divergence costs only two Jacobian-vector products per ODE step — comparable to Hutchinson with two probes — and avoids the trace estimator’s variance entirely. We use it for both training and evaluation here. (Hutchinson becomes the right choice as dim⁡\dim grows; see section 7 for a comparison.)

unconditional FFJORD on shape (2,)
  vector field        : DiffeqMLP, hidden=(64, 64), tanh
  trainable parameters: 4546
  divergence mode     : exact (2 JVPs / step in 2D)
  cond_shape          : None

3. Train

fit_flow, the pipekit-train loop of notebook 01, minimises the negative log-likelihood under the flow, with the gradient clipped to a global norm of 5 (clip_norm). Each gradient step requires a vmapped ODE solve over the batch — FFJORD is expensive compared with closed-form flows. We keep the run short (80 epochs, batch 128) for a notebook; for a real fit you would train longer.

<Figure size 660x440 with 1 Axes>

4. Tighten the evaluation solver

Training used loose tolerances (10-4) for speed; for clean density plots we re-instantiate with the same trained vector field and tighten the solver. We also switch to the direct adjoint, which is more accurate at evaluation time when we don’t need backward gradients.

5. Density and samples

Plot the learned density on a grid (using the exact-mode flow) alongside samples drawn from the trained flow.

<Figure size 1320x550 with 3 Axes>

6. Vector field at three times

The vector field fθ(t,x)f_\theta(t, x) is what the ODE integrates. Visualising it as a quiver plot at a few times shows how the flow morphs the base Gaussian into the data distribution. At t=0t=0 the trajectory starts (data side); at t=1t=1 it arrives at the base side (since inverse_and_log_det integrates from t1t_1 back to t0t_0, “data → base” corresponds to t→1t \to 1).

WARNING:matplotlib.font_manager:findfont: Failed to find font weight semibold for DejaVu Sans, now using 700.
<Figure size 1980x715 with 3 Axes>

7. Hutchinson vs. exact: how many probes do you need?

gauss_flows’s FFJORD uses fixed Hutchinson probes per instance. That stabilises training (the log-det is a deterministic function of parameters) but the estimate still carries the variance of a finite probe set. The mean over many ODE steps converges to the trace, so error scales as O(1/nsamples)\mathcal{O}(1/\sqrt{n_\text{samples}}).

Here we hold the trained vector field fixed and rebuild FFJORD with various probe counts, then compute the bias (mean difference vs. exact) and RMSE of log⁡p\log p on a held-out batch.

exact   mean log p = -1.6206 (reference)

  n_probes    mean log p        bias        RMSE
         1       -1.6314     -0.0108      1.8635
         4       -1.6260     -0.0054      0.9317
        16       -1.6219     -0.0013      0.2329
        64       -1.6219     -0.0013      0.2329
       256       -1.6218     -0.0012      0.2038
<Figure size 770x495 with 1 Axes>

Two takeaways:

  • With a single Rademacher probe, the per-point error in log⁡p\log p is the integrated trace-estimator variance over the ODE — non-trivial. It shrinks as 1/n1/\sqrt{n} as expected.

  • The mean log-density bias is much smaller than the RMSE: averaging across evaluation points cancels the per-point variance, so reported NLLs are reasonable even at small nn. Per-point values (e.g. for OOD scoring or anomaly detection) need either more probes or the exact trace.