AI Logic

Architectures

Latent Diffusion (Stable Diffusion)

Updated:

Architecture of Latent Diffusion. The left side shows training, where the encoder compresses an image into a latent and the U-Net predicts the noise, and generation, where a latent is built from noise and the decoder turns it back into an image. The right side shows how conditions are injected by cross-attention inside the U-Net, concatenation of spatially aligned conditions, and the trade-off of the downsampling factor f

Background and Overview

Latent Diffusion (Latent Diffusion Model, LDM) is a method that compresses images into a small latent representation with an autoencoder and trains and samples a diffusion model in that latent space. Because the data handled is much smaller than raw pixels, it greatly reduces the computation for training and generation with almost no loss in image quality. In addition, by adding cross-attention to the noise-predicting U-Net, it can generate images from many kinds of conditions, such as text or layouts.

Rombach, Blattmann, Lorenz, Esser, and Ommer introduced it in 2021 in the paper "High-Resolution Image Synthesis with Latent Diffusion Models," which was accepted at CVPR 2022. Stable Diffusion, which generates images from text, is a model trained with this method.

The problem the paper set out to solve was the heavy cost of diffusion models that operate in pixel space.

  • Training is expensive: The most powerful diffusion model at the time (ADM) needed 150 to 1,000 V100 GPU-days of computation to train.
  • Generation is expensive too: Generating 50,000 images with the same model took about 5 days on a single A100 GPU, because the full-size image passes through the network hundreds of times.

Examining trained diffusion models, the paper noticed that learning can be split into two stages: "perceptual compression," which discards imperceptible fine details, and "semantic compression," which learns the meaning and composition of images. The former carries little information relative to the number of pixels, so the idea of LDM is to hand it off to an autoencoder first and let the diffusion model focus on the latter.

LDM can be used for tasks such as the following.

  • Unconditional image generation: Faces, landscapes, room images, and so on.
  • Text-to-image generation: Generating images conditioned on text (Stable Diffusion).
  • Image-to-image translation: Super-resolution, inpainting, and image generation from semantic maps.

Theory

LDM is trained in two stages. First, an autoencoder is trained and frozen; then a diffusion model is trained in its latent space.

Stage 1: Autoencoder for perceptual compression

An RGB image x∈RH×W×3\boldsymbol{x} \in \mathbb{R}^{H \times W \times 3} is mapped by the encoder E\mathcal{E} to a latent representation z=E(x)∈Rh×w×c\boldsymbol{z} = \mathcal{E}(\boldsymbol{x}) \in \mathbb{R}^{h \times w \times c}, and the decoder D\mathcal{D} maps it back to x~=D(z)\tilde{\boldsymbol{x}} = \mathcal{D}(\boldsymbol{z}) (Section 3.1). The spatial downsampling factor is written f=H/h=W/wf = H/h = W/w, and several values of f=2mf = 2^m are tested.

  • Loss: A perceptual loss (reconstruction error in feature space) is combined with an adversarial loss from a discriminator that judges whether each small patch of the image is real. Pixel-level L1 or L2 error alone makes reconstructions blurry.
  • Latent-space regularization: Two variants are tested to keep the latent variance from growing too large: a weak KL penalty toward a standard normal distribution as in a VAE (KL-reg., weight around 10−610^{-6}) and vector quantization (VQ-reg.). Both are applied very weakly to keep reconstructions accurate (Appendix G).

Because the latent z\boldsymbol{z} retains a two-dimensional spatial structure, the diffusion model's U-Net can handle it efficiently even with mild downsampling. The advantage is that it does not need the strong compression required by earlier two-stage methods that flatten the latent into 1D and model it autoregressively.

Stage 2: Diffusion model in latent space

The diffusion part is the same as DDPM. Noise is added to the latent z\boldsymbol{z} instead of the pixels x\boldsymbol{x}, and the model predicts the added noise ϵ\boldsymbol{\epsilon} (Eq. 2).

