AAI, Built

Act IV · Generation and Perception

Part 20 of 31

Four Ways to Generate

Master'sstarts at this level55 min of film18 chaptersprerequisites: Part 1, Part 5, Part 7, Part 9

How can a machine learn a distribution well enough to draw new samples from it?

The part opens with digits nobody wrote, sampled from four of its own models, and sets the test bench: three densities in the plane (two moons, a ring of eight Gaussians, a checkerboard) and MNIST at 14 x 14 pixels with 16 grey levels. Maximum likelihood is minimum KL, and each family is one way to make it tractable. A PixelCNN factors the image by the chain rule, with an exact likelihood and 196 sequential passes per sample. A VAE bounds the likelihood by the ELBO, and the part makes posterior collapse happen with an autoregressive decoder. A GAN replaces likelihood by a game: the optimal discriminator turns the value into a Jensen-Shannon divergence, the ring collapses to a few modes, and simultaneous gradient steps on min max xy spiral out by exactly sqrt(1 + eta^2) per step. Wasserstein critics, coupling flows with a triangular Jacobian, neural ODEs with a trace, and the energy models of Hopfield and Boltzmann up to Langevin sampling with the score follow. The part turns to judging: FID is derived as a Fréchet distance and shown to miss what precision and recall catch. It ends with five models on one budget of 6 x 10^12 training FLOPs, and with the families meeting again inside tokenizers and fast samplers.

What you need. Multivariable calculus (Jacobians, determinants) and probability densities; entropy and KL from Part 1 and Markov chain Monte Carlo from Part 5.

Mathematics and history
autoregressive models, VAEs, GANs and WGAN, normalizing flows, neural ODEs, energy models, FID
Models, data
Hopfield, Boltzmann, StyleGAN

What you will be able to do

Undergraduate

  • Explain what it means to sample from, evaluate and encode with a generative model, and name what each of the five families gives up.
  • Write an image's probability by the chain rule and say why sampling it takes one pass per pixel.

Master's

  • Derive the ELBO and its gap, the optimal discriminator and the Jensen-Shannon form of the GAN value.
  • Compute a coupling layer's log-determinant and its inverse, and derive the instantaneous change of variables for a continuous flow.
  • Derive the RBM's conditionals and free energy, and write a Langevin step from a score.

Research

  • State Kantorovich-Rubinstein duality, derive the WGAN objective from it, and explain why Jensen-Shannon is flat at log 2 for disjoint supports.
  • Analyse simultaneous, alternating, extragradient and optimistic steps on a bilinear game through the eigenvalues of their update matrices.

Engineering

  • Report a generator with FID, precision and recall together, stating the feature network, the sample size and the reference set.
  • Diagnose mode collapse and posterior collapse from training curves, and choose a remedy (gradient penalty, free bits) knowing its cost per step.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 17 min · Master's 45 min · Research 55 min · Engineering 27 min.

  1. 0Digits nobody wroteUndergraduate2 min
  2. 1The generative problemUndergraduate3 min
  3. 2One pixel at a timeUndergraduate4 min
  4. 3From Helmholtz machines to the VAEMaster's3 min
  5. 4Training a VAE: rate, distortion, collapseMaster's4 min
  6. 5The adversarial gameUndergraduate3 min
  7. 6Why GANs spiralMaster's2 min
  8. 7Wasserstein GANsResearch3 min
  9. 8GANs at scale: BigGAN, StyleGAN, inversionEngineering2 min
  10. 9Normalizing flowsMaster's3 min
  11. 10Neural ODEs and continuous flowsResearch3 min
  12. 11Hopfield and BoltzmannUndergraduate3 min
  13. 12Contrastive divergenceMaster's3 min
  14. 13Langevin dynamics and the scoreMaster's3 min
  15. 14Judging a generatorEngineering4 min
  16. 15Five models, one budgetEngineering4 min
  17. 16Where the families meetResearch5 min
  18. Recap, problems, and what comes nextAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Digits nobody wroteUndergraduate2 min

None of these sixty-four digits was written by a person. Each block was drawn by a different model, trained in a new cloud run with two CPUs allocated and one numerical thread. Their mean recorded training time was about 4 minutes, on the same sixty thousand handwritten digits. The first writes a digit one pixel at a time. The second squeezes every digit into sixteen numbers and learns to expand them again. The third learned by playing a game against a critic. And the fourth bends random noise, smoothly and invertibly, into ink.

Real handwriting looks like this: samples from some distribution p of x that nobody can write down. The question of this part: from examples alone, how do you learn a distribution you can draw new examples from? The field found four answers that work, and one older one that it keeps coming back to. Build the example one piece at a time. Compress it into a code and learn to expand the code. Set two networks against each other. Bend simple noise with an invertible map. Or carve an energy landscape that the data sits at the bottom of. Diffusion, next time, is built from these pieces.

This is Part 20 of AI, Built, and the start of its fourth act: generation and perception. In this part: the generative problem and its history; autoregressive models; latent variables, from the Helmholtz machine to the variational autoencoder; adversarial games, why they spiral, and how Wasserstein distance and StyleGAN tamed them; invertible maps, from coupling layers to neural ODEs; energy, from Hopfield and Boltzmann to Langevin dynamics and the score; and how to judge a generator, with five digit-model baselines trained in the cloud and compared on one declared, registry-counted model budget.

1The generative problemUndergraduate3 min

Here is the problem at its smallest: twenty thousand points in the plane, drawn from a distribution p in the shape of two moons. Because we made it, we can compute the target density, numerically along the arcs for these moons; real images or text generally do not give us that access. A generative model is a distribution q, learned from the samples, that we can sample from; ideally one we can also evaluate, and one that gives each x a code, a short description of what it is.

The workhorse for fitting q is maximum likelihood, from Part 1: minimize the average surprise, minus log q. Split that average in two. The data's own entropy, which no model can beat, plus the KL divergence from p to q, the price of being wrong. So maximum likelihood is minimum KL. For our three test densities, we estimate the entropy reference from two hundred thousand draws per density; the moons density is evaluated numerically along its arcs: 1.76 nats for the moons, 0.31 for the ring of eight Gaussians, 2.08 for the checkerboard.

How we got here. In 1948 Claude Shannon generated English letter by letter: the first autoregressive model. In the 1980s memories became the valleys of an energy, in Hopfield's network and the Boltzmann machine; in 1995 the Helmholtz machine added a second network to guess hidden causes. Stacked Boltzmann machines restarted deep learning in 2006. Then, within three years, variational autoencoders, adversarial networks, invertible flows and PixelCNN. GANs made the sharpest images until 2021, when diffusion overtook them. Today's systems combine all of these ideas.

What each family offers. An autoregressive model: the exact likelihood and stable training, but samples one piece at a time. A VAE: one-pass sampling and a code, but only a bound on the likelihood. A GAN: one pass, no likelihood at all, and famously hard to train. A flow: everything on paper, paid for in architecture. An energy model: a density known only up to a constant, and slow sampling. Xiao, Kreis and Vahdat called it a trilemma: sharp samples, coverage of the data, fast sampling. Most families managed two.

Our test bench: three densities in the plane, small enough to see everything a model does, each hard in its own way. And images: the MNIST digits, sixty thousand to train on, ten thousand to test, averaged down to fourteen by fourteen pixels of sixteen grey levels. Every image model gets the same budget of arithmetic, counted operation by operation, and several random starts.

2One pixel at a timeUndergraduate4 min

The first answer needs no new mathematics. Any distribution factors by the chain rule: the first variable, times the second given the first, times the third given the first two, and so on. Each factor is one prediction: the next variable, given everything before it. Learn every factor and you have the distribution exactly; sample them in order and you have a sample. Shannon's English, every language model in this series, and now a digit.

In the plane, the first factor, p of x one, is a curve along the bottom. The second, p of x two given x one, is a different curve for every slice: a mixture of ten Gaussians set by a small network fed x one. Multiply the two: the density the model learns, replayed through training, beside its held-out surprise.

An image is the same story with more variables: the 196 pixels of a digit in reading order. To predict this pixel the model may look at every pixel before it, and nothing after; it outputs sixteen probabilities, one per grey level, like a language model's next token. The trick that makes training fast is a mask: every filter has its future half set to zero, so one pass predicts all 196 pixels at once, each from its own past. From NADE and MADE came PixelRNN and PixelCNN, by Aaron van den Oord and colleagues at DeepMind in 2016, and WaveNet for speech.

There's a catch. At random initialization, we differentiate the sum of absolute logits for one pixel, accumulate absolute input gradients over eight random inputs, and apply a relative threshold. Pink marks an undetected earlier pixel when its mirror is detected. With masked filters stacked naively, the probe marks an asymmetric wedge above and to the right. The second PixelCNN paper splits the network in two: a vertical stack for rows above, feeding a horizontal stack for the row so far. This design addresses the naive stack's characteristic wedge. The finite thresholded probe can still leave earlier pixels undetected; it does not prove a missing structural connection. We train the two-stack layout.

Here is ours learning: on the left, its held-out surprise in bits per pixel; on the right, what it draws at each checkpoint. Untrained, it pays 3.99 bits per pixel, about uniform guessing, and draws static. Then it learns that most pixels are black, that ink comes in strokes, and their shapes. It ends at 0.86 bits per pixel; three seeds end between 0.86 and 0.86.

And here is one digit being drawn, with the model's sixteen probabilities for the next pixel. In the margin it is sure: black. At a stroke's edge it hesitates, and the coin it tosses shapes the digit. The price is the order: 196 sequential network passes per digit; the GAN uses one. In the recorded batched timing, the PixelCNN averaged 78.0 milliseconds per digit, about 14,697 times the GAN's batched time per digit. Each timing covered two thousand digits: four batches of five hundred for the PixelCNN, one batch of two thousand for the GAN. This is amortized throughput per digit, not isolated single-digit latency. The measured time ratio also depends on architecture, batching and the work included in each timing; it does not follow from the pass count alone.

3From Helmholtz machines to the VAEMaster's3 min

The second answer adds something hidden: every digit comes from a code z, a few numbers drawn from a plain Gaussian. A decoder turns each code into a distribution over images. Here is a real one, with a code of two numbers: every point of the plane decodes to a digit, and the digits flow into one another. An image's probability is then an average over all the codes that could have made it, an integral we can't compute. And going back, from image to code, needs Bayes' rule, with the same integral below.

In 1995 Peter Dayan, Geoffrey Hinton, Radford Neal and Richard Zemel proposed learning Bayes' rule: a second network, a recognition model q, that guesses an image's hidden causes. The Helmholtz machine, after Hermann von Helmholtz, who called perception unconscious inference. Awake, it guesses the causes of real images with q, and trains the generator to reproduce them. Asleep, it dreams causes and images, and trains q to recover the causes. It worked, awkwardly: q learned from dreams, and the two phases had no shared objective. Eighteen years later the fix was a single bound.

Here is the bound. Start from the log-probability of an image. Multiply and divide by q of z given x, so the integral becomes an average over codes drawn from q. The log of an average is at least the average of the log: Jensen. Two terms remain: a reconstruction, decoding a code drawn from q; and the KL divergence from q to the prior, the nats the code carries about x, its rate. Together, the evidence lower bound, the ELBO. The gap is the KL divergence from q to the true posterior, so raising the bound improves the model and the guesser at once: one objective, where the Helmholtz machine had two.

