Diffusion for Images

Dive into Deep Learning · §17.4

Image Diffusion Architectures, Evaluation, and Guidance
multi-scale U-Net · time & class conditioning · EMA weights · Fréchet distance & 1/n floor · classifier-free guidance (CFG)

Scaling Diffusion from the 2D Plane to 784-D Images

Motivation

  • 1. Multi-resolution U-Net: Global 28 \times 28 receptive field at high noise (t \to 1) and full-resolution skip connections at low noise (t \to 0).
  • 2. Weight EMA & label dropout: EMA damps minibatch SGD noise; 10\% random label dropout trains conditional and unconditional fields in one network.
  • 3. Calibrated FD & Classifier-Free Guidance (CFG): Benchmark 5{,}000 samples against the 1/n real-vs.-real floor, and extrapolate from \mathbf{u}_\varnothing to \mathbf{u}_c at scale \gamma.

The Time- and Class-Conditioned Denoising U-Net

Multi-Resolution Backbone

A stack of full-resolution 3 \times 3 convolutions would need 14 layers just for one pixel’s receptive field to span 28 pixels. The U-Net (Ronneberger et al., 2015; Ho et al., 2020) combines coarse global context with fine spatial skip connections:

  • Encoder–decoder hierarchy: Two stride-2 convolutions halve resolution twice (28 \times 28 \to 14 \times 14 \to 7 \times 7) while doubling channels (64 \to 128), so a 3 \times 3 kernel at the bottleneck sees most of the image.
  • Full-resolution skip connections: Concatenating encoder feature maps to decoder stages preserves sharp edges that the 7 \times 7 bottleneck would blur.
  • Per-block conditioning (UNetBlock): GroupNorm (8 groups, avoiding cross-noise-level batch mixing) + SiLU + 3 \times 3 conv, adding a linear projection of the time-plus-label embedding as a per-channel bias.

Where Parameters Live vs. Where FLOPs Are Spent

Systems Profile of the U-Net

  • Low resolution holds the capacity: The 14 \times 14 and 7 \times 7 stages hold 80\% of the 1.20\text{M} parameters (38\% in the 7 \times 7 bottleneck for just 8\% of the compute).
  • Full resolution dominates the arithmetic: The 28 \times 28 blocks hold 18\% of the weights but consume 57\% of the 266\text{M} MACs (about 15\times more compute per weight than 7 \times 7).

Where Parameters Live vs. Where FLOPs Are Spent (Code)

Systems Profile of the U-Net

torch.manual_seed(0)
dev = d2l.try_gpu()
net = UNet(ch=64, num_classes=10).to(dev)
levels = {28: ['inc', 'down1', 'up0', 'outc'], 14: ['pool1', 'down2', 'up1'],
          7: ['pool2', 'mid']}  # the blocks whose output has each size
for side, names in levels.items():
    params = [p for n in names for p in getattr(net, n).parameters()]
    kernels = sum(p.numel() for p in params if p.dim() == 4)  # convolutions
    print(f'{side} x {side}: {sum(p.numel() for p in params):,} parameters, '
          f'{kernels * side ** 2 / 1e6:.0f}M multiply-adds per image')
print(f'total: {d2l.num_params(net):,} parameters')
28 x 28: 211,329 parameters, 152M multiply-adds per image
14 x 14: 493,376 parameters, 92M multiply-adds per image
7 x 7: 459,776 parameters, 22M multiply-adds per image
total: 1,198,913 parameters

Joint Conditioning via Random Label Dropout

One Network, Two Vector Fields

\mathcal{L}(\boldsymbol\theta) = \mathbb{E}_{\mathbf{x}_0, c, t, \boldsymbol\epsilon}\Big[\big\|\mathbf{u}_{\boldsymbol\theta}\big((1-t)\mathbf{x}_0 + t\boldsymbol\epsilon,\; t,\; \tilde{c}\big) - (\boldsymbol\epsilon - \mathbf{x}_0)\big\|^2\Big]

  • Null label token (\varnothing = 10): In every minibatch of 128 images, 10\% of class labels are randomly replaced with \varnothing = 10, row 11 of an 11 \times emb_dim label-embedding table.
  • Shared representation: One U-Net learns both the class-conditional velocity \mathbf{u}_{\boldsymbol\theta}(\mathbf{x}_t, t, c) (90\%) and unconditional velocity \mathbf{u}_{\boldsymbol\theta}(\mathbf{x}_t, t, \varnothing) (10\%) with zero parameter overhead.