LLDM=EE(x),ϵ∼N(0,I),t[∥ϵ−ϵθ(zt,t)∥22]L_{\mathrm{LDM}} = \mathbb{E}_{\mathcal{E}(\boldsymbol{x}), \boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I}), t}\Big[\big\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\boldsymbol{z}_t, t)\big\|_2^2\Big]

tt is drawn uniformly from 1 to TT, and zt\boldsymbol{z}_t is z0=E(x)\boldsymbol{z}_0 = \mathcal{E}(\boldsymbol{x}) with noise added. ϵθ\boldsymbol{\epsilon}_\theta is a time-conditioned U-Net built mainly from 2D convolutions. Because the forward process is fixed, zt\boldsymbol{z}_t can be obtained during training just by passing through E\mathcal{E}. At generation time, the denoised z0\boldsymbol{z}_0 in latent space is turned back into an image with a single pass through the decoder D\mathcal{D}.

Conditioning: cross-attention

A condition yy (text, class, layout, and so on) is mapped by a domain-specific encoder τθ\tau_\theta to τθ(y)∈RM×dτ\tau_\theta(y) \in \mathbb{R}^{M \times d_\tau} and injected into intermediate layers of the U-Net via cross-attention (Section 3.3).

Attention(Q,K,V)=softmax(QK⊤d)V,Q=WQ(i)φi(zt), K=WK(i)τθ(y), V=WV(i)τθ(y)\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(\frac{QK^{\top}}{\sqrt{d}}\right) V, \quad Q = W_Q^{(i)} \varphi_i(\boldsymbol{z}_t),\ K = W_K^{(i)} \tau_\theta(y),\ V = W_V^{(i)} \tau_\theta(y)

φi(zt)\varphi_i(\boldsymbol{z}_t) is the flattened feature of the ii-th U-Net layer, and WQ(i),WK(i),WV(i)W_Q^{(i)}, W_K^{(i)}, W_V^{(i)} are learned matrices. Each image position acts as a "query," and scaled dot-product attention decides which part of the condition to attend to. The conditional loss is the following, and τθ\tau_\theta and ϵθ\boldsymbol{\epsilon}_\theta are trained jointly (Eq. 3).

LLDM=EE(x),y,ϵ∼N(0,I),t[∥ϵ−ϵθ(zt,t,τθ(y))∥22]L_{\mathrm{LDM}} = \mathbb{E}_{\mathcal{E}(\boldsymbol{x}), y, \boldsymbol{\epsilon} \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I}), t}\Big[\big\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\boldsymbol{z}_t, t, \tau_\theta(y))\big\|_2^2\Big]

For text-to-image generation, τθ\tau_\theta is a Transformer, and text is split with the BERT tokenizer before being fed in (Section 4.3.1). Conditions spatially aligned with the image, such as in super-resolution or semantic maps, are concatenated with zt\boldsymbol{z}_t along the channel dimension instead of going through cross-attention.

Training and generation steps

  1. Train the autoencoder (E\mathcal{E}, D\mathcal{D}) and freeze it.
  2. Map training images to latents z0\boldsymbol{z}_0 with E\mathcal{E}. KL-reg. latents are divided by a standard deviation estimated from the first batch to bring their variance to 1 (Appendix G).
  3. Sample a step tt and noise ϵ\boldsymbol{\epsilon} to build zt\boldsymbol{z}_t, and update the U-Net (and τθ\tau_\theta) with Eq. 3.
  4. At generation, denoise from zT∼N(0,I)\boldsymbol{z}_T \sim \mathcal{N}(\boldsymbol{0}, \boldsymbol{I}) with the U-Net. The paper uses the DDIM sampler in many experiments.
  5. Pass the resulting z0\boldsymbol{z}_0 through the decoder D\mathcal{D} to obtain an image.

Once trained, the autoencoder can be reused for training other diffusion models and for other tasks. This saves a great deal of computation when retraining diffusion models many times for experiments.