One problem remains: you can't take the gradient of a coin toss. So move the randomness: the encoder outputs a mean and a spread, and the code is the mean plus the spread times fresh noise. The noise is now just an input, and gradients flow back into the encoder: the reparameterization trick. For Gaussians, the KL term has a closed form. Diederik Kingma and Max Welling published this in December 2013, and Danilo Rezende, Shakir Mohamed and Daan Wierstra, independently, weeks later: the variational autoencoder.

Ours has a sixteen-number code, and a decoder that gives every pixel a bell-shaped distribution cut into the sixteen grey levels: 852,392 parameters. So its bound is in the PixelCNN's units, bits per pixel.

4Training a VAE: rate, distortion, collapseMaster's4 min

Here is our VAE learning: the negative ELBO's two costs, in nats per held-out digit. The replay curves use the first two thousand held-out digits. At first reconstruction costs 303 nats and the rate is 0.0. Then the rate climbs and the reconstructions sharpen: better reconstruction at a higher coding cost. By the end the rate costs 12.8 nats and the decoder needs 133; the final ELBO-based estimated upper bound on negative log-likelihood is 1.08 bits per pixel on all ten thousand held-out digits. An importance-weighted estimate of a theoretically tighter bound, with 64 codes per digit, is 1.05 on the first one thousand held-out digits. These reported figures are not a matched-cohort comparison. These are decoded locations, not conditional pixel draws. Of the sixteen latent means, 6 exceed our activity threshold: variance above zero point zero one across the held-out digits. That is an operational measure of activity, not a count of all information-carrying coordinates.

What does the code learn? With two numbers per digit we can watch: each dot is a held-out digit at its code, coloured by its label. The encoder spreads them out, and digits of a kind gather, though nobody told it the labels, while the KL term keeps the cloud near the origin. Decode an even grid of codes, and the decoder locations give a map of digits, with smooth blends between regions. These grid pictures do not draw the conditional pixel noise.

The two terms pull against each other; weight the KL by beta, and you have Irina Higgins's beta-VAE. We trained six betas, from to , two seeds each: each dot is a run, its rate against its distortion. At beta the coding rate is nats with active numbers; at , nats with . These pictures are decoder locations. Active here means that a posterior mean's variance across held-out digits exceeds zero point zero one. A large beta gives smooth, generic location images: the code pins down fewer details.

Switched-off code numbers have a name, posterior collapse, and we can make it happen. A VAE on the moons, with a decoder that predicts x one and x two separately from the code: to get the moons' shape it must use the code, and its rate settles at nats per point. Now give the decoder chapter two's power: x two from the code and x one.

The code costs rate, and a decoder that can model the data alone gets nothing for it. Samuel Bowman and colleagues hit this in 2016, with a VAE for sentences. All models here have sixteen latent dimensions. The main VAE is a full-budget reference; each PixelVAE gets half that nominal budget. Their architectures and exposure differ, so this is not a decoder-only controlled comparison. The plain and free-bits PixelVAEs share architecture, seed and nominal budget. Their classifier-agreement comparison is descriptive for this paired seed, not an established general benefit.

One more thing: on the ring, the VAE spreads samples into the gaps; only 27 percent land within three standard deviations of a mode. A smooth code blurs whatever is sharp: the VAE's famous softness. The fixes became whole lines of work: deeper codes, discrete codes, and the autoencoder in front of every latent diffusion model.

5The adversarial gameUndergraduate3 min

The third answer throws the likelihood away. In 2014 Ian Goodfellow and colleagues in Yoshua Bengio's lab set two networks against each other. A generator turns noise into a sample, never seeing the data. A discriminator outputs the probability that a sample is real. One learns to tell them apart, the other to fool it: counterfeiters against the police, in the paper's words. As one value: the discriminator maximizes its log-probability of being right, the generator minimizes it.

What does a winning discriminator learn? Write the value as an integral, with q for the generator's distribution. At each x it picks one number, D of x, to maximize a log D plus b log one minus D: set the derivative to zero. The best discriminator is p over p plus q, the data's share of the probability at x. Real where the data dominates, fake where the generator does, one half where they agree.

Put the best discriminator back. Halve p plus q inside each log, and two KL divergences appear, to the average m, minus log four. Together: the Jensen-Shannon divergence, symmetric, at most log two, zero exactly when q equals p. Against a perfect critic, the generator minimizes a divergence without ever writing down a density: the 2014 paper's theorem. Whether training finds that minimum is the rest of this chapter and the next.

The first practical problem appears on day one: the fakes are bad, and D of G of z sits near zero. Through D's sigmoid, the minimax generator gradient can nearly vanish. Goodfellow's fix, in the same paper: maximize the probability of fooling, minus log D, whose logit gradient stays strong there. The fix has a cost, found by Martin Arjovsky and Léon Bottou in 2017. For smooth positive densities, with the optimal discriminator at the current parameters held fixed during the generator update, its gradient is that of reverse KL minus twice Jensen-Shannon, evaluated at those parameters. Reverse KL barely penalizes missing a mode.

Here is that cost on the ring: the discriminator's verdict as the background, bright for real, and the generator's samples from three hundred fixed noise vectors. This is mode collapse: a generator that makes only a few kinds of thing.

6Why GANs spiralMaster's2 min

The smallest game: one player picks x and wants x times y small, the other picks y and wants it large. Each follows its own gradient: x moves by minus y, y by plus x. Draw those velocities: no downhill anywhere, only turning. The Jacobian's eigenvalues are plus and minus i, pure rotation. Gradient descent was built for valleys; a game can be a whirlpool.

Take real steps, both players at once, step size eta: each step multiplies by this matrix. Its eigenvalues have size root one plus eta squared, more than one. So simultaneous steps spiral out: after 60 steps the radius has grown 3.2 times. Taking turns closes the spiral into an orbit; its radius ends at 0.96. To converge, look ahead: extragradient steps with the gradient at a trial point, optimistic descent extrapolates the last one. Both spiral in, to 0.31 and 0.29.

Real GANs do this. Lars Mescheder, Andreas Geiger and Sebastian Nowozin boiled one down to two numbers: data at zero, the generator at theta, a discriminator with slope psi. Around the equilibrium, the same rotation. Simultaneous steps spiral out; alternating steps circle. Their fix penalizes the discriminator's gradient on real data, here gamma over two psi squared: friction, and the path settles at equilibrium. StyleGAN trains with this penalty, R1.

Back to the ring: each row a mode, each column a checkpoint, brightness the generator's samples there. The bands wander from mode to mode: the toy game's rotation, in a space of distributions. The field fought it with penalties, look-ahead steps, separate learning rates, and spectral normalization.

7Wasserstein GANsResearch3 min

Martin Arjovsky, Soumith Chintala and Léon Bottou asked what Jensen-Shannon does when distributions don't overlap, the normal case for images. Their example: the data a segment at x equals zero, the model the same segment at theta. For any theta but zero, JS is log two: flat, no gradient, no sign that theta is getting closer. Discriminators trained at seventeen values of theta stay within 0.00 of log two. A distance that measures how far the mass must move gives a V whose slope points home; a trained critic puts it at 0.52 for theta 0.50.

That is the earth mover's distance: p a pile of sand, q a hole of the same volume. A transport plan says how much sand goes where; its cost is mass times distance. Wasserstein-1 is the cheapest plan's cost. Gaspard Monge posed the problem in 1781; Leonid Kantorovich gave its modern form in 1942.

Cheapest plans between image distributions are hopeless to compute, but by Kantorovich and Rubinstein's duality the distance is also the largest gap in expectation that a function of slope at most one can open between p and q. So a critic f, with any real output, learns to open the gap, and the generator to close it. The hard part is the slope limit; the first Wasserstein GAN clipped every weight. Ishaan Gulrajani and colleagues saw that for optimally transport-coupled points the optimal critic has unit slope along their segment. WGAN-GP uses this to motivate a soft penalty on random real-fake interpolations; it is not a theorem requiring unit slope for every random pair.

Back to the ring, same networks, same generator steps. The background is now the critic, a landscape high where the data is. The samples climb it toward the modes.

The cure has a price: five critic updates per generator step, each penalty needing a second backward pass. Counted on our digit models, a WGAN-GP step costs 5.4 GAN steps, so on one budget the GAN takes 16,380 generator steps and WGAN-GP 3,011. Chapter fifteen shows what that buys.

8GANs at scale: BigGAN, StyleGAN, inversionEngineering2 min

First, ours: two-layer networks on the digits, and what the generator draws from sixteen fixed noise vectors. Blobs, then strokes, then digits. The two losses don't fall like a learning curve; they balance. Nothing here says when the generator is good, one reason GANs needed chapter fourteen's measuring sticks.

From there to photographs took four years. In 2015 Alec Radford, Luke Metz and Soumith Chintala found convolutional GANs that trained reliably, whose noise vectors did arithmetic: a smiling woman, minus a woman, plus a man, gave a smiling man. In 2017 Tero Karras and colleagues at NVIDIA grew the networks during training, up to 1024 pixels. In 2018 Andrew Brock, Jeff Donahue and Karen Simonyan scaled a GAN to ImageNet: an Inception score of 166.5 and an FID of 7.4 at 128 pixels, against a previous best of 52.5 and 18.6. And Karras's group rebuilt the generator itself: StyleGAN.

StyleGAN's generator starts not from the noise but from a learned four-by-four constant, upsampled block by block. The noise goes through an eight-layer mapping network to a code w, and w sets each block's style, a scale and shift per channel; fresh noise adds details like freckles. Styles can be mixed, coarse layers from one face, fine ones from another, and straight lines in w's space became meaningful edits.

BigGAN's truncation trick: at sampling time, resample any noise coordinate larger than t, keeping the generator near the middle of what it learned. On our GAN, with chapter fourteen's precision and recall:

A GAN has no encoder: to edit a real photograph, first find the noise that would produce it, by gradient descent on the difference between G of z and the image. That's GAN inversion. Eight unseen test digits, four random starts each, the best kept, steps. A line between two found codes morphs one digit into the other; in StyleGAN's w space this became photo editing, from iGAN in 2016 to DragGAN in 2023.

9Normalizing flowsMaster's3 min

The fourth answer keeps the likelihood exact and sampling one pass: push simple noise z through an invertible function g. Where g stretches, probability thins; where it squeezes, it piles up. Probability is conserved, interval by interval. So the density of x is that of its z, times how much the inverse map shrinks a small interval; in many dimensions, the inverse map's Jacobian determinant. The likelihood is exact. Esteban Tabak and Eric Vanden-Eijnden described such flows in 2010; Danilo Rezende and Shakir Mohamed brought them to deep learning in 2015.

The catch is the determinant, d cubed operations for a d by d Jacobian. Laurent Dinh, with Yoshua Bengio, found a way around it. Split the variables in two; copy the first half; scale and shift the second by amounts s and t that any network computes from the first. The Jacobian is triangular, so the log-determinant is just the sum of the s's. The inverse is as cheap: subtract t, divide by e to the s. Ours agrees with autograd's full determinant to within ten to the minus 4 nats. Stack such layers, alternating halves, and the flow can bend anything.

