CS58700 - Foundations of Deep Learning¶

Spring 2026¶

Instructor and Copyright: Bruno Ribeiro¶


(Generative) Diffusion Models¶

In this lecture we will cover the theoretical foundations, the mathematical formulation, and the practical implementation details of generative diffusion models.

Task:

  • Unsupervised learning:
  • Training data: $\mathcal{D}^\text{(tr)} = \{(x_i^\text{(tr)})\}_{i=1}^{N^\text{(tr)}}$ sampled from $p(x)$.
  • Goal: Output new samples from $p(x)$ (Implicit generative model)

1. Introduction to Diffusion Models¶

1.1. Definitions¶

  • Diffusion models are similar to VAEs as it tries to optimize an objective function by
    1. first projecting the data onto a random noise space: $\text{input} \to \text{noise}$
    2. Then, $\text{noise} \to \text{output}$ (producing the output from this noise).
  • The difference is that diffusion models aim to model a series of noise distributions in a Markov Chain and denoises the data in a sequential fashion.

Input and output of diffusion models is similar to VAEs but the method is different

  • Training data: $\{x_i\}^n_{i=1}$ i.i.d. sampled from $p_0(x)$, with $x_i \in \mathbb{R}^L$, and $L \geq 1$.
  • Our Goal: generate data from $p_0(x)$
  • Method: we are using diffusion model of $T$ steps, which includes two processes:

No description has been provided for this image

  1. The forward diffusion process (diffusion process): represented as the dashed arrows; is fixed to a first-order Markov chain, with the given input $X_0 \sim p_0(x)$ that gradually adds Gaussian noise to the data $X_{t-1}$ and obtain $X_{t} \ ($ where $t = (1,2,3,...,T))$

  2. The reverse process: represented as the solid arrows ($q_\theta$); is also defined as a first-order Markov chain that learning the Gaussian noise added in the forward diffusion process and removing it from $X_{t+1}$ to retrieve $X_{t} \ ($ where $t = (T-1,T-2,T-3,...,0))$, starting at $X_T \sim q_T(x_T)$

Also, $X_1, X_2,...,X_T$ in both the diffusion or reverse process are latents as of the same dimensionality as the data $X_0 \sim p_0(x)$, which is $L$.

2. Mathematical Formulation¶

2.1. Forward Diffusion Process¶

  • Given a data point sampled from a real data distribution $X_0 \sim p_0(x)$, the forward process is defined as a first-order Markov chain that progressively adds Gaussian noise to the data. Specifically:

  • The forward diffusion process gradually adds Gaussian noise to an image over $T$ timesteps according to a variance schedule $\{\beta_t\}_{t=1}^T$, where each $\beta_t$ is a scalar in $(0, 1)$ and the sequence is monotonically increasing, i.e., $\beta_1 < \beta_2 < ... < \beta_T$.

    • Gaussian property: Let $X \sim N(\mu,\sigma_x^2)$ and $Y \sim N(\mu,\sigma_y^2)$ be independent random variables that are normally distributed, then if $Z = X + Y$, $Z$ is also normally distributed, where $Z \sim N(\mu,\sigma_x^2+\sigma_y^2)$.
    • Gaussian property: Let $X \sim N (\mu, \sigma^2)$ and $Y = aX + b$, which means $Y$ is a linear transform of X, then $Y$ is also normally distributed, where $Y \sim N (a\mu + b, a^2\sigma^2)$

Q: Can we find a formula for the forward diffusion: $q_t(x_t|x_0)$?¶

A:¶

  • To derive the formula for the forward diffusion $q_t(x_t|x_0)$, let's start by defining $\alpha_t = 1 - \beta_t$ and $\epsilon_{t} \sim N (\mathbf{0}, \mathbf{I})$.
  • By applying the reparameterization trick to $q_t(x_t|x_{t-1})$, we obtain: $$x_t = \sqrt{\alpha_t}x_{t-1}+\sqrt{1-\alpha_t}\epsilon_{t}.$$
  • Using the properties of linear transformations in normal distributions, we find that $\sqrt{\alpha_t}x_{t-1} \sim N(\sqrt{\alpha_t}\cdot\sqrt{\alpha_{t-1}}\mu_{t-1}, \alpha_t(1-\alpha_{t-1})\mathbf{I})$ and $\sqrt{1-\alpha_t}\epsilon_{t} \sim N(\mathbf{0}, (1-\alpha_{t})\mathbf{I})$, where $\mu_{t-1}$ is the mean of $x_{t-1}$.
  • Since $x_{t-1}$ itself can be represented as a transformation of $x_{t-2}$, we can iteratively apply this process.
  • By recursively applying the transformation and use the above properties of Gaussian distributions, we can derive that: $$x_t \sim N(\sqrt{\overline{\alpha}_t}x_0, (1-\overline{\alpha}_t)\mathbf{I}),$$ where $\overline{\alpha}_t = \prod_{s=0}^t\alpha_s$. This step involves recognizing that at each step $t$, the mean of $x_t$ is scaled by $\sqrt{\alpha_t}$ from its previous value, and the variance accumulates additively as $(1-\alpha_t)$ times the identity matrix.
  • Consequently, we can express $q_t(x_t|x_0)$ as: $$q_t(x_t|x_0) = N(\sqrt{\overline{\alpha}_t}x_0, (1-\overline{\alpha}_t)\mathbf{I}).$$

  • Furthermore, solving for $x_0$ in terms of $x_t$, we find: $$x_0 = \frac{1}{\sqrt{\overline{\alpha}_t}} x_t - \frac{\sqrt{1-\overline{\alpha}_t}}{\sqrt{\overline{\alpha}_t}}\epsilon,$$ where $\epsilon \sim N(\mathbf{0}, \mathbf{I})$.

  • This expression for $x_0$ in terms of $x_t$ and $\epsilon$ provides a direct link between the initial data point $x_0$ and its diffusion at time $t$, $x_t$, highlighting the reversibility of the diffusion process.

  • In code, this is implemented in the q_sample function:

def q_sample(x_start, t, noise=None):
    """
    Forward diffusion process: add noise to the images
    """
    if noise is None:
        noise = torch.randn_like(x_start)
        
    sqrt_alphas_cumprod_t = extract(sqrt_alphas_cumprod, t, x_start.shape)
    sqrt_one_minus_alphas_cumprod_t = extract(sqrt_one_minus_alphas_cumprod, t, x_start.shape)
    
    return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise

Properties of Diffusion Models¶

  • Recall: Adding two independent random variables that are normally distributed
    • Let $X \sim N(\mu_x,\sigma_x^2)$ and $Y \sim N(\mu_y,\sigma_y^2)$ be independent random variables that are normally distributed, then if $Z = X + Y$, $Z$ is also normally distributed, where $Z \sim N(\mu_x+\mu_y,\sigma_x^2+\sigma_y^2)$

In diffusion models, the forward process is designed such that as $t$ approaches $T$, the distribution of $x_t$ converges to an isotropic Gaussian: $$\lim_{t \to T} q(x_t|x_0) = \mathcal{N}(\mathbf{0}, \mathbf{I}).$$

This convergence happens because: $$\lim_{t \to T} \bar{\alpha}_t = \lim_{t \to T} \prod_{i=1}^{t}(1-\beta_i) = 0.$$

Assuming a proper schedule for $\beta_t$ that ensures $\prod_{i=1}^{T}(1-\beta_i) \approx 0$.

When $\bar{\alpha}_t \approx 0$, we have: $$x_t \approx \sqrt{1 - \bar{\alpha}_t}\epsilon \approx \epsilon \sim \mathcal{N}(\mathbf{0}, \mathbf{I}).$$

Practical Implications¶

This property has several important implications:

  1. Sampling: We can start the reverse diffusion process from pure Gaussian noise.
  2. Training Objective: The model can be trained to predict the noise component $\epsilon$ from $x_t$.
  3. Finite Time Steps: In practice, $T$ only needs to be large enough to ensure that $\bar{\alpha}_T$ is sufficiently close to zero, typically around 1000 steps.
  4. Distribution Transformation: The diffusion process can be viewed as a transformation from a complex data distribution $p(x_0)$ to a simple isotropic Gaussian distribution $p(x_T) \approx \mathcal{N}(\mathbf{0}, \mathbf{I})$.

2.2 Reverse Diffusion Process¶

As we mentioned above, with $T$ big enough, we have $X_T \sim N({\bf 0}, {\bf I})$.

Let $q_T(x_T) = N(\mathbf{0}, \mathbf{I})$ be the distribtion of $X_T$.

Also, as we introduced, $q_\theta$ is the reverse process distribution

