VQ-VAE and adversarial autoencoders: other ways to shape the code
Two autoencoders that replace the VAE's KL term. A VQ-VAE snaps each code to the nearest of a set of learned vectors; an adversarial autoencoder trains a discriminator to make codes look like prior draws.
What runs in CodeSplash
- DNN037Vector-quantized VAE (VQ-VAE) Explained here
- DNN039Adversarial autoencoder (AAE) Explained here
You will be able to
- Describe nearest-vector quantization, the straight-through gradient and the commitment loss
- Explain why a discrete code needs a separate prior model before you can sample
- Describe how an adversarial autoencoder matches the aggregate posterior to the prior
- Say what CodeSplash runs here and what it explains only
Snap to the nearest vector
ReadA VQ-VAEVQ-VAEAn autoencoder whose code snaps to the nearest of a fixed set of learned vectors, giving discrete codes instead of Gaussian ones. keeps a table of learned vectors . The encoder's output is replaced by its nearest table entry:
The decoder only ever sees table entries, so each row (or each patch of an image) becomes an index into the table. Discrete codes suit data with natural categories, and they make it possible to model codes with the same tools as text.
Reference · DNN037 · Explained hereVector-quantized VAE (VQ-VAE)VQ-VAE replaces continuous stochastic codes with nearest-neighbor entries from a learned codebook. It produces discrete latent tokens for images and other modalities, often followed by a separately trained prior over…Three codes, three table entries
ReadIn the reference's example three encoder outputs meet a table of three vectors. They pick entries 1, 2 and 0 (counting from 0), and the commitment loss is 0.005.
import numpy as np
Z = np.array([[.8, .2], [-.1, .9], [.1, .1]]) # encoder outputs
E = np.array([[0., 0.], [1., 0.], [0., 1.]]) # the learned table
d = ((Z[:, None, :] - E[None, :, :]) ** 2).sum(-1)
idx = d.argmin(1)
print(idx, .25 * np.mean((Z - E[idx]) ** 2)) # indices, commitment lossZ <- matrix(c(.8, .2, -.1, .9, .1, .1), ncol = 2, byrow = TRUE)
E <- matrix(c(0, 0, 1, 0, 0, 1), ncol = 2, byrow = TRUE)
d <- outer(seq_len(nrow(Z)), seq_len(nrow(E)), Vectorize(function(i, k) sum((Z[i, ] - E[k, ])^2)))
idx <- apply(d, 1, which.min) # 1-based indices
print(c(idx, .25 * mean((Z - E[idx, ])^2))) # indices, commitment lossR counts from 1, so its indices are one higher: the same choice.
Gradients through a lookup
ReadPicking the nearest entry has no useful gradient. VQ-VAE uses the straight-through estimatorStraight-through estimatorTreats a step with no useful gradient (rounding, nearest-code lookup) as the identity on the backward pass.: on the backward pass it pretends the lookup was the identity and copies the decoder's gradient to the encoder.
Two extra terms do the rest. A codebook term moves each chosen entry toward the encoder outputs that picked it. A commitment term, weighted by a small , keeps encoder outputs near their entries so they don't drift.
Watch for dead entries: vectors no row ever picks. Report how many entries are used, and the perplexity of their use, not only the rebuild error.
Sampling needs a second model
PredictPredict first
A VQ-VAE was trained on images, each encoded as a grid of table indices. How do you generate a new image?
Reveal
Fit a separate prior over index grids, often an autoregressive model, and sample from it. The VQ-VAE alone has no trained prior; picking entries uniformly ignores which codes occur together.
Match the codes with a discriminator
ReadAn adversarial autoencoderAdversarial autoencoderAn autoencoder whose codes are pushed to look like prior draws by a discriminator, instead of by a KL term. keeps a deterministic encoder and drops the KL term. Instead, a discriminator learns to tell codes of real rows from draws of the prior, and the encoder learns to fool it.
What gets matched is the aggregate posteriorAggregate posteriorThe distribution of codes over the whole dataset, the mix of every row's posterior; it should match the prior you sample from.: the distribution of codes over the whole dataset. That is the distribution that matters for sampling, since you will decode prior draws and want them to land where real codes landed.
Reference · DNN039 · Explained hereAdversarial autoencoder (AAE)AAE trains reconstruction while an adversarial discriminator aligns the aggregated encoder-code distribution with a chosen prior.The adversarial terms
ReadIn the reference's example the discriminator rates three prior draws as likely real and three encoded rows as likely fake. Its loss is 0.592. The encoder's total loss, rebuild plus a small weight on fooling the discriminator, is 0.274.
Training inherits GAN trouble: the two players can oscillate, and the discriminator can win too easily. Check that prior samples decode to realistic rows, not only that the losses settled.
What runs here
ReadCheck: discrete and adversarial codes
CheckpointCheck yourself
How does a VQ-VAE send gradients from the decoder back to the encoder through the nearest-entry lookup?
Show the answer
Answer: a
The straight-through estimator passes the decoder's gradient unchanged to the encoder output. Separate codebook and commitment terms train the table and keep the two close.
Check yourself
A VQ-VAE with 512 table entries rebuilds images well, but only 40 entries are ever used. What should you report?
Show the answer
Answer: b
Dead entries are a known failure. Report how many entries are used and how evenly, alongside rebuild error.
Check yourself
Why can't you sample a new image from a trained VQ-VAE alone?
Show the answer
Answer: b
The table and decoder define how indices become images. Which index grids are plausible is learned by a separate prior over the codes.
Check yourself
What does an adversarial autoencoder's discriminator try to tell apart?
Show the answer
Answer: b
It works in code space. Fooling it pushes the distribution of codes over the dataset toward the prior you'll sample from.
Check yourself
How does an adversarial autoencoder differ from a VAE?
Show the answer
Answer: a
A VAE pulls every row's code distribution toward the prior. An AAE only asks that codes, pooled over rows, look like prior draws. It gives no likelihood bound, and inherits GAN training trouble.
Recap
Recap- A VQ-VAE snaps codes to the nearest learned vector; straight-through gradients and a commitment term train it.
- Check codebook use, and fit a separate prior over codes before sampling.
- An adversarial autoencoder matches the pooled codes to the prior with a discriminator instead of a KL term.
- Both are explained here; CodeSplash runs the VAE and TVAE.
Concepts in this lesson