Forward vs inverse
One bijection, two directions: the one we make cheap decides what the flow is good at
02 · Forward vs inverse¶
A normalizing flow is a bijection , so it can run in either direction. That sounds symmetric, but it almost never is: one direction is a closed-form expression and the other needs an iterative solve. Which direction we make cheap decides whether the flow is good at density estimation or at sampling.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import time
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 optimistix as optx
from flowjax.bijections import Invert
from flowjax.distributions import Transformed
from jaxtyping import ArrayLike, Float, Int, PRNGKeyArray
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import style_ax, use_compact_figures
from gauss_flows_maps.bijections import MixtureGaussianCDF
from gauss_flows_maps.monotone import monotone_inverse
from gauss_flows_models.flows import gaussianization_flow
# Root finds and log-determinants get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(2)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "optimistix", "flowjax", "gauss_flows_models")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
optimistix : 0.1.0
flowjax : 19.1.0
gauss_flows_models: 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. A flow runs both ways¶
Let map data to a standard-normal latent . The two things we ask of a flow use opposite directions. Scoring a point is the log-density (4), which needs and its log-determinant. Drawing a point runs the map backwards from a base draw,
which needs and no log-determinant at all.
| Operation | Direction | Needs | Used for |
|---|---|---|---|
log_prob(x) | density, | and , (4) | density estimation, maximum-likelihood training |
sample(key, shape) | sampling, | , (1) | generation, simulation |
Both are always possible, since that is what a bijection means, but their cost can differ sharply. The culprit is the marginal transform.
2. Analytic forward, iterative inverse¶
The atom of Gaussianization is a map on one coordinate built from a mixture of Gaussians, with weights summing to one, means and scales . Its CDF is
where is the standard-normal CDF, and the marginal map sends through to a level and then through the standard-normal quantile function:
Both and have closed forms, so the forward map is one line. The inverse is not: is a sum of CDFs and has no closed-form inverse, so is the root of
Because is increasing, (4) has exactly one root, and a bracketing method finds it without derivatives or a starting guess. We hand it to optimistix Kidger, 2021, the solver library gauss_flows itself depends on, with its Bisection solver on the bracket .
Why
Each step keeps the half of the bracket where changes sign, so the root stays inside and the bracket width halves. After steps the width is , and the midpoint is at most half of that from the root.
# Shapes: component (M) = 3
PerComponent = Float[ArrayLike, " component"]
# wₘ, the mixture weights, (component)
weights: PerComponent = jnp.array([0.4, 0.35, 0.25])
# μₘ, the component means, (component)
means: PerComponent = jnp.array([-1.5, 0.3, 2.0])
# σₘ, the component scales, (component)
scales: PerComponent = jnp.array([0.4, 0.6, 0.5])
Scalar = Float[ArrayLike, ""]
# user
# F(x) = ∑ₘ wₘ Φ((x − μₘ) / σₘ)
def mixture_cdf(point: Scalar) -> Scalar:
"""The mixture CDF F at a scalar ``point``."""
return jnp.sum(weights * jstats.norm.cdf(point, means, scales))The inverse hands (4) to the bisection solver of optimistix on the bracket .
# today (optimistix)
# bisection, stopping at a relative tolerance of 10⁻¹⁰
solver = optx.Bisection(rtol=1e-10, atol=1e-12)
# user
# x = F⁻¹(τ), the root of F(x) − τ on the bracket [−12, 12]
def mixture_quantile(level: Scalar, max_steps: int = 200) -> Scalar:
"""The root of F(x) − τ for the level τ = ``level``, after at most ``max_steps``."""
# today (optimistix)
# solve F(x) − τ = 0 from x⁽⁰⁾ = 0 inside [−12, 12]
solution: optx.Solution = optx.root_find(
lambda point, tau: mixture_cdf(point) - tau,
solver,
0.0,
args=level,
options={"lower": -12.0, "upper": 12.0},
max_steps=max_steps,
throw=False,
)
return solution.valueA round trip pushes samples forward through and recovers them with the root find.
# Shapes: sample (N) = 400
PerSample = Float[ArrayLike, " sample"]
# x ~ N(0.3, 1.2²), (sample)
x_true: PerSample = jnp.asarray(rng.normal(0.3, 1.2, size=400))
# user
# τ = F(x), (sample)
levels: PerSample = jax.vmap(mixture_cdf)(x_true)
# user
# x̂ = F⁻¹(τ), by bisection, (sample)
x_recovered: PerSample = jax.vmap(mixture_quantile)(levels)
# maxₙ |x − x̂|
round_trip_error: float = float(jnp.max(jnp.abs(x_true - x_recovered)))
print(f"round trip x → F(x) → F⁻¹(F(x)): max |error| = {round_trip_error:.2e}")round trip x → F(x) → F⁻¹(F(x)): max |error| = 1.63e-10
At one level we track the residual against the solver budget .
# Shapes: step = solver budgets n = 1, …, 45
# n = 1, …, 45, (step)
step_budgets: Int[ArrayLike, " step"] = np.arange(1, 46)
# τ = 0.7
level: float = 0.7
# user
# |F(x⁽ⁿ⁾) − τ| after a budget of n steps
residuals: Float[ArrayLike, " step"] = np.array(
[
abs(float(mixture_cdf(mixture_quantile(level, int(n))) - level))
for n in step_budgets
]
)
print(f"residual after 5 steps: {residuals[4]:.1e}")
print(f"residual after 20 steps: {residuals[19]:.1e}")
print(f"residual after 45 steps: {residuals[44]:.1e}")residual after 5 steps: 3.0e-02
residual after 20 steps: 1.4e-06
residual after 45 steps: 2.0e-13
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
x_grid = jnp.linspace(-4, 4, 500)
axes[0].plot(x_grid, jax.vmap(mixture_cdf)(x_grid), color="C0", lw=2, label="$F(x)$")
for tau in [0.2, 0.5, 0.8]:
x_tau = float(mixture_quantile(jnp.asarray(tau)))
axes[0].hlines(tau, -4, x_tau, color="C1", lw=1, ls=":")
axes[0].vlines(x_tau, 0, tau, color="C1", lw=1, ls=":")
axes[0].plot(x_tau, tau, "o", color="C1", ms=6)
axes[0].set(
title="forward is a formula, inverse is a root find",
xlabel="$x$",
ylabel=r"$\tau = F(x)$",
)
axes[0].legend(loc="upper left")
style_ax(axes[0])
axes[1].semilogy(step_budgets, residuals, "-o", color="C3", ms=3)
axes[1].set(
title="bisection residual against the solver budget",
xlabel="solver steps $n$",
ylabel=r"$|F(x^{(n)}) - \tau|$",
)
style_ax(axes[1])
fig.tight_layout()
plt.show()
Figure 1:Left: the mixture CDF is one closed-form sum, and inverting it means reading the curve from right to left, which the root find does for three levels . Right: the bisection residual against the solver budget falls geometrically, as the bisection bound predicts, until the solver meets its tolerance and stops.
The round trip recovers every sample to within the solver tolerance, and the residual falls by orders of magnitude within a few dozen steps. The inverse is accurate and robust, but it is a loop, where the forward map is a single expression.
gauss_flows packages this pattern as monotone_inverse: the bracketed inverse of any elementwise increasing function, with gradients through the implicit function theorem and Chandrupatla’s method as the default solver. It recovers the same samples.
# today (gauss_flows)
# x̂ = F⁻¹(τ) for all 400 levels at once, by the bracketed inverse, (sample)
x_library: PerSample = monotone_inverse(
jax.vmap(mixture_cdf),
levels,
-12.0,
12.0,
rtol=1e-12,
atol=1e-12,
max_steps=200,
)
# maxₙ |x − x̂| for the bisection above
error_bisection: float = float(jnp.max(jnp.abs(x_true - x_recovered)))
# maxₙ |x − x̂| for monotone_inverse
error_library: float = float(jnp.max(jnp.abs(x_true - x_library)))
print(f"bisection: max |x - F⁻¹(F(x))| = {error_bisection:.2e}")
print(f"monotone_inverse: max |x - F⁻¹(F(x))| = {error_library:.2e}")bisection: max |x - F⁻¹(F(x))| = 1.63e-10
monotone_inverse: max |x - F⁻¹(F(x))| = 2.70e-13
3. The asymmetry on a real flow¶
gaussianization_flow builds its marginal layers from MixtureGaussianCDF, whose transform is the closed-form map (3) and whose inverse is the root find. FlowJax’s Transformed reads its bijection as the sampling direction, base to data, so the factory stores , the Gaussianizing stack, and wraps it in Invert. log_prob then runs the closed-form maps, and sample runs a root find inside every marginal layer. We time both on the same six-layer flow in , compiled and warmed up first so the race is fair.
# Shapes: sample (N) = 5,000; state (D_x) = 2
# the root key
key: PRNGKeyArray = jr.key(0)
# today (gauss_flows)
# f, six layers of mixture marginals and rotations, wrapped in Invert
flow: Transformed = gaussianization_flow(key, n_dims=2, n_layers=6, n_components=8)
print(f"the flow's bijection is {type(flow.bijection).__name__}(...) of f")
SampleState = Float[ArrayLike, "sample state"]
# x ~ N(0, I), the points to score, (sample, state)
data: SampleState = jnp.asarray(rng.standard_normal((5000, 2)))the flow's bijection is Invert(...) of f
Both directions are compiled with eqx.filter_jit, and mean_seconds averages a call over three repeats.
# user
# log p(x), the density direction
def score_points(flow: Transformed, points: SampleState) -> PerSample:
"""The log-density of ``flow`` at each row of ``points``."""
return flow.log_prob(points)
# user
# x = f⁻¹(z) with z ~ N(0, I), the sampling direction
def draw_points(flow: Transformed, key: PRNGKeyArray) -> SampleState:
"""5000 draws from ``flow``."""
return flow.sample(key, (5000,))
# user
# log p(x), compiled
log_prob: Callable[[Transformed, SampleState], PerSample] = eqx.filter_jit(score_points)
# user
# x = f⁻¹(z), compiled
sample: Callable[[Transformed, PRNGKeyArray], SampleState] = eqx.filter_jit(draw_points)
# user
# the mean wall-clock time of run(i) over i = 0, …, n_repeats − 1
def mean_seconds(run: Callable[[int], object], n_repeats: int = 3) -> float:
"""The mean time of ``run(i)`` over ``n_repeats`` calls, in seconds."""
# the start time
start: float = time.perf_counter()
for i in range(n_repeats):
jax.block_until_ready(run(i))
return (time.perf_counter() - start) / n_repeatsWe compile both directions once, then time each on the same 5000 points.
# user
# compile log p(x) before timing
jax.block_until_ready(log_prob(flow, data))
# user
# compile f⁻¹ before timing
jax.block_until_ready(sample(flow, key))
# user
# time of log p(x): closed-form maps only
seconds_log_prob: float = mean_seconds(lambda i: log_prob(flow, data))
# user
# time of f⁻¹(z): one root find per coordinate per marginal layer
seconds_sample: float = mean_seconds(lambda i: sample(flow, jr.fold_in(key, i)))
# the ratio of the two times
slowdown: float = seconds_sample / seconds_log_prob
print(f"log_prob (closed form) : {seconds_log_prob * 1e3:7.2f} ms for 5000 points")
print(f"sample (root finds) : {seconds_sample * 1e3:7.2f} ms for 5000 points")
print(f"sample is {slowdown:.0f} times slower than log_prob")log_prob (closed form) : 88.22 ms for 5000 points
sample (root finds) : 1830.77 ms for 5000 points
sample is 21 times slower than log_prob
The samples are real: they score finitely under the same flow.
# user
# x = f⁻¹(z) for fresh z, (sample, state)
drawn: SampleState = sample(flow, jr.key(1))
# user
# log p(x) at the draws, (sample)
drawn_log_prob: PerSample = log_prob(flow, drawn)
print(f"log_prob of the samples is finite: {bool(jnp.isfinite(drawn_log_prob).all())}")log_prob of the samples is finite: True
fig, ax = plt.subplots(figsize=(7, 4.5))
bars = ax.bar(
["log_prob\n(density direction)", "sample\n(sampling direction)"],
[seconds_log_prob * 1e3, seconds_sample * 1e3],
color=["C0", "C1"],
)
ax.bar_label(bars, fmt="%.1f ms", padding=3)
ax.set(
ylabel="wall-clock time (ms per 5000 points)",
title=f"same flow, opposite directions: {slowdown:.0f} times apart",
)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:Wall-clock time of the two directions of one Gaussianization flow on 5000 points, compiled and warmed up. sample runs a root find in every marginal layer, log_prob only closed-form maps.
On the machine that ran this notebook, sample took more than ten times as long as log_prob; the printed ratio depends on the hardware, but the gap does not go away. Every sample pays for one bracketed solve per coordinate per marginal layer.
4. Choosing the cheap direction¶
The map and its inverse describe the same flow, but we choose which of them to store as the closed-form direction, and the other one pays the iterative price.
Density-estimation flows call
log_probconstantly, during maximum-likelihood training and at every evaluation. They store the density direction in closed form: fast training, slow sampling. The Gaussianization flows ofgauss_flowsmake this choice, which is the asymmetry of section 3.Sampling and variational flows call
sampleconstantly, for instance to draw from an approximate posterior. They store the sampling direction in closed form: fast sampling, slow density.
In FlowJax the switch is one wrapper, Invert, which swaps the transform and inverse of a bijection.
# Shapes: state (D_x) = 2
# today (gauss_flows)
# T(x) = Φ⁻¹(F(x)) on each of the 2 coordinates
marginal = MixtureGaussianCDF(n_components=8, shape=(2,))
# one point x ∈ ℝ², (state)
x_point: Float[ArrayLike, " state"] = jnp.array([0.4, -0.7])
# today (flowjax)
# Invert(T), whose transform is T⁻¹
swapped = Invert(marginal)
# today (flowjax)
# Invert(T).transform(x) = T⁻¹(x)
same: bool = bool(jnp.allclose(swapped.transform(x_point), marginal.inverse(x_point)))
print(f"Invert(marginal).transform(x) == marginal.inverse(x): {same}")Invert(marginal).transform(x) == marginal.inverse(x): True
Which direction is called forward is a choice of labels, not a property of the map.
Recap¶
| Concept | Equation | In code |
|---|---|---|
| density direction | (4) | flow.log_prob(x) |
| sampling direction | (1) | flow.sample(key, shape) |
| marginal map, closed form | (2), (3) | MixtureGaussianCDF.transform |
| its inverse, a root find | (4), (5) | optimistix.root_find, monotone_inverse |
| measured asymmetry | sample many times slower than log_prob | Figure 2 |
| choosing the cheap direction | swap transform and inverse | flowjax.bijections.Invert |
Next. We have been mapping to a standard Gaussian without asking why that target. The next notebook shows the properties (maximum entropy, independent coordinates, a trivial score) that make the natural destination.
- Kidger, P. (2021). On Neural Differential Equations [Phdthesis]. University of Oxford.
- Papamakarios, G., Pavlakou, T., & Murray, I. (2017). Masked Autoregressive Flow for Density Estimation. Advances in Neural Information Processing Systems (NeurIPS).
- Kingma, D. P., Salimans, T., Jozefowicz, R., Chen, X., Sutskever, I., & Welling, M. (2016). Improving Variational Inference with Inverse Autoregressive Flow. Advances in Neural Information Processing Systems (NeurIPS).