Normalizing Flows
A transformation you can undo exactly: one input gives one output, and the output gives the input back.
The simple noise the flow starts from, usually a Gaussian (a bell-shaped cloud).
The true probability density the model gives to a data point, with no lower bound or approximation.
One number that says how much a transformation stretches or squeezes space at a point.
The rule that turns a density before a map into a density after it, using the stretch factor.
A grid of numbers with zeros on one side of the diagonal. Its determinant is just the product of the diagonal.
A layer that copies half the numbers and transforms the other half using the copied half. It is easy to invert.
A flow made of infinitely many tiny steps, written as a differential equation. Flow matching trains one.
After this lesson, you will be able to:
- Apply the change-of-variables formula to compute exact likelihoods through any invertible transformation, and understand why generative modeling can be reframed as 'find a bijection from noise to data'
- Build coupling layers (NICE/RealNVP) that are simultaneously invertible AND have a triangular Jacobian whose determinant is a single multiplication — the trick that makes flows tractable
- Compare normalizing flows against VAEs, GANs, and diffusion: when exact likelihood matters, flows win; when sample quality matters at the same parameter count, diffusion wins
- Recognize Continuous Normalizing Flows (Neural ODEs) as the bridge from discrete-step flows to Flow Matching — the same ODE framing, different training objective
Before you start
Picture a rubber sheet with a round blob of dots printed on it. Stretch and twist the sheet without tearing or folding it, and the blob becomes a moon shape. Nothing tore, so you can untwist the sheet exactly. A normalizing flow is a stack of such stretches, and how much the sheet stretched tells you how the density changed.
#The Generative Modeling Trilemma
#The Change of Variables Formula
A tiny example first. Suppose a flow doubles every number: x = 2z. Stretching by 2 spreads the same probability over twice the length, so the density at x is half the density at z. The determinant term in the formula is exactly this stretch factor.
If x = f(z) and f is invertible with differentiable inverse, then:
Take logs to make it computable in practice and to compose multiple layers cleanly:
The whole training objective is one line: maximize log-likelihood. No discriminator, no KL term to balance, no noise schedule to tune. The catch: that determinant. The density rule itself, with its Jacobian determinant, is derived in Multivariate Gaussian & Joint Distributions in the Math track.
Do: Raise the number of flow steps, pick a target shape, and flip the direction.Notice: The Gaussian cloud bends step by step into the target shape, and flipping runs it back.Why: Drawn stand-in, not a trained flow: the bending map is hand-built to show the idea of an invertible map.
#Why the Determinant Is the Hard Part
#The Cheap Case: Triangular Jacobians
The rest of this lesson leans on one fact about matrices. If every entry above the diagonal is zero, the determinant is just the product of the diagonal entries, which costs d multiplications instead of about d cubed operations. Every layer design below is a way of forcing the Jacobian into that shape. The derivation is optional reading.
#Planar and Radial Flows: Cheap Determinants from Rank-One Updates
The earliest flow layers (Rezende and Mohamed, 2015) took a different route to a cheap determinant. The planar flow is f(z) = z + u h(w^T z + b), with vectors u and w, a number b and a smooth scalar function h such as tanh. It pushes points along the fixed direction u by an amount that depends on which side of a hyperplane they sit. The radial flow is f(z) = z + beta h(r)(z - z0) with r the distance from a centre z0 and h(r) = 1/(alpha + r), which pushes points away from or toward z0. In both, the Jacobian is a scaled identity plus a rank-one matrix, and the matrix determinant lemma gives its determinant in O(d). Both derivations are optional.
#Coupling Layers: The NICE/RealNVP Trick
The breakthrough came from Dinh et al. 2014 (NICE) and 2017 (RealNVP): split the input vector into two halves and only transform one of them.
The two claims in the box above (the Jacobian is triangular with a one-line log-determinant, and the inverse needs no inversion of s or t) follow from the layer's definition. The derivation is optional reading.
Drag the four inputs, turn the strength of s and t up and down, swap which half is frozen, and press invert; watch that the Jacobian has an exactly zero block, that its determinant is the product of the diagonal so the log-det equals the sum of s however complicated the networks are, and that the inverse recovers x.
Do: Drag the four inputs, change the strength of s and t, swap the frozen half, and press invert.Notice: The Jacobian has an exact zero block, and the log-determinant equals the sum of s.Why: Only the scale terms sit on the diagonal, so s and t can be any networks. Computed exactly from the formulas, not trained.
#Composing Layers: Log-Likelihood Becomes a Sum
The stacked formula comes from the chain rule for Jacobians. The derivation also shows where the base density is evaluated and why the data-to-noise code flips the sign. It is optional reading.
#Glow: Production-Quality Flows
Glow (Kingma & Dhariwal 2018) added two key tricks that pushed flows to photorealistic faces:
- Invertible 1×1 convolutions. Replace the fixed half-split with a learned linear shuffle. The 1×1 conv weight matrix W is c×c, where c is the channel count (for example 64×64), so its determinant is computable in O(c³), which is tiny. This lets the model learn which dimensions to entangle in each layer rather than relying on a hardcoded split.
- Multi-scale architecture. Periodically halve the spatial resolution by factoring out half the dimensions and routing them straight to the output. This dramatically reduces compute per layer at high resolutions and matches the way images carry information across scales.
Images are integers, so flows are trained on dequantised pixels (a little uniform noise added to each integer value, which turns the discrete data into a continuous density) and are scored in bits per dimension, the negative log base 2 likelihood divided by the number of dimensions. The 1 by 1 convolution's log-determinant is the one new formula in Glow, and it follows from the block structure of its Jacobian. The derivation is optional reading.
You stack 8 affine coupling layers but use the SAME mask pattern (top-half passive, bottom-half active) on every layer. What goes wrong?
The top half of the input passes through unchanged in every single layer, so the network can never modify it. RealNVP and Glow alternate the mask pattern (e.g., top-passive on odd layers, bottom-passive on even layers), or, in Glow, replace the fixed split with a learned 1×1 conv shuffle so every dimension gets its turn in motion.
#Continuous Normalizing Flows: The ODE View
The discrete-step flow z_0 → z_1 → ... → z_L can be taken to a continuous limit. Imagine infinitely many infinitesimal layers, each making a tiny change. The whole flow becomes the solution of an ordinary differential equation:
The trace of the Jacobian is the only quantity a continuous flow needs for its likelihood. In one dimension it is just the derivative f_z, and the next derivation gets it from the change-of-variables rule applied to one tiny step. In d dimensions the derivative becomes the trace of the Jacobian, the divergence of f. It is optional reading.
#Autoregressive Flows: The Other Family
p(x) = p(x_1) · p(x_2 | x_1) · p(x_3 | x_1, x_2) · ...
Each conditional is a learned transform of a Gaussian. The Jacobian is triangular by construction (later dimensions depend only on earlier ones), so the determinant is again the product of diagonal entries.
Both the triangular structure of autoregressive flows and the speed asymmetry between MAF and IAF can be derived from one formula. The derivation is optional reading.
#Implementation: 2D RealNVP From Scratch
The cell below runs in your browser: a numpy-only RealNVP with hand-written gradients. The PyTorch original after it does not run here, so copy it to Colab if you want autograd and a GPU.
Tests: Verify the samples lie roughly on the two-moons distribution (their mean and spread should match the data's). Verify the reconstruction error is at floating-point noise level (about 1e-16 in float64), proving the bijection is exact, and that the analytic log-determinant of a layer matches the numerical Jacobian.
# Build a 4-layer RealNVP on a 2D toy dataset
import torch
import torch.nn as nn
import math
torch.manual_seed(42)
class AffineCoupling(nn.Module):
"""Affine coupling layer with alternating mask."""
def __init__(self, dim, hidden=64, swap=False):
super().__init__()
self.dim = dim
self.swap = swap
# s and t each map d/2 -> d/2 (no inversion of s,t needed)
self.net = nn.Sequential(
nn.Linear(dim // 2, hidden),
nn.ReLU(),
nn.Linear(hidden, hidden),
nn.ReLU(),
nn.Linear(hidden, dim), # outputs [s; t] concatenated
)
def split(self, x):
x_a, x_b = x.chunk(2, dim=-1)
if self.swap:
x_a, x_b = x_b, x_a
return x_a, x_b
def merge(self, a, b):
if self.swap:
a, b = b, a
return torch.cat([a, b], dim=-1)
def forward(self, x):
# data -> noise (used for log-likelihood)
x_a, x_b = self.split(x)
st = self.net(x_a)
s, t = st.chunk(2, dim=-1)
s = torch.tanh(s) # clamp scale for stability
y_b = (x_b - t) * torch.exp(-s)
y = self.merge(x_a, y_b)
log_det = -s.sum(dim=-1)
return y, log_det
def inverse(self, y):
# noise -> data (used for sampling)
y_a, y_b = self.split(y)
st = self.net(y_a)
s, t = st.chunk(2, dim=-1)
s = torch.tanh(s)
x_b = y_b * torch.exp(s) + t
return self.merge(y_a, x_b)
class RealNVP(nn.Module):
def __init__(self, dim=2, n_layers=4, hidden=64):
super().__init__()
self.dim = dim
self.layers = nn.ModuleList([
AffineCoupling(dim, hidden, swap=(i % 2 == 1))
for i in range(n_layers)
])
self.register_buffer("base_mean", torch.zeros(dim))
self.register_buffer("base_logvar", torch.zeros(dim))
def base_log_prob(self, z):
return -0.5 * (z ** 2).sum(dim=-1) - 0.5 * self.dim * math.log(2 * math.pi)
def log_prob(self, x):
z = x
log_det_total = 0.0
for layer in self.layers:
z, log_det = layer(z)
log_det_total = log_det_total + log_det
return self.base_log_prob(z) + log_det_total
@torch.no_grad()
def sample(self, n=512):
z = torch.randn(n, self.dim)
x = z
for layer in reversed(self.layers):
x = layer.inverse(x)
return x
def two_moons(n=2048):
"""Toy 2D dataset: two crescent shapes."""
n_per = n // 2
t = torch.rand(n_per) * math.pi
x1 = torch.stack([torch.cos(t), torch.sin(t)], dim=-1)
x2 = torch.stack([1 - torch.cos(t), 0.5 - torch.sin(t)], dim=-1)
x = torch.cat([x1, x2], dim=0)
x = x + 0.1 * torch.randn_like(x)
return x
# === Train ===
model = RealNVP(dim=2, n_layers=4, hidden=64)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
data = two_moons(4096)
for epoch in range(2000):
idx = torch.randint(0, len(data), (256,))
batch = data[idx]
loss = -model.log_prob(batch).mean()
opt.zero_grad()
loss.backward()
opt.step()
if epoch % 200 == 0:
print(f"epoch {epoch:4d} nll={loss.item():.3f}")
# === Sample and verify exact invertibility ===
samples = model.sample(8)
print("\nSamples from learned distribution:")
print(samples)
# Forward through the layers, then inverse — should match input bit-by-bit
x_test = data[:4]
z = x_test.clone()
for layer in model.layers:
z, _ = layer(z)
x_recovered = z
for layer in reversed(model.layers):
x_recovered = layer.inverse(x_recovered)
print(f"\nMax reconstruction error: {(x_test - x_recovered).abs().max().item():.2e}")
print("(should be ~1e-7, within float32 numerical precision, proving the bijection is exact)")
# CHALLENGE: extend to a checkerboard distribution. Increase n_layers to 8.
# Plot a 2D heatmap of model.log_prob over a grid to see the learned density.#Glow Architecture: From Toy 2D to 256x256 Faces
Glow's full recipe stacks three things:
- Actnorm. A per-channel affine transform initialized so the first batch has zero mean and unit variance. Replaces BatchNorm (which isn't invertible across batches).
- Invertible 1x1 conv. A learned channel-mixing matrix. The determinant is computable in O(c³) where c is the channel count (small).
- Affine coupling. Same RealNVP coupling, but the s and t networks are convolutional.
Three of these stacked = one "step of flow." Stack 32 steps per scale, halve resolution between scales (multi-scale architecture), and you have the Glow architecture, which produced 256x256 face samples with exact log-likelihoods.
#Why Diffusion Won (and Where Flows Still Win)
By 2022, flows had been overtaken on image quality by diffusion models. The reason isn't fundamental — it's that:
- Diffusion scales gracefully: bigger models, more compute, more steps → better samples. Flows appear to hit a quality ceiling per parameter because the architecture must remain invertible.
- Diffusion trains on a simple regression loss (predict noise). Flows train on direct log-likelihood, which is theoretically the right objective but harder to optimize at scale.
But flows still dominate where exact likelihood matters:
- Physics simulation (lattice QCD, statistical mechanics) — you need exact ratios of probabilities for Markov-chain Monte Carlo
- Anomaly detection. Exact log-likelihood gives a meaningful "weirdness" score
- Variational inference for Bayesian models. Flows parameterize approximate posteriors that you can score and sample from
- Compression. Exact likelihood = exact bit-coding length (lossless compression bound)
#Key Takeaways
- The change-of-variables formula reduces generative modeling to designing invertible neural networks —
log p(x) = log p(z) + log|det J|, where J is the Jacobian of the transform; if you can build invertible networks with tractable Jacobians, you have a generative model with exact likelihood and exact sampling - Coupling layers solve the determinant problem. Split the input, freeze one half, transform the other half conditioned on the frozen half; the resulting Jacobian is triangular, so the determinant is just the product of the scale factors — O(d) instead of O(d³)
- Stack many alternating coupling layers, then add 1x1 convs and multi-scale routing for production quality — RealNVP, Glow, and the autoregressive variants are all variations on this theme; the trick is making the architecture rich enough to model real data while keeping every layer invertible
- Continuous Normalizing Flows reframe stacked layers as an ODE. Z(T) = z(0) + integral of f_theta from 0 to T; this is the conceptual ancestor of Flow Matching and the modern image models built on it
- Flows lost the image-generation race to diffusion at large scale, but stayed crucial for exact-likelihood applications — physics, chemistry, Bayesian inference, lossless compression, and as a foundation for Flow Matching, which trains FLUX.1 and SD3
#Quick Check
Why do affine coupling layers (RealNVP) have a tractable Jacobian determinant?