Latent Diffusion and Transformers

Dive into Deep Learning · §17.7

Latent Diffusion and Diffusion Transformers (DiT)
perceptual compression (VAE) · rate–distortion–modelability · latent rescaling · patch tokens & adaLN-Zero · U-Net vs. DiT scaling

Why Pixel-Space Diffusion Hits a Compute Wall

Motivation

  • Quadratic & quartic spatial scaling: A 512 \times 512 \times 3 image has 786{,}432 values (1{,}000\times more than 28 \times 28); self-attention scales as (HW)^2 across all 50 sampling steps.
  • Imperceptible high-frequency bits: Most pixel dimensions carry fine grain that human viewers barely notice.
  • Two breakthroughs: Compress via a perceptual autoencoder into latents (Rombach et al., 2022) and replace U-Nets with patch-token Diffusion Transformers (Peebles & Xie, 2023).

Perceptual vs. Semantic Compression

The Latent Diffusion Pipeline

Latent diffusion factors image generation into a frozen perceptual autoencoder (\mathcal{E}, \mathcal{D}) and a latent diffusion model trained on \mathbf{z}_0 = \mathcal{E}(\mathbf{x}_0):

  • Spatial compression ratios:
    • Our Fashion-MNIST benchmark: 28 \times 28 \times 1 (784 pixels) \to 7 \times 7 \times 4 (196 latents, 4\times compression, 16\times fewer spatial positions).
    • Stable Diffusion: 512 \times 512 \times 3 (786{,}432 values) \to 64 \times 64 \times 4 (16{,}384 latents, 48\times compression, 64\times fewer spatial positions).
  • The three-way trade-off (Dieleman, 2025):
    • Rate: Number of latent dimensions (196).
    • Distortion: Reconstruction loss of the decoder \mathcal{D}(\mathcal{E}(\mathbf{x}_0)) vs. \mathbf{x}_0.
    • Modelability: How easily the diffusion model learns the latent distribution.

Regularizing the Autoencoder Latent Space

Why Plain Autoencoders Fail for Diffusion

\mathcal{L}_{\textrm{AE}}(\mathbf{x}) = \frac{1}{784}\|\mathbf{x} - \mathcal{D}(\mathbf{z})\|^2 + \frac{\beta}{196}\sum_{j=1}^{196} \frac{1}{2}\big(\mu_j^2 + s_j^2 - 1 - \log s_j^2\big)

  • Three requirements for diffusable latents: (1) unit scale matching \boldsymbol\epsilon \sim \mathcal{N}(\mathbf{0}, \mathbf{I}), (2) no heavy-tailed outliers, and (3) a smooth decoding manifold via \mathbf{z} = \boldsymbol\mu + \mathbf{s} \odot \boldsymbol\xi.
  • Light KL weighting (\beta = 10^{-4}): Anchors scale near 1 and prevents posterior collapse (s_j \to 0) while preserving sharp reconstructions.

Implementing the KL-Regularized Autoencoder

Residual Convolutional Encoder and Decoder

Our Autoencoder downsamples 28 \times 28 \times 1 \to 14 \times 14 \to 7 \times 7 \times 8 (splitting into 4 mean and 4 clamped log-variance channels) and mirrors the hierarchy in the decoder:

class Autoencoder(nn.Module):
    def encode(self, x):
        mean, log_var = self.encoder(x).chunk(2, dim=1)
        return mean, log_var.clamp(-30, 20)

    def forward(self, x):
        mean, log_var = self.encode(x)
        z = mean + (0.5 * log_var).exp() * torch.randn_like(mean)
        kl = 0.5 * (mean ** 2 + log_var.exp() - 1 - log_var).mean()
        return self.decoder(z), kl

Autoencoder Reconstructions & Distortion Reference

Measuring Reconstruction Quality on Fashion-MNIST

We train our residual convolutional Autoencoder (2.4\text{M} parameters) for 20{,}000 cosine-decayed Adam updates at \beta = 10^{-4} and score 5{,}000 test reconstructions against the 5{,}000-image real-vs.-real FD floor (0.17):

x_hat = d2l.batched(lambda x: ae.decoder(ae.encode(x)[0]), X_test[5000:])
fd_rec = fd(x_hat)
print(f'reconstructions: squared error {((x_hat - X_test[5000:]) ** 2).mean():.4f}'
      f' per pixel, FD {fd_rec:.2f}')
reconstructions: squared error 0.0038 per pixel, FD 0.69

