Glow: Generative Flow with Invertible 1x1 Convolutions

Diederik P. Kingma, Prafulla Dhariwal

Introduction

Two major unsolved problems in the field of machine learning are (1) data-efficiency: the ability to learn from few datapoints, like humans; and (2) generalization: robustness to changes of the task or its context. AI systems, for example, often do not work at all when given inputs that are different from their training distribution. A promise of generative models, a major branch of machine learning, is to overcome these limitations by: (1) learning realistic world models, potentially allowing agents to plan in a world model before actual interaction with the world, and (2) learning meaningful features of the input while requiring little or no human supervision or labeling. Since such features can be learned from large unlabeled datasets and are not necessarily task-specific, downstream solutions based on those features could potentially be more robust and more data efficient. In this paper we work towards this ultimate vision, in addition to intermediate applications, by aiming to improve upon the state-of-the-art of generative models.

Generative modeling is generally concerned with the extremely challenging task of modeling all dependencies within very high-dimensional input data, usually specified in the form of a full joint probability distribution. Since such joint models potentially capture all patterns that are present in the data, the applications of accurate generative models are near endless. Immediate applications are as diverse as speech synthesis, text analysis, semi-supervised learning and model-based control; see Section 4 for references.

The discipline of generative modeling has experienced enormous leaps in capabilities in recent years, mostly with likelihood-based methods (Graves, , 2013; Kingma and Welling, , 2013, 2018; Dinh et al., , 2014; van den Oord et al., 2016a, ) and generative adversarial networks (GANs) (Goodfellow et al., , 2014) (see Section 4). Likelihood-based methods can be divided into three categories:

Autoregressive models (Hochreiter and Schmidhuber, , 1997; Graves, , 2013; van den Oord et al., 2016a, ; van den Oord et al., 2016b, ; Van Den Oord et al., , 2016). Those have the advantage of simplicity, but have as disadvantage that synthesis has limited parallelizability, since the computational length of synthesis is proportional to the dimensionality of the data; this is especially troublesome for large images or video.

Variational autoencoders (VAEs) (Kingma and Welling, , 2013, 2018), which optimize a lower bound on the log-likelihood of the data. Variational autoencoders have the advantage of parallelizability of training and synthesis, but can be comparatively challenging to optimize (Kingma et al., , 2016).

Flow-based generative models, first described in NICE (Dinh et al., , 2014) and extended in RealNVP (Dinh et al., , 2016). We explain the key ideas behind this class of model in the following sections.

Flow-based generative models have so far gained little attention in the research community compared to GANs (Goodfellow et al., , 2014) and VAEs (Kingma and Welling, , 2013). Some of the merits of flow-based generative models include:

Exact latent-variable inference and log-likelihood evaluation. In VAEs, one is able to infer only approximately the value of the latent variables that correspond to a datapoint. GAN’s have no encoder at all to infer the latents. In reversible generative models, this can be done exactly without approximation. Not only does this lead to accurate inference, it also enables optimization of the exact log-likelihood of the data, instead of a lower bound of it.

Efficient inference and efficient synthesis. Autoregressive models, such as the PixelCNN (van den Oord et al., 2016b, ), are also reversible, however synthesis from such models is difficult to parallelize, and typically inefficient on parallel hardware. Flow-based generative models like Glow (and RealNVP) are efficient to parallelize for both inference and synthesis.

Useful latent space for downstream tasks. The hidden layers of autoregressive models have unknown marginal distributions, making it much more difficult to perform valid manipulation of data. In GANs, datapoints can usually not be directly represented in a latent space, as they have no encoder and might not have full support over the data distribution. (Grover et al., , 2018). This is not the case for reversible generative models and VAEs, which allow for various applications such as interpolations between datapoints and meaningful modifications of existing datapoints.

Significant potential for memory savings. Computing gradients in reversible neural networks requires an amount of memory that is constant instead of linear in their depth, as explained in the RevNet paper (Gomez et al., , 2017).

