Density destructors
Naming the object: an invertible map that destroys structure, built by alternating a marginal Gaussianization with a rotation
04 · Density destructors¶
The earlier notebooks assembled the parts: an invertible map carries a density ((4)), maps compose with additive log-determinants ((4)), and a standard Gaussian is the natural target. Now we name the object those parts describe, a density destructor, and build one.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import rbig
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 SCATTER_KW, style_ax, use_compact_figures
from gauss_flows_models.inference import fit_rbig
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "rbig", "gauss_flows_models")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
matplotlib : 3.11.2
rbig : 0.1.16
gauss_flows_models: 0.3.0
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
Throughout, the data are points of two moons in coordinates, standardised per coordinate so that the target is .
# Shapes: sample (N) = 2,000; state (D_x) = 2
SampleState = Float[ArrayLike, "sample state"]
# x̃ ~ two moons, noise 0.05, (sample, state)
moons: SampleState
moons, _ = make_moons(2000, noise=0.05, random_state=0)
# x_d = (x̃_d − mean(x̃_d)) / std(x̃_d), per coordinate d, (sample, state)
data: SampleState = (moons - moons.mean(0)) / moons.std(0)1. What is a density destructor?¶
The map destroys the density: everything that made structured (skew, heavy tails, several modes, dependence between coordinates) is removed, and isotropic Gaussian noise is left. “Normalizing flow” in machine learning, “Gaussianization” in signal processing and “density destructor” Inouye & Ravikumar, 2018 are three names for this one map, and each earlier notebook is one of the things it gives us:
| Once we have a destructor | we get | from |
|---|---|---|
| the log-density (4), with (5) for a deep | an exact density | notebooks 00 and 01 |
| run backward on Gaussian noise, (4) | a generator | notebook 02 |
| independent coordinates with Gaussian marginals | coordinates in which information measures are easy | notebook 03 |
The whole curriculum is about building good destructors.
2. The classic recipe: a nonlinearity and a rotation¶
How do we build for a tangled distribution like two moons? Gaussianization Chen & Gopinath, 2000, in the form of rotation-based iterative Gaussianization Laparra et al., 2011, alternates two moves that each fix what the other cannot.
Marginal Gaussianization. Each coordinate , for , goes through its own CDF and then the inverse standard-normal CDF,
where is the CDF of coordinate and the standard-normal CDF. Every axis becomes standard normal, but an elementwise map cannot touch the dependence between axes.
Rotation. An orthogonal matrix , with , mixes the axes. It is free, , and it turns the dependence left by into new non-Gaussian structure along each axis, which the next marginal step can remove.
One layer of the destructor is a marginal step followed by a rotation,
and the destructor is the composition (1) of such layers. We take one layer with rbig and look at the data after each move (Figure 1).
# today (rbig)
# fit g, one CDF F_d per coordinate
marginal_step = rbig.MarginalGaussianize().fit(data)
# today (rbig)
# g(x)_d = Φ⁻¹(F_d(x_d)), (sample, state)
data_marginal: SampleState = marginal_step.transform(data)
# today (rbig)
# fit a random orthogonal Q, QᵀQ = I
rotation_step = rbig.RandomRotation(random_state=0).fit(data_marginal)
# today (rbig)
# f₁(x) = Q g(x), (sample, state)
data_rotated: SampleState = rotation_step.transform(data_marginal)
Scalar = Float[ArrayLike, ""]
# corr(g(x)₁, g(x)₂)
correlation: Scalar = np.corrcoef(data_marginal.T)[0, 1]
print(f"per-axis std after the marginal step: {data_marginal.std(0).round(4)}")
print(f"correlation after the marginal step: {correlation:.3f}")per-axis std after the marginal step: [0.9997 0.9997]
correlation after the marginal step: -0.375
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
panels = [
(data, "data $\\mathbf{x}$", "C0"),
(data_marginal, "after the marginal step $g$", "C1"),
(data_rotated, "after the rotation $\\mathbf{Q}$", "C1"),
]
for ax, (points, title, color) in zip(axes, panels, strict=True):
ax.scatter(points[:, 0], points[:, 1], color=color, **SCATTER_KW)
ax.set(title=title, xlim=(-4, 4), ylim=(-4, 4), xlabel="$x_1$", ylabel="$x_2$")
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:One layer on two moons. Left: the standardised data. Middle: after the marginal Gaussianization each axis is standard normal but the crescents remain. Right: after a random rotation the leftover structure is spread across both axes.
After the marginal step each axis has unit standard deviation, yet the crescents are still there and the two axes are still correlated: an elementwise map cannot remove dependence. The rotation moves that structure onto new axes, where it again looks non-Gaussian coordinate by coordinate, so the next marginal step has something to work on. One RBIGLayer in rbig is exactly this pair.
3. Iterate: the picture behind Gaussianization¶
Stacking many layers grinds the distribution down towards . rbig.AnnealedRBIG is this iterated destructor; we fit layers and look at the data after 0, 3, 12 and all 30 of them (Figure 2).
# K, the number of layers
n_layers = 30
# today (rbig)
# f = f_K ∘ … ∘ f₁ with fₖ = Qₖ gₖ and random rotations
destructor = rbig.AnnealedRBIG(n_layers=n_layers, rotation="random", random_state=0)
# today (rbig)
# fit each layer to the output of the one before
destructor.fit(data)
# user
# x_K = f_K ∘ … ∘ f₁(x), with K = n_applied
def through_layers(n_applied: int) -> SampleState:
"""The data after the first ``n_applied`` layers of ``destructor``."""
# x₀ = x, (sample, state)
current: SampleState = data
for layer in destructor.layers_[:n_applied]:
# today (rbig)
# xₖ = fₖ(xₖ₋₁)
current = layer.transform(current)
return currentPushing the data through all of the layers gives the latent, and we check its first two moments and the likelihood rbig assigns to the data.
SampleLatent = Float[ArrayLike, "sample latent"]
# user
# z = f(x), the data through all K layers, (sample, latent)
latent_rbig: SampleLatent = through_layers(len(destructor.layers_))
print(f"fitted layers: {len(destructor.layers_)}")
print(f"latent per-axis mean: {latent_rbig.mean(0).round(4)}")
print(f"latent per-axis std: {latent_rbig.std(0).round(4)}")
print(f"latent correlation: {np.corrcoef(latent_rbig.T)[0, 1]:.4f}")
print(f"mean log-likelihood (rbig): {destructor.score(data):.3f}")fitted layers: 30
latent per-axis mean: [-0. 0.]
latent per-axis std: [0.9999 0.9994]
latent correlation: -0.0005
mean log-likelihood (rbig): -1.662
fig, axes = plt.subplots(1, 4, figsize=(16, 4.5))
for ax, n_applied in zip(axes, [0, 3, 12, n_layers], strict=True):
points = through_layers(n_applied)
color = "C0" if n_applied == 0 else "C1"
ax.scatter(points[:, 0], points[:, 1], color=color, **SCATTER_KW)
title = "data" if n_applied == 0 else f"{n_applied} layers"
ax.set(title=title, xlim=(-4, 4), ylim=(-4, 4), xlabel="$z_1$", ylabel="$z_2$")
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:Two moons pushed through 0, 3, 12 and 30 layers of rbig.AnnealedRBIG. The crescents are worn away layer by layer until an isotropic Gaussian cloud is left.
After 30 layers the latent has zero mean, unit standard deviation on each axis and almost no correlation between the axes: the moons have been destroyed. That sequence is Gaussianization, an iterated nonlinearity and rotation grinding the structure away. How many layers are enough is a convergence question, which notebook 06 answers with Gaussianity diagnostics.
4. Run it backward to generate¶
A destructor is invertible, so its inverse is a generator: draw Gaussian noise and push it back through the inverted layers,
rbig does this with sample, which inverts each marginal step and transposes each rotation (Figure 3).
# today (rbig)
# x = f⁻¹(z) with z ~ N(0, I), 2,000 draws, (sample, state)
generated: SampleState = np.asarray(destructor.sample(2000, random_state=1))fig, axes = plt.subplots(1, 2, figsize=(10, 5), sharex=True, sharey=True)
axes[0].scatter(data[:, 0], data[:, 1], color="C0", **SCATTER_KW)
axes[0].set(title="data $\\mathbf{x} \\sim p_x$")
axes[1].scatter(generated[:, 0], generated[:, 1], color="C2", **SCATTER_KW)
axes[1].set(title="samples $f^{-1}(\\mathbf{z})$")
for ax in axes:
ax.set(xlim=(-3, 3), ylim=(-3, 3), xlabel="$x_1$", ylabel="$x_2$")
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 3:Left: the two-moons data. Right: 2000 samples from the inverse of the rbig destructor applied to standard-normal noise.
The same map, read in reverse, turns Gaussian noise back into two moons. A good destructor is a density estimator in one direction and a generative model in the other: one object, both jobs.
5. The bridge: the same destructor in gauss_flows¶
fit_rbig builds the destructor as a FlowJax Transformed distribution. Each of its layers is a PCA rotation followed by a MixtureGaussianCDF marginal, fitted in closed form (an EM fit per coordinate, no gradients) to the state that reaches it, exactly the greedy construction of section 3. Its bijection runs from the base to the data, so the destructor is the bijection’s inverse. We fit 8 layers and look at the latent and at samples (Figure 4).
# the data as a JAX array, (sample, state)
data_jax: SampleState = jnp.asarray(data)
# today (gauss_flows)
# 8 layers, each a PCA rotation and an M-component MixtureGaussianCDF marginal
flow: Transformed = fit_rbig(data_jax, n_layers=8, n_components=8)
# today (gauss_flows)
# z = f(x), the inverse of the flow's bijection, (sample, latent)
latent_flow: SampleLatent = np.asarray(jax.vmap(flow.bijection.inverse)(data_jax))
PerSample = Float[ArrayLike, " sample"]
# today (gauss_flows)
# log p_x(x) = log p_z(f(x)) + log |det ∂f/∂x|, (sample)
log_px_flow: PerSample = flow.log_prob(data_jax)
# today (gauss_flows)
# x = f⁻¹(z) with z ~ N(0, I), 2,000 draws, (sample, state)
generated_flow: SampleState = np.asarray(flow.sample(jr.key(1), (2000,)))
print(f"latent per-axis mean: {latent_flow.mean(0).round(4)}")
print(f"latent per-axis std: {latent_flow.std(0).round(4)}")
print(f"latent correlation: {np.corrcoef(latent_flow.T)[0, 1]:.4f}")
print(f"mean log-likelihood (gauss_flows): {float(log_px_flow.mean()):.3f}")latent per-axis mean: [0.0005 0. ]
latent per-axis std: [1.005 1.0035]
latent correlation: -0.0015
mean log-likelihood (gauss_flows): -1.351
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].scatter(latent_flow[:, 0], latent_flow[:, 1], color="C1", **SCATTER_KW)
axes[0].set(title="latent $f(\\mathbf{x})$", xlim=(-4, 4), ylim=(-4, 4))
axes[0].set(xlabel="$z_1$", ylabel="$z_2$")
axes[1].scatter(generated_flow[:, 0], generated_flow[:, 1], color="C2", **SCATTER_KW)
axes[1].set(title="samples from the flow", xlim=(-3, 3), ylim=(-3, 3))
axes[1].set(xlabel="$x_1$", ylabel="$x_2$")
for ax in axes:
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 4:The gauss_flows destructor from fit_rbig with 8 layers. Left: the latent f(x) of the two-moons data, standardised but with structure left. Right: 2000 samples drawn from the flow, which join the tips of the moons.
With 8 layers the gauss_flows latent has zero mean, unit standard deviation and almost no correlation, the same first two moments as the 30-layer rbig latent. The scatter still shows structure, though, and the samples join the tips of the two moons. Matching the mean and covariance does not make a distribution Gaussian; notebook 06 gives tests that see the difference. Because the flow is a FlowJax distribution, it also gives the exact log-density (5) and samples, and it is the warm start that later parts refine by training on the likelihood. The two packages model the marginals differently (Gaussian mixtures here, empirical CDFs in rbig), so their mean log-likelihoods differ.
Recap¶
| Concept | Equation | In code |
|---|---|---|
| density destructor | (1) | rbig.AnnealedRBIG, fit_rbig |
| marginal Gaussianization | (2) | rbig.MarginalGaussianize |
| one layer | (3) | marginal step, then rbig.RandomRotation |
| many layers | (1) | destructor.layers_ |
| density of a deep destructor | (5) | flow.log_prob(x) |
| generate | (4) | destructor.sample, flow.sample |
Next. Iterating many times is numerically delicate: CDFs reach 0 and 1, blows up there, and log-determinants must not drift. The next notebook covers the clamping, jitter and float64 bookkeeping that keep a deep destructor stable.
- Inouye, D. I., & Ravikumar, P. (2018). Deep Density Destructors. International Conference on Machine Learning (ICML).
- Chen, S. S., & Gopinath, R. A. (2000). Gaussianization. Advances in Neural Information Processing Systems (NeurIPS).
- Laparra, V., Camps-Valls, G., & Malo, J. (2011). Iterative Gaussianization: From ICA to Random Rotations. IEEE Transactions on Neural Networks, 22(4), 537–549. 10.1109/TNN.2011.2106511
- Meng, C., Song, Y., Song, J., & Ermon, S. (2020). Gaussianization Flows. International Conference on Artificial Intelligence and Statistics (AISTATS).