Course contents 22 / 33

22 / 33 · Normalizing Flows

Normalizing flows: change of variables

How a chain of invertible maps turns a spherical Gaussian into a model with an exact likelihood, why the Jacobian determinant appears in the change-of-variables formula, and why flows insist on triangular Jacobians.

On this page 9

A GAN produces samples but cannot tell us how likely a given image is. A VAE can, but only through a lower bound. Normalizing flows take a third route (Rezende and Mohamed, 2015; Papamakarios et al., 2021; Kobyzev, Prince and Brubaker, 2021): start from a simple density, push it through an invertible map, and compute the density of the result exactly with the change-of-variables formula. This note builds that formula, stacks it into a flow, compares flows with the other model families, and ends with the trick that makes flows computable: a triangular Jacobian. How to build layers with that property is the subject of the next note, Flow architectures.

Notation. The map ff always goes from the latent space to the data space, f:Z→Xf: \mathcal Z \to \mathcal X, so x=f(z)x = f(z) generates data and z=f−1(x)z = f^{-1}(x) encodes it. pZp_Z is the base (latent) density and pθ(x)p_\theta(x) the model density of the data. For a map gg, Jg(u)=∂g(u)/∂uJ_g(u) = \partial g(u)/\partial u is its Jacobian matrix at the point uu.

The model: invertible maps out of a Gaussian#

Take a continuous random variable zz with a simple density, a spherical Gaussian:

z∼pZ(z)=N(z; 0, I).z \sim p_Z(z) = \mathcal N(z;\, 0,\, I).

“Spherical” means the covariance is a multiple of the identity (here exactly II): the same spread in every direction and spherical contours. The data are produced by a chain of KK maps,

x=fθ(z)=fK∘⋯∘f2∘f1(z),x = f_\theta(z) = f_K \circ \dots \circ f_2 \circ f_1 (z),

and each fif_i is invertible (bijective): every point of the output space is the image of exactly one input point. For the density formula below, each fif_i must also be differentiable with a differentiable inverse (a diffeomorphism). Then the whole chain is invertible too, with f−1=f1−1∘f2−1∘⋯∘fK−1f^{-1} = f_1^{-1} \circ f_2^{-1} \circ \dots \circ f_K^{-1}. A diffeomorphism needs dim⁡z=dim⁡x\dim z = \dim x. The chain rule applied to f−1∘f=idf^{-1}\circ f = \mathrm{id} and f∘f−1=idf\circ f^{-1} = \mathrm{id} gives Jf−1Jf=IJ_{f^{-1}}J_f = I and JfJf−1=IJ_fJ_{f^{-1}} = I, and a product of an m×nm\times n and an n×mn\times m matrix has rank at most min⁡(m,n)\min(m, n), so both identities can hold only when m=nm = n. Unlike in a VAE, the latent vector is therefore 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 the inverse f⁻¹ carries it back (green, right to left). Because every fᵢ in the chain is a bijection, no two points of Z land on the same x and no x is left without a preimage. The X positions are computed from the same invertible 2-D map that is used later to show the Jacobian as local geometry.

Why not just read off the base density?#

We want pθ(x)p_\theta(x). The first guess is to map xx back and read off the base density, pθ(x)=?pZ(f−1(x))p_\theta(x) \overset{?}{=} p_Z(f^{-1}(x)). This is wrong, because the answer depends on how ff behaves: on how much it stretches or squeezes space around each point.

A one-line counterexample: in one dimension let z∼N(0,1)z \sim \mathcal N(0, 1) and x=f(z)=2zx = f(z) = 2z. The naive guess gives pZ(x/2)p_Z(x/2), which integrates to 22 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 naive value is 0.3520.352 and the correct one is 0.1760.176: ff spreads the same probability over twice the length, so the density must halve.

Change of variables#

