Simple Algorithm
Deep Learning · Emergence · 28 min

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

LVQ=−log⁡pθ(x∣zq)⏟reconstruction+∥sg⁡[ze]−ek∗∥22⏟codebook+β ∥ze−sg⁡[ek∗]∥22⏟commitment\loss_{\text{VQ}}=\underbrace{-\log p_{\boldsymbol\theta}(\mathbf x\mid\mathbf z_q)}_{\text{reconstruction}}+\underbrace{\norm{\operatorname{sg}[\mathbf z_e]-\mathbf e_{k^*}}_2^2}_{\text{codebook}}+\beta\,\underbrace{\norm{\mathbf z_e-\operatorname{sg}[\mathbf e_{k^*}]}_2^2}_{\text{commitment}}
sg⁡[⋅]\operatorname{sg}[\cdot] is the stop-gradient: the identity going forward, zero derivative going backward. The decoder is trained by the first term only, the codewords by the second only, and the encoder by the first and third. Van den Oord et al. used β=0.25\beta=0.25 and report results robust for β\beta from 0.10.1 to 22.

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 arg min⁡\argmin 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 ∂L/∂zq\partial\loss/\partial\mathbf z_q onto ze\mathbf z_e. In code, zq←ze+sg⁡[zq−ze]\mathbf z_q\leftarrow\mathbf z_e+\operatorname{sg}[\mathbf z_q-\mathbf z_e] has the value zq\mathbf z_q and the gradient of ze\mathbf z_e. The estimate is biased, but because the commitment term keeps ze\mathbf z_e close to zq\mathbf z_q, the decoder's gradient at zq\mathbf z_q is a reasonable proxy for its gradient at ze\mathbf z_e.

python
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.

DerivationProof, and the EMA update
  1. ∇ek∑z∈Sk∥z−ek∥2=2∑z∈Sk(ek−z)=0  ⟺  ek=1nk∑z∈Skz\nabla_{\mathbf e_k}\sum_{\mathbf z\in S_k}\norm{\mathbf z-\mathbf e_k}^2=2\sum_{\mathbf z\in S_k}(\mathbf e_k-\mathbf z)=\mathbf 0\iff\mathbf e_k=\frac1{n_k}\sum_{\mathbf z\in S_k}\mathbf z

    The objective is a convex quadratic in ek\mathbf e_k. Setting its gradient to zero gives the centroid:

  2. Nk←γNk+(1−γ) nk,mk←γ mk+(1−γ)∑z∈Skz,ek←mk/NkN_k\leftarrow\gamma N_k+(1-\gamma)\,n_k,\qquad\mathbf m_k\leftarrow\gamma\,\mathbf m_k+(1-\gamma)\sum_{\mathbf z\in S_k}\mathbf z,\qquad\mathbf e_k\leftarrow\mathbf m_k/N_k

    A gradient step of size η\eta on the batch's codebook loss is ek←ek−2ηnk(ek−zˉk)\mathbf e_k\leftarrow\mathbf e_k-2\eta n_k(\mathbf e_k-\bar{\mathbf z}_k), a move toward the batch centroid zˉk\bar{\mathbf z}_k. Replacing it with exponential moving averages of the counts and sums, with decay γ\gamma (van den Oord et al. used 0.990.99), tracks the centroid of all recent assignments directly:

  3. 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 nk=0n_k=0 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 128×128128\times128 ImageNet images, van den Oord et al. used a 32×3232\times32 grid with K=512K=512, a 42.6-fold reduction in bits (128⋅128⋅3⋅8128\cdot128\cdot3\cdot8 against 32⋅32⋅932\cdot32\cdot9). 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.

min⁡E,G,Zmax⁡D E[LVQ(E,G,Z)+λ LGAN({E,G,Z},D)],λ=∥∇GLLrec∥∥∇GLLGAN∥+δ\min_{E,G,\mathcal Z}\max_D\ \E\big[\loss_{\text{VQ}}(E,G,\mathcal Z)+\lambda\,\loss_{\text{GAN}}(\{E,G,\mathcal Z\},D)\big],\qquad\lambda=\frac{\norm{\nabla_{G_L}\loss_{\text{rec}}}}{\norm{\nabla_{G_L}\loss_{\text{GAN}}}+\delta}
GLG_L is the decoder's last layer and δ=10−6\delta=10^{-6}. The adaptive weight balances the two gradients at the decoder's output, so neither loss swamps the other as their scales drift during training; the adversarial term is switched on only after a warm-up.

