Normalizing Flows & Deep Density Models
Exact likelihoods through invertible maps.
A normalizing flow turns a simple density into a complicated one through an invertible network, and pays for the flexibility with one bookkeeping term: the log-determinant of a Jacobian. That single term dictates every architecture in the family. This lesson derives the change-of-variables objective, builds layers whose determinants are cheap, proves that triangular maps can carry any positive density onto any other, and follows the idea to continuous-time flows and flow matching, the bridge to diffusion models.
What you’ll learn
- Derive the change-of-variables formula and the maximum-likelihood objective of a flow, and show that maximizing likelihood minimizes the forward KL divergence.
- Build coupling layers (NICE, RealNVP, Glow) and autoregressive layers (MAF, IAF) with triangular Jacobians, and explain their trade-off between density evaluation and sampling.
- Prove the Knothe–Rosenblatt construction, which makes increasing triangular maps universal, and explain the topological limits of flows.
- Derive the instantaneous change of variables, Hutchinson's trace estimator and the flow-matching objective, and compare flows with VAEs, GANs and diffusion models.
Change of variables and maximum likelihood
A normalizing flow starts from a base density , usually , and a diffeomorphism . Sampling is , . Density evaluation runs the inverse , the direction that "normalizes" data into noise.
In one dimension with increasing, . Differentiate:
In dimensions the substitution rule for integrals, for every set , gives the absolute Jacobian determinant, the local factor by which stretches volume:
Stack invertible layers, , with and . Determinants multiply, so log-determinants add:
Fit by maximum likelihood. Averaged over the data distribution, the log-likelihood is minus a cross-entropy, which splits into the data's entropy (fixed) and a KL divergence:
Maximum likelihood therefore minimizes the forward KL divergence, which punishes a model for putting little mass where data occur: flows trained this way are mass-covering. Flows used for variational inference (Rezende & Mohamed, 2015) minimize the reverse divergence instead, which needs only samples from and an unnormalized target .
A general determinant costs , hopeless when is the number of pixels, so the whole art is to design layers with triangular Jacobians, whose determinants are products of diagonal entries. Two practical details. Discrete data such as 8-bit pixels are dequantized by adding uniform noise on to each integer value; by Jensen's inequality the continuous model's expected log-density is then a lower bound on the discrete log-likelihood. And image likelihoods are reported in bits per dimension, on the 0–255 pixel scale.
A density on is pushed through . What is ?
- nats
- : rescaling does not change densities
- nats
- nats
Show the answer
C. nats
The inverse map is with , so . Stretching every axis by 2 multiplies volume by , and the same probability spread over more volume means lower density.
Layers with triangular Jacobians
Coupling layers (NICE: Dinh, Krueger & Bengio, 2015; RealNVP: Dinh, Sohl-Dickstein & Bengio, 2017) split , leave one half alone and transform the other with parameters computed from the first. The networks and are arbitrary: they are never inverted.
The forward map:
The Jacobian is block lower triangular, with the identity in one diagonal block and a diagonal matrix in the other. The messy block does not enter the determinant:
Inversion only re-evaluates and on the unchanged half:
Successive layers alternate which half is transformed, so every coordinate gets updated. NICE uses the additive case , which preserves volume, plus a final diagonal scaling. Glow (Kingma & Dhariwal, 2018) adds activation normalization and an invertible convolution: one learned matrix mixes the channels at each of the pixel positions, adding to the log-determinant, and an LU factorization of makes that cheap.
Autoregressive flows make each coordinate an affine function of a noise variable, given the coordinates before it: with . The Jacobian of is triangular, so . The masked autoregressive flow (MAF; Papamakarios, Pavlakou & Murray, 2017) computes all from in one pass of a masked network, so density evaluation is fast, but sampling must produce in turn. The inverse autoregressive flow (IAF; Kingma, Salimans, Jozefowicz, Chen, Sutskever & Welling, 2016) conditions on instead, making sampling one pass and the density of an arbitrary sequential. It suits variational posteriors, which only need the densities of their own samples. RealNVP is the special case of MAF in which half the coordinates are left unchanged and the other half are conditioned only on that half.
| Layer | Density of data | Sampling | |
|---|---|---|---|
| Additive coupling (NICE) | one pass | one pass | |
| Affine coupling (RealNVP) | one pass | one pass | |
| convolution (Glow) | one pass | one pass | |
| Masked autoregressive (MAF) | one pass | sequential passes | |
| Inverse autoregressive (IAF) | , generator direction | sequential passes | one pass |
import torch
import torch.nn as nn
class AffineCoupling(nn.Module):
"""y_A = x_A, y_B = x_B * exp(s(x_A)) + t(x_A). d must be even."""
def __init__(self, d, hidden=256):
super().__init__()
self.net = nn.Sequential(nn.Linear(d // 2, hidden), nn.ReLU(),
nn.Linear(hidden, d)) # outputs s and t
def forward(self, x): # x -> (y, log|det J|)
xa, xb = x.chunk(2, dim=-1)
s, t = self.net(xa).chunk(2, dim=-1)
s = torch.tanh(s) # keep the scales bounded
return torch.cat([xa, xb * torch.exp(s) + t], dim=-1), s.sum(dim=-1)
def inverse(self, y):
ya, yb = y.chunk(2, dim=-1)
s, t = self.net(ya).chunk(2, dim=-1)
s = torch.tanh(s)
return torch.cat([ya, (yb - t) * torch.exp(-s)], dim=-1)A full flow stacks such layers with permutations between them, sums the returned log-determinants, and adds of the final output; training maximizes that total over mini-batches.
Triangular maps are universal
Map to the uniform distribution on one coordinate at a time, using conditional distribution functions:
Given , the variable is uniform (the probability integral transform), whatever the condition. So is uniform and independent of , which are functions of , and is uniform on the cube. The map is triangular with , so
Build the same way. It is invertible, and the inverse of an increasing triangular map is increasing triangular, as is a composition of two. So below pushes to . Uniqueness: given , the -th component must carry one conditional distribution onto another monotonically, and in one dimension that map is unique.
Read backward, generates coordinate by coordinate from independent uniforms, : an autoregressive flow whose -th map is a conditional quantile function. So autoregressive flows whose per-coordinate maps can be any increasing function, such as monotone neural networks (Huang, Krueger, Lacoste & Courville, 2018) or monotone splines, are universal density approximators. A single affine layer is not, and depth, permutations between layers or richer monotone maps restore the expressivity. Coupling flows built from affine layers can also approximate a broad class of diffeomorphisms (Teshima et al., 2020).
Limits. A flow is a diffeomorphism of , so its density is positive everywhere and the Gaussian's single blob can be stretched and folded but never torn. A target whose support has separate pieces or holes can only be approximated by squeezing mass out of the gaps, which takes very large and very small Jacobians, and well-separated modes strain a flow in the same way. Cornish, Caterini, Deligiannidis & Doucet (2020) prove that approximating a target whose support differs topologically from the base's ever more closely forces the flow to become arbitrarily close to non-invertible, numerically. Data concentrated near a lower-dimensional set, as images are, strain flows in a similar way.
With a standard Gaussian base, which densities can a single affine autoregressive layer represent?
- Any density, because it is autoregressive
- Only the standard Gaussian
- Only densities with independent coordinates
- Exactly those whose conditionals are Gaussian, with means and variances that may depend on
Show the answer
D. Exactly those whose conditionals are Gaussian, with means and variances that may depend on
Given , is an affine function of one standard normal, so it is Gaussian with mean and variance . A bimodal conditional is out of reach; it needs a non-affine monotone map or more layers.
Continuous flows and flow matching
Let depth go to the limit of infinitely many infinitesimal layers. A continuous normalizing flow (Chen, Rubanova, Bettencourt & Duvenaud, 2018) defines by an ODE, , from to . Any Lipschitz vector field gives an invertible map, since the ODE can be run backward, so the network needs no special structure. The price moves from the architecture to the bookkeeping:
The density of obeys the continuity equation, conservation of probability mass along the flow:
Follow one trajectory. Since , the total derivative of along the path is
Integrate from 0 to 1. The sum of log-determinants of a discrete flow becomes an integral of a trace:
The exact trace takes about vector–Jacobian products. Hutchinson's estimator (Hutchinson, 1989) is unbiased with one, which is how FFJORD (Grathwohl, Chen, Bettencourt, Sutskever & Duvenaud, 2019) scaled continuous flows to images:
Training a continuous flow by maximum likelihood still means solving the ODE at every step. Flow matching (Lipman, Chen, Ben-Hamu, Nickel & Le, 2023) avoids simulation altogether. Choose a path from noise to data, for instance the straight line between a noise sample and an independent data point . Conditional on the pair, its velocity is simply , and the network regresses on that.
Expand both squared errors. The terms are identical, and the terms without do not depend on :
The cross terms agree by the tower property, conditioning on :
Sampling solves the learned ODE from noise, and density evaluation integrates the trace along the same path. Diffusion models fit the same frame. Song, Sohl-Dickstein, Kingma, Kumar, Ermon & Poole (2021) showed that a diffusion process has a deterministic ODE with the same marginal distributions, which samples the same distribution and gives exact likelihoods through the instantaneous change of variables; and Gaussian probability paths in flow matching include diffusion-style paths as special cases.
| Family | Trained by | Sampling cost | Main weakness | |
|---|---|---|---|---|
| Discrete flow | exact maximum likelihood | exact | one pass | layers restricted to cheap Jacobians |
| Continuous flow, flow matching | likelihood with ODE solves, or simulation-free regression | exact, via an ODE and a trace | one ODE solve, many network calls | slow sampling and likelihood evaluation |
| Diffusion, score model | denoising score matching, a weighted ELBO | bound, or exact via the probability-flow ODE | many denoising steps | slow sampling, though distillation helps |
| VAE | ELBO | lower bound only | one pass | blurrier samples; a gap between the bound and |
| GAN | adversarial game | none | one pass | unstable training; can drop modes |
Key takeaways
- A flow's density is , with log-determinants adding over layers. Maximum likelihood minimizes the forward KL divergence, so flows are mass-covering.
- Coupling layers (NICE, RealNVP, Glow) and autoregressive layers (MAF, IAF) make Jacobians triangular. Coupling is fast in both directions; MAF is fast for density evaluation and IAF for sampling.
- The Knothe–Rosenblatt construction, built from conditional distribution functions, shows that increasing triangular maps can push any positive density onto any other, so sufficiently flexible autoregressive flows are universal. Diffeomorphisms cannot change topology, though, so flows strain on supports with holes or separate pieces.
- Continuous flows replace the log-determinant by , estimated with Hutchinson's trick. Flow matching trains them without simulation by regressing on conditional velocities such as .
- Diffusion models fit the same frame through their probability-flow ODE, which gives exact likelihoods. Likelihood and sample quality are largely independent measures, so a model must be judged by the one its use requires.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A flow maps data to latents by , with base density . Which expression is ?
Show the answer
B.
Probability is conserved: , and . Where expands volume (it spreads data out to look like noise), the data density is correspondingly higher.
You train by maximum likelihood on millions of data points and rarely need samples. Which autoregressive layer fits?
- IAF, because it samples in one pass
- Either: autoregressive layers are equally fast in both directions
- Neither: autoregressive flows cannot evaluate densities exactly
- MAF, because it evaluates the density of any data point in one pass
Show the answer
D. MAF, because it evaluates the density of any data point in one pass
MAF conditions on , so a masked network computes every from the data in parallel, and training touches only the fast direction. IAF reverses the trade-off.
Why does FFJORD estimate with Hutchinson's estimator ?
- The exact trace needs about vector–Jacobian products, while the estimate needs one and is unbiased
- The trace is undefined for continuous-time flows
- It computes the determinant exactly in time
- It makes the ODE solver more stable
Show the answer
A. The exact trace needs about vector–Jacobian products, while the estimate needs one and is unbiased
For any with , , and is one reverse-mode product. The noise this adds to the log-likelihood is the price of unconstrained architectures.
Flow matching with straight paths regresses on , which is random given . Why does it still learn the right vector field?
- Because is in fact determined by
- Because the network memorizes each noise–data pair
- Because the conditional loss equals the marginal loss plus a constant, so its minimizer is , the marginal velocity
- It does not: training must solve the ODE to correct the targets
Show the answer
C. Because the conditional loss equals the marginal loss plus a constant, so its minimizer is , the marginal velocity
Squared error is minimized by a conditional mean. Expanding the square, the cross term agrees with the marginal one by the tower property, and the rest does not depend on . Training needs no simulation at all.
Further reading
- L. Dinh, J. Sohl-Dickstein & S. Bengio, "Density estimation using Real NVP," ICLR (2017).
- G. Papamakarios, T. Pavlakou & I. Murray, "Masked autoregressive flow for density estimation," NeurIPS (2017).
- R. T. Q. Chen, Y. Rubanova, J. Bettencourt & D. Duvenaud, "Neural ordinary differential equations," NeurIPS (2018).
- Y. Lipman, R. T. Q. Chen, H. Ben-Hamu, M. Nickel & M. Le, "Flow matching for generative modeling," ICLR (2023).
- G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed & B. Lakshminarayanan, "Normalizing flows for probabilistic modeling and inference," Journal of Machine Learning Research 22(57), 1–64 (2021).