Numerical mechanics of bijectors
Saturated CDFs, clamps, log-space probits, precision and the round-trip test
05 · Numerical mechanics of bijectors¶
A Gaussianization flow applies the marginal step many times Chen & Gopinath, 2000Laparra et al., 2011, where is the CDF of one dimension of the data and is the probit, the inverse of the standard-normal CDF . On paper each step is harmless. In floating point rounds to exactly 0 or 1 far enough into the tails, the probit sends those values to , and a sum of thousands of log-determinants slowly loses its low-order digits. This notebook is the engineering that keeps the maths of the earlier notebooks runnable.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import math
from collections.abc import Callable
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import jax.scipy.stats as jstats
import matplotlib.pyplot as plt
import numpy as np
import rbig
from jaxtyping import ArrayLike, Float, Int
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import (
HouseholderRotation,
MixtureGaussianCDF,
MixtureLogisticCDF,
RQSplineMarginal,
)
# The subject is precision, so float64 is on; section 3 uses explicit float32.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(5)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "rbig", "gauss_flows_maps")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_maps: 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
1. Where the round-trip error lives¶
A bijection should come back exactly: . We compare two marginal maps on samples of . The first is the empirical-CDF marginal of rbig, which interpolates the CDF between the sorted samples. The second is a smooth MixtureGaussianCDF placed on the same data with from_data. Figure 1 plots the round-trip error of each sample against , its distance into the tail.
# Shapes: sample (N) = 4,000; state (D_x) = 1
SampleState = Float[ArrayLike, "sample state"]
SampleLatent = Float[ArrayLike, "sample latent"]
# user
# |f⁻¹(f(xₙ)) − xₙ| for every sample
def round_trip_error(bijection: eqx.Module, samples: SampleState) -> SampleState:
"""|f⁻¹(f(x)) − x| for every row of ``samples``."""
# zₙ = f(xₙ), (sample, latent)
latents: SampleLatent = jax.vmap(bijection.transform)(samples)
# x̂ₙ = f⁻¹(zₙ), (sample, state)
recovered: SampleState = jax.vmap(bijection.inverse)(latents)
return jnp.abs(recovered - samples)
# user
# the round trip, compiled once per bijection
compiled_round_trip_error: Callable[[eqx.Module, SampleState], SampleState]
compiled_round_trip_error = eqx.filter_jit(round_trip_error)# x ~ 𝒩(0, 1.6²), (sample, state)
samples: SampleState = rng.standard_normal((4000, 1)) * 1.6
PerSample = Float[ArrayLike, " sample"]
# |xₙ|, the distance of each sample into the tail
distance: PerSample = np.abs(samples)[:, 0]
# today (rbig)
# fit F̂_N to the samples, then the probit
ecdf_marginal = rbig.MarginalGaussianize().fit(samples)
# today (rbig)
# z = Φ⁻¹(F̂_N(x)), (sample, latent)
latent_ecdf: SampleLatent = ecdf_marginal.transform(samples)
# today (rbig)
# x̂ = F̂_N⁻¹(Φ(z)), (sample, state)
recovered_ecdf: SampleState = ecdf_marginal.inverse_transform(latent_ecdf)
# |x̂ₙ − xₙ| for the empirical CDF
error_ecdf: PerSample = np.abs(recovered_ecdf - samples)[:, 0]The gauss_flows marginal goes through the same round trip, and we average both errors in the bulk and in the tails.
# the samples as a JAX array, (sample, state)
samples_jax: SampleState = jnp.asarray(samples)
# today (gauss_flows)
# a Gaussian-mixture CDF with 8 components, placed on the samples
smooth_marginal: MixtureGaussianCDF = MixtureGaussianCDF.from_data(
samples_jax, n_components=8
)
# user
# |x̂ₙ − xₙ| for the mixture CDF
error_smooth: PerSample = np.asarray(
compiled_round_trip_error(smooth_marginal, samples_jax)
)[:, 0]
Scalar = Float[ArrayLike, ""]
for name, error in [("empirical CDF", error_ecdf), ("mixture CDF", error_smooth)]:
# mean error in the bulk, |x| < 1
bulk: Scalar = error[distance < 1].mean()
# mean error in the tails, |x| > 3
tail: Scalar = error[distance > 3].mean()
print(f"{name:14s} mean error |x| < 1: {bulk:.1e} |x| > 3: {tail:.1e}")empirical CDF mean error |x| < 1: 1.3e-04 |x| > 3: 9.8e-03
mixture CDF mean error |x| < 1: 2.1e-16 |x| > 3: 2.2e-17
floor = 1e-17
fig, ax = plt.subplots(figsize=(12, 4.5))
ax.scatter(
distance,
np.maximum(error_ecdf, floor),
color=DATA_COLOR,
label="empirical CDF (rbig)",
**SCATTER_KW,
)
ax.scatter(
distance,
np.maximum(error_smooth, floor),
color=LATENT_COLOR,
label="Gaussian-mixture CDF (gauss_flows)",
**SCATTER_KW,
)
ax.set_yscale("log")
ax.set(xlabel="$|x|$", ylabel=r"round-trip error $|f^{-1}(f(x)) - x|$")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:Round-trip error of each sample against its distance into the tail. The empirical CDF (rbig) loses accuracy as |x| grows; the smooth mixture CDF stays near the float64 floor everywhere.
The empirical CDF’s mean error grows by more than an order of magnitude from the bulk () to the tails (), because it has no information between and beyond the sparse tail samples. The mixture CDF is smooth and strictly increasing everywhere, and its round trip stays near the float64 floor. A marginal estimator’s tail behaviour decides whether it can be inverted, which is why parametric flows use smooth CDFs (mixtures, splines) rather than a raw empirical CDF.
2. Two guards against a saturated CDF¶
Even a smooth CDF rounds to exactly 0 or 1 far enough into the tail, and . The classic guard is a clamp: keep the CDF inside , with a small , before the probit,
which caps the latent at a ceiling set by alone,
The clamp trades a small bias in the tails for latents that are always finite. Figure 2 shows the trade-off on a two-component Gaussian mixture CDF, with weights 0.5, means and standard deviations 0.5.
# Shapes: component (M) = 2
PerComponent = Float[ArrayLike, " component"]
# w = (0.5, 0.5), (component)
weights: PerComponent = jnp.array([0.5, 0.5])
# μ = (−1.5, 1.5), (component)
means: PerComponent = jnp.array([-1.5, 1.5])
# σ = (0.5, 0.5), (component)
stds: PerComponent = jnp.array([0.5, 0.5])
# user
# F(x) = ∑ⱼ wⱼ Φ((x − μⱼ) / σⱼ)
def mixture_cdf(point: Scalar) -> Scalar:
"""The CDF of the two-component Gaussian mixture at one point."""
return jnp.sum(weights * jstats.norm.cdf(point, means, stds))We evaluate it at 1,500 points on and clamp it at three values of .
# Shapes: test = 1,500 evaluation points
PerTestPoint = Float[ArrayLike, " test"]
# evaluation points on [−7, 7], (test)
test_points: PerTestPoint = jnp.linspace(-7, 7, 1500)
# user
# F(x) at each evaluation point, (test)
cdf_test: PerTestPoint = jax.vmap(mixture_cdf)(test_points)
clamped_latents = {}
for eps in [1e-1, 1e-3, 1e-7]:
# z = Φ⁻¹(clip(F(x), ε, 1 − ε))
clamped_latents[eps] = jstats.norm.ppf(jnp.clip(cdf_test, eps, 1 - eps))
# z = Φ⁻¹(F(x)), without a clamp, (test)
unclamped: PerTestPoint = jstats.norm.ppf(cdf_test)
# the number of latents that are ±∞
n_infinite: int = int(jnp.sum(~jnp.isfinite(unclamped)))
print(f"unclamped: {n_infinite} of {test_points.size} latents are ±inf")unclamped: 153 of 1500 latents are ±inf
The ceiling (2) depends on alone, so we trace it for from 10-15 to 10-1.
# Shapes: clamp = 60 values of ε
PerClamp = Float[ArrayLike, " clamp"]
# ε from 10⁻¹⁵ to 10⁻¹, log-spaced, (clamp)
eps_values: PerClamp = np.logspace(-15, -1, 60)
# |z|_max = Φ⁻¹(1 − ε)
ceiling: PerClamp = jstats.norm.ppf(1 - eps_values)
# Φ⁻¹(1 − 10⁻⁶), the ceiling of MixtureLogisticCDF
logistic_ceiling: float = float(jstats.norm.ppf(1 - 1e-6))
for eps in [1e-3, 1e-6, 1e-7]:
# |z|_max = Φ⁻¹(1 − ε)
ceiling_at_eps: float = float(jstats.norm.ppf(1 - eps))
print(f"eps = {eps:.0e}: ceiling = {ceiling_at_eps:.2f}")eps = 1e-03: ceiling = 3.09
eps = 1e-06: ceiling = 4.75
eps = 1e-07: ceiling = 5.20
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
for eps, z_clamped in clamped_latents.items():
axes[0].plot(
test_points,
z_clamped,
lw=1.8,
label=rf"$\varepsilon = 10^{{{math.log10(eps):.0f}}}$",
)
axes[0].set(xlabel="$x$", ylabel="$z$", ylim=(-6.5, 6.5))
axes[0].legend()
style_ax(axes[0])
axes[1].semilogx(eps_values, ceiling, color="C4", lw=1.8)
axes[1].plot(
1e-6, logistic_ceiling, "ko", label="MixtureLogisticCDF, $\\varepsilon = 10^{-6}$"
)
axes[1].set(
xlabel=r"clamp $\varepsilon$", ylabel=r"ceiling $\Phi^{-1}(1 - \varepsilon)$"
)
axes[1].legend()
style_ax(axes[1])
fig.tight_layout()
plt.show()
Figure 2:Left: the clamped marginal map for three values of the clamp ε; each flattens at its ceiling. Right: the latent ceiling Φ⁻¹(1 − ε) as a function of ε, with the clamp of MixtureLogisticCDF marked.
A smaller lets the latent reach further into the tails, and the ceiling grows only slowly: caps at 3.09, at 5.20. Without a clamp the latent becomes wherever the CDF rounds to 0 or 1.
The two mixture marginals of gauss_flows use different guards. MixtureLogisticCDF clamps with , so its latent never exceeds 4.75. MixtureGaussianCDF works with instead of . In the lower tail it solves
for by Newton’s method on the log-CDF, which stays accurate where itself would underflow, and in the upper tail it does the same with the survival function . We push a few points through both, with their default parameters, and back.
# today (gauss_flows)
# a logistic-mixture marginal with 8 components, clamped at ε = 10⁻⁶
logistic = MixtureLogisticCDF(n_components=8, shape=(1,))
# today (gauss_flows)
# a Gaussian-mixture marginal with 8 components and the log-space probit
gaussian = MixtureGaussianCDF(n_components=8, shape=(1,))Each point goes to its latent through both marginals and comes back through their inverses.
PerLatent = Float[ArrayLike, " latent"]
print(" x | logistic: z back | Gaussian: z back")
for x_value in [3.0, 6.0, 10.0, 15.0, 25.0]:
# one point x as a state of one coordinate, (state)
point: Float[ArrayLike, " state"] = jnp.array([x_value])
# today (gauss_flows)
# z = Φ⁻¹(clip(F(x), ε, 1 − ε)), (latent)
latent_logistic: PerLatent = logistic.transform(point)
# today (gauss_flows)
# z solving log Φ(z) = log F(x), (latent)
latent_gaussian: PerLatent = gaussian.transform(point)
# today (gauss_flows)
# x̂ = f⁻¹(z) for the logistic mixture
back_logistic: float = float(logistic.inverse(latent_logistic)[0])
# today (gauss_flows)
# x̂ = f⁻¹(z) for the Gaussian mixture
back_gaussian: float = float(gaussian.inverse(latent_gaussian)[0])
print(
f" {x_value:5.1f} | {float(latent_logistic[0]):7.3f} {back_logistic:10.4f}"
f" | {float(latent_gaussian[0]):7.3f} {back_gaussian:10.4f}"
) x | logistic: z back | Gaussian: z back
3.0 | 2.214 3.0000 | 4.297 3.0000
6.0 | 3.560 6.0000 | 8.594 6.0000
10.0 | 4.753 9.6453 | 14.324 10.0000
15.0 | 4.753 9.6453 | 21.485 15.0000
25.0 | 4.753 9.6453 | 35.809 25.0000
The tail inverse of MixtureGaussianCDF was not always this robust. A round-trip test like the one in section 4 caught its bisection bracket being too narrow for tail samples (gauss_flows#108), and the fix is what lets the table above return .
3. Precision of a deep log-determinant¶
A deep flow sums one log-determinant per layer, (4), and FlowJax’s Chain and Scan add them one at a time. Every addition rounds the running total to the working precision, with a relative error of about in float32 and in float64, so the error of the sum grows with the number of layers . We sum per-layer terms in three ways and compare each with the exactly rounded sum from math.fsum. The terms are random stand-ins of order one, , since only their size matters here.
# Shapes: layer (K) = 100,000 per-layer log-determinants
PerLayer = Float[ArrayLike, " layer"]
# ℓₖ ~ 𝒩(−0.5, 0.5²), k = 1, …, 10⁵, (layer)
layer_log_dets: PerLayer = rng.normal(-0.5, 0.5, 100_000)
# user
# sₖ = sₖ₋₁ + ℓₖ, one rounding per layer, as a chain of layers adds them
def running_sum(terms: PerLayer) -> PerLayer:
"""Every partial sum s₁, …, s_K of ``terms``, in their own precision."""
# user
# sₖ = sₖ₋₁ + ℓₖ, carried and recorded
def add(total: Scalar, term: Scalar) -> tuple[Scalar, Scalar]:
"""One layer's addition."""
# sₖ₋₁ + ℓₖ
new_total: Scalar = total + term
return new_total, new_total
# s₁, …, s_K by a scan from s₀ = 0, (layer)
partial_sums: PerLayer
_, partial_sums = jax.lax.scan(add, jnp.zeros((), terms.dtype), terms)
return partial_sumsWe run the compiled running sum in float32 and in float64, and pick 25 depths from 1 to 105 at which to compare it with the exact sum.
# Shapes: depth = 25 values of K
# user
# the running sum, compiled once per precision
compiled_running_sum: Callable[[PerLayer], PerLayer] = jax.jit(running_sum)
# ℓₖ in float32, (layer)
terms_32: PerLayer = jnp.asarray(layer_log_dets, jnp.float32)
# user
# sₖ in float32, (layer)
running_32: PerLayer = np.asarray(compiled_running_sum(terms_32))
# ℓₖ in float64, (layer)
terms_64: PerLayer = jnp.asarray(layer_log_dets, jnp.float64)
# user
# sₖ in float64, (layer)
running_64: PerLayer = np.asarray(compiled_running_sum(terms_64))
# K from 1 to 10⁵, log-spaced integers without repeats, (depth)
depths: Int[ArrayLike, " depth"] = np.unique(np.logspace(0, 5, 26).astype(int))At each depth we measure the three errors against the exactly rounded sum from math.fsum.
drift = {"float32, running": [], "float32, pairwise": [], "float64, running": []}
for depth in depths:
# ∑ₖ ℓₖ, rounded once
exact: float = math.fsum(layer_log_dets[:depth])
# ∑ₖ ℓₖ, pairwise in float32 as jnp.sum adds
pairwise_32: float = float(jnp.sum(terms_32[:depth]))
# |s_K − ∑ₖ ℓₖ| for the float32 running sum
drift["float32, running"].append(abs(float(running_32[depth - 1]) - exact))
# |pairwise − ∑ₖ ℓₖ| in float32
drift["float32, pairwise"].append(abs(pairwise_32 - exact))
# |s_K − ∑ₖ ℓₖ| for the float64 running sum
drift["float64, running"].append(abs(float(running_64[depth - 1]) - exact))
for depth in [100, 1000, 10_000, 100_000]:
# the position of K among the depths
index: int = int(np.searchsorted(depths, depth))
# the three errors at that depth
row: str = " ".join(
f"{name}: {values[index]:.1e}" for name, values in drift.items()
)
print(f"K = {depths[index]:6d} {row}")K = 100 float32, running: 2.3e-06 float32, pairwise: 2.3e-06 float64, running: 2.1e-14
K = 1000 float32, running: 2.1e-04 float32, pairwise: 3.0e-05 float64, running: 5.7e-14
K = 10000 float32, running: 3.8e-03 float32, pairwise: 1.1e-04 float64, running: 2.7e-12
K = 100000 float32, running: 5.2e-01 float32, pairwise: 2.0e-04 float64, running: 2.6e-10
fig, ax = plt.subplots(figsize=(12, 4.5))
for (name, values), color in zip(drift.items(), ["C3", "C1", "C0"], strict=True):
ax.loglog(depths, np.maximum(values, 1e-14), "-o", ms=3, color=color, label=name)
ax.set(xlabel="number of layers $K$", ylabel="error of the sum (nats)")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 3:Error of a sum of K per-layer log-determinants against its exactly rounded value. A float32 running sum, as a flow’s chain accumulates it, drifts fastest; a float32 pairwise sum (jnp.sum) drifts less; a float64 running sum stays near its floor.
The float32 running sum is off by about nats after a hundred layers, after 104 and half a nat after 105. The pairwise float32 sum of jnp.sum grows far more slowly, to at 105, and float64 stays below 10-9 throughout. For the tens of layers of a typical flow, float32 is accurate enough, which is why the library defaults to it. The drift matters for very deep stacks, such as an iterative RBIG fit with many more layers, and when two log-likelihoods that differ by little are compared; that is when to switch the accumulation to float64.
4. The round-trip test¶
The defining contract of a bijection is . In code it becomes a test with a tolerance over a batch of samples , :
It is the cheapest guard against a broken inverse, a missing clamp or a precision bug, and every layer in gauss_flows has one in its test suite. We run it on four bijections, with samples in dimensions and in float64, and include the empirical-CDF marginal of rbig for contrast. The rotation gets random reflections, since the default ones cancel to the identity.
# Shapes: sample (N) = 512; state (D_x) = 3; reflection = 3 Householder vectors
# D_x = 3
state_size: int = 3
# xₙ ~ 𝒩(0, I), (sample, state)
samples: SampleState = rng.standard_normal((512, state_size))
# the samples as a JAX array, (sample, state)
samples_jax: SampleState = jnp.asarray(samples)
# today (gauss_flows)
# a rotation by D_x Householder reflections
rotation = HouseholderRotation(n_reflections=state_size, shape=(state_size,))
# random reflection vectors vₖ ~ 𝒩(0, I), (reflection, state)
reflections: Float[ArrayLike, "reflection state"] = jr.normal(
jr.key(0), rotation.params.shape
)
# the rotation with the random reflections in place of the default ones
random_rotation: eqx.Module = eqx.tree_at(
lambda layer: layer.params, rotation, reflections
)We run each bijection forward and back on the same samples and keep its worst error.
# today (gauss_flows)
# the four bijections under test
bijections = {
"MixtureGaussianCDF": MixtureGaussianCDF.from_data(samples_jax, n_components=8),
"MixtureLogisticCDF": MixtureLogisticCDF(n_components=8, shape=(state_size,)),
"RQSplineMarginal": RQSplineMarginal(n_bins=8, shape=(state_size,)),
"HouseholderRotation": random_rotation,
}
# user
# maxₙ ‖f⁻¹(f(xₙ)) − xₙ‖_∞ for each bijection
max_errors: dict[str, float] = {
name: float(np.max(compiled_round_trip_error(bijection, samples_jax)))
for name, bijection in bijections.items()
}The empirical-CDF marginal of rbig goes through the same test, at the tolerance .
# today (rbig)
# fit F̂_N to each coordinate, then the probit
ecdf_marginal = rbig.MarginalGaussianize().fit(samples)
# today (rbig)
# z = Φ⁻¹(F̂_N(x)), (sample, latent)
latent_ecdf: SampleLatent = ecdf_marginal.transform(samples)
# today (rbig)
# x̂ = F̂_N⁻¹(Φ(z)), (sample, state)
recovered_ecdf: SampleState = ecdf_marginal.inverse_transform(latent_ecdf)
# maxₙ ‖x̂ₙ − xₙ‖_∞ for the empirical CDF
max_errors["rbig empirical CDF"] = float(np.max(np.abs(recovered_ecdf - samples)))
# δ
tolerance: float = 1e-8
print(f"round trip at tolerance {tolerance:.0e}:")
for name, error in max_errors.items():
# pass when the worst error is below δ
verdict: str = "pass" if error < tolerance else "FAIL"
print(f" {verdict} {name:20s} {error:.1e}")round trip at tolerance 1e-08:
pass MixtureGaussianCDF 5.8e-15
pass MixtureLogisticCDF 1.2e-14
pass RQSplineMarginal 4.4e-16
pass HouseholderRotation 2.7e-15
FAIL rbig empirical CDF 5.0e-01
fig, ax = plt.subplots(figsize=(12, 4))
names = list(max_errors)
values = [max(max_errors[name], 1e-17) for name in names]
colors = ["C2" if max_errors[name] < tolerance else "C3" for name in names]
ax.barh(names, values, color=colors)
ax.axvline(tolerance, color="k", ls="--", lw=1, label=r"tolerance $\delta$")
ax.set_xscale("log")
ax.set(xlabel=r"$\max_n \|f^{-1}(f(\mathbf{x}_n)) - \mathbf{x}_n\|_\infty$")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 4:Round-trip test at tolerance δ = 1e-8 (dashed). The four gauss_flows bijections pass near the float64 floor; the empirical-CDF marginal of rbig fails.
The four gauss_flows bijections pass with errors near the float64 floor. The empirical-CDF marginal fails, and that failure is not a bug to fix: an empirical CDF has no information between and beyond the samples, as section 1 showed. A round-trip test that runs in CI on random inputs is what catches a real inverse bug, such as the bracket of gauss_flows#108, and what lets us stack a hundred layers and trust the composition.
Recap¶
| Hazard | Symptom | Guard |
|---|---|---|
| the CDF rounds to 0 or 1 | latents of , no inverse | a smooth CDF with the clamp (1) or the log-space probit (3) |
| a clamp that is too tight | tails flattened at the ceiling (2) | place the marginal on the data, or use the log-space probit |
| a float32 sum of log-determinants (4) | drift that grows with depth | float64 accumulation for deep stacks |
| a broken inverse | silently wrong samples and densities | the round-trip test (4) in CI |
Next. We can now build a Gaussianizing map and trust it. The next notebook asks how to measure whether its output actually reached : QQ plots, moments, negentropy and multivariate normality tests.
- 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