Diffusion Models: Learning to Undo Noise
Deconstruct modern Denoising Diffusion Probabilistic Models (DDPM) and Latent Diffusion Models (LDM): forward Markov noise schedules, reverse denoising networks, classifier-free guidance, noise schedulers, and U-Net vs DiT backbones.
Contentsand lesson path
On this page
Lessons of Autoencoders & Generative Models
- Squeeze and Rebuild: What Autoencoders Learn Concept · 20 min
- Lab: Denoising and Anomaly Detection with an Autoencoder Lab · 30 min
- From Reconstruction to Generation: VAEs and GANs Concept · 25 min
- Diffusion Models: Learning to Undo Noise Concept · 25 min
- Lab: Generate, Adapt with LoRA and Evaluate a Diffusion Model Lab · 30 min
- Check: Choosing and Judging a Generative Model Knowledge check · 8 questions
What you will learn
- Explain how a diffusion model learns to reverse a noising process, and generate images with a pretrained latent diffusion pipeline while controlling the scheduler, number of steps, guidance scale and seed.
Prerequisites: Deep Learning Fundamentals
01. Denoising Diffusion Probabilistic Models and Latent Diffusion
Over the past several years, diffusion models have emerged as the dominant paradigm for high-fidelity generative modeling across computer vision, audio synthesis, protein folding, and multimodal systems. While GANs rely on precarious adversarial games and VAEs often suffer from blurry reconstructions, Denoising Diffusion Probabilistic Models (DDPM) (Sohl-Dickstein et al. 2015, Ho et al. 2020) formulate generation as an iterative physical process inspired by non-equilibrium thermodynamics: systematically destroying structure through a forward Gaussian noise schedule, and training a neural network to invert that destruction step-by-step.
- The Forward Diffusion Process ($q$): Given a clean data point $x_0 \sim q(x_0)$, the forward process is a fixed, non-trainable Markov chain that incrementally injects Gaussian noise across $T$ discrete timesteps (commonly $T = 1,000$) according to a variance schedule $\beta_1, \beta_2, \dots, \beta_T \in (0, 1)$:
$$q(x_t \mid x_{t-1}) = \mathcal{N}\left(x_t; \sqrt{1 - \beta_t} x_{t-1}, \beta_t I\right)$$
Crucially, by defining $\alpha_t = 1 - \beta_t$ and the cumulative product $\bar{\alpha}t = \prod{s=1}^t \alpha_s$, we can jump directly from clean input $x_0$ to any arbitrary noisy state $x_t$ in closed form without simulating intermediate steps:
$$x_t = \sqrt{\bar{\alpha}_t} x_0 + \sqrt{1 - \bar{\alpha}_t} \epsilon, \quad \text{where } \epsilon \sim \mathcal{N}(0, I)$$
As $t \to T$, $\bar{\alpha}_t \to 0$, causing $x_T$ to become virtually indistinguishable from pure isotropic Gaussian noise $\mathcal{N}(0, I)$.
- The Reverse Denoising Process ($p_\theta$): To generate a new image from scratch, we sample pure noise $x_T \sim \mathcal{N}(0, I)$ and trace the reverse trajectory step-by-step back to $x_0$. Although the true reverse distribution $q(x_{t-1} \mid x_t)$ is intractable, it can be approximated by a neural network parameterizing Gaussian transitions $p_\theta(x_{t-1} \mid x_t) = \mathcal{N}(x_{t-1}; \mu_\theta(x_t, t), \Sigma_\theta(x_t, t))$. Rather than predicting the clean image $x_0$ directly, Ho et al. showed that training the network $\epsilon_\theta(x_t, t)$ to predict the exact noise vector $\epsilon$ that was added yields superior empirical visual quality:
$$\mathcal{L}{\text{simple}}(\theta) = \mathbb{E}{t \sim \mathcal{U}(1, T), x_0, \epsilon \sim \mathcal{N}(0, I)}\left[|\epsilon - \epsilon_\theta(x_t, t)|^2_2\right]$$
-
Noise Schedulers and Accelerated Sampling: The original DDPM sampling procedure requires iterating through all $T = 1,000$ reverse steps, resulting in prohibitive inference latency (e.g., 10 to 30 seconds per image). Modern production pipelines employ advanced differential equation solvers:
- DDIM (Denoising Diffusion Implicit Models): Formulates a non-Markovian forward process sharing the same marginal distributions, allowing deterministic sampling in just 20 to 50 steps.
- DPM-Solver / UniPC: High-order numerical ODE solvers that generate photorealistic samples in as few as 10 to 25 evaluation steps.
-
Classifier-Free Guidance (CFG): In conditional generation (e.g., text-to-image), models often ignore complex prompt nuances or produce low-contrast outputs. Classifier-Free Guidance (Ho & Salimans, 2021) trains a single network on both conditioned inputs $\epsilon_\theta(x_t, t, c)$ and unconditioned inputs $\epsilon_\theta(x_t, t, \emptyset)$ by randomly dropping the prompt conditioning token $c$ (e.g., with 10% probability during training). During inference, the predicted noise is extrapolated:
$$\tilde{\epsilon}\theta(x_t, t, c) = \epsilon\theta(x_t, t, \emptyset) + s \cdot \left(\epsilon_\theta(x_t, t, c) - \epsilon_\theta(x_t, t, \emptyset)\right)$$
The guidance scale $s \ge 1.0$ (typically $7.0$ to $8.5$) magnifies the prompt-aligned gradient direction away from generic unconditioned generations, dramatically sharpening image composition and adherence to text.
-
Latent Diffusion Models (LDM / Stable Diffusion): Running high-dimensional convolution operations directly in pixel space (e.g., $512 \times 512 \times 3 = 786,432$ values) requires immense GPU memory and compute. Rombach et al. (2022) solved this via Latent Diffusion Models: an autoencoder (specifically an autoencoding VAE) pre-trained with perceptual and adversarial loss compresses the pixel image into a compact latent tensor $z_0 \in \mathbb{R}^{4 \times 64 \times 64}$. The diffusion and reverse denoising processes operate entirely within this compressed latent space, reducing spatial dimensionality by a factor of 48 while preserving high-frequency semantic details. Once the reverse latent diffusion completes, the VAE decoder decodes the final latent $z_0$ back into high-resolution pixel space in a single forward pass.
-
Backbone Architectures: U-Net vs Diffusion Transformers (DiT): While early models employed convolutional U-Nets augmented with self-attention and cross-attention blocks, modern architectures (such as Stable Diffusion 3, Flux, and Sora) utilize Diffusion Transformers (DiT). DiT divides latent representations into visual patches and processes them with standard transformer layers, enabling predictable compute scaling and superior compositional synthesis.
-
Continuous-Time Score SDEs and Probability Flow ODEs: Yang Song et al. (2020) unified diffusion models under the framework of Stochastic Differential Equations (SDEs). The forward process becomes an Itô SDE $dx = f(x, t) dt + g(t) dw$, and its reverse-time counterpart solves:
$$dx = \left[f(x, t) - g(t)^2 \nabla_x \log p_t(x)\right] dt + g(t) d\bar{w}$$
The denoising network directly parameterizes the score function: $\nabla_x \log p_t(x) \approx -\frac{\epsilon_\theta(x_t, t)}{\sqrt{1 - \bar{\alpha}_t}}$. Furthermore, every diffusion SDE possesses an associated deterministic Probability Flow ODE sharing identical marginal distributions. This enables deterministic inversion, allowing practitioners to project real images back into latent noise for high-precision semantic image editing.
-
Rectified Flow and Straight Trajectory Matching: Traditional diffusion processes trace curved, stochastic trajectories in data space, requiring dozens of integration steps to avoid discretization drift. Next-generation foundational models leverage Flow Matching and Rectified Flow (Lipman et al., Albergo et al.). By defining straight linear interpolation paths between data and noise $x_t = (1 - t) x_0 + t x_1$ with constant target velocity $v_t = x_1 - x_0$, networks learn straight vector fields that can be solved accurately in as few as 2 to 4 Euler steps, slashing production inference latency by over 80%.
-
Vector Arithmetic in Negative Prompting: Classifier-Free Guidance naturally generalizes to negative prompting: $\tilde{\epsilon} = \epsilon_\emptyset + s_{\text{pos}}(\epsilon_{\text{pos}} - \epsilon_\emptyset) - s_{\text{neg}}(\epsilon_{\text{neg}} - \epsilon_\emptyset)$. By computing an unconditioned vector subtraction against negative keywords (e.g., "blurry, mutated hands, watermarks"), the sampling trajectory repels away from unwanted probability modes, providing fine-grained directional control over the synthesized output.
import torch
import numpy as np
def linear_beta_schedule(timesteps=1000, beta_start=0.0001, beta_end=0.02):
return torch.linspace(beta_start, beta_end, timesteps)
# Precompute cumulative variance factors
betas = linear_beta_schedule(1000)
alphas = 1.0 - betas
alphas_cumprod = torch.cumprod(alphas, dim=0)
def forward_sample(x_0, t, noise=None):
if noise is None:
noise = torch.randn_like(x_0)
sqrt_alpha_bar = torch.sqrt(alphas_cumprod[t]).view(-1, 1, 1, 1)
sqrt_one_minus_alpha = torch.sqrt(1.0 - alphas_cumprod[t]).view(-1, 1, 1, 1)
return sqrt_alpha_bar * x_0 + sqrt_one_minus_alpha * noise, noise
def apply_classifier_free_guidance(noise_cond, noise_uncond, guidance_scale=7.5):
# Extrapolate toward the conditioned prompt prediction
return noise_uncond + guidance_scale * (noise_cond - noise_uncond)
# Test closed-form forward sampling at step t=500
mock_img = torch.zeros((1, 3, 64, 64))
noisy_img, injected = forward_sample(mock_img, torch.tensor([500]))
print(f"Noisy shape: {noisy_img.shape}, Injected noise std: {injected.std():.4f}")
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.