Push a Gaussian through invertible maps and the density of every data point is exact: the change-of-variables formula, why a triangular Jacobian makes it cheap, and where flows struggle.
Let z have the triangular density pZ(z)=2z on [0,1]. Reflect and stretch it with x=3−2z. At x=2 the inverse gives z=0.5, where the base density is 1. The transformed density is only 0.5: every small interval has become twice as long. Across the whole new support, pX(x)=(3−x)/2 for 1≤x≤3, which integrates to 1. Reflection reverses the slope of the density; stretching changes its height. Both effects must be accounted for.
Keeping track of how a map stretches space is all a normalizing flow needs. The GANs of the previous section, up to image translation, produce images but cannot say how likely an image is; a VAE can, but only through a lower bound. A normalizing flow pushes a simple density through an invertible map and records the stretching, so the density of every data point is exact and training is plain maximum likelihood (Rezende and Mohamed, 2015; Papamakarios et al., 2021).
Draw z∈Rd from the standard normal base density pZ(z)=N(z;0,I) and produce the data by a chain of K maps,
x=f(z)=fK∘⋯∘f2∘f1(z).
Each fi is a diffeomorphism: a bijection that is differentiable and has a differentiable inverse. The chain is then invertible too, with f−1=f1−1∘⋯∘fK−1. Throughout the course the map goes from latent to data, f:z↦x, so f generates and f−1 encodes. The density that the model gives to data is pθ(x), where θ collects the parameters of the maps.
Write Jf(z)=∂f(z)/∂z for the Jacobian matrix of f at z: row k holds the partial derivatives of output k, column j those with respect to input zj. Differentiating f−1(f(z))=z and f(f−1(x))=x with the chain rule gives
Jf−1(x)Jf(z)Jf(z)Jf−1(x)=I,=I,x=f(z).
If z had n coordinates and x had m, these would be products of an n×m and an m×n matrix. Such a product has rank at most min(m,n), while the identities need ranks n and m, so both can hold only when m=n. Unlike in a VAE, the latent vector of a flow is as large as the data.
Figure
Every point of Z has exactly one partner in X
The flow f carries each latent point z to a data point x = f(z) (blue, left to right), and f⁻¹ carries it back (green). Every fᵢ in the chain is a bijection, so no two points of Z share an x and every x has a preimage.
The guess of the opening, pθ(x)=?pZ(f−1(x)), fails for every map that stretches or squeezes. Take z∼N(0,1) and x=2z. The guess pZ(x/2) integrates to 2 over the real line, so it is not even a density. The true distribution is x∼N(0,4), with density pZ(x/2)/2. At x=1 the guess gives 0.352 and the truth is 0.176: f spreads the same probability over twice the length.
Start in one dimension, with an increasing f. An increasing map keeps order, so the event {f(Z)≤x} is the event {Z≤f−1(x)}, and the two distribution functions agree. Differentiating them gives the density:
The fourth line is the chain rule. The last one uses (f−1)′(x)=1/f′(z), which comes from differentiating f(f−1(x))=x. For a decreasing f the inequality flips, FX(x)=1−FZ(f−1(x)), and the derivative gains a minus sign that f′<0 cancels. Both cases read pθ(x)=pZ(z)/∣f′(z)∣, as the probability course derives in full. In the opening example f′(z)=−2, so pX(2)=pZ(0.5)/2=21; the absolute value makes the density positive despite the reflection.
The formula conserves probability band by band. An interval of width dz around z holds probability pZ(z)dz; f sends it to an interval of width ∣f′(z)∣dz around x, which must hold the same probability.
In d dimensions, widths become volumes. Near a point z the map is close to linear,
f(z+δ)≈f(z)+Jf(z)δ,
so a small cube with edges εe1,…,εed goes to a parallelepiped with edges εJf(z)ej: the columns of Jf(z), scaled by ε. A linear map multiplies every volume by the absolute value of its determinant (the determinant as a volume factor), so the image has volume ∣detJf(z)∣εd. It must carry the probability pZ(z)εd of the cube, which divides the density by ∣detJf(z)∣.
Figure
The Jacobian is local geometry
Here det J_f(z) = e^(0.35·z₁). The amber and red areas change by factors of 0.65 and 1.55. A finite cell averages the local determinant across the cell; this need not equal its value at the centre.
The multiple integrals note turns this picture into a derivation, by changing variables in the integral P(X∈B)=P(Z∈f−1(B)). Its result, in our notation, is the change-of-variables formula:
pθ(x)=pZ(z)detJf(z)−1,z=f−1(x).(1)
The first identity of the previous section gives Jf−1(x)=Jf(z)−1, and det(A−1)=1/detA, so the same formula can be written with the Jacobian of the inverse, evaluated at the data point:
pθ(x)=pZ(f−1(x))detJf−1(x).
Where f expands volumes, ∣detJf∣>1, the same probability is spread thinner and the density falls. Where it contracts them, the density rises. A map with ∣detJf∣=1 preserves volume and density, although a shear can still change the shape completely. Where detJf(z)=0, the linearization δ↦Jf(z)δ flattens a small cube onto a lower-dimensional set of zero volume. The map itself need not do so: f(z)=z3 is a bijection of R with f′(0)=0. But the identity Jf−1Jf=I cannot hold at such a point, so the inverse is not differentiable there (here x1/3 has an infinite slope at 0), and (1) would divide by zero. Flow layers are built so that detJf=0 everywhere.
Figure
What |det J| does to a small square
The dashed unit square and its image (filled) under four linear maps; |det J| is the factor by which the area changes. The shear changes the shape and keeps det = 1. With det = 0 the square collapses onto a segment, and the map cannot be inverted.
The highlighted band retains probability 0.152 while stretching by a factor of 2.13. Its average density falls by the same factor. Stronger stretching near zero creates two density peaks.
Take pZ=N(0,1) and the map of the figure,
f(z)f′(z)=z+0.8tanh(2z),=1+1.6sech2(2z)>0,
where the derivative uses dudtanhu=sech2u and the chain rule. Since f′>0 everywhere, f is strictly increasing. The bounded tanh term also gives f(z)→±∞ as z→±∞, so the map is onto R and hence a bijection. Its inverse has no closed form, and a one-dimensional root search finds it. The density is pθ(x)=pZ(z)/f′(z) with z=f−1(x):
z
x=f(z)
f′(z)
pZ(z)
pθ(x)
0
0
2.600
0.3989
0.1534
0.5
1.109
1.672
0.3521
0.2106
1
1.771
1.113
0.2420
0.2174
2
2.799
1.002
0.0540
0.0539
Near the origin f stretches space by a factor of 2.6, so the density there falls well below the Gaussian peak; in the tails f′≈1 and the density hardly changes. One smooth increasing map has turned a single bump into two, with maxima pθ≈0.234 at x≈±1.50. In log form, at z=0.5, logpθ(x)=logpZ(z)−logf′(z)=−1.044−0.514=−1.558.
The band z∈[0.1,0.5] holds probability Φ(0.5)−Φ(0.1)=0.152. Its image x∈[0.258,1.109] is 2.13 times wider, so the average density over it drops by the same factor, from 0.379 to 0.178.
A linear map x=Jz has the same Jacobian J everywhere. For J=2I in two dimensions, every direction is stretched twice and detJ=4: a unit square becomes a 2×2 square, and pθ(x)=pZ(z)/4. As a check, z∼N(0,I) gives x=2z∼N(0,4I), whose density at the origin is 1/(2π⋅4)=0.0398, a quarter of 1/(2π).
For J=diag(2,−2) the square is also mirrored and detJ=−4. The sign of a determinant records orientation; the change of volume, and with it the change of density, uses only ∣detJ∣=4. That is why (1) has an absolute value.
Figure
A Jacobian that stretches each direction by a factor of 2
Top: J = diag(2, 2) turns the unit square into a 2 × 2 square, so the density falls to a quarter. Bottom: J = diag(2, −2) also mirrors the second axis, and the amber quarter-turn marker runs clockwise. Here det J = −4, but the area and the density factor use only |det J| = 4.
Name the intermediate points of the chain z0=z and zi=fi(zi−1) for i=1,…,K, so that zK=x. By the chain rule, the Jacobian of the composition is the product of the layer Jacobians, each taken at its own input point. The determinant of a product is the product of the determinants (properties of the determinant), and the logarithm turns the product into a sum:
The third line is the logarithm of (1). To evaluate (2) we push x backwards through the layers, zK→zK−1→⋯→z0, and collect one log-determinant per layer. This construction is a normalizing flow: the density flows through a sequence of invertible maps, and read backwards the chain normalizes the data, turning it into something close to a standard normal sample once the model fits. The name, and the definition of a flow as a composition of simple maps, come from Tabak and Turner (2013); Rezende and Mohamed used them for variational inference (Papamakarios et al., 2021, §2.4). Their own layers were planar and radial maps, whose determinants are cheap for a reason other than the one below (Flow architectures, part G).
Sampling runs the chain forwards: draw z∼N(0,I) and compute x=f(z). Evaluating a density runs it backwards. Which direction is cheap depends on the layers. Masked autoregressive flows evaluate densities in one pass and sample slowly, inverse autoregressive flows do the reverse, and coupling layers are cheap both ways (Flow architectures, part B).
Equation (2) is an exact log-likelihood, with no bound and no sampling. Training minimizes the average negative log-likelihood over a dataset x(1),…,x(N), which estimates the forward KL divergence from the data distribution to the model up to a constant (why cross-entropy is the loss we minimize):
where zi(n) are the intermediate points of x(n), with zK(n)=x(n) and z0(n)=f−1(x(n)).
The two terms pull against each other, as the smallest flow shows. Fit x=az+b with a>0 to one-dimensional data. Then z=(x−b)/a, logpZ(z)=−z2/2+const and log∣detJ∣=loga, so
Setting the derivatives to zero gives b=xˉ and a2=N−1∑n(x(n)−xˉ)2, the maximum-likelihood variance with denominator N. Without the log-determinant, increasing a keeps improving the first term towards a finite upper bound, with no finite maximizing scale for nonconstant data: every z is pushed towards 0, where the Gaussian peaks. The term −loga charges the model for the volume it squeezes, and so stops it from collapsing all data onto z=0.
Images: dequantization, rescaling and bits per dimension#
Optional depth: the preprocessing behind a reported number of bits per dimension. The rest of the note does not depend on it.
Formula (1) gives a density, so it suits continuous data. Pixels are discrete, x∈{0,…,255}d, and a continuous model can raise its likelihood without bound by piling its mass onto those points. In one dimension, put a Gaussian of width σ with weight 2561 on each of the 256 values: the density at every value is at least 1/(256σ2π), so the log-likelihood of any pixel data grows like −logσ as σ→0. Flows are therefore trained on dequantized data x~=x+u with u∼U[0,1)d. The probability the model gives to the discrete value x is P(x)=∫[0,1)dpθ(x+u)du, and Jensen’s inequality for the concave logarithm gives
Image likelihoods are reported as bits per dimension, −log2P(x)/d, the length per coordinate of a lossless code built from the model (bits per dimension in the autoregressive note). A model that spreads its probability evenly over the 256 values scores exactly 8. For a flow the reported number is −Eu[log2pθ(x+u)]/d, by the inequality above an upper bound on the discrete value.
Networks rarely see raw pixel values. With x′=x~/127.5−1, roughly in [−1,1], the flow models the density of x′. The map x~↦x′ has the constant Jacobian 127.51I, and (1) relates the two densities:
Bits per dimension in pixel units are those in model units plus log2127.5≈6.99. In general, if one quantization level has width a after preprocessing, the offset is −log2a bits per dimension (Kingma and Dhariwal, 2018, eq. 2): log2255≈7.99 for x/255 and exactly 8 for x/256. A flow that reports −3.50 bits per dimension on x′ (toy numbers) has −3.50+6.99=3.49 in pixel units. A negative value in model units is normal, because a density on a narrow range can exceed 1; only pixel-unit numbers compare with the likelihood table of the autoregressive note.
The noise must span exactly one level in the units the network sees. With x′=x/127.5−1 that means adding u/127.5, the same as adding u before rescaling. Noise of width 1 in x′ units would smear each value over about 127 levels, and no noise at all brings back the unbounded likelihood.
A nonlinear preprocessing adds a log-determinant that depends on the pixel. Pixel values are bounded while a Gaussian base lives on all of Rd, so RealNVP models the logit of rescaled pixels (Dinh, Sohl-Dickstein and Bengio, 2017, §4.1). In the symmetric form of its reference code,
py=α+(1−2α)256x~,α=0.05,=log1−pp,
so p∈[0.05,0.95) and y stays within about ±2.94. The derivative is dy/dx~=(1−2α)/(256p(1−p)) per coordinate, so by (1)
The correction is about 6.15 bits for a mid-grey value (x~=128.5) and 3.80 bits for the darkest and brightest ones (x~=0.5 or 255.5). Flows built for images are in Flow architectures, part F.
GAN: a generator maps noise to a sample, and a discriminator labels inputs real or fake; there is no likelihood and no way back from x to z. VAE: a stochastic encoder and decoder give an approximate posterior and a lower bound on log p(x). Flow: one invertible map, exact in both directions, with dim z = dim x.
A GAN defines its distribution only through samples, and nothing guarantees that a real x has a latent code at all. A flow answers both questions exactly; the price is a latent as large as the data and layers restricted to cheap determinants. Diffusion models, later in the course, return to a lower bound on the log-likelihood, an ELBO.
Everything above hinges on log∣detJ∣. For a general d×d matrix it costs O(d3) by LU factorization, about 32d3 floating-point operations (what elimination costs). A 32×32 grayscale image already has d=1024; at d=1000 that is about 6.7⋅108 operations for every example, every layer and every training step. For a general network even forming J takes d backward passes, one per row.
The way out is to build layers whose Jacobian is triangular. Expanding the determinant of a lower-triangular matrix along its first row leaves a11 times the determinant of the remaining lower-triangular block; repeating the step leaves the diagonal (properties of the determinant):
detJlog∣detJ∣=i=1∏dJii,=i=1∑dlog∣Jii∣.
That costs O(d), about 103 operations instead of about 109, and needs only the diagonal entries.
Figure
Why a triangular Jacobian is the trick
With zeros above the diagonal, log|det A| = Σ log|aᵢᵢ|. For d = 1000, a general determinant by LU costs on the order of d³ = 10⁹ operations per example and per layer; the triangular one needs d = 10³ multiplications. Bars are on a log₁₀ scale.
A triangular structure also makes the map easy to invert. If Jf is lower-triangular everywhere, output i depends only on inputs 1,…,i. If each diagonal entry is continuous and nonzero everywhere, it keeps one sign, so each output is strictly monotone in its own input. The map can then be inverted one coordinate at a time: z1 from x1, then z2 from x2 and the known z1, and so on. It is a bijection of Rd when each of these one-dimensional maps is onto R, as the affine maps zi↦eszi+t of coupling layers are.
Triangular maps look like a strong restriction. They are not, in the following sense: every density that is positive everywhere, with differentiable conditional distribution functions, is the image of a uniform density under a triangular map (Papamakarios et al., 2021, §2.2).
A small case first. Let x1∼Exp(1) and x2∣x1∼N(x1,1), and map each coordinate through its conditional distribution function:
The map is triangular, because u1 ignores x2. Its diagonal entries are the derivatives of the distribution functions, which are the densities e−x1 and φ(x2−x1). Their product is the joint density by the chain rule of probability. At x=(1,1.5) the diagonal is 0.368 and 0.352, and the product 0.1295 equals p(x); the point goes to u=(0.632,0.691). The density of this example is zero for x1<0, so the statement above, which asks for a density positive everywhere, does not cover it as written; the construction still works on the region where the density is positive, (0,∞)×R, which u maps onto the open square (0,1)2.
The general argument follows the same steps. Write p(x)=∏ip(xi∣x<i) and define ui=Fi(xi∣x<i), the conditional distribution function. Each Fi is strictly increasing in xi, because its derivative p(xi∣x<i) is positive, so the map is invertible coordinate by coordinate. Its Jacobian is lower-triangular with detJF=∏ip(xi∣x<i)=p(x). Formula (1), applied to F, gives the density of u:
pU(u)=p(x)∣detJF(x)∣−1=1,u∈(0,1)d.
So u is uniform on the unit cube, and F−1 turns uniform noise into x. Applying the standard normal distribution function Φ to each coordinate of z∼N(0,I) gives uniform noise as well, by the probability integral transform, so f=F−1∘Φ is a flow from a Gaussian to p. Read backwards, F−1 is the sampler of an autoregressive model, coordinate after coordinate; the next note builds layers on exactly this structure.
The construction promises that a flow exists. It does not promise that the flow is easy to represent. Take a toy target with two separated modes, p(x)=21N(−4,0.52)+21N(4,0.52), and the one-dimensional flow from the previous section, f=F−1∘Φ. Its slope follows from the one-dimensional form of (1), f′(z)=pZ(z)/p(x):
Point
z
p(x)
f′(z)
centre of a mode, x=−4
−0.674
0.399
0.80
x=−2
≈0
1.3⋅10−4
about 3.0⋅103
the gap, x=0
0
1.0⋅10−14
about 4⋅1013
The whole stretch ∣x∣<2 comes from ∣z∣<4⋅10−5. A network’s slope is limited by its weights. By the chain rule the derivative of a composition is the product of the layers’ derivatives, and with activations of slope at most 1, such as ReLU or tanh, each layer contributes at most the norm of its weight matrix. A slope of 4⋅1013 needs a product of norms at least that large, for example ten layers of norm 23 each. A flow with moderate weights is far less steep: it leaves visible probability in the gap, and its samples land between the modes.
There is a separate topological restriction in any dimension. A diffeomorphism of Rd applied to a Gaussian gives a density that is positive everywhere: in (1) both pZ(z) and ∣detJf(z)∣ are finite and nonzero. Such a flow cannot exactly represent support split by an open region of zero density, or probability concentrated entirely on a lower-dimensional surface. It can approximate these targets, potentially with severe stretching or compression (Papamakarios et al., 2021, §5.5). The number of local peaks is not preserved: our smooth one-dimensional example already turns one peak into two. The Gaussian mixture above is positive everywhere, so an exact flow exists; its very steep middle is a conditioning problem, not a disconnected-support obstruction.
Run python3 scripts/notes/generative-practice.py normalizing-flows. The standard-library experiment generates 4,096 values from a Gaussian with mean 0.45 and standard deviation 1.6, using seed 9303. Fit an affine flow by the sample mean and the maximum-likelihood scale. The saved fit gives 0.455304 and 1.605013.
Evaluate density with the inverse map and the log-determinant. Mean negative log likelihood is 1.892071 nats. Doubling the fitted scale increases it to 2.210218, so the wider model fits worse.
Omit the log-determinant and repeat. The apparent objective falls from 1.418939 to 1.043939 when the scale doubles. This rewards spreading probability without paying for the extra volume.
Numerically integrate over eight fitted standard deviations on each side. The corrected density has mass 1.000000; the expression without the Jacobian has mass 1.605013, matching the scale rather than one. This is a one-dimensional likelihood and normalization check. It does not train a spline flow or establish coverage of complicated multimodal data.
The example, script and observations were newly authored for this course with Codex assistance; the numerical results are from the linked run.
Flows need layers that are expressive and still have a determinant that is cheap by construction. Flow architectures builds them: coupling layers, masked autoregressive layers and Glow’s invertible 1×1 convolutions, then spline couplings and multi-scale flows for images.
G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed, B. Lakshminarayanan. Normalizing flows for probabilistic modeling and inference. JMLR, 22(57), 2021. §2.1 (definition), §2.2 (expressive power), §2.4 (history of the name), §5.5 (topological constraints).