Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Latent Diffusion,
explained.
Diffusion models could already paint stunning images — if you owned a data center. Denoising every pixel, hundreds of times, at high resolution, was brutally expensive; the best generators lived behind closed doors. This paper found the shortcut that broke it open: don't denoise pixels at all. Shrink the image to a tiny latent sketch, do the slow work there, then decode. That single move is why image generation ended up on your laptop — and why it's called Stable Diffusion.
Contents 17 sections
The delta The pixel-space cost problem The big idea: denoise a sketch, not the pixels The VAE: a perceptual compressor Denoising in the latent space Steering it with text: cross-attention The limits Why it still matters How it works The math The evidence Where this shows up in production Since then Solve it yourself Questions Check yourself Where this sitsWhat changes against pixel diffusion: the denoising moves into a small space
Rungs 4 to 6 denoise pixels, which means every one of the sampling steps is a full network pass at the image's full resolution. That is the remaining cost, and it is what kept high-resolution diffusion inside organisations with clusters.
The change rests on an observation about where the compute was going. Most of the bits in an image are perceptually irrelevant high-frequency detail — exact texture, sensor noise, the precise placement of individual leaves — and a diffusion model denoising pixels spends the majority of its capacity and its compute modelling them. But that detail is exactly what an autoencoder reconstructs well and cheaply. So: compress the image with an autoencoder into a much smaller latent, run the entire diffusion process there, and decode once at the end. The diffusion model now spends its capacity on semantics — what is in the picture and where — and the decoder handles texture.
Stated in units, that is an order-of-magnitude reduction in the compute of both training and sampling, which is the difference between a model that a lab runs and one that runs on a consumer graphics card. The second contribution is the conditioning mechanism: text is injected by cross-attention into the denoiser, which is general — anything you can encode as a sequence can steer generation the same way, and that is why the same architecture handles text, layouts, depth maps and image prompts without redesign. Note the ladder closing a loop here: rung 1, which lost as a generator, is the component that makes the winner affordable.
The pixel-space cost problem
Diffusion models generate by starting from pure noise and denoising it step by step until an image emerges. It works beautifully — but the earlier models did this directly on pixels. A 512×512 RGB image is nearly 800,000 numbers, and the model has to process all of them at every one of dozens or hundreds of denoising steps.
The cruel part is that most of those pixels carry redundant, high-frequency detail — texture and noise the eye barely registers. The model burns enormous compute perfecting bits that don't matter perceptually. That inefficiency put high-resolution diffusion out of reach for anyone without a fleet of GPUs, keeping the best image generators locked inside big labs.
The big idea: denoise a sketch, not the pixels
The insight is to split the problem into two jobs done by two networks. First, a compressor learns to squeeze an image into a small latent representation that keeps the meaningful structure and throws away the imperceptible detail. Then the diffusion model does all its slow denoising work in that compact latent space — never touching raw pixels until the very end, when a decoder blows the finished latent back up to full resolution.
It's the difference between planning a painting as a rough thumbnail versus fussing over every brushstroke from the start. Get the composition right on the small sketch, cheaply, then render the detail once. The paper calls this a latent diffusion model — diffusion moved off the pixel grid and onto a tiny latent grid.
512×512×3
64×64×4
512×512×3
The VAE: a perceptual compressor
The compressor is an autoencoder — in the KL-regularized variant a VAE (variational autoencoder) with a tiny KL weight, in the other a vector-quantized one — trained once, separately. Its encoder maps a 512×512 image down to roughly a 64×64 latent grid — about an 8× reduction per side, so tens of times fewer numbers to work with. Its decoder does the reverse, reconstructing a full image from a latent.
Crucially, the VAE is trained with perceptual and adversarial losses so it preserves what looks right rather than matching pixels exactly. It discards precisely the imperceptible high-frequency detail that was wasting the diffusion model's time. After training, the VAE is frozen and its latent space becomes the fixed "canvas" the diffusion model paints on.
Stage one (VAE) handles perceptual compression — remove imperceptible detail. Stage two (diffusion) handles semantic generation — arrange meaningful content. Separating them is the whole efficiency trick.
Denoising in the latent space
Inside the latent space, it's ordinary diffusion. During training, a clean latent is progressively corrupted with noise; a U-Net is taught to predict and remove that noise one step at a time. At generation, you start from a random latent — pure noise — and run the U-Net repeatedly to denoise it into a coherent latent, which the VAE decoder then turns into an image.
The U-Net is the workhorse: an encoder-decoder with skip connections that's well suited to grid-shaped data. Because the grid it operates on is now tiny, each denoising step is cheap — the same number of steps as pixel diffusion, but each one a fraction of the cost. That's where the order-of-magnitude speedup comes from.
And "a fraction" is a precise fraction. A downsample factor f shrinks each side, so the number of spatial positions the U-Net processes drops by f² — and the U-Net's attention layers, being quadratic in positions, drop by f⁴:
Same denoising steps, each on a 64×-smaller canvas — the entire efficiency story, in exponents of one number.
Steering it with text: cross-attention
A generator you can't direct is a curiosity. Latent diffusion adds flexible conditioning through cross-attention. A prompt like "an astronaut riding a horse" is turned into embeddings by a text encoder, and at several layers inside the U-Net, the image latents attend to those text embeddings — asking, at every location, "which words should shape what I generate here?"
This is the same attention mechanism from Transformers, now bridging two modalities: image latents as queries, text tokens as keys and values. The general form means the same machinery can condition on text, another image, a segmentation map, or a layout — text-to-image is just the most famous case. It's how a sentence becomes a specific picture rather than a random one.
The limits
The compression is lossy. Because the VAE throws away detail, latent diffusion can fumble the finest textures and small structured detail such as text in a sign, which the decoder has to rebuild from a few latent cells. (Miscounted fingers, the other notorious failure, are usually blamed on the generative model rather than on this compression.) It's still an iterative sampler, so generation takes many steps unless sped up by later distillation methods.
And it inherits the ethics of its training data: models trained on huge web scrapes can reproduce biases, memorize and regurgitate copyrighted images, and enable convincing fakes. The very openness that made Stable Diffusion powerful also made these harms widely accessible — a tension the field is still working through.
Why it still matters
Latent diffusion is the architecture that democratized generative imagery. By moving the expensive process into a compressed space, it turned a data-center capability into an open-source download — and the resulting ecosystem (Stable Diffusion, ControlNet, LoRA fine-tunes, and countless apps) reshaped art, design, and content overnight.
The pattern generalized far beyond images: "compress with an autoencoder, then generate in the latent space, conditioned by cross-attention" now underpins state-of-the-art video and audio generators too. When a modern model makes a video from a prompt, it is very likely running diffusion in a latent space — the idea this paper made standard.
Pair this with the diffusion models breakdown (the denoising idea itself) and CLIP (the text encoder that guides many text-to-image systems). Together they're the recipe behind modern image generation.
How latent diffusion models are built and trained, step by step
Rombach, Blattmann, Lorenz, Esser and Ommer split image synthesis into two stages trained separately: perceptual compression by an autoencoder, then generative modeling by a diffusion model that never sees pixels. Most of the paper's design questions are about where to draw the line between the two stages.
- Train the autoencoder. An encoder E maps an image x of size H×W×3 to a latent z = E(x) of size h×w×c, and a decoder D maps it back. The downsampling factor f = H/h is a power of two; the paper tried f ∈ {1, 2, 4, 8, 16, 32}. The loss combines a perceptual (LPIPS) loss with a patch-based adversarial loss, as in VQGAN, so reconstructions stay sharp instead of averaging into blur as a plain L1 or L2 loss would.
- Regularize the latent. Two variants keep the latent space well behaved. KL-reg adds a very small KL penalty toward a standard normal, a VAE whose KL weight is close to zero. VQ-reg puts a vector-quantization layer inside the decoder, so the latent the diffusion model works on is the continuous one before quantization.
- Rescale it. For the KL-regularized models, latents are divided by one scalar, their standard deviation estimated from encoded training images, so they have roughly unit variance before noise is added. Stable Diffusion's familiar scaling factor of 0.18215 is that constant written as a multiplier.
- Train the diffusion model in latent space. Freeze E and D. A time-conditioned U-Net εθ is trained with the DDPM noise-prediction loss on zt, the noised latent. Because the latent keeps a spatial layout, the U-Net's convolutional inductive biases still apply, which a flattened or one-dimensional latent would lose.
- Condition through cross-attention. A domain-specific encoder τθ turns the condition y (a caption, a class label, a semantic layout) into a sequence of embeddings. At several U-Net resolutions, attention layers take queries from the image features and keys and values from τθ(y). τθ and the U-Net are trained together.
- Or through concatenation. When the condition is itself an image aligned with the output, such as the low-resolution input for super-resolution, the masked image for inpainting or a semantic map, it is concatenated with zt along the channel axis.
- Sample. Start from Gaussian noise in latent space, run a DDIM sampler with the trained U-Net, optionally with classifier-free guidance, and decode once with D.
The paper's text-to-image model, and what Stable Diffusion changed
The paper's text-to-image model is a 1.45-billion-parameter KL-regularized LDM with f = 8, trained on LAION-400M. Its τθ is a transformer trained from scratch on top of a BERT tokenizer, not CLIP. Stable Diffusion, released in 2022 by the CompVis group with Stability AI and Runway, kept the f = 8, four-channel KL autoencoder and a cross-attention U-Net of about 860 million parameters, but swapped τθ for a frozen CLIP ViT-L/14 text encoder and trained at 512×512 on LAION data, so a 512×512 image becomes a 64×64×4 latent.
Why the split pays
The autoencoder is trained once and reused by every diffusion model built on it, so its cost is paid once. The expensive part, the diffusion model, runs every training step and every sampling step on a grid 64 times smaller in area at f = 8.
The latent diffusion objective, cross-attention and latent scaling
E(x)— the frozen encoder's latent, h×w×c with h = H/f.σ̂— a single scalar, the standard deviation of encoded training latents; Stable Diffusion's 0.18215 is 1/σ̂ for its autoencoder.φi(zt)— the U-Net's flattened features at layer i, one query per latent position.τθ(y)— M condition tokens; keys and values come only from them, so each position reads from the tokens relevant to it.WQ, WK, WV— learned projections, separate for each layer i.
Extremes of f: at f = 1 the latent is the image and this is ordinary pixel-space diffusion; at f = 32 the latent is so small that the decoder must invent most of the detail and quality stalls. Without σ̂, a latent with standard deviation well above 1 makes every noise level look cleaner than the schedule assumes, so zT is far from pure noise and sampling from N(0, I) starts in the wrong place.
What the latent diffusion paper measured
The evidence comes in two parts: an ablation of the compression factor f, and results across unconditional, class-conditional, text-to-image, super-resolution, inpainting and layout-to-image tasks, mostly scored by FID (lower is better).
For the f ablation, class-conditional ImageNet models from LDM-1 to LDM-32 were trained the same way and compared at matching numbers of steps. Small factors trained slowly: the paper reports an FID gap of about 38 between pixel-based LDM-1 and LDM-8 after 2 million training steps. Large factors stalled, because at f = 32 the first stage throws away too much and fidelity stops improving early. Factors from 4 to 16 struck the balance.
| Task | Model | Result |
|---|---|---|
| Unconditional CelebA-HQ, 256×256 | LDM-4 | FID 5.11, a new state of the art at the time |
| Class-conditional ImageNet, 256×256 | LDM-4, classifier-free guidance at scale 1.5 | FID 3.60, against 4.59 for classifier-guided ADM; 10.56 without guidance |
| Text-to-image, zero-shot MS-COCO, 256×256 | 1.45B KL-regularized LDM-8, guidance scale 1.5 | FID 12.63 with guidance, 23.31 without; GLIDE, a much larger model, 12.24 |
Two results cut against the simple story. Comparing the two regularizers, VQ-regularized latents sometimes gave better samples than KL-regularized ones even though their reconstructions were slightly worse, so the best autoencoder for reconstruction is not automatically the best space to generate in. And the guidance rows show how much of the headline quality comes from classifier-free guidance rather than from the latent space itself: the text-to-image FID roughly halves when it is switched on.
The central claim is about cost: FID competitive with or better than pixel-space diffusion models at a fraction of their training and sampling compute. That is what let a model of this design be released publicly and run on a single consumer GPU, while the autoencoder's reconstruction quality remained a hard ceiling on fine detail such as small text.
Where this shows up in production
- The three-part pipeline in code
A diffusers Stable Diffusion pipeline is this paper's diagram: a text encoder, a denoising U-Net looped over latents, and an
AutoencoderKLthat decodes once at the end after dividing byvae.config.scaling_factor. Swapping a scheduler, a LoRA or a fine-tuned VAE touches one part and leaves the others alone. - Inpainting by channel concatenation
Stable Diffusion's inpainting U-Net takes 9 input channels instead of 4: the noisy latent, the latent of the masked image and a downsampled mask, the concatenation route this paper used for spatially aligned conditions.
- The decoder as the memory peak
At high resolutions the single VAE decode can need more memory than a denoising step on the small latent. diffusers offers
enable_vae_tiling()andenable_vae_slicing()to decode in pieces, at some risk of visible seams with tiling. - Audio and video in a latent
AudioLDM runs latent diffusion over an autoencoder of mel spectrograms, and video models compress clips into latents with a time axis before denoising, the step the Sora report builds on.
- In interviews
Expect the f² arithmetic for a 512×512 image, why the autoencoder caps fine detail such as small text, cross-attention against concatenation, and what goes wrong if latents are not rescaled.
What the authors admit, and what happened next
The autoencoder is a hard ceiling, and this is the honest cost: anything the encoder discards, the diffusion model cannot generate, because it never sees it and the decoder must invent it. That is precisely why models of this family were for years bad at small text inside images and at fine high-frequency structure — the failure is in the compressor, not the generator, and no amount of diffusion capacity fixes it. The compression ratio is the single most consequential design choice in the system.
Training is also two-stage, so the autoencoder is fitted without knowing what the diffusion model will find difficult, and an adversarial term is used in the decoder to keep reconstructions sharp — which quietly means rung 2 is in the pipeline too.
How it held up: this is the architecture of deployed image generation. Its release as open weights is also the single largest reason a public ecosystem of fine-tunes, adapters and tooling exists for image models at all, which is a social consequence of a compute decision. The general lesson transfers past images: run the expensive iterative process in the smallest representation that preserves what you care about, and let a cheap decoder restore the rest.
Price the latent-space speedup
Latent diffusion's whole argument is a downsample factor and its powers. This computes what Stable Diffusion's f = 8 VAE actually buys: how many fewer numbers the diffusion model touches, how many fewer spatial positions the U-Net processes, and — because self-attention is quadratic in positions — how the attention cost drops by f⁴. Watch a 512×512 image collapse to a 64×64 latent, 64× fewer positions, and a 4,096× cheaper attention step. Change the resolution or the factor.
Write the body of latent_budget. Everything else in the file is
already written; this is the function the paper is about. Press ▶ Run to check it against
the 7 assertions below — they start red.
- An 8x downsample gives 64x fewer spatial positions
- A 512 image at f=8 becomes a 64x64 latent grid
- Per-position (conv) work drops by f squared
- Attention, quadratic in positions, drops by f to the fourth
- The latent tensor is far smaller than the raw image
- Latent_budget collects the grid, the number count and both savings
- Halving the downsample factor quadruples the numbers to diffuse
Questions people ask about Latent Diffusion
What is the Stable Diffusion VAE scaling factor of 0.18215?
It is the latent rescaling step from the latent diffusion paper, specialized to Stable Diffusion's autoencoder. Latents from a KL-regularized encoder do not have unit variance, so the paper divides them by a single scalar, their standard deviation estimated on encoded training images, before diffusion. For the Stable Diffusion v1 autoencoder that standard deviation is about 5.5, so code multiplies encoder outputs by 0.18215 and divides by it again before decoding. Skipping the factor leaves latents several times larger than the noise schedule assumes, so noised latents carry far more signal than intended and the sampler's starting noise does not match training. Autoencoders trained later have their own constants; SDXL's is 0.13025.
Why does latent diffusion use a downsampling factor of 8?
The paper trained class-conditional ImageNet models with downsampling factors of 1, 2, 4, 8, 16 and 32, trained the same way. Factors of 1 and 2 trained slowly, because the diffusion model still spends its capacity on pixel-level detail; after 2 million steps the paper reports an FID gap of about 38 between the pixel-space model and the f = 8 model. Factors of 16 and especially 32 compressed so hard that quality stalled early, since anything the encoder discards is lost to the generator. Factors from 4 to 16 balanced the two, and f = 8 with four latent channels became the Stable Diffusion choice: a 512×512 image becomes a 64×64×4 latent, 48 times fewer numbers, cheap enough for consumer GPUs while still reconstructing well.
How does cross-attention conditioning work in latent diffusion?
A condition encoder, a transformer in the case of text, turns the prompt into a sequence of token embeddings. Inside the U-Net, at several resolutions, an attention layer computes queries from the image features at every latent position and keys and values from the token embeddings, then mixes the values according to the softmax of the query-key products. Each latent position therefore reads from whichever words are relevant to it. The projections are learned separately for each layer, and the condition encoder is trained jointly with the U-Net in the paper. The design is generic: the same mechanism conditioned the paper's models on captions, class labels and semantic layouts, and later work used it for image prompts and other inputs without changing the backbone.
Did the latent diffusion paper use CLIP as its text encoder?
No. The paper's text-to-image model, a 1.45-billion-parameter latent diffusion model trained on LAION-400M, used a transformer text encoder trained from scratch together with the diffusion model, on top of a BERT tokenizer. CLIP arrives with Stable Diffusion, the open model built on this architecture afterwards: version 1 replaced the learned encoder with OpenAI's frozen CLIP ViT-L/14 text encoder, kept the f = 8 autoencoder and used an 860-million-parameter cross-attention U-Net trained at 512×512 on LAION data. Version 2 switched to an OpenCLIP text encoder. So descriptions of Stable Diffusion's CLIP conditioning describe a design choice made after the paper, not a result reported in it.
What is the difference between KL-regularized and VQ-regularized autoencoders in latent diffusion?
Both are trained with perceptual and patch-based adversarial losses; they differ in how they keep the latent space tame. The KL-regularized version adds a very small KL penalty toward a standard normal, so it behaves like a VAE whose KL weight is close to zero, and its latents need rescaling to unit variance. The VQ-regularized version places a vector-quantization layer inside the decoder, which makes it a VQGAN with the quantizer absorbed into the decoder, so diffusion runs on the continuous latent before quantization. The paper found VQ-regularized latents sometimes gave better samples despite slightly worse reconstructions. Stable Diffusion uses the KL version with f = 8 and four channels.
When does latent diffusion concatenate the condition instead of using cross-attention?
When the condition is an image that is spatially aligned with the output. For super-resolution the low-resolution image, for inpainting the masked image and its mask, and for semantic synthesis the label map are concatenated with the noised latent along the channel dimension, so each latent position sees the condition at the same position directly. Cross-attention is used when the condition is not a grid aligned with the image, such as a caption, a class label or a set of layout boxes, because attention lets every position read from any token. The spatially conditioned models can also be run convolutionally on inputs larger than their training size, which the paper used to produce larger coherent landscape images.
4 questions to test what you just read
Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.
A 512×512×3 image is encoded with f = 8 and c = 4. How many numbers does the diffusion model see, and how do the counts change for f = 16 with c = 16?
Show answer
f = 8: 64 × 64 × 4 = 16,384 numbers, 48× fewer than 786,432 pixel values, at 4,096 positions. f = 16, c = 16: 32 × 32 × 16 = 16,384 numbers too, but only 1,024 positions, so self-attention over positions costs 16× less. Same count of numbers, very different spatial compression.
What goes wrong if you encode images with Stable Diffusion’s autoencoder and skip the 0.18215 scaling before training a diffusion model on them?
Show answer
The latents keep a standard deviation of about 1/0.18215 ≈ 5.5. At every timestep the signal term √ᾱt z is then about 5.5× larger relative to the noise than the schedule assumes, a signal-to-noise ratio roughly 30× too high, so even zT still carries the image and sampling from pure N(0, I) starts from a state the model never saw.
Why did the f = 32 model stall in quality however long it trained?
Show answer
Anything the encoder discards cannot be generated: the diffusion model only ever sees latents, and the decoder must invent what is missing. At f = 32 a 256×256 image becomes an 8×8 grid, so the first stage, not the diffusion model, sets the ceiling, and more diffusion training cannot raise it.
In Stable Diffusion a 64×64 latent attends to 77 text tokens. How large is one cross-attention score matrix per head, and how does it compare with self-attention at the same resolution?
Show answer
Cross-attention: 4,096 queries × 77 keys = 315,392 scores. Self-attention at 64×64: 4,096 × 4,096 ≈ 16.8 million, about 53× more. Conditioning on text is cheap; attending across image positions is what dominates the cost at high resolution.
Generating pixels
Ten papers from the first latent-variable generator to video and real-time 3D. The diffusion half is strictly cumulative — each rung removes a cost the last one paid.
- 1VAE2014
- 2GANs2014
- 3VQ-VAE2017
- 4DDPM2020
- 5DDIM2021
- 6Classifier-Free Guidance2021
- 7Latent Diffusion2022
- 8Sora2024
- 9NeRF2020
- 103D Gaussian Splatting2023
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Paper Breakdowns
- Attention Is All You NeedThe paper that introduced the Transformer — the architecture underneath GPT, BERT, Claude, and Gemini. Self-attention, Query/Key/Value, multi-head attention, positional encoding, and the real BLEU results, explained in depth with analogies and animated visuals, not just equations.Read →
- Word2VecHow words became math. Dense word vectors learned from the company a word keeps, so king − man + woman lands near queen. Skip-gram, CBOW, the distributional hypothesis, and the origin of every embedding model powering search and RAG.Read →
- ResNetThe skip connection that made deep learning deep. Why stacking layers made networks worse, and how residual learning let them reach 150+ layers and win ImageNet — the identity shortcut every Transformer still uses inside every block.Read →
- Vision Transformer (ViT)When an image became 16×16 words. Cut a picture into patches, treat each patch as a token, and feed them to a plain Transformer — no convolutions. Patch embeddings, the class token, and why data scale lets attention beat the CNNs that ruled computer vision for a decade.Read →
- DDPMThe original denoising diffusion math — the paper that made diffusion work. A fixed forward process adds Gaussian noise over many steps; a U-Net learns the reverse. The masterstroke: train the network to simply predict the added noise with a plain MSE loss. The foundation under every modern image generator.Read →
- GANsThe counterfeiter and the detective. Two networks locked in a game: a generator forging fakes from noise and a discriminator trying to catch them. The minimax objective that taught machines to imagine, its notorious instabilities and mode collapse, and how diffusion later overtook it.Read →