Randomness in Motion
What does it mean for a model to hand us a distribution, and how do we draw from it?
Six hundred random dots flow into the letters 'AI': a diffusion model in miniature, and the place the part is heading. It starts with the bell curve, from Bernoulli's law of large numbers and a Galton board to the central limit theorem as repeated convolution, then Gaussians in many dimensions and conditioning. Fitting follows: maximum likelihood and its bias, Fisher information and the Cramer-Rao bound, Bayes's rule with a Gaussian prior as weight decay, and maximum entropy, which yields the softmax. Markov, Chebyshev, Chernoff and Hoeffding bound how far an average strays. The part turns from describing distributions to drawing from them: inverse-CDF, rejection, Box-Muller and the Gumbel-max trick, then temperature, top-k, top-p and min-p on GPT-2's next-word distribution. Markov chains, Monte Carlo, score-function gradients, Metropolis-Hastings and Langevin dynamics sample what cannot be sampled directly. It ends in continuous time: Brownian motion, Ito's lemma, stochastic differential equations and the Fokker-Planck equation, with the reverse-time SDE that ran the opening.
What you need. Integrals of one variable; the entropy of Part 1, the matrices of Part 3 and the gradients and Lagrange multipliers of Part 4.
- Mathematics and history
- Gaussians, MLE and Bayes, exponential families, concentration, sampling and decoding, Markov chains, Monte Carlo, MCMC, Brownian motion, SDEs, Fokker–Planck
What you will be able to do
Undergraduate
- Explain why sums of many small independent effects look like a bell curve, and fit a mean and a spread by maximum likelihood.
- Update a belief with Bayes's rule, and say how a prior acts as regularization.
- Describe what temperature, top-k and top-p each do to a next-token distribution.
Master's
- Derive the conditional of a multivariate Gaussian, the Cramer-Rao bound, and the maximum-entropy distribution under a mean constraint.
- Derive Hoeffding's inequality from Markov's, and the Gumbel-max trick.
- Derive Metropolis-Hastings from detailed balance, and the score-function gradient with a baseline.
Research
- Derive Ito's lemma from the quadratic variation of Brownian motion, and the Fokker-Planck equation from Ito's lemma by integration by parts.
- Bound a reversible chain's mixing time by its spectral gap, and state the strong and weak orders of the Euler-Maruyama scheme.
Engineering
- Choose and report a decoding rule, measuring surprise, diversity and repetition rather than likelihood alone.
- Diagnose an importance-sampling or score-function estimate by its effective sample size and variance, and reduce the variance with a baseline or reparameterization.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 22 min · Master's 49 min · Research 55 min · Engineering 29 min.
- 0Out of noiseUndergraduate2 min
- 1The bell curveUndergraduate3 min
- 2Bells in many dimensionsMaster's3 min
- 3Fitting a bell: maximum likelihoodUndergraduate3 min
- 4How precise can an estimate be?Master's4 min
- 5Belief as a distributionUndergraduate3 min
- 6Maximum entropyMaster's3 min
- 7How far from the average?Master's3 min
- 8Rolling loaded diceUndergraduate3 min
- 9How a language model choosesEngineering3 min
- 10Chains with short memoriesMaster's3 min
- 11Answers from random samplesUndergraduate3 min
- 12The gradient of an averageEngineering3 min
- 13Sampling the unsampleableMaster's3 min
- 14Brownian motionUndergraduate3 min
- 15Itô's lemmaResearch3 min
- 16Randomness with a pushMaster's2 min
- 17The density's own lawResearch3 min
- Recap, problems, and what comes nextAll tracks3 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.
Out of noiseUndergraduate2 min
Here are six hundred dots, scattered completely at random. Now let each one wander. Each step adds a random kick and a drift: the current position divided by two, plus the score. The green arrows show only score directions, with their lengths rescaled. Watch what the randomness builds.
This is, in miniature, how today's image and video generators work. They start from noise and let it flow, one random step at a time, into a picture. Here the score is computed exactly from our toy letter distribution. A generative model learns the score component; the other drift term is already known. We'll build it in part twenty-one.
Run it the other way, with the arrows gone, and the letters dissolve back into noise. Both directions are random motion, and the same mathematics describes them.
The mathematics is older than computers. It began in 1654, in letters between Pascal and Fermat about splitting the stakes of an unfinished game. Bernoulli proved that averages settle; de Moivre found the bell curve; Bayes and Laplace reasoned from effects back to causes; Gauss fitted orbits. Einstein explained the jiggling of pollen, Fisher made likelihood the way to fit models, and Ito gave random motion its own calculus. At Los Alamos the first computers were set to sampling, and today the same ideas choose a chatbot's every word and turn noise into pictures.
This is Part 5 of AI, Built, the last of the foundations. In it: why sums are bell-shaped, in one dimension and many; fitting, precision and belief; how far averages stray; drawing samples, and how a language model picks a word; Markov chains and Monte Carlo; and random motion, with a calculus of its own. Every result is computed here, on a laptop.
1The bell curveUndergraduate3 min
Flip a fair coin and track the share of heads. Six runs of five thousand flips all settle toward a half, here between 0.489 and 0.512: Jacob Bernoulli's law of large numbers, published in 1713. How far off is a run after n flips? About one over the square root of n, and the shape of that scatter is this chapter's subject.
Here is the scatter made visible: balls dropped through twelve rows of pegs, bouncing left or right, fifty-fifty. Where one lands counts its right bounces. Eighty start to show a shape.
A thousand make it unmistakable. Counting paths gives the exact chances: twelve choose k, out of two to the twelve. The smooth curve hugging them is the bell, the normal distribution, with a centre mu and a width sigma, here six and the square root of three. De Moivre found it in 1733, as the limit of exactly these counts.
Why a bell, and why so often? One die: six flat bars. Two dice: a triangle. Three: already rounding off. Six, twelve: the bell. That's the central limit theorem: add independent draws from the same distribution, with positive finite variance. After centering and rescaling, the sum approaches a bell, with a spread that grows like the square root of their number. Laplace proved it in 1810.
Why? Two dice add up to s in every way of splitting s: x on one die, s minus x on the other. For densities the sum becomes an integral, a convolution. Picture it with a lopsided piece, the exponential. Flip a copy, slide it to s, multiply: the area of the overlap is the density of the sum at s. Slide s along, and the area traces out the density of two pieces. n pieces take n minus one convolutions.
So convolve again and again. One exponential, all on one side. Two, three, five: each convolution smooths and spreads it. Ten, thirty: the lopsidedness fades, and what is left is the bell. Among nondegenerate distributions with finite variance, the bell is the only shape preserved when independent copies are added and then centered and rescaled.
How fast does the bell arrive? Measure the largest gap between the sum's cumulative distribution and the bell's. For the exponential it falls on a line of slope : the gap shrinks like one over the square root of n, after sixty-four pieces. That is the Berry-Esseen theorem: the gap is at most a constant times the third absolute moment over the cube of the spread, over the square root of n, and the measured gap sits under it.
2Bells in many dimensionsMaster's3 min
Start with the simplest cloud in the plane: two independent standard bells, one along each axis. Every Gaussian in any dimension is this, put through a linear map: x equals mu plus L times z. The map is summed up by the covariance, sigma, which is L times L transposed: how each pair of coordinates moves together. The density's contours are ellipses, with their axes along the eigenvectors of the covariance and lengths set by the square roots of its eigenvalues, straight out of part three.
Now the question that matters for prediction: if we learn some coordinates, x b, what is left of the others, x a? With x b fixed, the conditional density is the joint density, rescaled. Its log is a quadratic form in the inverse of the covariance, called the precision. Collect the terms in x a and complete the square: a bell again, with precision lambda a a. Inverting the covariance in blocks gives its covariance: sigma a a minus sigma a b sigma b b inverse sigma b a, the Schur complement. And its mean moves from mu a by a linear function of what we learned.
Check it on samples. Draw four hundred thousand points and keep the ones in a thin strip where x two is . Their x one values form a bell. The formulas predict its mean, , and its variance, ; the points in the strip give and . Slide the strip, and the conditional mean traces a straight line. Galton drew it in 1886 for the heights of parents and children, and called it regression: tall parents have children who are tall, but less so.
This one formula does a great deal of work. In 1960, Rudolf Kalman used it to track a moving object, conditioning on each new measurement; his filter navigated Apollo. A Gaussian process puts a bell over whole functions, and fitting it to data is this conditioning. In diffusion training, the clean sample is also given: the posterior of the previous noisy step is then exactly Gaussian. The learned reverse step does not know that clean sample; a Gaussian transition is an approximation, not this exact posterior.
3Fitting a bell: maximum likelihoodUndergraduate3 min
Here are the thousand balls again. Which bell describes them best? Try one. Score it like this: at each ball, read off the bell's height. That height is a probability density: how crowded the outcomes are there. Make a histogram's bars narrower and narrower, and it becomes a smooth curve like this one; the area under it between two points is the probability of landing between them. Take the log of the height, and average over all the balls. That's the log-likelihood: how well this bell predicted where the balls actually went. A bell in the wrong place scores badly. So does one that's too narrow, or too wide. The best bell, the maximum likelihood fit, is the one under which the data was least surprising.
Score every possible bell, every centre and every width, and the scores form a landscape. In this Gaussian example, follow the gradient uphill toward the analytic optimum. A general likelihood can have several peaks; a local climb alone does not certify its top. At the summit, the centre is the balls' average, , and the width is their spread, , close to the square root of three that the pegs predict. For a bell, maximum likelihood comes out as the two most natural summaries of the data.
And here's the connection to everything else. Maximizing the average log-likelihood is the same as minimizing the average surprise, and that's part one's cross-entropy, measured against the data. Maximum likelihood is minimum cross-entropy. It's how every model in this series is trained, from a bell curve to a language model.
Is maximum likelihood right on average? For the centre, yes. For the spread, no. Measure spread around the sample's own average and you lose a little: the average sits closer to the data than the true centre does. On average, the loss is exactly one sigma squared, so the maximum-likelihood variance is too small by a factor n minus one over n. The bias fades as n grows. Fisher, who named likelihood in 1922, cared less about bias than about efficiency: how small the error can be. That is the next chapter.
4How precise can an estimate be?Master's4 min
Here is a distribution with heavy tails, the Cauchy. It looks like a bell, but its tails are so heavy that it has no average: now and then a draw lands absurdly far out. Try to estimate its centre from a hundred draws. The sample average is useless: its spread never shrinks; the middle half of the averages spans at draws and still at . The median concentrates around the centre. The orange curve uses a multistart likelihood fit: the best candidate found from several starting points. That search does not certify the global maximum. How should we compare these computations with a theoretical precision limit?
For regular models and unbiased estimates, there is a variance bound. Fisher found the key in 1925. The score is the slope of the log-likelihood in the parameter: how much each observation pulls the estimate. When differentiation can pass under the integral, it averages to zero at the true value, because the density always integrates to one. Its variance is the Fisher information: how sharply the data pins theta down. For the Cauchy it is one half; over two hundred thousand draws we measure . For n independent draws, sum the scores into S n. Its variance is n times the information of one draw. An unbiased estimate moves one for one with theta, so its covariance with this total score is one. And Cauchy-Schwarz says a covariance squared is at most the product of the variances. So no unbiased estimate can have variance below one over n times the information: the Cramer-Rao bound, proved by Rao in 1945 and Cramer in 1946.
Now compare the computation with theory. Multiply each estimate's variance by n. The line at two is the Cramer-Rao benchmark for unbiased estimates in this regular independent-sample model. At draws the median's measured value is . Its large-sample value is pi squared over four, about percent above two. Our multistart likelihood fit gives at draws; We keep the best candidate found and check stationarity separately; the global maximum is not certified. Fisher's efficiency theorem concerns a consistent maximum-likelihood estimator under standard regularity conditions: its large-sample asymptotic variance is the inverse information. This is neither a finite-sample promise for biased estimators nor a certificate for our numerical search.
With many parameters, the information becomes a matrix: the average outer product of the score. In 1998 Shun-ichi Amari proposed measuring steps of gradient descent by it, so that a step is judged by how much the model's predictions change, not its weights: the natural gradient. In 2017, elastic weight consolidation used it to protect what a network had learned. And today's curvature-aware optimizers approximate it, or a close cousin, layer by layer. Part eleven picks them up.
5Belief as a distributionUndergraduate3 min
How often is a letter an e? Before reading anything, we have no idea: any fraction from zero to one seems as plausible as any other. That's a belief, and we can draw it, as a flat line over every possibility. Bayes's rule, from Thomas Bayes's essay of 1763 and found again by Laplace in 1774, says how to update a belief when evidence arrives. Multiply what you believed by how well each possibility explains the evidence, then rescale, so the total is one again. That's what the sign, proportional to, means: equal, up to that rescaling.
Read the first ten letters: 3 e's. The belief leans toward 0.3, but it's still wide. After a hundred letters, it's narrower. After a thousand, narrower still. After ten thousand, it's a sharp peak near 0.127: ninety-five percent of the belief lies between 0.120 and 0.134. The whole passage, all 16,322 letters, gives 0.122, inside that range.
Why did the belief keep this shape? Each letter multiplies in theta or one minus theta, so after k e's in n letters the likelihood is theta to the k, times one minus theta to the n minus k. Start from a prior of the same shape, a Beta distribution, and the exponents simply add: the belief stays a Beta, and updating is counting. Its mean is k plus a over n plus a plus b: the prior acts like a imagined e's and b other letters. With a flat prior that is Laplace's rule of succession from 1774: k plus one over n plus two, 0.33 after the first ten letters. Different priors start apart, and the same letters pull them together: by ten thousand letters, they agree.
A belief can also be used to pick a single answer: the peak of the posterior, called MAP, maximum a posteriori. Put a Gaussian prior on a model's weights, saying small weights are likelier, and Gaussian noise on its outputs. The MAP answer minimizes squared error plus lambda times the squared size of the weights: the weight decay used to train nearly every network, with lambda the noise over the prior's spread, squared. Ten points from a sine wave, and a polynomial of degree nine. Maximum likelihood threads every point and swings wildly between them. The prior tames it.
6Maximum entropyMaster's3 min
Here is a puzzle from the physicist Edwin Jaynes. A die is loaded so that its faces average four and a half instead of three and a half. What is the chance of each face? Infinitely many dice have that average: this one, this one, this one. Jaynes's answer: pick the one that assumes nothing else, the one with the most uncertainty left, measured by part one's entropy. Anything less spread out claims knowledge we do not have.
Finding it is part four's constrained optimization. Maximize the entropy, subject to two constraints: the chances add to one, and they average four and a half. Give each constraint a Lagrange multiplier. Setting the derivative to zero makes the log of each chance a straight line in the face: the chance of face k is e to the lambda k, divided by a normalizer, Z. The only unknown is lambda, and the derivative of log Z is the average, so one equation fixes it.
Solving that one equation is a tiny training run. Start from the fair die, with lambda zero, and nudge lambda by how far the average is from four and a half. The die tilts toward its high faces, and settles at lambda : the chance of each face is about times the one below it. Its entropy is nats. Twenty thousand other dice with the same average, made at random: .
The same recipe gives the distributions this series keeps meeting. On the line, fix the mean and the variance, solve numerically, and out comes the bell: it is the most uncertain distribution with a given spread. Fix the average distance from zero instead, and you get Laplace's double exponential. Fix the average energy of a physical system, and you get Boltzmann and Gibbs's distribution, e to the minus energy over temperature, where inverse temperature is the Lagrange multiplier, with Boltzmann's constant set to one. With scores in place of negative energies, that is the softmax at the end of every language model. All of them are one family, the exponential family, and in it the gradient of the log normalizer is the average. So fitting one by maximum likelihood just matches the data's averages.
7How far from the average?Master's3 min
The law of large numbers says an average settles. Learning from data needs more: how often is it still far off? A million runs of a hundred fair flips. The share of heads reaches in a fraction of them. Here we can count, but a model's test data never shows us this picture. For independent draws, we need a guarantee that holds whatever the distribution's shape, knowing that each value lies between zero and one.
Each bound comes from the one before. Markov's: a quantity that is never negative can't often be much bigger than its average. Apply it to the squared distance from the mean: Chebyshev's, the variance over epsilon squared, and an average of n has n times less variance. Chernoff's idea: apply Markov to e to the t times the sum; independence splits it into a product, and the tail falls exponentially in n. For values between zero and one, Hoeffding's lemma bounds each factor, and the best t gives e to the minus two n epsilon squared: Hoeffding's inequality, from 1963.
Now put them against the truth, on a log scale. The exact tail, and a million simulated runs on top of it. Markov's bound hardly falls at all; at epsilon of it allows . Chebyshev's falls like one over epsilon squared: . Chernoff's and Hoeffding's fall exponentially, and nearly coincide here: and . Hoeffding's is still times the true : a conservative bound rather than the exact binomial tail.
Turn it around. How many flips guarantee that the share overshoots by at most percent of the time? Chebyshev's bound asks for ; Hoeffding's, ; Chernoff's, . For fair coins the smallest qualifying fixed sample size is . Integer coin counts make the exact tail oscillate: every sample size from onward qualifies. The best bound asks for times the minimum; bounds are conservative, even for known fair coins. Part eight uses exactly this to bound a model's true error from its test score, and part twenty-six used Hoeffding's bound to explore.
8Rolling loaded diceUndergraduate3 min
A model never hands us a word, only a distribution, and to write anything we must roll loaded dice. Lay the probabilities end to end from zero to one, so each letter owns a stretch as long as its probability. Pick a uniform random point and take the letter it lands in: the inverse of the cumulative distribution. These are drawn from part one's letter frequencies.
The same trick works for continuous distributions. For the exponential, x is minus the log of one minus u: twenty thousand draws match the density, with a largest CDF gap of 0.006. When the inverse is hard to compute, John von Neumann's rejection method of 1951 needs only the density: scatter points uniformly in a box over the curve, and keep the ones under it. The kept points follow the density. The price is waste: 40.3 percent are kept, one over the box's height, as predicted, and in many dimensions that share collapses.
The bell itself has no simple inverse CDF, but a pair of bells does, in polar coordinates. Two independent bells have a density that depends only on the distance from the centre. So the angle is uniform, and the squared radius, halved, is exponential, which we just learned to draw. Two uniform numbers in, two independent bells out: the Box-Muller transform of 1958.
One more trick, used constantly in machine learning. To pick option i with the softmax of its score, add independent Gumbel noise to each score, minus the log of minus the log of a uniform number, and take the largest. The winner follows the softmax exactly: the Gumbel is the shape of maxima. Two hundred thousand picks against the softmax: It needs only the scores, never the normalizer, and turns sampling into maximization.
Sampling can't be differentiated: a pick is a pick. In 2017 two groups proposed relaxing it. Replace the argmax by a softmax with a temperature, tau: the Gumbel-softmax. Cold, at a tenth, each draw is nearly a one-hot pick, its largest entry 0.95 on average. At one it is softer, and at five it is a blur, 0.25. The temperature trades faithfulness for smooth gradients; it trained the discrete codes of the first DALL-E.
9How a language model choosesEngineering3 min
A language model ends every step with a distribution over its vocabulary, and decoding picks from it. Here's GPT-2's distribution for the token after: Spade sat down in the armchair, and. Its favourite gets only percent. The first dial is temperature: divide the scores by T before the softmax, the Gibbs distribution of chapter six.
Turn it down, below one, and the distribution sharpens toward the favourites. Turn it up, and it flattens, until any token at all might come next. The entropy follows the dial: bits at a half, at one, at two.
Here's what comes out. Always taking the favourite is safe and flat. At a half, still sensible. At one, sampling the model's own distribution, it's stranger and more varied. At two, it falls apart: the tail of fifty thousand unlikely tokens, each tiny, together wins too often.
Temperature reshapes the distribution, but the long tail of unlikely tokens is always there. The other dials cut it off. Two real moments for GPT-2: an open one, where the favourite has percent, and a nearly certain one, where it has . Top-k keeps a fixed number of tokens: too many in the second case, too few in the first. Top-p, nucleus sampling, keeps the fewest tokens whose probabilities add up to p, so the cut adapts: at nine tenths it keeps tokens in the open case and in the certain one. Min-p keeps every token at least a fraction as likely as the favourite: at a tenth, and .
Which rule writes best? We tested them on the series' own small model, trained on the thirty novels: held-out passages, sampled continuations per passage for each stochastic setting, and one greedy continuation per passage: settings total. A larger model, GPT-2, scores separately tokenized continuations in nats per continuation character. ; percent of its four-token runs repeat, against at most percent for any sampled setting. Likelihood alone does not measure text quality.
Here is one passage, continued four ways. Pure sampling uses the untruncated distribution. The other examples restrict its tail. Min-p, proposed in 2024 to allow higher temperatures, was challenged by a 2025 re-analysis that found its evidence weaker than reported. Part nineteen adds the other half of decoding: constraining what may be written at all.
10Chains with short memoriesMaster's3 min
A Markov chain is randomness with a short memory: what comes next depends only on where you are now. Here's one built from part one's letters, with three states: a space, a vowel, or a consonant. The arrows carry the chances of what comes next: after a vowel, a consonant 71 percent of the time. Follow one walker, and count the time it spends in each state.
Keep going, and the shares settle: 19 percent spaces, 31 percent vowels, 50 percent consonants, as in the books. Markov did exactly this by hand in 1913, with twenty thousand letters of Pushkin.
Follow the whole distribution instead of a single walker, and each step is a multiplication by the table of chances, the transition matrix. The distribution that a step leaves unchanged is the chain's stationary distribution. It's an eigenvector of the matrix, with eigenvalue one, straight out of part three.
Now all twenty-seven letters, with part one's full table. Start from certainty: the letter q. One step later, it's almost surely a u. Then the possibilities spread out, and within 5 steps the chain has forgotten where it started: what's left is the letter frequencies. How fast it forgets is set by the matrix's second-largest eigenvalue, 0.30 here: each step shrinks the distance left by roughly that factor.
There is an easy way to know a distribution is stationary. Suppose that, in it, as much probability flows from i to j in one step as from j to i: detailed balance. Sum over i, and pi times P is pi: balanced flows mean nothing changes. It's enough, not necessary. English isn't balanced: then is times as common as then . But when we build chains to sample, in chapter thirteen, detailed balance is how we make them land where we want.
One minus the second eigenvalue is the spectral gap, and a chain with a bottleneck has a tiny one. Here is a walk on forty-one sites, aimed at a distribution with two wells and a barrier between them, starting at the left end. The left well fills within a few hundred steps, but after 300,000 steps the right well is still filling. Raise the barrier and the gap shrinks. Against one over the gap, the steps to mix rise along a line of slope 0.98, from 638 to 26,284,798, between the theory's two bounds. Stuck chains are the central difficulty of chapter thirteen.
11Answers from random samplesUndergraduate3 min
The method was born at Los Alamos. In 1946 the mathematician Stanislaw Ulam, recovering from an illness, wondered how often solitaire comes out, and saw it was easier to play a hundred games and count. John von Neumann turned the idea into a way to follow neutrons through a bomb core, and in 1948 Klara von Neumann and Nicholas Metropolis ran it on ENIAC. Metropolis named it after the casino.
Here's a strange way to compute pi: throw darts at a square, completely at random. The share inside the circle is the circle's share of the area, pi over four, so four times that share estimates pi. Watch it as the darts pile up: it lurches, then homes in.
After four thousand darts: 3.158. The shaded band is how far off a run like this typically is, and it narrows like one over the square root of the number of darts.
Repeat the experiment many times at each size and measure the typical error. On log scales it falls on a line of slope -0.50. The error shrinks like one over the square root of the number of samples: each extra digit costs a hundred times more. That's slow, but the rate doesn't care about dimension: it is the same in a million dimensions, where any grid would be hopeless.
Monte Carlo has one weakness: rare events. How often does a standard bell land above four? Exactly, about times in a hundred thousand. The rug shows the first four hundred recorded direct draws, plus every rare hit from the full run.
The fix is to cheat, and then correct for it. Draw from a bell that lands out there half the time. Then weight each sample by how much likelier it is under the real distribution than under the one you drew from. The proposal rug shows its first four hundred recorded draws. Both estimates use all draws each. For importance sampling, A single run is evidence, not a guarantee of improvement.
Importance sampling has a weakness of its own: the weights. This weight-based effective sample size diagnoses their concentration; it always lies between one and n. Aim at a bell with a proposal just percent wider. In one dimension, of samples count; in fifty, ; in two hundred the diagnostic says . The population-moment, large-n proxy is . Rare large weights can be missing from a finite run, so the diagnostic alone does not certify accuracy. That is why reinforcement learning clips its importance ratios, in part twenty-six.
12The gradient of an averageEngineering3 min
Much of machine learning ends with an average over random choices: the expected reward of a policy, the expected score of a sampled answer. We want its gradient, to improve the model. But the thing being averaged may have no slope at all: a reward that switches on and off, a judge who says yes or no. Only the distribution moves smoothly as the parameters change. How do we differentiate through the sampling?
Move the gradient inside the integral: only the density depends on theta. Then the log-derivative trick: the gradient of p is p times the gradient of log p, and the gradient is again an average, of f times the score, which we met in chapter four. Sample, and average. f itself is never differentiated. And since the score averages to zero, any constant b can be subtracted from f without changing the answer: a baseline. Peter Glynn called this the likelihood-ratio method in 1990; Ronald Williams made it a learning rule for neural networks in 1992, REINFORCE.
The catch is noise. Take a case we can check: the gradient of the average of x squared, for a bell centred at one; the answer is two. The estimator gets it right on average, over samples, but one sample's estimate has a variance of . A baseline cuts that. Its variance-minimizing value weights f by the squared score; here it is , and brings the variance to . When f does have a slope, there is a better way: write the sample as mu plus noise and differentiate through it, the reparameterization trick, with variance . Variational autoencoders train that way, in part twenty; rewards and judges need the score function.
The same estimator trains models with no gradient at all. Smooth f by adding noise to the parameters, and its gradient is an average of f at random probes, times the probe: evolution strategies, used by Salimans and colleagues at OpenAI in 2017 to train simulated robots and Atari players. Here it descends a curved valley, sixteen probes a step. We correct the same-batch baseline by N over N minus one to keep the iid estimate unbiased. Measured against the smoothed objective at the start, the mean squared error of one estimate is without it and with it; the gradient's squared norm is . Reinforcement learning's policy gradients are this estimator, with baselines, in part twenty-six.
13Sampling the unsampleableMaster's3 min
Markov chain Monte Carlo. Often there's no direct way to draw samples: all we can do is evaluate how likely each point is, and only up to an unknown constant, as with Bayes's rule. Here's a density with two bumps. In 1953 at Los Alamos, Nicholas Metropolis, Arianna and Marshall Rosenbluth, and Augusta and Edward Teller, computing on the MANIAC, found a way to sample anything like it: take a random walk. Propose a small random step. If it goes uphill, take it. If downhill, take it with probability the ratio of the heights; otherwise stay put.
Only the ratio appears, so the unknown constant cancels. Keep walking: the visits pile up like the density, because this Markov chain's stationary distribution is the one we wanted. This made Bayesian statistics practical in the 1990s, and physicists still sample molecules this way.
Why does it work? Chapter ten's detailed balance. A step from x to y is proposed with probability q, then accepted with probability a. Balance asks that the flows match, which fixes only the ratio of the acceptances. Make the larger one equal to one: W. K. Hastings's rule of 1970, for any proposal. With a symmetric proposal the q's cancel, and it is Metropolis's rule.
There is another way to explore, from physics. In 1908 Paul Langevin wrote a particle's motion in a fluid as a push plus random kicks. Make the push the score, the slope of log p, uphill toward likelier places, and the kicks Brownian; in small steps it is one line of code. Fifteen hundred particles start as noise; above them, their density. It moves under the score. For occupancy, The continuous-time process has p as an invariant distribution, as chapter seventeen proves under regularity conditions. Mixing takes time, and the finite-step unadjusted scheme can bias equilibrium. With mini-batch scores it sampled neural networks' weights in 2011, and with learned scores, the first score-based image models.
How well do they mix? Run four samplers for twenty thousand steps each, five times, and follow one coordinate. The table reports post-burn-in hops and the coordinate's variance conditional on x less than zero. For the variance, For MALA's variance, The Metropolis correction preserves the target distribution; a finite chain still needs to mix. Hop counts alone do not identify why transitions are rare. Part twenty-one samples blurred versions first.
14Brownian motionUndergraduate3 min
In 1827 the botanist Robert Brown watched pollen in water jiggle, endlessly, for no visible reason. A model: a walk that steps up or down at random. Eight steps. Sixty-four smaller ones. A thousand and twenty-four. Shrink each step like one over the square root of their number, so that the variance, the average squared distance from the start, stays exactly t, and the walks settle into one random object: Brownian motion. Louis Bachelier used it for stock prices in 1900, and Norbert Wiener built it rigorously in 1923. It is continuous everywhere, and so jagged it has no slope anywhere.
Now draw sixty of them. At any moment, where they've got to follows a bell, centred at zero, with spread the square root of t. Twice the time gives about 1.4 times the spread, not twice: it's the central limit theorem again, the position being a sum of many tiny kicks. On twenty thousand paths the variances come out at 0.25, 0.49, 0.74 and 0.98: t.
Brownian paths have one more property that changes calculus. Square each tiny step and add the squares. For a smooth curve that sum vanishes as the steps shrink. For Brownian motion it climbs steadily along the line t. Each squared step has mean delta t and variance of order delta t squared, so the sum's mean is t and its spread vanishes. On four hundred paths: 0.99, give or take 0.32, with sixteen steps; 0.999, give or take 0.011, with sixteen thousand. The path's plain length, meanwhile, grows without limit: 102 already. In shorthand, dW squared equals dt: Paul Levy's theorem of 1940, and the rule behind the next chapter.
In two dimensions, a cloud released at one point spreads into a widening bell. Follow the density instead of the particles, and it obeys an equation with no randomness in it at all: the heat equation. Einstein worked this out in 1905 and used it to argue that molecules are real; a few years later Jean Perrin measured the jiggling, and counted them.
15Itô's lemmaResearch3 min
Ordinary calculus says the integral of W d W is one half W squared. For Brownian motion, it depends on where in each little step you evaluate W. Take the left point, the value before the step. A little algebra splits the sum in two. The first part telescopes to one half W squared. The second is half the sum of squared steps, which chapter fourteen showed is t, not zero. So the left-point integral is one half W squared minus one half. Over paths the left-point sums close in on it as the steps shrink, : their averages are and . The choice of point matters, which never happens for smooth curves.
The same thing changes the chain rule. Expand a function of W to second order. In ordinary calculus the squared term is negligible. Here dW squared is dt, the same size as everything else we keep: the chain rule gains a term, one half f double prime dt. That is Ito's lemma, and for any process with drift mu and noise sigma it reads like this. Check it on e to the W, path by path. With the extra term the gap closes as the steps shrink, at a slope of -0.56; without it, it stalls at about 0.79. And on average, e to the W at time one is 1.649, not one: the square root of e, 1.649, as the extra drift predicts.
This calculus has a dramatic history. In 1940, Wolfgang Doeblin, a young mathematician serving in the French army, mailed the Academy of Sciences a sealed envelope; he died that June, and when it was opened in 2000 it held a version of the same formula. Kiyosi Ito published the stochastic integral in 1944 and the formula in 1951. Black, Scholes and Merton priced options with it in 1973, and it is the working tool for running diffusion models in part twenty-one. Midpoints give Stratonovich's integral, with the ordinary chain rule. The left-point Itô integral uses only information available before each increment. Midpoint limits define a different integral, which also has numerical schemes; one must use the matching drift and interpretation.
16Randomness with a pushMaster's2 min
Brownian motion is pure jiggle. Add a push, and you have a stochastic differential equation. At each instant, the change in x is a push, f of x times dt, where dt is a tiny tick of time, plus a random kick: g times dW, the tiny piece of Brownian motion in that tick. To simulate one, take small steps: push, then kick, with a kick the size of the square root of the step.
The simplest interesting one is a spring pulling back toward zero, plus noise. Forty particles start at 2.5. The push pulls them home, the noise keeps them stirred, and they settle into a bell around zero, its width set by the balance between the two. Leonard Ornstein and George Uhlenbeck described it in 1930, and it is the forward process of diffusion models.
How good is that simple scheme? Test it where the exact answer is known: a quantity that grows by a random percentage each instant, geometric Brownian motion, the model of a stock price. With the same random kicks, coarse steps wander off the exact path, and fine steps follow it. Over paths: Gisiro Maruyama proved the scheme converges in 1955. Diffusion models' samplers are, at heart, this scheme run backwards, and part twenty-one spends chapters on doing better with fewer steps.
17The density's own lawResearch3 min
Chapter fourteen found the heat equation for a cloud of pure noise. With a push added, here is the general law, from Ito's lemma. Take any smooth test function phi of a process with drift f and noise g. Average: the random term has mean zero. Write the averages as integrals against the density p. Integrate by parts to move the derivatives from phi onto p. Since this holds for every phi, the integrands agree: the Fokker-Planck equation, a deterministic law for the density. Adriaan Fokker and Max Planck wrote it for molecules; Kolmogorov derived it in general in 1931.
Check it on the Ornstein-Uhlenbeck process. Start with data that has two peaks, and let every point drift toward zero and jiggle. Twenty thousand particles and the equation solved on a grid move together: the histogram densities stay within of the exact bin-average density, with both normalized on the shown window from minus four to four. The grid stays within of the exact answer. Wait long enough, and every trace of the data is gone: a plain standard bell. That's what a diffusion model does to its training images.
Now the promise from chapter thirteen. Langevin dynamics has drift the score of a target pi, and noise of variance two. Put that into Fokker-Planck. If the density is pi, the drift term gives minus pi double prime, the noise term plus pi double prime, and they cancel: pi is invariant for the continuous-time process, under the usual smoothness and boundary conditions. Reaching it also requires mixing. The finite-step particles of chapter thirteen only approximate this process; unadjusted discretization can shift the equilibrium.
Can the film run backwards, from the bell to the data? In 1982 Brian Anderson showed that, reversed in time, it is another stochastic differential equation. For the spatially constant noise coefficient used here, the reverse drift has one extra term: the score, the slope of the log of the density at that moment, an arrow saying which way the data gets likelier. It points uphill, toward the data.
Know the score at every noise level, every point on the slide from data into noise, and you can turn noise into data. It's the field of arrows from the start of this part. There, it was computed exactly from the letters. A diffusion model learns it from millions of images, with a network, and that's part twenty-one.
Recap, problems, and what comes nextAll tracks3 min
Let's take stock. Centered, rescaled sums of independent, identically distributed pieces with positive finite variance approach a bell. With a finite third absolute moment, Berry-Esseen bounds the gap by a constant over the square root of n. Conditioning a bell gives a bell. In regular models, maximum likelihood is asymptotically efficient: for our Cauchy fit, n times its measured variance is against the bound of two. Bayes's rule is counting, and a prior is a regularizer. Maximum entropy gives the exponential family, softmax included. Hoeffding's bound needed flips where sufficed, and held everywhere. Sampling turns uniform numbers into anything; decoding trades diversity for predictability. Chains forget at the rate of their spectral gap in the lazy reversible setting; Monte Carlo errors with finite variance fall like one over root n, and importance weights can collapse in high dimensions. Metropolis corrections preserve the target; fixed-step unadjusted Langevin can bias it. Random motion has its own calculus, whose density obeys Fokker and Planck's law.
All of this comes back. Maximum likelihood and Fisher information train the models of parts six and eleven. Bayes, Markov chains and their samplers return in part seven, and the concentration inequalities become generalization bounds in part eight. Decoding is extended in part nineteen. Score-function gradients and importance weights are reinforcement learning, in parts twenty-six and twenty-seven. And stochastic differential equations describe noisy training in part eleven and generation in parts twenty and twenty-one.
Here are six problems to try, from convolutions to the Ornstein-Uhlenbeck process's stationary bell. Pause here and work through them; full solutions are in this part's notes.
Next time, act two begins: learning from data. We start with the classics: least squares and its geometry, which is maximum likelihood under Gaussian noise; logistic regression; kernels and support vector machines; trees and boosting. They ran machine learning before deep learning, and on tables of data they still often win.
Blitzstein and Hwang's Introduction to Probability is a friendly place to start; MacKay's book has the best chapters on Monte Carlo methods, and Levin and Peres's on mixing. Thanks for watching, and see you in part six.
Where it goes next. Maximum likelihood and Fisher information return in Parts 6 and 11; Bayes, Markov chains and their samplers in Part 7; the concentration inequalities as generalization bounds in Part 8; decoding in Part 19; score-function gradients and importance weights in Parts 26 and 27; and SDEs as noisy training in Part 11 and as generation in Parts 20 and 21.
Key results
The part's results in one place, for revision.
Try it
Lab 5 · Particles against their density's own law
Simulate dx = -x dt + sqrt(2) dW from x = 2 with the Euler-Maruyama scheme, solve the Fokker-Planck equation for the same process on a grid, and compare both with the exact Gaussian solution; then take steps that are too large and predict the bias they cause.
python -m videos.ai.labs 5
needs numpy, scipy, matplotlib · download lab05.py ·
source on GitHubt = 0.25: mean, variance of 20,000 particles +1.562, 0.399 (exact +1.558, 0.393); KS distance 0.0058
t = 1.0: mean, variance of 20,000 particles +0.741, 0.862 (exact +0.736, 0.865); KS distance 0.0041
t = 3.0: mean, variance of 20,000 particles +0.096, 1.004 (exact +0.100, 0.998); KS distance 0.0050
t = 1: Fokker-Planck on a grid against the exact density largest difference 0.0001 (peak height 0.429)
dt = 0.5: stationary variance 1.320 (the scheme's own 1.333; the process's 1.000)
The particles, the grid solution of the Fokker-Planck equation and the formula describe the same bell sliding to zero and widening to variance 1; the discretization is exact only as dt goes to zero, and with dt = 0.5 it settles to a bell a third too wide.
The code (99 lines; it asserts its own result)
"""Lab 5: run an Ornstein-Uhlenbeck process three ways: particles, the Fokker-Planck equation on a grid, the formula."""
import numpy as np
from scipy import stats
from videos.coursekit import labs
TITLE = "Particles against their density's own law"
GOAL = ("Simulate dx = -x dt + sqrt(2) dW from x = 2 with the Euler-Maruyama scheme, solve the Fokker-Planck "
"equation for the same process on a grid, and compare both with the exact Gaussian solution; then take "
"steps that are too large and predict the bias they cause.")
TASKS = [
"Replace the drift -x by the score of a two-bump density (the sum of two Gaussians): Langevin dynamics. Does "
"the histogram reach both bumps, and how long does it take?",
"Halve dt four times and plot the error of the variance at t = 1 against dt on log axes. What is the slope, "
"and which order of convergence (strong or weak) is it?",
"Run the process backwards from t = 3 with Anderson's reverse-time SDE, using the exact score of the "
"Gaussian at each time, and check that the particles return to a tight cloud around x = 2.",
]
THETA, SIGMA, X0 = 1.0, np.sqrt(2.0), 2.0
def exact(t):
"""Mean and variance of x_t: the solution of the Fokker-Planck equation from a point mass at X0."""
return X0 * np.exp(-THETA * t), SIGMA ** 2 / (2 * THETA) * (1 - np.exp(-2 * THETA * t))
def fokker_planck(grid, p, t0, t1, dt):
"""Explicit finite volumes for dp/dt = d(theta x p)/dx + (sigma^2 / 2) d2p/dx2, with no flux at the ends."""
dx, D = grid[1] - grid[0], SIGMA ** 2 / 2
faces = (grid[:-1] + grid[1:]) / 2
for _ in range(int(round((t1 - t0) / dt))):
flux = -THETA * faces * (p[:-1] + p[1:]) / 2 - D * (p[1:] - p[:-1]) / dx # probability moving right
p = p - dt / dx * np.diff(np.concatenate([[0.0], flux, [0.0]]))
return p
def run(seed=0):
rng = np.random.default_rng(seed)
n, dt, checks = 20000, 0.01, (0.25, 1.0, 3.0)
lab = labs.Lab()
x, paths, snaps = np.full(n, X0), [np.full(40, X0)], {}
for k in range(1, int(round(checks[-1] / dt)) + 1):
x = x - THETA * x * dt + SIGMA * np.sqrt(dt) * rng.standard_normal(n) # one Euler-Maruyama step
paths.append(x[:40].copy())
for t in checks:
if k == int(round(t / dt)):
snaps[t] = x.copy()
for t in checks:
m, v = exact(t)
xs = snaps[t]
ks = stats.kstest((xs - m) / np.sqrt(v), "norm").statistic
lab.row(f"t = {t}: mean, variance of 20,000 particles", f"{xs.mean():+.3f}, {xs.var():.3f} (exact {m:+.3f}, {v:.3f}); "
f"KS distance {ks:.4f}")
assert abs(xs.mean() - m) < 0.03 + 4 * np.sqrt(v / n), "the mean decays like exp(-t)"
assert abs(xs.var() / v - 1) < 0.05, "the variance follows 1 - exp(-2t)"
assert ks < 0.02, "the particles are Gaussian with the predicted mean and variance"
# The same law on a grid, started from the exact density at t = 0.05 (a point mass has no grid density).
grid = np.linspace(-6, 6, 241)
m0, v0 = exact(0.05)
p = fokker_planck(grid, stats.norm.pdf(grid, m0, np.sqrt(v0)), 0.05, 1.0, 5e-4)
m1, v1 = exact(1.0)
gap = np.abs(p - stats.norm.pdf(grid, m1, np.sqrt(v1))).max()
lab.row("t = 1: Fokker-Planck on a grid against the exact density", f"largest difference {gap:.4f} (peak height "
f"{stats.norm.pdf(0, 0, np.sqrt(v1)):.3f})")
assert gap < 0.01 and abs(p.sum() * (grid[1] - grid[0]) - 1) < 1e-6, "the grid solution matches and conserves probability"
# Too large a step: the scheme has its own stationary variance, sigma^2 / (2 theta - theta^2 dt).
big = 0.5
y = rng.standard_normal(n) * SIGMA / np.sqrt(2 * THETA)
for _ in range(60):
y = y - THETA * y * big + SIGMA * np.sqrt(big) * rng.standard_normal(n)
predicted = SIGMA ** 2 / (2 * THETA - THETA ** 2 * big)
lab.row("dt = 0.5: stationary variance", f"{y.var():.3f} (the scheme's own {predicted:.3f}; the process's "
f"{SIGMA ** 2 / (2 * THETA):.3f})")
assert abs(y.var() / predicted - 1) < 0.05 and y.var() > 1.2, "a coarse step inflates the stationary variance"
lab.note = ("The particles, the grid solution of the Fokker-Planck equation and the formula describe the same "
"bell sliding to zero and widening to variance 1; the discretization is exact only as dt goes to "
"zero, and with dt = 0.5 it settles to a bell a third too wide.")
fig, ax = labs.figure(2, size=(11, 4.2))
ts = np.arange(len(paths)) * dt
ax[0].plot(ts, np.array(paths), color=labs.BLUE, alpha=0.25, lw=0.6)
m, v = exact(ts)
ax[0].plot(ts, m, color=labs.GOLD, label="exact mean")
ax[0].fill_between(ts, m - np.sqrt(v), m + np.sqrt(v), color=labs.GOLD, alpha=0.18, label="mean ± one standard deviation")
ax[0].set(title="40 Euler-Maruyama paths of dx = -x dt + √2 dW", xlabel="time t", ylabel="x")
ax[0].legend(loc="upper right")
bins = np.linspace(-4, 4.5, 70)
for t, color in zip(checks, (labs.RED, labs.GREEN, labs.BLUE)):
mt, vt = exact(t)
ax[1].hist(snaps[t], bins=bins, density=True, color=color, alpha=0.35)
ax[1].plot(grid, stats.norm.pdf(grid, mt, np.sqrt(vt)), color=color, label=f"t = {t}: exact density")
ax[1].plot(grid, p, "--", color=labs.INK, lw=1.2, label="t = 1: Fokker-Planck on the grid")
ax[1].set(title="Histograms of the particles against the density", xlabel="x", ylabel="density", xlim=(-4, 4.5))
ax[1].legend(loc="upper left")
lab.fig = fig
return lab
Now change it
- Replace the drift -x by the score of a two-bump density (the sum of two Gaussians): Langevin dynamics. Does the histogram reach both bumps, and how long does it take?
- Halve dt four times and plot the error of the variance at t = 1 against dt on log axes. What is the slope, and which order of convergence (strong or weak) is it?
- Run the process backwards from t = 3 with Anderson's reverse-time SDE, using the exact score of the Gaussian at each time, and check that the particles return to a tight cloud around x = 2.
Problems, with solutions
Try each problem before opening its solution.
1. Sums are convolutions. Show that the density of X + Y, for independent X, Y with densities f, g, is f ∗ g. For f = g = e⁻ˣ on x > 0, compute f ∗ f and f ∗ f ∗ f.
Solution
P(X + Y ≤ s) = ∫ f(x) P(Y ≤ s − x) dx = ∫ f(x) G(s − x) dx; differentiating in s gives ∫ f(x) g(s − x) dx = (f ∗ g)(s). For the exponential, (f ∗ f)(s) = ∫₀ˢ e⁻ˣ e^{−(s−x)} dx = s e⁻ˢ, and (f ∗ f ∗ f)(s) = ∫₀ˢ x e⁻ˣ e^{−(s−x)} dx = s² e⁻ˢ / 2: the Gamma densities, sⁿ⁻¹e⁻ˢ/(n − 1)!.
2. Fisher information. Compute the Fisher information of N(θ, σ²) in θ, and of the Cauchy location; which estimators reach the Cramér–Rao bound?
Solution
For the normal, s = (x − θ)/σ², I = E[s²] = 1/σ²: the bound is σ²/n, which the sample mean reaches exactly for every n. For the Cauchy, s = 2u/(1 + u²) with u = x − θ, and I = (1/π)∫ 4u²/(1 + u²)³ du = 1/2: the bound is 2/n. The maximum-likelihood estimate reaches it as n → ∞ (it is asymptotically efficient), the median does not (π²/(4n)), and the average has no variance at all.
3. Maximum entropy on the integers. Show that the maximum-entropy distribution on {0, 1, 2, …} with mean m is geometric.
Solution
With multipliers for Σp_k = 1 and Σk p_k = m, stationarity gives log p_k = α − 1 + λk, so p_k = C r^k with r = e^λ < 1 (for the sum to converge). Normalizing, p_k = (1 − r) r^k, whose mean is r/(1 − r) = m, so r = m/(1 + m).
4. How many samples. Use Hoeffding's inequality to find n so that an average of n values in [0, 1] is within 0.01 of its mean with probability 0.999.
Solution
Two-sided, P(|X̄ − μ| ≥ ε) ≤ 2e^{−2nε²}. Setting 2e^{−2n · 10⁻⁴} ≤ 10⁻³ gives n ≥ ln(2000)/(2 · 10⁻⁴) = 38,004.5, so n = 38,005. (Chebyshev would ask for 1/(4ε²δ) = 2,500,000.)
5. The Gumbel-max trick. Show that argmaxᵢ(zᵢ + Gᵢ), with independent standard Gumbel Gᵢ, picks i with probability e^{zᵢ}/Σⱼe^{zⱼ}.
Solution
A Gumbel has CDF F(x) = exp(−e^{−x}) and density e^{−x}F(x). Option i wins when zᵢ + Gᵢ = y beats every other: P = ∫ e^{−(y−zᵢ)} F(y − zᵢ) Πⱼ≠ᵢ F(y − zⱼ) dy = ∫ e^{zᵢ} e^{−y} exp(−e^{−y} Z) dy with Z = Σⱼ e^{zⱼ}. Substituting t = e^{−y}: e^{zᵢ} ∫₀^∞ e^{−tZ} dt = e^{zᵢ}/Z.
6. The Ornstein–Uhlenbeck stationary bell. For dx = −θx dt + σ dW, find the stationary density from the Fokker–Planck equation.
Solution
∂p/∂t = ∂(θxp)/∂x + (σ²/2) ∂²p/∂x². Stationary: the flux θxp + (σ²/2)p′ is constant, and zero since p vanishes at infinity. So p′/p = −2θx/σ², p ∝ exp(−θx²/σ²): a bell with variance σ²/(2θ), as in chapter 16.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| law of large numbers | 大数定律 |
| central limit theorem | 中心极限定理 |
| normal (Gaussian) distribution, bell curve | 正态(高斯)分布,钟形曲线 |
| convolution (of densities) | (密度的)卷积 |
| Berry–Esseen theorem, Kolmogorov distance | 贝里-埃森定理,柯尔莫哥洛夫距离 |
| covariance matrix, precision matrix | 协方差矩阵,精度矩阵 |
| conditioning, Schur complement | 条件化,舒尔补 |
| regression (Galton's), regression to the mean | (高尔顿的)回归,向均值回归 |
| Kalman filter, Gaussian process | 卡尔曼滤波,高斯过程 |
| bias (of an estimator), Bessel's correction | (估计量的)偏差,贝塞尔校正 |
| score (of a parameter), Fisher information | (参数的)分数,费希尔信息 |
| Cramér–Rao bound, efficient estimator | 克拉默-拉奥下界,有效估计量 |
| Cauchy distribution | 柯西分布 |
| natural gradient, elastic weight consolidation | 自然梯度,弹性权重巩固 |
| conjugate prior, Beta distribution | 共轭先验,贝塔分布 |
| rule of succession | 接续法则 |
| maximum a posteriori (MAP), weight decay | 最大后验(MAP),权重衰减 |
| maximum entropy, Lagrange multiplier | 最大熵,拉格朗日乘子 |
| exponential family, log-partition function | 指数族,对数配分函数 |
| Gibbs (Boltzmann) distribution | 吉布斯(玻尔兹曼)分布 |
| Markov's, Chebyshev's, Chernoff's, Hoeffding's inequality | 马尔可夫不等式,切比雪夫不等式,切尔诺夫界,霍夫丁不等式 |
| inverse-CDF sampling, rejection sampling | 逆累积分布函数采样,拒绝采样 |
| Box–Muller transform | 博克斯-穆勒变换 |
| Gumbel-max trick, Gumbel-softmax | 冈贝尔最大值技巧,冈贝尔-softmax |
| greedy decoding, top-k, top-p (nucleus), min-p | 贪心解码,top-k,top-p(核采样),min-p |
| stationary distribution, transition matrix | 平稳分布,转移矩阵 |
| detailed balance, reversible chain | 细致平衡,可逆链 |
| spectral gap, mixing time, relaxation time | 谱间隙,混合时间,弛豫时间 |
| importance sampling, effective sample size | 重要性采样,有效样本量 |
| score-function (log-derivative) estimator, baseline | 分数函数(对数导数)估计量,基线 |
| reparameterization trick | 重参数化技巧 |
| evolution strategies | 进化策略 |
| Metropolis–Hastings | 梅特罗波利斯-黑斯廷斯算法 |
| Langevin dynamics, MALA | 朗之万动力学,MALA |
| integrated autocorrelation time | 积分自相关时间 |
| Brownian motion, scaling limit | 布朗运动,标度极限 |
| quadratic variation | 二次变差 |
| Itô integral, Itô's lemma, Stratonovich integral | 伊藤积分,伊藤引理,斯特拉托诺维奇积分 |
| stochastic differential equation, Euler–Maruyama | 随机微分方程,欧拉-丸山方法 |
| strong / weak convergence order | 强 / 弱收敛阶 |
| Ornstein–Uhlenbeck process | 奥恩斯坦-乌伦贝克过程 |
| Fokker–Planck equation | 福克-普朗克方程 |
| reverse-time SDE | 反向时间SDE |
Sources
- Min-p (Nguyen et al., arXiv 2407.01082, ICLR 2025) was challenged by Schaeffer et al., Min-p, Max Exaggeration (arXiv 2506.13681, 2025); the chapter says so.
- Itô's stochastic integral is 1944 (Proc. Imp. Acad. Tokyo 20); the formula ("Itô's lemma") is 1951 (Nagoya Math. J. 3). Doeblin's pli cacheté was sent in February 1940 and opened in 2000; he died in June 1940.
- The Brandeis dice problem is from Jaynes's 1962 Brandeis Summer School lectures; the maximum-entropy principle is Jaynes (1957).
- The Berry–Esseen constant 0.4748 for identically distributed summands is Shevtsova (2011, arXiv 1111.6554).
- Kalman filtering in the Apollo guidance computer; ES training of simulated robots and Atari (Salimans et al. 2017); the first DALL-E's discrete VAE trained with a Gumbel-softmax relaxation (Ramesh et al. 2021).
Sources
Books: J. K. Blitzstein & J. Hwang, Introduction to Probability (2019); L. Wasserman, All of Statistics (2004); D. J. C. MacKay, Information Theory, Inference, and Learning Algorithms (2003); D. A. Levin & Y. Peres, Markov Chains and Mixing Times (2017); B. Øksendal, Stochastic Differential Equations (2003); S. Boucheron, G. Lugosi & P. Massart, Concentration Inequalities (2013); C. M. Bishop, Pattern Recognition and Machine Learning (2006).
Papers: de Moivre (1733); Laplace (1774, 1810); Bayes (1763); Gauss (1809); Galton (1886, 1889); Markov (1906, 1913); Einstein (1905); Bachelier (1900); Langevin (1908); Fokker (1914); Planck (1917); Wiener (1923); Fisher (1922, 1925); Ornstein & Uhlenbeck (1930); Kolmogorov (1931); Lévy (1940); Berry (1941); Esseen (1942); Itô (1944, 1951); Rao (1945); Cramér (1946); Metropolis & Ulam (1949); von Neumann (1951); Chernoff (1952); Metropolis, Rosenbluth, Rosenbluth, Teller & Teller (1953); Gumbel (1954); Maruyama (1955); Jaynes (1957); Box & Muller (1958); Kalman (1960); Hoeffding (1963); Stratonovich (1966); Hastings (1970); Anderson (1982); Glynn (1990); Williams (1992); Roberts & Tweedie (1996); Amari (1998); Shevtsova (2011); Welling & Teh (2011); Kingma & Welling (2013); Maddison, Tarlow & Minka (2014); Sohl-Dickstein et al. (2015); Jang, Gu & Poole (2017); Maddison, Mnih & Teh (2017); Kirkpatrick et al. (2017); Salimans et al. (2017); Fan, Lewis & Dauphin (2018); Holtzman et al. (2020); Song et al. (2021); Nguyen et al. (2024); Schaeffer et al. (2025).
About this partfrom its README
Part 5 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). A model hands us distributions: it is fitted by maximum likelihood, it is sampled to write, its gradients are averages over random choices, and the newest image generators are random motion run backwards. This part is the probability behind all of that, from Pascal and Fermat's letters to the Fokker–Planck equation, with the history of each idea and where it shows up in today's models. Every number on screen is computed here, small and on a CPU, or cited.
What is computed and built
python -m videos.ai.ai5.compute writes every item to .cache/ai5/. The numbers quoted above, plus:
-
Decoding (
decoding, resumable by setting). The novels model continues twelve deterministic held-out prompts of 32 generator tokens. Each of fifteen stochastic settings generates eight 40-token continuations per prompt; greedy generates one. These configuration totals are 1,452 generated continuations and 58,080 tokens. Full generated strings and character counts were not retained for an independent raw-row recount.GPT-2 revision
607a30d783dfa663caf39e06633721c8d4cfcd7escores separately tokenized prompt/continuation boundaries in nats per true continuation Unicode character, without silent truncation. This convention and changed prompt selection make these results numerically incomparable with the old metric-v2 table. Diversity pools generator-token bigrams within a prompt; repetition counts generator-token 4-grams, not word sequences.
| Setting | NLL (nats/character) | Distinct token bigrams | Repeated token 4-grams | Mean tokens kept |
|---|---|---|---|---|
| greedy0.0 | 0.540234 | — | 35.1351% | 1.000 |
| temp0.5 | 0.851139 | 0.695246 | 2.1396% | 4096.000 |
| temp0.7 | 0.997609 | 0.833600 | 0.4223% | 4096.000 |
| temp1.0 | 1.281646 | 0.936165 | 0.0282% | 4096.000 |
| temp1.3 | 1.613097 | 0.989049 | 0.0000% | 4096.000 |
| topk5 | 0.827322 | 0.733707 | 0.9009% | 5.000 |
| topk20 | 0.997796 | 0.883814 | 0.0282% | 20.000 |
| topk100 | 1.170755 | 0.923077 | 0.0845% | 100.000 |
| topp0.5 | 0.885511 | 0.767628 | 0.5349% | 11.448 |
| topp0.8 | 1.059453 | 0.889957 | 0.1126% | 63.650 |
| topp0.9 | 1.147806 | 0.930288 | 0.0000% | 145.573 |
| topp0.95 | 1.189928 | 0.928152 | 0.0282% | 272.284 |
| minp0.02 | 1.042255 | 0.894765 | 0.0563% | 45.579 |
| minp0.05 | 0.983257 | 0.846955 | 0.5068% | 21.750 |
| minp0.1 | 0.902881 | 0.810897 | 0.4223% | 11.161 |
| minp0.2 | 0.841291 | 0.709402 | 1.4640% | 5.484 |
| Held-out human reference | 1.012341 | — | 0.0000% | — |
At diversity 0.85, linear interpolation within observed supports gives temperature 1.043026, top-k 0.959394, top-p 1.002637 and min-p 0.987015 nats/character. All four rules cover this target; their common support is [0.767628, 0.894765]. Top-k is lowest in this descriptive interpolation of one run. This does not establish significance or generalization. Greedy has the lowest surprise and the most repetition; likelihood alone does not measure text quality.
The mean across sixteen settings of SD(promptwise NLL/character)/√12 is 0.051391 nats/character; the mean passage SD is 0.178025. This descriptive SE concerns an unweighted average of promptwise ratios. It is not the uncertainty of the character-weighted headline score, passage-to-passage spread, a calibrated confidence interval, or model/run-to-run uncertainty. Raw character weights were not saved to estimate weighted uncertainty.
Parent-recorded elapsed intervals were 651.410 seconds for decoding and 781.241 seconds summed across all 28 child processes, including setup/imports. The 56 payload files total 3,090,034 bytes. These observations describe this cloud run, not a portable runtime promise.
Chapter notes
- Out of noise. 600 random dots flow, by the reverse-time SDE with the exact score of the noised letters, into "AI"; run forwards, the letters dissolve. How we got here, 1654–2020 (Pascal and Fermat, Bernoulli, de Moivre, Bayes and Laplace, Gauss, Einstein, Fisher, Itô, Metropolis et al., diffusion models and nucleus sampling); the plan.
- 1. The bell curve. Bernoulli's law of large numbers (1713): six runs of 5,000 flips settle between 0.489 and 0.512. A Galton board, 1,000 balls through 12 rows (χ² = 12.1 against the binomial); C(12, k)/2¹² and de Moivre's curve (1733); dice sums for k = 1 … 12; the central limit theorem (Laplace 1810). Why: the density of a sum is a convolution, derived and pictured (an exponential's flipped copy sliding, the overlap tracing s e⁻ˢ); repeated convolution on a grid (checked against the exact Gamma CDF) turns the exponential into the bell. How fast: the Kolmogorov distance falls with slope −0.50 for the exponential (0.158 → 0.017 at n = 64), under the Berry–Esseen bound C ρ/σ³√n with C = 0.4748 (Berry 1941, Esseen 1942, Shevtsova 2011); for the symmetric uniform, slope −1.02.
- 2. Bells in many dimensions. Every Gaussian is μ + Lz; Σ = LLᵀ; elliptical contours along Σ's eigenvectors. Conditioning derived (precision, completing the square, the Schur complement). Checked: of 400,000 points, the 2,568 in the strip x₂ = 1.5 ± 0.02 have mean 0.796 and variance 0.448 against the predicted 0.804 and 0.4375; in four dimensions, two given two, off by at most 0.036. Galton's regression (1886); the Kalman filter (1960), Gaussian processes, and diffusion's Gaussian posteriors (Part 21).
- 3. Fitting a bell: maximum likelihood. The log-likelihood as a score, the probability density, the (μ, σ) landscape climbed by gradient ascent to μ̂ = 5.96, σ̂ = 1.71 (√3 predicted); maximum likelihood is minimum cross-entropy. The bias of σ̂², derived (E = (n−1)/n σ²) and measured on 40,000 samples of each size (0.800 at n = 5; Bessel's correction 0.999); Fisher (1922).
- 4. How precise can an estimate be? The Cauchy location: the sample average never improves (its interquartile range stays near 2 from n = 5 to 500); the median and a multistart likelihood fit do (global optimality is not certified). Score, Fisher information (measured variance of the Cauchy score 0.4998 against 1/2) and the Cramér–Rao bound derived (Fisher 1925; Rao 1945; Cramér 1946). Measured on 4,000 samples of each size: n·Var(the likelihood fit) falls from 4.74 at n = 5 to 2.02 at n = 500 (bound 2); the median levels at 2.49 (π²/4). The Fisher matrix in training: natural gradient (Amari 1998), EWC (Kirkpatrick et al. 2017), K-FAC and Shampoo (Part 11).
- 5. Belief as a distribution. Bayes's rule (Bayes 1763, Laplace 1774) on the frequency of "e" in Part 1's passage, live from a flat prior: 95% of the belief between 0.1205 and 0.1335 after 10,000 letters, the whole passage at 0.1221. Beta–binomial conjugacy derived; Laplace's rule of succession; three priors pulled together by the same letters. MAP as regularization derived: a Gaussian prior is weight decay, λ = σ²/τ². Ten points from sin 2πx and a degree-9 polynomial (Bishop's example): median test error 0.247 for maximum likelihood, 0.025 for MAP at λ ≈ 3 × 10⁻⁴, over 200 training sets.
- 6. Maximum entropy. Jaynes's Brandeis die (average 4.5); the maximum-entropy solution derived with Lagrange multipliers (p_k ∝ e^{λk}); the dual fitted by gradient steps from the fair die, replayed: λ = 0.371, p = (0.054, 0.079, 0.114, 0.165, 0.240, 0.347), entropy 1.6136 nats, above all 20,000 random dice with the same average (highest 1.6135). On the line: fixing mean and variance gives the bell (to 3 × 10⁻¹⁴), fixing E|x| gives Laplace's double exponential; fixing the average energy gives Boltzmann and Gibbs's distribution, the softmax; the exponential family and moment matching.
- 7. How far from the average? A million runs of 100 fair flips; Markov, Chebyshev, Chernoff and Hoeffding derived in a chain; against the exact tail at ε = 0.1 (0.0284): 0.83, 0.25, 0.134, 0.135. Flips needed to guarantee P(overshoot ≥ 0.05) ≤ 0.05: Chebyshev 2,000, Hoeffding 600, Chernoff 599, the smallest qualifying fixed sample size 262; all sample sizes from 281 onward qualify (the exact binomial tail oscillates with integer counts). Part 8's generalization bounds; Part 26's UCB.
- 8. Rolling loaded dice. Inverse-CDF sampling (letters; exponentials: KS 0.006); von Neumann's rejection sampling (1951; Beta(2, 5), 40.3% kept, 1/M = 40.7% predicted); Box–Muller derived (1958; KS 0.002, correlation −0.008); the Gumbel-max trick derived and checked (200,000 picks against the softmax, χ² = 3.9 on 5 degrees of freedom; Gumbel 1954, Luce 1959, Yellott 1977, Maddison et al. 2014); Gumbel-softmax at τ = 0.1, 1, 5 (largest entry 0.95, 0.58, 0.25; Jang, Gu & Poole 2017; Maddison, Mnih & Teh 2017).
- 9. How a language model chooses. GPT-2's next-word distribution under a temperature dial (entropy 4.7, 9.0, 13.5 bits at T = ½, 1, 2) and its samples; top-k (Fan et al. 2018), top-p (Holtzman et al. 2020) and min-p (Nguyen et al. 2024; re-analysed by Schaeffer et al. 2025), the top-p cut sliding over two real GPT-2 distributions (an open one and a nearly certain one: at p = 0.9, 1,210 words against 1; min-p 0.1, 40 against 1). The experiment: the series' novels model uses 16 settings on 12 held-out passages: 8 continuations per stochastic setting, one for greedy; GPT-2 judges each by its surprise; at equal diversity 0.85, top-k has the lowest interpolated surprise in this run (0.959 against 1.043 nats per character for temperature alone); greedy repeats 35.1% of its token 4-grams (see Computed results).
- 10. Chains with short memories. A three-state chain from Part 1's letters; its stationary distribution as the eigenvector of eigenvalue 1 (Markov 1906, 1913); all 27 letters from "q", forgotten within five steps at the rate of the second eigenvalue, 0.30. Detailed balance derived; English is not reversible ("e" then space is 10 times as common as space then "e"). The spectral gap: a walk on 41 sites in a double well; its mixing time against 1/gap over eight barrier heights rises from 638 to 26 million steps, slope 0.98, between the bounds (t_rel − 1) ln 2 and t_rel ln(4/π_min) (Levin & Peres).
- 11. Answers from random samples. Los Alamos: Ulam's solitaire (1946), von Neumann's neutrons, ENIAC (1948). π from 4,000 darts; the error's slope −0.50 over 200 runs at nine sizes; a rare event, P(Z > 4) = 3.17 × 10⁻⁵: two hits in 10,000 plain draws, within 1% by importance sampling. The effective sample size of importance weights against dimension (proposal 1.25× wider): 4,671 of 5,000 in one dimension, 184 in fifty, 10.5 measured in two hundred, where the population-moment large-sample proxy is 0.005; this proxy is not the exact finite-sample ESS.
- 12. The gradient of an average. The log-derivative trick derived; baselines (Glynn 1990; Williams 1992). For ∇ E[x²], x ~ N(1, 1): the estimate averages 1.998 (truly 2) with per-sample variance 30.0, 13.9 with the best baseline (b = 3.99), and 4.0 reparameterized (Kingma & Welling 2013). Evolution strategies (Salimans et al. 2017) on a curved valley, 8 runs each at equal iteration caps (early divergence uses fewer probes). For the Gaussian-smoothed objective, the mean squared gradient-estimation error is 398.7 plain, 16.8 with an unbiased leave-one-out-equivalent baseline, and 15.6 with mirrored probes (the squared reference-gradient norm is 37.2164). The smoothed optimum differs from the original objective's optimum. With the same step size, 2 of 8 plain runs diverge, none with the baseline.
- 13. Sampling the unsampleable. Metropolis et al. (1953, MANIAC): the walk on a two-bump density, proposals accepted and rejected, 65% of the time in the bump that holds two thirds. Metropolis–Hastings derived from detailed balance (Hastings 1970). Langevin dynamics (Langevin 1908; MALA, Roberts & Tweedie 1996; SGLD, Welling & Teh 2011): 1,500 particles from noise with their density evolving in 3D; L¹ distance from the target 1.19 → 0.23; 59% in the left bump. Mixing measured, four samplers × 5 seeds × 20,000 steps: hops between the bumps and the conditional variance within the left one (conditional variance 0.3414) — random-walk Metropolis 70 hops, 0.34; small-step Langevin 13, 0.36; big-step Langevin 228 but 0.56 (biased); MALA 6, 0.34.
- 14. Brownian motion. Brown (1827); random walks with 8, 64, 1,024 steps of ±1/√n; Bachelier (1900), Wiener (1923), Donsker's scaling limit; 60 paths shown against the mean ± one standard deviation, ±√t (not pathwise bounds), variances 0.25, 0.49, 0.74, 0.98 on 20,000 paths. Quadratic variation derived and measured on 400 paths: Σ(ΔW)² = 0.99 ± 0.32 with 16 steps, 0.999 ± 0.011 with 16,384, while Σ|ΔW| reaches 102 (Lévy 1940). A cloud in the plane; the heat equation; Einstein (1905), Perrin (1908).
- 15. Itô's lemma. ∫W dW with left points derived (½W² − ½) and checked on 2,000 paths (error 0.22 → 0.007 from 10 to 10,000 steps; midpoints give ½W² exactly). Itô's lemma derived; checked path by path on e^W (gap 0.66 → 0.012, slope −0.56; without the ½f″ dt term it stalls at 0.79) and on average, E[e^{W₁}] = 1.649 against e^{1/2} = 1.6487. Doeblin's sealed envelope (1940, opened 2000), Itô (1944, 1951), Stratonovich (1966), Black–Scholes–Merton (1973).
- 16. Randomness with a push. dx = f dt + g dW; Euler–Maruyama; the Ornstein–Uhlenbeck process (1930) settling to its bell. Euler–Maruyama's convergence on geometric Brownian motion against the exact solution from the same noise, 20,000 paths: strong error slope 0.54, weak error slope 0.95 (Maruyama 1955).
- 17. The density's own law. The Fokker–Planck equation derived from Itô's lemma by integration by parts (Fokker 1914, Planck 1917, Kolmogorov 1931); solved on a grid for the OU process against 20,000 particles (histograms within 0.0382 of exact bin-average densities conditioned on the plotted interval, the grid within 0.000411 of the exact density); Langevin's stationary density is the target, derived; Anderson's reverse-time SDE (1982) and the score, in 1D and in the plane (Part 21).
- Recap, where it comes back, six problems, Part 6's teaser, references.
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The CLT by repeated convolution.
- Multivariate Gaussians; conditioning via the Schur complement.
- MLE bias; Fisher information and Cramér–Rao.
- Bayes: Beta–binomial live; MAP as regularization.
- Exponential families and maximum entropy (softmax and Gibbs as max-ent).
- Concentration: Markov, Chebyshev, Chernoff/Hoeffding (Part 8 uses them).
- Sampling: inverse CDF, rejection, Box–Muller; the Gumbel-max trick and Gumbel-softmax.
- LLM decoding: temperature, top-k, top-p, min-p.
- Markov chains: stationary distributions as eigenvectors, detailed balance, spectral gap.
- Monte Carlo at 1/√n; importance sampling and ESS; the score-function estimator (REINFORCE and evolution strategies come back).
- Metropolis–Hastings from detailed balance; Langevin dynamics.
- Brownian motion as a scaling limit; quadratic variation; Itô's lemma.
- SDEs, Euler–Maruyama; Fokker–Planck derived; Ornstein–Uhlenbeck (Part 21's forward process).
Visuals: ParticleFlow Langevin with its density evolving in 3D; the top-p cut sliding over a real next-token
distribution.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. 和就是卷积。 证明:独立的X、Y,密度分别为f、g,则X + Y的密度是f ∗ g。对x > 0上的f = g = e⁻ˣ,计算f ∗ f与f ∗ f ∗ f。
解答
P(X + Y ≤ s) = ∫ f(x) G(s − x) dx,对s求导得∫ f(x) g(s − x) dx = (f ∗ g)(s)。对指数分布, (f ∗ f)(s) = ∫₀ˢ e⁻ˣ e^{−(s−x)} dx = s e⁻ˢ,(f ∗ f ∗ f)(s) = s² e⁻ˢ / 2:即伽马分布的密度sⁿ⁻¹e⁻ˢ/(n − 1)!。
2. 费希尔信息。 求N(θ, σ²)关于θ的费希尔信息,以及柯西分布位置参数的费希尔信息;哪些估计量能达到克拉默-拉奥下界?
解答
正态分布的分数s = (x − θ)/σ²,I = 1/σ²,下界σ²/n,样本均值对任何n都恰好达到。柯西分布的s = 2u/(1 + u²), I = 1/2,下界2/n;最大似然估计在n → ∞时达到(渐近有效),中位数达不到(π²/(4n)),平均值连方差都没有。
3. 整数上的最大熵。 证明:在{0, 1, 2, …}上、均值为m的最大熵分布是几何分布。
解答
对Σp_k = 1与Σk p_k = m引入乘子,驻点条件给出log p_k = α − 1 + λk,即p_k = C r^k,r = e^λ < 1。归一化得 p_k = (1 − r) r^k,均值r/(1 − r) = m,故r = m/(1 + m)。
4. 需要多少样本。 用霍夫丁不等式求n,使n个[0, 1]内取值的平均以0.999的概率落在均值的0.01以内。
解答
双侧形式P(|X̄ − μ| ≥ ε) ≤ 2e^{−2nε²}。令2e^{−2n · 10⁻⁴} ≤ 10⁻³,得n ≥ ln(2000)/(2 × 10⁻⁴) = 38004.5,故n = 38005。 (切比雪夫不等式要求1/(4ε²δ) = 250万。)
5. 冈贝尔最大值技巧。 证明:对独立的标准冈贝尔噪声Gᵢ,argmaxᵢ(zᵢ + Gᵢ)选中i的概率是e^{zᵢ}/Σⱼe^{zⱼ}。
解答
冈贝尔分布的累积分布函数F(x) = exp(−e^{−x}),密度e^{−x}F(x)。选项i获胜的概率为 ∫ e^{−(y−zᵢ)} F(y − zᵢ) Πⱼ≠ᵢ F(y − zⱼ) dy = ∫ e^{zᵢ} e^{−y} exp(−e^{−y} Z) dy,其中Z = Σⱼ e^{zⱼ}。令t = e^{−y}, 得e^{zᵢ} ∫₀^∞ e^{−tZ} dt = e^{zᵢ}/Z。
6. 奥恩斯坦-乌伦贝克过程的平稳钟形曲线。 对dx = −θx dt + σ dW,由福克-普朗克方程求平稳密度。
解答
∂p/∂t = ∂(θxp)/∂x + (σ²/2) ∂²p/∂x²。平稳时通量θxp + (σ²/2)p′为常数,又因p在无穷远处为零,常数为零。 于是p′/p = −2θx/σ²,p ∝ exp(−θx²/σ²):方差为σ²/(2θ)的钟形曲线,与第16章一致。
Build the film
python -m videos.ai.ai5.compute # the part's numbers, into .cache/ai5
python tools/build.py ai5 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai5 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai5. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python tools/make.py ai5 # compute, then the narrated cut in English and Chinese
python -m videos.ai.ai5.compute # the numbers alone (needs Part 1's books, .cache/ai1; GPT-2 small;
# the series' novels model, python -m explainer.ai.novels)
python tools/build.py ai5 # English
python tools/build.py ai5 --lang zh # Chinese
python tools/qa_scene.py ai5 Decoding # one chapter, silent, with a contact sheet
The compute is seeded throughout. Decoding saves each setting and resumes only with matching consumed-input, producer and runtime identities. Runtime depends on hardware, dependencies and load; the measured cloud run is reported above. Use cached-only QA for frozen reviewed data rather than triggering a producer during rendering.