01 / 34 · Foundations
What generative modeling is
Learning to produce new data from examples of an unknown distribution, how a computer turns uniform random numbers into samples, and what six families of models compute: the likelihood exactly, a lower bound on it, or nothing.
On this page 7
A classifier answers a question about an object: is this image a cat? A generative model produces the object itself: a new image of a cat that was not in the training set. The two tasks differ in shape. A classifier has one right answer per input. A request for “a cat on a sofa” has endless right answers, some more plausible than others, and the model has to produce them with the right frequencies.
The problem: examples of an unknown distribution#
We treat a data set as independent draws from some distribution:
For images, is a vector of pixel values; for text, a sequence of tokens; for audio, a waveform. Nobody can write down the density of “photographs of cats”, so is unknown. All we have is the sample.
The goal is a model with parameters such that , and from which we can draw new samples . If the approximation is good, the new samples look like the data without copying it.
Generative modeling: from examples to a model and back to examples
Why not simply store the data and replay it? A model that puts probability on each training point is the best possible fit to the sample: on a finite set of outcomes the average log-likelihood of is minus the cross-entropy from the empirical distribution to , which Gibbs’ inequality maximizes at that distribution itself. Every one of its samples is a copy.
For continuous data it is worse. Put a Gaussian bump of width on each of the training points in dimensions, . At a training point the sum is at least its own term:
so the likelihood of the sample grows without bound as the bumps shrink, the unbounded-likelihood failure of mixtures. A useful model is restricted to a family that cannot memorize, and its quality is judged on data it has not seen (Kaiming He, MIT 6.S978, lecture 1; Stanford CS236 notes).
The classical guarantees of maximum likelihood, consistency and asymptotic efficiency, need conditions: the model family contains the true distribution and is identifiable, the log-likelihood is smooth, and the sample grows while the number of parameters stays fixed. The Probability course states them with the Fisher information. A network with more parameters than training images is far from that regime (BMML lecture notes, 2026, lecture 1).
Most applications want a conditional model : an image for a text prompt , speech for a sentence, a translation for a source sentence, a high-resolution image for a small one. The unconditional case is the same problem with an empty condition, and the course treats it first.
What a generative model is for#
Sampling new objects is the most visible use. A model that can also evaluate gives a density estimate: one possible anomaly score, since low density can flag unusual objects. The score depends on the representation, because a density changes under a change of variables, and a high density at a point does not mean that the point looks typical; the anomaly detection note works through these limits. A good density model is also a good compressor. A prefix code can give each discrete a codeword of bits, because these lengths satisfy the Kraft inequality, , which is exactly the condition for such a code to exist. Each then costs less than bits, and no prefix code has a shorter average length than the entropy (Cover and Thomas, 2006, chapter 5).
Models with a latent variable, such as the VAE, also learn a representation: they map each object to a low-dimensional code whose directions often carry meaning, without labels. Not every family offers all three uses, and the trade-offs between them shape the rest of the course (Stanford CS236 notes).
What “approximate” means: a divergence to minimize#
To train we need a number that says how far it is from . The standard choice is the Kullback–Leibler divergence (Entropy, cross-entropy and KL divergence):
The first term does not depend on . Minimizing the divergence therefore means maximizing the expected log-likelihood of the data under the model. With the sample in place of the expectation this is maximum likelihood:
The catch is that this needs as a number. For flexible models it is often impossible to compute, and the families in this course differ mainly in how they get around that: an exact formula, a lower bound, or a different objective altogether (Isachenko, lecture 1). The fitting note runs this objective on the simplest case, a Gaussian fitted by gradient descent.
How a computer samples at all#
A model is only generative if we can draw from it. Computers do not draw from arbitrary distributions directly. Everything starts from one primitive, uniform random numbers, and every later step transforms the samples of an easy distribution into samples of a harder one. The Probability course surveys these techniques; here we follow the chain to the point where neural networks take over.
Step 1: uniform numbers#
A processor is deterministic, so programs get their random numbers from a pseudo-random generator. It keeps an internal state , updates it by a fixed rule and returns a number computed from the state. The starting state is set from a seed. The simplest rule is the linear congruential generator (Knuth, 1997, §3.2.1). A toy version with 16 states is
From the seed it visits and returns to 7. Over one cycle each of the 16 values appears exactly once, which is what “uniform” means for a generator.
Where the "random" numbers come from
The toy has two defects. It repeats after 16 numbers. And consecutive pairs fall on a few lines: dividing the rule by 16 gives , where the integer is what the removes, and leaves only . So every pair lies on one of five parallel lines of slope 5. Real generators keep the state-and-rule design and remove both. NumPy’s default, PCG64, has a 128-bit state and scrambles it before output (O’Neill, 2014); on GPUs, PyTorch uses Philox, which computes the -th number directly from and the seed so that thousands of threads can draw at once (Salmon et al., 2011).
The seed is what makes an experiment repeatable, and the guarantee is narrow. The same seed reproduces the same numbers only with the same generator, the same calls in the same order and the same library build. NumPy keeps its raw streams stable across versions, but samplers built on them, such as normal, may change between releases (NumPy documentation).
Step 2: any one-dimensional distribution, by inverting the CDF#
Suppose we need an outcome , or with probabilities , and . Cut into pieces of exactly these lengths, , and , draw and return the outcome whose piece contains it. A uniform number falls into a piece with probability equal to its length. The cut points are the running totals of the probabilities, the cumulative distribution function , so sampling is a lookup: the first outcome whose running total exceeds .
Sampling a discrete distribution: cut the interval [0, 1)
For a continuous, strictly increasing CDF the same lookup asks which has accumulated exactly of the probability. With ,
This is inverse transform sampling (Devroye, 1986, §II.2). It works because exactly when , which has probability ; the functions of random variables note gives the proof and the version for CDFs with jumps. For the exponential distribution with rate , solving gives
With , the uniform numbers , , and become , , and . Half of all samples land in the short stretch below , and the last 1% spread over everything beyond : the long tail appears by itself.
For the standard normal, is , whose inverse has no formula in elementary functions. Libraries evaluate with rational approximations accurate to about 16 digits (Wichura, 1988). The figure shows why the recipe produces a bell.
From uniform to normal through the inverse CDF
Step 3: the standard normal, by Box–Muller#
Box and Muller found an exact shortcut that turns two independent uniforms into two independent standard normals (Box and Muller, 1958):
It is step 2 in polar coordinates. Take two independent standard normals, with joint density , and write them in polar coordinates . The map from to has Jacobian determinant , so by the densities under a transform section of the Mathematics course
The density is a function of alone times a function of alone, so is uniform on and independent of . The squared radius has the distribution function
an exponential with rate . Step 2 samples it as , and since is uniform too, works as well. The constructed then has the joint distribution of the polar coordinates of a normal pair, and so has the distribution of the pair itself.
For and the distance is , the angle is , and the point is .
Box–Muller step by step: two uniform numbers → a point of the normal cloud
A floating-point generator on can return exactly 0, where , so code feeds the logarithm instead. Libraries use faster variants of the same idea; NumPy’s normal sampler uses the ziggurat method.
Step 4: any Gaussian, by an affine map#
Steps 1–3 give standard normal noise , a round cloud centred at zero. A shift and a linear map turn it into any Gaussian: for any matrix with ,
The next note chooses and turns this map into a model with trainable parameters. The first four steps fit in a few lines:
import numpy as np
rng = np.random.default_rng(0) # the seed fixes the whole stream
u = rng.random((100_000, 3)) # step 1: U(0, 1), three columns
print(u[0].round(4)) # [0.637 0.2698 0.041 ]
x = -np.log1p(-u[:, 0]) # step 2: exponential, x = -ln(1 - u)
print(x.mean().round(3), np.median(x).round(3)) # theory: 1 and ln 2 = 0.693
r = np.sqrt(-2 * np.log1p(-u[:, 1])) # step 3: Box-Muller, 1 - u is never 0
phi = 2 * np.pi * u[:, 2]
z = np.stack([r * np.cos(phi), r * np.sin(phi)], axis=1)
print(z.std(axis=0).round(3), np.corrcoef(z.T)[0, 1].round(3))
mu, Sigma = np.array([1.0, 2.0]), np.array([[2.0, 0.8], [0.8, 1.0]])
L = np.linalg.cholesky(Sigma) # step 4: any A with A A^T = Sigma
xg = mu + z @ L.T
print(xg.mean(axis=0).round(2), np.cov(xg.T).round(2).ravel())
[0.637 0.2698 0.041 ]
1.005 0.694
[0.997 0.994] -0.001
[0.99 2. ] [1.99 0.79 0.79 0.99]
The exponential sample has mean and median against the exact and . The normal pair has unit spread and no correlation, and the affine map lands on the requested mean and covariance up to sampling noise.
Step 5: anything else, by a learned nonlinear map#
Gaussians are ellipsoids. Images, speech and text have distributions of far more complicated shape, and to reach them we push the noise through a nonlinear map:
The distribution of is the pushforward of the noise distribution through . In a generative model is a neural network, and training chooses so that the pushforward matches the data.
Sampling as a chain of transformations of noise
This is the central picture of the course: a generative model is simple noise plus a learned transformation. Some of the transformation is designed by hand, such as the order in which an autoregressive model generates pixels or the noising schedule of a diffusion model, and the rest is learned (Kaiming He, MIT 6.S978, lecture 1). For a one-pass generator, sampling is easy by construction. The hard part is choosing , which needs some way to compare the pushforward with the data.
When is invertible and smooth, the density of has a formula, the change of variables:
It is derived in Multiple integrals and is the starting point of normalizing flows. For a general network there is no such formula, and that is where the families diverge.
Why this is hard#
Inverting a CDF solves sampling in one dimension, and a Gaussian has a formula in any dimension. Real data has neither. A colour image has coordinates. Even a binary image has possible values, so a table of their probabilities needs numbers (Isachenko, lecture 1). A joint CDF exists, but sampling coordinate by coordinate would need every conditional CDF, which is exactly what we do not know.
Natural images also fill a tiny part of that space. An array of independent random pixels looks like noise, because neighbouring pixels of a photograph are strongly correlated and these are not. Measurements agree: nearest-neighbour estimates put the intrinsic dimension of ImageNet, whose colour images have coordinates, between 26 and 43 (Pope et al., 2021, Table 1). Real images lie close to a much lower-dimensional surface, and the model has to put nearly all its probability there.
Finally, a flexible function becomes a density only after division by , an integral over the whole space. For a neural network it has no closed form, and numerical integration does not rescue it. A grid with only 10 points per coordinate has nodes for a image (why grids fail), and uniform random points almost never land on the thin region where is large. Without the integral the likelihood cannot be evaluated.
The two basic rules of probability show where the difficulty sits (BMML lecture notes, 2026, lecture 1). The product rule factorizes any joint distribution into one-dimensional conditionals,
which is exact and is the whole idea of autoregressive models; the price is sequential steps per sample. The sum rule gives the density of a model with a latent code as an integral,
which has no closed form once the decoder is a nonlinear network. With a linear decoder and Gaussian noise it does: that model is probabilistic PCA, the starting point of the VAE note. The VAE, diffusion models and GANs are three ways of living with this integral.
Only the latent code is integrated out. In the VAE and in diffusion models the network weights are point estimates, one value found by optimizing an objective; the latent variables , or the noisy images of a diffusion chain, are what is integrated over or sampled.
Six ways around it#
Each family keeps the “noise plus transformation” picture and differs in what it gives up to make training possible. Two groups stand out: likelihood-based models, which compute exactly or bound it, and likelihood-free models such as GANs, which compare samples instead. The cost of a sample is a second axis. A VAE or a GAN needs one network pass; an autoregressive model needs one pass per element, and energy-based and diffusion models need many steps of a chain (Murphy, 2023, Table 20.1).
Six families: noise becomes data; what differs is what can be computed
| Family | How a sample is drawn | What can be computed | Notes |
|---|---|---|---|
| Variational autoencoder (VAE) | , then a learned decoder | a lower bound on , the ELBO | VAE, variants |
| Generative adversarial network (GAN) | , then in one pass | no density, only samples | GAN, WGAN and six branch notes |
| Normalizing flow | , then a chain of invertible maps | the exact | Flows, architectures |
| Energy-based model (EBM) | a noisy Markov chain started from noise, many steps | up to the unknown | MCMC samplers, EBMs |
| Diffusion model | start from noise , denoise step by step to | a lower bound on | Forward process, objective, score matching, continuous time, latent diffusion |
| Autoregressive model | one value or token at a time, each given the previous ones | the exact | PixelRNN and PixelCNN, transformers |
Not every model gives a likelihood, and a likelihood does not always reflect how good samples look. Mix a good model with a model of white noise and sample from : 99% of the samples are noise. Since and the logarithm is increasing,
The log-likelihood drops by at most nats per image, while the log-likelihoods of different models of images can differ by thousands of nats (Theis, van den Oord and Bethge, 2016, §3.2). The course therefore also measures models from their samples alone, before it needs those measurements to compare GANs.
The plan of the course#
The sections build on each other in this order; flows, energy-based models, diffusion and autoregressive models are parallel routes from the same foundations.
| Section | Notes | What it adds |
|---|---|---|
| Foundations | Gaussians, entropy and KL, fitting with KL, training background, autoencoders | the maximum-likelihood objective and the network blocks |
| Variational autoencoders | VAE, β-VAE and VQ-VAE | a latent code, trained through a lower bound |
| Evaluation | Inception Score, FID, LPIPS, precision and recall, human evaluation | judging samples when there is no likelihood |
| GANs | GAN, WGAN; branches on scaling, StyleGAN, α-GAN, CycleGAN, StarGAN and beyond | learning by comparing samples with a discriminator |
| Normalizing flows | change of variables, flow architectures | exact likelihood through invertible maps |
| Energy-based models | MCMC samplers, energy-based models | unnormalized densities and their samplers |
| Diffusion | DDPM, score matching, continuous-time diffusion and flow matching, latent diffusion, drag editing | learning to reverse a gradual noising process |
| Autoregressive models | PixelRNN and PixelCNN, transformers over image tokens | exact likelihood by the chain rule |
| Audio | text-to-speech and music | the same tools on sound |
What you should remember#
- Data is a sample from an unknown ; a generative model is a we can sample from, fitted so that .
- Minimizing is maximum likelihood, which needs as a number.
- A family that can memorize the sample wins the likelihood and generalizes nothing; judge on held-out data.
- Sampling ladder: uniform numbers, inverse CDF, Box–Muller, an affine map, a learned nonlinear map.
- The families differ in what they can compute: a bound (VAE, diffusion), nothing (GAN), the likelihood up to a constant (EBM) or exactly (flows, autoregressive).
Next#
The first rung of the ladder that later models stand on is the Gaussian: how a matrix square root turns standard noise into any Gaussian, and how to make its parameters trainable. That is Multivariate Gaussian distributions.
References#
- BMML team. Байесовские методы в анализе данных (Bayesian methods in data analysis), lecture notes, 2026. GitHub repository. Lecture 1: the product and sum rules, Bayes’ theorem, maximum likelihood and its asymptotic guarantees.
- S. Ermon, A. Grover et al. Stanford CS236 course notes: “Introduction” (learning and the three inference queries) and “Autoregressive models” (learning by maximum likelihood, validation log-likelihood).
- R. Isachenko. Deep Generative Models, MIPT/YSDA, 2025. Lecture 1: problem statement, the histogram model, divergence minimization and maximum likelihood.
- K. He. MIT 6.S978 Deep Generative Models, Fall 2024. Lecture 1: generative versus discriminative models, overfitting a distribution, simple-to-complex mappings.
- K. P. Murphy. Probabilistic Machine Learning: Advanced Topics. MIT Press, 2023. Chapter 20: the families compared by density, sampling, training and latents (Table 20.1).
- L. Theis, A. van den Oord, M. Bethge. A note on the evaluation of generative models. ICLR, 2016. §3.2: a mixture with 99% noise loses at most nats of log-likelihood.
- P. Pope, C. Zhu, A. Abdelkader, M. Goldblum, T. Goldstein. The intrinsic dimension of images and its impact on learning. ICLR, 2021. §5, Table 1: intrinsic-dimension estimates of image datasets.
- T. M. Cover, J. A. Thomas. Elements of Information Theory, 2nd ed. Wiley, 2006. Chapter 5: the Kraft inequality and the entropy bound on the length of prefix codes.
- L. Devroye. Non-Uniform Random Variate Generation. Springer, 1986. §II.2: the inversion method.
- G. E. P. Box, M. E. Muller. A note on the generation of random normal deviates. Annals of Mathematical Statistics, 29(2), 1958.
- D. E. Knuth. The Art of Computer Programming, vol. 2: Seminumerical Algorithms, 3rd ed. Addison-Wesley, 1997. §3.2.1: linear congruential generators.
- M. J. Wichura. Algorithm AS 241: the percentage points of the normal distribution. Applied Statistics, 37(3), 1988.
- M. E. O’Neill. PCG: a family of simple fast space-efficient statistically good algorithms for random number generation. Technical report HMC-CS-2014-0905, Harvey Mudd College, 2014.
- J. K. Salmon, M. A. Moraes, R. O. Dror, D. E. Shaw. Parallel random numbers: as easy as 1, 2, 3. SC ‘11, 2011. The Philox generator.
- NumPy developers. Random sampling: compatibility policy. NumPy documentation. What a seed does and does not reproduce.