LLGA · Course notes

Multimodal Generative AI

CSC_52002_EP · Year 1 · Period 2

Contents

Introduction and overview

Module Multimodal Generative AI
Code CSC_52002_EP
Team and workload Head (“responsable” on the 2026–2027 sheet, also head of the X3A session): Xi Wang (École Polytechnique) · teaching team listed on the sheet: Mohamed Alami Chehboune, Lucas Degeorge, Eleftherios Tsonis, Yuanzhi Zhu · teaching volume not displayed on the 2026–2027 sheet (36 h per the LLGA curriculum wiki, see the session plan) · 4.5 ECTS · VAEs, GANs, diffusion, CLIP and text-to-image, then video, sound and robot actions — how generative models bring together several modalities.
Period Autumn semester · period 2 (from 04/01/2027 to 19/03/2027) · X3A session “Multimodal Generative AI” (code X3A LU3); course taught in English
Assessment Not displayed: the 2026–2027 sheet gives no assessment modality, and its LLGA section shows no resit rule or pass threshold (those displayed belong to other programs)
Status in the program P2 option — Choose 1Graph × LLM route one of the Period 2 “Choose 1” electives of the official LLGA 1 – S2 2026–2027 list, preselected by the Graph × LLM route of the home page

Audience: an engineer who knows a CNN / autoencoder and wants to generate or align text×image. Empirical first: a VAE whose reconstructions blur (KL weight \beta_{\mathrm{KL}} too high); a GAN that mode-collapses after 20 k steps; a CLIP whose retrieval drops as soon as the domain leaves the web — then we name ELBO, diffusion, guidance.

VAE, GAN, diffusion, CLIP and text-to-image. Bridge to neural rendering and generative control in M2.

What you will be able to do

Official objectives and syllabus (2026-2027 catalog)

The official 2026–2027 sheet (French title “IA générative multimodale”, scheduled session “Multimodal Generative AI”, period X-3A-P2, from 04/01/2027 to 19/03/2027, taught in English) carries a two-paragraph description in English.

Generative AI lets machines interpret and process data through several modalities and sensors — vision, audio, touch — and its multimodal development is presented as both a major scientific advance and a paradigm shift for industries from healthcare to automotive, with tools such as Dall-E 3, Midjourney and GPT-Vision building on large vision models, and autonomous-driving companies expanding. The class announces that it goes beyond CNNs and transformers to the advanced topics of multimodal generative AI: “from image to video generation, sound, robot actions”.

Nothing else is displayed: no teaching volume, no prerequisites, no assessment modality, no programme.

Element of the official description Course section
Beyond CNNs and transformers: advanced generative families Chapters 1 to 4 (VAEs and VQ-VAE, GANs and Wasserstein, DDPM and score diffusion, guidance, DDIM, flows and flow matching, latent diffusion)
Image generation; large vision models behind Dall-E 3, Midjourney, GPT-Vision Chapters 5 (CLIP, vision-language alignment) and 6 (the complete text-to-image pipeline); section 8.4 (multimodal LLMs that read images)
Video generation Section 8.1 (video latent diffusion, Definition 8.1; token budget, Example 8.2; temporal consistency and FVD)
Sound (audio modality) Section 8.2 (log-mel spectrograms and codec tokens, Definition 8.3; bitrate, Example 8.4; text-to-audio models and CLAP, Definition 8.5)
Robot actions Section 8.3 (diffusion policy, Definition 8.6; multimodal actions, Example 8.7; vision-language-action models, Definition 8.8)
Tactile information (touch sensors) Section 8.3, note “Touch, and the industries named by the description”
Industries reshaped: healthcare, automotive, autonomous driving Section 8.3 note (driving world models, medical image synthesis); chapter 7 (evaluation, costs, ethics) as the reading grid

Every element of the description now has a section in these notes. Our extensions, beyond the official description: the refresher chapter 0 (Gaussians, networks, and recalls of the ELBO proved in Deep Learning) and chapter 9 (research notes on video generation, guidance and distillation, self-study).

Where this course fits in the program

Module of period 2 of M1 (teaching volume not displayed on the 2026–2027 sheet; 36 h and 4.5 ECTS per the LLGA curriculum wiki), of which Xi Wang is the official head (“responsable” on the 2026–2027 sheet). It is one of the Period 2 “Choose 1” electives, and the Graph × LLM route of the home page preselects it. Official prerequisites: not displayed on the sheet. This is where the master’s program shifts from learning representations to multimodal generation.

Course outline

Session plan

36 h in class = 12 sessions of 3 h. The SynapseS 2026–2027 sheet of this course displays no teaching volume (neither in-person hours nor a lecture/tutorial split, and its description is shorter than in earlier versions), but the LLGA curriculum page of the programme wiki (msct.dix.polytechnique.fr/llga, last modified on 9 September 2026 by the programme director) states that “all subsequent M1 courses are 36h and will credit 4.5 ECTS”.

No session-by-session programme is published either, so the split below is our proposal for covering these notes in that time. Level 1 = foundations (reviews, definitions, first worked examples), 2 = core models and their derivations, 3 = current frontiers; the level never goes down from one session to the next.

The ELBO, the reparameterization trick, the Gaussian KL and the GAN equilibrium are proved in Deep Learning (P1), which every student of this course took. Chapters 0–2 now take two sessions instead of four. Of the two sessions this frees, one goes to flows and flow matching (session 6), the other to more time for robot actions and the project (sessions 11–12).

Session Hours Level Content Practice
1 3 h 1 ch. 0 Review: Gaussians, recalls of the ELBO, reparameterization and Gaussian KL, U-Net and cross-attention; ch. 1 conditional and hierarchical VAEs, posterior collapse Ex. 2; lab: the MiniVAE of ch. 1 on MNIST
2 3 h 2 ch. 1 VQ-VAE and hierarchical sampling; ch. 2 GAN equilibrium (recall), mode collapse, WGAN and gradient penalty, StyleGAN, CycleGAN, IS, FID and the Gaussian W2 Ex. 3, 7
3 3 h 2 ch. 3 Forward process, learned reverse process and its ELBO (3.1–3.2) Ex. 1, 8
4 3 h 2 ch. 3 Predicting the noise = predicting the score (3.3), denoising score matching (3.4), Langevin sampling, DDPM in code Ex. 6, 10
5 3 h 2 ch. 4.1 Classifier guidance, classifier-free guidance; ch. 4.2 DDIM, the SDE viewpoint, fast solvers Ex. 4
6 3 h 2 ch. 4.3 Flows: change of variables, affine coupling, continuous flows, conditional flow matching lab: the flow-matching code of 4.3 on two moons, Euler with 2, 5 and 20 steps
7 3 h 2 ch. 4.4 Latent diffusion, ControlNet, inpainting, DiT lab: DDPM vs DDIM sampling with 1000, 50 and 20 steps
8 3 h 2 ch. 5 CLIP: ViT recap, contrastive loss, temperature, zero-shot classification Ex. 5, 11
9 3 h 2 ch. 6 Text-to-image: the complete pipeline, the Diffusers loop, prompts, negative prompts, seeds; ch. 7 Evaluation, costs, ethics Ex. 9; Ex. 14 (start the project)
10 3 h 3 ch. 8.1 Video generation; ch. 8.2 Sound generation Ex. 12
11 3 h 3 ch. 8.3 Robot actions and tactile sensing Ex. 13 (diffusion-policy lab)
12 3 h 3 ch. 8.4 Multimodal LLMs, 3D, world models; project review Ex. 14 (project review)

Self-study, outside the 36 h (about 3 h in total): ch. 9 Course research notes — action tubelets, guidance-weight schedulers, video generation and one-step distillation (≈ 3 h).

How to study this module

Independent note This module is the multimodal generative component of the master’s program: it crosses the LLM track (CLIP and multimodal LLMs) with the mathematical rigor of transport (Wasserstein, FID), and prepares the control of generation in M2 in Control in Generative AI. Creative industries, data synthesis, computer-aided design: industrial demand there is immense, and the questions of evaluation, costs and ethics it raises are at the heart of the field’s current debates.

0. Review: probabilities, networks, ELBO

This module builds the entire edifice of multimodal generative models on four bricks: Gaussians (the only probabilistic object diffusion will need), the evidence lower bound (ELBO), the reparameterization trick (making sampling differentiable) and encoder-decoder architectures (CNN, U-Net, attention).

Every student of this course took Deep Learning in Period 1, whose chapter 9 proves the ELBO, the reparameterization trick and the Gaussian KL. This chapter recalls them in the form used later, and proves only what is new here: the sum of Gaussians that makes diffusion computable.

Reminders from previous modules

  • CNN: convolutions, U-Net (encoder-decoder skip connections);
  • Transformers & cross-attention: image queries, text keys/values — the mechanism that “injects” the prompt into a generator;
  • Gaussians and Markov chains: additive noise, \mathcal{N}(0,1), reparameterization — diffusion is just a Markov chain of Gaussian noises (Refresher Statistics, 2.7 or Reinforcement Learning, ch. 0 for Markov chains);
  • EM / PCA (Machine Learning module): the VAE is a probabilistic cousin of PCA — alternating maximization of a lower bound, principal axes = latent directions.

Property 0.1 — Sum of independent Gaussians If X \sim \mathcal{N}(\mu_1, \sigma_1^2) and Y \sim \mathcal{N}(\mu_2, \sigma_2^2) are independent, then X + Y \sim \mathcal{N}(\mu_1 + \mu_2,\ \sigma_1^2 + \sigma_2^2). The means add, the variances add — it is this rule that makes diffusion “computable in a single step” (chapter 3).

Proof. Proof (characteristic function). For Z \sim \mathcal{N}(\mu, \sigma^2), one computes \varphi_Z(t) = \mathbb{E}[e^{itZ}] = e^{i\mu t - \frac{1}{2}\sigma^2 t^2} (a Gaussian integral after completing the square). By independence, \varphi_{X+Y}(t) = \varphi_X(t)\,\varphi_Y(t) = e^{i(\mu_1+\mu_2)t - \frac{1}{2}(\sigma_1^2+\sigma_2^2)t^2}, which is the characteristic function of a \mathcal{N}(\mu_1+\mu_2,\ \sigma_1^2+\sigma_2^2); Lévy’s uniqueness theorem concludes. ∎

Recall — proved in Deep Learning (P1), section 9.2

  • Theorem 0.2 — ELBO (Deep Learning, theorem 9.2). For every x and every encoder q_\phi(z \mid x) whose support contains that of the posterior p_\theta(z \mid x), \log p_\theta(x) \;=\; \mathrm{ELBO}_\phi(x) + \mathrm{KL}\big(q_\phi(z\mid x) \,\|\, p_\theta(z\mid x)\big) \;\ge\; \mathrm{ELBO}_\phi(x), \mathrm{ELBO}_\phi(x) = \mathbb{E}_{q_\phi(z\mid x)}\big[\log p_\theta(x \mid z)\big] - \mathrm{KL}\big(q_\phi(z\mid x)\,\|\,p(z)\big). The gap is exactly the KL to the true posterior: maximizing the ELBO raises the likelihood and pulls q_\phi(z \mid x) toward the posterior. Proof idea: expand that KL with Bayes’ rule for p_\theta(z \mid x).
  • Definition 0.3 — Reparameterization trick (Deep Learning, proposition 9.3). Write z = \mu_\phi(x) + \sigma_\phi(x) \odot \epsilon with \epsilon \sim \mathcal{N}(0, I). The law of the noise no longer depends on \phi, so the gradient passes under the expectation: \nabla_\phi\, \mathbb{E}_{q_\phi}[f(z)] = \mathbb{E}_{\epsilon}\big[\nabla_\phi f(\mu_\phi(x) + \sigma_\phi(x)\odot\epsilon)\big]. Diffusion uses the same device when it writes x_t as a function of x_0 and of a Gaussian \epsilon (ch. 3).
  • Proposition 0.4 — KL between diagonal Gaussians (Deep Learning, proposition 9.4, there with p = \mathcal{N}(0, I)). For q = \mathcal{N}(\mu_1, \mathrm{diag}\,\sigma_1^2) and p = \mathcal{N}(\mu_2, \mathrm{diag}\,\sigma_2^2), \mathrm{KL}(q \| p) = \tfrac{1}{2}\sum_i \left[\frac{\sigma_{1,i}^2 + (\mu_{1,i}-\mu_{2,i})^2}{\sigma_{2,i}^2} + \log\frac{\sigma_{2,i}^2}{\sigma_{1,i}^2} - 1\right]. VAE training and the diffusion loss of ch. 3 both rest on this closed form; exercise 2 proves the general scalar case, with solution.

Networks. A CNN applies the same filter locally; its receptive field grows with depth, trading resolution for context. The U-Net couples an encoder (downsampling, global semantics) and a decoder (upsampling, local precision) through skip connections that short-circuit the bottleneck: it is the reference denoising architecture for diffusion.

Cross-attention injects the text: \mathrm{Attn}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V, \qquad Q = H_{\text{image}}W_Q, \quad K = E_{\text{text}}W_K, \quad V = E_{\text{text}}W_V, where the rows of H_{\text{image}} are the spatial activations of the denoiser, the rows of E_{\text{text}} the tokens of the prompt, and d_k the width of a query: every image position “queries” the text (cf. Deep Learning module, ch. 6).

Family Learning Strengths Weaknesses
VAE likelihood (ELBO) structured latent, fast blurry, loose ELBO
GAN adversarial sharp, realistic unstable, lost modes
Diffusion denoising (score) SOTA quality/diversity, guidance slow (multi-step), costly
Autoregressive sequential cross-entropy exact probabilistic slow sequential

1. VAEs and latent spaces

