Autoencoders and VAEs: latents and image tokenizers

How images become the small continuous latents diffusion models work in and the discrete tokens autoregressive models predict: why a plain autoencoder cannot generate, the VAE and its loss in working form, β, posterior collapse, blur, VQ-VAE and codebook collapse, FSQ and LFQ, VQGAN and tokens per image, the autoencoders inside real generators and their scaling factors, and how to evaluate one. Tiny models trained on an Apple M1 Pro, nine pretrained autoencoders on the same 16 images, published results kept apart. A child of Topic: generative-and-multimodal. Data as of October 2026. Reading: 40 min, plus 17 in closed details.

An autoencoder squeezes an image into a small latent and draws it back. What you ask that latent to be decides what a generator can do with it: any numbers (a plain autoencoder: good copies, but random codes decode to nonsense), a Gaussian per image pulled towards N(0, I) (a VAE: you can sample it), or a grid of integers from a codebook (VQ, FSQ, LFQ: tokens a transformer can predict). Whatever the generator makes, the decoder has to draw, so its skill caps every image.

Fig. 1, step by step: one test image through the topic's three tiny models

  1. The image: 1,024 numbers. A Fashion-MNIST test garment, 28 × 28 grey pixels padded to 32 × 32, the input of every tiny model here.
  2. The encoder narrows it. Two stride-2 convolutions halve the grid twice while adding channels: 16 × 16 × 32, then 8 × 8 × 64 (the topic's shared ConvAE, root src/data/nets.py; each glass plate stands for 8 channels). The decoder, faint on the right, is its mirror image.
  3. Plain autoencoder: any 16 numbers. A linear layer squeezes the map to 16 numbers, here -17.9 to 16.6, wherever training put them; the decoder draws them back at 26.0 dB on this image. Random codes decode to nonsense (section 2).
  4. VAE: 16 means and 16 spreads. The same network outputs a mean μ (here -2.0 to 1.0) and a spread σ (0.07 to 0.84) per number, a small Gaussian pulled towards N(0, I) by a KL term, so random draws decode to garments; it costs sharpness: 23.5 dB.
  5. VQ-VAE: 64 tokens. The 8 × 8 map keeps 8 channels and each position is replaced by the nearest of 128 learned vectors; its index is a 7-bit token (colours here: token ids; equal colours, equal tokens), 448 bits per image, predicted like words: 26.1 dB, the best of the three on this image.
  6. The generator works in the middle. Train the autoencoder once; a diffusion or flow model then learns the continuous latents and a transformer the tokens, and whatever it makes, the decoder has to draw, so the decoder caps every image.

One set of images, three bottlenecks: the latent's form is the design choice

image, 32 × 32 = 1,024 numbers→encoder→latent: the generator works here→decoder→image
InputThe latent (same encoder and decoder networks; only the middle differs)OutputPSNR
Plain autoencoder: 16 numbersStandard deviation 5.0 to 9.5 per number over the test set.
21.4 dB
VAE: 16 means and 16 spreadsPulled towards N(0, I); a little softer.
20.15 dB
VQ-VAE: 8 × 8 grid of integers64 tokens of 7 bits.
23.8 dB

Four Fashion-MNIST test images through three tiny models trained for the topic (root Latent lab recordings); PSNR over the 10,000 test images. A generator then learns the middle column: diffusion or flow for continuous latents, a transformer for tokens. measured on Apple M1 Pro

Why 64 tokens of 7 bits beat 16 real numbers (depth)

From the old root Latent lab: the VQ-VAE reconstructs better than the 16-number autoencoder (23.8 dB against 21.4 dB above), although each of its slots holds only 7 bits. A real number in a network is not infinitely precise in practice: the decoder can only use the precision training made it sensitive to, so spatial layout (64 positions, each with its own code) beats a few global numbers.

The five kinds in one table: latent, loss, failure, use (reference)
KindWhat the latent isTrained withMain failureUsed for, 2026
Plain autoencoderAny numbers; no shape imposedReconstruction loss onlyRandom codes decode to nonsense (section 2)Compression, features; generation only with a density fitted afterwards
VAEA Gaussian per image, pulled towards N(0, I)Reconstruction + β × KL (the negative ELBO at β = 1)Blur; posterior collapse with a strong decoder (sections 6, 7)With a tiny KL weight and perceptual and adversarial losses: the compressor of every latent diffusion and flow model
VQ-VAEA grid of integers, each the index of the nearest codebook vectorReconstruction + codebook + commitment losses, straight-through gradientCodebook collapse (section 8)Image tokens for autoregressive and masked generators
VQGANThe same, sharperVQ-VAE losses + LPIPS + patch-GAN lossGAN instability; collapse at large codebooks (section 10)The standard image tokenizer recipe since 2021
FSQ, LFQIntegers from rounding each channel (FSQ) or taking its sign (LFQ)Reconstruction (+ the VQGAN losses); no codebook to learnFew channels limit what one token holds (section 9)Large-vocabulary tokenizers (MAGVIT-v2, Cosmos, recent video tokenizers)

You need: nothing beyond PyTorch and likelihoods. Why "reconstruction plus KL" bounds the log-likelihood (the ELBO's derivation) is on Variational inference and generative-model maths; what runs on these latents is on Latent diffusion and diffusion transformers and Native multimodal and any-to-any models.

New terms

Latent (code)
the encoder's output, the small description the decoder rebuilds the image from.
Reparameterisation
z = μ + σε with ε drawn outside the network, so gradients reach μ and σ.
KL term, rate
KL(q(z | x) ‖ N(0, I)): how many nats the code carries about the image; its weight is β.
Active unit
a latent dimension whose mean varies across images (variance over 0.01); an inactive one carries nothing.
Posterior collapse
the KL falls to about 0 and the decoder ignores the code.
Codebook, VQ
K learned vectors; vector quantization replaces each encoder vector by the nearest one and keeps its index as a token.
Straight-through
copying the decoder's gradient past the non-differentiable lookup or rounding to the encoder.
FSQ, LFQ
quantizers with a fixed grid instead of a learned codebook: round each channel to a few levels, or keep only its sign.
Scaling factor
the constant (SD 1.x: 0.18215) that brings a diffusion VAE's latent to unit scale before noising.
LPIPS, rFID
a perceptual distance between two images; a Fréchet distance between a set of reconstructions and the originals.

The running example (the topic's, root src/data/README.md): Fashion-MNIST (70,000 grey 28 × 28 clothing images, 10 classes, padded to 32 × 32) for every tiny model, all on the topic's shared ConvAE (two stride-2 convolutions to an 8 × 8 grid and back) with one recipe (seed 0, batch 128, AdamW at 10−3, 5,000 steps, about two minutes on the laptop's GPU); and the topic's 16 colour test images at 512 × 512 (four public-domain or CC0 photographs, six synthetic scenes, six SD 1.5 generations) for pretrained autoencoders.

1. Why generate in a latent, and the two kinds of latent

A diffusion model runs its network 25 to 50 times per image and an autoregressive model predicts one symbol at a time, so both pay for every number they work on, and most of a 512 × 512 image's 786,432 numbers are detail the eye barely registers (the LDM paper's rate-distortion argument, LDM paper page). So: train an autoencoder once, generate latents, decode once at the end.

Continuous latent, for diffusion and flow

A small grid of real numbers; a VAE in name, trained with a tiny KL weight plus perceptual and adversarial losses (section 11).

Discrete tokens, for autoregressive and masked models

A small grid of integers, each one of K codebook entries, predicted like words so images and text share one sequence (sections 8 to 10).

The cost, either way. Detail the decoder cannot draw (small text, distant faces, fine texture) cannot appear, however good the generator. Positions set the generator's sequence length or spatial size; channels or codebook size set what each position carries. The trade-off is rate (what the latent carries) against distortion (reconstruction error) against how easy the latent is to model, and reconstruction measurements (encode, decode, compare) and generation measurements (sample, decode, compare distributions) often disagree.

What a generator works on for one 512 × 512 image, to scale

Pixels (RGB)786,432
FLUX.1 latent, 64 × 64 × 1665,536
SD 1.5 latent, 64 × 64 × 416,384
DC-AE latent, 16 × 16 × 328,192
Chameleon tokens, 13 bits each1,024

Linear scale; shapes from each model's config (section 11) and Chameleon's paper (section 10), counts derived as height × width × channels. SD 1.5 keeps 48 times fewer numbers than the pixels.

2. Why a plain autoencoder does not generate, and what the VAE changes

To generate, you pick a code and decode it, but a plain autoencoder never says which codes are valid: training only decodes real images' codes, a scattered cloud at whatever scale training chose. Fig. 2: 600 test images (60 per class) through a 2-number autoencoder and a 2-number VAE, identical except for the KL term (root Latent lab recordings, runs ae2, vae2).

  1. The autoencoder's codes. Each ball is one test image at its 2-number code, coloured by class. Training put them in a box from z1 -15 to 34 and z2 -32 to 38, in class islands with gaps between them; nothing said where valid codes are.
  2. Where N(0, I) draws land. The dashed circle of radius 2 holds 86% of 2-D N(0, I) draws (1 − e−2) derived; in this box it is smaller than one decode-grid cell, so every random code lands in one small region and decodes to one blob (the tile: what the decoder draws at the grid point nearest the origin).
  3. The VAE's codes fill N(0, I). Same network, plus the KL term: the means sit in a disc of radius about 3 around the origin, box −3 to 3 on both axes, the classes still in neighbourhoods.
  4. Each code is a small Gaussian. The rings are each image's own σ, to scale: on average 0.0589 against the prior's 1, so each image claims a tiny ellipse of the prior.
  5. A random draw decodes to a garment. A draw near the origin, decoded by each model: the VAE draws a plausible garment, the autoencoder its one blob. The VAE's gain is a known density, N(0, I) by construction.
Predict: decode 1,000 random codes z ~ N(0, I) with the 16-number autoencoder. What comes out?

Three readings. N(0, I) fails for the autoencoder. A Gaussian fitted to its own codes beats the VAE: what makes a latent usable is knowing where the codes are, which can be learned after training (Ghosh et al., From Variational to Deterministic Autoencoders, 2019) published; the VAE's gain is that the density is N(0, I) by construction, with no second stage. And all are far from the floor: a decoder fed a simple Gaussian cannot model the data's many modes, which is why real systems put a diffusion or autoregressive model on top of the latent.

Random codes, decoded: the scale of the codes is what matters

Plain autoencoder (16 numbers), z ~ N(0, I): FD 1,756
Same autoencoder, z from a Gaussian fitted to its own training codes: FD 611
VAE (16 numbers, β = 1), z ~ N(0, I): FD 689

FD: Fréchet distance between 1,000 decoded samples and the 10,000 test images in the topic classifier's 128-d feature space (the FID formula with a domain network; lower is better). 1,000 real validation images score 18.9, the floor at this sample size. "Fitted": mean and covariance of 10,000 training codes, then z = mean + Lε with L the Cholesky factor. First 8 of the 1,000 shown. measured on Apple M1 Pro (CPU)

Walking between two images: pixels blend ghosts, a latent walk changes the garment

Mixing pixels
Straight line between the 16-number autoencoder's codes
Straight line between the 16-number VAE's means

t = 0, 1/8, ..., 1; latent rows end on reconstructions. The two latent walks differ little here; the VAE's advantage is off the data (the random codes above). Latent diffusion models interpolate the starting noise instead, spherically (DDIM, section 5.3). measured

Same images, two latent spaces: the VAE puts its codes where N(0, I) draws land

Plain autoencoder, 2 numbers: box z1 -15 to 34, z2 -32 to 38
VAE, 2 numbers (the means): box −3 to 3 on both axes

Dashed circle: radius 2 (Fig. 2). "Decodes": what the decoder draws at 81 grid points. measured (root Latent lab recordings, runs ae2, vae2)

3. The VAE: an encoder that outputs a distribution

The VAE's encoder outputs a mean μ and a log-variance log σ2 per latent dimension: a small Gaussian per image instead of a point. Training decodes a random draw from it and charges for its distance from N(0, I).

  1. The encoder outputs μ and σ. For one test image, the 16-number VAE’s recorded mean and spread per number (the network outputs log σ2; σ is drawn): μ from -2.04 to 0.95, σ from 0.07 to 0.84.
  2. Draw ε outside the network. Sixteen standard-normal numbers drawn outside the network (one draw, illustrative): the randomness enters from outside.
  3. Combine: z = μ + σ · ε. Each number of the code is its mean moved by its own spread times its own noise, so a dimension with a small σ barely moves.
  4. Decode and score. The decoder draws x̂ from z, and the loss adds the reconstruction to β times the KL.
  5. Gradients flow back to μ and σ. z is differentiable in μ and σ (∂z/∂μ = 1, ∂z/∂σ = ε), so the decoder’s gradient reaches the encoder; ε is a constant of the backward pass. Sampling z directly from N(μ, σ2) has no such path.
  6. The KL charge, number by number. ½(μ2 + σ2 − 1 − log σ2) per number, 0 only at μ = 0, σ = 1: this image pays 14.94 nats, from 0.03 to 3.69 per number (the test-set mean is 17.11).
z = μ(x) + σ(x) · ε,   ε ~ N(0, I)
loss = reconstruction(x, decoder(z)) + β · ½ Σj (μj2 + σj2 − 1 − log σj2)
KL
the second term is KL(N(μ, σ2) ‖ N(0, I)) in closed form, in nats; 0 only when μ = 0 and σ = 1, when the code carries nothing
β
1 gives the negative ELBO, the standard VAE loss (derivation: the Math page); section 5 varies it
The code that trained every VAE here, and its last log line (code)
# ConvVAE, the topic's src/data/nets.py lines 249 to 252
def forward(self, x):
    mu, logvar = self.encode(x)
    z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu)     # the reparameterisation trick
    return self.decode(z), mu, logvar

# objectives.py lines 130 to 136
def vae_loss(model, x, y=None, beta=1.0):
    """Negative ELBO (beta = 1) per image: reconstruction + beta * KL(q(z|x) || N(0, I))."""
    logits, mu, logvar = model(x)
    rec = recon_bce(logits, x)
    kl = 0.5 * (mu.pow(2) + logvar.exp() - 1 - logvar).flatten(1).sum(1).mean()
    loss = rec + beta * kl
    return loss, {"loss": loss.item(), "rec": rec.item(), "kl": kl.item()}
{"step": 5000, "sec": 114.99, "grad_norm": 89.1906, "loss": 239.70682, "rec": 222.66508, "kl": 17.04174}

Last log line of the 16-number VAE at β = 1 (root Latent lab recording vae16_b1p0.jsonl). diffusers samples the same way: x = self.mean + self.std * sample (vae.py line 711, v0.41.0), with the log-variance clamped to [−30, 20] (line 694).

The cost, measured. The 16-number VAE pays 17.11 nats of KL per test image and reconstructs worse than the plain autoencoder (218.14 against 212.28 nats, 20.15 against 21.4 dB); in return its codes sit where N(0, I) expects them. In the 2-number VAE the encoder's σ averages 0.0589: each image claims a tiny ellipse of a space whose spread is 1. measured

How to check. Log the KL per dimension: near 0 means unused (μ always about 0, σ about 1). Active units count dimensions whose μ varies across images with variance above 0.01 (Burda et al. 2015); this VAE uses 16 of 16.

A 2-number VAE on MNIST: training curves, test numbers, latent map (measured, a second dataset)

The same model on handwritten digits instead of garments, trained in nats per image with its own script (built for the Math page's ELBO sections and moved here; the ELBO's gap and its split are taught on Variational inference and generative-model maths, sections 3 and 4).

Setup (src/vi_mnist/vae.py, PyTorch 2.11 on 2 CPU threads): MNIST handwritten digits, 60,000 for training and 10,000 for testing, binarised (pixel above 127 becomes 1); encoder 784 to 400 (ReLU) to a 2-D mean and log-variance; decoder 2 to 400 (ReLU) to 784 Bernoulli logits; Adam at 10−3, batches of 128, 30 epochs (14,070 steps, about 1.5 to 4 seconds per epoch). A 2-D latent is chosen so it can be drawn; it reconstructs worse than a larger one (the 16-D MNIST sweep in section 5).

The two terms during training (training batches, averaged over each 100 steps; nats per image). Left axis: reconstruction, −Eq log p(x | z). Right axis: KL(q(z | x) ‖ p(z)).

What the curves say. Reconstruction falls fast (222.5 nats at step 100, 159 by step 700, 138 at the end on training batches). The KL first falls (7.1 to 5.4 nats by step 700) and then slowly rises to about 6.3: early on the cheapest way to raise the ELBO is to keep codes near the prior; once the decoder can use precise codes, buying information about each image in the latent pays for its KL. On the test set after 30 epochs: reconstruction 143.98 and KL 6.22, so the negative ELBO is 150.20 nats per image. The KL is the number of nats the code carries about each image (at most; it is an upper bound on that mutual information, Information theory for ML, section 8): about 6.2 nats, 9 bits, enough to say which digit and roughly how it is drawn, not the 144 nats of pixel detail the decoder still has to guess.

The posterior widths are tiny. Averaged over test images, the encoder's standard deviations are 0.066 and 0.086 against the prior's 1: each image owns a small patch of the latent plane. Below: 1,500 test images' codes coloured by digit, a 10 by 10 grid of decoded latent points (Kingma and Welling's Figure 4 recipe: grid points at evenly spaced quantiles of the prior), and ten reconstructions.

These numbers are not comparable with papers
Published MNIST log-likelihoods (around −80 to −90 nats) use dynamically binarised MNIST (each pixel resampled as Bernoulli of its grey level every epoch) and larger latents. Thresholding at 127, as here, gives a different, less noisy dataset, so the same model scores differently. Compare likelihoods only on the same data, binarisation and test split.

The same 2-D VAE, trained on binarised MNIST (784-400-2 encoder, 2-400-784 Bernoulli decoder, 30 epochs). Left: where the encoder puts 1,500 test images (the mean of each q(z | x)), coloured by the digit's true label, which the model never saw. Right: what the decoder draws at a 10 by 10 grid of latent points. Click a grid cell to mark its z on the map; click a digit to highlight it. The grid covers the prior's central 92% (quantiles 0.04 to 0.96 per axis); the codes themselves spread wider than the prior (standard deviations 1.55 and 1.08 across these images), because the KL term pulls each image's q towards N(0, I) only on average, against the reconstruction term.

Reconstructions

Top: a binarised test image (the first of each digit in the test set). Bottom: the decoder's pixel probabilities at the encoder's mean code. With only 2 latent numbers the decoder draws a typical version of the digit, not this exact one: the 144 nats of reconstruction error per image.

Measurements

All numbers in nats per image, test set unless stated. Training script src/vi_mnist/vae.py; gap split by the Math page's src/data/vae_gap.py on the same checkpoint; one run, seed fixed (another seed would move the last digits).

4. The loss in working form: two numbers, and their units

The two terms balance as the derivation intends only when both are log-probabilities of a whole image, in the same unit; change how either is summed or averaged and you have silently changed β.

loss per image = −log p(x | z)  [summed over all pixels]
+ β · KL(q(z | x) ‖ N(0, I))  [summed over all latent dimensions]
−log p(x | z)
the reconstruction term in nats for the whole image: Bernoulli cross-entropy for the tiny models here, a Gaussian (squared error) or Laplace (absolute error) likelihood elsewhere
KL
the rate: how many nats the code carries about this image on average

Reading the two numbers. The 16-number VAE ends at 218.14 nats of reconstruction plus 17.11 of KL per test image: 235.25 nats, 0.331 bits per pixel (divide by 1,024 and by ln 2) derived. The KL is the code's budget, 24.7 bits, about a short sentence.

Predict: a tutorial computes the reconstruction with F.binary_cross_entropy(..., reduction="mean") (the default, averaging over the 1,024 pixels) and the KL summed over the 16 dimensions. How many of the 16 latent dimensions stay in use?

The Gaussian decoder's σ is a β. Squared error is a Gaussian decoder with fixed σ: −log p(x | z) = Σ (x − x̂)2 / (2σ2) + a constant, so plain "MSE summed + KL" fixes σ2 = 1/2 and the KL's relative weight is 2σ2 derived. On pixels in [−1, 1], σ = 0.1 makes squared error 100 times dearer than σ = 1: the code carries 65.26 nats instead of 13.21 and reconstructs at 21.39 dB instead of 19.61, but random-code samples get worse (prior FD 813.1 against 661.4): section 5's trade-off, reached by moving a "noise level" nobody thinks of as a weight. All 16 dimensions stay active in both. Or learn σ, as the LDM autoencoder does (closed block below). measured

How to check. Log reconstruction and KL separately, in nats per image; check the reconstruction is summed over pixels (or β rescaled); count active units. A KL near zero under a fine-looking loss curve is the signature.

Four losses that all say β = 1 in the code; the units decide what β really is

Reconstruction termLikelihoodKL natsActive of 16PSNR dBPrior FD
16-number VAE, β = 1 (reference)Bernoulli, summed over pixels17.111620.15689
Mean over pixelsBernoulli, averaged over the 1,024 pixels0.00010.932,382
Squared error, σ = 1Gaussian, Σ(x − x̂)2 / 213.211619.61661
Squared error, σ = 0.1Gaussian, Σ(x − x̂)2 / 0.0265.261621.39813

Three VAEs trained exactly like the reference except for the reconstruction term; 10,000 test images, decoded from the posterior mean; prior FD as in section 2. measured on Apple M1 Pro; src/train_av.py (make_e_loss), src/elbo/eval_elbo.py.

The LDM autoencoder's loss: a learned σ, and LPIPS once per pixel (reference code)

It learns one log-variance for its whole reconstruction term (nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar, contperceptual.py line 53), so its effective weight between reconstruction and KL moves during training. In the same function the LPIPS distance, one number per image, is added to the L1 error of every pixel before the sum (lines 48 to 51 and 57: rec_loss = rec_loss + self.perceptual_weight * p_loss, then torch.sum(...) / shape[0]), so the perceptual term counts once per pixel and channel, 786,432 times at 512 × 512. The KL, summed over the latent and weighted by 10−6 (line 83), is tiny against it by design. Source read at CompVis/latent-diffusion a506df575647.

5. β: a price per nat, and the blur it buys

Raise β and the encoder sends less: reconstructions blur and dimensions switch off, but codes hug N(0, I) more tightly; lower it and you approach the plain autoencoder. Five 16-number VAEs, identical except for β.

Reading the sweep. From β 0.1 to 10 the KL falls from 43.92 to 3.79 nats per image and reconstruction error rises from 212.61 to 250.06 nats (21.35 to 16.43 dB): the blur you see. At β = 10 only 5 of 16 dimensions stay active. Random-code samples are best in the middle (FD 694 at 0.3, 689 at 1) and worse at both ends: at 0.1 the codes drift from N(0, I) (FD 734); at 10 the samples are blurry and less varied (FD 1,029, class entropy 1.685 nats against 1.991 at 1). measured

β-VAE. Higgins et al. use β > 1 on purpose, trading reconstruction for disentangled factors, single dimensions that each move one property (beta-VAE, ICLR 2017) published. Generators use the other end: section 11's autoencoders run at a KL weight of about 10−6 and fix blur with other losses (section 7).

Predict before you drag: at β = 10, are random-code samples better or worse than at β = 1?

0.10.31310
Test images
Reconstructions at this β
Decoded from 8 random codes z ~ N(0, I) (the same draws at every β)

Recorded runs at β = 0.1, 0.3, 1, 3, 10 (root Latent lab recordings). KL and reconstruction in nats per image on the 10,000 test images; prior FD as in section 2. measured on Apple M1 Pro

The same sweep on MNIST, with the likelihood: best near β = 1, half the dimensions dead at β = 8 (measured, a second dataset)
Five VAEs with a 16-D latent: the best log-likelihood near β = 1, and half the dimensions dead at β = 8 (binarised MNIST, the 784-400 network of the 2-number MNIST VAE in section 3 with a 16-D latent, 15 epochs each; test set; rec. is the reconstruction term; src/vi_mnist/vae.py). Bars: the KL carried by each of the 16 latent dimensions, sorted. "Active": how many of the 16 dimensions have a posterior mean that varies across images (variance above 0.01, the criterion of Burda et al. 2015, section 5.2). log p: importance-weighted estimate, K = 1,000, first 1,000 test images.

The five rows (rec., KL, active dimensions, log p): β = 0.5: 55.1, 34.4, 16, −83.9; β = 1: 60.5, 27.1, 16, −81.7; β = 2: 71.1, 19.6, 16, −82.9; β = 4: 93.7, 11.4, 14, −91.3; β = 8: 125.1, 5.5, 8, −111.3.

What the Fashion-MNIST sweep above cannot show is the likelihood: only β = 1 trains on a bound of log p(x), and the importance-weighted estimate is best there. At β = 8 half the dimensions carry no information: their q(zj | x) equals the prior for every image, KL exactly 0, and the decoder ignores them, partial posterior collapse. It becomes total when the decoder can model x without any code: Bowman et al. 2015 found an LSTM text decoder drove the KL to zero, so the VAE became a plain language model; their fixes were KL annealing and word dropout (weaken the decoder so it must use z). The fixes measured, with free bits, are in section 6, and VQ-VAE's codebook in section 8.

6. Posterior collapse: when the decoder does not need the code

The KL is exactly 0 when the encoder ignores the image and outputs N(0, I) for everyone. If the decoder can reconstruct well without the code, nothing pays for leaving that optimum: posterior collapse. Section 4 caused it with loss units; here a strong decoder does.

A decoder that does not need z. A PixelCNN decoder predicts each pixel from the true pixels above and to its left (masked convolutions) plus the code, so it can predict most of an image from its own context. Here: the topic's VAE encoder (16 numbers), a PixelCNN decoder of one 7 × 7 and five 3 × 3 masked layers, 64 channels, the code added as a learned bias to every layer (src/collapse/pixelvae.py), 385,441 parameters, the usual recipe.

  1. An ordinary decoder uses its code. Row 1, the 16-number VAE of section 3: every dimension carries something, 0.21 to 2.56 nats, 17.11 in all.
  2. A PixelCNN decoder, plain ELBO. The red column replays the KL during training (log scale): 3.39 nats at step 100, then it drains; at the end all 16 columns are empty, 0 of 16 active.
  3. KL annealing only delays it. The weight (the gauge) rises from 0 to 1 over the first 2,500 steps. While it is small the code is used heavily (155 nats at step 100, weight 0.03; 13.1 at step 400), then it drains as the weight reaches 1, to 0.001 nats.
  4. Free bits keep the code alive. No charge for the first λ = 0.5 nats of each dimension: every column sits near the floor (the glass plane), 6.91 nats in all, 16 of 16 active.
  5. The price. The green boxes are what the code is worth (the shuffle test below): 0, 0 and 5.53 nats. Yet free bits’ true negative ELBO (212.07 nats) is worse than the collapsed run’s (206.17): with a decoder this strong, collapse is the optimum.
Predict: trained with the plain ELBO (β = 1), how much does this VAE's code carry, compared with the 17.11 nats of the VAE with an ordinary decoder?

Three fixes, same model, same data. KL annealing (Bowman et al. 2016): raise the KL weight from 0 to 1 (here over the first half of training) so the encoder learns to carry information before the KL charges for it. Free bits (Kingma et al. 2016, IAF): do not charge for the first λ nats of each dimension, Σj max(λ, KLj), KLj averaged over the minibatch (here λ = 0.5). Or weaken the decoder: information the decoder can model locally is not worth sending through z, so limit its receptive field to what the code should leave out (Chen et al., Variational Lossy Autoencoder).

What the runs show. The plain ELBO collapsed completely. Annealing did not save it: the code was used while the weight was small (about 13 nats and all 16 dimensions at step 400), then drained away as the weight reached 1. Free bits kept the code alive, each dimension near the 0.5-nat floor, worth 5.53 nats of reconstruction, at a price: its true negative ELBO (212.07) is worse than the collapsed run's (206.17). By the ELBO's own measure ignoring the code is the better model: with a decoder this strong collapse is the optimum, not an accident (Chen et al.'s point), so if you want a code for downstream use, likelihood alone is the wrong target. measured, one seed each

Costs, and how to check. Annealing and free bits change the objective, so compare models on the true negative ELBO; free bits can leave dimensions carrying exactly λ nats of noise; annealing only delays the KL; a weaker decoder costs likelihood. Collapse threatens any VAE with a powerful decoder (text VAEs, PixelCNN and transformer decoders, some audio and video models). Check KL per dimension and active units over training, and run the shuffle test: if the code does not change the output, it is not used.

The KL during training: annealing uses the code while the weight is small, then loses it

KL per image in nats, minibatch averages every 100 steps. The annealed run's KL weight rises from 0 to 1 over the first 2,500 steps (dotted, right axis). measured on Apple M1 Pro (MPS)

The four runs, test set, nats per image

RunKLActive of 16Reconstruction (own code)Code's worthNegative ELBO
Plain ELBO0.000206.10.0206.2
KL annealing (0 to 1 over 2,500 steps)0.000206.40.0206.5
Free bits, λ = 0.5 nats per dimension6.9116204.75.5212.1
No code (pure PixelCNN)0.000206.50.0206.5
VAE with an ordinary decoder, for scale17.1116218.1n/a235.2

"Code's worth": how much the reconstruction term worsens when each image is decoded from another image's code (0: the code is ignored). "No code": the same PixelCNN with z fixed at 0. One seed each. measured on Apple M1 Pro

Decode from each image's own code: does the output depend on the code?

The test images
Decoded from each image's own code
Decoded from 8 random codes z ~ N(0, I)
Sampled from each image's own code (each pixel drawn black or white with its predicted probability)

The first two decoded rows write each pixel's predicted probability back in raster order (not how the model was trained, so they show what the code changes, not good samples); the last row samples properly. This small PixelCNN, with the original's blind spot, samples poorly either way. measured (CPU); src/collapse/eval_collapse.py.

Where the fixes come from (provenance)

Bowman et al. anneal "from a vanilla autoencoder to a vae" (arXiv 1511.06349); DALL-E's dVAE raised its KL weight from 0 to 6.6 over the first 5,000 updates (Ramesh et al. 2021, appendix A.2). Free bits is from the IAF paper's appendix (arXiv 1606.04934); its appendix C.8 found λ from 0.125 to 2 helpful on CIFAR-10; here λ = 0.5 frees up to 8 nats in total. All four PixelCNN models beat the ordinary-decoder VAE's 235.25 nats by a wide margin. Bowman et al.'s LSTM text decoder, where collapse is total, is in section 5's closed MNIST β sweep.

KL per latent dimension at the end of training (chart)

Free bits' bars sit at the 0.5-nat floor; the plain and annealed runs' are empty. Test set.

7. Why reconstructions blur, and what fixes it

Pixel-loss autoencoders give soft reconstructions, VAEs more so. Four causes, each with its own fix:

  1. The pixel loss rewards the average. Where the code does not pin down a detail, squared error is minimised by the mean of all images consistent with it, and the mean of slightly different sharp edges is a soft edge (L1's median is the same in kind). Fix: a perceptual or adversarial loss.
  2. Too little rate. A small latent, a high β or a large Gaussian σ leaves more to average over. Fix: more channels or tokens, a smaller KL weight.
  3. The VAE's sampling noise. Training decodes μ + σε, so the decoder hedges against a jittered code; decoding μ at test time helps only a little.
  4. The downsampling factor. At 8 × downsampling a 1-pixel stroke shares a latent cell with 63 other pixels; the decoder redraws it from nothing.

The trade-off you cannot escape. At a given rate, the lowest pixel error and the most realistic output are different targets (Blau and Michaeli, The perception-distortion trade-off, 2018): a decoder that draws plausible fur where the code was unsure scores a worse PSNR than one that draws the average blur. Judge a tokenizer for generation on realism, not PSNR alone.

What the runs show. LPIPS traded pixel error for realism: PSNR 23.8 to 22.95 dB, rFD 71.25 to 20.9; rFD is measured in a different network than the one trained on, so its drop is the honest evidence. The patch GAN did not help at this scale (rFD 28.37; one seed, tiny grey images, 2,500 adversarial steps), which says nothing against GANs on photographs. measured

The same tokenizer, three losses: LPIPS trades pixel error for realism

A 128-code VQ tokenizer with restarts (section 8) trained three ways: pixel loss; plus LPIPS (feature distance in a pretrained AlexNet, Zhang et al. 2018); plus a patch discriminator on 8 × 8 regions from step 2,500 (hinge loss, adaptive weight as in the LDM code): section 10's VQGAN recipe at toy scale. rFD: Fréchet distance between classifier features of all 10,000 reconstructions and the originals (0 is a perfect copy); LPIPS on the first 2,000 (grey to three channels, 64 × 64, torchmetrics 1.9.0, AlexNet v0.1). measured on Apple M1 Pro, one seed each

8. VQ-VAE: an image as tokens, and keeping the codebook alive

Keep the latent as a grid (here 8 × 8 positions of 8 numbers) and replace each position's vector ze by the nearest of K learned vectors e, the codebook (here K = 128): the image becomes 64 integers (van den Oord et al. 2017). The lookup has no gradient, so the decoder's gradient is copied to ze unchanged (the straight-through estimator, z_st = ze + (zq - ze).detach()), and two terms train the codebook and keep the encoder near it:

loss = reconstruction + ‖sg[ze] − e‖2 + β ‖ze − sg[e]‖2
sg
stop-gradient: the first extra term (the codebook loss) moves only the codes, the second (the commitment loss, β = 0.25 in the paper, eq. 3, and here) only the encoder

Dead codes. A code that is never the nearest to any encoder output gets no gradient, never moves and is never chosen: codebook collapse. With the usual initialisation (uniform in ±1/K, far smaller than the encoder's outputs) most codes die in the first few hundred steps (the real runs below). Fig. 5 shows the mechanism on a 2-D toy.

  1. Encoder outputs and a fresh codebook. 600 points stand for encoder outputs (frozen here; in real training the encoder moves too); 16 codes start in a tiny square at the origin, uniform in ±1/16, the usual default. illustrative, computed in the page
  2. Each output snaps to its nearest code. Each colour is one code's share of the points. With the codes bunched in the middle only those on the outside of the bunch win: 8 of 16 win any point; the others (red) get no gradient.
  3. Plain VQ: live codes move to the mean of their points (what the codebook loss does in the limit), dead codes stay put. In this toy they recover as the live codes leave the centre (16 of 16 by training step 5), but usage stays uneven: perplexity 11.3, the effective number of equally used codes. In real training the healing is slow (58 of 128 codes used at step 200, below).
  4. Restarts re-seed dead codes on the data. Every 3 steps a code that won nothing jumps to a random encoder output (Jukebox’s restart), so it comes back where the data is: perplexity 12.2.
  5. FSQ [4, 4]: a fixed grid, nothing to learn. Each coordinate is squashed by tanh and rounded to one of 4 levels, so the 16 codes are a fixed grid (drawn where each level sits in the encoder’s units); a code is unused only if the encoder never sends a point there: 15 of 16 here.
  6. LFQ, 2 bits: the sign of each coordinate. In 2-D that is 4 codes, the quadrants (a real LFQ uses log2 K channels: 18 for 218 codes); MAGVIT-v2 adds an entropy penalty so every sign pattern gets used.
  7. Measured: the real 128-code tokenizer. Every code sorted by how often it appears in the 640,000 test tokens (height: square root of the count; red: never): plain VQ ends with 118 codes in use, restarts with all 128.

Read the library version critically: diffusers' VectorQuantizer keeps a known bug, "due to a bug the beta term was applied to the wrong term" (vae.py lines 574 to 576 and 651 to 654, v0.41.0): with the default legacy=True, β multiplies the codebook term.

The quantizer that trained the tokens here (code)
    def quantize(self, ze):                    # the topic's src/latent/vq.py
        B, D, H, W = ze.shape
        flat = ze.permute(0, 2, 3, 1).reshape(-1, D)
        E = self.codebook.weight
        d = flat.pow(2).sum(1, keepdim=True) - 2 * flat @ E.t() + E.pow(2).sum(1)[None]
        idx = d.argmin(1)
        zq = E[idx].view(B, H, W, D).permute(0, 3, 1, 2)
        return zq, idx.view(B, H, W)
    def forward(self, x):
        ze = self.ae.encode(x)
        zq, idx = self.quantize(ze)
        z_st = ze + (zq - ze).detach()                              # straight-through estimator
        return self.ae.decode(z_st), ze, zq, idx

The fixes in use, each run here on the same tokenizer:

  • Dead-code restarts: re-seed unused codes from random encoder outputs of the current batch (Jukebox, Dhariwal et al. 2020, section 3.1).
  • EMA codebook: each code becomes a moving average of the outputs assigned to it (decay 0.99, Laplace-smoothed counts; VQ-VAE appendix A.1). Stabler, but a code that wins nothing still does not move.
  • Normalised codes: L2-normalise ze and the codebook, so every code lives on the data's sphere, usually with 8 to 32-number codes (ViT-VQGAN's "factorized codes", Yu et al. 2021, section 3.2).
  • Not run here: k-means initialisation on the first batch's encoder outputs (SoundStream, which also uses EMA and restarts: Zeghidour et al. 2021, section III-C) and the rotation trick, a better-than-copied gradient (Fifty et al. 2024).

Reading it. At 128 codes plain VQ crashes early (58 of 128 codes used in the window ending at step 200) and heals slowly; restarts refill the book by step 700; both end at similar PSNR (Jukebox: without restarts models "can converge to the same test error and codebook usage but require more training steps" published). Usage is not quality: the EMA codebook uses all 128 codes at the lowest perplexity (57.9), and the L2-normalised run leaves 37 unused yet has the lowest rFD. At 1,024 codes plain VQ ends with 151 in use (15%), about what the 128-code model uses: 3 extra bits per token bought and not used (log2 1,024 − log2 128; Correction the 2026-10-17 page said 7). Restarts bring it to 1,021. And 64 tokens of 7 bits (448 bits) reconstruct better than 16 real numbers (23.8 against 21.4 dB): a grid of local codes suits images, blank corners sharing a few codes and the garment getting its own. On the 128-code VQ-VAE’s token map of the topic’s retired Latent lab (2026-10-17) a test image takes 28 to 43 distinct codes for its 64 positions, and the same blank corner gets the same few codes across images (117, 72, 26 recur). measured

How to check. Log codes used and perplexity every few hundred steps; a perplexity far below K means you are paying for a codebook you do not have, and the bigger K, the more it matters.

Codebook usage on the test set: the plain recipe wastes most of a 1,024-code book

Variant (click a row)KCodes usedPerplexityPSNR dBrFD
VQ, plain12811882.124.0366.4
VQ + restarts12812888.523.8071.2
VQ, EMA codebook12812857.924.1759.0
VQ, L2-normalised codes1289174.423.8851.9
VQ, plain1,02415194.624.3569.1
VQ + restarts1,0241,021630.124.2362.0
Codes used in each window of 100 training steps (selected run bold)
The selected image as 64 tokens (point at a cell to highlight every cell with the same token)

Codes used: distinct codes among the 640,000 test tokens; perplexity: exp of the entropy of code frequencies, the effective number of equally used codes. The K = 128 plain and restart rows are the root Latent lab's recorded checkpoints re-scored with the same script (PSNR matches the recordings). One seed each: a few rFD points between the 128-code runs are within what a second seed could move. measured on Apple M1 Pro; src/quant/

How often each code is used, sorted (chart, any run)

9. FSQ and LFQ: quantizers with nothing to collapse

Codebook collapse happens because the codebook is learned. Remove it: fix the code grid and let the encoder learn to use it (Fig. 5's FSQ and LFQ steps in section 8 show the two grids).

FSQ: finite scalar quantization

Squash each of a few channels (3 to 10) with tanh and round it to one of Li levels; the codebook is the product of the levels ([8, 5, 5, 5]: 1,000 codes from 4 channels). No codebook or commitment loss, straight-through rounding (Mentzer et al. 2023): usage "≈100% for most models, without relying on any auxiliary losses", Li ≥ 5 recommended published.

LFQ: lookup-free quantization

log2 K channels, each quantized to its sign; the token is the binary number the signs spell (18 channels: 262,144 codes, no lookup). An entropy penalty, E[H(q(z))] − H[E(q(z))], makes each token confident and all tokens used (MAGVIT-v2, Yu et al. 2023, eq. 3 to 5; weight 0.1, commitment 0.25) published.

Reading it. FSQ [8, 5, 5, 5] used 996 of 1,000 codes with no auxiliary loss, was best on every measure (rFD 29.85) and trained fastest (103.3 s against 282.5: no distances to K codes). At 125 codes FSQ used all of them and landed with the VQ variants. LFQ did worst: at 10 bits only 395 of 1,024 codes were used, and its entropy penalty matters (7-bit perplexity 12.6 without it, 23.3 with it). Sign bits on 7 to 10 channels suit a tiny model poorly; MAGVIT-v2 uses 18 bits and a far larger encoder, so this does not test its result. measured

The cost, and when to choose them. Fewer numbers per token (3 to 18 channels against VQ's 8 to 256) on fixed levels. In return large vocabularies become usable: MAGVIT-v2 reports reconstruction and generation both improving as LFQ's vocabulary grows, "a property not observed in current VQ-VAE methods", and FSQ finds VQ "is actually worse for large codebooks" published. Choose them for thousands to hundreds of thousands of codes, or when VQ's collapse keeps returning; check usage, and generation (section 10).

At about 1,000 codes, FSQ uses its whole grid and beats every VQ variant

QuantizerCodes KUsed (test)PerplexityPSNR dBLPIPSrFDTrain s
FSQ [5, 5, 5]12512573.424.090.06757.8140
LFQ, 7 bits12812723.322.020.095114.4297
LFQ, 7 bits, no entropy loss1288212.622.010.098116.0302
VQ + restarts (section 8)1,0241,021630.124.230.07462.0282
FSQ [8, 5, 5, 5]1,000996277.725.170.05229.9103
LFQ, 10 bits1,02439533.522.560.08181.0339

Same network, 64 tokens per image and recipe as section 8; only the quantizer differs. measured on Apple M1 Pro, one seed each

FSQ's bounding function, as ported here (code)
def bound(self, z):                     # FSQ paper appendix A.1, def bound, ported to PyTorch (src/quant/quantizers.py)
    eps = 1e-3
    half_l = (self.L - 1) * (1 - eps) / 2
    offset = torch.where(self.L % 2 == 1, 0.0, 0.5)   # even L needs an asymmetric range
    shift = torch.tan(offset / half_l)
    return torch.tanh(z + shift) * half_l - offset

q = round_ste(self.bound(z))            # integers; round_ste(x) = x + (round(x) - x).detach()
zq = q / (self.L // 2)                  # what the decoder sees, about [-1, 1]

10. VQGAN, and how many tokens an image costs

A pixel-loss VQ-VAE blurs (section 7). VQGAN (Esser, Rombach, Ommer 2020) kept the VQ-VAE and changed the loss; it is still the recipe behind nearly every image tokenizer.

loss = L1 or L2 pixel loss + LPIPS
+ codebook and commitment losses + λ · patch-GAN loss
patch GAN
a small convolutional discriminator scores every patch as real or reconstructed; the autoencoder is trained to fool it, so texture must look real, not merely average
λ
set each step from the ratio of the two losses' gradient norms at the decoder's last layer, so the GAN term never swamps reconstruction (calculate_adaptive_weight, the same function in the LDM code, lines 32 to 43); the discriminator starts only after the autoencoder can reconstruct (LDM's disc_start 50,001)

The catch at large codebooks. The 16,384-code VQGAN reconstructs better but uses only 5.9% of its codes (1,024 codes: 44%), per IBQ Table 1, arXiv 2412.02692v2 independent. Section 8's fixes made large codebooks work: in ViT-VQGAN's ablation at 8,192 codes, usage rises from 4% with 256-dimensional codes to 96% with 32-dimensional L2-normalised ones (rFID 3.68 to 1.55), and removing the normalisation at 32 dimensions drops usage to 2% (Yu et al. 2021, Table 4) published.

What the losses bought, in VQGAN's own table (ImageNet validation, 256 × 256)

TokenizerLatent gridCodesrFID
DALL-E dVAE (Gumbel-softmax, pixel loss)32 × 328,19232.01
VQGAN, f = 1616 × 161,0247.94
VQGAN, f = 1616 × 1616,3844.98
VQGAN, f = 8 (Gumbel)32 × 328,1921.49

rFID: Fréchet distance between Inception features of the reconstructions and the originals. VQGAN Table 5, arXiv 2012.09841v3 published; the DALL-E row is VQGAN's measurement of OpenAI's released dVAE. The column the paper labels "Codebook Size" is the latent grid. At toy scale here, LPIPS cut rFD from 71.25 to 20.9 for 0.85 dB of PSNR (section 7).

Tokens per image is sequence length. The token count sets an autoregressive model's cost (attention roughly with its square); the vocabulary sets what each token carries (log2 K bits) and how hard prediction is. Most settled on f = 16 and 1,024 to 16,384 codes; halving f quadruples the sequence.

  1. The image: 786,432 numbers. 512 × 512 pixels in 3 colour channels (the grid is drawn every 32 pixels).
  2. f = 8: a 64 × 64 grid, 4,096 tokens. Kandinsky 2.2’s MoVQ, measured here, with 16,384 codes: each token stands for an 8 × 8 patch.
  3. f = 16: 32 × 32 = 1,024 tokens. aMUSEd’s VQGAN, measured here, with 8,192 codes (13 bits a token), the same count as Chameleon: each token covers 16 × 16 pixels.
  4. f = 32: 16 × 16 = 256 positions. (512 / 32)2 derived: each covers 32 × 32 pixels, so one position must describe a whole region.
  5. Halving f quadruples the sequence. 4,096, 1,024 and 256 tokens (bars to scale) make 16,777,216, 1,048,576 and 65,536 attention pairs (tokens2, derived): from f = 16 to f = 8 the attention cost grows about 16 times.

Larger vocabularies reconstruct better but are harder to predict. MAGVIT-v2's Figure 1 shows generation first improving, then worsening as a VQ vocabulary grows, its reason "the vocabulary size of most language models for visual generation is around 1-8k" published. Chameleon names its ceiling: "A core weakness of our tokenizer is in reconstructing images with a large amount of text, therefore upper bounding the capability of our models" published. And tokens made for reconstruction are not features made for understanding: Janus keeps SigLIP for understanding and a VQ tokenizer for generation, and one VQ tokenizer for both scores far worse on understanding (POPE 60.1 against 87.0, arXiv 2410.13848v1, Table 5) published.

Measured here: aMUSEd's VQGAN (f = 16, 8,192 codes) gives 1,024 tokens per 512 × 512 image and Kandinsky 2.2's MoVQ (f = 8, 16,384 codes) 4,096, at mean PSNR 26.6981 and 31.2394 dB against 31.2019 for SD 1.5's continuous VAE (Tokenizer comparator). measured

Predict, then pick: what does going from f = 16 to f = 8 do to attention cost at 512 × 512?

Tokens = (resolution / f)2; bits = tokens × log2 K; attention pairs = tokens2, against Chameleon's 1,024 tokens (512 × 512, f = 16), which "encodes a 512x512 image into 1024 discrete tokens from a codebook of size 8192" (arXiv 2405.09818v2). derived

Sixteen published tokenizers: grid, codes, bits per image, rFID (reference table)
TokenizerYearQuantizerRes.GridTokensCodesBits per imagerFIDNote
VQ-VAE2017VQ12832 × 321,0245129,216n/aImageNet 128; no rFID (predates it)
DALL-E dVAE2021Gumbel-softmax VQ25632 × 321,0248,19213,31232.01measured by the VQGAN authors
VQGAN2020VQ + LPIPS + GAN25616 × 1625616,3843,5844.98also 1,024 codes: 7.94
ViT-VQGAN2021VQ, 32-d L2-normalised codes25632 × 321,0248,19213,3121.28the tokenizer of Parti
MaskGIT2022VQ25616 × 162561,0242,5602.28as listed by LlamaGen and TiTok
MUSE (base)2023VQ25616 × 162568,1923,328n/asuper-resolution stage: f = 8, 64 × 64 at 512
RQ-VAE2022residual VQ, depth 42568 × 8 × 425616,3843,5843.2050 epochs; 4.73 at the shorter schedule
MAGVIT-v22023LFQ, 18 bits128262,1441.15ImageNet 128; video tokenizer: 5 × 16 × 16 latent for 17 frames
Chameleon2024VQ5121,024 tokens1,0248,19213,312n/atext reconstruction named as its weakness
LlamaGen2024VQ, 8-d L2-normalised codes25616 × 1625616,3843,5842.19usage 97%; f = 8: 1,024 tokens, rFID 0.59; also Janus's generation tokenizer
VAR2024multi-scale residual VQ25610 scales, 1 × 1 to 16 × 166804,0968,160n/ascales from its code, not its text
TiTok-L-3220241-D VQ25632 tokens324,0963842.21
Emu32024VQ (SBER-MoVQGAN)51264 × 644,09632,76861,440n/a4 × 8 × 8 for video
Open-MAGVIT22024LFQ, 18 bits25616 × 16256262,1444,6081.17usage 100%; open reproduction of MAGVIT-v2
IBQ2024VQ, gradient to every code25616 × 16256262,1444,6081.00usage 84%
Cosmos DI16x162025FSQ (8,8,8,5,5,5)25616 × 1625664,0004,0872.518NVIDIA's own protocol; DI8x8: 1.265

Each row from the named paper's own text or table (vendor figures unless marked), checked 2026-10-17; rFID on ImageNet validation (50,000 images) at the stated resolution. Bits per image derived: tokens × log2(codes), written by src/make_pub_table.mjs from the list in it.

Relatives: residual, multi-scale and 1-D tokenizers (depth)

Residual quantization (RQ-VAE, Lee et al. 2022) quantizes the leftover error again with the same codebook, D times, so each position holds D codes: at 8 × 8 positions, depth 4 reaches rFID 4.73 where a one-code VQGAN at 8 × 8 is at 17.95 even with 131,072 codes; the paper: "increasing the quantization depth D is more effective ... than increasing the codebook size K" published. Neural audio codecs use the same idea (the sibling Video and audio generation). Multi-scale tokenizers (VAR, Tian et al. 2024) quantize the residual at growing resolutions, 1 × 1 up to 16 × 16 in its code (10 scales, 680 tokens, one shared codebook of 4,096), so the generator predicts coarse to fine. 1-D tokenizers (TiTok, Yu et al. 2024) drop the grid: 32 tokens for a 256 × 256 image at rFID 2.21 published.

11. The autoencoders inside latent diffusion, and their scaling factors

The Stable Diffusion 1.5 autoencoder (AutoencoderKL, 83,653,863 parameters counted from the loaded module) maps 512 × 512 × 3 to 64 × 64 × 4: f = 8, 4 channels (block_out_channels [128, 256, 512, 512] in the pinned config). A VAE in name only: its KL weight is 0.000001 (latent-diffusion autoencoder_kl_32x32x4.yaml line 11), a million times less than section 3's β = 1. Its sharpness comes from the rest of its loss, LPIPSWithDiscriminator (contperceptual.py lines 48 to 83): L1 + LPIPS + the tiny KL + a patch GAN from step 50,001, VQGAN's recipe with a KL in place of the codebook.

Measured on the 16 test images (float32, posterior mean): photographs come back at 26.7 to 30.9 dB, the synthetic graphics (shapes, text, chart, clock) at 32.3 to 37.5 dB, the busiest generated image (the puppy on grass) at 20.64 dB. Float16 moves PSNR by at most 0.1 dB and gives no NaNs. The encoder's own σ is 5e-05 to 0.00103 against a latent standard deviation of 4.1 to 6.9: with a KL weight of 10−6 the "variational" part is negligible and the encoder is in practice deterministic. measured on Apple M1 Pro (MPS), diffusers 0.41.0, SD 1.5 at revision 451f4fe16113

The scaling factor 0.18215

A diffusion schedule assumes its input has a scale near 1; SD's raw latents do not (a 10−6 KL never asked for it), so the LDM authors divide by the latent's standard deviation on the first training batch (scale_by_std, ddpm.py line 489: 1. / z.flatten().std()), and SD 1.x froze the result as 0.18215. On the 16 test images the raw latent's standard deviation is 5.5068, so 1 / std = 0.18159, within 0.3% of 0.18215; after × 0.18215 it is 1.0031. measured

Every later autoencoder has its own recipe, because later latents are not zero-mean or not equally scaled per channel: SDXL multiplies by 0.13025; SD3 and FLUX.1 subtract a shift and then scale (FLUX.1: (z − 0.1159) × 0.3611); Qwen-Image normalises each of 16 channels with its own mean and standard deviation; FLUX.2 patchifies 2 × 2 to 128 channels and applies batch-norm running statistics; DC-AE multiplies by 0.41407. Each must be undone exactly before decoding: leaving out FLUX.1's shift moved PSNR from 36.2837 to 35.5369 dB on the 16 test images, small and silent, harmful wherever exact colours matter, as in editing. measured

Forget the factor and the latent is 5.49 times too large: the same noise barely touches it

The cat's latent noised at timesteps 0, 300, 600 and 999 of SD's schedule with the same noise, then decoded; PSNR against the original under each tile. Forgetting the factor makes the latent 1 / 0.18215 = 5.49 times too large, so its signal-to-noise ratio is 30.1 times higher at every timestep (5.492) derived: the raw cat is still recognisable at t = 999 (17.27 dB) while the scaled one is mostly noise by t = 300 (15.12 dB). The U-Net, shown a far cleaner input than the timestep says, removes "noise" that is really image. The LDM paper's words for the unscaled case: SNR "very high", and the model "allocates a lot of semantic detail early on" (LDM paper page, D.1). measured

Three ways to get it wrong, with no error message

Pixel std (contrast, red channel, 0 to 255). Row 1, the cat's latent: right 32.6; not divided, a grey ghost 7.7; divided twice, blown out 75.2. Row 2, image-to-image ("a photograph of a tabby cat", strength 0.6, 25 DPM-Solver steps, guidance 7.5, seed 0): right 38.2; SDXL's factor, latent 1.4 times too small, over-contrasted 48.9; factor 1, smeared and flat 22.2. Row 3, one text-to-image latent: right 65.1; not divided, grey fog 15.2; divided by SDXL's factor, over-saturated 75.9. SD 1.5 fp16, root src/latent/sd_scale.py. measured on Apple M1 Pro (MPS)

Seven generator autoencoders: f, channels, numbers per image, normalisation, source (reference table and code locations)

Where it lives in code. The pinned SD 1.5 vae/config.json has no scaling_factor key; diffusers falls back to the class default 0.18215 (autoencoder_kl.py line 90, v0.41.0). Pipelines multiply after encoding (img2img line 771) and divide before decoding (text-to-image line 1085).

AutoencoderfChannelsNumbers for 1,024 × 1,024Normalisation before the generatorSource
SD 1.x8465,536× 0.18215diffusers default (config has no key)
SDXL8465,536× 0.13025sdxl-vae config
SD3, SD 3.5816262,144(z − 0.0609) × 1.5305diffusers convert_sd3_to_diffusers.py lines 337 to 338 (the official repo is gated)
FLUX.1816262,144(z − 0.1159) × 0.3611BFL flux src/flux/util.py; Z-Image-Turbo's config
FLUX.2832524,2882 × 2 patches to 128 channels, then batch-norm running mean and stdFLUX.2 [klein] 4B vae/config.json; diffusers pipeline_flux2.py line 617
Qwen-Image (Wan 2.1 VAE)816262,144per-channel (z − mean) / std, 16 pairs in the configQwen-Image vae/config.json; pipeline_qwenimage.py lines 710 to 713
DC-AE f32c32 (Sana)323232,768× 0.41407dc-ae-f32c32-sana-1.1 config

Numbers for 1,024 × 1,024: (1,024 / f)2 × channels derived. All read 2026-10-17.

Why channels went from 4 to 16 to 32

More channels keep more detail at the same f. SD3's own ablation at f = 8 (Esser et al. 2024, Table 3; dataset and resolution not stated) published:

ChannelsFID (reconstruction)Perceptual similaritySSIMPSNR
42.410.850.7525.12
81.560.680.7926.40
161.060.450.8628.62

The catch: richer latents are harder to model. SD3 accepts it because "predicting latents with higher d is a more difficult task, and thus models with increased capacity should be able to perform better for larger d" (its Figure 10). At smaller scale it bites: VA-VAE at f = 16 on ImageNet 256 (Yao et al. 2025, Table 2) published goes from 16 to 32 to 64 channels and reconstruction FID improves from 0.49 to 0.26 to 0.17 while generation FID (same LightningDiT-B) worsens from 16.24 to 22.62 to 36.83; aligning the latent to DINOv2 features (their "VF loss") recovers most of it (f16d32: 15.82).

Measured: the same 16 images through nine. The 16- and 32-channel VAEs lead on mean PSNR (FLUX.1 36.2837 dB, FLUX.2 35.7031, Qwen-Image 35.1088, against 31.2019 for SD 1.5 and 31.0981 for SDXL); FLUX.2 is best on SSIM and LPIPS (0.009); DC-AE, with 8 times fewer numbers than SD 1.5, reaches 30.0056 dB; every model's worst image is the SD-generated puppy on grass. Two surprises: SDXL's VAE, reported beating SD 1.x on COCO at 256, scores slightly below it here on all three measures (16 images: a caution, not a ranking); and in float16 it produced NaN values on all 16 images, already in the encoder, while the fp16-fix VAE matched float32 to 0.06 dB. measured on Apple M1 Pro

4 channels against 32, same 8 × downsampling, same crop

160 × 160 crops of the 512 × 512 test images at full resolution (WebP at quality 90, a little softness shared by every tile). The other seven autoencoders: the Tokenizer comparator. measured on Apple M1 Pro

Other levers: learnability, batch size, a text-tuned decoder, deeper compression (depth)

Black Forest Labs describe the learnability tension for FLUX: FLUX.1's VAE reconstructs far better than SD's but is harder to learn (generation FID 10.13 against SD's 7.73 after their flow-matching training), and FLUX.2's was retrained "to achieve better learnability and higher image quality at the same time" (rFID 0.1124 against FLUX.1's 0.1761; generation FID 3.70) (BFL, FLUX.2 representation comparison, FLUX.2 announcement, 2025-11-25) vendor claims, own evaluation.

SDXL kept SD's architecture and retrained it "at a larger batch-size (256 vs 9)" with an EMA of the weights, beating SD 1.x on every reconstruction metric on COCO at 256 × 256 (rFID 4.4 against 5.0; Podell et al. 2023, Table 3) published. Qwen-Image froze the Wan 2.1 encoder and fine-tuned only the decoder on text-rich images (documents, slides, posters), with reconstruction and perceptual losses but no adversarial loss ("the discriminator is unable to provide effective guidance" at that quality): text-image PSNR 36.63 against 26.77 for the Wan 2.1 decoder it started from (Qwen-Image report, Table 2) vendor. DC-AE compresses 32 × per side with residual shortcuts and a staged high-resolution adaptation; at f = 64 on ImageNet 512 it reports rFID 0.22 where the SD-VAE design trained at the same latent shape reaches 16.84, and 19.1 × faster inference for the same generator (Chen et al. 2024, Table 2) published. All these share the LDM family's design: a convolutional encoder and decoder (DC-AE adds attention-like blocks), a KL weight of about 10−6, L1 + LPIPS + patch GAN.

12. Evaluating an autoencoder or tokenizer

Fidelity to the image

PSNR: 10 log10(2552 / MSE) in dB; pixel-exact, so it prefers blur to plausible detail. SSIM: local means, contrasts and correlations in small windows, 1 is identical. LPIPS: distance between deep features weighted by a model fitted to human judgements, 0 is identical; tracks what people notice best.

Realism of the set

rFID: Fréchet distance between Inception features of reconstructions and originals over a set, usually the 50,000 ImageNet validation images at 256 × 256 (LlamaGen: "r-FID, reconstruction-FID on 256×256 ImageNet 50k validation set", arXiv 2406.06525v1). Punishes blur, needs thousands of images; protocols differ (FSQ uses the training set, arXiv 2309.15505v2).

The tokens themselves

Codes used and perplexity (section 8); tokens and bits per image (section 10); encode and decode time and memory; for a continuous latent, its per-channel statistics (section 11).

What it is for

Generation FID of a generator trained on the latents, at fixed compute: the only measure of "easy to model", and it can move against reconstruction (sections 10 and 11).

What it shows. On the cat and the Hubble field the reconstruction is far closer in deep features than the equal-PSNR blur (cat 0.0142 against 0.0459; Hubble 0.0221 against 0.171): the blur erases faint galaxies and fur the decoder redraws. SSIM does not agree everywhere (on the Hubble field it prefers the blur, 0.7514 against 0.6936). On the text card the matching blur is only 0.507 px and wins on every measure: on flat graphics the decoder's errors are small artefacts along edges, which is why SD-class models garble small text. measured

Metrics disagree on real autoencoders too. On the comparator's 16 images PSNR puts FLUX.1 first, SSIM and LPIPS FLUX.2; MoVQ is fourth by PSNR but seventh by SSIM; Qwen-Image is third by PSNR and SSIM but fourth by LPIPS, behind SD 1.5. measured Cross-paper tables are rougher still (closed block).

Same PSNR, different picture: the SD reconstruction against a blur tuned to the same pixel error

For each image a Gaussian blur of the original whose strength was searched until its PSNR equals the SD 1.5 reconstruction's. Feature distance: cosine distance between the 2,048-d Inception pool features (torch-fidelity's inception-v3-compat), a stand-in for LPIPS (root src/latent/perc_demo.py); lower is closer. 160 × 160 crops. measured (CPU)

Comparing papers: LPIPS scales and rFID protocols differ (depth)

LPIPS as computed here (torchmetrics 1.9.0, AlexNet, v0.1 weights) ranges from 0.009 to 0.0801 across the nine, yet SDXL's Table 3 reports LPIPS of 0.88 to 0.96 and BFL's table 0.27 to 1.67, without saying how they were scaled. NVIDIA's Cosmos report re-ran rivals under its own protocol and got different rFIDs from their own papers (LlamaGen at f = 16: 1.657 in Cosmos's Table 8 against 2.19 in LlamaGen's). Numbers compare only at the same resolution, dataset, image count and metric implementation; re-measure the candidates you are choosing between on your own images.

How to check a tokenizer you are about to use. Round-trip a few hundred of your own images; look at full-resolution crops of text, faces and texture; compute PSNR, SSIM and LPIPS; compare float16 with float32 once; check the normalised latent's mean and std are near 0 and 1; count codes used; and train a small generator on the candidates before committing.

Depth: mistakes, rehearsal, what transfers

Common mistakes, with what they look like (13)
Sampling a plain autoencoder from N(0, I)
Its codes live at whatever scale training chose (standard deviation 5.0 to 9.5 per dimension here), so N(0, I) samples sit in one corner and decode to one blob (section 2). Print the codes' mean and std before sampling; fit a density, or use a VAE.
Reading a lower reconstruction loss as a better generator
The plain autoencoder reconstructs best and generates worst from N(0, I) (section 2). Score samples separately, with a stated sample size and floor.
Averaging the reconstruction over pixels while summing the KL
An effective β equal to the number of pixels: 0 of 16 active units and every reconstruction the average garment (section 4). Nothing errors; the loss curve looks fine. Check KL per image in nats, and active units.
Plain MSE plus KL, without asking what σ that implies
Summed squared error plus KL is a Gaussian decoder with σ2 = 1/2, and σ is a β (section 4). Choose σ deliberately, or learn it.
Turning β up to fix blurry samples
Higher β makes reconstructions blurrier and switches dimensions off (section 5). Blur comes from the pixel loss; the cure is a perceptual or adversarial loss, or a stronger generator on top of the latent.
A powerful decoder and a KL that drops to zero
Posterior collapse: the PixelCNN decoder here ended with a KL of 0 nats and decoded the same picture whatever the code (section 6). Run the shuffle test; use free bits or limit the decoder.
A large codebook with the default initialisation and no usage logging
At K = 1,024 the plain VQ recipe used 151 codes on the test set (section 8). Log codes used and perplexity; restart dead codes, use EMA with k-means initialisation or normalised codes, or switch to FSQ.
Trusting a library's commitment loss without reading it
diffusers' VectorQuantizer applies β to the wrong term unless legacy=False (section 8).
The wrong scaling factor, or a forgotten shift
Each autoencoder has its own (SD 1.x 0.18215, SDXL 0.13025, FLUX.1 a shift and a scale). Missing at encode time, the denoiser sees inputs far cleaner than the timestep says; missing at decode time, colours wash out or blow up (section 11). Check that the std of normalised latents of real images is near 1, and that encode, normalise, unnormalise, decode reproduces the image.
Running an autoencoder in float16 without checking for NaNs
The SDXL VAE in float16 returned NaN values on all 16 of the 16 test images, already in the encoder's output; the fp16-fix VAE (same architecture, rescaled internal activations, madebyollin/sdxl-vae-fp16-fix) did not, and SD 1.5's is fine in float16 (section 11). diffusers' force_upcast config flag exists for this. Compare one image in float32 and float16 before a batch run.
Comparing PSNR across resolutions, crops or colour spaces
Grey 28 × 28 images through the tiny tokenizers (22 to 25 dB) and 512 × 512 colour images through SD 1.5's VAE (20.6 to 37.5 dB, depending on the image) are not on one scale, and neither are papers that compute it at 256 or on luminance only. Compare tokenizers on the same images at the same resolution.
Quoting an rFID from a few hundred images
Fréchet distances are biased upwards at small N: the topic's real-against-real floor is 2.54 at 10,000 images and about 15.6 at 1,000 (root src/data/README.md). Use thousands at least, and state N.
Choosing the tokenizer by reconstruction alone
More channels or a larger vocabulary reconstruct better and can be harder to model (sections 10 and 11). Train a small generator on the candidate latents and measure generation before committing.
Interview rehearsal (design questions the sections do not pose)
Why do latent diffusion models not diffuse in pixel space?
Cost and focus: 786,432 numbers against 16,384 in SD's latent (48 times fewer), and the denoiser runs 25 to 50 times per image; the autoencoder removes imperceptible detail once, so the generator spends its capacity on composition. The price is the decoder's ceiling and a second model to train.
Design: an autoregressive text-to-image model at 512 × 512. Choose the tokenizer.
Sequence length sets cost: f = 16 gives 1,024 tokens per image (Chameleon's choice), f = 8 gives 4,096. Vocabulary: 8k to 16k VQ codes with L2-normalised low-dimensional codes and restarts, or FSQ or LFQ for larger vocabularies; train with L1 or L2 + LPIPS + patch GAN on data like the target (text-heavy if text rendering matters, since the decoder's ceiling binds). Measure rFID, LPIPS, usage and a small AR model's generation FID for two or three candidates. Trade-offs: fewer tokens are faster but lose detail; a larger vocabulary reconstructs better but is harder to predict.
Design: a latent diffusion model's outputs have mangled small text. Generator or autoencoder?
Round-trip real images with small text through the autoencoder alone. If the reconstructions already mangle it, the decoder's ceiling is the cause (SD 1.5's VAE does, section 12) and no generator can fix it: use a VAE with more channels or a text-tuned decoder (Qwen-Image's), or higher resolution. If reconstructions are fine, look at the generator (data, text encoder, guidance).
A colleague's img2img outputs come back smeared and flat, or over-contrasted, with no error. First check?
The scaling factor: latents not multiplied by the model's factor (smeared) or multiplied by another model's (over-contrasted). Print the std of the latents fed to the U-Net; it should be near 1 (section 11).
What transfers from this laptop (provenance)

Measured on Apple M1 Pro: every tiny model trained in about 2 to 5 minutes on the laptop's GPU (MPS, float32, batch 128); the pretrained autoencoders ran one at a time. What transfers: the mechanisms and their direction (loss units changing β, the scale mismatch that sinks N(0, I) sampling, the β trade-off, collapse with a strong decoder and what the fixes do, dead codes at large K and FSQ's near-full usage, perceptual losses trading PSNR for realism), and the pretrained autoencoders' reconstruction metrics and every scaling-factor effect (deterministic arithmetic on the same weights). What does not: absolute numbers of the tiny models (one seed each, 5,000 steps, a 28 × 28 dataset; FD and rFD in a small Fashion-MNIST classifier's feature space, comparable only within this page), rankings from 16 test images, and all timings.