Skip to content

Flow matching of turbulence: sampling vorticity fields

generative flow_matching_turbulence.py

A generative model trained on snapshots of 2-D decaying turbulence draws new ones. The training fields come from jno.spectral, one solver run per field; the model is a U-Net velocity field trained by conditional flow matching, as in the galaxy tutorial. Are the new fields real turbulence, or copies?

Two samples side by side, each starting at t = 0 as Gaussian noise (a fine speckle in light purple and green) and ending at t = 1 as a smooth vorticity field of rounded vortices and thin filaments, purple for negative and green for positive vorticity.

Two draws of the Gaussian prior carried along the learned velocity, from noise to vorticity, on one colour scale.

The problem

The data are vorticity fields \(\omega(x,y)\) on a periodic \(64\times64\) grid at the late time \(t=8\), each from its own random initial field:

\[\partial_t \omega + \mathbf u\cdot\nabla\omega = \nu\Delta\omega, \qquad \Delta\psi = -\omega, \qquad \nu = 10^{-3} .\]

The model learns a velocity \(v_\theta(x,t)\) that carries \(\mathcal N(0,I)\) to the distribution of these fields, by regressing onto the straight-path velocity \(x_1-x_0\) at \(x_t=(1-t)x_0+tx_1\).

The jNO code

The data are one jno.spectral solve per field, saved only at \(t=0\) and \(t=T\):

def vorticity_at_T(w0):  # vorticity at t = T, shape (N, N)
    (wf, _) = jno.spectral(
        [
            w.t + psi.y * w.x - psi.x * w.y - NU * (w.xx + w.yy),
            psi.xx + psi.yy + w,
            psi.mean,
            W(x0, y0) - jnp.asarray(w0.reshape(-1, 1)),
            *[U(*lo) - U(*hi) for U in (W, Psi) for lo, hi in (((xl, yl), (xr, yr)), ((xb, yb), (xt, yt)))],
        ]
    ).solve(time=jno.solve.etdrk4(), save_ts=np.array([0.0, T]))
    return np.asarray(wf)[-1].reshape(N, N)

Each training field is stored with its seven mirrored and rotated copies: the equations are invariant under the symmetries of the square (a mirror image has the opposite vorticity).

The probability path is written as formulas, with one field per domain row:

rows = len(data) * jno.shape.rect(0.0, 0.0, 1.0, 1.0).structured(n=3).domain()
rows.variable("interior")
rows.variable("w", data)
x1 = rows.variable("w")
x0_, t_ = jno.noise.gaussian(std=1.0, like=x1), jno.noise.uniform(0.0, 1.0, ndim=1)
x_t = (1 - t_) * x0_ + t_ * x1

The velocity is a U-Net with circular padding, which sees the flow time as one more constant channel:

v = jno.nn(Velocity(foundax.unet2d(in_channels=2, out_channels=1, depth=4, wf=5, padding_mode="circular", key=KEY)))
v.optimizer(optax.chain(optax.clip_by_global_norm(1.0), optax.adam(optax.cosine_decay_schedule(1e-3, EPOCHS, 0.01))))
stats = jno.core([(v(x_t, t_) - (x1 - x0_)).mse]).solve(epochs=EPOCHS, batchsize=BATCH)

Sampling marches Gaussian noise along it with v.flow(z, time=(0.0, 1.0, 101)).

Result

Top row: five held-out solver vorticity fields. Bottom row: five generated fields. Both are purple and green blobs and filaments on one symmetric colour scale; the generated ones have more short streaks.

Top: held-out solver fields. Bottom: generated fields. Against 128 held-out solver fields:

check result
energy spectrum \(E(k)\), \(k=1\ldots21\): largest factor 0.164 decades (two solver sets: 0.019)
vorticity histogram: total-variation distance 0.018
box-mean vorticity of any sample 0.039 \(\omega_\mathrm{rms}\)
cosine similarity to the nearest training field (all shifts and symmetries) median 0.34 (held-out solver fields: 0.37)

Left: isotropic energy spectrum E(k) on log-log axes for the training solver fields, the held-out solver fields (the two coincide) and the generated fields; the generated one sits slightly above them for k from 5 to 20. Right: histogram of the vorticity in units of its rms on a log axis, generated against held out; the generated tails are a little heavier.

The spectrum is right at the large scales and a little too energetic at \(k\gtrsim5\), where the generated fields have streaks; the histogram tails are slightly too heavy. A generated field is no closer to a training field than a fresh solver field is, so the model does not copy its training set.