Why It Works

The reasons LDM delivers high image quality with little computation can be summarized in three points.

  • It skips computation on invisible details: Most of the bits in a digital image go to imperceptible fine details. A pixel-space diffusion model can downweight these in the loss, but the network's computation and gradients still have to run over every pixel. LDM hands this part to the autoencoder, so the diffusion model only needs to compute on the small latent.
  • It compresses mildly while keeping the 2D structure: Because the latent preserves its spatial structure, it stays in the form that a convolutional U-Net handles well. Since strong compression is unnecessary, reconstruction quality stays high. In the paper's comparison, the reconstruction of the f=4f = 4 autoencoder (PSNR 27.4, reconstruction FID 0.58) was more accurate than DALL-E with f=8f = 8 (22.8, 32.01) and VQGAN with f=16f = 16 (19.9, 4.98) (Figure 1).
  • There is a sweet spot for the downsampling factor: Without compression (f=1,2f = 1, 2), the diffusion model also has to handle perceptual compression, so training is slow; with too much compression (f=32f = 32), information is lost and quality plateaus. The balance is good for f=4f = 4 to 1616 (Section 4.1).

As an everyday analogy, a pixel-space diffusion model is like repainting the entire surface of one large canvas every time. LDM is a division of labor: first settle the composition on a scaled-down sketch (the latent), then have a skilled finisher (the decoder) paint in the details in one go.

Cross-attention learns the relationship between each image position and each token of the condition. Just by swapping τθ\tau_\theta for each type of condition, the same U-Net mechanism can handle text, classes, and layouts.

Experimental Results

Comparing downsampling factors (Section 4.1)

For class-conditional generation on ImageNet, f∈{1,2,4,8,16,32}f \in \{1, 2, 4, 8, 16, 32\} were compared by training each for 2 million steps with the same number of parameters and the same compute (a single A100 GPU). After 2 million steps, there was a gap of 38 in FID between the pixel-space model (LDM-1) and LDM-8. When generation speed and FID were compared by varying the number of DDIM steps, LDM-4 and LDM-8 also offered the best trade-off (Figure 7).

Unconditional image generation (Table 1, 256 × 256, excerpt of FID; lower is better)

DatasetCompared methodsLDM
CelebA-HQLSGM 7.22, UDM 7.16, PGGAN 8.05.11 (LDM-4)
FFHQStyleGAN 4.16, ProjectedGAN 3.084.98 (LDM-4)
LSUN-ChurchesDDPM 7.89, StyleGAN2 3.86, ProjectedGAN 1.594.02 (LDM-8)
LSUN-BedroomsDDPM 4.9, ADM 1.90, ProjectedGAN 1.522.95 (LDM-4)

On CelebA-HQ, it outperformed earlier likelihood-based models and GANs. On LSUN-Bedrooms, it came close to ADM with half of ADM's parameters and a quarter of its training compute.

Text-to-image generation (Table 2, MS-COCO validation set, 256 × 256)

ModelFIDISParameters
CogView27.1018.204B
GLIDE12.24—6B
Make-A-Scene11.84—4B
LDM-KL-823.3120.031.45B
LDM-KL-8-G (classifier-free guidance)12.6330.291.45B

With a 1.45-billion-parameter model trained on LAION-400M, classifier-free guidance brought the FID close to that of the much larger GLIDE and Make-A-Scene.

Class-conditional image generation (Table 3, ImageNet 256 × 256)

ModelFIDISParameters
BigGAN-deep6.95203.6340M
ADM-G4.59186.7608M
LDM-4-G (classifier-free guidance)3.60247.67400M

Inpainting (Tables 6 and 7, Places)

Compared with the pixel-space model, training and generation were at least 2.7 times faster, and FID improved by at least 1.6 times. A large model fine-tuned at 512 × 512 reached an FID of 9.39 on hard images with 40 to 50% masked, beating the dedicated method LaMa (12.0).