Now, going backwards, can first need to calculate $p_{t-1}(x_{t-1}|x_t, x_0)$ in closed form.¶

  • Applying Bayes' theorem to find the conditional distribution $p_{t-1}(x_{t-1}|x_t, x_0)$, we have: $$p_{t-1}(x_{t-1}|x_t, x_0) = \frac{p_t(x_{t}|x_{t-1}, x_0)p_t(x_{t-1}|x_0)}{p_t(x_t|x_0)} = \frac{p_t(x_{t}|x_{t-1})p_t(x_{t-1}|x_0)}{p_t(x_t|x_0)}.$$ Each term in our expression is a Gaussian distribution:
  1. Forward process transition: $p_t(x_{t}|x_{t-1}) = \mathcal{N}(x_t; \sqrt{\alpha_t}x_{t-1}, \beta_t\mathbf{I})$
  2. Marginal at t-1: $p_t(x_{t-1}|x_0) = \mathcal{N}(x_{t-1}; \sqrt{\overline{\alpha}_{t-1}}x_0, (1-\overline{\alpha}_{t-1})\mathbf{I})$
  3. Marginal at t: $p_t(x_t|x_0) = \mathcal{N}(x_t; \sqrt{\overline{\alpha}_t}x_0, (1-\overline{\alpha}_t)\mathbf{I})$.
  • Hence, we can express these using the probability density function (pdf) of the Normal distribution: \begin{equation} \begin{aligned} p_{t-1}(x_{t-1}|x_t, x_0) &= \frac{[\frac{1}{\sqrt{2\pi\beta_t}}exp(\frac{-1}{2}(\frac{(x_t-\sqrt{\alpha_t}x_{t-1})^2}{\beta_t}))][\frac{1}{\sqrt{2\pi(1-\overline{\alpha}_{t-1})}}exp(\frac{-1}{2}(\frac{(x_{t-1}-\sqrt{\overline{\alpha}_{t-1}}x_0)^2}{1-\overline{\alpha}_{t-1}}))]}{\frac{1}{\sqrt{2\pi(1-\overline{\alpha}_t)}}exp(\frac{-1}{2}(\frac{(x_{t}-\sqrt{\overline{\alpha}_t}x_0)^2}{1-\overline{\alpha}_t}))}\\ &\propto exp(-\frac{1}{2}[\frac{(x_t-\sqrt{\alpha_t}x_{t-1})^2}{\beta_t}+\frac{(x_{t-1}-\sqrt{\overline{\alpha}_{t-1}}x_0)^2}{1-\overline{\alpha}_{t-1}}-\frac{(x_{t}-\sqrt{\overline{\alpha}_t}x_0)^2}{1-\overline{\alpha}_t}])\\ &= exp(-\frac{1}{2}[(\frac{\alpha_t}{\beta_t}+\frac{1}{1-\overline{\alpha}_{t-1}})x_{t-1}^2-(\frac{2\sqrt{\overline{\alpha}_t}}{1-\overline{\alpha}_t}x_0+\frac{2\sqrt{\alpha_t}}{\beta_t}x_t)x_{t-1}+f(x_t,x_0)])\\ &= exp(-\frac{1}{2}[(\frac{\alpha_t}{\beta_t}+\frac{1}{1-\overline{\alpha}_{t-1}})x_{t-1}^2-2(\frac{\sqrt{\overline{\alpha}_t}}{1-\overline{\alpha}_t}x_0+\frac{\sqrt{\alpha_t}}{\beta_t}x_t)x_{t-1}+f(x_t,x_0)]),\\ \end{aligned} \end{equation} where $f(x_t,x_0)$ contains terms that don't depend on $x_{t-1}$.

  • The quadratic form in the exponent shows that $p_{t-1}(x_{t-1}|x_t, x_0)$ is Gaussian. By completing the square, we can express it as:

$$p_{t-1}(x_{t-1}|x_t, x_0) = \mathcal{N}(x_{t-1}; \tilde{\mu}_t(x_t, x_0), \tilde{\beta}_t\mathbf{I})$$

with $$ \tilde{\beta}_t = \frac{1}{\frac{\alpha_t}{\beta_t}+\frac{1}{1-\overline{\alpha}_{t-1}}} = \frac{\beta_t(1-\overline{\alpha}_{t-1})}{\alpha_t+\alpha_t\overline{\alpha}_{t-1}+\beta_t} = \frac{1-\overline{\alpha}_{t-1}}{1-\overline{\alpha}_t}\beta_t $$ and $$ \tilde{\mu}_t(x_t,x_0) = \frac{\frac{\sqrt{\overline{\alpha}_{t}}}{1-\overline{\alpha}_{t}}x_0 + \frac{\sqrt{\alpha_t}}{\beta_t}x_t}{\frac{\alpha_t}{\beta_t}+\frac{1}{1-\overline{\alpha}_{t-1}}} = \frac{\sqrt{\overline{\alpha}_{t-1}}\beta_t}{1-\overline{\alpha}_{t}}x_0 + \frac{\sqrt{\alpha_t}(1-\overline{\alpha}_{t-1})}{1-\overline{\alpha}_{t}}x_t.$$

-Thus, $p_{t-1}(x_{t-1}|x_t, x_0) = N(\tilde{\mu}_t(x_t,x_0), \tilde{\beta}_t\mathbf{I})$, providing the conditional distribution of $x_{t-1}$ given $x_t$ and $x_0$.

  • In sampling, this can be implemented in this p_sample function:
@torch.no_grad()
def p_sample(model, x, t, t_index):
    """
    Sample x_{t-1} from x_t and the model at timestep t
    """
    betas_t = extract(betas, t, x.shape)
    sqrt_one_minus_alphas_cumprod_t = extract(sqrt_one_minus_alphas_cumprod, t, x.shape)
    sqrt_recip_alphas_t = extract(sqrt_recip_alphas, t, x.shape)
    
    # Convert t to float and normalize
    t_normalized = t.float() / time_steps
    
    # Equation 11 in the DDPM paper
    model_mean = sqrt_recip_alphas_t * (
        x - betas_t * model(x, t_normalized) / sqrt_one_minus_alphas_cumprod_t
    )
    
    if t_index == 0:
        return model_mean
    else:
        posterior_variance_t = extract(posterior_variance, t, x.shape)
        noise = torch.randn_like(x)
        return model_mean + torch.sqrt(posterior_variance_t) * noise

