◆ AI All-in-One

Level 3 In-Depth AI · Generative AI

What Generative Models Do

A generative model learns what a whole collection of data looks like, so that it can produce new examples that could have come from the same collection. This chapter explains the idea of a learned distribution and compares the main families of generative models.

Level
●●●●● Easy
Reading
13 min
To learn it well
45 minutes to read, 30 minutes to practise
↗ Plan a path here

Read first

Probability DistributionsNeural Networks

This leads to

Music and Voice GenerationDiffusion ModelsNormalizing Flows and Flow MatchingGenerative Adversarial NetworksVariational AutoencodersDeepfakes and Misinformation
The full path from zero — 15 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Vectors
  4. Derivatives and Slopes
  5. How Machines Learn
  6. Probability Distributions
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. What Generative Models Do

Read them roughly in this order. See it on the concept map →

Why it matters

Most of the machine learning in this guide so far has been about answering questions about data: is this email spam, what digit is in this picture, what will the house sell for. A generative model does something that feels quite different. It produces new data: a photo of a cat that never existed, a paragraph of text, a voice reading a sentence, a short video clip, a new protein shape.

Every headline "generative AI" system is one of these. ChatGPT-style language models generate text one token at a time. Image tools such as Stable Diffusion, Midjourney and DALL·E generate pictures with diffusion or flow matching. Video models such as Sora and Veo extend the same ideas to moving images (Video Generation). Voice and music tools generate sound (Music and Voice Generation). The same machinery also has quieter uses. It can make synthetic training data, fill in missing parts of an image, compress data, and spot anomalies, because a model that knows what normal data looks like can notice data that doesn't fit.

This chapter is the map for the whole Generative AI part. It explains the one idea all these systems share and introduces the main families. Each family gets its own chapter.

The intuition

Imagine you have looked at ten thousand photographs of faces. You haven't memorised any single face, but you have absorbed what faces are like. Two eyes, roughly level. A nose between them. Skin tones in a certain range. Hair on top more often than below. If someone asked you to sketch a new face, you could do it, and it would look plausible without being a copy of any face you saw.

A generative model learns the same kind of knowledge, in numbers. Mathematicians call "what the data is like" the data distribution, written p(x)p(x). Here xx is one example (one image, one sentence) and p(x)p(x) says how likely that example is to show up. A realistic face photo has relatively high p(x)p(x). A screen of random coloured static has a p(x)p(x) of essentially zero, because nothing like it ever appears among real photos. A generative model is a learned approximation of p(x)p(x) that you can sample from. Each time you ask, it hands you a fresh xx that would be at home in the data.

1. Training data1,000 real examples (250 shown) 2. Learned distribution p(x)a mixture of 10 Gaussian blobs 3. New samples250 points drawn from p(x) fit draw each dot is oneexample x high density on the moons,near zero in the gaps like the data,but not copies of it
Fig. 1 The idea of every generative model, in two dimensions. Left: training points. Middle: a model fitted to them, here a mixture of Gaussian blobs, puts high probability on the moon shapes and almost none in the gaps. Right: sampling from the model gives new points that look like the data but are not copies of it.

Compare this with the models you met earlier. A spam filter is a discriminative model. It learns p(y∣x)p(y \mid x), the probability of a label yy given an input xx. It only has to find the boundary between spam and not-spam. It never needs to know what a typical email looks like. A generative model has to know where all the data lives, in every direction. That is a much harder job, which is why generative models are usually much larger and are trained on much more data.

Key idea A generative model learns the distribution of the training data, p(x)p(x), well enough to draw new samples from it. The families differ in how they represent that distribution and how they turn random numbers into a sample.

How it works

Why this is hard

For two-dimensional points, as in the picture, you can fit a distribution with a few blobs. Real data is far bigger. A small 256×256 colour photo is 196,608 numbers (256×256×3256 \times 256 \times 3), so each image is a single point in a 196,608-dimensional space. Almost every point in that space is meaningless static. Real photos occupy a vanishingly thin, curved region inside it. Data scientists call this region a manifold (see t-SNE and UMAP). The model has to find that region and learn how probability spreads along it, from a finite number of examples, without simply memorising them.

