Quick recap
The key takeaways of every lesson on one page. Read it in ten minutes to refresh the whole track; open a lesson when a point feels unclear.
01 Latent variables and the ELBO
- A generative model is a distribution that we can sample; some families can also evaluate it exactly (autoregressive, flows), some only bound it (VAE, diffusion), some not at all (GAN).
- Maximum likelihood minimizes the forward KL: . Forward KL is mode covering; reverse KL is mode seeking.
- A latent variable model samples , then ; its evidence and its posterior are usually intractable.
- For any : , with .
- EM sets to the exact posterior (gap 0) and then maximizes over ; it never decreases .
- A VAE encoder has two gaps: the approximation gap (the family is too simple) and the amortization gap (the encoder misses the best member of ).
- The IWAE bound equals the ELBO at , never decreases in , stays below , and its gap shrinks like .
02 Variational autoencoders
- A VAE minimizes distortion plus rate , which is minus the ELBO, with a Gaussian encoder .
- Reparameterization , , gives the pathwise gradient; it is usually much less noisy than the score-function estimator, but needs a continuous and a differentiable .
- ; a dimension is free only at , .
- "Summed squared error $+\ \beta,$KL" is the ELBO of a Gaussian decoder with ; a mean-reduced MSE with a summed KL silently sets .
- Posterior collapse () can be the optimum of the ELBO; in a linear VAE, direction is active iff .
- The β-VAE minimizes : larger β gives lower rate and higher distortion; it is a likelihood bound only for .
- VQ-VAE quantizes to the nearest code, passes gradients straight through, and has three loss terms: reconstruction, codebook and commitment; unused codes get no gradient and stay dead.
03 Autoregressive models
- Chain rule: every joint distribution factorizes as , for any order of the variables.
- An autoregressive model is normalized when each factor is a normalized distribution and depends only on ; a leak of into factor gives a near-zero training loss and an invalid model.
- Training is maximum likelihood with teacher forcing: a sum of cross-entropy terms on true prefixes, computed in one masked pass. It minimizes .
- Evaluating costs one pass; sampling costs sequential passes (ancestral sampling).
- Exposure bias is the mismatch between true prefixes in training and generated prefixes in sampling; the likelihood stays exact.
- MADE masks: hidden units read units of degree their own, outputs read only strictly lower degrees; the mask product is strictly lower triangular.
- PixelCNN uses mask A (no center) in layer 1 and mask B (with center) after it; stacked masks leave a blind spot, , removed by the two-stack design.
- A transformer LM uses causal attention plus a one-token shift; past keys and values never change, so the KV cache is exact.
04 Normalizing flows
- Change of variables: if with a smooth bijection, then ; where squeezes volume, the density of is high.
- For a composition : ; in the sampling direction the log-determinants are subtracted.
- An affine coupling layer has a triangular Jacobian, at cost , and an exact inverse; and can be any networks.
- Glow's convolution adds , which costs in the LU form.
- MAF () evaluates densities in one pass and samples in passes; IAF is the reverse, and it gets of its own samples in one pass.
- Continuous flows: ; Hutchinson's estimator needs one vector-Jacobian product per probe (FFJORD).
- The probability-flow ODE of diffusion models and flow-matching models are continuous flows, so this formula gives their exact likelihood.
- Flows keep the dimension, and their density is positive everywhere: separated modes need very large Jacobians.
05 GANs and Wasserstein GANs
- The optimal discriminator is , so : a perfect discriminator estimates the density ratio.
- With , the GAN value is , minimized only at .
- The generator learns only through at its own samples; where is flat, it learns nothing.
- The saturating generator loss has gradient in the logit, which vanishes when rejects fakes; the non-saturating loss has gradient there.
- For disjoint supports, JSD is for every generator, so it gives no gradient; this is the normal case for thin, low-dimensional data.
- Gradient play on a game can cycle: in the Dirac-GAN the Jacobian has eigenvalues , simultaneous steps spiral out, alternating steps circle, and an R1 penalty converges.
- The f-GAN bound is tight at ; every such critic estimates a function of the density ratio.
- ; it is continuous where JSD jumps, and the critic is kept Lipschitz by clipping, a gradient penalty, or spectral normalization.
06 EBMs, score matching, Langevin
- An EBM is ; the partition function is intractable, and only differences of energy matter.
- : the positive phase lowers the energy at the data, the negative phase raises it at model samples; for the optimum matches moments.
- Langevin dynamics is noisy gradient descent; the continuous SDE has as stationary density (Fokker–Planck), and it needs only the score.
- ULA with a finite step is biased: for the stationary variance is . MALA adds a Metropolis–Hastings step that removes the bias but needs the energy, not only the score.
- Contrastive divergence starts short chains at the data (cheap, biased); persistent chains keep running between updates and stay closer to .
- The score does not contain .
- Denoising score matching regresses on ; it equals explicit score matching on plus a constant, so its minimizer is and its minimum is positive.
- Tweedie: . A single small noise level fails on separated modes (blind to weights, crossing time ); annealing from large to small fixes both.
07 Denoising diffusion (DDPM)
- The forward process has the closed form with , so training never runs the chain.
- DDPM is a hierarchical latent variable model with a fixed encoder; it is trained with the ELBO of lesson 01.
- The forward posterior is Gaussian with variance and mean .
- The negative ELBO is , with one Gaussian KL per step between the forward posterior and the learned reverse step.
- With the ε-parameterization each is plus a constant; sets all weights to 1, which gives better samples and a slightly worse likelihood.
- Ancestral sampling: , with at the last step; network calls per sample.
- is exact for a single data point and for unit-variance Gaussian data; with 1000 steps both give similar samples.
- A Gaussian reverse step is accurate only for small forward steps; with few large steps the true reverse conditional can be multimodal.
08 Diffusion parameterizations
- At one noise level ; knowing and one of , , or the score gives all the others by linear maps (score ).
- In the VP case is rotated by the angle with , , so .
- The squared-loss optimum is the conditional mean, and Tweedie's formula gives it: . So all targets share one optimum.
- Converting errors: multiplies by (bad at high noise), by (bad at low noise), or by or (never more than 1).
- For one output, and (VP) : the losses differ only by an SNR weight.
- Every diffusion loss is over ; the ELBO has , has , and weights that decrease in are ELBOs with noise augmentation.
- The continuous-time ELBO depends on the schedule only through and ; the schedule still sets the training variance, the weight of -defined losses, and the sampler grid.
- EDM: , , give unit-variance inputs and targets; leaks the image mean, fixed by zero terminal SNR with -prediction.
09 Reverse SDEs, PF-ODE and samplers
- The forward process is an SDE : VP , (the limit of DDPM); VE , ; EDM .
- Reverse-time SDE (Anderson 1982): , run from to , has the marginals ; ancestral DDPM sampling is its Euler–Maruyama discretization.
- Probability-flow ODE (Song et al. 2021): has the same marginals (the Fokker–Planck equation is a continuity equation); in EDM coordinates .
- Reverse SDE and PF-ODE give the same distributions but different paths; the ODE is deterministic and invertible, the SDE's noise partly corrects earlier errors but needs more steps.
- DDIM: ; every keeps the DDPM marginals, so one trained network serves all; is ancestral DDPM with .
- DDIM with is Euler's method for the PF-ODE in , so it is first order; Heun is second order and costs NFE for steps ending at .
- Karras schedule: ; puts most levels at low noise, where the paths bend; compare samplers at equal NFE.
10 Flow matching and rectified flow
- Flow matching learns the velocity of an ODE from noise () to data () by regression on the conditional paths with targets ; no ODE is solved in training.
- The marginal velocity generates the marginal path (marginalization trick, proved with the continuity equation).
- with a constant (the conditional variance of the target), so both losses have the same gradient; the CFM loss of a perfect model is , not 0.
- For a Gaussian path ; for the linear path , so velocity, denoiser and score are linear maps of each other, and diffusion's PF-ODE is the flow-matching ODE of its own path.
- An Euler step of linear-path flow matching equals a DDIM step; one Euler step from lands on the data mean, because the first velocity is an average direction.
- Straight conditional paths give curved marginal paths that never cross; curvature is what costs sampling steps.
- Rectified flow: the flow's own pairs have no higher convex transport cost; reflow retrains on them, the squared cost drops by , and paths become straighter (in 1D, straight after one round).
- The time convention differs between papers: and .
11 Guidance
- Bayes' rule for scores: at every noise level, with the noisy classifier .
- At high noise the noisy classifier is nearly flat; in the two-class toy its slope falls from (clean) to at . A clean classifier used on is wrong.
- Classifier guidance: with a classifier trained on noisy inputs.
- Classifier-free guidance: train one network with condition dropout (10–20%), sample with ; unconditional, conditional; Ho and Salimans' ; 2 NFE per guided step.
- CFG equals the conditional model plus times guidance with the implicit classifier .
- Guided samples do not follow the tilted target , because tilting and noising do not commute; ODE and SDE samplers give different results, and in a Gaussian model the ODE gives variance .
- Guidance raises precision and lowers recall; FID is best at a moderate . Limited-interval guidance (only middle noise levels) and autoguidance (a weaker copy of the same model) reduce the loss of diversity.
12 Few-step generation
- Multimodal data bends PF-ODE paths: at high noise the denoiser predicts the mean of the modes, so one large step lands between them. One data point gives straight paths, and one Euler step is exact.
- One Euler step from to lands on the denoiser output ; for data this is .
- Progressive distillation: the student target makes one student DDIM step equal two teacher steps; halving rounds reach steps.
- Few-step students need - or -prediction: at an -output carries no information about , errors are multiplied by , and the -loss weight on is .
- A consistency model learns , the end of the PF-ODE path; and enforce and rule out constant solutions.
- Zero consistency-distillation loss gives the teacher's consistency function up to (solver order ), so CD is capped by the teacher; consistency training uses the pair , an unbiased but noisy Euler step.
- Regression-based few-step methods blur at 1–2 steps; adversarial and distribution-matching methods are sharp but mode-seeking and lose the seed-to-sample map. Always check diversity and calibration after distillation.
13 Latent diffusion and DiT
- Latent diffusion trains an autoencoder once, runs diffusion on its latent of shape , and decodes once; the compression in values is (48 for , , ).
- Small keeps perceptual detail that the diffusion model must then learn; large loses information the decoder cannot restore; the decoder sets a ceiling on quality.
- Latents with standard deviation have effective SNR , a log-SNR shift of ; Stable Diffusion's factor makes them unit-variance.
- A DiT with patch size has tokens; self-attention costs about multiply-adds per block and the linear layers ; doubling or halving multiplies the attention term by 16.
- Conditions enter by shape: maps by concatenation, global vectors by adaLN, token sequences by cross-attention (queries from the latent, keys and values from the text) or joint attention.
- adaLN-Zero regresses shift, scale and gate from the conditioning vector, with the gate starting at 0, so every block is the identity at initialization and the gates learn first.
- MM-DiT (Stable Diffusion 3) concatenates text and image tokens for one joint attention with separate weights per modality, so text and image read each other; the cost is .
14 Evaluating generative models
- Three kinds of evaluation answer three questions: likelihood (density on test data), sample-based distances (does the set of samples look like the data), and forecast scores (was the predicted distribution good for the outcome that happened).
- With uniform dequantization, (Jensen), and for data rescaled to ; the uniform model has 8 bpd.
- FID is the Fréchet distance between Gaussians fitted to Inception features; compute it with the symmetric form and
eigh. - The FID estimate is biased upward, about for white features, so FID values are comparable only at equal , features and preprocessing; KID (the unbiased MMD² with a cubic kernel) has mean 0 for equal distributions and can be negative.
- k-NN precision measures fidelity (generated samples inside the real support) and recall measures diversity (real samples inside the generated support); mode collapse gives high precision and low recall.
- A good likelihood does not imply good samples: mixing in 99% junk costs at most nats per image, bits/dim for .
- The CRPS is strictly proper; the standard ensemble estimator is biased up by , the fair estimator (with ) is unbiased.
- A calibrated ensemble has a flat rank histogram (U = too narrow, dome = too wide, slope = bias) and a corrected spread–skill ratio spread/RMSE near 1.
15 Inverse problems and assimilation
- The posterior score at every noise level splits: , with the noisy likelihood .
- is sharp at low noise and almost flat at high noise; in general it is intractable, because it needs the whole denoising posterior.
- Linear-Gaussian case: with (second-order Tweedie); adding the prior score gives the score of the noised exact posterior.
- DPS uses : it drops , so it is too strong at high noise by (scalar case), gives over-confident samples, and can point the wrong way for a multimodal .
- ΠGDM adds (exact for unit-variance Gaussian data); moment matching adds the second-order Tweedie covariance (exact for Gaussian priors).
- Zero-shot guidance serves any operator but is approximate and slow; an amortized conditional model is fast but must be retrained for a new operator; SDEdit is not posterior sampling.
- Score-based data assimilation uses a diffusion prior over trajectories plus observation guidance; for a linear-Gaussian model the exact version reproduces the Kalman smoother.
- Test posterior samplers with known posteriors, SBC rank histograms and coverage (calibration), plus a proper score (sharpness): a sampler that ignores passes SBC.