Here is that bending, our eight coupling layers on the moons: a square grid of the noise plane, and noise samples. Each layer slides points along one axis, by amounts set by the other. The grid shears and folds, but never tears or crosses itself. After the eighth, noise has become the moons, and the map read backwards gives each point its exact probability. On the checkerboard, the same layers cut the plane into squares.

Training, replayed on the checkerboard. Mass drains from the empty squares into the filled ones. Against each floor, the flow ends nats above it on the moons, on the ring, on the checkerboard.

On digits, here is what our flow draws: noisy strokes; turning the noise down, Glow's trick, makes them cleaner and more alike. After Glow drew faces in 2018, flows trailed for years, until in 2024 Shuangfei Zhai and colleagues at Apple built one from transformer blocks and reported samples comparable to diffusion models.

10Neural ODEs and continuous flowsResearch3 min

A residual network updates its state a little each layer: h plus f of h. That's one Euler step of an ordinary differential equation. Shrink the step to zero, and the state flows along a velocity field a network defines. Ricky Chen, Yulia Rubanova, Jesse Bettencourt and David Duvenaud called these neural ODEs, a best paper at NeurIPS 2018. Run the solver backwards to invert: a flow without coupling layers.

How does density change along the flow? Over one small step, by the last chapter's change of variables. To first order, the determinant of the identity plus a small matrix is one plus its trace. In the limit, the log-density falls at the rate of the field's divergence, the trace of its Jacobian. Integrating along the path gives the exact continuous-time change-of-variables identity, without coupling-layer constraints. The likelihood values we compute use numerical integration; an exact divergence does not remove solver error. But even a trace costs one backward pass per dimension.

The way out is Hutchinson's trick of 1989: draw a random vector epsilon with mean zero and variance one, and compute epsilon transpose A epsilon. On average, only the diagonal survives: the trace, from one probe and one backward pass. Random signs give less variance than Gaussians, since the diagonal terms never vary; measured at four hundred points of a trained flow, the formulas hold to 2 percent, and the signs' variance is 0.47 times the Gaussians'. FFJORD, in 2019, built on it: in 196 dimensions one probe is 67 times faster than the exact trace, here.

A continuous flow on the moons, three seeds each way: trained with the exact trace, or one random-sign probe per path. Both held-out NLL curves use eight RK4 steps and exact divergence, so they remain numerical likelihood estimates. The mean recorded instrumented run time was seconds with the exact trace and with the probe.

And the flow itself: seven hundred noise points carried by the learned field from time zero to one, over five density snapshots. Paths use forty RK4 steps. The initial density is analytic; later snapshots use two, four, six and eight RK4 steps, with image cross-fades connecting snapshot times. The cloud stretches, splits and curls into two moons. Training still solves the ODE at every step; Part 21's flow matching learns such fields by regression instead.

11Hopfield and BoltzmannUndergraduate3 min

The fifth answer is the oldest. In 1982 the physicist John Hopfield gave a network of plus-or-minus-one neurons, with symmetric connections, an energy. One neuron at a time takes the sign of its input. A flip changes the energy by minus the flip times the input, and the two agree in sign, so the energy only falls: the network settles into a valley. Hebb's rule, from Part 9, makes chosen patterns the valleys: a memory, stored as the bottom of a landscape.

Here is one: 196 neurons, one per pixel, one digit stored. Start from that digit with a quarter of its pixels flipped. Neuron by neuron the state slides downhill, the energy falling with every change. It settles on the stored digit exactly. A damaged copy is enough to find the memory.

How much can it hold? Store random patterns, recall each from a damaged copy. With neurons, fewer than half come back once there are patterns per neuron; Amit, Gutfreund and Sompolinsky's spin-glass theory puts the limit at about 0.138. Digits look alike, overlapping by on average, which is worse.

The fix came over thirty years later: Dmitry Krotov and Hopfield sharpened the energy, and Hubert Ramsauer and colleagues wrote the update as compare, softmax, average. With it, our network . Our binary test normalizes the overlaps by the number of neurons and takes the sign after averaging. The continuous compare-softmax-average step is attention, from Part 13: the state the query, the memories the keys and values. An attention layer is a Hopfield network taking one step.

In 1985 David Ackley, Geoffrey Hinton and Terrence Sejnowski made the neurons random, so the network samples the Boltzmann distribution of physics: e to the minus energy over temperature, over a normalizer Z. They added hidden units: the machine's own features. The learning rule: measure how often pairs of units are on together with the data clamped, again running free, and strengthen each connection by the difference, until the machine's dreams match the world. The catch: each measurement needs equilibrium, which can take forever. In 2024 Hopfield and Hinton shared the Nobel Prize in Physics, for foundational discoveries and inventions that enable machine learning with artificial neural networks.

12Contrastive divergenceMaster's3 min

The way out was to restrict the machine: two layers, visible and hidden, connected across but not within; Paul Smolensky's harmonium of 1986, today's restricted Boltzmann machine. One weight matrix couples the layers. Given one layer, the other's units are independent, each a sigmoid of its input. Ours: 196 visible units, our digits in black and white, and sixteen hidden units, for a reason you'll see.

Sum the hidden units out: the log-probability of an image is minus its free energy, minus log Z. The free energy is a sum of softplus terms. The gradient of log Z is an average under the model. So the weights' gradient is the Boltzmann rule: data correlations minus model correlations. The second still needs samples from the model.

Geoffrey Hinton's shortcut, in 2002: start the chain at a training digit, run k steps of Gibbs sampling, a whole layer at a time, and use where it got to. With k equal to one it's biased, but it learns, and fast: contrastive divergence. Tijmen Tieleman, in 2008, kept the chains running between updates: persistent CD.

Does contrastive divergence maximize the likelihood? Z sums over two to the 196 images, but also over the hidden states, and sixteen hidden units have only sixty-five thousand. So here is the exact held-out log-likelihood, three methods, three seeds each, equal updates.

What does it learn? Each hidden unit's weights, as a picture, show what turns it on: forty of a hundred-unit machine's, positive for ink, negative for paper. To dream, run the chain from binary random pixels: one step, ten, a hundred, a thousand. After the initial binary image, the displays show conditional visible probabilities at the Gibbs checkpoints. With sixteen hidden units we can weigh every hidden state, then draw each binary visible pixel from its conditional Bernoulli distribution. The lower strip contains those exact binary samples. In 2006 Hinton, Simon Osindero and Yee-Whye Teh stacked RBMs into deep belief nets, and deep learning's revival began; six years later backpropagation on GPUs made that unnecessary. The ideas stayed: an energy, and samples drawn by a chain.

13Langevin dynamics and the scoreMaster's3 min

The general idea: any network with one output is an energy, and e to the minus energy over its integral Z defines a density when Z is finite, with no masks, no invertibility, no code. Its gradient has the same two phases: lower the data's energy, raise the model's samples'. In the plane Z is estimated on a finite-box grid, so our ring model's NLL is approximate: 0.92 nats, against a floor of 0.31. In 196 dimensions, no grid will do.

Sampling comes from physics: Paul Langevin's 1908 particle, drifting downhill and kicked at random. As an algorithm: step up the log-density, add a little noise, repeat. In continuous time, under suitable conditions, p is stationary by Part 5's Fokker-Planck equation. Finite unadjusted Euler steps approximate it, with discretization bias and possible slow mixing. The step needs the gradient of log p. Z is a constant, so its gradient vanishes: the normalizer that made training hard is gone from sampling. That gradient is the score, the direction of steepest rise; here, for our ring model, arrows into the eight valleys.

So train an energy with its own Langevin chains: move a pool of chains 40 steps, lower the energy of real points, raise it where the chains end. Yilun Du and Igor Mordatch made this work for images in 2019. On the ring: valleys open where the data is, the chains fall in, and the energy rises where chains crowd without data. It ends 0.61 nats above the floor.

And sampling: uniform noise, then 240 Langevin steps on each learned energy. The points slide into the valleys and jitter there. On the ring, long chains land on 8, 8 and 8 of the eight modes, in three seeds, needing neither Z nor an inverse: only the score.

The catch is the bridge to the next part. Two Gaussians, holding twenty and eighty percent, their score known exactly. Start points uniformly and run Langevin. Each point falls into the nearer valley and stays, so the heavy mode gets percent, set by the start, , not the density's eighty: the local score barely reflects the relative weights of modes this far apart. Yang Song and Stefano Ermon's fix, in 2019: blur with heavy noise, where valleys merge, then turn the noise down level by level. On images that needs the score at every noise level, learned by denoising, as Hyvarinen and Vincent showed: diffusion, Part 21. And in 2025 Equilibrium Matching made images by descending a learned energy.

14Judging a generatorEngineering4 min

How good is a generative model? Its held-out likelihood isn't enough, as Lucas Theis, Aaron van den Oord and Matthias Bethge showed in 2016: dilute a good model, one sample in a hundred from it, the rest noise. The log-likelihood drops by at most log one hundred, about 4.6 nats per image; its per-pixel penalty shrinks as image dimension grows. The samples are ninety-nine percent garbage. And GANs generally have no tractable likelihood. So the field judges samples directly.

The standard since 2017 is the Fréchet Inception Distance, a distance between Gaussians. In one dimension the cheapest move maps quantile to quantile, and the squared Wasserstein distance is the squared gap in means plus the squared gap in spreads. In many dimensions, covariances and a trace of matrix roots: Dowson and Landau, 1982. Martin Heusel and colleagues fitted those Gaussians to the features a trained classifier sees, real against generated. They used Inception, trained on ImageNet; for digits, we use a digit classifier's last hidden layer, 128 numbers, 98.86 percent accurate on the test digits.

A check: A three-by-three blur gives . A warning: few samples bias FID upward. Real digits against the test set score with samples, with , with . So compare at equal sample counts: ours use , putting a perfect model at about .

One number can't separate good samples from good coverage. Mehdi Sajjadi and colleagues, then Tuomas Kynkäänniemi and colleagues at NVIDIA, split it in two. Around each real point, a ball out to its third nearest real neighbour: where the data lives. Precision: the share of generated samples inside real balls. Recall: the share of real points inside generated balls. The drawing shows one hundred twenty points of each kind; the scores use two thousand of each. Chapter five's non-saturating GAN, seed zero: precision , recall .

Every family on the ring, three seeds each. Highest precision: the autoregressive model, 0.97; highest recall: the VAE, 0.99; lowest precision: the VAE, 0.30. And why FID alone is dangerous: one Gaussian blob with the ring's mean and covariance has a Fréchet distance of 0.002, about that between two samples of the ring itself, and a precision of 0.10.

These distribution scores alone cannot rule out memorization: replaying training digits can score well, an FID of , precision , recall . So we check: each sample's nearest training digit. Real test digits sit a median from theirs.

15Five models, one budgetEngineering4 min

