Phase 1: Diffusion Model Fundamentals · 50 min · Python · PyTorch · Hugging Face Diffusers
The Concept
The VAE: variational autoencoder
The VAE (Variational Autoencoder) is the compression model. It has two parts:
Encoder: Image (512x512x3) → Latent (64x64x4)
Decoder: Latent (64x64x4) → Image (512x512x3)
The encoder compresses the image by a factor of 8 in each spatial dimension (512→64) and reduces channels from 3 to 4. The total compression:
Pixel space: 512 × 512 × 3 = 786,432 values
Latent space: 64 × 64 × 4 = 16,384 values
Compression: 786,432 / 16,384 = 48x
This 48x compression means diffusion runs on 16,384 values instead of 786,432 — a massive reduction in compute and memory.
from diffusers import AutoencoderKL
import torch
# Load the VAE from Stable Diffusion
vae = AutoencoderKL.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="vae")
vae.to("cuda")
# Encode: image → latent
image_tensor = torch.randn(1, 3, 512, 512).cuda() # (B, C, H, W)
latent = vae.encode(image_tensor).latent_dist.sample()
# latent shape: (1, 4, 64, 64) — 48x compressed
# Decode: latent → image
reconstructed = vae.decode(latent).sample
# reconstructed shape: (1, 3, 512, 512) — back to pixel space
Why latent diffusion works
The VAE learns to preserve the semantically meaningful information in the image while discarding high-frequency details that are perceptually less important. The latent space captures:
- Global structure: objects, layout, composition
- Colors: dominant color palette
- Textures: at a coarse level
It discards:
- Pixel-perfect details: exact edge positions
- High-frequency noise: imperceptible patterns
This is fine for generation because the diffusion model creates the structure, and the VAE decoder fills in the details during decoding.
The full latent diffusion pipeline
1. Text Encoding: "a cat on a windowsill" → CLIP/T5 embeddings
2. Latent Noise: Generate random noise in latent space (64x64x4)
3. Diffusion: Run T denoising steps in latent space (not pixel space!)
4. VAE Decode: Latent (64x64x4) → Image (512x512x3)
5. Output: Final generated image
The critical difference from pixel-space diffusion: steps 2 and 3 operate on 64x64x4 latents, not 512x512x3 pixels. This is the 48x compute reduction.
A 512x512 RGB image has 786,432 pixel values. After VAE encoding to a 64x64x4 latent, how many values remain, and what is the compression ratio?
64 × 64 × 4 = 16,384 latent values. 786,432 / 16,384 = 48x compression. This means diffusion runs on 48x fewer values, which is why Stable Diffusion can run on consumer GPUs with 8GB VRAM instead of data center GPUs.
VAE quality matters
The VAE is not just a compression tool — it directly affects output quality. A better VAE means:
- Sharper images: better high-frequency detail reconstruction
- Better faces: less blurring in portrait regions
- More accurate colors: less color shift during encode-decode
This is why people swap VAEs in Stable Diffusion:
# Load SDXL with a better VAE
from diffusers import StableDiffusionXLPipeline, AutoencoderKL
# Better VAE (e.g., sdxl-vae-fp16-fix)
custom_vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
vae=custom_vae, # Swap in the better VAE
torch_dtype=torch.float16,
)
Latent space interpolation
One powerful application of latent space: interpolating between images. By encoding two images and linearly interpolating their latents, you get a smooth transition that passes through meaningful semantic space.
def interpolate_latents(vae, image1, image2, num_steps=10):
"""Interpolate between two images in latent space."""
# Encode both images
latent1 = vae.encode(image1).latent_dist.sample()
latent2 = vae.encode(image2).latent_dist.sample()
# Linear interpolation
images = []
for i in range(num_steps):
alpha = i / (num_steps - 1)
interpolated = (1 - alpha) * latent1 + alpha * latent2
decoded = vae.decode(interpolated).sample
images.append(decoded)
return images
This produces a smooth morph between the two images — something that's difficult to achieve in pixel space because pixel interpolation produces double-exposure effects, not semantic transitions.
FLUX and latent diffusion
FLUX also uses latent diffusion, but with a different VAE:
| Model | VAE Latent Shape | Compression | VAE Channels |
|---|
| SD 1.5 | (4, 64, 64) for 512x512 | 48x | 4 |
| SDXL | (4, 128, 128) for 1024x1024 | 48x | 4 |
| FLUX | (16, 128, 128) for 1024x1024 | 12x | 16 |
FLUX uses 16 channels (vs 4 for SDXL) and less spatial compression (8x vs 8x but 16 channels). This means FLUX's latent space is richer — more information per spatial location — which contributes to its higher quality.