Generative Models: The Big Picture
What it means to learn a data distribution, and how autoencoders, VAEs, GANs, autoregressive models, normalizing flows and diffusion each solve the problem differently.
Most models you have met so far answer a question about an input: is this email spam?, what number is in this photo? A Generative model does something harder: it learns what the data itself looks like, well enough to create new examples that were never in the training set. Every AI image generator, voice cloner and chatbot is a generative model. This lesson maps the main families so that the next lessons (GANs, diffusion, Stable Diffusion) have a place to land.
Discriminative vs. generative
Formally, a discriminative classifier models p(y | x): the probability of a label given the input. A generative model models p(x) (or p(x | y) when it is conditioned on a label or text prompt). If you can sample from p(x), you can produce new data. Images are extremely high-dimensional (a 512×512 RGB image has 786,432 numbers), yet real photos occupy a tiny, structured region of that space; generative models try to find and describe that region.
- p(y | x)
- probability of label y given the input x: what a classifier outputs, e.g. p(cat | photo) = 0.9
- p(x)
- probability (density) of the data x itself: how typical this image is among all possible images
- p(x | y)
- probability of data x given a condition y, e.g. images of the class 'dog' or images matching a text prompt
- |
- 'given': everything to the right of the bar is known
- ~
- 'is sampled from': draw a random value from the distribution on the right
- x_new
- a brand-new generated example
- p_θ(x)
- the model's learned distribution; θ (theta) are its parameters (the network weights)
▸Worked example
Autoencoders: compress, then rebuild
An Autoencoder has two halves. The Encoder squeezes the input x into a small code z (the bottleneck); the Decoder tries to rebuild x from z. Because z is much smaller than x, the network is forced to keep only the most important information. The space of all possible codes is called the Latent space.
- x
- the input, e.g. 784 pixel values of a 28×28 image
- f_φ
- the encoder network; φ (phi) are its weights
- z
- the code (bottleneck), much shorter than x, e.g. 16 numbers
- g_θ
- the decoder network; θ (theta) are its weights
- x̂
- x-hat: the reconstruction, same shape as x
- ‖x − x̂‖²
- squared Euclidean distance: subtract element by element, square, add up
- L
- the reconstruction loss that training minimizes
▸Worked example
Variational autoencoders (VAE)
A Variational autoencoder (VAE) (Kingma & Welling, 2013)[1] fixes the holes. The encoder outputs a distribution (a mean μ and standard deviation σ per latent dimension) instead of a single point, and training adds a penalty (the KL divergence) that pulls each of these distributions towards a standard normal N(0, I). The result: codes overlap and fill a smooth, roughly Gaussian region. After training you simply sample z ~ N(0, I) and decode it. The training objective is the ELBO (evidence lower bound): reconstruct well, but keep the code distribution close to the prior.
- log p_θ(x)
- log-likelihood of the image under the model (higher = more probable); cannot be computed exactly
- ≥
- 'is greater than or equal to': the right side is a lower bound
- E_{q_φ(z|x)}
- average over codes z drawn from the encoder's distribution (in practice one sample per image)
- log p_θ(x|z)
- how probable x is when decoding z: the negative reconstruction error (e.g. −BCE)
- q_φ(z|x)
- the encoder's Gaussian over codes for this x, N(μ, σ²)
- β
- beta: weight of the KL term (1 = standard VAE)
- KL
- Kullback–Leibler divergence: how different two distributions are (≥ 0, and 0 only if identical)
- ‖
- separates the two distributions compared by KL( q ‖ p )
- N(0, I)
- the prior: standard normal, mean 0, each dimension independent with variance 1
▸Worked example
- μ
- mu: the encoder's mean vector, one number per latent dimension
- σ
- sigma: standard deviation vector, σ = exp(½ · log σ²)
- ⊙
- element-wise multiplication
- ε
- epsilon: random noise, same size as μ
- ~
- 'is sampled from'
- N(0, I)
- standard normal distribution
- −½
- minus one half
- Σⱼ
- sum over latent dimensions j = 1 … z_dim
- log σⱼ²
- the log-variance the encoder outputs for dimension j
- μⱼ²
- squared mean of dimension j: penalizes codes far from 0
- σⱼ²
- variance of dimension j
▸Worked example
- What it is
- How many numbers the encoder uses to describe one input: the size of the bottleneck.
- ↑ If you increase it
- Reconstructions get sharper and more detailed, but the space is harder to fill with the prior, so random samples can look less coherent; more parameters and compute.
- ↓ If you decrease it
- Stronger compression: blurrier reconstructions that keep only coarse structure, but a smoother, easier-to-sample space. Too small and different inputs collapse onto the same code.
- Typical values
- 2–32 for MNIST-scale toy VAEs (2 lets you plot the space). Stable Diffusion's VAE keeps a spatial latent: 4 channels at 1/8 resolution (64×64×4 for a 512×512 image); SD3/FLUX use 16 channels.
- What it is
- Multiplier on the KL term of the VAE loss: how strongly the latent codes are pushed towards N(0, I).
- ↑ If you increase it
- Smoother, more disentangled latent space (individual dimensions may map to single factors such as rotation or size), but blurrier reconstructions. Very large β causes posterior collapse: the decoder ignores z.
- ↓ If you decrease it
- Sharper reconstructions, but the model drifts towards a plain autoencoder: holes appear in the latent space and random samples get worse. Latent-diffusion VAEs use a tiny KL weight because a diffusion model, not the prior, does the sampling.
- Typical values
- 1.0 for a standard VAE; 2–10 for β-VAE disentanglement experiments; around 1e-6 in Stable Diffusion's autoencoder.
import torch
import torch.nn as nn
import torch.nn.functional as F
class VAE(nn.Module):
def __init__(self, x_dim=784, h_dim=400, z_dim=16):
super().__init__()
self.enc = nn.Sequential(nn.Linear(x_dim, h_dim), nn.ReLU())
self.mu = nn.Linear(h_dim, z_dim)
self.logvar = nn.Linear(h_dim, z_dim)
self.dec = nn.Sequential(
nn.Linear(z_dim, h_dim), nn.ReLU(), nn.Linear(h_dim, x_dim), nn.Sigmoid()
)
def forward(self, x):
h = self.enc(x)
mu, logvar = self.mu(h), self.logvar(h)
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu) # reparameterization
return self.dec(z), mu, logvar
def vae_loss(x_hat, x, mu, logvar, beta=1.0):
recon = F.binary_cross_entropy(x_hat, x, reduction="sum")
kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return recon + beta * kl
# Generate: decode random points from the prior N(0, I)
model = VAE()
with torch.no_grad():
samples = model.dec(torch.randn(8, 16)) # 8 new images, 784 pixels eachGANs: a generator vs. a critic
A Generative adversarial network (GAN) (Goodfellow et al., 2014)[2] skips likelihoods entirely. A generator turns random noise z into an image; a discriminator tries to tell real images from generated ones. They train against each other, and the generator improves until its fakes are hard to distinguish. GANs produce sharp images in a single forward pass but are notoriously unstable to train and can suffer mode collapse (covering only a few kinds of output). The next lesson is all about them.
Autoregressive models: one piece at a time
Autoregressive models use the chain rule of probability: generate the first element, then the second given the first, and so on. This is exactly how a GPT-style Large language model (LLM) writes text (Next-token prediction). For images, the elements can be pixels (PixelCNN) or discrete image tokens produced by a VQ-VAE-style tokenizer (DALL·E 2021, Parti). Likelihood is exact and training is stable, but sampling is sequential, so long sequences are slow.
- p(x)
- probability of the whole sequence x
- Π_{i=1}^{n}
- product over i = 1 … n: multiply all the terms
- n
- number of elements (pixels or tokens)
- xᵢ
- the i-th element
- p(xᵢ | x₁, …, x_{i−1})
- probability of element i given all earlier elements: what the network outputs
- |
- 'given'
▸Worked example
Normalizing flows: invertible transformations
A normalizing flow builds an invertible network f that maps simple noise z to data x = f(z). Because f can be inverted exactly, the change-of-variables formula gives the exact likelihood of any image. Examples are RealNVP (Dinh et al., 2016)[6] and Glow. The price: every layer must be invertible with an easy-to-compute determinant, which limits architecture choices. The modern descendant, Flow matching (rectified flow), keeps the 'flow' idea but learns a continuous velocity field instead and now powers Stable Diffusion 3 and FLUX.
- log
- natural logarithm
- p_X(x)
- density of the data x
- p_Z
- density of the simple base distribution, usually a standard normal
- f⁻¹
- the inverse of the flow network: data → noise
- ∂f⁻¹(x)/∂x
- the Jacobian: matrix of all partial derivatives of the inverse map (D × D for D-dimensional data)
- det
- determinant: by how much the map scales a small volume
- |
- absolute value (the bars around det)
▸Worked example
Diffusion models: learn to remove noise
A Diffusion model destroys training images by adding Gaussian noise in many small steps, then trains a network to undo one step at a time (Ho et al., 2020)[3]. To generate, start from pure noise and denoise repeatedly. Diffusion gives excellent quality and diversity with stable training, which is why it overtook GANs for text-to-image around 2021–2022. The cost is many network evaluations per image, an issue later work (DDIM, better solvers, distillation, flow matching) attacks directly. A friendly long-form explanation is Lilian Weng's blog post[4].
| Family | Sample quality | Sampling speed | Likelihood | Training | Well-known examples |
|---|---|---|---|---|---|
| VAE | Medium, often blurry | Fast (1 pass) | Lower bound (ELBO) | Stable | VQ-VAE, the autoencoder inside Stable Diffusion |
| GAN | High, sharp | Fast (1 pass) | None | Unstable, mode collapse | DCGAN, StyleGAN, BigGAN |
| Autoregressive | High | Slow (sequential) | Exact | Stable | PixelCNN, GPT, DALL·E (2021), Parti |
| Normalizing flow | Medium | Fast | Exact | Stable, constrained architecture | RealNVP, Glow |
| Diffusion / flow matching | Very high and diverse | Slower (many steps), improving fast | Bound (ELBO) or via ODE | Stable | DDPM, Stable Diffusion, Imagen, SD3, FLUX, Sora |
▸Go deeper: where the ELBO comes from, and how generators are evaluated
We want to maximise log p(x) = log ∫ p(x|z) p(z) dz, but the integral over all z is intractable. Introduce an approximate posterior q(z|x) (the encoder) and apply Jensen's inequality: log p(x) = log E_q[p(x|z)p(z)/q(z|x)] ≥ E_q[log p(x|z)] − KL(q(z|x) ‖ p(z)). The gap between the two sides is exactly KL(q(z|x) ‖ p(z|x)), so a better encoder gives a tighter bound. Diffusion models are trained with a (reweighted) version of the same bound, with the forward noising process playing the role of a fixed encoder[3].
- FID (Fréchet Inception Distance): compares the statistics of Inception-network features of real vs. generated images. Lower is better; it rewards both quality and diversity.
- Inception Score: higher when each image is confidently classifiable and the set covers many classes. Older and easier to game than FID.
- Log-likelihood / bits per dimension: available for VAEs, flows, autoregressive and diffusion models, but good likelihood does not guarantee good-looking samples.
- CLIP score and human preference: for text-to-image, how well the image matches the prompt, plus side-by-side human ratings.
Chapter 20 of the Deep Learning book (Goodfellow, Bengio & Courville)[5] surveys the pre-diffusion landscape of deep generative models in depth.
Quiz
References
- [1]Auto-Encoding Variational BayesPaperKingma & Welling2013arxiv.org
- [2]Generative Adversarial NetworksPaperGoodfellow et al.2014arxiv.org
- [3]Denoising Diffusion Probabilistic ModelsPaperHo et al.2020arxiv.org
- [4]What are Diffusion Models?ArticleLilian Weng2021lilianweng.github.io
- [5]Deep Learning (Chapter 20: Deep Generative Models)BookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [6]Density estimation using Real NVPPaperDinh et al.2016arxiv.org