Now the five image models, side by side, on equal terms. Every one got the same budget of arithmetic, six trillion registry-counted model FLOPs of training, using PyTorch formulas for supported operations, and every one was trained from three random starts. Equal arithmetic doesn't mean equal anything else. A convolution reuses its weights at every pixel, so the PixelCNN has the fewest parameters and does the most arithmetic per digit: it saw 99 thousand training digits, while the GAN saw 2.1 million. And the last column is the cost of drawing one sample: one pass for every model except the PixelCNN, which needs 196.

Here is what each one draws, seed zero, the first sixteen samples, not chosen, beside real digits. Look before reading the numbers: which look sharpest, which most varied, which most like real handwriting? The measurements come next.

First, FID: the distance between our classifier's view of the generated digits and of the real ones, two thousand generated digits against a reference of ten thousand test digits. Real samples scored , the line for real digits. Each dot is one seed: the spread between seeds is part of the result. Precision and recall use the first two thousand test digits as their reference. In our recorded matched-state three-seed VAE sampler check, drawing conditional pixels increased mean FID from 40.209 to 46.338 and lowered precision from 0.8155 to 0.7603, while recall rose from 0.5643 to 0.7100. Correct likelihood sampling changed the measured trade-off in that check; it was not a quality-score improvement.

Second, reported bits per pixel for the three families we can score tractably, on held-out digits: exact for the PixelCNN, estimated upper bounds for the VAE and the flow. The latter are finite Monte Carlo estimates, not guaranteed bounds in each realization. PixelCNN and the flow use all ten thousand held-out digits; the VAE uses a 64-code importance-weighted estimate on the first one thousand. The lowest reported score is for , at bits per pixel, then at , and at .

Third, a coarse but telling check: which digits does each model draw? The classifier labels two thousand samples of each, and real data has each digit about one time in ten. Mode dropping, at the scale of whole classes, is the easiest failure to see.

So, at this small scale and on one budget, who won what? Sampling uses batched throughput per digit. We group families whose mean sampling time is less than twice the fastest mean. This is a heuristic grouping, not a statistical tie. Which is best depends on what the model is for, and on scale: GANs drew the sharpest images for years, at sizes far beyond ours.

16Where the families meetResearch5 min

For six years GANs drew the sharpest images. In 2021 Prafulla Dhariwal and Alex Nichol, at OpenAI, titled a paper with what happened: diffusion models beat GANs on image synthesis. On ImageNet at 256 pixels, BigGAN-deep had an FID of 6.95; guided diffusion, 4.59. The GAN's precision was the highest, but its recall only 0.28: convincing images of a narrow slice of the world. The reasons are ones this part has met: an objective that charges for every mode missed, a stable regression instead of a game, and a recipe that kept improving as it grew.

Meanwhile the families combined. In 2017 Aaron van den Oord, Oriol Vinyals and Koray Kavukcuoglu gave the VAE a discrete code. Each encoder vector snaps to the nearest entry of a learned codebook, so an image becomes a grid of integers: tokens. Gradients pass straight through the snap. Over the tokens, a PixelCNN learns the prior. In 2021 VQGAN added a GAN loss to sharpen the decoder and a transformer over the tokens; DALL-E wrote text and image tokens with one transformer. A VAE to make tokens, a GAN to make them look good, an autoregressive model to write them: the front end of today's image systems, opened up in Parts 22 and 23.

We built a small one: each digit becomes a seven-by-seven grid of tokens, each one of codebook entries, and a decoder turns the grid back. The codebook's perplexity is : its effective codebook size among entries. Written at fixed width a grid is bits; the transformer's held-out code-sequence negative log-likelihood is bits per digit, not an actual compressed-file size or a marginal image likelihood. We sample tokens from the transformer, then display decoder locations rather than conditional pixel draws. We also tested using only training inputs for code revival. In this paired seed both checks selected the same dead codes: the final tokenizer, prior, outputs and measured scores were unchanged. The repair removes a test-driven decision; no performance improvement was observed in this pair.

Reading order is slow, and a strange order for a picture. In 2024 Keyu Tian and colleagues at ByteDance and Peking University predicted not the next token but the next scale. One token for the whole image, then a two-by-two map, then larger maps, each predicted at once given all the coarser ones. On ImageNet at 256 pixels: an FID of 1.73, from 18.65 for raster order, about twenty times faster; a NeurIPS 2024 outstanding paper.

And the GAN didn't die. Diffusion needs dozens of network passes per image; a generator needs one. To get one step back, diffusion models are distilled into generators, and the best distillers use a discriminator. Axel Sauer and colleagues at Stability AI trained SDXL-Turbo, one to four steps, with a GAN loss and a diffusion teacher; then SD3-Turbo, with a discriminator built from a diffusion model. Tianwei Yin and colleagues' DMD2 added a GAN loss on real images: an FID of 1.28 on small ImageNet images, in one step. R3GAN rebuilt the GAN itself with a principled loss. Consistency models reach diffusion quality in two steps, and in 2026 Kaiming He's group trained one-step generators by drifting their samples onto the data: an FID of 1.54 on ImageNet.

So this is where the four answers, and the fifth, ended up. The VAE and the GAN became the tokenizers and latent spaces that many image and video models start from. The autoregressive model writes those tokens, a scale or a token at a time. The energy model's score, learned at every noise level, became diffusion, with the VAE's bound inside it. The neural ODE became flow matching. And the GAN's discriminator came back to make diffusion fast. Which is why the next part, diffusion, is built from pieces you have now seen.

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. An autoregressive model writes an image one piece at a time, with an exact likelihood and a slow sampler. A VAE learns a code and a decoder together with one bound, trading rate against distortion. A GAN learns from a critic, and the game can collapse onto a few modes and spiral around its equilibrium; a Wasserstein critic and gradient penalties tame it. A flow bends noise into data, invertibly, with an exact likelihood, and a neural ODE does it continuously, with a trace in place of a determinant. A Boltzmann machine is an energy, trained by contrasting the data with its own dreams; and Langevin dynamics samples any energy using only its score, given enough noise to cross between modes.

All of this comes back. The score, learned at every noise level, is diffusion, next time, with flow matching training continuous flows by regression. Autoencoders and their tokens are the front end of the image, video and audio models of Parts 22 and 23, and next-scale prediction returns in Part 22. The contrastive idea, pull the data up and push everything else down, drives the self-supervised learning of Part 24. And the question of how to judge a model, and how its metrics fail, closes the series.

Here are six problems to try, from the optimal discriminator to the Fréchet distance. Pause here and work through them; full solutions are in this part's notes.

Next time: diffusion. Add noise to the data at every level, from a whisper to a roar; learn the score at each level by learning to remove the noise; then walk back from pure noise, level by level, the annealed Langevin of chapter thirteen grown up. Part 21: diffusion and flow.

To go deeper, Simon Prince's Understanding Deep Learning covers GANs, flows and VAEs clearly, and for free; Kevin Murphy's second volume covers every family in this part, in depth. Thanks for watching, and see you in Part 21.

Where it goes next. The score, learned at every noise level, becomes diffusion in Part 21, where flow matching trains continuous flows by regression. Autoencoders and their tokens are the front end of the image, video and audio models of Parts 22 and 23, and next-scale prediction returns in Part 22. The contrastive idea drives the self-supervised learning of Part 24, and judging a model returns in Part 31.

Key results

The part's results in one place, for revision.

The ELBO's gap\(\displaystyle \log p(x)-\operatorname{ELBO}=\operatorname{KL}\bigl(q(z\mid x)\,\|\,p(z\mid x)\bigr)\)
The optimal discriminator\(\displaystyle D^*=\frac{p}{p+q},\qquad\allowbreak V(D^*,G)=-\log 4+2\operatorname{JS}(p\,\|\,q)\)
Simultaneous steps on xy\(\displaystyle |\lambda|=|1\pm i\eta|=\sqrt{1+\eta^2}>1\)
A coupling layer\(\displaystyle y_b=x_b\odot e^{s(x_a)}+t(x_a),\qquad\allowbreak \log|\det J|=\sum_i s_i(x_a)\)
A continuous flow\(\displaystyle \frac{d\log p(z(t))}{dt}=-\operatorname{tr}\frac{\partial f}{\partial z}\)
Fréchet distance in 1D\(\displaystyle W_2^2=(\mu_1-\mu_2)^2+(\sigma_1-\sigma_2)^2\)

Try it

Lab 20 · The adversarial game: the optimal discriminator and the spiral

Train a logistic discriminator between samples of p = N(0, 1) and q = N(1.5, 1) with the series' autodiff and compare it with D* = p/(p + q) and its value with -log 4 + 2 JS; then run simultaneous, alternating and extragradient steps on min_x max_y xy and compare each radius with its eigenvalue.

Figure produced by Lab 20: The adversarial game: the optimal discriminator and the spiral
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.ai.labs 20 needs numpy, scipy, matplotlib · download lab20.py · source on GitHub
discriminator's logit a + b x + c x^2  1.131 -1.492 x -0.010 x^2   (optimal 1.125 -1.500 x)
largest |D - D*| on [-2.5, 4]          0.002
value V(D, G) on fresh samples         -0.9408   (-log 4 + 2 JS = -0.9440,  -log 4 = -1.3863)
simultaneous: growth per step          1.019804   (sqrt(1 + eta^2) = 1.019804)
simultaneous: radius after 60 steps    3.24 x the start
alternating: radius stays within       0.940 to 1.039
extragradient: shrink per step         0.980612   (theory 0.980612)

A discriminator trained to its optimum reports the Jensen-Shannon divergence between data and generator; but when both players step at once the game's field rotates, and plain gradient steps spiral away from the equilibrium they circle.
The code (117 lines; it asserts its own result)
"""Lab 20: train a discriminator to its optimum p/(p + q), then let two players follow their gradients on xy."""

import numpy as np

from videos.coursekit import labs
from explainer.ai.autodiff import Tensor, sigmoid

TITLE = "The adversarial game: the optimal discriminator and the spiral"
GOAL = ("Train a logistic discriminator between samples of p = N(0, 1) and q = N(1.5, 1) with the series' autodiff and "
        "compare it with D* = p/(p + q) and its value with -log 4 + 2 JS; then run simultaneous, alternating and "
        "extragradient steps on min_x max_y xy and compare each radius with its eigenvalue.")
TASKS = [
    "Move q to N(4, 1). How close does the value get to its ceiling of 0, and what happens to the gradient of log(1 - D) under q?",
    "Add the penalty -gamma/2 y^2 to the y player's objective (gamma = 0.5) and find which methods now converge.",
    "Replace extragradient by optimistic steps, x - 2 eta g_t + eta g_(t-1), and compare its contraction per step.",
]


def norm_pdf(x, mu):
    return np.exp(-0.5 * (x - mu) ** 2) / np.sqrt(2 * np.pi)


def game_grads(x, y):
    """dV/dx and dV/dy for V = xy, by reverse-mode autodiff."""
    xt, yt = Tensor(x, requires_grad=True), Tensor(y, requires_grad=True)
    (xt * yt).backward()
    return float(xt.grad), float(yt.grad)


