Introduction
VQ-VAEs [@VQVAE; @VQVAE2] model high dimensional data $x$ with low-dimensional discrete latents $z$. A likelihood function $p_\theta(x|z)$ is parameterized with a decoder that maps from latent space to observation space. A uniform prior distribution $p(z)$ is defined over a discrete space of latent codes. As in the variational inference framework [@neurVI], an approximate posterior is defined over the latents: $$\begin{align} \small q_{\phi}(z = k|x) = \begin{cases}1 \quad\text{for} \enspace k = \text{argmin}_j ||z_e(x) - e_j||2\ 0\quad \text{otherwise}\end{cases} \end{align}$$ The codebook $(e_i){i=1}^N$ enumerates a list of vectors and an encoder $z_e(x)$ maps into latent space. A vector quantization operation then maps the encoded observation to the nearest code. During training the encoder and decoder are trained jointly to minimize the loss: $$\begin{equation} \label{eqn:vqvaeloss} \small
- \log p_{\theta}(x|z=k) + ||\text{\textit{sg}}[z_e(x)] - e_k||_{2}^2 \+ \beta||z_e(x) - \text{\textit{sg}}[e_k]||_2^2 : , \end{equation}$$ where sg is a stop gradient operator. The first term is referred to as the reconstruction loss, the second term is the codebook loss and the final term is the commitment loss. In practice, the codes $e_k$ are learnt via an online exponential moving average version of k-means.
Lossy compression schemes will invariably use some form of quantization to select codes for transmission. This section examines the behaviour of quantization-based models trained using maximum-likelihood.
Consider performing standard lossy compression on datapoints sampled from the distribution shown in Figure 1{reference-type="ref" reference="fig:toy_distribution"}. Each datapoint is encoded to an encoding consisting of only a small number of bits. Each encoding is then decoded to obtain an imperfect (lossy) reconstruction of the original datapoint. We desire a lossy compression system that shows the following behaviour:
Low Bitrates The encoding of each datapoint should consist of as few bits as possible.
Realism The reconstruction of each datapoint should not take on a value that has low probability under the original distribution. For the distribution in Figure 1{reference-type="ref" reference="fig:toy_distribution"}, this corresponds to regions outside of the four modes. We term such reconstructions unrealistic. In other words, it should never be the case that a reconstruction is clearly not from the original distribution. A link can be drawn between these areas of low probability in the original data distribution and the blurry/unrealistic samples often seen when using VAEs for reconstruction tasks.
We begin by using a VQ-VAE to compress and reconstruct samples from the density shown in Figure 1{reference-type="ref" reference="fig:toy_distribution"}. We first train a VQ-VAE that uses a latent space of 4 codewords. The encodings produced by this VQ-VAE will therefore each be of size 2 bits ($= \text{log}_24$). The red trace in Figure 2{reference-type="ref" reference="fig:toy_single_layer_vqvae"} shows the density of the reconstructions from this 4-code VQ-VAE. It is a perfect match of the density function that the original datapoints were sampled from. There are no unrealistic reconstructions as all reconstructed datapoints fall in regions of high density under the original distribution.
We now fit a VQ-VAE with a 2 codeword (1 bit) latent space to the original density. The green trace of Figure 2{reference-type="ref" reference="fig:toy_single_layer_vqvae"} shows the result. The mode-covering behaviour shown by this VQ-VAE causes reconstructions to fall in regions of low probability under the original distribution. Therefore, nearly all reconstructions are unrealistic. This mode-covering is a well known pathology of all likelihood-based models trained using the asymmetric divergence $\text{KL}[p_{\theta}(x)||p(x)]$. [@Adaptive_Density_Estimation] show mode-covering limits the perceptual quality of reconstructions. To reiterate, this is because mode-covering produces unrealistic samples.
The question then arises: can we do better and produce realistic reconstructions using only a 1 bit encoding?
We now take the pretrained 4-code VQ-VAE that produces the red trace in Figure 2{reference-type="ref" reference="fig:toy_single_layer_vqvae"}. We term this VQ-VAE Layer 1. We then train a new 2-code VQ-VAE, which we term Layer 2, to compress and reconstruct the encodings produced by Layer 1. The resulting system is a quantized hierarchy.
We can then compress and reconstruct datapoints sampled from the original distribution using the whole quantized hierarchy, as shown in Algorithm [alg:quantized_hierarchy_lossy_compression]{reference-type="ref" reference="alg:quantized_hierarchy_lossy_compression"}. Algorithm [alg:quantized_hierarchy_lossy_compression]{reference-type="ref" reference="alg:quantized_hierarchy_lossy_compression"} is a simplification of the Hierarchical Quantized Autoencoder (HQA) described in Section 5.2.1{reference-type="ref" reference="section:hqm-methods"}.
:::: algorithm ::: algorithmic $x$: Datapoint to be compressed $e_1 \gets \text{Encoder}_1(x)$ $e_2 \gets \text{Encoder}_2(e_1)$ $q_2 \gets \text{Quantize}(e_2)$ Transmit $q_2$ $\hat{e}_1 \gets \text{Decoder}_2(q_2)$ $\hat{q}_1 \gets \text{Quantize}(\hat{e}_1)$ $\hat{x} \gets \text{Decoder}_1(\hat{q}_1)$ $\hat{x}$: Lossy reconstruction of $x$ ::: ::::
For VQ-VAE, each codeword is represented as a vector in a continuous latent space. If we consider the points in the latent space of Layer 1 that are actually used for encodings, there are only 4 points that are used: the locations of the 4 codewords. In other words, the distribution over the latent space of Layer 1 contains 4 modes.
Layer 2 is used to compress and reconstruct points from the latent space of Layer 1. As the latent space of Layer 1 contains 4 modes but Layer 2 only uses 2 codewords, Layer 2 will mode-cover for the same reasons described above. However, this mode-covering is now over the latent space of Layer 1 and not over the input space of the original distribution.
This mode-covering can now be resolved through quantization. The decode from Layer 2 can be quantized to a code in Layer 1's latent space (i.e quantized to a mode). Therefore, the reconstructions of Layer 1's latent space, and hence the final reconstruction, are more likely to be realistic.
VQ-VAE uses a deterministic quantization procedure which always quantizes to the code that is geometrically closest to the input embedding. We can use the quantized hierarchy introduced, along with deterministic quantization, to reconstruct samples from the original distribution. The result is shown by the red trace in Figure 3{reference-type="ref" reference="fig:toy_deterministic"}. For the reasons outlined above, no mode-covering behaviour is observed and all reconstructions are realistic. However, mode-dropping is now occurring.
If a stochastic quantization scheme is introduced (c.f. Section 5.1{reference-type="ref" reference="section:stoch_post"}) then this mode-dropping behaviour can also be resolved. Figure 5{reference-type="ref" reference="fig:toy_stochastic"} shows the result of using the quantized hierarchy, now with stochastic quantization. No mode-dropping or mode-covering behaviour is present. Note that the quantized hierarchy uses 1 bit encodings, the same size as the encoding of the 2-code VQ-VAE that failed to model the distribution (c.f. Figure 2{reference-type="ref" reference="fig:toy_single_layer_vqvae"}). This result shows that, under a given information bottleneck, probabilistic quantized hierarchies allow for fundamentally different density modelling behaviour than equivalent single layer systems. Furthermore, unlike deterministic compression, there is no single decoded data; there are now many possible decodes.
Therefore, we propose that probabilistic quantized hierarchies can mitigate the unrealistic reconstructions produced by likelihood-based systems for the following reasons:
Hierarchy: By choosing to model a distribution using a hierarchical latent space of increasingly compressed representations, mode-covering behaviour in the input space can be exchanged for mode-covering behaviour in the latent space. This also acts as a good meta-prior to match the hierarchical structure of natural data [@lazaro2016hierarchical].
Quantization: Quantization allows for the resolution of mode-covering behaviour in latent space, encouraging realistic reconstructions that fall in regions of high density in the input space.
Stochastic Quantization: If quantization is performed deterministically then diversity of reconstructions is sacrificed. By quantizing stochastically, mode-dropping behaviour can be mitigated. In addition, this introduces the stochasticity typically required for low-rate lossy compression in a natural manner.
We depart from the deterministic posterior of VQ-VAE and instead use the stochastic posterior introduced by @ConRelax: $$\begin{equation} q(z=k|x) \propto \exp-||z_e(x) - e_k||_2^2 : . \label{eqn:stochastic_posterior} \end{equation}$$ Quantization can then be performed by sampling from $q(z=k|x)$. At train-time, a differentiable sample can be obtained from this posterior using the Gumbel Softmax relaxtion [@Gumbel; @Concrete]. While training HQA, we linearly decay the Gumbel Softmax temperature to $0$ so the soft quantization operation closely resembles hard quantization, which is required when compressing to a fixed rate. At test-time we simply take a sample from Equation [eqn:stochastic_posterior]{reference-type="ref" reference="eqn:stochastic_posterior"}.
Crucially, under this formulation of the posterior, $z_e(x)$ (henceforth $z_e$) must be positioned well relative to all codes in the latent space, not just the nearest code [@vq_wu]. As $z_e$ implicitly defines a distribution over all codes, it carries more information about $x$ than a single quantized latent sampled from $q(z|x)$. This is exploited by the HQA hierarchy, as discussed below.
In a single layer model, the encoder generates a posterior $q = q(z|x)$ over the codes given by Equation [eqn:stochastic_posterior]{reference-type="ref" reference="eqn:stochastic_posterior"}. To calculate a reconstruction loss we sample from this posterior and decode. Additionally, we augment this with two loss terms that depend on $q$: $$\begin{equation} \label{eqn:our_loss} \mathcal{L} = \underbrace{-\log p(x|z=k)}{\text{reconstruction loss}} - \underbrace{\mathcal{H}[q(z|x)]}{\text{entropy}} + \underbrace{\mathbb{E}_{q(z|x)}||z_e(x) - e_z||2^2}{\text{probabilistic commitment loss}} : . \end{equation}$$ This objective is the sum of the reconstruction loss as in a normal VQ-VAE (Equation [eqn:vqvaeloss]{reference-type="ref" reference="eqn:vqvaeloss"}), the entropy of $q$, and a term similar to the codebook/commitment loss in Equation [eqn:vqvaeloss]{reference-type="ref" reference="eqn:vqvaeloss"} but instead taken over all codes, weighted by their probability under $q$. The objective $\mathcal{L}$ resembles placing a Gaussian Mixture Model (GMM) prior over the latent space and calculating the Evidence Lower BOund (ELBO), which we derive in Appendix 9{reference-type="ref" reference="sec:prop_vqvae"}.
When training higher layers of HQA, we take take the reconstruction target to be $z_e$ from the previous layer. This novel choice of reconstruction target is motivated by noting that the embedding of $z_e$ implicitly represents a distribution over codes. By training higher layers to minimize the MSE between $z_e$ from the layer below and an estimate $\hat{z}_e$, the higher layer learns to reconstruct a full distribution over code indices, not just a sample from this distribution. Empirically, the results in Section 6.2{reference-type="ref" reference="sec:mnist"} show this leads to gains in reconstruction quality.
In this way, a higher level VQ-VAE can be thought of as reconstructing the full posterior of the layer below, as opposed to a sample from this posterior (as in @HAMS). The predicted $\hat{z}_e$ is used to estimate the posterior of the layer below using Equation [eqn:our_loss]{reference-type="ref" reference="eqn:our_loss"}, from which we can easily sample to perform stochastic quantization, as motivated in Section 4{reference-type="ref" reference="motivation"}.
The Markovian latent structure of HQA - where each latent space is independent given the previous layer - allows us to train each layer sequentially in a greedy manner as shown in Figure 7{reference-type="ref" reference="fig:systemdiagram"} (left). This leads to lower memory footprints and increased flexibility as we are able to ensure the performance of each layer before moving onto the next. Appendix 11{reference-type="ref" reference="sec:algorithm"} describes algorithm in full.
The loss given by Equation [eqn:our_loss]{reference-type="ref" reference="eqn:our_loss"}, in combination with the use of the Gumbel-Softmax, allows for the code embeddings to be learnt directly without resorting to moving average methods. This introduces a new pathology where codes that are assigned low probability under $q(z|x)$ for all $x$ receive low magnitude gradients and become unused. During training, we reinitialise these unused codes near codes of high usage. This results in significantly higher effective rates. Code resetting mirrors prior work in online GMM training [@fastGMM; @EfficientGMM] and over-parameterized latent spaces [@overparamEM].
Method
Each layer in the HQA stack is composed of an encoder, decoder and vector quantization layer. Encoders and decoders are feed forward networks composed of convolutional layers with 3x3 filters. Optional dilated convolutions are used in the decoder to increase the decoder's receptive field. Each code in the VQ layer codebook is represented by a 64 dimensional vector. The input $\hat{z_e}$ to layers 2 and above are normalized using running statistics, which was shown to stabilise training. A $\operatorname{sigmoid}$ activation is applied to the output of the decoder in the first layer.
The downsampling needed for compression is achieved through a strided convolution in the encoder and upsampling through nearest neighbour interpolation in the decoder. Each HQA layer is trained greedily with an MSE loss; gradients are only back-propagated through that single layer. For the first layer, the loss is taken between input pixels and decoder outputs, while all other layers calculate the loss between the input embedding $z_e$ and the predicted $\hat{z_e}$.
Optimization is performed using RAdam [@liu2019variance] with a learning rate of 4e-4 which is cosine annealed in the final third of training. Each layer was trained with distributed training across 8 Nvidia TITAN RTX's for CelebA, whilst MNIST was trained on a single TITAN X. During training, the Gumbel softmax temperature is linearly annealed to 0.01, with an initial temperature of 0.4 and 0.66 for CelebA and MNIST respectively.
::: table* L1 L2 L3 L4 L5 L6 L7
Input size 64 64 32 16 8 4 2 Batch size 1024 1024 1024 1024 1024 1024 1024 Encoder layers 3 3 3 3 3 3 3 Decoder layers 6 6 6 6 6 6 6 Encoder hidden units 64 64 512 512 512 512 512 Decoder hidden units 64 64 512 512 512 512 512 Codebook size 512 512 512 512 512 512 512 $\beta_e$ (entropy loss coefficient) 5e-5 5e-5 5e-5 5e-5 5e-5 5e-5 5e-5 $\beta_c$ (commitment loss coefficient) 5e-5 5e-5 5e-5 5e-5 5e-5 5e-5 5e-5 Training steps 100k 100k 100k 100k 60k 30k 30k Dropout 0.0 0.0 0.0 0.5 0.5 0.5 0.5 :::
::: table* L1 L2 L3 L4 L5
Input size 32 16 8 4 2 Batch size 512 512 512 512 512 Encoder layers 3 3 3 3 3 Decoder layers 3 3 3 3 3 Encoder hidden units 16 16 32 48 80 Decoder hidden units 16 32 48 80 128 Codebook size 256 256 256 256 256 $\beta_e$ (entropy loss coefficient) 1e-3 1e-3 1e-3 1e-3 1e-3 $\beta_c$ (commitment loss coefficient) 1e-3 1e-3 1e-3 1e-3 1e-3 Training steps 18k 18k 18k 18k 18k :::
The implemented HAMs architecture follows @HAMS. Notably, it implements an MSE loss on pixels but all other layers use cross entropy for the reconstruction term. Separate commitment and codebook loss terms are also used. The codebook is not learnt directly, but updated via an online exponential moving average version of k-means. For the CelebA experiment a smaller batch sizes where used than the 1024 used for HQA. This is because we found training of HAMs to be very unstable if large batch sizes were used.
::: table* L1 L2 L3 L4 L5 L6 L7
Input size 64 64 32 16 8 4 2 Batch size 32 64 64 64 64 64 64 Encoder conv layers 3 3 3 3 3 3 3 Decoder conv layers 3 3 3 3 3 3 3 Encoder hidden units 64 80 256 256 256 256 512 Decoder hidden units 64 80 512 512 512 512 512 Encoder residual blocks 2 2 2 3 3 2 1 Decoder residual blocks 2 2 2 3 3 2 1 Codebook size 512 512 512 512 512 512 512 $\beta$ (commitment loss coefficient) 1 50 50 50 50 50 10 Learning rate 4e-4 4e-4 4e-4 4e-4 1e-4 1e-4 1e-4 Training steps 250k 300k 50k 50k 50k 50k 25k :::
::: table* L1 L2 L3 L4 L5
Input size 32 16 8 4 2 Batch size 256 256 256 256 256 Encoder conv layers 3 3 3 3 3 Decoder conv layers 3 3 3 3 3 Encoder hidden units 16 16 32 48 80 Decoder hidden units 16 26 40 58 96 Encoder residual blocks 0 0 0 0 0 Decoder residual blocks 0 0 0 0 0 Codebook size 256 256 256 256 256 $\beta$ (commitment loss coefficient) 0.02 0.02 0.02 0.02 0.02 Learning rate 4e-4 4e-4 4e-4 4e-4 1e-4 Training steps 18k 18k 18k 18k 18k :::
The implemented VQ-VAE [@VQVAE] architecture is comparable to HAMs, with the noticeable exception that there is no hierarchy. The same compression rates are achieved through downsampling multiple times. The entire network is trained end-to-end as a single layer, instead of greedily with local losses. The layers denoted in the table below refer VQ-VAE systems with equivalent compression factors to the same HQA and HAM layers. In all instances predictions are made in pixel space. The residual block implementation is based on the original VQ-VAE. As with HAMs, small batch sizes had to be used for the CelebA experiment as large batch sizes lead to instability.
::: table* L1 L2 L3 L4 L5 L6 L7
Input size 64 64 32 16 8 4 2 Batch size 32 64 64 64 64 64 64 Encoder conv layers 2 3 4 5 6 7 8 Decoder conv layers 3 4 5 6 7 8 9 Encoder hidden units 64 80 256 256 384 400 512 Decoder hidden units 64 80 256 512 512 512 512 Encoder residual blocks 2 3 4 4 4 4 2 Decoder residual blocks 2 3 4 4 4 4 2 Codebook size 512 512 512 512 512 512 512 $\beta$ (commitment loss coefficient) 0.05 0.25 0.25 0.25 0.25 0.25 0.25 Learning rate 4e-5 4e-5 4e-5 1e-4 1e-4 1e-4 1e-4 Training steps 250k 250k 250k 150k 150k 150k 50k :::
::: table* L1 L2 L3 L4 L5
Input size 32 16 8 4 2
Batch size 512 512 512 512 512
Encoder conv layers 2 3 4 5 6
Decoder conv layers 3 4 5 6 7
Encoder hidden units 22 40 50 62 78
Decoder hidden units 16 18 20 22 22
Encoder residual blocks 0 0 0 0 0
Decoder residual blocks 0 0 0 0 0
Codebook size 256 256 256 256 256
$\beta$ (commitment loss coefficient) 0.125 0.125 0.125 0.125 0.125
Learning rate 4e-4 4e-4 4e-4 4e-4 4e-4
Training steps 18k 18k 18k 18k 18k
:::
During training, the total number of times that $z_e$ is quantized to each code is accumulated over 20 batches. After these 20 batches, the most and least used code, $e_m$ and $e_l$ respectively, are found. If the usage of $e_l$ is less than 3% than that of $e_m$, the position of $e_l$ is reset such that $e_l := e_m + \epsilon$ where $\epsilon \sim N(0, 0.01)$. This scheme is activate for the first 75% of training.
:::: algorithm ::: algorithmic $\bm{e}$: codebook embeddings, $e_k$: embdding for code $k$, $N$: number of codes in each layer $L$: number of layers in stack $\theta_i \gets$ Initialize network parameters for encoders ($Encoder_{i}$) and decoders ($Decoder_{i}$) $\forall i \in L$
$\tau \gets 0.4$ $X \gets$ Random minibatch
$\bm{z_{e-lower}} \gets$ X $\bm{z_{e-lower}} \gets$ $Encoder_{0..l-1}(X)$
$\bm{z_e} \gets$ $Encoder_{l}(\bm{z_{e-lower}})$ $p(k|\bm{z_e}) = \exp\left(-\frac{1}{2}||\bm{z_e} - \bm{e}k||2^2\right) / \sum{i=1}^N \exp\left(-\frac{1}{2}||\bm{z_e} - \bm{e}i||2^2\right))$ $\text{softonehot} \sim$ $\text{RelaxedCategorical}(\tau, p(k|\bm{z_e}))$ $\bm{z{q-soft}} \gets$ $\text{softonehot} * \bm{e}$ $\bm{\hat{z}{e-lower}} \gets$ $Decoder{l}(\bm{z_{q-soft}})$
$\mathcal{L'}{recon} = \left(\bm{\hat{z}{e-lower}} - \bm{z_{e-lower}}\right)^2$ $\mathcal{L}{entropy} = \sum_k p(k|\bm{z_e}) \log p(k|\bm{z_e})$ $\mathcal{L}{commit} = \sum_k p(k|\bm{z_e}) ||\bm{z_e} - e_k||_2^2$
$\theta_i \gets \theta_i - \eta\nabla_{\theta_i} (\mathcal{L'}{recon} + \beta_e \mathcal{L}{entropy} + \beta_c \mathcal{L}_{commit} ))$ $\tau \gets anneal(\tau)$ ::: ::::
:::: algorithm ::: algorithmic $\bm{e}$: codebook embeddings $L$: number of layers in stack Trained encoders ($Encoder_{i}$) and decoders ($Decoder_{i}$) $\forall i \in L$ $x$: Datapoint to reconstruct $\bm{z_e} \gets$ $Encoder_{0..l}(x)$
$p(k|\bm{z_e}) = \exp\left(-\frac{1}{2}||\bm{z_e} - \bm{e}_k||2^2\right) / \sum{i=1}^N \exp\left(-\frac{1}{2}||\bm{z_e} - \bm{e}_i||2^2\right))$ $\text{onehot} \sim$ $p(k|\bm{z_e})$ $\bm{z_q} \gets$ $\text{onehot}* \bm{e}$ $\bm{z_e} \gets Decoder{l}(\bm{z_q})$ $\bm{z_e}$ ::: ::::
Note that for hard reconstructions at fixed rates, we do not necessarily need to perform hard-quantized codebook lookups except on the very top codebook. For simplicity, and to provide a single hierarchy where each layer can provide compression at a fixed rate, we anneal the temperature close to zero and at test time always perform hard quantization operations at each layer as outlined in Algorithm [alg:reconstruct]{reference-type="ref" reference="alg:reconstruct"}.
[^1]: Equal contribution.
[^2]: Code available at https://github.com/speechmatics/hqa