2.2.1. Learning a reverse proposal $p_\theta(x_{t-1}|x_t)$ that does not need $x_0$.¶

  • With $x_t$ and $x_{t-1}$ in hands
  • Consider now a neural network with a proposal distribution $$p_\theta(x_{t-1} | x_t) = \mathcal{N}(x_{t-1}; \mu_\theta(x_t, t), \beta_t \mathbf{I}),$$ where: $$\mu_\theta(x_t, t) = \frac{1}{\sqrt{\alpha_{t}}}\left(x_t - \frac{\beta_t}{\sqrt{1-\overline{\alpha}_t}}\epsilon_\theta(x_t,t)\right).$$

Training Objective¶

  • The training objective is to predict the noise that was added during the forward process, so we can undo it.
  • Since $$x_t = \sqrt{\alpha_t}x_{t-1}+\sqrt{1-\alpha_t}\epsilon_{t},$$ for a randomly sampled timestep $t$, the model is trained to predict $\epsilon_t$ from $x_t$ using the loss: $$\mathcal{L} = \mathbb{E}_{t, x_0, \epsilon_t} \left[ \|\epsilon_t - \epsilon_\theta(\sqrt{\alpha_t}\mathbf{x}_0 + \sqrt{1 - \alpha_t}\epsilon_t, t)\|^2 \right]$$ This is implemented in the p_losses function:
def p_losses(denoise_model, x_start, t, noise=None):
    """
    Calculate the loss for training
    """
    if noise is None:
        noise = torch.randn_like(x_start)
        
    x_noisy = q_sample(x_start, t, noise=noise)
    
    # Convert t to float and normalize
    t_normalized = t.float() / time_steps
    predicted_noise = denoise_model(x_noisy, t_normalized)
    
    return F.mse_loss(predicted_noise, noise)

3. Model Architecture¶

The implementation uses a U-Net architecture, which is common for diffusion models due to its strong performance in image-to-image translation tasks.

3.1 U-Net Structure¶

The U-Net consists of:

  1. A downsampling path that reduces spatial dimensions while increasing feature channels
  2. A bottleneck in the middle
  3. An upsampling path that increases spatial dimensions while decreasing feature channels
  4. Skip connections between corresponding layers in the downsampling and upsampling paths

No description has been provided for this image

3.2 Time Embedding¶

3.2.1 Mathematical Foundation¶

In diffusion models, the neural network must be conditioned on the timestep $t$ to properly reverse the noise addition process. This is because the amount and distribution of noise varies throughout the diffusion process, and the denoising strategy must adapt accordingly.

To formally state this, our model $\epsilon_\theta$ is a function that maps:

$\epsilon_\theta: \mathcal{X} \times \mathcal{T} \rightarrow \mathcal{X}$

Where:

  • $\mathcal{X}$ is the image space
  • $\mathcal{T}$ is the timestep space (an integer from 1 to $T$)

However, the integer timestep $t$ doesn't directly provide a rich representation for neural network conditioning. The solution is to create a higher-dimensional embedding of $t$.

3.2.2 Time Embedding Implementation¶

The implementation uses a Multi-Layer Perceptron (MLP) to project the scalar timestep into a high-dimensional embedding space:

# Time embedding
self.time_embedding = nn.Sequential(
    nn.Linear(1, 128),
    nn.SiLU(),
    nn.Linear(128, 256)
)

The process can be described mathematically as:

$\text{temb}(t) = \text{MLP}(t/T)$

Where:

  • $t$ is the integer timestep
  • $T$ is the total number of timesteps (1000 in this implementation)
  • $\text{MLP}$ is a 2-layer network with SiLU activation

Note that in the code, time is normalized to be in the range $[0, 1]$ before being passed to the embedding network:

# Convert t to float and normalize
t_normalized = t.float() / time_steps

3.2.3 Integration into the Model¶

The time embedding is injected into each residual block of the U-Net:

class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
        self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
        self.time_mlp = nn.Linear(256, out_channels)
        self.skip_connection = nn.Conv2d(in_channels, out_channels, 1) if in_channels != out_channels else nn.Identity()
        
    def forward(self, x, t):
        residual = x
        t = F.silu(self.time_mlp(t))[:, :, None, None]
        x = F.silu(self.conv1(x))
        x = x + t
        x = F.silu(self.conv2(x))
        return x + self.skip_connection(residual)

Mathematically, this operation can be described as:

$h_i = \text{Conv}_i(h_{i-1}) + \text{Project}(\text{temb}(t))$

Where:

  • $h_i$ is the output of layer $i$
  • $\text{Conv}_i$ is the convolutional operation
  • $\text{Project}$ maps the time embedding to the appropriate number of channels via a linear layer
  • $\text{temb}(t)$ is the time embedding