Training Cost vs. Sampling Cost in Image Diffusion

Training Dynamics & Compute Budget

We train our 1.2\text{M}-parameter U-Net with Adam (\text{lr} = 10^{-3}, batch size 128, EMA half-life 1{,}000) for 15{,}000 updates:

  • Rapid convergence to the velocity floor: Per-pixel velocity MSE drops from \approx 0.50 to \approx 0.20 within the first 1{,}000 steps and plateaus at the conditional variance floor.
  • Why sampling can cost more than training: 15{,}000 updates process 1.92\text{M} training images (\approx 5.8\text{M} forward-equivalent passes), whereas generating the 5{,}000-image evaluation suites in this section takes \approx 20\text{M} U-Net evaluations (3.5\times the training arithmetic).

Class-Conditional Garment Generation in 50 Steps

Euler ODE Samples

Integrating the EMA U-Net velocity field with 50 Euler steps (ode_sample on the linear path) generates 40 class-conditioned garments (one class per column):

Coarse-to-Fine Trajectory: Shape Early, Detail Late

Inspecting the Implied Clean Image Along Time

The velocity implies a clean-image posterior mean \hat{\mathbf{x}}_0(\mathbf{x}_t) = \mathbf{x}_t - t\,\mathbf{u}_{\boldsymbol\theta}(\mathbf{x}_t, t, c); forward noising (rows 1–2) vs. a 50-step reverse trajectory (row 3) shows when structure forms:

  • At pure noise (t = 1.0): Knowing only the label “Ankle boot”, the MSE-optimal prediction \hat{\mathbf{x}}_0 is the blurred class-mean boot (\textrm{RMS} = 0.07 from class mean).
  • Outline commits by t = 0.6: Even when the state \mathbf{x}_{0.6} is 60\% Gaussian noise, \hat{\mathbf{x}}_0 has already locked onto the final sample’s silhouette (\textrm{RMS} \le 0.14 from the finished t = 0 sample).
  • Late steps (t < 0.4): Refine high-frequency edges, shading, and texture.

RMS from the image: 0.00 0.07 0.11 0.16 0.24 0.43
RMS from the class mean: 0.46 0.46 0.45 0.43 0.36 0.07
RMS from the sample: 0.00 0.03 0.07 0.12 0.19 0.32

Exponential Moving Average (EMA) of Model Weights

Stabilizing Stochastic Gradient Iterates

\bar{\boldsymbol\theta}_k = \beta_{\textrm{EMA}}\,\bar{\boldsymbol\theta}_{k-1} + (1 - \beta_{\textrm{EMA}})\,\boldsymbol\theta_k, \qquad \beta_{\textrm{EMA}} = 2^{-1 / n_{1/2}}

  • Half-life parameterization (n_{1/2} = 1{,}000): Weights from 1{,}000 updates ago carry half the weight of the current iterate (\beta_{\textrm{EMA}} \approx 0.9993), damping random minibatch (t, \boldsymbol\epsilon) jitter.
  • Sizing n_{1/2} to the budget: Too short retains SGD noise; too long drags in underfit early weights.

Evaluating Sample Distributions: Fréchet Distance

Wasserstein-2 Distance in Classifier Features

Pixel-space Euclidean distance fails to measure perceptual quality (shifting a sneaker by 2 pixels produces a huge L_2 error). The Fréchet distance (FD) (Heusel et al., 2017) fits Gaussians \mathcal{N}(\boldsymbol\mu_p, \boldsymbol\Sigma_p) and \mathcal{N}(\boldsymbol\mu_q, \boldsymbol\Sigma_q) to 128-D features extracted by a domain classifier (FeatureCNN, about 93\% test accuracy):