The reconstruction reference (\mathrm{FD} \approx 0.65–0.80): If a latent diffusion model generated the encoder’s exact latent distribution, decoding its samples would yield this reconstruction FD.

Calibrating Latent Scale and Tail Kurtosis

Matching the Unit-Variance Noise Schedule

encoded = d2l.batched(lambda x: torch.cat(ae.encode(x), 1), X)
mu, log_var = encoded.chunk(2, dim=1)       # mean and log variance
s = (0.5 * log_var).exp()
z = mu + s * torch.randn_like(mu)
scale = 1 / z.std().item()
kurtosis = (((z - z.mean()) * scale) ** 4).mean() - 3
print(f'latent std {z.std():.2f} (scale factor {scale:.2f}), encoder std '
      f'{s.mean():.3f}, excess kurtosis {kurtosis:.2f}')
latent std 0.94 (scale factor 1.06), encoder std 0.026, excess kurtosis -0.20
  • Mandatory scale factor c = 1/\mathrm{std}(\mathbf{z}): Unscaled latents of std \varsigma shift log-SNR by +\log \varsigma^2 (Stable Diffusion’s \varsigma \approx 5.5 uses c = 0.18215 to avoid a +3.4\text{ nat} shift).
  • Sub-Gaussian tails: Excess kurtosis \le 0 confirms the KL penalty eliminated heavy-tailed outliers.

Pixel U-Net vs. Latent U-Net: Quality and FLOPs

Running Identical Flow Matching in Latent Space

With rescaled latents \mathbf{z}_0 = c\,(\boldsymbol\mu + \mathbf{s} \odot \boldsymbol\xi) \in \mathbb{R}^{4 \times 7 \times 7}, the velocity regression loss \mathbb{E}\|\mathbf{u}_{\boldsymbol\theta}(\mathbf{z}_t, t) - (\boldsymbol\epsilon - \mathbf{z}_0)\|^2 and 50-step Euler ODE sampler run unchanged:

GFLOP per training step: latent U-Net 15, pixel U-Net 203
  • >13\times compute reduction per step: The latent U-Net (7 \times 7 input) requires only \approx 12–15\text{ GFLOP} per training step vs. \approx 200\text{ GFLOP} for the pixel U-Net (28 \times 28 input).
  • The modelability gap at 28 \times 28: Decoded latent samples score \mathrm{FD} \approx 2.0–2.2 vs. \approx 1.5 for the pixel U-Net and \approx 0.7 for autoencoder reconstructions.

FD: pixel U-Net 1.54, latent U-Net 2.07

Diagnosing the Latent Gap: Decoder vs. Diffusion Error

Testing a 10× Stronger KL Weight (β = 10⁻³)

Why do decoded latent diffusion samples score \mathrm{FD} \approx 2.0 when reconstructions score \approx 0.7? We test two competing hypotheses by training a second autoencoder ae_10 with 10\times higher KL weight (\beta = 10^{-3}):

  • Hypothesis A: Decoder intolerance: At \beta = 10^{-4}, the encoder blurs codes by only \mathbf{s}/\mathrm{std}(\boldsymbol\mu) \approx 3\%, so the decoder might shatter slightly off-manifold latents produced by the diffusion model.
  • Hypothesis B: Latent diffusion modeling error: The diffusion U-Net itself makes large distributional errors on the compressed 7 \times 7 \times 4 latent code.
beta 0.0001
  encoder std 0.028, reconstructions: error 0.0038, FD 0.69
  sigma 0.1: change 0.0023 per pixel, FD 0.55
  sigma 0.3: change 0.0205 per pixel, FD 0.71
  sigma 0.5: change 0.0545 per pixel, FD 3.46
beta 0.001
  encoder std 0.194, reconstructions: error 0.0041, FD 0.96
  sigma 0.1: change 0.0027 per pixel, FD 0.87
  sigma 0.3: change 0.0232 per pixel, FD 0.54
  sigma 0.5: change 0.0619 per pixel, FD 1.33

Perturbation Tolerance vs. End-to-End Sample Quality

Dieleman’s Modelability Trade-Off in Action

Training two latent U-Nets (seeds 10, 11) on each autoencoder’s latents settles which hypothesis drives the gap:

beta 0.0001: latent U-Net FD 2.04 and 2.02
beta 0.001: latent U-Net FD 2.78 and 2.68
  • \beta = 10^{-3} makes the decoder tolerant to random noise: Adding \sigma = 0.5 Gaussian noise to real test latents degrades ae_10 to only \mathrm{FD} \approx 1.3 (whereas the \beta = 10^{-4} decoder jumps to \mathrm{FD} > 3.0).
  • Yet \beta = 10^{-3} yields worse end-to-end diffusion samples (\mathrm{FD} \approx 2.7 vs. 2.1): Because a 50\% random latent perturbation on ae_10 costs only 1.3 FD while trained latent U-Nets score about 2.7, the gap is latent diffusion modeling error, not decoder fragility.
  • Takeaway: Keep the autoencoder KL weight light (\beta = 10^{-4}) so reconstructions stay sharp and latent channels remain easy to model.

Diffusion Transformers (DiT): Patchifying Images

Replacing Convolutions with Sequence Attention

  • Patch tokenization (PatchEmbedding): A stride-p, p \times p conv partitions H \times W \times C into L = (H/p)(W/p) tokens of dim d (L = 49 for 28 \times 28 pixels at p = 4, or 7 \times 7 latents at p = 1).
  • Quadratic attention governed by p: Self-attention scales as L^2 = (HW/p^2)^2 (p = 1 on 28 \times 28 pixels costs 256\times more attention FLOPs than p = 4).
  • Linear unpatchify head: Projects each token \mathbb{R}^d \to \mathbb{R}^{p^2 C} and reshapes back to (H, W, C).

Conditioning Transformers via adaLN-Zero

Adaptive Layer Norm with Zero-Initialized Gates

How should time t and class label y steer every Transformer block? Peebles & Xie (2023) found that adaptive layer normalization with zero-initialized gates (adaLN-Zero) outperforms cross-attention and token concatenation:

\mathbf{X} \leftarrow \mathbf{X} + \mathbf{g}_1 \odot \mathrm{Attn}\!\Big(\mathrm{LN}(\mathbf{X}) \odot (\mathbf{1} + \mathbf{a}_1) + \mathbf{b}_1\Big)

\mathbf{X} \leftarrow \mathbf{X} + \mathbf{g}_2 \odot \mathrm{MLP}\!\Big(\mathrm{LN}(\mathbf{X}) \odot (\mathbf{1} + \mathbf{a}_2) + \mathbf{b}_2\Big)

  • Six modulation vectors per block: A linear layer on \mathrm{SiLU}(\mathbf{c}) outputs (\mathbf{b}_1, \mathbf{a}_1, \mathbf{g}_1, \mathbf{b}_2, \mathbf{a}_2, \mathbf{g}_2) \in \mathbb{R}^{6d} shared across all L tokens.
  • Identity initialization (Zero): Initializing the ada linear layers and final output projection to zero sets \mathbf{g}_1 = \mathbf{g}_2 = \mathbf{0}, so every block starts as an exact identity map and the untrained network outputs \mathbf{0} everywhere.

Implementing DiTBlock with adaLN-Zero

Extending ViTBlock with Zero-Initialized Modulation

DiTBlock disables the built-in affine parameters of LayerNorm and predicts six modulation vectors (shift1, scale1, gate1, shift2, scale2, gate2) from the condition vector c:

class DiTBlock(d2l.ViTBlock):
    """ViTBlock with adaLN-Zero: the condition c sets a shift, a scale and a
    gate for each sublayer; the gates start at zero."""
    def __init__(self, num_hiddens, mlp_num_hiddens, num_heads):
        super().__init__(num_hiddens, mlp_num_hiddens, num_heads, dropout=0.0,
                         use_bias=True)
        ln = lambda: nn.LayerNorm(num_hiddens, elementwise_affine=False,
                                  eps=1e-6)
        self.norm1, self.norm2 = ln(), ln()
        self.ada = nn.Sequential(nn.SiLU(),
                                 nn.Linear(num_hiddens, 6 * num_hiddens))
        nn.init.zeros_(self.ada[1].weight), nn.init.zeros_(self.ada[1].bias)

    def forward(self, X, c):
        shift1, scale1, gate1, shift2, scale2, gate2 = (
            self.ada(c)[:, None].chunk(6, dim=-1))
        X_mod = self.norm1(X) * (1 + scale1) + shift1
        X = X + gate1 * self.attention(X_mod, X_mod, X_mod)
        return X + gate2 * self.ffn(self.norm2(X) * (1 + scale2) + shift2)

Text Conditioning: Cross-Attention vs. Multimodal DiT

Conditioning on Variable-Length Token Sequences

\mathrm{CrossAttn}(\mathbf{Y}, \mathbf{X}_{\textrm{text}}) = \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}}\right)\mathbf{V} \in \mathbb{R}^{m \times d}

  • Cross-attention lookup (Rombach et al., 2022): Image tokens supply queries \mathbf{Q}; frozen text embeddings supply keys/values \mathbf{K}, \mathbf{V} (precomputed once per prompt outside the 50-step sampling loop).
  • Joint Multimodal DiT (MM-DiT; Esser et al., 2024): Concatenates m image and n text tokens into one sequence of length m + n for bidirectional self-attention in every block.

Verifying DiT Shapes, Parameters, and Zero Init

Weight Reuse in Convolutions vs. Transformers

Passing a batch of 8 images through our 6-block, width-256 DiT (patch_size = 4, 4 heads) verifies token shapes and exact zero initialization:

dit = d2l.DiT().to(dev)       # width 256, depth 6, 4 heads, 4 x 4 patches
x, t = X[:8], torch.rand(8, device=dev)
with torch.no_grad():
    tokens, out = dit.patch(x), dit(x, t)
print('images', tuple(x.shape), '-> tokens', tuple(tokens.shape),
      '-> output', tuple(out.shape))
print(f'parameters: DiT {d2l.num_params(dit) / 1e6:.2f}M, '
      f'U-Net {d2l.num_params(d2l.UNet(ch=64)) / 1e6:.2f}M')
print('output at initialization all zero:', bool((out == 0).all()))
images (8, 1, 28, 28) -> tokens (8, 49, 256) -> output (8, 1, 28, 28)
parameters: DiT 7.39M, U-Net 1.20M
output at initialization all zero: True
  • Why DiT-M has 6\times more parameters (7.39\text{M}) than U-Net (1.20\text{M}) at similar FLOPs: Full-resolution U-Net convolutions reuse a tiny 3 \times 3 kernel across 28 \times 28 = 784 spatial positions, whereas DiT applies large d \times 4d dense matrices across only L = 49 patch tokens.

Scaling Comparison: U-Net vs. DiT on Pixel Diffusion

Parameters vs. GFLOPs per Step on Fashion-MNIST

We train two Transformer sizes (DiT-S: width 128, depth 4; DiT-M: width 256, depth 6) and two U-Net widths (ch = 32 and ch = 64) on pixels for 20{,}000 updates across two seeds each:

DiT-S     1.26M parameters   32 GFLOP per step   FD 4.82, 4.83
DiT-M     7.39M parameters  185 GFLOP per step   FD 1.89, 1.89
U-Net 32  0.34M parameters   51 GFLOP per step   FD 2.47, 2.52
U-Net 64  1.20M parameters  203 GFLOP per step   FD 1.54, 1.51
  • At small scale, convolutional inductive bias wins: DiT-S (1.26\text{M} params) matches U-Net 64 (1.20\text{M} params) in parameter count but scores 3\times higher FD (\approx 4.7 vs. 1.5).
  • Steeper compute scaling slope for DiT: Scaling DiT compute 5.8\times cuts FD by 2.7\times (4.7 \to 1.8), whereas scaling U-Net compute 4\times cuts FD by 1.65\times (2.5 \to 1.5).

Visualizing Samples Across Backbones and Scales

Comparing DiT-S, DiT-M, U-Net 32, and U-Net 64

Eight samples from the same initial noise in all four pixel models show their ODE trajectories align:

  • Shared ODE mapping: In almost every column, both DiTs and both U-Nets map the same initial noise to the same garment and pose: all four approximate the same probability-flow ODE.
  • Why human eyes need FD: While 8 thumbnails look visually comparable between row 1 (DiT-S, \mathrm{FD} \approx 4.7) and row 4 (U-Net 64, \mathrm{FD} \approx 1.5), FD over 5{,}000 samples detects subtle edge distortion and covariance drift.

Combining Latents and Transformers: When Each Wins

Architectural Decision Matrix

  • Low resolution (\le 64^2): Use Pixel U-Net; pixel FLOPs are cheap and avoid the autoencoder modelability gap (\mathrm{FD} \approx 1.5 vs. 2.0).
  • High resolution (512^2+) at scale: Use Latent DiT (p=2); cuts spatial positions 64\times while Transformer tokens scale cleanly with GFLOPs.
  • Large-patch pixel DiTs (Li & He, 2026): Predict clean \hat{\mathbf{x}}_0 to project out high-D orthogonal noise.

Combining Latents and Transformers: When Each Wins (Code)

Architectural Decision Matrix

torch.manual_seed(8)
net = d2l.DiT(img_size=7, patch_size=1, num_channels=4,
              **sizes['DiT-M']).to(dev)
