◆ AI All-in-One

Level 3 In-Depth AI · Generative AI

Latent Diffusion and Stable Diffusion

Latent diffusion runs the diffusion process on a small compressed version of an image instead of on raw pixels, which makes it dozens of times cheaper. A text encoder and cross-attention let a prompt steer the result, and classifier-free guidance makes the model follow the prompt closely. Together these ideas are Stable Diffusion.

Level
●●●●● Intermediate
Reading
14 min
To learn it well
1 hour to read, an hour to practise
↗ Plan a path here

Read first

Diffusion ModelsVariational AutoencodersCLIP and Contrastive Learning

This leads to

Text-to-Image in Practice
The full path from zero — 43 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Probability Distributions
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Supervised, Unsupervised and Reinforcement Learning
  12. Gradient Descent
  13. Entropy, Cross-Entropy and KL Divergence
  14. Tensors and Shapes
  15. Supervised Learning
  16. Images as Data
  17. Linear Regression
  18. The Perceptron
  19. Logistic Regression
  20. Neural Networks
  21. Convolutional Neural Networks
  22. Recurrent Neural Networks
  23. Backpropagation
  24. Activation Functions
  25. Word Embeddings
  26. What Generative Models Do
  27. Autoencoders
  28. Vanishing and Exploding Gradients
  29. Normalization Layers: BatchNorm and LayerNorm
  30. Image Classification
  31. Diffusion Models
  32. Variational Autoencoders
  33. LSTMs and GRUs
  34. Residual Connections
  35. Sequence-to-Sequence Models
  36. Attention
  37. Self-Attention and Multi-Head Attention
  38. Positional Encodings
  39. The Transformer
  40. BERT and Encoder Models
  41. Vision Transformers
  42. Sentence Embeddings
  43. CLIP and Contrastive Learning
  44. Latent Diffusion and Stable Diffusion

Read them roughly in this order. See it on the concept map →

Why it matters

The Diffusion Models chapter showed how to generate data by removing noise step by step. Applied directly to pixels, that is very expensive. A 512×512 colour image has 786,432 numbers, and the denoiser must process all of them at every one of dozens of steps, for every image, during both training and generation. The first high-quality diffusion models needed hundreds of GPU-days to train.

Latent diffusion (Rombach and colleagues, 2021) made the approach affordable with one idea: don't diffuse pixels; diffuse a compressed code. An autoencoder first squeezes each image into a much smaller "latent" grid, the diffusion model learns to generate those grids, and the autoencoder's decoder turns the result back into pixels. Add a text encoder so that a prompt can steer the result, and you have Stable Diffusion, released openly in August 2022. It ran on a gaming GPU, could be downloaded by anyone, and started an explosion of open image tools.

Almost every image and video generator since follows this recipe: compress, generate in the latent space, decode. The denoiser changed from a U-Net to a Transformer (Diffusion Transformers), the training objective often changed to Normalizing Flows and Flow Matching, and the text encoders grew. The skeleton described here is still the standard one as of late 2026.

The intuition

Think of how an architect works. They don't design a building by deciding the position of every brick. They work on a floor plan at a much coarser level ("kitchen here, window there"), and a builder who knows how kitchens and windows are built turns the plan into bricks.

Latent diffusion splits image generation the same way:

  1. The builder: a VAE. Trained once, separately, to compress a 512×512×3 image into a 64×64×4 latent and to reconstruct the image from it almost perfectly. The latent keeps what is where (shapes, colours, layout, textures) and drops the pixel-level redundancy the decoder can fill back in.
  2. The architect: a diffusion model in latent space. It learns to generate 64×64×4 latents, 48 times fewer numbers than the pixels. All the expensive steps happen here.
  3. The client's brief: the text prompt. A pretrained text encoder turns the prompt into a list of vectors. The denoiser looks at those vectors at every step through cross-attention, so the words shape what emerges.

A final trick, classifier-free guidance, turns up how strongly the model follows the brief.

“a red fox in snow” prompt, split into tokens Text encoder CLIP, frozen 77 × 768 vectors one per token Latent space 64 × 64 × 4 numbers z_T pure noise U-Net denoiser ε_θ(z_t, t, text) ResNet blocks + time step t self-attention: image ↔ image cross-attention Q from image; K, V from text applied 20–50 times, removing noise each time z_0 clean latent VAE decoder Image 512 × 512 × 3 Training (once, on a huge set of image–caption pairs) image → VAE encoder z_0 + noise → z_t U-Net predicts noise loss ‖ε − ε̂‖² The VAE (8× smaller per side) and text encoder are trained separately and frozen; only the U-Net learns here.
Fig. 1 Stable Diffusion's architecture. A frozen text encoder turns the prompt into one vector per token. Generation happens entirely in the 64×64×4 latent space: start from noise and apply the U-Net denoiser 20 to 50 times. Its cross-attention layers let each image position look up the relevant words. A VAE decoder turns the final latent into a 512×512 image. During training, real images are encoded to latents, noised, and the U-Net learns to predict the noise.

