Search

Search papers and lessons

High-Resolution Image Synthesis with Latent Diffusion Models

Robin Rombach, Andreas Blattmann, Dominik Lorenz et al. · 2021

Rombach et al. (2021) train diffusion models in the compressed latent space of a pretrained autoencoder and add cross-attention, so high-resolution image generation becomes much cheaper and can be conditioned on text.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Architectures
  • Generative models
  • Linear algebra
  • Neural network basics
  • Sign in to see your progress

TL;DR

Diffusion models make excellent image generators, but they run every denoising step on full-resolution pixels, which makes training take hundreds of GPU days and sampling slow. Rombach and colleagues first compress images with an autoencoder into a smaller latent space that keeps the perceptual detail, then train the diffusion model there. Cross-attention layers let the same model take text, layouts or other inputs as conditions.

Where you'll see it: the architecture behind Stable Diffusion and the many image generators that followed it, and in inpainting and super-resolution tools built on the same pretrained autoencoders.

The problem

Diffusion models had reached the top of image synthesis benchmarks by 2021, beating GANs on sample quality and coverage of the data. The authors point to three costs. Training the strongest models took hundreds of GPU days. Sampling 50,000 images from one pixel-space model took about five days on a single A100 GPU. Each sample needed many sequential evaluations of the same network. These costs kept the field in the hands of a few large labs, and they carried a large energy footprint.

Attempts to fix this with autoregressive models on compressed codes, such as VQ-VAE and VQGAN, had a different problem. Their compression had to be strong, which meant billions of parameters and a loss of detail, or it had to be weak, which meant high cost. The paper asks whether a diffusion model can work on a compressed representation without losing the quality that made it attractive.

Key idea

The paper splits generation into two stages, which the authors describe as perceptual compression and semantic compression. An autoencoder first removes imperceptible high-frequency detail. It is trained once, with a perceptual loss and a patch-based adversarial loss, so that its reconstructions look right. A diffusion model is then trained on the autoencoder's latent codes, where the model only has to learn the semantic structure of the data.

The latent space is two-dimensional, with width and height, so the diffusion model can keep the convolutional inductive bias of a UNet. The authors do not need the heavy spatial compression that earlier one-dimensional, autoregressive approaches required. The autoencoder can therefore compress by a modest factor, such as 4 or 8 in each spatial direction, and keep detail that the earlier models lost.

The second idea is conditioning. A domain-specific encoder turns a prompt, a semantic map or a bounding-box layout into a sequence of tokens, and cross-attention layers inside the UNet let each spatial position of the image attend to those tokens. The same architecture therefore handles class labels, text and spatially aligned inputs.

The method

Perceptual compression

An image xx in RH×W×3\mathbb{R}^{H \times W \times 3} is encoded to z=E(x)z = \mathcal{E}(x) with zz in Rh×w×c\mathbb{R}^{h \times w \times c}, and decoded back to x~=D(z)\tilde{x} = \mathcal{D}(z). The encoder downsamples by a factor f=H/h=W/wf = H/h = W/w, and the paper tests ff equal to 1, 2, 4, 8, 16 and 32. The autoencoder is trained with a perceptual loss and a patch-based adversarial objective, which the paper says confines the reconstructions to the image manifold. Pixel-wise L1L_1 or L2L_2 losses alone are known to produce blur, which is why the perceptual and adversarial terms are used.

Two regularizers keep the latent space from growing without bound. The KL-regularized version adds a low-weighted penalty (a factor of about 10−610^{-6} in the appendix) that pulls the latent towards a standard normal, as a variational autoencoder does. The VQ-regularized version uses a vector-quantization layer that the paper absorbs into the decoder. Both are used in the paper's experiments, with only very small regularization in each case so that reconstructions stay high-fidelity.

The diffusion objective

A diffusion model defines a fixed forward process that gradually adds Gaussian noise to a data point, and learns the reverse process. The paper uses the simplified, re-weighted objective of DDPM, in which a network ϵθ\epsilon_\theta predicts the noise that was added to the noisy input xtx_t at a randomly chosen step tt:

LDM=Ex,ϵ∼N(0,1),t[∥ϵ−ϵθ(xt,t)∥22].L_{DM} = \mathbb{E}_{x, \epsilon \sim \mathcal{N}(0, 1), t}\left[\left\lVert \epsilon - \epsilon_\theta(x_t, t) \right\rVert_2^2\right].

