{'fraction_non_alphanumeric': 0.030331134927177796, 'fraction_numerical': 0.006114317120087936, 'mean_word_length': 4.501322751322752, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
AVAE: Adversarial Variational Auto Encoder

Among the wide variety of image generative models, two models stand out: Variational Auto Encoders (VAE) and Generative Adversarial Networks (GAN). GANs can produce realistic images, but they suffer from mode collapse and do not provide simple ways to get the latent representation of an image. On the other hand, VAEs do not have these problems, but they often generate images less realistic than GANs. In this article, we explain that this lack of realism is partially due to a common underestimation of the natural image manifold dimensionality. To solve this issue we introduce a new framework that combines VAE and GAN in a novel and complementary way to produce an auto-encoding model that keeps VAEs properties while generating images of GAN-quality. We evaluate our approach both qualitatively and quantitatively on five image datasets.


Introduction
Since the original GAN paper [9], generative models have successfully leveraged the power of deep learning to generate complex data distribution with increasing fidelity. Generative models are now used for a wide variety of tasks, including notably sample generation but also photo manipulation [4], style transfer [33], pre-processing for face recognition [13], text to image translation [30] and controlled image generation [26].
In the literature, two families of generative models stand out for image data: Variational Auto Encoders (VAE) [16] and Generative Adversarial Networks (GAN) [9], each exhibiting respective advantages and limitations. GANs usually produce more realistic images [3,14] but they are notoriously difficult to train and suffer from mode collapse [24]. Moreover, when using GANs, there is no trivial way to get the latent representation of an image, limiting their use. In contrast, VAE models do not share these problems but the images they generate suffer from a lack of realism. It is often explained by the use of inappropriate reconstruction errors. Some previous works [2,7,8] have proposed solutions to solve these problems by combining or modifying these two frameworks. However, these methods exhibit a trade-off between the realism of the generated images and the fidelity of the reconstructions. In this paper, we show that GANs and VAEs can be complementary in the sense that we can derive two complementary losses from them. From this observation, we propose the AVAE model which is a VAE style model to produce samples of comparable quality as those generated by a GAN while allowing high fidelity reconstructions when used as an auto-encoder. In comparison to [2] who first introduces the idea of a combination of the two frameworks, we provide theoretical insights to show the pertinence of our approach and we address the problem of the trade-off between realism and reconstruction accuracy.
The paper is organized as follows. We begin with a reminder of GAN and VAE frameworks and explain their limitations. Then we investigate how they can be combined effectively. We thus propose an effective approach to do so, named AVAE. At last, we present a qualitative and quantitative evaluation of the performance of our model on a variety of image datasets comparing it with the state of the art. We also show that our method scales well to high resolution images.

Variational Auto Encoders
VAE [16] is a framework to learn deep latent variable models. It assumes that observed data X result from random variables z ∼ p(z) in a latent space Z such that it exists a deterministic function f : (z, ) → x, being a stochastic noise. The probability of observing x knowing z is estimated by a decoder model p θ d : z → p θ d (x|z) parametrized by θ d and on the contrary, the probability that z is the latent source of x is estimated by a encoder model q θe : x → q θe (z|x) parametrized by θ e . To estimate the parameters of the generative model of the data X = (x (1) , ..., x (N ) ) with N the number of observed samples, we maximize the log likelihood of the observations: log [16] proposes to maximize a tractable lower bound, leading to the following loss to train the VAE: with p θ d usually chosen as a Gaussian distribution N (x; µ θ d (z), Id) and KL the Kullback-Leibler divergence. Hence, the term interpreted as a reconstruction error and is estimated by Monte-Carlo method (usually with a single sample), and the term L P = KL ( q θe (z|x) p(z)) forces the distribution of the latent space to match the prior p(z). Usually, p(z) is a standard Gaussian distribution N (z; 0, Id)). The L P term acts as an information bottleneck on the latent produced by the encoder. Indeed: with I the mutual information between x and z. This term thus limits the amount of information about the original image that goes through the latent code and pushes the distribution of the latent code produced by the encoder to match the prior latent code distribution.