Key idea Latent diffusion = VAE (compress the image 8× per side) + diffusion in the small latent space + text conditioning through cross-attention + classifier-free guidance to follow the prompt more closely. This is the recipe behind Stable Diffusion and most later image and video generators.

How it works

1. The autoencoder: perceptual compression

Stable Diffusion's autoencoder maps an image x\mathbf{x} of size 512×512×3512 \times 512 \times 3 to a latent z=E(x)\mathbf{z} = \mathcal{E}(\mathbf{x}) of size 64×64×464 \times 64 \times 4, and back with a decoder D\mathcal{D}, so D(E(x))≈x\mathcal{D}(\mathcal{E}(\mathbf{x})) \approx \mathbf{x}. Each side shrinks by a factor of f=8f = 8. Each latent "pixel" summarises an 8×8 patch with 4 numbers instead of 192.

It is a convolutional Variational Autoencoders with a very small KL penalty. The KL term only keeps the latents well-behaved, not close to a perfect Gaussian. Reconstruction is trained with a perceptual loss (compare features of a pretrained network, not raw pixels) and an adversarial loss (a GAN-style discriminator), so decoded images are sharp rather than blurry. The authors call this perceptual compression: the autoencoder removes detail the eye doesn't care about. The diffusion model then handles semantic content, what the picture shows.

Why not compress further? The paper compared factors from 1 (pixels) to 32. At f=4f = 4 to 88 quality stayed high and training became far cheaper. At f=32f = 32 the decoder lost too much detail. Since 64×64=4,09664 \times 64 = 4{,}096 latent positions replace 512×512=262,144512 \times 512 = 262{,}144 pixel positions, and attention costs grow with the square of the number of positions, the saving inside attention layers is far larger than 48×.

The latents are multiplied by a constant (0.18215 for Stable Diffusion 1.x) so that their spread is about 1, as the diffusion noise schedule expects.

2. Diffusion in latent space

The diffusion part is exactly the DDPM of the last chapter with x\mathbf{x} replaced by z\mathbf{z}:

L=∥ϵ−ϵθ(zt,t,τ(y))∥2,zt=αˉt E(x)+1−αˉt ϵL = \big\lVert \boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\mathbf{z}_t, t, \tau(y)) \big\rVert^2, \qquad \mathbf{z}_t = \sqrt{\bar\alpha_t}\,\mathcal{E}(\mathbf{x}) + \sqrt{1-\bar\alpha_t}\,\boldsymbol\epsilon
  • E(x)\mathcal{E}(\mathbf{x}) is the clean latent of a training image.
  • yy is that image's caption, and τ(y)\tau(y) is the text encoder's output for it. Its symbol is the Greek letter tau.
  • ϵθ\boldsymbol{\epsilon}_\theta is the denoiser, a U-Net of about 860 million parameters in Stable Diffusion 1.x, which now also receives the text.

To generate: sample zT∼N(0,I)\mathbf{z}_T \sim \mathcal{N}(\mathbf{0}, \mathbf{I}) of shape 64×64×464 \times 64 \times 4, run a sampler (DDIM, Euler, DPM-Solver and so on, typically 20–50 steps), and decode once: x^=D(z0)\hat{\mathbf{x}} = \mathcal{D}(\mathbf{z}_0).

3. Text conditioning with cross-attention

The text encoder is a pretrained, frozen Transformer. Stable Diffusion 1.x uses the text half of CLIP ViT-L/14 (about 123 million parameters). The prompt is cut into at most 77 tokens, and the encoder outputs a 768-number vector for each, a 77×76877 \times 768 matrix of context-aware word meanings. Because CLIP was trained to match images with captions, its text vectors already carry visual meaning.

The U-Net uses these through cross-attention layers placed after its convolution blocks. In Self-Attention and Multi-Head Attention, a sequence attends to itself. In cross-attention, the queries come from one source and the keys and values from another:

Attention(Q,K,V)=softmax⁡ ⁣(QK⊤d)V,Q=WQ himage,    K=WK τ(y),    V=WV τ(y)\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \operatorname{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}}\right)\mathbf{V}, \quad \mathbf{Q} = \mathbf{W}_Q\, \mathbf{h}_{\text{image}}, \;\; \mathbf{K} = \mathbf{W}_K\, \tau(y), \;\; \mathbf{V} = \mathbf{W}_V\, \tau(y)
  • himage\mathbf{h}_{\text{image}} is the U-Net's internal feature map, one vector per spatial position (for example 4,096 positions at 64×64).
  • τ(y)\tau(y) is the 77×76877 \times 768 text matrix.
  • WQ,WK,WV\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V are learned projection matrices, and dd is the vector size after projection.
  • QK⊤\mathbf{Q}\mathbf{K}^\top has one row per image position and one column per token: here a 4,096×774{,}096 \times 77 table of how relevant each word is to each spot in the picture. The softmax turns each row into weights that add to 1, and multiplying by V\mathbf{V} blends the word vectors accordingly.

In plain words: every position in the image asks "which words are about me?" and pulls in their meaning. A patch in the sky region attends mostly to "snow" or "sky". A patch where a head is forming attends to "fox". Researchers have used exactly these attention maps to edit images by changing words (the "prompt-to-prompt" method).

The same mechanism accepts any sequence of vectors, which is why the paper also conditioned on class labels, layouts and low-resolution images.

4. Classifier-free guidance

A conditional model trained this way follows the prompt only loosely. Its samples are diverse but often only vaguely match the text. Classifier-free guidance (CFG; Ho and Salimans, 2022) fixes this with a simple trick.

Training: randomly replace the caption with an empty prompt some of the time (10% for Stable Diffusion). One network then learns two things: denoising with a prompt and denoising without one.

Sampling: at every step, run the denoiser twice, once with the prompt and once with the empty prompt, and extrapolate from the unconditional prediction past the conditional one:

ϵ^=ϵθ(zt,t,∅)+w (ϵθ(zt,t,y)−ϵθ(zt,t,∅))\hat{\boldsymbol\epsilon} = \boldsymbol\epsilon_\theta(\mathbf{z}_t, t, \varnothing) + w \,\big(\boldsymbol\epsilon_\theta(\mathbf{z}_t, t, y) - \boldsymbol\epsilon_\theta(\mathbf{z}_t, t, \varnothing)\big)
  • ∅\varnothing is the empty prompt.
  • The difference in brackets is "what the prompt changes", the direction that makes the image more like the text.
  • ww is the guidance scale. w=0w = 0 ignores the prompt, w=1w = 1 is the plain conditional model, and w>1w > 1 exaggerates the prompt's effect. Stable Diffusion's default is 7.5.

The same formula works with velocities in Normalizing Flows and Flow Matching models. The cost is two network passes per step, usually batched together.

The code below trains a tiny conditional flow-matching model on the two-moons data, where the "prompt" is just "upper moon" or "lower moon", and samples with different guidance scales:

w = 0unconditional53% · 88% · 0.97 w = 1plain conditional100% · 99% · 0.69 w = 3tighter, more typical100% · 100% · 0.47 w = 7overshoots the data100% · 81% · 0.32 Under each panel (2,000 samples): % on the requested lower moon · % within 0.1 of real data · spreadgrey: training data for both moons; green: samples asked for "lower moon" with guidance scale w
Fig. 2 Classifier-free guidance on 2-D data, from the code below. Each panel asks for the lower moon (green) at a different guidance scale w. At w = 0 the prompt is ignored and samples cover both moons. At w = 1 they follow the prompt. At w = 3 they crowd into the most typical part of the moon and lose spread. At w = 7 they overshoot and fall off the data. Real text-to-image models show the same trade-off: higher guidance means closer prompt following, less variety and, eventually, oversaturated, distorted images.
Guidance ww On the requested moon Within 0.1 of real data Spread (std)
0 53% 88% 0.97
1 100% 99% 0.69
3 100% 100% 0.47
7 100% 81% 0.32

Guidance trades diversity for fidelity to the condition. Moderate values (around 3–8 for most U-Net image models) make outputs match prompts much better. Very high values give harsh colours, over-sharpened edges and repetitive compositions, the image equivalent of the overshoot at w=7w = 7. Distilled and flow-matching models often use lower values, so check the model card. See Text-to-Image in Practice for practical settings.

Before CFG there was classifier guidance (Dhariwal and Nichol, 2021), which steered sampling with the gradients of a separately trained, noise-aware image classifier. CFG removes the need for that extra classifier, hence the name.

