The first notebook trained a Gaussianization flow by stacking unconditional marginal layers (mixture CDF per dim) and rotations. The marginal layers can only Gaussianize each dimension independently; cross-dimensional structure is left entirely to the rotations.
A coupling layer (Real NVP, 2016) replaces that with a conditional transform. Given a split of the input dims:
Split with the identity half and the transformed half.
A conditioner network outputs the mixture parameters for each dimension in .
Apply the mixture-CDF Gaussianization to using those per-example parameters: .
Leave unchanged.
Since the Jacobian is lower triangular, the log-det is just the sum of per-b-dim diagonal contributions — same form as the unconditional marginal layer, but now the distribution of depends on , so cross-dimensional structure is learnt directly. We pair two coupling layers with swapped halves inside each block so both halves get transformed (the flowjax equivalent of the Keras [coupling(mask=m), coupling(mask=~m)] pair is [coupling, Flip, coupling, Flip]).
Mathematical structure¶
Notation and shapes¶
Throughout: batch dimension , input dimensionality , mixture components .
With the default half-split for we have dim passes through, dim gets transformed.
splits into and .
The bijector — GMM per b-dim¶
Each transformed dimension has its own per-example mixture of Gaussians,
and the per-b-dim forward is exactly the mixture-CDF Gaussianization from notebook 01 — the same primitive, only difference is that now depend on :
The per-example parameter tensors have shape .
The conditioner — a plain MLP¶
MixtureGaussianCDFCoupling wraps flowjax.bijections.Coupling with a default nn_width × nn_depth MLP conditioner whose final Dense is not zero-initialised by default. To reproduce the Keras flow’s “flow starts at identity” behavior you can use fit_rbig_coupling (notebook 03), which installs zero-kernel final Dense weights and a data-adapted bias — equivalent to a full-data IG init.
Log-scale clamp¶
Raw conditioner outputs for are passed through a bounded map before being exponentiated,
with default so . This keeps scales from blowing up or collapsing during training, especially when the conditioner is still warming up.
Jacobian of the coupling layer¶
With and , the Jacobian is block-triangular:
The lower-left off-diagonal depends on (the conditioner Jacobian) but that block doesn’t enter the determinant — only the diagonal of the bottom-right matters. Same diagonal-log-det structure as the unconditional layer.
Comparison to classical Real NVP (affine coupling)¶
Real NVP / Glow use an affine coupling,
Our layer uses a mixture-CDF coupling — strictly more expressive per-b-dim (can handle multimodal conditional distributions), same diagonal-Jacobian structure, same cost.
Half-swap pair per block¶
A single coupling layer only transforms one half. One block therefore uses two coupling layers with swapped halves ([coupling, Flip, coupling, Flip]) so both halves get touched. A Householder rotation at the start of each block mixes information across dims before the pair fires.
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 seaborn as sns
from flowjax.bijections import Chain, Flip, Invert, Scan
from flowjax.distributions import Normal, Transformed
import paramax
from pipekit_train import ArrayDataset, EarlyStopping, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from sklearn.datasets import make_moons
from gauss_flows_models.inference import negative_log_likelihood
from gauss_flows_maps.bijections import MixtureGaussianCDFCoupling
from gauss_flows_maps._src.transforms.bijections.linear.rotation import (
HouseholderRotation,
)
# --- global plot styling ------------------------------------------------------
sns.set_theme(context="poster", style="whitegrid", palette="deep", font_scale=0.85)
plt.rcParams.update(
{
"figure.dpi": 110,
"savefig.dpi": 110,
"savefig.bbox": "tight",
"savefig.pad_inches": 0.2,
"figure.constrained_layout.use": True,
"figure.constrained_layout.h_pad": 0.1,
"figure.constrained_layout.w_pad": 0.1,
"axes.grid.which": "both",
"grid.linewidth": 0.7,
"grid.alpha": 0.5,
"axes.edgecolor": "0.25",
"axes.linewidth": 1.1,
"axes.titleweight": "semibold",
"axes.labelpad": 6,
}
)
def style_axes(ax, *, aspect=None, grid=True):
if grid:
ax.minorticks_on()
ax.grid(True, which="major", linewidth=0.8, alpha=0.6)
ax.grid(True, which="minor", linewidth=0.4, alpha=0.3)
if aspect is not None:
ax.set_aspect(aspect)
return ax
def style_jointgrid(g, aspect="equal"):
style_axes(g.ax_joint, aspect=aspect)
style_axes(g.ax_marg_x, grid=False)
style_axes(g.ax_marg_y, grid=False)
for spine in ("top", "right"):
g.ax_marg_x.spines[spine].set_visible(False)
g.ax_marg_y.spines[spine].set_visible(False)
palette = sns.color_palette("deep")/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¶
Same two-moons dataset as in notebook 01 so the comparison is clean.
X_raw, _ = make_moons(n_samples=5000, noise=0.05, random_state=0)
X = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)
X = jnp.asarray(X, dtype=jnp.float32)
g = sns.jointplot(
x=np.asarray(X[:, 0]),
y=np.asarray(X[:, 1]),
kind="scatter",
color=palette[0],
height=7.5,
ratio=5,
space=0.1,
joint_kws={"s": 10, "alpha": 0.55},
marginal_kws={"bins": 50, "color": palette[0], "alpha": 0.75, "edgecolor": "white"},
)
g.set_axis_labels("$x_1$", "$x_2$")
g.figure.suptitle("Two moons (standardised)", y=1.02)
style_jointgrid(g)
plt.show()/home/azureuser/localfiles/geo_repos/geo_ml/gauss_flows-fit/.venv/lib/python3.13/site-packages/seaborn/axisgrid.py:1766: UserWarning: The figure layout has changed to tight
f.tight_layout()

