AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
◐Image Generation
  1. Generative Models: The Big Picture
  2. Generative Adversarial Networks (GANs)
  3. Diffusion Models: From Noise to Image
  4. Stable Diffusion in Practice
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Image Generation

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.

Intermediate~22 min·6 references
Key terms
Generative modelAutoencoderVariational autoencoder (VAE)Latent spaceGenerative adversarial network (GAN)Diffusion modelFlow matching (rectified flow)

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.

≈
Art critic vs. painter
A discriminative model is an art critic: shown a painting, it says 'this is a Van Gogh'. A generative model is a painter who has studied thousands of Van Goghs and can paint a new one in that style. The painter must understand far more: brush strokes, colour palettes, composition, and how all of these vary together.

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.

discriminative: p(y | x) generative: p(x) or p(x | y) sample: x_new ~ p_θ(x)
θ are the model's learned parameters; the goal is p_θ(x) ≈ p_data(x).
In words: A discriminative model answers 'given this image x, how likely is each label y?', while a generative model describes how likely every possible image is (optionally given a label y), so it can also invent new ones by sampling. Training a generative model means adjusting θ until p_θ(x) puts high probability where real data lives.
Symbols(hover a symbol in the formula)
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
Toy 'images' of 2 pixels, each 0 (black) or 1 (white): only 4 possible images. Training data (8 images): 00, 00, 11, 11, 11, 01, 11, 00 Generative model by counting: p(00) = 3/8 = 0.375, p(11) = 4/8 = 0.5, p(01) = 1/8 = 0.125, p(10) = 0 Check: 0.375 + 0.5 + 0.125 + 0 = 1 Sample x_new ~ p(x): draw a uniform random number u between 0 and 1, say u = 0.62 00 covers 0 ≤ u < 0.375, 11 covers 0.375 ≤ u < 0.875 → u falls in 11 → x_new = 11 A discriminative model only learns something like p(y = 'all white' | x = 11) = 1 and cannot produce images.

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.

z = f_φ(x) x̂ = g_θ(z) L = ‖x − x̂‖²
Encoder f, decoder g, reconstruction loss.
In words: Encode x into a short code z, decode z back into a reconstruction x̂, and measure the squared distance between the two. Lowering L forces the small code z to keep exactly the information needed to rebuild x.
Symbols(hover a symbol in the formula)
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
x = (1, 0, 1, 1) (4 pixels) Encoder: z = f_φ(x) = (0.8, 0.3) (2 numbers: the bottleneck) Decoder: x̂ = g_θ(z) = (0.9, 0.2, 0.7, 1.0) x − x̂ = (0.1, −0.2, 0.3, 0.0) L = 0.1² + 0.2² + 0.3² + 0² = 0.01 + 0.04 + 0.09 + 0 = 0.14 Real sizes: MNIST 784 pixels → z of 16 numbers → 784 pixels (784 / 16 = 49× compression).
i
Why a plain autoencoder is a poor generator
Nothing forces the codes to fill the latent space nicely. Training images may map to scattered islands, with 'holes' in between. Pick a random z and decode it, and you usually get garbage, because that z lies in a hole the decoder never saw. Autoencoders are great for compression and denoising, but to generate we need a latent space we can sample from.

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) ≥ E_{q_φ(z|x)}[ log p_θ(x|z) ] − β · KL( q_φ(z|x) ‖ N(0, I) )
First term: reconstruction quality. Second term: regularizer that keeps the latent space smooth. β = 1 is the original VAE; β ≠ 1 gives a β-VAE.
In words: The log-probability the model gives an image is at least 'how well the decoder rebuilds x from codes the encoder suggests' minus 'how far the encoder's code distribution strays from a standard normal'. The right-hand side (the ELBO) can be computed, so training maximizes it; the VAE loss is its negative.
Symbols(hover a symbol in the formula)
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
One MNIST image, one sampled z: Reconstruction term: log p_θ(x|z) = −90 (BCE of 90 nats) KL term: KL = 25 β = 1: ELBO = −90 − 1 · 25 = −115 → log p_θ(x) ≥ −115, loss = 115 β = 4 (β-VAE): ELBO = −90 − 4 · 25 = −190 KL now costs 4× more, so training shrinks it (smoother latent space) at the price of blurrier reconstructions.
z = μ + σ ⊙ ε, ε ~ N(0, I) KL = −½ Σⱼ (1 + log σⱼ² − μⱼ² − σⱼ²)
The reparameterization trick moves the randomness into ε, so gradients can flow through μ and σ. The KL term has this closed form for Gaussians.
In words: Left: instead of sampling z directly (which would block gradients), sample plain noise ε and shift and scale it with the encoder's μ and σ. Right: for Gaussians the KL penalty has this closed form, summed over the latent dimensions j; it is 0 exactly when every μⱼ = 0 and σⱼ = 1.
Symbols(hover a symbol in the formula)
μ
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
2-D latent: μ = (0.5, −1.0), log σ² = (0, −2) → σ = (e⁰, e⁻¹) = (1, 0.3679) Noise ε = (0.2, −1.5) z₁ = 0.5 + 1 · 0.2 = 0.7; z₂ = −1.0 + 0.3679 · (−1.5) = −1.5518 KL, dimension 1: 1 + 0 − 0.25 − 1 = −0.25 KL, dimension 2: 1 + (−2) − 1 − e⁻² = 1 − 2 − 1 − 0.1353 = −2.1353 KL = −½ · (−0.25 − 2.1353) = 1.1927 (μ = 0 and log σ² = 0 in every dimension would give KL = 0.)
Loading interactive…
Press Walk through to follow one training example from x to the loss, then tap μ, log σ², ε and the KL box. Notice that the only randomness is ε, and that deleting the KL box (and the noise) leaves a plain autoencoder.
knobLatent dimension (z_dim)
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.
knobβ (KL weight)
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.
python
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 each
A minimal VAE in PyTorch (for 28×28 images flattened to 784 values).

