Diffusion models
Train a network to predict the noise added to real data; generate by starting from pure noise and removing predicted noise step by step. Quality, steps and latency trade off directly.
Analogy: A restorer who has watched thousands of photos fade into static learns to reverse one small step of fading. Repeat that step enough times on pure static and a new photo appears.
How it works
- Training uses a plain MSE loss on the predicted noise: stable, with no adversarial game as in GANs.
- Latent diffusion runs in a VAE's compressed space, with 48× fewer values than pixels, then decodes back.
- The denoiser was a U-Net; newer models use diffusion transformers (DiT), which scale like LLMs.
- Classifier-free guidance follows the prompt more as w rises, but loses diversity and costs 2 passes per step.
- Samplers like DDIM cut 1,000 steps to tens; distillation reaches 1–4, trading away detail and diversity.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your text-to-image endpoint runs SDXL base at 30 steps with CFG and takes seconds per image. Product now wants live previews that update while the user types. What do you propose?
Go deeper
Full explanation
A diffusion model generates by learning to undo noise. Training: take a real image, add Gaussian noise at a random level t (closed form, no loop) and train a network to predict the noise that was added. Plain MSE loss: stable, no adversarial game as in GANs. Sampling: start from pure noise and repeatedly remove the predicted noise, over ~20–50 steps, until an image emerges.
Latent diffusion (Stable Diffusion) makes it affordable: a VAE compresses a 512×512×3 image into a 64×64×4 latent (48× fewer values), diffusion runs there, and the decoder maps back to pixels.
The denoiser was a U-Net (a conv encoder–decoder with skip connections); newer models use diffusion transformers (DiT) over latent patches, which scale like LLMs (SD3, FLUX, Sora).
Text conditioning: a text encoder (CLIP, T5) feeds the denoiser through cross-attention. Classifier-free guidance (CFG) trains with the prompt sometimes dropped, then extrapolates away from the unconditional prediction: ε = ε_u + w·(ε_c − ε_u). A higher w follows the prompt more but loses diversity, and each step costs 2 passes.
Steps vs quality vs latency is the core trade-off. Better ODE samplers (DDIM, DPM-Solver) cut DDPM's 1,000 steps to tens; distillation (LCM, SDXL Turbo) reaches 1–4. Flow matching (rectified flow), the newer formulation, learns a velocity along near-straight noise-to-data paths, so fewer steps suffice.
Code Noise-prediction training step, then sampling with diffusers
import torch, torch.nn.functional as F
from diffusers import AutoPipelineForText2Image
T = 1000
betas = torch.linspace(1e-4, 0.02, T) # DDPM linear noise schedule
alpha_bar = torch.cumprod(1 - betas, dim=0) # share of signal left at step t
def train_step(model, x0, text_emb, null_emb, opt, p_uncond=0.1):
"""x0: clean latents (B, 4, 64, 64). The model learns to predict the noise."""
B = x0.shape[0]
t = torch.randint(0, T, (B,)) # random noise level per sample
eps = torch.randn_like(x0)
a = alpha_bar[t].view(B, 1, 1, 1)
xt = a.sqrt() * x0 + (1 - a).sqrt() * eps # jump straight to step t, no loop
# Drop the prompt ~10% of the time: one model learns cond + uncond (for CFG)
drop = (torch.rand(B) < p_uncond).view(B, 1, 1)
cond = torch.where(drop, null_emb, text_emb)
loss = F.mse_loss(model(xt, t, cond), eps) # plain MSE on the noise
opt.zero_grad(); loss.backward(); opt.step()
return loss.item()
MODEL = "stabilityai/stable-diffusion-xl-base-1.0" # any text-to-image checkpoint
pipe = AutoPipelineForText2Image.from_pretrained(MODEL, torch_dtype=torch.float16).to("cuda")
image = pipe(
"isometric illustration of a data center, soft morning light",
num_inference_steps=30, # latency ~ steps x 2 passes (CFG)
guidance_scale=7.0, # eps_u + w * (eps_c - eps_u): prompt adherence vs diversity
).images[0]Real example
A design tool generates 1024×1024 product shots. SDXL base at 30 steps with CFG means 60 denoiser evaluations per image (batched as 30 passes of 2) on a 128×128×4 latent: seconds per image. For live previews while the user types, SDXL Turbo samples 512×512 in 1–4 steps with no CFG: 15–60× fewer evaluations, each on a latent 4× smaller, at the cost of detail and diversity. You ship both: Turbo for previews, the full model for the final render, and you cache the prompt's text embeddings between the two.
Trade-offs +3 · −4
+ You gain
- State-of-the-art quality and diversity for images, video and audio; stable training (MSE loss, no GAN mode collapse).
- Flexible conditioning on one model: text, reference images, depth or pose (ControlNet), inpainting, editing.
- A quality dial at inference: trade steps and guidance for latency without retraining.
− You pay
- Iterative: tens of full forward passes per output, so seconds of latency without distillation.
- Compute grows with resolution (and frames for video); DiT attention grows quadratically with latent tokens.
- Guidance and distillation trade diversity for fidelity; hands, text and counts still fail.
- Hard to evaluate: FID and CLIP score track human preference only loosely.
Use it when
Generating or editing images, video or audio from text or other conditions: creative tools, inpainting, super-resolution, product shots, synthetic training data for vision models.
Avoid it when
Hard real-time or on-device budgets without a distilled few-step model; outputs that need exact text, layout or counts (render them instead); plain text generation, where autoregressive LLMs dominate.
Numbers to know 5
- DDPM trains with T = 1,000 noise steps; DDIM samples in tens of steps, 10–50× faster wall-clock (Song et al., 2020).
- Stable Diffusion v1: 512×512×3 → 64×64×4 latent (48× fewer values); ~860M-param U-Net plus a 123M CLIP text encoder.
- CFG costs 2 denoiser passes per step; the diffusers Stable Diffusion pipeline defaults to guidance 7.5.
- Distilled models (LCM, SDXL Turbo) sample in 1–4 steps; SDXL Turbo runs at 512×512 without CFG.
- Rule of thumb: cost per image ≈ steps × (2 with CFG) × one denoiser pass, which grows with resolution.
Common pitfalls 4
- Cranking guidance: oversaturated, artifact-heavy images and less diversity. Tune w together with steps.
- Evaluating at 50 steps, then shipping 20: test the exact sampler, step count and guidance you serve.
- Applying CFG or negative prompts to a distilled model trained without them (Turbo expects guidance 0).
- A scheduler that doesn't match the model's noise schedule or prediction target (noise, v or velocity): silent garbage.
Interview questions 3
Answer out loud first, then reveal.
Explain how a diffusion model is trained and sampled.Show answer
In training I take a clean sample, pick a random timestep, mix in Gaussian noise with the closed-form schedule and train the network to predict that noise with MSE. One random timestep per example, so training is cheap and stable. Sampling inverts it: start from pure noise, predict the noise, take a solver step toward clean data and repeat, typically 20 to 50 times. Text enters through cross-attention, and classifier-free guidance strengthens it. In latent diffusion all of this runs in a VAE latent, 48 times smaller than the pixels.
How does serving a diffusion model differ from serving an LLM?Show answer
LLM decode is memory-bandwidth bound: one token at a time, a KV cache, cost proportional to output length, and continuous batching is the key optimization. Diffusion is compute-bound: each step is a full forward pass over the whole latent in parallel, for a fixed number of steps, doubled by CFG, with no KV cache. Cost per image is predictable from steps and resolution. So my levers differ: fewer steps through better samplers or distillation, generating small and upscaling, batching same-shape requests, lower precision and compilation, and caching prompt embeddings. Latency is seconds, so I design an async UX with fast previews.
What is flow matching, and why did SD3 and FLUX adopt it?Show answer
Flow matching trains the network to predict a velocity that moves a sample from noise to data along a chosen path. With rectified flow the path is a straight line, xₜ = (1 − t)·x₀ + t·ε, so the target is simply ε − x₀. It is simpler and more general than the noise-prediction view, and straighter paths let an ODE solver take bigger steps for the same quality. Esser et al. showed rectified-flow transformers scale well, which is why SD3 and FLUX use them. The practical consequence for me: fewer sampling steps, so lower serving cost.