8.4Stable Diffusion & classifier-free guidance
Run diffusion in a small latent space, steer it with a text encoder through cross-attention, and turn up the guidance knob to make it actually follow your prompt.
From “a diffusion model” to “type a sentence, get a picture”
The previous lesson built a diffusion model that can generate some image from noise. Two problems stand between that and a text-to-image product. First, cost: denoising a 512×512 RGB image means running a big network over 786,432 numbers, dozens of times per picture. Second, control: an unconditional model gives you a random sample of its training data, not “an astronaut riding a horse in watercolor”.
Stable Diffusion’s answers come from the paper High-Resolution Image Synthesis with Latent Diffusion Models (Rombach, Blattmann, Lorenz, Esser and Ommer, 2021), whose model was trained and released in 2022 with Stability AI and Runway. The answers are: diffuse in a compressed space (latent diffusionLatent diffusionRunning diffusion in a VAE's compressed latent space instead of pixel space. Stable Diffusion works this way.), feed in text with cross-attentionCross-attentionAttention where queries come from one sequence (e.g. image latents) and keys/values from another (e.g. text tokens)., and steer at sampling time with classifier-free guidanceClassifier-free guidance (CFG)At sampling time, the conditional and unconditional predictions are mixed and pushed further toward the conditional one to follow the prompt more closely.. Because the weights were released openly, it became the base for a huge ecosystem of fine-tunes and tools, which you’ll meet in ControlNet, LoRA, img2img & inpainting.
An architect doesn’t design a skyscraper at full scale. They work on small sketches where one stroke stands for a whole wall, and only at the end hand the final sketch to a builder who fills in every brick. The sketchbook is the latent space, the builder is the VAE decoder, and the architect revising the sketch over and over is the U-Net denoising loop.
Now add a client who keeps saying “more like the brief!”. Each revision, the architect asks two questions: what would I draw without the brief, and what would I draw with it? Then they exaggerate the difference. A little insistence gives designs that clearly match the brief. Too much, and every design becomes the same over-the-top caricature. That insistence is the guidance scale.
Latent diffusion: denoise a sketch, not the pixels
Most of an image’s pixels encode fine, locally predictable detail: textures, sharp edges, sensor noise. Rombach et al. split the job in two. A VAEVariational autoencoder (VAE)An autoencoder whose latent space is regularized to be smooth and samplable, so new data can be generated by decoding random latents. (an autoencoder with a KL penalty, trained with perceptual and adversarial losses so its reconstructions stay sharp; see Autoencoders, VAEs & latent space) learns to compress each image, and the diffusion model only has to model the much smaller latent.
For Stable Diffusion 1.x and 2.x, the encoder downsamples by 8× in each spatial direction and keeps 4 channels: a 512×512×3 image becomes a 64×64×4 latent, 48 times fewer numbers. Diffusion runs entirely on those latents; the decoder is called once at the very end. That made high-resolution generation feasible on a single consumer GPU. Later models kept the idea but widened the latent: SD3 and FLUX use 16 latent channels, which preserves more detail.
The denoiser: a U-Net that reads text
The denoiser in SD 1.x is a U-NetU-NetA convolutional encoder-decoder with skip connections, the classic denoiser backbone in diffusion models. of about 860M parameters. Its shape is an hourglass: ResNet blocks progressively downsample the latent (64 → 32 → 16 → 8), then upsample back, with skip connections carrying detail across. Three inputs flow in:
- The noisy latent , which is what’s being denoised.
- The timestep , turned into a sinusoidal embedding (the same trick as Transformer positional encodingsPositional encodingInformation added to token representations so the model knows word order. Examples: sinusoidal, learned, RoPE.), passed through a small MLP, and added inside every ResNet block. This tells the network how noisy its input is.
- The text, via cross-attention layers interleaved at the lower resolutions. The prompt is tokenized to 77 tokens and encoded by a frozen CLIPCLIPOpenAI's 2021 model that learns a shared embedding space for images and text by contrasting matching and non-matching pairs. text encoder (CLIP ViT-L/14 in SD 1.x, 768 dimensions per token). In each cross-attention layer, every latent position forms a query; the text tokens supply the keys and values. So a position in the image can “look up” the words relevant to it, which is how “red” ends up on the ball and not the sky.
The text encoder changed with each generation. SD 2.x switched to OpenCLIP ViT-H/14. SDXL (2023) used two text encoders, OpenCLIP ViT-bigG/14 and CLIP ViT-L/14, concatenating their features, with a U-Net about three times larger. SD3 (2024) added a third, the T5-XXL language model, alongside two CLIP encoders, and replaced the U-Net with a Transformer; that is the subject of Diffusion Transformers & flow matching.
ResNet blocks process the latent at several resolutions; the timestep enters as an embedding added inside each block; text enters through cross-attention, where image positions (queries) look up the text tokens (keys and values). With CFG it runs twice per step: with and without the prompt.
The scheduler (or sampler) is the code that turns the U-Net’s noise prediction into the next latent: the DDIM update from the last lesson, or newer ODE solvers like Euler, Heun or DPM-Solver++. Schedulers are swappable at inference without retraining, which is why interfaces like ComfyUI or the diffusers library let you pick one from a menu. Good solvers produce clean images in 20–30 steps.
Classifier-free guidance
Train this model with captions and you will be disappointed: samples are vaguely related to the prompt, but loose. The model has learned honestly, and for many captions that distribution is broad and messy, because training captions are noisy.
An early fix, classifier guidance (Dhariwal and Nichol, 2021), trained a separate classifier on noisy images and added its gradient to push samples toward a class. It worked, but needed an extra noise-aware classifier. Ho and Salimans (2022) found a way to get the same effect for free:
- During training, randomly replace the caption with an empty one some fraction of the time (SD 1.x dropped the text 10% of the time). Now one network knows both the conditional prediction and the unconditional one .
- During sampling, run both and combine them:
The difference is a direction: “what the prompt changes”. With you get the unconditional model, with the plain conditional model, and with you extrapolate, pushing further in the prompt’s direction than the model itself believes is right. Stable Diffusion’s common default is . The cost is two U-Net evaluations per step (usually batched together).
Shaded clouds: training data by class. Black dots: 180 samples from the same starting noise.
Here the “denoiser” is exact: for this toy data, the conditional and unconditional noise predictions can be computed in closed form, then mixed with the CFG formula and run through a 40-step DDIM sampler. Things to try:
- . The prompt is ignored, and samples land on cats, dogs and birds in proportion to the data. Only about a third are on-target.
- . The honest conditional model: nearly all samples are cats, spread over the whole cat region. Diversity is close to 1.
- . Samples are pushed toward the side of the cat region farthest from the dogs and birds. Fidelity readouts look great, but diversity has dropped: you’ve traded variety for “prompt-ness”.
- . Many samples overshoot the data altogether. In real images this is the familiar over-guided look: oversaturated colors, harsh contrast, the same pose every time.
Why “away from the others”? Guidance adds extra copies of the direction , an implicit classifier’s gradient. That gradient keeps growing where the image is most unlike other classes, not where it is most typical of this one. Large therefore finds caricatures.
The knobs on every image generator, explained
You now know enough to decode the settings panel of any Stable Diffusion interface:
- Seed. Fixes the initial latent noise . Same seed, prompt, sampler and settings give the same image; change only the seed and you get a new composition.
- Steps. How many times the denoising loop runs. Each step is two U-Net passes with CFG, so 30 steps means 60 network evaluations.
- Sampler / scheduler. The ODE or SDE solver that turns predictions into steps. Deterministic ones (DDIM, Euler) converge to a fixed image as steps grow; “ancestral” ones inject fresh noise and keep changing.
- Guidance scale (CFG). The above: how hard to push toward the prompt.
- Width and height. Set the latent size (pixels ÷ 8). Going far beyond the training resolution tends to produce duplicated subjects, because the U-Net has only ever seen compositions at its native scale.
MATH CORNER · optionalWhy CFG sharpens: the implicit classifier, with numbers
Recall from the diffusion lesson that the noise prediction is a scaled score: . Bayes’ rule says
So the CFG combination, written in score form, is
the score of the tilted distribution . Raising the classifier’s probability to the power sharpens it: regions where the class is only probably right get suppressed.
Worked example. Take three candidate images with prior and class probability :
| image | weight | share | weight | share | ||
|---|---|---|---|---|---|---|
| typical cat | 0.50 | 0.80 | 0.400 | 0.56 | 0.094 | 0.49 |
| extreme cat | 0.10 | 0.99 | 0.099 | 0.14 | 0.093 | 0.49 |
| cat-ish dog | 0.40 | 0.55 | 0.220 | 0.31 | 0.005 | 0.02 |
At the ambiguous “cat-ish dog” still gets almost a third of the samples. At it has all but vanished, and the typical and extreme cats are tied even though the extreme one is 5× rarer in the data. Push to 15 and the extreme cat wins outright ( versus ). That’s the collapse toward caricature you saw in the demo. (Strictly, CFG at each noise level is not exactly sampling from , but this captures the trend.)
In code
With Hugging Face diffusers, the whole pipeline is a few lines; the guided loop inside it looks like the sketch underneath.
from diffusers import StableDiffusionPipeline
import torch
pipe = StableDiffusionPipeline.from_pretrained(
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda")
img = pipe("a watercolor fox in the snow", negative_prompt="blurry",
guidance_scale=7.5, num_inference_steps=30).images[0]
# What happens inside (simplified):
# cond = text_encoder(tokenize(prompt)) # 77 x 768
# uncond = text_encoder(tokenize(negative_prompt)) # or ""
# z = torch.randn(1, 4, 64, 64) # the seed lives here
# for t in scheduler.timesteps:
# e_u, e_c = unet(torch.cat([z, z]), t, torch.cat([uncond, cond])).chunk(2)
# eps = e_u + guidance_scale * (e_c - e_u) # classifier-free guidance
# z = scheduler.step(eps, t, z).prev_sample
# image = vae.decode(z / vae.config.scaling_factor)
- “Stable Diffusion generates pixels directly.” The U-Net never sees pixels. It denoises a 64×64×4 latent (for 512×512 output), and the VAE decoder turns that into an image once at the end.
- “Higher guidance is always better.” Guidance trades diversity and realism for prompt adherence. Past roughly 7–12 for SD 1.x, images become oversaturated and samey; the demo shows samples leaving the data entirely.
- “Classifier-free guidance needs a separate unconditional model.” The same network learns both, because the caption is dropped for a fraction of training examples. The ‘empty prompt’ is just another input.
- “The text encoder is trained along with the image model.” In SD 1.x and SDXL the CLIP text encoders are frozen, pretrained models. Only the U-Net (and separately the VAE) is trained for generation.
- “More sampling steps always helps.” With a good solver, quality saturates around 20–50 steps; beyond that you mostly pay time.
Check your understanding
Q1.Why does Stable Diffusion run diffusion in a VAE latent space instead of pixel space?
Q2.In the U-Net's cross-attention layers, where do queries, keys and values come from?
Q3.With ε̂ = ε_uncond + w(ε_cond − ε_uncond), what does w = 1 correspond to?
Q4.How does a single network provide both conditional and unconditional predictions for CFG?
Q5.You crank the guidance scale to 20. What is the most likely outcome?
Further reading
- paperHigh-Resolution Image Synthesis with Latent Diffusion Models (Rombach et al., 2021) — The latent diffusion paper behind Stable Diffusion.
- paperClassifier-Free Diffusion Guidance (Ho & Salimans, 2022) — Conditioning dropout and the guidance formula.
- paperSDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis (Podell et al., 2023) — Bigger U-Net, two text encoders, refiner.
- paperDiffusion Models Beat GANs on Image Synthesis (Dhariwal & Nichol, 2021) — Classifier guidance, the predecessor of CFG.
- blogThe Illustrated Stable Diffusion (Jay Alammar) — A visual walk through the components.
- docsHugging Face diffusers documentation — Pipelines, schedulers and the guided loop in real code.