\mathrm{FD}(p, q) = \underbrace{\|\boldsymbol\mu_p - \boldsymbol\mu_q\|^2}_{\text{mean shift (e.g., class skew)}} + \underbrace{\operatorname{tr}\!\Big(\boldsymbol\Sigma_p + \boldsymbol\Sigma_q - 2\big(\boldsymbol\Sigma_p^{1/2}\boldsymbol\Sigma_q\boldsymbol\Sigma_p^{1/2}\big)^{1/2}\Big)}_{\text{covariance mismatch (e.g., mode collapse or blur)}}

def fd_and_agreement(cnn, imgs, f_ref):
    """FD to the reference features, and the fraction of samples that the
    feature network assigns to the requested class i % 10."""
    f = fd_features(cnn, imgs)
    cls = cnn.head(f.to(imgs.device)).argmax(1)
    agree = (cls == torch.arange(len(imgs), device=cls.device) % 10)
    return d2l.fid_score(f, f_ref), agree.float().mean().item()

fd_ema, agree_ema = fd_and_agreement(cnn, generate(ema), f_test[:5000])
print(f'5,000 samples: FD {fd_ema:.2f}, class agreement {agree_ema:.3f}')
5,000 samples: FD 0.82, class agreement 0.880

Calibrating FD: The 1/n Finite-Sample Floor

Why Raw FD Numbers Require a Reference Scale

  • Why disjoint real sets score > 0: Sample covariances fluctuate by O(1/\sqrt{n}), creating an upward +O(1/n) bias through (\boldsymbol\Sigma_p^{1/2}\boldsymbol\Sigma_q\boldsymbol\Sigma_p^{1/2})^{1/2}.
  • Two iron laws: (1) Never compare FD across different sample sizes n (real floor drops 5\times from 0.87 at n = 1{,}000 to 0.17 at n = 5{,}000); (2) ignore differences smaller than the multi-seed noise floor (\pm 0.05 at n = 5{,}000).

Calibrating FD: The 1/n Finite-Sample Floor (Code)

Why Raw FD Numbers Require a Reference Scale

f_real = fd_features(cnn, X[:25_000])  # five disjoint sets of 5,000
for n in (1000, 5000):
    sets = [f_real[i * n:(i + 1) * n] for i in range(5)]
    fd = np.array([float(d2l.fid_score(f, f_test[:n])) for f in sets])
    kid = np.array([float(d2l.kid_score(f, f_test[:n])) for f in sets])
    print(f'{n:,} real images, five sets: FD {fd.mean():.2f} '
          f'({fd.min():.2f} to {fd.max():.2f}), KID {kid.mean():.4f} '
          f'({kid.min():.4f} to {kid.max():.4f})')
1,000 real images, five sets: FD 0.88 (0.82 to 0.96), KID 0.0053 (-0.0070 to 0.0227)
5,000 real images, five sets: FD 0.17 (0.15 to 0.19), KID -0.0018 (-0.0051 to 0.0023)

Paired Ablation: EMA Weights vs. 1,000-Step Chain

Measuring EMA and Step Count on Shared Noise

On three shared draws of 5{,}000 noise tensors: 50 Euler steps on the EMA weights (ema) and on the raw final iterate (net), and 1,000 ancestral VP steps (via make_pred):

for seed in range(3):  # three draws of the initial noise
    fd = [fd_and_agreement(cnn, generate(model, sampler=sampler, seed=seed),
                           f_test[:5000])[0]
          for model, sampler in ((ema, euler50), (net, euler50),
                                 (ema, ancestral1000))]
    print(f'noise {seed}: Euler 50 average {fd[0]:.2f}, last weights '
          f'{fd[1]:.2f} ({fd[1] - fd[0]:+.2f}); chain with 1,000 steps '
          f'{fd[2]:.2f} ({fd[2] - fd[0]:+.2f})')
noise 0: Euler 50 average 0.82, last weights 1.36 (+0.55); chain with 1,000 steps 0.69 (-0.13)
noise 1: Euler 50 average 0.84, last weights 1.46 (+0.63); chain with 1,000 steps 0.66 (-0.18)
noise 2: Euler 50 average 0.83, last weights 1.36 (+0.53); chain with 1,000 steps 0.68 (-0.15)
  • EMA provides a massive \approx +0.5 FD win: In every draw, raw final weights score \approx 1.3–1.5 vs. \approx 0.8 for EMA, while EMA varies by only \pm 0.02 across noise seeds.
  • 1,000-step ancestral chain gains \approx 0.15 FD: Achieves \approx 0.65 FD at 20\times the compute cost of 50 Euler steps (motivating the fast higher-order solvers of §17.5).

