30 / 34 · Diffusion Models
Latent diffusion and Stable Diffusion
Run diffusion in the latent space of an autoencoder instead of on pixels, condition it on text, steer it with classifier and classifier-free guidance, sample it in tens of steps, and edit images with the same model.
On this page 9
A diffusion model is a VAE with a fixed encoder: the noising chain plays the encoder, and the many-step denoiser is the decoder (VAE note). It generates sharp and diverse images, and it is slow. Every step runs a network over every pixel, and a colour image has of them. Most of that work goes into detail nobody looks at, such as the exact grain of grass or the noise of a camera sensor.
Latent diffusion (Rombach et al., 2022) trains the diffusion model in the latent space of an autoencoder instead. In Stable Diffusion the latent of that image is , which is numbers, 48 times fewer. The latent is also kept close to a simple distribution by the autoencoder’s own training, which may make it easier for diffusion to model (Конспект курса «Байесовские методы в анализе данных», 2026, лекция 6). Stable Diffusion is this design with a text encoder attached; the sizes in this note are those of its versions 1.x and 2.x.
Two kinds of compression#
A trained image model compresses in two senses. Perceptual compression throws away high-frequency detail that changes many bits of an image and almost nothing that a person perceives. Semantic compression keeps the layout and content: which objects, where, in what style. A likelihood-based model in pixel space is charged for every bit, and Rombach et al. find that most of those bits belong to the perceptual part. Latent diffusion gives each part to a model suited to it: an autoencoder for the first, a diffusion model for the second.
The savings are larger still for attention. Self-attention over the latent grid compares pairs of positions; over the pixels it would compare , 4096 times more. Pixel-space diffusion models therefore attend only at coarse resolutions. Even in the latent, one attention map of entries takes 67 MB in 32-bit floats, per head and per image, which is why libraries offer to compute attention in slices at some cost in speed.
The autoencoder#
The first stage is trained once and then frozen. Its loss has three parts. A reconstruction term compares the output with the image. A perceptual loss compares deep features of the two, as LPIPS does. A patch-based adversarial loss has a discriminator judge small patches, so that reconstructions stay sharp instead of averaging into blur.
The latent is kept near a simple distribution in one of two ways: a slight KL penalty toward , as in a VAE with a very small weight on the KL term, or a vector-quantization layer, as in VQ-VAE. Unlike a VAE used as a generator, this autoencoder is not asked to make good samples from its prior: the diffusion model is the prior. Because the KL penalty is weak, the latents do not have unit variance, and Stable Diffusion multiplies them by a fixed constant so that diffusion starts from data of roughly unit variance.
The downsampling factor , the ratio of image side to latent side, sets the split between the two models. With the diffusion model still does all the perceptual work and trains slowly; with the autoencoder loses information that the decoder cannot restore. Rombach et al. find between 4 and 16 a good balance, and and best.
Diffusion in the latent#
Write for the encoder, for the decoder, for the latent of an image , and for the encoded condition , such as a prompt. Training is the DDPM objective with in place of :
Generation draws , runs a sampler in the latent space and decodes once at the end, . The network is a U-Net, convolutional, with attention layers at the lower resolutions.
Latent diffusion: Stable Diffusion at 512×512
Conditioning through cross-attention#
The condition enters through cross-attention (if you have taken the NLP course, its attention note is background; the formula below is all this note uses): the queries come from the U-Net features of the latent, flattened over positions, and the keys and values from the encoded condition:
Every position of the latent attends over the tokens of the prompt, so different regions can follow different words. In Stable Diffusion is a frozen text encoder that turns a prompt into 77 token vectors: CLIP ViT-L/14 with 768 dimensions in versions 1.x, OpenCLIP ViT-H/14 with 1024 in versions 2.x. The same mechanism accepts other conditions, such as class labels, segmentation maps or low-resolution images.
Since every token reaches the U-Net as its own vector, a word can be emphasised or toned down after encoding, without retraining. A common rule moves the token’s vector away from, or toward, the vector at the same position for an empty prompt, , with to boost the word. The change acts through cross-attention: the key decides how much the latent attends to the token, the value what it reads from it.
Classifier guidance#
A conditional model sampled as it is follows its condition only loosely. Suppose we have an unconditional diffusion model and want class . Bayes’ rule at noise level gives . Take the logarithm and the gradient in ; the term does not depend on and drops out:
The conditional score is the unconditional one plus the gradient of a classifier that sees the noisy input. Classifier guidance (Dhariwal and Nichol, 2021) trains such a classifier on noised data and adds its gradient, multiplied by a scale , to the score at every sampling step. Through the noise–score relation , the guided noise prediction is
Why scale? Dhariwal and Nichol found that with the classifier gave the final samples reasonable probabilities, about 50%, yet the images did not look like the class; larger scales fixed this (§4.3). A scale is an exponent: , and , renormalized over classes, is a sharper classifier. Guidance with follows the score of and favours inputs the classifier is very sure of: higher fidelity, less diversity. The cost is a second network, trained on noisy inputs at every noise level, and following its gradient can be read as an adversarial attack on it, so better classifier-based scores need not mean better images (Ho and Salimans, 2022, §1).
Classifier-free guidance#
Classifier-free guidance (Ho and Salimans, 2022) gets the classifier from the diffusion model itself. Bayes’ rule read the other way gives an implicit classifier, . Substitute it into the guided score:
Both scores come from one network. During training the condition is replaced by an empty one, , in a fraction of the steps, 10 or 20% in the paper (50% worked worse), so the network learns and together. Multiplying the guided score by gives the guided noise prediction:
is unconditional, the plain conditional model, and extrapolates beyond it; Ho and Salimans write . Stable Diffusion 1.x and 2.x are usually sampled with . Each step costs two network evaluations, one with the prompt and one without.
A score at each noise level, not a target distribution. The identity holds separately at every step: the guided prediction is the score of . For and the family is the noising of one distribution. For other it is in general not the noising of any single distribution, so a sampler driven by the guided score need not end at , and the stochastic DDPM sampler and the deterministic DDIM sampler can end at different distributions with the same network (Bradley and Nakkiran, 2024). What the identity fixes is the direction of each step: toward regions that the implicit classifier at that noise level favours.
Worked example. Take the toy pair and . The tilted density is Gaussian with precision , the sum of the weighted precisions, and mean divided by that precision:
| tilted density: mean, sd | 2.40, 0.63 | 2.55, 0.41 |
| stochastic sampler: mean, sd | 2.62, 0.52 | 2.67, 0.31 |
| deterministic sampler: mean, sd | 2.99, 0.25 | 2.88, 0.01 |
The samplers use the exact Gaussian scores, so no network error enters, with the continuous version of DDPM’s linear schedule ( from to , time from for data to for noise) and a start at . Each is Gaussian, and the clean distribution it would be the noising of has mean at the last step but at for : no single target exists. The samplers agree with the tilted density in direction and go further. Guidance narrows the distribution and pushes it past the conditional mean, away from the unconditional one: samples more typical of the prompt and less diverse, the precision side of the precision and recall trade-off.
At the last step the guided score points to a narrower, shifted density
Fewer steps#
DDPM samples with as many steps as it was trained with, 1000, because each step undoes one small Gaussian step. Fast samplers use a deterministic description of the same model: the probability-flow ODE, which has the same marginals as the noising process at every time. It lives in the continuous time of that note: runs over from data to noise, is the noise rate and the signal coefficient, so . DDPM’s step of sits at time , where is the limit of DDPM’s product (derived there). From here on a subscript means continuous time: and . With the score replaced by the scaled noise predictor the ODE reads
Integrating it from down to maps every noise latent to one sample, and a solver that takes large steps needs few network evaluations.
DDIM is Euler’s method in the right coordinates. Divide the latent by its signal coefficient and measure time by the noise-to-signal ratio:
so that along the noising path. Differentiate by the product rule, substitute the ODE and ; the terms in cancel:
From , differentiation gives , which is the same factor:
Dividing the two, the ODE becomes (Song, Meng and Ermon, 2021, Eq. 14). Euler’s method holds at its value at over the step to an earlier time with its smaller , so . Multiplying back by gives the DDIM update (their Eq. 12 without added noise):
Predict the clean latent, then noise it again to the level of time with the same predicted noise. The time can be any earlier time, so a 50-step schedule visits every twentieth of DDPM’s 1000 training steps, DDIM is deterministic and maps each noise latent to one image. Running its update in the other direction, from an image toward noise, gives an approximate inversion: the ideal ODE can be integrated both ways, but each Euler step evaluates at the start of the step, so the backward pass does not exactly undo the forward one.
Worked example. One-dimensional data , the exact noise predictor, DDPM’s discrete linear schedule, (DDPM’s step ) from its exact distribution and DDIM steps evenly spaced in . The samples should have standard deviation :
| DDIM steps | 1 | 10 | 50 | 1000 |
|---|---|---|---|---|
| sd of the samples | 0.002 | 0.370 | 0.471 | 0.4985 |
| the point 0.8, inverted and regenerated | 0.44 | 0.71 | 0.80 |
A single step from pure noise returns , which is close to the mean of all data, and too few first-order steps shrink the samples toward that mean. The inversion row shows that even an exact noise predictor does not make the round trip exact with few steps.
Higher-order solvers. In , half the log signal-to-noise ratio, the exact solution of the ODE is an integral of times the noise predictor (Lu et al., 2022a, Eq. 3.4). DPM-Solver expands the noise predictor in a Taylor series in over each step and integrates the exponential weight exactly. Its first-order version is DDIM; the second- and third-order versions spend two or three network evaluations per step and need far fewer steps. DPM-Solver++ (Lu et al., 2022b) applies the idea to the predicted clean latent and reuses the previous step’s evaluation, which keeps it stable at the large guidance scales of text-to-image models. Lu et al. (2022b) report that guided sampling, pixel or latent, needs about 100 to 250 steps to converge with DDIM and 15 to 20 with DPM-Solver++. The network does not change between samplers, only the update rule between its evaluations, which is why diffusion libraries let the sampler, the scheduler, be swapped after training.
Distillation. The other way to cut steps changes the network. Progressive distillation trains a student to reproduce in one DDIM step what the teacher does in two, then repeats with the student as teacher, halving the steps each round; Salimans and Ho (2022) go from thousands of steps to 4. A consistency model (Song et al., 2023) learns a function that maps any point of a probability-flow trajectory directly to the trajectory’s start at , trained so that all points of one trajectory give the same output; it samples with one network evaluation, or a few for better quality.
Editing with the same model#
Image-to-image (SDEdit, Meng et al., 2022) encodes an existing image, noises it to an intermediate step, , and runs the remaining denoising steps with a new prompt. The strength chooses the step: with 40 sampling steps and , the last 24 are run. Low strength keeps the composition; strength 1 ignores the input.
Inpainting changes only a masked region. At every step the latent outside the mask is replaced by the original latent noised to the same step, and only the masked part follows the model:
where is the mask downsampled to the latent grid, where the image may change, and is the sampler’s update. With the mask acts on pixel blocks, and the decoder blends the edge. Dedicated inpainting models instead receive the mask and the masked image as extra input channels.
LoRA fine-tunes the attention layers with low-rank updates (PEFT note) to teach a style or a subject from a few images. For a weight it trains numbers instead of : with that is of the layer for and for .
Textual inversion (Gal et al., 2023) freezes everything and learns only the embedding of a new token, such as <S*>, from three to five images of a concept. It minimizes the diffusion loss of prompts such as “a photo of <S*>” with in place of the token’s embedding (their Eq. 2); the token can then be used in any prompt.
What changed#
| Pixel-space diffusion | Latent diffusion | |
|---|---|---|
| Numbers per step at | , plus one decoder pass per image | |
| Who removes imperceptible detail | the diffusion model, slowly | the autoencoder, once |
| Attention | only at coarse resolutions | over the whole latent grid |
| Conditioning on text | possible, costly | cross-attention to a frozen text encoder |
| Ceiling on detail | the network | the decoder |
The number of steps is set by the sampler in both columns: the same DDIM, DPM-Solver or distilled samplers apply.
Where it breaks#
The decoder sets a ceiling. With and four channels, every block of pixels, numbers, is described by latent numbers. Detail smaller than a block, such as small printed text, a face a few blocks wide or an exact texture, exists in the output only if the decoder can produce it from those four numbers; the diffusion model cannot add what cannot express. The same block size limits inpainting, whose mask edges fall on the latent grid.
The text encoder sets another. A frozen CLIP-like encoder with 77 tokens is trained to match images and captions, and struggles with counting, spatial relations and long prompts; cross-attention can only use what encodes. Guidance trades diversity for adherence, and the best trade for a metric is not the strongest guidance. On class-conditional ImageNet, Ho and Salimans (2022, §4.1) get the best FID with weak guidance, to , and the best Inception score with ; Stable Diffusion’s usual is far stronger than the best-FID setting. The toy example shows the extreme: at the deterministic sampler leaves a standard deviation of , almost one image.
What you should remember#
- An autoencoder removes perceptual detail once; diffusion runs in its latent, 48 times smaller than the image in Stable Diffusion.
- Text enters through cross-attention: queries from the latent, keys and values from the text encoder.
- Classifier guidance adds to the score; classifier-free guidance gets that gradient as the conditional minus the unconditional score.
- Guided samplers follow step by step, not a fixed target; guidance narrows and shifts the samples.
- DDIM is Euler’s method for the probability-flow ODE in ; higher-order solvers and distillation cut the steps further.
Notebook#
The advanced diffusion notebook of the HSE-LAMBDA Deep Generative Models repository uses the Hugging Face Diffusers library. It has no saved outputs, so it documents the procedure only; cell numbers count every cell, markdown included, from 1.
- Text-to-image (cells 5–9) with
stabilityai/stable-diffusion-2-1-basein float32, 25 steps and guidance scale 7.5, with attention slicing to lower the peak memory. The markdown gives the text embedding as , the size for version 1.x; this 2.1 model has a 1024-dimensional encoder. - Schedulers (cells 10–12). The ODE in the markdown keeps only the noise term; the probability-flow ODE also has a term in and a factor .
swap_schedulerreplaces the scheduler of the same pipeline object and returns it, sopipe_eulerandpipe_dpmare one pipeline, and both images of the side-by-side are produced with DPM-Solver++. - Batch generation and prompt weighting with the Compel library (cells 13–16): each
+multiplies a token’s weight by 1.1 and each-by 0.9, soball--has weight andforest---, applied to the text-encoder output as described above. - Image-to-image (cells 17–20) on a picture with strength 0.6, which runs 24 of 40 steps, and 1.0.
- Inpainting (cells 21–22) with the same base checkpoint and 50 steps. Its U-Net has 4 input channels, so the pipeline uses the latent replacement above, not a mask-conditioned model.
- A pixel-art LoRA in SD-XL fused with scale 0.8 (cells 23–24). The markdown says a LoRA trains about 0.2% of SD-XL’s parameters; this adapter has rank 32 and 85.1 million parameters, about 3.3% of the 2.6-billion-parameter U-Net (Podell et al., 2023).
- Textual inversion (cells 25–26) with a concept token loaded into
runwayml/stable-diffusion-v1-5, a repository now published asstable-diffusion-v1-5/stable-diffusion-v1-5, to which the old id redirects.
Next#
Text, masks and the strength of image-to-image say what should appear and roughly where, but not exactly where a given point of the image should end up. The next note, Point-based image editing: DragGAN and DragDiffusion, makes edits of the form “move this point there”: first by optimizing the latent code of a GAN, then by optimizing the noisy latent of a diffusion model, inverted with DDIM.
References#
- R. Rombach, A. Blattmann, D. Lorenz, P. Esser, B. Ommer. High-Resolution Image Synthesis with Latent Diffusion Models. CVPR, 2022.
- Конспект курса «Байесовские методы в анализе данных», 2026, github.com/bmml-team/bmml_ftda, лекция 6 (diffusion as a VAE with a fixed encoder; latent diffusion models).
- P. Dhariwal, A. Nichol. Diffusion Models Beat GANs on Image Synthesis. NeurIPS, 2021. §4.1–4.3 (classifier guidance and its scale).
- J. Ho, T. Salimans. Classifier-Free Diffusion Guidance. NeurIPS Workshop on Deep Generative Models, 2021. §1 (the adversarial reading of classifier guidance), §4.1 (guidance strength), §4.2 (the unconditional fraction).
- A. Bradley, P. Nakkiran. Classifier-Free Guidance is a Predictor-Corrector. arXiv:2408.09000, 2024.
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. §25.5 (faster sampling, distillation, latent diffusion), §25.6 (classifier and classifier-free guidance).
- J. Song, C. Meng, S. Ermon. Denoising Diffusion Implicit Models. ICLR, 2021.
- C. Lu, Y. Zhou, F. Bao, J. Chen, C. Li, J. Zhu. DPM-Solver: A Fast ODE Solver for Diffusion Probabilistic Model Sampling in Around 10 Steps. NeurIPS, 2022 (cited as Lu et al., 2022a). Eq. 3.4 (exact solution), §4.1 (DDIM as DPM-Solver-1).
- C. Lu, Y. Zhou, F. Bao, J. Chen, C. Li, J. Zhu. DPM-Solver++: Fast Solver for Guided Sampling of Diffusion Probabilistic Models. arXiv:2211.01095, 2022 (cited as Lu et al., 2022b). §1 and §7 (step counts with guidance).
- T. Salimans, J. Ho. Progressive Distillation for Fast Sampling of Diffusion Models. ICLR, 2022.
- Y. Song, P. Dhariwal, M. Chen, I. Sutskever. Consistency Models. ICML, 2023. §3 (the consistency function and self-consistency).
- C. Meng, Y. He, Y. Song, J. Song, J. Wu, J.-Y. Zhu, S. Ermon. SDEdit: Guided Image Synthesis and Editing with Stochastic Differential Equations. ICLR, 2022.
- R. Gal, Y. Alaluf, Y. Atzmon, O. Patashnik, A. H. Bermano, G. Chechik, D. Cohen-Or. An Image is Worth One Word: Personalizing Text-to-Image Generation using Textual Inversion. ICLR, 2023.
- D. Podell, Z. English, K. Lacey, A. Blattmann, T. Dockhorn, J. Müller, J. Penna, R. Rombach. SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis. arXiv:2307.01952, 2023. §2.1 (2.6 billion parameters in the U-Net).