Full script

The whole script, as it runs in the tests
"""Flow matching of 2-D turbulence: a generative model for vorticity fields, trained on jno.spectral snapshots.

The data are late-time snapshots of decaying 2-D turbulence on a periodic box (vorticity-streamfunction, ETDRK4,
64^2 modes, 3/2 dealiasing) from many random initial conditions. A U-Net with periodic padding learns the velocity
field of conditional flow matching (Lipman et al. 2023); sampling marches Gaussian noise along it with `Model.flow`.
Checks against held-out solver fields: isotropic energy spectrum E(k), vorticity histogram, zero mean vorticity, and a
nearest-neighbour search (all shifts, rotations and reflections) showing that samples are not copies of training fields.
"""

import equinox as eqx
import foundax
import jax
import jax.numpy as jnp
import numpy as np
import optax

import jno

run = jno.setup(__file__)
L, N, NU, T, STEPS = 2 * np.pi, 64, 1.0e-3, 8.0, 800  # periodic box, grid, viscosity, snapshot time, ETDRK4 steps
N_TRAIN, N_TEST, N_GEN = 512, 128, 256  # solver runs for training / held-out, generated samples
EPOCHS, BATCH, KEY = 20000, 32, jax.random.PRNGKey(0)

# 1. Data: one jno.spectral solve per random initial vorticity (a random-phase ring of modes around k = 5, rms 2).
d = jno.shape.rect(0.0, 0.0, L, L).domain(time=(0.0, T, STEPS + 1))
W = d.unknown(space=("fourier", "fourier"), order=(N, N), name="w")
Psi = d.unknown(space=("fourier", "fourier"), order=(N, N), name="psi")
x, y, t = d.variable("interior", split=True)
x0, y0, _ = d.variable("initial", split=True)
(xl, yl, _), (xr, yr, _) = d.variable("left", split=True), d.variable("right", split=True)
(xb, yb, _), (xt, yt, _) = d.variable("bottom", split=True), d.variable("top", split=True)
dealiased = jno.sp(dealias=3 / 2)
w, psi = W.bind(x=x, y=y, t=t, scheme=dealiased), Psi.bind(x=x, y=y, scheme=dealiased)

k1, k2 = 2 * np.pi * np.fft.fftfreq(N, d=L / N), 2 * np.pi * np.fft.rfftfreq(N, d=L / N)
K = np.hypot(*np.meshgrid(k1, k2, indexing="ij"))


def initial_vorticity(seed):
    phase = np.random.default_rng(seed).uniform(0, 2 * np.pi, K.shape)
    w0 = np.fft.irfft2(np.where(K > 0, np.exp(-0.5 * ((K - 5.0) / 1.5) ** 2), 0.0) * np.exp(1j * phase), s=(N, N))
    return 2.0 * (w0 - w0.mean()) / w0.std()


def vorticity_at_T(w0):  # vorticity at t = T, shape (N, N)
    (wf, _) = jno.spectral(
        [
            w.t + psi.y * w.x - psi.x * w.y - NU * (w.xx + w.yy),
            psi.xx + psi.yy + w,
            psi.mean,
            W(x0, y0) - jnp.asarray(w0.reshape(-1, 1)),
            *[U(*lo) - U(*hi) for U in (W, Psi) for lo, hi in (((xl, yl), (xr, yr)), ((xb, yb), (xt, yt)))],
        ]
    ).solve(time=jno.solve.etdrk4(), save_ts=np.array([0.0, T]))
    return np.asarray(wf)[-1].reshape(N, N)


fields = np.stack([vorticity_at_T(initial_vorticity(s)) for s in range(N_TRAIN + N_TEST)])
train, test = fields[:N_TRAIN], fields[N_TRAIN:]
SIGMA = train.std()  # the prior is N(0, 1): measure vorticity in units of its rms


def dihedral(a):  # the 8 symmetries of the square; a mirror image has the opposite vorticity
    return np.concatenate([s for k in range(4) for r in [np.rot90(a, k, (1, 2))] for s in (r, -r[:, ::-1])])


data = (dihedral(train) / SIGMA).astype(np.float32)[:, None, :, :, None]  # (8 N_TRAIN, 1, N, N, 1)