Limitations of the VAE framework
Understanding and improving VAE are active subjects of research. Some works have focused on reducing the gap in quality which often exists between reconstructions produced by VAEs and images sampled with them [6]. Others have aimed at learning more interpretable latent space structure [17]. While dealing with interesting issues, these papers are not in line with the problem tackled in this paper related to the lack or realism and the blurry aspect of images generated or reconstructed with VAEs. As we have seen, L P acts as an information bottleneck which limits the information about the original image x that passes through the latent code. This creates an uncertainty on the attributes plausible reconstructions E optimal reconstruction Figure 1: Illustration on why VAEs produce blurry reconstructions. Consider the example of a binary frontier in an image i and a latent code z which corresponds to the position of the frontier x front . If q θe (z|i) = N (x front , σ) then p θe (x front |z) = N (z, σ) and the optimal reconstruction of the which is a smooth transition between black and white instead of a sharp transition in the original binary image.
of the original image x when trying to reconstruct it. This uncertainty combined with the use of the mean square error as a reconstruction error causes the generated images µ θ d (z) to be blurry. Indeed under those circumstances, the optimal value for each pixel of the reconstructed image is its expected value given the information available in the latent code [23] (See Figure 1 for an illustration).
The second aspect that prevents VAE and AE in general to produce realistic samples is the use of a pixel-wise reconstruction error combined with the high dimensionality of the natural image manifold. Indeed, it is often assumed that natural images lie on a low dimensional manifold of image space, in particular because of a strong redundancy at a local scale [18]. This point is globally asserted by empirical evidence [28] but can be mitigated with regard to textures. We argue that textures like wood, hair or waves of the ocean are living in a much higher dimensional manifold. This manifold thus cannot be captured in the low dimensional latent space of generative models even in the absence of an explicit information bottleneck. Indeed, it would require a network with a very high capacity to map the low dimensional latent into a high dimensional manifold. One can convince himself of this fact by considering that hair configuration is the product of the configuration of each individual strand of hair. GANs can partially overcome this problem with mode collapse on textures by generating only a subset of this manifold which is enough to fool the discriminator network. However, the use of a powerful pixel-wise reconstruction error in the case of VAE prevents the decoder from using this strategy leading to unrealistic results.

Generative Adversarial Networks
GAN globally consists in training two neural networks with adversarial objectives to generate samples indistinguishable from the samples taken from the dataset. The generator network parametrized by θ g is trained to map a random vector to the data space. The discriminator or critic network parametrized by θ c is a classifier that is trained to distinguish real samples from generated ones. The key point is that the generator does not have access to real data and can only improve its parameters through its ability to fool the discriminator. The objective of the critic is: while the generator tries to fool the critic by minimizing:

Limitations of the GAN framework
GANs have proven to be very successful for generation tasks but suffer from two major limitations in comparison to VAEs: mode collapse and the absence of an encoder network. Mode collapse occurs when, at each step, the generator is able to only produce a few different samples. In its extreme case, the generator only produces one type of sample, that is thus easily recognized by the discriminator. In return, the discriminator does not need real data to train and its feedback to the generator through back-propagation does no longer contain useful information. More commonly, the generator produces a limited number of samples and interpolation of them. Even when a GAN appears to have attained a good solution, mode collapse may have occurred slightly and some modes of the data distribution may be missed by the generator. Mode collapse also raises the question of the existence of an acceptable pseudo-inverse mapping of the generator defined on the entire dataset space. The second issue is that the GAN framework does not provide an explicit model to find the latent space fibers of samples as it does not have an encoder.

