Course contents 22 / 34

22 / 34 · Normalizing Flows

Normalizing flows: change of variables

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.

On this page 9

Let zz have the triangular density pZ(z)=2zp_Z(z) = 2z on [0,1][0, 1]. Reflect and stretch it with x=3−2zx = 3 - 2z. At x=2x = 2 the inverse gives z=0.5z = 0.5, where the base density is 1. The transformed density is only 0.50.5: every small interval has become twice as long. Across the whole new support, pX(x)=(3−x)/2p_X(x) = (3-x)/2 for 1≤x≤31 \le x \le 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).

The model: invertible maps out of a Gaussian#

Draw z∈Rdz \in \mathbb R^d from the standard normal base density pZ(z)=N(z; 0,I)p_Z(z) = \mathcal N(z;\, 0, I) and produce the data by a chain of KK maps,

x=f(z)=fK∘⋯∘f2∘f1(z).x = f(z) = f_K \circ \dots \circ f_2 \circ f_1(z) .

Each fif_i 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−1f^{-1} = f_1^{-1} \circ \dots \circ f_K^{-1}. Throughout the course the map goes from latent to data, f:z↦xf: z \mapsto x, so ff generates and f−1f^{-1} encodes. The density that the model gives to data is pθ(x)p_\theta(x), where θ\theta collects the parameters of the maps.

Write Jf(z)=∂f(z)/∂zJ_f(z) = \partial f(z)/\partial z for the Jacobian matrix of ff at zz: row kk holds the partial derivatives of output kk, column jj those with respect to input zjz_j. Differentiating f−1(f(z))=zf^{-1}(f(z)) = z and f(f−1(x))=xf(f^{-1}(x)) = x with the chain rule gives

Jf−1(x) Jf(z)=I,Jf(z) Jf−1(x)=I,x=f(z).\begin{aligned} J_{f^{-1}}(x)\, J_f(z) &= I, \\ J_f(z)\, J_{f^{-1}}(x) &= I, \qquad x = f(z) . \end{aligned}

If zz had nn coordinates and xx had mm, these would be products of an n×mn \times m and an m×nm \times n matrix. Such a product has rank at most min⁡(m,n)\min(m, n), while the identities need ranks nn and mm, so both can hold only when m=nm = 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

Points mapped between latent space Z and data space XTwo coordinate systems side by side, Z on the left and X on the right. Three points in Z are each joined to one point in X by a pair of parallel arrows: a blue arrow labelled f pointing from Z to X and a green arrow labelled f inverse pointing back from X to Z. The three points in Z are representative latent points (z is distributed as a standard Gaussian), and each x equals f of z.Zz ~ N(0, I)Xx = f(z)ff−1zxPoints mapped between latent space Z and data space XTwo coordinate systems side by side, Z on the left and X on the right. Three points in Z are each joined to one point in X by a pair of parallel arrows: a blue arrow labelled f pointing from Z to X and a green arrow labelled f inverse pointing back from X to Z. The three points in Z are representative latent points (z is distributed as a standard Gaussian), and each x equals f of z.Zz ~ N(0, I)Xx = f(z)ff−1zx
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.

Why not just read off the base density?#

The guess of the opening, pθ(x)=?pZ(f−1(x))p_\theta(x) \overset{?}{=} p_Z(f^{-1}(x)), fails for every map that stretches or squeezes. Take z∼N(0,1)z \sim \mathcal N(0, 1) and x=2zx = 2z. The guess pZ(x/2)p_Z(x/2) integrates to 2 over the real line, so it is not even a density. The true distribution is x∼N(0,4)x \sim \mathcal N(0, 4), with density pZ(x/2)/2p_Z(x/2)/2. At x=1x = 1 the guess gives 0.3520.352 and the truth is 0.1760.176: ff spreads the same probability over twice the length.

Change of variables#

Start in one dimension, with an increasing ff. An increasing map keeps order, so the event {f(Z)≤x}\{f(Z) \le x\} is the event {Z≤f−1(x)}\{Z \le f^{-1}(x)\}, and the two distribution functions agree. Differentiating them gives the density:

FX(x)=P(f(Z)≤x)=P(Z≤f−1(x))=FZ(f−1(x)),pθ(x)=pZ(f−1(x)) (f−1)′(x)=pZ(z)f′(z),z=f−1(x).\begin{aligned} F_X(x) &= P\big(f(Z) \le x\big) \\ &= P\big(Z \le f^{-1}(x)\big) \\ &= F_Z\big(f^{-1}(x)\big), \\ p_\theta(x) &= p_Z\big(f^{-1}(x)\big)\, \big(f^{-1}\big)'(x) \\ &= \frac{p_Z(z)}{f'(z)}, \qquad z = f^{-1}(x) . \end{aligned}

The fourth line is the chain rule. The last one uses (f−1)′(x)=1/f′(z)(f^{-1})'(x) = 1/f'(z), which comes from differentiating f(f−1(x))=xf(f^{-1}(x)) = x. For a decreasing ff the inequality flips, FX(x)=1−FZ(f−1(x))F_X(x) = 1 - F_Z(f^{-1}(x)), and the derivative gains a minus sign that f′<0f' < 0 cancels. Both cases read pθ(x)=pZ(z)/∣f′(z)∣p_\theta(x) = p_Z(z)/\lvert f'(z)\rvert, as the probability course derives in full. In the opening example f′(z)=−2f'(z) = -2, so pX(2)=pZ(0.5)/2=12p_X(2) = p_Z(0.5)/2 = \tfrac12; the absolute value makes the density positive despite the reflection.

The formula conserves probability band by band. An interval of width dzdz around zz holds probability pZ(z) dzp_Z(z)\, dz; ff sends it to an interval of width ∣f′(z)∣ dz\lvert f'(z)\rvert\, dz around xx, which must hold the same probability.

In dd dimensions, widths become volumes. Near a point zz the map is close to linear,

f(z+δ)≈f(z)+Jf(z) δ,f(z + \delta) \approx f(z) + J_f(z)\, \delta ,

so a small cube with edges εe1,…,εed\varepsilon e_1, \dots, \varepsilon e_d goes to a parallelepiped with edges εJf(z)ej\varepsilon J_f(z) e_j: the columns of Jf(z)J_f(z), scaled by ε\varepsilon. A linear map multiplies every volume by the absolute value of its determinant (the determinant as a volume factor), so the image has volume ∣det⁡Jf(z)∣ εd\lvert\det J_f(z)\rvert\, \varepsilon^d. It must carry the probability pZ(z) εdp_Z(z)\, \varepsilon^d of the cube, which divides the density by ∣det⁡Jf(z)∣\lvert\det J_f(z)\rvert.

Figure

The Jacobian is local geometry

A grid warped by a nonlinear flowLeft or top: a regular square grid in Z with two highlighted cells. Right or bottom: the same grid after the map f, now curved and fanned out to the right. The amber cell on the left side is squashed to 0.65 times its area, close to the absolute Jacobian determinant 0.65 at its centre. The red cell on the right side is stretched to 1.55 times its area, close to the determinant 1.55.ZXfsquashed:|det J| ≈ 0.65stretched:|det J| ≈ 1.55A grid warped by a nonlinear flowLeft or top: a regular square grid in Z with two highlighted cells. Right or bottom: the same grid after the map f, now curved and fanned out to the right. The amber cell on the left side is squashed to 0.65 times its area, close to the absolute Jacobian determinant 0.65 at its centre. The red cell on the right side is stretched to 1.55 times its area, close to the determinant 1.55.ZXfsquashed:|det J| ≈ 0.65stretched:|det J| ≈ 1.55
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))P(X \in B) = P(Z \in f^{-1}(B)). Its result, in our notation, is the change-of-variables formula:

  pθ(x)=pZ(z) ∣det⁡Jf(z)∣−1,z=f−1(x).  (1)\boxed{\; p_\theta(x) = p_Z(z)\, \big\lvert\det J_f(z)\big\rvert^{-1}, \qquad z = f^{-1}(x) . \;} \tag{1}

The first identity of the previous section gives Jf−1(x)=Jf(z)−1J_{f^{-1}}(x) = J_f(z)^{-1}, and det⁡(A−1)=1/det⁡A\det(A^{-1}) = 1/\det A, so the same formula can be written with the Jacobian of the inverse, evaluated at the data point:

pθ(x)=pZ(f−1(x)) ∣det⁡Jf−1(x)∣.p_\theta(x) = p_Z\big(f^{-1}(x)\big)\, \big\lvert\det J_{f^{-1}}(x)\big\rvert .

