Guide to AI and Data Courses · Lecture Notes

Chapter 13: Generative Models

We type "a red house on top of a snowy mountain" into a text box, and a few seconds later a picture that has never existed appears on the screen. It is not a copy of any photograph; the model has learned how millions of images are distributed and has drawn a new sample from that distribution. Generative Models is the course about this idea: how do we express a data distribution, how do we train it, and how do we sample from it? These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

Generative and discriminative
Separate "predict the label" problems from "generate the data" problems; explain likelihood and perplexity.
Autoregressive model
Build a bigram model from a small text and compute the likelihood and perplexity of a sequence by hand.
Latent variables and VAEs
Compute the KL divergence between Gaussians and draw a sample with the reparameterization trick.
Adversarial networks and diffusion
Find the optimal discriminator and compute a noised sample in the forward process of diffusion.
Place of the course
State what separates generative models from deep learning, probabilistic graphical models, natural language processing and computer graphics.

13.1What question does the course ask?

How does a model generate new samples that look like real data?

Generative models learn the probability distribution of data and generate new samples from it. A discriminative model asks "is this image a cat?", while a generative model asks "how are cat images distributed, and how do I draw a new one?"

A discriminative model learns the label given an input x, that is, the conditional distribution p(y | x). A generative model learns the distribution of the data itself, p(x). A model that knows the distribution can do two things: say how probable an example is (likelihood) and draw new examples from it. The second is the main interest of the course.

The difficulty is that data such as images or text is high-dimensional. A 64×64 color image has 12,288 numbers, and the joint distribution of these numbers cannot be written as a table. The four families of the course get around this in four different ways: splitting the distribution into conditional pieces (autoregressive models), generating from a low-dimensional hidden variable (VAEs), never computing the likelihood but pitting a generator against a discriminator (GANs), or learning to erase noise step by step (diffusion).

13.1.1Training and evaluating

Most generative models are trained to increase the likelihood of real data under the model. This is the same as reducing the KL divergence between the real distribution and the model distribution. Since the likelihood cannot be computed directly in every family, sample quality is measured separately: FID for images, perplexity for text, and human judgment for both. "It looks nice" is not enough; diversity and memorization are checked too.

13.1.2At a glance

CriterionGenerative Models
Approachlearning the data distribution
Inputhuge, mostly unlabeled data
Outputnew samples: images, text, audio
Success measurerealism and diversity (FID etc.)
Math loadhigh
Data needsvery large

13.2A short history

YearMilestone
2013Kingma and Welling propose the variational autoencoder (VAE).
2014Goodfellow and colleagues introduce generative adversarial networks (GANs), pitting a generator against a discriminator.
2015Sohl-Dickstein and colleagues publish the idea of diffusion models that undo noise step by step.
2018OpenAI's first GPT: an autoregressive transformer pretrained on a large text corpus.
2020Ho, Jain and Abbeel's DDPM brings diffusion models to the front of image generation.
2022Stable Diffusion is released with open weights; ChatGPT brings generative models to a wide audience.

13.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
LikelihoodThe probability the model assigns to real data; training increases it.
Latent spaceLow-dimensional hidden variables that summarize samples.
Autoencoder and VAEEncode, decode; a VAE forces the latent space into a regular distribution.
GANA generator makes fake samples, a discriminator tries to tell them from real ones.
DiffusionAdds noise to data; a network learns to remove it step by step.
Autoregressive modelPredicts each token from the previous ones: GPT.
Conditional generationGeneration guided by text, a class or a sketch.
EvaluationFID, perplexity and human evaluation.

13.4Likelihood and autoregressive models

The probability of a sequence splits into conditional pieces by the chain rule of probability: p(x1, …, xn) = p(x1) · p(x2 | x1) · … · p(xn | x1, …, xn−1). Autoregressive models teach each conditional factor to a neural network (or, in the simplest case, to a table of counts). The GPT family is the large-scale form of this idea: it predicts each token from the ones before it, and when generating, it appends the chosen token to the input and draws the next.

Definition 13.1 (Likelihood and perplexity)

For training data, the log-likelihood is the sum Σ ln p(xt | previous tokens); training increases it. Perplexity is the exponential of the negative average log-likelihood per token: exp(−(1/N) Σ ln p). It reads as the number of equally likely options the model is torn between at each step, on average.

Example 13.1: A bigram model from a three-sentence text