Related Works
To leverage both the advantages of GANs and VAEs, [2] proposed the VAE/GAN architecture which combines them. They propose to add a discriminator to push reconstructions from the VAE toward more realism and replaced the standard reconstruction error by a perceptual similarity metric based on the filters learned by the discriminator. This approach is problematic because the discriminator is trained to predict whether an image is a real one or a fake one. Thus, the features extracted from it may not be adapted to describe image content making them a disputable choice to base a similarity metric on. As an example, we noticed that VAE/GAN sometimes fails to reconstruct precisely skin color on the CelebA dataset (see Figure 7) as this information might be useless to some extent for the discriminator. If carefully tuned, this approach tends to work well in practice and allows sharper reconstructions. Nevertheless, [8] pointed out that this approach also tends to exhibit a compromise between VAE and GAN and produces less realistic samples than GAN. They propose the BiGAN architecture [7] which is composed of an encoder that transforms real images into latent codes, a generator that transforms latent codes sampled randomly into images and a discriminator which tries to guess the origin of a couple of image/latent. While this approach is very elegant and produces samples of the same quality as GANs, it is aimed at finding good feature representations in an unsupervised way and often fails to produce very accurate reconstructions. In [5] and [21], the authors propose variations of the BiGAN framework and additional theoretical insights about the latter. They produce more accurate reconstructions in terms of MSE but they are blurry (no hair texture when trained on faces images) which is precisely the issue we aim at solving here. In [4], the authors propose a variation of the VAE/GAN framework where the encoder and the discriminator network are a unique model. While it is not clear why this choice is a good one or not, the model reconstruction loss is the combination between a pixel-wise error and the VAE/GAN reconstruction loss which introduces a compromise between the blurriness of the reconstructions and the features reconstruction fidelity. Similarly, [12] have proposed an elegant framework where the discrimination is made on the latent space. Our approach introduces a reconstruction loss that does not interfere with the realism of the images while being linked with the MSE. By combining our reconstruction loss with adversarial training, we are able to produce photo-realistic reconstructions with no compromise on fidelity. Moreover, our framework is theoretically grounded and is not limited to image data as we show on a toy example (Section 5.1) that it can be used in a more general context.
A recent work published at ECCV 2020 proposed an architecture very similar to ours [20], but differs from our work on several crucial points. First, the reconstruction loss at the core of our contribution is different, due to the theoretical aspects developed in the following. We were primarily interested in the theoretical aspects behind the realism of generated images while their work focuses more on the disentangled properties of the framework. Our evaluation method also differs on the choice of datasets and metrics. Overall, we believe that our works complement each other well. 4 The AVAE framework 4

.1 Complementarity between VAE and GAN
Despite their differences, we show that VAE and GAN exhibit some form of complementarity and that we can build a hybrid approach that solves several problems listed above. One naive hybridization could be to train a VAE with an additional adversarial loss term to push reconstructions toward more realism. However, as we have seen, optimal reconstructions are not always realistic. This approach would lead to choosing a trade-off between reconstruction accuracy and realism as both have conflicting objectives. One of the contributions of this paper is to show that we can derive two complementary losses from the VAE and GAN frameworks which share an optimal solution allowing accurate and realistic reconstructions. In the GAN framework, we can derive a manifold loss L M from the discriminator network which judges the realism of a given sample. This loss can be interpreted as a "distance" between the data manifold and a sample as described in [32]. In the VAE framework, we train an encoder which maps data in a latent space Z. This latent space can be seen as a map of the data manifold. Distances in the latent space can be interpreted as a distance between two points of the data manifold. This loss is noted L Z . Our intuition, depicted by Figure 2, is that these two losses can be used in conjunction to train a model which produces realistic images while keeping approximately the latent space organization of a VAE.
We give here further explanation on why the VAE framework fails to produce realistic images and what conditions a reconstruction error should satisfy to achieve accurate and realistic reconstructions. Let us consider an auto encoder that uses a reconstruction error of the form L (x, y) = x − y 2 . Let us note x the input, z the output of the encoder E θe andx the output of the decoder D θ d . With the parameters of the encoder fixed, the optimal reconstruction should minimize the expected cost over the potential imagesx that could have produced the observed z.
Thus the optimal solution is given byx * (z) = Ex ∼p θe (x|z) [x]. The problem is that, in this case the optimal reconstructionx * is the expected value of all the possible reconstructions given the knowledge of the latent code. It leads to a blurry reconstruction, quite unlikely under the data distribution p D (i.e. p D (x * ) is small).
In a more general setting we can consider objectives of the form: L(x, x) = ||f (x) − g(x)|| 2 where f is an arbitrary differentiable function and g is a more general stochastic function. In this case, the optimal solution verifies: This objective has a common optimum with the GAN objective, if and only if we have p(f (x * (z))) = p(f (x)) for z ∼ p(z) and x ∼ p D (x). However, to be what we can call a good reconstruction error, f and g should also carry the maximum of information about their input and be close to each other to make the loss able to discriminate between accurate and not accurate reconstructions.

