Fits a 2D torus with circular spline couplings that keep each angle periodic.
from __future__ import annotations
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import paramax
from flowjax.bijections import Chain, Permute
from flowjax.distributions import Normal, Transformed
from pipekit_train import ArrayDataset, EarlyStopping, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from gauss_flows_models.inference import negative_log_likelihood
from gauss_flows_maps.bijections import CircularRQSplineCoupling
def style_ax(ax):
ax.grid(True, which="major", alpha=0.3)
ax.grid(True, which="minor", alpha=0.1)
ax.minorticks_on()
SCATTER_KW = dict(s=30, edgecolors="k", linewidths=0.5, alpha=0.5, zorder=5)/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
Generate a toroidal dataset¶
Each sample is an angle pair; a two-mode mixture builds torus structure.
data_key, theta_key, phi_key, mix_key = jr.split(jr.key(0), 4)
n_samples = 3000
component = jr.bernoulli(mix_key, 0.5, (n_samples,))
theta_raw = jr.normal(theta_key, (n_samples,)) * 0.35 + jnp.where(component, 0.9, -0.9)
phi_raw = jr.normal(phi_key, (n_samples,)) * 0.3 + jnp.where(component, 1.3, -1.3)
wrap = lambda arr: ((arr + jnp.pi) % (2 * jnp.pi)) - jnp.pi
theta = wrap(theta_raw)
phi = wrap(phi_raw)
data = jnp.stack([theta, phi], axis=1)fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(data[:, 0], data[:, 1], **SCATTER_KW)
ax.set_xlabel(r"$\theta$")
ax.set_ylabel(r"$\phi$")
style_ax(ax)
ax.set_title("Samples on the torus (angles in radians)")
plt.show()
Build and train a circular coupling flow¶
Stack circular spline couplings with permutations and train by maximum likelihood.
class FlowNLL:
"""pipekit-train's task: gauss_flows's negative log-likelihood of a batch."""
def loss_fn(self, flow, batch, key):
x, condition = batch
# an unconditional dataset has no targets, ()
condition = None if isinstance(condition, tuple) else condition
loss = negative_log_likelihood(flow, x, key=key, condition=condition)
return loss, {"loss": loss}
def fit_flow(
key,
flow,
x,
*,
condition=None,
learning_rate=5e-3,
clip_norm=None,
max_epochs=100,
max_patience=10,
batch_size=256,
val_prop=0.1,
):
"""Fit `flow` to the rows of `x` by maximum likelihood with pipekit-train.
A fraction `val_prop` of the rows is held out. Training stops after
`max_patience` epochs without a lower validation loss, and the flow of the
best epoch is returned with the per-epoch train and validation losses.
"""
split_key, loop_key = jr.split(key)
# one shuffle, then the last val_prop of the rows held out
order = np.asarray(jr.permutation(split_key, len(x)))
n_train = len(x) - round(val_prop * len(x))
train_rows, val_rows = order[:n_train], order[n_train:]
def rows(a, idx):
return () if a is None else np.asarray(a)[idx]
batch_size = min(batch_size, n_train)
steps_per_epoch = n_train // batch_size
optimizer = {"name": "adam", "lr": learning_rate}
if clip_norm is not None:
optimizer["clip_norm"] = clip_norm
# paramax.NonTrainable leaves (fixed rotations) stay out of the optimiser
trainable = jax.tree.map(
eqx.is_inexact_array,
flow,
is_leaf=lambda leaf: isinstance(leaf, paramax.NonTrainable),
)
history = History()
trained, _ = TrainingLoop(
EquinoxModelOp(flow, trainable=trainable),
ArrayDataset(rows(x, train_rows), rows(condition, train_rows)),
val_dataset=ArrayDataset(rows(x, val_rows), rows(condition, val_rows)),
task=FlowNLL(),
optimizer_config=optimizer,
max_steps=max_epochs * steps_per_epoch,
steps_per_epoch=steps_per_epoch,
eval_every_n_steps=steps_per_epoch,
log_every_n_steps=steps_per_epoch,
batch_size=batch_size,
seed=int(jr.randint(loop_key, (), 0, 2**31 - 1)),
callbacks=(
history,
EarlyStopping("loss", patience=max_patience, restore_best=True),
),
).run()
# the mean training loss of each epoch, and the validation loss after it
step_losses = np.array([metrics["loss"] for _, metrics in history.train])
n_epochs = len(step_losses) // steps_per_epoch
epoch_losses = step_losses[: n_epochs * steps_per_epoch].reshape(n_epochs, -1)
val_losses = np.array([metrics["loss"] for _, metrics in history.eval])
return trained.module, {"train": epoch_losses.mean(axis=1), "val": val_losses}layer_keys = jr.split(data_key, 4)
layers = []
for layer_key in layer_keys:
bij_key, perm_key = jr.split(layer_key)
layers.append(
CircularRQSplineCoupling(
bij_key,
shape=(2,),
n_bins=12,
nn_width=64,
nn_depth=1,
)
)
layers.append(Permute(jr.permutation(perm_key, jnp.arange(2))))
bijection = Chain(layers).merge_chains()
base = Normal(jnp.zeros(2))
dist = Transformed(base, bijection)
trained_dist, losses = fit_flow(
data_key,
dist,
data,
learning_rate=5e-4,
max_epochs=150,
max_patience=10,
batch_size=256,
val_prop=0.1,
)loss_fig, loss_ax = plt.subplots(figsize=(6, 4))
epoch_axis = jnp.arange(len(losses["train"]))
loss_ax.plot(epoch_axis, losses["train"], label="train")
loss_ax.plot(epoch_axis, losses["val"], label="val")
loss_ax.set_xlabel("Epoch")
loss_ax.set_ylabel("Negative log-likelihood")
loss_ax.legend()
style_ax(loss_ax)
loss_ax.set_title("Training curve")
plt.show()
Sample from the trained circular flow¶
Samples respect angular topology: a shift leaves log-probability unchanged.
sample_key = jr.key(1)
flow_samples = trained_dist.sample(sample_key, (3000,))
fig, (ax_data, ax_flow) = plt.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True)
ax_data.scatter(data[:, 0], data[:, 1], **SCATTER_KW)
ax_data.set_title("Training data")
style_ax(ax_data)
ax_flow.scatter(flow_samples[:, 0], flow_samples[:, 1], **SCATTER_KW)
ax_flow.set_title("Flow samples")
style_ax(ax_flow)
for ax in (ax_data, ax_flow):
ax.set_xlabel(r"$\theta$")
ax.set_ylabel(r"$\phi$")
ax.set_xlim(-jnp.pi, jnp.pi)
ax.set_ylim(-jnp.pi, jnp.pi)
fig.tight_layout()
plt.show()