Coupling and diagonal equivalence
A coupling flow whose conditioners return constants is a diagonal Gaussianization flow; we check it block by block, and find where it fails today
06 · Coupling and diagonal equivalence¶
Notebook 05 started a coupling flow from fit_rbig_coupling and found that its conditioners return constants until training switches them on. A coupling whose conditioner returns a constant no longer couples anything: it is a marginal map on its active half. So a warm-started coupling flow should be the diagonal Gaussianization flow that fit_rbig builds, written with many more numbers. The example Zero-kernel coupling ≡ diagonal Gaussianization proves this lemma by lemma and shows training breaking it. Here we test the claim layer by layer, which shows where float32 rounding enters, and where the equivalence fails today.
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.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
from flowjax.distributions import Transformed
from jaxtyping import ArrayLike, Float
from sklearn.datasets import make_moons
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import style_ax, use_compact_figures
from gauss_flows_models.inference import (
fit_rbig,
fit_rbig_coupling,
negative_log_likelihood,
)
rng = np.random.default_rng(0)
np.set_printoptions(precision=4, suppress=True)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "flowjax", "gauss_flows_models")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
flowjax : 19.1.0
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
1. Why a zero readout gives a marginal map¶
The last layer of a coupling’s conditioner is affine (1). When its weight is zero, the conditioner returns its bias whatever the passive half, so the transformer’s parameters no longer depend on , and the coupling of (1) becomes
The block of the Jacobian below the diagonal (3) is zero, so the layer maps each active coordinate on its own. For MixtureGaussianCDFCoupling the transformer is the mixture Gaussianization (3) of the mixture that encodes. fit_rbig_coupling builds each layer as a PCA frame followed by two such couplings with a flip after each, so that each coordinate is active once; the pair is one diagonal layer (2). It fits each by the same per-coordinate EM, with the same seeds, as fit_rbig fits its marginals, so the two warm starts should be one map.
2. Four layers: one map¶
The data are those of Part 4: two moons with noise of standard deviation 0.08, standardised, split into training rows and held-out rows. Both builders work in float32 (fit_rbig cannot run in float64 today, gauss_flows#247).
# Shapes: sample (N) = 4,000; state (D_x) = 2; train (N_t) = 3,000; held_out (N_v) = 1,000
SampleState = Float[ArrayLike, "sample state"]
# today (scikit-learn)
# two interleaved half circles with noise of standard deviation 0.08, (sample, state)
raw: SampleState
raw, _ = make_moons(n_samples=4000, noise=0.08, random_state=0)
# x = (raw − x̄) / s, in float32, (sample, state)
samples: SampleState = ((raw - raw.mean(axis=0)) / raw.std(axis=0)).astype(np.float32)
# a random order of the rows, (sample)
order: Float[ArrayLike, " sample"] = 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:]]# today (gauss_flows)
# K = 4 layers of a PCA frame and a diagonal 8-component mixture marginal, fitted by EM
diagonal_flow: Transformed = fit_rbig(
jnp.asarray(train_points), n_layers=4, n_components=8, random_state=0
)
# today (gauss_flows)
# K = 4 layers of a PCA frame and two zero-readout mixture couplings, fitted by the same EM
coupling_flow: Transformed = fit_rbig_coupling(
jnp.asarray(train_points), jr.key(0), n_layers=4, n_components=8, random_state=0
)
for name, flow in [("diagonal", diagonal_flow), ("coupling", coupling_flow)]:
# the blocks of the flow, in the density direction
blocks: list = list(flow.bijection.bijection.bijections)
# today (equinox)
# every array of the flow
arrays: list = jax.tree.leaves(eqx.filter(flow, eqx.is_inexact_array))
print(
f"{name}: {len(blocks)} blocks, first layer {[type(block).__name__ for block in blocks[: 2 if name == 'diagonal' else 5]]}, {sum(array.size for array in arrays)} numbers"
)diagonal: 8 blocks, first layer ['FixedRotation', 'MixtureGaussianCDF'], 212 numbers
coupling: 20 blocks, first layer ['FixedRotation', 'MixtureGaussianCDFCoupling', 'Flip', 'MixtureGaussianCDFCoupling', 'Flip'], 46804 numbers
Both flows start each layer with a PCA frame. The diagonal flow holds 212 numbers: four frames, eight mixtures of 8 components with a weight, a mean and a scale each, and the base’s location and scale. The coupling flow holds 46,804, about 220 times more: each of its eight couplings has a conditioner MLP of width 64 and depth 2, and at the warm start only the readout’s bias of each conditioner has any effect on the map.
One function runs the blocks of a flow one at a time, in the density direction, and keeps the state at the end of each layer: every 2 blocks for the diagonal flow, every 5 for the coupling flow.
# Shapes: layer = K layers
# user
# xₖ after each layer k, `per_layer` blocks to a layer, (layer, sample, state)
def layer_states(
flow: Transformed, per_layer: int, points: SampleState
) -> Float[ArrayLike, "layer sample state"]:
"""The points after each layer of ``flow``, in the density direction."""
# the states, one entry per layer
states: list = []
# x₀ = x, (sample, state)
state: SampleState = jnp.asarray(points)
for index, block in enumerate(flow.bijection.bijection.bijections):
# today (flowjax)
# the block's map, (sample, state)
state = jax.vmap(block.transform)(state)
if (index + 1) % per_layer == 0:
states.append(np.asarray(state))
return np.stack(states)LayerSample = Float[ArrayLike, "layer sample"]
# user
# ‖xₖ(coupling) − xₖ(diagonal)‖ for every layer and point, (layer, sample)
def layer_gaps(
diagonal: Transformed, coupling: Transformed, points: SampleState
) -> LayerSample:
"""The distance between the two flows' states after each layer."""
# user
# the diagonal flow's states, (layer, sample, state)
diagonal_states: Float[ArrayLike, "layer sample state"] = layer_states(
diagonal, 2, points
)
# user
# the coupling flow's states, (layer, sample, state)
coupling_states: Float[ArrayLike, "layer sample state"] = layer_states(
coupling, 5, points
)
return np.linalg.norm(coupling_states - diagonal_states, axis=-1)We compare the two flows on the training rows.
# user
# ‖xₖ(coupling) − xₖ(diagonal)‖ on the training rows, (layer, train)
gaps_4: Float[ArrayLike, "layer train"] = layer_gaps(
diagonal_flow, coupling_flow, train_points
)
for layer, gap in enumerate(gaps_4, start=1):
print(f"layer {layer}: median {np.median(gap):.1e}, max {gap.max():.1e}")layer 1: median 1.9e-07, max 3.7e-05
layer 2: median 2.2e-05, max 4.7e-04
layer 3: median 6.6e-05, max 6.7e-04
layer 4: median 3.4e-05, max 3.6e-04
# today (gauss_flows)
# −(1/N) ∑ₙ log p_x(xₙ) of both flows, on training and held-out rows
for name, flow in [("diagonal", diagonal_flow), ("coupling", coupling_flow)]:
print(
f"{name}: NLL {float(negative_log_likelihood(flow, train_points)):.5f} on training rows, {float(negative_log_likelihood(flow, held_points)):.5f} held out"
)diagonal: NLL 2.02326 on training rows, 2.09955 held out
coupling: NLL 2.02327 on training rows, 2.09417 held out
With 4 layers the two flows are one map to float32 rounding. After the first layer their states agree to in the median and at worst, and the largest gap stays below through all four layers. The largest gaps are at points in the tails, where the coupling takes the probit of the mixture CDF itself while MixtureGaussianCDF works with its logarithm, and loses digits as the CDF approaches 1. The training NLLs agree to 10-5 nats. The held-out NLLs differ by 0.005 nats (2.09955 against 2.09417), and the whole difference comes from three held-out rows that the diagonal flow sends beyond -5 in a latent coordinate: the coupling flow cannot send them that far, for the reason section 3 finds.
3. Eight layers: where it breaks¶
We build both flows again with layers and compare them the same way.
# today (gauss_flows)
# K = 8 layers, diagonal
diagonal_flow_8: Transformed = fit_rbig(
jnp.asarray(train_points), n_layers=8, n_components=8, random_state=0
)
# today (gauss_flows)
# K = 8 layers, coupling
coupling_flow_8: Transformed = fit_rbig_coupling(
jnp.asarray(train_points), jr.key(0), n_layers=8, n_components=8, random_state=0
)
# user
# ‖xₖ(coupling) − xₖ(diagonal)‖ on the training rows, (layer, train)
gaps_8: Float[ArrayLike, "layer train"] = layer_gaps(
diagonal_flow_8, coupling_flow_8, train_points
)
for layer, gap in enumerate(gaps_8, start=1):
print(f"layer {layer}: median {np.median(gap):.1e}, max {gap.max():.1e}")layer 1: median 1.9e-07, max 3.7e-05
layer 2: median 2.2e-05, max 4.7e-04
layer 3: median 6.6e-05, max 6.7e-04
layer 4: median 3.4e-05, max 3.6e-04
layer 5: median 5.0e-05, max 5.0e-01
layer 6: median 4.2e-02, max 8.6e-01
layer 7: median 1.9e+00, max 7.5e+00
layer 8: median 1.9e+00, max 8.3e+00
fig, ax = plt.subplots(figsize=(7.5, 4.4))
for gaps, colour, name in [(gaps_8, "C1", "8 layers"), (gaps_4, "C0", "4 layers")]:
layers = np.arange(1, len(gaps) + 1)
ax.plot(
layers,
np.median(gaps, axis=1),
"o-",
color=colour,
lw=2,
label=f"{name}, median",
)
ax.plot(
layers, gaps.max(axis=1), "s--", color=colour, lw=1.5, label=f"{name}, largest"
)
ax.set(yscale="log", xlabel="layer k", ylabel="distance between the states")
ax.legend()
style_ax(ax)
plt.show()
Figure 1:The distance between the states of the coupling flow and the diagonal flow after each layer, on the training rows: the median (solid) and the largest (dashed), for 4 layers (blue) and 8 layers (orange), on a log scale. The first four layers of the two pairs coincide.
Both builders are deterministic, so the first four layers of the 8-layer flows are those of the 4-layer flows, gaps included. In layer 5 the median gap is still , but one point jumps to 0.5. From layer 6 on the median grows, and after layer 7 the two flows send a typical point 1.9 apart. We look at the point that jumps in layer 5.
# the layer where the largest gap first exceeds 0.1, counting from 0
first_layer: int = int(np.argmax(gaps_8.max(axis=1) > 0.1))
# user
# the states going into that layer's marginal step: after its PCA frame, (train, state)
diagonal_rotated: Float[ArrayLike, "train state"] = layer_states(
diagonal_flow_8, 2, train_points
)[first_layer - 1]
# the point with the largest gap after that layer
worst: int = int(np.argmax(gaps_8[first_layer]))
# the layer's PCA frame and marginal in the diagonal flow
diagonal_blocks: list = list(diagonal_flow_8.bijection.bijection.bijections)[
2 * first_layer : 2 * first_layer + 2
]
# the layer's PCA frame, two couplings and two flips in the coupling flow
coupling_blocks: list = list(coupling_flow_8.bijection.bijection.bijections)[
5 * first_layer : 5 * first_layer + 5
]# today (flowjax)
# the point in the layer's PCA frame, (state)
framed: Float[ArrayLike, " state"] = diagonal_blocks[0].transform(
diagonal_rotated[worst]
)
# today (gauss_flows)
# the diagonal marginal of that point, (state)
diagonal_out: Float[ArrayLike, " state"] = diagonal_blocks[1].transform(framed)
# the coupling pair of the same point, (state)
coupling_out: Float[ArrayLike, " state"] = framed
for block in coupling_blocks[1:]:
# today (gauss_flows)
# one coupling or flip, (state)
coupling_out = block.transform(coupling_out)
print(
f"layer {first_layer + 1}, training row {worst}: in the PCA frame {np.asarray(framed)}"
)
print(f" diagonal marginal: {np.asarray(diagonal_out)}")
print(f" coupling pair: {np.asarray(coupling_out)}")layer 5, training row 2071: in the PCA frame [1.6596 4.2851]
diagonal marginal: [1.6513 5.2507]
coupling pair: [1.6512 4.7508]
In layer 5’s PCA frame this training row has 4.285 in its second coordinate, far in the tail of that layer’s mixture. The diagonal marginal sends it to 5.251. The coupling sends it to 4.7508, which is , the largest value it can return: it clips the mixture CDF to before the probit. Past that value the coupling is not invertible and its log-determinant is wrong, a bug in gauss_flows (gauss_flows#260). fit_rbig_coupling moves its states from layer to layer through the same clipped formula, so it fits layer 6 to states that differ from those of fit_rbig in this one row.
# user
# max |Q_k(coupling) − Q_k(diagonal)| for the PCA frame of every layer
for layer in range(8):
# today (flowjax)
# the diagonal flow's frame of layer k, applied to the unit vectors, (state, state)
diagonal_frame: Float[ArrayLike, "state state"] = jax.vmap(
list(diagonal_flow_8.bijection.bijection.bijections)[2 * layer].transform
)(jnp.eye(2))
# today (flowjax)
# the coupling flow's frame of layer k, (state, state)
coupling_frame: Float[ArrayLike, "state state"] = jax.vmap(
list(coupling_flow_8.bijection.bijection.bijections)[5 * layer].transform
)(jnp.eye(2))
print(
f"layer {layer + 1}: frames differ by {float(jnp.abs(coupling_frame - diagonal_frame).max()):.1e}"
)layer 1: frames differ by 0.0e+00
layer 2: frames differ by 1.1e-05
layer 3: frames differ by 2.4e-05
layer 4: frames differ by 2.4e-05
layer 5: frames differ by 3.9e-05
layer 6: frames differ by 2.5e-02
layer 7: frames differ by 1.4e+00
layer 8: frames differ by 1.6e+00
# today (gauss_flows)
# −(1/N) ∑ₙ log p_x(xₙ) of the 8-layer flows, on training and held-out rows
for name, flow in [("diagonal", diagonal_flow_8), ("coupling", coupling_flow_8)]:
print(
f"{name}: NLL {float(negative_log_likelihood(flow, train_points)):.3f} on training rows, {float(negative_log_likelihood(flow, held_points)):.3f} held out"
)diagonal: NLL 1.926 on training rows, 2.430 held out
coupling: NLL 1.830 on training rows, 2.022 held out
One row out of 3,000 is enough. Layer 6’s PCA frame moves by , the EM fits after it land elsewhere, and by layer 7 the frames differ by 1.4: the two flows are now different maps, and different densities, with training NLLs of 1.830 for the coupling flow and 1.926 for the diagonal one, and held-out NLLs of 2.022 and 2.430. We read neither as the better model; once the coupling works in log space the two should agree at any depth, which the docs ticket gauss_flows#261 will check.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| a zero readout makes a coupling a marginal map | (1), (1) | fit_rbig_coupling |
| a coupling pair with flips is one diagonal layer | (2) | [FixedRotation, MixtureGaussianCDFCoupling, Flip, MixtureGaussianCDFCoupling, Flip] |
| the two warm starts compared layer by layer | (2) | layer_states, layer_gaps |
| where the equivalence fails today | (3) | the coupling’s clipped CDF, gauss_flows#260 |
RBIG, the diagonal Gaussianization flow and the zero-readout coupling flow are three ways of writing one map; the coupling flow adds a conditioner that training can switch on, as notebook 05 showed.
Next. Notebook 07 stacks coupling layers deeper: what depth buys, how the gradient grows with it, and the residual maps that give up the coupling’s triangular Jacobian.