Relationship to Stable Diffusion

Stable Diffusion is a text-to-image Latent Diffusion model trained and released by the paper authors' group (CompVis) with support from Stability AI and LAION. According to the official repository (CompVis/stable-diffusion), Stable Diffusion v1 is configured as follows.

ItemDetails
AutoencoderDownsamples height and width to 1/8 (f=8f = 8)
Noise-prediction network860M-parameter U-Net
Text encoder (τθ\tau_\theta)Frozen CLIP ViT-L/14 text encoder (123M parameters)
Training dataSubset of LAION-5B; pretrained at 256 × 256 and fine-tuned at 512 × 512

The paper's text-to-image model used a Transformer for τθ\tau_\theta trained jointly, whereas Stable Diffusion uses a pretrained CLIP text encoder kept frozen. The mechanism of diffusing in latent space and injecting text through cross-attention is the same as in the paper.

Practical Considerations

Keep the following points in mind when using LDM.

  • Normalize the latent scale: KL-reg. latents, as is, have a variance that deviates from 1. The paper divides them by a standard deviation estimated from the first batch to bring the variance to 1. This value is applied in reverse when the generated latent is passed back to the decoder. The paper notes that this scale (which affects the signal-to-noise ratio) strongly influences results when generating large images convolutionally.
  • Choose the downsampling factor by data complexity: For complex data such as ImageNet, too much compression degrades quality. In the paper, f=4f = 4 or 88 gave good results.
  • Autoencoder quality is the ceiling: Fine details in generated images cannot exceed the reconstruction quality of the decoder.
  • It extends convolutionally to larger images: For spatially aligned conditions, as in super-resolution and generation from semantic maps, a model trained at 256 × 256 could be applied as is to larger images (such as 512 × 1024).

Generation with LDM is still slower than with GANs, which produce an image in a single pass (Section 5 of the paper). Also, for tasks that require fine pixel-level accuracy, the reconstruction error of the autoencoder becomes the limit. The paper notes that its super-resolution models are also somewhat constrained in this respect.

Comparison with Other Methods

The following compares LDM with closely related generative models from the same angles.

MethodSpace where diffusion happensNetworkHow conditions are addedComputational cost
DDPMPixelsU-Net(Unconditional)Heavy
ADM (pixel diffusion model)PixelsU-NetClass, classifier guidanceVery heavy
LDMAutoencoder latentU-Net + cross-attentionCross-attention (text, class, layout), concatenation (images)Light
DiTSame latent as LDMTransformerClass via adaLNAdjusted by model size
VQGAN + TransformerQuantized latent (strongly compressed)Autoregressive TransformerPrepended tokensNeeds a large model

Since LDM is a diffusion model, generation still passes through the network once per step. To reduce the number of steps, combine it with a sampler such as DDIM.

Rough guidelines for choosing are as follows.

  • To train and generate high-resolution images with limited compute: LDM is a good fit.
  • To generate images from text or layouts: LDM (Stable Diffusion and others), which can inject conditions via cross-attention, is a good fit.
  • To scale up the noise-prediction network for better performance: DiT, which replaces the U-Net with a Transformer in the same latent space, is also a candidate.
  • When pixel-level accuracy matters most: Also consider pixel-space diffusion models that do not go through an autoencoder.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