Concrete scene: a team generates product images from short briefs. With a guidance weight that is too high, the images are saturated and leave the distribution of real photos; too low, the prompt is ignored. Such failures can only be diagnosed by someone who knows which objective each generator optimizes. This chapter starts with the simplest one, the VAE, which learns to compress an image into a few latent numbers and to decode it back.

What breaks Posterior collapse (VAE); mode collapse (GAN); miscalibrated guidance (diffusion); evaluating only FID while missing semantic failures.

Definition 1.1 — Conditional & hierarchical VAE Conditioning the generation: p_\theta(x \mid c) with c a class, a text (encoded), another modality. Hierarchical VAEs (HiVAE) stack latents p(z_1 \mid z_2)\, p(z_2 \mid z_3)\dots; VQ-VAEs quantize the latent into a learned dictionary (discrete codes — the ancestor of image tokens); VQ-VAE-2 reached image fidelity before diffusion.

What the latent buys Compressing a 512 \times 512 \times 3 image into a 64 \times 64 \times 4 latent divides the number of spatial positions by 64 (and the number of values by 48); all large image generative models (Stable Diffusion, DALL·E 2/3) generate in latent space — the autoencoder (light) and the generator (heavy) are decoupled. The same principle applies to graphs: latent graph, discrete codes (Graph ML module, ch. 9).

Theorem 1.2 — ELBO decomposition: reconstruction + regularization (recall) The ELBO of theorem 0.2 is the sum of two forces (expanded term by term in Deep Learning, section 9.2): \mathrm{ELBO}_\phi(x) = \underbrace{\mathbb{E}_{q_\phi(z\mid x)}\big[\log p_\theta(x \mid z)\big]}_{\text{reconstruction}} \;-\; \underbrace{\mathrm{KL}\big(q_\phi(z\mid x)\,\|\,p(z)\big)}_{\text{latent regularization}}. Interpretation of the two forces: the first term asks for a z that explains x (auto-encoding), the second for a z that is typical under the prior.

The tension between the two structures the latent space: without the KL, q can memorize (“hole” regions not covered by the prior); without reconstruction, z encodes nothing.

From the ELBO to the lab losses When p_\theta(x\mid z) is a diagonal Gaussian of mean D_\theta(z) and fixed variance \sigma^2, the reconstruction term equals -\frac{1}{2\sigma^2}\|x - D_\theta(z)\|^2 + \mathrm{cst}: the “reconstruction MSE” of the labs is nothing but the negative of a Gaussian log-likelihood, and a Bernoulli decoder gives the binary cross-entropy of the code below. When q_\phi and p are Gaussian, the second term closes via prop. 0.4.

Posterior collapse: diagnosis and remedies The decoder (often an autoregressive transformer) becomes so powerful that it ignores z: q_\phi(z\mid x) \to p(z), the KL drops toward 0 and the VAE degenerates into a non-conditional model (the latent “collapses”). Causes: a strong autoregressive decoder, a dominant KL early in training, an overly simple prior.

  • KL annealing: weight the KL by a coefficient \beta_{\mathrm{KL}} that slowly rises from 0 to 1 — let the reconstruction settle first;
  • \beta-VAE (Higgins et al., 2017): maximizing the reconstruction term minus \beta_{\mathrm{KL}} times the KL, with \beta_{\mathrm{KL}} > 1, forces a disentangled latent (one direction = one factor of variation); in practice, against collapse one rather uses \beta_{\mathrm{KL}} < 1.
  • Notation. On this page \beta_{\mathrm{KL}} is the KL weight, \beta_c the VQ commitment weight (construction 1.3), and a bare \beta_t always the noise schedule of ch. 3.
  • Free bits: penalize the KL per dimension only beyond a budget \lambda: \max(\mathrm{KL}_j, \lambda) — every dimension receives a free “information allowance”, which prevents it from dying.

Construction 1.3 — VQ-VAE: quantizing the latent The encoder produces z_e(x) \in \mathbb{R}^{H \times W \times D}; a codebook \{e_1, \dots, e_K\} \subset \mathbb{R}^D is learned; each position is quantized to the nearest code: z_q(x) = e_k, \qquad k = \arg\min_j \|z_e(x) - e_j\|_2. The argmin is not differentiable. One uses the straight-through estimator (gradient copy) and the total loss: \mathcal{L} = -\log p_\theta\big(x \mid z_q\big) + \big\|\mathrm{sg}[z_e] - e\big\|_2^2 + \beta_c\,\big\|z_e - \mathrm{sg}[e]\big\|_2^2, where \mathrm{sg} is the stop-gradient operator and \beta_c the commitment weight (0.25 in the original paper).

Proof. Why this three-term loss?

  • (i) The reconstruction must be a function of the quantized codes z_q — but \nabla_{z_e} z_q = 0 (argmin): we define \frac{\partial \mathcal{L}}{\partial z_e} \mathrel{:=} \frac{\partial \mathcal{L}}{\partial z_q} (straight-through); the estimator is biased yet empirically effective.
  • (ii) The term \|\mathrm{sg}[z_e] - e\|^2 is quadratic in e (the codes migrate toward the produced encodings); the stop-gradient symmetrically prevents the encoder from moving.
  • (iii) The term \beta_c\|z_e - \mathrm{sg}[e]\|^2 does the opposite: it pulls the encoder toward the codes.

The codebook term (ii) and the commitment term (iii) synchronize encoder and dictionary, while the first term trains the decoder; together they implement a continuous K-means inside the training loop. ∎

Hierarchy and sampling. In a HiVAE, the ELBO becomes \mathbb{E}_{q(z_1, z_2\mid x)}\big[\log p_\theta(x \mid z_1) + \log p(z_1 \mid z_2) + \log p(z_2) - \log q_\phi(z_1 \mid x, z_2) - \log q_\phi(z_2 \mid x)\big], each level compressing the previous one (the “low” scales govern composition, the “high” ones the details — exactly the levels of a U-Net).

To generate: sample z \sim \mathcal{N}(0, I) (or the levels of the learned prior, as in VQ-VAE-2), then decode in a single network pass; latent traversals (interpolating z between two images) are the visual test of the continuity of the learned space.

import torch

class MiniVAE(torch.nn.Module):
    """Minimal convolutional VAE for MNIST-like data (28x28)."""
    def __init__(self, d=8):
        super().__init__()
        self.enc = torch.nn.Sequential(            # x: (B,1,28,28)
            torch.nn.Conv2d(1, 32, 4, 2, 1), torch.nn.ReLU(),   # 14x14
            torch.nn.Conv2d(32, 64, 4, 2, 1), torch.nn.ReLU(),  # 7x7
            torch.nn.Flatten(), torch.nn.Linear(64*7*7, 2*d))
        self.dec = torch.nn.Sequential(
            torch.nn.Linear(d, 64*7*7), torch.nn.Unflatten(1, (64, 7, 7)),
            torch.nn.ConvTranspose2d(64, 32, 4, 2, 1), torch.nn.ReLU(),
            torch.nn.ConvTranspose2d(32, 1, 4, 2, 1), torch.nn.Sigmoid())
    def forward(self, x):
        h = self.enc(x); mu, logvar = h.chunk(2, dim=1)
        z = mu + torch.exp(0.5*logvar) * torch.randn_like(mu)   # reparametrization
        return self.dec(z), mu, logvar

def vae_loss(x, xh, mu, logvar, beta_kl=1.0):
    rec = torch.nn.functional.binary_cross_entropy(
        xh, x, reduction="sum") / x.size(0)                      # reconstruction
    kl  = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) / x.size(0)  # prop. 0.4
    return rec + beta_kl * kl                                   # -ELBO when beta_kl = 1

LLGA analogies The VQ-VAE manufactures image tokens: DALL·E 1 generates these tokens autoregressively (LLMs module), latent diffusion replaces them with continuous denoising (ch. 4). On graphs, the same discrete/continuous dichotomy opposes discrete VAEs and edge diffusion (Graph ML, ch. 9); in NLP, the CLIP “latent” (ch. 5) is the shared text-image space.

2. GANs: adversary, equilibrium, Wasserstein

VAE samples are blurry because the decoder is trained to be right on average. A GAN drops the likelihood altogether: a generator learns to produce samples that a second network, the discriminator, cannot tell apart from real data. This chapter analyzes that game, its equilibrium, its failure modes, and the Wasserstein variant that repairs its gradients.

Definition 2.1 — The minimax game and its refinements \min_G \max_D\ V(D, G) = \mathbb{E}_{x \sim p_{\mathrm{data}}}[\log D(x)] + \mathbb{E}_{z \sim p(z)}[\log(1 - D(G(z)))] D classifies “real/fake”, G forges counterfeits. In practice one uses the non-saturated form \max_G \mathbb{E}_z[\log D(G(z))] (same equilibria, stronger gradients early in training), or alternative losses: least-squares GAN, hinge. Conditional version: G(z, c), D(x, c) — Pix2Pix (image-to-image with an L1 reconstruction constraint).

Recall — proved in Deep Learning (P1), section 9.3

  • Theorem 2.2 — Equilibrium of the game (Deep Learning, theorem 9.6). (i) For fixed G, the optimal discriminator is D^*_G(x) = \frac{p_{\mathrm{data}}(x)}{p_{\mathrm{data}}(x) + p_g(x)}.
    1. For every G, the value of the game at this discriminator is C(G) = V(D^*_G, G) = -\log 4 + 2\,\mathrm{JS}(p_{\mathrm{data}} \| p_g), \qquad \mathrm{JS}(p\|q) = \tfrac12\mathrm{KL}\big(p\,\|\,\tfrac{p+q}{2}\big) + \tfrac12\mathrm{KL}\big(q\,\|\,\tfrac{p+q}{2}\big). Since \mathrm{JS} \ge 0 with equality iff p_g = p_{\mathrm{data}}, the global minimum C(G^*) = -\log 4 is attained only there: at equilibrium, the generator exactly reproduces the data distribution.
  • Proof idea: maximize a\log D + b\log(1-D) pointwise in D \in (0,1), which gives D^* = a/(a+b); then substitute and rewrite both logarithms against the mixture \tfrac12(p_{\mathrm{data}} + p_g).

Example 2.3 — The Gaussian case If p_{\mathrm{data}} = \mathcal{N}(\mu, \sigma^2) and p_g = \mathcal{N}(\mu_g, \sigma_g^2), formula (i) gives an explicit D^* (via the densities): the optimal classifier is a sigmoid of a quadratic score — two Gaussians separate along a quadratic boundary. Backpropagating \log D^*(G(z)) pushes \mu_g \to \mu and \sigma_g^2 \to \sigma^2: this is the toy version (exercise 3) of the theorem.

Mode collapse: analysis and mitigations The theorem describes the global equilibrium, but the game is non-cooperative: G may find it profitable to produce in a loop one highly deceptive image (one mode of the distribution), then switch to another — oscillations and loss of diversity. The gradient of G only “sees” the generated points: never-sampled modes are never corrected. Mitigations:

  • Minibatch discrimination (Salimans et al., 2016): a learned tensor T maps the features f(x_i) of each sample to a matrix M_i with rows M_{i,b}, b = 1, \dots, B. Each row gives one intra-batch similarity feature; the vector of these features is concatenated with the input features and fed to the next layer of D: c_b(x_i, x_j) = \exp\!\big(-\|M_{i,b} - M_{j,b}\|_1\big), \qquad o(x_i)_b = \sum_{j=1}^{n} c_b(x_i, x_j) — the discriminator detects “all-identical” batches;
  • Unrolled GAN: G is trained against the D it will face (k lookahead steps of the discriminator), which removes pure pursuit cycles;
  • LLGA monitoring: intra-batch diversity (mean LPIPS), FID on large cohorts — the industrial diagnostics of ch. 7.

Construction 2.4 — WGAN: Wasserstein to the rescue of JS When the supports of p and q are disjoint or “nearly” so, JS is constant (value \log 2) and its gradient vanishes: no more learning signal. The Wasserstein distance W_1, on the other hand, stays informative. By the Kantorovich–Rubinstein duality (sketched below): W_1(p, q) = \sup_{\|f\|_L \le 1}\ \mathbb{E}_{p}[f(x)] - \mathbb{E}_{q}[f(x)], hence the adversarial learning \min_G \max_{\|D\|_L \le 1} \mathbb{E}_{p}[D] - \mathbb{E}_{q}[D]: D becomes a 1-Lipschitz critic, and the loss is continuous in the parameters of G even at disjoint supports.

Proof. Sketch of the duality, with W_1(p, q) = \inf_\gamma \mathbb{E}_\gamma\|x - y\| over the couplings \gamma of p and q.

  • Easy direction. For every 1-Lipschitz f and every coupling \gamma, \mathbb{E}_p[f] - \mathbb{E}_q[f] = \mathbb{E}_{\gamma}[f(x) - f(y)] \le \mathbb{E}_{\gamma}[\|x - y\|]; taking the infimum over the couplings gives \sup \le W_1.
  • Equality, in three steps.
    1. Linear-programming duality for the transport problem gives W_1(p, q) = \sup\big\{\mathbb{E}_p[f] + \mathbb{E}_q[g] \;:\; f(x) + g(y) \le \|x - y\| \text{ for all } x, y\big\}.
    2. For a feasible pair, replacing g by f^c(y) = \inf_x \|x - y\| - f(x) keeps the pair feasible and can only increase the objective; f^c is 1-Lipschitz, as an infimum of 1-Lipschitz functions of y.
    3. A 1-Lipschitz h satisfies h^c = -h: the choice x = y in the infimum gives one inequality, the Lipschitz bound the other. Replacing then the first function by (f^c)^c = -f^c, which again keeps the pair feasible and cannot lower the objective, leaves a pair (\varphi, -\varphi) with \varphi 1-Lipschitz: the supremum of the theorem.

