Simple Algorithm
Deep Learning · Emergence · 28 min

Latent Spaces for Generative Models

Autoencoders built for diffusion: compression, the reconstruction–generation trade-off and semantic latents.

Most images generated in the mid-2020s were never generated as pixels. A diffusion model or transformer produced a small grid of latent numbers, and an autoencoder's decoder painted the picture. That autoencoder decides what the generator can express, how fast it trains and how sharp the result is, and its latent space has a geometry of its own: straight lines leave the data, and distances lie.

What you’ll learn

  • Explain why generators are trained in an autoencoder's latent space, and how the downsampling factor, channel count, regularization and losses of that autoencoder are chosen.
  • Describe the reconstruction–generation trade-off and the evidence for it, and how aligning latents or hidden states with pretrained representations eases generation.
  • Prove that Gaussian latents concentrate near radius d\sqrt d, compute why linear midpoints are atypical, and derive spherical interpolation.
  • Find attribute directions in latent space, and derive the pullback metric J⊤JJ^\top J that makes geodesics follow the data.

Two kinds of compression

Most of the bits in a photograph encode detail the eye barely registers: exact grain, sensor noise, the precise texture of a lawn. A likelihood-trained pixel model must spend capacity on all of it. Rombach et al. (2022) split the job in two. An autoencoder performs perceptual compression: it discards imperceptible detail and maps the image to a smaller latent grid, trained once. A generative model then performs semantic compression: it learns the distribution of those latents, which is what actually varies from image to image. Latent diffusion runs the whole diffusion process on the latents and decodes once at the end. (The Artificial Intelligence course's Deep Layer lesson on diffusion computes the savings.)

The autoencoder is a design problem with four main knobs:

  • Spatial downsampling ff and channels cc. An H×W×3H\times W\times3 image becomes Hf×Wf×c\frac Hf\times\frac Wf\times c. Rombach et al. tested f∈{1,2,4,8,16,32}f\in\{1,2,4,8,16,32\} and found ff between 4 and 16 the best balance: f=1,2f=1,2 trained slowly, while at f=32f=32 quality stalled because too much was lost before generation began. Stable Diffusion's widely used autoencoder has f=8f=8, c=4c=4.
  • Regularization. Either a very weak KL penalty toward N(0,I)\mathcal N(\mathbf 0,I), making it a VAE whose KL term mainly keeps the latent scale in check, or a vector-quantization layer (see Learned Tokenizers for Images & Audio). Latents are usually rescaled to unit variance before the generator sees them.
  • Losses. Pixel L1 or L2 alone gives blur, so reconstruction adds a perceptual loss and a patch-based adversarial loss, as in VQGAN; the decoder may invent plausible texture.
  • Architecture. Convolutional encoders and decoders, sometimes with attention at the lowest resolution, and increasingly transformer-based ones.
Predict before you look

An autoencoder with f=8f=8 and c=4c=4 encodes a 1024×10241024\times1024 RGB image. How many numbers does the latent contain?

Show the answer

65536 numbers

(1024/8)2×4=1282×4=65,536(1024/8)^2\times4=128^2\times4=65{,}536, against 10242×3=3,145,7281024^2\times3=3{,}145{,}728 pixel values: 48 times fewer. A diffusion transformer that cuts the latent into 2×22\times2 patches sees 642=4,09664^2=4{,}096 tokens, and attention cost grows with the square of that count, which is why higher compression is sought for high resolutions.

The reconstruction–generation trade-off

A better autoencoder is not automatically a better foundation for generation. More latent capacity reconstructs better, but gives the generator a harder distribution to learn. The evidence:

  • More channels. Esser et al. (2024) trained f=8f=8 autoencoders with 4, 8 and 16 latent channels. Reconstruction improved at each step (reconstruction FID 2.41→1.56→1.062.41\to1.56\to1.06, PSNR 25.1→26.4→28.625.1\to26.4\to28.6 dB), but flow-matching models trained on the 16-channel latents needed more depth to catch up, with the gap closing only for the larger models. They chose 16 channels because they planned to scale.
  • Bigger vocabularies. For discrete tokens, Yu et al. (2024) found that growing a VQ codebook kept improving reconstruction but eventually hurt generation (see Learned Tokenizers for Images & Audio).
  • Aligned latents. Yao, Yang & Wang (2025) describe the same dilemma for high-dimensional continuous tokenizers: reconstruction improves, but diffusion models train much more slowly on them. Their VA-VAE adds a loss that aligns the latents with the features of a pretrained vision foundation model, which structures the latent space and, they report, restores fast convergence without giving up reconstruction.
  • Deep compression. Pushing ff to 32 and beyond shrinks the token count for high-resolution generation. Chen et al. (2025) made such autoencoders reconstruct well by having the network learn residuals on top of fixed space-to-channel shortcuts, plus a staged adaptation to high resolution, reaching spatial compression up to 128.
KnobRaisesCosts
Larger ff (fewer latent positions)generation speed, especially at high resolutionreconstruction detail, unless channels or architecture compensate
More channels ccreconstruction fidelitya harder latent distribution; needs larger generators
Stronger KL or smaller codebookregularity and ease of modelingreconstruction fidelity
Perceptual and adversarial lossessharpness at a given ratefaithfulness: plausible invented detail
Alignment with pretrained featurestraining speed and quality of the generatordependence on a pretrained encoder; possible loss of fine detail
No single number rates an autoencoder. The test that matters is the quality of a generator trained on its latents, which is expensive to run.

The geometry of Gaussian latents

Whatever the architecture, many generators draw their latents from N(0,Id)\mathcal N(\mathbf 0,I_d): a GAN's input, a VAE's prior, the starting noise of a diffusion or flow model. In high dimensions this distribution does not look like a bump. Its density peaks at the origin, but almost all of its mass lies in a thin shell.

DerivationProof of the moments, and the midpoint
  1. E∥z∥2=d,Var⁡∥z∥2=d (3−1)=2d\E\norm{\mathbf z}^2=d,\qquad\Var\norm{\mathbf z}^2=d\,(3-1)=2d

    ∥z∥2=∑izi2\norm{\mathbf z}^2=\sum_iz_i^2 is a sum of dd independent squares with Ezi2=1\E z_i^2=1 and Ezi4=3\E z_i^4=3, so each term has variance 22:

  2. m=12(z1+z2)∼N(0,12Id)⟹∥m∥≈d/2\mathbf m=\tfrac12(\mathbf z_1+\mathbf z_2)\sim\mathcal N\big(\mathbf 0,\tfrac12I_d\big)\quad\Longrightarrow\quad\norm{\mathbf m}\approx\sqrt{d/2}

    The midpoint of two independent latents is Gaussian with half the variance per coordinate, so its norm concentrates at a different radius:

  3. With x=d/16x=d/16 the lower tail bound gives P(∥z∥2≤d/2)≤e−d/16P(\norm{\mathbf z}^2\le d/2)\le e^{-d/16}, while ∥m∥2≤d/2\norm{\mathbf m}^2\le d/2 is equivalent to χd2≤d\chi^2_d\le d, which holds for slightly more than half of all midpoints. For d=512d=512, more than half of the linear midpoints lie in a ball to which the prior gives probability below e−32≈10−14e^{-32}\approx10^{-14}: they are points the generator essentially never saw in training.

Predict before you look

Two latents are drawn independently from N(0,I512)\mathcal N(\mathbf 0,I_{512}); each has norm close to 512≈22.6\sqrt{512}\approx22.6. What is the typical norm of their linear midpoint?

Show the answer

16

m∼N(0,12I)\mathbf m\sim\mathcal N(\mathbf 0,\tfrac12I), so ∥m∥≈512/2=16\norm{\mathbf m}\approx\sqrt{512/2}=16, with a spread of about 0.50.5. Prior samples have norms of 22.6±0.722.6\pm0.7; in a simulation of 2,000 pairs, the largest midpoint norm (17.6) stayed below the smallest prior norm (20.3). The midpoint is not a typical latent at all.

White (2016) therefore proposed spherical linear interpolation, slerp, borrowed from computer animation: move along the great circle between the two latents instead of the chord. With cos⁡Ω=z1⊤z2/(∥z1∥∥z2∥)\cos\Omega=\mathbf z_1^\top\mathbf z_2/(\norm{\mathbf z_1}\norm{\mathbf z_2}),

slerp⁡(z1,z2;t)=sin⁡((1−t)Ω)sin⁡Ω z1+sin⁡(tΩ)sin⁡Ω z2,t∈[0,1].\operatorname{slerp}(\mathbf z_1,\mathbf z_2;t)=\frac{\sin\big((1-t)\Omega\big)}{\sin\Omega}\,\mathbf z_1+\frac{\sin(t\Omega)}{\sin\Omega}\,\mathbf z_2,\qquad t\in[0,1].

If ∥z1∥=∥z2∥=r\norm{\mathbf z_1}=\norm{\mathbf z_2}=r, every point of the path has norm exactly rr: expanding the squared norm and using the identity sin⁡2a+sin⁡2b+2sin⁡asin⁡bcos⁡(a+b)=sin⁡2(a+b)\sin^2a+\sin^2b+2\sin a\sin b\cos(a+b)=\sin^2(a+b) with a+b=Ωa+b=\Omega gives r2r^2. Since two prior samples have nearly equal norms, slerp keeps the whole path in the typical shell. Perceptual path length in StyleGAN uses slerp in its Gaussian input space for this reason (see Style-Based Generators).

Directions and distances in latent space

Attribute directions. If an attribute varies roughly linearly in latent space, editing is vector addition. Radford, Metz & Chintala (2016) showed it with DCGAN faces: averaging the latents of three samples per concept (single samples were unstable) and computing smiling woman −- neutral woman ++ neutral man gave latents that decode to smiling men. InterFaceGAN (Shen, Gu, Tang & Zhou, 2020) made it systematic: label generated faces with attribute classifiers, fit a linear SVM in latent space for each binary attribute (pose, smile, age, gender, eyeglasses), and edit with z←z+αn\mathbf z\leftarrow\mathbf z+\alpha\mathbf n along the unit normal n\mathbf n of the separating hyperplane. Because such directions are often correlated (age with eyeglasses, say), a conditional edit moves along n1−(n1⊤n2)n2\mathbf n_1-(\mathbf n_1^\top\mathbf n_2)\mathbf n_2, the part of one normal orthogonal to another. GANSpace (Härkönen, Hertzmann, Lehtinen & Paris, 2020) found directions without labels, as principal components of sampled intermediate latents (or of BigGAN's early features, transferred back by regression), and applied them to selected layers only.

Word embeddings show the same phenomenon in a different trained space, and you can test it directly:

Distances. A decoder g:Rk→RDg:\R^k\to\R^D distorts space: two latents close in Euclidean distance can decode to very different images, and a straight latent path can sweep through outputs that look nothing like data. The fix is to measure lengths in data space. A small step dzd\mathbf z moves the output by J(z) dzJ(\mathbf z)\,d\mathbf z, where JJ is the decoder's Jacobian, so its squared length is dz⊤J⊤J dzd\mathbf z^\top J^\top J\,d\mathbf z:

M(z)=J(z)⊤J(z),Length⁡[γ]=∫01γ˙(t)⊤M(γ(t)) γ˙(t)  dtM(\mathbf z)=J(\mathbf z)^\top J(\mathbf z),\qquad\operatorname{Length}[\boldsymbol\gamma]=\int_0^1\sqrt{\dot{\boldsymbol\gamma}(t)^\top M\big(\boldsymbol\gamma(t)\big)\,\dot{\boldsymbol\gamma}(t)}\;dt
MM is the pullback of the Euclidean metric: a Riemannian metric on latent space under which a curve's length is the length of its decoded image. Geodesics, the shortest curves, are straight lines only where MM is constant, for instance for an affine decoder. det⁡M(z)\sqrt{\det M(\mathbf z)} measures how much the decoder magnifies volume near z\mathbf z.
DerivationStochastic decoders (Arvanitidis, Hansen & Hauberg, 2018)
  1. dg=(Jμ(z)+diag⁡(ϵ) Jσ(z)) dzdg=\big(J_{\boldsymbol\mu}(\mathbf z)+\diag(\boldsymbol\epsilon)\,J_{\boldsymbol\sigma}(\mathbf z)\big)\,d\mathbf z

    A VAE decoder has a mean and a standard deviation, g(z)=μ(z)+σ(z)⊙ϵg(\mathbf z)=\boldsymbol\mu(\mathbf z)+\boldsymbol\sigma(\mathbf z)\odot\boldsymbol\epsilon with ϵ∼N(0,I)\boldsymbol\epsilon\sim\mathcal N(\mathbf 0,I). For a fixed ϵ\boldsymbol\epsilon, a small step changes the output by

  2. Eϵ∥dg∥2=dz⊤(Jμ⊤Jμ+Jσ⊤Jσ) dz\E_{\boldsymbol\epsilon}\norm{dg}^2=d\mathbf z^\top\big(J_{\boldsymbol\mu}^\top J_{\boldsymbol\mu}+J_{\boldsymbol\sigma}^\top J_{\boldsymbol\sigma}\big)\,d\mathbf z

    Average the squared length over ϵ\boldsymbol\epsilon. The cross terms vanish because Eϵ=0\E\boldsymbol\epsilon=\mathbf 0, and E[diag⁡(ϵ)2]=I\E[\diag(\boldsymbol\epsilon)^2]=I:

  3. The expected metric adds the variance term Jσ⊤JσJ_{\boldsymbol\sigma}^\top J_{\boldsymbol\sigma}. If the decoder's uncertainty grows away from the training data, as it should, curves through empty regions become long, and geodesics bend to follow the data. Arvanitidis et al. found that standard decoders extrapolate their variance poorly, giving misleadingly confident estimates off the data, and proposed variance networks that grow away from the data; with them, latent distances and interpolations improved markedly.

Key takeaways

  • Latent generators split the work: an autoencoder does perceptual compression once, and the generator models the much smaller latents; ff between 4 and 16 balanced cost and quality for latent diffusion.
  • More latent capacity reconstructs better but can make generation harder; aligning latents (VA-VAE) or generator features (REPA) with pretrained representations eases training.
  • Gaussian latents concentrate at norm d\sqrt d and linear midpoints at d/2\sqrt{d/2}, far outside the typical shell for large dd; slerp keeps interpolations typical.
  • Attributes often lie along linear directions (DCGAN arithmetic, InterFaceGAN hyperplanes, GANSpace components), and the pullback metric J⊤JJ^\top J (plus Jσ⊤JσJ_{\boldsymbol\sigma}^\top J_{\boldsymbol\sigma} for stochastic decoders) measures latent distances by their effect on the output.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Latents are drawn from N(0,I128)\mathcal N(\mathbf 0,I_{128}). Why might decoding the straight-line midpoint of two latents give a washed-out image?

  1. The midpoint has norm about 88, while prior samples have norm about 11.311.3: it lies in a region the decoder almost never saw
  2. The midpoint is itself a sample from the prior, so it should decode normally; any washing out is a decoder bug
  3. Midpoints have larger norm than prior samples, which saturates the decoder
  4. Linear interpolation changes the dimension of the latent
Show the answer

A. The midpoint has norm about 88, while prior samples have norm about 11.311.3: it lies in a region the decoder almost never saw

Prior samples concentrate at ∥z∥≈128≈11.3\norm{\mathbf z}\approx\sqrt{128}\approx11.3, but m∼N(0,12I)\mathbf m\sim\mathcal N(\mathbf 0,\tfrac12I) concentrates at 64=8\sqrt{64}=8. The decoder was trained almost only on latents near the typical shell, so nothing constrains its output at the midpoint, which often looks atypical; slerp keeps the path on the shell.

Question 2

You raise your autoencoder's latent channels from 4 to 16 and its reconstructions improve markedly. What does the evidence of Esser et al. (2024) suggest about generation?

  1. Generation improves just as much, at every model size
  2. Generation is unaffected, since the generator only sees the latents
  3. The richer latents are harder to model: small generators do worse, and only larger generators close the gap
  4. Generation becomes impossible, because 16-channel latents cannot be normalized
Show the answer

C. The richer latents are harder to model: small generators do worse, and only larger generators close the gap

Reconstruction improved at every step from 4 to 16 channels, but flow models trained on the 16-channel latents needed more depth to match the others; the authors chose 16 channels because they planned to scale up. Better reconstruction and easier generation pull in different directions.

Question 3

Under the pullback metric M(z)=J(z)⊤J(z)M(\mathbf z)=J(\mathbf z)^\top J(\mathbf z), for which decoder are straight lines in latent space always shortest paths?

  1. Any decoder trained with a KL penalty toward N(0,I)\mathcal N(\mathbf 0,I)
  2. Any decoder whose outputs are normalized to unit variance
  3. Any decoder with zero output variance
  4. An affine decoder g(z)=Az+bg(\mathbf z)=A\mathbf z+\mathbf b, whose Jacobian is constant
Show the answer

D. An affine decoder g(z)=Az+bg(\mathbf z)=A\mathbf z+\mathbf b, whose Jacobian is constant

With constant J=AJ=A the metric A⊤AA^\top A is the same everywhere, which makes latent space a flat (Euclidean, if AA has full column rank) space in which straight lines are geodesics. A nonlinear decoder's Jacobian varies, curving the geometry.

Question 4

What does REPA (Yu et al., 2025) add to diffusion-transformer training?

  1. A loss aligning the autoencoder's latents with CLIP text embeddings
  2. A loss aligning projected hidden states of an early transformer block with a frozen self-supervised encoder's features of the clean image
  3. A perceptual loss on the decoded output
  4. A discriminator on the latents
Show the answer

B. A loss aligning projected hidden states of an early transformer block with a frozen self-supervised encoder's features of the clean image

The diffusion transformer is regularized so that its early hidden states, after a small projection, match DINOv2 features of the clean image. The generator is spared from discovering good intermediate representations on its own, and Yu et al. report more than 17-fold faster training to a baseline's quality.

Further reading

  • R. Rombach, A. Blattmann, D. Lorenz, P. Esser & B. Ommer, "High-resolution image synthesis with latent diffusion models," CVPR (2022).
  • J. Yao, B. Yang & X. Wang, "Reconstruction vs. generation: Taming optimization dilemma in latent diffusion models," CVPR (2025).
  • T. White, "Sampling generative networks," arXiv:1609.04468 (2016).
  • Y. Shen, J. Gu, X. Tang & B. Zhou, "Interpreting the latent space of GANs for semantic face editing," CVPR (2020).
  • G. Arvanitidis, L. K. Hansen & S. Hauberg, "Latent space oddity: on the curvature of deep generative models," ICLR (2018).