Stable Diffusion's versions in brief

Model Year Denoiser Text encoder(s) Native size
SD 1.x 2022 U-Net, ~860M CLIP ViT-L/14 512×512
SD 2.x 2022 U-Net, ~865M OpenCLIP ViT-H 768×768
SDXL 2023 U-Net, ~2.6B CLIP ViT-L + OpenCLIP ViT-bigG 1024×1024
SD 3 2024 MM-DiT Transformer, rectified flow two CLIPs + T5-XXL 1024×1024

Other model families, such as FLUX, Imagen and DALL·E 3, differ in components and training data but share the latent-plus-conditioning design. Imagen is an exception: it diffuses in pixel space with a cascade of upsamplers. Its paper found that a larger text encoder (T5-XXL) improved results more than a larger image model did.

In code

A conditional flow-matching model with classifier-free guidance, in PyTorch. It is the latent-diffusion recipe in miniature, minus the autoencoder: a label instead of a prompt, label dropout during training, and guided sampling. It runs in about 15 seconds on a CPU.

import torch, torch.nn as nn, torch.nn.functional as F
from sklearn.datasets import make_moons

torch.manual_seed(0)
Xnp, ynp = make_moons(10_000, noise=0.03, random_state=0)
X = torch.tensor(Xnp, dtype=torch.float32); X = (X - X.mean(0)) / X.std(0)
y = torch.tensor(ynp)                                   # 0 = upper moon, 1 = lower moon
NULL = 2                                                # extra "no condition" label

net = nn.Sequential(nn.Linear(2 + 1 + 3, 128), nn.SiLU(), nn.Linear(128, 128), nn.SiLU(),
                    nn.Linear(128, 128), nn.SiLU(), nn.Linear(128, 2))
def v(x, t, label):                                     # velocity, conditioned on a label
    return net(torch.cat([x, t, F.one_hot(label, 3).float()], 1))

opt = torch.optim.Adam(net.parameters(), lr=1e-3)
for step in range(6000):                                # flow matching with label dropout
    i = torch.randint(0, len(X), (512,))
    x1, label = X[i], y[i].clone()
    label[torch.rand(512) < 0.2] = NULL                 # 20% of the time: hide the label
    x0, t = torch.randn_like(x1), torch.rand(512, 1)
    loss = ((v((1 - t) * x0 + t * x1, t, label) - (x1 - x0)) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()

def sample(label, w, n=2000, steps=50):                 # classifier-free guidance
    x, c, u = torch.randn(n, 2), torch.full((n,), label), torch.full((n,), NULL)
    with torch.no_grad():
        for k in range(steps):
            t = torch.full((n, 1), k / steps)
            v_c, v_u = v(x, t, c), v(x, t, u)
            x = x + (v_u + w * (v_c - v_u)) / steps     # w = guidance scale
    return x

for w in [0.0, 1.0, 3.0, 7.0]:
    s = sample(label=1, w=w)                            # ask for the lower moon
    nearest = torch.cdist(s, X).min(1).indices
    d = torch.cdist(s, X).min(1).values
    print(f"w={w:3.1f}  on lower moon {(y[nearest] == 1).float().mean():.0%}  "
          f"within 0.1 of data {(d < 0.1).float().mean():.0%}  spread (std) {s.std(0).mean():.2f}")

# w=0.0  on lower moon 53%  within 0.1 of data 88%  spread (std) 0.97
# w=1.0  on lower moon 100%  within 0.1 of data 99%  spread (std) 0.69
# w=3.0  on lower moon 100%  within 0.1 of data 100%  spread (std) 0.47
# w=7.0  on lower moon 100%  within 0.1 of data 81%  spread (std) 0.32

With the real Stable Diffusion, the Hugging Face diffusers library exposes every part of the architecture above. This needs a download of a few gigabytes and, realistically, a GPU, so it is not run here:

import torch
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
).to("cuda")

print(type(pipe.text_encoder).__name__, type(pipe.unet).__name__, type(pipe.vae).__name__)
# CLIPTextModel UNet2DConditionModel AutoencoderKL
print(pipe.vae.config.scaling_factor)        # 0.18215

image = pipe("a red fox in snow, telephoto photograph",
             num_inference_steps=30,          # sampler steps in latent space
             guidance_scale=7.5).images[0]    # classifier-free guidance w
image.save("fox.png")

