Learned Tokenizers for Images & Audio
VQ-VAE, VQGAN, residual and finite scalar quantization.
Transformers model sequences of discrete tokens, and images and sound are not made of tokens. Learned tokenizers fix that: an autoencoder whose code is forced through a finite vocabulary turns a photo into a few hundred integers and a second of audio into a few hundred more, at compression ratios of tens to hundreds. How to train through a rounding step, and how to keep a vocabulary alive, turn out to be the hard parts.
What you’ll learn
- Define the VQ-VAE bottleneck and loss, explain the role of each term, and derive the straight-through gradient and the EMA codebook update as online k-means.
- Explain how VQGAN's perceptual and adversarial losses make aggressive downsampling usable, and how a transformer prior over codes generates images.
- Diagnose codebook collapse and compare its remedies: k-means initialization, dead-code reset, low-dimensional normalized lookup and entropy penalties.
- Compute bitrates of residual vector quantizers in neural audio codecs, and explain how finite scalar and lookup-free quantization replace the learned codebook.
Vector quantization as a bottleneck
Each term has one job. The codebook term moves each selected codeword toward the encoder outputs assigned to it. The commitment term stops the encoder outputs from drifting arbitrarily far from their codewords; without it, nothing bounds them, since the codebook term only moves the codewords. And the reconstruction term would never reach the encoder, because is piecewise constant: its derivative is zero almost everywhere.
The straight-through estimator (Bengio, Léonard & Courville, 2013) bridges the gap by pretending the quantizer is the identity in the backward pass: it copies onto . In code, has the value and the gradient of . The estimate is biased, but because the commitment term keeps close to , the decoder's gradient at is a reasonable proxy for its gradient at .
import torch
import torch.nn.functional as F
def vector_quantize(z_e, codebook, beta=0.25):
# z_e: (N, D) encoder outputs, flattened over the grid; codebook: (K, D) parameter
d = (z_e.pow(2).sum(1, keepdim=True)
- 2 * z_e @ codebook.t()
+ codebook.pow(2).sum(1)) # (N, K) squared distances
idx = d.argmin(dim=1) # the tokens
z_q = codebook[idx]
codebook_loss = F.mse_loss(z_q, z_e.detach()) # moves codewords
commit_loss = F.mse_loss(z_e, z_q.detach()) # anchors the encoder
z_q = z_e + (z_q - z_e).detach() # straight-through estimator
return z_q, idx, codebook_loss + beta * commit_loss.detach() is PyTorch's stop-gradient. The last line returns a tensor whose value is the quantized vector but whose gradient flows to z_e unchanged.
The objective is a convex quadratic in . Setting its gradient to zero gives the centroid:
A gradient step of size on the batch's codebook loss is , a move toward the batch centroid . Replacing it with exponential moving averages of the counts and sums, with decay (van den Oord et al. used ), tracks the centroid of all recent assignments directly:
The EMA variant needs no codebook loss and no learning rate for the codebook, and it is widely used in audio codecs. Both versions share k-means' weakness: a codeword that is nobody's nearest neighbor has and never moves.
Priors over codes, and VQGAN
A trained tokenizer is half a generative model. The other half is a prior over token grids, fitted afterward by maximum likelihood on the tokens of the training set: a PixelCNN in the original VQ-VAE, a transformer in later work. To sample, draw a token grid from the prior and decode it. The prior works on a far shorter sequence than the pixels: for ImageNet images, van den Oord et al. used a grid with , a 42.6-fold reduction in bits ( against ). VQ-VAE-2 (Razavi, van den Oord & Vinyals, 2019) added a hierarchy: a coarse top grid for global structure and a finer bottom grid, encoded conditionally on the top, for texture and detail, each with its own autoregressive prior.
Push the downsampling further and squared-error reconstructions turn to mush. VQGAN (Esser, Rombach & Ommer, 2021) keeps the VQ bottleneck but changes what "reconstruct" means. It replaces the pixel loss with a perceptual loss (distances between features of a pretrained network) and adds a patch-based discriminator that judges whether local patches of the reconstruction look real. The decoder becomes a conditional generator: it may invent high-frequency detail, as long as it is plausible and consistent with the tokens.
With a downsampling factor , a image becomes a grid: 256 tokens from a vocabulary of 1,024 in the default setting (16,384 for class-conditional ImageNet). A GPT-style transformer then models the 256 tokens autoregressively, and for megapixel images it is applied in a sliding window. The recipe, tokenize with a perceptual-adversarial autoencoder, then model the tokens, became a template: latent diffusion trains the same kind of autoencoder with a continuous, KL-regularized or VQ-regularized latent and runs diffusion there instead (Rombach et al., 2022; see Latent Spaces for Generative Models).
Think first DALL·E's first version (Ramesh et al., 2021) turned each RGB image into a grid of tokens from a vocabulary of 8,192. By what factor does that shrink the number of bits, if pixels take 8 bits per channel?
The image holds bits; the tokens hold bits, about 118 times fewer. That discrete VAE was trained with a Gumbel-softmax relaxation of the token choice rather than a straight-through estimator.
Codebook collapse
A codebook of entries can carry bits per token only if all entries are used. In practice many codewords die. At initialization some codewords lie far from every encoder output; they are never selected, receive no gradient from the codebook term (or no EMA update), and stay stranded, while the encoder outputs and the live codewords co-adapt elsewhere. Usage is measured by the fraction of codes used on held-out data, or by the perplexity of the empirical code distribution , the effective vocabulary size. Mentzer et al. (2024) report that in their image models VQ used under half of its codewords once the codebook exceeded entries.
Remedies attack the problem at different points:
- Initialize with data. Run k-means on the first batch of encoder outputs and use the centroids as the initial codebook (SoundStream; Zeghidour et al., 2022).
- Reset dead codes. Track an EMA of each code's usage and replace any code whose count falls below a threshold with an encoder output sampled from the current batch (SoundStream, EnCodec).
- Look up in a small, normalized space. ViT-VQGAN (Yu et al., 2022) projects encoder outputs to a low-dimensional space (as few as 8 dimensions) for the lookup and -normalizes both outputs and codewords, so that matching is by cosine similarity on a sphere; usage and reconstruction both improved.
- Penalize low entropy. Add a term that rewards confident per-token assignments but a uniform average usage, as in MAGVIT-v2 (below).
In a VQ layer trained with the codebook loss , codeword has not been the nearest neighbor of any encoder output for thousands of steps. What happens to it?
- It drifts toward the mean of all encoder outputs
- The commitment loss pulls encoder outputs toward it
- It is pushed away from the data
- Nothing: it receives no gradient and stays where it is unless it is explicitly reset
Show the answer
D. Nothing: it receives no gradient and stays where it is unless it is explicitly reset
The codebook term involves only the selected codeword for each output, so an unselected codeword has zero gradient, and the EMA update has . Like an empty cluster in k-means, it stays dead until something, such as a reset to a current encoder output, moves it.
Residual quantization and neural audio codecs
Audio is the hardest test of a single codebook. A neural audio codec encodes a waveform into latent frames per second and must hit a bitrate , so each frame gets bits. SoundStream (Zeghidour et al., 2022) at 24 kHz uses encoder strides , one frame per 320 samples, so ; at 6 kbps each frame gets 80 bits, which a single quantizer could spend only with codewords. Residual vector quantization (RVQ) spends the bits in stages instead:
Two training tricks make RVQ codecs practical. Quantizer dropout samples uniformly from for each training example and uses only the first stages, so one model learns to decode at every bitrate; SoundStream covers 3 to 18 kbps this way. And the codebooks use EMA updates with k-means initialization and dead-code replacement, exactly the remedies of the previous step. EnCodec (Défossez et al., 2023) follows the same design at 75 frames per second with 1,024-entry codebooks, adds a multi-scale spectrogram discriminator, and offers 1.5 to 24 kbps by varying the number of stages.
Codec tokens made audio a language-modeling problem. AudioLM (Borsos et al., 2023) generates speech and piano continuations with a hierarchy of transformers: first coarse "semantic" tokens from a self-supervised speech model, then the coarse RVQ stages of a SoundStream codec, then its fine stages. The stage index doubles as a level of detail, which lets a generator spend its effort on the coarse tokens first.
EnCodec's 24 kHz model emits 75 frames per second and uses codebooks of 1,024 entries. How many residual stages does it need for 6 kbps?
Show the answer
8 stages
Each stage adds bits per second, so 6,000 bits per second needs stages. The same arithmetic gives 2 stages at 1.5 kbps and 32 at 24 kbps.
Codebooks without codebooks: FSQ and LFQ
Finite scalar quantization (FSQ; Mentzer et al., 2024) removes the learned codebook entirely. Project the encoder output down to a handful of dimensions (typically fewer than 10), squash coordinate into a bounded interval, and round it to one of integer levels. The codebook is implicit: the grid of all level combinations, of size . Gradients cross the rounding with the straight-through estimator, and nothing else is needed: no codebook loss, no commitment loss, no reseeding, no entropy penalty.
import torch
def fsq(z, levels):
# z: (..., d) encoder outputs; odd levels per coordinate, e.g. [7, 5, 5, 5, 5]
half = (torch.tensor(levels, dtype=z.dtype) - 1) / 2
bounded = half * torch.tanh(z) # in (-half, half)
q = bounded + (torch.round(bounded) - bounded).detach() # straight-through round
return q / half # a grid in [-1, 1]With odd , coordinate rounds to one of the integers from to . Even need an asymmetric offset, which the paper's implementation adds. The token index is the mixed-radix number formed by the rounded coordinates.
FSQ with levels , the configuration Mentzer et al. recommend for a codebook of about . How many codes does the implicit codebook have?
Show the answer
64000 codes
, close to , from six scalars and no stored vectors. Their other recommendations follow the same pattern: for about (240 codes), for about (1,000).
Why does it work? Every point of the bounded box rounds to some grid point, and the encoder is free to spread its outputs over the whole box, so there are no stranded codewords to collapse. Mentzer et al. report near-complete usage even for codebooks around , where VQ in the same models used under half its codes, and generation quality competitive with VQ when FSQ replaced it in MaskGIT-style image generators. The price is a fixed, axis-aligned grid: the encoder, not the codebook, must do all the adapting.
Lookup-free quantization (LFQ), introduced with the MAGVIT-v2 tokenizer (Yu et al., 2024), is the two-level extreme: each of coordinates is quantized to its sign, , and the token index is the binary number . With the vocabulary has 262,144 entries and no embedding table. An entropy penalty, , pushes each token toward a confident assignment while keeping average usage spread out. Yu et al. found that with VQ a larger vocabulary improved reconstruction but eventually hurt generation, while with LFQ both kept improving as the vocabulary grew.
| Quantizer | Learned table | Effective vocabulary | Auxiliary losses | Typical home |
|---|---|---|---|---|
| VQ | codewords | , minus dead codes | codebook (or EMA) and commitment | VQ-VAE, VQGAN image tokens |
| RVQ | tables of | reconstructions | as VQ, per stage; quantizer dropout | neural audio codecs |
| FSQ | none (fixed grid) | none | image and video tokenizers | |
| LFQ | none (signs) | for coordinates | entropy penalty | MAGVIT-v2 image and video tokens |
Key takeaways
- A VQ-VAE snaps each encoder vector to its nearest codeword, turning an image into a grid of tokens; its loss combines reconstruction, a codebook term and a commitment term .
- Gradients cross the argmin by the straight-through estimator; the codebook term (or its EMA version) is online k-means and inherits k-means' dead clusters, fought with data initialization, dead-code resets, normalized low-dimensional lookup and entropy penalties.
- VQGAN's perceptual and patch-adversarial losses make downsampling usable, and a transformer prior over the token grid generates images.
- Residual VQ spends bits per second in coarse-to-fine stages and underlies neural audio codecs; quantizer dropout makes one codec serve many bitrates.
- FSQ and LFQ replace the learned table with a fixed grid of levels or sign patterns, removing collapse and the auxiliary losses.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the VQ-VAE loss, which term updates the codewords?
- , the codebook term
- , the commitment term
- The reconstruction term, through the straight-through estimator
- None: codewords are fixed at initialization
Show the answer
A. , the codebook term
The stop-gradient on makes the codebook term move only the codeword, toward the outputs assigned to it. The commitment term moves only the encoder, and the straight-through estimator sends the reconstruction gradient to the encoder, not to the codebook.
What gradient does the straight-through estimator give the encoder output from the reconstruction loss?
- Zero, because the nearest-neighbor lookup is piecewise constant
- The gradient of the loss with respect to the quantized vector, , copied unchanged
- The exact derivative of the quantizer, computed by finite differences
- The gradient with respect to the codeword, scaled by
Show the answer
B. The gradient of the loss with respect to the quantized vector, , copied unchanged
The quantizer is treated as the identity in the backward pass. This is biased, since the true derivative is zero almost everywhere, but the commitment term keeps near , where the copied gradient is a reasonable proxy.
A speech codec produces 50 latent frames per second and quantizes each with 12 residual stages of 2,048 codewords. What is its bitrate?
- 600 bits per second
- 1.2 megabits per second
- 6.6 kilobits per second
- 13.2 kilobits per second
Show the answer
C. 6.6 kilobits per second
Each stage sends one index of bits per frame: bits per second.
Why does finite scalar quantization not suffer from codebook collapse?
- It adds a stronger commitment loss than VQ
- It resets unused codes more often
- It uses a much smaller vocabulary than VQ
- Its codebook is a fixed grid over a bounded box, so every rounded output is a valid code and no learned codewords can be stranded away from the data
Show the answer
D. Its codebook is a fixed grid over a bounded box, so every rounded output is a valid code and no learned codewords can be stranded away from the data
Collapse in VQ comes from learned codewords that no encoder output selects and that then never move. FSQ has no learned codewords: the encoder learns to spread its outputs over the grid, and Mentzer et al. report near-complete usage without any auxiliary loss.
Further reading
- A. van den Oord, O. Vinyals & K. Kavukcuoglu, "Neural discrete representation learning," NeurIPS (2017).
- P. Esser, R. Rombach & B. Ommer, "Taming transformers for high-resolution image synthesis," CVPR (2021).
- N. Zeghidour, A. Luebs, A. Omran, J. Skoglund & M. Tagliasacchi, "SoundStream: an end-to-end neural audio codec," IEEE/ACM Transactions on Audio, Speech, and Language Processing (2022).
- F. Mentzer, D. Minnen, E. Agustsson & M. Tschannen, "Finite scalar quantization: VQ-VAE made simple," ICLR (2024).
- L. Yu et al., "Language model beats diffusion: tokenizer is key to visual generation," ICLR (2024).