Foundations to Frontier
Tests
H. Generative Models › H7 Diffusion Models

Latent diffusion (Stable Diffusion)

Latent diffusion (Rombach et al., 2022) splits image generation into two stages. An autoencoder first compresses images into a small latent grid, removing imperceptible detail (perceptual compression). A diffusion model is then trained and sampled entirely in that latent space (semantic generation), and the decoder turns the final latent back into pixels. Every denoising step costs 48 times fewer values for Stable Diffusion's 64×64×4 latents of a 512×512 image, which is what made high-resolution text-to-image generation affordable and open. This page covers the VAE with KL or VQ regularisation, the latent scale factor (0.18215), text conditioning by cross-attention with CLIP or T5 encoders and classifier-free guidance, and the lineage SD 1.x → SDXL → SD3 and FLUX. In the exercises you build a linear (PCA) autoencoder and then sample 2-D latents and 64-pixel 'images' with the exact mixture score in place of a trained network. Two latent dimensions kept all content (4.1% of variance left, all of it detail). The latent scale mattered: latents scaled to std 0.2 gave a 21 times larger Fréchet distance at 10 steps than unit-std latents, and std 5.5 left signal at t = T and was worse at 50 steps. Few-step pixel-space sampling kept only half the fine detail.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Paint the sketch, let the decoder do the brushwork

Most of the numbers in a photo describe fine texture your eye barely notices. Latent diffusion first trains an autoencoder that squeezes an image into a much smaller grid of numbers and back, keeping what matters and throwing away imperceptible detail. The diffusion model then does all its slow, step-by-step denoising on the small grid, and the decoder paints in the texture at the end. That is how Stable Diffusion runs on a consumer graphics card. The demo shows how much smaller the latent is for different settings.

Conditional diffusion lab
A 512×512 RGB image has 786,432 values (top). A VAE with f = 8 and 4 channels gives a 64×64×4 latent with 16,384 values (bottom), 48× fewer. Every denoising step runs on the small one.
Why engineers care

Compressing first and generating second is now the standard recipe for images, video, audio, weather fields and satellite imagery, because the expensive iterative part runs on a representation dozens of times smaller than the raw data.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Latent diffusion runs the denoising in…
  2. 2. The autoencoder mainly removes…
  3. 3. Stable Diffusion 1.x maps 512×512 images to latents of…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Two stages

  • Stage 1, autoencoder: encoder E, decoder D with downsampling factor f (SD: f = 8) and c latent channels (SD 1.x and SDXL: 4; SD3 and FLUX: 16). Trained with reconstruction, perceptual (LPIPS) and patch-GAN losses, plus a small KL penalty (KL-VAE) or a vector-quantisation layer (VQ) to keep the latent space well behaved.
  • Scale factor: latents are multiplied by a constant so they have roughly unit variance before diffusion (0.18215 for SD 1.x, about 1/5.49; SDXL 0.13025). The noise schedule assumes unit-scale data.
  • Stage 2, diffusion: an ε- or v-prediction U-Net (SD 1.x, 860M parameters; SDXL 2.6B) or a transformer (SD3’s MMDiT, FLUX) trained on z = scale · E(x).
  • Conditioning: cross-attention from U-Net features to text tokens from a frozen CLIP ViT-L/14 (SD 1.x), two CLIP encoders (SDXL) or CLIP plus T5-XXL (SD3); classifier-free guidance with about 10% caption dropout.
  • Cost: a 512×512×3 image has 786,432 values; its latent has 16,384, 48× fewer, and attention over the latent grid is affordable.
  • Schedule: SD uses a ‘scaled linear’ β schedule from 0.00085 to 0.012 over 1000 steps, ending at ᾱ_T ≈ 0.0047; the non-zero terminal SNR was later identified as a flaw (Lin et al., 2024).
  • Floor: samples can be no better than the decoder; reconstruction quality (rFID) bounds generation quality.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Stable Diffusion 1.x latent scale factor:
  2. 2. Text conditioning in SD 1.x enters through…
  3. 3. SD3 and FLUX latents have…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Working with latents