There are two basic jobs a model might do with p(x)p(x):

  1. Evaluate it: given an xx, say how likely it is. This is useful for anomaly detection and for training.
  2. Sample from it: produce new xx values with the right frequencies.

Different families are good at different jobs. Nearly all of them use one shared trick for sampling: start from simple randomness and transform it. Computers can easily draw numbers from a standard Gaussian (bell-curve) distribution. A generative model is a learned function that turns those easy random numbers into hard, structured data. The random input is often called a latent variable or latent code, written zz. "Latent" means hidden: zz is not observed in the data. The model invents it to explain the data.

Training: make the data likely

How do you tell a model it has learned a good p(x)p(x)? The most common answer is maximum likelihood: adjust the parameters θ\theta so that the training examples get as high a probability as possible. Because multiplying thousands of small probabilities underflows, everyone works with logarithms and maximises the average log-likelihood:

1N∑i=1Nlog⁡pθ(xi)\frac{1}{N} \sum_{i=1}^{N} \log p_\theta(x_i)

Here xix_i is the ii-th of NN training examples, pθp_\theta is the model's distribution with parameters θ\theta, and log⁡\log is the natural logarithm. In practice you minimise the negative of this, the negative log-likelihood, with Gradient Descent. This is exactly the cross-entropy loss that trains language models. A model trained this way is called a likelihood-based model. The Entropy, Cross-Entropy and KL Divergence chapter shows that maximising likelihood is the same as making the model's distribution as close as possible to the data's, measured by KL divergence.

Some families cannot compute pθ(x)p_\theta(x) at all. A GAN is the famous example: it is a sampler with no formula for the probability. These are implicit generative models, and they need a different training signal, such as a second network acting as a judge.

A worked example with real numbers

The code below fits a mixture of ten Gaussians to 1,000 two-dimensional points shaped like two interlocking moons. That is the picture above. After fitting:

  • A point on one of the moons, (1.0,0.0)(1.0, 0.0), gets a log-density of −1.26-1.26, so the density is e−1.26≈0.28e^{-1.26} \approx 0.28.
  • A point in the empty space below, (0.0,−1.0)(0.0, -1.0), gets −47.52-47.52, so the density is e−47.52≈2×10−21e^{-47.52} \approx 2 \times 10^{-21}: effectively impossible.
  • The average log-likelihood of the training data is −0.372-0.372. Training pushed this number as high as it could.

So the model has learned where the data lives. Ask it for samples and it produces new points along the moons. That is generation in miniature.

The main families

Every family answers two questions differently: how do you represent p(x)p(x) and how do you sample?

Generative model learn p(x) from examples, then sample new x Piece by piece one token, pixel or sample at a time Noise → data in one jump a network maps a random code z to an example x Noise → data in many steps a network takes 1–1,000 small steps from noise Autoregressive predicts nextpiece from past GPT, WaveNet VAE encoder + decodersmooth latent 2013 GAN generator foolsa discriminator 2014, StyleGAN Normalizing flow invertible layers,exact p(x) RealNVP, Glow Diffusion learns to removeadded noise DDPM, SD 1.5 Flow matching learns a velocitynoise → data SD 3, FLUX As of 2026, most text models are autoregressive; most image and video models are diffusion or flow matching, often with a VAE-style autoencoder to compress the data first.
Fig. 2 The family tree of modern generative models, grouped by how they turn randomness into data: piece by piece, in one jump from a random code, or in many small steps from noise.

Autoregressive models split an example into pieces and predict each piece from the ones before it. For text the pieces are tokens. The chain rule of probability makes this exact: p(x)=p(x1) p(x2∣x1) p(x3∣x1,x2)⋯p(x) = p(x_1)\,p(x_2 \mid x_1)\,p(x_3 \mid x_1, x_2)\cdots. Sampling draws one piece, appends it, and repeats. They are trained by plain maximum likelihood, they are stable and they scale beautifully, which is why all mainstream LLMs are autoregressive (Language Modeling and Next-Token Prediction). The cost is speed: generating 1,000 pieces takes 1,000 sequential steps. They were used for images (PixelCNN) and audio (WaveNet) too, and they returned to audio as "audio token" models (Music and Voice Generation).

