ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing
ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing

All Courses

Introduction to Diffusion Models for Generative AI
Chapter 1: Generative Modeling Fundamentals
Overview of Generative Models
Motivation for Diffusion Models
The Core Idea: Noise and Denoise
Probabilistic Framework Introduction
Quiz for Chapter 1
Chapter 2: The Forward Diffusion Process
Defining the Markov Chain
Gaussian Noise Schedule
Mathematical Formulation per Step
Sampling from Intermediate Steps
Properties of the Forward Process
Practice: Simulating Forward Diffusion
Quiz for Chapter 2
Chapter 3: The Reverse Diffusion Process
The Goal: Reversing the Markov Chain
Approximating the Reverse Transition
Parameterizing the Reverse Process with Neural Networks
Predicting the Noise Component
Mathematical Formulation of the Denoising Step
Quiz for Chapter 3
Chapter 4: Model Architecture and Training
The U-Net Architecture for Noise Prediction
Integrating Timestep Information
Defining the Training Objective
Simplified Training Loss Derivation
The Training Algorithm
Hands-on Practical: Setting up the U-Net
Quiz for Chapter 4
Chapter 5: Sampling and Generation Process
Generating Data from Noise
The DDPM Sampling Algorithm
Understanding Sampling Variance
Introduction to Faster Sampling: DDIM
The DDIM Sampling Algorithm
Trade-offs Between DDPM and DDIM
Practice: Implementing Sampling Loops
Quiz for Chapter 5
Chapter 6: Conditional Generation with Diffusion Models
Motivation for Conditional Generation
Classifier Guidance
Classifier-Free Guidance (CFG)
Implementing Classifier-Free Guidance
Text Conditioning Basics
Architecture Modifications for Conditioning
Hands-on Practical: Applying Guidance
Quiz for Chapter 6

Implementing Classifier-Free Guidance

Classifier-Free Guidance (CFG) offers a powerful way to steer the generation process without relying on a separate, pre-trained classifier model. This technique avoids potential issues tied to classifier accuracy or domain mismatch, becoming a standard method in modern diffusion models.

The core idea is to train a single diffusion model ϵθ\epsilon_\thetaϵθ​ that can operate both conditionally and unconditionally. This is achieved through a modification during the training phase.

Training with Conditional Dropout

During training, for each data sample x0x_0x0​ and its corresponding conditioning information yyy (like a class label or text embedding), we do the following:

  1. Sample a timestep t∼U(1,T)t \sim \mathcal{U}(1, T)t∼U(1,T).
  2. Sample noise ϵ∼N(0,I)\epsilon \sim \mathcal{N}(0, \mathbf{I})ϵ∼N(0,I).
  3. Compute the noisy sample xtx_txt​ using the forward process equation: xt=αˉtx0+1−αˉtϵx_t = \sqrt{\bar{\alpha}_t} x_0 + \sqrt{1 - \bar{\alpha}_t} \epsilonxt​=αˉt​​x0​+1−αˉt​​ϵ.
  4. With a certain probability puncondp_{uncond}puncond​ (e.g., 10-20%), replace the actual conditioning information yyy with a special null or unconditional token, denoted as ∅\emptyset∅. This replacement acts like a form of "conditional dropout".
  5. Feed the noisy sample xtx_txt​, the timestep ttt, and the (potentially replaced) conditioning information into the U-Net model: ϵpred=ϵθ(xt,t,yeff)\epsilon_{pred} = \epsilon_\theta(x_t, t, y_{eff})ϵpred​=ϵθ​(xt​,t,yeff​), where yeffy_{eff}yeff​ is either yyy or ∅\emptyset∅.
  6. Calculate the loss, typically the Mean Squared Error (MSE), between the predicted noise ϵpred\epsilon_{pred}ϵpred​ and the true noise ϵ\epsilonϵ: L=∣∣ϵ−ϵpred∣∣2L = ||\epsilon - \epsilon_{pred}||^2L=∣∣ϵ−ϵpred​∣∣2.
  7. Update the model parameters θ\thetaθ using gradient descent on this loss.

By randomly omitting the conditioning information during training, the model learns two things simultaneously:

  • How to predict the noise given the condition: ϵθ(xt,t,y)\epsilon_\theta(x_t, t, y)ϵθ​(xt​,t,y).
  • How to predict the noise unconditionally: ϵθ(xt,t,∅)\epsilon_\theta(x_t, t, \emptyset)ϵθ​(xt​,t,∅).

The null token ∅\emptyset∅ needs a specific representation. For class labels, it might be a dedicated "unconditional" class index. For text embeddings (like CLIP embeddings), it's often a fixed, learnable embedding vector trained alongside the model to represent the absence of text conditioning.

Sampling with Guidance

