!!! note “Requirements”
Beyond gauss_flows, this notebook uses the
rbig package and pandas:
pip install rbig pandas.
This notebook reproduces the
RBIG information-theory notebook
for gauss_flows. We estimate four information-theoretic quantities of a
correlated multivariate Gaussian:
Entropy
Total correlation
Mutual information
KL divergence
Every quantity here ultimately reduces to a differential entropy — the expected surprise of some distribution. The only thing that changes between methods is how we get a density to take that expectation against. We compute each quantity three ways:
| Method | Density object used | Needs a Jacobian? |
|---|---|---|
| Analytical | the known Gaussian covariance (ground truth) | — |
| Change-of-variables | the exact flow density | yes |
| RBIG-way | per-layer total-correlation reduction (no density evaluated) | no |
As icing on the cake we run three models:
RBIG —
AnnealedRBIGfrom therbigpackage.GF-Diagonal — a
gauss_flowsdiagonal Gaussianization flow (fit_rbig).GF-Coupling — a
gauss_flowsmixture-CDF coupling flow (fit_rbig_coupling).
Both gauss_flows models are RBIG warm-started (see the
RBIG warm-start notebook) and then briefly
fine-tuned, so they converge quickly to an accurate density.
0. The measures and their equations¶
All four quantities are functionals of a density. For a continuous random vector with density :
Differential entropy — the average log-density:
For a Gaussian this has a closed form that depends only on the covariance:
Total correlation (multi-information) — the KL divergence between the joint and the product of its marginals, i.e. all the statistical dependence among the coordinates:
For a Gaussian it collapses to a determinant ratio (equivalently, minus the log-determinant of the correlation matrix ):
Mutual information between two blocks — the special case of total correlation between two groups of variables:
KL divergence between two densities — the expected log-ratio:
with the Gaussian closed form (used below for the mean-shifted case)
The change-of-variables (density) route¶
A normalizing flow is an invertible map that pushes the data to a simple base . The change-of-variables formula gives the data density exactly:
Once we can evaluate , entropy is a one-line Monte-Carlo estimate,
, and MI / KL follow from their
definitions above. Both RBIG’s AnnealedRBIG.score_samples and the
gauss_flows flow.log_prob implement exactly this formula — the Jacobian
is accumulated layer by layer.
The RBIG-way (iterative reduction) route¶
A Gaussianization flow is a stack of layers, each a marginal Gaussianization followed by a rotation. After layer the data is , and each layer removes some dependence. Define the information reduction of a layer as the drop in total correlation it produces:
Because the final latent is (approximately) independent standard-normal with , the reductions telescope to the total correlation of the data — without ever evaluating a density or a Jacobian:
Entropy then follows from the marginal decomposition, and KL from a per-marginal divergence to a standard normal plus the residual dependence:
where applies the reference () Gaussianization to the query () samples.
Iterative vs. trained: two ways to build the same flow¶
The two gauss_flows models are fit in fundamentally different ways, and it is
worth being explicit about the contrast — it is the reason the RBIG warm-start
matters.
| Iterative (RBIG) | Trained (gradient ML) | |
|---|---|---|
| How it is fit | greedily, one layer at a time, with closed-form / EM sub-fits (PCA rotation + per-dim mixture or histogram). No gradients. | jointly, by gradient descent on all parameters at once. |
| Objective | each layer locally maximizes the Gaussianity of the current marginals (maximizes ). | globally minimizes the negative log-likelihood , i.e. . |
| Natural estimator | per-layer reduction (the RBIG-way). | the exact density (change-of-variables). |
| Cost & behaviour | fast, deterministic, hard to overfit; but needs many layers and each layer is only locally optimal. | fewer, more expressive layers; can couple dimensions a rotation cannot; but needs a good initialization and an optimizer. |
Crucially the two agree in the limit: both drive the latent toward
independence, so both recover the same . They differ in how
they get there — the iterative method takes many cheap, locally-greedy steps,
while the trained method takes a few expensive, globally-coordinated ones. The
best of both worlds is to warm-start the trainable flow from the iterative
RBIG solution and then fine-tune: the flow already sits near a good optimum,
so a handful of gradient epochs sharpen the density rather than having to
discover the Gaussianization from scratch. That is exactly the recipe used for
both gauss_flows models below.
1. Synthetic data¶
We build a 4-dimensional Gaussian split into two 2-D blocks and with cross-correlations and , exactly as in the RBIG notebook. Because the data is Gaussian, every measure has a closed form, which gives us an exact yardstick for the two estimators. For the KL divergence we use a mean-shifted copy of .
from __future__ import annotations
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
import pandas as pd
import paramax
from pipekit_train import ArrayDataset, EarlyStopping, History, TrainingLoop
from pipekit_train.backends.equinox import EquinoxModelOp
from gauss_flows_models.info_theory import (
entropy,
entropy_reduction,
gaussian_entropy,
gaussian_kl_divergence,
gaussian_mutual_information,
gaussian_total_correlation,
kl_divergence,
kl_divergence_reduction,
mutual_information,
total_correlation,
total_correlation_reduction,
)
from gauss_flows_models.inference import (
fit_rbig,
fit_rbig_coupling,
negative_log_likelihood,
)
from rbig import (
AnnealedRBIG,
estimate_entropy,
estimate_kld,
estimate_mi,
estimate_tc,
kl_divergence_rbig,
mutual_information_rbig,
total_correlation_rbig,
)/home/azureuser/.cache/uv/archive-v0/f1Q8rI7QUTdFMdRtBr6AD/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
seed = 42
rng = np.random.RandomState(seed)
n_samples = 2_000
d = 2 # dimensionality per block
# Joint covariance for [X, Y] with cross-correlations.
C_full = np.eye(2 * d)
C_full[0, d] = C_full[d, 0] = 0.8 # x0 <-> y0
C_full[1, d + 1] = C_full[d + 1, 1] = 0.5 # x1 <-> y1
joint = rng.multivariate_normal(np.zeros(2 * d), C_full, size=n_samples)
X = joint[:, :d].astype(np.float32)
Y = joint[:, d:].astype(np.float32)
XY = joint.astype(np.float32)
CX = C_full[:d, :d]
CY = C_full[d:, d:]
# Mean-shifted distribution for the KL divergence.
mu_shift = np.array([0.5, 0.0])
X_shifted = rng.multivariate_normal(mu_shift, CX, size=n_samples).astype(np.float32)
Xj, Yj, XYj = jnp.asarray(X), jnp.asarray(Y), jnp.asarray(XY)
Xs_j = jnp.asarray(X_shifted)
print(f"X: {X.shape}, Y: {Y.shape}, XY: {XY.shape}")X: (2000, 2), Y: (2000, 2), XY: (2000, 4)
2. Analytical ground truth¶
Closed-form Gaussian expressions via gauss_flows’s analytical helpers — these
evaluate the equations from Section 0 directly on the known covariance, so they
are exact (up to the sampling of the empirical covariance).
H_X_true = float(gaussian_entropy(CX))
H_Y_true = float(gaussian_entropy(CY))
H_XY_true = float(gaussian_entropy(C_full))
TC_X_true = float(gaussian_total_correlation(CX))
TC_XY_true = float(gaussian_total_correlation(C_full))
MI_true = float(gaussian_mutual_information(C_full, dim_x=d))
KL_true = float(
gaussian_kl_divergence(mu_shift, CX, np.zeros(d), CX)
) # KL(N(mu, CX) || N(0, CX))
print(f"H(X) = {H_X_true:+.4f}")
print(f"H(X,Y) = {H_XY_true:+.4f}")
print(f"TC(X) = {TC_X_true:+.4f}")
print(f"TC(X,Y) = {TC_XY_true:+.4f}")
print(f"MI(X;Y) = {MI_true:+.4f}")
print(f"KL = {KL_true:+.4f}")H(X) = +2.8379
H(X,Y) = +5.0211
TC(X) = +0.0000
TC(X,Y) = +0.6547
MI(X;Y) = +0.6547
KL = +0.1250
3. Fit the three models¶
3a. RBIG (rbig package)¶
AnnealedRBIG is the iterative model: it Gaussianizes greedily, one
(rotation, marginal) block at a time, recording the total correlation
remaining after each block. No gradients are involved.
rbig_kw = dict(n_layers=20, rotation="pca", patience=10, random_state=seed)
rbig_X = AnnealedRBIG(**rbig_kw).fit(X)
rbig_Y = AnnealedRBIG(**rbig_kw).fit(Y)
rbig_XY = AnnealedRBIG(**rbig_kw).fit(XY)
rbig_ref = AnnealedRBIG(**rbig_kw).fit(X) # reference Q = N(0, CX) for the KL3b. gauss_flows models — RBIG warm-start + short fine-tune¶
Each flow is first warm-started with the gradient-free RBIG procedure
(Section “Iterative vs. trained”), which already places it near a good
Gaussianization, and then fine-tuned with a few epochs of
fit_flow, the pipekit-train loop of notebook 01 (gradient maximum-likelihood). Because the
warm-start did the heavy lifting, only light training is needed for the density
to become accurate.
class FlowNLL:
"""pipekit-train's task: gauss_flows's negative log-likelihood of a batch."""
def loss_fn(self, flow, batch, key):
x, condition = batch
# an unconditional dataset has no targets, ()
condition = None if isinstance(condition, tuple) else condition
loss = negative_log_likelihood(flow, x, key=key, condition=condition)
return loss, {"loss": loss}
def fit_flow(
key,
flow,
x,
*,
condition=None,
learning_rate=5e-3,
clip_norm=None,
max_epochs=100,
max_patience=10,
batch_size=256,
val_prop=0.1,
):
"""Fit `flow` to the rows of `x` by maximum likelihood with pipekit-train.
A fraction `val_prop` of the rows is held out. Training stops after
`max_patience` epochs without a lower validation loss, and the flow of the
best epoch is returned with the per-epoch train and validation losses.
"""
split_key, loop_key = jr.split(key)
# one shuffle, then the last val_prop of the rows held out
order = np.asarray(jr.permutation(split_key, len(x)))
n_train = len(x) - round(val_prop * len(x))
train_rows, val_rows = order[:n_train], order[n_train:]
def rows(a, idx):
return () if a is None else np.asarray(a)[idx]
batch_size = min(batch_size, n_train)
steps_per_epoch = n_train // batch_size
optimizer = {"name": "adam", "lr": learning_rate}
if clip_norm is not None:
optimizer["clip_norm"] = clip_norm
# paramax.NonTrainable leaves (fixed rotations) stay out of the optimiser
trainable = jax.tree.map(
eqx.is_inexact_array,
flow,
is_leaf=lambda leaf: isinstance(leaf, paramax.NonTrainable),
)
history = History()
trained, _ = TrainingLoop(
EquinoxModelOp(flow, trainable=trainable),
ArrayDataset(rows(x, train_rows), rows(condition, train_rows)),
val_dataset=ArrayDataset(rows(x, val_rows), rows(condition, val_rows)),
task=FlowNLL(),
optimizer_config=optimizer,
max_steps=max_epochs * steps_per_epoch,
steps_per_epoch=steps_per_epoch,
eval_every_n_steps=steps_per_epoch,
log_every_n_steps=steps_per_epoch,
batch_size=batch_size,
seed=int(jr.randint(loop_key, (), 0, 2**31 - 1)),
callbacks=(
history,
EarlyStopping("loss", patience=max_patience, restore_best=True),
),
).run()
# the mean training loss of each epoch, and the validation loss after it
step_losses = np.array([metrics["loss"] for _, metrics in history.train])
n_epochs = len(step_losses) // steps_per_epoch
epoch_losses = step_losses[: n_epochs * steps_per_epoch].reshape(n_epochs, -1)
val_losses = np.array([metrics["loss"] for _, metrics in history.eval])
return trained.module, {"train": epoch_losses.mean(axis=1), "val": val_losses}def fit_diagonal(data, key, n_layers=8, n_components=8, max_epochs=80):
"""RBIG warm-started diagonal Gaussianization flow + short fine-tune."""
flow = fit_rbig(jnp.asarray(data), n_layers=n_layers, n_components=n_components)
flow, _ = fit_flow(
key,
flow,
jnp.asarray(data),
learning_rate=5e-3,
max_epochs=max_epochs,
max_patience=max_epochs,
batch_size=256,
val_prop=0.1,
)
return flow
def fit_coupling(data, key, n_layers=4, n_components=8, max_epochs=80):
"""RBIG warm-started mixture-CDF coupling flow + short fine-tune."""
k_init, k_train = jr.split(key)
flow = fit_rbig_coupling(
jnp.asarray(data),
k_init,
n_layers=n_layers,
n_components=n_components,
nn_width=64,
nn_depth=2,
)
flow, _ = fit_flow(
k_train,
flow,
jnp.asarray(data),
learning_rate=3e-3,
max_epochs=max_epochs,
max_patience=max_epochs,
batch_size=256,
val_prop=0.1,
)
return flow
keys = jr.split(jr.key(0), 8)
diag_X = fit_diagonal(X, keys[0])
diag_Y = fit_diagonal(Y, keys[1])
diag_XY = fit_diagonal(XY, keys[2])
diag_shift = fit_diagonal(X_shifted, keys[3])
cpl_X = fit_coupling(X, keys[4])
cpl_Y = fit_coupling(Y, keys[5])
cpl_XY = fit_coupling(XY, keys[6])
cpl_shift = fit_coupling(X_shifted, keys[7])
# Sanity check: mean log-likelihood per model.
for name, flow in [("GF-Diagonal", diag_XY), ("GF-Coupling", cpl_XY)]:
ll = float(jnp.mean(jax.vmap(flow.log_prob)(XYj)))
print(f"{name:12s} mean log-likelihood on XY: {ll:+.4f} nats")GF-Diagonal mean log-likelihood on XY: -5.0724 nats
GF-Coupling mean log-likelihood on XY: -4.9694 nats
4. Change-of-variables estimates¶
Here every estimate uses an exact log-density, following
and the definitions of MI and KL.
For the flows the density is flow.log_prob (Monte-Carlo over flow samples);
for RBIG it is AnnealedRBIG.score_samples (the same change-of-variables
formula, with the per-layer log-determinant Jacobian).
mc = jr.split(jr.key(1), 24)
n_mc = 5000
# --- GF-Diagonal ---
H_X_diag = float(entropy(diag_X, n_mc, key=mc[0]))
H_XY_diag = float(entropy(diag_XY, n_mc, key=mc[1]))
TC_X_diag = float(total_correlation(diag_X, n_mc, key=mc[2]))
TC_XY_diag = float(total_correlation(diag_XY, n_mc, key=mc[3]))
MI_diag = float(mutual_information(diag_XY, diag_X, diag_Y, n_mc, key=mc[4]))
KL_diag = float(kl_divergence(diag_shift, diag_X, n_mc, key=mc[5]))
# --- GF-Coupling ---
H_X_cpl = float(entropy(cpl_X, n_mc, key=mc[6]))
H_XY_cpl = float(entropy(cpl_XY, n_mc, key=mc[7]))
TC_X_cpl = float(total_correlation(cpl_X, n_mc, key=mc[8]))
TC_XY_cpl = float(total_correlation(cpl_XY, n_mc, key=mc[9]))
MI_cpl = float(mutual_information(cpl_XY, cpl_X, cpl_Y, n_mc, key=mc[10]))
KL_cpl = float(kl_divergence(cpl_shift, cpl_X, n_mc, key=mc[11]))
# --- RBIG ---
H_X_rbig_cov = float(rbig_X.entropy())
H_XY_rbig_cov = float(rbig_XY.entropy())
TC_X_rbig_cov = float(total_correlation_rbig(X))
TC_XY_rbig_cov = float(total_correlation_rbig(XY))
MI_rbig_cov = float(mutual_information_rbig(rbig_X, rbig_Y, rbig_XY))
KL_rbig_cov = float(kl_divergence_rbig(rbig_ref, X_shifted))5. RBIG-way estimates¶
These accumulate the total correlation removed by the Gaussianization
(), with entropy and KL following
the decompositions in Section 0. No Jacobian is evaluated. For the flows we use
total_correlation_reduction / entropy_reduction / kl_divergence_reduction;
for RBIG we use the estimate_* helpers. Mutual information is the total
correlation of the jointly Gaussianized blocks,
.
def mi_reduction(flow_x, flow_y, x, y, fit_joint):
"""RBIG-way MI = total correlation of [G_X(x), G_Y(y)]."""
zx = jax.vmap(flow_x.bijection.inverse)(jnp.asarray(x))
zy = jax.vmap(flow_y.bijection.inverse)(jnp.asarray(y))
z = jnp.concatenate([zx, zy], axis=-1)
flow_z = fit_joint(np.asarray(z))
return float(total_correlation_reduction(flow_z, z))
# --- GF-Diagonal ---
H_X_diag_r = float(entropy_reduction(diag_X, Xj))
H_XY_diag_r = float(entropy_reduction(diag_XY, XYj))
TC_X_diag_r = float(total_correlation_reduction(diag_X, Xj))
TC_XY_diag_r = float(total_correlation_reduction(diag_XY, XYj))
MI_diag_r = mi_reduction(diag_X, diag_Y, X, Y, lambda z: fit_diagonal(z, jr.key(100)))
KL_diag_r = float(kl_divergence_reduction(diag_X, Xs_j))
# --- GF-Coupling ---
H_X_cpl_r = float(entropy_reduction(cpl_X, Xj))
H_XY_cpl_r = float(entropy_reduction(cpl_XY, XYj))
TC_X_cpl_r = float(total_correlation_reduction(cpl_X, Xj))
TC_XY_cpl_r = float(total_correlation_reduction(cpl_XY, XYj))
MI_cpl_r = mi_reduction(cpl_X, cpl_Y, X, Y, lambda z: fit_coupling(z, jr.key(101)))
KL_cpl_r = float(kl_divergence_reduction(cpl_X, Xs_j))
# --- RBIG ---
H_X_rbig_r = float(estimate_entropy(X, **rbig_kw))
H_XY_rbig_r = float(estimate_entropy(XY, **rbig_kw))
TC_X_rbig_r = float(estimate_tc(X, **rbig_kw))
TC_XY_rbig_r = float(estimate_tc(XY, **rbig_kw))
MI_rbig_r = float(estimate_mi(X, Y, **rbig_kw))
KL_rbig_r = float(estimate_kld(X_shifted, X, **rbig_kw))6. Comparison¶
Columns are the three models; rows group the measures by estimation method.
Read the two change-of-vars / RBIG-way rows for each measure side by side:
the iterative RBIG-way estimates (which only need per-layer reductions)
track the analytical values about as well as the trained change-of-variables
estimates (which need the full density), confirming that the two routes agree.
rows = [
("H(X)", "change-of-vars", H_X_true, H_X_rbig_cov, H_X_diag, H_X_cpl),
("H(X)", "RBIG-way", H_X_true, H_X_rbig_r, H_X_diag_r, H_X_cpl_r),
("H(X,Y)", "change-of-vars", H_XY_true, H_XY_rbig_cov, H_XY_diag, H_XY_cpl),
("H(X,Y)", "RBIG-way", H_XY_true, H_XY_rbig_r, H_XY_diag_r, H_XY_cpl_r),
("TC(X)", "change-of-vars", TC_X_true, TC_X_rbig_cov, TC_X_diag, TC_X_cpl),
("TC(X)", "RBIG-way", TC_X_true, TC_X_rbig_r, TC_X_diag_r, TC_X_cpl_r),
("TC(X,Y)", "change-of-vars", TC_XY_true, TC_XY_rbig_cov, TC_XY_diag, TC_XY_cpl),
("TC(X,Y)", "RBIG-way", TC_XY_true, TC_XY_rbig_r, TC_XY_diag_r, TC_XY_cpl_r),
("MI(X;Y)", "change-of-vars", MI_true, MI_rbig_cov, MI_diag, MI_cpl),
("MI(X;Y)", "RBIG-way", MI_true, MI_rbig_r, MI_diag_r, MI_cpl_r),
("KL(P||Q)", "change-of-vars", KL_true, KL_rbig_cov, KL_diag, KL_cpl),
("KL(P||Q)", "RBIG-way", KL_true, KL_rbig_r, KL_diag_r, KL_cpl_r),
]
table = pd.DataFrame(
rows,
columns=["measure", "method", "Analytical", "RBIG", "GF-Diagonal", "GF-Coupling"],
)
table = table.set_index(["measure", "method"])
table.round(4)7. Visual comparison¶
Absolute error of each estimator against the analytical ground truth. Lower is better; the two panels let us compare the change-of-variables (trained density) and RBIG-way (iterative reduction) routes directly.
measures = ["H(X)", "H(X,Y)", "TC(X)", "TC(X,Y)", "MI(X;Y)", "KL(P||Q)"]
models = ["RBIG", "GF-Diagonal", "GF-Coupling"]
fig, axes = plt.subplots(1, 2, figsize=(13, 4.5), sharey=True)
for ax, method in zip(axes, ["change-of-vars", "RBIG-way"]):
sub = table.xs(method, level="method")
err = (sub[models].sub(sub["Analytical"], axis=0)).abs()
err = err.reindex(measures)
x = np.arange(len(measures))
w = 0.25
for i, m in enumerate(models):
ax.bar(x + (i - 1) * w, err[m].values, width=w, label=m)
ax.set_xticks(x)
ax.set_xticklabels(measures, rotation=30, ha="right")
ax.set_title(f"|estimate - analytical| ({method})")
ax.set_ylabel("absolute error (nats)")
ax.legend()
fig.tight_layout()
plt.show()
Summary¶
All three models recover the analytical Gaussian quantities closely. The two estimation routes mirror the two ways the flows are built:
the change-of-variables route leans on each model’s exact log-density — the natural estimator for a trained (maximum-likelihood) flow;
the RBIG-way route only needs the total correlation removed by Gaussianization, — the natural estimator for an iterative flow, and it never forms a Jacobian.
The RBIG warm-start is what lets the gauss_flows diagonal and coupling flows
reach accurate densities after only a short fine-tune: the iterative solution
supplies a near-optimal initialization, and gradient training then sharpens it.