Variational autoencoders (VAEs) learn two networks. An encoder squeezes each example into a small latent code, and a decoder turns codes back into examples. Training makes the codes follow a simple Gaussian, so at generation time you draw zz from that Gaussian and decode it. VAEs are fast and have smooth, meaningful latent spaces, but on their own they make blurry images. Today their main job is as the compressor inside latent diffusion models. See Autoencoders and Variational Autoencoders.

Generative adversarial networks (GANs) pit a generator, which turns noise into samples, against a discriminator that tries to tell real from fake. They produce sharp images in a single network pass. But training is a delicate balancing act, and they tend to drop rare kinds of data. See Generative Adversarial Networks.

Normalizing flows build the noise-to-data map from invertible layers, so the exact likelihood can be computed. The invertibility requirement limits the architecture, and they have mostly been overtaken. See Normalizing Flows and Flow Matching.

Diffusion models learn to undo a gradual noising process. Generation starts from pure noise and removes a little noise at each of many steps. They train stably, cover the data well, and have powered nearly every strong image generator since 2022. Their weakness is the number of steps. See Diffusion Models, Latent Diffusion and Stable Diffusion and Diffusion Transformers.

Flow matching learns a velocity field that carries noise smoothly to data, often along straight lines. It is a simpler, closely related cousin of diffusion and is used by several leading image and video models as of late 2026. See Normalizing Flows and Flow Matching.

Comparing them

People often summarise the trade-offs with three wishes: sample quality (do samples look real?), mode coverage (does the model produce all the kinds of data, including rare ones, in the right proportions?), and fast sampling. A "mode" is a peak in the distribution, such as one moon, one digit class or one breed of dog.

Family Quality Coverage Sampling speed Exact p(x)p(x)?
Autoregressive high high slow (one step per piece) yes
VAE blurry alone high fast (one pass) lower bound only
GAN high often poor fast (one pass) no
Normalizing flow moderate high fast yes
Diffusion very high high slow (tens of passes) bound / with extra work
Flow matching very high high fewer passes than diffusion with extra work

No family wins every column, and much modern research mixes them. Stable Diffusion, for example, uses a VAE to compress images, a diffusion model to generate in the compressed space, and a Transformer text encoder to steer it.

In code

Here is the simplest possible generative model: a mixture of Gaussians from scikit-learn, fitted to the moons data from the picture. It does both jobs, sampling and evaluating likelihood.

import numpy as np
from sklearn.datasets import make_moons
from sklearn.mixture import GaussianMixture

# Training data: 1,000 points shaped like two interlocking moons
X, _ = make_moons(n_samples=1000, noise=0.05, random_state=0)

# A generative model: a mixture of 10 Gaussian "blobs"
gm = GaussianMixture(n_components=10, random_state=0).fit(X)

# 1. Sample: create brand-new points that look like the data
new_points, _ = gm.sample(5)
print(new_points.round(2))
# [[ 1.21 -0.45]
#  [ 0.46  0.94]
#  [ 0.86  0.51]
#  [-0.31  0.95]
#  [-0.54  0.88]]

# 2. Score: how likely is a point under the learned distribution?
on_moon  = np.array([[1.0, 0.0]])     # the right-hand tip of the upper moon
off_moon = np.array([[0.0, -1.0]])    # empty space below both moons
print("log p(on moon) :", gm.score_samples(on_moon).round(2))    # [-1.26]
print("log p(off moon):", gm.score_samples(off_moon).round(2))   # [-47.52]
print("average log-likelihood:", round(gm.score(X), 3))          # -0.372

A Gaussian mixture works in two dimensions but collapses in thousands, because you would need astronomically many blobs to cover the thin, curved manifold of real images. The rest of this part replaces the blobs with neural networks. The two jobs stay the same: fit p(x)p(x), then sample from it.