Where ff expands volumes, ∣det⁡Jf∣>1\lvert\det J_f\rvert > 1, the same probability is spread thinner and the density falls. Where it contracts them, the density rises. A map with ∣det⁡Jf∣=1\lvert\det J_f\rvert = 1 preserves volume and density, although a shear can still change the shape completely. Where det⁡Jf(z)=0\det J_f(z) = 0, the linearization δ↦Jf(z) δ\delta \mapsto J_f(z)\,\delta flattens a small cube onto a lower-dimensional set of zero volume. The map itself need not do so: f(z)=z3f(z) = z^3 is a bijection of R\mathbb R with f′(0)=0f'(0) = 0. But the identity Jf−1Jf=IJ_{f^{-1}} J_f = I cannot hold at such a point, so the inverse is not differentiable there (here x1/3x^{1/3} has an infinite slope at 0), and (1) would divide by zero. Flow layers are built so that det⁡Jf≠0\det J_f \ne 0 everywhere.

Figure

What |det J| does to a small square

Area scaling for determinants 2, 0.5, 1 and 0Four panels in a two by two grid, each with a dashed unit square and its image under a 2 by 2 matrix. Top left: matrix with rows 2 0 and 0 1, determinant 2, the area is doubled. Top right: rows 1 0.4 and 0 0.5, determinant 0.5, the area is halved. Bottom left: a shear with rows 1 0.8 and 0 1, determinant 1, the area is preserved although the shape changes. Bottom right: rows 1 0.5 and 0.6 0.3, determinant 0, the square is crushed onto a line segment and the map is not invertible.det J = 2 ⇒ doubled2001det J = 0.5 ⇒ halved10.400.5det J = 1 ⇒ preserved10.801det J = 0 ⇒ crushed10.50.60.3not invertible ⇒ unusable for flows
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.

A worked one-dimensional example#

Figure

Change of variables in one dimension

A slab of probability mass carried through a one-dimensional flowCentre: the increasing curve x = f(z) = z + 0.8 tanh(2z), steep near the origin and close to slope 1 in the tails. Below it, the standard normal density p_Z(z), with the slab z from 0.1 to 0.5 shaded; its probability mass is about 0.152. Pale bands carry the slab up to the curve and across to the right panel, where the model density p_theta(x) is drawn sideways. The image of the slab, x from 0.258 to 1.109, is wider and the shaded area there has the same mass but lower height. p_theta has two bumps because f stretches the region around zero.-2-1012-3-2-10123zxx = f(z)zpZ(z)Δz = 0.4pθ(x)Δx ≈ 0.851same probability mass,different widthmass ≈ 0.152A slab of probability mass carried through a one-dimensional flowCentre: the increasing curve x = f(z) = z + 0.8 tanh(2z), steep near the origin and close to slope 1 in the tails. Below it, the standard normal density p_Z(z), with the slab z from 0.1 to 0.5 shaded; its probability mass is about 0.152. Pale bands carry the slab up to the curve and across to the right panel, where the model density p_theta(x) is drawn sideways. The image of the slab, x from 0.258 to 1.109, is wider and the shaded area there has the same mass but lower height. p_theta has two bumps because f stretches the region around zero.-2-1012-3-2-10123zxx = f(z)zpZ(z)Δz = 0.4pθ(x)Δx ≈ 0.851same probabilitymass, differentwidthmass ≈ 0.152
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)p_Z = \mathcal N(0, 1) and the map of the figure,

f(z)=z+0.8tanh⁡(2z),f′(z)=1+1.6 sech⁡2(2z)>0,\begin{aligned} f(z) &= z + 0.8 \tanh(2z), \\ f'(z) &= 1 + 1.6\, \operatorname{sech}^2(2z) > 0 , \end{aligned}

where the derivative uses ddutanh⁡u=sech⁡2u\tfrac{d}{du}\tanh u = \operatorname{sech}^2 u and the chain rule. Since f′>0f' > 0 everywhere, ff is strictly increasing. The bounded tanh⁡\tanh term also gives f(z)→±∞f(z) \to \pm\infty as z→±∞z \to \pm\infty, so the map is onto R\mathbb 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)p_\theta(x) = p_Z(z)/f'(z) with z=f−1(x)z = f^{-1}(x):

zzx=f(z)x = f(z)f′(z)f'(z)pZ(z)p_Z(z)pθ(x)p_\theta(x)
00002.6002.6000.39890.39890.15340.1534
0.50.51.1091.1091.6721.6720.35210.35210.21060.2106
111.7711.7711.1131.1130.24200.24200.21740.2174
222.7992.7991.0021.0020.05400.05400.05390.0539

