Post

Diffusion Models - Fundamentals

Diffusion Models - Fundamentals

Diffusion models (DDPMs and score-based SDEs) are generative models that learn to reverse a gradual noising process, turning noise into data. They have become state of the art for high-fidelity image, audio, and video synthesis.

Intuition

  • Forward: gradually add Gaussian noise to data until it becomes near-isotropic Gaussian.
  • Reverse: learn a denoiser/score network that removes a little noise at each time step.

Forward (Diffusion) Process

Define noise variances \(\{\beta_t\}_{t=1}^T\) with \(\alpha_t = 1-\beta_t\) and \(\bar\alpha_t = \prod_{s=1}^t \alpha_s\).

At each step: \(q(x_t\mid x_{t-1}) = \mathcal{N}\big(\sqrt{\alpha_t}\, x_{t-1},\; (1-\alpha_t)\, I\big).\) Closed form (conditioning on $x_0$): \(x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1-\bar\alpha_t}\, \epsilon,\quad \epsilon \sim \mathcal{N}(0, I).\)

Reverse (Denoising) Process and Training

Parameterize the reverse distribution as: \(p_\theta(x_{t-1}\mid x_t) = \mathcal{N}\big(\mu_\theta(x_t,t),\; \sigma_t^2 I\big),\) with the simplified training objective that predicts the noise $\epsilon$ directly: \(\mathcal{L}(\theta) = \mathbb{E}_{t,\,x_0,\,\epsilon}\Big[\;\big\|\,\epsilon - \epsilon_\theta\big(x_t, t\big)\,\big\|_2^2\;\Big],\quad x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1-\bar\alpha_t}\, \epsilon.\) Popular parameterizations:

  • $\epsilon$-prediction (noise prediction; common in Stable Diffusion)
  • $x_0$-prediction (predict clean data)
  • $v$-prediction (linear combo improving stability)

Sampling (DDPM / DDIM)

Ancestral DDPM sampling iteratively draws $x_{t-1} \sim p_\theta(x_{t-1}\mid x_t)$. DDIM provides a deterministic sampler: \(\hat{x}_0 = \frac{x_t - \sqrt{1-\bar\alpha_t}\,\epsilon_\theta(x_t,t)}{\sqrt{\bar\alpha_t}},\quad x_{t-1} = \sqrt{\bar\alpha_{t-1}}\,\hat{x}_0 + \sqrt{1-\bar\alpha_{t-1}}\,\hat{\epsilon}.\)

Guidance (Controllable Generation)

  • Classifier guidance: use an external classifier $p(y\mid x)$ to nudge the score.
  • Classifier-free guidance (CFG): use conditional/unconditional predictions: \(\hat{\epsilon} = \epsilon_{\text{uncond}} + w\,\big(\epsilon_{\text{cond}} - \epsilon_{\text{uncond}}\big),\quad w \ge 0.\)

Noise Schedules and Variants

  • Linear, cosine, or learned $\beta_t$ schedules
  • Score-based SDEs: continuous-time formulation with predictor–corrector samplers
  • Latent Diffusion (LDM): operate in VAE latent space; enables high-res synthesis (e.g., Stable Diffusion)
  • Conditioning: text (cross-attention), class labels, ControlNets for structure guidance

Minimal PyTorch Training Sketch (Noise Prediction)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Pseudocode
import torch
from torch import nn

class UNet(nn.Module):
    def __init__(self):
        super().__init__()
        # define a small UNet/ResNet here (omitted)
    def forward(self, x_t, t_embed):
        return torch.zeros_like(x_t)  # epsilon_theta(x_t, t)

# precompute alpha_bar[t]
alpha_bar = torch.linspace(1.0, 0.0001, steps=1000)  # placeholder schedule

model = UNet()
optim = torch.optim.AdamW(model.parameters(), lr=1e-4)

for x0 in dataloader:  # x0 in [-1, 1]
    t = torch.randint(1, len(alpha_bar), (x0.size(0),))
    ab = alpha_bar[t].view(-1, 1, 1, 1)
    eps = torch.randn_like(x0)
    x_t = (ab.sqrt()) * x0 + (1 - ab).sqrt() * eps

    t_embed = t  # use sinusoidal/time embedding in practice
    eps_pred = model(x_t, t_embed)
    loss = (eps - eps_pred).pow(2).mean()

    optim.zero_grad(); loss.backward(); optim.step()

Practical Tips

  • Normalize inputs to $[-1, 1]$; use cosine schedule or well-tuned linear schedule
  • Use EMA of weights for sampling; gradient clipping; mixed precision
  • Set $T$ (timesteps) larger for training (e.g., 1000) and use fast samplers at inference
  • For text-to-image, train in latent space (LDM) with cross-attention conditioning

Evaluation

  • FID (lower is better), precision/recall for fidelity/diversity
  • CLIP score (text–image alignment), aesthetic scores when applicable

References

  • Denoising Diffusion Probabilistic Models (Ho et al., 2020)
  • Denoising Diffusion Implicit Models (DDIM; Song et al., 2021)
  • Score-Based Generative Modeling through SDEs (Song et al., 2021)
  • High-Resolution Image Synthesis with Latent Diffusion Models (Rombach et al., 2022)
This post is licensed under CC BY 4.0 by the author.