Common pitfalls

  • Judging by cherry-picked samples. Any model looks good on its best outputs. Look at many random, unfiltered samples, and use numerical metrics such as FID (Fréchet Inception Distance, which compares statistics of real and generated images) alongside human judgement.
  • Confusing memorisation with generation. A model that reproduces training images exactly has a perfect-looking output and has learned nothing general. Large image models have been shown to regurgitate some training images that were duplicated many times in their data. Check samples against their nearest training neighbours.
  • Ignoring coverage. A model can make beautiful samples of a few kinds of data and never produce the rest. Count how often each kind appears, as the Generative Adversarial Networks chapter does with its eight blobs.
  • Trusting likelihood alone. High log-likelihood and good-looking samples don't always go together. Models can score well while sampling poorly, and the reverse.

Watch out Generative models reproduce the patterns in their training data, including biases, private information and copyrighted material. What a model produces is only as fair, safe and lawful as what it learned from. See Bias and Fairness, Privacy, Data and Copyright and Deepfakes and Misinformation.

Where it leads

A bit of history

Generative modelling is older than deep learning. Statisticians fitted mixtures of Gaussians and hidden Markov models for decades, and speech recognisers used them until the 2010s. Neural generative models began with Boltzmann machines in the 1980s (Hinton and Sejnowski). In 2006 Hinton's deep belief networks helped restart interest in deep learning itself.

The modern era began with two papers a few months apart: Kingma and Welling's variational autoencoder (December 2013) and Goodfellow and colleagues' generative adversarial networks (June 2014). GANs dominated image generation for the rest of the decade, reaching photorealistic faces with StyleGAN (2018). In parallel, PixelCNN and WaveNet (2016) showed autoregressive models could generate images and natural-sounding speech. GPT-2 (2019) and GPT-3 (2020) showed how far the autoregressive approach could go with text.

Diffusion models were proposed by Sohl-Dickstein and colleagues in 2015 but stayed a curiosity until Ho, Jain and Abbeel's DDPM paper (2020). In 2021 Dhariwal and Nichol reported diffusion models beating GANs on image quality. DALL·E 2, Imagen and Stable Diffusion followed in 2022. Flow matching (2022) and diffusion Transformers (2022) set up the generation of image and video models that followed from 2024.

Try it

  1. Run the code with n_components=2 and then n_components=50. Compare the average log-likelihood and look at the samples (plot them with matplotlib). Which one underfits? Which one is starting to memorise?
  2. Evaluate gm.score_samples on the point (0.5,0.25)(0.5, 0.25), which lies between the two moons. Is it closer to the on-moon or the off-moon value?
  3. For each of these tasks, say whether you need a generative or a discriminative model: detecting fraudulent transactions with no fraud labels; reading handwritten postcodes; making extra training photos of a rare plant disease.

Hint for 1: with 50 blobs, gm.score(X) keeps rising, but compare it with the score on a fresh make_moons sample drawn with a different random_state.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A spam filter and an image generator are both trained on data. What does the image generator have to learn that the spam filter does not?

  2. A Gaussian mixture fitted to the two-moons data gives a point on a moon a log-density of -1.26 and a point in the empty space below a log-density of -47.52. What does this tell you?

  3. You need a model that makes sharp images in a single network pass, and you can live with it sometimes missing rare kinds of data. Which family fits best according to the comparison table?

  4. A colleague shows you twelve beautiful samples from a new image model and says it is ready. What is the most important thing to check first?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

CS236: Deep Generative Models (course notes)

Stefano Ermon & Aditya Grover (Stanford) · Intermediate · Free

Stanford's course on generative models: autoregressive models, VAEs, normalizing flows, GANs and energy-based models, with free lecture notes.

Book

Understanding Deep Learning

Simon J. D. Prince · 2023 · Intermediate · Free

A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.

Article

Lil'Log

Lilian Weng · Advanced · Free

Deep, carefully referenced survey posts on diffusion, agents, RL, hallucination, attention and more.

Book

Probabilistic Machine Learning

Kevin P. Murphy · Advanced · Free

A comprehensive two-volume reference viewing ML through probability. Free drafts online.

Paper

Generative Adversarial Networks

Goodfellow et al. · 2014 · Advanced · Free

The original GAN paper: a generator and a discriminator trained against each other.

Paper

Auto-Encoding Variational Bayes

Kingma & Welling · 2013 · Advanced · Free

Introduced the variational autoencoder and the reparameterisation trick.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/generative-models.md