Convergence and stopping
Each RBIG layer removes exactly the marginal divergence it Gaussianizes away, so the per-layer reduction tells the loop when to stop
01 · Convergence and stopping¶
Notebook 00 ran a fixed thirty layers. How many does a dataset need, and how can the loop tell from the data that it is done? Laparra et al. Laparra et al., 2011 answer with an identity: each layer lowers the KL divergence from by exactly the divergence its marginal step removes, so the per-layer reduction is a convergence signal, and the reductions add up to the divergence of the data. We check the identity on a dataset where the answer is known exactly, build a stopping rule on it, and compare that rule with the one in rbig.
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 matplotlib.pyplot as plt
import numpy as np
import rbig
from jaxtyping import ArrayLike, Float
from scipy import integrate, stats
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("numpy", "scipy", "matplotlib", "rbig")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
numpy : 2.4.3
scipy : 1.17.1
matplotlib: 3.11.2
rbig : 0.1.16
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. A dataset with a known answer¶
To test a convergence signal we need a dataset whose distance from a standard normal is known. We bend a standard-normal cloud into a banana with a shear of strength ,
The shear’s Jacobian is triangular with ones on the diagonal, so its log-determinant is zero and the banana has the entropy of the cloud it came from, . Its KL divergence from is then the expected squared norm it gained, , which is
exactly. We take , so the loop has 0.49 nats to remove.
# Shapes: sample (N) = 2,000; state (D_x) = 2
SampleState = Float[ArrayLike, "sample state"]
# β, the strength of the shear
bend: float = 0.7
# w ~ 𝒩(0, I), (sample, state)
draws: SampleState = rng.standard_normal((2000, 2))
# x₂ = w₂ + β (w₁² − 1), (sample)
sheared: Float[ArrayLike, " sample"] = draws[:, 1] + bend * (draws[:, 0] ** 2 - 1)
# x = (w₁, x₂), (sample, state)
samples: SampleState = np.column_stack([draws[:, 0], sheared])The total correlation (5) needs one more number. The first coordinate is standard normal and the joint entropy is , so , and the density of is a one-dimensional integral over , which we evaluate on a grid.
# Shapes: grid_line = 2,201 points on [−8, 14]; node = 4,001 quadrature nodes on [−10, 10]
# a grid over the support of x₂, (grid_line)
grid: Float[ArrayLike, " grid_line"] = np.linspace(-8, 14, 2201)
# the nodes t of the integral over w₁, (node)
nodes: Float[ArrayLike, " node"] = np.linspace(-10, 10, 4001)
# 𝒩(t; 0, 1) 𝒩(x₂ − β (t² − 1); 0, 1) at every grid value and node, (grid_line, node)
integrand: Float[ArrayLike, "grid_line node"] = stats.norm.pdf(nodes) * stats.norm.pdf(
grid[:, None] - bend * (nodes**2 - 1)
)
# p(x₂) = ∫ 𝒩(t; 0, 1) 𝒩(x₂ − β (t² − 1); 0, 1) dt, (grid_line)
grid_density: Float[ArrayLike, " grid_line"] = integrate.trapezoid(
integrand, nodes, axis=1
)From the density follow the entropy of , the total correlation and the KL divergence of the second marginal; by (3) the last two must add up to .
# ℍ[p_{x₂}] = −∫ p log p
sheared_entropy: float = -integrate.trapezoid(
grid_density * np.log(grid_density + 1e-300), grid
)
# ½ log(2πe), the entropy of 𝒩(0, 1)
normal_entropy: float = 0.5 * np.log(2 * np.pi * np.e)
# TC[p_x] = ℍ[p_{x₂}] − ½ log(2πe)
tc_exact: float = sheared_entropy - normal_entropy
# KL[p_{x₂} ‖ 𝒩(0, 1)] = −ℍ[p_{x₂}] + ½ 𝔼[x₂²] + ½ log 2π, with 𝔼[x₂²] = 1 + 2β²
marginal_kl_exact: float = (
-sheared_entropy + 0.5 * (1 + 2 * bend**2) + 0.5 * np.log(2 * np.pi)
)
print(
f"TC {tc_exact:.4f}, marginal KL {marginal_kl_exact:.4f}, sum {tc_exact + marginal_kl_exact:.4f}, beta^2 {bend**2:.4f}"
)TC 0.2852, marginal KL 0.2048, sum 0.4900, beta^2 0.4900
Of the 0.49 nats, 0.285 are dependence between the coordinates and 0.205 are the non-Gaussian second marginal. Before running the loop we try the direct estimate of the total correlation in rbig.
# today (rbig)
# TC with kernel-density marginal entropies and a Gaussian fit to the joint
tc_direct: float = rbig.total_correlation(samples)
print(f"rbig.total_correlation {tc_direct:+.4f} nats, exact {tc_exact:+.4f}")rbig.total_correlation -0.0590 nats, exact +0.2852
It returns a negative number for a quantity that cannot be negative. rbig.total_correlation estimates the joint entropy by fitting a Gaussian to the data, and a Gaussian has the largest entropy at a given covariance (1), so the estimate is too low by the joint negentropy of the banana. That is a bug in rbig (rbig#160). RBIG itself never needs the joint entropy of the raw data, as the next section shows.
2. What one layer removes¶
The KL divergence from splits into the total correlation and one divergence per marginal (3). The marginal step of a layer sets every marginal term to zero and leaves the total correlation where it was (7), and the rotation keeps the total (8). So layer lowers the divergence by exactly
where is coordinate of the state that layer receives. Every is non-negative, so the divergence never rises, and the reductions add up to the divergence of the data,
The first marginal step removes only the marginal terms of the data, so the total correlation is what the later layers remove,
Each term of is a one-dimensional divergence, which rbig.kl_to_standard_normal estimates from a kernel density by quadrature.
One layer is the marginal step and a rotation, either PCA or a fresh random rotation, as in notebook 00.
# Shapes: layer (K) = 30
# user
# x_k = Q_k g_k(x_{k−1})
def rbig_layer(points: SampleState, kind: str, k: int) -> SampleState:
"""One RBIG layer with a PCA or a random rotation, fitted to ``points``."""
# today (rbig)
# fit ĝ_k to each coordinate of x_{k−1}
marginal = rbig.MarginalGaussianize().fit(points)
# today (rbig)
# g_k(x_{k−1}), (sample, state)
marginalised: SampleState = marginal.transform(points)
# today (rbig)
# fit Q_k, PCA or a fresh random rotation, to g_k(x_{k−1})
rotation: rbig.PCARotation | rbig.RandomRotation = (
rbig.PCARotation(whiten=False)
if kind == "PCA"
else rbig.RandomRotation(random_state=k)
)
rotation.fit(marginalised)
# today (rbig)
# Q_k g_k(x_{k−1}), (sample, state)
return rotation.transform(marginalised)The loop records and then applies layer .
PerLayer = Float[ArrayLike, " layer"]
# user
# run K layers and return Δ_k for k = 1, …, K and the state x_K
def reduction_trace(points: SampleState, kind: str, n_layers: int = 30):
"""Run ``n_layers`` RBIG layers with ``kind`` rotations, recording Δ_k."""
# Δ_1, …, Δ_k so far
reductions: list[float] = []
for k in range(n_layers):
# today (rbig)
# Δ_k = ∑_d KL[p_{x_{k−1,d}} ‖ 𝒩(0, 1)]
reductions.append(rbig.kl_to_standard_normal(points).sum())
# user
# x_k = Q_k g_k(x_{k−1}), (sample, state)
points: SampleState = rbig_layer(points, kind, k)
return np.array(reductions), pointsA layer applied to data that are already standard normal removes nothing, so whatever the estimator reports there is noise. We run eight random-rotation layers on five standard-normal datasets of the same size and take the 95% quantile of from the second layer on as the floor .
# Shapes: draw = 5 standard-normal datasets
# user
# Δ_2, …, Δ_8 of the loop on five standard-normal datasets, (draw, layer)
null_traces: Float[ArrayLike, "draw layer"] = np.array(
[
reduction_trace(rng.standard_normal((2000, 2)), "random", 8)[0][1:]
for _ in range(5)
]
)
# Δ⋆, the 95% quantile of Δ_k on standard-normal data
reduction_floor: float = np.quantile(null_traces, 0.95)
print(
f"Delta_k on standard-normal data: mean {null_traces.mean():.4f}, 95% quantile {reduction_floor:.4f}"
)Delta_k on standard-normal data: mean 0.0026, 95% quantile 0.0047
A reduction below is indistinguishable from no reduction at all. We run thirty layers with PCA rotations and thirty with random rotations on the banana and compare the running sums with the exact divergence and total correlation.
# Δ_1, …, Δ_K of each loop
traces: dict[str, PerLayer] = {}
# x_K of each loop
latents: dict[str, SampleState] = {}
for kind in ["PCA", "random"]:
# user
# Δ_1, …, Δ_K and x_K, (layer), (sample, state)
trace: PerLayer
latent: SampleState
trace, latent = reduction_trace(samples, kind)
traces[kind] = trace
latents[kind] = latent
# ∑_{k ≤ K} Δ_k after 5, 10 and 30 layers
running: list[str] = [f"{trace[:k].sum():.3f}" for k in (5, 10, 30)]
# ∑_{k ≥ 2} Δ_k
tc_estimate: float = trace[1:].sum()
print(
f"{kind:6s} Delta_1 {trace[0]:.3f}, sum after 5, 10, 30 layers {running}, sum from layer 2 {tc_estimate:.3f}"
)PCA Delta_1 0.211, sum after 5, 10, 30 layers ['0.443', '0.456', '0.481'], sum from layer 2 0.270
random Delta_1 0.211, sum after 5, 10, 30 layers ['0.388', '0.435', '0.499'], sum from layer 2 0.288
colors = {"PCA": DATA_COLOR, "random": LATENT_COLOR}
layer_index = np.arange(1, 31)
fig, (left, right) = plt.subplots(1, 2, figsize=(12, 4.2))
for kind, trace in traces.items():
left.semilogy(layer_index, trace, "o-", ms=3, color=colors[kind], label=kind)
right.plot(layer_index, trace.cumsum(), "o-", ms=3, color=colors[kind], label=kind)
left.axhspan(1e-4, reduction_floor, color="0.85", label="noise floor")
left.set(xlabel="layer k", ylabel="Δ_k (nats)", ylim=(1e-3, 0.5))
right.axhline(bend**2, color="0.3", ls="--", lw=1, label="exact KL = β²")
right.set(xlabel="layer k", ylabel="∑ Δ up to layer k (nats)", ylim=(0, 0.6))
for ax in (left, right):
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:Left: the reduction Δ_k each layer makes, with PCA and with random rotations, on a log scale; the band is the estimator’s noise floor, below its 95% quantile Δ⋆. Right: the running sum of the reductions against the exact divergence β² = 0.49 nats. PCA’s reductions fall steadily into the floor; random rotations remove less per layer, unevenly, and need more layers to reach it.
The identity holds to the accuracy of the estimator. The first reduction, 0.211 nats, is the divergence of the raw marginals, against an exact 0.205, and the sums of the later reductions estimate the total correlation at 0.270 (PCA) and 0.288 (random), against an exact 0.285. After thirty layers the running sums reach 0.481 and 0.499 nats against 0.49. That is as close as the estimator allows: each of the thirty reductions carries up to nats of noise. The late layers still remove real divergence, but less per layer than the estimator can tell from nothing.
3. A stopping rule¶
We stop at the first layer where the reduction has been below the floor for three consecutive layers, the last three layers having removed nothing the estimator can detect.
# user
# the first K at which Δ_{K−2}, Δ_{K−1}, Δ_K are all below Δ⋆
def stopping_depth(trace: PerLayer, patience: int = 3) -> int:
"""The number of layers after which ``patience`` reductions in a row are below the floor."""
# the number of consecutive reductions below Δ⋆
quiet = 0
for k, reduction in enumerate(trace, start=1):
# count the consecutive reductions below Δ⋆
quiet: int = quiet + 1 if reduction < reduction_floor else 0
if quiet == patience:
return k
return len(trace)We read off the depth and the two sums at that depth.
for kind, trace in traces.items():
# user
# K at the stop
depth: int = stopping_depth(trace)
# ∑_{k ≤ K} Δ_k at the stop
kl_at_stop: float = trace[:depth].sum()
# ∑_{2 ≤ k ≤ K} Δ_k at the stop
tc_at_stop: float = trace[1:depth].sum()
print(
f"{kind:6s} stops after {depth:2d} layers: KL {kl_at_stop:.3f} (exact {bend**2:.3f}), TC {tc_at_stop:.3f} (exact {tc_exact:.3f})"
)PCA stops after 9 layers: KL 0.454 (exact 0.490), TC 0.243 (exact 0.285)
random stops after 15 layers: KL 0.467 (exact 0.490), TC 0.256 (exact 0.285)
The rule needs no layer count from us. It stops the PCA loop after 9 layers, with 93% of the divergence removed, and the random-rotation loop after 15, with 95%, because a random rotation keeps exposing structure the earlier ones missed and its reductions keep jumping above the floor. What is left, about 0.02 to 0.04 nats, is the residual term of (4): real divergence, spread over many later layers that each remove less than the floor. Stopping trades that residual for depth. After thirty layers both latents are round clouds.
panels = {
"data": samples,
"PCA, 30 layers": latents["PCA"],
"random, 30 layers": latents["random"],
}
fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.3), sharex=True, sharey=True)
for ax, (title, points) in zip(axes, panels.items(), strict=True):
color = DATA_COLOR if title == "data" else LATENT_COLOR
ax.scatter(points[:, 0], points[:, 1], color=color, **SCATTER_KW)
ax.set(title=title, xlabel="first coordinate", xlim=(-4, 6), ylim=(-4, 6))
ax.set_aspect("equal")
style_ax(ax)
axes[0].set_ylabel("second coordinate")
fig.tight_layout()
plt.show()
Figure 2:The banana (left) and its latent after thirty RBIG layers with PCA rotations (centre) and random rotations (right). Both loops have reached a round cloud; the reductions of the last layers are inside the estimator’s noise floor.
4. The stopping rule in rbig¶
rbig.AnnealedRBIG runs the same loop and stops when its record of the total correlation, tc_per_layer_, has changed by less than tol for patience consecutive layers. It records the direct estimate of section 1 after every layer, and we look at the first few entries.
# today (rbig)
# RBIG with PCA rotations, at most 40 layers, stopped by tol and patience
annealed = rbig.AnnealedRBIG(
n_layers=40, rotation="pca", patience=10, tol=1e-4, random_state=0
).fit(samples)
# today (rbig)
# the TC record: the raw data, then the state after each layer, (layer)
tc_record: PerLayer = np.asarray(annealed.tc_per_layer_)
print(
f"layers {len(annealed.layers_)}, tc_per_layer_[:4] {tc_record[:4].round(4).tolist()}"
)layers 20, tc_per_layer_[:4] [-0.059, -0.1373, -0.0785, -0.0313]
Every entry is negative. Once a PCA rotation has decorrelated the state, a Gaussian fit to it has the summed entropies of Gaussian marginals, so the direct estimate becomes minus the summed marginal negentropies (3), a measure of how far the marginals still are from Gaussian rather than of dependence. It still falls to zero as the loop converges, so it works as a stopping signal, but its values are not total correlations. The total correlation AnnealedRBIG reports is the first entry minus the last.
# today (rbig)
# TC₀ − TC_K from the record
tc_reported: float = annealed.total_correlation_reduction()
print(
f"AnnealedRBIG.total_correlation_reduction {tc_reported:+.4f} nats, exact {tc_exact:+.4f}"
)AnnealedRBIG.total_correlation_reduction -0.0593 nats, exact +0.2852
It inherits the wrong sign of the first entry, which is the direct estimate on the raw data; that is a bug in rbig (rbig#162). The sum of reductions (5) never estimates a joint entropy, which is why it got the total correlation right in section 2. The depth AnnealedRBIG picks depends on tol, and on how noisy its signal is for each rotation.
# user
# the number of layers AnnealedRBIG fits before it stops, at most 40
def annealed_depth(kind: str, tol: float) -> int:
"""The depth ``AnnealedRBIG`` picks with ``kind`` rotations and tolerance ``tol``."""
# today (rbig)
# RBIG stopped by tol and patience
model = rbig.AnnealedRBIG(
n_layers=40, rotation=kind, patience=10, tol=tol, random_state=0
)
model.fit(samples)
return len(model.layers_)We sweep tol over three decades for both rotations.
for kind in ["pca", "random"]:
# user
# the depth for tol = 10⁻², 10⁻³, 10⁻⁴
depths: list[int] = [annealed_depth(kind, tol) for tol in (1e-2, 1e-3, 1e-4)]
print(f"{kind:6s} depth for tol 1e-2, 1e-3, 1e-4: {depths}")pca depth for tol 1e-2, 1e-3, 1e-4: [15, 17, 20]
random depth for tol 1e-2, 1e-3, 1e-4: [22, 37, 40]
Each tenfold tighter tol adds layers, and with random rotations at 10-4 the loop runs to the cap of 40: each new rotation moves the record by more than 10-4 even when the state is close to Gaussian. A tolerance only means something next to the noise of the signal it is compared with, which is why our rule uses the measured floor .
Finally, AnnealedRBIG estimates the entropy of the data as minus the mean log-density of its training points. The banana’s entropy is exact, .
# today (rbig)
# ℍ[p_x] ≈ −(1/N) ∑ₙ log p̂(xₙ)
entropy_estimate: float = annealed.entropy()
# ℍ[p_x] = ℍ[𝒩(0, I)] = log(2πe)
entropy_exact: float = 2 * normal_entropy
print(f"AnnealedRBIG.entropy {entropy_estimate:.4f} nats, exact {entropy_exact:.4f}")AnnealedRBIG.entropy 2.8426 nats, exact 2.8379
The two agree to 0.005 nats. The entropy comes from the stack’s log-determinants and never needs a Gaussian fit to non-Gaussian data.
Recap¶
| Piece | Equation | In code |
|---|---|---|
| a banana with a known divergence | (1), (2) | samples |
| what layer removes | (3) | rbig.kl_to_standard_normal(points).sum() |
| the reductions add up to the divergence | (4) | trace.cumsum() |
| the total correlation, the RBIG way | (5) | trace[1:].sum() |
| the stopping rule | three times in a row | stopping_depth |
rbig’s stopping rule | change in tc_per_layer_ below tol | AnnealedRBIG(tol=..., patience=...) |
Next. PCA and random rotations converged here at different speeds. The next notebook compares the rotations on data where the choice matters.
- 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