Skip to content

Flow matching: a spiral galaxy from noise

generative flow_matching_galaxy.py

A cloud of random points flows into a two-arm spiral galaxy. A network learns the velocity field that carries noise to the data, by conditional flow matching, and sampling marches that field as an ODE. The galaxy is a demanding target: a model that loses the winding of the arms, or empties one of them, shows it at once.

6000 samples, drawn from a Gaussian at t = 0, flowing along the trained velocity field into a two-arm spiral galaxy at t = 1; the faint grey dots are the training data.

6000 samples marched from a Gaussian at \(t=0\) to the galaxy at \(t=1\); the grey dots are the training data.

The problem

Learn a velocity field \(v_\theta(x,t)\) whose flow carries the prior \(p_0=\mathcal N(0,I)\) to the data \(p_1\). For the straight path between a prior draw \(x_0\) and a data point \(x_1\),

\[x_t = (1-t)\,x_0 + t\,x_1, \qquad \frac{dx_t}{dt} = x_1 - x_0,\]

so training is a regression onto a constant velocity (Lipman et al., "Flow Matching for Generative Modeling", ICLR 2023, §3):

\[\min_\theta\ \mathbb E_{t,x_0,x_1}\big\lVert v_\theta(x_t,t) - (x_1-x_0)\big\rVert^2 .\]

The data are 16 384 points: two logarithmic arms \(r=R_0e^{B\varphi}\) with a scatter that grows outward, and a Gaussian core.

The jNO code

The data enter as a point cloud, and the probability path is written as the formula it is. like= takes each draw's shape from an expression, so it follows the point subsampling of solve(points=...):

domain = jno.domain.from_array({"data": data})
d0, d1, _ = domain.variable("data")
x1 = jno.np.concatenate([d0, d1])  # the data sample

x0 = jno.noise.gaussian(std=1.0, like=x1)  # prior draw
t = jno.noise.uniform(low=0.0, high=1.0, like=d0)  # path time, one per point
x_t = (1 - t) * x0 + t * x1  # the linear (optimal-transport) path
target = x1 - x0  # its velocity, constant along the path

The whole objective is one term; points= minibatches the point axis of the dataset:

v = jno.nn(foundax.mlp(D + 1, output_dim=D, hidden_dims=256, num_layers=4, activation=jax.nn.swish, key=KEY))
v.optimizer(optax.adam(3e-3))
crux = jno.core([(v(x_t, t) - target).mse])  # the whole objective
stats = crux.solve(epochs=EPOCHS, points=POINTS)

Sampling marches \(dx/dt=v(x,t)\) with Heun's method:

z = jax.random.normal(jax.random.PRNGKey(1), (6000, D))
path = np.asarray(v.flow(z, time=(0.0, 1.0, 121), save=True))  # (121, 6000, D)
samples = path[-1]

A symbolic start point would instead return a node that composes into another jno.core term list.

Result

final flow-matching loss 0.957 (irreducible: \(x_t\) does not tell which pair produced it)
samples within 0.4 rad of an arm 0.71 (data: 0.76; a uniform angle: 0.25)
largest gap between the radial densities of samples and data 0.058

Full script

The whole script, as it runs in the tests
"""Conditional flow matching: train a velocity, march it as an ODE

The target is a two-arm spiral galaxy: a bright core and two logarithmic arms whose density falls off outward.
It fails *loudly* in two independent ways: a collapsed velocity loses the arms (the angle no longer winds with
the radius), and a mode-dropping one empties one arm.

Lipman et al., "Flow Matching for Generative Modeling", ICLR 2023 (§3, the conditional objective).
"""

import foundax
import jax
import numpy as np
import optax

import jno

run = jno.setup(__file__)
KEY, D, N, EPOCHS, POINTS = jax.random.PRNGKey(0), 2, 16384, 12000, 2048  # POINTS: the point axis, not the sample axis

# Two logarithmic arms r = R0 exp(B phi), phi in [0, PHI] (the angle along the arm, density falling outward),
# a thicker scatter outward, and a bright Gaussian core.
rng = np.random.default_rng(0)
R0, B, PHI = 0.12, 0.35, 9.5
phi = PHI * rng.beta(1.0, 1.3, N)  # the position along the arm
r = R0 * np.exp(B * phi)
theta = phi + np.pi * rng.integers(0, 2, N)  # arm 0 or arm 1
arms = np.stack([np.cos(theta), np.sin(theta)], -1) * r[:, None] + (0.04 + 0.06 * r)[:, None] * rng.normal(size=(N, D))
core = 0.28 * rng.normal(size=(N, D))
data = np.where((rng.random(N) < 0.2)[:, None], core, arms).astype(np.float32)

domain = jno.domain.from_array({"data": data})
d0, d1, _ = domain.variable("data")
x1 = jno.np.concatenate([d0, d1])  # the data sample

# The probability path as the formula it is. `like=` takes the draw's shape from the expression, so the prior
# tracks solve(points=...); a shape written down by hand would go stale and fail by broadcasting.
x0 = jno.noise.gaussian(std=1.0, like=x1)  # prior draw
t = jno.noise.uniform(low=0.0, high=1.0, like=d0)  # path time, one per point
x_t = (1 - t) * x0 + t * x1  # the linear (optimal-transport) path
target = x1 - x0  # its velocity, constant along the path

v = jno.nn(foundax.mlp(D + 1, output_dim=D, hidden_dims=256, num_layers=4, activation=jax.nn.swish, key=KEY))
v.optimizer(optax.adam(3e-3))

crux = jno.core([(v(x_t, t) - target).mse])  # the whole objective
stats = crux.solve(epochs=EPOCHS, points=POINTS)
final_loss = float(stats.training_logs[-1]["total_loss"][-1])
print(f"final CFM loss: {final_loss:.4f}   (an O(1) plateau is correct: the objective is irreducible)")

# Sample: march the trained velocity from Gaussian draws, state first and time second, 120 Heun steps.
z = jax.random.normal(jax.random.PRNGKey(1), (6000, D))
path = np.asarray(v.flow(z, time=(0.0, 1.0, 121), save=True))  # (121, 6000, D)
samples = path[-1]


# Check: the angle of a sample against the arm law theta = ln(r / R0) / B (mod pi), and the radial density.
def off_arm(p):
    r, theta = np.linalg.norm(p, axis=-1), np.arctan2(p[:, 1], p[:, 0])
    sel = (r > 0.5) & (r < 3.0)  # outside the core, inside the outer cut-off
    off = (theta - np.log(r / R0) / B)[sel] % np.pi
    return np.minimum(off, np.pi - off)  # distance to the nearest arm in angle, rad


on_arm = np.mean(off_arm(samples) < 0.4)  # a uniform angle would give 0.4 * 2 / pi = 25 %
on_arm_data = np.mean(off_arm(data) < 0.4)
hist = lambda p: np.histogram(np.linalg.norm(p, axis=-1), bins=8, range=(0, 4), density=True)[0]
radial_gap = np.abs(hist(samples) - hist(data)).max()
print(f"samples within 0.4 rad of an arm: {on_arm:.2f}   (data: {on_arm_data:.2f}, uniform angle: 0.25)")
print(f"max radial-density gap, samples against data: {radial_gap:.3f}")
assert on_arm > 0.85 * on_arm_data and radial_gap < 0.1