# 2. Flow matching. One sample per row; the path x_t = (1-t) x0 + t x1 and its velocity x1 - x0 are written as formulas.
rows = len(data) * jno.shape.rect(0.0, 0.0, 1.0, 1.0).structured(n=3).domain()
rows.variable("interior")
rows.variable("w", data)
x1 = rows.variable("w")
x0_, t_ = jno.noise.gaussian(std=1.0, like=x1), jno.noise.uniform(0.0, 1.0, ndim=1)
x_t = (1 - t_) * x0_ + t_ * x1


class Velocity(eqx.Module):  # a U-Net that also sees the time as one more (constant) channel, on any leading batch axes
    unet: eqx.Module

    def __call__(self, x, t):
        tau = jnp.broadcast_to(jnp.ravel(t)[0], (*x.shape[:-1], 1))
        h = jnp.concatenate([x, tau], axis=-1)
        return jax.vmap(self.unet)(h.reshape(-1, *h.shape[-3:])).reshape(x.shape)


v = jno.nn(Velocity(foundax.unet2d(in_channels=2, out_channels=1, depth=4, wf=5, padding_mode="circular", key=KEY)))
v.optimizer(optax.chain(optax.clip_by_global_norm(1.0), optax.adam(optax.cosine_decay_schedule(1e-3, EPOCHS, 0.01))))
stats = jno.core([(v(x_t, t_) - (x1 - x0_)).mse]).solve(epochs=EPOCHS, batchsize=BATCH)
print(f"final CFM loss {float(stats.training_logs[-1]['total_loss'][-1]):.4f}")

# 3. Sampling: march Gaussian noise along the learned velocity (100 Heun steps), then back to physical units.
z = jax.random.normal(jax.random.PRNGKey(1), (N_GEN, N, N, 1))
march = lambda z, **kw: np.asarray(v.flow(z, time=(0.0, 1.0, 101), **kw))[..., 0] * SIGMA
samples = np.concatenate([march(c) for c in np.split(np.asarray(z), 4)])  # in chunks of 64: the march keeps every step
path = march(z[:4], save=True)  # the 4 first samples at every step: (101, 4, N, N)


# 4. Checks against the held-out solver fields.
def spectrum(a):  # isotropic kinetic-energy spectrum E(k), k = 1 .. N/3 (the dealiased range); E = |w_k|^2 / (2 k^2)
    kk = np.rint(np.hypot(*np.meshgrid(*[np.fft.fftfreq(N, 1 / N)] * 2, indexing="ij"))).astype(int)
    e = 0.5 * np.mean(np.abs(np.fft.fft2(a)) ** 2, 0) / N**4 / np.maximum(kk, 1) ** 2
    return np.bincount(kk.ravel(), e.ravel())[1 : N // 3 + 1]


def histogram(a):  # probability of w / SIGMA in 40 bins on [-4, 4]
    return np.histogram(a / SIGMA, bins=40, range=(-4, 4))[0] / a.size


def best_match(
    a, ref
):  # largest cosine similarity of each field in a with any field of ref, over shifts and the 8 symmetries
    nrm = lambda b: b / np.linalg.norm(b.reshape(len(b), -1), axis=1)[:, None, None]
    fr = np.fft.rfft2(nrm(ref))
    best = []
    for s in nrm(a):
        fs = np.fft.rfft2(dihedral(s[None]))  # (8, N, N/2+1)
        best.append(np.fft.irfft2(np.conj(fs)[:, None] * fr[None], s=(N, N)).max())
    return np.array(best)


gap = np.abs(np.log10(spectrum(samples) / spectrum(test))).max()  # largest factor between the spectra, in decades
floor = np.abs(np.log10(spectrum(train) / spectrum(test))).max()  # the same for two sets of real fields (sampling noise)
tv = 0.5 * np.abs(histogram(samples) - histogram(test)).sum()  # total-variation distance of the vorticity histograms
mean_w = np.abs(samples.mean((1, 2))).max() / SIGMA  # the box-mean vorticity of any sample, in units of rms
sim, sim_test = best_match(samples, train), best_match(test, train)
print(f"E(k) gap {gap:.3f} decades (train vs test {floor:.3f}), histogram TV {tv:.3f}, |mean w| <= {mean_w:.3f} rms")
print(
    f"nearest training field, cosine similarity: samples {np.median(sim):.2f} (max {sim.max():.2f}), held-out {np.median(sim_test):.2f}"
)
assert gap < 0.3 and tv < 0.07 and mean_w < 0.1 and sim.max() < 0.95 and np.median(sim) < np.median(sim_test) + 0.1