With a downsampling factor f=16f=16, a 256×256256\times256 image becomes a 16×1616\times16 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 256×256256\times256 RGB image into a 32×3232\times32 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 256⋅256⋅3⋅8=1,572,864256\cdot256\cdot3\cdot8=1{,}572{,}864 bits; the tokens hold 1,024⋅log⁡28192=1,024⋅13=13,3121{,}024\cdot\log_2 8192=1{,}024\cdot13=13{,}312 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 KK entries can carry log⁡2K\log_2K 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 exp⁡H(p^)\exp H(\hat p) of the empirical code distribution p^\hat p, 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 2112^{11} 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 ℓ2\ell_2-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).
Check your understanding

In a VQ layer trained with the codebook loss ∥sg⁡[ze]−ek∥2\norm{\operatorname{sg}[\mathbf z_e]-\mathbf e_k}^2, codeword e7\mathbf e_7 has not been the nearest neighbor of any encoder output for thousands of steps. What happens to it?

  1. It drifts toward the mean of all encoder outputs
  2. The commitment loss pulls encoder outputs toward it
  3. It is pushed away from the data
  4. 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 nk=0n_k=0. 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 SS latent frames per second and must hit a bitrate RR, so each frame gets R/SR/S bits. SoundStream (Zeghidour et al., 2022) at 24 kHz uses encoder strides 2,4,5,82,4,5,8, one frame per 320 samples, so S=75S=75; at 6 kbps each frame gets 80 bits, which a single quantizer could spend only with 2802^{80} codewords. Residual vector quantization (RVQ) spends the bits in stages instead:

r0=y,qi=Qi(ri−1),ri=ri−1−qi(i=1,…,Nq),y^=∑i=1Nqqi,R=S⋅Nq⋅log⁡2K\mathbf r_0=\mathbf y,\qquad\mathbf q_i=Q_i(\mathbf r_{i-1}),\qquad\mathbf r_i=\mathbf r_{i-1}-\mathbf q_i\quad(i=1,\dots,N_q),\qquad\hat{\mathbf y}=\sum_{i=1}^{N_q}\mathbf q_i,\qquad R=S\cdot N_q\cdot\log_2K
Each quantizer QiQ_i is an ordinary VQ codebook of size KK applied to what the previous stages left over. With Nq=8N_q=8 codebooks of K=1024K=1024 entries, the 80 bits are 8×108\times10: 8×10248\times1024 stored vectors index 2802^{80} possible reconstructions.

Two training tricks make RVQ codecs practical. Quantizer dropout samples nqn_q uniformly from {1,…,Nq}\{1,\dots,N_q\} for each training example and uses only the first nqn_q 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.

Predict before you look

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 75×log⁡21024=75×10=75075\times\log_2 1024=75\times10=750 bits per second, so 6,000 bits per second needs 6000/750=86000/750=8 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 dd (typically fewer than 10), squash coordinate ii into a bounded interval, and round it to one of LiL_i integer levels. The codebook is implicit: the grid of all level combinations, of size ∏iLi\prod_iL_i. 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.

python
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 LiL_i, coordinate ii rounds to one of the LiL_i integers from −(Li−1)/2-(L_i-1)/2 to (Li−1)/2(L_i-1)/2. Even LiL_i need an asymmetric offset, which the paper's implementation adds. The token index is the mixed-radix number formed by the rounded coordinates.

Predict before you look

FSQ with levels [8,8,8,5,5,5][8,8,8,5,5,5], the configuration Mentzer et al. recommend for a codebook of about 2162^{16}. How many codes does the implicit codebook have?

Show the answer

64000 codes

