Towards a better understanding of Vector Quantized Autoencoders
Year: 2018

Abstract:
Deep neural networks with discrete latent variables offer the promise of better symbolic reasoning, and learning abstractions that are more useful to new tasks. There has been a surge in interest in discrete latent variable models, however, despite several recent improvements, the training of discrete latent variable models has remained challenging and their performance has mostly failed to match their continuous counterparts. Recent work on vector quantized autoencoders (VQ-VAE) has made substantial progress in this direction, with its perplexity almost matching that of a VAE on datasets such as CIFAR-10. In this work, we investigate an alternate training technique for VQ-VAE, inspired by its connection to the Expectation Maximization (EM) algorithm. Training the discrete autoencoder with EM and combining it with sequence level knowledge distillation alows us to develop a nonautoregressive machine translation model whose accuracy almost matches a strong greedy autoregressive baseline Transformer, while being 3.3 times faster at inference.

heading: 1 Introduction
text: Unsupervised learning of meaningful representations is a fundamental problem in machine learning since obtaining labeled data can often be very expensive. Continuous representations have largely been the workhorse of unsupervised deep learning models of images (Goodfellow et al., 2014; van den Oord et al., 2016; Kingma et al., 2016; Salimans et al., 2017; Parmar et al., 2018), audio (Van Den Oord et al., 2016; Reed et al., 2017), and video (Kalchbrenner et al., 2016). However, it is often the case that datasets are more naturally modeled as a sequence of discrete symbols rather than continuous ones. For example, language and speech are inherently discrete in nature and images are often concisely described by language, see e.g., Vinyals et al. (2015). Improved discrete latent variable models could also prove useful for learning novel data compression algorithms (Theis et al., 2017), while having far more interpretable representations of the data.
We build on Vector Quantized Variational Autoencoder (VQ-VAE) (van den Oord et al., 2017), a recently proposed training technique for learning discrete latent variables. The method uses a learned code-book combined with nearest neighbor search to train the discrete latent variable model. The nearest neighbor search is performed between the encoder output and the embedding of the latent code using the `2 distance metric. VQ-VAE adopts the standard latent variable model generative process, first sampling latent codes from a prior, P (z), which are then consumed by the decoder to generate data from P (x | z). In van den Oord et al. (2017), the authors use both uniform and autoregressive priors for P (z). The resulting discrete autoencoder obtains impressive results on unconditional image, speech, and video generation. In particular, on image generation, VQ-VAE was shown to perform almost on par with continuous VAEs on datasets such as CIFAR-10 (van den Oord et al., 2017). An extension of this method to conditional supervised generation, out-performs continuous autoencoders on WMT English-German translation task (Kaiser et al., 2018).
The work of Kaiser et al. (2018) introduced the Latent Transformer, which set a new stateof-the-art in non-autoregressive Neural Machine Translation. However, additional training heuristics, namely, exponential moving averages (EMA) of cluster assignment counts, and
product quantization (Norouzi & Fleet, 2013) were essential to achieve competitive results with VQ-VAE. In this work, we show that tuning for the code-book size can significantly outperform the results presented in Kaiser et al. (2018). We also exploit VQ-VAE’s connection with the expectation maximization (EM) algorithm (Dempster et al., 1977), yielding additional improvements. With both improvements, we achieve a BLEU score of 22.4 on English to German translation, outperforming Kaiser et al. (2018) by 2.6 BLEU. Knowledge distillation (Hinton et al., 2015; Kim & Rush, 2016) provides significant gains with our best models and EM, achieving 26.7 BLEU, which almost matches the autoregressive transformer model with no beam search at 27.0 BLEU, while being 3.3× faster. Our contributions can be summarized as follows:
1. We show that VQ-VAE from van den Oord et al. (2017) can outperform previous state-of-the-art without product quantization.
2. Inspired by the EM algorithm, we introduce a new training algorithm for training discrete variational autoencoders, that outperforms the previous best result with discrete latent autoencoders for neural machine translation.
3. Using EM training, and combining it sequence level knowledge distillation (Hinton et al., 2015; Kim & Rush, 2016), allows us to develop a non-autoregressive machine translation model whose accuracy almost matches a strong greedy autoregressive baseline Transformer, while being 3.3 times faster at inference.
4. On the larger English-French dataset, we show that denoising discrete autoencoders gives us a significant improvement (1.0 BLEU) on top of our non-autoregressive baseline (see Section D).

heading: 2 VQ-VAE and the Hard EM Algorithm
text: The connection between K-means, and hard EM, or the Viterbi EM algorithm is well known (Bottou & Bengio, 1995), where the former can be seen a special case of hard-EM style algorithm with a mixture-of-Gaussians model with identity covariance and uniform prior over cluster probabilities. In the following sections we briefly explain the VQ-VAE discrete autoencoder for completeness and it’s connection to classical EM.

heading: 2.1 VQ-VAE discretization algorithm
text: VQ-VAE models the joint distribution PΘ(x, z) where Θ are the model parameters, x is the data point and z is the sequence of discrete latent variables or codes. Each position in the encoded sequence has its own set of latent codes. Given a data point, the discrete latent code in each position is selected independently using the encoder output. For simplicity, we describe the procedure for selecting the discrete latent code (zi) in one position given the data point (xi). The encoder output ze(xi) ∈ RD is passed through a discretization bottleneck using a nearest-neighbor lookup on embedding vectors e ∈ RK×D. Here K is the number of latent codes (in a particular position of the discrete latent sequence) in the model. More specifically, the discrete latent variable assignment is given by,
zi = arg min j∈[K] ‖ze(xi)− ej‖2 (1)
The selected latent variable’s embedding is passed as input to the decoder,
zq(xi) = ezi
The model is trained to minimize:
L = lr + β ‖ze(xi)− sg (zq(xi))‖2 , (2) where lr is the reconstruction loss of the decoder given zq(x) (e.g., the cross entropy loss), and, sg (.) is the stop gradient operator defined as follows:
sg (x) = { x forward pass 0 backward pass
To train the embedding vectors e ∈ RK×D, van den Oord et al. (2017) proposed using a gradient based loss function
‖sg (ze(xi))− zq(xi)‖2 , (3)
and also suggested an alternate technique of training the embeddings: by maintaining an exponential moving average (EMA) of all the encoder hidden states that get assigned to it. It was observed in Kaiser et al. (2018) that the EMA update for training the code-book embedding, results in more stable training than using gradient-based methods. We analyze this in more detail in Section 5.1.1.
Specifically, an exponential moving average is maintained over the following two quantities: 1) the embeddings ej for every j ∈ [1, . . . ,K] and, 2) the count cj measuring the number of encoder hidden states that have ej as it’s nearest neighbor. The counts are updated in a mini-batch of targets as:
cj ← λcj + (1− λ) ∑ i 1 [zq(xi) = ej ] , (4)
with the embedding ej being subsequently updated as:
ej ← λej + (1− λ) ∑ i 1 [zq(xi) = ej ] ze(xi) cj , (5)
where 1[.] is the indicator function and λ is a decay parameter which we set to 0.999 in our experiments. This amounts to doing stochastic gradient in the space of both code-book embeddings and cluster assignments. These techniques have also been successfully used in minibatch K-means (Sculley, 2010) and online EM (Liang & Klein, 2009; Sato & Ishii, 2000).
The generative process for our latent variable NMT model, P (y, z | x), begins by autoregressively sampling a sequence of discrete latent codes from a model conditioned on the input x,
P (z | x) = |z|∏ i=1 P ( zi | z1,...,(i−1), x ) , (6)
which we refer to as the Latent Predictor model (Kaiser et al., 2018). The decoder then consumes this sequence of discrete latent variables to generate the target y all at once, where
P (y | z, x) = |y|∏ j=1 P (yj | z, x). (7)
The autoregressive learned prior prior is fit on the discrete latent variables produced by the autoencoder. Our goal is to learn a sequence of latents, that is much shorter than the targets, |z| |y|, thereby speeding up decoding significantly with no loss in accuracy. The architecture of the encoder, the decoder, and the latent predictor model are described in further detail in Section 5.
2.2 Hard EM and the K-means algorithm
In this section we briefly recall the hard Expectation maximization (EM) algorithm (Dempster et al., 1977). Given a set of data points (x1, . . . , xN ), the hard EM algorithm approximately solves the following optimization problem:
Θ∗ = arg max Θ max z1,...,zN PΘ(x1, . . . , xN , z1, . . . , zN ), (8)
Hard EM performs coordinate descent over the following two coordinates: the model parameters Θ, and the hidden variables z1, . . . , zN . In other words, hard EM consists of repeating the following two steps until convergence:
1. E step: (z1, . . . , zN )← arg maxz1,...,zN PΘ(x1, . . . , xN , z1, . . . , zN ),
2. M step: Θ← arg maxΘ PΘ(x1, . . . , xN , z1, . . . , zN )
A special case of the hard EM algorithm is K-means clustering (MacQueen et al., 1967; Bottou & Bengio, 1995) where the likelihood is modelled by a Gaussian with identity covariance matrix. Here, the means of the K Gaussians are the parameters to be estimated,
Θ = 〈µ1, . . . , µK〉, µk ∈ RD.
With a uniform prior over the hidden variables (PΘ(zi) = 1K ), the marginal is given by PΘ(xi | zi) = N (µzi , I)(xi). In this case, equation (8) is equivalent to:
( µ1, . . . , µK )∗ = arg max
µ1,...,µK min z1,...,zN N∑ i=1 ‖µzi − xi‖22 (9)
Note that optimizing equation (9) is NP-hard, however one can find a local optima by applying coordinate descent until convergence:
1. E step: Cluster assignment is given by,
zi ← arg min j∈[K] ∥∥µj − xi∥∥22 , (10) 2. M step: The means of the clusters are updated as,
cj ← N∑ i=1 1[zi = j]; µ j ← 1 cj N∑ i=1 1[zi = j]xi. (11)
We can now easily see the connections between the training updates of VQ-VAE and K-means clustering. The encoder output ze(x) ∈ RD corresponds to the data point while the discrete latent variables corresponds to clusters. Given this, Equation 1 is equivalent to the E-step (Equation 10) and the EMA updates in Equation 4 and Equation 5 converge to the M-step (Equation 11) in the limit. The M-step in K-means overwrites the old values while the EMA updates interpolate between the old values and the M step update.

heading: 3 VQ-VAE training with EM
text: In this section, we investigate a new training strategy for VQ-VAE using the EM algorithm.

heading: 3.1 Expectation Maximization
text: First, we briefly describe the EM algorithm. While the hard EM procedure selects one cluster or latent variable assignment for a data point, here the data point is assigned to a mixture of clusters. Now, the optimization objective is given by,
Θ∗ = arg max Θ PΘ(x1, . . . , xN )
= arg max Θ ∑ z1,...,zN PΘ(x1, . . . , xN , z1, . . . , zN )
Coordinate descent algorithm is again used to approximately solve the above optimization algorithm. The E and M step are given by:
1. E step:
ρ(zi)← PΘ(zi | xi), (12)
2. M step:
Θ← arg max Θ Ezi∼ρ[logPΘ(xi, zi)] (13)

heading: 3.2 Vector Quantized Autoencoders trained with EM
text: Now, we describe vector quantized autoencoders training using the EM algorithm. As discussed in the previous section, the encoder output ze(x) ∈ RD corresponds to the data point while the discrete latent variables corresponds to clusters. The E step instead of hard assignment now produces a probability distribution over the set of discrete latent variables (Equation 12). Following VQ-VAE, we continue to assume a uniform prior over clusters, since we observe that training the cluster priors seemed to cause the cluster assignments to collapse to only a few clusters. The probability distribution is modeled as a Gaussian with identity covariance matrix,
PΘ(zi | ze(xi)) ∝ e−‖ezi−ze(xi)‖ 2 2
As an alternative to computing the full expectation term in the M step (Equation 13) we perform Monte-Carlo Expectation Maximization (Wei & Tanner, 1990) by drawing m samples z1i , · · · , zmi ∼ Multinomial ( −‖e1 − ze(xi)‖22 , . . . ,−‖eK − ze(xi)‖ 2 2 ) , where
Multinomial(l1, . . . , lK) refers to the K-way multinomial distribution with logits l1, . . . , lK . This results in a less diffuse target for the autoregressive prior. Thus, the E step can be finally written as:
E step: z1i , . . . , z m i ← Multinomial ( −‖e1 − ze(xi)‖22 , . . . ,−‖eK − ze(xi)‖ 2 2 ) The model parameters Θ are then updated to maximize this Monte-Carlo estimate in the M step given by
M step: cj ← 1
m N∑ i=1 m∑ l=1 1 [ zli = j ] ; ej ← 1 mcj N∑ i=1 m∑ l=1 1 [ zli = j ] ze(xi).
Instead of exactly following the above M step update, we use the EMA version of this update similar to the one described in Section 2.1.
When sending the embedding of the discrete latent to the decoder, instead of sending the posterior mode, argmaxzP (z | x), similar to hard EM and K-means, we send the average of the embeddings of the sampled latents:
zq(xi) = 1
m m∑ l=1 ezli . (14)
Since m latent code embeddings are sent to the decoder in the forward pass, all of them are updated in the backward pass for a single training example. In hard EM training, only one of them is updated during training. Sending averaged embeddings also results in more stable training using the EM algorithm compared to VQ-VAE as shown in Section 5.
To train the latent predictor model (Section 2.1) in this case, we use an approach similar to label smoothing (Pereyra et al., 2017): the latent predictor model is trained to minimize the cross entropy loss with the labels being the average of the one-hot labels of z1i , . . . , zmi .

heading: 4 Other Related Work
text: Variational autoencoders were first introduced by Kingma & Welling (2014) for training continuous representations; unfortunately, training them for discrete latent variable models has proved challenging. One promising approach has been to use various gradient estimators for discrete latent variable models, starting with the REINFORCE estimator of Williams (1992), an unbiased, high-variance gradient estimator. Subsequent work on improving the variance of the REINFORCE estimator are REBAR (Tucker et al., 2017) and RELAX (Grathwohl et al., 2017). An alternate approach towards gradient estimators is to use continuous relaxations of categorical distributions, for e.g., the Gumbel-Softmax reparametrization trick (Jang et al.,
2016; Maddison et al., 2016). These methods provide biased but low variance gradients for training.
Machine translation using deep neural networks have been shown to achieve impressive results (Sutskever et al., 2014; Bahdanau et al., 2014; Cho et al., 2014; Vaswani et al., 2017). The state-of-the-art models in Neural Machine Translation are all auto-regressive, which means that during decoding, the model consumes all previously generated tokens to predict the next one. Recently, there have been multiple efforts to speed-up machine translation decoding. Gu et al. (2017) attempts to address this issue by using the Transformer model (Vaswani et al., 2017) together with the REINFORCE algorithm (Williams, 1992), to model the fertilities of words. The main drawback of the approach of Gu et al. (2017) is the need for extensive fine-tuning to make policy gradients work, as well as the non-generic nature of the solution. Lee et al. (2018) propose a non-autoregressive model using iterative refinement. Here, instead of decoding the target sentence in one-shot, the output is successively refined to produce the final output. While the output is produced in parallel at each step, the refinement steps happen sequentially.

heading: 5 Experiments
text: In this section we report our experiments with VQ-VAE and EM on the English-German translation task, with the aim of improving the decoding speed of autoregressive translation models. Our model and generative process follows the architecture proposed in Kaiser et al. (2018) and is depicted in Figure 1. For all our experiments, we use the Adam (Kingma & Ba, 2014) optimizer and decay the learning rate exponentially after initial warm-up steps. Unless otherwise stated, the dimension of the hidden states of the encoder and the decoder is 512, see Table 4 for a comparison of models with lower dimension. For all configurations we select the optimal hyperparameters by using WMT’13 English-German as the validation set and reporting the BLEU score on the WMT’14 English-German test set.

heading: 5.1 Machine Translation
text: In Neural Machine Translation with latent variables, we model P (y, z | x), where y and x are the target and source sentence respectively. Our model architecture, depicted in Figure 1, is similar to the one in Kaiser et al. (2018). The encoder function is a series of strided convolutional layers with residual convolutional layers in between and takes target sentence y
as input. The source sentence x is converted to a sequence of hidden states through multiple causal self-attention layers. In Kaiser et al. (2018), the encoder of the autoencoder attends additionally to this sequence of continuous representation of the source sentence. We use VQ-VAE as the discretization algorithm. The decoders, applied after the bottleneck layer uses transposed convolution layers whose continuous output is fed to a transformer decoder with causal attention, which generates the output.
The results are summarized in Table 1. Our implementation of VQ-VAE achieves a significantly better BLEU score and faster decoding speed compared to Kaiser et al. (2018). We found that tuning the code-book size (number of clusters) for using 212 discrete latents achieves the best accuracy which is 16 times smaller as compared to the code-book size in Kaiser et al. (2018). Additionally, we see a large improvement in the performance of the model by using sequence-level distillation (Hinton et al., 2015; Kim & Rush, 2016), as has been observed previously in non-autoregressive models (Gu et al., 2017; Lee et al., 2018). Our teacher model is a base Transformer (Vaswani et al., 2017) that achieves a BLEU score of 28.1 and 27.0 on the WMT’14 test set using beam search decoding and greedy decoding respectively. The distilled data is decoded from the base Transformer using a beam size of 4. Our VQ-VAE model trained with soft EM and distillation, achieves a BLEU score of 26.7, without noisy parallel decoding (Gu et al., 2017). This perforamce is 1.4 bleu points lower than an autoregressive model decoded with a beam size of 4, while being 4.1× faster. Importantly, we nearly match the same autoregressive model with beam size 1 (greedy decoding), with a 3.3× speedup. The length of the sequence of discrete latent variables is shorter than that of target sentence y. Specifically, at each compression step of the encoder we reduce its length by half. We denote by nc, the compression factor for the latents, i.e. the number of steps for which we do this compression. In almost all our experiments, we use nc = 3 reducing the length by 8. We can decrease the decoding time further by increasing the number of compression steps. As shown in Table 1, by setting nc to 4, the decoding time drops to 58 milliseconds achieving 25.4 BLEU while a NAT model (Gu et al., 2017) with similar decoding speed achieves only 18.7 BLEU. Note that, all NAT models also train with sequence level knowledge distillation from an autoregressive teacher.

heading: 5.1.1 Analysis
text: Attention to Source Sentence Encoder: While the encoder of the discrete autoencoder in Kaiser et al. (2018) attends to the output of the encoder of the source sentence, we find that to be unnecessary, with both models achieving the same BLEU score with 212 latents. Removing this attention step results in more stable training (see Figure 3) and is the main reason why VQ-VAE works in our setup (see Table 1) without the use of Product Quantization (DVQ) (Kaiser et al., 2018). Note that the decoder of the discrete autoencoder in both Kaiser et al. (2018) and our work does not attend to the source sentence.
Size of Discrete Latent Variable code-book: Table 2 shows the BLEU score for different code-book sizes for models trained using VQ-VAE without distillation. While Kaiser et al. (2018) use 216 as their code-book size, we find that 212 gives the best performance.
Number of samples in Monte-Carlo EM update: While training with EM, we perform a Monte-Carlo update with a small number of samples (Section 3.2). Table 3 shows the impact of number of samples on the final BLEU score.
VQ-VAE vs Other Discretization Techniques: We compare the Gumbel-Softmax of (Jang et al., 2016; Maddison et al., 2016) and the improved semantic hashing discretization technique proposed in Kaiser et al. (2018) to VQ-VAE. When trained with sequence level knowledge distillation, the model using Gumbel-Softmax reached 23.2 BLEU, the model using improved semantic hashing reached 24.1 BLEU, and the model using VQ-VAE reached 26.4 BLEU on WMT’14 English-German.
* Speedup reported for these items are compared to the decode time of 408 ms for an autoregressive Transformer from Gu et al. (2017).

heading: 6 Conclusion
text: We investigate an alternate training technique for VQ-VAE inspired by its connection to the EM algorithm. Training the discrete autoencoder with EM and combining it with sequence level knowledge distillation, allows us to develop a non-autoregressive machine translation model whose accuracy almost matches a greedy autoregressive baseline, while being 3.3 times faster at inference. While sequence distillation is very important for training our best model, we find that the improvements from EM on harder tasks is quite significant. We hope that our results will inspire further research on using vector quantization for fast decoding of autoregressive sequence models.

heading: B Ablation Tables

heading: C Additional Analysis
text: Gradient based update vs EMA update of code-book: The original VQ-VAE paper (van den Oord et al., 2017) proposed a gradient based update rule for learning the code-book where the code-book entries are trained by minimizing ‖sg (ze(x))− zq(x)‖2. However, it was found in Kaiser et al. (2018) that the EMA update worked better than this gradient based loss. Note that if the gradient based loss was minimized using SGD then the update rule for the embeddings is
ej ← (1− η)ej + η (∑
i 1 [zq(xi) = ej ] ze(xi)∑ i 1 [zq(xi) = ej ]
) , (15)
for a learning rate η. This is quite similar to the EMA update rule of Equation 5, with the only difference being that the latter also maintains an EMA over the counts cj . When using SGD with momentum or Adam, the update rule becomes quite different however, since we now take the moving average of the gradient term itself, before subtracting it from current value of the embedding ej . This is similar to the issue of using weight decay with Adam, where using the `2 penalty in the loss function results in worse performance (Loshchilov & Hutter, 2017).
Model Size: The effect of model size on BLEU score for models trained with EM and distillation is shown in Table 4.
Robustness of EM to Hyperparameters: While EM training gives a small performance improvement, we find that it also leads to more robust training for machine translation.
Our experiments on image reconstruction on SVHN (Netzer et al., 2011) in section A also highlight the robustness of EM training. The training approach from van den Oord et al. (2017) exhibits high variance on reconstruction quality, while EM is much more stable, resulting in good reconstructions in almost all training runs.
Emergence of EOS/PAD latent: We observe that all the latent sentences for a specific experiment with VQ-VAE or EM end with a fixed latent indicating the end of the sequence. Since we always fix the length of the latent sentence to be 2nc times smaller than the true sentence, the model learns to pad the remainder of the latent sequence with this special code (see Table 5 for examples). Note that one can speed up decoding even further by stopping the Latent Predictor (LP) model as soon as it outputs this special code.
Denoising autoencoder: We also use word dropout with a dropout rate of 0.3 and word permutation with a shuffle rate of 0.5 as in Lample et al. (2018). On the WMT EnglishGerman we did not notice any improvement from using these regularization techniques, but on the larger WMT English-French dataset, we observe that using a denoising autoencoder significantly improves performance with a gain of 1.0 BLEU on VQ-VAE and 0.9 BLEU over EM (see Table 6).
Additional analysis on latents: In order to compute correlations between the discrete latents and n-grams in the original text, we computed Point-wise Mutual Information (PMI) and tf-idf scores where the latents are treated as documents. However, we were unable to see any semantic patterns that stood out in this analysis.