2. Build a coupling flow¶
Each block is [HouseholderRotation, MixtureGaussianCDFCoupling, Flip, MixtureGaussianCDFCoupling, Flip]. The two coupling layers with complementary halves (separated by Flip) together transform all dimensions; the Householder rotation mixes the already-transformed state before the next block.
With d = 2 and the default half-split, the first coupling conditions on dim 0 and transforms dim 1, the Flip swaps dim order, the second coupling conditions on the ex-dim-1 (now first) and transforms the ex-dim-0 (now second), and the trailing Flip restores dim order so the next block’s rotation sees the expected orientation.
key = jr.key(0)
flow_key, train_key, sample_key = jr.split(key, 3)
n_blocks = 4
n_components = 8
nn_width = 64
nn_depth = 2
n_dims = 2
def make_block(k):
rot_key, coup1_key, coup2_key = jr.split(k, 3)
rot = HouseholderRotation(n_reflections=n_dims, shape=(n_dims,))
rot = eqx.tree_at(lambda r: r.params, rot, jr.normal(rot_key, rot.params.shape))
coup1 = MixtureGaussianCDFCoupling(
coup1_key,
shape=(n_dims,),
n_components=n_components,
nn_width=nn_width,
nn_depth=nn_depth,
)
coup2 = MixtureGaussianCDFCoupling(
coup2_key,
shape=(n_dims,),
n_components=n_components,
nn_width=nn_width,
nn_depth=nn_depth,
)
flip = Flip(shape=(n_dims,))
return Chain([rot, coup1, flip, coup2, flip])
blocks = eqx.filter_vmap(make_block)(jr.split(flow_key, n_blocks))
bijection = Invert(Scan(blocks))
base = Normal(jnp.zeros(n_dims))
flow = Transformed(base, bijection)
n_params = sum(
int(np.prod(p.shape))
for p in jax.tree_util.tree_leaves(eqx.filter(flow, eqx.is_inexact_array))
)
print(f"blocks : {n_blocks}")
print(f"sub-bijections per block : 5 (rot, coupling, flip, coupling, flip)")
print(f"mixture components / dim : {n_components}")
print(f"total inexact-array params: {n_params}")blocks : 4
sub-bijections per block : 5 (rot, coupling, flip, coupling, flip)
mixture components / dim : 8
total inexact-array params: 46804
3. Train¶
Same training recipe as the marginal-only flow (Adam on gauss_flows’s NLL in a pipekit-train TrainingLoop, through the fit_flow of notebook 01, 200 epochs), so differences in the final density/pushforward are attributable to the coupling architecture.
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}trained, losses = fit_flow(
train_key,
flow,
X,
learning_rate=2e-3,
max_epochs=200,
max_patience=20,
batch_size=256,
val_prop=0.1,
)
train_loss = np.asarray(losses["train"])
val_loss = np.asarray(losses["val"])
fig, axes = plt.subplots(1, 2, figsize=(17, 6.5))
c = palette[0]
ax = axes[0]
ax.plot(train_loss, color=c, linewidth=2.2, label="train")
ax.plot(val_loss, color=palette[3], linewidth=2.2, alpha=0.85, label="val")
ax.set_xlabel("epoch")
ax.set_ylabel(r"training loss $(-\log p_X + \text{const})$")
ax.set_title("Full training curve")
ax.legend(frameon=False)
style_axes(ax)
ax = axes[1]
tail_start = 20
tail_t = train_loss[tail_start:]
tail_v = val_loss[tail_start:]
ax.plot(
range(tail_start, len(train_loss)), tail_t, color=c, linewidth=2.2, label="train"
)
ax.plot(
range(tail_start, len(val_loss)),
tail_v,
color=palette[3],
linewidth=2.2,
alpha=0.85,
label="val",
)
lo = min(tail_t.min(), tail_v.min())
hi = max(tail_t.max(), tail_v.max())
span = hi - lo
ax.set_ylim(lo - 0.05 * span, hi + 0.05 * span)
ax.set_xlabel("epoch")
ax.set_ylabel("loss")
ax.set_title(f"Zoomed (epochs $\\geq$ {tail_start})")
ax.legend(frameon=False)
style_axes(ax)
plt.show()
print(f"final train NLL: {train_loss[-1]:+.4f} (min: {train_loss.min():+.4f})")
print(f"final val NLL: {val_loss[-1]:+.4f} (min: {val_loss.min():+.4f})")WARNING:matplotlib.font_manager:findfont: Failed to find font weight semibold for DejaVu Sans, now using 700.
WARNING:matplotlib.font_manager:findfont: Failed to find font weight semibold for DejaVu Sans, now using 700.

