Latent diffusion and guidance¶
Two ideas turned diffusion from a slow research curiosity into Stable Diffusion, FLUX and Sora: run the diffusion in the compressed latent space of an autoencoder, where almost no bits are wasted on imperceptible detail, and steer each denoising step with classifier-free guidance, which pushes samples towards what the prompt makes more likely. Learn both and you can read the architecture of every modern image and video generator.
10,000 ft
Diffusion models learn to turn noise into data by repeated denoising, and flow matching recast the same job as learning a velocity field. On their own they are slow and expensive in pixel space and they ignore the prompt more than users want. Latent diffusion (Rombach et al., 2021) splits the problem in two: an autoencoder handles perceptual compression once, and the diffusion model learns only the semantic structure of the compressed latents. Guidance (classifier guidance in 2021, classifier-free guidance in 2022) trades sample diversity for prompt adherence and quality with a single dial. Stable Diffusion 1–3, SDXL, FLUX, DALL·E 3-era systems and nearly every video generator in video and world models are latent diffusion or latent flow models with guidance; their text encoders come from CLIP and T5, and their denoisers are U-Nets or transformers.
2,000 ft
Training happens in two stages. First, train an autoencoder \((\mathcal{E}, \mathcal{D})\) to compress a 512×512×3 image into, say, a 64×64×4 latent and back, with perceptual and adversarial losses so that the reconstruction looks right. Freeze it. Second, train a diffusion (or flow) model on the latents \(z = \mathcal{E}(x)\), conditioned on a text embedding through cross-attention, and drop the text 10% of the time so the same network also learns the unconditional model. To sample: start from Gaussian noise in latent space; at each step run the denoiser twice (with and without the prompt) and extrapolate from the unconditional prediction past the conditional one by the guidance scale \(s\); after 20–50 steps, decode the latent to pixels once.
Ground level¶
Why pixels are the wrong place to diffuse¶
Most of the bits in an image are spent on things nobody would notice if they changed: exact grain, the precise phase of high-frequency texture, sensor noise. A likelihood-trained model in pixel space must model all of them. Rombach and colleagues measured this directly: plotting rate (bits) against distortion for a trained pixel-space diffusion model, almost all of the rate goes on imperceptible detail, and only a small early part of the curve carries the semantic content (Figure 2 of the LDM paper). They call the two regimes perceptual compression and semantic compression.
The cost of pixel space is also structural. A 512×512 image has 262,144 pixel positions; self-attention over all of them would need a \(262{,}144^2 \approx 6.9\times10^{10}\)-entry attention matrix per head per layer. Pixel-space systems such as Imagen therefore generate at 64×64 and stack two super-resolution diffusion models on top (a cascade). Latent diffusion removes the problem at the root:
Worked example: what the autoencoder buys
| Model | Image | Latent | Values in image | Values in latent | Compression |
|---|---|---|---|---|---|
| Stable Diffusion 1.x | 512×512×3 | 64×64×4 | 786,432 | 16,384 | 48× |
| SDXL | 1024×1024×3 | 128×128×4 | 3,145,728 | 65,536 | 48× |
| SD3 / FLUX.1 | 1024×1024×3 | 128×128×16 | 3,145,728 | 262,144 | 12× |
Self-attention at SD 1.x's 64×64 latent is over 4,096 positions: a 16.8 million-entry attention matrix, 4,096 times smaller than in pixel space. SD3 and FLUX then patchify the 16-channel latent into 2×2 patches, giving \(64\times64 = 4{,}096\) tokens of dimension \(2\cdot2\cdot16 = 64\) for a 1024×1024 image. (Latent sizes: the SD 1.x inference config and the FLUX reference code; SD3's choice of 16 channels is in Section 5.2.1 of Esser et al. 2024.)
The first stage: an autoencoder that only has to look right¶
The autoencoder is trained once, on images alone, with a loss that cares about appearance rather than pixel-exact reconstruction:
Three choices matter.
- The adversarial term. A patch-based discriminator (from VQGAN, Esser, Rombach and Ommer 2020) punishes blur. An L2-only autoencoder at 48× compression produces mush; with a patch GAN it produces sharp, plausible texture. This is exactly the "perceptual compression" job: invent convincing high-frequency detail so the diffusion model never has to. (See GANs for why adversarial losses sharpen.)
- A tiny KL weight. The LDM paper weights the KL term by about \(10^{-6}\) (Appendix G). That is nothing like a real VAE: the encoder is nearly deterministic and the latent is not close to \(\mathcal{N}(0,I)\). The KL term only stops the latent from drifting to arbitrary scales. A VQ layer is the alternative regulariser; both work.
- Downsampling factor \(f\) and channels \(c\). The LDM paper trained diffusion models on autoencoders with \(f \in \{1,2,4,8,16,32\}\). Small \(f\) leaves the diffusion model doing perceptual compression (slow training); large \(f\) throws away information the decoder cannot recover (quality stalls). LDM-4 to LDM-16 sat in the sweet spot, with an FID gap of 38 between pixel-space LDM-1 and LDM-8 after 2M ImageNet steps. Later work raised the channel count instead: SD3 found that going from 4 to 16 channels at \(f=8\) markedly improved reconstruction and that larger diffusion models exploit it better; DC-AE (Chen et al. 2024) pushes \(f\) to 32–64 with many channels to cut token counts further.
The latent is then scaled to roughly unit variance before diffusion. SD 1.x multiplies by 0.18215, SDXL by 0.13025, and FLUX subtracts 0.1159 and multiplies by 0.3611. These magic numbers are the inverse of the latent standard deviation measured on data (LDM Appendix G). They matter because the noise schedule assumes unit-variance signal: if the latent had variance 30, adding \(\sigma_t=1\) noise would barely touch it and the "high-noise" half of the schedule would be wasted (LDM Appendix D.1 shows the effect).
The latent is perceptual, not semantic
A 64×64×4 SD latent, viewed as an image, looks like a small, oddly coloured thumbnail of the picture. It encodes local appearance at 8×8-pixel granularity. Interpolating two latents cross-fades textures; it does not morph a cat into a dog. Semantic structure lives in what the diffusion model learns over these latents, not in the autoencoder.
The second stage: a conditional denoiser in latent space¶
The diffusion model is the same as in diffusion models, with \(x\) replaced by \(z\):
where \(\tau_\theta(y)\) is the encoded condition (text tokens, a class, a layout). Flow-matching models such as SD3 and FLUX replace \(\epsilon\)-prediction with velocity prediction on the straight path \(z_t = (1-t)z + t\epsilon\) (see score and flow matching); nothing on this page depends on which parameterisation you pick.
How the text gets in: cross-attention. Inside the denoiser, image features attend to text tokens. With \(N\) spatial positions of width \(d\) and \(M\) text tokens of width \(d_\tau\):
Every pixel of the latent asks "which words are about me?" and pulls in their values. In SD 1.x, \(\tau\) is the frozen CLIP ViT-L/14 text encoder, so \(M = 77\) and \(d_\tau = 768\); at the 64×64 level the attention matrix is \(4096\times77\). The attention maps are interpretable enough that editing them is an image-editing method: Prompt-to-Prompt (Hertz et al. 2022) swaps a word and keeps the maps, changing the object while keeping the layout. (Attention covers the mechanism in general.)
The backbone: from U-Net to transformer. The original LDMs and SD 1–2 use a convolutional U-Net (860M parameters in SD 1.x) with self- and cross-attention blocks at the lower resolutions. SDXL (Podell et al. 2023) made the U-Net three times larger (2.6B), concatenated two text encoders (CLIP ViT-L and OpenCLIP ViT-bigG), and added micro-conditioning on the original image size and crop coordinates, which fixed SD's habit of cutting off heads (a side effect of random cropping in training). DiT (Peebles and Xie 2022) replaced the U-Net with a plain transformer over latent patches, conditioning on timestep and class through adaLN-Zero (the conditioning vector predicts LayerNorm scale and shift, and a gate initialised to zero), and showed FID falling steadily with Gflops, reaching 2.27 on ImageNet 256. SD3's MM-DiT runs text and image tokens through joint attention, one sequence, with separate weights per modality; FLUX.1 is a 12-billion-parameter rectified-flow transformer in the same family.
Control beyond the prompt¶
Because the condition enters through a few well-defined doors, the ecosystem grew adapters that add new conditions without retraining the base model:
- Concatenation. Feed extra channels next to \(z_t\): a masked image for inpainting, the source image for InstructPix2Pix (Brooks et al. 2022).
- ControlNet (Zhang, Rao and Agrawala 2023) makes a trainable copy of the U-Net's encoder, feeds it an edge map, depth map or pose skeleton, and adds its outputs back into the locked model through zero convolutions: 1×1 convolutions initialised to zero, so training starts from exactly the original model and cannot damage it.
- Image prompts. IP-Adapter (Ye et al. 2023) adds a second, decoupled cross-attention over CLIP image embeddings; T2I-Adapter (Mou et al. 2023) is a light ControlNet alternative.
- Personalisation. Textual Inversion (Gal et al. 2022) learns a new word embedding from 3–5 photos; DreamBooth (Ruiz et al. 2022) fine-tunes the whole model on them with a prior-preservation loss; in practice people train LoRA adapters on the attention weights.
Guidance: the dial that made text-to-image work¶
A conditional diffusion model trained by maximum likelihood will, correctly, produce samples that are only loosely related to the prompt, because that is what the training data looks like: captions are noisy and many images fit them weakly. Users want the opposite trade: fewer, more typical, more on-prompt samples. Guidance buys that.
Classifier guidance (Dhariwal and Nichol 2021) trains a separate classifier \(p_\phi(c\mid x_t)\) on noisy images and adds its gradient to the score at every step. By Bayes' rule,
so scaling the second term by \(\gamma>1\) over-weights "looks like class \(c\)". It worked (diffusion beat BigGAN on ImageNet for the first time), but it needs a noise-aware classifier for every kind of condition, and for text there is no such classifier.
Classifier-free guidance (CFG) (Ho and Salimans 2022) removes the classifier. Train one network on both tasks by replacing the condition with a null token \(\varnothing\) a fraction \(p_{\text{uncond}}\) of the time (0.1–0.2 worked equally well in the paper; 0.5 was worse; Stable Diffusion v1.3+ dropped the text 10% of the time). At sampling time, combine the two predictions:
\(s = 1\) is plain conditional sampling; \(s = 0\) is unconditional; \(s > 1\) extrapolates past the
conditional prediction in the direction "what the prompt changes". (Ho and Salimans write
\((1+w)\epsilon_c - w\epsilon_\varnothing\), so their \(w = s-1\); libraries such as diffusers expose
\(s\) as guidance_scale, defaulting to 7.5 for SD 1.x, 5.0 for SDXL and 7.0 for SD3.)
Worked example: one guided step, by hand
Take a single latent coordinate. The unconditional model predicts noise \(\epsilon_\varnothing = 0.20\), the conditional model \(\epsilon_c = 0.50\). With \(s = 7.5\): \(\tilde\epsilon = 0.20 + 7.5\times0.30 = 2.45\). The prompt's effect (+0.30) has been amplified 7.5 times. If \(\alpha_t = 0.6\), \(\sigma_t = 0.8\) and \(z_t = 1.0\), the implied clean latent is \(\hat z_0 = (z_t - \sigma_t\tilde\epsilon)/\alpha_t = (1 - 1.96)/0.6 = -1.60\), against \((1 - 0.40)/0.6 = 1.00\) without guidance. In a unit-variance latent, \(-1.6\) is already an unusual value; at \(s = 15\) it would be \(-4.6\). Multiply that across thousands of coordinates and you get the over-saturated "burnt" look of over-guided images.
What guidance does to the samples, and how people tame it¶
Guidance has three effects, which you can see in the toy experiment under Build it:
- Higher prompt adherence. In Ho and Salimans' ImageNet experiments, Inception Score (which rewards confidently classifiable images) rises monotonically with \(w\).
- Lower diversity. FID (which also penalises missing variety) is best at small guidance (\(w = 0.1\) or \(0.3\)) and worsens as \(w\) grows. The trade-off is the whole point.
- Overshoot. At high scales samples leave the data distribution: saturated colours, excessive contrast, cartoonish smoothness.
The fixes are all small modifications to the formula above:
- Thresholding. Imagen (Saharia et al. 2022) clips the predicted \(\hat x_0\) each step; dynamic thresholding sets \(p\) to a high percentile of \(|\hat x_0|\), and if \(p>1\) clips to \([-p, p]\) and divides by \(p\).
- Guidance rescale. Lin et al. 2023 rescale the guided prediction to the standard deviation of the conditional one and blend with factor \(\phi\approx0.7\) (they found \(\phi \in [0.5, 0.75]\) works with \(s = 7.5\)).
- Guidance interval. Kynkäänniemi et al. 2024 show that guidance is harmful at high noise (it collapses the global layout towards a few modes), mostly unnecessary at low noise, and useful only in the middle. Applying it only there improved the ImageNet-512 record FID from 1.81 to 1.40 and also saves compute.
- Autoguidance. Karras et al. 2024 replace the unconditional model with a smaller, less-trained version of the same conditional model. The extrapolation then pushes away from the weak model's characteristic errors rather than away from "any image", improving quality without the diversity loss (record ImageNet FIDs of 1.01 at 64×64 and 1.25 at 512×512).
- Negative prompts. Replace \(\varnothing\) with the embedding of text you want to avoid ("blurry, extra fingers"). The extrapolation now points from that text towards the prompt.
The cost of guidance, and getting rid of it¶
CFG doubles the work: two network evaluations per step (batched together), so 50 steps cost 100
forward passes. Guidance distillation (Meng et al. 2022)
trains a student to reproduce the guided output in one pass, with \(s\) as an input; FLUX.1 [dev]
is "trained using guidance distillation" according to its
model card, which is why it takes a
guidance number but runs one pass per step. Step-count distillation goes further: progressive
distillation (Salimans and Ho 2022) halves the steps
repeatedly; latent consistency models (Luo et al. 2023) map
any point on the trajectory straight to its end; adversarial diffusion distillation
(Sauer et al. 2023, SDXL Turbo) adds a GAN loss and reaches
1–4 steps. FLUX.1 [schnell] uses latent adversarial diffusion distillation for 1–4 steps (its
model card). See
distillation for the general idea.
Noise schedules have to match the latent and the resolution¶
Two schedule bugs are worth knowing because they explain visible artefacts.
Non-zero terminal SNR. SD 1.x's "scaled linear" schedule (\(\beta\) from 0.00085 to 0.012 over 1,000 steps) ends at \(z_T = 0.068\,z_0 + 0.998\,\epsilon\): the model never trains on pure noise, yet sampling starts from pure noise. The leaked low-frequency signal at training time means the model learns to keep the mean brightness of \(z_T\), and since pure noise has mean zero, every image comes out medium-grey on average. You cannot get a truly black or white image. Lin et al. 2023 fix it by rescaling the schedule to zero terminal SNR and switching to \(v\)-prediction.
Resolution. More pixels mean more independent noisy observations of the same content, so a given \(t\) destroys less information at 1024² than at 256². SD3 derives a timestep shift that equalises the uncertainty across resolutions (see The maths) and uses shift \(\alpha = 3\) at 1024×1024. The diffusion-noise figure below lets you feel how fast structure disappears under different schedules.
History¶
How the idea was found
Latent generative modelling predates diffusion: VQ-VAE (van den Oord et al. 2017) and VQGAN (Esser, Rombach and Ommer, 2020) trained an autoregressive transformer on discrete codes from a learned autoencoder. Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser and Björn Ommer, at LMU Munich and Heidelberg, swapped the autoregressive prior for a diffusion model and added cross-attention conditioning (December 2021). The compute bill fell enough that, with a compute donation from Stability AI and LAION's image–text data, the group trained Stable Diffusion and released the weights in August 2022. Running on a 10 GB consumer GPU, it put image generation on millions of machines and spawned the adapter ecosystem above. The same authors went on to SDXL, SD3 and, at Black Forest Labs, FLUX. Classifier-free guidance appeared first as a NeurIPS 2021 workshop paper by Jonathan Ho and Tim Salimans; every text-to-image model since has used it or a distilled version of it.
First principles¶
Why split the work at all? A generative model's job divides into two kinds of information. Perceptual detail (texture, grain) is enormous in bits but nearly free of long-range structure; any plausible fill-in will do. Semantic content (what is where) is small in bits but carries all the long-range dependencies. A likelihood model that does both at once spends its capacity in proportion to bits, i.e. mostly on texture. An autoencoder with a perceptual and adversarial loss can do the first job well with purely local computation (convolutions), once, and can be reused for every downstream model. The expensive, global, iterative model then works only on what is left. The rate–distortion argument also predicts the failure on the other side: compress too hard and you start discarding semantic information that no decoder can restore, which is exactly the LDM-32 result.
Why guidance has to exist. Maximum-likelihood training is mass-covering: the model must put probability on every image the caption could describe, including blurry, off-topic and badly framed ones from the scrape. Sampling from it faithfully reproduces that mess. There is no training-loss fix that both stays maximum likelihood and stops covering the mess, so the fix lives at sampling time: re-weight the learned distribution towards regions where the condition is more identifiable. Bayes tells us what that re-weighting is: multiply by \(p(c\mid x)^{\gamma-1}\).
Why it can be done with one network. \(\nabla\log p(c\mid x) = \nabla\log p(x\mid c) - \nabla\log p(x)\): the classifier gradient is the difference of two scores, and a diffusion model trained with condition dropout already has both. No separate classifier, no adversarial gradients through a classifier, and it works for any condition you can drop.
What it costs. You are no longer sampling the model's distribution. Changing \(s\) trades diversity and calibration for typicality. Worse, as the toy experiment below shows, CFG does not even sample the tilted distribution \(p(x)\,p(c\mid x)^\gamma\) that motivates it: the guided "score" at noise level \(t\) is \(\nabla\log\big(p_t(x)\,p_t(c\mid x)^\gamma\big)\), but noising does not commute with raising to a power: the noised version of \(p\,q^\gamma\) is not \(p_t\,q_t^\gamma\). The sampler follows a sequence of distributions that does not belong to any single diffusion process, and the errors compound into overshoot. Guidance-interval and autoguidance methods are attempts to keep the benefit while reducing that inconsistency.
The maths¶
The guided score. With \(\gamma = s\),
Since \(\epsilon_\theta(z_t, \cdot) \approx -\sigma_t \nabla_z \log p_t(z_t\mid\cdot)\), multiplying through by \(-\sigma_t\) gives the CFG formula \(\tilde\epsilon = (1-s)\epsilon_\varnothing + s\,\epsilon_c\), identical to the one above. The same linear combination applies to \(v\)-predictions or flow velocities, because each is an affine function of the score at fixed \((z_t, t)\).
The tilted target at \(t=0\). If the combination were exact at every noise level, the sampler would produce
For a Gaussian class \(p(z\mid c) = \mathcal N(\mu_c, s_0^2)\) and a uniform-ish \(p(z)\), this is a Gaussian with variance \(s_0^2/\gamma\): guidance at scale \(\gamma\) shrinks the class spread by \(\sqrt\gamma\). That is the "diversity loss" in its simplest form.
Cross-attention cost. For \(N\) latent positions, \(M\) text tokens and width \(d\), cross-attention costs \(O(NMd)\) and self-attention \(O(N^2 d)\). In SD 1.x at the 64×64 level, \(N = 4096\), \(M = 77\): self-attention dominates by a factor \(N/M \approx 53\). That is why U-Nets put attention only at the lower resolutions and why patchify-then-transformer designs care so much about \(f\).
Derivation: SD3's resolution-dependent timestep shift
Use the rectified-flow forward process \(z_t = (1-t)z_0 + t\epsilon\) and imagine a constant image, every one of its \(n\) latent values equal to \(c\). Each noisy value is an independent observation \(Y = (1-t)c + t\eta\) with \(\eta\sim\mathcal N(0,1)\). The best estimate of \(c\) from \(n\) of them is \(\hat c = \frac{1}{(1-t)n}\sum_i z_{t,i}\), whose standard deviation is
Demand the same uncertainty at resolution \(m\) as at resolution \(n\): \(\sigma(t_m, m) = \sigma(t_n, n)\). Writing \(\alpha = \sqrt{m/n}\),
In log-SNR terms, \(\lambda = 2\log\frac{1-t}{t}\), this is a constant shift \(\lambda_{t_m} = \lambda_{t_n} - 2\log\alpha\). Example: with \(\alpha = 3\) (SD3's choice at 1024²), the midpoint \(t_n = 0.5\) maps to \(t_m = 1.5/2 = 0.75\): the sampler spends much more of its schedule at high noise, where the global layout of a large image is decided. The same argument explains why DDPM's schedules, tuned at 32×32 to 256×256, under-noise megapixel images.
Shapes through SD 1.x for one 512×512 image, batch 2 for CFG:
| Tensor | Shape |
|---|---|
| Text tokens → CLIP text encoder | \(2\times77\to2\times77\times768\) (row 0: empty prompt, row 1: prompt) |
| Noisy latent \(z_t\) (duplicated) | \(2\times4\times64\times64\) |
| U-Net output \(\epsilon_\theta\) | \(2\times4\times64\times64\), split into \(\epsilon_\varnothing, \epsilon_c\) |
| Guided \(\tilde\epsilon\) | \(1\times4\times64\times64\) |
| Decoder output | \(1\times3\times512\times512\) |
Build it¶
You do not need a GPU to understand guidance. For a mixture of Gaussians the noised density is known in closed form, so we can compute exact conditional and unconditional scores and run a real deterministic DDIM sampler with CFG. Two classes on a line: \(p(x\mid c{=}0) = \mathcal N(-1, 0.6^2)\), \(p(x\mid c{=}1) = \mathcal N(1, 0.6^2)\), equal priors. We guide towards class 1 and compare the samples with the tilted distribution \(p(x\mid c)^{s}\,p(x)^{1-s}\) computed on a grid.
import numpy as np
# Data: two classes on a line. p(x|c) = N(mu_c, s^2), p(c) = 1/2 each.
mu, s = np.array([-1.0, 1.0]), 0.6
def alpha_sigma(t): # cosine VP schedule, t in [0, 1]
a = np.cos(0.5 * np.pi * t)
return a, np.sqrt(1 - a**2)
def eps_hat(x, t, c=None):
"""Exact noise prediction -sigma * score of the noised density p_t(x | c)."""
a, sig = alpha_sigma(t)
var = a**2 * s**2 + sig**2 # noised component variance
comps = [0, 1] if c is None else [c]
logw = np.stack([-(x - a * mu[k])**2 / (2 * var) for k in comps])
w = np.exp(logw - logw.max(0)); w /= w.sum(0) # posterior over components
score = sum(w[i] * -(x - a * mu[k]) / var for i, k in enumerate(comps))
return -sig * score
def sample(scale, n=20000, steps=200, seed=0):
rng = np.random.default_rng(seed)
ts = np.linspace(0.999, 0.0, steps + 1)
x = rng.standard_normal(n)
for t, t_next in zip(ts[:-1], ts[1:]): # deterministic DDIM (probability-flow ODE)
e_u, e_c = eps_hat(x, t), eps_hat(x, t, c=1)
e = e_u + scale * (e_c - e_u) # classifier-free guidance
a, sig = alpha_sigma(t); a2, sig2 = alpha_sigma(t_next)
x0 = (x - sig * e) / a
x = a2 * x0 + sig2 * e
return x
grid = np.linspace(-4, 5, 9001); dx = grid[1] - grid[0]
def gauss(x, m): return np.exp(-(x - m)**2 / (2 * s**2))
p_c = gauss(grid, 1.0); p_u = 0.5 * (gauss(grid, -1.0) + p_c)
print(" scale | CFG sample: mean std P(x>0) | tilted p(x|c)^g p(x)^(1-g): mean std")
for g in [0.0, 1.0, 3.0, 7.0]:
x = sample(g)
tilt = p_c**g * p_u**(1 - g); tilt /= tilt.sum() * dx
m = (grid * tilt).sum() * dx; sd = np.sqrt(((grid - m)**2 * tilt).sum() * dx)
print(f"{g:6.1f} | {x.mean():7.3f} {x.std():5.3f} {np.mean(x > 0):6.3f} |"
f" {m:7.3f} {sd:5.3f}")
Output:
scale | CFG sample: mean std P(x>0) | tilted p(x|c)^g p(x)^(1-g): mean std
0.0 | 0.004 1.159 0.498 | 0.000 1.166
1.0 | 1.002 0.593 0.955 | 1.000 0.600
3.0 | 1.630 0.374 1.000 | 1.111 0.522
7.0 | 2.243 0.304 1.000 | 1.176 0.488
Read it row by row. At \(s = 0\) and \(s = 1\) the sampler is exact: it reproduces the mixture and the class. At \(s = 3\) every sample is now on the class-1 side (adherence up), the spread has shrunk from 0.6 to 0.37 (diversity down), and the mean has moved to 1.63, well past the class mean of 1. At \(s = 7\) the mean is 2.24, more than two class standard deviations beyond where any class-1 data lives: that is the overshoot you see as saturation in images. The tilted distribution that motivates CFG would have stayed near 1.1–1.2: the sampler is not sampling it.
Things to try
- Guidance interval. Apply guidance only when \(0.2 < t < 0.8\). How do mean and spread change at \(s = 3\)? (This is Kynkäänniemi et al.'s fix in miniature.)
- Guidance rescale. After computing
e, rescale it to the standard deviation ofe_cacross the batch and blend with \(\phi = 0.7\). Does the overshoot shrink? - Negative prompt. Replace
e_uby the class-0 prediction. What happens to the mean? - Overlap. Move the class means to \(\pm0.3\). Guidance now has to separate overlapping classes; watch how the overshoot grows.
- A real one. With PyTorch and the
diffuserslibrary, load an SD pipeline and sweepguidance_scaleover 1, 3, 7.5, 15 with a fixed seed; then decode the same latent withpipe.vaeafter multiplying by the wrong scale factor and see what the 0.18215 is for.
In practice¶
- Defaults. SD 1.x: 25–50 steps, \(s\) 7–8. SDXL: 25–40 steps, \(s\) 5–7. SD3: 28 steps, \(s\) 7 (the diffusers defaults). Guidance-distilled models (FLUX.1 [dev]) take a guidance value as an input instead, with one pass per step; step-distilled models (Turbo, LCM, [schnell]) want 1–8 steps and little or no guidance.
- The text encoder is often the bottleneck. SD3 trained with three text encoders and dropped each independently 46.3% of the time, so T5 can be removed at inference to save memory; the paper reports little loss on most prompts but worse text rendering without it. Prompt understanding scales more with the text encoder than with the denoiser (Imagen found scaling the T5 encoder mattered more than scaling the U-Net).
- Captions are data. SD3 re-captioned half of its images with a VLM (CogVLM), because scraped alt-text omits background, composition and visible text. See vision-language models.
- Preference tuning. SD3 was aligned with DPO after pre-training; see DPO and friends for the method.
- Two seeds of confusion. The same seed with a different sampler, step count or resolution gives an unrelated image; the seed only fixes \(z_T\).
Common misconceptions¶
\"The guidance scale is how much the model listens to the prompt\"
It is an extrapolation factor. Past about 10–15 on SD-family models, extra "listening" is mostly overshoot: saturation and loss of detail, not better adherence. Adherence problems (wrong counts, swapped attributes) come from the text encoder and the training captions.
\"Latent diffusion is a VAE plus diffusion, so the latent is Gaussian\"
The KL weight of about \(10^{-6}\) makes the encoder nearly deterministic; the latent is a compressed image, not a sample from \(\mathcal N(0, I)\). That is why it needs to be rescaled, and why the "VAE" in Stable Diffusion is best thought of as a perceptual codec.
\"CFG samples from p(x) p(c|x)^γ\"
That is the motivation, not the result. The toy experiment shows the sampled mean landing at 2.24 where the tilted distribution has 1.18.
Check yourself¶
Why does Stable Diffusion multiply its latents by 0.18215?
The KL-regularised autoencoder's latents have a standard deviation of about 1/0.18215 ≈ 5.5. The noise schedule assumes unit-variance data; without rescaling, noise of standard deviation 1 would barely perturb the latent until very late in the schedule, so much of the training and sampling budget would be spent at effectively high signal-to-noise ratio. The constant is the inverse of the standard deviation measured on a batch of encoded images.
SD3-style model, f = 8, 16 channels, 2×2 patches. How many image tokens at 1024×768, and what is each token's dimension before projection?
The latent is \(128\times96\times16\). Patchifying 2×2 gives \(64\times48 = 3{,}072\) tokens, each \(2\cdot2\cdot16 = 64\) values, linearly projected to the model width.
What does guidance scale s = 0 produce? s = 1? What is Ho and Salimans' w for diffusers' default 7.5?
\(s = 0\): unconditional samples. \(s = 1\): ordinary conditional samples, no guidance. \(w = s - 1 = 6.5\).
Explain, with Bayes' rule, why CFG needs no classifier.
\(\nabla\log p(c\mid x) = \nabla\log p(x\mid c) - \nabla\log p(x)\). A model trained with condition dropout estimates both scores, so the classifier gradient is the difference of two outputs of the same network.
A user complains that SD 1.5 cannot make a pure black image even when asked. Why?
The training schedule never reaches zero SNR: at \(t = T\), \(z_T = 0.068\,z_0 + 0.998\,\epsilon\). The model learns to preserve the low-frequency mean leaked through that 0.068, but at inference \(z_T\) is pure noise with mean about zero, so outputs inherit a medium mean brightness. Zero-terminal-SNR schedules with \(v\)-prediction fix it (Lin et al. 2023).
Why is guidance harmful at the highest noise levels?
At high noise the denoiser is deciding the global layout. The extrapolation there pushes all trajectories towards the few layouts most typical of the prompt, collapsing variety in composition, and the over-shoot at that stage propagates through every later step. In the middle of the schedule guidance mainly sharpens features that are already decided, which is where it helps (Kynkäänniemi et al. 2024).
Hard: in the toy experiment, the CFG sample mean at s = 7 is 2.24 but the tilted target's mean is 1.18. Where does the extra push come from?
At high noise, \(p_t(c\mid x)\) is nearly flat, so the conditional and unconditional scores differ by a small, nearly constant vector pointing towards class 1. Multiplying it by 7 moves the whole trajectory early; later steps then see an \(x_t\) that is already far on the class-1 side, where the conditional and unconditional scores differ again in the same direction. The pushes accumulate along the trajectory. The tilted target, by contrast, re-weights only the final density; its mean is bounded by where class-1 data has mass. The two differ because noising does not commute with exponentiating a density.
Hard: why did SDXL need micro-conditioning on crop coordinates?
Training on random crops of larger images teaches the model that partly cropped objects are normal. Conditioning on the crop offset lets the model learn what cropping looks like as a function of an input; at inference you pass offset (0, 0) and get centred, uncropped compositions. It is a general trick: turn a nuisance variable of the data pipeline into a condition, then set it to the value you want.
Go deeper¶
Papers
- High-Resolution Image Synthesis with Latent Diffusion Models — Rombach, Blattmann, Lorenz, Esser and Ommer, 2021. Read Figure 2 (perceptual vs semantic compression), Section 4.1 (the f sweep) and Appendix G (the autoencoder and the rescaling).
- Classifier-Free Diffusion Guidance — Ho and Salimans, 2022. Eight pages; Section 3.2 and Algorithm 2 are the whole method.
- Diffusion Models Beat GANs on Image Synthesis — Dhariwal and Nichol, 2021. Classifier guidance, Section 4.
- Photorealistic Text-to-Image Diffusion Models with Deep Language Understanding — Saharia et al., 2022 (Imagen). Text-encoder scaling and dynamic thresholding.
- SDXL — Podell et al., 2023. Micro-conditioning, Section 2.2.
- Scalable Diffusion Models with Transformers — Peebles and Xie, 2022. DiT and adaLN-Zero.
- Scaling Rectified Flow Transformers for High-Resolution Image Synthesis — Esser et al., 2024 (SD3). MM-DiT, 16-channel latents, the timestep-shift derivation.
- Adding Conditional Control to Text-to-Image Diffusion Models — Zhang, Rao and Agrawala, 2023 (ControlNet).
- Common Diffusion Noise Schedules and Sample Steps are Flawed — Lin et al., 2023. Zero terminal SNR and guidance rescale.
- Applying Guidance in a Limited Interval — Kynkäänniemi et al., 2024; and Guiding a Diffusion Model with a Bad Version of Itself — Karras et al., 2024. The two best recent papers on what guidance really does.
Videos and lectures
- But how do AI images and videos actually work? — Welch Labs, on 3Blue1Brown, 2025. Diffusion, CLIP and guidance, visualised.
- MIT 6.S184 Lecture 3B: Classifier-free guidance and Lecture 4: Latent spaces — Peter Holderrieth, 2026.
- Coding Stable Diffusion from scratch in PyTorch — Umar Jamil. Every block of SD 1.x, typed out.
Articles and blog posts
- Guidance: a cheat code for diffusion models and The geometry of diffusion guidance — Sander Dieleman. The clearest writing on why guidance works and what it distorts.
- Generative modelling in latent space — Sander Dieleman, 2025. Why two-stage models won, and how to think about latent design.
- The Illustrated Stable Diffusion — Jay Alammar. The component diagram to keep in your head.
Courses and books
- MIT 6.S184: Introduction to Flow Matching and Diffusion Models — Holderrieth et al. Notes, labs, and a latent diffusion model built from scratch.
- Hugging Face Diffusion Models Course — Hands-on with diffusers, including guidance and fine-tuning.
Code
- CompVis/latent-diffusion — The original implementation.
- huggingface/diffusers — Read
pipeline_stable_diffusion.py: the CFG lines andrescale_noise_cfgare a dozen lines. - black-forest-labs/flux — A compact reference for a modern rectified-flow transformer and its autoencoder.
Where this leads¶
- Vision transformers and CLIP — where the text encoders and the DiT's patch tokens come from.
- Video and world models — the same recipe with a spatio-temporal autoencoder and a much bigger transformer.
- Score matching and flow matching — the velocity-prediction view that SD3 and FLUX train with.
- Vision-language models — the models that now write the captions these generators are trained on.
- Parameter-efficient fine-tuning — how people actually personalise these models.