This is a sum of equally weighted denoising autoencoders over the time steps, and it is closely related to denoising score matching. The latent model replaces the image with its latent code:

LLDM=EE(x),ϵ∼N(0,1),t[∥ϵ−ϵθ(zt,t)∥22].L_{LDM} = \mathbb{E}_{\mathcal{E}(x), \epsilon \sim \mathcal{N}(0, 1), t}\left[\left\lVert \epsilon - \epsilon_\theta(z_t, t) \right\rVert_2^2\right].

The encoder is frozen during diffusion training, so each ztz_t is computed from E(x)\mathcal{E}(x) once per example. Sampling runs the reverse process in latent space and then decodes the final latent with one pass through D\mathcal{D}.

Because the autoencoder is fixed, the same trained first stage can be reused for many diffusion models, which the paper uses for different tasks.

Cross-attention conditioning

To condition on a prompt or another input yy, the paper adds a domain-specific encoder τθ\tau_\theta that maps yy to a sequence τθ(y)\tau_\theta(y) of MM vectors. Inside the UNet, an intermediate feature map φi(zt)\varphi_i(z_t), flattened to NN positions, produces queries, and the encoded condition produces keys and values:

Q=WQ(i)φi(zt),K=WK(i)τθ(y),V=WV(i)τθ(y),Q = W_Q^{(i)} \varphi_i(z_t), \qquad K = W_K^{(i)} \tau_\theta(y), \qquad V = W_V^{(i)} \tau_\theta(y), Attention(Q,K,V)=softmax ⁣(QKTd)V.\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^{T}}{\sqrt{d}}\right) V.

The conditional objective is the same as before with ϵθ(zt,t,τθ(y))\epsilon_\theta(z_t, t, \tau_\theta(y)) in place of the unconditioned network, and τθ\tau_\theta and ϵθ\epsilon_\theta are trained jointly. For text, τθ\tau_\theta is a transformer that reads a tokenized prompt. For semantic maps and other spatially aligned inputs, the paper concatenates the downsampled condition to the UNet input instead.

Classifier-free guidance (Ho and Salimans, 2021) is used in the text-to-image and class-conditional models. It trains with the condition dropped at random and combines the conditional and unconditional predictions at sampling time, with a guidance scale ss. The paper uses s=10.0s = 10.0 for the text-to-image samples in its figures.

Worked examples

Example
The compression arithmetic

Take a 512×512512 \times 512 RGB image. In pixel space the diffusion model's input has 512×512×3=786,432512 \times 512 \times 3 = 786{,}432 values.

  1. Use the encoder with downsampling factor f=8f = 8. The latent has spatial size 512/8=64512/8 = 64 in each direction.
  2. Suppose the latent has c=4c = 4 channels. The latent has 64×64×4=16,38464 \times 64 \times 4 = 16{,}384 values.
  3. The diffusion model now works on 16,38416{,}384 values instead of 786,432786{,}432, a reduction by a factor of 4848.
  4. Each denoising step therefore touches roughly 4848 times fewer values, and the convolutions in the UNet cost roughly that much less per step.
  5. The measured gain is much smaller than the 48×48\times value count, because cost is not proportional to value count alone (the decoder pass, memory traffic and the rest of the pipeline also matter). The paper reports a speed-up of at least 2.7×2.7\times between pixel-based and latent-based diffusion in its inpainting comparison, with the same parameter count, and this measured figure is the one to remember.
Example
Attention over a prompt

Take a condition of three tokens, so M=3M = 3, and an image feature map flattened to N=2N = 2 positions. Use d=2d = 2 for the key and query width.

  1. Suppose the query for position 1 is q1=(1,0)q_1 = (1, 0), and the keys for the three tokens are k1=(1,0)k_1 = (1, 0), k2=(0,1)k_2 = (0, 1) and k3=(1,1)k_3 = (1, 1).
  2. The scores are q1⋅kj/2q_1 \cdot k_j / \sqrt{2}, giving 1/2≈0.7071/\sqrt{2} \approx 0.707, 00, and 1/2≈0.7071/\sqrt{2} \approx 0.707.
  3. The softmax of [0.707,0,0.707][0.707, 0, 0.707] is about [0.401,0.198,0.401][0.401, 0.198, 0.401].
  4. The output for position 1 is the weighted sum of the values, so it draws about 40 percent from token 1, 20 percent from token 2 and 40 percent from token 3.
  5. Position 1 therefore takes its information mainly from the tokens that match its query. Each spatial position does this separately, which is how a single prompt can affect the whole image.

