Module 19

Generative Models

How does a model learn a data distribution to generate new samples that share its statistical properties?

lessons
28
duration
50 h 10 min
concepts
156
available in English
28 / 28
completed by you
0 of 28

Where it fits

Overview

Explore major families of deep generative models through their treatment of likelihood: autoregressive models with exact density, autoencoders and VAEs with their ELBO, GANs as a generator–discriminator game, normalizing flows, energy- and score-based models, discrete- and continuous-time diffusion, latent diffusion and flow matching. Derive their objectives and implement each family first in NumPy on 2D data or 8×8 digits, then in PyTorch on MNIST, Fashion-MNIST and CIFAR-10. Finish with rigorous evaluation, fast samplers, guidance, few-step generation, discrete diffusion, memorization theory and the frontier of continuous autoregression and unified models.

Why it matters

Diffusion and flow matching generate images, video, audio and increasingly robot actions and molecules, while LLMs are autoregressive generative models. Understanding objectives through their derivations makes it possible to read new papers and identify their design choices. This module directly supports the diffusion-model project, imitation-learning diffusion policies, multimodal tokenizers and honest evaluation of generative systems, including metrics, memorization and training-data leakage.

Lessons 28

  1. 01Review: learning a distribution, divergences and the map of generative modelsReview maximum likelihood as forward KL minimization and alternative divergences (reverse KL, Jensen-Shannon, Wasserstein and Fisher), focusing on the behavior each induces. Build a taxonomy based on likelihood access, investigate disjoint low-dimensional supports, and introduce the trade-off between quality, diversity and speed.Review80 min
  2. 02Autoregressive models: the chain rule as a modelFactorize a distribution exactly into conditional distributions and parameterize them with a network for exact likelihood and parallel training. Develop FVSBN, NADE and MADE, whose masks enforce ordering in one pass. Study continuous outputs, sequential ancestral sampling and order-agnostic training. GPUCore95 min
  3. 03Autoregressive models for images and audio: PixelCNN, WaveNet and bits per dimensionApply autoregression to spatial and temporal data. Build PixelCNN masked convolutions, diagnose the blind spot and address it with Gated PixelCNN, derive PixelCNN++ discretized logistic-mixture likelihood, and study WaveNet dilated causal convolutions. Interpret bits per dimension as a compression rate. GPUCore110 min
  4. 04Autoencoders: compression, noise and the geometry of dataExtend the linear autoencoder (PCA) to nonlinear encoders and decoders and study why reconstruction alone is insufficient. Investigate the identity trap, contractive and sparse regularization, denoising autoencoders and their relation to the score of a smoothed density, and latent holes that motivate VAEs. GPUCore85 min
  5. 05The variational autoencoder: a complete derivation of the ELBOAdd a prior and likelihood to an autoencoder to obtain a trainable deep latent-variable model. Derive the VAE ELBO in two ways, identify its gap as KL to the true posterior, specialize reparameterization to a Gaussian encoder, and calculate each term. Study how decoder likelihood sets the reconstruction-KL trade-off and why samples may look blurred. GPUCore120 min
  6. 06Training VAEs for real: posterior collapse, β-VAE and tighter boundsDiagnose posterior collapse and aggregate-posterior mismatch, explore the rate-distortion curve with β, examine disentanglement claims, and estimate likelihood with importance sampling and the IWAE bound. GPUCore100 min
  7. 07Hierarchical VAEs and discrete latents: NVAE, VQ-VAE and tokenizersExplore two ways to enrich a single Gaussian latent: top-down hierarchical VAEs, which connect autoregression and diffusion, and discrete representations using Gumbel-softmax, VQ-VAE, codebook diagnostics, finite scalar quantization and two-stage generation. GPUAdvanced115 min
  8. 08GANs: the game between generator and discriminatorGANs generate without evaluable likelihood: an implicit generator learns against a classifier distinguishing real and generated data. Derive the optimal discriminator and game value in terms of Jensen-Shannon divergence, interpret density-ratio estimation, and study gradient saturation, mode collapse, oscillation and DCGAN. GPUCore110 min
  9. 09GAN dynamics and stabilization: Wasserstein, penalties and spectral normalizationStudy GAN training dynamics through the Dirac-GAN linearization, generalize objectives using f-divergences, derive WGAN from transport duality, and examine gradient penalties, spectral normalization, R1 and modern training recipes. GPUAdvanced115 min
  10. 10Conditional GANs, StyleGAN and the adversarial loss as a toolControl generation and use the discriminator as a learned loss. Study conditional GANs and projection discriminators, pix2pix and CycleGAN image translation, style-based generation and truncation, and perceptual plus adversarial reconstruction losses. GPUAdvanced105 min
  11. 11Evaluating generative models: likelihood, FID, precision and recallStudy the limits of likelihood, including its mismatch with sample quality and the out-of-distribution paradox. Derive and compare Inception Score, FID, MMD, KID and precision-coverage metrics, their biases and feature-extractor dependence, then build an evaluation harness. GPUCore100 min
  12. 12Normalizing flows: change of variables and coupling layersBuild normalizing flows as differentiable bijections with tractable density, sampling and latent inference. Develop planar flows, NICE and RealNVP affine coupling, multiscale architectures and Glow, then derive dequantization for discrete pixels. GPUCore110 min
  13. 13Autoregressive, spline, residual and continuous flowsIncrease per-layer flow expressivity while studying the cost of inverse evaluation. Compare MAF and IAF, rational-quadratic splines, residual flows and continuous flows including FFJORD, then examine topological limits and the motivation for flow matching. GPUAdvanced110 min
  14. 14Energy-based modelsDefine energy-based distributions and derive maximum-likelihood gradients as positive and negative phases. Approximate the negative phase with contrastive divergence, persistent chains and Langevin dynamics, study RBMs and short-run sampling, and reinterpret a classifier as a joint energy model. GPUCore105 min
  15. 15Score matching: learning the gradient of the log-densityModel the score rather than the partition function. Derive implicit score matching by integration by parts, its random-projection variant, denoising score matching and its equivalence to smoothed-density score matching, and Tweedie's formula connecting optimal denoisers to scores. GPUCore110 min
  16. 16Score-based models: multiple noise levels and annealed Langevin dynamicsStudy three obstacles to score-based generation: lower-dimensional data, low-density regions and local insensitivity to mixture weights. Perturb at multiple noise levels, sample with annealed Langevin dynamics, design noise schedules and steps, and connect discrete levels to continuous-time diffusion. GPUCore95 min
  17. 17Denoising diffusion probabilistic models: a complete derivation of the objectiveDerive a diffusion model as a hierarchical VAE with a fixed noisy encoder: its forward marginal and posterior, diffusion ELBO, parameterizations, simplified noise loss and connection to denoising score matching. Implement a DDPM from scratch. GPUCore120 min
  18. 18Diffusion in practice: U-Net, time conditioning, schedules and weightingsBuild a diffusion U-Net with time conditioning, compare schedules in log SNR and correct terminal SNR, relate epsilon, x_0 and v parameterizations, study loss weighting, and use EMA and mixed precision in a practical training protocol. GPUCore115 min
  19. 19Continuous-time diffusion: SDEs, the reverse process and the probability flow ODEConnect DDPM and NCSN to continuous-time stochastic differential equations; derive the probability-flow ODE, study reverse-time sampling and likelihood weighting, and compute flow likelihood with Hutchinson's estimator. GPUAdvanced120 min
  20. 20Fast samplers: DDIM, EDM and high-order solversDerive DDIM and its relation to Euler integration, study EDM preconditioning, noise grids and Heun sampling, and compare exponential solvers and DDIM inversion under a measured evaluation budget. GPUAdvanced115 min
  21. 21Conditional generation and guidance: classifier guidance, classifier-free guidance and editingDerive conditional and classifier-free guidance, distinguish instantaneous tilted densities from guided-process output laws, and use learned diffusion priors for image editing and inverse problems. GPUCore105 min
  22. 22Latent diffusion and Diffusion TransformersStudy latent diffusion, first-stage compression and scaling, diffusion transformers and adaLN-Zero; train a DiT on precomputed latents and examine a text-to-image pipeline. GPUCore115 min
  23. 23Flow matching: learning the velocity field by regressionDerive conditional flow matching from probability paths, conditional and marginal fields, and regression; explore Gaussian paths and rectified flow, then compare numerical sampling and diffusion. GPUCore115 min
  24. 24Flow matching in depth: unification with diffusion, couplings and straight pathsRelate scores, diffusion and flow velocities; study timestep weighting, stochastic interpolants, minibatch optimal transport, stable Sinkhorn, reflow and their measured costs. GPUAdvanced110 min
  25. 25Few-step generation: distillation, consistency models and mean flowsStudy progressive distillation, consistency models, distribution matching and flow maps for few-step generation, including their training costs and evaluation limits. GPUResearch115 min
  26. 26Discrete diffusion and diffusion language modelsDerive categorical diffusion transitions and masked-diffusion objectives, connect random reveal orders to autoregression, and compare parallel decoding and language-model evaluation. GPUResearch110 min
  27. 27Theory of diffusion: convergence, memorization and generalizationConnect score error to convergence, derive the empirical optimal denoiser, and investigate memorization, generalization and spectral structure in diffusion models. GPUResearch105 min
  28. 28Frontier: continuous autoregression, multiscale generation and unified modelsCompare autoregressive and diffusion combinations, next-scale prediction, compact tokenizers and multimodal generation, then evaluate model claims through six explicit design decisions. GPUResearch100 min

