Skip to content
BIASED

Flow architectures

The layers that real image flows are built from: MAF and IAF autoregressive layers with MADE masks, splines, Glow's invertible 1×1 convolution and ActNorm, the squeeze and multi-scale architecture, and conditional flows.

What a flow on images needs

The topic The change of variables left us with one working layer. An affine coupling layer copies half of the coordinates and scales and shifts the other half with networks of the copied half. Its Jacobian is triangular, so log⁡∣det⁡Jf∣\log\lvert\det J_f\rvert is a plain sum of the scales. Stacked with swaps in between, such layers already make a flow.

A real image needs more than that. A 64×6464 \times 64 colour image has D=64⋅64⋅3=12288D = 64 \cdot 64 \cdot 3 = 12288 coordinates, and a general Jacobian of that size would cost about 23D3≈1.2⋅1012\tfrac23 D^3 \approx 1.2 \cdot 10^{12} operations per layer and per example. So every layer of this topic keeps the two rules of the previous one: an inverse we can compute and a cheap log-determinant. Within those rules we meet four more parts:

  1. autoregressive layers, a second way to get a triangle, and the masks that build them from one network;
  2. spline layers, a more flexible element-wise map than "scale and shift";
  3. Glow's linear layers, a learned 1×11 \times 1 convolution that mixes channels and ActNorm that normalizes them;
  4. the image skeleton: masks on the pixel grid, the squeeze, and multiple scales.

One fact serves all of them. The inverse of a layer has the inverse Jacobian, Jf−1(z)=Jf(x)−1J_{f^{-1}}(z) = J_f(x)^{-1} at z=f(x)z = f(x), and the determinant of an inverse matrix is the reciprocal. So a determinant that is cheap in one direction is cheap in the other, and the log-determinant only changes sign.

The autoregressive layer

A coupling layer lets half of the coordinates depend on the other half. Push the idea to the end: let each coordinate depend on all the coordinates before it. Take an autoregressive model with Gaussian conditionals, where μi\mu_i and αi\alpha_i (a log standard deviation) are any functions of the earlier coordinates x<i=(x1,…,xi−1)x_{<i} = (x_1, \dots, x_{i-1}):

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).

This model is already a flow (Papamakarios, Pavlakou and Murray, 2017). Sampling draws z∼N(0,I)z \sim \mathcal N(0, I) and computes xi=zieαi+μix_i = z_i e^{\alpha_i} + \mu_i, one coordinate after another. Solving for zz gives the map from data to noise:

zi=(xi−μi(x<i)) e−αi(x<i),∂zi∂xi=e−αi(x<i).z_i = \big(x_i - \mu_i(x_{<i})\big)\, e^{-\alpha_i(x_{<i})}, \qquad \frac{\partial z_i}{\partial x_i} = e^{-\alpha_i(x_{<i})}.

Coordinate ziz_i depends on x1,…,xix_1, \dots, x_i only, so the Jacobian is lower-triangular. Its diagonal holds the factors e−αie^{-\alpha_i}, and

log⁡∣det⁡Jf(x)∣=−∑i=1Dαi(x<i).\log\lvert\det J_f(x)\rvert = -\sum_{i=1}^{D} \alpha_i(x_{<i}).

The change of variables gives back exactly the likelihood of the autoregressive model, as it should. A small example with D=2D = 2: take μ1=α1=0\mu_1 = \alpha_1 = 0, μ2(x1)=α2(x1)=x1/2\mu_2(x_1) = \alpha_2(x_1) = x_1/2, and the point x=(1,2)x = (1, 2). Then z1=1z_1 = 1, z2=1.5 e−0.5≈0.910z_2 = 1.5\, e^{-0.5} \approx 0.910, and the log-determinant is −0.5-0.5: the layer squeezes x2x_2, because its conditional standard deviation e0.5e^{0.5} is larger than one. In total log⁡p(x)=log⁡φ(1)+log⁡φ(0.910)−0.5≈−3.252\log p(x) = \log\varphi(1) + \log\varphi(0.910) - 0.5 \approx -3.252 nats, where φ\varphi is the standard normal density.

MAF and IAF: which direction is fast

The same layer can be run in two ways, and they are fast in opposite directions.

A masked autoregressive flow (MAF; Papamakarios, Pavlakou and Murray, 2017) is the layer of the previous block: μi\mu_i and αi\alpha_i read the data side x<ix_{<i}. To evaluate a density, all of xx is known, so one network pass gives every μi\mu_i and αi\alpha_i at once. To sample, we need x1x_1 before we can compute μ2(x1)\mu_2(x_1), then x2x_2 before μ3\mu_3, and so on: DD passes one after another.

An inverse autoregressive flow (IAF; Kingma et al., 2016) lets the shift and scale read the noise side instead:

xi=zi eαi(z<i)+μi(z<i).x_i = z_i\, e^{\alpha_i(z_{<i})} + \mu_i(z_{<i}).

Now all of zz is known when we sample, so sampling takes one pass. The density of a given xx takes DD passes, because recovering ziz_i needs z<iz_{<i} first. There is one important exception: for its own samples the IAF already knows zz, so it can score them in one pass. That is exactly what a VAE posterior needs: draw a code and compute its log⁡q\log q.

The coupling layer sits in between. It is the autoregressive layer in which the first kk coordinates are copied and every later μi\mu_i, αi\alpha_i reads only x1,…,xkx_1, \dots, x_k. Both directions then take one pass. The price is that a coupling layer changes only part of the coordinates, so it needs more layers to do the same work.

MADE masks

An autoregressive layer needs 2D2D outputs, μi\mu_i and αi\alpha_i for every ii, and output ii must not see the inputs xi,…,xDx_i, \dots, x_D. Training DD separate networks would be wasteful. MADE (Germain et al., 2015) uses one ordinary fully connected network and multiplies its weights by fixed binary masks.

Every unit gets a degree m(⋅)m(\cdot). Input jj has degree jj, output ii has degree ii, and each hidden unit uu gets some 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. Written as masks, with rows as receivers:

Muj=1[m(j)≤m(u)],Miuout=1[m(u)<i].M_{uj} = \mathbf 1\big[m(j) \le m(u)\big], \qquad M^{\text{out}}_{iu} = \mathbf 1\big[m(u) < i\big].

Take D=3D = 3 and four hidden units of degrees (1,2,1,2)(1, 2, 1, 2):

M=[100110100110],Mout=[000010101111],MoutM=[000200420].M = \begin{bmatrix} 1&0&0\\ 1&1&0\\ 1&0&0\\ 1&1&0 \end{bmatrix}, \qquad M^{\text{out}} = \begin{bmatrix} 0&0&0&0\\ 1&0&1&0\\ 1&1&1&1 \end{bmatrix}, \qquad M^{\text{out}} M = \begin{bmatrix} 0&0&0\\ 2&0&0\\ 4&2&0 \end{bmatrix}.

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 μi\mu_i and αi\alpha_i depend on x<ix_{<i} only, exactly as required. Output 11 receives nothing at all and is a learned constant, which is right: x1x_1 has no earlier coordinates to condition on.

Where one layer falls short

One affine autoregressive layer has a hard limit. Given x<ix_{<i}, the coordinate xix_i is an affine function of one Gaussian ziz_i, so every conditional is Gaussian, hence unimodal.

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. Given x1x_1, the data put two narrow bumps at x2=±x1x_2 = \pm x_1. With unlimited data, maximum likelihood picks the Gaussian with the true conditional mean and variance (the forward-KL fit by moments from Fitting distributions with KL). The random sign makes the mean 00, and the variance is x12+0.01x_1^2 + 0.01. At x1=2x_1 = 2 the model puts its peak at x2=0x_2 = 0, 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. Mass-covering, exactly as forward KL promised.

There are two fixes.

  • Stack layers and reorder. The next layer models the zz of the previous one in a different coordinate order. A MAF of five such layers already learns multimodal conditionals.
  • Use a more flexible element-wise map. The triangle needs only a strictly increasing, differentiable map gg with a computable inverse, whose parameters come from a network of the conditioning coordinates. The diagonal entry of the Jacobian becomes g′g', and the log-determinant is ∑ilog⁡g′(xb,i)\sum_i \log g'(x_{b,i}). Neural spline flows (Durkan et al., 2019) take gg to be a monotone rational-quadratic spline: KK bins on an interval [−B,B][-B, B], the identity outside it. Inverting one bin means solving a quadratic equation, so both directions stay cheap.

Glow's linear layers: 1×1 convolution and ActNorm

Between couplings a flow permutes coordinates, and a permutation is a linear map with a fixed matrix. Glow (Kingma and Dhariwal, 2018) learns that matrix. 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. Each output pixel reads only its own input pixel, so the Jacobian is block-diagonal with hwhw copies of WW:

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 still costs O(C3)O(C^3). Glow stores WW already factored,

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

where PP is a fixed permutation, LL is lower-triangular with ones on the diagonal, UU is strictly upper-triangular and s∈RCs \in \mathbb R^C. The determinant of a product is the product of determinants, det⁡P=±1\det P = \pm 1, det⁡L=1\det L = 1, and a triangular matrix contributes the product of its diagonal. So

log⁡∣det⁡W∣=∑c=1Clog⁡∣sc∣,\log\lvert\det W\rvert = \sum_{c=1}^{C} \log\lvert s_c\rvert ,