Results

The experiments cover unconditional generation, text-to-image, class-conditional ImageNet, super-resolution, inpainting and layout-to-image. The comparisons are against pixel-space diffusion and against GAN, autoregressive and earlier diffusion models, with FID as the main sample-quality measure and precision and recall for coverage.

  • Compression trade-off. The authors train models with downsampling factors from 1 to 32 under the same compute budget. Pixel-space training (factor 1) is slow. Factors 4 to 16 give the best balance. Factor 32 stalls early, and at 2 million training steps on ImageNet the pixel-based model and LDM-8 are separated by an FID gap of 38 in favour of LDM-8.
  • Unconditional generation. On CelebA-HQ at 256 by 256, the paper's text reports a new state-of-the-art FID of 5.11, ahead of previous likelihood-based models and GANs. The caption of the appendix figure of CelebA-HQ samples, which uses 500 DDIM steps, gives FID 5.15 for the same LDM-4 model. The text does not say which sampler setting yields 5.11 (Table 1 is not in the extracted paper text), so treat 5.11 as the headline number and 5.15 as the figure tied to that specific sample set. It also outperforms LSGM, which trains the autoencoder and the prior jointly. The model is close to ADM on LSUN-Bedrooms while using about half its parameters and four times less training compute. Precision and recall are better than GAN baselines.
  • Text-to-image. A 1.45 billion parameter KL-regularized model trained on LAION-400M, with a BERT-style text encoder, improves on earlier autoregressive and GAN results on MS-COCO. With classifier-free guidance, the guided model is on par with the strongest autoregressive and diffusion systems of the time while using far fewer parameters.
  • Class-conditional ImageNet. The paper outperforms the ADM diffusion model on ImageNet while needing much less compute and fewer parameters.
  • Super-resolution. For 4×4\times bicubic upscaling on ImageNet, LDM-SR beats SR3 on FID while SR3 has a better Inception Score. A plain image-regression model gets the highest PSNR and SSIM, which the authors say favour blurriness. The paper's user study compares LDM-SR with a pixel-space baseline, not with SR3, and the authors say it affirms the good performance of LDM-SR.
  • Inpainting. Latent models give a speed-up of at least 2.7×2.7\times over pixel-space diffusion, with FID improved by at least 1.6×1.6\times. The large model, fine-tuned at 512×512512 \times 512, sets a new state of the art on the inpainting benchmark.
  • Convolutional sampling. Models trained at 256×256256 \times 256 generate consistent images up to about 1024×10241024 \times 1024 when the conditioning is spatially aligned, with the latent scaled to the right signal-to-noise ratio.

Where the compression helps and where it hurts

The paper is open about its limits, and most of them come from the choice of compression.

SituationProblemBetter choice
Very strong compression, f=32f = 32The first stage discards detail the diffusion model cannot recover, and quality stalls earlyUse ff in the range 4 to 8
No compression, f=1f = 1Training and sampling are as slow as pixel-space diffusionUse a latent space
Tasks that need exact pixel accuracyThe autoencoder's reconstruction error becomes a bottleneckPixel-space model, or a post-hoc correction
Very large imagesSampling is still sequential and slower than a GANFewer sampling steps with a faster sampler, or a GAN for latency-critical use
Joint training of autoencoder and priorWeighting reconstruction against generation is delicateTrain the autoencoder first and freeze it

The authors also flag that their autoencoder is trained on a fixed dataset, so the latent space inherits that dataset's biases. The societal-impact section raises the usual concerns: easier production of manipulated images, possible reproduction of training data, and bias in the data.

Why it mattered

Diffusion probabilistic models were introduced by Sohl-Dickstein and colleagues in 2015. Ho, Jain and Abbeel showed in 2020 that a simplified training objective gave high-quality images, and this is the objective the paper builds on. Earlier, two-stage methods used autoregressive models over compressed codes, from VQ-VAE and its successors. VQGAN added an adversarial and perceptual objective to the first stage.

