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.

Gaussianization Flow on Two-Moons

A minimal demonstration of a Gaussianization flow — a normalising flow built from two kinds of bijectors stacked in blocks:

  1. Rotation. Either a Householder product (trainable, Q=∏j(I−2vjvj⊤/∥vj∥2)Q = \prod_j (I - 2 v_j v_j^\top / \lVert v_j \rVert^2)) or a fixed orthogonal matrix (frozen at initialisation, optionally from the data PCA). Rotations have log⁡∣det⁡J∣=0\log\lvert\det J\rvert = 0, so they are “free” — their only job is to redistribute non-Gaussianity across dimensions.

  2. Marginal Gaussianization. For each dimension independently, apply zi=Φ−1(Fi(xi))z_i = \Phi^{-1}(F_i(x_i)) where FiF_i is a trainable mixture-of-Gaussians CDF. This is where the flow does its work: after enough stacked blocks, the pushforward is approximately N(0,I)\mathcal{N}(0, I).

The model is trained end-to-end by maximising

log⁡pX(x)  =  log⁡pZ(f(x))  +  ∑ℓlog⁡∣det⁡Jfℓ(⋅)∣\log p_X(x) \;=\; \log p_Z(f(x)) \;+\; \sum_\ell \log\lvert\det J_{f_\ell}(\cdot)\rvert

with pZ=N(0,I)p_Z = \mathcal{N}(0, I). gauss_flows computes it for a batch with negative_log_likelihood, and pipekit-train’s TrainingLoop minimises it.

Mathematical background

The 1-D probability integral transform

For a univariate random variable X∼pX \sim p with strictly increasing CDF FF, the classical result is that F(X)∼Uniform[0,1]F(X) \sim \text{Uniform}[0, 1]. Composing with the standard-normal quantile Φ−1\Phi^{-1} gives

z  =  Φ−1 ⁣(F(x))  ∼  N(0,1).z \;=\; \Phi^{-1}\!\big(F(x)\big) \;\sim\; \mathcal{N}(0, 1).

So in 1-D we can Gaussianize any continuous distribution exactly, given its true CDF. The catch is that we don’t know FF; we have to estimate it.

Mixture-of-Gaussians CDF

We approximate FF with a mixture of KK normals,

F(x; π,μ,σ)  =  ∑k=1Kπk Φ ⁣((x−μk)/σk),F(x;\,\pi, \mu, \sigma) \;=\; \sum_{k=1}^{K} \pi_k \,\Phi\!\big((x - \mu_k)/\sigma_k\big),

with π∈ΔK−1\pi \in \Delta^{K-1}, μ∈RK\mu \in \mathbb{R}^K, σ∈R>0K\sigma \in \mathbb{R}_{>0}^K. The corresponding pdf is

f(x; π,μ,σ)  =  ∑kπk σk−1 φ ⁣((x−μk)/σk).f(x;\,\pi, \mu, \sigma) \;=\; \sum_{k} \pi_k \,\sigma_k^{-1}\,\varphi\!\big((x - \mu_k)/\sigma_k\big).

For dd input dimensions we fit one such mixture per dim independently — parameter tensors all have shape (d,K)(d, K) in our layer, so for d=2d = 2 and K=8K = 8 that’s 3⋅2⋅8=483 \cdot 2 \cdot 8 = 48 numbers. The forward map and its log-derivative on dim ii are

zi  =  Φ−1 ⁣(Fi(xi)),log⁡∣∂zi/∂xi∣  =  log⁡fi(xi)  −  log⁡φ(zi).z_i \;=\; \Phi^{-1}\!\big(F_i(x_i)\big), \qquad \log\lvert \partial z_i / \partial x_i \rvert \;=\; \log f_i(x_i) \;-\; \log \varphi(z_i).

Log-determinant structure of a flow block

One block is rotation → marginal. With x∈Rdx \in \mathbb{R}^d for any dd, the rotation Q∈O(d)Q \in O(d) has log⁡∣det⁡Q∣=0\log\lvert\det Q\rvert = 0, so it contributes nothing. The marginal’s Jacobian is diagonal, so

log⁡∣det⁡Jblock(x)∣  =  ∑i=1d[log⁡fi(xirot)−log⁡φ(zi)]\log\lvert\det J_{\text{block}}(x) \rvert \;=\; \sum_{i = 1}^{d} \big[\log f_i(x_i^{\text{rot}}) - \log \varphi(z_i)\big]

with xrot=Qxx^{\text{rot}} = Q x and zi=Φ−1(Fi(xirot))z_i = \Phi^{-1}(F_i(x_i^{\text{rot}})). Stacking LL blocks sums LL such terms. Everything is differentiable, so we can train by maximum likelihood.

Iterative vs parametric Gaussianization