Step (1) is the hard part. Optimal Transport proves it in the discrete case (theorem 2.1, ch. 2) and derives this duality as proposition 4.2, ch. 4; read it only, since that course sits in the same “Choose 1” group.

The Lipschitz constraint in practice: gradient penalty. Weight clipping (original WGAN) enforces Lipschitzness too brutally. Instead we penalize the deviation of the gradient norm from 1 on interpolations \tilde x = \epsilon x + (1-\epsilon)\hat x between data x and generation \hat x: \mathcal{L}_{\mathrm{GP}} = \lambda\,\big(\|\nabla_{\tilde x} D(\tilde x)\|_2 - 1\big)^2. Why (\|\nabla D\| - 1)^2 and not \max(0, \|\nabla D\| - 1): penalizing too-small gradients as well prevents D from flattening out (loss of signal); why interpolations: the supremum of the dual “lives” along the transport segments between the two distributions — that is where the constraint matters. ∎

Architecture 2.5 — StyleGAN: from noise to style

  1. Mapping network: w = m(z), an 8-layer MLP — w lives in a “disentangled” space where directions correspond to attributes;
  2. AdaIN (adaptive instance norm): at each generator layer, the style modulates the instance normalization: \mathrm{AdaIN}(x, w) = \sigma(w_s)\,\frac{x - \mu(x)}{\sigma(x)} + w_b, where (w_s, w_b) are affine transformations of w specific to the layer — each resolution receives its own style;
  3. Style mixing: during training, inject two different w depending on the layers (one for coarse resolutions, the other for fine ones) — this regularizes the mapping and uncovers the structure/texture hierarchy;
  4. Truncation trick: at generation, w' = \bar w + \psi\,(w - \bar w) with \psi < 1, \bar w the mapping mean — one stays in the high densities: higher fidelity, reduced diversity (exercise 7).

CycleGAN: cycle consistency, proved useful Without training pairs, translate X \to Y with G and Y \to X with F using \mathcal{L}_{\mathrm{cyc}} = \mathbb{E}_x\big[\|F(G(x)) - x\|_1\big] + \mathbb{E}_y\big[\|G(F(y)) - y\|_1\big]. Why this is the right constraint. The adversarial loss alone allows G(x) = y_0 for every x (a single highly “realistic” image fools D: cross-domain collapse, and the content of x is lost).

If F(G(x)) = x for every x in the support, then G is injective: it can neither collapse modes nor destroy content information — it can only change what F knows how to restore.

Cycle consistency is an information-preserving constraint made differentiable; combined with the adversarial loss (which imposes the target-domain style), it achieves the translation. The L1 term (rather than L2) favors sharpness (less blurry averaging).

Evaluation: IS and FID Inception Score: \mathrm{IS} = \exp\big(\mathbb{E}_x\,\mathrm{KL}(\,p(y\mid x)\,\|\,p(y)\,)\big) — each image must be clearly classifiable (p(y\mid x) peaked) and the whole set diverse (p(y) spread).

FID: fit a Gaussian to the Inception features of the real images (\mu_r, \Sigma_r) and of the generated ones (\mu_g, \Sigma_g), then \mathrm{FID} = \|\mu_r - \mu_g\|^2 + \mathrm{tr}\big(\Sigma_r + \Sigma_g - 2(\Sigma_r\Sigma_g)^{1/2}\big) \;=\; W_2^2\ \text{(Bures) between the two Gaussians} — the squared Wasserstein-2 distance between the two fitted Gaussians, by proposition 2.6 below; analysis of sampling biases in ch. 7.

Why diffusion eventually dominated: stable loss (a simple denoising MSE), no equilibrium to maintain, natural diversity — but GANs remain unbeatable in speed (1 step) and live on in super-resolution and editing.

Proposition 2.6 — Wasserstein-2 between Gaussians (Bures) With W_2^2(p, q) = \inf_\gamma \mathbb{E}_\gamma\|x - y\|^2 over the couplings of p and q, W_2^2\big(\mathcal{N}(m_1, \Sigma_1), \mathcal{N}(m_2, \Sigma_2)\big) = \|m_1 - m_2\|^2 + \mathcal{B}^2(\Sigma_1, \Sigma_2), \mathcal{B}^2(\Sigma_1, \Sigma_2) = \mathrm{tr}\Big(\Sigma_1 + \Sigma_2 - 2\big(\Sigma_1^{1/2}\Sigma_2\Sigma_1^{1/2}\big)^{1/2}\Big), where \mathcal{B} is the Bures distance between covariance matrices. The FID writes \mathrm{tr}(\Sigma_r\Sigma_g)^{1/2} for the same trace: \Sigma_r\Sigma_g is similar to \Sigma_r^{1/2}\Sigma_g\Sigma_r^{1/2}, so they have the same nonnegative eigenvalues.

Proof. Sketch in three steps (the full proof is Optimal Transport, theorem 2.7, reading only).

  1. The means separate. Write \tilde x = x - m_1 and \tilde y = y - m_2. For any coupling the cross term has zero mean, so \mathbb{E}\|x - y\|^2 = \|m_1 - m_2\|^2 + \mathbb{E}\|\tilde x - \tilde y\|^2.
  2. A trace to maximize. With the cross-covariance C = \mathbb{E}[\tilde x\tilde y^\top], \mathbb{E}\|\tilde x - \tilde y\|^2 = \mathrm{tr}\,\Sigma_1 + \mathrm{tr}\,\Sigma_2 - 2\,\mathrm{tr}\,C. The joint covariance of (\tilde x, \tilde y) must stay positive semidefinite, and the largest \mathrm{tr}\,C it allows is \mathrm{tr}\big(\Sigma_1^{1/2}\Sigma_2\Sigma_1^{1/2}\big)^{1/2}.
  3. It is attained by a linear map. For \Sigma_1 invertible, take \tilde y = A\tilde x with A = \Sigma_1^{-1/2}\big(\Sigma_1^{1/2}\Sigma_2\Sigma_1^{1/2}\big)^{1/2}\Sigma_1^{-1/2}, which is symmetric and maps \mathcal{N}(0, \Sigma_1) to \mathcal{N}(0, \Sigma_2); substituting gives the formula. ∎

3. Diffusion: DDPM and score matching

Diffusion models generate by reversing a destruction: noise is added to an image step by step until nothing is left, and a network learns to undo one step at a time. Each step is a small Gaussian problem, which makes training a stable regression — the reason why diffusion replaced GANs at the top of image generation.

Model 3.1 — Forward process (noising) A Markov chain that adds Gaussian noise: q(x_t \mid x_{t-1}) = \mathcal{N}\big(\sqrt{1 - \beta_t}\, x_{t-1},\ \beta_t I\big), \qquad t = 1, \dots, T, with increasing \beta_t. Key property (composition of Gaussians): q(x_t \mid x_0) = \mathcal{N}\big(\sqrt{\bar\alpha_t}\, x_0,\ (1 - \bar\alpha_t) I\big), \qquad \alpha_t = 1 - \beta_t,\quad \bar\alpha_t = \prod_{s = 1}^{t}\alpha_s. For T = 1000, \bar\alpha_T \approx 0: the image has become pure noise.

Proof. By induction on t.

  • Base case: t = 1: x_1 = \sqrt{\alpha_1}\,x_0 + \sqrt{1 - \alpha_1}\,\epsilon, so q(x_1 \mid x_0) = \mathcal{N}(\sqrt{\bar\alpha_1}x_0,\ (1-\bar\alpha_1)I) by definition.
  • Inductive step: assume x_{t-1} \mid x_0 \sim \mathcal{N}(\sqrt{\bar\alpha_{t-1}}\,x_0,\ (1-\bar\alpha_{t-1})I). Then x_t = \sqrt{\alpha_t}\,x_{t-1} + \sqrt{1-\alpha_t}\,\epsilon, \qquad \epsilon \perp x_{t-1} \mid x_0. By property 0.1 (sum of independent Gaussians), the mean is \sqrt{\alpha_t}\cdot\sqrt{\bar\alpha_{t-1}}\,x_0 = \sqrt{\bar\alpha_t}\,x_0 (since \alpha_t \bar\alpha_{t-1} = \bar\alpha_t) and the variance is \alpha_t(1-\bar\alpha_{t-1}) + (1-\alpha_t) = 1 - \bar\alpha_{t-1} + \alpha_t\bar\alpha_{t-1} = 1 - \bar\alpha_t. ∎

Variance schedule: linear or cosine The choice of the \beta_t sets the speed of destruction. Linear (\beta_t: 10^{-4} \to 0.02, original DDPM): high frequencies die too fast, and the end of the chain is needlessly noisy. Cosine (Nichol & Dhariwal, 2021): \bar\alpha_t = \frac{f(t)}{f(0)}, \qquad f(t) = \cos^2\!\left(\frac{t/T + 0.008}{1.008}\cdot\frac{\pi}{2}\right), which gives a gently sloped decay of \bar\alpha_t, effective also at low resolution. Rule of thumb: the schedule must destroy information uniformly across the scales of the image.

Model 3.2 — Learned reverse process and per-step ELBO p_\theta(x_{t-1} \mid x_t) = \mathcal{N}\big(\mu_\theta(x_t, t),\ \sigma_t^2 I\big), \qquad p(x_T) = \mathcal{N}(0, I), and training reduces to a simple MSE:

Key result — the DDPM training loss \mathcal{L} = \mathbb{E}_{x_0, \epsilon, t}\big[\|\epsilon - \epsilon_\theta(x_t, t)\|^2\big], \qquad x_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1 - \bar\alpha_t}\,\epsilon.

Proof.

  • Step 1 — telescoping. Applying thm. 0.2 to the chain p_\theta(x_{0:T}) with q(x_{1:T}\mid x_0), the ELBO rewrites (Markov chain, telescoped products): -\mathrm{ELBO} = \mathrm{KL}\big(q(x_T\mid x_0)\,\|\,\mathcal{N}(0,I)\big) + \sum_{t=2}^{T}\mathbb{E}_q\!\left[\mathrm{KL}\big(q(x_{t-1}\mid x_t, x_0)\,\|\,p_\theta(x_{t-1}\mid x_t)\big)\right] - \mathbb{E}_q\big[\log p_\theta(x_0 \mid x_1)\big] = L_T + \sum_{t \ge 2} L_{t-1} + L_0.
  • Step 2 — closed-form forward posterior. By Bayes’ rule q(x_{t-1}\mid x_t, x_0) \propto q(x_t \mid x_{t-1})\,q(x_{t-1}\mid x_0): a product of two Gaussians in x_{t-1}, hence Gaussian; completing the square: q(x_{t-1}\mid x_t, x_0) = \mathcal{N}\big(\tilde\mu_t(x_t, x_0),\ \tilde\beta_t I\big), \quad \tilde\beta_t = \frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\,\beta_t,\quad \tilde\mu_t = \frac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1-\bar\alpha_t}\,x_0 + \frac{\sqrt{\alpha_t}(1-\bar\alpha_{t-1})}{1-\bar\alpha_t}\,x_t.
  • Step 3 — every L_{t-1} is a KL of Gaussians: closed by prop. 0.4. If we set \sigma_t^2 = \tilde\beta_t, what remains is to align the means: L_{t-1} = C + \frac{1}{2\sigma_t^2}\|\tilde\mu_t - \mu_\theta\|^2.
  • Step 4 — noise parameterization. We choose \mu_\theta(x_t, t) = \frac{1}{\sqrt{\alpha_t}}\Big(x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\epsilon_\theta(x_t, t)\Big), which amounts (substituting x_0 = (x_t - \sqrt{1-\bar\alpha_t}\,\epsilon)/\sqrt{\bar\alpha_t} into \tilde\mu_t) to requiring \epsilon_\theta \approx \epsilon; all the remaining factors are known constants absorbed into the weighting.

Hence the single MSE of model 3.2 — a remarkable result: five lines of theory for a one-line loss. ∎

Theorem 3.3 — Predicting the noise = predicting the score \epsilon = -\sqrt{1-\bar\alpha_t}\;\nabla_{x_t}\log p(x_t \mid x_0). The denoising MSE is therefore a conditional score matching: the network learns \nabla_x \log p — exactly the object of the “score-based” family of Song et al. (2021), which unifies diffusion and SDEs (ch. 4).

Proof. For a Gaussian density p(x_t \mid x_0) = \mathcal{N}(x_t;\ m, s^2 I) with m = \sqrt{\bar\alpha_t}\,x_0, s^2 = 1 - \bar\alpha_t, we compute \nabla_{x_t}\log p(x_t\mid x_0) = \nabla_{x_t}\left[-\frac{\|x_t - m\|^2}{2s^2}\right] + 0 = -\frac{x_t - \sqrt{\bar\alpha_t}\,x_0}{1-\bar\alpha_t}. Now x_t - \sqrt{\bar\alpha_t}\,x_0 = \sqrt{1-\bar\alpha_t}\,\epsilon, so \nabla_{x_t}\log p = -\epsilon/\sqrt{1-\bar\alpha_t}, that is \epsilon = -\sqrt{1-\bar\alpha_t}\,\nabla_{x_t}\log p(x_t \mid x_0). ∎

Theorem 3.3 is about the conditional score, given the clean image x_0. Sampling needs the score \nabla\log p_t(x_t) of the noised data distribution p_t itself, which no formula gives. The next theorem shows that regressing on the conditional score is enough.

Theorem 3.4 — Denoising score matching (Vincent, 2011) Let p be the data law, q(\tilde x \mid x) a noising kernel and q(\tilde x) = \int q(\tilde x \mid x)\,p(x)\,dx the noised marginal. For every score model s_\theta, \mathbb{E}_{\tilde x \sim q}\big\|s_\theta(\tilde x) - \nabla\log q(\tilde x)\big\|^2 = \mathbb{E}_{x \sim p,\ \tilde x \sim q(\cdot\mid x)}\big\|s_\theta(\tilde x) - \nabla_{\tilde x}\log q(\tilde x \mid x)\big\|^2 + C, where C does not depend on \theta. Both losses have the same minimizer: the marginal score.

