A diffusion model is a type of generative model that gradually denoises data starting from pure noise to generate realistic samples, such as images. It has gained popularity due to its high-quality output in image synthesis tasks.
Libraries and Setup
python
CopyEdit
!pip install -q -U einops datasets matplotlib tqdm
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from einops import rearrange
from tqdm.auto import tqdm
These libraries are essential for:
Building the neural network (torch)
Visualizing results (matplotlib)
Structuring tensors (einops)
Progress display (tqdm)
2. Helper Functions
Functions like exists(), default() are utilities for model flexibility and clean code.
3. Neural Network Components
Residual: A block that adds the input back after applying a function (skip connection).
Upsample and Downsample: Used to change the resolution of feature maps during generation.
4. Diffusion Model Structure
The model follows a UNet-like architecture and includes:
Time embedding
Noise schedule
Training loop to minimize denoising error
5. Sampling and Visualization
Once trained, the model can:
Start from random noise
Iteratively denoise to generate an image
Show intermediate steps using matplotlib
This is the target image we want the model to learn to generate.
Downsampled Input
The image is resized to a lower resolution (128×128) for training and input.
Noise Input
This is the starting point — random noise used by the diffusion model in the reverse denoising process.
This image illustrates how a trained diffusion model transforms pure noise into a recognizable image of two cats. The model starts with random noise (far right) and denoises it step-by-step until it produces the final image (far left).
Step 0 (Rightmost): Random Gaussian noise
Step n (Middle): Partial structure appears (e.g., blurry shapes of cats)
Final Step (Leftmost): Clear image resembling the training data
Final Output (Generated Image) – the model’s final denoised image (of the two cats on a pink couch).
Earlier Denoising Steps – each subsequent image is one step earlier in the reverse diffusion process.
Pure Noise (Rightmost) – the starting point: completely random noise.
Google colab Notebook page :