def run(seed=0):
    rng = np.random.default_rng(seed)
    theta, n = 1.5, 4000
    real, fake = rng.standard_normal(n), theta + rng.standard_normal(n)
    feats = lambda x: np.column_stack([np.ones_like(x), x, x * x])

    # the discriminator ascends V(D, G) = E_p log D + E_q log(1 - D); its logit is a + b x + c x^2
    w = Tensor(np.zeros(3), requires_grad=True)
    Fr, Ff = Tensor(feats(real)), Tensor(feats(fake))
    for _ in range(1500):
        w.grad[:] = 0
        value = sigmoid(Fr @ w).log().mean() + sigmoid(-(Ff @ w)).log().mean()
        value.backward()
        w.data += 0.25 * w.grad
    a, b, c = w.data
    # fresh samples, so the value is not flattered by the fit
    real2, fake2 = rng.standard_normal(n), theta + rng.standard_normal(n)
    D = lambda x: 1 / (1 + np.exp(-(feats(x) @ w.data)))
    v_hat = np.log(D(real2)).mean() + np.log(1 - D(fake2)).mean()
    grid = np.linspace(-8, 10, 20001)
    p, q = norm_pdf(grid, 0), norm_pdf(grid, theta)
    m = (p + q) / 2
    js = 0.5 * np.trapezoid(p * np.log(p / m), grid) + 0.5 * np.trapezoid(q * np.log(q / m), grid)
    v_star = -np.log(4) + 2 * js
    xs = np.linspace(-2.5, 4, 200)
    d_star = norm_pdf(xs, 0) / (norm_pdf(xs, 0) + norm_pdf(xs, theta))
    d_gap = np.abs(D(xs) - d_star).max()

    # the game min_x max_y xy, both players following their own gradient
    eta, T = 0.2, 60
    start = rng.standard_normal(2)
    start /= np.linalg.norm(start)
    paths = {}
    for name in ("simultaneous", "alternating", "extragradient"):
        x, y = start
        path = [(x, y)]
        for _ in range(T):
            gx, gy = game_grads(x, y)
            if name == "simultaneous":
                x, y = x - eta * gx, y + eta * gy
            elif name == "alternating":
                x = x - eta * gx
                y = y + eta * game_grads(x, y)[1]
            else:  # look ahead half a step, then step with the gradient found there
                hx, hy = game_grads(x - eta * gx, y + eta * gy)
                x, y = x - eta * hx, y + eta * hy
            path.append((x, y))
        paths[name] = np.array(path)
    radius = {k: np.linalg.norm(v, axis=1) for k, v in paths.items()}
    rate_sim = radius["simultaneous"][1:] / radius["simultaneous"][:-1]
    rate_eg = radius["extragradient"][1:] / radius["extragradient"][:-1]
    eg_theory = np.sqrt((1 - eta ** 2) ** 2 + eta ** 2)

    lab = labs.Lab()
    lab.row("discriminator's logit a + b x + c x^2", f"{a:.3f} {b:+.3f} x {c:+.3f} x^2   (optimal {theta ** 2 / 2:.3f} {-theta:+.3f} x)")
    lab.row("largest |D - D*| on [-2.5, 4]", f"{d_gap:.3f}")
    lab.row("value V(D, G) on fresh samples", f"{v_hat:.4f}   (-log 4 + 2 JS = {v_star:.4f},  -log 4 = {-np.log(4):.4f})")
    lab.row("simultaneous: growth per step", f"{rate_sim.mean():.6f}   (sqrt(1 + eta^2) = {np.sqrt(1 + eta ** 2):.6f})")
    lab.row(f"simultaneous: radius after {T} steps", f"{radius['simultaneous'][-1]:.2f} x the start")
    lab.row("alternating: radius stays within", f"{radius['alternating'].min():.3f} to {radius['alternating'].max():.3f}")
    lab.row("extragradient: shrink per step", f"{rate_eg.mean():.6f}   (theory {eg_theory:.6f})")
    lab.note = ("A discriminator trained to its optimum reports the Jensen-Shannon divergence between data and generator; "
                "but when both players step at once the game's field rotates, and plain gradient steps spiral away from "
                "the equilibrium they circle.")

    assert abs(b + theta) < 0.2 and abs(a - theta ** 2 / 2) < 0.2 and abs(c) < 0.1, "the logit is log p/q"
    assert d_gap < 0.06, "the trained discriminator is p/(p + q)"
    assert abs(v_hat - v_star) < 0.05 and v_hat > -np.log(4) + 0.3, "its value is -log 4 + 2 JS"
    assert np.allclose(rate_sim, np.sqrt(1 + eta ** 2), atol=1e-12), "simultaneous steps grow by sqrt(1 + eta^2)"
    assert abs(radius["simultaneous"][-1] - (1 + eta ** 2) ** (T / 2)) < 1e-9
    assert radius["alternating"].max() < 1.25 and radius["alternating"].min() > 0.8, "alternating steps orbit"
    assert np.allclose(rate_eg, eg_theory, atol=1e-12) and eg_theory < 1, "extragradient spirals in"

    fig, ax = labs.figure(2, size=(11, 4.2))
    ax[0].plot(xs, norm_pdf(xs, 0), color=labs.MUTED, ls="--", lw=1.2, label="data p = N(0, 1)")
    ax[0].plot(xs, norm_pdf(xs, theta), color=labs.MUTED, ls=":", lw=1.2, label="generator q = N(1.5, 1)")
    ax[0].plot(xs, d_star, color=labs.GOLD, lw=3, alpha=0.6, label="D* = p/(p + q)")
    ax[0].plot(xs, D(xs), color=labs.BLUE, label="trained discriminator")
    ax[0].set(title="The discriminator at its optimum", xlabel="x", ylabel="density, or D(x)")
    ax[0].legend(loc="upper right")
    for name, color in (("simultaneous", labs.RED), ("alternating", labs.BLUE), ("extragradient", labs.GREEN)):
        ax[1].plot(*paths[name].T, color=color, lw=1.3, label=name)
    ax[1].plot(0, 0, "o", color=labs.GOLD, ms=6)
    ax[1].plot(*start, "o", color=labs.INK, ms=4)
    ax[1].set(title=f"min max xy, {T} steps of size {eta}", xlabel="x (minimizes)", ylabel="y (maximizes)", aspect="equal")
    ax[1].legend(loc="upper right")
    lab.fig = fig
    return lab

Now change it

  1. Move q to N(4, 1). How close does the value get to its ceiling of 0, and what happens to the gradient of log(1 - D) under q?
  2. Add the penalty -gamma/2 y^2 to the y player's objective (gamma = 0.5) and find which methods now converge.
  3. Replace extragradient by optimistic steps, x - 2 eta g_t + eta g_(t-1), and compare its contraction per step.

Problems, with solutions

Try each problem before opening its solution.

1. The optimal discriminator. Show that for a fixed generator with distribution q, the best discriminator is D* = p/(p + q), and that V(D*, G) = −log 4 + 2 JS(p‖q).

Solution

V = ∫ [p log D + q log(1 − D)] dx, and at each x the integrand a log y + b log(1 − y) has derivative a/y − b/(1 − y), zero at y = a/(a + b); its second derivative is negative, so this is the maximum: D* = p/(p + q). Substituting, V = E_p[log p/(p + q)] + E_q[log q/(p + q)]. Write p + q = 2m with m = (p + q)/2: each term is E[log p/m] − log 2, so V = KL(p‖m) + KL(q‖m) − log 4 = 2 JS(p‖q) − log 4, minimized (at −log 4) exactly when q = p.

2. The ELBO's gap, and collapse. Show log p(x) − ELBO = KL(q(z|x)‖p(z|x)). If the decoder can represent p(x) exactly without using z, show that q(z|x) = p(z) maximizes the ELBO.

Solution

ELBO = E_q[log p(x, z) − log q(z|x)] = E_q[log p(x) + log p(z|x) − log q(z|x)] = log p(x) − KL(q(z|x)‖p(z|x)). If the decoder ignores z and equals p(x), then p(x|z) = p(x), the true posterior is the prior, and the ELBO is log p(x) − KL(q(z|x)‖p(z)), at most log p(x) with equality for q(z|x) = p(z). Any use of z must buy more reconstruction than it costs in KL; a decoder that needs nothing from z gets nothing for it.

3. A coupling layer. For y_a = x_a, y_b = x_b ⊙ exp(s(x_a)) + t(x_a), show log|det J| = Σᵢ sᵢ(x_a), and write the inverse.

Solution

∂y_a/∂x_a = I and ∂y_a/∂x_b = 0, so J is block lower-triangular with diagonal blocks I and diag(exp(s(x_a))); its determinant is the product of the diagonal, exp(Σ sᵢ), positive. Inverse: x_a = y_a (copied), then x_b = (y_b − t(y_a)) ⊙ exp(−s(y_a)); s and t are never inverted, only evaluated.

4. Hutchinson's estimator. Show E[εᵀAε] = tr A when E[εεᵀ] = I. For Rademacher ε (entries ±1), show the variance is 2 Σ_{i≠j} S_ij², with S = (A + Aᵀ)/2.

Solution

E[εᵀAε] = Σ_ij A_ij E[εᵢεⱼ] = Σᵢ A_ii. Since εᵀAε = εᵀSε, write it as Σᵢ S_ii εᵢ² + Σ_{i≠j} S_ij εᵢεⱼ; for signs εᵢ² = 1, so the first sum is the constant tr A, and the variance is that of Σ_{i≠j} S_ij εᵢεⱼ = 2 Σ_{i<j} S_ij εᵢεⱼ. The products εᵢεⱼ (i < j) have mean 0, variance 1 and are pairwise uncorrelated, so the variance is 4 Σ_{i<j} S_ij² = 2 Σ_{i≠j} S_ij². (For Gaussian ε the diagonal terms vary too, adding 2 Σᵢ S_ii²: total 2‖S‖_F².)

5. The RBM's conditionals. For E(v, h) = −bᵀv − cᵀh − vᵀWh with binary units, derive p(h_j = 1 | v) = σ(c_j + W_{:j}ᵀv) and the free energy F(v) = −bᵀv − Σⱼ log(1 + exp(c_j + W_{:j}ᵀv)).

Solution

p(h | v) ∝ exp(cᵀh + vᵀWh) = Πⱼ exp(h_j (c_j + W_{:j}ᵀv)): a product over j, so the h_j are independent given v, each with p(h_j = 1 | v) = e^{aⱼ}/(1 + e^{aⱼ}) = σ(aⱼ), aⱼ = c_j + W_{:j}ᵀv. Summing h out, Σ_h e^{−E(v,h)} = e^{bᵀv} Πⱼ (1 + e^{aⱼ}) = e^{−F(v)} with F as stated.

6. The 2-Wasserstein distance between 1D Gaussians. Show that W₂²(N(μ₁, σ₁²), N(μ₂, σ₂²)) = (μ₁ − μ₂)² + (σ₁ − σ₂)².

Solution

In one dimension the optimal coupling is monotone, quantile to quantile: x₂ = μ₂ + (σ₂/σ₁)(x₁ − μ₁). With x₁ = μ₁ + σ₁ζ, ζ ~ N(0, 1), x₁ − x₂ = (μ₁ − μ₂) + (σ₁ − σ₂)ζ, so E(x₁ − x₂)² = (μ₁ − μ₂)² + (σ₁ − σ₂)². This is the d = 1 case of ‖μ₁ − μ₂‖² + tr(Σ₁ + Σ₂ − 2(Σ₁^{1/2}Σ₂Σ₁^{1/2})^{1/2}), FID's formula.