During the generation (sampling) process, we leverage the model's ability to make both conditional and unconditional predictions at each step. For a given timestep ttt and the current noisy sample xtx_txt​, we compute two noise predictions:

  1. Unconditional Prediction: ϵuncond=ϵθ(xt,t,∅)\epsilon_{uncond} = \epsilon_\theta(x_t, t, \emptyset)ϵuncond​=ϵθ​(xt​,t,∅)
  2. Conditional Prediction: ϵcond=ϵθ(xt,t,y)\epsilon_{cond} = \epsilon_\theta(x_t, t, y)ϵcond​=ϵθ​(xt​,t,y) (where yyy is the desired condition for the output)

Instead of using just ϵcond\epsilon_{cond}ϵcond​ to perform the denoising step, we combine these two predictions using a guidance scale parameter www (often called guidance strength or scale, sometimes denoted sss or γ\gammaγ). The combined noise prediction ϵ~t\tilde{\epsilon}_tϵ~t​ is calculated as:

ϵ~t=ϵuncond+w⋅(ϵcond−ϵuncond)\tilde{\epsilon}_t = \epsilon_{uncond} + w \cdot (\epsilon_{cond} - \epsilon_{uncond})ϵ~t​=ϵuncond​+w⋅(ϵcond​−ϵuncond​)

This formula has a clear interpretation:

  • Start with the unconditional noise prediction ϵuncond\epsilon_{uncond}ϵuncond​.
  • Calculate the "guidance direction": the difference between the conditional and unconditional predictions (ϵcond−ϵuncond)(\epsilon_{cond} - \epsilon_{uncond})(ϵcond​−ϵuncond​). This vector points from the unconditional generation path towards the conditional one.
  • Scale this direction by the guidance scale www and add it to the unconditional prediction.

An equivalent way to write this is:

ϵ~t=(1−w)ϵuncond+w⋅ϵcond\tilde{\epsilon}_t = (1-w)\epsilon_{uncond} + w \cdot \epsilon_{cond}ϵ~t​=(1−w)ϵuncond​+w⋅ϵcond​

From this form, we can see:

  • If w=0w = 0w=0, we get ϵ~t=ϵuncond\tilde{\epsilon}_t = \epsilon_{uncond}ϵ~t​=ϵuncond​, resulting in purely unconditional generation.
  • If w=1w = 1w=1, we get ϵ~t=ϵcond\tilde{\epsilon}_t = \epsilon_{cond}ϵ~t​=ϵcond​, which corresponds to standard conditional generation without extra guidance amplification.
  • If w>1w > 1w>1, we extrapolate along the guidance direction, pushing the generation more strongly towards the condition yyy.

This combined noise estimate ϵ~t\tilde{\epsilon}_tϵ~t​ is then used in the standard denoising step (e.g., the DDPM or DDIM update rule) to compute the less noisy sample xt−1x_{t-1}xt−1​. The process repeats from t=Tt=Tt=T down to t=1t=1t=1.

The diagram below illustrates the computation at a single sampling step:

Flow diagram for calculating the guided noise prediction ϵ~t\tilde{\epsilon}_tϵ~t​ using Classifier-Free Guidance at a single denoising step ttt.

Practical Notes

  • Guidance Scale (www): This is a critical hyperparameter. Typical values range from 1.51.51.5 to 151515. Higher values enforce the condition more strongly, which can improve alignment (e.g., making an image look more like the text prompt) but may lead to saturation, artifacts, or reduced diversity in the generated samples. Lower values yield more diverse but potentially less condition-aligned results. You often need to experiment to find a good balance for your specific task and model.
  • Conditioning Input: How yyy and ∅\emptyset∅ are integrated into the U-Net architecture is important. Common methods include adding their embeddings to the timestep embeddings or using cross-attention layers within the U-Net blocks, allowing the model to attend to relevant parts of the conditioning information. We'll discuss architecture modifications in more detail later.
  • Computational Cost: CFG requires running the model forward twice per sampling step (once conditional, once unconditional). This roughly doubles the computational cost of sampling compared to standard conditional or unconditional generation. This trade-off is often acceptable given the significant improvement in control and quality.

Implementing CFG involves modifying both the training loop (to handle conditional dropout) and the sampling loop (to perform the two forward passes and combine the results). The next sections will explore specific architectural changes often used for conditioning and provide practical examples.

  • Photorealistic Text-to-Image Diffusion Models with Deep Language Understanding, Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S. Sara Mahdavi, Rapha Gontijo Lopes, Tim Salimans, Jonathan Ho, David J Fleet, Mohammad Norouzi, 2022 arXiv preprint arXiv:2205.11487 DOI: 10.48550/arXiv.2205.11487 - Formalizes Classifier-Free Guidance (CFG) and demonstrates its effectiveness in achieving high-quality, text-aligned image generation, providing the standard formulation used today.
  • Denoising Diffusion Probabilistic Models, Jonathan Ho, Ajay Jain, Pieter Abbeel, 2020 Advances in Neural Information Processing Systems 33 (NeurIPS 2020) DOI: 10.48550/arXiv.2006.11239 - The foundational paper that introduced Denoising Diffusion Probabilistic Models (DDPMs), providing the theoretical and practical basis for the diffusion models on which CFG is applied.

© 2026 ApX Machine Learning