Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Bending a bell curve without losing probability
Start with points scattered like a bell curve. Move every point with a smooth rule that never folds space over itself, and you get a new cloud of points with a new shape. Where the rule stretches space, the points spread out and the density drops; where it squeezes space, the density rises. The change-of-variables formula is the bookkeeping that tracks this exactly, so a flow can say not only how to draw samples but also precisely how likely any given point is. The demo bends a bell curve with a smooth bump and shows the new density.
Exact densities make flows useful where a calibrated likelihood matters: anomaly scores on spacecraft telemetry, posterior estimation for inverse problems in remote sensing, and sampling in physics simulations.
- 1. A normalizing flow maps a simple density to a complex one with…
- 2. Where a map stretches space, the density…
- 3. A flow can compute the density of a data point…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.The formula and its pieces
- Setup: base variable z with density p_Z (usually N(0, I)); data x = f(z) with f invertible and differentiable, inverse g = f⁻¹.
- Change of variables: p_X(x) = p_Z(g(x)) · |det ∂g/∂x| = p_Z(z) · |det ∂f/∂z|⁻¹. In logs: log p_X(x) = log p_Z(g(x)) + log |det J_g(x)|.
- Why the determinant: locally f is linear with Jacobian J; a small box of volume dV around z maps to a parallelotope of volume |det J| dV, and probability mass is conserved.
- Composition: f = f_K ∘ … ∘ f_1 gives log |det J| = Σ_k log |det J_k|, so flows are built from many simple layers.
- Cost: a dense D×D determinant costs O(D³). Flow layers are designed so the Jacobian is triangular (log-det = Σ log |diagonal|, O(D)), or otherwise cheap.
- Two directions: the density needs g (data → noise); sampling needs f (noise → data). Some designs make one direction fast and the other slow.
- Training: maximise Σ log p_X(x_n), i.e. minimise forward KL from the data to the model. In nats per example, or bits per dimension = NLL / (D ln 2).
- Discrete data: add uniform noise to 8-bit pixels (dequantisation) so a continuous density is meaningful; bits/dim then includes the D ln 256 bin-volume term.
- 1. log p_X(x) = log p_Z(g(x)) + …
- 2. Log-dets of composed layers…
- 3. A triangular Jacobian's log-det costs…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Writing flow log-densities
Exercise 1.
- The standard normal log-density.
- An affine flow x = A z + b (its density is N(b, AAᵀ)).
- An elementwise flow given its inverse and the inverse’s derivative.
Practice.
- Always work in log space and sum log-dets; never multiply raw determinants.
- Use slogdet, or a triangular structure, instead of det.
- Test a new layer by comparing its analytic log-det with log |det| of a finite-difference Jacobian on a few points.
- Test invertibility: g(f(z)) should match z to about 1e-10 in float64.
- Report test NLL in nats per example for low-dimensional data and bits per dimension for images.
import torch
from torch.distributions import Normal, TransformedDistribution
from torch.distributions.transforms import AffineTransform, ExpTransform
base = Normal(torch.zeros(2), torch.ones(2))
flow = TransformedDistribution(base, [AffineTransform(loc=0.0, scale=0.5), ExpTransform()])
x = flow.sample((5,))
print(flow.log_prob(x).sum(-1)) # change of variables applied layer by layer- 1. A finite-difference Jacobian is useful to…
- 2. Report image likelihoods in…
- 3. Combine layer log-dets by…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Derivation. For invertible f, P(X ∈ A) = P(Z ∈ g(A)) = ∫_g(A) p_Z(z) dz. Substituting z = g(x), dz = |det J_g(x)| dx (the multivariable substitution rule), gives ∫_A p_Z(g(x)) |det J_g(x)| dx for every set A, which identifies p_X. The inverse function theorem gives J_g(x) = J_f(z)⁻¹, so |det J_g| = 1 / |det J_f|.
Maximum likelihood is forward KL. E_data[−log p_X(x)] = KL(p_data ‖ p_X) + H(p_data). Minimising NLL therefore drives the model toward the data, and the gap between a model’s test NLL and the true density’s NLL is the KL divergence.
Why the log-det cannot be dropped. Without it, the objective −log p_Z(g(x)) rewards mapping all data to the mode of p_Z: contract everything to z ≈ 0. For a linear flow x = L z + μ that means making L huge. The log-det term −log |det L| charges for exactly that volume.
Universality. In 1-D, F_X⁻¹(Φ(z)) is an exact flow for any continuous density; in D dimensions the Knothe–Rosenblatt rearrangement (a triangular map built from conditional CDFs) is one too, which is why triangular, autoregressive structures are enough in principle.
Exercise check. The map x = (z1, z2·exp(z1/2) + 0.5(z1² − 1)) has a triangular Jacobian with determinant exp(z1/2). On a 60×60 grid over [−4, 4]² the formula with the Jacobian matched a 200000-sample histogram to a total-variation distance of 0.031, partly sampling noise and partly the 1.9% of mass outside the window (grid mass 0.981). Without the factor the distance was 0.204 and the ‘density’ had mass 1.086.
- 1. Minimising NLL is equivalent to minimising…
- 2. Without the log-det, maximum likelihood would…
- 3. A triangular map built from conditional CDFs is the…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.Does the Jacobian term really matter, numerically and in training?
History.
- E. G. Tabak and E. Vanden-Eijnden, “Density estimation by dual ascent of the log-likelihood” (2010), and Tabak and Turner (2013): the term “normalizing flow” for density estimation.
- D. J. Rezende and S. Mohamed, “Variational inference with normalizing flows” (2015): flows as flexible posteriors.
- L. Dinh, D. Krueger and Y. Bengio, “NICE” (2014): tractable deep flows for density estimation.
- G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed and B. Lakshminarayanan, “Normalizing flows for probabilistic modeling and inference” (JMLR, 2021): the standard review.
Exercise 2.
- Push-forward check: 200000 samples of z ~ N(0, I) pushed through x = (z1, z2·exp(z1/2) + 0.5(z1² − 1)); 60×60 histogram on [−4, 4]² compared with the formula with and without |det|.
- Training check: a linear flow x = L z + μ (lower-triangular L, log-diagonal parameterisation) fitted to 2000 two-moons points by Adam, 600 steps, with and without the −log |det L| term; compared with the closed-form Gaussian MLE.
| measure | seed 0 | seed 1 | seed 2 |
|---|---|---|---|
| TV distance, with Jacobian | 0.031 | 0.031 | 0.032 |
| TV distance, without Jacobian | 0.204 | 0.204 | 0.202 |
| mass of Jacobian-free ‘density’ | 1.086 | 1.086 | 1.086 |
| Gaussian MLE NLL (nats) | 2.747 | 2.716 | 2.709 |
| linear flow NLL | 2.747 | 2.716 | 2.709 |
| no log-det: abs det L | 474 | 474 | 474 |
| no log-det: true NLL | 8.001 | 8.001 | 8.002 |
- Formula verified: with the Jacobian the formula matched the histogram up to sampling noise and window truncation; without it, the density was wrong by a total-variation distance of 0.2.
- Linear flow = Gaussian: maximum likelihood for an affine flow recovered the Gaussian MLE to three decimals on every seed.
- Without the log-det, the optimiser kept inflating det L (474 after 600 steps, still growing), making the latent codes tiny and the true NLL 5.3 nats worse.
- Caveat: 2-D toy maps; in high dimensions the same failure appears as collapsing or exploding scales.
Change of variables in AI, robotics and aerospace
- Exact likelihoods: flows give calibrated densities for anomaly detection on telemetry and for likelihood-based model comparison.
- Simulation-based inference: conditional flows (neural posterior estimation, e.g. the sbi package) estimate posteriors of physical parameters from simulated observations, used in astrophysics and atmospheric retrievals.
- Reparameterisation: the same formula underlies the reparameterisation trick, tanh-squashed Gaussian policies in SAC (with the log(1 − tanh²) correction) and bijectors in TensorFlow Probability and Pyro.
References
- E. G. Tabak and E. Vanden-Eijnden (2010). “Density estimation by dual ascent of the log-likelihood.” Communications in Mathematical Sciences.
- D. J. Rezende and S. Mohamed (2015). “Variational inference with normalizing flows.” ICML.
- G. Papamakarios et al. (2021). “Normalizing flows for probabilistic modeling and inference.” JMLR.
- I. Kobyzev, S. Prince and M. Brubaker (2021). “Normalizing flows: an introduction and review of current methods.” IEEE TPAMI.