Exercise 1.

  • The scaled-linear schedule.
  • A PCA autoencoder (encode and decode).
  • The scale factor.
  • Latent shapes and compression ratio.

Practice.

  • With diffusers, load a pipeline and inspect pipe.vae.config.scaling_factor; encode with vae.encode(x).latent_dist.sample() * scaling_factor.
  • Fine-tune in latent space: cache latents once, then train only the denoiser (LoRA or full).
  • Check the autoencoder on your domain first: decode encoded images and measure reconstruction (PSNR, LPIPS) on, for example, multispectral or SAR tiles; the 3-channel RGB VAE may not fit 13-band data.
  • Retrain or fine-tune the VAE when the domain differs; recompute the scale factor from your latents.
  • Use 16-channel VAEs (SD3, FLUX) when fine detail such as text or thin structures matters.
import torch
from diffusers import AutoencoderKL
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse").eval()
x = torch.rand(1, 3, 512, 512) * 2 - 1                       # an image in [-1, 1]
with torch.no_grad():
    z = vae.encode(x).latent_dist.sample() * vae.config.scaling_factor   # 1×4×64×64, std ≈ 1
    x_rec = vae.decode(z / vae.config.scaling_factor).sample
print(z.shape, z.std().item(), (x - x_rec).abs().mean().item())
🐍 Exercise 1: schedules, a linear autoencoder and latent shapes
Write the scaled-linear schedule, a PCA autoencoder with a scale factor, and the latent shape and compression ratio of a VAE.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Before diffusion, latents are multiplied by…
  2. 2. For 13-band satellite data, first check…
  3. 3. Latent fine-tuning is cheaper because…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why compress first. Likelihood-trained pixel diffusion spends most capacity on imperceptible high-frequency detail (rate–distortion: most bits are in small-variance directions). The autoencoder removes these directions with a perceptual and adversarial loss, so the diffusion model only models the low-dimensional content, and the decoder synthesises plausible texture.

Why the scale matters. The schedule fixes how much signal remains at each t: x_t = √ᾱ_t z + √(1−ᾱ_t) ε. If z is much larger than 1, the last step still contains signal (√ᾱ_T · std is 0.38 for std 5.5 under SD’s schedule), so starting from pure noise is wrong. If z is much smaller than 1, the signal is gone after the first few percent of steps, and the content is decided in the last few steps, where a coarse sampler errs.

Small-variance directions are stiff. In pixel space, detail directions have variance far below the noise level for most of the trajectory; a deterministic sampler with large steps shrinks them (the denoised estimate √ᾱ s² / (ᾱ s² + 1 − ᾱ) · x_t is near zero until the last steps). Removing them via the autoencoder avoids the problem, and the decoder supplies detail.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Pixel-space likelihood training spends capacity on…
  2. 2. Latents much larger than 1 cause…
  3. 3. Latents much smaller than 1 cause…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much of the data does a small latent keep, how much does the latent scale matter, and what does pixel-space sampling get wrong with few steps?

History.

  • R. Rombach, A. Blattmann, D. Lorenz, P. Esser and B. Ommer, “High-resolution image synthesis with latent diffusion models” (CVPR 2022): Stable Diffusion’s basis.
  • P. Esser, R. Rombach and B. Ommer, “Taming transformers” (2021): the VQGAN autoencoder.
  • D. Podell et al., “SDXL” (2024); P. Esser et al., “Scaling rectified flow transformers” (SD3, 2024).