heading: D Preliminary Results on English French
text: In this section we report preliminary results on the WMT English-French dataset without using knowledge distillation from an autoregressive teacher (Hinton et al., 2015; Kim & Rush, 2016). We use a Transformer base model from Vaswani et al. (2017). Our best non-autoregressive base model trained on non-distilled targets gets 30.0 BLEU compared to the autoregressive base model with the same choice of hyperparameters, which gets 33.3 BLEU (see Table 6). As in the case of English-German, we anticipate that using knowledge distillation Hinton et al. (2015) will likely close this gap.

Review summaries:
The paper presents an alternative view on the training procedure for the VQ-VAE. The authors have noticed that there is a close connection between the original training algorithm and the well-known EM algorithm. Then, they proposed to use the soft EM algorithm. In the experiments the authors showed that the soft EM allows to obtain significantly better results than the standard learning procedure on both image and text datasets.

This paper discusses VQ-VAE for learning discrete latent variables, and its application to NMT with a non-autoregressive decoder to reduce latency (obtained by producing a number of latent variables that is much smaller than the number of target words, and then producing all target words in parallel conditioned on the latent variables and the source text). The authors show the connection between the existing EMA technique for learning the discrete latent states and hard EM, and introduce a Monte-Carlo EM algorithm as a new learning technique. They show strong empirical results on EN-DE NMT with a latent Transformer (Kaiser et al. (2018)).