Change of variables from scratch
The one formula the whole curriculum is built on, in 1-D, 2-D and D-D
00 · Change of variables from scratch¶
Every Gaussianization method in this curriculum (RBIG, coupling flows, FFJORD, spline flows) is a way of building an invertible map that turns messy data into a standard Gaussian. The one fact that makes such a map useful for density estimation is the change-of-variables formula Rezende & Mohamed, 2015Papamakarios et al., 2021: it says how a probability density changes when we push it through . Get this formula and its log-determinant bookkeeping right and the rest of the course is engineering.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
from jaxtyping import ArrayLike, Float
from matplotlib.collections import PolyCollection
from scipy import stats
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
GAUSS_KW,
LATENT_COLOR,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import MixtureGaussianCDF
# Log-determinants are sums of many logs, so they get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "scipy", "matplotlib", "gauss_flows_maps")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
scipy : 1.17.1
matplotlib : 3.11.2
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. The 1-D formula¶
Let be a continuous random variable with density , and let be smooth and strictly monotone, hence invertible. The latent variable is , with density .
Derivation from conservation of mass
Probability mass is conserved over an infinitesimal interval, so . Since , dividing by gives (1). Read the other way, the latent density is at the point .
The factor is the local stretch or squeeze of the line under , and it is what keeps the transformed density normalised.
Worked example. Take with , so is log-normal, and the map . Then is standard normal by construction, so we know the answer and can check the formula. Here , so (1) predicts . Figure 1 compares that prediction with a histogram of .
# Shapes: sample (N) = 200,000; test = 400 evaluation points
PerSample = Float[ArrayLike, " sample"]
# w ~ N(0, 1), (sample)
normal_draws: PerSample = rng.standard_normal(200_000)
# x = eʷ, log-normal, (sample)
samples: PerSample = np.exp(normal_draws)
# user
# f(x) = log x, elementwise
def log_map(values: Float[ArrayLike, "..."]) -> Float[ArrayLike, "..."]:
"""The map ``f(x) = log x``."""
return jnp.log(values)
PerTestPoint = Float[ArrayLike, " test"]
# user
# f'(x) by autodiff, so 1/x is never hand-coded
def log_map_derivative(points: PerTestPoint) -> PerTestPoint:
"""The derivative of ``log_map`` at each point."""
return jax.vmap(jax.grad(log_map))(points)
# evaluation points on [0.05, 8], (test)
test_points: PerTestPoint = jnp.linspace(0.05, 8.0, 400)
# p_x(x), the log-normal density, (test)
density_x: PerTestPoint = stats.lognorm.pdf(np.asarray(test_points), s=1.0)The prediction evaluates (1) at the image of each evaluation point.
# user
# z = f(x) at the evaluation points, (test)
latent_at_test: PerTestPoint = np.asarray(log_map(test_points))
# user
# p_z(f(x)) = p_x(x) / |f'(x)|, (test)
density_z_predicted: PerTestPoint = density_x / np.abs(
np.asarray(log_map_derivative(test_points))
)
# user
# z = f(x) for every sample, (sample)
latent_samples: PerSample = np.asarray(log_map(samples))
# evaluation points on [−4, 4] for 𝒩(0, 1), (test)
latent_test: PerTestPoint = np.linspace(-4, 4, 400)fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
axes[0].hist(samples, bins=200, density=True, range=(0, 8), color=DATA_COLOR, alpha=0.5)
axes[0].plot(test_points, density_x, "k-", lw=1.5, label=r"$p_x$ (log-normal)")
axes[0].set(title=r"data space: $x = e^w$", xlabel="$x$", ylabel="density")
axes[0].legend()
style_ax(axes[0])
axes[1].hist(
latent_samples,
bins=200,
density=True,
range=(-4, 4),
color=LATENT_COLOR,
alpha=0.5,
label="histogram of $z = f(x)$",
)
axes[1].plot(
latent_at_test,
density_z_predicted,
"r-",
lw=1.8,
label="change-of-variables prediction",
)
axes[1].plot(
latent_test, stats.norm.pdf(latent_test), **GAUSS_KW, label=r"$\mathcal{N}(0, 1)$"
)
axes[1].set(title=r"latent space: $z = \log x$", xlabel="$z$")
axes[1].legend()
style_ax(axes[1])
fig.tight_layout()
plt.show()
Figure 1:Left: samples of the log-normal and its density . Right: the histogram of , the prediction of the change-of-variables formula and the standard-normal density.
The red prediction lands on both the histogram of and the analytic curve. The factor does real work: drop it and the prediction no longer integrates to one.
2. The -dimensional formula¶
In dimensions the input is , the map is and the latent is . The derivative becomes the Jacobian matrix , whose rows are the outputs,
and the absolute value of its determinant takes the place of .
The scalar is the local volume change: the factor by which inflates or shrinks a small box of probability mass around .
Linear case. For an affine map , with and , the Jacobian is constant, , so everywhere. We can read the answer off and check it against autodiff.
# Shapes: state (D_x) = 2; latent (D_x) = 2
LatentState = Float[ArrayLike, "latent state"]
PerLatent = Float[ArrayLike, " latent"]
PerState = Float[ArrayLike, " state"]
# A, a fixed 2 × 2 matrix, (latent, state)
matrix_a: LatentState = jnp.array([[1.3, 0.7], [-0.4, 0.9]])
# b, a fixed offset, (latent)
offset_b: PerLatent = jnp.array([0.5, -1.0])
# user
# f(x) = A x + b
def f_lin(point: PerState) -> PerLatent:
"""The affine map ``A x + b``."""
return matrix_a @ point + offset_bAt one point , autodiff gives the Jacobian, and its determinant should match .
Scalar = Float[ArrayLike, ""]
# x₀, one point of the plane, (state)
point_lin: PerState = jnp.array([0.3, -1.2])
# user
# J_f(x₀), by forward-mode autodiff, (latent, state)
jacobian_lin: LatentState = jax.jacfwd(f_lin)(point_lin)
# |det J_f(x₀)|
abs_det_autodiff: Scalar = jnp.abs(jnp.linalg.det(jacobian_lin))
# |det A|
abs_det_by_hand: Scalar = jnp.abs(jnp.linalg.det(matrix_a))
# log|det J_f(x₀)|
log_det_lin: Scalar = jnp.linalg.slogdet(jacobian_lin)[1]
print("autodiff Jacobian J_f(x0):\n", np.asarray(jacobian_lin))
print(f"|det J_f| (autodiff) = {abs_det_autodiff:.6f}")
print(f"|det A| (by hand) = {abs_det_by_hand:.6f}")
print(f"log|det J_f| (autodiff) = {log_det_lin:.6f}")autodiff Jacobian J_f(x0):
[[ 1.3 0.7]
[-0.4 0.9]]
|det J_f| (autodiff) = 1.450000
|det A| (by hand) = 1.450000
log|det J_f| (autodiff) = 0.371564
The determinant is an area change. Lay a grid over the plane, push every cell through , and colour each warped cell by at its centre (Figure 2). For the linear map every cell scales by the same . For the nonlinear map the determinant varies with position, which is why (3) evaluates afresh at every point.
# user
# f(x) = x + 0.5 [sin(1.5 x₂), sin(1.5 x₁)]ᵀ
def f_wave(point: PerState) -> PerLatent:
"""The nonlinear wave map of the plane."""
return point + 0.5 * jnp.array([jnp.sin(1.5 * point[1]), jnp.sin(1.5 * point[0])])def warp_grid(ax, fn, title, lo=-2.5, hi=2.5, n=14):
"""Push an n × n grid through fn and colour each cell by |det J_fn| at its centre."""
edges = np.linspace(lo, hi, n + 1)
fn_v = jax.vmap(fn)
def abs_det(p):
# |det J_fn(p)| = exp(log|det J_fn(p)|)
return jnp.exp(jnp.linalg.slogdet(jax.jacfwd(fn)(p))[1])
polys, vals = [], []
for i in range(n):
for j in range(n):
corners = jnp.array(
[
[edges[i], edges[j]],
[edges[i + 1], edges[j]],
[edges[i + 1], edges[j + 1]],
[edges[i], edges[j + 1]],
]
)
polys.append(np.asarray(fn_v(corners)))
center = corners.mean(axis=0)
vals.append(float(abs_det(center)))
pc = PolyCollection(
polys,
array=np.array(vals),
cmap="viridis",
edgecolors="k",
linewidths=0.25,
alpha=0.95,
)
ax.add_collection(pc)
ax.autoscale_view()
ax.set_aspect("equal")
ax.set(title=title, xlabel="$z_1$", ylabel="$z_2$")
style_ax(ax)
return pc
fig, axes = plt.subplots(1, 2, figsize=(12, 5), constrained_layout=True)
warp_grid(axes[0], f_lin, r"linear $f(\mathbf{x}) = \mathbf{A}\mathbf{x} + \mathbf{b}$")
pc = warp_grid(axes[1], f_wave, r"nonlinear $f$: $|\det \mathbf{J}_f|$ varies")
fig.colorbar(pc, ax=axes, shrink=0.85, label=r"$|\det \mathbf{J}_f(\mathbf{x})|$")
plt.show()
Figure 2:A 14 × 14 grid pushed through the linear map (left) and the nonlinear map (right), each cell coloured by at its centre.
On the left the grid becomes identical parallelograms, all scaled by . On the right the cells warp unevenly: expanded regions are larger and brighter, compressed ones smaller and darker. (3) handles both cases the same way because it reads locally.
3. Always work in log space¶
Densities span many orders of magnitude, and the determinant of a matrix is a product of numbers, so both overflow or underflow quickly. Flows therefore never form ; they add its logarithm.
jax.numpy.linalg.slogdet returns stably, with the sign kept apart. We check (4) on a nonlinear map in dimensions,
where is a fixed, well-conditioned mixing matrix and acts elementwise. The Jacobian comes from autodiff, so the check is fully generic.
# Shapes: state (D_x) = 5; latent (D_x) = 5
D_x = 5
# M = I + 0.3 ε, εᵢⱼ ~ N(0, 1), (latent, state)
mixing_m: LatentState = jnp.asarray(
rng.standard_normal((D_x, D_x)) * 0.3 + jnp.eye(D_x)
)
# user
# f(x) = M tanh(0.7 x) + 0.5 x
def f_tanh(point: PerState) -> PerLatent:
"""The nonlinear map with a fixed mixing matrix."""
return mixing_m @ jnp.tanh(0.7 * point) + 0.5 * point
# user
# log|det J_f(x)| from the full autodiff Jacobian
def log_det_autodiff(point: PerState) -> Scalar:
"""The log-determinant of ``f_tanh`` at ``point``, by brute force."""
# J_f(x), by forward-mode autodiff, (latent, state)
jacobian: LatentState = jax.jacfwd(f_tanh)(point)
return jnp.linalg.slogdet(jacobian)[1]The log density adds the base log density at the image to the log-determinant.
# user
# log p_x(x) = log 𝒩(f(x); 0, I) + log|det J_f(x)|
def log_p_x(point: PerState) -> Scalar:
"""The log density of the data under ``f_tanh`` and a standard-normal base."""
# user
# z = f(x), (latent)
latent: PerLatent = f_tanh(point)
# log p_z(z) = log 𝒩(z; 0, I)
log_p_z: Scalar = jax.scipy.stats.multivariate_normal.logpdf(
latent, jnp.zeros(D_x), jnp.eye(D_x)
)
# user
# log p_x(x) = log p_z(z) + log|det J_f(x)|
return log_p_z + log_det_autodiff(point)We evaluate both terms at one standard-normal point.
# x, one standard-normal point, (state)
tanh_input: PerState = jnp.asarray(rng.standard_normal(D_x))
# user
# log|det J_f(x)|
log_det_tanh: Scalar = log_det_autodiff(tanh_input)
# user
# log p_x(x)
log_p_tanh: Scalar = log_p_x(tanh_input)
print(f"log p_z(f(x)) = {log_p_tanh - log_det_tanh:.6f}")
print(f"log|det J_f(x)| = {log_det_tanh:.6f}")
print(f"log p_x(x) = {log_p_tanh:.6f}")log p_z(f(x)) = -7.987257
log|det J_f(x)| = -0.126274
log p_x(x) = -8.113531
The same function, batched with vmap, evaluates a whole sample at once.
# Shapes: sample (N) = 4,000; state (D_x) = 5
SampleState = Float[ArrayLike, "sample state"]
# xₙ ~ 𝒩(0, I), (sample, state)
samples_tanh: SampleState = jnp.asarray(rng.standard_normal((4000, D_x)))
# user
# log p_x(xₙ) for every sample, (sample)
log_p_samples: PerSample = jax.vmap(log_p_x)(samples_tanh)
# every log density finite
all_finite: bool = bool(jnp.all(jnp.isfinite(log_p_samples)))
print(f"\nbatched over {samples_tanh.shape[0]} points, all finite: {all_finite}")
batched over 4000 points, all finite: True
4. The bridge: a bijector reports this exact number¶
Every bijector in gauss_flows has transform_and_log_det(x), which returns . The second value is the log-determinant we have been computing. The library works it out analytically and cheaply, with no determinant, but it must agree with a brute-force autodiff Jacobian. We confirm that on MixtureGaussianCDF, the marginal bijector at the heart of Gaussianization.
# today (gauss_flows)
# an 8-component mixture CDF on each of the D_x = 5 coordinates
bijector = MixtureGaussianCDF(n_components=8, shape=(D_x,))
# x, one standard-normal point, (state)
bijector_input: PerState = jnp.asarray(rng.standard_normal(D_x))
latent_lib: PerLatent
log_det_lib: Scalar
# today (gauss_flows)
# (z, log|det J_f(x)|), the log-determinant analytic
latent_lib, log_det_lib = bijector.transform_and_log_det(bijector_input)
# today (gauss_flows)
# J_f(x), by autodiff of the bijector's own transform, (latent, state)
jacobian_lib: LatentState = jax.jacfwd(bijector.transform)(bijector_input)
# log|det J_f(x)| by brute force
log_det_brute: Scalar = jnp.linalg.slogdet(jacobian_lib)[1]
print(f"gauss_flows log|det J_f| = {log_det_lib:.10f}")
print(f"autodiff log|det J_f| = {log_det_brute:.10f}")
print(f"absolute difference = {abs(log_det_lib - log_det_brute):.2e}")
assert jnp.allclose(log_det_lib, log_det_brute, atol=1e-6)gauss_flows log|det J_f| = 1.7966266902
autodiff log|det J_f| = 1.7966266902
absolute difference = 8.88e-16
The two agree to floating-point precision. The formula of sections 1 to 3 is what the package returns, so once you trust the formula you can trust the library, and stop computing determinants by hand: the analytic log-determinant is exact and far cheaper.
Recap¶
| Concept | Formula | In code |
|---|---|---|
| 1-D change of variables | (1) | p_x / abs(jax.grad(f)(x)) |
| -D change of variables | (3) | slogdet(jax.jacfwd(f)(x)) |
| log density | (4) | log_p_z + log_det |
| the library’s job | analytic | bijector.transform_and_log_det(x) |
Next. One bijector is rarely enough. The next notebook stacks maps, , and shows that their log-determinants add, which is the rule that lets us build deep flows.
- Rezende, D. J., & Mohamed, S. (2015). Variational Inference with Normalizing Flows. International Conference on Machine Learning (ICML).
- Papamakarios, G., Nalisnick, E., Rezende, D. J., Mohamed, S., & Lakshminarayanan, B. (2021). Normalizing Flows for Probabilistic Modeling and Inference. Journal of Machine Learning Research, 22(57), 1–64.