Bayes’ Rule on Scores and Classifier Guidance

Steering Generation Toward a Class

How can we push samples more strongly toward class c than the standard conditional distribution p_t(\mathbf{x} \mid c)? Writing Bayes’ rule at noise level t, p_t(\mathbf{x} \mid c) = p_t(\mathbf{x})\,p_t(c \mid \mathbf{x}) / p(c), and taking \nabla_{\mathbf{x}} \log(\cdot) eliminates the prior p(c):

\nabla_{\mathbf{x}} \log p_t(\mathbf{x} \mid c) = \nabla_{\mathbf{x}} \log p_t(\mathbf{x}) + \nabla_{\mathbf{x}} \log p_t(c \mid \mathbf{x})

  • Classifier guidance (Dhariwal & Nichol, 2021): Amplifies the log-likelihood gradient of an external noise-aware classifier p_{\boldsymbol\phi}(c \mid \mathbf{x}, t) by a guidance scale \gamma \ge 0: \tilde{\mathbf{s}}(\mathbf{x}, t, c) = \nabla_{\mathbf{x}} \log p_t(\mathbf{x}) + \gamma\,\nabla_{\mathbf{x}} \log p_{\boldsymbol\phi}(c \mid \mathbf{x}, t)
  • Drawback of external classifier guidance: Requires training a separate noise-conditioned classifier p_{\boldsymbol\phi}(c \mid \mathbf{x}_t, t) across all t \in [0, 1], and ascending \nabla_{\mathbf{x}} \log p_{\boldsymbol\phi} can exploit adversarial classifier directions.

Classifier-Free Guidance (CFG): Implicit Steering

Eliminating the External Classifier

\tilde{\mathbf{u}}(\mathbf{x}, t, c) = \mathbf{u}_{\boldsymbol\theta}(\mathbf{x}, t, \varnothing) + \gamma\,\big(\mathbf{u}_{\boldsymbol\theta}(\mathbf{x}, t, c) - \mathbf{u}_{\boldsymbol\theta}(\mathbf{x}, t, \varnothing)\big)

  • Implicit Bayes classifier gradient (Ho & Salimans, 2022): Inverts Bayes’ rule so \nabla_{\mathbf{x}}\log p_t(c \mid \mathbf{x}) = \mathbf{s}_c(\mathbf{x}, t) - \mathbf{s}_\varnothing(\mathbf{x}, t).
  • Universal dictionary invariance: Because (1 - \gamma) + \gamma = 1, the exact same linear extrapolation applies identically to \hat{\mathbf{x}}_0, \hat{\boldsymbol\epsilon}, \hat{\mathbf{v}}, score, and velocity predictions.

Geometry and Batched Implementation of CFG

Extrapolating Beyond the Conditional Mean

For \gamma > 1, \hat{\mathbf{x}}_0^\gamma = \hat{\mathbf{x}}_0^\varnothing + \gamma(\hat{\mathbf{x}}_0^c - \hat{\mathbf{x}}_0^\varnothing) extrapolates past the class posterior mean:

def cfg(net, c, gamma):
    """Classifier-free guidance: (x, t) -> u + gamma (u_c - u), u unlabeled.

    gamma is a Python number; at gamma = 1 this is conditional(net, c)."""
    if gamma == 1:
        return d2l.conditional(net, c)
    null = torch.full_like(c, net.num_classes)
    def guided(x, t):  # one doubled batch: labeled, then unlabeled
        out_c, out = net(torch.cat([x, x]), torch.cat([t, t]),
                         torch.cat([c, null])).chunk(2)
        return out + gamma * (out_c - out)
    return guided
  • Doubled batch per step: For \gamma \neq 1, cfg concatenates [\mathbf{x}, \mathbf{x}] with labels [c, \varnothing], doubling per-step compute (100 U-Net passes for 50 Euler steps).

The Guidance Trade-Off: Diversity vs. Typicality

5,000 samples per guidance scale γ, shared noise

Guidance trades coverage (FD) for class adherence:

gamma 0.00: FD  2.74, class agreement 0.099
gamma 1.00: FD  0.82, class agreement 0.880
gamma 1.25: FD  0.84, class agreement 0.931
gamma 1.50: FD  1.13, class agreement 0.962
gamma 2.00: FD  2.05, class agreement 0.985
gamma 3.00: FD  4.07, class agreement 0.997
gamma 4.00: FD  5.86, class agreement 0.999
  • \gamma = 0: agreement at chance (10%), FD near 2.7.
  • \gamma \approx 1: lowest FD (about 0.8); agreement near 90\%, close to the feature network’s 93\% on real test images.
  • \gamma \ge 3: agreement above 99\%, but FD rises to 4–6 as samples collapse onto class prototypes.

Visualizing Unconditional (γ = 0) vs. Guided (γ = 4)

Canonical Prototypes vs. Ambiguous Samples

The same 40 initial noises at \gamma = 0 (left) and \gamma = 4 (right) show why people often prefer high \gamma despite its worse FD:

Diagnosing the Unconditional (γ = 0) FD Degradation

Class Skew vs. Within-Class Sample Quality

Why is the unconditional FD (\gamma = 0, \mathrm{FD} \approx 2.75) more than three times higher than the conditional FD (\gamma = 1, \mathrm{FD} \approx 0.82)? We test whether skewed class proportions explain the gap:

gamma 0.0: mean term 0.71 of FD 2.74
gamma 1.0: mean term 0.28 of FD 0.82
    T-shirt: test images 0.101, gamma 0 0.097
    trouser: test images 0.099, gamma 0 0.080
   pullover: test images 0.102, gamma 0 0.144
      dress: test images 0.102, gamma 0 0.097
       coat: test images 0.099, gamma 0 0.100
     sandal: test images 0.099, gamma 0 0.074
      shirt: test images 0.096, gamma 0 0.104
    sneaker: test images 0.103, gamma 0 0.095
        bag: test images 0.100, gamma 0 0.099
 ankle boot: test images 0.098, gamma 0 0.111
real images, uniform class mix: mean term 0.04 of FD 0.19
real images, gamma 0 class mix: mean term 0.13 of FD 0.38
  • Class skew accounts for < 15\% of the gap: Although \gamma = 0 overproduces pullovers (13\%–14\%) and underproduces sandals (6\%–7\%), resampling 5{,}000 real images to that exact skewed histogram raises real FD by only 0.2–0.3 (from 0.19 to 0.4–0.5).
  • The true cause (> 85\% of the gap): Trained on only 10\% of minibatches without class hints, \mathbf{u}_{\boldsymbol\theta}(\mathbf{x}_t, t, \varnothing) produces more ambiguous, blended garments—and its errors enter every guided step with weight (1 - \gamma).

Theory: Why Guided ODE Trajectories Overshoot the Tilt

Exact Analysis on Gaussian Classes

\frac{1}{v} = \frac{\gamma}{s^2} - \frac{\gamma - 1}{S^2} > \frac{1}{s^2}, \qquad \boldsymbol\mu_{\textrm{tilt}} = \frac{\gamma v}{s^2}\,\boldsymbol\mu_c

  • Static tilt vs. dynamic ODE overshoot (\mu_c = 1, s = 0.5, S^2 = 2, \gamma = 4):
    • Static t = 0 tilted density \tilde{p}_0 \propto p_0^{1-\gamma}p_0(\cdot \mid c)^\gamma narrows width 2\times (0.50 \to 0.26) and shifts mean to 1.10.
    • Integrating the guided ODE from t = 1 \to 0 shrinks width about 23\times to 0.02 and shifts the mean to 1.23.

Why High-Noise Guidance Breaks the Curvature Bound

Path Inconsistency & Modern Remedies

  • Gaussian convolution curvature ceiling: Any valid marginal density p_t = p_0 * \mathcal{N}(\mathbf{0}, \sigma_t^2\mathbf{I}) obeys -\nabla^2\log p_t(\mathbf{x}) \preceq (1/\sigma_t^2)\mathbf{I}.
  • Violation at high noise: For \gamma > S^2/(S^2 - s^2) = 8/7, the guided precision 1/v_t exceeds 1/t^2 near t = 1 (violating the bound across t \in (0.24, 1] at \gamma = 4).
  • Modern remedies: Apply \gamma > 1 only in a middle guidance interval (Kynkäänniemi et al., 2024) or use autoguidance against a weaker conditional model (Karras et al., 2024).

Concept Check: Receptive Fields, FD Floors & CFG

Check Your Understanding

Test your grasp of U-Net design, Fréchet distance calibration, and classifier-free guidance:

  1. U-Net downsampling vs. receptive field: Each 3 \times 3 convolution expands a pixel’s receptive field by 2 pixels (1 + 2k after k layers). How many layers k are needed to span 28 pixels at full resolution vs. the 7 \times 7 bottleneck?
  2. Comparing FDs across sample sizes: Model A achieves \mathrm{FD} = 0.85 evaluated on n = 1{,}000 images; Model B achieves \mathrm{FD} = 0.80 evaluated on n = 5{,}000 images (using the same FeatureCNN). Which model is closer to the real distribution?
  3. Gaussian guidance calculation: For class \mathcal{N}(1, 0.5^2) inside \mathcal{N}(0, 2) at guidance scale \gamma = 2, what are the static tilted variance v, standard deviation \sqrt{v}, and mean?

Answers:

  1. At 28 \times 28, 1 + 2k \ge 28 \implies \mathbf{k = 14} layers. At 7 \times 7 (where each site covers a 4 \times 4 patch), 1 + 2k \ge 7 \implies \mathbf{k = 3} layers.
  2. Model A is much better: At n = 1{,}000, the real-vs.-real reference floor is \approx 0.87, so Model A (0.85) is indistinguishable from real data. At n = 5{,}000, the real floor is \approx 0.17, so Model B (0.80) is nearly 5\times above the floor.
  3. 1/v = \gamma/s^2 - (\gamma - 1)/S^2 = 2/0.25 - 1/2 = 7.5 \implies v = 2/15 \approx 0.133 (width \sqrt{v} \approx \mathbf{0.37} < 0.5), and \text{mean} = \gamma v / s^2 = 2(2/15)/0.25 \approx \mathbf{1.07} > 1.

Summary: Image Diffusion, Evaluation, and Guidance

Key Takeaways

Component Mechanism / Formula Quantitative Finding on Fashion-MNIST Best-Practice Guideline
Denoising U-Net 28 \to 14 \to 7 encoder–decoder + skips 80\% params at low res; 57\% MACs at 28 \times 28 Put channel capacity at low resolution; use GroupNorm
Weight EMA \bar{\boldsymbol\theta} \leftarrow \bar{\boldsymbol\theta} + (1 - 2^{-1/n_{1/2}})(\boldsymbol\theta - \bar{\boldsymbol\theta}) Lowers FD by 0.45–0.55 vs. final iterate Always sample from EMA weights (n_{1/2} \approx 10^3–10^4)
Fréchet Distance (FD) \|\boldsymbol\mu_p - \boldsymbol\mu_q\|^2 + \operatorname{tr}(\boldsymbol\Sigma_p + \boldsymbol\Sigma_q - 2(\boldsymbol\Sigma_p^{1/2}\boldsymbol\Sigma_q\boldsymbol\Sigma_p^{1/2})^{1/2}) Real floor drops 5\times from 0.87 (1\text{k}) to 0.17 (5\text{k}) Always report sample size n and real-vs.-real floor
Label Dropout Replace label c \leftarrow \varnothing with p_{\textrm{drop}} = 0.1 Trains \mathbf{u}_c (90\%) and \mathbf{u}_\varnothing (10\%) jointly p_{\textrm{drop}} \in [0.1, 0.2] suffices for the unconditional baseline
Classifier-Free Guidance \tilde{\mathbf{u}} = \mathbf{u}_\varnothing + \gamma(\mathbf{u}_c - \mathbf{u}_\varnothing) \gamma = 1.25 lifts agreement 89\% \to 94\% at flat FD Mild \gamma \approx 1.25 for distribution FD; \gamma > 2 for typicality