Architecture
Similarly to VAE, the proposed AVAE framework is based on an encoder E θe and a decoder D θ d . We add two additional models: a generator G θg and a critic C θc . The role of the generator is to produce realistic samples from latent codes. The VAE part of our framework is similar to classical VAE: it is a parametrized model q θe (z|x) = N (z; µ θe (x), Σ θe ) with Σ θe a diagonal matrix of the form diag(σ 2 θe ). The prior distribution of the latent codes is p(z) = N (z; 0, Id) and p θ d (x|z) = N (x; µ θ d (z), Id). With such choices, O VAE (θ e , θ d ; x) can be estimated by a Monte-Carlo method. Indeed, the Kullback-Leibler divergence term of the loss KL (q θe (z|x) p(z)) is equal to: The reconstruction term of the loss E q θe (z|x) [log p θ d (x|z)] can be estimated by Monte-Carlo, sampling z from q θe (z|x) and noting that: z being sampled from q θe (z|x), the loss of the VAE for one sample is the following (without constant terms): For the generator part, when we want to use it for reconstruction, we build its input by concatenating z the latent code produced by the encoder with a random vector ξ sampled from N (0, Id) to form the latent code for our generator. z encodes the information captured by the encoder while ξ encode the variation not captured by it. With this choices, we sample from p θg (x|z) by taking x = G θg (z, ξ). Note that ξ can be removed if we consider that for a given z there is only one possible reconstruction but we present here the general setting as we consider. To sample a random image from the generator we simply sample z from the prior distribution defined in the VAE part and ξ from N (0, Id). Ideally, the generator should invert the encoder and thus p θg (x|z) should be as close as possible than p θe (x|z). This consideration leads us to minimizing the following negative log likelihood with z ∼ N (0, Id) and x ∼ p θg (x|z) : Figure 3: Summary of our Adversarial Variational Auto Encoder framework. E θe , D θ d , G θg , C θc are respectively the encoder, decoder, generator and critic (discriminator). Note that the weights of the encoder E θe are shared between the two architectures. Images are denoted by the letter x and latent codes by the letter z.
with H θg the differential entropy of the distribution p θg (x). The term log p θe (z|x) can be computed directly: log p θe (z|x) = log N (z; µ θe (x), Σ θe ) We define the reconstruction loss L Z by removing constant terms in Equation 11: We can estimate the second term by training a classifier C that discriminates generated images from real ones by minimizing the cross-entropy: Under this loss, the optimal solution for C is: L M is then defined by sampling x from p θg (x). Hence: Indeed, logit C ≈ logit C * = log which is an unbiased estimator of the Kullback-Leibler divergence term. Minimizing the differential entropy H θg of the distribution p θg (x) will push it to Initialize parameters of the models: θ e , θ d , θ g , θ c while training do {Forward pass.} x real ← batch of images sampled from the dataset.
{Compute losses gradients and update parameters. be as peaked as possible and is not data dependent. Moreover, this term is intractable. Hence, as a form of regularization, we remove it. One problem still remains. Indeed the optimal reconstruction for L a Z verifies the following equation: µ θe (x * (z)) = z and thus p(µ θe (x * (z))) = N (µ θe (x * (z)); 0, I) while p(µ θe (x)) = N (µ θe (x); 0, I − Σ). To solve this problem, we propose to replace the expression of L a Z by: With this loss the optimal solutionx * (z) verifies µ θe (x * (z)) = 1 − σ 2 θe z thus p(µ θe (x * (z))) = N (µ θe (x); 0, I − Σ) = p(µ θe (x)) as we have seen, its ensure that this loss has a common optimum with the GAN objective. This new loss takes into account the fact that when σ θe is large, the observed z is mostly noise and µ θe (x) is close to zero. The loss resulting from these considerations is L G = L b Z + L M . It combines a GAN type loss L M and a reconstruction loss on the latent codes L Z which is similar to that described in Section 4.1. The AVAE framework is globally presented in Figure 3, with the relations between its components, and Figure 4.2 gives the algorithm to train it. From a GAN perspective, the method can be viewed as constraining the latent space organization of the generator with the encoder model. It thus limits to some point the problem of mode collapse as the reconstruction error on the latent code prevents the generator to produce similar samples. As a consequence, it counteracts the mechanism pointed out by [24] to explain mode collapse by pushing generated samples apart from each other. The proposed architecture differs from VAE/GAN on several important aspects. The decoder and generator are separated in our work and our reconstruction error is based on the encoder model and not on the discriminator as in VAE/GAN to ensure that the error is informative about the image content.
Implementation details: all the low resolution experiments have been conducted with Tensorflow 2.0 [1] on an NVIDIA GTX 1080 Ti GPU with 11Go of memory. Full code will be available on github. All models share similar architecture blocks, inspired by [27], to allow a fair comparison. Architecture details are presented in Figure 5. Each model is trained with hyper-parameters recommended in [27] for 5e4 iterations with a batch size of 64. Because the reconstruction loss of the VAE part of VAE/GAN is a perceptual loss which differs from the MSE used in our model and in   (5) and use 'same' padding. σ z is chosen independent of x and is learned directly. w is a width multiplier (we typically use w = 128). For the BiGAN implementation, we use a two-hidden-layer MLP for the latent code inputs and a critic-style architecture for the image inputs. The two outputs representations are then concatenated and used as input of a two-hidden-layers MLP.
the classical VAE, the balance between the Kullback-Leibler divergence term and the reconstruction term in the VAE loss is not the same between models. We observed that the Kullback-Leibler divergence term is usually much higher for the VAE/GAN model which indicates that it conveys much more information in its latent code and thus introduces a bias in the reconstruction performance comparison between models. To solve this problem, we introduced a hyper-parameter β to weight the Kullback-Leibler divergence in the encoder loss as in [11] in order to get similar Kullback-Leibler divergences. This hyper-parameter search leads us to the following (β LSUN bedroom = 4, β celeba = 5, β CIFAR10 = 10, β CIFAR100 = 10, β SVHN = 20). The high resolution experiment was conducted with a network architecture derived from the StyleGAN V2 architecture [15] trained on 8 NVIDIA Quadro P5000 GPUs.

Toy dataset
We begin by testing our approach on a toy dataset to validate the theory. The dataset is composed of 2D points generated from two generative factors z 1 and z 2 . The data generation procedure is the following: z 1 , z 2 , ∼ N (0, 1) and x = f (z 1 , z 2 , ) = (3z 1 + 0.1 , cos(3z 1 ) + tanh(3z 2 ) + 0.1 ). For the model, we use a latent space of dimension one to simulate the problem of the low dimensionality of the latent space compared to the high dimensionality of the data manifold. Models are two-hiddenlayer perceptrons with 128 units. Models are trained with the method described proposed in this paper. We then draw the manifold of the generated points to see how the model behave compared to a VAE. Results of this experiment can be seen in Figure 6 where we can see that reconstructions from the VAE are in a region of low likelihood of the data distribution while AVAE reconstructions follow the shape of the VAE manifold while covering regions of higher likelihood. It shows that our model is able to produce realistic reconstructions even when the latent code do not contain all the information needed to reconstruct the original image perfectly. Here there is an ambiguity as we do not know if the original sample is from the top distribution or the bottom one given a latent code corresponds to two. In order to produce a realistic result the generator has to make an arbitrary choice. Our approach allows the generator to make such choice while the decoder from the VAE outputs the average of possible choices resulting in an unlikely/unrealistic reconstruction. On the same Figure we can see that when using a stochastic generator with additional latent variables, it learns to generate missing regions of the data distribution while keeping the VAE latent space structure.

Qualitative results
Here, we present some qualitative results on the CelebA SVHN and LSUN bedroom datasets. A comparison of samples reconstruction between our model and other models is presented in Figure 7.
We also present a visual comparison of samples generated by our model and other generative models in Figure 8. Additional qualitative results will be available on github. We can see on these figures that generated images are of comparable quality of GAN generated images for both generation and reconstructions. VAE reconstructions and generated samples look blurry, BiGAN generated images are of good quality but reconstructions are not accurate. VAE/GAN produces both good reconstructions and generated samples. However, while our judgment is subjective, we find that reconstructions produced by VAE/GAN are less accurate than ours and images are less realistic than with GAN, BiGAN or our approach. One may notice that for the LSUN bedroom dataset, reconstructions produced by our model are not convincing. However, we can explain this by the very poor performance of the VAE suggesting that not enough information passes through the latent code to create a reconstruction visually close to the original image. However, even here, our model still produces sharp images close to the target ones in terms of MSE showing that our model follows the latent structure of the VAE trained with the MSE as a reconstruction error.
We also conducted an experiment on higher resolution images (256x256 FFHQ face images) to see if our method can be scaled to high resolution images. To conduct this experiment, we made straightforward modifications to the style GAN V2 [15] using the approach proposed here. Results of this experiments are presented in Figure 9. These results confirm the scalability of the proposed approach to bigger architectures.

Quantitative results
To quantitatively evaluate the performance of our method, we selected several metrics. The quality of the reconstructed images is evaluated by the Mean Squared Error or MSE and the LPIPS [31].
We use the FID [10] to measure the realism of generated images. A comparison between VAE, GAN, BiGAN [8,7], VAE/GAN [2], and our model is presented in Table 1. Reconstructions errors are computed on validation images not used during training, namely the test or validation splits of TensorFlow datasets. FID is computed over 50000 randomly generated samples and compared to training data samples as FID requires a lot of samples to be calibrated. It must be noted that some metrics are biased toward some architectures: the MSE is favorable to the VAE model because it is the loss used to train it. It is also the case for our approach, as information contained in the latent code is optimized to produce accurate reconstructions in terms of MSE. VAE/GAN is also advantaged in terms of LPIPS and FID as this model uses a perceptual similarity metric based on a classifier as a reconstruction error and the FID and LPIPS are also based on deep features. Globally, our model exhibits a good compromise between accurate reconstructions (MSE and LPIPS) and realism (FID), thus combining the best of VAE and GAN.

Discussion
The proposed framework can be used to generate images from a pre-trained representation. Thus, it is not a feature learning method and only features learned by the VAE are described by the representation. However, while we focused on a VAE architecture to produce the latent representation, our approach can be further extended. Indeed one could for example train a classifier while constraining its last feature layer in the same way the latent code is constrained and use it as a latent code in our method in order to focus on different features of the image. One could even concatenate several of these representation to train a model which fits their needs. We keep this extension as a potential future work.  : Qualitative results on high resolution images. left to right: original images, reconstructions with the VAE decoder, reconstructions with the generator. This figure shows that with a limited amount of information the decoder fails to produce realistic reconstruction while our generator is capable of it. Note that the fidelity of the reconstruction is ultimately limited by the information contained in the latent code produced by the encoder.