Composition and the additive log-determinant
Why deep flows work: stack maps, and their log-determinants add
01 · Composition and the additive log-determinant¶
Notebook 00 gave us one invertible map and its log-determinant, the last term of (4). A single elementwise CDF or a single rotation cannot turn a tangled distribution into a standard Gaussian, so we stack many simple maps into a deep one. Stacking is cheap, and normalizing flows exist at all Rezende & Mohamed, 2015Dinh et al., 2017, because of a one-line consequence of the chain rule: when maps compose, their log-determinants add.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
from collections.abc import Callable
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
from flowjax.bijections import Chain
from jaxtyping import ArrayLike, Float, Key
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import style_ax, use_compact_figures
from gauss_flows_maps.bijections import HouseholderRotation, MixtureGaussianCDF
# Log-determinants are sums of many logs, so they get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(1)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "flowjax", "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
flowjax : 19.1.0
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 composition rule¶
Write a deep map as a composition of bijections,
where each layer acts on the state left by the one before it,
starting from the input, , and ending at the latent, . Every state is a vector .
By the chain rule the Jacobian of the whole map is a product of the layer Jacobians, each evaluated at the intermediate state it acts on:
The log-determinant of a deep flow is therefore a sum of cheap per-layer terms, and no determinant of the whole composition is ever formed.
2. Check it from scratch¶
We compose three simple invertible maps in dimensions: an affine mixer , an elementwise nonlinearity , and a linear map , with and . The total log-determinant is computed two ways: by autodiff of the whole composition, and by the running sum (4).
# Shapes: state (D_x) = 2
StateMatrix = Float[ArrayLike, "state state"]
# A₁ = I + 0.5 G, with Gᵢⱼ ~ N(0, 1), (state, state)
matrix_1: StateMatrix = jnp.asarray(rng.standard_normal((2, 2)) * 0.5 + jnp.eye(2))
# A₂ = I + 0.5 G, (state, state)
matrix_2: StateMatrix = jnp.asarray(rng.standard_normal((2, 2)) * 0.5 + jnp.eye(2))
PerState = Float[ArrayLike, " state"]
# b ~ N(0, I), (state)
offset: PerState = jnp.asarray(rng.standard_normal(2))The three layers act on one state vector each.
# user
# f₁(x) = A₁ x + b
def f1(state: PerState) -> PerState:
"""The affine mixer."""
return matrix_1 @ state + offset
# user
# f₂(x) = tanh(0.8 x) + 0.3 x, elementwise and increasing, so invertible
def f2(state: PerState) -> PerState:
"""The elementwise nonlinearity."""
return jnp.tanh(0.8 * state) + 0.3 * state
# user
# f₃(x) = A₂ x
def f3(state: PerState) -> PerState:
"""The linear map."""
return matrix_2 @ state
layers = [f1, f2, f3]Composing them walks the state through the layers in order, as in (2).
# user
# f = f_K ∘ … ∘ f₁, applying the layers in order
def compose(fns: list[Callable]) -> Callable:
"""The composition of ``fns``, the first one applied first."""
# user
# x ↦ f_K(… f₁(x))
def composed(state: PerState) -> PerState:
# x₀ = x, (state)
current: PerState = state
for fn in fns:
# xₖ = fₖ(xₖ₋₁), (state)
current: PerState = fn(current)
return current
return composedThe log-determinant of one map comes from its autodiff Jacobian.
Scalar = Float[ArrayLike, ""]
# user
# log |det J_fn(x)|, from the autodiff Jacobian
def layer_log_det(fn: Callable, state: PerState) -> Scalar:
"""The log-determinant of ``fn`` at ``state``."""
# J_fn(x), (state, state)
jacobian: StateMatrix = jax.jacfwd(fn)(state)
log_det: Scalar
# log |det J_fn(x)|
_, log_det = jnp.linalg.slogdet(jacobian)
return log_detNow the two totals, at one random input.
# x ~ N(0, I), (state)
input_state: PerState = jnp.asarray(rng.standard_normal(2))
# user
# log |det J_f(x)| of the whole composition, by autodiff
log_det_whole: Scalar = layer_log_det(compose(layers), input_state)
# ∑ₖ log |det J_fₖ(xₖ₋₁)|, walking the states from x₀ = x
log_det_sum: Scalar = 0.0
# x₀ = x, (state)
state_k: PerState = input_state
for fn in layers:
# user
# add log |det J_fₖ(xₖ₋₁)|
log_det_sum: Scalar = log_det_sum + layer_log_det(fn, state_k)
# xₖ = fₖ(xₖ₋₁), (state)
state_k: PerState = fn(state_k)
print(f"whole composition, autodiff = {log_det_whole:.10f}")
print(f"sum over layers = {log_det_sum:.10f}")
print(f"absolute difference = {abs(log_det_whole - log_det_sum):.2e}")
assert jnp.allclose(log_det_whole, log_det_sum, atol=1e-10)whole composition, autodiff = -0.5000126365
sum over layers = -0.5000126365
absolute difference = 0.00e+00
3. The intermediates matter¶
A common slip is to evaluate every layer at the original input . The linear layers do not care, since their Jacobians are constant, but the Jacobian of the nonlinear depends on where it is evaluated, so the shortcut gives the wrong total.
# user
# ∑ₖ log |det J_fₖ(x₀)|, every term at the input: wrong for the nonlinear layer
log_det_wrong: Scalar = sum(layer_log_det(fn, input_state) for fn in layers)
print(f"states x_(k-1), correct = {log_det_sum:.8f}")
print(f"all at x_0, wrong = {log_det_wrong:.8f}")
print(f"gap from the nonlinearity = {abs(log_det_sum - log_det_wrong):.4f}")states x_(k-1), correct = -0.50001264
all at x_0, wrong = -0.35780308
gap from the nonlinearity = 0.1422
The whole gap comes from : feeding it instead of evaluates its stretch factor at the wrong point. Flow libraries get this right by construction, since each bijection receives the output of the one before it.
4. The log-density of a deep flow¶
Substituting (4) into the log-density (4) of notebook 00 gives the density of a deep flow with a standard-normal base:
Every layer adds one term. A layer with changes the geometry for free; orthogonal rotations are the standard example. That is why Gaussianization alternates rotations, which move mass between axes at no cost, with marginal transforms, which do the density work.
5. The bridge: a stack of gauss_flows blocks¶
A Gaussianization flow is a chain of rotation and marginal blocks. Here the rotation is a HouseholderRotation and the marginal a MixtureGaussianCDF, each the layer of (1) through its transform_and_log_det. FlowJax’s Chain composes them with the rule (4). We push points of a skewed 2-D dataset through four blocks by hand. Each rotation gets random reflections, and each marginal is fitted to the state that reaches it with MixtureGaussianCDF.from_data, as RBIG does. We record the mean log-determinant of each layer and compare the total with Chain’s own.
# Shapes: sample (N) = 4,000; state (D_x) = 2
SampleState = Float[ArrayLike, "sample state"]
# u ~ N(0, I), (sample, state)
standard_draws: SampleState = rng.standard_normal((4000, 2))
PerSample = Float[ArrayLike, " sample"]
# u₁, (sample)
first_coordinate: PerSample = standard_draws[:, 0]
# u₂ + 0.4 u₁² − 0.4, bent into a banana, (sample)
bent_coordinate: PerSample = standard_draws[:, 1] + 0.4 * first_coordinate**2 - 0.4
# the banana, stacked as (u₁, u₂ + 0.4 u₁² − 0.4), (sample, state)
banana: SampleState = np.stack([first_coordinate, bent_coordinate], axis=1)
# x = (banana − mean) / std, per coordinate, (sample, state)
samples: SampleState = jnp.asarray((banana - banana.mean(0)) / banana.std(0))Each rotation gets random reflections, since the default ones are equal and cancel to the identity.
# Shapes: reflection = 2 Householder vectors
# user
# Q = H₂ H₁, with random Householder vectors
def random_rotation(key: Key[ArrayLike, ""]) -> HouseholderRotation:
"""A 2-D HouseholderRotation with two random reflections."""
# today (gauss_flows)
# Q = H₂ H₁, with the default vectors
rotation = HouseholderRotation(n_reflections=2, shape=(2,))
# vᵢ ~ N(0, I), (reflection, state)
reflections: Float[ArrayLike, "reflection state"] = jr.normal(
key, rotation.params.shape
)
# Q with the random vᵢ in place of the defaults
return eqx.tree_at(lambda r: r.params, rotation, reflections)One block rotates the state that reaches it, then fits a marginal to the rotated state and applies it.
# Shapes: layer = 2 layers per block, the rotation and the marginal
PerLayer = Float[ArrayLike, " layer"]
# user
# xₖ = T(Q xₖ₋₁), with the mean log |det| of each layer
def fit_block(key: Key[ArrayLike, ""], block_input: SampleState) -> tuple:
"""One rotation and marginal block, fitted to ``block_input``."""
# user
# Q, with random reflections
rotation: HouseholderRotation = random_rotation(key)
rotated: SampleState
rotation_log_det: PerSample
# today (gauss_flows)
# Q x and log |det Q| = 0, for the whole batch
rotated, rotation_log_det = jax.vmap(rotation.transform_and_log_det)(block_input)
# today (gauss_flows)
# the marginal T, fitted to the state that reaches it, as RBIG does
marginal: MixtureGaussianCDF = MixtureGaussianCDF.from_data(rotated, n_components=8)
block_output: SampleState
marginal_log_det: PerSample
# today (gauss_flows)
# T(Q x) and log |det J_T(Q x)|, for the whole batch
block_output, marginal_log_det = jax.vmap(marginal.transform_and_log_det)(rotated)
# mean over the samples of each layer's log |det|, (layer)
layer_means: PerLayer = jnp.stack(
[rotation_log_det.mean(), marginal_log_det.mean()]
)
return rotation, marginal, block_output, layer_meansFour blocks, each fitted to the output of the one before.
# Shapes: block = 4 rotation and marginal blocks
n_blocks: int = 4
# one PRNG key per block
block_keys: Key[ArrayLike, " block"] = jr.split(jr.key(0), n_blocks)
# the ledger: each layer, its name and its mean log |det|
bijections, names, mean_log_dets = [], [], []
# x₀ = x, (sample, state)
state_k: SampleState = samples
for k, block_key in enumerate(block_keys):
# user
# block k, fitted to xₖ₋₁, (layer)
rotation: HouseholderRotation
marginal: MixtureGaussianCDF
layer_means: PerLayer
rotation, marginal, state_k, layer_means = fit_block(block_key, state_k)
# record the block's two layers
mean_log_dets += layer_means.tolist()
bijections += [rotation, marginal]
names += [f"rotation {k + 1}", f"marginal {k + 1}"]FlowJax’s Chain of the eight layers must give the same total.
# today (flowjax)
# f = the chain of the eight layers
chain = Chain(bijections)
log_det_chain: PerSample
# today (flowjax)
# log |det J_f(x)| at each sample
_, log_det_chain = jax.vmap(chain.transform_and_log_det)(samples)
print(f"sum of the layers' mean log-dets = {np.sum(mean_log_dets):.8f}")
print(f"Chain's mean log-det = {float(jnp.mean(log_det_chain)):.8f}")
assert np.isclose(np.sum(mean_log_dets), float(jnp.mean(log_det_chain)), atol=1e-8)sum of the layers' mean log-dets = -0.56291187
Chain's mean log-det = -0.56291187
fig, ax = plt.subplots(figsize=(12, 4.5))
colors = ["0.6" if name.startswith("rotation") else "C1" for name in names]
positions = np.arange(len(mean_log_dets))
ax.bar(positions, mean_log_dets, color=colors)
ax.axhline(0, color="k", lw=0.8)
is_rotation = np.array([name.startswith("rotation") for name in names])
ax.scatter(
positions[is_rotation],
np.zeros(is_rotation.sum()),
marker="s",
color="0.4",
zorder=3,
label="rotation (exactly zero)",
)
ax.plot(
positions,
np.cumsum(mean_log_dets),
"-o",
color="C0",
lw=1.5,
ms=4,
label="running total",
)
ax.set_xticks(positions, names, rotation=45, ha="right")
ax.set(ylabel=r"mean $\log|\det \mathbf{J}_{f_k}|$")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:Mean log-determinant of each layer of four rotation and marginal blocks and its running total (line). The rotations (grey squares) contribute exactly zero; the marginals (orange bars) carry the whole log-determinant.
The grey rotation markers sit at exactly zero: an orthogonal map has , so it costs nothing in the density ledger. The orange marginal bars carry the whole log-determinant, and the blue line is their running total, the sum in (5) that a flow adds to when it scores a point.
Recap¶
| Concept | Equation | In code |
|---|---|---|
| composition of layers | (1), (2) | compose(layers) |
| Jacobian of a composition | (3) | jax.jacfwd(compose(layers)) |
| log-determinants add | (4) | a running sum over the layers |
| log-density of a deep flow | (5) | flow.log_prob(x) |
| rotations are free | the grey markers | |
| the library does it | (4) inside Chain and Scan | Chain(bijections) |
Next. We have built maps in the data-to-latent direction. The next notebook asks which direction a flow should store and which it should compute, a choice that splits flows into those good at density estimation and those good at fast sampling.
- Rezende, D. J., & Mohamed, S. (2015). Variational Inference with Normalizing Flows. International Conference on Machine Learning (ICML).
- Dinh, L., Sohl-Dickstein, J., & Bengio, S. (2017). Density Estimation using Real NVP. International Conference on Learning Representations (ICLR).