_, dit_latent, _ = d2l.train_regression(net, loss_fn, latent_batch_fn, 20_000)
gflops = d2l.train_step_gflops(net, loss_fn, latent_shape)
print(f'latent DiT-M, {gflops:.0f} GFLOP per step: FD '
      f'{fd(decode(sample(dit_latent, latent_shape))):.2f}; latent U-Net '
      f'{fd_latent:.2f}; reconstructions {fd_rec:.2f}')
latent DiT-M, 185 GFLOP per step: FD 1.89; latent U-Net 2.07; reconstructions 0.69

Concept Check: Latent Scaling, adaLN-Zero & Tokens

Check Your Understanding

Test your understanding of latent diffusion autoencoders and Diffusion Transformers:

  1. Stable Diffusion’s 0.18215 scale factor: Stable Diffusion multiplies its autoencoder latents by c = 0.18215 before adding unit-variance Gaussian noise. What was the raw latent standard deviation \varsigma, and by how many nats would skipping c shift the log-SNR \lambda_t?
  2. Partial zero initialization in DiT: Suppose every DiTBlock’s ada gate starts at zero, and the final norm modulation starts at zero, except the final linear output layer self.out uses standard random initialization. What does the untrained DiT output at time t?

Answers:

  1. Raw latent std was \varsigma = 1 / 0.18215 \approx \mathbf{5.49} (variance \varsigma^2 \approx 30.1). Skipping c inflates signal variance 30\times at every t, shifting \lambda_t upward by +\log(30.1) \approx \mathbf{+3.4\text{ nats}}.
  2. Every DiTBlock computes the exact identity (\mathbf{g}_1 = \mathbf{g}_2 = \mathbf{0}), so the network outputs self.out(self.ln(patch(x) + pos))—a nonzero linear projection of the normalized input patches that is completely independent of time t.

Concept Check: Latent Scaling, adaLN-Zero & Tokens (cont.)

Check Your Understanding

  1. Token count and attention scaling at 1024 \times 1024: Using an 8\times downsampling autoencoder and 2 \times 2 latent patches (p = 2), how many tokens L does a DiT process on a 1024 \times 1024 image compared to 512 \times 512, and by what factor does self-attention cost increase?

Answer:

  1. The latent grid is 128 \times 128 \times 4, so p = 2 yields L = 64^2 = \mathbf{4{,}096\text{ tokens}} (4\times the 1{,}024 tokens at 512^2), increasing quadratic self-attention cost O(L^2) by 16\times.

Summary: Latent Diffusion and Transformer Backbones

Key Takeaways

Component / Concept Mathematical / Architectural Form Empirical Finding in §17.7 Design Recommendation
Perceptual Autoencoder \frac{1}{d}\|\mathbf{x} - \hat{\mathbf{x}}\|^2 + \frac{\beta}{d_z}D_{\mathrm{KL}}(\mathcal{N}(\boldsymbol\mu, \mathbf{s}^2) \,\|\, \mathcal{N}(\mathbf{0}, \mathbf{I})) \beta = 10^{-4} gives \mathrm{FD}_{\textrm{rec}} \approx 0.7, kurtosis \le 0 Keep KL weight light (\beta \approx 10^{-4}) to preserve modelability
Latent Rescaling \mathbf{z}_0 = c\,(\boldsymbol\mu + \mathbf{s} \odot \boldsymbol\xi), \quad c = 1 / \mathrm{std}(\mathbf{z}) c \approx 1.05 here (c = 0.18215 in Stable Diffusion) Mandatory so latent signal variance matches unit noise \boldsymbol\epsilon
Latent U-Net (7 \times 7 \times 4) Standard velocity flow matching on \mathbf{z}_t Cuts step compute 13\text{--}17\times (200 \to 12\text{ GFLOP}) Essential for high-resolution (512^2+) convolutional models
DiT Patchification Stride-p conv \to L = (H/p)(W/p) tokens p = 4 maps 28 \times 28 to L = 49 tokens (16 pixels each) Choose p to balance quadratic O(L^2) attention vs. patch dim
adaLN-Zero Modulation \mathbf{X} + \mathbf{g} \odot f\big(\mathrm{LN}(\mathbf{X}) \odot (\mathbf{1} + \mathbf{a}) + \mathbf{b}\big) Untrained output is identically \mathbf{0}; stabilizes deep DiTs Zero-initialize all conditioning gates and final output layer
U-Net vs. DiT Scaling Convolutional hierarchy vs. isotropic tokens U-Net wins at \le 200\text{ GFLOP}; DiT has steeper slope Use U-Net at small budgets; use DiT when scaling compute