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}')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
Motivation
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):
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)
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), klMeasuring 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):

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.
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
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

FD: pixel U-Net 1.54, latent U-Net 2.07
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}):
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
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
ae_10 to only \mathrm{FD} \approx 1.3 (whereas the \beta = 10^{-4} decoder jumps to \mathrm{FD} > 3.0).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.Replacing Convolutions with Sequence Attention
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).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)
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.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)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}
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
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
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).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:
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.Architectural Decision Matrix
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
Check Your Understanding
Test your understanding of latent diffusion autoencoders and Diffusion Transformers:
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:
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.Check Your Understanding
Answer:
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 |