In this paper we propose a new a generative flow coined Glow, with various new elements as described in Section 3. In Section 5, we compare our model quantitatively with previous flows, and in Section 6, we study the qualitative aspects of our model on high-resolution datasets.

Background: Flow-based Generative Models

Let x\mathbf{x} be a high-dimensional random vector with unknown true distribution xp(x)\mathbf{x}\sim p^{*}(\mathbf{x}). We collect an i.i.d. dataset D\mathcal{D}, and choose a model pθ(x)p_{\boldsymbol{\theta}}(\mathbf{x}) with parameters θ\boldsymbol{\theta}. In case of discrete data x\mathbf{x}, the log-likelihood objective is then equivalent to minimizing:

In case of continuous data x\mathbf{x}, we minimize the following:

In most flow-based generative models (Dinh et al., , 2014, 2016), the generative process is defined as:

We focus on functions where f\mathbf{f} (and, likewise, g\mathbf{g}) is composed of a sequence of transformations: f=f1f2fK\mathbf{f}=\mathbf{f}_{1}\circ\mathbf{f}_{2}\circ\cdots\circ\mathbf{f}_{K}, such that the relationship between x\mathbf{x} and z\mathbf{z} can be written as:

Such a sequence of invertible transformations is also called a (normalizing) flow (Rezende and Mohamed, , 2015). Under the change of variables of eq. (4), the probability density function (pdf) of the model given a datapoint can be written as:

where we define h0x\mathbf{h}_{0}\triangleq\mathbf{x} and hKz\mathbf{h}_{K}\triangleq\mathbf{z} for conciseness. The scalar value logdet(dhi/dhi1)\log|\det(d\mathbf{h}_{i}/d\mathbf{h}_{i-1})| is the logarithm of the absolute value of the determinant of the Jacobian matrix (dhi/dhi1)(d\mathbf{h}_{i}/d\mathbf{h}_{i-1}), also called the log-determinant. This value is the change in log-density when going from hi1\mathbf{h}_{i-1} to hi\mathbf{h}_{i} under transformation fi\mathbf{f}_{i}. While it may look intimidating, its value can be surprisingly simple to compute for certain choices of transformations, as previously explored in (Deco and Brauer, , 1995; Dinh et al., , 2014; Rezende and Mohamed, , 2015; Kingma et al., , 2016). The basic idea is to choose transformations whose Jacobian dhi/dhi1d\mathbf{h}_{i}/d\mathbf{h}_{i-1} is a triangular matrix. For those transformations, the log-determinant is simple:

where sum()\textnormal{{sum}}() takes the sum over all vector elements, log()\log() takes the element-wise logarithm, and diag()\textnormal{{diag}}() takes the diagonal of the Jacobian matrix.

Proposed Generative Flow

We propose a new flow, building on the NICE and RealNVP flows proposed in (Dinh et al., , 2014, 2016). It consists of a series of steps of flow, combined in a multi-scale architecture; see Figure 2. Each step of flow consists of actnorm (Section 3.1) followed by an invertible 1×11\times 1 convolution (Section 3.2), followed by a coupling layer (Section 3.3).

This flow is combined with a multi-scale architecture; due to space constraints we refer to (Dinh et al., , 2016) for more details. This architecture has a depth of flow KK, and number of levels LL (Figure 2).

In Dinh et al., (2016), the authors propose the use of batch normalization (Ioffe and Szegedy, , 2015) to alleviate the problems encountered when training deep models. However, since the variance of activations noise added by batch normalization is inversely proportional to minibatch size per GPU or other processing unit (PU), performance is known to degrade for small per-PU minibatch size. For large images, due to memory constraints, we learn with minibatch size 1 per PU. We propose an actnorm layer (for activation normalizaton), that performs an affine transformation of the activations using a scale and bias parameter per channel, similar to batch normalization. These parameters are initialized such that the post-actnorm activations per-channel have zero mean and unit variance given an initial minibatch of data. This is a form of data dependent initialization (Salimans and Kingma, , 2016). After initialization, the scale and bias are treated as regular trainable parameters that are independent of the data.