8⋅8⋅8⋅5⋅5⋅5=512⋅125=64,0008\cdot8\cdot8\cdot5\cdot5\cdot5=512\cdot125=64{,}000, close to 216=65,5362^{16}=65{,}536, from six scalars and no stored vectors. Their other recommendations follow the same pattern: [8,6,5][8,6,5] for about 282^8 (240 codes), [8,5,5,5][8,5,5,5] for about 2102^{10} (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 2142^{14}, 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 log⁡2K\log_2K coordinates is quantized to its sign, q(zi)=sign⁡(zi)∈{−1,1}q(z_i)=\operatorname{sign}(z_i)\in\{-1,1\}, and the token index is the binary number ∑i2i−11[zi>0]\sum_i2^{i-1}\mathbb 1[z_i>0]. With K=218K=2^{18} the vocabulary has 262,144 entries and no embedding table. An entropy penalty, E[H(q(z))]−H(E[q(z)])\E\big[H(q(\mathbf z))\big]-H\big(\E[q(\mathbf z)]\big), 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.

QuantizerLearned tableEffective vocabularyAuxiliary lossesTypical home
VQK×DK\times D codewordsKK, minus dead codescodebook (or EMA) and commitmentVQ-VAE, VQGAN image tokens
RVQNqN_q tables of K×DK\times DKNqK^{N_q} reconstructionsas VQ, per stage; quantizer dropoutneural audio codecs
FSQnone (fixed grid)∏iLi\prod_iL_inoneimage and video tokenizers
LFQnone (signs)2d2^{d} for dd coordinatesentropy penaltyMAGVIT-v2 image and video tokens
All four are trained through the quantizer with the straight-through estimator. What differs is where the vocabulary lives and what keeps it in use.

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 β∥ze−sg⁡[e]∥2\beta\norm{\mathbf z_e-\operatorname{sg}[\mathbf e]}^2.
  • 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 16×16\times downsampling usable, and a transformer prior over the token grid generates images.
  • Residual VQ spends R=S⋅Nq⋅log⁡2KR=S\cdot N_q\cdot\log_2K 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 ∏iLi\prod_iL_i levels or 2d2^d 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.

Question 1

In the VQ-VAE loss, which term updates the codewords?

  1. ∥sg⁡[ze]−ek∗∥2\norm{\operatorname{sg}[\mathbf z_e]-\mathbf e_{k^*}}^2, the codebook term
  2. β∥ze−sg⁡[ek∗]∥2\beta\norm{\mathbf z_e-\operatorname{sg}[\mathbf e_{k^*}]}^2, the commitment term
  3. The reconstruction term, through the straight-through estimator
  4. None: codewords are fixed at initialization
Show the answer

A. ∥sg⁡[ze]−ek∗∥2\norm{\operatorname{sg}[\mathbf z_e]-\mathbf e_{k^*}}^2, the codebook term

The stop-gradient on ze\mathbf z_e 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.

Question 2

What gradient does the straight-through estimator give the encoder output ze\mathbf z_e from the reconstruction loss?

  1. Zero, because the nearest-neighbor lookup is piecewise constant
  2. The gradient of the loss with respect to the quantized vector, ∂L/∂zq\partial\loss/\partial\mathbf z_q, copied unchanged
  3. The exact derivative of the quantizer, computed by finite differences
  4. The gradient with respect to the codeword, scaled by β\beta
Show the answer

B. The gradient of the loss with respect to the quantized vector, ∂L/∂zq\partial\loss/\partial\mathbf z_q, 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 ze\mathbf z_e near zq\mathbf z_q, where the copied gradient is a reasonable proxy.

Question 3

A speech codec produces 50 latent frames per second and quantizes each with 12 residual stages of 2,048 codewords. What is its bitrate?

  1. 600 bits per second
  2. 1.2 megabits per second
  3. 6.6 kilobits per second
  4. 13.2 kilobits per second
Show the answer

C. 6.6 kilobits per second

Each stage sends one index of log⁡22048=11\log_2 2048=11 bits per frame: R=S⋅Nq⋅log⁡2K=50⋅12⋅11=6,600R=S\cdot N_q\cdot\log_2K=50\cdot12\cdot11=6{,}600 bits per second.

Question 4

Why does finite scalar quantization not suffer from codebook collapse?

  1. It adds a stronger commitment loss than VQ
  2. It resets unused codes more often
  3. It uses a much smaller vocabulary than VQ
  4. 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).