Exercise 2. ‘Images’ are 64 pixels (8×8): content z ∈ ℝ² from a four-mode Gaussian mixture with weights 0.4, 0.3, 0.2, 0.1, rendered through two smooth ramp patterns, plus fine detail (pixel noise, std 0.1). The autoencoder is PCA. Because everything is Gaussian, the latent and pixel distributions are exact Gaussian mixtures, so we sample with their exact score instead of a trained network. DDIM on SD’s scaled-linear schedule; 4000 latent samples, 1000 pixel samples. Quality: Fréchet distance (FD) between a Gaussian fit to the samples and the true latent moments, and the TV of mode weights.

autoencoder latent dimensions 1 2 4 8
variance unexplained 0.408 0.041 0.039 0.036
sampling space, latent std FD, 10 steps FD, 50 steps TV, 50 steps
latent, std 0.2 (too small) 1.797 0.110 0.008
latent, std 1 (scaled) 0.085 0.0027 0.012
latent, std 2.7 (raw PCA) 0.056 0.0087 0.014
latent, std 5.5 (like an unscaled SD VAE) 0.112 0.045 0.025
pixel space (64 values) 0.067 0.045 0.039
  • Compression: two latent dimensions captured the content; the remaining 4.1% of variance was pure detail, which a PCA decoder cannot regenerate (a GAN-trained decoder would synthesise it).
  • Too-small latents were 21 times worse than unit latents at 10 steps (FD 1.797 against 0.085): the content was decided in the last few steps.
  • Too-large latents: std 5.5 left signal at t = T (Gaussian KL from N(0, I) 0.0091, against under 0.0001 at std 1) and had FD 0.045 against 0.0027 at 50 steps; seeds 1 and 2 gave 0.032 and 0.032 against 0.018 and 0.0025. Not a strict optimum at 1: at 10 steps the raw std 2.7 was slightly better than std 1 on all three seeds.
  • Pixel space: content quality was in the same range (FD 0.067 at 10 steps; at 50 steps 0.045, 0.010 and 0.080 on seeds 0–2, noisy because only 1000 samples were affordable), but the fine detail came out with std 0.049 at 10 steps and 0.074 at 50 steps against the true 0.1: few-step deterministic sampling shrinks small-variance directions. Each pixel-space step also handles 32 times more values.
  • Seeds 1 and 2: std-0.2 FD at 10 steps 1.729 and 1.729; pixel detail std at 10 steps 0.049 and 0.049.
  • Caveat: a linear autoencoder and exact scores; real VAEs are nonlinear and real denoisers have finite capacity, which is where most of latent diffusion’s practical advantage comes from.
🐍 Exercise 2 (research): how much of the data does a small latent keep, how much does the latent scale matter, and what does pixel-space sampling get wrong with few steps?
Fit a PCA autoencoder to toy 64-pixel images, sample latents with different scale factors and pixels directly with an exact-score DDIM sampler, and compare Fréchet distances and detail.

Latent diffusion in AI, robotics and aerospace

  • Earth observation: latent diffusion models trained on satellite imagery (for example DiffusionSat, 2024) generate and super-resolve scenes conditioned on metadata; domain-specific autoencoders handle multispectral bands.
  • Weather and climate: generative weather models increasingly diffuse in learned latent spaces of atmospheric fields to make ensembles affordable.
  • Video and world models: video diffusion and robot world models compress frames spatially and temporally before diffusion; the compression ratio sets what can be simulated in real time.

References

  1. R. Rombach, A. Blattmann, D. Lorenz, P. Esser and B. Ommer (2022). “High-resolution image synthesis with latent diffusion models.” CVPR.
  2. P. Esser, R. Rombach and B. Ommer (2021). “Taming transformers for high-resolution image synthesis.” CVPR.
  3. D. Podell et al. (2024). “SDXL: improving latent diffusion models for high-resolution image synthesis.” ICLR.
  4. P. Esser et al. (2024). “Scaling rectified flow transformers for high-resolution image synthesis.” ICML.
  5. S. Lin, B. Liu, J. Li and X. Yang (2024). “Common diffusion noise schedules and sample steps are flawed.” WACV.