A variational autoencoder gives you a bound on log p(x). A normalizing flow gives you log p(x) itself, because it is built from layers you can undo and whose effect on volume you can measure. This lesson pairs with Lecture 23 of CMU's 11-785 (Fall 2026), linked under Watch & read. The schedule lists that lecture as normalizing flows and diffusion; this lesson builds the flow half, and the next lesson builds the diffusion half. You build affine coupling layers in PyTorch that run in both directions, track the log-determinant of each, and train a stack of them by maximum likelihood.
The idea is an invertible function f that maps data x to a latent z = f(x) with a simple density p_z, usually a standard normal. Probability is conserved, which gives the change of variables formula:
log p(x) = log p_z(f(x)) + log |det J|, where J is the Jacobian of f at x.
Start in one dimension, with z = (x - m) / s. An interval of x of width w lands on an interval of z of width w / s, and both hold the same probability. So the density of x is the density of z times 1/s, and 1/s is the determinant here. The formula therefore returns the density of a normal with mean m and standard deviation s. Take m = 2, s = 0.5 and x = 2.5. Then z = 1, log p_z(1) = -1.4189, log(1/s) = 0.6931, and the sum -0.7258 is the log-density of a normal(2, 0.5) at 2.5.
The determinant term is bookkeeping for volume. Without it, p_z(f(x)) integrates to s, not to 1: as a function of x it has the height of the standard normal and only s times its width. Measure it: sum the density over a fine grid.
import numpy as np
m, s, x = 2.0, 0.5, 2.5
z = (x - m) / s
log_pz = -0.5 * z**2 - 0.5 * np.log(2 * np.pi)
print(round(log_pz, 4), round(-np.log(s), 4), round(log_pz - np.log(s), 4))
grid = np.linspace(-6, 10, 160001)
step = grid[1] - grid[0]
pz = np.exp(-0.5 * ((grid - m) / s) ** 2) / np.sqrt(2 * np.pi)
print(round(pz.sum() * step, 4), round((pz / s).sum() * step, 4))The first line reproduces the numbers above. The second shows 0.5 without the term and 1.0 with it.
In D dimensions two problems appear. A general network cannot be inverted, and the determinant of a general D by D Jacobian costs on the order of D³ operations. A coupling layer removes both. A mask splits the coordinates in two parts. The part where the mask is 1 passes through unchanged and is the only input of a small network, which returns a scale s and a shift t for the other part:
y_b = x_b · exp(s(x_a)) + t(x_a), y_a = x_a.
The inverse needs no network inversion: y_a = x_a is known, so the same network gives the same s and t, and x_b = (y_b - t(y_a)) · exp(-s(y_a)). The Jacobian is triangular, with ones for the passed coordinates and exp(s) for the others, so its log-determinant is the sum of s over the transformed coordinates. This build keeps s between -1 and 1 with a tanh, so exp(s) cannot explode.
Here is one layer on one point, with a mask that keeps x₁ and with s = tanh(x₁) and t = x₁² standing in for a network. It runs the layer both ways and measures the Jacobian by finite differences.
import numpy as np
def forward(x):
s, t = np.tanh(x[0]), x[0] ** 2
return np.array([x[0], x[1] * np.exp(s) + t]), s
def inverse(z):
s, t = np.tanh(z[0]), z[0] ** 2
return np.array([z[0], (z[1] - t) * np.exp(-s)])
x = np.array([0.5, 2.0])
z, s = forward(x)
print(z.round(4).tolist(), inverse(z).round(4).tolist())
eps = 1e-6
cols = [(forward(x + eps * e)[0] - forward(x - eps * e)[0]) / (2 * eps) for e in np.eye(2)]
jac = np.stack(cols, axis=1)
print(jac.round(4).tolist())
print(round(float(np.log(abs(np.linalg.det(jac)))), 4), round(float(s), 4))The zero above the diagonal makes the determinant cheap. The entry below it, 3.4969, depends on how s and t change with x₁ and never enters the determinant. The last line shows log|det J| equal to s.
One layer leaves the masked part untouched, so you stack layers with alternating masks. Two directions then do two jobs. Data to latent gives the likelihood: run the layers in order, add each log-determinant, and evaluate the standard normal at the end. Latent to data gives samples: draw z from a standard normal and apply the inverses from the last layer to the first. Training minimizes the mean negative log-likelihood directly. There is no encoder and no bound. When the data comes from a known density, that density's own negative log-likelihood on the same data is the number to compare against.
The three generative models of this course sit at different points. The VAE optimizes a bound and samples in one pass. A flow has the exact likelihood and samples in one pass, at the price of invertible layers and a latent as large as the data. A diffusion model gives up the exact likelihood for a simple training target and samples in many steps.
Mistakes to look for:
- Subtracting the log-determinant, or leaving it out. The values still look like log-densities, so only a measurement exposes it.
- Undoing the scale before the shift. The inverse of x · eˢ + t is (z - t) · e⁻ˢ.
- Applying the inverses in forward order when sampling. They must run from the last layer to the first.
- Feeding the net the whole vector instead of the masked half. The inverse can then no longer recompute s and t.
The tests verify the layer three independent ways: autograd's Jacobian and slogdet against your log-determinant, a closed form for a layer with constant s and t, and a grid sum of the density that must come to 1. A flow that passes all three has a valid, normalized density. That does not show that it fits any real data. The data here is two-dimensional, and image flows add multi-scale architectures and other invertible layers that this lesson does not cover.