3.2.4 Spatial Adaption¶

The time embedding is initially a vector (batch_size × 256). To add it to the convolutional features, it needs to be adapted to the spatial dimensions:

t = F.silu(self.time_mlp(t))[:, :, None, None]

This applies an additional SiLU activation and reshapes the time features from (batch_size × out_channels) to (batch_size × out_channels × 1 × 1), which is then broadcast to match the spatial dimensions of the convolutional features during the addition operation.

3.2.5 Alternatives to MLP Time Embedding¶

While this implementation uses a simple MLP for time embedding, other approaches include:

  1. Sinusoidal Position Embedding: Similar to Transformer positional encoding, using sine and cosine functions at different frequencies:

$\text{temb}(t)_i = \begin{cases} \sin(t/10000^{2i/d}), & \text{if } i \text{ is even} \\ \cos(t/10000^{2i/d}), & \text{if } i \text{ is odd} \end{cases}$

Where $d$ is the embedding dimension and $i$ ranges from 0 to $d-1$.

  1. Learnable Embedding Table: Directly learn an embedding for each timestep, similar to word embeddings in NLP:

$\text{temb}(t) = E[t]$

Where $E$ is a lookup table of shape $(T, d)$.

The choice of time embedding strategy affects how the model understands the diffusion process and can impact generation quality.

4. Noise Scheduling¶

4.1 Importance of Noise Scheduling¶

The noise schedule is a key component of diffusion models that determines:

  • How quickly information is destroyed during the forward process
  • The difficulty of the reverse denoising task at each timestep
  • The overall sample quality and training stability

Poor noise scheduling can lead to:

  • Mode collapse (if noise is added too quickly)
  • Slow convergence (if noise is added too slowly)
  • Poor sample quality or training instability

4.2 Linear Schedule¶

The implementation uses a linear noise schedule:

# Linear noise schedule
betas = torch.linspace(beta_start, beta_end, time_steps)
alphas = 1 - betas
alphas_cumprod = torch.cumprod(alphas, dim=0)

With hyperparameters:

time_steps = 1000
beta_start = 1e-4
beta_end = 0.02

This creates a sequence of $\beta_t$ values that increases linearly from $10^{-4}$ to $0.02$ over 1000 timesteps.

4.3 Derived Quantities¶

From the basic schedule, several important quantities are derived:

alphas = 1 - betas  # α_t
alphas_cumprod = torch.cumprod(alphas, dim=0)  # ᾱ_t = ∏_{i=1}^{t} α_i
alphas_cumprod_prev = F.pad(alphas_cumprod[:-1], (1, 0), value=1.0)  # ᾱ_{t-1}
sqrt_recip_alphas = torch.sqrt(1.0 / alphas)  # 1/√α_t
sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod)  # √ᾱ_t
sqrt_one_minus_alphas_cumprod = torch.sqrt(1 - alphas_cumprod)  # √(1-ᾱ_t)
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)  # σ²_t

These quantities are used in the forward and reverse diffusion processes:

  • sqrt_alphas_cumprod and sqrt_one_minus_alphas_cumprod are used in the forward process to directly sample $x_t$ given $x_0$.
  • sqrt_recip_alphas and posterior_variance are used in the reverse process to compute the mean and variance for sampling $x_{t-1}$ given $x_t$.

4.4 Alternative Schedules¶

While this implementation uses a linear schedule, several alternatives have been proposed in the literature:

  1. Cosine Schedule: $\bar{\alpha}_t = \cos^2\left(\frac{t/T \cdot \pi}{2}\right)$

    This schedule slows down the diffusion process at both the beginning and end, which can improve sample quality.

  2. Quadratic Schedule: $\beta_t = \beta_{\min} + (\beta_{\max} - \beta_{\min}) \cdot \left(\frac{t}{T}\right)^2$

    This adds noise more gradually at the beginning and more rapidly towards the end.

  3. Sigmoid Schedule: $\beta_t = \beta_{\min} + (\beta_{\max} - \beta_{\min}) \cdot \sigma\left(s \cdot \left(\frac{t}{T} - m\right)\right)$

    Where $\sigma$ is the sigmoid function, $s$ controls the steepness, and $m$ controls the midpoint.

  4. Learned Schedule: Some works have proposed learning the noise schedule along with the model parameters.

5. Sampling Process¶

The sampling process starts from pure noise and iteratively applies the learned reverse diffusion process:

@torch.no_grad()
def p_sample_loop(model, shape):
    """
    Generate samples from the model using the sampling loop
    """
    device = next(model.parameters()).device
    
    b = shape[0]
    # Start with random noise
    img = torch.randn(shape, device=device)
    
    for i in tqdm(reversed(range(0, time_steps)), desc='Sampling loop time step', total=time_steps):
        img = p_sample(model, img, torch.full((b,), i, device=device, dtype=torch.long), i)
        
    return img

6. Training Loop¶

The training loop samples random timesteps for each batch and trains the model to predict the noise:

def train():
    for epoch in range(num_epochs):
        model.train()
        train_loss = 0.0
        
        for batch, (images, _) in enumerate(tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}", leave=False)):
            images = images.to(device)
            batch_size = images.shape[0]
            
            # Sample random timesteps for each image
            t = torch.randint(0, time_steps, (batch_size,), device=device).long()
            
            # Calculate loss
            loss = p_losses(model, images, t)
            
            # Backpropagation
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            
            train_loss += loss.item()

7. Alternatives¶

7.1 Improved Sampling Techniques¶

The provided code implements a basic DDPM sampling approach. Recent advancements include:

  1. DDIM (Denoising Diffusion Implicit Models) - Allows for faster sampling with fewer steps
  2. Classifier Guidance - Uses a classifier to guide the sampling process towards specific classes
  3. PLMS (Pseudo Linear Multistep) - Improves sample quality by using multiple previous estimates

7.2 Conditional Generation¶

The current implementation is unconditional. To extend it to conditional generation:

  1. Modify the U-Net to accept a conditioning vector (e.g., a class embedding)
  2. Incorporate this conditioning into each residual block
  3. Adjust the training and sampling procedures accordingly
In [1]:
# Complete code
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import os
from PIL import Image
from torch.utils.data import Dataset

# Set random seed for reproducibility
torch.manual_seed(42)
np.random.seed(42)

# Ampere+ specific optimizations
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True

# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")

# Hyperparameters
batch_size = 64  # Reduce batch size for larger images
image_size = 128  # CelebA-HQ is typically 1024x1024, but we will resize to 128x128 for performance
channels = 3  # RGB images

time_steps = 1000 # Diffusion time steps
beta_start = 1e-4
beta_end = 0.02
learning_rate = 1e-4
num_epochs = 300
Using device: cpu
In [2]:
# Linear noise schedule
betas = torch.linspace(beta_start, beta_end, time_steps)
alphas = 1 - betas
alphas_cumprod = torch.cumprod(alphas, dim=0)
alphas_cumprod_prev = F.pad(alphas_cumprod[:-1], (1, 0), value=1.0)
sqrt_recip_alphas = torch.sqrt(1.0 / alphas)
sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod)
sqrt_one_minus_alphas_cumprod = torch.sqrt(1 - alphas_cumprod)
posterior_variance = betas * (1. - alphas_cumprod_prev) / (1. - alphas_cumprod)

train_dataset = None
train_loader = None
In [3]:
# CelebA-HQ Dataset
class CelebAHQDataset(Dataset):
    def __init__(self, root_dir, transform=None):
        """
        Args:
            root_dir (string): Directory with all the images.
            transform (callable, optional): Optional transform to be applied on a sample.
        """
        self.root_dir = root_dir
        self.transform = transform
        self.image_files = [f for f in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, f))]
        
    def __len__(self):
        return len(self.image_files)
    
    def __getitem__(self, idx):
        img_name = os.path.join(self.root_dir, self.image_files[idx])
        image = Image.open(img_name).convert('RGB')
        
        if self.transform:
            image = self.transform(image)
            
        return image, 0  # The second value is a dummy label

# Data transformations
transform = transforms.Compose([
    transforms.Resize((image_size, image_size)),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))  # Normalize to [-1, 1]
])

# Load CelebA-HQ dataset
# Change this path to where your CelebA-HQ dataset is stored
celeba_hq_path = './data/celeba_hq/celeba_hq_256'
In [4]:
# Simple Unet model with good capacity for large, more complex images
class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels):
        super().__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1)
        self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
        self.time_mlp = nn.Linear(256, out_channels)
        self.skip_connection = nn.Conv2d(in_channels, out_channels, 1) if in_channels != out_channels else nn.Identity()
        self.norm1 = nn.BatchNorm2d(out_channels)
        self.norm2 = nn.BatchNorm2d(out_channels)
        
    def forward(self, x, t):
        residual = x
        t = F.silu(self.time_mlp(t))[:, :, None, None]
        x = F.silu(self.norm1(self.conv1(x)))
        x = x + t
        x = F.silu(self.norm2(self.conv2(x)))
        return x + self.skip_connection(residual)
