Overview

6 Control what images to generate in diffusion models

This chapter shows how to move from unguided image synthesis to controllable generation with conditional diffusion models. It explains how conditioning lets you request specific outputs (such as a coat or sandal) and introduces classifier-free guidance (CFG), a technique that removes the need for an external classifier by jointly training the model with and without conditioning. By interpolating between conditional and unconditional predictions, CFG provides a simple, effective control knob—the guidance scale—to trade off fidelity to the request against output diversity, laying the groundwork for later text-to-image systems.

To make this concrete, the chapter builds a denoising U-Net from scratch and turns it into a conditional generator by injecting two kinds of embeddings: time-step embeddings (to identify the diffusion step) and label embeddings (to specify the desired class). The U-Net follows the classic contracting–bottleneck–expansive design with skip connections; down blocks use convolutions and max pooling to compress features, while up blocks use transposed convolutions to reconstruct detail. The chapter demystifies these components with hands-on, numerical illustrations of max pooling and transposed convolution, then shows how label masking during training enables the same network to act as both conditional and unconditional model—an essential ingredient for CFG.

A DDPM framework ties everything together: a noise scheduler corrupts clean images (FashionMNIST), the U-Net predicts the noise, and training minimizes mean squared error between true and predicted noise. At sampling time, the procedure runs both conditional and unconditional passes and blends them with a guidance weight to steer results; higher weights tighten adherence to the label at the cost of variety, while lower weights do the opposite. By the end, you can train a conditional diffusion model that generates requested classes on demand and modulate the fidelity–diversity balance, establishing the technical foundation that later chapters extend to text prompts and higher-resolution, color image synthesis used in modern latent diffusion systems.

The eight-step roadmap for building a text-to-image generator from scratch. This chapter zeroes in on step 4, empowering your diffusion model to generate specific types of images on command using classifier-free guidance, a breakthrough technique used in state-of-the-art text-to-image generation models.
A diagram of classifier-free guidance. In classifier-free guidance, we jointly train a conditional (top left part of the figure) and unconditional (bottom left part) diffusion model to attain a trade-off between sample quality and diversity. By embedding the conditioning information directly in the diffusion model, we can use the model as either a conditional model or an unconditional model. At inference, classifier-free guidance is applied by interpolating between the model’s conditional and unconditional predictions. The guidance parameter, w, controls how closely the generated image adheres to the conditioning information.
How to embed the time steps and the class labels in the denoising U-Net model. When training the U-Net, we add noise to clean images in the training set. We then feed the noisy images, along with the time steps the noisy images are in and the class labels, to the U-Net to train it to predict the noise in the images. The embedding blocks in the U-Net convert a time step, such as 25, into two time embeddings, with dimensions (512, 1, 1) and (256, 1, 1), respectively. Similarly, a class label, such as 2 (which means the image is a pullover), is converted into two label embeddings, with dimensions (512, 1, 1) and (256, 1, 1), respectively. The time embeddings and label embeddings will be used in the expansive path (i.e., decoder) of the U-Net.
A diagram illustrating the components of the denoising U-Net model. The U-Net takes noisy images, time steps, and labels as inputs and predicts the noise in the noisy images. The architecture consists of three main parts: a contracting path (encoder), an expansive path (decoder), and a bottleneck connecting the two. The contracting path extracts features and downsamples the images through convolutional and pooling layers, progressively capturing higher levels of abstraction. The expansive path reconstructs the feature maps by upsampling the images and utilizes skip connections to merge corresponding features from the contracting path. Finally, the bottleneck serves as a bridge between the encoder and decoder, processing the most abstracted features before reconstruction.
A numerical example of how max pooling works, with a kernel size of 2x2 and a stride equal to 2.
A numerical example of how transposed convolutional operations work.
Comparing the generated images with real images. The top row shows images generated by the trained denoising U-Net model, with labels 0 to 9, respectively. The bottom row displays real images from the training set, also with labels 0 to 9.
Generated images by the trained denoising U-Net model when the guidance parameter is high (with a value of 5). The first column shows images generated with the label 0 (meaning a t-shirt). The second column is trousers (with the label 1), and so on. The last column shows ankle boots, with labels 9.