One training step of Latent Diffusion by Rombach et al. (2022) (Eq. 3) and cross-attention inside the U-Net (Section 3.3).
encoder and decoder are an autoencoder trained beforehand and frozen; unet is a network that returns eps_theta(z_t, t, context).
Noise is added the same way as in DDPM (T = 1000, linear beta)
"""

T = 1000
betas = torch.linspace(1e-4, 0.02, T)
alpha_bars = torch.cumprod(1.0 - betas, dim=0)


class CrossAttention(nn.Module):
  """Q comes from the U-Net feature phi_i(z_t); K and V come from the condition representation tau_theta(y)"""
  def __init__(self, dim, context_dim, heads=8):
    super().__init__()
    # nn.MultiheadAttention can set the input dims of K and V separately via kdim/vdim. batch_first=True gives (B, length, dim)
    self.attn = nn.MultiheadAttention(dim, heads, kdim=context_dim, vdim=context_dim, batch_first=True)
    self.norm = nn.LayerNorm(dim)

  def forward(self, h, context):
    B, C, H, W = h.shape
    q = h.flatten(2).transpose(1, 2)                   # flatten the feature map to (B, H*W, C)
    out, _ = self.attn(self.norm(q), context, context)  # softmax(Q K^T / sqrt(d)) V
    return h + out.transpose(1, 2).reshape(B, C, H, W)  # add as a residual and restore the original shape


def ldm_training_step(encoder, unet, text_encoder, images, tokens, scale, optimizer):
  """Eq. 3: predict the noise added to the latent z_t. encoder (E) is frozen; unet and text_encoder (tau_theta) are trained"""
  with torch.no_grad():
    z0 = encoder(images) / scale                       # divide KL-reg. latents by the std to bring the variance to 1
  t = torch.randint(1, T + 1, (z0.size(0),), device=z0.device)
  eps = torch.randn_like(z0)
  ab = alpha_bars.to(z0.device)[t - 1].view(-1, 1, 1, 1)
  zt = ab.sqrt() * z0 + (1 - ab).sqrt() * eps          # apply DDPM's noising to the latent
  context = text_encoder(tokens)                       # tau_theta(y): (B, M, d_tau)
  loss = F.mse_loss(unet(zt, t, context), eps)
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
  return loss.item()


@torch.no_grad()
def decode(decoder, z0, scale):
  """Undo the scale normalization of the generated latent, then pass it once through decoder D to get an image"""
  return decoder(z0 * scale)


# Example running only cross-attention: inject a length-77, 768-dim condition into a 64-channel 8×8 feature map
block = CrossAttention(dim=64, context_dim=768)
h = torch.randn(2, 64, 8, 8)
context = torch.randn(2, 77, 768)
out = block(h, context)                                  # same shape as the input (2, 64, 8, 8)

FAQ

Q. Are Latent Diffusion and Stable Diffusion the same thing?
A.

Latent Diffusion is the name of a method (a paper) for training diffusion models in latent space. Stable Diffusion is a text-to-image model trained with this method on a subset of LAION-5B and released publicly. According to the official repository, it consists of an autoencoder that downsamples height and width to 1/8, an 860M-parameter U-Net, and a frozen CLIP ViT-L/14 text encoder.

Q. Why does diffusing in latent space make things faster?
A.

Because the noise-predicting network runs on a latent downsampled to 1/f1/f in height and width, rather than on the pixel image. For example, with f=8f = 8, height and width each shrink to 1/8, so the number of positions handled drops to 1/64. The tens to hundreds of generation iterations also run on this small latent, and a single pass through the decoder at the end turns it back into an image. In the paper's inpainting experiments, it was at least 2.7 times faster than the pixel-space model.

Q. What downsampling factor f is best?
A.

In the paper's comparison, f=4f = 4 to 1616 gave a good balance of speed and quality, with f=4f = 4 and 88 performing especially well. At f=1,2f = 1, 2, the diffusion model has to handle fine details too, so training is slow; at f=32f = 32, information is lost and quality plateaus. For complex data such as ImageNet, avoiding excessive compression preserves quality.

References

  1. Rombach, R., Blattmann, A., Lorenz, D., Esser, P., & Ommer, B. (2022). High-Resolution Image Synthesis with Latent Diffusion Models. CVPR 2022. arXiv:2112.10752.
  2. CompVis. Stable Diffusion (official repository).
  3. Ho, J., Jain, A., & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. NeurIPS 2020. arXiv:2006.11239.