Generating Diverse High-Fidelity Images with VQ-VAE-2

Ali Razavi, Aaron van den Oord, Oriol Vinyals

Introduction

Deep generative models have significantly improved in the past few years . This is, in part, thanks to architectural innovations as well as computation advances that allows training them at larger scale in both amount of data and model size. The samples generated from these models are hard to distinguish from real data without close inspection, and their applications range from super resolution to domain editing , artistic manipulation , or text-to-speech and music generation .

We distinguish two main types of generative models: likelihood based models, which include VAEs , flow based and autoregressive models ; and implicit generative models such as Generative Adversarial Networks (GANs) . Each of these models offer several trade-offs such as sample quality, diversity, speed, etc.

GANs optimize a minimax objective with a generator neural network producing images by mapping random noise onto an image, and a discriminator defining the generators’ loss function by classifying its samples as real or fake. Larger scale GAN models can now generate high-quality and high-resolution images . However, it is well known that samples from these models do not fully capture the diversity of the true distribution. Furthermore, GANs are challenging to evaluate, and a satisfactory generalization measure on a test set to assess overfitting does not yet exist. For model comparison and selection, researchers have used image samples or proxy measures of image quality such as Inception Score (IS) and Fréchet Inception Distance (FID) .

In contrast, likelihood based methods optimize negative log-likelihood (NLL) of the training data. This objective allows model-comparison and measuring generalization to unseen data. Additionally, since the probability that the model assigns to all examples in the training set is maximized, likelihood based models, in principle, cover all modes of the data, and do not suffer from the problems of mode collapse and lack of diversity seen in GANs. In spite of these advantages, directly maximizing likelihood in the pixel space can be challenging. First, NLL in pixel space is not always a good measure of sample quality , and cannot be reliably used to make comparisons between different model classes. There is no intrinsic incentive for these models to focus on, for example, global structure. Some of these issues are alleviated by introducing inductive biases such as multi-scale or by modeling the dominant bit planes in an image .

In this paper we use ideas from lossy compression to relieve the generative model from modeling negligible information. Indeed, techniques such as JPEG have shown that it is often possible to remove more than 80% of the data without noticeably changing the perceived image quality. As proposed by , we compress images into a discrete latent space by vector-quantizing intermediate representations of an autoencoder. These representations are over 30x smaller than the original image, but still allow the decoder to reconstruct the images with little distortion. The prior over these discrete representations can be modeled with a state of the art PixelCNN with self-attention , called PixelSnail . When sampling from this prior, the decoded images also exhibit the same high quality and coherence of the reconstructions (see Fig. 1). Furthermore, the training and sampling of this generative model over the discrete latent space is also 30x faster than when directly applied to the pixels, allowing us to train on much higher resolution images. Finally, the encoder and decoder used in this work retains the simplicity and speed of the original VQ-VAE, which means that the proposed method is an attractive solution for situations in which fast, low-overhead encoding and decoding of large images are required.

Background

The VQ-VAE model can be better understood as a communication system. It comprises of an encoder that maps observations onto a sequence of discrete latent variables, and a decoder that reconstructs the observations from these discrete variables. Both encoder and decoder use a shared codebook. More formally, the encoder is a non-linear mapping from the input space, xx, to a vector E(x)E(x). This vector is then quantized based on its distance to the prototype vectors in the codebook ek,k1Ke_{k},k\in 1\ldots K such that each vector E(x)E(x) is replaced by the index of the nearest prototype vector in the codebook, and is transmitted to the decoder (note that this process can be lossy).

The decoder maps back the received indices to their corresponding vectors in the codebook, from which it reconstructs the data via another non-linear function. To learn these mappings, the gradient of the reconstruction error is then back-propagated through the decoder, and to the encoder using the straight-through gradient estimator.

The VQ-VAE model incorporates two additional terms in its objective to align the vector space of the codebook with the output of the encoder. The codebook loss, which only applies to the codebook variables, brings the selected codebook e\mathbf{e} close to the output of the encoder, E(x)E(\mathbf{x}). The commitment loss, which only applies to the encoder weights, encourages the output of the encoder to stay close to the chosen codebook vector to prevent it from fluctuating too frequently from one code vector to another. The overall objective is described in equation 2, where e\mathbf{e} is the quantized code for the training example x\mathbf{x}, EE is the encoder function and DD is the decoder function. The operator sgsg refers to a stop-gradient operation that blocks gradients from flowing into its argument, and β\beta is a hyperparameter which controls the reluctance to change the code corresponding to the encoder output.

As proposed in , we use the exponential moving average updates for the codebook, as a replacement for the codebook loss (the second loss term in Equation equation 2):