Near the origin ff stretches space by a factor of 2.62.6, so the density there falls well below the Gaussian peak; in the tails f′≈1f' \approx 1 and the density hardly changes. One smooth increasing map has turned a single bump into two, with maxima pθ≈0.234p_\theta \approx 0.234 at x≈±1.50x \approx \pm 1.50. In log form, at z=0.5z = 0.5, log⁡pθ(x)=log⁡pZ(z)−log⁡f′(z)=−1.044−0.514=−1.558\log p_\theta(x) = \log p_Z(z) - \log f'(z) = -1.044 - 0.514 = -1.558.

The band z∈[0.1,0.5]z \in [0.1, 0.5] holds probability Φ(0.5)−Φ(0.1)=0.152\Phi(0.5) - \Phi(0.1) = 0.152. Its image x∈[0.258,1.109]x \in [0.258, 1.109] is 2.132.13 times wider, so the average density over it drops by the same factor, from 0.3790.379 to 0.1780.178.

Example: stretching space by a factor of 2#

A linear map x=Jzx = Jz has the same Jacobian JJ everywhere. For J=2IJ = 2I in two dimensions, every direction is stretched twice and det⁡J=4\det J = 4: a unit square becomes a 2×22 \times 2 square, and pθ(x)=pZ(z)/4p_\theta(x) = p_Z(z)/4. As a check, z∼N(0,I)z \sim \mathcal N(0, I) gives x=2z∼N(0,4I)x = 2z \sim \mathcal N(0, 4I), whose density at the origin is 1/(2π⋅4)=0.03981/(2\pi \cdot 4) = 0.0398, a quarter of 1/(2π)1/(2\pi).

For J=diag⁡(2,−2)J = \operatorname{diag}(2, -2) the square is also mirrored and det⁡J=−4\det J = -4. The sign of a determinant records orientation; the change of volume, and with it the change of density, uses only ∣det⁡J∣=4\lvert\det J\rvert = 4. That is why (1) has an absolute value.

Figure

A Jacobian that stretches each direction by a factor of 2

Unit square mapped by two diagonal JacobiansTwo rows. In each row a unit square in latent space Z, with an amber quarter-turn arrow running counterclockwise inside it, is mapped by a matrix J to data space X. In the first row J has diagonal entries 2 and 2; the image is a 2 by 2 square above the axis, det J equals 4, the area is multiplied by 4 and the density divided by 4. In the second row J has diagonal entries 2 and minus 2; the image is a 2 by 2 square below the horizontal axis, the quarter-turn arrow now runs clockwise, det J equals minus 4, but the absolute determinant is still 4 and the area is the same.Zarea 1J =2002det J = 2·2 − 0·0 = 4area 4X|det J| = 4stretch 2 times:area × 4,density ÷ 4Zarea 1J =200−2det J = −4area 4X|det J| = 4orientation flipped,same area × 4,density ÷ 4Unit square mapped by two diagonal JacobiansTwo rows. In each row a unit square in latent space Z, with an amber quarter-turn arrow running counterclockwise inside it, is mapped by a matrix J to data space X. In the first row J has diagonal entries 2 and 2; the image is a 2 by 2 square above the axis, det J equals 4, the area is multiplied by 4 and the density divided by 4. In the second row J has diagonal entries 2 and minus 2; the image is a 2 by 2 square below the horizontal axis, the quarter-turn arrow now runs clockwise, det J equals minus 4, but the absolute determinant is still 4 and the area is the same.Zarea 1J =2002det J = 2·2 − 0·0 = 4area 4X|det J| = 4: stretch 2 timesarea × 4, density ÷ 4Zarea 1J =200−2det J = −4area 4X|det J| = 4: orientation flipped,same area × 4, density ÷ 4
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.

Stacking maps: a normalizing flow#

Name the intermediate points of the chain z0=zz_0 = z and zi=fi(zi−1)z_i = f_i(z_{i-1}) for i=1,…,Ki = 1, \dots, K, so that zK=xz_K = 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:

det⁡Jf(z0)=det⁡(JfK(zK−1)⋯Jf1(z0))=∏i=1Kdet⁡Jfi(zi−1),log⁡pθ(x)=log⁡pZ(z0)−log⁡∣det⁡Jf(z0)∣=log⁡pZ(z0)−∑i=1Klog⁡∣det⁡Jfi(zi−1)∣.(2)\begin{aligned} \det J_f(z_0) &= \det\big(J_{f_K}(z_{K-1}) \cdots J_{f_1}(z_0)\big) \\ &= \prod_{i=1}^{K} \det J_{f_i}(z_{i-1}), \\ \log p_\theta(x) &= \log p_Z(z_0) - \log\big\lvert\det J_f(z_0)\big\rvert \\ &= \log p_Z(z_0) - \sum_{i=1}^{K} \log\big\lvert\det J_{f_i}(z_{i-1})\big\rvert . \end{aligned} \tag{2}

The third line is the logarithm of (1). To evaluate (2) we push xx backwards through the layers, zK→zK−1→⋯→z0z_K \to z_{K-1} \to \dots \to z_0, 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)z \sim \mathcal N(0, I) and compute x=f(z)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).

Maximum likelihood#

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)x^{(1)}, \dots, 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):

L(θ)=−1N∑n=1N[log⁡pZ(z0(n))−∑i=1Klog⁡∣det⁡Jfi(zi−1(n))∣],\begin{aligned} \mathcal L(\theta) = -\frac1N \sum_{n=1}^{N} \Big[ & \log p_Z\big(z_0^{(n)}\big) \\ &- \sum_{i=1}^{K} \log\big\lvert\det J_{f_i}\big(z_{i-1}^{(n)}\big)\big\rvert \Big] , \end{aligned}

where zi(n)z_i^{(n)} are the intermediate points of x(n)x^{(n)}, with zK(n)=x(n)z_K^{(n)} = x^{(n)} and z0(n)=f−1(x(n))z_0^{(n)} = f^{-1}(x^{(n)}).

The two terms pull against each other, as the smallest flow shows. Fit x=az+bx = az + b with a>0a > 0 to one-dimensional data. Then z=(x−b)/az = (x - b)/a, log⁡pZ(z)=−z2/2+const\log p_Z(z) = -z^2/2 + \text{const} and log⁡∣det⁡J∣=log⁡a\log\lvert\det J\rvert = \log a, so

−NL(a,b)=∑n[−(x(n)−b)22a2−log⁡a]+const,∂(−NL)∂a=∑n(x(n)−b)2a3−Na.\begin{aligned} -N \mathcal L(a, b) &= \sum_{n} \Big[-\frac{(x^{(n)} - b)^2}{2a^2} - \log a\Big] + \text{const}, \\ \frac{\partial (-N\mathcal L)}{\partial a} &= \sum_{n} \frac{(x^{(n)} - b)^2}{a^3} - \frac{N}{a} . \end{aligned}

