Stable Diffusion Architecture
Stable Diffusion is a latent diffusion model (LDM) that performs the iterative denoising process of diffusion models within a compressed latent space rather than pixel space, enabling high-quality image synthesis at dramatically reduced computational cost. It matters because it democratized high-resolution generative image synthesis — running on consumer GPUs — while establishing the architectural blueprint for nearly all subsequent text-to-image, text-to-video, and multimodal generation systems. The counterintuitive fact: the model never directly generates pixels; it generates compressed noise in a 64× smaller space, and a separately trained decoder reconstructs the final image.
The central insight of Stable Diffusion is the latent space trick: instead of denoising a 512×512×3 pixel tensor (786,432 values), the diffusion process operates on a 64×64×4 latent tensor (16,384 values) — a 48× reduction in dimensionality. A pretrained Variational Autoencoder compresses images into this latent space and reconstructs them back; the diffusion U-Net never touches pixel space at all. This separation of perceptual compression (VAE) from semantic generation (U-Net + CLIP) is what makes the architecture both efficient and steerable by text. The "aha moment": diffusion models are expensive not because of their iterative nature but because of the space they iterate in — move to latent space and the cost collapses.
How It Works
1. The VAE: Perceptual Compression
The Variational Autoencoder (VAE) is trained with a combination of reconstruction loss, KL-divergence regularization, and a patch-based adversarial loss. Given an image , the encoder maps it to a latent distribution:
Explanation: The encoder spatially downsamples the image by factor (typically ) to produce a compact latent tensor with channels. Here, are pixel height/width; are latent height/width; is the downsampling factor; is the number of latent channels. The VAE decoder inverts this: . The VAE training objective is:
Explanation: The VAE is trained to reconstruct faithfully (first term), keep the latent distribution close to a standard Gaussian (KL term), and produce perceptually sharp outputs via an adversarial patch discriminator (third term). Where is a pixel-level reconstruction loss (L1 or perceptual LPIPS), is the KL divergence, is the PatchGAN discriminator loss, and are loss weights (typically and ). ---
2. The Forward Diffusion Process
The forward (noising) process incrementally adds Gaussian noise to the latent over timesteps according to a fixed Markov chain:
Explanation: At timestep , the noisy latent is a mixture of the original latent (scaled by ) and pure Gaussian noise, where as . Here is the cumulative noise schedule product; is the variance schedule at step (often cosine or linear); is the total number of timesteps (typically 1000 during training). This allows sampling directly from in one step — no sequential iteration needed during training. ---
3. The Denoising U-Net and Conditioning
The U-Net is trained to predict the noise added to to produce , conditioned on timestep and text embedding :
Explanation: The U-Net learns to estimate which noise was added to the latent at timestep , guided by the text prompt embedding, so it can be subtracted to recover a cleaner latent. Where is the denoising U-Net with parameters ; is the noisy latent; is the CLIP text encoder output for prompt ; and the expectation is over all training images, noise samples, timesteps, and prompts. ---
4. Classifier-Free Guidance
Stable Diffusion uses Classifier-Free Guidance (CFG) at inference to amplify prompt adherence without a separate classifier:
Explanation: The final noise prediction is the unconditional prediction shifted in the direction of the conditional prediction by guidance scale , pushing the sample toward prompt-consistent regions of the latent distribution. Where is the unconditional noise prediction (null-text condition); is the text-conditioned prediction; is the guidance scale (typically 7.5); and is the guided noise estimate used for the denoising update. Higher increases prompt fidelity at the cost of diversity and potential oversaturation. ---
PyTorch Sketch: The Core Inference Loop
```python import torch from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler from transformers import CLIPTextModel, CLIPTokenizer
# Load components vae = AutoencoderKL.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="vae") unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="unet") text_encoder = CLIPTextModel.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="text_encoder") tokenizer = CLIPTokenizer.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="tokenizer") scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-2-1", subfolder="scheduler") device = "cuda" guidance_scale = 7.5 num_inference_steps = 50
# 1. Encode text prompt prompt = "a photorealistic mountain lake at sunset" tokens = tokenizer([prompt, ""], padding="max_length", return_tensors="pt").to(device) text_embeddings = text_encoder(tokens.input_ids)[0] # [2, 77, 1024]
# 2. Initialize random latent latents = torch.randn(1, 4, 64, 64, device=device) # z_T ~ N(0, I) scheduler.set_timesteps(num_inference_steps)
# 3. Iterative denoising in latent space for t in scheduler.timesteps: latent_input = torch.cat([latents] * 2) # duplicate for CFG with torch.no_grad(): noise_pred = unet(latent_input, t, encoder_hidden_states=text_embeddings).sample
# Classifier-free guidance (Eq. 5) noise_uncond, noise_cond = noise_pred.chunk(2) noise_pred = noise_uncond + guidance_scale * (noise_cond - noise_uncond) latents = scheduler.step(noise_pred, t, latents).prev_sample
# 4. Decode latent → pixel space latents = latents / vae.config.scaling_factor with torch.no_grad(): image = vae.decode(latents).sample # [1, 3, 512, 512] image = (image / 2 + 0.5).clamp(0, 1) ``` The `vae.config.scaling_factor` (0.18215 for SD 1.x) normalizes the latent distribution to unit variance before denoising — a subtle but critical detail that causes NaN artifacts if omitted. ---
Cross-Attention: How Text Controls the Image
Text conditioning enters the U-Net via cross-attention layers inserted between the convolutional residual blocks. The spatial features of the U-Net serve as queries, and the CLIP text embeddings serve as keys and values: ```python
# Simplified cross-attention inside U-Net ResBlock class CrossAttention(nn.Module): def __init__(self, query_dim, context_dim, heads=8, head_dim=64): super().__init__() inner_dim = heads * head_dim self.to_q = nn.Linear(query_dim, inner_dim, bias=False) self.to_k = nn.Linear(context_dim, inner_dim, bias=False) self.to_v = nn.Linear(context_dim, inner_dim, bias=False) self.to_out = nn.Linear(inner_dim, query_dim) self.heads = heads self.scale = head_dim ** -0.5 def forward(self, x, context):
# x: [B, HW, C_spatial] context: [B, 77, C_text] Q = self.to_q(x) # spatial features → queries K = self.to_k(context) # text tokens → keys V = self.to_v(context) # text tokens → values
# Scaled dot-product attention attn = torch.softmax(Q @ K.transpose(-1, -2) * self.scale, dim=-1) return self.to_out(attn @ V) ``` This is why prompt token order and length matter: each spatial position in the U-Net attends to all 77 CLIP tokens, and the attention weights directly determine which text concepts influence which image regions.
Robin Rombach is a computer vision researcher who completed his PhD at LMU Munich under Björn Ommer and later joined Stability AI. His landmark 2022 paper "High-Resolution Image Synthesis with Latent Diffusion Models" introduced the core LDM architecture — the compression-then-diffusion approach that became Stable Diffusion — showing that perceptual compression into latent space reduces computational cost by orders of magnitude while preserving generation quality. A surprising historical note: the original LDM paper was submitted to CVPR 2022 as a general-purpose framework for audio, semantic maps, and images — Stability AI's decision to scale it specifically for text-to-image synthesis on the LAION-5B dataset was a later engineering and funding decision, not part of the original academic vision.
Jonathan Ho is a research scientist at Google Brain (now Google DeepMind) who completed his PhD at UC Berkeley under Pieter Abbeel. His 2020 paper "Denoising Diffusion Probabilistic Models" (DDPM) established the modern formulation of diffusion models as score-matching through a Markov noising process, demonstrating that the simplified noise-prediction objective (Eq. 4) outperforms the variational lower bound objective — a counterintuitive finding that unlocked practical training. Ho also co-authored the classifier-free guidance paper that enables the CFG mechanism (Eq. 5) used in all modern text-to-image systems.