Two ways to choose the block parameters {(Qℓ,πℓ,μℓ,σℓ)}ℓ=1L\{(Q_\ell, \pi_\ell, \mu_\ell, \sigma_\ell)\}_{\ell=1}^L — same architecture, very different philosophies.

  • Iterative Gaussianization (RBIG — Laparra & Malo 2011): greedy, non-gradient, one block at a time. Given the current state YY, fit Qℓ=Q_\ell = PCA(Y)(Y), rotate, fit a per-dim GMM on the rotated data, apply the marginal transform numerically, move on. Laparra shows the negentropy J(Yℓ)=DKL(Yℓ ∥ N(0,I))J(Y_\ell) = D_\text{KL}(Y_\ell \,\|\, \mathcal{N}(0, I)) decreases at a geometric rate under mild conditions. No gradients ever flow — each block is fit once and frozen. Cheap, remarkably good, and a useful warm start (see notebook 03).

  • Parametric Gaussianization: the flow is the same architecture, but all parameters (π,μ,σ,Q)(\pi, \mu, \sigma, Q) across all blocks are learned jointly by gradient descent on the exact NLL. Gradients backprop through the composition, so later blocks can compensate for finite-KK approximation errors in earlier blocks — something RBIG fundamentally cannot do. This notebook trains a parametric Gaussianization flow from scratch.

Both target the same optimum (pZ=Np_Z = \mathcal{N} on the latent), but the path to it is different. Empirically, parametric + IG warm-start is the best of both worlds — notebook 03 shows the numbers.

/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 so each dimension has unit variance, which keeps the initial mixture-component scales (initialised to σ=1\sigma = 1) well-matched to the data.

/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 the flow

Eight blocks of [MixtureGaussianCDF, HouseholderRotation] (the flowjax equivalent of the Keras (Householder, MixtureCDFGaussianization) pair). Mixture means are initialised from Uniform(-3, 3) and Householder reflector vectors from a standard normal; this breaks the init symmetry so training sees useful gradients from epoch 0.

number of blocks           : 8
mixture components / dim   : 8
total trainable parameters : 420

3. Train

The docs train every flow with pipekit-train, which the docs install and gauss_flows itself never imports. gauss_flows supplies the loss, negative_log_likelihood, the exact per-sample NLL with the Jacobian log-dets of every layer; pipekit-train’s TrainingLoop draws the batches, steps Adam and evaluates a held-out tenth of the data after each epoch. EarlyStopping(restore_best=True) stops after max_patience epochs without a lower validation loss and returns the flow of the best epoch. Leaves wrapped in paramax.NonTrainable (fixed rotations) are kept out of the optimiser through EquinoxModelOp’s trainable filter.

fit_flow below wraps those pieces in one call; each later notebook repeats it so that it runs on its own. Without pipekit, fit_gaussianization_flow does the same job on the same loss.

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.2222   (min: +1.1933)
final   val NLL: +1.2135   (min: +1.1981)

4. Pushforward: is z=f(x)z = f(x) actually Gaussian?

The whole point of Gaussianization is that after training, the flow maps the data to an approximate standard normal. A jointplot shows the pushforward scatter together with per-dimension histograms; the black reference curves are φ(z)\varphi(z) so we can eyeball the fit.

pushforward diagnostics
  mean:      [-0.248, -0.341]   target = [0, 0]
  cov[0,0]:  0.413                  target = 1
  cov[1,1]:  0.203                  target = 1
  cov[0,1]:  +0.007                  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>

5. Learned density log⁡pX(x)\log p_X(x)

Evaluate the flow’s exact density on a grid via flow.log_prob. For a normalising flow this is cheap: one forward pass plus the log-det accumulation — no Monte-Carlo integration is needed.

<Figure size 1870x825 with 4 Axes>

6. Sampling from the flow

Draw z∼N(0,I)z \sim \mathcal{N}(0, I) and invert the composition: x=f−1(z)x = f^{-1}(z). The inverse of each MixtureGaussianCDF layer uses a vectorised bisection on Fi(xi)=Φ(zi)F_i(x_i) = \Phi(z_i); the HouseholderRotation inverse is applying the reflections in reverse order (each reflection is self-inverse).

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

7. Round-trip inversion

A flow is a bijection by construction, so f−1(f(x))=xf^{-1}(f(x)) = x up to floating-point and the ε\varepsilon-clamp on F(x)∈[ε,1−ε]F(x) \in [\varepsilon, 1-\varepsilon] that keeps Φ−1\Phi^{-1} bounded. We verify this numerically on the training set.

round-trip L2 error  ||f^{-1}(f(x)) - x||_2
  median : 1.48e-06
  95th%  : 3.95e-06
  max    : 2.50e-05
<Figure size 1100x605 with 1 Axes>

8. Layer-by-layer Gaussianization

The intermediate states x, f1(x), (f2∘f1)(x),…x,\, f_1(x),\, (f_2 \circ f_1)(x), \ldots show how the distribution progressively deforms towards a standard normal. Rotations shuffle the mass across axes; marginal layers pull the per-dimension CDFs towards Φ\Phi.

<Figure size 1485x1485 with 9 Axes>

What to look at

  • Pushforward jointplot: the scatter should look isotropic and the marginals should sit right under the black N(0,1)\mathcal{N}(0, 1) curves.

  • Density contour: should trace the two-moons shape. This is a learned bivariate density, evaluated in closed form on a grid.

  • Sample jointplots: data and samples side-by-side — the 2-D morphology and the per-dim marginals should match.

  • Round-trip error: numerical precision baseline for the bijection; typical error is ≲10−4\lesssim 10^{-4} with a few tail outliers from the CDF clamp.

  • Layer-by-layer: the intuition behind a Gaussianization flow — each (Rotation, Marginal) block nudges the distribution closer to N(0,I)\mathcal{N}(0, I).