2 Invertible 1×1111\times 1 convolution

(Dinh et al., , 2014, 2016) proposed a flow containing the equivalent of a permutation that reverses the ordering of the channels. We propose to replace this fixed permutation with a (learned) invertible 1×11\times 1 convolution, where the weight matrix is initialized as a random rotation matrix. Note that a 1×11\times 1 convolution with equal number of input and output channels is a generalization of a permutation operation.

The log-determinant of an invertible 1×11\times 1 convolution of a h×w×ch\times w\times c tensor h\mathbf{h} with c×cc\times c weight matrix W\mathbf{W} is straightforward to compute:

The cost of computing or differentiating det(W)\det(\mathbf{W}) is O(c3)\mathcal{O}(c^{3}), which is often comparable to the cost computing conv2D(h;W)\textnormal{{conv2D}}(\mathbf{h};\mathbf{W}) which is O(hwc2)\mathcal{O}(h\cdot w\cdot c^{2}). We initialize the weights W\mathbf{W} as a random rotation matrix, having a log-determinant of 0; after one SGD step these values start to diverge from 0.

This cost of computing det(W)\det(\mathbf{W}) can be reduced from O(c3)\mathcal{O}(c^{3}) to O(c)\mathcal{O}(c) by parameterizing W\mathbf{W} directly in its LU decomposition:

where P\mathbf{P} is a permutation matrix, L\mathbf{L} is a lower triangular matrix with ones on the diagonal, U\mathbf{U} is an upper triangular matrix with zeros on the diagonal, and s\mathbf{s} is a vector. The log-determinant is then simply:

The difference in computational cost will become significant for large cc, although for the networks in our experiments we did not measure a large difference in wallclock computation time.

In this parameterization, we initialize the parameters by first sampling a random rotation matrix W\mathbf{W}, then computing the corresponding value of P\mathbf{P} (which remains fixed) and the corresponding initial values of L\mathbf{L} and U\mathbf{U} and s\mathbf{s} (which are optimized).

3 Affine Coupling Layers

A powerful reversible transformation where the forward function, the reverse function and the log-determinant are computationally efficient, is the affine coupling layer introduced in (Dinh et al., , 2014, 2016). See Table 1. An additive coupling layer is a special case with s=1\mathbf{s}=1 and a log-determinant of 0.

We initialize the last convolution of each NN()\textnormal{{NN}}() with zeros, such that each affine coupling layer initially performs an identity function; we found that this helps training very deep networks.

Split and concatenation.

As in (Dinh et al., , 2014), the split()\textnormal{{split}}() function splits h\mathbf{h} the input tensor into two halves along the channel dimension, while the concat()\textnormal{{concat}}() operation performs the corresponding reverse operation: concatenation into a single tensor. In (Dinh et al., , 2016), another type of split was introduced: along the spatial dimensions using a checkerboard pattern. In this work we only perform splits along the channel dimension, simplifying the overall architecture.

Permutation.

Each step of flow above should be preceded by some kind of permutation of the variables that ensures that after sufficient steps of flow, each dimensions can affect every other dimension. The type of permutation specifically done in (Dinh et al., , 2014, 2016) is equivalent to simply reversing the ordering of the channels (features) before performing an additive coupling layer. An alternative is to perform a (fixed) random permutation. Our invertible 1x1 convolution is a generalization of such permutations. In experiments we compare these three choices.

Related Work