The training text is three sentences: "the cat slept", "the dog slept", "the cat ran". We put [S] at the start and [E] at the end of each sentence. In a bigram model each word depends only on the previous one: p(w | previous) = count(previous, w) / count(previous).

  1. Counts. [S]→the 3 times. the→cat 2, the→dog 1. cat→slept 1, cat→ran 1. dog→slept 1. slept→[E] 2, ran→[E] 1.
  2. Probabilities. p(the | [S]) = 1; p(cat | the) = 2/3; p(dog | the) = 1/3; p(slept | cat) = p(ran | cat) = 1/2; p(slept | dog) = 1; p([E] | slept) = p([E] | ran) = 1.
  3. Likelihood of a sentence. "the cat slept": 1 · 2/3 · 1/2 · 1 = 1/3. "the dog slept": 1 · 1/3 · 1 · 1 = 1/3. All three sentences get 1/3; their product is 1/27.
  4. Perplexity. The three sentences contain 12 predictions (per sentence: the, cat/dog, slept/ran, [E]). The average log-likelihood is 3 · ln(1/3) / 12 ≈ −0.275; perplexity is exp(0.275) = 31/4 ≈ 1.32.
  5. Sampling. We start from [S]; "the" comes. Then we choose at random between cat and dog with probabilities 2/3 and 1/3, and so on. We stop when [E] comes.

The model explains the training sentences with perplexity 1.32: at each step there is almost a single option. For an unseen sentence such as "the dog ran", however, p(ran | dog) = 0, so the likelihood is zero and the perplexity infinite.

This last observation shows the weak side of maximum likelihood estimation: a count table treats whatever it has not seen in training as impossible. In practice a small constant is added to the counts (smoothing), or the conditional probabilities are learned by a neural network; because the network shares information among similar contexts, it can give some probability to an unseen sentence. Large transformer-based language models are the far end of this road.

Common mistake

Reading perplexity like accuracy. Perplexity is comparable only under the same vocabulary and the same tokenization: the perplexity of a model that predicts single letters cannot be compared directly with that of a model that predicts words. A model that gives equal probability to 6 words at every step has perplexity exactly 6; that is the baseline of random guessing.

13.5Latent variables and the variational autoencoder

We can assume that images live in a small region of the 12,288-dimensional space: faces vary, but they can be described with a few hundred free features (pose, lighting, age, and so on). We denote these features by a latent variable z. Generation takes two steps: choose z ~ N(0, 1), then produce x with a decoder network. In training, an encoder proposes, for a given x, a distribution of plausible z values, of the form N(μ, σ2).

Definition 13.2 (The VAE loss)

For one example the loss has two terms: the reconstruction error (how badly the decoder rebuilds x) plus the KL term, the distance of the encoder's proposed distribution from the standard normal. For a one-dimensional Gaussian, KL(N(μ, σ2) ‖ N(0, 1)) = ½ (μ2 + σ2 − 1 − ln σ2). The negative of this sum is the ELBO (a lower bound on the log-likelihood).

The KL term keeps the latent space regular, so that at generation time every z drawn from N(0, 1) lands in a region the decoder knows. During training, drawing z would cut the gradient; the reparameterization trick fixes this: z = μ + σ · ε, ε ~ N(0, 1). The randomness moves into ε, and the gradient flows through μ and σ.

Example 13.2: The VAE loss for one example

A one-dimensional toy model (the values are illustrative): the true value is x = 3, the decoder is x̂ = 2z, the reconstruction error is (x − x̂)2. Let us compare two encoders; the drawn noise is ε = 0.8 for both.

  1. Encoder A: μ = 1, σ = 0.5. KL = ½ (1 + 0.25 − 1 − ln 0.25) = ½ (0.25 + 1.386) ≈ 0.818.
  2. z = 1 + 0.5 · 0.8 = 1.4; x̂ = 2.8; error (3 − 2.8)2 = 0.04. Loss ≈ 0.04 + 0.818 = 0.858.
  3. Encoder B: μ = 0, σ = 1 (exactly the standard normal). KL = ½ (0 + 1 − 1 − 0) = 0.
  4. z = 0 + 1 · 0.8 = 0.8; x̂ = 1.6; error (3 − 1.6)2 = 1.96. Loss = 1.96 + 0 = 1.96.

B is perfect as far as the KL is concerned, but because it proposes a fixed distribution without looking at the input, it cannot reconstruct the object. A adapts to the input and pays some KL in return. Training a VAE is finding the balance between these two terms. The loss falls from 1.96 to 0.86.

