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
- Builds on
- 15 concepts →
- Quiz
- 4 questions ↓
The full path from zero — 15 concepts before this one
- What Is AI?
- Probability Basics
- Vectors
- Derivatives and Slopes
- How Machines Learn
- Probability Distributions
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- 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 . Here is one example (one image, one sentence) and says how likely that example is to show up. A realistic face photo has relatively high . A screen of random coloured static has a of essentially zero, because nothing like it ever appears among real photos. A generative model is a learned approximation of that you can sample from. Each time you ask, it hands you a fresh that would be at home in the data.
Compare this with the models you met earlier. A spam filter is a discriminative model. It learns , the probability of a label given an input . 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, , 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 (), 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 :
- Evaluate it: given an , say how likely it is. This is useful for anomaly detection and for training.
- Sample from it: produce new 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 . "Latent" means hidden: 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 ? The most common answer is maximum likelihood: adjust the parameters 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:
Here is the -th of training examples, is the model's distribution with parameters , and 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 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, , gets a log-density of , so the density is .
- A point in the empty space below, , gets , so the density is : effectively impossible.
- The average log-likelihood of the training data is . 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 and how do you sample?
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: . 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 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 ? |
|---|---|---|---|---|
| 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 , 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
- Autoencoders and then Variational Autoencoders: compressing data into a latent space and sampling from it.
- Generative Adversarial Networks: the adversarial game that made the first photorealistic faces.
- Diffusion Models: the noise-removal idea behind modern image generation, then Normalizing Flows and Flow Matching, Latent Diffusion and Stable Diffusion and Diffusion Transformers.
- Practice: Text-to-Image in Practice, Video Generation and Music and Voice Generation.
- The autoregressive family is covered in the language model part: Language Modeling and Next-Token Prediction and GPT and Decoder-Only Models.
- Synthetic Data uses generative models to make training data for other models.
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
- Run the code with
n_components=2and thenn_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?- Evaluate
gm.score_sampleson the point , which lies between the two moons. Is it closer to the on-moon or the off-moon value?- 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 freshmake_moonssample drawn with a differentrandom_state.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
CS236: Deep Generative Models (course notes)
Stanford's course on generative models: autoregressive models, VAEs, normalizing flows, GANs and energy-based models, with free lecture notes.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Lil'Log
Deep, carefully referenced survey posts on diffusion, agents, RL, hallucination, attention and more.
Probabilistic Machine Learning
A comprehensive two-volume reference viewing ML through probability. Free drafts online.
Generative Adversarial Networks
The original GAN paper: a generator and a discriminator trained against each other.
Auto-Encoding Variational Bayes
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