This work builds upon the ideas and flows proposed in (Dinh et al., , 2014) (NICE) and (Dinh et al., , 2016) (RealNVP); comparisons with this work are made throughout this paper. In (Papamakarios et al., , 2017) (MAF), the authors propose a generative flow based on IAF (Kingma et al., , 2016); however, since synthesis from MAF is non-parallelizable and therefore inefficient, we omit it from comparisons. Synthesis from autoregressive (AR) models (Hochreiter and Schmidhuber, , 1997; Graves, , 2013; van den Oord et al., 2016a, ; van den Oord et al., 2016b, ; Van Den Oord et al., , 2016) is similarly non-parallelizable. Synthesis of high-dimensional data typically takes multiple orders of magnitude longer with AR models; see (Kingma et al., , 2016; Oord et al., , 2017) for evidence. Sampling 256×256256\times 256 images with our largest models takes less than one second on current hardware. More specifically, generating a 256×256256\times 256 image at batch size 1 takes about 130ms on a single 1080 Ti, and about 550ms on a K80

GANs (Goodfellow et al., , 2014) are arguably best known for their ability to synthesize large and realistic images (Karras et al., , 2017), in contrast with likelihood-based methods. Downsides of GANs are their general lack of latent-space encoders, their general lack of full support over the data (Grover et al., , 2018), their difficulty of optimization, and their difficulty of assessing overfitting and generalization.

Quantitative Experiments

We begin our experiments by comparing how our new flow compares against RealNVP (Dinh et al., , 2016). We then apply our model on other standard datasets and compare log-likelihoods against previous generative models. See the appendix for optimization details. In our experiments, we let each NN()\textnormal{{NN}}() have three convolutional layers, where the two hidden layers have ReLU activation functions and 512 channels. The first and last convolutions are 3×33\times 3, while the center convolution is 1×11\times 1, since both its input and output have a large number of channels, in contrast with the first and last convolution.

We choose the architecture described in Section 3, and consider three variations for the permutation of the channel variables - a reversing operation as described in the RealNVP, a fixed random permutation, and our invertible 1×11\times 1 convolution. We compare for models with only additive coupling layers, and models with affine coupling. As described earlier, we initialize all models with a data-dependent initialization which normalizes the activations of each layer. All models were trained with K=32K=32 and L=3L=3. The model with 1×11\times 1 convolution has a negligible 0.2%0.2\% larger amount of parameters.

We compare the average negative log-likelihood (bits per dimension) on the CIFAR-10 (Krizhevsky, , 2009) dataset, keeping all training conditions constant and averaging across three random seeds. The results are in Figure 3. As we see, for both additive and affine couplings, the invertible 1×11\times 1 convolution achieves a lower negative log likelihood and converges faster. The affine coupling models also converge faster than the additive coupling models. We noted that the increase in wallclock time for the invertible 1×11\times 1 convolution model was only 7%\approx 7\%, thus the operation is computationally efficient as well.

Comparison with RealNVP on standard benchmarks.

Besides the permutation operation, the RealNVP architecture has other differences such as the spatial coupling layers. In order to verify that our proposed architecture is overall competitive with the RealNVP architecture, we compare our models on various natural images datasets. In particular, we compare on CIFAR-10, ImageNet (Russakovsky et al., , 2015) and LSUN (Yu et al., , 2015) datasets. We follow the same preprocessing as in (Dinh et al., , 2016). For Imagenet, we use the 32×3232\times 32 and 64×6464\times 64 downsampled version of ImageNet (Oord et al., , 2016), and for LSUN we downsample to 96×9696\times 96 and take random crops of 64×6464\times 64. We also include the bits/dimension for our model trained on 256×256256\times 256 CelebA HQ used in our qualitative experiments.Since the original CelebA HQ dataset didn’t have a validation set, we separated it into a training set of 27000 images and a validation set of 3000 images As we see in Table 2, our model achieves a significant improvement on all the datasets.

Qualitative Experiments