Common mistake

Using the encoder at generation time. The encoder exists only to propose z during training. When generating a new sample there is no input: z is drawn directly from N(0, 1) and given only to the decoder. The KL term is there precisely so that these drawn z values resemble the codes the decoder has seen.

13.6Adversarial networks and diffusion

There are two other routes when the likelihood is hard to compute. In a GAN, a generator G makes samples from noise and a discriminator D guesses whether a sample is real or fake; the two play a zero-sum game. In diffusion, noise is added to the data step by step and a network learns to predict that noise; generation is the reverse of this process.

13.6.1GAN: the optimal discriminator

For a fixed generator, the best behavior of the discriminator is known in closed form. If at some point the real data probability is p and the generator probability is q, the optimal discriminator says D*(x) = p / (p + q). If the generator manages q = p, then D* = ½ everywhere: the discriminator has to flip a coin.

Example 13.3: A data distribution with two points

Let the data live only at points A and B (the values are illustrative): the real distribution is p = (0.8, 0.2) and the generator is q = (0.4, 0.6).

  1. Optimal discriminator. D*(A) = 0.8 / 1.2 ≈ 0.667; D*(B) = 0.2 / 0.8 = 0.25. It calls A real and B fake.
  2. Value of the game V = Ep[ln D] + Eq[ln(1 − D)] = 0.8 ln(2/3) + 0.2 ln(1/4) + 0.4 ln(1/3) + 0.6 ln(3/4) ≈ −1.214.
  3. If the generator is perfect (q = p) D* = ½ and V = ln ½ + ln ½ = −ln 4 ≈ −1.386.

The difference, −1.214 − (−1.386) = 0.173, measures the distance between the two distributions (twice the Jensen-Shannon divergence: 2 · 0.0863). The generator tries to reduce V, that is, to drive this difference to zero against the best discriminator.

13.6.2Diffusion: adding noise and taking it back

In the forward process each step applies xt = √αt · xt−1 + √(1 − αt) · εt. Since a sum of Gaussians is Gaussian, all the steps can be written in one move: with ᾱt = α1 · … · αt, xt = √ᾱt · x0 + √(1 − ᾱt) · ε. For a given xt, the network predicts ε; the loss is (ε − ε̂)2.

Example 13.4: A three-step forward process

A one-dimensional data point x0 = 2; α = 0.9, 0.8, 0.7 (the values are illustrative).

  1. Cumulative product. ᾱ1 = 0.9; ᾱ2 = 0.9 · 0.8 = 0.72; ᾱ3 = 0.72 · 0.7 = 0.504.
  2. Coefficients (t = 3). Signal √0.504 ≈ 0.710, noise √0.496 ≈ 0.704. After three steps signal and noise carry almost equal weight.
  3. One sample. For ε = 1, x3 = 0.710 · 2 + 0.704 · 1 ≈ 2.12.
  4. Reversing. Let the network predict ε̂ = 0.8. x̂0 = (x3 − 0.704 · ε̂) / 0.710 ≈ (2.124 − 0.563) / 0.710 ≈ 2.20; the loss is (1 − 0.8)2 = 0.04. A perfect prediction (ε̂ = 1) would give x̂0 = 2.

Real diffusion models use hundreds of steps; ᾱt approaches zero and xT becomes pure noise. Generation starts from pure noise and removes the noise step by step using the network's predictions.

Common mistake

Thinking of the GAN discriminator as a useful classifier once training ends. As the generator improves, D* → ½; in the end the discriminator flips a coin. Its low accuracy is therefore not a bug but a sign that training is going well. The real problem is stability: the generator can get stuck producing only a few kinds of samples (mode collapse).

13.7How is the course taught?

13.7.1A typical workflow

Datasetimages, text,audioModel thedistributionVAE, GAN,diffusionTrainlikelihood,adversarialSamplefrom noiseto dataEvaluateFID, humanjudgment
Figure 13.1: A typical workflow in Generative Models

A diffusion model adds noise step by step to millions of images and trains a network to predict that noise. At generation time it starts from pure noise, removes it over dozens of steps guided by a text prompt, and arrives at an image never seen before.

