In my last post on VAEs, I went from SVD to a VAE step by step: straight axes, then curved axes, then a latent space packed into a Gaussian so you can sample from it. Every latent there is a list of real numbers.
LLMs work differently. They predict the next token from a fixed vocabulary, and each token is just an integer. So I wondered: what if the latent of a VAE were a token too? Could an image become a grid of integers, so it could be generated the same way text is?
That’s what a VQ-VAE (vector-quantised VAE, van den Oord et al., 2017) does.
How I picture it: XGBoost
XGBoost makes a rough guess, looks at the error that’s left (the residual), and fits the next tree to that error. Round after round, the error shrinks.
A VQ-VAE encoder feels similar to me. It outputs a vector, and that vector is compared with its nearest entry in a codebook, a learned list of vectors. The gap between the two is a residual. Each training step uses it to nudge the encoder, along with the error in the rebuilt image, and the outputs settle close to the codebook. With squared error, this link is direct: the gradient is just the residual times 2.
The analogy has a limit. XGBoost adds a new tree each round and keeps the old ones fixed. A plain VQ-VAE has one encoder and updates its weights in place, and the codebook moves too. The closer match to boosting is the residual VQ-VAE at the end of this post, which stacks codebooks, each one fitting what the last one left behind.
The one change: snap to a codebook
A VQ-VAE keeps the encoder and decoder. It adds a codebook: a list of \(K\) learned vectors, each with an index from 0 to \(K-1\).

- The encoder turns the input into a grid of vectors, \(z_e\).
- Each vector is replaced by the closest vector in the codebook. All you need to store is which one, an integer.
- Those codebook vectors, \(z_q\), go to the decoder, which rebuilds the input.
The codebook is a vocabulary that the model learns by itself. The middle grid of integers is the “sentence” that describes the image.
The arc again
Here’s the same 2D arc from the VAE post (the same 400 points), this time with a codebook of 8 vectors. Each point is stored as just one integer from 0 to 7:

Each point is described with very little information in all three methods, but in different ways:
| Method | What stores one point | Error |
|---|---|---|
| SVD | 1 real number, along a straight line | 0.129 |
| Autoencoder | 1 real number, along a learned curve | 0.006 |
| Vector quantisation | 1 integer out of 8 (3 bits) | 0.040 |
The SVD connection carries on, just in a different form. SVD gives you a few directions and stores how far along each one you are. A codebook gives you a few points and stores which one you’re nearest to. If that sounds like k-means, it is. The codebook is basically k-means clustering that runs inside the network and gets learned together with the encoder. (For this figure I literally ran k-means.)
Two problems, two small tricks
Problem 1: “nearest” has no gradient. Picking the closest code is an argmin, so a tiny change to the encoder output usually changes nothing, and when it does, the output jumps. Backprop can’t get through that.
The fix is the straight-through estimator. On the forward pass, use the snapped vector. On the backward pass, pretend the snapping never happened and copy the decoder’s gradient straight back to the encoder (the dashed red arrow in the diagram). In PyTorch it’s one line:
z_q = z_e + (z_q - z_e).detach() # forward: z_q, backward: gradient flows to z_eProblem 2: the codebook gets no gradient either, because of that same shortcut. So the loss gets two extra terms that pull the codes and the encoder outputs towards each other:
\[ \mathcal{L} = \underbrace{\lVert x - \hat{x} \rVert^2}_{\text{reconstruction}} + \underbrace{\lVert \text{sg}[z_e] - e \rVert^2}_{\text{move codes to encoder outputs}} + \beta\,\underbrace{\lVert z_e - \text{sg}[e] \rVert^2}_{\text{keep the encoder near its code}} \]
\(\text{sg}\) means stop-gradient (.detach()), so each term moves only one side. The second term moves each code towards the encoder outputs assigned to it, which is the k-means update again. The third, the commitment loss, stops the encoder outputs from drifting away from the codes. The paper uses \(\beta = 0.25\).
The whole quantiser is a few lines:
dist = torch.cdist(z_e, codebook) # distance to every code
idx = dist.argmin(dim=-1) # the integers we store
z_q = codebook[idx]
loss = ((z_e.detach() - z_q) ** 2).mean() + 0.25 * ((z_e - z_q.detach()) ** 2).mean()
z_q = z_e + (z_q - z_e).detach() # straight-throughWhere did the KL term go?
In the VAE post, the KL term was what made sampling possible. Here it’s gone. The paper’s reasoning: the encoder picks exactly one code, and if the prior is uniform over \(K\) codes, the KL works out to the constant \(\log K\). A constant has no gradient, so it’s dropped.
So how do you generate? In two stages:
- Train the VQ-VAE. Now every image has a grid of integers.
- Train a second model to generate those integer grids, the same way a language model generates tokens. The paper used a PixelCNN. Today it’s often a transformer (which is mostly matrix multiplication).
Sample a grid of integers, look up the codes, decode, and you get a new image.
This is what made VQ-VAE so useful. Images become sequences of tokens. In the paper, 128×128 colour ImageNet images become 32×32 grids of codes with \(K = 512\), about 42.6× fewer bits, and the decoder can still rebuild them.
Next: Next-Concept Modeling
Next-Concept Modeling (NCM) is built on a variant called a multiscale residual VQ-VAE. Residual means you quantise, look at what’s left over, and quantise that again with another codebook, as many times as you like. Multiscale means the first levels use very few codes for the gist and later levels use more for the detail. That coarse-to-fine stack is what lets NCM write a whole sentence in a few passes, and it’s the topic of the next post.
Sources
- van den Oord, Vinyals, Kavukcuoglu. Neural Discrete Representation Learning. NeurIPS 2017, arXiv:1711.00937.
- Bengio, Léonard, Courville. Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation. arXiv:1308.3432, 2013. (The straight-through estimator.)