Consequence for DDPM. Take the kernel q(x_t \mid x_0) of model 3.1 and set s_\theta = -\epsilon_\theta/\sqrt{1-\bar\alpha_t}. By theorem 3.3, the right-hand side becomes the noise MSE of model 3.2 divided by 1-\bar\alpha_t. A trained denoiser therefore gives the marginal score: \nabla_{x_t}\log p_t(x_t) \;\approx\; -\frac{\epsilon_\theta(x_t, t)}{\sqrt{1-\bar\alpha_t}}.

Proof. Expand both squares.

  • The terms in \|s_\theta\|^2 agree: on the right, \tilde x has marginal law q.
  • The terms without s_\theta do not depend on \theta; they go into C.
  • The cross terms agree. Using \nabla q = q\,\nabla\log q twice, and exchanging gradient and integral, \mathbb{E}_{q(\tilde x)}\big[s_\theta^\top\nabla\log q(\tilde x)\big] = \int s_\theta(\tilde x)^\top \!\int p(x)\,\nabla_{\tilde x} q(\tilde x \mid x)\,dx\,d\tilde x = \mathbb{E}_{p(x)\,q(\tilde x\mid x)}\big[s_\theta(\tilde x)^\top\nabla_{\tilde x}\log q(\tilde x \mid x)\big]. ∎

Sampling with a score: Langevin dynamics A score alone is enough to sample. The unadjusted Langevin algorithm (ULA) with step \gamma iterates x_{k+1} = x_k + \gamma\,s(x_k) + \sqrt{2\gamma}\,z_k, \qquad z_k \sim \mathcal{N}(0, I). When s = \nabla\log p and \gamma is small, its stationary law is close to p: Probability and Monte Carlo, ch. 9 proves that p is invariant for the continuous dynamics and computes the \mathcal{O}(\gamma) bias of the discretization.

A score learned on clean data is poor far from the data, exactly where a chain started from noise begins. Annealed Langevin (Song & Ermon, 2019) therefore runs a few Langevin steps at each of a decreasing sequence of noise levels, using the scores of the noised marginals that theorem 3.4 teaches the network.

The DDPM reverse step of model 3.2 is a close relative: one “predictor” move from level t to level t-1. Predictor–corrector samplers (Song et al., 2021) add Langevin “corrector” steps at each level.

import torch

def forward_diffusion(x0, t, alphas_bar, eps=None):
    """x_t = sqrt(a_bar_t) x0 + sqrt(1 - a_bar_t) * eps   (in one step!)"""
    if eps is None: eps = torch.randn_like(x0)
    return alphas_bar[t].sqrt()[:, None, None, None] * x0 \
         + (1 - alphas_bar[t]).sqrt()[:, None, None, None] * eps, eps

# Training (typical DDPM loop):
# x0 = batch of images; t ~ U{1..T}
xt, eps = forward_diffusion(x0, t, alphas_bar)
loss = torch.nn.functional.mse_loss(unet(xt, t), eps)   # predict the noise
loss.backward()

# Sampling (T steps, formula of model 3.2):
x = torch.randn(n, c, h, w)                    # x_T ~ N(0, I)
for t in reversed(range(T)):
    eps = unet(x, t)
    mu = (x - beta[t]/(1 - alphas_bar[t]).sqrt() * eps) / alpha[t].sqrt()
    x = mu + beta[t].sqrt() * torch.randn_like(x) if t > 0 else mu

LLGA analogies The diffusion U-Net uses self-attention (a transformer on a grid); DiTs replace everything with transformers on patches; and diffusion on graphs (DiGress) noises/denoises node and edge types — the same algorithm, another space (Graph ML module, ch. 9). The derivation “Markov chain → ELBO → per-step KL → MSE” we have just done is literally the same as the one in Deep Learning module ch. 9 for the VAE — diffusion is a VAE of depth T with shared parameters.

4. Guidance, DDIM, flows and latent diffusion

A trained diffusion model samples from the whole data distribution, slowly, in pixel space. This chapter adds the ingredients that turn it into a product: guidance, to follow a condition such as a prompt (4.1); faster samplers, to need 20 steps instead of 1000 (4.2); and latent diffusion, to work in a compressed space (4.4). In between, section 4.3 reads diffusion as a flow and derives flow matching, its simpler successor.

4.1. Guidance

Classifier guidance (Dhariwal & Nichol, 2021) By Bayes, \log p(x_t \mid y) = \log p(y \mid x_t) + \log p(x_t) - \log p(y); taking the gradient in x_t, the last term disappears: \nabla_{x_t}\log p(x_t \mid y) = \nabla_{x_t}\log p(x_t) + \nabla_{x_t}\log p(y\mid x_t). Via thm. 3.3 (\epsilon corresponds to -\sqrt{1-\bar\alpha_t}\,\nabla\log p), the guided denoiser is \tilde\epsilon = \epsilon_\theta(x_t, t) - \sqrt{1-\bar\alpha_t}\,\nabla_{x_t}\log p_\psi(y \mid x_t), where p_\psi is a classifier trained on the noised x_t. Powerful but costly: a classifier must be trained and evaluated at every step.

Theorem 4.1 — Classifier-free guidance (CFG) as a combined direction Train \epsilon_\theta(x_t, t, c) with c sometimes replaced by \varnothing (condition dropout, ~10 %); at generation, extrapolate the conditional direction:

Key result — classifier-free guidance \tilde\epsilon = \epsilon_\theta(x_t, t, \varnothing) + w\big(\epsilon_\theta(x_t, t, c) - \epsilon_\theta(x_t, t, \varnothing)\big), \qquad w > 1.

Exact interpretation: \tilde\epsilon is (up to the factor -\sqrt{1-\bar\alpha_t}) the score of the unnormalized distribution p_w(x_t \mid c) \;\propto\; p(x_t \mid c)^{w}\, p(x_t)^{1-w}.

Convention. This is the canonical form of CFG on this site: w = 1 is the plain conditional model, w = 0 the unconditional one. Control in Generative AI, 7.1 and Graph Generative Models, ch. 7 recall it from here, and Advanced Deep Learning, ch. 10 writes it in the same form. A text that writes (1+w')\,\epsilon_c - w'\,\epsilon_\varnothing uses w' = w - 1.

Proof. Again by Bayes, \nabla\log p(x_t\mid c) = \nabla\log p(c \mid x_t) + \nabla\log p(x_t) (the term \log p(c) is constant in x_t). The score of p_w is therefore \nabla\log p_w = w\,\nabla\log p(x_t\mid c) + (1-w)\,\nabla\log p(x_t) = \nabla\log p(x_t) + w\big(\nabla\log p(x_t\mid c) - \nabla\log p(x_t)\big). Replacing each score by the corresponding denoiser (thm. 3.3), we obtain exactly the CFG rule: it combines unconditional score + w times the difference of the scores.

For w = 1 we recover the conditional score; for w = 0 the unconditional one; for w > 1, the effective distribution p(x_t\mid c)^w p(x_t)^{1-w} over-weights the conditioning: it is more “peaked” (higher fidelity, better prompt-following) and less diverse. This is the “creativity” slider of all text-to-image tools — and a research topic in its own right (cf. ch. 9, schedules w(t)). ∎

4.2. Faster sampling: DDIM and the probability-flow ODE

Construction 4.2 — DDIM: deriving a family of samplers DDPM fixes p_\theta(x_{t-1}\mid x_t) as a Gaussian Markov kernel. The DDIM trick: any process whose marginals q(x_t \mid x_0) are those of model 3.1 and whose expectation is written as a function of \hat x_0 leads to the same loss. We posit the non-Markovian family (parameterized by \sigma_t): q_\sigma(x_{t-1}\mid x_t, x_0) = \mathcal{N}\big(\sqrt{\bar\alpha_{t-1}}\,x_0 + \sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\;\tfrac{x_t - \sqrt{\bar\alpha_t}\,x_0}{\sqrt{1-\bar\alpha_t}},\ \sigma_t^2 I\big).

  • \sigma_t = \sqrt{\tilde\beta_t} recovers DDPM (the original Markov process);
  • \sigma_t = 0 gives deterministic DDIM: same initial noise x_T ⇒ same image (editing via a shared trajectory, reproducible seed);
  • the marginals q(x_t\mid x_0) are unchanged ⇒ the training loss (\epsilon-MSE) is identical; only the sampler changes;
  • Step skipping: the loss depends on the forward process only through the marginals q(x_t \mid x_0), so the same trained network serves a process defined on a sub-sequence \tau_1 < \tau_2 < \dots < \tau_S of the steps, for any choice of \sigma, stochastic samplers included — 20 to 50 steps instead of 1000. Determinism is not what allows the skipping; \sigma = 0 is simply the choice that degrades least when S is small.

Proof. Let us check the consistency of the marginals. From x_{t-1}\mid x_0 \sim \mathcal{N}(\sqrt{\bar\alpha_{t-1}}x_0,\ (1-\bar\alpha_{t-1})I) and the definition above, the proposed mean reads a\,x_0 + b\,(x_t - \sqrt{\bar\alpha_t}x_0) with b = \sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}/\sqrt{1-\bar\alpha_t}; conditionally on x_0, x_t is Gaussian centered at \sqrt{\bar\alpha_t}\,x_0, so the mean of x_{t-1} is indeed \sqrt{\bar\alpha_{t-1}}\,x_0 and its variance b^2(1-\bar\alpha_t) + \sigma_t^2 = 1-\bar\alpha_{t-1} — the desired marginal. We thus obtain infinitely many samplers compatible with the same trained \epsilon_\theta. ∎

The SDE viewpoint (Song et al., 2021) As T \to \infty, the forward process converges to the SDE dx = f(x, t)\,dt + g(t)\,dw. Then every SDE has a deterministic companion with the same marginal laws, the probability flow ODE: \frac{dx}{dt} = f(x, t) - \tfrac{1}{2}g(t)^2\,\nabla_x \log p_t(x). Generating = integrating this ODE backward: this is the theoretical bridge between DDIM (deterministic) and the fast solvers below.

Fast solvers. DPM-Solver handles the probability-flow ODE by separating the linear part (exactly integrable, since the drift f is linear in x) from the non-linear part (the score): “exponential integrator” schemes at 10–15 steps. Distillation (consistency models, LCM, adversarial distillation — cf. ch. 9, Di[M]o) targets 1 to 4 steps, and quantization (fp16, fp8) compresses the compute — a panorama revisited in M2 ML Ops.

4.3. Flows: from change of variables to flow matching

A diffusion model turns noise into data through many small stochastic steps. A flow does it with an invertible map, or with an ordinary differential equation. This section builds flows from the change-of-variables formula, shows that the probability-flow ODE of 4.2 is one, and derives flow matching.

Flow matching is the training rule behind Stable Diffusion 3, the action expert of π0 (section 8.3) and flow-based speech synthesis (Speech Technology, ch. 7); the change of variables is also the starting point of the graph flows of Graph Generative Models, ch. 4.

Proposition 4.3 — Change of variables Let \Phi be a diffeomorphism of \mathbb{R}^d and x = \Phi(z) with z \sim p_Z. Then \log p_X(x) = \log p_Z(z) - \log\big|\det J_\Phi(z)\big|, \qquad z = \Phi^{-1}(x). For a composition \Phi = \Phi_K \circ \dots \circ \Phi_1, the log-determinants add up. A normalizing flow is such a composition with p_Z = \mathcal{N}(0, I), trained by maximizing this exact log-likelihood — no ELBO, no adversary.

Proof. For a measurable set A, \mathbb{P}(x \in A) = \mathbb{P}\big(z \in \Phi^{-1}(A)\big) = \int_{\Phi^{-1}(A)} p_Z(z)\,dz. The substitution z = \Phi^{-1}(x) multiplies dz by |\det J_{\Phi^{-1}}(x)| = |\det J_\Phi(z)|^{-1}, which gives the density. For a composition, the chain rule makes the Jacobian a product of Jacobians, and the determinant of a product is the product of the determinants. ∎

Definition 4.4 — Affine coupling layer (Dinh, Sohl-Dickstein and Bengio, 2017) Split x = (x_a, x_b) and keep the first half: y_a = x_a, \qquad y_b = x_b \odot \exp\big(s(x_a)\big) + m(x_a), where the scale s and the shift m are arbitrary networks. The inverse is explicit, x_b = (y_b - m(y_a)) \odot \exp(-s(y_a)), and the Jacobian is triangular with diagonal (1, \dots, 1, e^{s(x_a)}), so \log\big|\det J\big| = \sum_j s_j(x_a). Neither s nor m is ever inverted. Stacking couplings that alternate the two halves (RealNVP, Glow) gives an expressive flow at the cost of one network pass per layer.

Continuous flows. Let a velocity field move points by \dot x = v(x, t). The law p_t of x_t then obeys the continuity equation, and along a trajectory the log-density changes by the divergence of v (Chen et al., 2018): \partial_t p_t + \nabla\cdot(p_t\,v) = 0, \qquad \frac{d}{dt}\log p_t(x_t) = -\nabla\cdot v(x_t, t). This is proposition 4.3 for the infinitesimal map x \mapsto x + v\,dt, whose log-determinant is \nabla\cdot v\,dt to first order.

The probability-flow ODE of 4.2 is such a flow, with v = f - \tfrac12 g^2\nabla\log p_t, and deterministic DDIM is one discretization of it. A trained diffusion model is therefore a continuous flow, learned by score matching instead of maximum likelihood. Flow matching keeps the flow and drops the diffusion: it chooses the path and regresses its velocity directly.