In [5]:
class UNet(nn.Module):
    def __init__(self):
        super().__init__()
        # Time embedding
        self.time_embedding = nn.Sequential(
            nn.Linear(1, 128),
            nn.SiLU(),
            nn.Linear(128, 256)
        )
        
        # Downsampling with more channels for RGB
        self.down1 = ResidualBlock(channels, 64)
        self.down2 = ResidualBlock(64, 128)
        self.down3 = ResidualBlock(128, 256)
        self.down4 = ResidualBlock(256, 512)  # Added an extra downsampling layer
        
        # Bottleneck
        self.bottleneck1 = ResidualBlock(512, 512)
        self.bottleneck2 = ResidualBlock(512, 512)
        
        # Upsampling
        self.up1 = ResidualBlock(512 + 512, 256)  # Bottleneck + down4 features
        self.up2 = ResidualBlock(256 + 256, 128)  # up1 + down3 features
        self.up3 = ResidualBlock(128 + 128, 64)   # up2 + down2 features
        self.up4 = ResidualBlock(64 + 64, 64)     # up3 + down1 features
        
        # Output
        self.final = nn.Conv2d(64, channels, 1)
        
        # Downsampling and upsampling
        self.pool = nn.MaxPool2d(2)
        self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False)
        
    def forward(self, x, t):
        # Time embedding
        t_emb = self.time_embedding(t.view(-1, 1))
        
        # Downsampling
        x1 = self.down1(x, t_emb)
        x = self.pool(x1)
        
        x2 = self.down2(x, t_emb)
        x = self.pool(x2)
        
        x3 = self.down3(x, t_emb)
        x = self.pool(x3)
        
        x4 = self.down4(x, t_emb)
        x = self.pool(x4)
        
        # Bottleneck
        x = self.bottleneck1(x, t_emb)
        x = self.bottleneck2(x, t_emb)
        
        # Upsampling
        x = self.upsample(x)
        
        # Ensure shapes match before concatenation
        if x.shape[2:] != x4.shape[2:]:
            x = F.interpolate(x, size=x4.shape[2:], mode='bilinear', align_corners=False)
        
        x = torch.cat([x, x4], dim=1)
        x = self.up1(x, t_emb)
        
        x = self.upsample(x)
        
        # Ensure shapes match
        if x.shape[2:] != x3.shape[2:]:
            x = F.interpolate(x, size=x3.shape[2:], mode='bilinear', align_corners=False)
            
        x = torch.cat([x, x3], dim=1)
        x = self.up2(x, t_emb)
        
        x = self.upsample(x)
        
        # Ensure shapes match
        if x.shape[2:] != x2.shape[2:]:
            x = F.interpolate(x, size=x2.shape[2:], mode='bilinear', align_corners=False)
            
        x = torch.cat([x, x2], dim=1)
        x = self.up3(x, t_emb)
        
        x = self.upsample(x)
        
        # Ensure shapes match
        if x.shape[2:] != x1.shape[2:]:
            x = F.interpolate(x, size=x1.shape[2:], mode='bilinear', align_corners=False)
            
        x = torch.cat([x, x1], dim=1)
        x = self.up4(x, t_emb)
        
        # Output
        return self.final(x)
In [6]:
# Functions for diffusion process
def extract(a, t, x_shape):
    """
    Extract coefficients at specified timesteps t and reshape to match x_shape
    """
    batch_size = t.shape[0]
    # Make sure both tensors are on the same device
    out = a.to(t.device).gather(-1, t)
    return out.reshape(batch_size, *((1,) * (len(x_shape) - 1)))
In [7]:
def q_sample(x_start, t, noise=None):
    """
    Forward diffusion process: add noise to the images
    """
    if noise is None:
        noise = torch.randn_like(x_start)
        
    sqrt_alphas_cumprod_t = extract(sqrt_alphas_cumprod, t, x_start.shape)
    sqrt_one_minus_alphas_cumprod_t = extract(sqrt_one_minus_alphas_cumprod, t, x_start.shape)
    
    return sqrt_alphas_cumprod_t * x_start + sqrt_one_minus_alphas_cumprod_t * noise
In [8]:
def p_losses(denoise_model, x_start, t, noise=None):
    """
    Calculate the loss for training
    """
    if noise is None:
        noise = torch.randn_like(x_start)
        
    x_noisy = q_sample(x_start, t, noise=noise)
    
    # Convert t to float and normalize
    t_normalized = t.float() / time_steps
    predicted_noise = denoise_model(x_noisy, t_normalized)
    
    return F.mse_loss(predicted_noise, noise)
In [9]:
@torch.no_grad()
def p_sample(model, x, t, t_index):
    """
    Sample from the model at timestep t
    """
    betas_t = extract(betas, t, x.shape)
    sqrt_one_minus_alphas_cumprod_t = extract(sqrt_one_minus_alphas_cumprod, t, x.shape)
    sqrt_recip_alphas_t = extract(sqrt_recip_alphas, t, x.shape)
    
    # Convert t to float and normalize
    t_normalized = t.float() / time_steps
    
    # Equation 11 in the DDPM paper (https://arxiv.org/abs/2006.11239)
    model_mean = sqrt_recip_alphas_t * (
        x - betas_t * model(x, t_normalized) / sqrt_one_minus_alphas_cumprod_t
    )
    
    if t_index == 0:
        return model_mean
    else:
        posterior_variance_t = extract(posterior_variance, t, x.shape)
        noise = torch.randn_like(x)
        return model_mean + torch.sqrt(posterior_variance_t) * noise
In [10]:
@torch.no_grad()
def p_sample_loop(model, shape):
    """
    Generate samples from the model using the sampling loop
    """
    device = next(model.parameters()).device
    
    b = shape[0]
    # Start with random noise
    img = torch.randn(shape, device=device)
    
    for i in tqdm(reversed(range(0, time_steps)), desc='Sampling loop time step', total=time_steps):
        img = p_sample(model, img, torch.full((b,), i, device=device, dtype=torch.long), i)
        
    return img