GANs: 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) = Π_{i=1}^{n} p(xᵢ | x₁, …, x_{i−1})
Autoregressive factorization.
In words: The probability of a whole image (or sentence) is the product of the probabilities of each piece given all the pieces before it. A network predicts each of these conditionals, and generation samples the pieces one by one in order.
Symbols(hover a symbol in the formula)
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
A 3-pixel binary image x = (1, 0, 1): p(x₁ = 1) = 0.6 p(x₂ = 0 | x₁ = 1) = 0.7 p(x₃ = 1 | x₁ = 1, x₂ = 0) = 0.9 p(x) = 0.6 · 0.7 · 0.9 = 0.378 In logs (what is actually trained): ln 0.6 + ln 0.7 + ln 0.9 = −0.5108 − 0.3567 − 0.1054 = −0.9729 Generation needs 3 sequential network calls; a 256×256 RGB image pixel by pixel would need 256 · 256 · 3 = 196,608.

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 p_X(x) = log p_Z(f⁻¹(x)) + log | det ∂f⁻¹(x)/∂x |
Change of variables: exact log-likelihood.
In words: To get the probability of an image, map it back to noise space with the inverse network, look up how likely that noise is, then correct for how much the network stretches or squeezes space at that point. The determinant term is that volume correction.
Symbols(hover a symbol in the formula)
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
1-D flow: x = f(z) = 2z + 1, so f⁻¹(x) = (x − 1)/2 and ∂f⁻¹/∂x = 1/2 Base distribution: standard normal, log p_Z(z) = −½z² − ½ ln(2π) = −½z² − 0.9189 For x = 3: z = (3 − 1)/2 = 1 log p_Z(1) = −0.5 − 0.9189 = −1.4189 log |1/2| = −0.6931 log p_X(3) = −1.4189 − 0.6931 = −2.1121 The flow stretches space 2×, so the density is halved (−0.6931 = ln ½).

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].

FamilySample qualitySampling speedLikelihoodTrainingWell-known examples
VAEMedium, often blurryFast (1 pass)Lower bound (ELBO)StableVQ-VAE, the autoencoder inside Stable Diffusion
GANHigh, sharpFast (1 pass)NoneUnstable, mode collapseDCGAN, StyleGAN, BigGAN
AutoregressiveHighSlow (sequential)ExactStablePixelCNN, GPT, DALL·E (2021), Parti
Normalizing flowMediumFastExactStable, constrained architectureRealNVP, Glow
Diffusion / flow matchingVery high and diverseSlower (many steps), improving fastBound (ELBO) or via ODEStableDDPM, Stable Diffusion, Imagen, SD3, FLUX, Sora
Rules of thumb; modern systems often combine families (e.g. a VAE + a diffusion model = latent diffusion).
!
Common pitfalls
Judging by loss alone: a lower VAE loss does not mean nicer samples, and GAN losses barely correlate with quality. Look at samples and use metrics such as FID. Memorization: a generator that copies training images can score well; check nearest neighbours in the training set. Confusing 'latent' meanings: a VAE latent is a vector or small feature map; a diffusion model's 'latent' at step t is a noisy image of the same size as its input.
▸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

1.
What does a generative model fundamentally learn?
2.
Why does a VAE use the reparameterization trick z = μ + σ ⊙ ε?
3.
What happens if you set β (the KL weight) in a VAE very high?
4.
Which family offers exact likelihood and single-pass sampling?
5.
You decode a random vector with a plain (non-variational) autoencoder and get garbage. Why?
Score: 0/5

References

  1. [1]
    Auto-Encoding Variational Bayes
    PaperKingma & Welling2013arxiv.org
  2. [2]
    Generative Adversarial Networks
    PaperGoodfellow et al.2014arxiv.org
  3. [3]
    Denoising Diffusion Probabilistic Models
    PaperHo et al.2020arxiv.org
  4. [4]
    What are Diffusion Models?
    ArticleLilian Weng2021lilianweng.github.io
  5. [5]
    Deep Learning (Chapter 20: Deep Generative Models)
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  6. [6]
    Density estimation using Real NVP
    PaperDinh et al.2016arxiv.org
← Previous
Agents & tool use: ReAct, function calling, MCP
Next →
Generative Adversarial Networks (GANs)