final train NLL: +1.1813 (min: +1.1744)
final val NLL: +1.2097 (min: +1.1608)
4. Pushforward and density¶
The pushforward should be approximately . A jointplot puts the 2-D scatter next to the per-dim marginals; the black reference curves are .
Unlike a marginal-only flow, here the conditioner can express the cross-dim dependence exactly (each is conditional on ) — the density contour in -space should trace the two moons sharply.
z = np.asarray(jax.vmap(trained.bijection.inverse)(X))
mean_z = z.mean(axis=0)
cov_z = np.cov(z, rowvar=False)
print("pushforward diagnostics")
print(f" mean: [{mean_z[0]:+.3f}, {mean_z[1]:+.3f}] target = [0, 0]")
print(f" cov[0,0]: {cov_z[0, 0]:.3f} target = 1")
print(f" cov[1,1]: {cov_z[1, 1]:.3f} target = 1")
print(f" cov[0,1]: {cov_z[0, 1]:+.3f} target = 0")
g = sns.jointplot(
x=z[:, 0],
y=z[:, 1],
kind="scatter",
color=palette[1],
height=7.5,
ratio=5,
space=0.1,
joint_kws={"s": 10, "alpha": 0.55},
marginal_kws={
"bins": 60,
"color": palette[1],
"alpha": 0.75,
"edgecolor": "white",
"stat": "density",
},
xlim=(-4, 4),
ylim=(-4, 4),
)
zz = np.linspace(-4, 4, 300)
phi = np.exp(-0.5 * zz**2) / np.sqrt(2 * np.pi)
g.ax_marg_x.plot(zz, phi, color="black", linewidth=2.0, label=r"$\mathcal{N}(0, 1)$")
g.ax_marg_y.plot(phi, zz, color="black", linewidth=2.0)
g.ax_marg_x.legend(loc="upper left", frameon=False, fontsize=11)
g.set_axis_labels("$z_1$", "$z_2$")
g.figure.suptitle(r"Pushforward $z = f(x)$", y=1.02)
style_jointgrid(g)
plt.show()pushforward diagnostics
mean: [+0.187, +0.070] target = [0, 0]
cov[0,0]: 0.866 target = 1
cov[1,1]: 1.378 target = 1
cov[0,1]: -0.071 target = 0
/home/azureuser/localfiles/geo_repos/geo_ml/gauss_flows-fit/.venv/lib/python3.13/site-packages/seaborn/axisgrid.py:1766: UserWarning: The figure layout has changed to tight
f.tight_layout()

grid = 220
xs = np.linspace(-2.5, 2.5, grid).astype("float32")
ys = np.linspace(-2.5, 2.5, grid).astype("float32")
xx, yy = np.meshgrid(xs, ys)
pts = np.stack([xx.ravel(), yy.ravel()], axis=-1).astype("float32")
log_px = np.asarray(jax.vmap(trained.log_prob)(jnp.asarray(pts))).reshape(grid, grid)
fig, axes = plt.subplots(1, 2, figsize=(17, 7.5))
ax = axes[0]
pcm = ax.pcolormesh(xx, yy, np.exp(log_px), cmap="magma", shading="auto")
ax.scatter(
np.asarray(X[:1000, 0]), np.asarray(X[:1000, 1]), s=2, alpha=0.25, color="white"
)
ax.set_title("Density $p_X(x)$")
ax.set_xlabel("$x_1$")
ax.set_ylabel("$x_2$")
style_axes(ax, aspect="equal")
fig.colorbar(pcm, ax=ax, shrink=0.85)
ax = axes[1]
pcm = ax.pcolormesh(xx, yy, np.clip(log_px, -10, None), cmap="viridis", shading="auto")
ax.scatter(
np.asarray(X[:1000, 0]), np.asarray(X[:1000, 1]), s=2, alpha=0.25, color="white"
)
ax.set_title(r"Log-density $\log p_X(x)$")
ax.set_xlabel("$x_1$")
ax.set_ylabel("$x_2$")
style_axes(ax, aspect="equal")
fig.colorbar(pcm, ax=ax, shrink=0.85)
plt.show()
5. Sampling from the flow¶
. Each coupling layer’s inverse bisects per b-dim via optimistix.Bisection, with preserved through the layer so the conditioner sees the same input in both directions.
samples = np.asarray(trained.sample(sample_key, (5000,)))
for data, title, col in [
(np.asarray(X), "Data", palette[0]),
(samples, r"Samples $x = f^{-1}(z), \; z \sim \mathcal{N}(0, I)$", palette[2]),
]:
g = sns.jointplot(
x=data[:, 0],
y=data[:, 1],
kind="scatter",
color=col,
height=7.5,
ratio=5,
space=0.1,
joint_kws={"s": 10, "alpha": 0.55},
marginal_kws={
"bins": 50,
"color": col,
"alpha": 0.75,
"edgecolor": "white",
},
xlim=(-2.5, 2.5),
ylim=(-2.5, 2.5),
)
g.set_axis_labels("$x_1$", "$x_2$")
g.figure.suptitle(title, y=1.02)
style_jointgrid(g)
plt.show()/home/azureuser/localfiles/geo_repos/geo_ml/gauss_flows-fit/.venv/lib/python3.13/site-packages/seaborn/axisgrid.py:1766: UserWarning: The figure layout has changed to tight
f.tight_layout()

/home/azureuser/localfiles/geo_repos/geo_ml/gauss_flows-fit/.venv/lib/python3.13/site-packages/seaborn/axisgrid.py:1766: UserWarning: The figure layout has changed to tight
f.tight_layout()

6. Round-trip inversion¶
Each coupling layer is a bijection by construction, so should recover to numerical precision. The inverse uses optimistix.Bisection on the mixture CDF; small tails from the -clamp on are the only residual error.
z_fwd = jax.vmap(trained.bijection.inverse)(X)
x_rt = jax.vmap(trained.bijection.transform)(z_fwd)
err = np.asarray(jnp.linalg.norm(x_rt - X, axis=-1))
print(r"round-trip L2 error ||f^{-1}(f(x)) - x||_2")
print(f" median : {np.median(err):.2e}")
print(f" 95th% : {np.percentile(err, 95):.2e}")
print(f" max : {err.max():.2e}")
fig, ax = plt.subplots(figsize=(10, 5.5))
ax.hist(
np.log10(err + 1e-12),
bins=50,
color=palette[3],
alpha=0.85,
edgecolor="white",
linewidth=0.5,
)
ax.set_xlabel(r"$\log_{10}$ round-trip error")
ax.set_ylabel("count")
ax.set_title("Round-trip error distribution")
style_axes(ax)
plt.show()round-trip L2 error ||f^{-1}(f(x)) - x||_2
median : 1.55e-06
95th% : 5.03e-06
max : 6.95e-04

7. Layer-by-layer view¶
States . Each coupling layer transforms one half while keeping the other intact (you can see the passthrough half pinned, the other half morphing). Rotations remix the state between coupling pairs, and the flips swap which half is transformed inside a block.
# Each "block" is Chain([rot, coup1, flip, coup2, flip]) with vmapped leaves.
scan_chain = trained.bijection.bijection.bijection # Invert → Scan → Chain
X_small = X[:2000]
states = [np.asarray(X_small)]
state = X_small
# Chain.bijections is a tuple of the 5 sub-bijections, each with vmapped leaves.
sub_names = ["rot", "coup₁", "flip", "coup₂", "flip"]
titles = []
for block_idx in range(n_blocks):
for sub_idx, name in enumerate(sub_names):
sub = jax.tree_util.tree_map(
lambda p, _b=block_idx: (
p[_b]
if isinstance(p, jax.Array) and p.ndim > 0 and p.shape[0] == n_blocks
else p
),
scan_chain.bijections[sub_idx],
)
state = jax.vmap(lambda s: sub.transform_and_log_det(s)[0])(state)
states.append(np.asarray(state))
titles.append(f"block {block_idx + 1}: {name}")
n_states = len(states)
ncol = 4
nrow = int(np.ceil(n_states / ncol))
fig, axes = plt.subplots(nrow, ncol, figsize=(4.5 * ncol, 4.5 * nrow))
axes = axes.ravel()
for i, (s, ax) in enumerate(zip(states, axes)):
ax.scatter(s[:, 0], s[:, 1], s=5, alpha=0.6, color=palette[0])
lim = 3.4 if i > 0 else 2.8
ax.set_xlim(-lim, lim)
ax.set_ylim(-lim, lim)
if i == 0:
ax.set_title("input $x$")
elif i == n_states - 1:
ax.set_title("output $z$")
else:
ax.set_title(titles[i - 1])
style_axes(ax, aspect="equal")
for ax in axes[n_states:]:
ax.axis("off")
plt.show()
Recap¶
Coupling = one half conditions, the other is transformed. Half-swap via
Flipinside the same block so both halves get touched.The same mixture-CDF primitive drives both the unconditional marginal layer (notebook 01) and this layer — only difference is that the params now come from a network output instead of a learned per-dim lookup.
Zero-kernel initialisation (via
fit_rbig_couplingin notebook 03) makes training warm-start from a data-adapted RBIG state instead of random.The flowjax coupling’s conditioner is a standard MLP; for 2D data with only one b-dim per coupling the “per-dim” vs “shared-mixture” distinction collapses, and there’s no reason to use anything other than the default MLP. See the research_notebook for higher-dim experiments where this matters.