where ni(t)n^{(t)}_{i} is the number of vectors in E(x)E(x) in the mini-batch that will be quantized to codebook item eie_{i}, and γ\gamma is a decay parameter with a value between 0 and 1. We used the default γ=0.99\gamma=0.99 in all our experiments. We use the released VQ-VAE implementation in the Sonnet library https://github.com/deepmind/sonnet/blob/master/sonnet/python/modules/nets/vqvae.py https://github.com/deepmind/sonnet/blob/master/sonnet/examples/vqvae_example.ipynb.

2 PixelCNN Family of Autoregressive Models

Deep autoregressive models are common probabilistic models that achieve state of the art results in density estimation across several data modalities . The main idea behind these models is to leverage the chain rule of probability to factorize the joint probability distribution over the input space into a product of conditional distributions for each dimension of the data given all the previous dimensions in some predefined order: pθ(x)=i=0npθ(xix<i)p_{\theta}({\mathbf{x}})=\prod_{i=0}^{n}p_{\theta}(x_{i}|{\mathbf{x}}_{<i}). Each conditional probability is parameterized by a deep neural network whose architecture is chosen according to the required inductive biases for the data.

Method

The proposed method follows a two-stage approach: first, we train a hierarchical VQ-VAE (see Fig. 2(a)) to encode images onto a discrete latent space, and then we fit a powerful PixelCNN prior over the discrete latent space induced by all the data.

As opposed to vanilla VQ-VAE, in this work we use a hierarchy of vector quantized codes to model large images. The main motivation behind this is to model local information, such as texture, separately from global information such as shape and geometry of objects. The prior model over each level can thus be tailored to capture the specific correlations that exist in that level. The structure of our multi-scale hierarchical encoder is illustrated in Fig. 2(a), with a top latent code which models global information, and a bottom latent code, conditioned on the top latent, responsible for representing local details (see Fig. 3). We note if we did not condition the bottom latent on the top latent, then the top latent would need to encode every detail from the pixels. We therefore allow each level in the hierarchy to separately depend on pixels, which encourages encoding complementary information in each latent map that can contribute to reducing the reconstruction error in the decoder. See algorithm 1 for more details.

For 256×256256\times 256 images, we use a two level latent hierarchy. As depicted in Fig. 2(a), the encoder network first transforms and downsamples the image by a factor of 44 to a 64×6464\times 64 representation which is quantized to our bottom level latent map. Another stack of residual blocks then further scales down the representations by a factor of two, yielding a top-level 32×3232\times 32 latent map after quantization. The decoder is similarly a feed-forward network that takes as input all levels of the quantized latent hierarchy. It consists of a few residual blocks followed by a number of strided transposed convolutions to upsample the representations back to the original image size.

2 Stage 2: Learning Priors over Latent Codes

In order to further compress the image, and to be able to sample from the model learned during stage 1, we learn a prior over the latent codes. Fitting prior distributions using neural networks from training data has become common practice, as it can significantly improve the performance of latent variable models . This procedure also reduces the gap between the marginal posterior and the prior. Thus, latent variables sampled from the learned prior at test time are close to what the decoder network has observed during training which results in more coherent outputs. From an information theoretic point of view, the process of fitting a prior to the learned posterior can be considered as lossless compression of the latent space by re-encoding the latent variables with a distribution that is a better approximation of their true distribution, and thus results in bit rates closer to Shannon’s entropy. Therefore the lower the gap between the true entropy and the negative log-likelihood of the learned prior, the more realistic image samples one can expect from decoding the latent samples.

In the VQ-VAE framework, this auxiliary prior is modeled with a powerful, autoregressive neural network such as PixelCNN in a post-hoc, second stage. The prior over the top latent map is responsible for structural global information. Thus, we equip it with multi-headed self-attention layers as in so it can benefit from a larger receptive field to capture correlations in spatial locations that are far apart in the image. In contrast, the conditional prior model for the bottom level over latents that encode local information will operate at a larger resolution. Using self-attention layers as in the top-level prior would not be practical due to memory constraints. For this prior over local information, we thus find that using large conditioning stacks (coming from the top prior) yields good performance (see Fig. 2(b)). The hierarchical factorization also allows us to train larger models: we train each prior separately, thereby leveraging all the available compute and memory on hardware accelerators. See algorithm 2 for more details.

