gauss_flows lets you make a flow conditional in three distinct places — the base distribution, the coupling layers, or both — with one consistent API: a single condition keyword that threads through SurVAEFlow.log_prob(...) and SurVAEFlow.sample(...). This notebook walks through the math of each variant, then shows the four resulting fits side by side on the two-moons dataset from notebook 01 (gaussianization_flow_2d).
We use the class label that notebook 01 discards (_, y = make_moons(...)) as the conditional context . make_moons returns indicating which crescent each point belongs to, so is the upper moon and is the lower moon — two well-separated, single-crescent conditional densities, well within RQSplineCoupling capacity.
0. Math primer — conditional normalizing flows¶
A normalizing flow defines a density on via an invertible map pulling samples back to a tractable base distribution :
For a chain with intermediate states , :
To make this conditional on a context , any of the three pieces — the base , the maps , or both — can be made functions of . The general conditional flow density is
The four variants in this notebook correspond to which factors are functions of :
| Variant | Density |
|---|---|
| None | $p_X(x) = p_Z!\big(f_\theta(x)\big),\big |
| Base only | $p_X(x \mid c) = p_Z!\big(f_\theta(x) ,\big |
| Coupling only | $p_X(x \mid c) = p_Z!\big(f_\theta(x; c)\big),\big |
| Both | $p_X(x \mid c) = p_Z!\big(f_\theta(x; c) ,\big |
Conditional base — ConditionalDiagGaussian¶
A diagonal Gaussian whose location and log-scale are functions of :
where is a small MLP. Closed-form log-density:
This handles per-class shifts: if the only thing that varies with is the position of the mode, the conditional base alone is enough.
Conditional coupling — RQSplineCoupling(cond_dim=...)¶
A coupling layer splits on a binary mask. The “passthrough” half is left alone; the “active” half goes through an elementwise transformer whose parameters are produced by a conditioner MLP that already takes as input. Adding cond_dim > 0 simply concatenates the external context to that input:
For an RQSplineCoupling, is a rational-quadratic spline whose knot positions and slopes come from . The Jacobian is triangular by construction, so
This handles per-class shape warps: the spline knots can move with , producing genuinely class-specific maps.
How the package routes condition¶
Each layer (and the base) declares whether it is conditional via a static attribute cond_shape:
cond_shape is None→ unconditional layer; the layer ignores anyconditionargument it receives.cond_shape == (D_c,)→ conditional layer; it expects a context of that shape.
SurVAEFlow.log_prob(x, key, condition=c) (and .sample(key, condition=c)) takes a single c and broadcasts it to every opted-in layer. There is no per-layer condition kwarg — you build the chain, decide for each layer whether it should look at via cond_dim=..., and the same flows through. flowjax’s _check_condition decorator raises if you forget to pass a context to a conditional layer.
For class-conditional density estimation specifically, ClassCondFlow(n_classes=..., event_shape=..., transforms=[...]) is sugar for “conditional base + unconditional transforms” with a label kwarg in place of condition. We don’t use it here because we want to expose all four variants explicitly.
For transforms that genuinely cannot take a context (rotations, normalizations, etc.), wrap them in Conditioner(key, inner=..., cond_dim=D_c) to add a FiLM-style affine modulation around the inner transform:
where comes from the shared AffineModulation and for a positive scale map (scale_map, by default). Its readout starts at zero, so and and the wrapper starts as itself for every .
1. Configurations under test¶
We compare four configurations under identical hyperparameters:
None (baseline = notebook 01’s setup): a fixed base + unconditional
RQSplineCouplingchain. The flow ignores entirely and fits the marginal — the full two-moons. Useful as a sanity check; reproduces notebook 01’s fit quality.Base only: a
ConditionalDiagGaussianbase whose come from the one-hot , paired with the same unconditionalRQSplineCouplingchain. The base shifts per class but the chain learns one shared crescent shape.Coupling only: a fixed base, paired with
RQSplineCoupling(cond_dim=2)layers that read the one-hot . The couplings learn class-specific shapes; class-specific shift has to be absorbed through the spline parameters — awkward, but doable for two-moons.Both: conditional base and conditional couplings — the same one-hot label flows to both. Full capacity.
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 Permute
from flowjax.distributions import Normal
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_models.distributions import ConditionalDiagGaussian
from gauss_flows_maps.bijections import RQSplineCoupling
from gauss_flows_models.flows import SurVAEFlow
# --- global plot styling (matches docs/notebooks/01_gaussianization_flow_2d) ----
sns.set_theme(context="poster", style="whitegrid", palette="deep", font_scale=0.85)
plt.rcParams.update(
{
"figure.dpi": 110,
"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
2. Data¶
Same make_moons(...) call as notebook 01 — 5000 points standardised to zero mean and unit variance — but we keep the class label and one-hot encode it as the context . Each crescent has points.
X_raw, y = 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)
C = jax.nn.one_hot(jnp.asarray(y, dtype=jnp.int32), num_classes=2)
print(f"X.shape={X.shape}, C.shape={C.shape}")
print(f"counts per class: y=0 -> {int((y == 0).sum())}, y=1 -> {int((y == 1).sum())}")X.shape=(5000, 2), C.shape=(5000, 2)
counts per class: y=0 -> 2500, y=1 -> 2500
# Show the marginal as a jointplot (matches notebook 01's data overview),
# colour-coded by class so the conditional structure is obvious.
g = sns.jointplot(
x=np.asarray(X[:, 0]),
y=np.asarray(X[:, 1]),
hue=np.asarray(y),
palette={0: palette[0], 1: palette[3]},
kind="scatter",
height=6.5,
ratio=5,
space=0.1,
joint_kws={"s": 10, "alpha": 0.55},
marginal_kws={"alpha": 0.6, "edgecolor": "white"},
legend=False,
)
g.set_axis_labels("$x_1$", "$x_2$")
g.figure.suptitle("Two moons (standardised) — colour = class label $y$", 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()

3. Four flow configurations¶
Each flow uses the same chain of four RQSplineCoupling layers separated by fixed permutations — splines for capacity, since fitting two-moons is not affine. The only difference between the four configurations is where conditioning happens.
| Flow | Base | Couplings | What can it model? |
|---|---|---|---|
flow_none | unconditional | only the marginal — ignores | |
flow_base | unconditional | per-class shift only | |
flow_coupling | cond_dim=2 | per-class shape warps | |
flow_both | cond_dim=2 | both — full capacity |
Architectural detail. A coupling layer leaves half the dims untouched, so we interleave fixed Permute layers between couplings to ensure every dim gets transformed. With and a 1-vs-1 split, a single Permute([1, 0]) between couplings is enough. We use spline transformers (rational-quadratic, 8 bins, interval ) because affine couplings cannot bend a Gaussian into a crescent.
N_LAYERS = 4
EVENT = (2,)
COND_DIM = 2 # one-hot (2,)
def make_flow(*, base_cond: bool, coupling_cond: bool, key):
"""Build an N_LAYERS-layer SurVAEFlow with the requested conditioning."""
base_key, *layer_keys, perm_key = jr.split(key, N_LAYERS + 2)
if base_cond:
base = ConditionalDiagGaussian(base_key, event_shape=EVENT, cond_dim=COND_DIM)
else:
base = Normal(jnp.zeros(EVENT))
cond_dim = COND_DIM if coupling_cond else None
perm = jr.permutation(perm_key, jnp.arange(EVENT[0]))
transforms = []
for i, k in enumerate(layer_keys):
transforms.append(
RQSplineCoupling(
k,
shape=EVENT,
n_bins=8,
interval=4.0,
cond_dim=cond_dim,
nn_width=64,
nn_depth=2,
)
)
if i < N_LAYERS - 1:
transforms.append(Permute(perm))
return SurVAEFlow(base, transforms)
CONFIGS = [
("none", dict(base_cond=False, coupling_cond=False)),
("base only", dict(base_cond=True, coupling_cond=False)),
("coupling only", dict(base_cond=False, coupling_cond=True)),
("both", dict(base_cond=True, coupling_cond=True)),
]
flows = {
name: make_flow(**kw, key=jr.key(11 + i)) for i, (name, kw) in enumerate(CONFIGS)
}
for name, flow in flows.items():
n_params = sum(
int(np.prod(p.shape))
for p in jax.tree_util.tree_leaves(eqx.filter(flow, eqx.is_array))
)
print(f"{name:>14s} trainable params: {n_params:6d}") none trainable params: 24448
base only trainable params: 29056
coupling only trainable params: 24960
both trainable params: 29568
4. Train each flow¶
All four flows minimize the same objective — negative log-likelihood under the model:
with . For the “none” and “coupling only” variants the on the base drops out; for the “none” and “base only” variants the inside drops out. Same code path for all four — only the layers’ cond_shapes differ.
fit_flow, the pipekit-train loop of notebook 01, trains each SurVAEFlow directly: gauss_flows’s negative_log_likelihood passes the step’s key and the context to SurVAEFlow.log_prob and averages over the batch, so no adapter to flowjax’s distribution API is needed. Hyperparameters match notebook 01 (learning_rate=5e-3, batch_size=256, max_epochs=600, max_patience=30).
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}def train(flow, *, key):
return fit_flow(
key,
flow,
X,
condition=C,
learning_rate=5e-3,
max_epochs=600,
max_patience=30,
batch_size=256,
val_prop=0.1,
)
trained = {}
losses_all = {}
for name, _ in CONFIGS:
print(f"training: {name}")
trained[name], losses_all[name] = train(
flows[name], key=jr.key(20 + abs(hash(name)) % 1000)
)training: none
training: base only
training: coupling only
training: both
fig, ax = plt.subplots(figsize=(8, 5))
config_palette = {
"none": palette[7],
"base only": palette[0],
"coupling only": palette[1],
"both": palette[3],
}
for name, _ in CONFIGS:
losses = losses_all[name]
ax.plot(losses["val"], label=name, color=config_palette[name], linewidth=2)
ax.set_xlabel("Epoch")
ax.set_ylabel("Validation NLL")
ax.set_title("Training curves — same data, same hyperparameters")
ax.legend(frameon=True)
style_axes(ax)
plt.show()WARNING:matplotlib.font_manager:findfont: Failed to find font weight semibold for DejaVu Sans, now using 700.

5. Per-class sample comparison¶
To draw conditional samples we exploit invertibility:
For each variant we draw samples per class and overlay them on the true class samples. Two rows (one per class) × four columns (one per configuration). The “none” flow has no class information — its panel is the same in both rows by construction.
eval_classes = jnp.array(
[
[1.0, 0.0], # y = 0 → upper moon
[0.0, 1.0], # y = 1 → lower moon
],
dtype=jnp.float32,
)
class_labels_text = ["y = 0 (upper moon)", "y = 1 (lower moon)"]
n_per_panel = 2000
def true_class_samples(class_idx):
mask = y == class_idx
return X[mask][:n_per_panel]
def flow_samples(flow, n, c, *, key):
cond = jnp.broadcast_to(c, (n, COND_DIM))
keys = jr.split(key, n)
return jax.vmap(lambda k, ci: flow.sample(k, condition=ci))(keys, cond)
config_names = ["none", "base only", "coupling only", "both"]
n_rows = len(eval_classes)
n_cols = len(config_names)
lim = 2.5
fig, axes = plt.subplots(
nrows=n_rows,
ncols=n_cols,
figsize=(4.0 * n_cols, 4.0 * n_rows),
sharex=True,
sharey=True,
)
for row, (c, label_text) in enumerate(zip(eval_classes, class_labels_text)):
class_idx = int(jnp.argmax(c))
true_s = true_class_samples(class_idx)
for col, name in enumerate(config_names):
flow_s = flow_samples(
trained[name],
n_per_panel,
c,
key=jr.fold_in(jr.key(100 + col), row),
)
ax = axes[row, col]
ax.scatter(
np.asarray(true_s[:, 0]),
np.asarray(true_s[:, 1]),
s=8,
alpha=0.45,
color=palette[0],
label="true",
edgecolors="none",
)
ax.scatter(
np.asarray(flow_s[:, 0]),
np.asarray(flow_s[:, 1]),
s=8,
alpha=0.45,
color=config_palette[name],
label="flow",
edgecolors="none",
)
ax.set_xlim(-lim, lim)
ax.set_ylim(-lim, lim)
if row == 0:
ax.set_title(name)
if col == 0:
ax.set_ylabel(label_text)
style_axes(ax, aspect="equal")
handles = [
plt.Line2D(
[0],
[0],
marker="o",
linestyle="",
markersize=8,
alpha=0.7,
color=palette[0],
label="true class samples",
),
plt.Line2D(
[0],
[0],
marker="o",
linestyle="",
markersize=8,
alpha=0.7,
color="0.4",
label="flow samples",
),
]
axes[0, 0].legend(handles=handles, loc="upper left", fontsize="small", framealpha=0.9)
plt.show()
What to look for
None (column 1): the flow ignores — it samples from the full two-moons every time, so half the samples land in the wrong crescent. The blue (true class) and grey (flow) samples only partially overlap.
Base only (column 2): the per-class mean is correct, but the unconditional spline chain learned one shape that has to serve both classes — the per-class crescent shape is muddier than the truth.
Coupling only (column 3): the spline couplings can read the one-hot label and produce class-specific crescents. Position and shape both come out cleanly because the couplings have enough capacity to absorb the per-class shift through the spline parameters.
Both (column 4): same crisp per-class fit as coupling-only, with the conditional base providing a per-class warm-start. Its final NLL is within run-to-run noise of coupling-only’s (in this run it is slightly worse, and with another training key the order can flip), so once the couplings read the label the conditional base adds little on two-moons.
6. Quantitative comparison¶
Mean per-example conditional log-likelihood under each fitted model:
Computed on the training set — we have no held-out oracle, but the four configurations can still be ranked.
def mean_flow_lp(flow):
@eqx.filter_jit
def f(x, c):
return jax.vmap(lambda xi, ci: flow.log_prob(xi, jr.key(0), condition=ci))(x, c)
return jnp.mean(f(X, C))
for name, _ in CONFIGS:
print(f"{name:<14s}: {float(mean_flow_lp(trained[name])):+.4f}")none : -1.1645
base only : -0.8162
coupling only : -0.4404
both : -0.4470
7. Takeaways¶
Modelling guidance.
Pick what to condition based on what your data needs. If only the position of varies with (location shift, isotropic scale), a conditional base alone is enough. If the shape varies — as it does here, since each class is a different crescent rather than a translated copy — conditional couplings are the natural fit. Real datasets usually benefit from both.
The conditioning capacity is multiplicative across layers. With conditional couplings, the per-class map composes class-dependent splines. A single conditional base contributes one Gaussian. Stacking helps mostly when the conditional density family is genuinely complex.
Keep modest. The conditioner MLPs concatenate to , so inflates the input layer. For categorical with many classes, prefer a learned embedding over one-hot encoding.
Implementation guidance for gauss_flows.
The same
conditionkeyword threads everywhere.SurVAEFlow.log_prob(x, key, condition=c)and.sample(key, condition=c)broadcast to every layer that opted in (cond_shape is not None); other layers ignore it. There is no per-layer condition kwarg.Inside a coupling there are two streams. The
untransformedhalf of is always a conditioning input — that is how coupling layers work. Addingcond_dim > 0also concatenates the external context onto the inner MLP. The two streams are merged inside flowjax and you never slice them apart from outside.For class-conditional density estimation, prefer
ClassCondFlow(n_classes=..., event_shape=..., transforms=[...]). It pairs aClassCondDiagGaussianbase (per-class learnable ) with an arbitrary chain of unconditional transforms, exposing alabelkeyword in place ofcondition. The construction validates that no transform in the chain is conditional, since the label flows only to the base.For transforms that genuinely cannot take a context (rotations, normalizations, periodic shifts), wrap them in
Conditioner(key, inner=..., cond_dim=D_c). The wrapper applies a FiLM-style affine modulation from the sharedAffineModulationaround the inner transform — preserving invertibility, giving a closed-form log-determinant and starting as the inner transform itself for every — and rejects inner transforms that are already conditional.Errors fail fast. Forgetting to pass
conditionto a flow with any conditional layer raises in flowjax’s_check_conditiondecorator; passing a wrong-shape context fails the same way.