The paper has five authors, Rombach, Blattmann, Lorenz, Esser and Ommer, and was published at CVPR in 2022. The released code and pretrained models were used as the base for the open text-to-image systems that followed, and the approach became widely known as Stable Diffusion. The architecture has since been extended to video and other modalities, but the central idea is the one in this paper: keep the diffusion process, move it to a learned latent space, and condition it through attention.

Reading guide

Read the paper in this order and use the prerequisites as follows.

  1. Introduction and Figures 1 and 2. Needs Diffusion Model and Generative Model. The argument is that most of the bits in an image are perceptual detail that a diffusion model spends compute on. Variational Autoencoder is useful background for the KL-regularized autoencoder.
  2. Related work. Needs Generative Model and the idea of GAN and autoregressive models. Read it briefly, since the comparisons come back in the experiments.
  3. Section 3.1, perceptual compression. Needs Convolutional Neural Network for the autoencoder architecture, and Kullback–Leibler Divergence for the KL penalty.
  4. Section 3.2, latent diffusion. Needs Denoising Diffusion Probabilistic Models (DDPM) for the simplified objective, Score Matching for the link to denoising score matching, and U-Net for the backbone. The latent objective in Eq. for LLDML_{LDM} is the paper's core change.
  5. Section 3.3, conditioning. Needs Attention Mechanism and Transformer. Cross-attention is the only new architectural component in the method.
  6. Section 4, experiments. Read the table captions and the section for the task you care about. Section 4.1 is the compression study, and Section 4.3.1 is the text-to-image model.

Check yourself

QuestionAn image is 256×256×3256 \times 256 \times 3 and the autoencoder uses downsampling factor f=4f = 4 with c=3c = 3 latent channels. How many values does the diffusion model process, and how many does pixel-space diffusion process?Show answer

Pixel space has 256×256×3=196,608256 \times 256 \times 3 = 196{,}608 values. The latent has spatial size 256/4=64256/4 = 64 in each direction, so it has 64×64×3=12,28864 \times 64 \times 3 = 12{,}288 values. The latent model processes 12,28812{,}288 values, which is 196,608/12,288=16196{,}608 / 12{,}288 = 16 times fewer. The number of spatial positions drops by a factor of f2=16f^2 = 16, which is the source of the reduction when the channel count is the same.

QuestionWhy does the paper use a fixed, pretrained autoencoder rather than training the autoencoder and the diffusion model together?Show answer

Joint training has to balance two goals. The autoencoder should reconstruct the image well, while the latent space should be easy for the diffusion model to learn. Weighting these goals is delicate, and the paper reports that joint training, as in LSGM, is outperformed. Freezing the autoencoder removes the balance problem, and the same first stage can then be reused for many diffusion models and tasks.

QuestionIn the cross-attention layer, what does the softmax over the keys do for one spatial position of the image, and why does this allow the same architecture to handle text and semantic maps?Show answer

For one position, the softmax turns the dot products between its query and each condition token's key into weights that sum to one. The output at that position is a weighted average of the value vectors, so the position draws information from the condition tokens that match it. Because the condition encoder τθ\tau_\theta is a separate module that outputs a sequence of vectors, the attention layer does not depend on what the condition is. A text transformer and a semantic-map encoder can each produce such a sequence, and the cross-attention layer works the same way for both.

QuestionA team wants to generate 1024×10241024 \times 1024 images with a model trained only on 256×256256 \times 256 images. Based on the paper's convolutional sampling section, what should they expect, and what does the paper say helps?Show answer

The paper reports that models trained on 256×256256 \times 256 images can generalize to larger resolutions when conditioned on spatially aligned inputs, such as semantic maps or low-resolution images, because the UNet is convolutional. The paper also notes that the signal-to-noise ratio set by the scale of the latent space significantly affects convolutional sampling, and that rescaling the latent by its standard deviation changes the results (shown for semantic synthesis). It shows its 1.45B text-to-image model rendering images larger than 256×256256 \times 256 when classifier-free guidance is combined with convolutional sampling. For unconditional models it notes that large samples can come out homogeneous and incoherent in global structure. The team should expect results to depend on the conditioning and the latent scaling, and should check them rather than assume the model generalizes.

Sources

Read the full paper

Robin Rombach, Andreas Blattmann, Dominik Lorenz et al., 2021. arXiv:2112.10752