Notes and sources

Glossary

English 中文
generative model 生成模型
sample, evaluate, encode 采样,计算(概率),编码
density estimation 密度估计
differential entropy, the floor h(p) 微分熵,下限h(p)
two moons, ring of eight Gaussians, checkerboard 双月,八个高斯组成的环(八峰环),棋盘格
autoregressive model 自回归模型
mixture density network (mixture of Gaussians) 混合密度网络(高斯混合)
NADE, MADE NADE,MADE
PixelCNN, PixelRNN, WaveNet PixelCNN,PixelRNN,WaveNet
masked convolution, mask A / mask B 掩码卷积,A型掩码 / B型掩码
receptive field, blind spot 感受野,盲区
vertical stack, horizontal stack 竖直栈,水平栈
bits per pixel 每像素比特数
latent variable, code z 隐变量,编码z
prior, posterior 先验,后验
Helmholtz machine, recognition model 亥姆霍兹机,识别模型
wake–sleep algorithm 醒-睡算法
amortized inference 摊销推断
variational autoencoder (VAE) 变分自编码器(VAE)
encoder, decoder 编码器,解码器
evidence lower bound (ELBO) 证据下界(ELBO)
reparameterization trick 重参数化技巧
reconstruction term 重建项
rate, distortion, rate–distortion trade-off 码率,失真,码率-失真权衡
importance-weighted bound (IWAE) 重要性加权下界(IWAE)
discretized logistic 离散化逻辑斯谛分布
active units 活跃单元
β-VAE, disentanglement β-VAE,解耦
posterior collapse 后验坍缩
free bits, KL annealing 自由比特,KL退火
generative adversarial network (GAN) 生成对抗网络(GAN)
generator, discriminator 生成器,判别器
minimax game, value function 极小极大博弈,值函数
optimal discriminator 最优判别器
Jensen–Shannon divergence 詹森-香农散度(JS散度)
saturating / non-saturating loss 饱和损失 / 非饱和损失
reverse KL 反向KL散度
mode (a peak of a distribution), modes covered 峰,覆盖的峰
mode collapse, mode dropping 模式坍缩,模式丢失
simultaneous / alternating gradient steps 同时梯度步 / 交替梯度步
extragradient, optimistic gradient descent 外梯度法,乐观梯度下降
Dirac-GAN, R1 penalty 狄拉克GAN,R1惩罚
two time-scale update rule (TTUR) 双时间尺度更新规则(TTUR)
spectral normalization 谱归一化
Wasserstein distance, earth mover's distance 瓦瑟斯坦距离,推土机距离
transport plan, coupling 运输方案,耦合
Kantorovich–Rubinstein duality 康托罗维奇–鲁宾斯坦对偶
1-Lipschitz, critic 1-利普希茨,评论家
weight clipping, gradient penalty (WGAN-GP) 权重截断,梯度惩罚(WGAN-GP)
DCGAN, progressive growing, BigGAN DCGAN,渐进式增长,BigGAN
StyleGAN, mapping network, style, style mixing StyleGAN,映射网络,风格,风格混合
truncation trick 截断技巧
GAN inversion GAN反演
normalizing flow 归一化流
change of variables 变量替换
Jacobian determinant, log-determinant 雅可比行列式,对数行列式
coupling layer (affine), NICE, RealNVP, Glow (仿射)耦合层,NICE,RealNVP,Glow
dequantization, logit transform 去量化,logit变换
temperature (sampling) (采样)温度
neural ODE, continuous normalizing flow 神经ODE,连续归一化流
instantaneous change of variables, divergence 瞬时变量替换,散度
trace, Hutchinson's estimator 迹,哈钦森估计量
Rademacher probe 拉德马赫探针(随机正负号探针)
FFJORD FFJORD
energy-based model, energy E 能量模型(基于能量的模型),能量E
partition function (normalizer) Z 配分函数(归一化常数)Z
Hopfield network, associative memory 霍普菲尔德网络,联想记忆
content-addressable memory 按内容寻址的记忆
capacity, spin glass, mixture state 容量,自旋玻璃,混合态
modern (dense) Hopfield network 现代(稠密)霍普菲尔德网络
Boltzmann machine, hidden / visible units 玻尔兹曼机,隐藏 / 可见单元
positive phase, negative phase 正相,负相
restricted Boltzmann machine (RBM), harmonium 受限玻尔兹曼机(RBM),harmonium
free energy 自由能
Gibbs sampling 吉布斯采样
contrastive divergence (CD-k), persistent CD 对比散度(CD-k),持续对比散度(PCD)
filters (of an RBM) (RBM的)滤波器
Langevin dynamics 朗之万动力学
score (function) 分数函数
replay buffer (of chains) (链的)回放池
annealed Langevin dynamics, noise levels 退火朗之万动力学,噪声水平
score matching, denoising score matching 分数匹配,去噪分数匹配
Equilibrium Matching 均衡匹配
Fréchet Inception Distance (FID) 弗雷歇Inception距离(FID)
Fréchet distance, 2-Wasserstein distance 弗雷歇距离,2-瓦瑟斯坦距离
Inception Score Inception分数
features (of a classifier) (分类器的)特征
precision, recall (for generators) 精确率,召回率(生成模型的)
memorization, nearest neighbour 死记硬背(记忆),最近邻
generative trilemma 生成学习三难困境
tokenizer, codebook, token 分词器,码本,词元
vector quantization (VQ-VAE), straight-through estimator 向量量化(VQ-VAE),直通估计器
perplexity (of a codebook) (码本的)困惑度
VQGAN, two-stage model VQGAN,两阶段模型
next-scale prediction (VAR) 下一尺度预测(VAR)
distillation, adversarial diffusion distillation 蒸馏,对抗扩散蒸馏
consistency model 一致性模型
drifting model 漂移模型

Sources

Books: I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (2016), ch. 16–20; S. J. D. Prince, Understanding Deep Learning (2023), ch. 14–17; K. P. Murphy, Probabilistic Machine Learning: Advanced Topics (2023), part IV; C. Villani, Optimal Transport: Old and New (2009).

Papers: C. E. Shannon (1948); J. J. Hopfield (1982); D. J. Amit, H. Gutfreund & H. Sompolinsky (1985); D. H. Ackley, G. E. Hinton & T. J. Sejnowski (1985); P. Smolensky (1986); G. E. Hinton, Training products of experts by minimizing contrastive divergence (2002); T. Tieleman (2008); G. E. Hinton, S. Osindero & Y.-W. Teh (2006); D. Krotov & J. J. Hopfield (2016); H. Ramsauer et al., Hopfield Networks is All You Need (2020); P. Dayan, G. E. Hinton, R. M. Neal & R. S. Zemel, The Helmholtz Machine (1995); G. E. Hinton, P. Dayan, B. J. Frey & R. M. Neal, The wake-sleep algorithm (1995); D. P. Kingma & M. Welling, Auto-Encoding Variational Bayes (2013); D. J. Rezende, S. Mohamed & D. Wierstra (2014); Y. Burda, R. Grosse & R. Salakhutdinov, IWAE (2016); S. R. Bowman et al. (2016); D. P. Kingma et al., IAF (2016); X. Chen et al., Variational Lossy Autoencoder (2017); I. Higgins et al., β-VAE (2017); A. A. Alemi et al., Fixing a Broken ELBO (2018); H. Larochelle & I. Murray, NADE (2011); M. Germain et al., MADE (2015); A. van den Oord, N. Kalchbrenner & K. Kavukcuoglu, Pixel Recurrent Neural Networks (2016); A. van den Oord et al., Conditional Image Generation with PixelCNN Decoders (2016), WaveNet (2016); T. Salimans et al., PixelCNN++ (2017); I. Goodfellow et al., Generative Adversarial Nets (2014); A. Radford, L. Metz & S. Chintala, DCGAN (2015); T. Salimans et al., Improved Techniques for Training GANs (2016); M. Arjovsky & L. Bottou (2017); M. Arjovsky, S. Chintala & L. Bottou, Wasserstein GAN (2017); I. Gulrajani et al., Improved Training of Wasserstein GANs (2017); G. M. Korpelevich (1976); C. Daskalakis et al., Training GANs with Optimism (2018); L. Mescheder, A. Geiger & S. Nowozin, Which Training Methods for GANs do actually Converge? (2018); T. Miyato et al., Spectral Normalization (2018); H. Zhang et al., SAGAN (2018); T. Karras et al., Progressive Growing of GANs (2018); A. Brock, J. Donahue & K. Simonyan, BigGAN (2019); T. Karras, S. Laine & T. Aila, StyleGAN (2019), and StyleGAN2 (2020), StyleGAN3 (2021); J.-Y. Zhu et al., iGAN (2016); R. Abdal, Y. Qin & P. Wonka, Image2StyleGAN (2019); X. Pan et al., DragGAN (2023); Y. Huang et al., The GAN is dead; long live the GAN! (2024); E. G. Tabak & E. Vanden-Eijnden (2010); D. J. Rezende & S. Mohamed, Variational Inference with Normalizing Flows (2015); L. Dinh, D. Krueger & Y. Bengio, NICE (2014); L. Dinh, J. Sohl-Dickstein & S. Bengio, RealNVP (2017); D. P. Kingma & P. Dhariwal, Glow (2018); S. Zhai et al., Normalizing Flows are Capable Generative Models (2025); R. T. Q. Chen, Y. Rubanova, J. Bettencourt & D. Duvenaud, Neural Ordinary Differential Equations (2018); W. Grathwohl et al., FFJORD (2019); M. F. Hutchinson (1989); Y. LeCun et al., A Tutorial on Energy-Based Learning (2006); P. Langevin (1908); A. Hyvärinen, Score Matching (2005); P. Vincent (2011); Y. Du & I. Mordatch (2019); E. Nijkamp et al. (2019); Y. Song & S. Ermon (2019); R. Wang & Y. Du, Equilibrium Matching (2025); L. Theis, A. van den Oord & M. Bethge (2016); M. Heusel et al. (2017); D. C. Dowson & B. V. Landau (1982); M. S. M. Sajjadi et al. (2018); T. Kynkäänniemi et al. (2019); G. Stein et al., Exposing flaws of generative model evaluation metrics (2023); Z. Xiao, K. Kreis & A. Vahdat (2022); P. Dhariwal & A. Nichol, Diffusion Models Beat GANs on Image Synthesis (2021); A. van den Oord, O. Vinyals & K. Kavukcuoglu, VQ-VAE (2017); P. Esser, R. Rombach & B. Ommer, Taming Transformers (2021); A. Ramesh et al., DALL·E (2021); K. Tian et al., Visual Autoregressive Modeling (2024); A. Sauer et al., Adversarial Diffusion Distillation (2023) and LADD (2024); T. Yin et al., DMD2 (2024); C. Lu & Y. Song, sCM (2025); M. Deng, H. Li, T. Li, Y. Du & K. He, Generative Modeling via Drifting (2026). Data: Y. LeCun, C. Cortes & C. J. C. Burges, MNIST (1998). The 2024 Nobel Prize citation is the Royal Swedish Academy of Sciences'.

