Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Coupling Flow with Mixture-CDF Transform

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:

  1. Split x=(xa,xb)x = (x_a, x_b) with xax_a the identity half and xbx_b the transformed half.

  2. A conditioner network θ(xa)\theta(x_a) outputs the mixture parameters (π,μ,log⁡σ)(\pi, \mu, \log\sigma) for each dimension in xbx_b.

  3. Apply the mixture-CDF Gaussianization to xbx_b using those per-example parameters: zb=Φ−1(F(xb;θ(xa)))z_b = \Phi^{-1}(F(x_b; \theta(x_a))).

  4. Leave za=xaz_a = x_a 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 zbz_b depends on xax_a, 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 NN, input dimensionality dd, mixture components KK.

  • With the default half-split for d=2d = 2 we have da=1d_a = 1 dim passes through, db=1d_b = 1 dim gets transformed.

  • x∈RN×dx \in \mathbb{R}^{N \times d} splits into xa∈RN×dax_a \in \mathbb{R}^{N \times d_a} and xb∈RN×dbx_b \in \mathbb{R}^{N \times d_b}.

The bijector — GMM per b-dim

Each transformed dimension i∈bi \in b has its own per-example mixture of KK Gaussians,

Fi(xb,i; πi,μi,σi)  =  ∑k=1Kπi,k Φ ⁣((xb,i−μi,k)/σi,k),F_i(x_{b,i};\,\pi_i, \mu_i, \sigma_i) \;=\; \sum_{k=1}^{K} \pi_{i,k}\,\Phi\!\big((x_{b,i} - \mu_{i,k})/\sigma_{i,k}\big),

and the per-b-dim forward is exactly the mixture-CDF Gaussianization from notebook 01 — the same primitive, only difference is that (πi,μi,σi)(\pi_i, \mu_i, \sigma_i) now depend on xax_a:

zb,i  =  Φ−1 ⁣(Fi(xb,i; θi(xa))).z_{b,i} \;=\; \Phi^{-1}\!\big(F_i(x_{b,i};\,\theta_i(x_a))\big).

The per-example parameter tensors have shape (N,db,K)(N, d_b, K).

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 log⁡σ\log \sigma are passed through a bounded map before being exponentiated,

log⁡σi,k  =  B tanh⁡(log⁡σ~i,k),\log \sigma_{i,k} \;=\; B\,\tanh(\tilde{\log\sigma}_{i,k}),

with default B=5B = 5 so σ∈[e−5,e5]≈[0.007,148]\sigma \in [e^{-5}, e^5] \approx [0.007, 148]. This keeps scales from blowing up or collapsing during training, especially when the conditioner is still warming up.

Jacobian of the coupling layer

With za=xaz_a = x_a and zb=Φ−1(F(xb; θ(xa)))z_b = \Phi^{-1}(F(x_b;\,\theta(x_a))), the Jacobian is block-triangular:

J  =  (Ida0∗diag(∂zb,i/∂xb,i)),log⁡∣det⁡J∣  =  ∑i∈blog⁡∣∂zb,i/∂xb,i∣.J \;=\; \begin{pmatrix} I_{d_a} & 0 \\ \ast & \mathrm{diag}(\partial z_{b,i} / \partial x_{b,i}) \end{pmatrix}, \qquad \log\lvert\det J\rvert \;=\; \sum_{i \in b} \log\lvert \partial z_{b,i} / \partial x_{b,i} \rvert.

The lower-left off-diagonal depends on ∂θ(xa)/∂xa\partial \theta(x_a)/\partial x_a (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,

zb  =  xb⊙exp⁡ ⁣(s(xa))+t(xa).z_b \;=\; x_b \odot \exp\!\big(s(x_a)\big) + t(x_a).

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.

/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.

/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()
<Figure size 825x825 with 3 Axes>

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.

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.

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.
<Figure size 1870x715 with 2 Axes>
final train NLL: +1.1813   (min: +1.1744)
final   val NLL: +1.2097   (min: +1.1608)

4. Pushforward and density

The pushforward z=f(x)z = f(x) should be approximately N(0,I)\mathcal{N}(0, I). A jointplot puts the 2-D scatter next to the per-dim marginals; the black reference curves are φ(z)\varphi(z).

Unlike a marginal-only flow, here the conditioner can express the cross-dim dependence exactly (each zbz_b is conditional on xax_a) — the density contour in xx-space should trace the two moons sharply.

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()
<Figure size 825x825 with 3 Axes>
<Figure size 1870x825 with 4 Axes>

5. Sampling from the flow

z∼N(0,I)↦x=f−1(z)z \sim \mathcal{N}(0, I) \mapsto x = f^{-1}(z). Each coupling layer’s inverse bisects F(xb;θ(za))=Φ(zb)F(x_b; \theta(z_a)) = \Phi(z_b) per b-dim via optimistix.Bisection, with za=xaz_a = x_a preserved through the layer so the conditioner sees the same input in both directions.

/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()
<Figure size 825x825 with 3 Axes>
/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()
<Figure size 825x825 with 3 Axes>

6. Round-trip inversion

Each coupling layer is a bijection by construction, so f−1(f(x))f^{-1}(f(x)) should recover xx to numerical precision. The inverse uses optimistix.Bisection on the mixture CDF; small tails from the ε\varepsilon-clamp on F(x)∈[ε,1−ε]F(x) \in [\varepsilon, 1 - \varepsilon] are the only residual error.

round-trip L2 error  ||f^{-1}(f(x)) - x||_2
  median : 1.55e-06
  95th%  : 5.03e-06
  max    : 6.95e-04
<Figure size 1100x605 with 1 Axes>

7. Layer-by-layer view

States x, f1(x), …, zx,\, f_1(x),\, \ldots,\, z. 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.

<Figure size 1980x2970 with 24 Axes>

Recap

  • Coupling = one half conditions, the other is transformed. Half-swap via Flip inside 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_coupling in 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.