13.7.2Topics over the semester

  1. Generative modeling; likelihood and KL divergence
  2. Autoregressive models: PixelCNN, transformers
  3. Variational autoencoders (VAE) and the ELBO
  4. Normalizing flows
  5. Generative adversarial networks and training stability
  6. Energy-based models
  7. Score matching and diffusion models
  8. Fast sampling and latent diffusion
  9. Conditional generation, classifier-free guidance
  10. Large language models: pretraining and fine-tuning
  11. Multimodal models: text to image
  12. Evaluation: FID, perplexity, human judgment

This is a typical semester; the order and coverage vary between universities.

13.7.3Skills you will gain

  • training VAEs and GANs in PyTorch
  • using diffusion models with Diffusers
  • fine-tuning language models with Transformers
  • measuring sample quality with FID
  • tracking and comparing training runs

13.7.4Try it yourself

The Try It: New Faces from Latent Space slide in the presentation lets you solve a typical problem of this course yourself: A game studio wants new characters from 60 cartoon faces. The model learned to compress each face into two numbers (z₁, z₂); generate a new face with the sliders or by clicking the plane on the left.

13.8Are you ready for this course?

13.8.1Prerequisites

CourseWhy it is needed
Deep LearningGANs, VAEs, diffusion, large language models
Information TheoryKL divergence, likelihood
Calculusworking comfortably with integrals, derivatives and probability densities
ProgrammingPython and a deep learning library (PyTorch)

13.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you build and train a neural network in PyTorch?Deep Learning
Can you explain probability densities, expectation and Bayes' rule?Probability and Statistics
Can you explain how backpropagation uses the chain rule to get gradients?Artificial Neural Networks
Can you compute an integral and the derivative of a logarithm?Integrals and derivatives from calculus

13.9Neighboring courses

Graphical ModelsDeep LearningComputer GraphicsNLPInformation TheoryGenerative Models
subfieldbuilds onshares methodsapplication
Figure 13.2: Neighbors of Generative Models and the kind of relation

13.9.1Where it overlaps

RelationCourseShared ground
subfieldThis course is a subfield of Deep LearningGANs, VAEs, diffusion, large language models
builds onThis course builds on Information TheoryKL divergence, likelihood
shares methodsShares methods with Natural Language Processing and Text Miningtext generation
shares methodsShares methods with Probabilistic Graphical Modelslatent variable models, variational inference
shares methodsShares methods with Computer Graphicsimage and scene synthesis

13.9.2Where it differs

  • Deep Learning: Deep learning is the general toolkit and mostly makes predictions; this course uses those tools to generate new samples from a data distribution.
  • Probabilistic Graphical Models: Graphical models build the structure between variables explicitly; the deep generative models here usually learn it implicitly.
  • Natural Language Processing and Text Mining: NLP also covers parsing and understanding language; this course looks at the shared principles of generating text, images and audio.
  • Computer Graphics: Computer graphics computes images from a physical description of a scene; generative models produce images by learning from data.

13.10In practice

13.10.1Applications

AreaWhat is done
Text-to-imagePictures and illustrations from a prompt.
Chat and writingText generation with large language models.
Audio synthesisNatural-sounding speech and music.
Data augmentationSynthetic samples for classes with little data.
Drug designProposing new candidate molecules.
Image editingInpainting missing regions, super-resolution.

13.10.2Risks and ethics

RiskExplanation
DeepfakesA person's face and voice are imitated without consent and used for fraud, blackmail and election disinformation.
Training data without consentWeb-scraped datasets such as LAION-5B contain works without their owners' permission; copyright lawsuits are ongoing.
Model collapseModels retrained on generated data lose the tails of the distribution over generations, and their outputs grow uniform.
The metric illusionMetrics such as FID do not always agree with human judgment; a model tuned to the metric can look worse to the eye.

These issues are discussed in depth in Explainable AI and AI Ethics.

13.10.3Tools and datasets

Tools: PyTorch, Hugging Face Diffusers, Hugging Face Transformers, JAX, Stable Diffusion, Weights & Biases.

Well-known datasets: MNIST, CelebA, CIFAR-10, LSUN, LAION-5B, FFHQ.

13.11Common misconceptions

Common mistake

A generative model copies its training data.

The goal is to learn the distribution; memorization can still happen and must be checked.

Common mistake

Generative AI is just chatbots.

Models that generate images, audio, video, molecules and code are also part of this course.

Common mistake

Realistic-looking output is correct output.

A model can produce plausible but wrong content; correctness is checked separately.

Common mistake

GANs are outdated; diffusion is always better.

Each family trades off speed, quality and diversity differently; a GAN generates in one step.

