Normalizing flows: change of variables, coupling, autoregressive and continuous flows
Before this lesson: lesson 01 (maximum likelihood) and lesson 03 (MADE, used inside MAF and IAF). From other tracks: change of variables for densities and Jacobians (calculus), Hutchinson's trace estimator (calculus), and the determinant (linear algebra). Time: about 90 minutes, plus the notebook.
Why this matters #
Flows are the second family with an exact likelihood, after autoregressive models (lesson 03). Unlike AR models, a coupling flow samples in one pass. Flows are standard tools for density estimation and variational inference (flexible posteriors), for simulation-based inference (MAF and neural spline flows estimate posteriors of simulator parameters), and for sampling physical systems (Boltzmann generators). The continuous version matters even more today: the probability-flow ODE of diffusion models and the ODE learned by flow matching (lesson 10) are continuous flows, and the instantaneous change of variables of this lesson is how you compute their exact log-likelihood.
1. Predict first #
2. The picture #
One affine map in 1D #
Let and with . An interval of length in -space becomes an interval of length in -space, and it holds the same probability. The same mass on a longer interval means a lower density, so the density is divided by :
Now write for the map from data to base. Then , and the formula reads: the density of is the base density at , times .
A curved map. The same holds point by point for any increasing map : near , the map looks like a line with slope . Where is steep, a small interval of covers a large interval of , so it collects a lot of probability: the density of is high. Where is flat, the density of is low.
Drag the yellow knots of the map . The aqua curve on the left is the base density along the axis. The top chart shows the model density in orange, and a histogram of samples with . The yellow probe interval and its image on the axis hold the same probability. Notice that the area under stays 1, and that the bumps appear where the map is steep.
and . What is ? ( is the standard normal density, .)
Here , so and . Then . The factor is with the absolute value: a density is never negative. Multiplying by is the most common sign of using the wrong direction of the map.
A flow is many such maps #
A normalizing flow makes a composition of invertible layers with learnable parameters: . It is used in two directions.
- Density direction (data base, ): compute and add up the of each layer. This gives , and the training loss.
- Sampling direction (base data, ): draw and invert the layers in reverse order.
In this track, always goes from data to base, . The review by Papamakarios et al. names the sampling map , with : it is the same object seen from the other side, and .
The design problem. Each layer must be (1) invertible, (2) cheap in (a general determinant costs ), and (3) expressive. There are two answers. Make the Jacobian triangular (coupling and autoregressive layers), or make the flow continuous in time, where the log-determinant becomes an integral of a trace.
Coupling layers bend space one coordinate at a time #
An affine coupling layer keeps half of the coordinates and uses them to shift and scale the other half. In 2D: keep ; replace by . The next layer keeps and changes . Each layer is simple, but a stack of them can bend a Gaussian into a curved, skewed shape, and the density stays exact.
Add layers and move the sliders of and . The orange heat map is the exact model density . The aqua curves are the straight grid lines of the base space, carried to data space by the sampling map : where they crowd together, the density is high. Drag the yellow point: each layer adds its own log-determinant, which is just of the kept coordinate. The grid sum of the density stays 1.
3. Definitions and main results #
3.1 The change-of-variables formula #
Theorem (change of variables). Let be a bijection, with and continuously differentiable, and let have density . Then
Why this is true. A small box around with volume is mapped to a small parallelogram around with volume (the determinant is the volume factor of the linear map ). Both hold the same probability: .
Proof.
- 1D, increasing: . Differentiate: .
- 1D, decreasing: , so . Both cases give .
- dimensions: for every set , , by the substitution of multivariable calculus.
- A density is fixed by its integrals over all sets, so the integrand is .
The calculus lesson on change of variables gives the substitution rule of step 3 in full.
Composition. Let , with , and . The chain rule gives , and the determinant of a product is the product of the determinants. So
Training minimizes the mean of over the data: maximum likelihood, the same as minimizing . You never form itself; each layer reports its own log-determinant.
The other direction. In the sampling direction, and : the sign flips, because . Check with : the data are more spread out than the base, so the density must go down, and indeed .
3.2 Affine coupling layers (RealNVP and Glow) #
Split . Let and be any networks from to vectors of the size of , and the elementwise product. The affine coupling layer (RealNVP; Dinh et al. 2017) is
- Jacobian. does not depend on , so the upper-right block is 0. Each depends on only through , so the lower-right block is diagonal:
- Log-determinant. The matrix is block lower triangular, so its determinant is the product of the diagonal entries: . The cost is . The block , which holds all the derivatives of the networks, never enters.
- Inverse. and . It needs only forward passes of and , so and never have to be inverted: they can be arbitrary networks.
- Stacking. One layer leaves unchanged, so the roles of and alternate (or the coordinates are permuted) between layers. The product of the layer Jacobians is a full matrix, but its log-determinant is still the sum of the layer terms.
In practice the log-scale is bounded, for example or a soft clamp, so each factor stays in a safe range early in training.
Which part of the Jacobian of an affine coupling layer never enters ?
The Jacobian is block lower triangular, and the determinant of a triangular matrix is the product of its diagonal entries. The off-diagonal block can be as complicated as you like: it does not change the determinant. This is why and can be deep networks.
Glow (Kingma and Dhariwal 2018) adds two layers for feature maps of size with channels:
- Actnorm: a per-channel scale and bias, initialized on the first batch so that each channel has zero mean and unit variance. Log-determinant: .
- Invertible convolution: the same matrix mixes the channels at every pixel. The Jacobian of the whole layer is block diagonal with copies of , so . With the LU form ( a fixed permutation, unit lower triangular, strictly upper triangular), : cost instead of . It generalizes the fixed permutation between coupling layers.
3.3 Autoregressive flows (MAF and IAF) #
An affine autoregressive layer transforms coordinate with a shift and a log-scale . Both come from one MADE network (lesson 03) with two outputs per dimension.
MAF (masked autoregressive flow; Papamakarios et al. 2017) works in the density direction:
- Jacobian. depends on only, so is lower triangular with diagonal entries . Hence .
- Density: one pass. All depend on the observed , so one MADE pass gives all of them.
- Sampling: passes. The inverse is , and must be known before . This is the ancestral sampling of lesson 03. An AR model with Gaussian conditionals is exactly a one-layer MAF.
IAF (inverse autoregressive flow; Kingma et al. 2016) works in the sampling direction. Its parameters depend on the base variables:
- Sampling: one pass, because is known.
- Density of its own samples: one pass. , and is kept from the sampling step.
- Density of an outside : passes. Recovering needs first.
Choose a flow and a task, then press Next pass. One MADE pass computes and for all at once, but entry is valid only when the network inputs are known. Entries that became valid in the last pass are yellow. Try all four cases: MAF density and IAF sampling finish in one pass; MAF sampling and IAF density need passes.
| Flow | of a data point | Sampling | Typical use |
|---|---|---|---|
| Coupling (RealNVP, Glow) | 1 pass | 1 pass | images, audio (WaveGlow); needs many layers |
| MAF | 1 pass | passes | density estimation, simulation-based inference |
| IAF | passes (own samples: 1) | 1 pass | VAE posteriors; fast students (Parallel WaveNet) |
| Continuous (FFJORD) | ODE solve + trace | ODE solve | free-form vector field; cost = number of evaluations |
A coupling layer is an autoregressive layer with only two blocks: block is conditioned on block , and on nothing. That is why it is fast in both directions, and less expressive per layer.
You want a flexible posterior inside a VAE. The ELBO needs samples and of those same samples. Which flow fits best?
The ELBO never asks for the density of a point that the flow did not generate. IAF keeps from the sampling step, so both the sample and its log-density cost one pass. MAF would need sequential passes to sample. This is the original use of IAF (Kingma et al. 2016).
3.4 Continuous flows: the instantaneous change of variables #
A continuous normalizing flow (CNF) defines the map by an ordinary differential equation
Any network that is Lipschitz in (and continuous in ) works. The solution map is invertible (solve the ODE backwards in time), and needs no special structure: no triangular Jacobian, no coupling.
Picture: one Euler step. The step has Jacobian , with , and . The change of variables for this small step gives . Now let .
Theorem (instantaneous change of variables; Chen et al. 2018). If solves and is the density of , then
The trace of the Jacobian is the divergence : the rate at which the flow expands volume. Expanding volume lowers the density along the path.
Proof (from the continuity equation)
- Probability mass moves with the flow, so solves the continuity equation .
- Along a trajectory, the total derivative is (chain rule, with ).
- Expand and insert step 1 into step 2: .
- Divide by : .
Integrate from the data at to the base at :
One ODE solver call integrates the state and the accumulated trace together. Training a CNF by maximum likelihood needs gradients through the solver (backpropagation through the solver steps, or the adjoint method of Chen et al. 2018).
Move the time , or press Play. A linear field (violet arrows) moves samples of ; the aqua points and the grey ellipses (1 and 2 standard deviations) show , which stays Gaussian, so everything is exact. The readouts compare the change of log-density along the magenta path, computed from the Gaussian formula, with . Drag the start point and try the presets: the two numbers always agree, and a rotation () keeps the density along every path.
Hutchinson's estimator (FFJORD). The exact trace needs backward passes, one per diagonal entry of . For any random vector with (Rademacher entries, or Gaussian),
because . The product is one vector-Jacobian product: one backward pass per probe, whatever is. FFJORD (Grathwohl et al. 2019) uses this estimator and keeps the same for a whole ODE solve, so the dynamics stay deterministic inside the solver. Two facts to remember. The estimate of is unbiased, but its exponential is not an unbiased estimate of (Jensen's inequality). And the variance of one probe is for Gaussian probes and for Rademacher probes, with : Rademacher probes add no noise from the diagonal. The calculus lesson proves the variance formulas.
Choose a Jacobian and a number of probes . The histograms show 2000 estimates of the trace with Gaussian and Rademacher probes; the black line is the true trace. The lower chart shows the variance against on log scales, with the formulas as dashed lines. Notice that both estimators are centered on the truth, that the variance falls like , and that Rademacher probes are exact for a diagonal Jacobian.
and has independent Rademacher entries ( with probability ). What is ?
, and . So the mean is . The values are or , each with probability ; their variance is . Only the cross terms cancel, not the diagonal.
Diffusion models and flow matching are continuous flows. The probability-flow ODE of a diffusion model (lesson 09) is , where and are the drift and the diffusion coefficient of the forward SDE (the letter has that meaning in lessons 07 to 15). It has the same marginals as the diffusion process. With the learned score inserted, its right side is a vector field like the one above, so the formula of this subsection gives the exact log-likelihood of that ODE model, up to solver error and trace noise. Song et al. (2021) report the bits per dimension of diffusion models this way. Flow matching and rectified flow (lesson 10) train the same kind of continuous flow without simulating the ODE; after training, the same formula gives their likelihood.
3.5 What flows cannot do #
- No change of dimension. A flow is a bijection between and with a square Jacobian. A flow cannot map data to a smaller latent space, as a VAE does. If had fewer dimensions than , the samples would lie on a lower-dimensional surface, which has zero volume in : there would be no density at all.
- Topology. A flow is a continuous bijection, and is positive everywhere, so everywhere: the model can never put exactly zero density between two separated modes. To make the density small there, the sampling map must stretch that region very strongly (huge ), which needs very large derivatives and is hard to learn.
Why can a normalizing flow not map 784-dimensional images to a 64-dimensional Gaussian latent?
The change-of-variables formula needs to be invertible and to exist, so and must have the same dimension. A map from 64 to 784 dimensions puts all samples on a 64-dimensional surface; such a distribution has no density in . (A matrix has no determinant at all.) VAEs and diffusion models in a latent space avoid this limit.
Answers to section 1. (1) : the log-determinant is . The networks cost one forward pass; no determinant is ever computed. (2) MAF evaluates in one pass, because its parameters depend on the observed . IAF samples in one pass, because its parameters depend on the known base variables . Each needs passes in its other direction.
4. Worked example #
(a) Two coupling layers in 2D (density direction, base ), at .
- Layer 1 keeps , with and . So , , and . Log-determinant: .
- Layer 2 keeps , with and . So and . Log-determinant: .
- Base: .
- Result: .
The layer Jacobians are triangular, (lower) and (upper), but their product has no zero entry. Still, , and .
Inverse. Undo layer 2 first: and . Then undo layer 1: and .
(b) A one-layer MAF is a Gaussian AR model. Take and (so ), and , (so , a "banana" shape). At :
- one pass: , log-determinant ;
- ;
- chain-rule check: .
Sampling from takes two passes: first , then .
(c) A linear continuous flow. with and . Here everywhere, so . Check with the discrete formula: the flow map is , and (Jacobi's formula ). The flow shrinks volume, so the density grows along each path, by the factor . This is the "worked example" preset of the figure above.
Hutchinson by hand: the four Rademacher probes give for . The mean is , and the variance is : with Rademacher probes, only the off-diagonal entries add noise.
5. In code #
NumPy and SciPy check the hand computations: the coupling layers with a finite-difference Jacobian, the MAF against the chain rule, Glow's log-determinant, the instantaneous change of variables on a nonlinear 2D flow, and Hutchinson's estimator. For (d), with vector field , we integrate the Jacobian of the flow map (it solves ) next to , and compare with .
import numpy as np
from scipy.integrate import solve_ivp
from scipy.stats import norm
# (a) The two coupling layers of section 4, density direction x -> z
def f(x):
y = np.array([x[0], x[1] * np.exp(x[0] / 2) - x[0]]) # layer 1 keeps x1
return np.array([y[0] * np.exp(-y[1] / 2) + 1, y[1]]) # layer 2 keeps y2
x = np.array([2.0, 1.0])
z = f(x)
h = 1e-6 # Jacobian by central differences
J = np.column_stack([(f(x + h * e) - f(x - h * e)) / (2 * h) for e in np.eye(2)])
logdet = np.linalg.slogdet(J)[1]
print(z.round(4), J.round(4).tolist()) # [2.3966 0.7183] [[0.4475, -1.8981], [0.3591, 2.7183]]
print(round(logdet, 4), round(norm.logpdf(z).sum() + logdet, 4)) # 0.6409 -4.3267
# (b) The one-layer MAF of section 4 equals the chain rule p(x1) p(x2 | x1)
x1, x2 = 2.0, 3.0
u = np.array([(x1 - 0.0) / 2.0, (x2 - x1**2) / 1.0]) # mu1 = 0, sigma1 = 2; mu2 = x1^2, sigma2 = 1
print(round(norm.logpdf(u).sum() - np.log(2.0), 4),
round(norm.logpdf(x1, 0, 2) + norm.logpdf(x2, x1**2, 1), 4)) # -3.531 -3.531
# (c) Glow's 1x1 convolution: the Jacobian is block diagonal with H*W copies of W
c, H, W_ = 3, 4, 5
Wmix = np.random.default_rng(0).normal(size=(c, c))
Jc = np.kron(np.eye(H * W_), Wmix) # (60, 60), pixel by pixel
print(round(np.linalg.slogdet(Jc)[1], 6), round(H * W_ * np.linalg.slogdet(Wmix)[1], 6))
# -16.271734 -16.271734
# (d) Instantaneous change of variables for dx/dt = tanh(Ax + b): integrate x, the Jacobian Phi
# of the flow map, and delta = -int tr(df/dx) dt together
A, b = np.array([[0.5, -2.0], [1.0, -1.0]]), np.array([0.3, -0.2])
def rhs(t, s):
xs, Phi = s[:2], s[2:6].reshape(2, 2)
Jf = np.diag(1 - np.tanh(A @ xs + b) ** 2) @ A # df/dx
return np.concatenate([np.tanh(A @ xs + b), (Jf @ Phi).ravel(), [-np.trace(Jf)]])
s0 = np.concatenate([[1.0, -0.5], np.eye(2).ravel(), [0.0]])
sol = solve_ivp(rhs, (0.0, 2.0), s0, rtol=1e-10, atol=1e-12)
Phi, delta = sol.y[2:6, -1].reshape(2, 2), sol.y[6, -1]
print(round(delta, 6), round(-np.log(abs(np.linalg.det(Phi))), 6)) # 0.213696 0.213696
# (e) Hutchinson on the 2x2 matrix of section 4: all four Rademacher probes
Alin = np.array([[-1.0, 2.0], [0.0, -0.5]])
eps = np.array([[1, 1], [1, -1], [-1, 1], [-1, -1]])
q = np.einsum("ni,ij,nj->n", eps, Alin, eps)
print(q, q.mean(), q.var()) # [ 0.5 -3.5 -3.5 0.5] -1.5 4.0
Check (d) is Liouville's formula : the instantaneous change of variables seen from the Jacobian side.
6. Where it shows up #
- Images and audio. RealNVP and Glow use coupling layers; WaveGlow uses them for speech. On CIFAR-10, Glow reaches 3.35 bits per dimension; strong AR models (PixelCNN++: 2.92) and diffusion models do better (lesson 14 explains how such numbers are compared).
- Variational inference. An IAF makes a VAE's flexible: the VAE needs only samples from and of those samples. Parallel WaveNet distills a slow AR WaveNet into a fast IAF student.
- Simulation-based inference. MAF and neural spline flows are standard conditional density estimators for neural posterior estimation, where a simulator exists but its likelihood is not available.
- Physics sampling. Boltzmann generators (Noé et al. 2019) and flows for lattice field theory sample with an exact density , then reweight by or add a Metropolis correction to remove the model's bias.
- Continuous flows in ML for science. Rectified-flow and flow-matching models are CNFs, and diffusion models have the probability-flow ODE. The held-out log-likelihood from the instantaneous change of variables is a strictly proper score for comparing such models of, for example, ground motion or weather fields. Report it on a fixed data scale: if a model is trained on in dimensions, then .
7. Common mistakes #
- Sign of the log-determinant. In the density direction, (add). In the sampling direction, (subtract). Check with : the density must go down.
- No alternation. Coupling layers with the same split keep unchanged forever.
- Unbounded scales. with a raw network output can overflow. Bound it (, a soft clamp) and initialize near the identity.
- MAF sampling in one pass, or IAF density of data in one pass. Each needs sequential passes in its slow direction.
- Forgetting preprocessing log-determinants. Scaling, logit transforms and dequantization change ; add their log-determinants before you compare likelihoods.
- Trusting one Hutchinson probe for evaluation, or exponentiating it as an unbiased likelihood. Use the exact trace or many probes for test numbers.
- Expecting a perfect fit of separated modes. The model density is positive everywhere, also between separated modes (section 3.5).
8. Check yourself #
- A coupling layer gives . What is of the layer, and of its inverse?
Answer
. The inverse layer has . - A Glow convolution acts on a feature map, and .
What does the layer add to in the density direction?
Answer
nats: the Jacobian has diagonal blocks equal to . - A MAF on dimensions. How many MADE passes does it need to evaluate of a batch of
data? To draw a batch of samples?
Answer
One pass for the density. 100 sequential passes for sampling, because needs . - Why is IAF a good VAE posterior but a poor density estimator for data?
Answer
A VAE needs samples and of those same samples: one pass each, since is known. The density of an outside point needs from , which takes sequential passes. - A CNF has with (a rotation). How does
change along a trajectory?
Answer
It stays constant: , so the flow is divergence-free and keeps volume. - Hutchinson with Rademacher probes on . Give the
possible values of , the mean and the variance.
Answer
, so or , each with probability . Mean ; variance .
State the change-of-variables formula for .
, with and a smooth bijection.
and . What is ?
.
Log-likelihood of a flow in the density direction?
, with and .
Affine coupling layer: formula and ?
, ; .
Why is the Jacobian of a coupling layer triangular?
does not depend on (zero block), and each depends on only through (diagonal block).
MAF vs IAF: which is fast for what?
MAF: density of data in one pass, sampling in passes. IAF: sampling in one pass (and of its own samples), density of outside data in passes.
Log-determinant of a Glow convolution on an map?
, because the Jacobian is block diagonal with copies of the matrix .
State the instantaneous change of variables.
For : .
What is Hutchinson's trace estimator, and why is it unbiased?
with ; unbiased because .
Why can a flow not have a lower-dimensional latent space?
It must be a bijection with a square Jacobian; samples from a lower-dimensional lie on a zero-volume surface and have no density in .
9. Interview angle #
- "Write the log-likelihood of a normalizing flow." — along the density direction.
- "Coupling or autoregressive flow?" — The cost table: coupling is fast both ways but weaker per layer; MAF is fast for density, IAF for sampling.
- "Derive the log-determinant of a Glow convolution." — Block-diagonal Jacobian with copies of : ; the LU form makes it .
- "How do you get the likelihood of a diffusion or flow-matching model?" — The instantaneous change of variables along the probability-flow ODE, with a Hutchinson or exact trace (for diffusion there is also the ELBO of lesson 07).
- "Why do flows give worse samples than diffusion models?" — The same dimension everywhere, the topology limit, many constrained layers, and maximum likelihood spends capacity on covering all the data. Flow matching and diffusion train an unconstrained network and get invertibility from the ODE.
10. Practice #
The notebook for this lesson has five exercises, each with a check cell and a folded solution, and a demonstration that trains a small RealNVP on two moons in NumPy:
- 1D change of variables: the density of , checked against a histogram of mapped samples.
- Affine coupling forward and inverse; compare the log-determinant with a finite-difference Jacobian.
- A RealNVP stack:
log_probandsample; check that the density integrates to 1 on a grid. - Hutchinson's estimator with Gaussian and Rademacher probes; compare the variances with the formulas.
- The linear ODE : check that the change of along a path is .
11. Watch and read #
- Papamakarios, Nalisnick, Rezende, Mohamed and Lakshminarayanan, Normalizing Flows for Probabilistic Modeling and Inference (JMLR 2021): §2 (definition and composition), §3.1 (coupling and autoregressive flows, the MAF/IAF cost asymmetry), §3.2 (linear flows, convolutions), §4.1 (continuous-time flows).
- Murphy, Probabilistic Machine Learning: Advanced Topics, free PDF: chapter 23 (§23.2.3 coupling flows, §23.2.4 autoregressive flows, §23.2.6 continuous-time flows).
- Dinh, Sohl-Dickstein and Bengio, Density estimation using Real NVP (ICLR 2017); Kingma and Dhariwal, Glow (2018).
- Papamakarios, Pavlakou and Murray, Masked Autoregressive Flow for Density Estimation (2017); Kingma et al., Improving Variational Inference with Inverse Autoregressive Flow (2016).
- Chen, Rubanova, Bettencourt and Duvenaud, Neural Ordinary Differential Equations (2018); Grathwohl et al., FFJORD (ICLR 2019), §3.1 (the trace estimator with a fixed noise vector).
- Lilian Weng, Flow-based Deep Generative Models: a readable overview.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.