Summary

  • Traditional diffusion models typically rely on external classifiers to guide the image generation process using a technique known as classifier guidance. In 2022, Jonathan Ho and Tim Salimans introduced classifier-free guidance and showed that effective guidance during generation can be achieved using a purely generative model without relying on an external classifier. Their approach involves jointly training a diffusion model under both conditional and unconditional settings.
  • The contracting path of a U-Net is designed to learn feature representations and progressively downsample the input image. This path usually consists of several blocks of convolutional layers followed by pooling layers. Convolutional layers extract feature maps by detecting patterns such as edges, textures, or shapes at various levels of abstraction. Pooling layers reduce the spatial dimensions of the feature maps, making the model computationally efficient while capturing more abstract representations.
  • The bottleneck path in U-Net serves as a bridge between the contracting and expansive paths. It processes the most abstracted features extracted by the contracting path and prepares them for reconstruction in the expansive path. The bottleneck contains layers with the smallest spatial dimensions and the most condensed information about the image.
  • The expansive path of a U-Net upscales the downsampled feature maps and reconstructs the image. This path usually consists of transposed convolutional layers and additional convolutional layers. Transposed convolutional layers upsample the feature maps, effectively filling in gaps and increasing spatial resolution.
  • To enhance the reconstruction process in a U-Net, skip connections are used to combine feature maps from the contracting path with those in the expansive path. This ensures that fine-grained details lost during downsampling are retained and incorporated back into the upsampled image.

FAQ

What is classifier-free guidance (CFG) and why is it useful in diffusion models?Classifier-free guidance is a technique where a single diffusion model is trained to operate both conditionally (with labels or prompts) and unconditionally (without them). Unlike older approaches that needed a separate classifier to steer generation, CFG removes this dependency, simplifying the pipeline and improving sample quality. It lets you balance fidelity to the condition and output diversity with one parameter during inference.
How is classifier-free guidance implemented during training and inference?Training: randomly “drop” the condition (e.g., mask labels) for a fraction of batches (about 10%) so the same U-Net learns both conditional and unconditional denoising. Inference: run the model twice—once with the condition and once without—and interpolate predictions. The final prediction is (1 + w) times the conditional minus w times the unconditional prediction, where w is the CFG scale.
What does the CFG scale (guide_w) control, and how should I set it?The CFG scale w controls the trade-off between fidelity and diversity. Higher w makes outputs adhere more closely to the requested label/prompt but reduces variety. Lower w increases diversity but may drift from the condition. Special case: w = 0 uses only the conditional prediction. In practice, try values like 1–5 and adjust based on how strictly you want the model to follow the condition.
How do we inject time-step and label information into the U-Net?Both time steps and labels are embedded with small MLP blocks (two linear layers with GELU). Time t (scalar normalized by n_T) produces embeddings shaped (512,1,1) and (256,1,1). Class labels are one-hot encoded (size 10), passed through similar embedding blocks to produce (512,1,1) and (256,1,1). These embeddings are added/multiplied into the decoder (up) path to condition denoising on time and class.
What is the role of the context mask and why do we mask labels during training?The context_mask toggles conditioning. When it is 1, labels are masked and the model learns to denoise unconditionally; when 0, labels are used for conditional denoising. Masking labels with about 10% probability teaches a single U-Net to behave as both conditional and unconditional models, which is essential for classifier-free guidance at inference time.
What are the key parts of the denoising U-Net used here?The U-Net has a contracting path (encoder) with convolution and max pooling to downsample and extract features, a bottleneck that processes the most abstract features, and an expansive path (decoder) with transposed convolutions and residual blocks to upsample and reconstruct. Skip connections concatenate encoder features into corresponding decoder stages to preserve detail.
How do down blocks and up blocks change image resolution?Down blocks use convolutions plus MaxPool2d(2) to halve height and width while increasing feature depth. Up blocks use ConvTranspose2d (stride 2, kernel 2) to double spatial size, then residual conv blocks to refine features. Skip connections feed encoder features into the corresponding up block to recover fine details lost during downsampling.
What does the DDPM class do during training, and what is the loss?DDPM samples a random time step for each image, adds noise according to a fixed schedule to produce x_t, and asks the U-Net to predict the added noise. The training loss is mean squared error between the true noise and the model’s predicted noise. Minimizing this teaches the model to denoise across all time steps.
How does the sampling function combine conditional and unconditional predictions?At each step, the batch is duplicated: half with labels (conditional) and half with labels masked (unconditional). The model outputs eps1 (conditional) and eps2 (unconditional). The guided prediction is eps = (1 + w)·eps1 − w·eps2. This yields fine-grained control over adherence to the condition via w, and is applied throughout the reverse diffusion steps.
What data and setup are used, and how long does training take?The chapter trains on grayscale FashionMNIST (10 classes, 28×28), normalized to [-1, 1], using a U-Net within a DDPM (1,000 steps). With a GPU, training for about 20 epochs typically completes in under an hour. The same ideas extend later to text conditioning and higher-resolution color images (as in Latent Diffusion and Stable Diffusion).

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Text-to-Image Generator (from Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Text-to-Image Generator (from Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Text-to-Image Generator (from Scratch) ebook for free