Vector quantization (VQ), initially introduced by Gray (1984), has recently seen a renaissance in the context of learning discrete representations with neural networks. Spurred by the success of VQ-VAE (Van Den Oord et al., 2017), Esser et al. (2020) and Villegas et al. (2022) showed that training an autoregressive transformer on the representations of a VQ-VAE trained with a GAN loss enables powerful image and video generation models, respectively.
At the same time, VQ has become popular component in image (Bao et al., 2021; Li et al., 2023) and audio (Baevski et al., 2019) representation learning, and is a promising building block for the next generation of multimodal large language models (Aghajanyan et al., 2022; Kim et al., 2023; Aghajanyan et al., 2023).
When training VQ-VAE, the goal is to learn a codebook whose elements induce a compressed, semantic representation of the input data (typically images). In the forward pass, an image is encoded into a representation (typically a sequence of feature vectors), and each vector in quantized to (i.e., replaced with) the closest vector in . The quantization operation is not differentiable. When training a VAE with VQ in the latent representation, Van Den Oord et al. (2017) use the straightthrough estimator (STE) (Bengio et al., 2013), copying the gradients from the decoder input to the encoder output, resulting in gradients to the encoder. Since this still does not produce gradients for the codebook vectors, they further introduce two auxiliary losses to pull the codeword vectors towards the (unquantized) representation vectors and vice-versa.
Components of VQ-VAE
The Vector Quantised-Variational AutoEncoder (VQ-VAE), differs from VAEs in two key ways: the encoder network outputs discrete, rather than continuous, codes; and the prior is learnt rather than static.
In VQ-VAE, we have:
An input image where are the height and width of the image.
A latent embedding space , called the codebook, where each is called a code and is the dimensionality of codes.
An encoder encodes an image into an embedding .
An operator called quantizer:
quantizes to , where . The quantization process is with subscript starting from to .
Therefore, for each element of , we use argmin to find the that is closest in distance to , i.e., minimizing the norm , to get .
A decoder decodes into an image , which is also called the reconstructed image of .
Forward pass
VQ-VAE
The forward pass of VQ-VAE consists of
First, we use encoder to encode the input image to get the embedding :
Next, we use quantizer to quantize the embedding to get the quantized embedding . Since contains embeddings, is composed of codes, of which each code is selected through a nearest-neighbor lookup (argmin()) to the codebook .
Finnally, we use decoder to decode to get the reconstructed image .
NOTES:
The encoded embedding and quantized embedding have the same dimentionality and they have the same embedding dimenstion (=) as .
We will sometimes use to refer .
Loss function
The overall loss function is: Since VQ-VAE leverages argmin() function, which is non-differentiable. The gradient from decoder input can not be passed to the encoder output . To solve this, we use a trick called the straight through estimator which applies a stop_gradient operator ( in the equation) to copy to .
The overall loss function has three components:
Reconstruction loss is the negative log-likelihood. In practice, it's common to replace it with MSE loss.
Codebook loss , which moves the embedding vectors towards the encoder output.
Commitment loss , which encourages the encoder output to stay close to the embedding space.
Model architecture
#TODO shape problem
VectorQuantizer
This layer takes a tensor to be quantized. The channel dimension will be used as the space in which to quantize. All other dimensions will be flattened and will be seen as different examples to quantize.
The output tensor will have the same shape as the input.
As an example for a BCHW tensor of shape [16, 64, 32, 32], we will first convert it to an BHWC tensor of shape [16, 32, 32, 64] and then reshape it into [16384, 64] and all 16384 vectors of size 64 will be quantized independently. In otherwords, the channels are used as the space in which to quantize.
All other dimensions will be flattened and be seen as different examples to quantize, 16384 in this case.
We will also implement a slightly modified version which will use exponential moving averages to update the embedding vectors instead of an auxillary loss. This has the advantage that the embedding updates are independent of the choice of optimizer for the encoder, decoder and other parts of the architecture. For most experiments the EMA version trains faster than the non-EMA version.
defforward(self, inputs): # convert inputs from BCHW -> BHWC inputs = inputs.permute(0, 2, 3, 1).contiguous() # (256, 64, 8, 8) BCHW --> (256, 8, 8, 64) BHWC input_shape = inputs.shape # BHWC # Flatten input flat_input = inputs.view(-1, self._embedding_dim) # Now set C'=64 (_embedding_dim), flatten `inputs` into (N, C'), where N=B*H*W, i.e., we have N=B*H*W vectors, each vector has dimension=C. # Calculate distances distances = (torch.sum(flat_input**2, dim=1, keepdim=True) + torch.sum(self._embedding.weight**2, dim=1) - 2 * torch.matmul(flat_input, self._embedding.weight.t())) # Each vector `z_e` has distances with all the quantized vectors `e_j` in the codebook, where j in K = `_num_embeddings`. # Encoding encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1)# For each vector `z_e`, select the index of the **closest** quantized vector `e_j` in the codebook. # For each each vector `z_e`, use the index of its corresponding `z_q` to create a one-hot encoding. encodings = torch.zeros(encoding_indices.shape[0], self._num_embeddings, device=inputs.device) encodings.scatter_(1, encoding_indices, 1) # Quantize and unflatten quantized = torch.matmul(encodings, self._embedding.weight).view(input_shape) # Use the one-hot encoding as the index to select the quantized vectors in the codebook. # Use EMA to update the embedding vectors if self.training: self._ema_cluster_size = self._ema_cluster_size * self._decay + \ (1 - self._decay) * torch.sum(encodings, 0) # Laplace smoothing of the cluster size n = torch.sum(self._ema_cluster_size.data) self._ema_cluster_size = ( (self._ema_cluster_size + self._epsilon) / (n + self._num_embeddings * self._epsilon) * n) dw = torch.matmul(encodings.t(), flat_input) self._ema_w = nn.Parameter(self._ema_w * self._decay + (1 - self._decay) * dw) self._embedding.weight = nn.Parameter(self._ema_w / self._ema_cluster_size.unsqueeze(1)) # Loss e_latent_loss = F.mse_loss(quantized.detach(), inputs) commitment_loss = self._commitment_cost * e_latent_loss codebook_loss = F.mse_loss(quantized, inputs.detach()) # Straight Through Estimator quantized = inputs + (quantized - inputs).detach() avg_probs = torch.mean(encodings, dim=0) perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10))) # convert quantized from BHWC -> BCHW return codebook_loss, commitment_loss, quantized.permute(0, 3, 1, 2).contiguous(), perplexity, encodings