Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Forward vs inverse

One bijection, two directions: the one we make cheap decides what the flow is good at

02 · Forward vs inverse

Open In Colab

A normalizing flow is a bijection ff, 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.

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 ff map data x∈RDx\vect{x} \in \mathbb{R}^{D_x} to a standard-normal latent z=f(x)∈RDx\vect{z} = f(\vect{x}) \in \mathbb{R}^{D_x}. The two things we ask of a flow use opposite directions. Scoring a point is the log-density (4), which needs ff and its log-determinant. Drawing a point runs the map backwards from a base draw,

x=f−1(z), with z∼N(0,I)\vect{x} = f^{-1}(\vect{z}), \text{ with } \vect{z} \sim \mathcal{N}(\vect{0}, \mat{I})

which needs f−1f^{-1} and no log-determinant at all.

OperationDirectionNeedsUsed for
log_prob(x)density, x→z\vect{x} \to \vect{z}f(x)f(\vect{x}) and log⁡∣det⁡Jf(x)∣\log \vert \det \mat{J}_f(\vect{x}) \vert, (4)density estimation, maximum-likelihood training
sample(key, shape)sampling, z→x\vect{z} \to \vect{x}f−1(z)f^{-1}(\vect{z}), (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 x∈Rx \in \mathbb{R} built from a mixture of MM Gaussians, with weights wm≥0w_m \ge 0 summing to one, means μm∈R\mu_m \in \mathbb{R} and scales σm>0\sigma_m > 0. Its CDF is

F(x)=∑m=1MwmΦ((x−μm)/σm)F(x) = \sum_{m=1}^{M} w_m \Phi((x - \mu_m) / \sigma_m)

where Φ\Phi is the standard-normal CDF, and the marginal map sends xx through FF to a level τ=F(x)∈(0,1)\tau = F(x) \in (0, 1) and then through the standard-normal quantile function:

z=Φ−1(F(x))z = \Phi^{-1}(F(x))

Both FF and Φ−1\Phi^{-1} have closed forms, so the forward map is one line. The inverse is not: FF is a sum of CDFs and has no closed-form inverse, so x=F−1(τ)x = F^{-1}(\tau) is the root of

F(x)−τ=0F(x) - \tau = 0

Because FF 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 [a,b]=[−12,12][a, b] = [-12, 12].

Why

Each step keeps the half of the bracket where F(x)−τF(x) - \tau changes sign, so the root stays inside and the bracket width halves. After nn steps the width is (b−a)/2n(b - a) / 2^{n}, and the midpoint is at most half of that from the root.

The inverse hands (4) to the bisection solver of optimistix on the bracket [−12,12][-12, 12].

A round trip pushes samples forward through FF and recovers them with the root find.

round trip x → F(x) → F⁻¹(F(x)): max |error| = 1.63e-10

At one level τ=0.7\tau = 0.7 we track the residual ∣F(x(n))−τ∣\vert F(x^{(n)}) - \tau \vert against the solver budget nn.

residual after  5 steps: 3.0e-02
residual after 20 steps: 1.4e-06
residual after 45 steps: 2.0e-13
<Figure size 1200x450 with 2 Axes>

Figure 1:Left: the mixture CDF FF is one closed-form sum, and inverting it means reading the curve from right to left, which the root find does for three levels τ\tau. 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.

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 ff, 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 Dx=2D_x = 2, compiled and warmed up first so the race is fair.

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.

We compile both directions once, then time each on the same 5000 points.

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.

log_prob of the samples is finite: True
<Figure size 700x450 with 1 Axes>

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 ff and its inverse f−1f^{-1} 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_prob constantly, during maximum-likelihood training and at every evaluation. They store the density direction in closed form: fast training, slow sampling. The Gaussianization flows of gauss_flows make this choice, which is the asymmetry of section 3.

  • Sampling and variational flows call sample constantly, 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.

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

ConceptEquationIn 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 asymmetrysample many times slower than log_probFigure 2
choosing the cheap directionswap transform and inverseflowjax.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 N(0,I)\mathcal{N}(\vect{0}, \mat{I}) the natural destination.

References
  1. Kidger, P. (2021). On Neural Differential Equations [Phdthesis]. University of Oxford.
  2. Papamakarios, G., Pavlakou, T., & Murray, I. (2017). Masked Autoregressive Flow for Density Estimation. Advances in Neural Information Processing Systems (NeurIPS).
  3. 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).