Setting the derivatives to zero gives b=xˉb = \bar x and a2=N−1∑n(x(n)−xˉ)2a^2 = N^{-1}\sum_n(x^{(n)}-\bar x)^2, the maximum-likelihood variance with denominator NN. Without the log-determinant, increasing aa keeps improving the first term towards a finite upper bound, with no finite maximizing scale for nonconstant data: every zz is pushed towards 0, where the Gaussian peaks. The term −log⁡a-\log a charges the model for the volume it squeezes, and so stops it from collapsing all data onto z=0z = 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}dx \in \{0, \dots, 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 σ\sigma with weight 1256\tfrac1{256} on each of the 256 values: the density at every value is at least 1/(256 σ2π)1/(256\,\sigma\sqrt{2\pi}), so the log-likelihood of any pixel data grows like −log⁡σ-\log\sigma as σ→0\sigma \to 0. Flows are therefore trained on dequantized data x~=x+u\tilde x = x + u with u∼U[0,1)du \sim \mathcal U[0, 1)^d. The probability the model gives to the discrete value xx is P(x)=∫[0,1)dpθ(x+u) duP(x) = \int_{[0,1)^d} p_\theta(x + u)\, du, and Jensen’s inequality for the concave logarithm gives

Eu[log⁡pθ(x+u)]≤log⁡P(x):\mathbb E_u\big[\log p_\theta(x + u)\big] \le \log P(x) :

the continuous log-likelihood of dequantized data is a lower bound on the discrete one (Theis, van den Oord and Bethge, 2016, §3.1).

Image likelihoods are reported as bits per dimension, −log⁡2P(x)/d-\log_2 P(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[log⁡2pθ(x+u)]/d-\mathbb E_u[\log_2 p_\theta(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−1x' = \tilde x/127.5 - 1, roughly in [−1,1][-1, 1], the flow models the density of x′x'. The map x~↦x′\tilde x \mapsto x' has the constant Jacobian 1127.5I\tfrac{1}{127.5} I, and (1) relates the two densities:

px~(x~)=px′(x′)⋅127.5−d,−log⁡2px~(x~)d=−log⁡2px′(x′)d+log⁡2127.5.\begin{aligned} p_{\tilde x}(\tilde x) &= p_{x'}(x') \cdot 127.5^{-d}, \\ -\frac{\log_2 p_{\tilde x}(\tilde x)}{d} &= -\frac{\log_2 p_{x'}(x')}{d} + \log_2 127.5 . \end{aligned}

Bits per dimension in pixel units are those in model units plus log⁡2127.5≈6.99\log_2 127.5 \approx 6.99. In general, if one quantization level has width aa after preprocessing, the offset is −log⁡2a-\log_2 a bits per dimension (Kingma and Dhariwal, 2018, eq. 2): log⁡2255≈7.99\log_2 255 \approx 7.99 for x/255x/255 and exactly 8 for x/256x/256. A flow that reports −3.50-3.50 bits per dimension on x′x' (toy numbers) has −3.50+6.99=3.49-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−1x' = x/127.5 - 1 that means adding u/127.5u/127.5, the same as adding uu before rescaling. Noise of width 1 in x′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\mathbb R^d, so RealNVP models the logit of rescaled pixels (Dinh, Sohl-Dickstein and Bengio, 2017, §4.1). In the symmetric form of its reference code,

p=α+(1−2α) x~256,α=0.05,y=log⁡p1−p,\begin{aligned} p &= \alpha + (1 - 2\alpha)\, \frac{\tilde x}{256}, \qquad \alpha = 0.05, \\ y &= \log\frac{p}{1 - p} , \end{aligned}

so p∈[0.05,0.95)p \in [0.05, 0.95) and yy stays within about ±2.94\pm 2.94. The derivative is dy/dx~=(1−2α)/(256 p(1−p))dy/d\tilde x = (1 - 2\alpha)/\big(256\, p(1 - p)\big) per coordinate, so by (1)

−log⁡2px~(x~)=−log⁡2py(y)+∑i=1dlog⁡2256 pi(1−pi)1−2α.\begin{aligned} -\log_2 p_{\tilde x}(\tilde x) &= -\log_2 p_y(y) \\ &\quad + \sum_{i=1}^{d} \log_2 \frac{256\, p_i (1 - p_i)}{1 - 2\alpha} . \end{aligned}

The correction is about 6.156.15 bits for a mid-grey value (x~=128.5\tilde x = 128.5) and 3.803.80 bits for the darkest and brightest ones (x~=0.5\tilde x = 0.5 or 255.5255.5). Flows built for images are in Flow architectures, part F.

How flows compare with GANs and VAEs#

Figure

Three ways to connect data x and latent z

GAN, VAE and flow architectures side by sideThree rows. GAN row: z goes into a widening generator G(z), which outputs a fake sample x prime; x prime and a real sample x both go into a narrowing discriminator D, which outputs 0 or 1. Notes: no log-likelihood, no inference of z. VAE row: x goes into a narrowing encoder q phi of z given x, which outputs a small z; z goes into a widening decoder p theta of x given z, which outputs x prime. Notes: lower bound ELBO, approximate posterior. Flow row: x goes into a rectangular box f inverse of x, data to latent, which outputs z of the same size as x; z goes into a box f of z, latent to data, which returns x exactly. Notes: exact log-likelihood, exact z equals f inverse of x.GANno log-likelihoodno inference of zVAElower bound (ELBO)approximate qφ(z|x)Flowexact log-likelihoodexact z = f⁻¹(x)zG(z)Generatorx′xD(x)Discriminator0/1real orfake?xqφ(z|x)Encoderzpθ(x|z)Decoderx′xf−1(x)data → latentzf(z)latent → dataxdim z= dim xGAN, VAE and flow architectures stackedThe same three diagrams stacked vertically. GAN: z to generator G to fake x prime; x prime and real x into discriminator D, output 0 or 1; no log-likelihood and no inference of z. VAE: x to encoder q phi of z given x to z to decoder p theta of x given z to x prime; lower bound ELBO and approximate posterior. Flow: x to f inverse, data to latent, to z of the same size, to f, latent to data, which returns x exactly; exact log-likelihood and exact z equals f inverse of x.GANno log-likelihood, no inference of zGeneratorDiscriminatorzG(z)x′xD(x)0/1VAElower bound (ELBO), approximate posteriorxqφ(z|x)Encoderzpθ(x|z)Decoderx′Flowexact log-likelihood, exact z = f⁻¹(x)xf−1(x)data → latentzf(z)latent → datax
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.
Log-likelihoodLatent of a given xx
GANnonenone
VAElower bound (ELBO)approximate posterior qϕ(z∣x)q_\phi(z \mid x)
Flowexact, (2)exact and deterministic, z=f−1(x)z = f^{-1}(x)

A GAN defines its distribution only through samples, and nothing guarantees that a real xx 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.

The trick: a triangular Jacobian#

Everything above hinges on log⁡∣det⁡J∣\log\lvert\det J\rvert. For a general d×dd \times d matrix it costs O(d3)O(d^3) by LU factorization, about 23d3\tfrac23 d^3 floating-point operations (what elimination costs). A 32×3232 \times 32 grayscale image already has d=1024d = 1024; at d=1000d = 1000 that is about 6.7⋅1086.7 \cdot 10^8 operations for every example, every layer and every training step. For a general network even forming JJ takes dd 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 a11a_{11} times the determinant of the remaining lower-triangular block; repeating the step leaves the diagonal (properties of the determinant):

det⁡J=∏i=1dJii,log⁡∣det⁡J∣=∑i=1dlog⁡∣Jii∣.\begin{aligned} \det J &= \prod_{i=1}^{d} J_{ii}, \\ \log\lvert\det J\rvert &= \sum_{i=1}^{d} \log\lvert J_{ii}\rvert . \end{aligned}

That costs O(d)O(d), about 10310^3 operations instead of about 10910^9, and needs only the diagonal entries.

Figure

Why a triangular Jacobian is the trick

Lower-triangular matrix and the cost of its determinantA 5 by 5 lower-triangular matrix A: the diagonal entries a11 to a55 are highlighted in amber, the entries below the diagonal are arbitrary, and every entry above the diagonal is 0. Next to it: det A equals the product of the diagonal entries. Two bars on a log scale compare the cost of a determinant for d equal to 1000: about 10 to the 9 operations for a general matrix versus 10 to the 3 for a triangular one.A =a110000a21a22000a31a32a3300a41a42a43a440a51a52a53a54a55det A = a11 · a22 ⋯ a55product of the diagonalcost of det for d = 1000:general d × d: O(d³)10⁹triangular: O(d)10³Lower-triangular matrix and the cost of its determinantA 5 by 5 lower-triangular matrix A: the diagonal entries a11 to a55 are highlighted in amber, the entries below the diagonal are arbitrary, and every entry above the diagonal is 0. Next to it: det A equals the product of the diagonal entries. Two bars on a log scale compare the cost of a determinant for d equal to 1000: about 10 to the 9 operations for a general matrix versus 10 to the 3 for a triangular one.A =a110000a21a22000a31a32a3300a41a42a43a440a51a52a53a54a55det A = a11 · a22 ⋯ a55product of the diagonalcost of det for d = 1000:general d × d: O(d³)10⁹triangular: O(d)10³
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 JfJ_f is lower-triangular everywhere, output ii depends only on inputs 1,…,i1, \dots, 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: z1z_1 from x1x_1, then z2z_2 from x2x_2 and the known z1z_1, and so on. It is a bijection of Rd\mathbb R^d when each of these one-dimensional maps is onto R\mathbb R, as the affine maps zi↦eszi+tz_i \mapsto e^{s} z_i + t of coupling layers are.

How expressive can a flow be?#

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)x_1 \sim \operatorname{Exp}(1) and x2∣x1∼N(x1,1)x_2 \mid x_1 \sim \mathcal N(x_1, 1), and map each coordinate through its conditional distribution function:

u1=F1(x1)=1−e−x1,u2=F2(x2∣x1)=Φ(x2−x1).\begin{aligned} u_1 &= F_1(x_1) = 1 - e^{-x_1}, \\ u_2 &= F_2(x_2 \mid x_1) = \Phi(x_2 - x_1) . \end{aligned}

The map is triangular, because u1u_1 ignores x2x_2. Its diagonal entries are the derivatives of the distribution functions, which are the densities e−x1e^{-x_1} and φ(x2−x1)\varphi(x_2 - x_1). Their product is the joint density by the chain rule of probability. At x=(1,1.5)x = (1, 1.5) the diagonal is 0.3680.368 and 0.3520.352, and the product 0.12950.1295 equals p(x)p(x); the point goes to u=(0.632,0.691)u = (0.632, 0.691). The density of this example is zero for x1<0x_1 < 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(0, \infty) \times \mathbb R, which uu maps onto the open square (0,1)2(0, 1)^2.

The general argument follows the same steps. Write p(x)=∏ip(xi∣x<i)p(x) = \prod_i p(x_i \mid x_{<i}) and define ui=Fi(xi∣x<i)u_i = F_i(x_i \mid x_{<i}), the conditional distribution function. Each FiF_i is strictly increasing in xix_i, because its derivative p(xi∣x<i)p(x_i \mid x_{<i}) is positive, so the map is invertible coordinate by coordinate. Its Jacobian is lower-triangular with det⁡JF=∏ip(xi∣x<i)=p(x)\det J_F = \prod_i p(x_i \mid x_{<i}) = p(x). Formula (1), applied to FF, gives the density of uu:

pU(u)=p(x) ∣det⁡JF(x)∣−1=1,u∈(0,1)d.p_U(u) = p(x)\, \lvert\det J_F(x)\rvert^{-1} = 1, \qquad u \in (0, 1)^d .

So uu is uniform on the unit cube, and F−1F^{-1} turns uniform noise into xx. Applying the standard normal distribution function Φ\Phi to each coordinate of z∼N(0,I)z \sim \mathcal N(0, I) gives uniform noise as well, by the probability integral transform, so f=F−1∘Φf = F^{-1} \circ \Phi is a flow from a Gaussian to pp. Read backwards, F−1F^{-1} is the sampler of an autoregressive model, coordinate after coordinate; the next note builds layers on exactly this structure.

Where it breaks: separated modes#

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)=12N(−4,0.52)+12N(4,0.52)p(x) = \tfrac12 \mathcal N(-4, 0.5^2) + \tfrac12 \mathcal N(4, 0.5^2), and the one-dimensional flow from the previous section, f=F−1∘Φf = F^{-1} \circ \Phi. Its slope follows from the one-dimensional form of (1), f′(z)=pZ(z)/p(x)f'(z) = p_Z(z)/p(x):

Pointzzp(x)p(x)f′(z)f'(z)
centre of a mode, x=−4x = -4−0.674-0.6740.3990.3990.800.80
x=−2x = -2≈0\approx 01.3⋅10−41.3 \cdot 10^{-4}about 3.0⋅1033.0 \cdot 10^{3}
the gap, x=0x = 0001.0⋅10−141.0 \cdot 10^{-14}about 4⋅10134 \cdot 10^{13}

The whole stretch ∣x∣<2\lvert x\rvert < 2 comes from ∣z∣<4⋅10−5\lvert z\rvert < 4 \cdot 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⋅10134 \cdot 10^{13} 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\mathbb R^d applied to a Gaussian gives a density that is positive everywhere: in (1) both pZ(z)p_Z(z) and ∣det⁡Jf(z)∣\lvert\det J_f(z)\rvert 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.

What you should remember#

  • Change of variables: pθ(x)=pZ(z) ∣det⁡Jf(z)∣−1p_\theta(x) = p_Z(z)\, \lvert\det J_f(z)\rvert^{-1} with z=f−1(x)z = f^{-1}(x); stretching volume lowers density.
  • A flow is a chain of diffeomorphisms with dim⁡z=dim⁡x\dim z = \dim x; its log-likelihood is log⁡pZ(z0)−∑ilog⁡∣det⁡Jfi∣\log p_Z(z_0) - \sum_i \log\lvert\det J_{f_i}\rvert, exact.
  • The log-determinant term stops maximum likelihood from collapsing the data onto the centre of the base.
  • A general determinant costs O(d3)O(d^3); a triangular one is the product of its diagonal, O(d)O(d).
  • Conditional distribution functions give a triangular flow to any positive smooth density, but separated modes need huge slopes.
  • On images: dequantize with noise of one level and add −log⁡2a-\log_2 a bits per dimension for a rescaling with level width aa.

Notebook#

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.

Next#

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×11 \times 1 convolutions, then spline couplings and multi-scale flows for images.

References#