Let f:Z→Xf: \mathcal Z \to \mathcal X be invertible, differentiable and with a differentiable inverse, and let pZ(z)p_Z(z) be a density defined over z∈Zz \in \mathcal Z.

One dimension. Probability mass is conserved. A small interval of width ∣dz∣|dz| around zz holds mass pZ(z) ∣dz∣p_Z(z)\,|dz|, and ff sends it to an interval of width ∣dx∣|dx| around x=f(z)x = f(z) that must hold the same mass:

pθ(x) ∣dx∣=pZ(z) ∣dz∣,p_\theta(x)\,|dx| = p_Z(z)\,|dz|,

so

pθ(x)=pZ(z)∣dzdx∣=pZ(f−1(x))∣f′(f−1(x))∣.p_\theta(x) = p_Z(z)\left|\frac{dz}{dx}\right| = \frac{p_Z(f^{-1}(x))}{\left|f'(f^{-1}(x))\right|}.

Any dimension. Widths become volumes, and we need the factor by which ff changes a small volume. Close to a point zz the map is approximately linear, f(z+δ)≈f(z)+Jf(z) δf(z + \delta) \approx f(z) + J_f(z)\,\delta, with the Jacobian matrix

Jf(z)=[∂f(1)∂z1⋯∂f(1)∂zd⋮⋱⋮∂f(d)∂z1⋯∂f(d)∂zd],J_f(z) = \begin{bmatrix} \dfrac{\partial f^{(1)}}{\partial z_1} & \cdots & \dfrac{\partial f^{(1)}}{\partial z_d} \\ \vdots & \ddots & \vdots \\ \dfrac{\partial f^{(d)}}{\partial z_1} & \cdots & \dfrac{\partial f^{(d)}}{\partial z_d} \end{bmatrix},

where f(1),…,f(d)f^{(1)},\dots,f^{(d)} are the output coordinates of ff: row kk of JfJ_f holds the partial derivatives of output kk, column jj those with respect to input zjz_j. A tiny cube with side ε\varepsilon at zz, spanned by the vectors εe1,…,εed\varepsilon e_1,\dots,\varepsilon e_d, is therefore sent to a tiny parallelepiped spanned by εJf(z)e1,…,εJf(z)ed\varepsilon J_f(z) e_1, \dots, \varepsilon J_f(z) e_d, that is, by the columns of Jf(z)J_f(z) scaled by ε\varepsilon. The volume of the parallelepiped spanned by the columns of a matrix AA is ∣det⁡A∣\lvert\det A\rvert, so ff multiplies small volumes near zz by ∣det⁡Jf(z)∣\lvert\det J_f(z)\rvert. In two dimensions a small square becomes a small parallelogram whose area is ∣det⁡Jf(z)∣\lvert\det J_f(z)\rvert times the area of the square.

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, matching the absolute Jacobian determinant 0.65 at its centre. The red cell on the right side is stretched to 1.55 times its area, matching 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, matching the absolute Jacobian determinant 0.65 at its centre. The red cell on the right side is stretched to 1.55 times its area, matching the determinant 1.55.ZXfsquashed:|det J| ≈ 0.65stretched:|det J| ≈ 1.55
A square grid in Z pushed through an invertible nonlinear map f. Here f(z) = (z₁ + 0.35·sin(1.2·b), b) with b = z₂·e^(0.35·z₁) + 0.2·z₁, so det J_f(z) = e^(0.35·z₁). Each small cell becomes an almost-parallelogram. Its area is multiplied by |det J_f| at that point: the amber cell (z₁ ≈ −1.25) shrinks to 0.65 of its area (det ≈ 0.65), and the red cell (z₁ ≈ 1.25) grows to 1.55 times its area (det ≈ 1.55).

Mass is conserved as in one dimension: a cube of volume εd\varepsilon^d holds mass pZ(z) εdp_Z(z)\,\varepsilon^d, and its image of volume ∣det⁡Jf(z)∣ εd\lvert\det J_f(z)\rvert\,\varepsilon^d must hold the same mass. Hence, with z=f−1(x)z = f^{-1}(x),

pθ(x)=pZ(f−1(x)) ∣det⁡∂f−1(x)∂x∣=pZ(z) ∣det⁡∂z∂x∣=pZ(z) ∣det⁡∂f(z)∂z∣−1.\begin{aligned} p_\theta(x) &= p_Z\big(f^{-1}(x)\big)\,\left|\det \frac{\partial f^{-1}(x)}{\partial x}\right| \\ &= p_Z(z)\,\left|\det \frac{\partial z}{\partial x}\right| \\ &= p_Z(z)\,\left|\det \frac{\partial f(z)}{\partial z}\right|^{-1}. \end{aligned}

The two forms say the same thing. The Jacobian of the inverse is evaluated at the data point, while the Jacobian of ff is evaluated at the latent point z=f−1(x)z = f^{-1}(x). They are linked by the inverse function theorem, Jf−1(x)=[Jf(z)]−1J_{f^{-1}}(x) = \big[J_f(z)\big]^{-1}, and det⁡(A−1)=1/det⁡A\det(A^{-1}) = 1/\det A. The factor ∣det⁡Jf∣|\det J_f| measures the expansion or contraction of space around the point (Papamakarios et al., 2021, §2.1). Where ff expands space, the same probability is spread thinner and the density drops; where ff contracts space, the density rises:

  • ∣det⁡Jf∣=2|\det J_f| = 2: volumes are doubled and the density is halved;
  • ∣det⁡Jf∣=0.5|\det J_f| = 0.5: volumes are halved and the density is doubled;
  • ∣det⁡Jf∣=1|\det J_f| = 1: volumes are preserved (the shape may still change), and so is the density;
  • det⁡Jf=0\det J_f = 0: the volume is crushed to zero. The linear map Jf(z)J_f(z) is not invertible, and then ff has no differentiable inverse at f(z)f(z), since a differentiable inverse would give Jf−1Jf=IJ_{f^{-1}}J_f = I. The density factor 1/∣det⁡Jf∣1/|\det J_f| is infinite there, and the formula above does not apply. Flow layers are therefore built with det⁡Jf≠0\det J_f \neq 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 areas, and in d dimensions volumes, are multiplied. A shear can change the shape completely and still have det = 1. When det = 0 the square collapses onto a segment: two dimensions are squeezed into one, the linear map cannot be inverted. A layer with det J = 0 at a point has no differentiable inverse there, so it falls outside the change-of-variables formula, which is why flow layers keep det J ≠ 0 everywhere.

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
Base density p_Z = N(0, 1) (bottom), the monotone flow x = f(z) = z + 0.8·tanh(2z) (centre) and the resulting model density p_θ(x) = p_Z(f⁻¹(x)) / f′(f⁻¹(x)) (right, drawn sideways). The slab z ∈ [0.1, 0.5] holds probability 0.152; f stretches it to x ∈ [0.258, 1.109], about 2.13 times wider, so the density there must be lower by the same factor. Near the origin f′(0) = 2.6, which turns the single Gaussian bump into two bumps.

Take pZ=N(0,1)p_Z = \mathcal N(0, 1) and the map in the figure,

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

The derivative is positive everywhere, so ff is strictly increasing and therefore invertible (the inverse has no closed form but is easy to find numerically). Then 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)=pZ(z)/f′(z)p_\theta(x) = p_Z(z)/f'(z)
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 is almost unchanged. The single bump becomes two bumps with maxima at x≈±1.50x \approx \pm 1.50 (that is z≈±0.77z \approx \pm 0.77), pθ≈0.234p_\theta \approx 0.234. Even one smooth invertible map can turn a unimodal base into a bimodal model. 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 slab 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 is x∈[0.258,1.109]x \in [0.258, 1.109], 2.132.13 times wider, so the average density over it drops from 0.3790.379 to 0.1780.178, by the same factor: same probability mass, different width.