which costs O(C)O(C). For example, with P=IP = I and s=(2,−0.5,1.5)s = (2, -0.5, 1.5) we get det⁡W=−1.5\det W = -1.5 and log⁡∣det⁡W∣=log⁡1.5≈0.405\log\lvert\det W\rvert = \log 1.5 \approx 0.405. The negative entry is harmless for the density, but a free scs_c could pass through zero on its way from −0.5-0.5 to +0.5+0.5, and there WW is singular. Glow therefore learns log⁡∣sc∣\log\lvert s_c\rvert and keeps the signs fixed.

The second linear layer is ActNorm: a per-channel scale and shift, xc′=eγcxc+τcx'_{c} = e^{\gamma_c} x_c + \tau_c at every pixel, with log⁡∣det⁡J∣=hw∑cγc\log\lvert\det J\rvert = hw \sum_c \gamma_c. It plays the role of batch normalization (see Batch normalization, gradients and convolutions), but its parameters do not depend on the batch. Glow trains on large images with one image per device, and statistics of a batch that small are mostly noise. ActNorm is initialized from the first minibatch so that every channel starts with zero mean and unit variance, and after that γ\gamma and τ\tau are ordinary trainable parameters.

Flows on images: masks, squeeze and scales

Convolutional networks for ss and tt need a split into xax_a and xbx_b that respects the pixel grid. RealNVP (Dinh, Sohl-Dickstein and Bengio, 2017) writes the split as a binary mask. A checkerboard mask copies the pixels whose row and column indices sum to an odd number, so every transformed pixel is conditioned on its four neighbours. A channel-wise mask copies half of the channels. Consecutive layers swap the roles of the two halves.

The squeeze trades space for channels. It cuts every 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. It only reorders coordinates, so its log-determinant is 00, but after it a 3×33 \times 3 convolution sees twice as far.

The multi-scale architecture saves work. After each scale, half of the variables are factored out: they go straight into the latent zz, and only the other half continues to the next scale. For a 64×64×364 \times 64 \times 3 image the first scale squeezes to 32×32×1232 \times 32 \times 12, sends 61446144 numbers to zz and continues with 32×32×632 \times 32 \times 6; the next scales send 30723072, 15361536, 768768 and finally the last 768768. They add up to 12288=D12288 = D, so no dimension is lost, yet the deep layers work on ever smaller tensors.

Glow keeps this skeleton. One step of flow is ActNorm, then a 1×11 \times 1 convolution, then an affine coupling whose last convolution starts at zero, so that every step starts as the identity. One scale squeezes, runs many such steps and factors out half.

Conditional flows and what comes next

A flow can be conditioned on a vector cc that it does not transform: the networks inside simply read cc as an extra input, as in s(xa,c)s(x_a, c) and t(xa,c)t(x_a, c). The Jacobian is taken in the transformed variable with cc fixed, so it keeps the same triangle and the same log-determinant. A conditional flow is an exact density p(x∣c)p(x \mid c), and inside a VAE it can replace any of its three Gaussians: an IAF as a richer posterior qφ(z∣x)q_\varphi(z \mid x), a MAF as a learned prior p(z)p(z), or a flow of coupling layers as the likelihood pθ(x∣z)p_\theta(x \mid z), as in VAPNEV (see β-VAE and VQ-VAE).

Layer Why det⁡J\det J is cheap log⁡∣det⁡J∣\log\lvert\det J\rvert One pass for
affine coupling triangle, copied half ∑isi(xa)\sum_i s_i(x_a) both directions
MAF triangle, masks −∑iαi(x<i)-\sum_i \alpha_i(x_{<i}) density
IAF triangle, masks ∑iαi(z<i)\sum_i \alpha_i(z_{<i}), noise to data sampling
spline coupling triangle, monotone pieces ∑ilog⁡g′(xb,i)\sum_i \log g'(x_{b,i}) both directions
1×11 \times 1 convolution W=PL(U+diag⁡(s))W = PL(U + \operatorname{diag}(s)) hw∑clog⁡∣sc∣hw\sum_c \log\lvert s_c\rvert both directions
ActNorm diagonal hw∑cγchw\sum_c \gamma_c both directions
squeeze, permutation reordering 00 both directions

Every row of this table is a restriction bought for an exact likelihood. And the exact number is not a judge of quality either: flows trained on CIFAR-10 give higher likelihood to never-seen SVHN house numbers (Nalisnick et al., 2019).

What if we drop the restrictions altogether? Any network Eθ(x)E_\theta(x) with one scalar output defines a density e−Eθ(x)/Zθe^{-E_\theta(x)}/Z_\theta, as long as the integral ZθZ_\theta is finite. Nobody can compute that integral for images, so the density is known only up to a constant. Before such a model can be trained, we need to draw samples from a density we cannot normalize. The main line picks this up in Sampling unnormalized densities: MALA and HMC.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.