About this partfrom its README

Part 20 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus), and the first part of Act IV, Generation and Perception. How a machine learns a distribution it can sample from: the four families that work — autoregressive models, variational autoencoders, generative adversarial networks, normalizing flows — and the older fifth, energy-based models, with their history from Shannon's letter-by-letter English (1948) to one-step generators (2026), and how to judge them. The recipes use three densities in the plane (two moons, a ring of eight Gaussians, a checkerboard) and MNIST digits averaged down to 14 × 14 pixels with 16 grey levels. The five main image families each receive a nominal 6 × 10¹² training-FLOP budget, counted by PyTorch's per-operation formulas, with three seeds; architectures, update counts and examples seen differ. Historical reported results and the separate, validated 2026-11-02 cloud experiments are identified below. The earlier run's date, hardware and weight files have not been independently established or recovered by this work.

  • Hook: digits nobody wrote. Samples from four of our models side by side (PixelCNN, VAE, GAN, RealNVP); the question; the five answers; the plan.
  • 1. The generative problem. A generative model as a distribution to sample, evaluate and encode; maximum likelihood as minimum KL, E_p[−log q] = h(p) + KL(p‖q), with the theoretical entropy floor illustrated by cached Monte Carlo reference estimates; how we got here (Shannon 1948, Hopfield 1982, Boltzmann machines 1985, the Helmholtz machine 1995, deep belief nets 2006, VAEs, GANs, NICE and PixelCNN 2013–16, StyleGAN and neural ODEs 2018, diffusion beating GANs in 2021, next-scale prediction 2024); the families' trade-offs and the generative trilemma (Xiao, Kreis & Vahdat 2022); the test bench.
  • 2. One pixel at a time. The chain rule; an autoregressive model in the plane, p(x₁) p(x₂ | x₁), each factor a mixture of ten Gaussians, its conditional slices and its training replay; masked convolutions (NADE, MADE, PixelRNN, PixelCNN, WaveNet); architectural blind spots of stacked masks and the two-stack construction designed to address them (van den Oord et al. 2016b), illustrated by a finite gradient-sensitivity probe rather than a proof of structural connectivity; our PixelCNN's training replayed (held-out bits per pixel and samples at each checkpoint, three seeds); one digit drawn pixel by pixel with its sixteen predicted probabilities; the cost of 196 sequential passes, measured against the GAN's one.
  • 3. From Helmholtz machines to the VAE. Latent-variable models and the intractable integral; the Helmholtz machine and the wake–sleep algorithm (Dayan, Hinton, Neal & Zemel 1995; Hinton, Dayan, Frey & Neal 1995); the ELBO derived (Jensen) with its gap KL(q(z|x)‖p(z|x)); the reparameterization trick and the Gaussian KL in closed form (Kingma & Welling 2013; Rezende, Mohamed & Wierstra 2014); our VAE (16-number code, discretized-logistic decoder over the 16 levels, after PixelCNN++).
  • 4. Training a VAE: rate, distortion, collapse. The two terms of the bound over training, with reconstructions and decoder-location snapshots at each checkpoint; the ELBO and a 64-sample importance-weighted bound in bits per pixel; active code units; a VAE with a 2-number code, the test digits' codes replayed through training and the decoded grid; β-VAE (Higgins et al. 2017) at β = 0.25 … 8, two seeds each: the rate–distortion curve (Alemi et al. 2018), active units and decoder-location diagnostics; posterior collapse made to happen: in the plane, a factorized decoder keeps its rate while an autoregressive decoder's falls nearly to zero (three seeds each); on digits, a VAE with a PixelCNN decoder, plain and with free bits (Kingma et al. 2016), its rate over training and whether digits decoded from one code keep their identity (judged by the classifier); the VAE's blur on the ring.
  • 5. The adversarial game. The GAN value function (Goodfellow et al. 2014); the optimal discriminator D* = p/(p + q) and V(D*, G) = −log 4 + 2 JS(p‖q), derived; the saturating loss log(1 − D) against the non-saturating −log D, with the generator's measured early gradient norms; the non-saturating gradient as reverse KL minus 2 JS at the current optimal discriminator, held fixed (Arjovsky & Bottou 2017); mode collapse on the ring, replayed (the discriminator's verdict under the generator's samples) for the seed that ended with the fewest modes; modes covered by the minimax and non-saturating losses over five seeds each.
  • 6. Why GANs spiral. min_x max_y xy: the rotating field, eigenvalues ±i; simultaneous steps spiral out by exactly √(1 + η²) per step (asserted), alternating steps orbit, extragradient (Korpelevich 1976) and optimistic steps (Daskalakis et al. 2018) spiral in; Mescheder, Geiger & Nowozin's Dirac-GAN (2018) with and without the R1 penalty; the ring GAN's mode occupancy, checkpoint by checkpoint.
  • 7. Wasserstein GANs. Arjovsky's parallel lines: Jensen–Shannon is flat at log 2 while W₁ = |θ|, both estimated by trained networks at seventeen offsets; the earth mover's distance (Monge 1781, Kantorovich 1942); Kantorovich– Rubinstein duality; weight clipping and the gradient penalty (Gulrajani et al. 2017); WGAN-GP on the ring against both GAN losses, five seeds each, same networks and generator steps; the price per generator step, counted.
  • 8. GANs at scale: BigGAN, StyleGAN, inversion. Our digit GAN replayed with its losses; DCGAN (2015), progressive growing (2017), BigGAN (2018: IS 166.5, FID 7.4 at 128², previous best 52.5 and 18.6), StyleGAN (mapping network, per-layer styles, noise, style mixing; schematic); the truncation trick measured on our GAN (precision, recall and FID against the truncation threshold); GAN inversion by gradient descent on z, four restarts per digit, against the VAE's encoder, and an interpolation (iGAN 2016, Image2StyleGAN 2019, DragGAN 2023).
  • 9. Normalizing flows. The change of variables in 1D and d dimensions (Tabak & Vanden-Eijnden 2010; Rezende & Mohamed 2015); affine coupling layers and their triangular Jacobian (NICE 2014, RealNVP 2017), the log-determinant checked against autograd's; the plane warped layer by layer by our 8-coupling flow (moons and checkerboard); training replayed and each toy's gap to its floor; RealNVP on digits at temperatures 1 and 0.7; Glow (2018) and TarFlow (Zhai et al., 2024/ICML 2025).
  • 10. Neural ODEs and continuous flows. Residual networks as Euler steps (Chen et al. 2018); the instantaneous change of variables d log p/dt = −tr(∂f/∂z), derived; Hutchinson's estimator (1989) and its variance for Gaussian and Rademacher probes, measured against the formulas; exact trace against one probe in 196 dimensions, timed; a continuous flow trained on the moons with the exact trace and with Hutchinson's estimator (FFJORD), three seeds each, both judged with the exact trace; 700 noise points carried along the learned field with the density at five times.
  • 11. Hopfield and Boltzmann. Hopfield's energy (1982) and why asynchronous updates never raise it; Hebb's rule; recall of a damaged digit replayed with its energy; capacity on random patterns against 0.138 N (Amit, Gutfreund & Sompolinsky 1985); correlated digits and mixture states; the modern softmax update (Krotov & Hopfield 2016; Ramsauer et al. 2020) as attention; the Boltzmann machine (Ackley, Hinton & Sejnowski 1985) and its two-phase learning rule; the 2024 Nobel Prize in Physics.
  • 12. Contrastive divergence. The restricted Boltzmann machine (Smolensky 1986), its factorized conditionals and free energy; the log-likelihood gradient as positive minus negative phase, derived; CD-k (Hinton 2002) and persistent CD (Tieleman 2008); with 16 hidden units the partition function is summed exactly over 2¹⁶ hidden states, so CD-1, CD-10 and PCD are compared on the true held-out log-likelihood, three seeds each; a 100-unit RBM's filters and Gibbs chains; exact samples of the 16-unit RBM; deep belief nets (2006).
  • 13. Langevin dynamics and the score. Energy-based models and their two-phase gradient (LeCun et al. 2006); in 2D, Z approximated on a finite-box grid, giving numerical likelihood estimates; Langevin dynamics (1908) and the score ∇ log p = −∇E, with Z gone; persistent Langevin training (Du & Mordatch 2019) replayed on the ring; sampling from noise on all three toys; the failure on separated modes (two Gaussians weighted 0.2/0.8, exact score) and annealed Langevin (Song & Ermon 2019), toward score matching (Hyvärinen 2005; Vincent 2011) and Part 21; Equilibrium Matching (Wang & Du 2025).
  • 14. Judging a generator. Why likelihood isn't enough (Theis, van den Oord & Bethge 2016); FID derived as the Fréchet (W₂) distance between Gaussians, 1D first (Dowson & Landau 1982; Heusel et al. 2017), on the features of our own digit classifier (its penultimate layer, 128 numbers); checks: FID against added noise and blur, and its bias against the sample size; precision and recall by k-nearest-neighbour balls (Sajjadi et al. 2018; Kynkäänniemi et al. 2019), drawn on the ring; every 2D family's precision and recall on the ring; a single Gaussian with the ring's mean and covariance (tiny Fréchet distance, low precision); memorization checked by nearest training digits.
  • 15. Five models, one budget. PixelCNN, VAE, GAN, WGAN-GP and RealNVP on 6 × 10¹² training FLOPs each: parameters, steps and digits seen; samples side by side; FID (mean and spread of three seeds), precision and recall; bits per pixel as reported likelihood scores, with their estimator/cohort qualifications below; which digits each model draws, by the classifier.
  • 16. Where the families meet. The 2021 turn (Dhariwal & Nichol: BigGAN-deep FID 6.95, precision 0.87, recall 0.28; guided ADM 4.59, 0.82, 0.52, ImageNet 256²); VQ-VAE (2017), VQGAN and DALL·E (2021): VAEs and GANs as tokenizers, autoregressive models over the tokens; our own VQ-VAE (49 tokens from 32 codes) with a small transformer prior; VAR's next-scale prediction (Tian et al. 2024: FID 1.73 vs 18.65, NeurIPS 2024 outstanding paper); GANs back inside fast samplers (ADD 2023, LADD 2024, DMD2 2024, R3GAN 2024, sCM 2024/25, drifting models 2026); the family tree.
  • Recap, where it comes back, problems, Part 21's teaser, references.
What is computed and builtHistorical reported results (earlier README)

The earlier README reported the following results for its published version. Its numbers and table rows are preserved here as historical reports, without claiming independently verified historical run dates, hardware or restored weights. They are separate from the 2026-11-02 results below. Means over seeds, ranges in brackets.