Our top-level prior network models 32×3232\times 32 latent variables. The residual gated convolution layers of PixelCNN are interspersed with causal multi-headed attention every five layers. To regularize the model, we incorporate dropout after each residual block as well as dropout on the logits of each attention matrix. We found that adding deep residual networks consisting of 1×11\times 1 convolutions on top of the PixelCNN stack further improves likelihood without slowing down training or increasing memory footprint too much. Our bottom-level conditional prior operates on latents with 64×6464\times 64 spatial dimension. This is significantly more expensive in terms of required memory and computation cost. As argued before, the information encoded in this level of the hierarchy mostly corresponds to local features, which do not require large receptive fields as they are conditioned on the top-level prior. Therefore, we use a less powerful network with no attention layers. We also find that using a deep residual conditioning stack significantly helps at this level.

3 Trading off Diversity with Classifier Based Rejection Sampling

Unlike GANs, probabilistic models trained with the maximum likelihood objective are forced to model all of the training data distribution. This is because the MLE objective can be expressed as the forward KL-divergence between the data and model distributions, which would be driven to infinity if an example in the training data is assigned zero mass. While the coverage of all modes in the data distribution is an appealing property of these models, the task is considerably more difficult than adversarial modeling, since likelihood based models need to fit all the modes present in the data. Furthermore, ancestral sampling from autoregressive models can in practice induce errors that can accumulate over long sequences and result in samples with reduced quality. Recent GAN frameworks have proposed automated procedures for sample selection to trade-off diversity and quality. In this work, we also propose an automated method for trading off diversity and quality of samples based on the intuition that the closer our samples are to the true data manifold, the more likely they are classified to the correct class labels by a pre-trained classifier. Specifically, we use a classifier network that is trained on ImageNet to score samples from our model according to the probability the classifier assigns to the correct class.

Related Works

The foundation of our work is the VQ-VAE framework of . Our prior network is based on Gated PixelCNN augmented with self-attention , as proposed in .

BigGAN is currently state-of-the-art in FID and Inception scores, and produces high quality high-resolution images. The improvements in BigGAN come mostly from incorporating architectural advances such as self-attention, better stabilization methods, scaling up the model on TPUs and a mechanism to trade-off sample diversity with sample quality. In our work we also investigate how the addition of some of these elements, in particular self-attention and compute scale, indeed also improve the quality of samples of VQ-VAE models.

Recent work has also been proposed to generate high resolution images with likelihood based models include Subscale Pixel Networks of . Similar to the parallel multi-scale model introduced in , SPN imposes a partitioning on the spatial dimensions, but unlike , SPN does not make the corresponding independence assumptions, whereby it trades sampling speed with density estimation performance and sample quality.

Hierarchical latent variables have been proposed in e.g. . Specifically for VQ-VAE, uses a hierarchy of latent codes for modeling and generating music using a WaveNet decoder. The specifics of the encoding is however different from ours: in our work, the bottom levels of hierarchy do not exclusively refine the information encoded by the top level, but they extract complementary information at each level, as discussed in Sect. 3.1. Additionally, as we are using simple, feed-forward decoders and optimizing mean squared error in the pixels, our model does not suffer from, and thus needs no mitigation for, the hierarchy collapse problems detailed in . Concurrent to our work, extends for generating high-resolution images. The primary difference to our work is the use of autoregressive decoders in the pixel space. In contrast, for reasons detailed in Sect. 3, we use autoregressive models exclusively as priors in the compressed latent space, which simplifies the model and greatly improves sampling speed. Additionally, the same differences with outlined above also exist between our method and .

Improving sample quality by rejection sampling has been previously explored for GANs as well as for VAEs which combines a learned rejecting sampling proposal with the prior in order to reduce its gap with the aggregate posterior.

Experiments

Objective evaluation and comparison of generative models, specially across model families, remains a challenge . Current image generation models trade-off sample quality and diversity (or precision vs recall ). In this section, we present quantitative and qualitative results of our model trained on ImageNet 256×256256\times 256. Sample quality is indeed high and sharp, across several representative classes as can be seen in the class conditional samples provided in Fig. 5. In terms of diversity, we provide samples from our model juxtaposed with those of BigGAN-deep , the state of the art GAN model Samples are taken from BigGAN’s colab notebook in TensorFlow hub: https://tfhub.dev/deepmind/biggan-deep-256/1 in Fig. 5. As can be seen in these side-by-side comparisons, VQ-VAE is able to provide samples of comparable fidelity and higher diversity.

To further assess the effectiveness of our multi-scale approach for capturing extremely long range dependencies in the data, we train a three level hierarchical model over the FFHQ dataset at 1024×10241024\times 1024 resolution. This dataset consists of 70000 high-quality human portraits with a considerable diversity in gender, skin colour, age, poses and attires. Although modeling faces is generally considered less difficult compared to ImageNet, at such a high resolution there are also unique modeling challenges that can probe generative models in interesting ways. For example, the symmetries that exist in faces require models capable of capturing long range dependencies: a model with restricted receptive field may choose plausible colours for each eye separately, but can miss the strong correlation between the two eyes that lie several hundred pixels apart from one another, yielding samples with mismatching eye colours.