Module capstone

Comparative generative lab on the local GPU

Using the same dataset (CIFAR-10 at 32×32, or CelebA at 64×64 if time permits) and compute budget, train and evaluate four families with the lesson 11 harness: a VAE with learned prior, a GAN with R1 or spectral normalization, a v-parameterized diffusion model and a flow-matching model with the same U-Net, the latter two class-conditioned with classifier-free guidance. Deliver a reproducible three-seed report comparing FID, KID, precision and coverage, bits per dimension where available, quality versus NFE curves for lesson 20 samplers, distillation to four or fewer steps, and a nearest-neighbor memorization analysis. The resulting code forms the basis of the integrated diffusion-model project.

Check what you already know

  • Prove that maximum likelihood minimizes KL(p_data ‖ p_θ) and predict whether a divergence covers or seeks modes.
  • Construct MADE masks and verify the autoregressive property with perturbations.
  • Derive a VAE ELBO using Jensen and the posterior-KL identity, including closed-form Gaussian KL.
  • Derive the optimal GAN discriminator and game value in terms of Jensen–Shannon divergence.
  • Calculate FID, KID and precision–coverage and explain finite-sample FID bias.
  • Write the inverse and log determinant of an affine coupling layer.
  • Derive implicit score matching by integration by parts and denoising score matching equivalence.
  • Derive q(x_t | x_0), q(x_{t-1} | x_t, x_0) and the simplified DDPM loss.
  • Derive the probability-flow ODE from the Fokker–Planck equation.
  • Implement DDIM and the EDM Heun sampler and measure convergence order.
  • Implement classifier-free guidance and explain what distribution it actually samples.
  • Prove that flow-matching and conditional flow-matching gradients coincide.

References