In [11]:
@torch.no_grad()
def sample(model, image_size, batch_size=16, channels=3):
    """
    Wrapper for p_sample_loop that returns images in the range [0, 1]
    """
    return p_sample_loop(model, shape=(batch_size, channels, image_size, image_size))

# Instantiate the model
model = UNet().to(device)
model = torch.compile(model)
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
In [12]:
# Helper function to display RGB images
def show_images(images, title="Generated Images"):
    # Convert images from the range [-1, 1] to [0, 1]
    images = (images + 1) / 2
    
    # Create a grid
    plt.figure(figsize=(10, 10))
    for i in range(min(16, images.shape[0])):
        plt.subplot(4, 4, i+1)
        # Transpose from [C, H, W] to [H, W, C]
        img = images[i].permute(1, 2, 0).cpu().numpy()
        # Clip to valid range
        img = np.clip(img, 0, 1)
        plt.imshow(img)
        plt.axis('off')
    plt.tight_layout()
    plt.title(title)
    return plt
In [13]:
# Training loop
def train():
    for epoch in range(num_epochs):
        model.train()
        train_loss = 0.0
        
        for batch, (images, _) in enumerate(tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}", leave=False, ncols=100)):
            images = images.to(device)
            batch_size = images.shape[0]
            
            # Sample random timesteps for each image
            t = torch.randint(0, time_steps, (batch_size,), device=device).long()
            
            # Calculate loss
            loss = p_losses(model, images, t)
            
            # Backpropagation
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            
            train_loss += loss.item()
            
            if batch % 1000 == 0:  # Print loss once in a while
                print(f"Batch {batch}, Loss: {loss.item():.6f}")
        
        avg_loss = train_loss / len(train_loader)
        print(f"Epoch [{epoch+1}/{num_epochs}], Loss: {avg_loss:.6f}")
        
        # Save some generated images after each epoch
        if (epoch + 1) % 5 == 0:
            model.eval()
            generated_images = sample(model, image_size=image_size, batch_size=16, channels=channels)
            
            # Plot and save
            plt_obj = show_images(generated_images, title=f"Generated Images - Epoch {epoch+1}")
            plt_obj.savefig(f'generated_celeba_epoch_{epoch+1}.png')
            plt_obj.close()    
            # Save model checkpoint
            torch.save(model.state_dict(), f'diffusion_celeba_model_epoch_{epoch+1}.pth')
In [14]:
def load(model, epoch):
    """
    Load a trained diffusion model from a checkpoint file
    
    Args:
        model: The UNet model instance to load weights into
        epoch: The epoch number of the checkpoint to load
    
    Returns:
        The model with loaded weights
    """
    model.load_state_dict(torch.load(f'diffusion_celeba_model_epoch_{epoch}.pth',map_location=device,weights_only=True))
    return model
In [ ]:
if __name__ == "__main__":
    train_from_scratch = False # Set to True to train from scratch. Otherwise it just uses a pre-trained model
    
    if train_from_scratch:
        # Create directory for the dataset if it doesn't exist
        os.makedirs(celeba_hq_path, exist_ok=True)
        # Check if the dataset folder has images
        if len(os.listdir(celeba_hq_path)) == 0:
            print(f"Warning: No images found in {celeba_hq_path}.")
            print("Please download the CelebA-HQ dataset and place the images in this directory.")
            print("You can find the dataset at https://github.com/tkarras/progressive_growing_of_gans")
            print("Make sure the images are at least 128x128 (see https://www.tensorflow.org/datasets/catalog/celeb_a_hq#celeb_a_hq128)")
        else:
            train_dataset = CelebAHQDataset(root_dir=celeba_hq_path, transform=transform)
            train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True)
            print(f"Found {len(train_dataset)} images in dataset.")
            print("Starting training...")
            train()
    else: # Otherwise it just uses a pre-trained model
        model = load(model,num_epochs)
        
    # Generate final samples
    print("Generating final samples...")
    model.eval()
    generated_images = sample(model, image_size=image_size, batch_size=36, channels=channels)
    
    # Plot and save final images
    plt.figure(figsize=(15, 15))
    for i in range(36):
        plt.subplot(6, 6, i+1)
        img = generated_images[i].permute(1, 2, 0).cpu().numpy()
        img = (img + 1) / 2  # Denormalize
        img = np.clip(img, 0, 1)
        plt.imshow(img)
        plt.axis('off')
    plt.tight_layout()
    plt.savefig('final_generated_celeba.png')
    plt.show()
    plt.close()
        
    print("Done.")
Generating final samples...
Sampling loop time step:  61%|█████████      | 606/1000 [38:40<25:27,  3.88s/it]
  • Epoch 5
    No description has been provided for this image
  • Epoch 295
    No description has been provided for this image
In [ ]: