Notebooks 01 and 02 trained Gaussianization / coupling flows from random initialisation. That works, but spends the first hundreds of epochs pulling the flow from a near-identity map towards the data.
Iterative Gaussianization (RBIG — Laparra & Malo 2011) is a non-gradient, greedy procedure that warm-starts the flow by walking block-by-block through the architecture and fitting each block’s parameters directly:
Rotation block — fit PCA on the current state ; push the eigenvectors into the rotation layer.
Marginal block — fit a per-dim mixture-of-Gaussians on the rotated data with scikit-learn’s
GaussianMixture, and assign directly into theMixtureGaussianCDFlayer weights.Coupling block — fit a per-b-dim GMM on the current ; zero the conditioner’s final Dense kernel and set its bias to the flattened GMM params. At initialisation the conditioner output is constant-in-, so the coupling layer acts like a diagonal marginal with the fitted mixture. Gradient training then lets the conditioner learn to modulate on .
Between blocks the current is propagated forward through the newly-parameterised bijector, so the next block sees data that has already been partially Gaussianized. A classical result (Laparra & Malo 2011, Chen & Gopinath 2000) is that this drives towards at a geometric rate — even with no gradient descent at all, the flow is already a decent density estimator after a handful of blocks.
The point of this notebook: a flow initialised this way starts at a much lower NLL than random init and reaches its training optimum in a fraction of the epochs.
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
import seaborn as sns
from flowjax.bijections import Chain, Flip, Invert, Scan
from flowjax.distributions import Normal, Transformed
from pipekit_train import ArrayDataset, EarlyStopping, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from sklearn.datasets import make_moons
from gauss_flows_maps.bijections import MixtureGaussianCDFCoupling
from gauss_flows_models.inference import (
fit_rbig,
fit_rbig_coupling,
negative_log_likelihood,
)
from gauss_flows_models.flows import gaussianization_flow
from gauss_flows_maps._src.transforms.bijections.coupling.mixture_cdf import (
MixtureGaussianCDFCoupling as _CouplingClass,
)
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")
COLOR_RANDOM = palette[3]
COLOR_IG = palette[2]/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¶
Two moons, standardised. Same data as notebooks 01/02 so the comparison is apples-to-apples.
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)2. Diagonal flow — random vs IG init¶
Build two identical diagonal flows, warm-start one of them from IG (fit_rbig), and train both with the same optimiser and schedule.
N_BLOCKS_DIAG = 8
N_COMPONENTS = 8
flow_random = gaussianization_flow(
jr.key(1),
n_dims=2,
n_layers=N_BLOCKS_DIAG,
n_components=N_COMPONENTS,
n_reflections=2,
)
flow_ig = fit_rbig(X, n_layers=N_BLOCKS_DIAG, n_components=N_COMPONENTS, random_state=0)Before any training: what did IG init already buy us?¶
RBIG on its own produces a density estimate. Below we compare the mean log-likelihood (per sample) of the IG-initialised flow against the random-init flow, both before a single gradient step.
lp_random0 = float(jax.vmap(flow_random.log_prob)(X).mean())
lp_ig0 = float(jax.vmap(flow_ig.log_prob)(X).mean())
print("mean log-likelihood before training:")
print(f" random init : {lp_random0:+.3f} nats/sample")
print(
f" IG init : {lp_ig0:+.3f} nats/sample "
f"(improvement: {lp_ig0 - lp_random0:+.3f})"
)mean log-likelihood before training:
random init : -14.324 nats/sample
IG init : -1.733 nats/sample (improvement: +12.590)
Pushforward at IG-init time¶
With no gradient training whatsoever, the pushforward of the IG-initialised flow should already be approximately . Jointplots make this immediately visible — the IG scatter should look isotropic and the marginals should line up with the black curves, while the random-init pushforward won’t.
z_ig0 = np.asarray(jax.vmap(flow_ig.bijection.inverse)(X))
z_rnd0 = np.asarray(jax.vmap(flow_random.bijection.inverse)(X))
zz = np.linspace(-4, 4, 300)
phi = np.exp(-0.5 * zz**2) / np.sqrt(2 * np.pi)
for z_sample, title, col in [
(z_rnd0, r"Random init $z = f(x)$ (no training)", COLOR_RANDOM),
(z_ig0, r"IG init $z = f(x)$ (no training)", COLOR_IG),
]:
g = sns.jointplot(
x=z_sample[:, 0],
y=z_sample[:, 1],
kind="scatter",
color=col,
height=7.5,
ratio=5,
space=0.1,
joint_kws={"s": 10, "alpha": 0.55},
marginal_kws={
"bins": 60,
"color": col,
"alpha": 0.75,
"edgecolor": "white",
"stat": "density",
},
xlim=(-4, 4),
ylim=(-4, 4),
)
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(title, y=1.02)
style_jointgrid(g)
plt.show()
mean_ig0 = z_ig0.mean(axis=0)
cov_ig0 = np.cov(z_ig0, rowvar=False)
print("IG-init pushforward (pre-training)")
print(f" mean: [{mean_ig0[0]:+.3f}, {mean_ig0[1]:+.3f}] target = [0, 0]")
print(
f" cov[0,0]:{cov_ig0[0, 0]:.3f} cov[1,1]:{cov_ig0[1, 1]:.3f} target = 1, 1"
)
print(f" cov[0,1]:{cov_ig0[0, 1]:+.3f} 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()

/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()

IG-init pushforward (pre-training)
mean: [+0.000, -0.000] target = [0, 0]
cov[0,0]:1.001 cov[1,1]:1.004 target = 1, 1
cov[0,1]:-0.008 target = 0
Samples at init (no training)¶
The pushforward picture above checks for the given training points. The more direct “is the flow already usable?” question is: sample , push through the inverse , and see whether the output looks like the training distribution. For IG init the answer should be “yes, roughly two-moons-shaped already”; for random init the answer is “no — the flow is essentially an arbitrary rotation of the base distribution”.
init_samples_rnd = np.asarray(flow_random.sample(jr.key(5), (3000,)))
init_samples_ig = np.asarray(flow_ig.sample(jr.key(5), (3000,)))
for s, title, col in [
(init_samples_rnd, "Random init — samples (no training)", COLOR_RANDOM),
(init_samples_ig, "IG init — samples (no training)", COLOR_IG),
]:
g = sns.jointplot(
x=s[:, 0],
y=s[:, 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()

Training comparison¶
Both flows, same optimiser, same 150 epochs. The IG curve starts at (and finishes near) the random curve’s final value — the zoomed panel on the right makes the small end-of-training gap legible.
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_random, losses_random = fit_flow(
jr.key(10),
flow_random,
X,
learning_rate=5e-3,
max_epochs=150,
max_patience=150,
batch_size=512,
val_prop=0.1,
)
trained_ig, losses_ig = fit_flow(
jr.key(11),
flow_ig,
X,
learning_rate=5e-3,
max_epochs=150,
max_patience=150,
batch_size=512,
val_prop=0.1,
)
rnd_curve = np.asarray(losses_random["train"])
ig_curve = np.asarray(losses_ig["train"])
fig, axes = plt.subplots(1, 2, figsize=(17, 6.5))
ax = axes[0]
ax.plot(rnd_curve, label="random init", color=COLOR_RANDOM, linewidth=2.2)
ax.plot(ig_curve, label="IG init", color=COLOR_IG, linewidth=2.2)
ax.set_xlabel("epoch")
ax.set_ylabel(r"training loss $(-\log p_X + \text{const})$")
ax.set_title("Diagonal flow — full")
ax.legend(frameon=True)
style_axes(ax)
ax = axes[1]
tail_start = 15
tail_rnd = rnd_curve[tail_start:]
tail_ig = ig_curve[tail_start:]
both = np.concatenate([tail_rnd, tail_ig])
span = both.max() - both.min()
ax.plot(
range(tail_start, len(rnd_curve)),
tail_rnd,
label="random init",
color=COLOR_RANDOM,
linewidth=2.2,
)
ax.plot(
range(tail_start, len(ig_curve)),
tail_ig,
label="IG init",
color=COLOR_IG,
linewidth=2.2,
)
ax.set_ylim(both.min() - 0.05 * span, both.max() + 0.05 * span)
ax.set_xlabel("epoch")
ax.set_ylabel("loss")
ax.set_title(rf"Zoomed (epochs $\geq$ {tail_start})")
ax.legend(frameon=True)
style_axes(ax)
plt.show()
print(
f"final loss: random init = {rnd_curve[-1]:+.3f} IG init = {ig_curve[-1]:+.3f}"
)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 loss: random init = +1.388 IG init = +1.154
Density and samples after training¶
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_rnd = np.asarray(jax.vmap(trained_random.log_prob)(jnp.asarray(pts))).reshape(
grid, grid
)
log_px_ig = np.asarray(jax.vmap(trained_ig.log_prob)(jnp.asarray(pts))).reshape(
grid, grid
)
fig, axes = plt.subplots(1, 2, figsize=(17, 7.5))
for ax, lp, title in zip(
axes, [log_px_rnd, log_px_ig], ["Random init — density", "IG init — density"]
):
pcm = ax.pcolormesh(xx, yy, np.exp(lp), cmap="magma", shading="auto")
ax.scatter(
np.asarray(X[:800, 0]), np.asarray(X[:800, 1]), s=2, alpha=0.25, color="white"
)
ax.set_title(title)
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()
samples_rnd = np.asarray(trained_random.sample(jr.key(2), (3000,)))
samples_ig = np.asarray(trained_ig.sample(jr.key(2), (3000,)))
for s, title, col in [
(samples_rnd, "Random init — samples", COLOR_RANDOM),
(samples_ig, "IG init — samples", COLOR_IG),
]:
g = sns.jointplot(
x=s[:, 0],
y=s[:, 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()

3. Coupling flow — random vs IG init¶
Same experiment with a coupling flow. IG init for coupling layers is weaker in isolation (the conditioner is not exercised at init — it emits a constant bias), but it still lets training skip the “the conditioner is effectively random, so the coupling transform is random” phase by handing it a sensible starting point where the conditioner behaves as a well-fit diagonal marginal.
N_BLOCKS_CPL = 4
NN_WIDTH = 64
NN_DEPTH = 2
def _build_random_coupling_flow(key, n_blocks, n_components):
"""Build a MixtureGaussianCDFCoupling flow with the same architecture as
``fit_rbig_coupling`` but random init (no IG warm-start)."""
def make_block(k):
rk, ck1, ck2 = jr.split(k, 3)
rot = HouseholderRotation(n_reflections=2, shape=(2,))
rot = eqx.tree_at(lambda r: r.params, rot, jr.normal(rk, rot.params.shape))
c1 = MixtureGaussianCDFCoupling(
ck1,
shape=(2,),
n_components=n_components,
nn_width=NN_WIDTH,
nn_depth=NN_DEPTH,
)
c2 = MixtureGaussianCDFCoupling(
ck2,
shape=(2,),
n_components=n_components,
nn_width=NN_WIDTH,
nn_depth=NN_DEPTH,
)
flip = Flip(shape=(2,))
return Chain([rot, c1, flip, c2, flip])
blocks = eqx.filter_vmap(make_block)(jr.split(key, n_blocks))
bijection = Invert(Scan(blocks))
return Transformed(Normal(jnp.zeros(2)), bijection)
cpl_random = _build_random_coupling_flow(
jr.key(3), n_blocks=N_BLOCKS_CPL, n_components=N_COMPONENTS
)
cpl_ig = fit_rbig_coupling(
X,
jr.key(3),
n_layers=N_BLOCKS_CPL,
n_components=N_COMPONENTS,
nn_width=NN_WIDTH,
nn_depth=NN_DEPTH,
)
lp_crnd0 = float(jax.vmap(cpl_random.log_prob)(X).mean())
lp_cig0 = float(jax.vmap(cpl_ig.log_prob)(X).mean())
print("mean log-likelihood before training (coupling flow):")
print(f" random init : {lp_crnd0:+.3f} nats/sample")
print(
f" IG init : {lp_cig0:+.3f} nats/sample "
f"(improvement: {lp_cig0 - lp_crnd0:+.3f})"
)mean log-likelihood before training (coupling flow):
random init : -2.838 nats/sample
IG init : -1.821 nats/sample (improvement: +1.017)
Coupling samples at init (no training)¶
Same sanity check for the coupling flow. IG-init coupling samples should already look moon-ish; random-init coupling samples are whatever a random MLP conditioner does to a sample.
init_csamples_rnd = np.asarray(cpl_random.sample(jr.key(6), (3000,)))
init_csamples_ig = np.asarray(cpl_ig.sample(jr.key(6), (3000,)))
for s, title, col in [
(init_csamples_rnd, "Coupling random init — samples (no training)", COLOR_RANDOM),
(init_csamples_ig, "Coupling IG init — samples (no training)", COLOR_IG),
]:
g = sns.jointplot(
x=s[:, 0],
y=s[:, 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()

Training comparison for the coupling flow¶
trained_crnd, losses_crnd = fit_flow(
jr.key(20),
cpl_random,
X,
learning_rate=3e-3,
max_epochs=100,
max_patience=100,
batch_size=512,
val_prop=0.1,
)
trained_cig, losses_cig = fit_flow(
jr.key(21),
cpl_ig,
X,
learning_rate=3e-3,
max_epochs=100,
max_patience=100,
batch_size=512,
val_prop=0.1,
)
crnd_curve = np.asarray(losses_crnd["train"])
cig_curve = np.asarray(losses_cig["train"])
fig, axes = plt.subplots(1, 2, figsize=(17, 6.5))
ax = axes[0]
ax.plot(crnd_curve, label="random init", color=COLOR_RANDOM, linewidth=2.2)
ax.plot(cig_curve, label="IG init", color=COLOR_IG, linewidth=2.2)
ax.set_xlabel("epoch")
ax.set_ylabel(r"training loss $(-\log p_X + \text{const})$")
ax.set_title("Coupling flow — full")
ax.legend(frameon=True)
style_axes(ax)
ax = axes[1]
tail_start = 10
tail_rnd = crnd_curve[tail_start:]
tail_ig = cig_curve[tail_start:]
both = np.concatenate([tail_rnd, tail_ig])
span = both.max() - both.min()
ax.plot(
range(tail_start, len(crnd_curve)),
tail_rnd,
label="random init",
color=COLOR_RANDOM,
linewidth=2.2,
)
ax.plot(
range(tail_start, len(cig_curve)),
tail_ig,
label="IG init",
color=COLOR_IG,
linewidth=2.2,
)
ax.set_ylim(both.min() - 0.05 * span, both.max() + 0.05 * span)
ax.set_xlabel("epoch")
ax.set_ylabel("loss")
ax.set_title(rf"Zoomed (epochs $\geq$ {tail_start})")
ax.legend(frameon=True)
style_axes(ax)
plt.show()
print(
f"final loss: random init = {crnd_curve[-1]:+.3f} IG init = {cig_curve[-1]:+.3f}"
)
final loss: random init = +1.842 IG init = +1.106
Coupling density and samples after training¶
log_px_crnd = np.asarray(jax.vmap(trained_crnd.log_prob)(jnp.asarray(pts))).reshape(
grid, grid
)
log_px_cig = np.asarray(jax.vmap(trained_cig.log_prob)(jnp.asarray(pts))).reshape(
grid, grid
)
fig, axes = plt.subplots(1, 2, figsize=(17, 7.5))
for ax, lp, title in zip(
axes,
[log_px_crnd, log_px_cig],
["Coupling — random init", "Coupling — IG init"],
):
pcm = ax.pcolormesh(xx, yy, np.exp(lp), cmap="magma", shading="auto")
ax.scatter(
np.asarray(X[:800, 0]), np.asarray(X[:800, 1]), s=2, alpha=0.25, color="white"
)
ax.set_title(title)
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()
csamples_rnd = np.asarray(trained_crnd.sample(jr.key(4), (3000,)))
csamples_ig = np.asarray(trained_cig.sample(jr.key(4), (3000,)))
for s, title, col in [
(csamples_rnd, "Coupling random init — samples", COLOR_RANDOM),
(csamples_ig, "Coupling IG init — samples", COLOR_IG),
]:
g = sns.jointplot(
x=s[:, 0],
y=s[:, 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()

4. Verifying the zero-kernel contract¶
Immediately after fit_rbig_coupling every MixtureGaussianCDFCoupling’s final Dense has a zero kernel (so the conditioner emits its bias for any input — the coupling layer behaves as a diagonal marginal on its b-half). During gradient training those kernels become non-zero as the conditioner learns to modulate on . Below: build a fresh coupling flow, IG-init it, check the kernels before any training, then train briefly and check again. Notebook 04 proves the full-flow equivalence.
def max_final_kernel(flow):
"""Return max|W| of every coupling's conditioner final Dense."""
out = []
chain = flow.bijection.bijection # Invert → Chain
for bij in chain.bijections:
if isinstance(bij, _CouplingClass):
final = bij._coupling.conditioner.layers[-1]
out.append(float(jnp.max(jnp.abs(final.weight))))
return out
cpl_probe = fit_rbig_coupling(
X,
jr.key(42),
n_layers=N_BLOCKS_CPL,
n_components=N_COMPONENTS,
nn_width=NN_WIDTH,
nn_depth=NN_DEPTH,
)
kernels_post_ig = max_final_kernel(cpl_probe)
print(
f"right after IG init (no train): max|W| per coupling = "
f"{[f'{k:.1e}' for k in kernels_post_ig]}"
)
print(f"all zero after IG init : {all(k < 1e-6 for k in kernels_post_ig)}")
probe_trained, _ = fit_flow(
jr.key(43),
cpl_probe,
X,
learning_rate=3e-3,
max_epochs=20,
max_patience=20,
batch_size=512,
val_prop=0.1,
)
kernels_after_train = max_final_kernel(probe_trained)
print(
f"after 20 epochs of training: max|W| per coupling = "
f"{[f'{k:.3f}' for k in kernels_after_train]}"
)
print("(non-zero is expected — the conditioner has started to modulate on x_a)")right after IG init (no train): max|W| per coupling = ['0.0e+00', '0.0e+00', '0.0e+00', '0.0e+00', '0.0e+00', '0.0e+00', '0.0e+00', '0.0e+00']
all zero after IG init : True
after 20 epochs of training: max|W| per coupling = ['0.085', '0.165', '0.104', '0.114', '0.170', '0.110', '0.104', '0.098']
(non-zero is expected — the conditioner has started to modulate on x_a)
Recap¶
RBIG (Laparra & Malo 2011) is a non-gradient greedy warm-start that fits each block’s parameters in sequence (PCA for rotation, sklearn
GaussianMixtureper dim for marginal/coupling) and propagates the data forward.For the diagonal flow the init is exact: the layer’s parameters are exactly the GMM fit, and the pre-training pushforward is already near .
For the coupling flow the conditioner’s inner Dense weights stay random, but the final Dense is forced to kernel=0, bias = fitted mixture params. So at init the coupling layer behaves like a diagonal marginal layer with the IG-fitted mixture; gradient training then lets the conditioner become genuinely conditional.
End result in both cases: lower starting NLL, faster convergence, and fewer chances for the optimiser to get stuck in a bad local minimum.