Diagonal against coupling flows
Per-coordinate marginal maps between rotations against maps conditioned on the other coordinates, compared at matched parameter counts
04 · Diagonal against coupling flows¶
The flows of Part 4 are diagonal: each layer (3) maps every coordinate with a one-dimensional map of its own, so the Jacobian of its marginal step is diagonal,
and the coordinates meet only through the rotations . A coupling layer (notebook 00) maps its active half with parameters computed from its passive half, so its Jacobian (3) has a block below the diagonal, and the coordinates meet inside every layer. That conditioner is a neural network, so a coupling layer also has far more parameters. Is the coupling flow more expressive, or does it just have more parameters? We compare the two at matched parameter counts, on a distribution built to need dependence between the coordinates: a two-armed spiral.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
repo = "git+https://github.com/jejjohnson/gauss_flows@main"
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
f"gauss-flows-maps @ {repo}#subdirectory=packages/gauss-flows-maps",
f"gauss-flows-models @ {repo}#subdirectory=packages/gauss-flows-models",
f"gauss-flows-docs[notebooks] @ {repo}#subdirectory=docs",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import equinox as eqx
import jax
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import optax
from flowjax.distributions import StandardNormal, Transformed
from jaxtyping import ArrayLike, Float
from pipekit_train import ArrayDataset, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import SCATTER_KW, style_ax, use_compact_figures
from gauss_flows_models.flows import coupling_gaussianization_flow, gaussianization_flow
from gauss_flows_models.inference import negative_log_likelihood
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "optax", "flowjax", "pipekit_train", "gauss_flows_models")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
optax : 0.2.8
flowjax : 19.1.0
pipekit_train : 0.3.4
gauss_flows_models: 0.3.1
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
The spiral has two arms: a point at arc parameter sits at , with the sign chosen at random and normal noise of standard deviation 0.08 added. Where one coordinate is, the other is confined to a few narrow bands, a dependence no per-coordinate map can express. We standardise points and split them into training rows and held-out rows, in float64.
# Shapes: sample (N) = 4,000; state (D_x) = 2; train (N_t) = 3,000; held_out (N_v) = 1,000
PerSample = Float[ArrayLike, " sample"]
# t ~ U(0.5, 3.5), (sample)
arc: PerSample = rng.uniform(0.5, 3.5, 4000)
# the arm, ±1 with equal probability, (sample)
arm: PerSample = rng.integers(0, 2, 4000) * 2 - 1
SampleState = Float[ArrayLike, "sample state"]
# ±(t cos 2.5t, t sin 2.5t) + 0.08 ε, (sample, state)
raw: SampleState = arm[:, None] * np.column_stack(
[arc * np.cos(2.5 * arc), arc * np.sin(2.5 * arc)]
)
raw = raw + 0.08 * rng.standard_normal((4000, 2))
# x = (raw − x̄) / s, (sample, state)
samples: SampleState = (raw - raw.mean(axis=0)) / raw.std(axis=0)
# a random order of the rows, (sample)
order: PerSample = rng.permutation(4000)
# the training rows, (train, state)
train_points: Float[ArrayLike, "train state"] = samples[order[:3000]]
# the held-out rows, (held_out, state)
held_points: Float[ArrayLike, "held_out state"] = samples[order[3000:]]1. What coupling_gaussianization_flow builds¶
Part 4 took gaussianization_flow apart. Its coupling counterpart, coupling_gaussianization_flow, stacks layers of a rational-quadratic-spline coupling Durkan et al., 2019, whose conditioner is an MLP of width nn_width and depth nn_depth, followed by a flip of the coordinates for (notebook 03). We build it with the defaults and count parameters per layer.
# Shapes: layer = K = 4 layers
# today (gauss_flows)
# K = 4 layers of an 8-bin spline coupling with a 2-layer MLP of width 64, and a flip
default_coupling: Transformed = coupling_gaussianization_flow(
jr.key(0), n_dims=2, n_layers=4
)
# the layer stack, run in the density direction by Invert
coupling_stack: eqx.Module = default_coupling.bijection.bijection
print(
f"bijection: {type(default_coupling.bijection).__name__}({type(coupling_stack).__name__}(...))"
)
print(
f"one layer: {[type(block).__name__ for block in coupling_stack.bijection.bijections]}"
)
print(f"base distribution: {type(default_coupling.base_dist).__name__}")bijection: Invert(Scan(...))
one layer: ['RQSplineCoupling', 'Flip']
base distribution: Normal
The structure matches gaussianization_flow’s: an Invert around a Scan over identical layers, so log_prob runs the layers forwards. Its base is FlowJax’s Normal, whose location and scale are trainable, so training moves the base away from , a bug in gauss_flows (gauss_flows#256). Unlike gaussianization_flow, this factory takes no base_dist, so below we put its bijection on a fixed StandardNormal base ourselves. Counting what is left to train:
# user
# the number of trainable numbers in a flow's bijection
def count_parameters(flow: Transformed) -> int:
"""The number of floating-point numbers in the bijection of ``flow``."""
# today (equinox)
# every trainable array of the bijection
arrays: list = jax.tree.leaves(eqx.filter(flow.bijection, eqx.is_inexact_array))
return sum(array.size for array in arrays)
# today (gauss_flows)
# K = 4 layers of an 8-component mixture marginal and a Householder rotation
default_diagonal: Transformed = gaussianization_flow(
jr.key(0), n_dims=2, n_layers=4, n_components=8
)
# user
# parameters per layer of each factory with its defaults
print(
f"per layer: diagonal {count_parameters(default_diagonal) // 4}, coupling {count_parameters(default_coupling) // 4}"
)per layer: diagonal 52, coupling 6108
A coupling layer with the default conditioner has over a hundred times the parameters of a diagonal layer, so comparing the two at the same number of layers says little. We compare them at matched parameter counts instead: we shrink the coupling conditioner to one hidden layer of width 16, and stack more diagonal layers. The ranges cannot match exactly, since a diagonal flow would need far more layers than it can usefully train to reach a coupling flow’s count, but they meet in the middle.
2. Likelihood against parameter count¶
We train diagonal flows with layers and coupling flows with layers, all on a fixed base, with the training recipe of Part 4: pipekit-train runs Adam on the mean negative log-likelihood (1) with a one-cycle cosine learning rate peaking at and the gradient clipped to a global norm of 1, here for 2,000 steps on batches of 512 rows.
# today (gauss_flows)
# diagonal flows of 4, 8 and 16 layers on a fixed 𝒩(0, I) base
diagonal_flows: dict = {
layers: gaussianization_flow(
jr.key(0),
n_dims=2,
n_layers=layers,
n_components=8,
base_dist=StandardNormal((2,)),
)
for layers in (4, 8, 16)
}
print(
"trainable numbers, diagonal:",
{layers: count_parameters(flow) for layers, flow in diagonal_flows.items()},
)trainable numbers, diagonal: {4: 208, 8: 416, 16: 832}
# today (gauss_flows)
# coupling flows of 2, 4 and 8 layers with a 1-layer MLP of width 16, put on a fixed 𝒩(0, I) base
coupling_flows: dict = {
layers: Transformed(
StandardNormal((2,)),
coupling_gaussianization_flow(
jr.key(0), n_dims=2, n_layers=layers, nn_width=16, nn_depth=1
).bijection,
)
for layers in (2, 4, 8)
}
print(
"trainable numbers, coupling:",
{layers: count_parameters(flow) for layers, flow in coupling_flows.items()},
)trainable numbers, coupling: {2: 1016, 4: 2032, 8: 4064}
Scalar = Float[ArrayLike, ""]
# user
# pipekit-train's task: 𝓛(θ) on one batch
class FlowNLL:
"""pipekit-train's task: the mean negative log-likelihood of a batch."""
# user
# 𝓛(θ) = −(1/N_b) ∑ₙ log p_x(xₙ; θ), also logged
def loss_fn(self, flow, batch, key):
# the points of the batch; its targets are empty, (batch, state)
batch_points: Float[ArrayLike, "batch state"]
batch_points, _ = batch
# today (gauss_flows)
# −(1/N_b) ∑ₙ log p_x(xₙ; θ)
loss: Scalar = negative_log_likelihood(flow, batch_points)
return loss, {"loss": loss}# Shapes: step = 2,000 training steps; batch (N_b) = 512
# today (optax)
# the learning rate of each step: up to 3 × 10⁻³, then down to almost zero
schedule: optax.Schedule = optax.cosine_onecycle_schedule(
transition_steps=2000, peak_value=3e-3
)
# today (pipekit)
# the held-out rows, with no targets
held_data = ArrayDataset(held_points, ())
# the settings every run shares
loop_settings: dict = {
"optimizer_config": {"name": "adam", "lr": schedule, "clip_norm": 1.0},
"val_dataset": held_data,
"task": FlowNLL(),
"max_steps": 2000,
"steps_per_epoch": 100,
"eval_every_n_steps": 100,
"log_every_n_steps": 100,
"batch_size": 512,
"seed": 1,
}# user
# θ after 2,000 Adam steps on 𝓛(θ)
def train_flow(flow: Transformed) -> Transformed:
"""Train every floating-point array of ``flow`` with the shared settings."""
# today (pipekit)
# the flow as a trainable model, every floating-point array trained
model_op = EquinoxModelOp(flow, trainable=eqx.is_inexact_array)
# today (pipekit)
# the loop over the training rows, which have no targets
loop = TrainingLoop(
model_op,
ArrayDataset(train_points, ()),
callbacks=(History(),),
**loop_settings,
)
# today (pipekit)
# θ after 2,000 steps, held by the model op
trained_op: EquinoxModelOp
trained_op, _ = loop.run()
return trained_op.moduleWe train the six flows; the diagonal ones take longer, since a Scan over 16 layers is slower per step than one over 2.
# user
# the diagonal flows after training
trained_diagonal: dict = {
layers: train_flow(flow) for layers, flow in diagonal_flows.items()
}
# user
# the coupling flows after training
trained_coupling: dict = {
layers: train_flow(flow) for layers, flow in coupling_flows.items()
}
for name, flows in [("diagonal", trained_diagonal), ("coupling", trained_coupling)]:
for layers, flow in flows.items():
print(
f"{name} K = {layers:2d}: {count_parameters(flow):4d} parameters, NLL {float(negative_log_likelihood(flow, train_points)):.3f} on training rows, {float(negative_log_likelihood(flow, held_points)):.3f} held out"
)diagonal K = 4: 208 parameters, NLL 2.637 on training rows, 2.634 held out
diagonal K = 8: 416 parameters, NLL 2.673 on training rows, 2.679 held out
diagonal K = 16: 832 parameters, NLL 2.716 on training rows, 2.716 held out
coupling K = 2: 1016 parameters, NLL 1.853 on training rows, 1.890 held out
coupling K = 4: 2032 parameters, NLL 1.659 on training rows, 1.700 held out
coupling K = 8: 4064 parameters, NLL 1.502 on training rows, 1.540 held out
fig, ax = plt.subplots(figsize=(8, 4.6))
for flows, color, marker, label in [
(trained_diagonal, "C0", "o", "diagonal"),
(trained_coupling, "C2", "s", "coupling"),
]:
counts = [count_parameters(flow) for flow in flows.values()]
held = [
float(negative_log_likelihood(flow, held_points)) for flow in flows.values()
]
ax.plot(counts, held, marker=marker, color=color, lw=2, ms=7, label=label)
ax.set(
xscale="log",
xlabel="number of parameters",
ylabel="held-out negative log-likelihood (nats)",
)
ax.legend()
style_ax(ax)
plt.show()
Figure 1:Held-out negative log-likelihood against the number of parameters, on a log scale, for diagonal flows of 4, 8 and 16 layers (blue circles) and coupling flows of 2, 4 and 8 layers with a small conditioner (green squares). Lower is better.
The two curves do not overlap. The diagonal flow sits between 2.63 and 2.72 nats held out over its whole range, and its deeper versions are slightly worse, not better: at this training budget, more layers of per-coordinate maps and rotations do not carve the spiral (a separate run with three times as many steps lowered both, but kept the 16-layer flow behind the 4-layer one). The smallest coupling flow, with 1,016 parameters against the deepest diagonal flow’s 832, is already 0.83 nats better held out, and the coupling flows keep improving as they grow, to 1.54 nats at 4,064 parameters. The advantage is not that coupling flows have more parameters: per parameter, a conditioner that lets one coordinate’s map depend on the other is far more efficient for this dependence.
3. The learned densities at similar parameter counts¶
The closest pair is the diagonal flow with 16 layers and the coupling flow with 2 layers. We evaluate both densities on a grid.
# Shapes: line = 120 points along each axis; test = 120 × 120 grid points
# 120 points from −2.5 to 2.5, (line)
grid_axis: Float[ArrayLike, " line"] = np.linspace(-2.5, 2.5, 120)
# the 120 × 120 grid over [−2.5, 2.5]², as rows, (test, state)
grid_points: Float[ArrayLike, "test state"] = np.stack(
np.meshgrid(grid_axis, grid_axis), axis=-1
).reshape(-1, 2)
PerTest = Float[ArrayLike, " test"]
# today (flowjax)
# p_x on the grid for the 16-layer diagonal flow, (test)
diagonal_grid: PerTest = np.exp(
np.asarray(jax.vmap(trained_diagonal[16].log_prob)(grid_points))
)
# today (flowjax)
# p_x on the grid for the 2-layer coupling flow, (test)
coupling_grid: PerTest = np.exp(
np.asarray(jax.vmap(trained_coupling[2].log_prob)(grid_points))
)fig, axes = plt.subplots(1, 3, figsize=(16.5, 5))
axes[0].scatter(held_points[:, 0], held_points[:, 1], color="C0", **SCATTER_KW)
axes[0].set(title="held-out data")
for ax, density, title in [
(
axes[1],
diagonal_grid,
f"diagonal, K = 16, {count_parameters(trained_diagonal[16])} parameters",
),
(
axes[2],
coupling_grid,
f"coupling, K = 2, {count_parameters(trained_coupling[2])} parameters",
),
]:
ax.contourf(
grid_axis, grid_axis, density.reshape(120, 120), levels=18, cmap="viridis"
)
ax.scatter(held_points[:, 0], held_points[:, 1], s=3, color="white", alpha=0.25)
ax.set(title=title)
for ax in axes:
ax.set(xlim=(-2.5, 2.5), ylim=(-2.5, 2.5), xlabel="first coordinate")
ax.set_aspect("equal")
style_ax(ax)
axes[0].set_ylabel("second coordinate")
fig.tight_layout()
plt.show()
Figure 2:The held-out spiral (left) and the densities of the 16-layer diagonal flow (centre) and the 2-layer coupling flow (right), each with the held-out points in white. The diagonal flow spreads its mass over a blob around the spiral; the coupling flow puts it along the arms.
With a similar budget, the diagonal flow spreads its mass over a blob that covers the spiral and the gaps between its arms, with its peak at the centre, while the coupling flow puts its mass along the arms. The conditioner does the work: it lets the map of one coordinate depend on where the other is, which is what the spiral needs. When the dependence between coordinates is mild, the cheaper diagonal flow and its RBIG warm start (Part 4) can be enough.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| a diagonal layer: per-coordinate maps, then a rotation | (3), (1) | gaussianization_flow |
| a coupling layer: maps conditioned on the other half | (1), (3) | coupling_gaussianization_flow, RQSplineCoupling and Flip |
| a fixed base for the coupling factory | (5) | Transformed(StandardNormal((2,)), flow.bijection), until gauss_flows#256 is fixed |
| a fair comparison | parameter counts from eqx.filter(flow.bijection, eqx.is_inexact_array) | |
| training | (1) | pipekit-train’s TrainingLoop on negative_log_likelihood |
Next. Coupling flows are more expressive, but they start from the identity and must learn everything by training. Notebook 05 starts one from a greedy RBIG fit instead, with fit_rbig_coupling.
- Durkan, C., Bekasov, A., Murray, I., & Papamakarios, G. (2019). Neural Spline Flows. Advances in Neural Information Processing Systems (NeurIPS).