2 Quantitative Evaluation

In this section, we report the results of our quantitative evaluations based on several metrics aiming to measure the quality as well as diversity of our samples.

One of the chief motivations to use likelihood based generative models is that negative log likelihood (NLL) on the test and training sets give an objective measure for generalization and allow us to monitor for over-fitting. We emphasize that other commonly used performance metrics such as FID and Inception Score completely ignore the issue of generalization; a model that simply memorizes the training data can obtain a perfect score on these metrics. The same issue also applies to some recently proposed metrics such as Precision-Recall and Classification Accuracy Scores . These sample-based metrics only provide a proxy for the quality and diversity of samples, but are oblivious to generalization to held-out images.

The NLL values for our top and bottom priors, reported in Fig. 1, are close for training and validation, indicating that neither of these networks overfit. We note that these NLL values are only comparable between prior models that use the same pretrained VQ-VAE encoder and decoder.

2.2 Precision - Recall Metric

Precision and Recall metrics are proposed as an alternative to FID and Inception score for evaluating the performance of GANs . These metrics aim to explicitly quantify the trade off between coverage (recall) and quality (precision). We compare samples from our model to those obtained from BigGAN- deep using the improved version of precision-recall with the same procedure outlined in for all 1000 classes in ImageNet.

Fig. 7(b) shows the Precision-Recall results for VQ-VAE and BigGan with the classifier based rejection sampling (’critic’, see section 3.3) for various rejection rates and the BigGan-deep results for different levels of truncation. VQ-VAE results in slightly lower levels of precision, but higher values for recall.

3 Classification Accuracy Score

We also evaluate our method using the recently proposed Classification Accuracy Score (CAS) , which requires training an ImageNet classifier only on samples from the candidate model, but then evaluates its classification accuracy on real images from the test set, thus measuring sample quality and diversity. The result of our evaluation with this metric are reported in Table 2. In the case of VQ-VAE, the ImageNet classifier is only trained on samples, which lack high frequency signal, noise, etc. (due to compression). Evaluating the classifier on VQ-VAE reconstructions of the test images closes the “domain gap” and improves the CAS score without need for retraining the classifier.

The two most common metrics for comparing GANs are Inception Score and Fréchet Inception Distance (FID) . Although these metrics have several drawbacks and enhanced metrics such as the ones presented in the previous section may prove more useful, we report our results in Fig. 7(a). We use the classifier-based rejection sampling as a way of trading off diversity with quality (Section 3.3). For VQ-VAE this improves both IS and FID scores, with the FID going from roughly 30\sim 30 to 10\sim 10. For BigGan-deep the rejection sampling (referred to as critic) works better than the truncation method proposed in the BigGAN paper . We observe that the inception classifier is quite sensitive to the slight blurriness or other perturbations introduced in the VQ-VAE reconstructions, as shown by an FID 10\sim 10 instead of 2\sim 2 when simply compressing the originals. For this reason, we also compute the FID between VQ-VAE samples and the reconstructions (which we denote as FID*) showing that the inception network statistics are much closer to real images data than what the FID would otherwise suggest.

Conclusion

We propose a simple method for generating diverse high resolution images using VQ-VAE with a powerful autoregressive model as prior. Our encoder and decoder architectures are kept simple and light-weight as in the original VQ-VAE, with the only difference that we use a hierarchical multi-scale latent maps for increased resolution. The fidelity of our best class conditional samples are competitive with the state of the art Generative Adversarial Networks, with broader diversity in several classes, contrasting our method against the known limitations of GANs. Still, concrete measures of sample quality and diversity are in their infancy, and visual inspection is still necessary. Lastly, we believe our experiments vindicate autoregressive modeling in the latent space as a simple and effective objective for learning large scale generative models.

We would like to thank Suman Ravuri, Jeff Donahue, Sander Dieleman, Jeffrey Defauw, Danilo J. Rezende, Karen Simonyan and Andy Brock for their help and feedback.

References

Appendix A Architecture Details and Hyperparameters

A.2 VQ-VAE Encoder and Decoder

Appendix B Additional Samples

Please follow the following link to access the full version of our paper, rendered without lossy compression, which includes additional samples.

https://drive.google.com/file/d/1H2nr_Cu7OK18tRemsWn_6o5DGMNYentM/view?usp=sharing