Example: stretching space by a factor of 2#

The simplest multivariate case is a linear map x=Jzx = Jz, whose Jacobian ∂x/∂z=J\partial x/\partial z = J is the same everywhere. With

J=[2002]J = \begin{bmatrix} 2 & 0 \\ 0 & 2 \end{bmatrix}

every direction is stretched 2 times, and det⁡J=2⋅2−0⋅0=4\det J = 2\cdot 2 - 0\cdot 0 = 4. A unit square of Z\mathcal Z becomes a 2×22\times 2 square of X\mathcal X, so

pθ(x)=pZ(z)∣1det⁡(∂x∂z)∣=pZ(z)4.p_\theta(x) = p_Z(z)\left|\frac{1}{\det\left(\frac{\partial x}{\partial z}\right)}\right| = \frac{p_Z(z)}{4}.

Check with z∼N(0,I)z \sim \mathcal N(0, I) in two dimensions: x=2z∼N(0,4I)x = 2z \sim \mathcal N(0, 4I), and indeed pθ(0)=12π⋅4=0.0398=14⋅12πp_\theta(0) = \frac{1}{2\pi\cdot 4} = 0.0398 = \frac14\cdot\frac{1}{2\pi}.

Orientation does not matter. For

J=[200−2],det⁡J=−4,J = \begin{bmatrix} 2 & 0 \\ 0 & -2 \end{bmatrix}, \qquad \det J = -4,

the square is also mirrored, but its area is still 44. The sign of the determinant records orientation; the change of volume, and hence of density, uses only ∣det⁡J∣=4|\det J| = 4. That is why the formula 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) sends the unit square of Z to a 2 × 2 square in X. The area grows from 1 to det J = 4, so the same probability is spread over four times the area and the density drops to a quarter: p_θ(x) = p_Z(z) / |det J|. Bottom: J = diag(2, −2) also flips the second axis. The amber quarter-turn marker now runs clockwise, det J = −4, but the area and the density factor depend only on |det J| = 4.

Stacking maps: a normalizing flow#

Now apply the formula to the whole chain z∼pZ(z)z \sim p_Z(z), x=fθ(z)=fK∘⋯∘f2∘f1(z)x = f_\theta(z) = f_K\circ\dots\circ f_2\circ f_1(z). Name the intermediate points

z0=z,zi=fi(zi−1)    (i=1,…,K),z_0 = z, \quad z_i = f_i(z_{i-1}) \;\; (i = 1,\dots,K),

so that zK=xz_K = x. The inverse runs the chain backwards, f−1=f1−1∘⋯∘fK−1f^{-1} = f_1^{-1}\circ\dots\circ f_K^{-1}, and by the chain rule its Jacobian is a product of the layer Jacobians, each taken at its own intermediate point: Jf−1(x)=Jf1−1(z1) Jf2−1(z2)⋯JfK−1(zK)J_{f^{-1}}(x) = J_{f_1^{-1}}(z_1)\,J_{f_2^{-1}}(z_2)\cdots J_{f_K^{-1}}(z_K). Since det⁡(AB)=det⁡A det⁡B\det(AB) = \det A\,\det B,

pθ(x)=pZ(z0) ∣det⁡∂f−1(x)∂x∣=pZ(z0)∏i=1K∣det⁡∂fi−1(zi)∂zi∣=pZ(z0)∏i=1K∣det⁡∂fi(zi−1)∂zi−1∣−1.\begin{aligned} p_\theta(x) &= p_Z(z_0)\,\left|\det\frac{\partial f^{-1}(x)}{\partial x}\right| \\ &= p_Z(z_0)\prod_{i=1}^{K}\left|\det\frac{\partial f_i^{-1}(z_i)}{\partial z_i}\right| \\ &= p_Z(z_0)\prod_{i=1}^{K}\left|\det\frac{\partial f_i(z_{i-1})}{\partial z_{i-1}}\right|^{-1}. \end{aligned}

To evaluate it we push xx backwards through the layers, zK=x→zK−1→⋯→z0z_K = x \to z_{K-1} \to \dots \to z_0, and collect one 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 (approximately, once the model fits) into a sample of the standard normal base. The name was popularized in machine learning by Rezende and Mohamed (2015), building on earlier work on density estimation by transforming data towards a Gaussian (Tabak and Vanden-Eijnden, 2010). Rezende and Mohamed’s flows were planar and radial maps, whose determinants are cheap for a different reason than the triangular layers below (Flow architectures, part G).

Sampling needs only the forward direction: draw z∼N(0,I)z \sim \mathcal N(0, I) and compute x=fθ(z)x = f_\theta(z); evaluating a density needs the inverse. Which of the two is cheap depends on the architecture: masked autoregressive flows (MAF; Papamakarios, Pavlakou and Murray, 2017) evaluate densities fast and sample slowly, inverse autoregressive flows (IAF; Kingma et al., 2016) the reverse, and coupling layers make both cheap (see Flow architectures). Sampling turns a simple zz into a sample of a complicated distribution; the density formula is what lets us fit fθf_\theta so that this distribution matches the data.

Maximum likelihood#

Take the logarithm and the product becomes a sum, with Jfi−1(zi)=∂fi−1(zi)/∂ziJ_{f_i^{-1}}(z_i) = \partial f_i^{-1}(z_i)/\partial z_i:

log⁡pθ(x)=log⁡pZ(z0)+∑i=1Klog⁡∣det⁡Jfi−1(zi)∣.\begin{aligned} \log p_\theta(x) &= \log p_Z(z_0) \\ &\quad + \sum_{i=1}^{K}\log\big|\det J_{f_i^{-1}}(z_i)\big| . \end{aligned}

This is an exact log-likelihood evaluation, with no bound and no sampling. Training is plain maximum likelihood, which minimizes the forward KL divergence from the data distribution to the model (why cross-entropy is the loss we minimize). As in the fitting note, the data density is unknown, so we minimize the negative log-likelihood over the dataset x(1),…,x(N)x^{(1)},\dots,x^{(N)}, now with a neural model:

L(θ)=−1N∑n=1N[log⁡pZ(z0(n))+∑i=1Klog⁡∣det⁡∂fi−1(zi(n))∂zi(n)∣],\begin{aligned} \mathcal L(\theta) &= -\frac1N\sum_{n=1}^{N}\Bigg[\log p_Z\big(z_0^{(n)}\big) \\ &\qquad + \sum_{i=1}^{K}\log\left|\det\frac{\partial f_i^{-1}(z_i^{(n)})}{\partial z_i^{(n)}}\right|\Bigg], \end{aligned}

where zi(n)z_i^{(n)} are the intermediate points of x(n)x^{(n)}: zK(n)=x(n)z_K^{(n)} = x^{(n)} and zi−1(n)=fi−1(zi(n))z_{i-1}^{(n)} = f_i^{-1}(z_i^{(n)}), so that z0(n)=fθ−1(x(n))z_0^{(n)} = f_\theta^{-1}(x^{(n)}).

The two terms pull against each other. The first wants every encoded point near the centre of the Gaussian. The second penalizes the inverse for squeezing space, so the model cannot score well by collapsing all the data to z=0z = 0.

Images: dequantization, rescaling and bits per dimension#

Optional depth: the preprocessing that turns a flow’s density on images into a reported number of bits per dimension, with a worked offset check. The rest of the note does not depend on it.

The formula gives a density, so it is exact for continuous data. Images are discrete, for example 8-bit pixel values x∈{0,…,255}dx \in \{0,\dots,255\}^d, and a continuous density could put arbitrarily high values on those points: a flow fitted to the raw values can push its likelihood up without bound by squeezing its mass onto them. Flows are therefore trained on dequantized data x~=x+u\tilde x = x + u with uniform noise 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 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 the dequantized data is a lower bound on the discrete log-likelihood (Theis, van den Oord and Bethge, 2016).

Bits per dimension. Image likelihoods are reported as −log⁡2P(x)/d-\log_2 P(x)/d, the number of bits per coordinate that a lossless code built from the model needs (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\big[\log_2 p_\theta(x + u)\big]/d, which by the inequality above is an upper bound on the discrete value.

Rescaling changes the density. Networks are rarely fed pixel values in [0,256)[0, 256). A common choice is x′=x~/127.5−1x' = \tilde x/127.5 - 1, which puts the data roughly in [−1,1][-1, 1]. The flow then models the density of x′x', and the change of variables relates it to the density of x~\tilde x: the map x~↦x′\tilde x\mapsto x' has the constant Jacobian 1127.5I\tfrac{1}{127.5}I, so

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

The 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, §2, eq. 2): log⁡2255≈7.99\log_2 255\approx 7.99 for x/255x/255, as produced by common image loaders, and exactly 8 for x/256x/256. For example (toy numbers), a flow that reports −3.50-3.50 bits/dim on x′x' has −3.50+6.99=3.49-3.50 + 6.99 = 3.49 bits/dim in pixel units. A negative value in model units is normal, because a density on a narrow range can exceed 1; only the pixel-unit number can be compared with published results such as the likelihood table of the autoregressive note.

The noise must live in the same units. Dequantization noise has to span exactly one level of whatever the network sees. With x′=x/127.5−1x' = x/127.5 - 1 that means adding u/127.5u/127.5 with u∼U[0,1)du\sim\mathcal U[0,1)^d, which is 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. NICE, for instance, dequantizes CIFAR-10 with uniform noise of width 1128\tfrac{1}{128} on data rescaled to [−1,1][-1, 1], where one level is 2256=1128\tfrac{2}{256} = \tfrac{1}{128} wide (Dinh, Krueger and Bengio, 2015, §5.1).

The logit transform. Pixel values are bounded, while a Gaussian base lives on all of Rd\mathbb R^d. To reduce boundary effects, RealNVP models the logit of the rescaled pixels (Dinh, Sohl-Dickstein and Bengio, 2017, §4.1):

y=logit⁡(p)=log⁡p1−p,p=α+(1−2α) x~256,α=0.05.\begin{gathered} y = \operatorname{logit}(p) = \log\frac{p}{1 - p}, \\[4pt] p = \alpha + (1 - 2\alpha)\,\frac{\tilde x}{256}, \qquad \alpha = 0.05 . \end{gathered}

The shift α\alpha keeps pp inside [0.05,0.95)[0.05, 0.95), so yy stays within about ±2.94\pm2.94 instead of running to ±∞\pm\infty at black and white pixels. This is the form of the reference implementation; the paper prints 1−α1 - \alpha in place of 1−2α1 - 2\alpha. The derivative of the transform 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

−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}

Unlike a linear rescaling, the correction depends on the pixel: 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 values (x~=0.5\tilde x = 0.5 or 255.5255.5). RealNVP includes this term in its bits per dimension. The Glow paper states that it follows RealNVP’s preprocessing (§5); its reference code instead rescales to [−12,12)[-\tfrac12, \tfrac12), adds noise of width 1256\tfrac{1}{256} and adds the constant −dlog⁡256-d\log 256 to the log-likelihood, which is the linear case above with a=1256a = \tfrac{1}{256}. Flows built for images are the subject of Flow architectures, part F.

Recap: GANs, VAEs and flows#

Figure

Recap: 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 z to a sample x′ and a discriminator only labels inputs as real or fake, so there is neither a likelihood nor a way back from x to z. VAE: a stochastic encoder q_φ(z|x) and decoder p_θ(x|z) give an approximate posterior and a lower bound (ELBO) on log p(x). Flow: a single invertible map; f⁻¹ takes x to z exactly and f takes z back to x, so z has the same dimension as x and the log-likelihood is exact. Arrows follow the note's convention f: z → x.
  • GAN (Goodfellow et al., 2014; see the GAN note). There is no log-likelihood evaluation: the generator defines its distribution only through samples. There is also no latent-variable inference: nothing maps xx back to zz, and nothing guarantees that the generator covers the full support of the data, so a real xx may have no latent code at all.
  • VAE (Kingma and Welling, 2014; see the VAE note). It optimizes a lower bound on the log-likelihood (the ELBO) and infers latents through an approximate posterior qϕ(z∣x)q_\phi(z\mid x).
  • Flow-based generative models, for example NICE (Dinh, Krueger and Bengio, 2015) and RealNVP (Dinh, Sohl-Dickstein and Bengio, 2017). They minimize the exact negative log-likelihood, and posterior inference is exact: z=f−1(x)z = f^{-1}(x), a deterministic answer.
  • Diffusion models complete the list; they come later in the course and, like VAEs, derive their training objective from a bound on the likelihood.
Log-likelihoodLatent inference
GANnonenone
VAElower bound (ELBO)approximate, qϕ(z∣x)q_\phi(z\mid x)
Flowexactexact, z=f−1(x)z = f^{-1}(x)

The trick: a triangular Jacobian#

Everything above hinges on ∣det⁡J∣|\det J|: if it can be computed, the density is exact; if it cannot be computed cheaply, the likelihood is impractical to evaluate and to train on at the scale of images. For a general network it is expensive. Computing the determinant of a general d×dd\times d matrix costs O(d3)O(d^3) with Gaussian elimination or an LU decomposition (Golub and Van Loan, 2013); naive cofactor expansion is even worse, O(d!)O(d!). Take d=1000d = 1000 (a 32×3232\times 32 grayscale image already has d=1024d = 1024): that is on the order of 10910^9 operations (about 23d3≈6.7×108\tfrac23 d^3 \approx 6.7\times 10^8 for LU) for every example, every layer and every training step. For a general network even forming JJ takes dd backward passes, one per row.

The trick that makes flows practical is to ensure the Jacobian is triangular. For a (lower-)triangular matrix, expanding the determinant along the first row and repeating on the remaining block leaves only the diagonal:

A=[a110⋯0a21a22⋱⋮⋮⋮⋱0an1an2⋯ann]⟹det⁡A=a11 a22⋯ann.\begin{gathered} A = \begin{bmatrix} a_{11} & 0 & \cdots & 0 \\ a_{21} & a_{22} & \ddots & \vdots \\ \vdots & \vdots & \ddots & 0 \\ a_{n1} & a_{n2} & \cdots & a_{nn} \end{bmatrix} \\ \Longrightarrow\quad \det A = a_{11}\, a_{22} \cdots a_{nn}. \end{gathered}

So if JJ is triangular,

det⁡J=∏i=1dJii,log⁡∣det⁡J∣=∑i=1dlog⁡∣Jii∣,\begin{gathered} \det J = \prod_{i=1}^{d} J_{ii}, \\ \log|\det J| = \sum_{i=1}^{d} \log|J_{ii}|, \end{gathered}

which costs O(d)O(d): about 10310^3 operations instead of about 10910^9, and only the diagonal entries are needed.

A triangular JJ is also invertible exactly when every diagonal entry is non-zero, which is easy to guarantee by construction. For the map itself the condition does more. If JfJ_f is lower-triangular everywhere, output ii depends only on inputs 1,…,i1,\dots,i. If each diagonal entry is continuous and non-zero everywhere, it keeps one sign, so each output is strictly monotone in its own input. The map is then injective and can 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 for the affine maps zi↦eszi+tz_i \mapsto e^{s}z_i + t of coupling layers.

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³
If every entry above the diagonal is zero, the determinant is the product of the diagonal entries, so log|det A| = Σ log|aᵢᵢ|. For d = 1000, a general determinant (LU decomposition) costs on the order of d³ = 10⁹ operations, for every example and every layer, whereas the triangular one needs d = 10³ multiplications. Bars are on a log₁₀ scale.

Notebook#

The normalizing-flows notebook of the HSE-LAMBDA Deep Generative Models repository (pinned commit; cell numbers count every cell, markdown included, from 1) builds on Andrej Karpathy’s pytorch-normalizing-flows library (Karpathy, 2019), included as nflib. The notebook has no saved outputs, so it documents procedures rather than results.

  • Cell 2 writes the change of variables from the generative side, log⁡p(zK)=log⁡p(z0)−∑ilog⁡∣det⁡∂fi/∂zi−1∣\log p(z_K) = \log p(z_0) - \sum_i \log\lvert\det \partial f_i/\partial z_{i-1}\rvert.
  • Cells 4–5 define three 2-D toy datasets: two moons (the one used), a mixture of four Gaussians with standard deviation 0.50.5, and the SIGGRAPH point set, which needs a siggraph.pkl file that is not included in the repository.
  • Cell 7 builds the model: a logistic prior, a uniform pushed through an inverse sigmoid, with log⁡pZ(z)=∑i[−log⁡(1+ezi)−log⁡(1+e−zi)]\log p_Z(z) = \sum_i\big[-\log(1 + e^{z_i}) - \log(1 + e^{-z_i})\big] (the Gaussian prior is commented out). NICE uses the same prior and prefers it for its better-behaved gradients (Dinh, Krueger and Bengio, 2015, §3.4). The change-of-variables formula holds for any base density, so only log⁡pZ\log p_Z changes. The flow is three blocks of ActNorm, an invertible 1×11\times1 “convolution” and a neural-spline coupling layer (8 spline bins, tail bound 3, hidden width 16), described in Flow architectures.
  • Cells 9–11 train with Adam (learning rate 10−410^{-4}, weight decay 10−510^{-5}) on the loss above: zs, prior_logprob, log_det = model(x_batch), logprob = prior_logprob + log_det, loss = -torch.sum(logprob), for 1000 iterations, each on a fresh batch of 128 samples. The loss is summed over the batch rather than averaged as in L(θ)\mathcal L(\theta), which only rescales the gradient. nflib names the directions the other way round from this note: its forward runs data → latent (our f−1f^{-1}) and accumulates our ∑ilog⁡∣det⁡∂fi−1/∂zi∣\sum_i \log\lvert\det \partial f_i^{-1}/\partial z_i\rvert, while model.sample draws from the prior and runs inverse (our ff).
  • Cells 13–17 map data to latents and prior samples to data, and show how a grid is warped layer by layer. Cell 13 draws its prior points with model.prior.sample([128, 2]); the prior already has two coordinates, so this returns a 128×2×2128\times2\times2 tensor and the scatter plot shows 256 prior points instead of 128, which is harmless (sample((128,)) gives the intended shape). Cell 17 runs one more training step and draws the grid warp once: its 500-step loop breaks at k=0k = 0.
  • Cell 19 colours a grid by prior_logprob.exp(), that is pZ(f−1(x))p_Z(f^{-1}(x)) without the log-determinant. This is exactly the naive formula from the start of this note; the model density is (prior_logprob + log_det).exp().

Next#

Flows need layers that are expressive and still have a cheap Jacobian determinant by construction. Flow architectures builds them: coupling layers (NICE, RealNVP), masked autoregressive layers (MAF, IAF) and Glow’s invertible 1×11\times1 convolutions, then spline couplings, ActNorm and multi-scale flows for images, and finally the planar and radial flows of Rezende and Mohamed.

References#