Definition 4.5 — Straight path and its conditional velocity Time runs the other way here. Following Lipman et al. (2023), t = 0 is noise and t = 1 is data, the convention of π0 and of flow-based speech synthesis. Draw x_0 \sim \mathcal{N}(0, I), x_1 \sim p_{\mathrm{data}} independently and t \sim \mathcal{U}[0, 1], and set x_t = (1 - t)\,x_0 + t\,x_1, \qquad \frac{dx_t}{dt} = x_1 - x_0. Each pair moves on a straight line at constant speed, and the law p_t of x_t goes from \mathcal{N}(0, I) to p_{\mathrm{data}}.

Theorem 4.6 — Conditional flow matching (Lipman et al., 2023; Liu et al., 2023) Let u_t(x) = \mathbb{E}[x_1 - x_0 \mid x_t = x] be the marginal velocity.

  1. The field u_t transports p_t: \partial_t p_t + \nabla\cdot(p_t u_t) = 0. Integrating \dot x = u_t(x) from a Gaussian sample at t = 0 therefore gives a data sample at t = 1.
  2. For every model v_\theta, with C independent of \theta, \mathcal{L}_{\mathrm{CFM}}(\theta) = \mathbb{E}_{t, x_0, x_1}\big\|v_\theta(x_t, t) - (x_1 - x_0)\big\|^2 = \mathbb{E}_{t, x_t}\big\|v_\theta(x_t, t) - u_t(x_t)\big\|^2 + C.

The intractable marginal velocity is learned by regressing on the known straight-line velocity — the same move as denoising score matching (theorem 3.4).

Proof.

  1. For a smooth, compactly supported test function \varphi, the chain rule and the tower property of conditional expectation give \frac{d}{dt}\mathbb{E}[\varphi(x_t)] = \mathbb{E}\big[\nabla\varphi(x_t)^\top(x_1 - x_0)\big] = \mathbb{E}\big[\nabla\varphi(x_t)^\top u_t(x_t)\big], which is the weak form of the continuity equation for (p_t, u_t).
  2. Write Y = x_1 - x_0, so that u_t(x_t) = \mathbb{E}[Y \mid x_t]. At fixed t, the model output is a function of x_t. The conditional expectation is an L^2 projection, so the residual Y - u_t(x_t) is orthogonal to every such function: \mathbb{E}\|v_\theta - Y\|^2 = \mathbb{E}\|v_\theta - u_t(x_t)\|^2 + \mathbb{E}\|u_t(x_t) - Y\|^2, and the last term, averaged over t, is C. ∎

Flow matching in practice

  • The loss has a floor. C > 0 as soon as straight lines cross, so even a perfect model keeps a loss well above zero (about 1 on the two-moons example below): judge the samples, not the loss value.
  • Few steps. Sampling integrates \dot x = v_\theta(x, t) from t = 0 to t = 1 with Euler or Heun steps. Nearly straight paths need few steps, and rectified flow (Liu et al., 2023) straightens them further by retraining on its own (noise, sample) pairs.
  • Same information as noise prediction. With Gaussian x_0, substituting x_1 = (x_t - (1-t)\,x_0)/t gives u_t(x_t) = \frac{x_t - \mathbb{E}[x_0 \mid x_t]}{t}: the optimal velocity is an affine function of the optimal noise prediction, so a velocity network accepts the same guidance rule (theorem 4.1, applied to v_\theta).
  • Where it is used. Stable Diffusion 3 (Esser et al., 2024) trains a rectified-flow transformer in latent space (4.4); the action expert of π0 (Definition 8.8) generates action chunks this way; Voicebox does it on mel spectrograms (Speech Technology, ch. 7).
# Flow matching on two moons (definition 4.5, theorem 4.6): CPU, about a minute
import torch
from sklearn.datasets import make_moons

data = torch.tensor(make_moons(4096, noise=0.05)[0], dtype=torch.float32)
v = torch.nn.Sequential(torch.nn.Linear(3, 128), torch.nn.SiLU(),
                        torch.nn.Linear(128, 128), torch.nn.SiLU(),
                        torch.nn.Linear(128, 2))              # v_theta(x_t, t)
opt = torch.optim.Adam(v.parameters(), 1e-3)
for step in range(5000):
    x1 = data[torch.randint(len(data), (256,))]               # data, t = 1
    x0 = torch.randn_like(x1)                                 # noise, t = 0
    t = torch.rand(256, 1)
    xt = (1 - t) * x0 + t * x1                                # straight path
    loss = ((v(torch.cat([xt, t], 1)) - (x1 - x0))**2).mean() # CFM loss
    opt.zero_grad(); loss.backward(); opt.step()

@torch.no_grad()
def sample(n, steps=20):                                      # Euler on dx/dt = v
    x = torch.randn(n, 2)
    for k in range(steps):
        t = torch.full((n, 1), k / steps)
        x = x + v(torch.cat([x, t], 1)) / steps
    return x

In our run, the mean distance from a sample to the nearest of the 4096 training points was 0.13 with 2 Euler steps, 0.09 with 5 and 0.08 with 20: a handful of steps already lands on the moons.

4.4. Latent diffusion, ControlNet and DiT

DiT: when the transformer replaces the U-Net The latent image is cut into 2\times2 patches that are “tokenized” (like a ViT); each block = self-attention over the patches + MLP, modulated by time and condition via adaLN-Zero: h \leftarrow h + a_1 \odot \mathrm{Attn}\big((1 + \gamma_1) \odot \mathrm{LN}(h) + \delta_1\big), \qquad h \leftarrow h + a_2 \odot \mathrm{MLP}\big((1 + \gamma_2) \odot \mathrm{LN}(h) + \delta_2\big), where the scales \gamma_k, shifts \delta_k and gates a_k come from t_{\mathrm{emb}} + c_{\mathrm{emb}} through one linear layer initialized to zero. At initialization every gate is zero, so every block starts as the identity.

The scale is written 1 + \gamma_k so that the normalized input survives at initialization. With a plain \gamma_k, the attention branch would receive a zero input and, PyTorch’s attention biases being zero at initialization, no gradient at all: it would never train.

Quality grows steadily with depth, width and the number of tokens — a “scaling law” behavior typical of transformers, and the basis of modern video generators (ch. 8).

# Minimal DiT: a block modulated by time (adaLN-Zero)
class DiTBlock(torch.nn.Module):
    def __init__(self, d, n_heads):
        super().__init__()
        self.norm1 = torch.nn.LayerNorm(d, elementwise_affine=False)
        self.attn  = torch.nn.MultiheadAttention(d, n_heads, batch_first=True)
        self.norm2 = torch.nn.LayerNorm(d, elementwise_affine=False)
        self.mlp   = torch.nn.Sequential(torch.nn.Linear(d, 4*d), torch.nn.GELU(),
                                         torch.nn.Linear(4*d, d))
        self.mod = torch.nn.Sequential(torch.nn.SiLU(), torch.nn.Linear(d, 6*d))
        torch.nn.init.zeros_(self.mod[-1].weight)   # adaLN-Zero: scales, shifts
        torch.nn.init.zeros_(self.mod[-1].bias)     # and gates all start at 0
    def forward(self, h, cond):                     # h: (B, N, d) patches, cond: (B, d)
        g1, b1, a1, g2, b2, a2 = self.mod(cond).unsqueeze(1).chunk(6, dim=-1)
        u = self.norm1(h) * (1 + g1) + b1           # 1 + g: LN(h) survives at init
        h = h + a1 * self.attn(u, u, u, need_weights=False)[0]
        return h + a2 * self.mlp(self.norm2(h) * (1 + g2) + b2)

5. CLIP and vision-language alignment

To steer an image generator with a sentence, text and images must be comparable: a caption and the picture it describes should map to nearby vectors. CLIP learns such a shared space from 400 million captioned images found on the web; this chapter derives its contrastive loss and shows what the shared space makes possible.

CLIP (Radford et al., 2021) Encode images and texts jointly in a shared space: an image encoder (ViT) and a text encoder (transformer); 400M (image, caption) pairs collected from the web; contrastive learning (InfoNCE) on massive batches (up to 32k pairs).

The ViT in one paragraph (recap of Deep Learning, 6.6). A Vision Transformer cuts an H \times W image into P \times P patches, flattens each patch and maps it linearly to a d-dimensional token, adds a position embedding and one learned [CLS] token, then runs standard transformer blocks (self-attention + MLP) over the HW/P^2 + 1 tokens. The projected output of the [CLS] token is the image embedding v.

For CLIP’s ViT-B/32 at 224 \times 224 pixels, that is 7 \times 7 = 49 patch tokens plus one.

Contrastive loss: derivation In a batch of N pairs (v_i, t_i) (images and texts encoded and normalized), we compute the similarity matrix S_{ij} = \langle v_i, t_j\rangle / \tau (\tau the temperature). The symmetric InfoNCE loss:

Key result — the symmetric InfoNCE loss \mathcal{L} = -\frac{1}{2N}\sum_{i=1}^{N}\Big[\log\frac{e^{S_{ii}}}{\sum_j e^{S_{ij}}} + \log\frac{e^{S_{ii}}}{\sum_j e^{S_{ji}}}\Big].

Each term is a cross-entropy: in the image→text direction, classifying the right caption among N candidates; in the text→image direction, the right image among N — two crossed softmaxes on the same matrix.

The same loss is defined, without this derivation, in Large Language Models, 8.2b, the vision-language recap that Geometric Data, ch. 8 reuses for text–shape retrieval; 8.2b points here for the derivation.

Proof. Where does this form come from? Let p_i(j) = \mathrm{softmax}(S_{i\cdot})_j denote the “which caption for image i” distribution. The first term is -\log p_i(i): maximize the probability of the correct match. Expanding, -\log p_i(i) = -S_{ii} + \log\sum_j e^{S_{ij}} \;\ge\; -S_{ii} + \log e^{S_{ii}} = 0, a bound that is approached when S_{ii} dominates the rest of its row: the loss pushes positive pairs up and the N-1 negatives down (the softmax is a competition between similarities).

Link with mutual information (Oord et al., 2018): for negatives drawn from the product law, one can show the bound I(v; t) \;\ge\; \log N - \mathcal{L}_N, where I is the mutual information between modalities: InfoNCE maximizes a lower bound on I, ever tighter as N grows — hence the value of giant batches (complete proof: Oord et al., 2018). ∎

Temperature \tau (learned, initialized at 0.07) rescales the logits before the softmax: small \tau = peaked distribution = gradient concentrated on the hardest negatives; large \tau = uniform gradients (exercise 11). A temperature, written T there, also rescales the logits of LLM decoding (M2 module) — same role: dosing the “severity” of the competition.

Zero-shot classification: worked example No more fixed classification heads: the classes become texts. To classify an image among K labels \ell_1, \dots, \ell_K: \hat k = \arg\max_k\ \big\langle v,\ t(\text{"a photo of a }\ell_k\text{"})\big\rangle. Numerical example. Assume a 3-dimensional space, three classes {dog, cat, graph} and the normalized text embeddings t_{\mathrm{dog}} = (0.8;\ 0.6;\ 0), \qquad t_{\mathrm{cat}} = (0.6;\ 0.8;\ 0), \qquad t_{\mathrm{graph}} = (0;\ 0;\ 1). For an image v = (0.7;\ 0.5;\ 0.5), the dot products are 0.56 + 0.30 = 0.86; \qquad 0.42 + 0.40 = 0.82; \qquad 0.5. Dog wins (argmax) — without any classifier ever having been trained on these classes: the transfer happens through language. Enriched prompts (“a photo of a \ell, a type of pet”) act as a textual prior that refines the position of the prototypes.

CLIP, the multimodal Swiss Army knife CLIP is used everywhere: the text encoder of diffusion models; a similarity judge (R-Precision); image-text retrieval; moderation.

CLIPScore for text-image alignment: w\cdot\max(\cos(v, t), 0) with w = 2.5 (calibrated on human judgments; a cosine above ~0.3 typically indicates a matching caption).

ImageBind (sketch): aligning six modalities (image, text, audio, depth, thermal, IMU) with the image as the pivot: each modality is contrasted with the image only, and by the transitivity of the shared space, audio ↔︎ text emerge without ever having been paired.

The bridge with the master’s program: one can also align graphs and text in a common space (GNN ↔︎ LLM embeddings, Graph ML, ch. 10) — the graph “modality” enters the same contrastive alignment machinery.

Go further — text–graph CLIP for molecules. Text2Mol (Edwards, Zhai and Ji, 2021) and MoleculeSTM (Liu et al., 2023) train this symmetric InfoNCE between a molecule encoder (a graph neural network in their graph variants, Graph ML, ch. 5) and a text encoder, on molecule–description pairs. The shared space then serves as a retriever, as a guide for a graph generator and as a reward: this is the Y1.4 project “Molecules from words”.

from PIL import Image
from transformers import CLIPProcessor, CLIPModel
import torch

model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
proc  = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")

img = Image.open("graphe.png")
texts = ["a graph drawing", "a cat", "a molecule", "a city map"]
inputs = proc(text=texts, images=img, return_tensors="pt", padding=True)
with torch.no_grad():
    out = model(**inputs)
probs = out.logits_per_image.softmax(dim=1)   # zero-shot classification
print(dict(zip(texts, probs[0].tolist())))

# InfoNCE loss "by hand" (batch of aligned pairs):
# logits = v_norm @ t_norm.T / tau ; targets = arange(N)
# loss = 0.5 * (CE(logits, tgt) + CE(logits.T, tgt))

6. Text-to-image: the complete pipeline

This chapter assembles the components of the previous chapters — tokenizer, text encoder, latent diffusion with guidance, decoder — into the pipeline of a modern text-to-image system, and explains the controls that users actually turn: prompts, negative prompts and seeds.

Architecture 6.1 — From sentence to pixel The industrial pipeline of a latent text-to-image generator:

Step Component Role / details
1. Tokenization BPE / SentencePiece prompt → token sequence (NLP module); truncated to 77–225 depending on the model
2. Text encoding CLIP text encoder + T5/ByT5 tokens → (L \times d) tensor; CLIP’s pooled embedding also conditions adaLN (DiT)
3. Latent diffusion U-Net or DiT + cross-attention noise → denoised latent (20–50 steps, solver of ch. 4, CFG \tilde\epsilon)
4. Decoding VAE decoder latent (64\times64) → image (512\times512) in a single pass
5. Refinement refiner / super-resolution ×2–4 upsampling (by diffusion at higher resolution or a super-resolution GAN — ch. 2)

Training the large models often freezes the text encoder and the VAE, learning only the denoiser; LoRA (Low-Rank Adaptation) even freezes the denoiser and learns only low-rank corrections in the cross-attention weights — the “domestic” thematic fine-tuning (a few dozen images, a few GPU-minutes).

The pipeline in about forty lines. The Diffusers library (Hugging Face) ships the whole chain as one call, but writing the loop by hand shows each step of Architecture 6.1. The code below loads the four components of Stable Diffusion v1.4, encodes the prompt and the negative prompt, and runs DDIM with classifier-free guidance in latent space before decoding. On a free cloud GPU in half precision it takes a few seconds per image; on a CPU, a few minutes.

import torch
from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler
from transformers import CLIPTokenizer, CLIPTextModel

repo = "CompVis/stable-diffusion-v1-4"
dev = "cuda" if torch.cuda.is_available() else "cpu"
dt = torch.float16 if dev == "cuda" else torch.float32
tok = CLIPTokenizer.from_pretrained(repo, subfolder="tokenizer")            # step 1
txt = CLIPTextModel.from_pretrained(repo, subfolder="text_encoder",
                                    torch_dtype=dt).to(dev)                 # step 2
unet = UNet2DConditionModel.from_pretrained(repo, subfolder="unet",
                                            torch_dtype=dt).to(dev)         # step 3
vae = AutoencoderKL.from_pretrained(repo, subfolder="vae",
                                    torch_dtype=dt).to(dev)                 # step 4
sched = DDIMScheduler.from_pretrained(repo, subfolder="scheduler")          # eta = 0

@torch.no_grad()
def encode(prompt):                                  # (1, 77, 768) text tokens
    ids = tok([prompt], padding="max_length", max_length=tok.model_max_length,
              truncation=True, return_tensors="pt").input_ids.to(dev)
    return txt(ids)[0]

