Course contents 23 / 34

23 / 34 · Normalizing Flows

Flow architectures

Layers that are invertible and have a cheap Jacobian determinant: coupling and autoregressive layers, Glow's invertible 1×1 convolutions, spline couplings, multi-scale flows for images, and conditional flows inside a VAE.

On this page 10

A 64×6464 \times 64 colour image has d=64⋅64⋅3=12288d = 64 \cdot 64 \cdot 3 = 12288 coordinates. A flow on such images needs, for every layer and every training example, the log-determinant of a 12288×1228812288 \times 12288 Jacobian. By elimination that costs about 23d3≈1.2⋅1012\tfrac23 d^3 \approx 1.2 \cdot 10^{12} operations. The previous note found the way out: a triangular Jacobian. How do we build such layers and still let arbitrary networks do the heavy lifting inside them?

One layer maps z∈Rdz \in \mathbb R^d to z′∈Rdz' \in \mathbb R^d, with Jacobian entries Jij=∂zi′/∂zjJ_{ij} = \partial z'_i/\partial z_j. Subscripts index coordinates, z<i=(z1,…,zi−1)z_{<i} = (z_1, \dots, z_{i-1}), and ⊙\odot is the element-wise product. The inverse layer has the reciprocal determinant, so a cheap determinant is cheap in both directions.

A. Coupling layers (NICE, RealNVP)#

Split the input into two parts, z=(za,zb)z = (z_a, z_b) with za∈Rkz_a \in \mathbb R^k and zb∈Rd−kz_b \in \mathbb R^{d-k}, and define

za′=za,zb′=zb⊙exp⁡(s(za))+t(za),\begin{aligned} z'_a &= z_a, \\ z'_b &= z_b \odot \exp\big(s(z_a)\big) + t(z_a), \end{aligned}

where s,t:Rk→Rd−ks, t: \mathbb R^k \to \mathbb R^{d-k} are arbitrary neural networks, the scale and translation networks. This is an affine coupling layer (Dinh, Sohl-Dickstein and Bengio, 2017).

Figure

An affine coupling layer and its inverse

Coupling layer block diagram, forward and inverseTop panel, forward pass: the input vector z is split into z_a and z_b. z_a passes straight through to the output as z prime a, and also feeds two network boxes s and t. z_b is multiplied element-wise by exp of s, then t is added, giving z prime b. The output halves are concatenated into z prime. Bottom panel, inverse pass, drawn with arrows reversed: z prime a is copied back to z_a, the same networks s and t read it, t is subtracted from z prime b and the result is multiplied by exp of minus s, giving z_b.⊙+zazbz′az′bzz′Forward pass: z → z′identity: z′a = zas(·)t(·)exp(s)tzb ⊙ exp(s(za))+ t(za)s(·), t(·): arbitrary neural networks of za−⊙zazbz′az′bzz′Inverse pass: z′ → zidentity: za = z′as(·)t(·)exp(−s)tz′b − t(za)⊙ exp(−s(za))same s and t, re-evaluated on za: no network is ever invertedCoupling layer block diagram, forward and inverse (stacked)Forward pass, top to bottom: z splits into z_a and z_b. z_a goes straight down to z prime a and feeds networks s and t. z_b is multiplied by exp of s and shifted by t, giving z prime b. Inverse pass, bottom to top: z prime b minus t, times exp of minus s, gives z_b, while z prime a is copied back to z_a.⊙+Forward: z → z′zazbz′az′bz′a = zas(·)t(·)exp(s)ts, t: arbitrary neural networks of za⊙−Inverse: z′ → zzazbz′az′bza = z′as(·)t(·)exp(−s)tsame s and t; no network is inverted
The first half is copied unchanged and fed to the networks s and t. The second half is multiplied element-wise by exp(s) and shifted by t. The inverse undoes only this element-wise step, evaluating s and t again on the same first half.

Each block of the Jacobian follows from the definition. The first part is copied, so its block is the identity and it does not depend on zbz_b. Coordinate ii of zb′z'_b involves only coordinate ii of zbz_b, and ss, tt do not read zbz_b at all, so the derivative with respect to zb,jz_{b,j} is esi(za)e^{s_i(z_a)} when j=ij = i and zero otherwise:

∂za′∂za=Ik,∂za′∂zb=0,∂zb,i′∂zb,j=δij esi(za),∂zb′∂za=a dense block.\begin{aligned} \frac{\partial z'_a}{\partial z_a} &= I_k, \\ \frac{\partial z'_a}{\partial z_b} &= 0, \\ \frac{\partial z'_{b,i}}{\partial z_{b,j}} &= \delta_{ij}\, e^{s_i(z_a)}, \\ \frac{\partial z'_b}{\partial z_a} &= \text{a dense block} . \end{aligned}

Here δij\delta_{ij} is 1 for i=ji = j and 0 otherwise. The dense block holds the derivatives of ss and tt, and it sits below the diagonal:

J=[Ik0∂zb′∂zadiag⁡(es(za))].J = \begin{bmatrix} I_k & 0 \\[2pt] \dfrac{\partial z'_b}{\partial z_a} & \operatorname{diag}\big(e^{s(z_a)}\big) \end{bmatrix} .

Every entry above the diagonal is zero, so JJ is lower-triangular and its determinant is the product of its diagonal: kk ones, then the scales.

det⁡J=1k⋅∏i=1d−kesi(za)=exp⁡(∑i=1d−ksi(za)),log⁡∣det⁡J∣=∑i=1d−ksi(za).\begin{aligned} \det J &= 1^k \cdot \prod_{i=1}^{d-k} e^{s_i(z_a)} \\ &= \exp\Big(\sum_{i=1}^{d-k} s_i(z_a)\Big), \\ \log\lvert\det J\rvert &= \sum_{i=1}^{d-k} s_i(z_a) . \end{aligned}

The determinant is positive, and the dense block never enters it, so ss and tt can be as deep as we like. With d=6d = 6 split 3+33 + 3 and s(za)=(0.2,−0.5,0.1)s(z_a) = (0.2, -0.5, 0.1) at some point, log⁡∣det⁡J∣=−0.2\log\lvert\det J\rvert = -0.2 and det⁡J=e−0.2≈0.819\det J = e^{-0.2} \approx 0.819: near that point the layer shrinks small volumes by about 18%, whatever the dense block contains.

Figure

Why the coupling Jacobian is lower-triangular

Block structure of the coupling-layer JacobianA six by six matrix with rows z prime a, z prime b and columns z_a, z_b, split three and three. Top-left block: identity, ones on the diagonal. Top-right block: hatched zeros, because z prime a does not depend on z_b. Bottom-left block: dense, filled with stars, the derivative of z prime b with respect to z_a. Bottom-right block: diagonal with entries e to the s1, e to the s2, e to the s3. Everything above the main diagonal is hatched. The determinant is the product of exp of s_i, which equals exp of the sum of s_i.Jij = ∂z′i / ∂zjzazbz′az′b101001∗∗∗es1∗∗∗0es2∗∗∗00es30identity blockz′a = zazero block:z′a does notdepend on zbdiagonal block:z′b depends on zbelement-wise, affinely∂z′b / ∂za: denses, t see all of zadet J = ∏ᵢ exp(si(za))= exp(Σᵢ si(za))Block structure of the coupling-layer Jacobian (compact)The same six by six Jacobian: identity block top-left, hatched zero block top-right, dense block bottom-left, diagonal block with e to the s_i bottom-right. A legend below explains each block, and the determinant equals the product of exp of s_i.Jij = ∂z′i / ∂zjzazbz′az′b101001∗∗∗es1∗∗∗0es2∗∗∗00es301identity: z′a = zazero: z′a ignores zbdense ∂z′b/∂za: s, t see all of zadiagonal: element-wise in zbdet J = ∏ᵢ exp(si) = exp(Σᵢ si)
Jacobian of a coupling layer with d = 6 split 3 + 3; entry (i, j) is the derivative of output i with respect to input j. Everything above the diagonal (hatched) is zero, so the determinant is the product of the diagonal: three ones and exp(sᵢ). The dense block never enters it.

The inverse reverses only the element-wise step. Since za′=zaz'_a = z_a, the networks can be evaluated again on the same input:

za=za′,zb=(zb′−t(za′))⊙exp⁡(−s(za′)).\begin{aligned} z_a &= z'_a, \\ z_b &= \big(z'_b - t(z'_a)\big) \odot \exp\big(-s(z'_a)\big) . \end{aligned}

Neither ss nor tt is ever inverted, so the layer is invertible for any networks, and both directions cost one pass.

NICE (Dinh, Krueger and Bengio, 2015) uses the additive coupling zb′=zb+t(za)z'_b = z_b + t(z_a), the case s≡0s \equiv 0 with det⁡J=1\det J = 1, and ends with a diagonal scaling layer that can change volume. Since zaz_a passes through unchanged, consecutive layers swap the halves or permute the coordinates; Glow generalizes the permutation to a learned invertible channel mixture (part C).

B. Autoregressive layers (MAF, IAF)#

An autoregressive model with Gaussian conditionals is already a flow (Papamakarios, Pavlakou and Murray, 2017, §3.1). In this part a layer connects a data-side vector xx to a base-side vector uu. Let

p(x)=∏i=1dN(xi; μi(x<i), e2αi(x<i)),p(x) = \prod_{i=1}^{d} \mathcal N\big(x_i;\, \mu_i(x_{<i}),\, e^{2\alpha_i(x_{<i})}\big) ,

where μi\mu_i and αi\alpha_i (a log standard deviation) are any functions of the earlier coordinates. Sampling draws u∼N(0,I)u \sim \mathcal N(0, I) and computes xi=uieαi+μix_i = u_i e^{\alpha_i} + \mu_i one coordinate after another. Solving for uu gives the inverse map, whose Jacobian is triangular because uiu_i depends on x1,…,xix_1, \dots, x_i only:

ui=(xi−μi(x<i)) e−αi(x<i),∂ui∂xi=e−αi(x<i),log⁡∣det⁡∂u∂x∣=−∑i=1dαi(x<i).\begin{aligned} u_i &= \big(x_i - \mu_i(x_{<i})\big)\, e^{-\alpha_i(x_{<i})}, \\ \frac{\partial u_i}{\partial x_i} &= e^{-\alpha_i(x_{<i})}, \\ \log\Big\lvert\det \frac{\partial u}{\partial x}\Big\rvert &= -\sum_{i=1}^{d} \alpha_i(x_{<i}) . \end{aligned}

The change of variables, log⁡p(x)=log⁡pU(u)+log⁡∣det⁡∂u/∂x∣\log p(x) = \log p_U(u) + \log\lvert\det \partial u/\partial x\rvert, gives back ∑i[log⁡φ(ui)−αi]=∑ilog⁡N(xi;μi,e2αi)\sum_i \big[\log\varphi(u_i) - \alpha_i\big] = \sum_i \log \mathcal N(x_i; \mu_i, e^{2\alpha_i}), the likelihood of the autoregressive model, as it should.

A masked autoregressive flow (MAF) stacks such layers, reordering the coordinates between them. Its μi\mu_i and αi\alpha_i read data-side coordinates, all known when we evaluate a density, so one network pass gives them all; sampling needs x1x_1 before μ2(x1)\mu_2(x_1), so it takes dd sequential passes.

An inverse autoregressive flow (IAF; Kingma et al., 2016) lets the shift and scale read the base side, xi=uieαi(u<i)+μi(u<i)x_i = u_i e^{\alpha_i(u_{<i})} + \mu_i(u_{<i}): sampling takes one pass and the density of a given xx takes dd. IAF still scores its own samples in one pass, because their uu is known, which is all variational inference needs.

A coupling layer is the special case in which μi=αi=0\mu_i = \alpha_i = 0 for i≤ki \le k and every later μi\mu_i, αi\alpha_i reads only x1,…,xkx_1, \dots, x_k (Papamakarios, Pavlakou and Murray, 2017, §3.3). Both directions then take one pass, at the price of changing only part of the coordinates per layer.

Masking: one network for all conditionals#

In the layer notation of part A, with zz on the data side, the density direction of MAF reads zi′=ziesi(z<i)+ti(z<i)z'_i = z_i e^{s_i(z_{<i})} + t_i(z_{<i}), with si=−αis_i = -\alpha_i and ti=−μie−αit_i = -\mu_i e^{-\alpha_i}. MAF computes all (si,ti)(s_i, t_i) with one network, MADE, whose weights are masked so that output ii never sees inputs i,…,di, \dots, d (Germain et al., 2015). Every unit gets a degree m(⋅)m(\cdot): input jj and output ii have degrees jj and ii, and each hidden unit uu gets m(u)∈{1,…,d−1}m(u) \in \{1, \dots, d - 1\}, the number of leading inputs it may depend on. A hidden unit reads units of degree at most its own; an output reads only hidden units of strictly smaller degree:

Muj=1[m(j)≤m(u)]hidden,Miuout=1[m(u)<i]output,h=(W⊙M) z+b.\begin{aligned} M_{uj} &= \mathbf 1\big[m(j) \le m(u)\big] && \text{hidden}, \\ M^{\text{out}}_{iu} &= \mathbf 1\big[m(u) < i\big] && \text{output}, \\ h &= (W \odot M)\, z + b . \end{aligned}

With d=3d = 3, four hidden units of degrees (1,2,1,2)(1, 2, 1, 2), and rows as receivers,

M(1)=[100110100110],M(2)=[000010101111],M(2)M(1)=[000200420].\begin{aligned} M^{(1)} &= \begin{bmatrix} 1&0&0\\ 1&1&0\\ 1&0&0\\ 1&1&0 \end{bmatrix}, \\ M^{(2)} &= \begin{bmatrix} 0&0&0&0\\ 1&0&1&0\\ 1&1&1&1 \end{bmatrix}, \\ M^{(2)} M^{(1)} &= \begin{bmatrix} 0&0&0\\ 2&0&0\\ 4&2&0 \end{bmatrix} . \end{aligned}

Entry (i,j)(i, j) of the product counts the paths from input jj to output ii. It is strictly lower-triangular, and a nonlinearity cannot create a path that the masks removed, so sis_i and tit_i depend on z<iz_{<i} only; output 1 receives nothing and is a learned constant.

Figure

Masked weights make the network autoregressive

MADE masks and the resulting Jacobian patternA masked network with inputs z1, z2, z3 of degrees 1, 2, 3, four hidden units of degrees 1, 2, 1, 2, and three outputs (s1, t1), (s2, t2), (s3, t3) of degrees 1, 2, 3. Hidden units of degree 1 read only z1; hidden units of degree 2 read z1 and z2; z3 feeds nothing. Output 1 has no incoming connections, output 2 reads the degree-1 hidden units, output 3 reads all hidden units. On the right, the three by three Jacobian of z prime with respect to z: diagonal entries e to the s_i, entries below the diagonal potentially non-zero, entries above the diagonal hatched zeros.inputshidden (degree m)outputsz1m = 1z2m = 2z3m = 31212s1, t1m = 1s2, t2m = 2s3, t3m = 3constantunusedm(j) ≤ m(u)m(u) < ihidden maskoutput mask (strict)z′i = zi esi + tielement-wiseJ = ∂z′ / ∂zz1z2z3z′1z′2z′3es1∗es2∗∗es3lower-triangularMADE masks and the resulting Jacobian pattern (stacked)The same masked network drawn top to bottom: inputs z1, z2, z3, four hidden units with degrees 1, 2, 1, 2, and outputs (s1, t1), (s2, t2), (s3, t3). Below it, the element-wise step z prime i equals z_i times e to the s_i plus t_i, and the resulting lower-triangular three by three Jacobian.inputshiddenoutputsm(j) ≤ m(u)m(u) < iz1m = 1z2m = 2z3m = 31212s1, t1m = 1s2, t2m = 2s3, t3m = 3constantunusedz′i = zi esi + tiJ = ∂z′ / ∂zz1z2z3z′1z′2z′3es1∗es2∗∗es3lower-triangular
Input j has degree j and hidden units have degrees from 1 to d − 1 = 2; hidden unit u reads input j only if m(j) ≤ m(u), and output i reads unit u only if m(u) < i. Only surviving connections are drawn: sᵢ and tᵢ depend on z₁, …, zᵢ₋₁ only, and the Jacobian is lower-triangular.

Where one layer breaks#

One affine autoregressive layer can only produce Gaussian conditionals: given x<ix_{<i}, xix_i is an affine function of the Gaussian uiu_i. Take a toy target shaped like an X: x1∼N(0,1)x_1 \sim \mathcal N(0, 1) and x2=±x1+0.1 εx_2 = \pm x_1 + 0.1\,\varepsilon with a random sign and ε∼N(0,1)\varepsilon \sim \mathcal N(0, 1). With unlimited data, maximum likelihood picks the Gaussian with the conditional mean mm and variance VV of x2x_2 given x1x_1 (steps below). The random sign makes m=0m = 0, and V=E[x22∣x1]=x12+0.01V = \mathbb E[x_2^2 \mid x_1] = x_1^2 + 0.01, so μ2(x1)=0\mu_2(x_1) = 0 and e2α2(x1)=x12+0.01e^{2\alpha_2(x_1)} = x_1^2 + 0.01. At x1=2x_1 = 2 the model puts its peak at x2=0x_2 = 0, with density 0.1990.199, where the data have essentially none (5.5⋅10−875.5 \cdot 10^{-87}); at the data point x2=2x_2 = 2 it gives 0.1210.121 against the true 1.991.99.

Derivation

With unlimited data, maximum likelihood minimizes the expected negative log-density under the true conditional. Splitting E[(x2−μ)2∣x1]\mathbb E[(x_2 - \mu)^2 \mid x_1] into variance plus squared bias gives

E[−log⁡N(x2;μ,σ2)∣x1]=12log⁡(2πσ2)+V+(m−μ)22σ2.\begin{aligned} \mathbb E\big[-\log \mathcal N(x_2; \mu, \sigma^2) \mid x_1\big] ={}& \tfrac12 \log (2\pi\sigma^2) \\ &+ \frac{V + (m - \mu)^2}{2\sigma^2} . \end{aligned}

Setting the derivatives in μ\mu and σ2\sigma^2 to zero gives μ=m\mu = m and σ2=V\sigma^2 = V.

Stacking layers with intervening permutations removes the single-layer Gaussian-conditional restriction: each layer models the transformed variables of the previous one. The five-layer result in Papamakarios, Pavlakou and Murray (2017), Fig. 1, uses a different, banana-shaped target; it is not a training result for our X-shaped example. Another approach is a more flexible element-wise map, part D.

C. Invertible convolutions (Glow)#

The permutation between couplings is a linear map with a fixed matrix; Glow replaces it with a learned invertible linear map (Kingma and Dhariwal, 2018, §3.2). On an image tensor of height hh, width ww and CC channels, a 1×11 \times 1 convolution applies the same C×CC \times C matrix WW to the channel vector of every pixel.

Ordered pixel by pixel, the Jacobian is block-diagonal with hwhw copies of WW, since each output pixel reads only its own input pixel. It is the product of hwhw matrices that each apply WW to one pixel and leave the rest alone, each with determinant det⁡W\det W, so

log⁡∣det⁡J∣=h⋅w⋅log⁡∣det⁡W∣.\log\lvert\det J\rvert = h \cdot w \cdot \log\lvert\det W\rvert .

A general det⁡W\det W costs O(C3)O(C^3). Glow stores WW in factored form,

W=P L (U+diag⁡(s)),W = P\, L\, \big(U + \operatorname{diag}(s)\big),

where PP is a fixed permutation matrix, LL is lower-triangular with ones on its diagonal, UU is strictly upper-triangular and s∈RCs \in \mathbb R^C. The determinant of a product is the product of determinants; a permutation matrix has determinant ±1\pm 1, since each row swap flips the sign; a triangular matrix has the product of its diagonal (properties of the determinant). So

det⁡W=det⁡P⋅det⁡L⋅det⁡(U+diag⁡(s))=(±1)⋅1⋅∏c=1Csc,log⁡∣det⁡W∣=∑c=1Clog⁡∣sc∣.\begin{aligned} \det W &= \det P \cdot \det L \cdot \det\big(U + \operatorname{diag}(s)\big) \\ &= (\pm 1) \cdot 1 \cdot \prod_{c=1}^{C} s_c, \\ \log\lvert\det W\rvert &= \sum_{c=1}^{C} \log\lvert s_c\rvert . \end{aligned}

That costs O(C)O(C). Applying W−1=(U+diag⁡(s))−1L−1P⊤W^{-1} = (U + \operatorname{diag}(s))^{-1} L^{-1} P^\top to one vector takes a permutation and two triangular solves, O(C2)O(C^2); constructing the full inverse is generally O(C3)O(C^3). Allowing the permutation to vary, this factorization covers every invertible matrix: elimination with row exchanges gives P′W=LU′P' W = L U' (row exchanges and pivoting), so W=P′⊤LU′W = P'^\top L U', and U′U' splits into its strictly upper part and its diagonal. Glow draws a random orthogonal matrix, factors it once, then keeps PP fixed and trains LL, UU and ss. That fixed choice of PP covers only its factorization chart, not every invertible matrix.

Figure

Glow's invertible 1×1 convolution

A one by one convolution as a per-pixel matrix product W = LULeft: a feature map drawn as a box of height h, width w and depth C, with one pixel highlighted through all channels. An arrow takes that pixel's channel vector z, of length C, into a box labelled W = P L U with P = I, containing a lower-triangular matrix L with ones on the diagonal and an upper-triangular matrix U with its diagonal highlighted. The output vector z prime goes back to the same pixel. Below: det L = 1, det U = product of U_ii, and log absolute det W = sum of log absolute U_ii; applied at all h times w pixels the layer log-determinant is h times w times that sum.h × wCone pixel, all channels:z ∈ ℝCzW = P L U (here P = I)LU1111·z′ = W zback tosame pixeldet L = 1det U = ∏ Uiilog |det W| = Σᵢ log |Uii|same W at all h·w positions, so the layer’s log|det J| is h·w · log|det W|A one by one convolution as a per-pixel matrix product (stacked)A feature map with one highlighted pixel; its channel vector z goes down into a box W = P L U (P = I) with a unit lower-triangular L and an upper-triangular U, and comes out as z prime. Below: log absolute det W equals the sum of log absolute U_ii.h × wCz ∈ ℝCW = P L U (P = I)LU1111·z′ = W zdet L = 1, det U = ∏ Uiilog |det W| = Σᵢ log |Uii|
At every pixel the vector of C channel values is multiplied by the same learned C × C matrix W = P L (U + diag s), drawn for C = 4 and P = I. L has ones on its diagonal. The right factor, labelled U in the drawing, is U + diag s of the text: the strictly upper-triangular part U and the highlighted diagonal s. So log|det W| = Σ log|s_c|; the layer's log-determinant is h·w times that.

A worked example with C=3C = 3 and P=IP = I:

L=[1000.510−121],U+diag⁡(s)=[21−10−0.53001.5],W=[21−1102.5−2−28.5].\begin{aligned} L &= \begin{bmatrix} 1&0&0\\ 0.5&1&0\\ -1&2&1 \end{bmatrix}, \\ U + \operatorname{diag}(s) &= \begin{bmatrix} 2&1&-1\\ 0&-0.5&3\\ 0&0&1.5 \end{bmatrix}, \\ W &= \begin{bmatrix} 2&1&-1\\ 1&0&2.5\\ -2&-2&8.5 \end{bmatrix} . \end{aligned}

Expanding det⁡W\det W directly gives −1.5=2⋅(−0.5)⋅1.5-1.5 = 2 \cdot (-0.5) \cdot 1.5, so log⁡∣det⁡W∣=log⁡1.5≈0.405\log\lvert\det W\rvert = \log 1.5 \approx 0.405. The negative entry s2=−0.5s_2 = -0.5 shows why the absolute value is needed.

A free scs_c can cross zero, where WW is singular; learning log⁡∣sc∣\log\lvert s_c\rvert with fixed signs rules this out. Some such restriction is unavoidable: det⁡\det is continuous in the entries, so by the intermediate value theorem every path from det⁡>0\det > 0 to det⁡<0\det < 0 meets a singular matrix, and an always-invertible parametrization over a connected space such as Rn\mathbb R^n fixes the sign of det⁡W\det W (Papamakarios et al., 2021, §3.2).

D. Spline couplings: neural spline flows#

Optional depth: a more flexible element-wise map. The rest of the note does not depend on it.

An affine map shifts and stretches a conditional distribution but keeps a unimodal one unimodal. The triangular argument needs only a strictly increasing, differentiable map gθg_\theta with a computable inverse; the diagonal entry of JJ becomes gθ′(zb,i)g_\theta'(z_{b,i}), with θ=NN(za)\theta = \mathrm{NN}(z_a).

Neural spline flows use a monotone rational-quadratic spline (Durkan et al., 2019, §3.1), after Gregory and Delbourgo (1982). The scalar map is the identity outside [−B,B][-B, B]; inside, KK bins are fixed by K+1K + 1 increasing knots (xk,yk)(x_k, y_k) from (−B,−B)(-B, -B) to (B,B)(B, B) and positive slopes δk\delta_k at the knots, with δ0=δK=1\delta_0 = \delta_K = 1 to match the tails. In bin kk, with chord slope sks_k and position ξ\xi,

sk=yk+1−ykxk+1−xk,ξ=x−xkxk+1−xk∈[0,1],g(x)=yk+(yk+1−yk)[skξ2+δkξ(1−ξ)]sk+(δk+1+δk−2sk) ξ(1−ξ).\begin{aligned} s_k &= \frac{y_{k+1} - y_k}{x_{k+1} - x_k}, \\ \xi &= \frac{x - x_k}{x_{k+1} - x_k} \in [0, 1], \\ g(x) &= y_k + \frac{(y_{k+1} - y_k)\big[s_k \xi^2 + \delta_k \xi(1 - \xi)\big]}{s_k + (\delta_{k+1} + \delta_k - 2 s_k)\, \xi (1 - \xi)} . \end{aligned}

At ξ=0\xi = 0 it gives yky_k; at ξ=1\xi = 1 the ratio of the quadratic parts is sk/sk=1s_k/s_k = 1, so the full increment is yk+1−yky_{k+1}-y_k and the result is yk+1y_{k+1}. The denominator equals sk(ξ2+(1−ξ)2)+(δk+δk+1)ξ(1−ξ)>0s_k(\xi^2 + (1 - \xi)^2) + (\delta_k + \delta_{k+1})\xi(1 - \xi) > 0. Differentiating the quotient gives

g′(x)=sk2[δk+1ξ2+2skξ(1−ξ)+δk(1−ξ)2][sk+(δk+1+δk−2sk) ξ(1−ξ)]2,g'(x) = \frac{s_k^2 \big[\delta_{k+1} \xi^2 + 2 s_k \xi (1 - \xi) + \delta_k (1 - \xi)^2\big]}{\big[s_k + (\delta_{k+1} + \delta_k - 2 s_k)\, \xi (1 - \xi)\big]^2} ,
Derivation

Write Δy=yk+1−yk\Delta y = y_{k+1} - y_k, Δx=xk+1−xk\Delta x = x_{k+1} - x_k, w=ξ(1−ξ)w = \xi(1 - \xi) and c=δk+1+δk−2skc = \delta_{k+1} + \delta_k - 2 s_k. Then g=yk+Δy N/Dg = y_k + \Delta y\, N/D with N=skξ2+δkwN = s_k \xi^2 + \delta_k w and D=sk+c wD = s_k + c\, w. Since dξ/dx=1/Δxd\xi/dx = 1/\Delta x and Δy/Δx=sk\Delta y/\Delta x = s_k, the chain rule and the quotient rule give, with primes for d/dξd/d\xi,

g′(x)=sk N′D−ND′D2.g'(x) = s_k\, \frac{N' D - N D'}{D^2} .

Here w′=1−2ξw' = 1 - 2\xi, N′=2skξ+δkw′N' = 2 s_k \xi + \delta_k w' and D′=c w′D' = c\, w'. Multiplying out, the two terms δkc ww′\delta_k c\, w w' cancel:

N′D−ND′=2sk2ξ+skδkw′+skc (2ξw−ξ2w′)=sk(2skξ+δk(1−2ξ)+c ξ2),\begin{aligned} N' D - N D' &= 2 s_k^2 \xi + s_k \delta_k w' + s_k c\,(2\xi w - \xi^2 w') \\ &= s_k\big(2 s_k \xi + \delta_k (1 - 2\xi) + c\, \xi^2\big) , \end{aligned}

because 2ξw−ξ2w′=2ξ2(1−ξ)−ξ2(1−2ξ)=ξ22\xi w - \xi^2 w' = 2\xi^2(1 - \xi) - \xi^2(1 - 2\xi) = \xi^2. Substituting cc and collecting powers of ξ\xi turns the bracket into δk+1ξ2+2skξ(1−ξ)+δk(1−ξ)2\delta_{k+1}\xi^2 + 2 s_k \xi(1 - \xi) + \delta_k(1 - \xi)^2, which gives the formula above.

The numerator terms are nonnegative, with at least one strictly positive at every point, so gg increases. At the ends of the bin g′g' equals δk\delta_k and δk+1\delta_{k+1}, so neighbouring pieces meet with the same slope. For each transformed coordinate the network outputs 3K−13K - 1 numbers: KK widths and KK heights, each passed through a softmax and multiplied by 2B2B, and K−1K - 1 inner derivatives passed through a softplus.

The inverse needs no iteration. Since gg increases, the bin of an output yy is found by comparing yy with the yky_k. Setting g(x)=yg(x) = y and multiplying out the fraction gives a quadratic aξ2+bξ+c=0a\xi^2 + b\xi + c = 0 with

a=(yk+1−yk)(sk−δk)+(y−yk)(δk+1+δk−2sk),b=(yk+1−yk) δk−(y−yk)(δk+1+δk−2sk),c=−sk(y−yk),\begin{aligned} a &= (y_{k+1} - y_k)(s_k - \delta_k) + (y - y_k)(\delta_{k+1} + \delta_k - 2 s_k), \\ b &= (y_{k+1} - y_k)\, \delta_k - (y - y_k)(\delta_{k+1} + \delta_k - 2 s_k), \\ c &= -s_k (y - y_k), \end{aligned}

whose root in [0,1][0, 1] is ξ=2c/(−b−b2−4ac)\xi = 2c/\big(-b - \sqrt{b^2 - 4ac}\big), the usual formula rewritten to avoid cancellation (Durkan et al., 2019, App. A).

Figure

A monotone rational-quadratic spline and its derivative

A monotone rational-quadratic spline and its derivativeLeft: an increasing curve through five knots, marked by dots, inside a dashed square from −3 to 3; the box of each bin is shaded behind its piece. Outside the square the curve continues as the diagonal y = x. Right: the derivative of the same function, positive everywhere, peaking near 4.25 in the second bin and equal to 1 at the edges and in the tails. The point x = −0.6 is marked on both plots: g = −1.025, g′ = 4.04.spline g(x)x−333−3x = −0.6g = −1.025identity tailknot (0, 1.2)K = 4 binsderivative g′(x)01234x−303g′ = 4.04δ = 1 at the edgesδk at the knotsA monotone rational-quadratic spline and its derivativeLeft: an increasing curve through five knots, marked by dots, inside a dashed square from −3 to 3; the box of each bin is shaded behind its piece. Outside the square the curve continues as the diagonal y = x. Right: the derivative of the same function, positive everywhere, peaking near 4.25 in the second bin and equal to 1 at the edges and in the tails. The point x = −0.6 is marked on both plots: g = −1.025, g′ = 4.04.spline g(x)x−333−3x = −0.6g = −1.025identity tailknot (0, 1.2)K = 4 binsderivative g′(x)01234x−303g′ = 4.04δ = 1 at the edges
A toy spline with K = 4 bins on [−3, 3]: knots (−3, −3), (−1.2, −2.4), (0, 1.2), (1.5, 2.2), (3, 3), inner derivatives δ = (0.4, 2.5, 0.5) and δ = 1 at the edges. Left: each piece joins opposite corners of its bin's box; outside [−3, 3] the map is the identity. Right: g′(x). The point x = −0.6 maps to g = −1.025, g′ = 4.04.

In the toy spline of the figure, x=−0.6x = -0.6 lies in bin k=1k = 1 with ξ=0.5\xi = 0.5:

QuantityValue
bin width, height, chord slope s1s_11.21.2, 3.63.6, 33
knot derivatives δ1\delta_1, δ2\delta_20.40.4, 2.52.5
g(−0.6)g(-0.6)−2.4+3.06/2.225≈−1.025-2.4 + 3.06/2.225 \approx -1.025
g′(−0.6)g'(-0.6), its log4.044.04, 1.401.40
inverse: aa, bb, cc at y=−1.0247y = -1.02475.0975.097, 5.7035.703, −4.126-4.126
recovered ξ\xi and xx0.5000.500, −0.6-0.6

This coordinate adds 1.401.40 to log⁡∣det⁡J∣\log\lvert\det J\rvert. Durkan et al. use B=3B = 3 and default to K=8K = 8, with exceptions noted for specific experiments (§5).

E. ActNorm: per-channel scale and shift with data-dependent initialization#

A normalization layer in a flow must be invertible with a known determinant. Batch normalization adds noise through its batch statistics, more so as the batch per device shrinks, and Glow trains on large images with one image per device (Kingma and Dhariwal, 2018, §3.1). Its ActNorm keeps an affine map per channel cc, with a log-scale γc\gamma_c and a shift τc\tau_c that do not depend on the batch:

zpqc′=eγczpqc+τc,z'_{pqc} = e^{\gamma_c} z_{pqc} + \tau_c ,

where p,qp, q index the pixel. The Jacobian is diagonal, with eγce^{\gamma_c} repeated at the hwhw pixels of channel cc, so log⁡∣det⁡J∣=hw∑cγc\log\lvert\det J\rvert = hw \sum_c \gamma_c.

The parameters are initialized from the first minibatch so that each output channel has zero mean and unit variance on it, γc=−log⁡std⁡c(z)\gamma_c = -\log \operatorname{std}_c(z) and τc=−mean⁡c(eγcz)\tau_c = -\operatorname{mean}_c(e^{\gamma_c} z); afterwards they are ordinary trainable parameters. These formulas assume positive channel standard deviations; a constant channel needs a positive numerical floor rather than division by zero. One step of Glow is ActNorm, a 1×11 \times 1 convolution and an affine coupling layer whose last convolution starts at zero, so that the coupling starts as the identity (§3.3).

F. Flows on images: squeeze, masks and multi-scale#

Convolutional networks for ss and tt need a split into zaz_a and zbz_b that respects the pixel grid.

Masks on the pixel grid#

RealNVP writes the coupling with a binary mask bb of the same shape as the image tensor (Dinh, Sohl-Dickstein and Bengio, 2017, §3.4):

z′=b⊙z+(1−b)⊙(z⊙es(b⊙z)+t(b⊙z)),log⁡∣det⁡J∣=∑(1−b)⊙s(b⊙z),\begin{aligned} z' &= b \odot z + (1 - b) \odot \Big(z \odot e^{s(b \odot z)} + t(b \odot z)\Big), \\ \log\lvert\det J\rvert &= \textstyle\sum (1 - b) \odot s(b \odot z), \end{aligned}

with the sum over all entries. Entries with b=1b = 1 play the role of zaz_a. A checkerboard mask sets b=1b = 1 where the row and column indices sum to an odd number, so the four neighbours of every transformed pixel condition it; a channel-wise mask sets b=1b = 1 on half of the channels. Consecutive layers alternate bb and 1−b1 - b.

Squeeze: trading space for channels#

The squeeze cuts each channel into 2×22 \times 2 squares and stacks the four values of a square as four channels, turning h×w×Ch \times w \times C into h2×w2×4C\tfrac h2 \times \tfrac w2 \times 4C (§3.6). With output channel 4c+2p+q4c + 2p + q holding offset (p,q)(p, q) of channel cc, a 4×4×14 \times 4 \times 1 input becomes

[12345678910111213141516]⟶[13911],[241012],[571315],[681416].\begin{bmatrix} 1&2&3&4\\ 5&6&7&8\\ 9&10&11&12\\ 13&14&15&16 \end{bmatrix} \longrightarrow \begin{bmatrix} 1&3\\ 9&11 \end{bmatrix}, \begin{bmatrix} 2&4\\ 10&12 \end{bmatrix}, \begin{bmatrix} 5&7\\ 13&15 \end{bmatrix}, \begin{bmatrix} 6&8\\ 14&16 \end{bmatrix} .

Squeezing only reorders coordinates, so its log-determinant is 0.

Factoring out half the variables at each scale#

RealNVP’s block for one scale is three checkerboard couplings, a squeeze and three channel-wise couplings (§3.6). After each block, half of the variables are factored out into the latent zz, and only the other half continues. With Φ(i)\Phi^{(i)} the block of scale ii and h(0)=xh^{(0)} = x, in the data-to-latent direction,

(z(i),h(i))=Φ(i)(h(i−1)),i<L,z(L)=Φ(L)(h(L−1)),z=(z(1),…,z(L)).\begin{aligned} \big(z^{(i)}, h^{(i)}\big) &= \Phi^{(i)}\big(h^{(i-1)}\big), \quad i < L, \\ z^{(L)} &= \Phi^{(L)}\big(h^{(L-1)}\big), \\ z &= \big(z^{(1)}, \dots, z^{(L)}\big) . \end{aligned}

The last scale has four checkerboard couplings and no squeeze, and the recursion stops at a 4×4×C4 \times 4 \times C input (§4.1). For a 64×64×364 \times 64 \times 3 image:

ScaleInputAfter squeezeFactored outContinues
164×64×364 \times 64 \times 332×32×1232 \times 32 \times 12614432×32×632 \times 32 \times 6
232×32×632 \times 32 \times 616×16×2416 \times 16 \times 24307216×16×1216 \times 16 \times 12
316×16×1216 \times 16 \times 128×8×488 \times 8 \times 4815368×8×248 \times 8 \times 24
48×8×248 \times 8 \times 244×4×964 \times 4 \times 967684×4×484 \times 4 \times 48
54×4×484 \times 4 \times 48none768

The factored-out parts add up to 12288=d12288 = d: the latent keeps every dimension, but the 28 couplings process 6(1+12+14+18)+4⋅116=11.56(1 + \tfrac12 + \tfrac14 + \tfrac18) + 4 \cdot \tfrac1{16} = 11.5 images’ worth of variables, about 41% of 28 full-size couplings. Glow keeps this skeleton, couples only along channels and puts its 1×11 \times 1 convolutions in place of fixed permutations (Kingma and Dhariwal, 2018, §3).

Interpolating and encoding with the exact inverse#

A flow has an exact encoder: each image xx has exactly one latent z=f−1(x)z = f^{-1}(x).

To interpolate, encode two images and decode points on a path between z1z_1 and z2z_2. The straight line leaves the region where the base puts its mass: ∥z∥\lVert z\rVert concentrates near d\sqrt d with a spread of about 0.710.71 (the Gaussian shell), while the midpoint of two independent draws has variance 12\tfrac12 per coordinate and length near d/2\sqrt{d/2}, 78.478.4 instead of 110.9110.9 for d=12288d = 12288. Weights whose squares sum to one, such as cos⁡π4 z1+sin⁡π4 z2\cos\tfrac\pi4\, z_1 + \sin\tfrac\pi4\, z_2, keep the length near d\sqrt d.

Glow samples at a reduced temperature, multiplying the base standard deviation by T=0.7T = 0.7 (§6). For a volume-preserving flow the determinant is constant, so pθ(x)∝exp⁡(−∥f−1(x)∥2/2)p_\theta(x) \propto \exp(-\lVert f^{-1}(x)\rVert^2/2), and the tempered base gives exp⁡(−∥f−1(x)∥2/(2T2))∝pθ(x)1/T2\exp(-\lVert f^{-1}(x)\rVert^2/(2T^2)) \propto p_\theta(x)^{1/T^2}, a sharpened model; the paper writes the exponent as T2T^2.

An exact likelihood does not tell whether an outside image looks like the training data: the evaluated flow, VAE and PixelCNN models trained on CIFAR-10 give higher likelihood to unseen SVHN house numbers (Nalisnick et al., 2019).

Conditional flows inside a VAE#

A flow can be conditioned on a vector cc that it does not transform: the networks inside read cc as an extra input, as in s(za,c)s(z_a, c), t(za,c)t(z_a, c) or μi(x<i,c)\mu_i(x_{<i}, c) (Papamakarios, Pavlakou and Murray, 2017, §3.4). The Jacobian is taken in the transformed variable at fixed cc, so it stays triangular with the same log-determinant. A conditional flow is thus an exact density p(x∣c)p(x \mid c), and inside a VAE it can replace any of the three Gaussians.

As the approximate posterior q(z∣x)q(z \mid x), an IAF reads a context vector from the encoder and subtracts each step’s log-determinant from log⁡q\log q (Kingma et al., 2016, Algorithm 1). As the prior p(z)p(z), MAF’s density direction scores the encoder’s codes in one pass. Changing the variable of the ELBO from zz to the flow’s base variable shows that such a prior is equivalent to an IAF posterior followed by a deeper decoder (Chen et al., 2017, §3.2).

Derivation

Let ϵ=h(z)\epsilon = h(z) be the autoregressive map of the prior, from code to base, so that by the change of variables p(z)=N(h(z);0,I) ∣det⁡Jh(z)∣p(z) = \mathcal N(h(z); 0, I)\, \lvert\det J_h(z)\rvert. Let q~(ϵ∣x)\tilde q(\epsilon \mid x) be the density of ϵ=h(z)\epsilon = h(z) when z∼q(z∣x)z \sim q(z \mid x); by the same formula q~(ϵ∣x)=q(z∣x) ∣det⁡Jh(z)∣−1\tilde q(\epsilon \mid x) = q(z \mid x)\, \lvert\det J_h(z)\rvert^{-1}. In the difference of logarithms the determinant cancels:

log⁡p(z)−log⁡q(z∣x)=log⁡N(ϵ;0,I)+log⁡∣det⁡Jh(z)∣−log⁡q~(ϵ∣x)−log⁡∣det⁡Jh(z)∣=log⁡N(ϵ;0,I)−log⁡q~(ϵ∣x).\begin{aligned} \log p(z) - \log q(z \mid x) &= \log \mathcal N(\epsilon; 0, I) + \log\lvert\det J_h(z)\rvert \\ &\quad - \log \tilde q(\epsilon \mid x) - \log\lvert\det J_h(z)\rvert \\ &= \log \mathcal N(\epsilon; 0, I) - \log \tilde q(\epsilon \mid x) . \end{aligned}

An average over z∼qz \sim q of a function of h(z)h(z) is an average over ϵ∼q~\epsilon \sim \tilde q, and z=h−1(ϵ)z = h^{-1}(\epsilon), so

ELBO=Eq~(ϵ∣x)[log⁡p(x∣h−1(ϵ))+log⁡N(ϵ;0,I)−log⁡q~(ϵ∣x)].\begin{aligned} \text{ELBO} = \mathbb E_{\tilde q(\epsilon \mid x)}\Big[ & \log p\big(x \mid h^{-1}(\epsilon)\big) \\ &+ \log \mathcal N(\epsilon; 0, I) - \log \tilde q(\epsilon \mid x)\Big] . \end{aligned}

This is the ELBO of a VAE with a standard normal prior on ϵ\epsilon, the posterior q~\tilde q and the decoder p(x∣h−1(ϵ))p(x \mid h^{-1}(\epsilon)). Coordinate ii of h(z)h(z) is (zi−μi(z<i)) e−αi(z<i)(z_i - \mu_i(z_{<i}))\, e^{-\alpha_i(z_{<i})}, an affine function of ziz_i with coefficients read from z<iz_{<i}: the form of an IAF step. So q~\tilde q is qq followed by an IAF, and h−1h^{-1} has moved into the decoder.

As the likelihood p(x∣z)p(x \mid z), a conditional flow replaces the pixel-wise Gaussian decoder. VAPNEV (Agrawal and Dukkipati, 2016) maps an image xx to a vector y=gz(x)y = g_z(x) of the same size by RealNVP coupling layers whose networks also read zz, and puts a Gaussian with decoder-predicted parameters on yy. By the change of variables,

log⁡p(x∣z)=log⁡N(gz(x); μ(z),diag⁡σ2(z))+log⁡∣det⁡Jgz(x)∣,\begin{aligned} \log p(x \mid z) ={}& \log \mathcal N\big(g_z(x);\, \mu(z), \operatorname{diag} \sigma^2(z)\big) \\ &+ \log\big\lvert\det J_{g_z}(x)\big\rvert , \end{aligned}

which enters the ELBO in place of the squared reconstruction error. It is an exact density of the whole image given the code, so it can model dependencies between pixels as far as the couplings can express them, while the pixel-wise Gaussian makes them independent. To sample, draw zz from the prior, yy from N(μ(z),diag⁡σ2(z))\mathcal N(\mu(z), \operatorname{diag}\sigma^2(z)), and compute x=gz−1(y)x = g_z^{-1}(y).

G. Planar and radial flows: cheap determinants without triangles#

Optional depth: the older rank-one route to a cheap determinant. The rest of the note does not depend on it.

The planar construction of Rezende and Mohamed (2015) has a Jacobian equal to the identity plus a rank-one matrix. Its radial counterpart uses a scalar multiple of the identity plus a rank-one matrix. For a,c∈Rda, c \in \mathbb R^d, I+ac⊤I + a c^\top leaves every vector orthogonal to cc unchanged, so d−1d - 1 eigenvalues equal 1; the trace d+c⊤ad + c^\top a fixes the last one, and the product of the eigenvalues gives the matrix determinant lemma:

det⁡(I+ac⊤)=1+c⊤a.\det\big(I + a c^\top\big) = 1 + c^\top a .

A planar flow with u,w∈Rdu, w \in \mathbb R^d and a scalar bb moves zz along uu by an amount that depends on its signed distance from the hyperplane w⊤z+b=0w^\top z + b = 0:

f(z)=z+utanh⁡(w⊤z+b),J=I+tanh⁡′(w⊤z+b) uw⊤,det⁡J=1+tanh⁡′(w⊤z+b) w⊤u.\begin{aligned} f(z) &= z + u \tanh(w^\top z + b), \\ J &= I + \tanh'(w^\top z + b)\, u w^\top, \\ \det J &= 1 + \tanh'(w^\top z + b)\, w^\top u . \end{aligned}

Taking w⊤w^\top of y=f(z)y = f(z) reduces invertibility to one dimension. With η=w⊤z\eta = w^\top z, w⊤y=η+w⊤utanh⁡(η+b)=g(η)w^\top y = \eta + w^\top u \tanh(\eta + b) = g(\eta), and once η\eta is known, z=y−utanh⁡(η+b)z = y - u\tanh(\eta + b). Since 0<tanh⁡′≤10 < \tanh' \le 1, g′(η)≥1+min⁡(w⊤u,0)g'(\eta) \ge 1 + \min(w^\top u, 0), so for w⊤u>−1w^\top u > -1 the function gg is strictly increasing; g(η)−ηg(\eta) - \eta is bounded, so gg is also onto R\mathbb R, and ff is a bijection with det⁡J>0\det J > 0 (Rezende and Mohamed, 2015, App. A.1). The inverse still needs a scalar root search per layer. Below the bound the map can fold: g(η)=η−2tanh⁡ηg(\eta) = \eta - 2\tanh\eta (w⊤u=−2w^\top u = -2, b=0b = 0) vanishes at 00 and ±1.915\pm 1.915.

A radial flow f(z)=z+β(z−z0)/(α+r)f(z) = z + \beta (z - z_0)/(\alpha + r), with r=∥z−z0∥r = \lVert z - z_0\rVert and α>0\alpha > 0, moves the distance from z0z_0 to ρ(r)=r(1+β/(α+r))\rho(r) = r\big(1 + \beta/(\alpha + r)\big), and det⁡J=(ρ/r)d−1ρ′(r)\det J = (\rho/r)^{d-1} \rho'(r), positive for β>−α\beta > -\alpha (steps below; App. A.2). At r=0r=0, use the continuous limit ρ/r=1+β/α\rho/r=1+\beta/\alpha. Unlike the planar case, the radial inverse is analytic: for output radius ρ\rho, solve r2+(α+β−ρ)r−αρ=0r^2+(\alpha+\beta-\rho)r-\alpha\rho=0 for its nonnegative root, then recover z=z0+(r/ρ)(y−z0)z=z_0+(r/\rho)(y-z_0). When ρ=0\rho=0, simply return z0z_0. Both families can enrich a variational posterior; the radial layer also permits a direct inverse.

Derivation

Write h(r)=β/(α+r)h(r) = \beta/(\alpha + r), so that f(z)=z+h(r)(z−z0)f(z) = z + h(r)(z - z_0). Since ∇r=(z−z0)/r\nabla r = (z - z_0)/r, the product rule gives the Jacobian, whose eigenvectors are the unit radial vector e=(z−z0)/re = (z - z_0)/r and every vv orthogonal to it:

J=(1+h) I+h′(r)r (z−z0)(z−z0)⊤,Jv=(1+h) v=ρ(r)r v,Je=(1+h+rh′) e=ρ′(r) e.\begin{aligned} J &= (1 + h)\, I + \frac{h'(r)}{r}\, (z - z_0)(z - z_0)^\top , \\ J v &= (1 + h)\, v = \frac{\rho(r)}{r}\, v , \\ J e &= (1 + h + r h')\, e = \rho'(r)\, e . \end{aligned}

The last line uses ρ=r(1+h)\rho = r(1 + h), so ρ′=1+h+rh′\rho' = 1 + h + r h', which with h′=−β/(α+r)2h' = -\beta/(\alpha + r)^2 equals 1+αβ/(α+r)21 + \alpha\beta/(\alpha + r)^2. So the d−1d - 1 orthogonal directions are stretched by ρ(r)/r\rho(r)/r, the radial one by ρ′(r)\rho'(r), and det⁡J=(ρ/r)d−1ρ′\det J = (\rho/r)^{d-1} \rho'. For β>−α\beta > -\alpha both factors are positive at every r≥0r \ge 0: 1+h>1−α/(α+r)≥01 + h > 1 - \alpha/(\alpha + r) \ge 0, and ρ′(r)≥min⁡(1, 1+β/α)>0\rho'(r) \ge \min(1,\, 1 + \beta/\alpha) > 0 (App. A.2).

Two later routes avoid triangles too: residual flows z+F(z)z + F(z) with a contraction FF (Murphy, 2023, §23.2.5), and continuous-time flows dz/dt=F(z,t)dz/dt = F(z, t), whose log-determinant changes at the rate tr⁡JF\operatorname{tr} J_F (Grathwohl et al., 2019); the continuous-time diffusion note builds on this view.

Choosing a layer#

Pushing a grid through a layer shows where it stretches and squeezes space; ∣det⁡J∣\lvert\det J\rvert is the local factor.

Figure

The Jacobian measures how a layer warps space

A square grid before and after one coupling layerLeft: a square grid in the z plane with one highlighted cell. Right: the same grid after the coupling layer. Vertical lines remain vertical, horizontal lines become wavy curves whose spacing grows to the right, where exp(s) exceeds 1, and shrinks to the left. The highlighted cell becomes a taller curved quadrilateral with 1.37 times the original area.before: zafter: z′ = f(z)z1z2z′1z′2coupling layerz′2 = z2 es(z1) + t(z1)area × 1.37vertical lines stay put; each strip is stretched by exp(s(z₁)) and shifted by t(z₁)A square grid before and after one coupling layer (stacked)Top: a square grid with one highlighted cell. Bottom: the grid after the coupling layer, vertical lines unchanged and horizontal lines bent and stretched; the highlighted cell has 1.37 times its original area.before: zz1z2coupling layerz′2 = z2 es(z1) + t(z1)z′1z′2after: z′ = f(z)area× 1.37vertical lines stay put; strips arestretched by exp(s(z₁)), shifted by t(z₁)
One 2-D affine coupling layer applied to a square grid, with s(z₁) = 0.5 tanh z₁ and t(z₁) = 0.5 sin 1.5z₁. Vertical lines stay put because z′₁ = z₁; each vertical strip is stretched by exp(s(z₁)) and shifted by t(z₁). The highlighted cell grows by a factor 1.37, the average of |det J| over its strip.
LayerWhy det⁡J\det J is cheaplog⁡∣det⁡J∣\log\lvert\det J\rvertFast directions
Affine couplingtriangular, copied half∑isi(za)\sum_i s_i(z_a)both
MAFtriangular, masks−∑iαi(x<i)-\sum_i \alpha_i(x_{<i}), data to basedensity
IAFtriangular, masks∑iαi(u<i)\sum_i \alpha_i(u_{<i}), base to datasampling
Spline couplingtriangular, monotone pieces∑ilog⁡g′(zb,i)\sum_i \log g'(z_{b,i})both
1×11 \times 1 convolutionW=PL(U+diag⁡(s))W = PL(U + \operatorname{diag}(s))hw∑clog⁡∣sc∣hw \sum_c \log\lvert s_c\rvertboth
ActNormdiagonalhw∑cγchw \sum_c \gamma_cboth
Squeeze, permutationreordering00both
Planaridentity plus rank onedeterminant lemmaforward; inverse needs root search
Radialscalar identity plus rank one(d−1)log⁡(ρ/r)+log⁡ρ′(r)(d-1)\log(\rho/r)+\log\rho'(r)both; inverse solves a quadratic

For d≥2d \ge 2, with sufficiently expressive, suitably regular scale/shift networks, affine couplings and invertible linear layers are distributionally universal: from an absolutely continuous base, a sequence of such flows can converge weakly to any target distribution (Teshima et al., 2020, Theorem 3). This does not promise exact representation by a finite network, convergence of densities, or successful training. Approximations may require very steep maps (separated modes), and the latent never gets smaller than the data.

What you should remember#

  • Coupling: copy zaz_a, scale and shift zbz_b by networks of zaz_a; log⁡∣det⁡J∣=∑isi(za)\log\lvert\det J\rvert = \sum_i s_i(z_a).
  • A Gaussian autoregressive model is a flow; MAF evaluates densities in one pass, IAF samples in one pass.
  • One affine layer gives Gaussian conditionals; stack layers and permute, or use splines.
  • Glow: W=PL(U+diag⁡(s))W = PL(U + \operatorname{diag}(s)), log⁡∣det⁡W∣=∑clog⁡∣sc∣\log\lvert\det W\rvert = \sum_c \log\lvert s_c\rvert, times hwhw for a 1×11 \times 1 convolution.
  • Images: masks, squeeze, half the variables factored out per scale; Glow step = ActNorm, 1×11 \times 1 convolution, coupling.
  • A conditional flow is an exact p(x∣c)p(x \mid c): in a VAE, the posterior, prior or likelihood.

Notebook#

Run python3 scripts/notes/generative-practice.py flow-architectures. The standalone implementation composes a new two-dimensional affine coupling, a coordinate swap and nonzero diagonal scaling. With latent coordinates (a,b)(a,b), its output is

x1=1.3(e0.3ab+0.2a2)−0.4,x2=0.7a+0.2.\begin{aligned} x_1 &= 1.3\bigl(e^{0.3a}b+0.2a^2\bigr)-0.4,\\ x_2 &= 0.7a+0.2. \end{aligned}
  • Recover aa from x2x_2, then recover bb from x1x_1. On three specified input points, the saved round trip agrees within 10−1210^{-12}. The parameters are fixed, so this checks the implementation rather than a training run.
  • Add the layers’ log absolute determinants: log⁡(1.3⋅0.7)+0.3a\log(1.3\cdot0.7)+0.3a. Compare with a central finite-difference Jacobian; the largest discrepancy is below 10−810^{-8}. The swap reverses orientation, so taking the logarithm of the signed determinant would be invalid.
  • Compute each output’s log density from its recovered Gaussian latent and this determinant. Setting either diagonal scale to zero would destroy invertibility; it is outside the tested model. No external flow library, image data, spline implementation or checkpoint is used.

The example, script and observations were newly authored for this course with Codex assistance; the numerical results are from the linked run.

Next#

Flows buy an exact likelihood by restricting the architecture. An energy-based model drops these restrictions: any network Eθ(x)E_\theta(x) with a scalar output defines a density e−Eθ(x)/Zθe^{-E_\theta(x)}/Z_\theta, provided Zθ=∫e−Eθ(x) dxZ_\theta = \int e^{-E_\theta(x)}\,dx is finite. Its value is unknown, so the next note builds Markov chain Monte Carlo samplers that need the density only up to ZθZ_\theta.

References#