13.12Summary

  • A generative model learns the distribution of the data; likelihood says how probable an example is, and sampling produces new examples.
  • Autoregressive models split the distribution into conditional pieces with the chain rule; the evaluation measure is perplexity, which equals V for V equally likely options.
  • A VAE generates through a latent z; the loss is reconstruction error plus a KL term, z is drawn by reparameterization in training and from N(0, 1) in generation.
  • In a GAN the optimal discriminator is p / (p + q); if the generator matches the real distribution the discriminator stays at ½. Training stability and mode collapse are the main difficulties.
  • Diffusion adds noise in the forward process and the network learns to predict it; the closed form xt = √ᾱt x0 + √(1 − ᾱt) ε makes training easy.

13.13Test Yourself

  1. In the bigram model built from the three-sentence text above, what is the likelihood of "the cat ran" (including [S] and [E])? What happens for "the dog ran"?

    Answer

    p(the | [S]) · p(cat | the) · p(ran | cat) · p([E] | ran) = 1 · 2/3 · 1/2 · 1 = 1/3. For "the dog ran", p(ran | dog) = 0, so the product is zero: the model treats an unseen sentence as impossible; smoothing fixes this.

  2. A language model gives equal probability to 8 words at every step. What is its perplexity? Show the work with ln.

    Answer

    At every step ln p = ln(1/8) = −2.079; the average is the same. Perplexity is exp(2.079) = 8. The model is as uncertain as if it chose among 8 options at each step.

  3. An encoder proposes μ = 2, σ = 1. What is KL(N(μ, σ2) ‖ N(0, 1))? Do the same for μ = 0, σ2 = 4.

    Answer

    First: ½ (4 + 1 − 1 − ln 1) = ½ · 4 = 2. Second: ½ (0 + 4 − 1 − ln 4) = ½ (3 − 1.386) ≈ 0.807. A mean far from 0 and a variance far from 1 both increase the KL.

  4. In forward diffusion with two steps, α1 = α2 = 0.5, x0 = 4 and ε = −1. What is x2?

    Answer

    ᾱ2 = 0.25. The signal coefficient is √0.25 = 0.5 and the noise coefficient is √0.75 ≈ 0.866. x2 = 0.5 · 4 + 0.866 · (−1) ≈ 1.134.

  5. At some point the real data probability is 0.3 and the generator probability is 0.1. What does the optimal discriminator say there? What if the generator reaches 0.3?

    Answer

    D* = 0.3 / (0.3 + 0.1) = 0.75: the point is probably real. If the generator reaches 0.3, D* = 0.3 / 0.6 = 0.5: the discriminator can no longer tell them apart.

  6. We want to generate a new image from a trained VAE. Which steps are taken? Is the encoder used?

    Answer

    z is drawn directly from N(0, 1) and given to the decoder; the encoder is not used because there is no input image. This works because the KL term kept the z values drawn in training inside the region the decoder knows.

13.14After this course

After generative models you can take Natural Language Processing for text generation, Computer Graphics for image and scene synthesis, or Explainable AI and AI Ethics for safe and responsible use of models. Information Theory and Probabilistic Graphical Models deepen the theoretical basis.

Related careers: Generative AI engineer, Researcher, Machine learning engineer, Creative technologist.

13.15Further reading

  • D. Foster, Generative Deep Learning (2nd ed., 2023): builds VAEs, GANs, diffusion models and transformers from scratch in Keras code; shows the four families of these notes in practice.
  • J. M. Tomczak, Deep Generative Modeling (2022): presents autoregressive models, flows, VAEs and GANs in a probabilistic framework, with the mathematics.
  • I. Goodfellow, Y. Bengio and A. Courville, Deep Learning (2016): gives the theoretical background of generative models (likelihood, latent variables, sampling) at textbook level.

13.16References

  1. Foster, Generative Deep Learning, 2nd ed., O'Reilly, 2023.
  2. Tomczak, Deep Generative Modeling, Springer, 2022.
  3. Goodfellow et al., "Generative Adversarial Nets", Advances in Neural Information Processing Systems 27, 2014.
  4. Kingma and Welling, "Auto-Encoding Variational Bayes", ICLR, 2014.
  5. Ho, Jain and Abbeel, "Denoising Diffusion Probabilistic Models", Advances in Neural Information Processing Systems 33, 2020.

Related pages: Slides · Slides (PDF) · Course page