- Explain the difference between learning p(x) and learning p(y|x), and the three abilities a generative model can provide: sampling, density evaluation and representation.
- Derive the VAE evidence lower bound and explain why the reparameterization trick makes it trainable with backpropagation.
- Explain the GAN minimax objective, the optimal discriminator, and why mode collapse and instability arise.
- Compute likelihoods for autoregressive and normalizing-flow models using the chain rule and change of variables.
- Compare generative families on sample quality, speed, likelihood and stability, and choose an appropriate family for a task.
- Implement and train a small VAE in PyTorch.
Before this: Probability and Statistics for AI, Information Theory and Loss Functions, Neural Networks and Backpropagation
Generative AI is the part of machine learning that produces new data: images, audio, video, text, molecules, code. Every modern system you have heard of, from chat assistants to text-to-image tools, is built on one of a small number of model families. If you understand what each family learns, how it is trained, and where it breaks, you can read any new paper or product announcement and place it on the map within minutes.
The core idea: learning a distribution
A discriminative model learns : given an input , how likely is each label ? A generative model learns itself (or for some condition such as a text prompt): how probable is this particular image, waveform or sentence among all the data the world could produce?
A useful picture: imagine every possible 64×64 color image as a point in a space with dimensions. Almost all of those points are static. Real photos occupy a thin, curved region (a "manifold") inside that space. A generative model is a map of that region: it tells you where the dense areas are and, crucially, lets you sample new points that land inside it.
Learning gives you up to three abilities, and the model families differ in which they provide cheaply:
- Sampling: draw new , where is the model distribution with parameters .
- Density evaluation: compute for a given (useful for compression, anomaly detection, and comparing models by likelihood).
- Representation: obtain a compact latent code that describes .
Training almost always means making close to the data distribution . The most common target is maximum likelihood, which is equivalent to minimizing the KL divergence :
The families below are different answers to one hard question: how do you build a that is flexible enough to describe photographs, yet tractable enough to train and sample?
Family 1: Autoregressive models
Any joint distribution can be factored exactly with the chain rule of probability. Order the dimensions of as :
An autoregressive model is a neural network that outputs each conditional. For text, are tokens and the network is a causal transformer: this is exactly how large language models work. For images, PixelRNN and PixelCNN (van den Oord et al., 2016) predicted pixels one at a time in raster order; WaveNet (van den Oord et al., 2016) did the same for raw audio samples. Today, images and audio are usually first compressed into discrete tokens by a learned codec (covered in later lessons), and a transformer predicts those tokens.
Worked example. A toy model generates three binary values. It predicts , then , then . The probability of the sequence is
so its negative log-likelihood is nats, or bits. Training minimizes the average of exactly this quantity over the dataset.
Strengths: exact likelihood, very stable training (it is just cross-entropy), and they scale predictably with data and compute. Weaknesses: sampling is sequential, so generating elements needs network evaluations (mitigated by KV caching and parallel decoding tricks); the fixed ordering is arbitrary for images; and errors can compound because each step conditions on the model's own earlier outputs.
Family 2: Variational autoencoders (VAEs)
Kingma and Welling introduced the VAE in "Auto-Encoding Variational Bayes" (2013). The idea is a latent-variable model: first draw a low-dimensional code from a simple prior , then generate from a decoder . The marginal likelihood is
which is intractable for a neural decoder because you cannot integrate over all . The VAE adds an encoder (inference network) with parameters that guesses which codes could have produced . Using Jensen's inequality you get the evidence lower bound (ELBO):
The gap between the two sides is exactly , so the bound is tight when the encoder matches the true posterior. Maximizing the ELBO trains both networks at once: the first term asks the decoder to reconstruct from codes the encoder proposes; the second keeps the encoder's codes close to the prior so that sampling at generation time lands somewhere the decoder understands.
The reparameterization trick
The encoder outputs a mean and standard deviation for a diagonal Gaussian. We need gradients of an expectation over with respect to , but sampling is not differentiable. The trick is to move the randomness outside the network:
where is element-wise multiplication. Now is a deterministic, differentiable function of given , so ordinary backpropagation works and gradient estimates have low variance.
For a diagonal Gaussian encoder and standard normal prior, the KL term has a closed form per latent dimension :
Worked example. A 2-dimensional latent with and :
- Dimension 1:
- Dimension 2:
- Total KL nats.
If the decoder's reconstruction log-likelihood for this (estimated with one sample of ) is , the ELBO is , and the training loss is its negative, .
Strengths: fast single-pass sampling, a meaningful latent space, a likelihood bound, stable training. Weaknesses: with simple Gaussian decoders, samples tend to be blurry because the reconstruction term behaves like mean-squared error, which averages over plausible outputs. Posterior collapse (the encoder ignores and the KL term goes to zero) is common when the decoder is powerful. The modern role of VAEs is mostly as compressors: the latent space of Stable Diffusion is a VAE (trained with extra perceptual and adversarial losses), and VQ-VAE (van den Oord et al., 2017) replaced the Gaussian latent with a discrete codebook, which is the ancestor of today's image and audio tokenizers.
Family 3: Generative adversarial networks (GANs)
Goodfellow et al. (2014) proposed training two networks against each other. A generator maps noise to a sample . A discriminator outputs the probability that its input is real. They play a minimax game:
For a fixed generator with sample distribution , the optimal discriminator is
For example, at a point where and , . Substituting back shows the generator is minimizing , where JSD is the Jensen–Shannon divergence; the global optimum is , where everywhere and . In practice, the generator is trained with the "non-saturating" loss instead, because has vanishing gradients early in training when easily rejects fakes.
GANs produced the sharpest images of the late 2010s (the StyleGAN line from NVIDIA is the best-known example) because the discriminator acts as a learned perceptual loss rather than pixel-wise error.
Failure modes
- Mode collapse: the generator finds a few outputs that fool the current discriminator and produces only those, covering a small part of the data distribution. The adversarial objective does not directly penalize missing modes.
- Training instability: it is a two-player game, not a single minimization. Gradients can oscillate, the discriminator can overpower the generator (vanishing generator gradients), and results are sensitive to architecture, learning rates and batch size. Remedies include Wasserstein GAN losses with gradient penalties, spectral normalization, two-timescale learning rates and careful architecture choices, but none make GANs as plug-and-play as likelihood training.
- No likelihood: you cannot evaluate , which makes model comparison depend on sample-based metrics such as FID.
GANs remain important as components: adversarial losses sharpen VAE decoders and neural audio codecs, and GAN vocoders such as HiFi-GAN convert spectrograms to waveforms in many speech systems.
Family 4: Normalizing flows
A flow builds from an invertible, differentiable function that maps data to a latent with a simple density . The change-of-variables formula gives an exact likelihood:
The Jacobian determinant accounts for how stretches or compresses volume. Worked 1D example: let with , so and . At , , , so .
Computing a determinant costs , so flows use layers with triangular Jacobians. Coupling layers (RealNVP, Dinh et al. 2016; Glow, Kingma and Dhariwal 2018) split into halves and transform one half with a scale and shift computed from the other; the log-determinant is just the sum of the log-scales. Rezende and Mohamed (2015) popularized the term "normalizing flow" for variational inference.
Strengths: exact likelihood, exact inversion, one-pass sampling. Weaknesses: the invertibility constraint forces the latent to have the same dimension as the data and limits architecture, so pure flows have lagged in sample quality. The ideas live on, however, in continuous-time flows and flow matching, which train a neural ODE velocity field and now power several leading image and video generators (see the diffusion lesson).
Family 5: Diffusion models
Diffusion models (Sohl-Dickstein et al., 2015; made practical by Ho, Jain and Abbeel's DDPM, 2020) define a fixed forward process that gradually adds Gaussian noise to data until nothing is left but noise, then train a network to reverse it one small step at a time. Each reverse step is an easy denoising problem, so training is a simple regression loss, stable and scalable. Sampling starts from pure noise and runs the learned denoiser for tens of steps. The training objective is a reweighted ELBO, so diffusion models also give likelihood bounds.
Diffusion (and its close relative flow matching) is the dominant approach for images, video and much of audio as of November 2026. Its main weakness is sampling cost: many network evaluations per sample, which a whole research area of fast samplers and distillation works to reduce. The next lesson covers it in depth.
Family 6: Energy-based models (briefly)
An energy-based model (EBM) assigns a scalar energy , low for realistic data, and defines
The partition function is intractable, which makes both likelihood training and sampling hard; sampling typically uses Markov chain Monte Carlo such as Langevin dynamics, which repeatedly steps along plus noise. EBMs are conceptually important because the gradient of the log-density, , does not depend on . That quantity is the score, and learning the score directly is exactly what score-based diffusion models do. In that sense diffusion is the practical descendant of energy-based thinking.
Comparison
The table summarizes typical behavior; individual models can deviate.
| Family | Sample quality | Sampling speed | Likelihood | Training stability | Typical use today |
|---|---|---|---|---|---|
| Autoregressive | High (with tokenizers) | Slow, sequential | Exact | Very stable | Text, audio tokens, some image systems |
| VAE | Moderate, often blurry | Fast, one pass | Lower bound | Stable | Latent compressors, tokenizers |
| GAN | High, sharp | Fast, one pass | None | Unstable | Vocoders, codec/decoder losses, fast distilled generators |
| Normalizing flow | Moderate | Fast, one pass | Exact | Stable | Density estimation, scientific modeling |
| Diffusion / flow matching | Very high | Slow (many steps), improvable | Bound (or exact via ODE) | Stable | Images, video, audio |
| Energy-based | Variable | Slow (MCMC) | Unnormalized | Hard | Research, compositional modeling |
A well-known framing is the "generative trilemma": high quality, fast sampling and mode coverage are hard to get simultaneously. GANs are fast and sharp but drop modes; VAEs and flows are fast with coverage but lower quality; diffusion has quality and coverage but is slow. Much of the last few years of research is about escaping that triangle, for example distilling diffusion models into few-step generators.
Code: a small VAE in PyTorch
This VAE learns the two-moons dataset (2D points), small enough to train on a CPU in seconds. It shows the encoder, reparameterization, closed-form KL and sampling.
import torch, torch.nn as nn
from sklearn.datasets import make_moons
X = torch.tensor(make_moons(4000, noise=0.05)[0], dtype=torch.float32)
class VAE(nn.Module):
def __init__(self, d=2, h=64, k=2):
super().__init__()
self.enc = nn.Sequential(nn.Linear(d, h), nn.ReLU(), nn.Linear(h, 2 * k))
self.dec = nn.Sequential(nn.Linear(k, h), nn.ReLU(), nn.Linear(h, d))
def forward(self, x):
mu, logvar = self.enc(x).chunk(2, dim=-1)
eps = torch.randn_like(mu)
z = mu + torch.exp(0.5 * logvar) * eps # reparameterization
return self.dec(z), mu, logvar
model = VAE()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for step in range(3000):
x = X[torch.randint(0, len(X), (256,))]
xhat, mu, logvar = model(x)
recon = ((xhat - x) ** 2).sum(-1).mean() # Gaussian decoder, fixed variance
kl = 0.5 * (mu**2 + logvar.exp() - 1 - logvar).sum(-1).mean()
loss = recon + 0.1 * kl # beta-weighted ELBO (beta = 0.1)
opt.zero_grad(); loss.backward(); opt.step()
if step % 1000 == 0:
print(step, round(recon.item(), 4), round(kl.item(), 4))
with torch.no_grad():
samples = model.dec(torch.randn(500, 2)) # generate: z ~ N(0, I)
print(samples[:5])
The 0.1 weight on the KL term makes this a β-VAE with β < 1: it trades a looser prior match for sharper reconstructions. With β = 1 on such a tiny model, samples typically smear into a blurry cloud that also fills the gap between the moons, a direct view of the VAE blurriness problem. Plot samples for both settings to compare (details vary by seed).
Common pitfalls
- Comparing likelihoods across families carelessly. Bits-per-dimension from a flow and an ELBO from a VAE are not directly comparable (one is exact, one is a bound), and likelihood correlates poorly with perceptual quality: a model can have excellent likelihood and ugly samples, or vice versa.
- Assuming sharp samples mean good coverage. A GAN can produce beautiful images while ignoring half the classes. Always check diversity (recall-style metrics, per-class counts, nearest-neighbor checks against training data).
- Forgetting the KL weight. Reported "VAE" results often use β ≠ 1 or KL annealing. Copying the architecture without the schedule leads to posterior collapse or blurry output.
- Using pixel MSE as the only loss for anything that must look realistic. Pixel losses average; perceptual and adversarial losses are why modern latent autoencoders look crisp.
- Treating memorization as generalization. Large generative models can reproduce near-copies of training examples. Deduplicate training data and test for near-duplicates of outputs.
In practice
Production systems as of November 2026 combine families rather than pick one. A typical image or video generator is a VAE-style autoencoder (trained with perceptual and adversarial losses) that compresses pixels into latents, plus a diffusion or flow-matching transformer that generates those latents. Text and code generation is autoregressive. Speech and music systems often use a codec (an autoencoder with vector quantization and GAN losses) whose tokens are generated by an autoregressive transformer, sometimes with a diffusion or flow stage on top. When you evaluate a new system, ask four questions: what is the representation (pixels, continuous latents, discrete tokens)? Which family generates it? How many network evaluations does one sample cost? How was quality measured, and does that metric capture diversity?
Key takeaways
- A generative model learns the data distribution p(x) (or p(x|c)), which can provide sampling, density evaluation and latent representations, though no family gives all three cheaply.
- Autoregressive models factor p(x) with the chain rule and train with plain cross-entropy, giving exact likelihoods and stable training at the cost of sequential sampling.
- VAEs maximize the ELBO, a reconstruction term minus a KL regularizer, made trainable by the reparameterization trick; today they mainly serve as latent compressors.
- GANs train a generator against a discriminator; they give sharp, fast samples but no likelihood and suffer from mode collapse and unstable training.
- Diffusion and flow-matching models dominate image, video and much audio generation because they train stably with a regression loss and cover the data well, though sampling needs many steps.
- Real systems combine families, for example an autoencoder for compression plus a diffusion transformer or autoregressive model for generation.
Terms in this lesson
- Generative model
- A model that represents a probability distribution over data, p(x) or p(x|c), from which new samples can be drawn.
- Evidence lower bound (ELBO)
- A tractable lower bound on log p(x) equal to the expected reconstruction log-likelihood minus the KL divergence between the approximate posterior and the prior.
- Reparameterization trick
- Writing a random latent as a deterministic function of model outputs and independent noise (z = mu + sigma * epsilon) so gradients can flow through sampling.
- Mode collapse
- A GAN failure in which the generator produces only a small subset of the data's variety because that subset fools the discriminator.
- Normalizing flow
- A generative model built from invertible transformations whose exact likelihood follows from the change-of-variables formula.
- Score
- The gradient of the log-density with respect to the data, grad_x log p(x), which does not depend on the normalizing constant.
- Posterior collapse
- A VAE failure in which the encoder's output matches the prior regardless of input, so the latent carries no information.
- Partition function
- The normalizing constant Z in an energy-based model that makes exp(-E(x))/Z integrate to one; usually intractable.
Check your understanding
- 1.
Which quantity does a VAE maximize during training?
- 2.
At a point x where p_data(x) = 0.2 and the generator's density p_g(x) = 0.6, what is the optimal GAN discriminator output D*(x)?
- 3.
You need to score how unusual each incoming sensor reading is with an exact density, and sample quality is secondary. Which family fits best?
- 4.
Why does the reparameterization trick help train VAEs?
- 5.
An autoregressive model assigns probabilities 0.5, 0.4 and 0.5 to the three tokens of a sequence. What is the sequence's negative log-likelihood in bits?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
A VAE encoder outputs and for one input. Compute the KL divergence to . If the one-sample reconstruction log-likelihood is , what is the ELBO?
Show solution
Per dimension, .
- Dim 1: .
- Dim 2: .
KL nats. ELBO nats, so the loss is .
- Exercise 2Core
A 1D flow maps data to latent with and . Compute at and at . Explain why the factor 3 appears.
Show solution
. At : , , so . At : , , so .
The map stretches -space by a factor of 3 when going to ; equivalently, data are concentrated in an interval 3 times narrower than the latent, so density in is 3 times higher. A density above 1 is fine for continuous variables.
- Exercise 3Core
Your team must choose a generative approach for each case and justify it in one sentence: (a) a 2 ms-latency generator of synthetic sensor traces on an edge device; (b) a photorealistic product-image generator where quality matters most and a few seconds per image is acceptable; (c) a compression codec where you need exact code lengths.
Show solution
(a) A GAN or a distilled one-step generator: single forward pass, and some loss of diversity is acceptable for synthetic traces (monitor for mode collapse). (b) A latent diffusion or flow-matching model: best quality and coverage, and the multi-step cost fits the time budget. (c) An autoregressive model or normalizing flow: both give exact likelihoods, and is the ideal code length under entropy coding.
- Exercise 4Challenge
Show that for a fixed generator, the GAN value function is maximized by , and that substituting gives .
Show solution
Write . For each , maximize over with , . The derivative gives , and the second derivative is negative, so this is the maximum.
Substitute, with :
.
Since , . JSD is non-negative and zero only when , so the generator's optimum is the data distribution.
- Exercise 5Challenge
Modify the lesson's VAE code to track posterior collapse: report the average KL per latent dimension, and run with and . What do you expect, and why?
Show solution
Add per-dimension KL logging:
kl_dim = 0.5 * (mu**2 + logvar.exp() - 1 - logvar).mean(0) # shape (k,) if step % 1000 == 0: print(step, [round(v, 3) for v in kl_dim.tolist()])Wrap training in a function taking
betaand useloss = recon + beta * kl. Expected: with , the KL penalty is strong relative to the small reconstruction error on 2D data, so one or both dimensions drift toward KL (collapsed: they carry no information) and reconstructions approach the data mean, giving blurry samples. With , both dimensions keep substantial KL because encoding information is cheap, reconstructions are sharp, but samples from may land in regions the decoder never saw because the aggregate posterior no longer matches the prior. Exact numbers vary by seed.
Further reading
- paperKingma & Welling, Auto-Encoding Variational Bayes (2013)
- paperGoodfellow et al., Generative Adversarial Nets (2014)
- paperKingma & Welling, An Introduction to Variational Autoencoders (2019)
- paperRezende & Mohamed, Variational Inference with Normalizing Flows (2015)
- bookGoodfellow, Bengio & Courville, Deep Learning, Ch. 20: Deep Generative Models (2016)
Go further
Sources
- Kingma & Welling, Auto-Encoding Variational Bayes
- Goodfellow et al., Generative Adversarial Nets
- Dinh, Sohl-Dickstein & Bengio, Density estimation using Real NVP
- Sohl-Dickstein et al., Deep Unsupervised Learning using Nonequilibrium Thermodynamics
- Ho, Jain & Abbeel, Denoising Diffusion Probabilistic Models
- van den Oord, Vinyals & Kavukcuoglu, Neural Discrete Representation Learning (VQ-VAE)
Fact-checked and last reviewed 2026-11-05