Code Architecture — Latent Diffusion Models Notebook
Overview
The notebook builds a very small latent diffusion model from scratch in PyTorch. A VAE turns 32×32 FashionMNIST images into 8×8×4 latents, and a U-Net is trained to denoise those latents. The same U-Net is also trained directly on pixels, and the two are compared on training time, sampling time and generated pictures. In the saved run (Tesla T4), latent diffusion trained about 4 times faster than pixel diffusion, but sampling took about the same time; sample quality is only judged by eye.
Notebook Structure
1. Setup and Imports
- PyTorch, torchvision, NumPy, matplotlib; nothing is installed
- Seed 42;
CUBLAS_WORKSPACE_CONFIGset before importing torch, cuDNN deterministic,torch.use_deterministic_algorithms(True, warn_only=True) - Figures as JPEG at 80 dpi; on Kaggle an
atexithook and a small background process copy the executed notebook toexecuted_solution.ipynb
2. Hyperparameters
- Images 32×32×1; 8,000 training images (
SUBSET_SIZE) - VAE: 4 latent channels, downsampling factor f = 4 (latent 8×8×4), 5 epochs, KL weight 0.001
- Diffusion: T = 200 steps, linear β from 1e-4 to 0.02, 5 epochs, batch size 128, U-Net base width 32, learning rate 2e-4
- Prints the number of positions (1,024 → 64, 16× fewer) and values (1,024 → 256, 4× fewer)
3. Toy Dataset
- FashionMNIST, scaled to [-1, 1], downloaded quietly into a temporary folder
- A random subset of 8,000 images; 62 batches of 128 (
drop_last=True, seeded shuffling)
4. Stage 1 — Autoencoder (VAE)
- Encoder: 3×3 conv (1 → 32) → two stride-2 convs with GroupNorm and SiLU (32 → 64 → 128) → 1×1 convs for the mean and log-variance (4 channels each)
- Decoder: 1×1 conv (4 → 128) → two transposed convs with GroupNorm and SiLU (128 → 128 → 64) → two 3×3 convs (64 → 32 → 1) → tanh
encode()samples z with the reparameterisation trick; 335,241 parameters- Trained with mean-squared reconstruction error + 0.001 × KL for 5 epochs with Adam (learning rate 1e-3), then frozen
- Shows 8 originals and reconstructions
5. Forward Diffusion Process
- Linear β schedule and
q_sample(x_0, t)= √ᾱ_t · x_0 + √(1 − ᾱ_t) · ε - Shows one latent noised at t = 0, 40, 80, 120, 160, 199, decoded with the VAE
- The latents are used as they are (not rescaled)
6. U-Net Denoiser (UNet)
- Sinusoidal time embedding → MLP (128 → 512 → 128)
conv_in→DownBlock(32 → 64) →DownBlock(64 → 128, self-attention) → middle (ResBlock, self-attention, ResBlock) →UpBlock(→ 64, self-attention) →UpBlock(→ 32) → GroupNorm, SiLU, conv to the input channelsResBlock: two 3×3 convs with GroupNorm and SiLU, time embedding added after the first, 1×1 skip if needed- Built twice: 4 input channels for latents (2,353,348 parameters) and 1 for pixels (2,351,617)
7. Train Latent Diffusion Model
train_diffusion(): Adam, learning rate 2e-4, noise-prediction MSE (the paper’s Eq. 2), 5 epochs; images are encoded with the frozen VAE on the fly- Prints the loss and elapsed time per epoch
8. Train Pixel-Space DDPM Baseline
- The same function on pixels (
use_vae=False)
9. Training Speed Comparison
- Loss curves and a bar chart of training times
- Prints the training time ratio (pixel / latent), the VAE training time and the total including the VAE
10. Sampling and Quality Comparison
ddpm_sample(): 200 reverse DDPM steps for 16 samples; latent samples are decoded with the VAE- Prints both sampling times and their ratio, and shows the 16 samples from each model
11. Comprehensive Speed Comparison
- Table of training time, VAE time, total time, sampling time, grid size, values per sample and U-Net parameters
12. Latent Space Interpolation
- Decodes 8 straight-line mixes between the latents of two training images
13. Summary
### What the run above showswith the saved run’s numbers
Key Shapes
| Stage | Shape (B = 128) |
|---|---|
| Images | (128, 1, 32, 32) |
Encoder after conv_in | (128, 32, 32, 32) |
Encoder after down1, down2 | (128, 64, 16, 16), (128, 128, 8, 8) |
| Latent z (mean, log-variance) | (128, 4, 8, 8) |
| Decoder output | (128, 1, 32, 32) |
| Latent U-Net input / output | (128, 4, 8, 8) |
Latent U-Net after down1, down2 | (128, 64, 4, 4), (128, 128, 2, 2) |
| Pixel U-Net input / output | (128, 1, 32, 32) |
Pixel U-Net after down1, down2 | (128, 64, 16, 16), (128, 128, 8, 8) |
The latent has 4× fewer values than the image (256 vs 1,024) and 16× fewer positions (64 vs 1,024).
Deliberate Simplifications vs Full Paper
- Data and size: 8,000 grayscale 32×32 FashionMNIST images, instead of 256×256 (and larger) colour images from datasets such as CelebA-HQ, ImageNet and LAION.
- Autoencoder: a small VAE trained only with mean-squared error and a KL penalty, instead of the paper’s autoencoder with a perceptual loss and a patch-based adversarial loss (Section 3.1).
- No latent rescaling: the latents are not rescaled by their standard deviation as the paper does for KL-regularised latents (Section 4.3.2, Appendix D.1); both models use the same plain linear noise schedule.
- No conditioning: unconditional generation only, so there is no cross-attention or text encoder (Section 3.3).
- Training: 5 epochs for each model and 200 diffusion steps, with DDPM sampling instead of DDIM.
- Evaluation: times and pictures only; no FID or other quality metric.