The plane. Reported entropy references: moons 1.758, ring 0.312, checkerboard 2.079 nats. Held-out NLL on the ring: autoregressive mixture model 0.33; RealNVP 0.68–0.80; energy model (finite-box grid-normalizer estimate) 0.61–1.67; VAE (importance-weighted bound) 2.52–2.55. Continuous flow on the moons: 1.846–1.863 trained with the exact trace, 1.850–1.871 with one Rademacher probe; in 196 dimensions one probe is 67× faster than the exact trace, and the probes' measured variances match the formulas (random signs: 0.47× the Gaussian probes' variance). Posterior collapse in 2D: factorized decoder rate 2.17–2.44 nats, autoregressive decoder 0.000–0.001.

GANs on the ring (five seeds each, same networks and generator steps): minimax loss 8, 8, 8, 8, 8 modes; non-saturating 8, 3, 8, 8, 1; WGAN-GP 8 in every seed, but only 64–70% of its samples within 3σ of a mode (82–88% for the non-saturating runs that did not collapse). The replay in chapter 5 is seed 4, the worst. Simultaneous gradient steps on xy spiral out by √(1 + η²) per step, 3.2× in 60 steps at η = 0.2 (asserted against the formula).

Precision and recall on the ring (k = 3, 2,000 points): autoregressive 0.97 / 0.98; RealNVP 0.78–0.84 / 0.96; WGAN-GP 0.63–0.71 / 0.93–0.96; energy model 0.37–0.83 / 0.98–0.99; non-saturating GAN 0.07–0.84 / 0.88–0.99; VAE 0.29–0.30 / 0.98–1.00. A single Gaussian with the ring's mean and covariance: Fréchet distance 0.002 (two samples of the ring itself: 0.004), precision 0.10.

Energy and memory. Hopfield (196 neurons, cues with 10% of bits flipped): every random pattern comes back up to 0.07 patterns per neuron, fewer than half from 0.15 on (theory: 0.138). Digits overlap far more: Hebb's rule recalls every digit only with up to two stored (the replay in chapter 11 therefore stores one), the softmax update (β = 8) every digit with up to four, and 30% of them with all ten. RBM with 16 hidden units, exact held-out log-likelihood after 4,800 updates: CD-1 −39.90, −39.94, −40.21; CD-10 −39.56, −39.58, −39.85; persistent CD −39.58, −39.58, −39.83 nats per digit. Langevin on two Gaussians (weights 0.2 / 0.8): plain chains end with 49% in the heavy mode (they started with 49%), annealed chains with 76%.

Digits, one budget (6 × 10¹² training FLOPs each, three seeds, 2,000 samples judged by a 98.86%-accurate classifier's 128 features; real digits score FID 1.05 against the test set):

model parameters steps FID precision recall bits per pixel
PixelCNN 56,368 1,551 47.1 (46.7–47.9) 0.51 0.83 0.857–0.859 (exact)
VAE 852,392 9,568 40.2 (36.4–42.6) 0.82 0.55 1.02–1.05 (IWAE bound)
GAN 241,093 16,380 53.8 (39.3–75.2) 0.75 0.40 —
WGAN-GP 241,093 3,011 46.7 (45.0–49.3) 0.52 0.70 —
RealNVP 1,205,856 6,589 28.0 (27.4–28.7) 0.77 0.84 1.13 (bound)

Historical reported amortized sampling time per image: PixelCNN about 70–80 ms (196 passes), the others well under 0.1 ms. These batch-throughput figures are not measured single-image latency. The GAN pair is 256 units wide: in a pilot at 512 units the budget bought only 5,133 generator steps and the samples stayed speckled (FID 110–119), so the width was halved before the final runs (both GANs, to keep their comparison fair); the GANs train on the 16 grey levels themselves, not on dequantized pixels. β-VAE (quarter budget, two seeds): rate falls from 23.5 nats (β = 0.25) to 0.0 (β = 8) while distortion rises from 142 to 248 nats. PixelVAE (half budget): plain, rate 1.3 nats per digit (against 13–14 for the plain VAE) and 12.5% of decodes keep the source digit's class (chance is 10%); with free bits of 1 nat per code number, 14.9 nats and 31.8%. VQ-VAE: 32 codes, perplexity 21.2, a 7 × 7 grid is 245 bits raw and 131 bits under the transformer prior; two-stage FID 67.4.

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. The generative problem.
  2. Autoregressive (PixelCNN).
  3. VAEs: ELBO, posterior collapse, β-VAE.
  4. GANs: the optimal discriminator → Jensen–Shannon; mode collapse; non-saturating loss; GAN dynamics as a rotating vector field.
  5. WGAN via Kantorovich–Rubinstein; gradient penalty; StyleGAN.
  6. Normalizing flows: change of variables, coupling layers, triangular log-det.
  7. Neural ODEs and continuous flows (trace, Hutchinson).
  8. Energy-based models: Hopfield and Boltzmann machines (the 2024 Nobel), contrastive divergence, Langevin sampling → the score.
  9. Evaluation: FID derived as Fréchet distance between Gaussians; precision/recall for generators.

Visuals: flows warping a grid; the GAN two-player field spiralling.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答

1. 最优判别器。 证明:对一个分布为q的固定生成器,最好的判别器是 D* = p/(p + q),并且 V(D*, G) = −log 4 + 2 JS(p‖q)。

解答

V = ∫ [p log D + q log(1 − D)] dx;在每个x处,被积函数 a log y + b log(1 − y) 的导数是 a/y − b/(1 − y),在 y = a/(a + b) 处为零,二阶导数为负,所以这是最大值:D* = p/(p + q)。代回去,V = E_p[log p/(p + q)] + E_q[log q/(p + q)]。 记 p + q = 2m,m = (p + q)/2:每一项都是 E[log p/m] − log 2,所以 V = KL(p‖m) + KL(q‖m) − log 4 = 2 JS(p‖q) − log 4, 当且仅当 q = p 时取到最小值 −log 4。

2. ELBO的差距,以及坍缩。 证明 log p(x) − ELBO = KL(q(z|x)‖p(z|x))。如果解码器不用z也能精确表示p(x),证明 q(z|x) = p(z) 使ELBO最大。

解答

ELBO = E_q[log p(x, z) − log q(z|x)] = E_q[log p(x) + log p(z|x) − log q(z|x)] = log p(x) − KL(q(z|x)‖p(z|x))。 如果解码器忽略z、并且等于p(x),那么 p(x|z) = p(x),真实后验就是先验,ELBO = log p(x) − KL(q(z|x)‖p(z)),至多为log p(x), 当 q(z|x) = p(z) 时取等号。任何对z的使用,换来的重建收益都必须超过它在KL上的代价;一个什么都不需要z的解码器,用z就什么也得不到。

3. 耦合层。 对 y_a = x_a,y_b = x_b ⊙ exp(s(x_a)) + t(x_a),证明 log|det J| = Σᵢ sᵢ(x_a),并写出逆变换。

解答

∂y_a/∂x_a = I,∂y_a/∂x_b = 0,所以J是分块下三角矩阵,对角块是I和diag(exp(s(x_a)));它的行列式等于对角线之积, exp(Σ sᵢ),为正。逆变换:x_a = y_a(直接复制),然后 x_b = (y_b − t(y_a)) ⊙ exp(−s(y_a));s和t从不需要求逆,只需要计算。

4. 哈钦森估计量。 证明当 E[εεᵀ] = I 时 E[εᵀAε] = tr A。对拉德马赫ε(分量取±1),证明方差是 2 Σ_{i≠j} S_ij²,其中 S = (A + Aᵀ)/2。

解答

E[εᵀAε] = Σ_ij A_ij E[εᵢεⱼ] = Σᵢ A_ii。由于 εᵀAε = εᵀSε,把它写成 Σᵢ S_ii εᵢ² + Σ_{i≠j} S_ij εᵢεⱼ; 取正负号时 εᵢ² = 1,所以第一项是常数tr A,方差就是 Σ_{i≠j} S_ij εᵢεⱼ = 2 Σ_{i<j} S_ij εᵢεⱼ 的方差。乘积 εᵢεⱼ(i < j) 均值为0、方差为1,并且两两不相关,所以方差是 4 Σ_{i<j} S_ij² = 2 Σ_{i≠j} S_ij²。(对高斯ε,对角项也会变化,再加上 2 Σᵢ S_ii²:总共是 2‖S‖_F²。)

5. RBM的条件分布。 对二值单元的 E(v, h) = −bᵀv − cᵀh − vᵀWh,推导 p(h_j = 1 | v) = σ(c_j + W_{:j}ᵀv),以及自由能 F(v) = −bᵀv − Σⱼ log(1 + exp(c_j + W_{:j}ᵀv))。

解答

p(h | v) ∝ exp(cᵀh + vᵀWh) = Πⱼ exp(h_j (c_j + W_{:j}ᵀv)):这是对j的乘积,所以给定v时各h_j独立, p(h_j = 1 | v) = e^{aⱼ}/(1 + e^{aⱼ}) = σ(aⱼ),其中 aⱼ = c_j + W_{:j}ᵀv。把h求和消掉, Σ_h e^{−E(v,h)} = e^{bᵀv} Πⱼ (1 + e^{aⱼ}) = e^{−F(v)},F如上所述。

6. 一维高斯之间的2-瓦瑟斯坦距离。 证明 W₂²(N(μ₁, σ₁²), N(μ₂, σ₂²)) = (μ₁ − μ₂)² + (σ₁ − σ₂)²。

解答

在一维里,最优耦合是单调的,分位数对分位数:x₂ = μ₂ + (σ₂/σ₁)(x₁ − μ₁)。令 x₁ = μ₁ + σ₁ζ,ζ ~ N(0, 1),则 x₁ − x₂ = (μ₁ − μ₂) + (σ₁ − σ₂)ζ,所以 E(x₁ − x₂)² = (μ₁ − μ₂)² + (σ₁ − σ₂)²。这正是FID公式 ‖μ₁ − μ₂‖² + tr(Σ₁ + Σ₂ − 2(Σ₁^{1/2}Σ₂Σ₁^{1/2})^{1/2}) 在 d = 1 时的情形。

Build the film

python -m videos.ai.ai20.compute        # the part's numbers, into .cache/ai20
python tools/build.py ai20                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai20 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/ai/ai20. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it

From the repo root:

python tools/make.py ai20                       # everything: the computations, then English and Chinese
python -m videos.ai.ai20.compute                # only the numbers (MNIST through Part 10's checked download)
python tools/build.py ai20                      # English
python tools/build.py ai20 --lang zh            # Chinese
AI20_SCALE=0.01 python -m videos.ai.ai20.compute   # a smoke test (into .cache/ai20_sampling_v2_quick/)

Everything is seeded (numpy PCG64 and torch.manual_seed, one generator per run) and runs on one torch thread (AI20_THREADS to change it); there is no multiprocessing. Every item made of several runs saves each run as it finishes (CACHE.partial); this reuses completed pieces, not an interrupted seed's optimizer state. Weights go to .cache/ai20_sampling_v2/models/; incompatible partials require reconciliation. The earlier README reported about two and a half hours on a busy 4-core machine. That is a historical runtime claim, not a measurement or hardware description of the 2026-11-02 experiments. MNIST uses Part 10's SHA256-checked consumer. Those experiments combine the original analytic products, same-day paired model states and new runs; they do not retrain every item or recover historical benchmark weights. See the versioned-cache section before requesting computation or rendering.