Common pitfalls

  • Expecting fine detail the VAE can't carry. Small text, faces far away, fingers and fine patterns pass through an 8×-per-side bottleneck. Some errors come from the decoder, not the diffusion model. Newer VAEs with more latent channels (16 in SD3 and FLUX) help.
  • Mismatched VAE and latent scaling. Each model family has its own VAE and scaling factor. Decoding SDXL latents with an SD 1.5 VAE, or forgetting the scaling factor, gives washed-out or noisy images.
  • Guidance set too high. Above about 10–12 on SD 1.x models, images become oversaturated and distorted. Higher is not "more accurate".
  • Prompts past the token limit. CLIP's encoder sees at most 77 tokens. Words beyond that are silently cut unless the tool handles long prompts specially.
  • Generating far from the native resolution. A model trained at 512×512 asked for 1024×1024 often repeats subjects (two heads, duplicated objects), because it has never seen a whole composition at that size.

Watch out Open latent diffusion models were trained on billions of images scraped from the web, including copyrighted works and photos of real people. The legal status of that training and of the outputs is still being decided in courts in several countries (as of late 2026). See Text-to-Image in Practice for practical rights and disclosure guidance and Privacy, Data and Copyright for the wider debate.

Where it leads

A bit of history

Robin Rombach, Andreas Blattmann, Dominik Lorenz, Patrick Esser and Björn Ommer (LMU Munich and Heidelberg University) posted High-Resolution Image Synthesis with Latent Diffusion Models in December 2021. It was presented at CVPR 2022. Esser and Rombach had earlier worked on VQGAN (2020), which pioneered generating in a learned compressed space. Ho and Salimans introduced classifier-free guidance at a NeurIPS 2021 workshop, and the full paper followed in 2022.

In August 2022 Stability AI, with CompVis and Runway, released Stable Diffusion 1.4, trained on a subset of the LAION-5B image–text dataset. Unlike DALL·E 2 and Imagen, the weights were public. Within months people had built inpainting tools, fine-tuning methods (DreamBooth, LoRA), ControlNet, and thousands of community models. SDXL followed in 2023, and SD3, built on a diffusion Transformer and rectified flow, in 2024. Several of the original authors went on to found Black Forest Labs, which released the FLUX.1 models in August 2024.

Try it

  1. In the code, change the label-dropout rate from 0.2 to 0.0 (never hide the label) and retrain. What happens when you sample with w=3w = 3, and why? (What does the model now output for NULL?)
  2. Try w=1.5w = 1.5 and w=5w = 5. Plot "spread" against ww. Where would you set the guidance scale for this "model", and why?
  3. Work out the size of the attention table QK⊤\mathbf{Q}\mathbf{K}^\top at a 32×32 U-Net level and at the 64×64 level, for self-attention (image to image) and for cross-attention (image to 77 tokens). Which is more expensive, and by how much?

Hint for 3: self-attention at 64×64 compares 4,096 positions with 4,096 positions.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Stable Diffusion runs diffusion on a 64×64×4 latent instead of a 512×512×3 image. Roughly how many times fewer numbers is that?

  2. In classifier-free guidance, what does a guidance scale of w = 1 give you?

  3. Your SD 1.x images come out oversaturated and distorted, with harsh colours. Which setting is the most likely cause?

  4. You write a very long, detailed prompt for Stable Diffusion 1.5 and the last part of it seems to have no effect. Why?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

The Illustrated Stable Diffusion

Jay Alammar · 2022 · Beginner · Free

A picture-led walk through Stable Diffusion's text encoder, U-Net denoiser and image decoder.

Tutorial

Stable Diffusion with Diffusers

Hugging Face · 2022 · Intermediate · Free

How Stable Diffusion works and how to run it, and write your own denoising loop, with the diffusers library.

Paper

Classifier-Free Diffusion Guidance

Ho & Salimans · 2022 · Advanced · Free

Train one model with and without the condition and extrapolate between the two: the guidance used by nearly every text-to-image model.

Interactive

Diffusion Explainer

Georgia Tech Polo Club · Beginner · Free

An interactive visual walk through how Stable Diffusion turns a prompt into an image, including the effect of the guidance scale.

Course

Hugging Face Diffusion Models Course

Hugging Face · Intermediate · Free

Theory and hands-on notebooks for training and using diffusion models with the diffusers library.

Article

Sander Dieleman's blog

Sander Dieleman · Advanced · Free

Deep, intuitive essays on diffusion by a Google DeepMind researcher: guidance, noise schedules, perspectives on diffusion, and diffusion vs autoregression.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/latent-diffusion.md