@torch.no_grad()
def generate(prompt, negative="", w=7.5, steps=30, seed=0, size=512):
    cond, uncond = encode(prompt), encode(negative)  # c_+ and c_- (empty = no condition)
    g = torch.Generator().manual_seed(seed)          # the seed fixes x_T
    z = torch.randn((1, unet.config.in_channels, size // 8, size // 8), generator=g)
    z = (z * sched.init_noise_sigma).to(dev, dt)
    sched.set_timesteps(steps)                       # DDIM sub-sequence (ch. 4.2)
    for t in sched.timesteps:
        zz = sched.scale_model_input(torch.cat([z, z]), t)
        e_u, e_c = unet(zz, t, encoder_hidden_states=torch.cat([uncond, cond])).sample.chunk(2)
        eps = e_u + w * (e_c - e_u)                  # CFG, theorem 4.1
        z = sched.step(eps, t, z).prev_sample
    x = vae.decode(z / vae.config.scaling_factor).sample      # latent -> pixels
    x = ((x.clamp(-1, 1) + 1) * 127.5)[0].permute(1, 2, 0)
    return x.round().to(torch.uint8).cpu().numpy()            # (512, 512, 3) image

# from PIL import Image
# Image.fromarray(generate("a watercolor of a molecule", negative="blurry")).save("out.png")

Each knob of this section is one argument: w is the guidance weight, negative the negative prompt, seed the initial noise, steps the length of the DDIM sub-sequence. Exercise 14 starts from this loop.

7. Evaluation, costs, ethics

A generator produces a distribution rather than a single answer, so its quality cannot be read off one sample, and its value depends as much on its cost and its uses as on its images. This chapter gives the metrics and their pitfalls, then the costs and the ethical questions that any deployment raises.

Panel of metrics

Metric Measures Known limits
FID distributional distance (W2/Bures on Inception features) sampling bias (overestimated at small N — always compare at equal N), sensitive to the feature backbone, blind to text
CLIPScore prompt-image alignment (cosine) CLIP feature set; rewards clichés that are easy to describe
LPIPS diversity / perceptual similarity between generated pairs judge network trained on limited human judgment
IS quality × diversity (classifier KL) sensitive to the classifier’s dominant class
Human studies pairwise preferences (Elo) costly, annotator biases — the final standard

The FID inherits the geometry of W_2 (proposition 2.6): the part \mathrm{tr}\big(\Sigma_r + \Sigma_g - 2(\Sigma_r\Sigma_g)^{1/2}\big) is the squared Bures distance \mathcal{B}^2(\Sigma_r, \Sigma_g) between covariances, consistent with \mathrm{FID} = W_2^2 in ch. 2.

Two practical pitfalls: (i) the number of samples — FID mechanically decreases with the cohort size; (ii) the features — InceptionV3 vs CLIP sometimes reorder the rankings. Always report (backbone, N, protocol).

Project Complete pipeline: light fine-tuning of a latent diffusion model on a small thematic set (LoRA on cross-attention), with parameterizable CFG; evaluate FID/CLIPScore before/after and analyze the effect of the guidance weight w (and of schedules w(t) — cf. ch. 9).

8. Beyond images: video, sound, robot actions, 3D, multimodal LLMs

Images were the testing ground; the same recipes — a compressed latent space, a denoiser or a transformer, a contrastive bridge to text — now extend to time (video), to sound, to the actions of a robot, to space (3D) and to language models that read images. The official description names exactly this progression, “from image to video generation, sound, robot actions”, and the sensors it lists (vision, audio, touch); sections 8.1–8.3 treat the three generated modalities, section 8.4 the remaining frontiers.

8.1. Video generation

Definition 8.1 — Video latent diffusion A clip is a tensor x \in \mathbb{R}^{F \times H \times W \times 3}. A causal 3D VAE (ch. 1) compresses it by a factor c_t in time and c_s in space, the first frame being kept on its own so that a single image is a valid one-frame video: the latent has F' = (F - 1)/c_t + 1 frames of size \frac{H}{c_s} \times \frac{W}{c_s}.

The denoiser is a DiT (ch. 4) over spacetime patches: with spatial patches p \times p, each latent frame gives S = \frac{H}{c_s p} \cdot \frac{W}{c_s p} tokens, N = F' S in total. It is trained with the noise-prediction loss of Model 3.2 on video latents, and conditioned on text (ch. 5–6), on a first frame (image-to-video) or on camera parameters.

Attention is either full over the N tokens, costing \mathcal{O}(N^2), or factorized: spatial attention inside each frame (F' S^2 pairs) followed by temporal attention across frames at each spatial position (S F'^2 pairs).

Example 8.2 — The token budget of five seconds of video A clip of F = 121 frames (about 5 s at 24 fps) at 512 \times 512, with c_t = 4, c_s = 8 and 2 \times 2 patches.

This gives F' = 120/4 + 1 = 31 latent frames of 64 \times 64, hence S = 32 \times 32 = 1024 tokens per frame and N = 31\,744 tokens — 31 times the token count of one 512 \times 512 image.

Full attention compares N^2 \approx 1.0 \times 10^9 pairs, about 961 times more than for the image; factorized attention needs 31 \cdot 1024^2 + 1024 \cdot 31^2 \approx 3.35 \times 10^7 pairs, thirty times fewer than full attention.

This arithmetic explains the cascades (generate at low resolution and frame rate, then upsample in space and time) and the cost of video models.

What breaks in video, and how it is measured Typical failures are flicker between frames, drifting identities and implausible motion. Standard remedies: start from a pretrained image model and insert temporal layers trained on video (Video LDM, Blattmann et al., 2023), train jointly on images and videos, and extend long videos autoregressively by conditioning each new chunk on the last frames. The video counterpart of FID (ch. 7) is the FVD (Fréchet Video Distance), the same Fréchet formula on the features of a video action-recognition network (I3D). Camera control and long-horizon coherence remain open problems (cf. AKiRa, ch. 9).

8.2. Sound generation

Definition 8.3 — Audio representations: log-mel spectrograms and neural codec tokens A waveform is sampled at f_s = 16–48 kHz (one second = 24,000 numbers at 24 kHz).

Spectrogram view: a short-time Fourier transform over sliding windows gives a time–frequency magnitude map; grouping frequencies on the perceptual mel scale, m = 2595 \log_{10}(1 + f/700), into 64–128 bands and taking logs yields a log-mel spectrogram, an image of size bands × frames to which the image models of ch. 1–4 apply; since the phase is discarded, a neural vocoder (HiFi-GAN, an adversarial model of ch. 2) maps it back to a waveform.

Token view: a neural codec (SoundStream, EnCodec) encodes the waveform into latent frames at a low rate (75 per second at 24 kHz) and quantizes each frame by residual vector quantization: q_1 = Q_1(z), \ \text{then}\ q_2 = Q_2(z - q_1),\ q_3 = Q_3(z - q_1 - q_2),\ \dots, \quad\text{so that}\quad z \approx \sum_{k=1}^{K} q_k — each codebook (VQ-VAE, ch. 1) refines the residual left by the previous ones.

Example 8.4 — Bitrate and sequence length of a codec With 75 frames per second and K = 8 codebooks of 1024 entries (10 bits each), the codec transmits 75 \times 8 \times 10 = 6000 bit/s, against 24\,000 \times 16 = 384\,000 bit/s for 16-bit audio: a compression factor of 64.

A 10-second clip becomes 750 frames \times\, 8 = 6000 tokens, the length of a long document for a language model.

Predicting the K codebooks of a frame in parallel with a one-step delay between successive codebooks (the “delay pattern” of MusicGen) brings the number of decoding steps from K T = 6000 down to T + K - 1 = 757.

Definition 8.5 — Text-to-audio and text-to-music generation Two families mirror those of images. Audio language models generate codec tokens autoregressively with a transformer conditioned on a text embedding: AudioLM (semantic tokens first, then acoustic tokens), MusicGen (text-to-music), VALL-E (text-to-speech in a voice given by a 3-second prompt).

Latent audio diffusion runs the diffusion of ch. 3–4 on a VAE latent of the mel spectrogram, conditioned by CLAP — CLIP (ch. 5) trained with the same InfoNCE loss on (audio, caption) pairs (AudioLDM).

Classifier-free guidance (ch. 4) and the FID-like evaluation of ch. 7 (Fréchet Audio Distance) carry over unchanged; speech generation is developed in the M2 module Speech Technology for Conversational AI.

8.3. Robot actions and tactile sensing

When a generative model drives a robot, the generated modality is the action: given observations o_t — camera images, joint positions, touch — produce the next commands a_t \in \mathbb{R}^d (end-effector displacement, gripper opening). Demonstrations by a human operator provide the data (imitation learning, RL module, section 6.5).

Definition 8.6 — Diffusion policy (Chi et al., 2023) Instead of regressing one action, model the whole conditional distribution p(A_t \mid o_t) of an action chunk A_t = (a_t, \dots, a_{t+H-1}) with a conditional diffusion model: train \epsilon_\theta(A^k, k, o_t) with the noise-prediction loss of Model 3.2, where A^k is the chunk noised at level k.

At run time, denoise from Gaussian noise in a few steps (DDIM, ch. 4), execute the first actions of the chunk, observe again and re-plan (receding horizon).

Example 8.7 — Why averaging actions fails To pass an obstacle, half of the demonstrations steer left (a = -1) and half right (a = +1), with spread 0.1: p(a \mid o) = \tfrac12\mathcal{N}(-1, 0.1^2) + \tfrac12\mathcal{N}(1, 0.1^2). A network trained with squared error outputs the conditional mean \mathbb{E}[a \mid o] = 0 — straight into the obstacle — where the demonstration density is only about 4 \times 10^{-22} times its value at \pm 1 (the ratio is 2e^{-50}), that is 10^{21} to 10^{22} times lower.

A generative policy samples -1 or +1, each a valid manoeuvre: multimodality of the action distribution is the reason generative models took over robot learning, exactly as mode coverage motivated diffusion over GANs for images (ch. 2–3).

Definition 8.8 — Vision-language-action models A VLA model starts from a pretrained vision-language model (section 8.4) and makes actions one more output modality. RT-2 (Brohan et al., 2023) discretizes each action dimension into 256 bins and emits actions as text tokens, co-trained on web image–text data and robot trajectories, so that web knowledge transfers to commands (“pick up the extinct animal”).

OpenVLA (Kim et al., 2024) is an open 7-billion-parameter model of this kind. π0 (Black et al., 2024) adds an action expert that generates continuous action chunks by flow matching, a continuous-time relative of diffusion.

With actions in [-1, 1], 256 bins give a resolution of 2/256 \approx 0.008, and a 7-dimensional command (six pose increments and the gripper) costs 7 tokens per control step.

Touch, and the industries named by the description Tactile sensing: camera-based tactile sensors (GelSight type) image the deformation of a soft membrane in contact with an object; their output is processed by the same image encoders and fused as extra tokens of the observation. Touch matters for contact-rich tasks — insertion, grasping fragile objects — where the gripper hides the contact from the cameras, and cross-modal generation (predicting touch from vision and the converse) is an active research topic.

Automotive: driving world models generate future camera views conditioned on the ego-vehicle’s actions (GAIA-1, Hu et al., 2023) and serve as learned simulators for rare situations; trajectory planners use diffusion over future paths.

Healthcare: synthetic medical images are used for data augmentation and privacy-preserving sharing, under the evaluation caveats of ch. 7 (a low FID does not prove clinical fidelity).

8.4. Multimodal LLMs, 3D and world models

Volume rendering in practice The integral is computed by quadrature. Sample N points t_1 < \dots < t_N along the ray, with spacings \delta_i = t_{i+1} - t_i, densities \sigma_i and colours c_i: \hat C(r) = \sum_{i=1}^{N} T_i\,\big(1 - e^{-\sigma_i\delta_i}\big)\,c_i, \qquad T_i = \exp\Big(-\sum_{j<i}\sigma_j\delta_j\Big). Each sample contributes its opacity 1 - e^{-\sigma_i\delta_i} times the transmittance T_i of everything in front of it. The weights are nonnegative, sum to 1 - T_{N+1} \le 1, and are differentiable in the densities and colours, so a squared error on pixel colours trains the MLP by backpropagation.

For the radiometry behind the formula, read Image Synthesis, ch. 10, optional: that course is a sibling elective of the same “Choose 1” group.

9. Course research notes (Kalogeiton et al.)

The 2026–2027 sheet names Xi Wang as head of the course; Vicky Kalogeiton, whose publications are presented below, is not listed on it, and this chapter is kept as research context for the course’s themes — video, guidance, distillation. Vicky Kalogeiton (CVLab — École Polytechnique / ECL; formerly Inria Grenoble, LEAR team) has worked since her PhD on a coherent program: localizing and understanding objects and actions in videos, and more recently, generating them. The three publications below exactly mark out the syllabus of this course — with video as the common thread.

ACT-detector — Action Tubelet Detector (ICCV 2017) arXiv:1705.01861 — V. Kalogeiton, P. Weinzaepfel, V. Ferrari, C. Schmid.

Problem. Spatio-temporal action detection: for each actor, find where (per-frame boxes) and when (temporal segment) each action is performed.

Method. Extending anchor-based detection (SSD) to the spatio-temporal domain: the input is a tubelet — k consecutive frames — and the network regresses and scores 3D cuboid-anchors (position, spatial scale, duration), with oversampling of frame-level features for small actors.

Results. State of the art at the time on UCF-Sports, J-HMDB and UCF101; the tubelet formalism fed the AVA benchmark.

Position in the course. This is the “before” of transformers: 3D convolution + anchors, while chapters 3–4 of this module describe the “after” (DiT); the notion of temporal scale (pyramid of durations) foreshadows the temporal pyramid of modern video-to-text models.

Analysis of Classifier-Free Guidance Weight Schedulers (TMLR 2024) arXiv:2404.13040 — X. Wang, N. Dufour, N. Andreou, M.-P. Cani, V. Fernández Abrevaya, D. Picard, V. Kalogeiton.

Problem. The guidance weight w of thm. 4.1 is constant in most tools — why not vary it during sampling?

Method. Systematic analysis of schedules w(t) (increasing, decreasing, bell-shaped) on text-to-image diffusion, with fidelity (CLIPScore) and diversity measurements.

Results. Variable w(t) profiles improve the fidelity/diversity trade-off compared to constant w; the behavior depends on the step (start vs end of the chain).

Position. Theorem 4.1 gives the theory of CFG at fixed w; this work shows that the temporal degree of freedom is underexploited — a textbook example of “fine engineering of a generative hyperparameter”, and a direct topic for the project of ch. 7.

Generating video: AKiRa and Di[M]o distillation (2024–2025) AKiRa — arXiv:2412.14158 (CVPR 2025) and Di[M]o — arXiv:2503.15457 (ICCV 2025).

AKiRa (Augmentation Kit on Rays): an augmentation kit for optical video generation — camera on rays, multi-view consistency; the camera-control question (ch. 8) handled on the training side.

Di[M]o: distilling a masked diffusion model into a one-step generator — the acceleration of ch. 4 pushed to the extreme (MDM → one-step generator).

Position. The two ends of the value chain: quality/consistency (AKiRa) and latency (Di[M]o) — exactly the two axes of the industrial trade-off of ch. 7.

Let us also mention Don’t drop your samples! Coherence-aware training benefits conditional diffusion (Dufour, Besnier, Kalogeiton and Picard, CVPR 2024). Instead of discarding the image–caption pairs whose caption fits the image poorly, it scores the coherence of each pair and gives that score to the denoiser as an extra condition; at sampling time one asks for high coherence. It is a data-side answer to noisy web captions, the weak point of the text conditioning of ch. 5–6.

The common thread Perceiving video (detection, 2017) → generating it (video diffusion, 2024–2025) → accelerating it (distillation): the CVLab research trajectory mirrors that of the field — and that of this course, from GANs (ch. 2) to guided latent diffusion (ch. 4) up to complete systems (ch. 6).

Exercises

  1. ★ Composition of noises. Show by induction that q(x_t \mid x_0) = \mathcal{N}(\sqrt{\bar\alpha_t} x_0, (1-\bar\alpha_t) I); why does this closed form make training efficient?
  2. ★ KL of Gaussians. Prove proposition 0.4 in the scalar case by computing \mathbb{E}_q[\log q - \log p]; check that the KL is zero iff \mu_1 = \mu_2, \sigma_1 = \sigma_2 and strictly positive otherwise.
  3. ★ Mode collapse. Simulate a 2D Gaussian→ring GAN; observe the collapse; compare with a diffusion model trained on the same set (diversity via LPIPS).
  4. ★ CFG. Show that w = 1 recovers the conditional prediction and w = 0 the unconditional one; generate a grid w \in \{0, 1, 5, 10\} and comment on the trade-off.
  5. ★ CLIP zero-shot. Compare the zero-shot accuracy of CLIP with the accuracy of a ResNet trained on 10 custom classes, as a function of the training size; where do the curves cross?
  6. ★ Epsilon or score? Using x_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1-\bar\alpha_t}\,\epsilon, show that \epsilon = -\sqrt{1-\bar\alpha_t}\,\nabla_{x_t}\log p(x_t \mid x_0).
  7. ★ Truncation. For a StyleGAN whose w approximately follows a centered Gaussian, show that the rule w' = \bar w + \psi(w - \bar w), \psi \in [0,1], reduces the variance of the generated style and comment on the quality/diversity trade-off as \psi \to 0.
  8. ★★ DDPM ELBO. Decompose the log-likelihood \log p_\theta(x_0) into per-step terms and show that the noise MSE dominates (the KLs between Gaussians are closed-form).
  9. ★★ FID and Wasserstein. Recall the formula for W_2^2 between Gaussians (proposition 2.6) and show that the FID is an estimate of it (features; sampling bias).
  10. ★★ Noise vs mean. Parameterize the denoiser as predicting x_0 (\hat x_0 = x_\theta(x_t, t)); express the corresponding loss and explain when this parameterization is preferable. Hint: recovering \hat x_0 from a predicted noise multiplies the noise error by \sqrt{(1-\bar\alpha_t)/\bar\alpha_t}, which blows up at large t (low signal-to-noise ratio); that is where predicting x_0, or the velocity, pays off.
  11. ★★ InfoNCE temperature. In the contrastive loss of ch. 5, show the effect of \tau \to 0 (peaked distribution, gradients concentrated on the hardest negatives) and of \tau \to \infty (uniform gradients, slowed learning).
  12. ★★ Video and audio budgets. (a) Redo Example 8.2 for a 10-second clip at 24 fps and 768 \times 768, with the same compression and patch sizes; give N, the full-attention pair count and the factorized one. (b) For a codec at 50 frames per second with 4 codebooks of 2048 entries, compute the bitrate, the number of tokens of a 30-second music clip and the number of decoding steps with and without the delay pattern of Example 8.4.
  13. ★★ Diffusion policy on a toy task. Generate 2D demonstrations that avoid an obstacle on the left or on the right (Example 8.7); train (a) an MLP regressor with squared error and (b) a small conditional diffusion model over 8-step action chunks (Definition 8.6); report the collision rate of each and plot sampled trajectories.
  14. ★★★ Project. Complete pipeline: light fine-tuning of a latent diffusion model on a small thematic set (LoRA on cross-attention), with parameterizable CFG; evaluate FID/CLIPScore before/after and analyze the effect of the guidance weight w — also testing variable schedules w(t) (cf. ch. 9).

Solution 1 — Composition of noises Induction: true at t=1 by definition. If x_{t-1}\mid x_0 is Gaussian with mean \sqrt{\bar\alpha_{t-1}}x_0 and variance (1-\bar\alpha_{t-1})I, then x_t = \sqrt{\alpha_t}x_{t-1} + \sqrt{1-\alpha_t}\,\epsilon with \epsilon independent; prop. 0.1 (sum of independent Gaussians) gives mean and variance \sqrt{\alpha_t\bar\alpha_{t-1}}x_0 = \sqrt{\bar\alpha_t}\,x_0, \qquad \alpha_t(1-\bar\alpha_{t-1}) + (1-\alpha_t) = 1-\bar\alpha_t. The closed form makes training efficient because the first t-1 steps are skipped: direct noising at any t, a single forward pass per training example.

Solution 2 — KL of Gaussians (scalar case) \mathrm{KL} = \mathbb{E}_q[\log q - \log p] with \log q(x) = -\frac12\log(2\pi\sigma_1^2) - \frac{(x-\mu_1)^2}{2\sigma_1^2} and likewise for p. Difference: \log q - \log p = \frac12\log\frac{\sigma_2^2}{\sigma_1^2} - \frac{(x-\mu_1)^2}{2\sigma_1^2} + \frac{(x-\mu_2)^2}{2\sigma_2^2}. Now \mathbb{E}_q[(x-\mu_1)^2] = \sigma_1^2 and \mathbb{E}_q[(x-\mu_2)^2] = \mathbb{E}[((x-\mu_1) + (\mu_1-\mu_2))^2] = \sigma_1^2 + (\mu_1-\mu_2)^2 (zero cross term). Hence \mathrm{KL}(q\|p) = \frac12\big[\log\frac{\sigma_2^2}{\sigma_1^2} + \frac{\sigma_1^2 + (\mu_1-\mu_2)^2}{\sigma_2^2} - 1\big]. This is \frac12[u - 1 - \log u] \ge 0 with u = \sigma_2^2/\sigma_1^2 (since \log u \le u - 1) plus a squared term: zero iff (\mu_1,\sigma_1) = (\mu_2,\sigma_2).

Solution 3 — 2D mini-GAN (code)

import torch
G = torch.nn.Sequential(torch.nn.Linear(2, 64), torch.nn.ReLU(),
                        torch.nn.Linear(64, 64), torch.nn.ReLU(),
                        torch.nn.Linear(64, 2))          # noise -> 2D point
D = torch.nn.Sequential(torch.nn.Linear(2, 64), torch.nn.ReLU(),
                        torch.nn.Linear(64, 1))          # point -> logit

def sample_ring(n, r=1.0, noise=.05):                    # true law: a ring
    a = torch.rand(n) * 2 * torch.pi
    return torch.stack([r*torch.cos(a), r*torch.sin(a)], 1) + noise*torch.randn(n, 2)

optG, optD = torch.optim.Adam(G.parameters(), 2e-4), torch.optim.Adam(D.parameters(), 2e-4)
bce = torch.nn.functional.binary_cross_entropy_with_logits
for step in range(5000):
    x = sample_ring(256); z = torch.randn(256, 2)
    lossD = bce(D(x), torch.ones(256, 1)) + bce(D(G(z)), torch.zeros(256, 1))
    optD.zero_grad(); lossD.backward(); optD.step()
    z = torch.randn(256, 2)
    lossG = bce(D(G(z)), torch.ones(256, 1))             # non-saturated form
    optG.zero_grad(); lossG.backward(); optG.step()
    if step % 1000 == 0: print(step, float(lossD), float(lossG))
# Observe: G concentrates on an arc of the circle (mode collapse);
# measure diversity: average distance between generated pairs.

The collapse is visible when the covered arc shrinks; compare with a 2D diffusion (same network for \epsilon_\theta): the denoising MSE covers the whole ring.

Solution 4 — CFG \tilde\epsilon = \epsilon_\theta(\varnothing) + w(\epsilon_\theta(c) - \epsilon_\theta(\varnothing)): for w = 0, \tilde\epsilon = \epsilon_\theta(\varnothing) (unconditional); for w = 1, \tilde\epsilon = \epsilon_\theta(c) (conditional).

For w > 1, the proof of thm. 4.1 shows that \tilde\epsilon is the score of p(x\mid c)^w p(x)^{1-w}: an “over-weighted” conditional distribution, more peaked — increased prompt fidelity, reduced diversity (fewer samples explored).

Typical grid: at w=0, off-topic images; w=1, correct and varied; w=5, highly compliant, repetitive; w=10, saturation (burnt colors, artifacts).

Solution 6 — Noise and score See the proof of theorem 3.3: for p(x_t\mid x_0) = \mathcal{N}(\sqrt{\bar\alpha_t}x_0, (1-\bar\alpha_t)I), \nabla_{x_t}\log p = -(x_t - \sqrt{\bar\alpha_t}x_0)/(1-\bar\alpha_t) = -\epsilon/\sqrt{1-\bar\alpha_t}, hence \epsilon = -\sqrt{1-\bar\alpha_t}\,\nabla_{x_t}\log p(x_t\mid x_0). Consequence: the denoising MSE is a regression onto the conditional score; integrating over x_0, it targets the marginal score \nabla\log p_t(x_t) — the starting point of the SDE formulation (ch. 4).

Solution 8 — DDPM ELBO (plan)

  1. Write the ELBO of the chain p_\theta(x_{0:T}) against q and telescope (Markov chain): L = L_T + \sum_{t \ge 2} L_{t-1} + L_0 with L_{t-1} = \mathrm{KL}(q(x_{t-1}\mid x_t,x_0)\,\|\,p_\theta(x_{t-1}\mid x_t)) and the reconstruction term L_0 = -\mathbb{E}_q[\log p_\theta(x_0\mid x_1)].
  2. q(x_{t-1}\mid x_t,x_0) is Gaussian (product of two Gaussians: Bayes + completing the square).
  3. Every L_{t-1} is a KL of Gaussians: closed (prop. 0.4); with \sigma_t^2 = \tilde\beta_t there remains the gap between the means \propto \|\tilde\mu_t - \mu_\theta\|^2.
  4. The parameterization \mu_\theta = \frac{1}{\sqrt{\alpha_t}}(x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\epsilon_\theta) exchanges the gap between means for the noise MSE — full details in the proof of model 3.2.

Solution 9 — FID and W2 (Bures) For two Gaussians \mathcal{N}(\mu_1,\Sigma_1), \mathcal{N}(\mu_2,\Sigma_2): W_2^2 = \|\mu_1 - \mu_2\|^2 + \mathrm{tr}\big(\Sigma_1 + \Sigma_2 - 2(\Sigma_1^{1/2}\Sigma_2\Sigma_1^{1/2})^{1/2}\big) (proof sketch: proposition 2.6; full proof in Optimal Transport, theorem 2.7, reading only).

The FID is exactly this formula applied to the Gaussians fitted to the Inception features of the two image sets — an approximation of W_2 both through the features (transport happens only in the backbone’s space) and through the moment estimates (\hat\mu, \hat\Sigma on N samples: the FID is biased upward at small N — always compare at equal cohort size).

Projects and assessment

The official assessment is not displayed: the fiche above reads “Not displayed: the 2026–2027 sheet gives no assessment modality, and its LLGA section shows no resit rule or pass threshold”. The subjects below are proposals of these notes, not official rules: a solo or group project can serve as the continuous assessment, and the exam proposal as a final written exam if the teaching team holds one.

The projects exercise mainly O2 (generative modelling theory: diffusion, guidance, flows) and O6 (multimodal generation of images, sound and actions), O5 through the text–graph CLIP subject, O7 (hands-on work with real models and data) and O8 through the model cards (costs, bias, provenance).

Solo projects

  1. [Solo · ≈ 20 h] Paper study: guidance-weight schedules under the microscope (Wang, Dufour, Andreou, Cani, Fernández Abrevaya, Picard and Kalogeiton, TMLR 2024). Does a guidance weight w(t) that varies along sampling really beat a constant weight, at equal compute?
    • Models and data: the class-conditional DiT-XL/2 at 256 px (Peebles and Xie, 2023; facebook/DiT-XL-2-256 in Diffusers) on 50 ImageNet classes, with the 2,500 ImageNet validation images of these classes as reference; then a text-to-image check with the Stable Diffusion loop of ch. 6 on 200 COCO 2017 validation captions.
    • Work: constant, linearly increasing, linearly decreasing and bell-shaped schedules at two mean weights, plus a negative-prompt variant (ch. 4.1, ch. 6); 20 DDIM steps (ch. 4.2); FID and KID, CLIPScore and mean pairwise LPIPS at equal N, backbone stated (ch. 7).
    • Success criterion: a fidelity–diversity Pareto plot with bootstrap error bars, and a clear yes or no on the paper’s main claim (ch. 9).
    • Deliverables: code, a 4–6 page report, a 10-minute talk; chapters 4, 6, 7 and 9.
  2. [Solo · ≈ 20 h] Diffusion policy against regression on multimodal demonstrations. Exercise 13 grown into a small simulator: when does a generative policy beat a regressor, and at what latency?
    • Data: bimodal demonstrations from your own 2D navigation simulator (an obstacle passed on the left or on the right), then the low-dimensional Push-T dataset released with Chi et al. (2023).
    • Work: a squared-error regressor and a conditional diffusion policy over action chunks of 8–16 steps (Definition 8.6), sampled with 5–10 DDIM steps in receding horizon (ch. 4.2, 8.3); as an option, a flow-matching head (4.3), as in π0.
    • Success criterion: success and collision rates over 100 episodes, mode coverage (share of left and right passes), and control latency per step.
    • Deliverables: code, report, talk; chapters 3, 4 and 8. It connects to imitation learning in Reinforcement Learning, 6.5.
  3. [Solo · ≈ 15 h] Flow matching against DDPM at equal compute. Is a straight path cheaper to sample than a diffusion?
    • Data: two moons and a ring of 8 Gaussians (synthetic), then MNIST at 28 × 28.
    • Work: the flow-matching code of 4.3 and a DDPM with the same network and the same number of gradient steps (ch. 3); samplers with 1, 2, 5, 10, 20 and 50 steps (Euler for the flow, DDIM for the diffusion); a Monte Carlo estimate of the loss floor C of theorem 4.6, compared with the final training loss.
    • Success criterion: quality against the number of steps, with 3 seeds: W_2 to held-out points in 2D (POT library), FID on the features of a small MNIST classifier.
    • Deliverables: code, report, talk; chapters 3 and 4.

Group projects

  1. [Group of 3 · ≈ 30 h each] LoRA fine-tuning of a latent diffusion model, with a guidance analysis (exercise 14). How far does a LoRA of a few megabytes move a text-to-image model toward a theme, and how does the best guidance weight move with it?
    • Model and data: Stable Diffusion v1.4 (ch. 6); a small captioned thematic set, such as the Naruto BLIP-captions set of the Diffusers LoRA tutorial (lambdalabs/naruto-blip-captions) or a set you caption yourself with BLIP; licence checked (the Naruto set states none, so its samples stay out of public deliverables).
    • Work: LoRA of rank 4–16 on the attention projections of the denoiser, held-out captions; a guidance grid over w and the schedules w(t) of ch. 9; negative prompts.
    • Split: data, captions and training; sampling grid and guidance analysis; evaluation and a model card (GPU-hours, bias audit on prompts that depict people, provenance and watermark, ch. 7).
    • Success criterion: a before/after table at equal N with the backbone stated (FID or KID against held-out images, CLIPScore, LPIPS diversity), and the weight w that maximizes CLIPScore at fixed diversity, before and after LoRA.
    • Deliverables: code, an 8–10 page joint report with the model card, a 20-minute talk; chapters 4–7 and 9.
  2. [Group of 3 · ≈ 30 h each] Text–graph CLIP and a text-guided graph diffusion for molecules. Can a contrastive text–molecule space retrieve molecules from their descriptions, then steer a graph generator toward them?
    • Data: ChEBI-20 (Edwards, Zhai and Ji, 2021), about 33,000 PubChem molecules with one natural-language description each, official split; molecular graphs from the SMILES strings with RDKit.
    • Work: a GIN encoder over molecular graphs (Graph ML, ch. 5) and a frozen pretrained text encoder with a trained projection (Text Mining & NLP, ch. 7), aligned by symmetric InfoNCE (ch. 5). Then a small discrete graph diffusion, DiGress-style (Graph ML, ch. 9), on the molecules of at most 20 heavy atoms, conditioned on the text embedding with condition dropout and classifier-free guidance (ch. 4.1).
    • Split: graph encoder and data pipeline; text side, contrastive training and retrieval; conditional graph diffusion and its evaluation.
    • Success criterion: text-to-molecule retrieval on the test split (MRR, Hits@1 and Hits@10, set against the numbers of Text2Mol); validity, uniqueness and novelty of generated molecules (RDKit), and their alignment with the prompt in the contrastive space as w grows.
    • Deliverables: code, joint report, talk; chapters 3–5 and 7. It is the core of the Y1.4 project, which adds a reward and RL fine-tuning (Reinforcement Learning, ch. 5).
  3. [Group of 3 · ≈ 30 h each] From codec tokens to text-to-sound. How far does a small codec-token transformer with the delay pattern go, set against a pretrained latent audio diffusion model?
    • Data: Clotho v2.1 (Drossos, Lipping and Virtanen, 2020), several thousand Freesound clips of 15–30 s with five captions each, under Creative Commons licences; clips cut to 10 s.
    • Work: tokenize with the pretrained 24 kHz EnCodec (Défossez et al., 2022), keeping 4 codebooks (8.2); train a small decoder-only transformer with the delay pattern of MusicGen (Example 8.4), conditioned on frozen CLAP text embeddings with condition dropout and classifier-free guidance (ch. 4.1, ch. 5). Baseline: the pretrained AudioLDM (Liu et al., 2023) through Diffusers.
    • Split: tokenization, delay pattern and data; transformer, conditioning and sampling; evaluation and listening test.
    • Success criterion: Fréchet Audio Distance (Kilgour et al., 2019) and CLAP score on held-out captions, a blind preference test with at least 10 listeners, and the real-time factor of generation.
    • Deliverables: code, joint report, talk with audio samples; chapters 4, 5, 7 and 8. It leads to Speech Technology, ch. 6–7.

Written exam (proposal)

Two hours, one handwritten A4 sheet allowed, a simple calculator allowed; four questions.

  1. Question (5 points). Explain classifier-free guidance: how the model is trained, the sampling rule, the distribution it targets, the effect of the weight w, its cost per step, and how a negative prompt fits in.
    • Expected: condition dropout (about 10 %) trains one network for both the conditional and the unconditional noise prediction.
    • The rule of theorem 4.1, with w = 0 unconditional, w = 1 conditional and w > 1 an extrapolation.
    • By Bayes, the guided prediction is the score of p(x_t \mid c)^w\,p(x_t)^{1-w}: higher fidelity, lower diversity, saturation at large w.
    • Two network evaluations per step; a negative prompt replaces the empty condition by c_-, pushing samples away from it.
  2. Question (6 points). A DDPM with T = 3 steps has the schedule \beta = (0.1, 0.2, 0.3).
      1. Compute \bar\alpha_1, \bar\alpha_2, \bar\alpha_3 and the law of x_3 given x_0.
      1. For x_0 = 2 and \epsilon = -1, compute x_3.
      1. Compute \tilde\beta_3 and the mean of model 3.2 at step 3 when the network predicts \epsilon exactly; check it against \tilde\mu_3(x_3, x_0).
    • Expected: (a) \bar\alpha = 0.9,\ 0.72,\ 0.504, so x_3 \mid x_0 \sim \mathcal{N}(0.710\,x_0,\ 0.496).
      1. x_3 = 0.710 \times 2 - 0.704 = 0.716.
      1. \tilde\beta_3 = 0.3 \times 0.28/0.496 \approx 0.169. The mean is (0.716 + 0.3/0.704)/\sqrt{0.7} \approx 1.364.
    • Check with Step 2 of the proof of model 3.2: \tilde\mu_3 = \frac{\sqrt{0.72}\times 0.3}{0.496}\times 2 + \frac{\sqrt{0.7}\times 0.28}{0.496}\times 0.716 \approx 1.026 + 0.338 = 1.364.
  3. Question (5 points). Flow matching with the straight path of definition 4.5.
      1. Prove that the function v minimizing \mathbb{E}\|v(x_t, t) - (x_1 - x_0)\|^2 is u_t(x) = \mathbb{E}[x_1 - x_0 \mid x_t = x], and that the excess loss of any other v is \mathbb{E}\|v - u_t\|^2.
      1. With x_0 \sim \mathcal{N}(0, I), show that u_t(x_t) = (x_t - \mathbb{E}[x_0 \mid x_t])/t, and deduce that a flow-matching model accepts classifier-free guidance.
    • Expected: (a) write Y = x_1 - x_0; the residual Y - \mathbb{E}[Y \mid x_t] is orthogonal to every function of x_t, which splits the loss into \mathbb{E}\|v - u_t\|^2 plus a constant (theorem 4.6).
      1. Take conditional expectations in x_1 = (x_t - (1-t)\,x_0)/t and subtract \mathbb{E}[x_0 \mid x_t].
    • The map from the noise prediction to the velocity is affine with the same coefficients for every condition, so mixing velocities with the CFG rule equals mixing noise predictions.
  4. Question (4 points). In the plane, let P_\theta be the law of (\theta, Z) with Z uniform on [0, 1]: a vertical segment at abscissa \theta.
      1. Compute \mathrm{JS}(P_0 \| P_\theta), \mathrm{KL}(P_\theta \| P_0) and W_1(P_0, P_\theta).
      1. Say what they imply for training a GAN and a WGAN (construction 2.4).
    • Expected: for \theta \neq 0 the supports are disjoint, so \mathrm{JS} = \log 2 and the KL is infinite; all three vanish at \theta = 0.
    • W_1 = |\theta|: the coupling that shifts each point by \theta costs |\theta|, and the 1-Lipschitz function f(x, y) = -\mathrm{sign}(\theta)\,x reaches this value in the dual of construction 2.4: \mathbb{E}_{P_0}[f] = 0 and \mathbb{E}_{P_\theta}[f] = -|\theta|.
    • JS is constant away from 0, so the GAN generator gets no gradient; W_1 has gradient \mathrm{sign}(\theta), the useful signal the WGAN critic provides (Arjovsky et al., 2017).

Grading rubric (proposal)

Criterion Weight What earns the marks
Question and model 15 % the generative model, its loss and its sampler written down and justified from the chapters
Correct implementation 25 % code that first reproduces a known number or figure (a published FID or retrieval score, the two-moons check of 4.3) before anything is changed
Evaluation protocol 20 % metrics at equal N with the feature backbone stated, held-out prompts or captions, seeds or bootstrap intervals, no test leakage
Analysis tied to the theory 25 % each result, failures included, explained by a statement of the course (guidance trade-off, score matching, straight paths, mode coverage)
Responsible deployment and communication 15 % a model card with costs, licences, bias audit and provenance (ch. 7); figures that answer the question; a talk on time

References