We now study the qualitative aspects of the model on high-resolution datasets. We choose the CelebA-HQ dataset (Karras et al., , 2017), which consists of 3000030000 high resolution images from the CelebA dataset, and train the same architecture as above but now for images at a resolution of 2562256^{2}, K=32K=32 and L=6L=6. To improve visual quality at the cost of slight decrease in color fidelity, we train our models on 55-bit images. We aim to study if our model can scale to high resolutions, produce realistic samples, and produce a meaningful latent space. Due to device memory constraints, at these resolutions we work with minibatch size 1 per PU, and use gradient checkpointing (Salimans and Bulatov, , 2017). In the future, we could use a constant amount of memory independent of depth by utilizing the reversibility of the model (Gomez et al., , 2017).

Consistent with earlier work on likelihood-based generative models (Parmar et al., , 2018), we found that sampling from a reduced-temperature model often results in higher-quality samples. When sampling with temperature TT, we sample from the distribution pθ,T(x)(pθ(x))T2p_{\boldsymbol{\theta},T}(\mathbf{x})\propto(p_{\boldsymbol{\theta}}(\mathbf{x}))^{T^{2}}. In case of additive coupling layers, this can be achieved simply by multiplying the standard deviation of pθ(z)p_{\boldsymbol{\theta}}(\mathbf{z}) by a factor of TT.

Figure 4 shows the random samples obtained from our model. The images are extremely high quality for a non-autoregressive likelihood based model. To see how well we can interpolate, we take a pair of real images, encode them with the encoder, and linearly interpolate between the latents to obtain samples. The results in Figure 5 show that the image manifold of the generator distribution is extremely smooth and almost all intermediate samples look like realistic faces.

Semantic Manipulation.

We now consider modifying attributes of an image. To do so, we use the labels in the CelebA dataset. Each image has a binary label corresponding to presence or absence of attributes like smiling, blond hair, young, etc. This gives us 3000030000 binary labels for each attribute. We then calculate the average latent vector zpos\mathbf{z}_{pos} for images with the attribute and zneg\mathbf{z}_{neg} for images without, and then use the difference (zposzneg)(\mathbf{z}_{pos}-\mathbf{z}_{neg}) as a direction for manipulating. Note that this is a relatively small amount of supervision, and is done after the model is trained (no labels were used while training), making it extremely easy to do for a variety of different target attributes. The results are shown in Figure 6.

Effect of temperature and model depth.

Figure 8 shows how the sample quality and diversity varies with temperature. The highest temperatures have noisy images, possibly due to overestimating the entropy of the data distribution, and thus we choose a temperature of 0.70.7 as a sweet spot for diversity and quality of samples. Figure 9 shows how model depth affects the ability of the model to learn long-range dependencies.

Conclusion

We propose a new type of flow, coined Glow, and demonstrate improved quantitative performance in terms of log-likelihood on standard image modeling benchmarks. In addition, we demonstrate that when trained on high-resolution faces, our model is able to synthesize realistic images. Our model is, to the best of our knowledge, the first likelihood-based model in the literature that can efficiently synthesize high-resolution natural images.

References

Appendix A Additional quantitative results

Appendix B Simple python implementation of the invertible 1×1111\times 1 convolution

Appendix C Optimization details

We use the Adam optimizer (Kingma and Ba, , 2015) with α=0.001\alpha=0.001 and default β1\beta_{1} and β2\beta_{2}. In out quantitative experiments (Section 5, Table 2) we used the following hyperparameters (Table 4).

In our qualitative experiments (Section 6), we used the following hyperparameters (Table 5)

Appendix D Extra samples from qualitative experiments

For the class conditional CIFAR-10 and 32×\times32 ImageNet samples, we used the same hyperparameters as the quantitative experiments, but with a class dependent prior at the top-most level. We also added a classification loss to predict the class label from the second last layer of the encoder, with a weight of λ=0.01\lambda=0.01. The results are in Figure 10.

Appendix E Extra samples from the quantitative experiments

For direct comparison with other work, datasets are preprocessed exactly as in Dinh et al., (2016). Results are in Figure 11 and Figure 12.