Diffusion models
Stable Diffusion's parts rebuilt — CLIP, a VAE, a UNet with attention, and the DDPM sampler that turns noise into an image.
- Write the forward noising process in closed form and read a noise schedule
- Follow one reverse (denoising) step of the DDPM sampler
- Explain classifier-free guidance, and spot two bugs that stop the pipeline
A diffusion model learns to undo noise. Training takes a real image, adds a random amount of Gaussian noise, and asks a network to predict the noise that was added. Generation starts from pure noise and removes the predicted noise step by step until an image is left. 08_transformer_diffusion rebuilds Stable Diffusion v1.5 around this idea and loads the released weights for inference.
The pipeline has four parts:
- CLIP turns the prompt into 77 token embeddings of size 768.
- The VAE encoder compresses a 512×512 image into a 4×64×64 latent; the decoder turns a latent back into pixels. Diffusion runs on the small latent.
- The UNet predicts the noise in a latent, given the timestep and — through cross-attention, as in the previous lesson — the prompt.
- The DDPM sampler schedules the noise and performs each denoising step.
Adding noise
Noise is added over \(T = 1000\) steps with small variances \(\beta_t\). Their cumulative effect has a closed form, so any step can be reached directly:
\[x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\; \varepsilon, \qquad \bar\alpha_t = \prod_{s \le t} (1 - \beta_s), \quad \varepsilon \sim \mathcal N(0, I)\]ddpm.py uses Stable Diffusion’s “scaled linear” schedule, with \(\sqrt{\beta_t}\) spaced evenly from \(\sqrt{0.00085}\) to \(\sqrt{0.012}\):
self.betas = torch.linspace(beta_start ** 0.5, beta_end ** 0.5, num_training_steps) ** 2
self.alpha_cumprod = torch.cumprod(1.0 - self.betas, 0)
Removing noise
At each of the 50 inference steps the UNet predicts \(\varepsilon\), and step uses it to estimate the clean latent and then the previous, slightly less noisy one — equations (15) and (7) of the DDPM paper:
pred_original_sample = (latents - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
pred_prev_sample = pred_original_sample_coeff * pred_original_sample \
+ pred_current_sample_coeff * latents
plus fresh noise scaled by the step’s variance, except at the last step.
Classifier-free guidance runs the UNet twice per step — with the prompt and with an empty one — and extrapolates away from the unconditional prediction:
model_output = cfg_scale * (output_cond - output_uncond) + output_uncond
With cfg_scale = 7.5 the prompt’s influence is multiplied 7.5 times, trading variety for faithfulness to the text.
Two bugs before the first image
The variance of each reverse step is clamped to avoid a zero:
variance = torch.clamp(variance, min=1e20)
min=1e20 should be min=1e-20. As written, every step’s variance becomes at least \(10^{20}\), so the noise added has a standard deviation of \(10^{10}\) — against true values between 0.03 and 0.45 for this schedule — and the latent is destroyed at the first step.
The image-to-image branch of pipeline.py reorders the image’s axes with torch.permute(0, 3, 1, 2), which passes no tensor; it should be input_image_tensor.permute(0, 3, 1, 2). The demo notebook’s saved output stops earlier still, with a TypeError from torch.cat, raised by an older version of pipeline.py (the current one passes a list, as torch.cat requires) — so no generated image has been saved yet.
Try it yourself. Without loading any weights, check the sampler on its own: build DDPMSampler(torch.Generator()), call set_inference_timesteps(50), and print _get_variance(t) ** 0.5 for a few timesteps before and after the clamp fix. Then verify the closed form numerically: noise a tensor with add_noise at t = 500 many times and check that the mean is \(\sqrt{\bar\alpha_{500}}\, x_0\) and the variance is \(1 - \bar\alpha_{500}\).