23 / 33 · Normalizing Flows
Flow architectures
How to build invertible layers with cheap Jacobian determinants: coupling layers (NICE, RealNVP), masked autoregressive layers (MAF, IAF), Glow's invertible 1×1 convolutions, rational-quadratic spline couplings, ActNorm, multi-scale flows on images, and the older planar and radial flows.
Normalizing flows: change of variables · Determinants ↗ · Neural networks · Batch normalization, gradients and convolutions
On this page 13
The change-of-variables note ended on a cost problem. Every layer of a flow contributes a term to the log-likelihood (with a plus sign when is the Jacobian of the data-to-latent map). For a general Jacobian that determinant costs . For a triangular Jacobian it is just the product of the diagonal entries, which costs . The question is therefore how to give a structure whose determinant is cheap by construction: triangular, a linear map stored in factored form, or the identity plus a low-rank term.
The answer comes in three designs: coupling layers (part A) and autoregressive layers (part B), whose Jacobians are triangular, and invertible convolutions (part C), whose Jacobian is block-diagonal with dense blocks stored as products of triangular factors. Each one keeps the layer invertible and its determinant cheap, while arbitrary neural networks still do the heavy lifting inside it. Three more parts build on them. Part D replaces the affine map inside a coupling layer with a monotone spline, part E adds ActNorm, the normalization layer of Glow, and part F assembles all of them into flows for images. Part G shows an older route to a cheap determinant that does not use triangular matrices at all: planar and radial flows. A first reading can take parts A, B, C and F; parts D and G are extensions.
Notation. One flow layer maps to . Its Jacobian is , with entries : row is an output coordinate and column an input coordinate. is the element-wise product, and of a vector acts element-wise. It does not matter here whether a layer is used in the data-to-latent or the latent-to-data direction. The inverse layer has the reciprocal determinant, so a determinant that is cheap in one direction is cheap in the other. A subscript indexes the coordinates of one vector (, ), not the layers of a flow as in the previous note. An image tensor has height , width and channels.
A. Coupling layers (NICE, RealNVP)#
Split the input into two parts,
and define the transform
where are arbitrary neural networks, called the scale and the translation network. Two facts make this work:
- does not depend on at all;
- depends on only affinely, and even element-wise: the -th coordinate involves only , multiplied by and shifted by .
An affine coupling layer and its inverse
The Jacobian. Those two facts fix the block structure of :
- Top left, , because .
- Top right, , because ignores .
- Bottom right, , because the dependence on is element-wise with slope .
- Bottom left, is a dense matrix involving the derivatives of and . It is complicated, but it does not matter.
So is lower-triangular, and its determinant is the product of its diagonal:
Here runs over the coordinates of , and is the -th output of the network .
The determinant is always positive, so no absolute value is needed. The layer is invertible for any choice of the networks and , not because (that alone only guarantees local invertibility) but because the inverse can be written down explicitly, as shown below. The dense block never enters the determinant: and can be as deep as we like without making any more expensive.
Why the coupling Jacobian is lower-triangular
For example, with split , suppose that at some point . Then and . Near this point the layer shrinks small volumes by about 18%, whatever the dense block contains.
The inverse reverses only the element-wise step. Since , the networks can be evaluated again on the same input:
Neither nor ever has to be inverted. Both directions cost one pass through the two networks.
B. Autoregressive layers (MAF, IAF)#
Ensure that each output dimension depends only on the previous ones:
Now is automatically lower-triangular:
- there is no dependence on dimensions , so for every ;
- the diagonal entries are .
so that
Again, the determinant is a product of diagonal entries. A coupling layer is the special case with just two blocks: conditions .
The concrete layer. In MAF, the masked autoregressive flow (Papamakarios, Pavlakou and Murray, 2017), each is affine in its own coordinate, with a scale and a shift computed from the coordinates strictly before it:
Here . Because and do not see , the diagonal entry is simply , and the layer can be inverted one coordinate at a time. The same layer is often written as , which is the form above with and .
Masking. We could give every coordinate its own network that reads , at the price of networks and sequential passes. MAF instead uses one network and masks its weights, so that
This network is MADE, the masked autoencoder for distribution estimation (Germain et al., 2015). The masks come from degrees, written here so as not to clash with the dimension :
- input has degree ;
- each hidden unit gets a degree (Germain et al., 2015, §4). The unit is allowed to depend on and nothing later. A degree of would be useless: such a unit could only feed outputs that come after , and there are none;
- the output unit that produces has degree .
In a hidden layer, hidden unit may read unit of the layer below only if the sender’s degree is at most the receiver’s:
The mask has the same shape as the layer’s weight matrix , and simply zeroes the forbidden weights. The output layer uses the strict inequality: its mask is if and otherwise, so output may read hidden unit only if . This is what makes depend on and not on itself.
A worked example. Take inputs, one hidden layer of four units with degrees and outputs of degrees . In both masks the rows are the receiving units and the columns the sending units. The hidden mask (rule ) and the output mask (rule ) are
Entry of their product counts the paths from input to output :
It is strictly lower-triangular. A nonlinearity such as ReLU cannot create a path that the masks removed, so depend only on . The element-wise step then adds the diagonal Output 1 receives no connections at all, so are learned constants (biases), as they should be: has nothing before it. Input feeds nothing, because no later coordinate needs it.
Masked weights make the network autoregressive
MAF versus IAF. The masked network gives all the in one pass when the conditioning variables are known. In MAF they are known in the data-to-latent direction, so the density of a data point is cheap. Sampling has to invert the layer coordinate by coordinate: needs first, which takes sequential passes. IAF, the inverse autoregressive flow (Kingma et al., 2016), swaps the two directions: its read the latent-side coordinates before . Sampling is one pass, but evaluating the density of an arbitrary given point is sequential. IAF can still score its own samples in one pass, because their latents are known, and that is what variational inference needs. Coupling layers are cheap in both directions because and read only , which passes through unchanged and is known in both directions. The price is that only half of the coordinates change per layer.
C. Invertible convolutions (Glow)#
Glow layers use invertible convolutions:
For an image-shaped tensor of height , width and channels, a convolution applies the same matrix to the vector of channel values at every pixel. It mixes channels and does nothing across space. Mixing channels is what the coupling layers need between them: it is a learned generalization of the fixed channel permutation (for example, reversing the channel order) that RealNVP uses between couplings (Kingma and Dhariwal, 2018, §3.2). The Jacobian of the whole layer is block-diagonal, with copies of on the diagonal, so
must be invertible, and a general costs . So is learned through its LU decomposition. Not every invertible matrix has an LU factorization without pivoting: the swap has none, because would have to be and then . Glow therefore adds a fixed permutation matrix :
The entries and are real numbers. stays fixed; the free entries of (below its unit diagonal) and of (on and above its diagonal) are the learnable parameters. Since , and ,
The layer is invertible exactly when every , and its inverse is : a permutation and two triangular solves. Unlike , a free parameter is not automatically non-zero.
Glow's invertible 1×1 convolution
For example, take and with
Expanding directly gives , which equals . Hence . The negative pivot shows why the absolute value is needed: is undefined.
D. Spline couplings: neural spline flows#
Optional depth: a more flexible element-wise map and the derivation of its inverse. The rest of the note does not depend on it.
Inside a coupling or autoregressive layer, each transformed coordinate goes through a one-dimensional map whose parameters come from a network: in part A. An affine map can shift and stretch a conditional distribution, but it cannot change its shape: a unimodal conditional stays unimodal after one layer. Nothing in the triangular argument needs the map to be affine. Any strictly increasing, differentiable function with a computable inverse will do. The diagonal entry of becomes , and is produced by the same kind of network as before: in a coupling layer, in an autoregressive one.
The rational-quadratic spline. Neural spline flows (Durkan et al., 2019, §3.1) use a monotone spline built from rational-quadratic pieces, the ratio of two quadratic polynomials, with the construction of Gregory and Delbourgo (1982). In this part is the scalar input of the map, not a data point. The spline maps onto itself and is the identity outside it. Inside, it is set by bins with knots , increasing from to , and by positive derivatives at the knots. The two edge derivatives are fixed, , so that the slope matches the identity tails. In bin let
( is the slope of the chord across the bin, not the scale network of part A). The spline in bin is
At it gives , and at the fraction is , so it gives : every piece joins two consecutive knots. The denominator can be rewritten as , which is positive. Its derivative is
with every term of the numerator positive, so is strictly increasing. At the derivative equals and at it equals : neighbouring pieces meet with the same slope, and the spline meets the tails with slope 1. The layer’s log-determinant is over the transformed coordinates; coordinates in the tails contribute .
Parameters. For every transformed coordinate the network outputs unconstrained numbers (Durkan et al., 2019, §3.1): for the bin widths and for the bin heights, each passed through a softmax and multiplied by , so that they are positive and fill the interval, and for the inner derivatives, passed through a softplus. Cumulative sums of the widths and heights, starting at , give the knots.
The inverse is a quadratic. Since increases, the bin of an output is found by comparing with the . Setting and multiplying out the fraction gives with
Exactly one root lies in (Durkan et al., 2019, App. A.3):
the usual formula rewritten so that it does not lose precision when is small. Then . Evaluation and inversion both cost a bin search and a few arithmetic operations, so a spline coupling layer, like an affine one, takes one network pass in each direction.
A monotone rational-quadratic spline and its derivative
A worked example (toy numbers, the spline of the figure). bins on with knots , , , , , inner derivatives and . The input lies in bin , with , width , , height and . Then and
This coordinate adds to . Inverting : , so , , , , and , which gives back .
Coupling and autoregressive versions. A spline replaces the affine map in either design. Durkan et al. call the results RQ-NSF (C) and RQ-NSF (AR) (§3.2): the coupling version is Glow with affine couplings replaced by spline couplings, and the autoregressive version is MAF or IAF with affine maps replaced by splines. In their coupling layer the identity half also passes through element-wise splines whose parameters are trained directly rather than predicted. With enough bins a monotone spline approximates any differentiable monotone function on ; in practice they fix and after finding little difference for between 1 and 5 (§5).
E. ActNorm: per-channel scale and shift with data-dependent initialization#
Deep flows train better with a normalization layer, and in a flow that layer must be invertible with a known determinant. RealNVP uses batch normalization (Dinh, Sohl-Dickstein and Bengio, 2017, §3.7): with the batch statistics , the map is a per-dimension rescaling with log-determinant . That formula treats and as constants supplied from outside the example, as RealNVP does with a running average over recent minibatches (App. E). Ordinary train-time batch normalization, differentiated as a function of the current batch, is a different map: each output depends on every example of the batch, and standardizing removes the batch’s own mean and scale, so the outputs alone do not determine the inputs. Batch normalization adds noise through its batch statistics, the noise grows as the batch per device shrinks, and Glow trains on large images with one image per device (§3.1). Its ActNorm layer keeps the affine form and drops the batch statistics (Kingma and Dhariwal, 2018, §3.1, Table 1). With a log-scale and a shift per channel ,
The Jacobian is diagonal, with the entry repeated at each of the positions of channel . Glow writes the scale itself, , and the log-determinant ; the log-scale keeps the scale positive automatically. The inverse is . On flat vectors the same layer has one per coordinate and ; it generalizes the diagonal scaling layer that NICE places at the top of its flow (Dinh, Krueger and Bengio, 2015, §3.3).
Data-dependent initialization. The parameters are set from the first minibatch so that each channel of the layer’s output has zero mean and unit variance on it:
which makes on that batch. From then on and are ordinary trainable parameters that do not depend on the data, unlike batch normalization. Every layer of a fresh flow therefore starts with well-scaled activations, whatever the depth.
For example (toy numbers), an ActNorm with log-scales on a tensor contributes nats.
One step of Glow is ActNorm, then a convolution, then an affine coupling layer (Kingma and Dhariwal, 2018, §3). The last convolution of each coupling network is initialized at zero, so that every coupling layer starts as the identity (§3.3). Both initializations aim at the same thing: a deep stack of invertible layers that starts close to a well-scaled identity map.
F. Flows on images: squeeze, masks and multi-scale#
An RGB image of pixels has coordinates. The layers above work on any vector, but an image flow should use convolutional networks for and , which means that the split into and must respect the pixel grid.
Masks on the pixel grid#
RealNVP writes the coupling with a binary mask of the same shape as the image tensor (Dinh, Sohl-Dickstein and Bengio, 2017, §3.4):
where the sum runs over all entries of the tensor. Entries with pass through and condition the rest, exactly as does in part A, and , are convolutional networks that map an tensor to one of the same shape. Two masks are used:
- checkerboard: where is odd, the same in every channel, so the four direct neighbours of every transformed pixel are among the conditioning pixels;
- channel-wise: on the first half of the channels and on the second half.
Consecutive layers alternate and , so that every entry is transformed.
Squeeze: trading space for channels#
The squeeze operation cuts each channel into squares and stacks the four values of each square as four channels, turning an tensor into an tensor (§3.6). With channel of the output holding the pixels at offset of channel , a input becomes
Squeezing only reorders the coordinates, so its Jacobian is a permutation matrix and its log-determinant is . It also explains why the two masks complement each other. With 0-based indices the checkerboard of this input is
and after squeezing its ones fill channels 1 and 2 (offsets and ) and its zeros channels 0 and 3. The channel-wise mask splits the squeezed channels into and , a different partition, so channels 0 and 3, which the checkerboard put on the same side, end up in different halves, as do channels 1 and 2: couplings after the squeeze condition each group on pixels that the checkerboard couplings kept together.
Factoring out half the variables at each scale#
RealNVP’s multi-scale architecture (§3.6) repeats one block per scale: three coupling layers with alternating checkerboard masks, a squeeze, and three coupling layers with alternating channel-wise masks. After each block, half of the variables are factored out: they leave the flow and become part of the latent , and only the other half continues to the next scale. In the data-to-latent direction, with the block of scale and ,
The last scale has four checkerboard couplings and no squeeze, and the recursion stops when its input is (§4.1). Every factored-out part is scored by the Gaussian base as soon as it leaves, so the loss is spread through the network, and the later scales are cheaper because they process fewer variables. For a image the recipe gives five scales:
| Scale | Input | After squeeze | Factored out | Continues |
|---|---|---|---|---|
| 1 | 6144 | |||
| 2 | 3072 | |||
| 3 | 1536 | |||
| 4 | 768 | |||
| 5 | none | 768 |
The factored-out sizes add up to : a multi-scale flow still keeps every dimension. Its 28 coupling layers process full-image equivalents of variables, about 41% of what 28 couplings on all variables would process. Variables factored out early have passed through fewer layers, and RealNVP describes them as finer, more local features (§3.6, App. D). In RealNVP the scale network ends in times a learned factor and the translation network has an affine output (§4.1).
The Glow step on image tensors#
Glow keeps the multi-scale skeleton with levels: each level is a squeeze followed by steps of ActNorm, convolution and affine coupling, and every level but the last ends with a split that factors out half of the variables (Kingma and Dhariwal, 2018, §3, Fig. 2). Its couplings split only along channels, a simplification over RealNVP (§3.3), and the learned convolutions replace the fixed channel reversal between couplings. All three layers act on tensors with per-channel parameters, and their log-determinants carry the factor (part C and part E). A convolution after one squeeze of an RGB image has and only weights. The coupling networks have three convolutions (, , ) with 512 hidden channels, and the CIFAR-10 comparisons use and (§5). Glow’s best results are 3.35 bits/dim on CIFAR-10 against 3.49 for RealNVP, and 3.81 against 3.98 on ImageNet (§5, Table 2). For CelebA-HQ faces it uses and on 5-bit images (§6).
Flattening the image instead#
The simplest image flow reshapes the image into a vector of numbers and applies the layers of parts A–D with fully connected networks. It works, and it needs no masks or squeezes, but it throws away the grid. An index split of the flattened channel-first tensor puts the whole red channel and the top half of the green channel into ; the networks have to learn from scratch which coordinates are neighbours; and the first layer of a coupling network with 1024 hidden units already has million weights. A learned dense mixing matrix between couplings would have entries, so a fixed permutation, for example a random one, is the practical choice. On CIFAR-10, NICE, whose couplings are fully connected networks on the flattened image, reaches 4.48 bits/dim against 3.49 for the convolutional multi-scale RealNVP (table). The two models also differ in depth and in additive versus affine couplings, so not all of the gap is due to the grid.
Likelihoods of image flows are reported in bits per dimension after undoing every preprocessing step, which adds the log-determinant of the preprocessing to the model’s own; Images: dequantization, rescaling and bits per dimension works this out for the common rescalings and for the logit transform of RealNVP.
Interpolating and encoding with the exact inverse#
A flow has an exact encoder: any image , including one from outside the training set, has exactly one latent , and gives back up to floating-point error. A VAE instead encodes into the parameters of , and its reconstruction is only as faithful as its decoder: the common pixel-wise Gaussian or squared-error decoder returns the mean of , which tends to be blurred, while a more expressive decoder likelihood can give sharp samples (VAE; variants in VAE variants). Three uses follow.
Interpolation. Encode two images, move along a path between and , and decode. The straight line leaves the region where the base puts its mass. For the length concentrates near with a spread of about (the Gaussian shell). If and behave like independent draws, their midpoint has length about . For that is instead of , about 46 spreads below the typical length. Weights whose squares sum to one keep the length typical. RealNVP’s paths between latents use such and weights (§4.2, eq. 19), and the midpoint has length about . Glow interpolates linearly between the latents of real faces and still reports realistic intermediate images (§6).
Temperature. Glow samples from a reduced-temperature model: it multiplies the standard deviation of the base by , trading diversity for quality (§6). For a volume-preserving flow, gives the density , a sharpened version of the model (the paper writes the exponent as ).
Encoding an outside image. Preprocess it exactly as the training data, compute , and compare it with the latents of training images, for example by Euclidean distance. Two cautions. If the latents behave like independent draws from the base, all pairwise distances are close to , so nearest neighbours differ only slightly from typical points. And the exact likelihood of the outside image does not say whether it looks like the training data: a Glow trained on CelebA assigns higher likelihood to SVHN house numbers, a dataset it has never seen, than to CelebA faces (Nalisnick et al., 2019, §3, Fig. 2).
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 first flows of Rezende and Mohamed (2015), §4.1, take another route to a cheap determinant. Their Jacobian is the identity plus a rank-one matrix, and the matrix determinant lemma gives its determinant in (Papamakarios et al., 2021, §3.3.2): for ,
Every vector orthogonal to is left unchanged by , so the eigenvalue has multiplicity at least ; the trace then fixes the last eigenvalue at , and the determinant is the product of the eigenvalues.
Planar flows. With and a scalar bias (not the mask of part F),
Rezende and Mohamed allow any smooth element-wise nonlinearity in place of ; the invertibility condition below is for .
The map moves only along , by an amount that depends on the signed distance from the hyperplane , so it expands or contracts the density across that hyperplane.
When is it invertible? Split into a part orthogonal to and a part along it, so that . Taking of gives the scalar equation
and once is known, . So is invertible exactly when is. Since , with only at , we get . If , is strictly increasing and onto , and is a bijection (Rezende and Mohamed, 2015, App. A.1). If , then while far away, so is not monotone and folds space onto itself. A diffeomorphism also needs everywhere, which holds for ; Rezende and Mohamed enforce this by replacing with , where . Even for an invertible planar flow, the inverse has no closed form: each layer needs a one-dimensional root search for .
For example (toy numbers), take , , , , so . At : , , and . Inverting needs the root of , which is , and then . With instead, and vanishes at and : every point with has three preimages.
Radial flows. With a centre , , and ,
The map keeps the direction from and changes only the distance, . The Jacobian of such a radial map is plus a rank-one term along : it stretches the directions orthogonal to by and the radial direction by . The determinant is the product of these stretches:
Both factors are positive for every when , and then increases from to , so is a bijection; Rezende and Mohamed state the condition and enforce it with (App. A.2). Unlike the planar flow, the radial flow can be inverted in closed form: the distance of an output satisfies , a quadratic in ,
whose roots have the product , so exactly one is non-negative; then . For example (toy numbers), with , , , a point at distance from the centre has and is mapped to distance ; the quadratic has the non-negative root .
Where they are used. Each layer reshapes the density along one direction or around one point, so many layers are needed, and the planar inverse is iterative. Neither matters for variational inference, the setting they were designed for: there one samples from a simple , pushes it forward through layers to , and accumulates with forward Jacobians only, as in an IAF. Planar and radial flows have mostly been used this way, as flexible posteriors for VAEs (Papamakarios et al., 2021, §3.3.2), while the layers of parts A–F were designed for exact densities of data.
How the layers warp space and stay invertible#
The Jacobian is how the flow warps space. Every layer above stretches some regions and squeezes others, and at a point is the local factor by which it changes small volumes. Pushing a regular grid through a trained flow, one layer at a time, and drawing the bent grid lines makes this visible. The figure below does it for a single coupling layer with simple hand-picked and .
The Jacobian measures how a layer warps space
Invertible by construction. Exact maximum likelihood needs the unique latent point of every data point and a Jacobian that never collapses volume; the general argument is in the change-of-variables section of the previous note, and the triangular-Jacobian section shows when a triangular map is invertible. For the layers of this note:
- Affine coupling and autoregressive layers are invertible for any and : their diagonals are positive and their inverses are explicit.
- Spline layers are invertible for any network output: every piece is strictly increasing and the inverse is the root of a quadratic.
- ActNorm is invertible because its scales are positive; a layer that learns the scale itself, as in the Glow paper, needs .
- Squeeze and fixed channel permutations only reorder coordinates.
- The convolution is invertible as long as every pivot , which a parameterization through with fixed signs guarantees (part C). The Glow paper’s has no such safeguard; there holds only in practice.
- Planar and radial flows are diffeomorphisms only under a constraint, or , enforced by a reparameterization.
Limitations#
- No compression. The latent has the dimension of the data: numbers for a image, however simple the image. Multi-scale factoring organizes the latent; it does not shrink it.
- Constrained layers. Every layer must be invertible with a tractable Jacobian, so a flow needs many simple layers, and in each Glow step two of the three layers only rescale or mix channels. Glow uses as many as 320 sub-transformations (Papamakarios et al., 2021, §3.4), and on CIFAR-10 its 3.35 bits/dim still trails the 2.92 of the autoregressive PixelCNN++.
- No holes in the density. A diffeomorphism of applied to a Gaussian gives a density that is positive everywhere. Data that lie on separate clusters or near a lower-dimensional surface can only be approximated, with very large Jacobians at the gaps.
- Likelihood is not quality. An exact likelihood measures compression, not how samples look, and it can rank unfamiliar images above familiar ones (part F).
Summary#
Normalizing flows are invertible neural networks that move probability mass in controlled ways. Each layer reports, through its Jacobian determinant, how much it stretched or squeezed space. Autoregressive flows whose element-wise transformation is a sufficiently flexible monotone function (neural or spline transformers) are universal density approximators under mild conditions (Huang et al., 2018, §4, Theorem 1; Papamakarios et al., 2021, §3.1). Affine layers are universal as well, in a weaker sense. Compositions of affine couplings and invertible linear maps (permutations suffice) approximate any diffeomorphism in on compact sets, provided the networks and are universal function approximators, and pushing a base density through such compositions reaches any target distribution in the limit, in the sense of convergence in distribution (Teshima et al., 2020, Theorems 2 and 3). The theorem is the right answer to “can affine flows express everything?”, but it leaves the practical questions open. It gives no bound on the number of layers; its construction transforms one coordinate per coupling and covers flat vectors, not directly Glow’s convolutional networks; and its approximating flows can be arbitrarily ill-conditioned. Koehler, Mehta and Risteski (2021) show that shallow affine coupling networks are universal in Wasserstein distance once such ill-conditioning is allowed, and Draxler et al. (2024) prove a universality theorem, in a sense built on the KL divergence, for well-conditioned coupling flows such as RealNVP.
The layers differ in where the cheap determinant comes from:
| Layer | Why is cheap | Cost of the two directions | |
|---|---|---|---|
| Coupling (NICE, RealNVP) | ; element-wise in | (NICE: ) | one pass each way |
| Autoregressive (MAF) | depends on only (masks) | density: one pass; sampling: passes | |
| Autoregressive (IAF) | same, but read the latent-side coordinates before | (of the latent-side coordinates before ) | sampling: one pass; density: passes |
| conv (Glow) | , fixed, triangular | one matrix product each way | |
| Spline coupling (NSF) | as coupling, with a monotone spline in place of the affine map | one pass each way; the inverse solves a quadratic per coordinate | |
| ActNorm | diagonal | one affine map each way | |
| Squeeze, permutation | reordering | free | |
| Planar | plus a rank-one matrix (determinant lemma) | forward ; inverse by a scalar root search | |
| Radial | scaled plus a rank-one matrix | forward ; inverse by a quadratic in |
- On images, couplings use checkerboard and channel-wise masks, squeezes trade space for channels, and half of the variables are factored out at each scale; Glow’s step is ActNorm, convolution and affine coupling.
- A flow encodes any image exactly, which allows interpolation and the encoding of outside images; linear paths between latents leave the typical shell of the base.
Notebook#
The normalizing-flows notebook and its library nflib (HSE-LAMBDA Deep Generative Models, branch spring-2025-long) implement the layers of parts A–E on flat vectors. Cell numbers count every cell, markdown included, from 1. The notebook has no saved outputs, so it documents procedures rather than results. In nflib, the forward method of every layer runs data → latent and returns the output with its log-determinant.
flows.py, coupling.AffineHalfFlowis part A: the forward pass computesx_b * exp(s) + tandlog_det = sum(s), the inverse(z_b - t) * exp(-s)andlog_det = sum(-s). Itsparityflag swaps which half conditions the other, so stacked layers alternate, andscale=Falsegives NICE’s additive coupling. For odd the transformed half is the larger one.flows.py, autoregressive.SlowMAFgives every coordinate its own MLP (a learned constant,LeafParam, for the first) and loops over coordinates in both directions.MAFuses oneARMLPthat returns for all coordinates in one pass:MAF.forwardis parallel andMAF.inverseloops over dimensions.IAFsimply swaps the two methods. Both MAF classes have aparityflag that reverses the coordinate order of the output, but with opposite meanings:MAFflips whenparity=True(z.flip),SlowMAFwhenparity=False.made.py.MaskedLinearcomputesF.linear(input, mask * weight, bias), that is , andMADE.update_masksapplies the degree rules of part B:self.m[l-1][:, None] <= self.m[l][None, :]for hidden layers andself.m[L-1][:, None] < self.m[-1][None, :]for the output layer. These are built as (in × out) arrays with 0-based degrees and transposed inMaskedLinear.set_mask.nets.py.MLPhas three hidden layers of widthnhwithLeakyReLU(0.2).ARMLPis MADE with three hidden layers of widthnh, a single mask and the natural ordering.PosEncMLPfeeds and features at frequencies 0.5, 1, 2, 4 and 8 into anMLP; nothing in the notebook uses it.flows.py, scale layers.AffineConstantFlowis a per-dimension affine layer,z = x * exp(s) + twithlog_det = sum(s), a generalization of NICE’s scaling layer; itssandtstart as standard normal draws.ActNormsubclasses it and implements part E on flat vectors: on its first forward call it setss = -log(x.std(0))andt = -mean(x * exp(s)), then trains them as ordinary parameters. The flagdata_dep_init_donethat guards this is a plain attribute, not part of thestate_dict, so a model rebuilt and loaded from a checkpoint re-initializes on its first forward call and overwrites the loadedsandt. Set the flag toTrueafter loading.flows.py,Invertible1x1Conv. It follows the paper’s parameterization of part C and learns directly, without a safeguard against . It starts from a random orthogonal matrix, factors it withtorch.linalg.lu, keeps as a fixed buffer, learns , and , applies the matrix to row vectors (z = x @ W, which leaves the determinant unchanged) and returnslog_det = sum(log(abs(S))). The inverse usestorch.linalg.inv(W).spline_flows.py.unconstrained_RQSandRQSimplement part D: the identity outside with zero log-determinant, the edge derivatives set to 1, minimum bin widths, heights and derivatives of , a bin search that counts the knots below the input, and the inverse2c / (-b - sqrt(discriminant))with-logabsdet.NSF_CLis a spline coupling layer with two MLPs:f1reads the first half and outputs parameters per coordinate of the second half, which it transforms;f2then reads the new second half and transforms the first. Each layer thus updates both halves, whereas the coupling layer of Durkan et al. (2019), eq. 9–11, gives the conditioning half splines with directly trained parameters. Its reshapes assume an even .NSF_ARis the autoregressive version, with a learned parameter vector for the first coordinate and one MLP per later coordinate; likeSlowMAFit loops over coordinates in both directions.- Two quirks of
spline_flows.py.NSF_CLandNSF_ARalready pass widths and heights through a softmax and multiply them by , andRQSapplies a softmax again. The final widths are therefore proportional to with a probability vector, so two bins can differ in width by a factor of at most for . The derivatives also pass through a softplus twice, so an inner knot derivative is never below . The spline stays monotone and invertible, but it is less flexible than the paper’s, which applies each transform once. - Notebook cell 2 lists planar and radial flows, RealNVP, MAF (in the form of part B), the convolution, ActNorm (as with diagonal ) and NSF.
nflibimplements neither planar nor radial flows. Cell 3 importsAffineConstantFlow,ActNorm,AffineHalfFlow,SlowMAF,MAF,IAF,Invertible1x1Conv,NSF_ARandNSF_CL, but cell 7 uses onlyActNorm,Invertible1x1ConvandNSF_CL(, , hidden width 16): three blocks of them on 2-D data, with a logistic base distribution. Each block is the Glow step of part E with a spline coupling, an RQ-NSF (C) layer; with and no spatial grid the “convolution” is a learned invertible mixing matrix. - Cell 15 pushes a grid backward through the trained flow (
model.inverse) and plots each layer’s point movements and grid warp, the experiment that the grid-warp figure imitates for a single coupling layer. Cell 17 sets up 500 more training steps with a redraw every 10 steps (point movements for up to nine layers and the grid warp of one layer), but its loop ends withbreakafter the first redraw, so as written it takes a single optimizer step and draws once.
The homework notebook 03_hw_vapnev of the same repository asks for three models of CelebA and a comparison of them. Its only saved outputs are the device (mps), the image shape [3, 64, 64] and a grid of 25 training images; the model cells are left empty.
- Cells 3–6: data.
CelebADatasetfrom the repository’sseminars/utils/datasets/celeba.py, withResize(64),CenterCrop(64),ToTensor()andx * 2 - 1, that is and . The pipeline adds no dequantization noise. A flow trained on these values sees only 256 distinct values per coordinate and can push its likelihood up without bound by concentrating mass on them. Add uniform noise of width before training, and add bits/dim to the reported negative log-likelihood (how this offset arises). - Cell 10, task 1: a normalizing flow on CelebA, evaluated by FID and negative log-likelihood. Any layers are allowed: convolutional flows (part F) or flows on the flattened image, which the task text expects to be simpler and weaker.
- Cell 12, task 2: a VAE on CelebA, evaluated by FID.
- Cell 14, task 3: VAPNEV (Agrawal and Dukkipati, 2016), a VAE whose likelihood is computed exactly by a real NVP instead of a pixel-wise Gaussian or Bernoulli, and a conditional version of it; see VAE variants.
- Cell 16, task 4: latent analysis. Which model interpolates better, encoding an image from outside CelebA and finding its nearest latents, and the most interesting sample. The flow side is in Interpolating and encoding with the exact inverse.
- Cell 18 asks for a written comparison with samples from every model.
Next#
Flows buy an exact likelihood by restricting the architecture: every layer must be invertible, with a Jacobian determinant that is cheap to compute, and the latent must keep the dimension of the data. An energy-based model drops every one of these restrictions. Any network that outputs a number defines a density , as long as is finite, but the normalizing constant is unknown, so neither sampling nor the likelihood gradient can be computed directly. Both then need Markov chain Monte Carlo. The next note, sampling unnormalized densities, builds the samplers that need the density only up to its constant: MALA, Hamiltonian Monte Carlo and NUTS.
References#
- L. Dinh, D. Krueger, Y. Bengio. NICE: Non-linear independent components estimation. ICLR Workshop, 2015. §3.3 (scaling layer).
- L. Dinh, J. Sohl-Dickstein, S. Bengio. Density estimation using Real NVP. ICLR, 2017. §3.4 (masks), §3.6 (squeeze and multi-scale architecture), §3.7 (batch normalization), §4.1 (preprocessing and architecture), App. D. Reference code: tensorflow/models,
research/real_nvp. - M. Germain, K. Gregor, I. Murray, H. Larochelle. MADE: Masked autoencoder for distribution estimation. ICML, 2015.
- G. Papamakarios, T. Pavlakou, I. Murray. Masked autoregressive flow for density estimation. NeurIPS, 2017.
- D. P. Kingma, T. Salimans, R. Jozefowicz, X. Chen, I. Sutskever, M. Welling. Improved variational inference with inverse autoregressive flow. NeurIPS, 2016.
- D. P. Kingma, P. Dhariwal. Glow: Generative flow with invertible 1×1 convolutions. NeurIPS, 2018. §3.1 (ActNorm), §3.2 (1×1 convolution), §3.3 (coupling, zero initialization), §5 (Table 2), §6 (temperature, interpolation). Reference code: openai/glow.
- C. Durkan, A. Bekasov, I. Murray, G. Papamakarios. Neural spline flows. NeurIPS, 2019. §3.1–3.2, §5, App. A.
- J. A. Gregory, R. Delbourgo. Piecewise rational quadratic interpolation to monotonic data. IMA Journal of Numerical Analysis, 2(2):123–130, 1982.
- D. J. Rezende, S. Mohamed. Variational inference with normalizing flows. ICML, 2015. §4.1 (planar and radial flows), App. A (invertibility conditions).
- E. Nalisnick, A. Matsukawa, Y. W. Teh, D. Gorur, B. Lakshminarayanan. Do deep generative models know what they don’t know? ICLR, 2019. §3.
- C.-W. Huang, D. Krueger, A. Lacoste, A. Courville. Neural autoregressive flows. ICML, 2018. §4, Theorem 1 (universal approximation).
- T. Teshima, I. Ishikawa, K. Tojo, K. Oono, M. Ikeda, M. Sugiyama. Coupling-based invertible neural networks are universal diffeomorphism approximators. NeurIPS, 2020. Theorems 2 and 3 (universality of affine coupling flows).
- F. Koehler, V. Mehta, A. Risteski. Representational aspects of depth and conditioning in normalizing flows. ICML, 2021.
- F. Draxler, S. Wahl, C. Schnörr, U. Köthe. On the universality of volume-preserving and coupling-based normalizing flows. ICML, 2024. §5.
- G. Papamakarios, E. Nalisnick, D. J. Rezende, S. Mohamed, B. Lakshminarayanan. Normalizing flows for probabilistic modeling and inference. JMLR, 22(57), 2021. §3.2, §3.3.2, §3.4.
- HSE-LAMBDA, Deep Generative Models course repository:
nf.ipynb,03_hw_vapnev.ipynb.