Fitting and Generalizing
A model is fitted to examples, so why should it work on anything else?
The part opens on the gap: Part 6's nearest-neighbour vote scores 93% on its own training pages and 68% on new ones. Risk, empirical risk and the Bayes risk are defined, and bias and variance are derived and measured over polynomial degrees. The classical guarantees are then built one step at a time: Hoeffding for one rule, the union bound for many, shattering, the Sauer-Shelah lemma and the VC bound, Rademacher complexity and margins. Computed on the 448 training pages, most of them say little or nothing; a PAC-Bayes bound optimized for a 9,217-weight network gives 35.6%, non-vacuous, against 2.8% measured. The part turns when a 300,034-weight network fits shuffled authors completely: the classical story cannot explain why the same network generalizes on true labels. The explanations since follow: gradient descent's implicit bias toward the minimum-norm and the max-margin fit, double descent with its peak at p = n, benign overfitting, and the unsettled debate over flat minima. It ends where generalizing stops being enough: covariate shift with importance weights, and passages a language model reproduces word for word once it has seen them often enough.
What you need. Probability with expectations and tail bounds (Part 5), least squares and the SVD (Parts 3 and 6).
- Mathematics and history
- ERM, bias–variance, VC, Rademacher, PAC-Bayes, implicit bias, double descent, distribution shift
What you will be able to do
Undergraduate
- Explain the difference between training error and risk, and why the best of many rules looks better on its training examples than it is.
- Split a model's expected squared error into bias, variance and noise, and read the U-shaped curve.
- Describe the random-label experiment and the double-descent curve, and say what each one contradicts.
Master's
- Derive the union bound for a finite family and the VC bound through the growth function and the Sauer-Shelah lemma.
- Compute the Rademacher complexity of norm-bounded linear rules, and state the margin bound.
- Prove that gradient descent from zero reaches the minimum-norm interpolant, and explain the peak at p = n through the smallest singular value.
Research
- Prove the PAC-Bayes theorem by a change of measure, and optimize the bound over a Gaussian posterior for a small network.
- State the effective-rank conditions for benign overfitting, and explain why a rescaling of the weights defeats sharpness as a measure of generalization.
Engineering
- Correct a covariate shift by importance weighting, with weights from a domain classifier, and report the effective sample size.
- Test a language model for extractable training passages, and explain how repetition in the training data and deduplication change the result.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 20 min · Master's 43 min · Research 51 min · Engineering 26 min.
- 0The gapUndergraduate3 min
- 1Risk, and the best possible ruleUndergraduate3 min
- 2Bias and variance, derivedUndergraduate2 min
- 3One rule, then manyUndergraduate4 min
- 4Shattering and the VC boundMaster's3 min
- 5Rademacher complexityMaster's3 min
- 6MarginsMaster's2 min
- 7PAC-Bayes: a bound that says somethingResearch3 min
- 8Compression and stabilityMaster's3 min
- 9Memorizing nonsenseUndergraduate2 min
- 10Implicit bias: the smallest fitMaster's2 min
- 11Implicit bias: the widest marginMaster's2 min
- 12Double descentUndergraduate3 min
- 13Double descent in samples and in epochsMaster's1 min
- 14Benign overfittingResearch2 min
- 15Flat minima and the sharpness debateResearch2 min
- 16Distribution shiftEngineering2 min
- 17Memorization in language modelsEngineering4 min
- 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.
The gapUndergraduate3 min
In part six, a model that asked only its single nearest neighbour got 93 percent of its own training pages right, and only 68 percent of new ones. Let more neighbours vote, and the two error rates meet. That gap is the central question of machine learning. A model is fitted to examples. Why should it work on anything else?
The question is old, and so are the first answers. In 1963 Wassily Hoeffding showed how tightly an average of many independent draws gathers around its mean. In 1971 Vladimir Vapnik and Alexey Chervonenkis turned that into a theory of learning: what a model can learn depends on how much it could fit. In 1984 Leslie Valiant defined learning itself, probably approximately correct. In 1992 Geman, Bienenstock and Doursat named the dilemma of bias against variance; in 1999 David McAllester gave bounds for averages of models, and in 2002 Bartlett and Mendelson measured capacity by fitting noise. Then deep learning broke the picture: in 2017 Zhang and colleagues showed networks memorizing random labels, in 2019 Belkin and colleagues found test error falling again past the point of fitting everything, and in 2020 Bartlett and colleagues proved when fitting noise is harmless. From 2021, Carlini and colleagues pulled training text out of language models, and by 2025 there were bounds that say something real about large language models, and courts ruling on what they memorize.
This is Part 8 of AI, Built: fitting and generalizing, or why models work on data they've never seen. Statistical guarantees assume independent samples from one distribution; our correlated book pages illustrate the calculations. In it: risk, the quantity we really care about, and the best any model could do; bias and variance, derived; how one rule's score on test data can be trusted, and what changes when we choose among many; capacity, measured three ways, each with the guarantee it buys; bounds that still say something for neural networks; the experiments that broke the classical story, and the explanations since; and finally what happens when the test data comes from somewhere else, and what a language model remembers word for word.
1Risk, and the best possible ruleUndergraduate3 min
What exactly are we trying to make small?
To say what generalizing means, we need two numbers. Here's a problem small enough to know completely: two classes, equally likely, each with its own spread of a single measurement x. A sample is forty points drawn from it. A rule h guesses the class from x, and the loss is one when it's wrong. Its risk is the expected loss over everything the world could send, the error rate on data it has never seen. Its empirical risk is the average loss on the sample we have: the training error. Generalizing means the second is a good guide to the first, even for a rule we chose by looking at the sample.
What's the best any rule could do? Average over x the chance that the guess at x is wrong. At each x the true class is one with some probability, eta of x; the best guess picks the likelier class, and is wrong with the smaller of eta and one minus eta. So no rule beats the average of that minimum: the Bayes risk, here the area where the two curves overlap, 0.217. The rule that achieves it says one wherever class one is the likelier: here, on an interval. It needs the true distribution, which we never have; it's the floor to measure learners against. Cover and Hart showed in 1967 that a single nearest neighbour, with endless data, errs at most twice as often.
Now a learner. Suppose it may only use thresholds: say one if x is above t. It picks the threshold with the fewest training errors. From forty points, thirty times, the chosen threshold jumps around the best one. Average over 400 samples at each size. With 10 examples, the training error is 15 percent, but the true risk of the chosen rule is 27: the training error is optimistic, because the rule was picked to look good on exactly those points. With 2,560, both settle near 23.0 percent, the best threshold's risk, and stay above the Bayes risk, 21.7. That splits the excess risk in two: approximation, because no threshold can draw an interval, and estimation, because the sample is finite. More data shrinks only the second; a richer family shrinks the first, and the rest of this part is about what it costs the second.
2Bias and variance, derivedUndergraduate2 min
Too simple, or too nervous?
The classical answer starts with a setting small enough to see everything: a smooth curve, and sixteen noisy points drawn from it. Fit a straight line. Draw sixteen new points and fit again, and again: it misses the curve's shape in the same way every time. That systematic miss is bias. Fit a polynomial of degree twelve: a sum of powers of x, up to x to the twelfth. The degree, the highest power, is roughly how many bends the curve can make. It bends closely around the points, but each new draw gives a wildly different curve. That's variance. In between, at degree , the fits hug the truth.
Why does the error split that way? Fix a point x. The answer y is the true curve f plus noise of variance sigma squared, and the fit f hat depends on the random training set. The noise is independent of the fit and averages to zero, so the cross term vanishes: the noise variance comes off on its own. In what's left, add and subtract the average fit, f bar. The fit's deviation from its own average also averages to zero, so again no cross term. Three pieces remain: the average fit's distance from the truth, squared, the squared bias; how much the fit varies from sample to sample, the variance; and the noise. Geman, Bienenstock and Doursat named the dilemma in 1992, for neural networks.
Now measure all three, over 200 training sets at every degree. Bias squared falls as the model gets more flexible. Variance rises. The noise is a floor no model can go below. Their sum is a U, with the best model at its bottom: flexible enough, and no more. And the circles are the error measured directly, on fresh noisy points: they sit on the sum, within 1 percent at every degree. For thirty years this U was the textbook picture: control the flexibility, and you control the error. Keep it in mind; chapter twelve finds a second descent beyond its right edge.
3One rule, then manyUndergraduate4 min
When can a score on test data be trusted?
Start with one rule, fixed in advance, and a test set. Each test case is a coin flip: the rule errs or it doesn't, and the measured error rate is the average of those flips. Part five proved Hoeffding's inequality: an average of n independent numbers between zero and one strays from its mean by epsilon with probability at most two e to the minus two n epsilon squared. Watch it happen. A rule whose true error is percent, measured on ten test cases, a hundred thousand times: only percent of the measurements have deviation less than five percentage points. On forty, percent. On , . On , percent: the histogram narrows like one over the square root of n.
On a log scale, the measured tail at a hundred and sixty test cases falls off like a parabola, and so does Hoeffding's bound, always above it. Chebyshev's bound, which uses only the variance, falls far more slowly. So how many test cases give a deviation of less than five percentage points, ninety-five percent of the time? Knowing the true error, the first qualifying n is . Hoeffding asks for , about times as many, but it needs to know nothing about the rule. Chebyshev asks for . That's why a held-out test set of a few thousand examples is a trustworthy score.
But a learner doesn't test one rule; it picks the best of many, on the same data. Here are 1,000 rules that know nothing at all, scored on 100 examples whose labels are coin flips. Each one's training error scatters around fifty percent, and the best of them scores 34. On ten thousand fresh cases, that winner's error is 50.4 percent. Choosing among many rules is what made the score lie. The fix is the union bound: the chance that any rule strays is at most the sum of the chances. Each is a Hoeffding tail. Set the total to delta and solve: with probability one minus delta, every rule in a finite family is within the square root of log of the family's size over n. The price of choosing grows only with the logarithm.
As the family grows from one rule to a million, scored on a hundred examples, the best training error drops from to percent, on labels that are pure noise. The largest gap between training and true error, ninety-five percent of the time, grows from to points, and the union bound, from to , stays above it Leslie Valiant made this the definition of learning in 1984: probably approximately correct. A family can be learned if enough examples make every rule's score trustworthy, with high probability, to within epsilon. For a finite family, the log of its size divided by epsilon squared is enough. But a line has infinitely many positions. The next chapter counts them properly.
4Shattering and the VC boundMaster's3 min
How do you count infinitely many lines?
A family of rules with infinitely many members can still be weak. Take lines in the plane, and three points. Colour the points any of the eight possible ways, and some line separates the colours every time. With four points, it fails: no line splits these two labellings, the crossing pattern of XOR. A family shatters a set of points if it can produce every labelling of them, and the largest set it can shatter is its VC dimension, after Vapnik and Chervonenkis: three for lines in the plane, and in general one more than the number of inputs a linear rule with a bias reads.
What matters is not how many rules a family has, but how many different labellings it can produce on the points in front of it: the growth function. For five points, half-planes produce of the thirty-two. Count it for every n by sweeping a line around: for points in general position, half-planes realize n squared minus n plus two labellings, on points, out of . The Sauer–Shelah lemma says this always happens: once a family cannot shatter any set of size d plus one, its growth is bounded by a polynomial of degree d, rather than continuing as two to the n. Intervals on a line, VC dimension two, meet their bound exactly. Polynomial instead of exponential is what lets an infinite family be learned.
That count buys a bound for IID binary classification, with 95 percent confidence here. The proof in four steps. First, compare the training sample with a second, imaginary one of the same size, a ghost sample: if training and true error are far apart, the two samples' errors probably are too. On the two samples together, the family acts as at most the growth function of two n rules, a finite number, so the union bound and Hoeffding apply. Sauer–Shelah makes that number a polynomial. Solve for epsilon: the gap shrinks like the square root of d log n over n. For lines in the plane on 448 pages, the gap is at most 0.23. For a linear rule on all seventy word rates, 0.76: hardly a guarantee; it would take about 60,400 pages to get it down to a tenth. And for the network of chapter nine, with three hundred thousand weights for 448 pages, it says nothing at all. That network generalizes anyway.
5Rademacher complexityMaster's3 min
How well can a family fit pure noise?
Counting labellings needs a family's worst case. There's a more direct test of capacity, done on the data you actually have. Give each training page a random label, a coin flip, plus or minus one, and ask the family to fit them. A linear rule on one word rate gets barely more than half. On all seventy, it fits percent of the coin flips: pure noise. This plot averages twelve regularized logistic fits; it shows achievable accuracy, not the supremum. Averaged over the coin flips, the best correlation the family can reach with random signs is its empirical Rademacher complexity, named for the random plus-or-minus-one variables of Hans Rademacher. A family that can fit noise well can make any training score look good.
And it bounds the gap. With probability one minus delta, every rule's true risk is at most its training risk, plus twice the Rademacher complexity of the losses, plus a term that shrinks like one over root n. The proof starts like VC's, with a ghost sample. Swapping a real example with its ghost twin is a random sign, so the gap becomes a correlation with random signs, with no counting at all. And because one example can move the supremum by at most one over n, McDiarmid's inequality, a cousin of Hoeffding's, makes the measured complexity concentrate. Koltchinskii, and Bartlett and Mendelson, gave it this form around 2002.
For linear rules with weights of length at most B, the complexity can be computed exactly. The best weight vector for given signs points along the signed sum of the inputs, by Cauchy–Schwarz, so the supremum is B over n times the length of that sum. Jensen moves the expectation inside the square root, and since independent signs are uncorrelated, the cross terms vanish: B over n times the root of the sum of squared lengths, at most B times the largest length R, over root n. On the pages: the measured complexity sits within 1 percent of the bound at every size, falling like one over root n. Twenty thousand random directions reach only 0.21; the formula's direction reaches 0.45. And notice what's missing: the dimension. Only the length of the weights counts, which is what the next chapter exploits.
6MarginsMaster's2 min
Can a confident fit be a simple one?
The Rademacher bound for linear rules depends on the weights' length, not on how many there are. To use that, measure how confidently a rule separates the data: its margin, the distance from each example to the boundary, on the right side of it. The support vector machine from part six chooses the line with the widest margin. On the pages it separates all 448 training pages, and here is the distribution of their margins: the closest page sits at 0.066 of the largest input's length. The margin loss at gamma counts the pages closer than gamma to the boundary: the share a rule gets right, but not confidently.
The bound comes in three steps. Replace the error, one when the margin is negative, with a ramp that's one below zero and zero above gamma; it lies between the error and the margin loss. Apply the Rademacher bound to the ramp. The ramp has slope one over gamma, and a contraction lemma says a Lipschitz function scales the complexity by its slope: the gap is two B R over gamma root n. The number of inputs never appears. Peter Bartlett made this the point in 1998: the size of the weights matters more than the number of them. Now illustrate it on the pages. These pages are correlated, preprocessing is fitted, and the radius is estimated from them. This is not an IID risk certificate. Small gamma: no margin loss, but a huge complexity term. Large gamma: the reverse.
Margins first explained a puzzle twenty years before deep learning's. Boosting builds a classifier from many weak ones, here single cuts on one word rate each, reweighting the examples it gets wrong. The explanation, by Schapire, Freund, Bartlett and Lee in 1998: with the training points all correct, later rounds keep pushing their margins outward, and the margin bound only cares about margins. The same shape, more training past zero training error and better on new data, is about to come back for neural networks.
7PAC-Bayes: a bound that says somethingResearch3 min
A bound that says something about a network?
Counting doesn't work for networks, so change what is bounded. Instead of one network, take a distribution over networks, a cloud of weights, and bound the average error of a network drawn from it. Before seeing any data, choose a prior P over weights. After training, the posterior Q is wherever the data moved you. David McAllester's PAC-Bayes theorem, from 1999: with high probability, the posterior's true error is close to its training error, and how close depends on just one number, the KL divergence of Q from P, part one's measure of how many nats the data had to tell you. A posterior that's broad, close to the prior, costs few nats, whatever the number of weights.
The proof is short. Start from a change of measure: an average under Q is at most the KL divergence from P plus the log of an exponential average under P. It's Gibbs' inequality from part one in disguise. For one fixed network, the chance that its training error is far from its true error is a binomial tail, so the exponential of n times their divergence averages to at most two root n. The prior was chosen without the data, so that holds averaged over P too. Markov's inequality turns the average into a statement that holds with probability one minus delta. Choose f to be n times the divergence, and use convexity: the bound. Nothing in it counts weights.
Now our own. A network with weights, trained on pages: twenty times more weights than examples. Following Dziugaite and Roy's recipe from 2017, the prior is a Gaussian centred on its random starting weights. These book pages are correlated and their preprocessing is fitted: this illustrates the calculation, rather than certifying the theorem's IID risk. Train briefly, then make the weights a cloud: a Gaussian around them, and optimize the bound itself, for steps. Watch the KL: from nats it settles near , while the cloud widens wherever the weights don't matter. The final account. Two thousand networks drawn from the cloud err on percent of the training pages, at most with confidence. The KL is nats. The same idea, with networks compressed hard, gave the first non-vacuous bounds for language models in 2024, Lotfi and colleagues; counting tokens instead of documents later that year, for models as large as Llama 2 70B.
8Compression and stabilityMaster's3 min
Two more ways to say "simple"
A third way to say a rule is simple: it can be described by a few of its own examples. Here are points, and the widest-margin line through the origin that separates them. Only points touch the margin: the support vectors. Littlestone and Warmuth showed in 1986 that such a learner generalizes like one with k parameters: its error is at most about k log n over n. The confidence term also pays for choosing k from the data. Here that's percent, much tighter than the VC bound for lines. On the pages the machine needs support vectors, and the bound is : a rule is only as simple as the examples it needs. Compression is also how the network bounds of the last chapter got tight: Arora and colleagues in 2018, and the language-model bounds, compress the network first.
A fourth: a rule is safe if it doesn't depend much on any single example. Call a learner beta-stable if swapping one training example for another changes its loss anywhere by at most beta. Then, on average, its true error exceeds its training error by at most beta, because swapping a training example for a fresh one is exactly how a training point turns into a test point. Bousquet and Elisseeff showed in 2002 that regularized learners are stable, with beta like one over lambda n. Measure it for ridge regression on the pages: swap one training page for a held-out one, and see how far any prediction moves. Stronger regularization, smaller change. And against n, the slope is -0.90, close to the predicted minus one.
Stability also applies to training itself. Run stochastic gradient descent twice, visiting the examples in the same order, on two training sets that differ in one page. The runs drift apart only when they meet the differing page: after 30 passes, by 0.066 on average, over twenty such pairs. Hardt, Recht and Singer proved in 2016 that, for convex losses, the drift grows at most in proportion to the step size times the number of steps, over n: train faster, generalize better. Here the bound is about 126 times the measured drift; true, and loose. For networks, which aren't convex, nothing this clean holds, and that's where the puzzles start.
9Memorizing nonsenseUndergraduate2 min
Can a network fit random labels?
Every bound so far charges for capacity. In 2016, Chiyuan Zhang and colleagues ran an experiment that showed why that can't be the whole story for networks. Take a network: layers of simple units, here the seventy word rates in, two layers of five hundred and twelve units, and two outputs, one per author. That's about 300 thousand weights. Train it on the 448 training pages with their true authors. It fits all of them, and gets 99.5 percent of new pages right. Now shuffle the authors, so every label is random. Same network, same training.
It fits these too, every one of them, only a little more slowly. It has memorized nonsense. And on new pages, it's at chance, as it must be. So the same network can memorize anything at all. Then counting what a model could fit can't explain why, given real labels, it finds a rule that works on new pages instead. Something in how it's trained prefers simple answers. The next two chapters prove it, in the simplest cases.
In what order does it memorize? Split the shuffled pages in two: by chance, about half got their true author back, and the rest a wrong one. A page lights up when the network gets its shuffled label right. With weights for pages, memorizing is quick.
Zhang and colleagues also turned the dial gradually, replacing a growing share of the labels with coin flips. Here that is on the pages, three seeds at each setting. Accuracy on new pages falls from percent with clean labels to with all of them random And the network fits every training label at every setting, The same network, the same training, the same zero training error, and anything from excellent to useless on new data. What it learns depends on the labels; any measure that looks only at the network and not at the data can't tell these apart.
10Implicit bias: the smallest fitMaster's2 min
Of all the perfect fits, which one does training find?
When a model has more weights than training examples, it can usually fit them all exactly, in infinitely many ways. Three weights and two equations: every point on this line fits both exactly. Which one does training pick? Run gradient descent on the squared error, starting from zero. Every step moves along a combination of the inputs, so the path never leaves the plane they span. It meets the line of exact fits at one point: the one nearest the origin, the fit with the smallest weights.
The proof is five lines. A gradient step subtracts X transpose times the residual. Start at zero, and every iterate is a combination of the training inputs: it lives in the row space of X. For full-row-rank X and a sufficiently small positive step, the squared loss goes to zero, so the limit fits every example. Only one exact fit lies in the row space: X transpose times X X transpose inverse times y, the pseudoinverse solution. And any other exact fit differs from it by a vector perpendicular to the row space, so by Pythagoras it's longer. Gradient descent, untold, chose the minimum-norm fit. That's an implicit bias: a preference the algorithm brings that no loss function asked for.
Check it with equations in unknowns. From zero, the distance to the pseudoinverse solution falls until it hits the limits of double precision, and the part of the weights outside the row space stays at rounding error the whole way. Start somewhere else, and descent still fits every equation, but stops away from the minimum-norm fit, So the answer depends on the start too: networks start near zero, with small random weights, and part nine of this series is about choosing that scale.
11Implicit bias: the widest marginMaster's2 min
What does a classifier do once it is perfect?
Classification has its own version. When the classes can be separated, the logistic loss can be made as small as you like, just by scaling the weights up, so there's no minimum at all, and infinitely many separating lines. Which direction does gradient descent head in? Here it is, step by step on a log scale. After one step the boundary is 30 degrees from the widest-margin line. After a hundred steps, 17.3; after ten thousand, 6.5; after a million, 2.9. It turns toward the support vector machine's line, slowly, while the weights keep growing and the loss keeps shrinking.
Why that line? The negative gradient is a weighted sum of the examples, each weighted by how badly it's classified. Once every point is right and the weights are large, those weights are exponentials of minus the margins. Exponentials decay so fast that the points with the smallest margins outweigh everything else: only the support vectors steer. The direction converges to a combination of support vectors with positive weights, which is exactly the form of the max-margin solution from part four's KKT conditions. Soudry and colleagues proved it in 2018 for a sufficiently small positive constant step. The weights grow like log t; for almost all datasets, direction error is bounded by a constant over log t, with an extra log log t factor in degenerate cases. Lyu and Li connected homogeneous neural networks to margin maximization in 2020.
Measure it. On a log axis of steps, the norm of the weights is a straight line: it grows by about for every factor of ten in steps, logarithmic growth. The angle falls, slowly. After a million steps the margin is , against the best possible . That slowness has a practical side: training long after the training error reaches zero keeps changing the model, toward larger margins, which is the boosting story again, now as a theorem about gradient descent.
12Double descentUndergraduate3 min
What happens past the point of fitting everything?
Here's the curve that came back. Turn each page into p random features: each feature is a fixed random mix of the seventy word rates, passed through a bend that zeroes anything negative. Only the weights on the features are learned, by least squares. When there are more features than pages, many fits match every training page exactly, so take the one with the smallest weights: of all the curves through the points, the calmest. With few features, the error on new pages falls, then rises again as p approaches the number of pages: the classical U. At exactly 448 features, as many as there are pages, the fit is forced through every point, and the error explodes. And then, past it, the error comes back down, lower than the bottom of the U.
In short: Belkin and colleagues named it double descent in 2019, and Nakkiran and colleagues found it in deep networks the same year. The training error is zero all along the second descent, so it can't be what decides. What decides is which of the many exact fits you get, and the smallest one is the simplest. And from chapter ten: gradient descent from zero finds exactly that smallest fit.
Why the peak, exactly at p equals n? Write the minimum-norm fit with the singular value decomposition of the feature matrix. It's a sum over directions, each label component divided by its singular value sigma i. Part of the labels is noise no feature explains. That part gets amplified by one over sigma, and its expected size is the noise variance times the sum of one over sigma squared. So everything hangs on the smallest singular value. Here are the feature matrix's singular values as p grows. With few features they stay well away from zero. As p approaches n, the smallest slides toward zero, and at p equals n it's only 0.0003: a square random matrix is nearly singular. Past it, with more features than pages, the smallest singular value climbs back up, and the noise is spread over directions that barely affect new pages.
The cure follows: don't divide by tiny numbers. Ridge regression adds lambda to each sigma squared, so the smallest directions are damped instead of amplified. With lambda 1 times p, the peak at 448 features is gone: the error there is 0.16, against 83.3 without it. Too little ridge leaves a bump; too much, and the fit is too timid everywhere. Nakkiran and colleagues showed in 2020 that well-tuned regularization removes the peak in such models. The peak was never a law of nature: it's an artifact of fitting noise exactly with barely enough features to do it.
13Double descent in samples and in epochsMaster's1 min
Can more data, or more training, hurt?
If the peak sits where the number of parameters equals the number of examples, then it can be reached from the other side too. Fix random features, and give the model more and more pages. With a little ridge, the curve simply falls. Nakkiran and colleagues found this sample-wise version in deep networks in 2019: for a fixed model, there's a range where more data hurts.
Nakkiran and colleagues also saw it in time: train a network longer and longer, and its test error can fall, rise, and fall again. The simplest model that does this is linear, with inputs on two very different scales. Gradient descent learns the large-scale directions first. The fast and slow curves each include the noise floor, with medians taken separately. They show two learning time scales, as Heckel and Yilmaz explained in 2021. For each draw, total test error is fast plus slow plus one noise floor; these plotted medians need not add exactly. Training error falls the whole time. When to stop training is not a question with one answer, which part twelve's grokking takes to an extreme.
14Benign overfittingResearch2 min
When is fitting the noise harmless?
Double descent showed fits that pass through every noisy label and still do well. How can fitting noise exactly be harmless? One way to chase noisy labels is to bend the whole curve; that spoils predictions elsewhere. Another is to follow the smooth truth almost everywhere, and reach each noisy label with a thin spike that touches almost no other input. That fit has zero training error, and on new data it's nearly as good as the truth. In high dimensions, the spikes come for free.
Bartlett, Long, Lugosi and Tsigler made this exact in 2020, for linear regression. Take a hundred noisy examples whose signal lives in five strong directions, and fit them exactly with the minimum-norm solution. Add D weak directions that together have a small total variance: as D grows, the excess error falls, to 0.023 with 40,000 of them, 9 percent of the noise level, though the fit reproduces every noisy label. Benign. Add instead D directions as strong as the signal's, and the excess error climbs to 5.0: the fit spreads its weight over directions that matter, and loses the signal. Harmful.
For our normalized spiked example, here is the spectral intuition: excess error has a signal-bias part, and a noise-variance part with two scales. The first counts the strong directions against the examples. The second compares n with the effective rank of the tail: how many directions share the weak variance. Many small directions can each absorb a little of the noise without moving predictions much: those are the spikes. And the tail as a whole acts like a ridge penalty on the strong directions; the resulting signal bias must also be small. With few strong directions, a broad weak tail, and small signal bias, interpolation can be benign. General guarantees require precise spectral and distributional conditions. For real networks the picture is more often in between: Mallinar and colleagues in 2022 called it tempered.
15Flat minima and the sharpness debateResearch2 min
Do flat valleys generalize better?
An older idea about why networks generalize: the shape of the valley training ends in. Suppose the test loss is the training loss shifted a little, because the test data differs a little. At the bottom of a flat valley, the shift costs almost nothing; at the bottom of a sharp one, it costs a lot. Hochreiter and Schmidhuber argued in 1997 that flat minima are simpler: their weights can be written down with fewer bits. In 2017 Keskar and colleagues reported that training with large batches finds sharper minima, and generalizes worse.
Test it, small. networks learn from points labelled by a teacher network, with four batch sizes, two step sizes and three seeds, . Sharpness is the largest eigenvalue of the training loss's Hessian, measured with part four's Hessian-vector products. Large studies agree on that much: across many settings, sharpness predicts generalization inconsistently, as Andriushchenko and colleagues found in 2023.
There's a deeper problem, pointed out by Dinh, Pascanu and the Bengios in 2017. A ReLU passes a positive scale straight through. So multiply the first layer by a, divide the second by a, and the network computes exactly the same function, to rounding error on every output. Same predictions, same test error. But its sharpness changes by a factor of 9 across these rescalings. Sharpness, as measured, depends on how the weights are written down, not only on what the network does, so it can't be the whole explanation. Scale-invariant versions, and training that seeks flat regions on purpose, like sharpness-aware minimization, came next; what sharpness has to do with the step size is part eleven's edge of stability.
16Distribution shiftEngineering2 min
What if the test data comes from somewhere else?
Everything so far assumed the test data comes from the same distribution as the training data. Often it doesn't. Here the true relationship is a cubic, the training inputs cluster around a half, and the inputs we'll be tested on cluster around zero. The rule from x to y hasn't changed, only where the inputs fall: covariate shift. Fit a straight line by least squares, and it serves the training region, where most of the points are. Weight each training point by how much more likely its x is under the test distribution, and the line turns to serve where the test inputs will be.
Why weights? The risk we care about averages the loss over the test distribution q. Provided p is positive wherever q is positive, multiply and divide by the training distribution p. Now it's an average over training inputs, of the loss times the ratio q over p. For a fixed predictor and independent draws from p, the error weighted by the exact ratio is an unbiased estimate of its test error. Hidetoshi Shimodaira proposed it in 2000. The price is the one part five met in importance sampling: a few points with huge weights dominate, and the effective sample size shrinks.
Over a thousand runs of training points: plain least squares has a test error of . Flattening the weights, the square root of the ratio, trades a little bias for less variance; : . In practice nobody knows q over p. But a classifier trained to tell training inputs from unlabelled test inputs estimates it, from the odds it assigns: . The exact weights leave an effective sample of only points out of . And covariate shift is the easy case: when the label frequencies change, or the rule itself drifts, the fixes are different, and sometimes there are none. Part thirty-one returns to this, as the problem of evaluating models on data like the world's.
17Memorization in language modelsEngineering4 min
What does a model remember word for word?
The last chapter is about what a model remembers exactly. Generalizing is not copying, but large models do both. In 2019 Nicholas Carlini and colleagues planted random secrets in training data and measured how readily models gave them back. In 2021 they pulled training text out of GPT-2 by sampling and filtering: over six hundred of eighteen hundred candidates were verbatim copies of training documents, some with names and contact details. In 2023 they measured it at scale: memorization grows log-linearly with model size, with how often a passage is repeated, and with the length of the prompt; the six-billion-parameter GPT-J had memorized at least one percent of its training data. Their test: give the model a prefix from the training data, and see whether greedy decoding continues it exactly.
Run that test on our own novels model. Its training text has million tokens, and long passages rarely repeat: no 64-token passage occurs more than times. Prompted with the first 32 tokens of a training passage, it reproduces the next 32 exactly in cases out of tried. This small model rarely reproduces these tested passages exactly; that does not establish that it memorized none of its training text. What makes words stick is repetition.
To see repetition at work, plant it. Continue training our model on its own text, into which passages sampled from held-out text are planted once each, more twice each, and so on up to times, with more not planted, as a control. Through steps of training, the passages planted most often become extractable first. By the end: percent of passages planted once, percent of those planted eight times, and percent of those planted times come back word for word; the control, percent.
Since then, memorization has become a practical and legal question. Deduplicating training data reduces it. In 2023 Nasr and colleagues found that asking a chat model to repeat one word forever made it drift into reciting training data. In 2025 Cooper and colleagues showed that some open-weight models have memorized large parts of popular books. Legal outcomes depend on the jurisdiction, model and evidence. In November 2025 a Munich court held that song lyrics memorized in a model are a copy, an appealable ruling at the time, while London's High Court held that the image model's weights at issue were not one. In the June 2025 Bartz and Kadrey cases, American judges had found the training uses fair on the records before them. Bartz separately rejected fair use for pirated library copies. And in early 2026 researchers reported extracting near-complete books from production chat models. Whether a model has learned or copied is no longer only a question for learning theory.
Recap, problems, and what comes nextAll tracks2 min
Let's take stock. Risk is the error on everything the world could send; training error flatters it, and the gap splits into approximation and estimation. Error splits into bias, variance and noise. One rule's test score is trustworthy by Hoeffding; choosing among many costs the log of how many, and an infinite family costs its growth function, a polynomial by Sauer and Shelah. Rademacher complexity and margins measure capacity by the size of the weights; under their assumptions, PAC-Bayes, compression and stability give useful bounds even for networks. Our own calculation was illustrative. Then the puzzles: networks memorize noise, gradient descent chooses the smallest fit and the widest margin, error descends twice, overfitting can be benign, and flatness is not the whole story. And when the data moves, or repeats, generalization gives way to weighting, and to memory.
Margins return in part nine, in the perceptron's convergence proof. Which minimum training finds, and how sharp it is, is part eleven's subject. Models far bigger than their data, grokking and scaling laws are part twelve's. And held-out scores, contaminated test sets, memorization and privacy come back when we look inside models and ask whether to trust them, in parts thirty and thirty-one.
Here are six problems to try, from sizing a test set to the variance of importance weights. Pause here and work through them; full solutions are in this part's notes.
Next time: networks themselves. From the perceptron and its winters to backpropagation; why a stack of simple layers can approximate any function, how depth cuts space into pieces, and how to start and keep signals alive through many layers. And the first neural language model joins the scoreboard.
Shalev-Shwartz and Ben-David's Understanding Machine Learning is the clearest book on the theory, and Francis Bach's Learning Theory from First Principles the most up to date. Thanks for watching, and see you in part nine.
Where it goes next. Margins return in Part 9 in the perceptron's convergence proof. Which minimum training finds, sharpness and the edge of stability are the subject of Part 11; models far bigger than their data, grokking and scaling laws belong to Part 12; held-out scores, contaminated test sets, memorization and privacy come back in Parts 30 and 31.
Key results
The part's results in one place, for revision.
Try it
Lab 8 · The smallest fit, and the peak at the interpolation threshold
Run gradient descent from zero on 20 equations in 60 unknowns and compare it with the pseudoinverse; then fit p random ReLU features to n = 40 noisy examples by the minimum-norm rule and trace the test error as p passes n.
python -m videos.ai.labs 8
needs numpy, scipy, matplotlib · download lab08.py ·
source on GitHubGD from zero: distance to the min-norm fit X+ y 7.0e-16 (residual 1.1e-16)
GD from a random start: distance to X+ y 7.3228 (the start's null-space part: 7.3228)
test error at the U's bottom (p < n) 0.341 at p = 12
test error at p = n = 40 39.7 (ridge 0.1: 0.287)
test error at p = 400 0.429
smallest singular value of the features 0.0048 at p = n (0.131 at p = 26, 0.194 at p = 400)
The minimum-norm fit divides the noise by each singular value; at p = n the smallest one is nearly zero, so the error peaks there and falls again as more features push the spectrum away from zero.
The code (102 lines; it asserts its own result)
"""Lab 8: watch gradient descent land on the minimum-norm fit, then find the double-descent peak at p = n."""
import numpy as np
from videos.coursekit import labs
from explainer.ai.autodiff import Tensor
TITLE = "The smallest fit, and the peak at the interpolation threshold"
GOAL = ("Run gradient descent from zero on 20 equations in 60 unknowns and compare it with the pseudoinverse; then fit "
"p random ReLU features to n = 40 noisy examples by the minimum-norm rule and trace the test error as p passes n.")
TASKS = [
"Set the label noise to 0. What is left of the peak at p = n, and which factor in the noise formula explains it?",
"Fix p = 40 features and vary the number of examples n from 10 to 160. Where does more data make the test error worse?",
"Start gradient descent from a random point instead of zero, and show that the weights it forgets to remove are orthogonal to every row of X.",
]
def descend(X, y, w0, steps=1500):
"""Gradient descent on half the squared error, with the gradient from the series' autodiff."""
w = Tensor(w0.copy(), requires_grad=True)
eta = 1 / np.linalg.eigvalsh(X @ X.T)[-1] # 1 / the largest squared singular value
for _ in range(steps):
w.grad[:] = 0
r = Tensor(X) @ w - y
((r * r).sum() * 0.5).backward()
w.data -= eta * w.grad
return w.data
def features(x, A, b):
return np.maximum(x @ A + b, 0) / np.sqrt(A.shape[1])
def min_norm(F, y, ridge=1e-10):
"""Least squares on F's columns; beyond p = n the fit of smallest norm, F'(FF')^-1 y. (ridge > 0: ridge regression.)"""
n, p = F.shape
if p <= n:
return np.linalg.solve(F.T @ F + ridge * np.eye(p), F.T @ y)
return F.T @ np.linalg.solve(F @ F.T + ridge * np.eye(n), y)
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. implicit bias: gradient descent from zero stays in the row space and stops at X^+ y
X, y = rng.standard_normal((20, 60)), rng.standard_normal(20)
pinv = X.T @ np.linalg.inv(X @ X.T) # X+ for a wide matrix of full row rank
w_min = pinv @ y
w_gd = descend(X, y, np.zeros(60))
start = rng.standard_normal(60)
w_far = descend(X, y, start)
null_part = start - pinv @ (X @ start) # the start's component outside the row space
d_zero, d_far = np.linalg.norm(w_gd - w_min), np.linalg.norm(w_far - w_min)
lab.row("GD from zero: distance to the min-norm fit X+ y", f"{d_zero:.1e} (residual {np.abs(X @ w_gd - y).max():.1e})")
lab.row("GD from a random start: distance to X+ y", f"{d_far:.4f} (the start's null-space part: {np.linalg.norm(null_part):.4f})")
assert d_zero < 1e-8, "from zero, gradient descent finds the minimum-norm interpolant"
assert abs(d_far - np.linalg.norm(null_part)) < 1e-8, "what gradient descent cannot see, it leaves untouched"
# 2. double descent: least squares on p random ReLU features, minimum norm beyond p = n
n, d, noise, draws = 40, 8, 0.5, 30
ps = np.array([4, 8, 12, 16, 20, 26, 32, 36, 39, 40, 41, 44, 50, 60, 80, 120, 200, 400])
beta = rng.standard_normal(d) / np.sqrt(d)
err, err_ridge, smin = (np.zeros((draws, len(ps))) for _ in range(3))
for k in range(draws):
xtr, xte = rng.standard_normal((n, d)), rng.standard_normal((200, d))
ytr, yte = xtr @ beta + noise * rng.standard_normal(n), xte @ beta
A, b = rng.standard_normal((d, ps.max())), rng.standard_normal(ps.max())
for j, p in enumerate(ps):
F, G = features(xtr, A[:, :p], b[:p]), features(xte, A[:, :p], b[:p])
err[k, j] = np.mean((G @ min_norm(F, ytr) - yte) ** 2)
err_ridge[k, j] = np.mean((G @ min_norm(F, ytr, ridge=0.1) - yte) ** 2)
gram = F.T @ F if p <= n else F @ F.T # its eigenvalues are the squared singular values
smin[k, j] = np.sqrt(max(np.linalg.eigvalsh(gram)[0], 0.0))
med, med_ridge, med_smin = np.median(err, 0), np.median(err_ridge, 0), np.median(smin, 0)
at_n = int(np.flatnonzero(ps == n)[0])
bottom = med[:at_n].min()
lab.row("test error at the U's bottom (p < n)", f"{bottom:.3f} at p = {ps[np.argmin(med[:at_n])]}")
lab.row("test error at p = n = 40", f"{med[at_n]:.1f} (ridge 0.1: {med_ridge[at_n]:.3f})")
lab.row("test error at p = 400", f"{med[-1]:.3f}")
lab.row("smallest singular value of the features", f"{med_smin[at_n]:.4f} at p = n ({med_smin[at_n - 4]:.3f} at p = {ps[at_n - 4]}, {med_smin[-1]:.3f} at p = 400)")
lab.note = ("The minimum-norm fit divides the noise by each singular value; at p = n the smallest one is nearly "
"zero, so the error peaks there and falls again as more features push the spectrum away from zero.")
assert np.argmax(med) == at_n and med[at_n] > 5 * bottom, "the peak sits at the interpolation threshold"
assert med[-1] < med[at_n] / 5, "past the threshold the error comes back down"
assert np.argmin(med_smin) == at_n, "the smallest singular value is smallest at p = n"
assert med_ridge[at_n] < med[at_n] / 5, "a little ridge removes the peak"
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].loglog(ps, med, "o-", color=labs.GOLD, ms=4, label="minimum-norm least squares")
ax[0].loglog(ps, med_ridge, "o-", color=labs.BLUE, ms=3, label="ridge, penalty 0.1")
ax[0].axvline(n, color=labs.MUTED, ls=":", lw=1)
ax[0].text(n * 1.08, med.max() * 0.6, "p = n", color=labs.MUTED)
ax[0].set(title="Test error against the number of features", xlabel="random ReLU features p (n = 40 examples)",
ylabel="test mean squared error (median of 30 draws)")
ax[0].legend(loc="upper left")
ax[1].loglog(ps, med_smin, "o-", color=labs.RED, ms=4)
ax[1].axvline(n, color=labs.MUTED, ls=":", lw=1)
ax[1].set(title="Why: the smallest singular value touches zero at p = n", xlabel="random ReLU features p",
ylabel="smallest singular value of the feature matrix")
lab.fig = fig
return lab
Now change it
- Set the label noise to 0. What is left of the peak at p = n, and which factor in the noise formula explains it?
- Fix p = 40 features and vary the number of examples n from 10 to 160. Where does more data make the test error worse?
- Start gradient descent from a random point instead of zero, and show that the weights it forgets to remove are orthogonal to every row of X.
Problems, with solutions
Try each problem before opening its solution.
- Sizing a test set. How many test examples guarantee, with probability 0.99, that the error rates of 100 fixed
models are all within 0.02 of their true values?
Solution
Union bound over Hoeffding: 2·100·e^(−2n·0.02²) ≤ 0.01 ⇔ n ≥ ln(20,000)/(2·0.0004) = 9.903/0.0008 ≈ 12,380.
- Intervals. Show intervals on the line have VC dimension 2 and growth function C(n, 2) + n + 1.
Solution
Two points: an interval can cover neither, either or both. Three ordered points cannot be labelled +, −, +: an interval containing the outer two contains the middle one. On n ordered points an interval labels + a contiguous run: choose its first and last point (C(n, 2) runs of length ≥ 2, n of length 1) or the empty run: C(n, 2) + n + 1 = Σᵢ₌₀² C(n, i), the Sauer–Shelah bound with d = 2.
- Massart's lemma for the ℓ₁ ball. For {x ↦ w·x : |w|₁ ≤ B} with |xᵢ|∞ ≤ X, show R̂_S ≤ BX√(2 ln(2d)/n).
Solution
sup over the ℓ₁ ball of w·v is B|v|∞ (Hölder; attained at a signed coordinate vector), so R̂_S = (B/n) E maxⱼ,± ±Σᵢσᵢxᵢⱼ, a maximum of N = 2d sums σ·a with |a|₂ ≤ X√n. Massart: E max ≤ max|a|₂ √(2 ln N). Hence R̂_S ≤ (B/n) X√n √(2 ln 2d).
- Gradient descent from w₀. Show that on ½|Xw − y|² with d > n and a small step, gradient descent from w₀
converges to X⁺y + (I − X⁺X)w₀.
Solution
P = X⁺X projects onto the row space. Every step adds Xᵀ(·) ∈ row(X), so (I − P)w_t = (I − P)w₀ forever, and Xw_t = XPw_t: the row-space part u_t = Pw_t follows gradient descent on ½|Xu − y|² inside row(X), where the loss is strictly convex with unique minimizer X⁺y. So w_t → X⁺y + (I − P)w₀, at distance |(I − P)w₀| from the minimum-norm fit (chapter 10 measured 5.970 for both).
- KL between Gaussians. For Q = N(μ, s²I), P = N(μ₀, λI) in d dimensions derive KL(Q‖P).
Solution
Per coordinate, E_Q[ln q − ln p] = −½ ln(2πs²) − ½ + ½ ln(2πλ) + (s² + (μ − μ₀)²)/(2λ); summing over d coordinates, KL = ½(ds²/λ + |μ − μ₀|²/λ − d − d ln(s²/λ)). (With a different s per coordinate, as in chapter 7, sum the per-coordinate terms.)
- Importance weights. Show the importance-weighted training error is unbiased for the test error, and that with
p = N(0, 1), q = N(0, 4) the weights have infinite variance.
Solution
E_p[w(x)ℓ(x)] = ∫p(q/p)ℓ = E_q[ℓ]. E_p[w²] = ∫q²/p dx ∝ ∫exp(−x²/4 + x²/2) dx = ∫exp(x²/4) dx = ∞: the test distribution has heavier tails than the training one, and the effective sample size collapses.
Notes and sources
Glossary
| English | 中文 |
|---|---|
| risk, empirical risk, Bayes risk, Bayes rule | 风险,经验风险,贝叶斯风险,贝叶斯规则 |
| excess risk; approximation error, estimation error | 超额风险;近似误差,估计误差 |
| bias–variance decomposition | 偏差–方差分解 |
| union bound; PAC (probably approximately correct) | 联合界;PAC(概率近似正确) |
| shatter, VC dimension, growth function | 打散,VC维,增长函数 |
| Sauer–Shelah lemma; ghost sample (symmetrization) | 绍尔–谢拉引理;影子样本(对称化) |
| (empirical) Rademacher complexity; McDiarmid's inequality | (经验)拉德马赫复杂度;麦克迪尔米德不等式 |
| margin, margin loss, ramp loss, contraction lemma | 间隔,间隔损失,斜坡损失,压缩引理 |
| boosting, decision stump | 提升法,决策树桩 |
| PAC-Bayes; prior, posterior; change of measure | PAC-贝叶斯;先验,后验;测度变换 |
| vacuous / non-vacuous bound | 空的界 / 非空的界 |
| sample compression scheme | 样本压缩方案 |
| (uniform) stability | (一致)稳定性 |
| random labels, label corruption | 随机标签,标签污染 |
| implicit bias; minimum-norm interpolant; row space | 隐式偏好;最小范数插值解;行空间 |
| max-margin direction | 最大间隔方向 |
| double descent; interpolation threshold; sample-wise, epoch-wise | 双下降;插值阈值;按样本数的,按训练轮数的 |
| benign / tempered / harmful overfitting; effective rank | 良性 / 温和 / 有害过拟合;有效秩 |
| flat minimum, sharpness, sharpness-aware minimization (SAM) | 平坦极小值,尖锐度,锐度感知最小化(SAM) |
| distribution shift, covariate shift, label shift, concept drift | 分布偏移,协变量偏移,标签偏移,概念漂移 |
| importance weighting, effective sample size | 重要性加权,有效样本量 |
| memorization, extractable, canary, deduplication | 记忆,可提取,金丝雀(植入的测试文本),去重 |
Sources
- Carlini et al., Extracting Training Data from Large Language Models (USENIX Security 2021): 1,800 candidates, "over 600" verbatim (arXiv:2012.07805). Carlini et al., Quantifying Memorization Across Neural Language Models (ICLR 2023, arXiv:2202.07646): three log-linear relationships; GPT-J memorizes at least 1% of the Pile; extractability defined with greedy decoding from a k-token prefix (the definition used in chapter 17).
- Cooper et al., Extracting memorized pieces of (copyrighted) books from open-weight language models (arXiv:2505.12546, 2025): Llama 3.1 70B memorizes some books, such as the first Harry Potter, almost entirely. Ahmed, Cooper, Koyejo & Liang, Extracting books from production language models (arXiv:2601.02671, January 2026): near-complete extraction of a book from some production models (one with a jailbreak).
- GEMA v. OpenAI, Munich Regional Court I, 11 November 2025 (42 O 14139/24): memorized lyrics are reproductions; not final (OpenAI said it would appeal). Getty Images v. Stability AI, [2025] EWHC 2863 (Ch), 4 November 2025: the model weights are not an infringing copy. Bartz v. Anthropic (23 June 2025) and Kadrey v. Meta (25 June 2025), N.D. Cal.: training held fair use (Bartz: not for pirated library copies). Later 2026 rulings (e.g. GEMA v. Suno, reported July 2026) are not on screen: only law-firm summaries were found.
- Lotfi et al., Non-Vacuous Generalization Bounds for Large Language Models (ICML 2024) and Unlocking Tokens as Data Points for Generalization Bounds on Larger Language Models (NeurIPS 2024, up to LLaMA2-70B).
- Valiant's Turing Award is the 2010 award (presented 2011).
- The VC bound on screen is Vapnik's form, √((d(ln(2n/d) + 1) + ln(4/δ))/n); the four-step proof shown gives the same rate with larger constants.
- Shimodaira (2000) is the source of importance-weighted least squares under covariate shift; the setup of chapter 16 (training inputs N(0.5, 0.5²), test inputs N(0, 0.3²), y = −x + x³) follows the example common in that literature and is labelled illustrative.
Sources
Books: S. Shalev-Shwartz & S. Ben-David, Understanding Machine Learning (2014); M. Mohri, A. Rostamizadeh & A. Talwalkar, Foundations of Machine Learning, 2nd ed. (2018); F. Bach, Learning Theory from First Principles (2024); V. Vapnik, The Nature of Statistical Learning Theory (1995); T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning (2009).
Papers: Hoeffding (1963); Vapnik & Chervonenkis (1971); Sauer (1972); Shelah (1972); Valiant, A Theory of the Learnable (1984); Littlestone & Warmuth (1986); Geman, Bienenstock & Doursat (1992); Hochreiter & Schmidhuber, Flat Minima (1997); Bartlett (1998); Schapire, Freund, Bartlett & Lee, Boosting the Margin (1998); McAllester (1999); Shimodaira (2000); Koltchinskii (2001); Bartlett & Mendelson (2002); Bousquet & Elisseeff (2002); Seeger (2002); Maurer (2004); Hardt, Recht & Singer (2016); Zhang, Bengio, Hardt, Recht & Vinyals (2017); Dziugaite & Roy (2017); Keskar et al. (2017); Dinh, Pascanu, Bengio & Bengio (2017); Soudry, Hoffer, Nacson, Gunasekar & Srebro (2018); Arora, Ge, Neyshabur & Zhang (2018); Belkin, Hsu, Ma & Mandal (2019); Nakkiran et al., Deep Double Descent and Optimal Regularization Can Mitigate Double Descent (2020); Lyu & Li (2020); Bartlett, Long, Lugosi & Tsigler (2020); Heckel & Yilmaz (2021); Foret et al., SAM (2021); Mallinar et al. (2022); Andriushchenko et al. (2023); Lotfi et al. (2022, 2024, 2024); Carlini et al. (2019, 2021, 2023); Kandpal, Wallace & Raffel (2022); Lee et al. (2022); Nasr et al. (2023); Cooper et al. (2025); Ahmed, Cooper, Koyejo & Liang (2026).
About this partfrom its README
Part 8 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 is fitted to examples; why should it work on anything else? This part
defines risk, empirical risk and Bayes risk; derives bias and variance; builds the classical guarantees one step at a
time (Hoeffding and the union bound, PAC learning, shattering and the growth function, Sauer–Shelah and the VC bound,
Rademacher complexity, margins); computes bounds that still say something for a network (PAC-Bayes, compression,
stability); then the experiments that broke the classical story and the explanations since (random labels, the
implicit bias of gradient descent, double descent in features, samples and epochs, benign overfitting, flat minima);
and ends where generalizing stops being enough: distribution shift and memorization in language models. The history
runs from Hoeffding (1963), Vapnik and Chervonenkis (1971) and Valiant (1984) to Zhang et al. (2017), Belkin et al.
(2019), Bartlett et al. (2020), Carlini et al. (2019–2023), and the 2024–26 state of the debate (non-vacuous bounds for
language models; memorization in court). Everything is computed by compute.py, small and on the CPU, mostly on Part
6's pages (Austen and Dickens: 448 pages to train, 191 held out) and on the series' novels model.
- The gap (hook). Part 6's nearest-neighbour vote: 93% of its own training pages, 68% of new ones; how we got here, 1963 to 2025, evenly spaced; the plan.
- 1. Risk, and the best possible rule. Two Gaussian classes (illustrative); risk and empirical risk (definition card); the Bayes rule and Bayes risk derived on a ladder (R* = 0.217, the overlap; the Bayes rule says 1 on an interval); Cover & Hart (1967). Threshold rules learned from n = 10 … 2,560 examples, 400 samples each: training error 15.2% against true risk 27.4% at n = 10, both near the best threshold's 23.0% at n = 2,560; excess risk = approximation + estimation.
- 2. Bias and variance, derived. Sixteen noisy points, 200 draws: lines (bias), degree 12 (variance), degree 5; E(y − f̂)² = bias² + variance + σ² derived step by step; Geman, Bienenstock & Doursat (1992); the U measured over degrees 0–15, with the directly measured test error within 1% of the sum at every degree.
- 3. One rule, then many. Hoeffding (theorem card; derived in Part 5); a 30% error rate measured on 10, 40, 160, 640 test cases, 100,000 times each: 27%, 39%, 81%, 99% of measurements within 5 points; the tail at n = 160 against Hoeffding and Chebyshev; test cases for ±5 points at 95%: exactly 315, Hoeffding 738, Chebyshev 1,680. 1,000 useless rules on coin-flip labels: the best scores 34% on 100 examples and 50.4% on 10,000 fresh ones; the union bound derived; the best training error, the 95% largest gap and the union bound for 1 … 10⁶ rules, exactly from the binomial (gap 10 → 27 points, bound 14 → 30); PAC learning (Valiant 1984).
- 4. Shattering and the VC bound. Lines shatter 3 points, not 4 (XOR); VC dimension (definition card); half-planes give 22 of the 32 labellings of 5 points; growth functions counted exactly by a rotating line (n² − n + 2 = 242 of 65,536 at n = 16; intervals meet Sauer–Shelah exactly); the Sauer–Shelah lemma (theorem card); the VC bound in four steps (ghost sample, union bound, Sauer–Shelah, solve); on 448 pages: lines in the plane 0.23, a linear rule on 70 rates 0.76 (60,400 pages for 0.1), and nothing for the 300,034-weight network.
- 5. Rademacher complexity. Linear rules on 1 … 70 word rates fitting coin flips (53% → 68%); the empirical Rademacher complexity (definition card); the bound (Koltchinskii 2001; Bartlett & Mendelson 2002); for |w| ≤ B, derived exactly (Cauchy–Schwarz, Jensen, uncorrelated signs): measured within 1.2% of B√(Σ|xᵢ|²)/n at every n, 20,000 random directions reaching 0.21 against the formula's 0.45.
- 6. Margins. The SVM on the pages (separable; 99.0% on new pages; the closest page at 0.066 of the largest input); the margin bound in three steps (ramp loss, Rademacher, contraction); Bartlett (1998); computed over γ: best 1.41, vacuous (the same margins would need about 6,000 pages); AdaBoost on stumps: training error 0 at round 19, test error 3.7% then, 0.5% at round 45, 1.6% at round 400, margin distributions moving right (Schapire, Freund, Bartlett & Lee 1998).
- 7. PAC-Bayes. Priors, posteriors, the theorem (McAllester 1999; Seeger 2002; Maurer 2004); its proof in four lines (change of measure, the binomial tail, Markov, Jensen); our 70 → 128 → 1 network (9,217 weights, 448 pages), Dziugaite & Roy's recipe, prior at the random initialization: 10,000 steps of optimizing the bound replayed (KL from thousands to 136 nats); 2,000 sampled networks err on 1.6% of the training pages (≤ 2.7% with confidence); the bound on the posterior's error is 35.6%, non-vacuous, against 2.8% measured on the test pages; Lotfi et al. (2024).
- 8. Compression and stability. The SVM on 200 separable points needs 2 support vectors (retrained on them alone: the same line, 1.5 × 10⁻⁹); the Littlestone–Warmuth bound 6.9% against VC 0.29; on the pages 47 support vectors, 0.72; uniform stability (definition card; Bousquet & Elisseeff 2002) measured for ridge regression (slope −0.90 against n, predicted −1); SGD twice on sets differing in one page (Hardt, Recht & Singer 2016): drift 0.066 after 30 passes against the bound's 8.4.
- 9. Memorizing nonsense. The 70 → 512 → 512 → 2 network (300,034 weights): true authors 99.5% on new pages, shuffled authors fit completely and 51% on new pages (Zhang et al.); the order of memorizing replayed page by page; the corruption sweep (0 … 100% of labels replaced by coin flips, three seeds): test accuracy 99.3% → 92.5% → 83.2% → 73.5% → 65.8% → 51.7%, every label fit within 20–40 steps.
- 10. Implicit bias: the smallest fit. Three weights, two equations, in 3D: gradient descent from zero stays in the row space and lands on the minimum-norm fit; the five-line proof; checked with 20 equations in 60 unknowns: distance to X⁺y 1.2 × 10⁻¹⁵, the part outside the row space 1.1 × 10⁻¹⁵; from a random start it stops 5.97 away, exactly the start's null-space part.
- 11. Implicit bias: the widest margin. Logistic regression by gradient descent on separable points, a million steps replayed: 30° from the max-margin direction after one step, 2.9° after 10⁶, |w| growing like log t; why (exponential tails, support vectors, KKT); Soudry et al. (2018), Lyu & Li (2020); angle × ln t falls from 73 to 41.
- 12. Double descent. Least squares on p random ReLU features of the pages (5 draws each): the U, a peak of 83 at p = n = 448, and 0.17 at p = 6,000 (below the U's 0.22); the minimum-norm fit's weights; why: β̂ = Σ uᵢᵀt/σᵢ vᵢ, noise amplified by Σ1/σᵢ², the smallest singular value 0.0003 at p = n (the spectrum sliding to zero, animated); ridge λ = p removes the peak (0.16 at p = n); Belkin et al. (2019), Nakkiran et al. (2020).
- 13. Double descent in samples and in epochs. p = 200 fixed features, n = 20 … 448 pages: the error rises from 0.30 to 19.8 at n = p (more data hurts), ridge flat; epoch-wise in a linear model with two feature scales (Heckel & Yilmaz 2021): low 1.97 at step 10, peak 3.31 at step 467, then 0.41, decomposed into fast and slow directions.
- 14. Benign overfitting. Smooth-plus-spikes against bending (schematic); 100 noisy examples, signal in 5 directions, plus D weak directions of total variance 5: excess error 0.023 at D = 40,000 (9% of the noise), against 5.0 with D strong ones; the effective-rank conditions (Bartlett, Long, Lugosi & Tsigler 2020); tempered overfitting (Mallinar et al. 2022).
- 15. Flat minima and the sharpness debate. Hochreiter & Schmidhuber (1997), Keskar et al. (2017); 24 networks (10 → 256 → 2) on a teacher's 300 points, batch 4 … 300, two step sizes, three seeds, each trained to training loss 0.01 (21 got there within 4,000 epochs): sharpness (top Hessian eigenvalue by Hessian-vector products) 0.70 at batch 4 against 0.89 at batch 300; rank correlation with test error −0.41 (test errors 19.4–20.6%): the sharper ones did slightly better here; the rescaling W₁·a, W₂/a leaves the function exactly unchanged and moves sharpness from 0.88 to 7.8 (Dinh et al. 2017); SAM (Foret et al. 2021); Andriushchenko et al. (2023).
- 16. Distribution shift. Covariate shift after Shimodaira (2000): least squares 0.316, importance-weighted 0.098 (the best line for the test inputs: 0.094), flattened 0.101, with weights estimated by a domain classifier 0.099 (1,000 runs); the derivation; effective sample size 42 of 100.
- 17. Memorization in language models. Carlini et al. (2019, 2021, 2023); the extraction test; the novels model: no 64-token training passage repeats more than 10 times and none of 436 is extracted, but the run before the first mistake grows with repetition (0.46 tokens seen once, 2.6 seen 9–16 times, 0.51 held out); the model trained on (279 steps, three passes over 250,000 tokens of its own text) with 16 unseen passages planted 1, 2, 4, … 64 times each: exactly extracted 0%, 6%, 19%, 81%, 100%, 100%, 100%, against 0% for 16 never planted, the replay showing the most repeated ones memorized first; a 64-times passage reproduced word for word on screen; deduplication (Kandpal et al. 2022; Lee et al. 2022), Nasr et al. (2023), Cooper et al. (2025), GEMA v. OpenAI (Munich, November 2025), Getty Images v. Stability AI (London, November 2025), Ahmed, Cooper et al. (2026).
- Recap, where it comes back, problems, Part 9's teaser, references.
What is computed and built
| Item | Result |
|---|---|
| risk | Bayes risk 0.217; best threshold 0.230; n = 10: training 0.152, true 0.274; n = 2,560: 0.227, 0.231 |
| bias–variance | best degree 5; measured test error within 0.8% of bias² + variance + σ² at every degree |
| Hoeffding | within ±5 points: 27%, 39%, 81%, 99% at n = 10, 40, 160, 640; n for 95%: exact 315, Hoeffding 738, Chebyshev 1,680 |
| union bound (n = 100) | best of 1 … 10⁶ useless rules: 51% → 27% training error; 95% largest gap 10 → 27 points; bound 14 → 30 |
| growth function | half-planes n² − n + 2 (242 at n = 16), 22 of 32 at n = 5; intervals = Sauer–Shelah exactly |
| VC bound, 448 pages | lines in the plane 0.23; linear on 70 rates 0.76 (0.1 needs 60,400 pages) |
| Rademacher | coin flips fitted 53% (1 rate) → 68% (70 rates); norm-bounded linear: measured ≥ 98.9% of the bound |
| margins | SVM separates the pages, 99.0% test, 47 SVs; margin bound 1.41 (needs ≈ 6,000 pages for 0.5) |
| AdaBoost | train error 0 at round 19 (test 3.7%); test 0.5% at round 45; 1.6% at round 400 |
| PAC-Bayes | 9,217 weights, KL 136 nats, λ = 0.042; Q's training error 1.6% (≤ 2.7%); bound 0.356; Q's test error 2.8% |
| compression | 2 support vectors of 200: bound 0.069 (VC 0.29); pages: 47 of 448, 0.72 |
| stability | ridge: slope −0.90 against n; SGD drift 0.066 after 30 passes, bound 8.4 |
| random labels | true labels 99.5% test; shuffled: all fit, 51.3% test; corruption 0 → 100%: 99.3% → 51.7% |
| min-norm | distance to X⁺y 1.2e-15; other start 5.970 away = predicted 5.970 |
| max margin | 30.0° → 2.9° after 10⁶ steps; margin 1.088 of 1.116; angle × ln t 73 → 41 |
| double descent | U bottom 0.22 (p = 112); 83 at p = n = 448; 0.17 at p = 6,000; σmin/√p = 0.0003 at p = n; ridge λ = p: 0.16 |
| sample-wise | p = 200: error 0.30 (n ≈ 60) → 19.8 at n = 200 |
| epoch-wise | 1.97 (step 10) → 3.31 (step 467) → 0.41 |
| benign | spiked: excess 0.023 at D = 40,000 (noise 0.25); isotropic 4.99 |
| sharpness | 21 of 24 runs reach loss 0.01; λmax 0.70 (batch 4) vs 0.89 (batch 300); Spearman ρ(λmax, test error) = −0.41; rescaling: same function, λmax 0.88 → 7.8 |
| covariate shift | test MSE: OLS 0.316, IW 0.098, flattened 0.101, estimated 0.099; best line 0.094; ESS 42/100 |
| memorization (novels model) | 0 of 436 training passages extracted; run before the first miss 0.46 → 2.6 tokens with repetition (held out 0.51) |
| canary | extracted after 279 steps: planted 1×, 2×, 4×, 8×, 16×, 32×, 64×: 0%, 6%, 19%, 81%, 100%, 100%, 100%; never planted 0% |
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Risk, empirical risk, Bayes risk.
- Bias–variance, derived.
- Hoeffding (simulated); finite classes by union bound.
- Growth function, Sauer–Shelah, the VC bound.
- Rademacher complexity; a bound for norm-bounded linear models; margins.
- PAC-Bayes (KL from Part 1); compression and stability bounds.
- Random labels (Zhang et al.).
- Implicit bias: GD finds the min-norm interpolant (proof), max-margin for logistic (Soudry et al.).
- Double descent explained by 1/σ at the interpolation threshold; sample- and epoch-wise; benign overfitting.
- Flat minima and the sharpness debate.
- Distribution shift: covariate shift, importance weighting.
- Memorization in LLMs (extractable training data).
Visuals: shattering animations; Hoeffding histograms tightening; the singular spectrum sliding to zero at the peak.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
- 测试集要多大。 要以0.99的概率保证100个固定模型的错误率都和真实值相差不超过0.02,需要多少个测试样本? 解答。 对霍夫丁不等式用联合界:2·100·e^(−2n·0.02²) ≤ 0.01 ⇔ n ≥ ln(20000)/(2·0.0004) ≈ 12380。
- 区间。 证明直线上的区间VC维为2,增长函数为C(n, 2) + n + 1。 解答。 两个点:区间可以一个都不盖、盖其中一个或两个都盖。三个排好序的点无法标成+、−、+:盖住两端的区间必然盖住中间的点。 n个排好序的点上,区间标为+的是一段连续的点:选首尾两点(长度≥2的有C(n, 2)段,长度为1的有n段),再加上空集: C(n, 2) + n + 1 = Σᵢ₌₀² C(n, i),恰好是d = 2时的绍尔–谢拉界。
- ℓ₁球的马萨特引理。 对{x ↦ w·x : |w|₁ ≤ B}且|xᵢ|∞ ≤ X,证明R̂_S ≤ BX√(2 ln(2d)/n)。 解答。 在ℓ₁球上w·v的上确界是B|v|∞(赫尔德不等式,在带符号的坐标向量处取到),所以R̂_S = (B/n) E max ±Σᵢσᵢxᵢⱼ, 是N = 2d个形如σ·a的和的最大值,且|a|₂ ≤ X√n。由马萨特引理,E max ≤ max|a|₂ √(2 ln N),于是R̂_S ≤ (B/n)X√n√(2 ln 2d)。
- 从w₀出发的梯度下降。 证明在d > n、步长很小时,½|Xw − y|²上的梯度下降从w₀出发收敛到X⁺y + (I − X⁺X)w₀。 解答。 P = X⁺X是到行空间的投影。每一步加上的Xᵀ(·)都在行空间里,所以(I − P)w_t始终等于(I − P)w₀;而Xw_t = XPw_t, 行空间部分u_t = Pw_t就是在行空间内对½|Xu − y|²做梯度下降,那里损失严格凸,唯一的极小点是X⁺y。所以w_t → X⁺y + (I − P)w₀, 离最小范数解的距离是|(I − P)w₀|(第10章两者都测得5.970)。
- 高斯分布之间的KL散度。 对d维的Q = N(μ, s²I)、P = N(μ₀, λI),推导KL(Q‖P)。 解答。 每个坐标上,E_Q[ln q − ln p] = −½ln(2πs²) − ½ + ½ln(2πλ) + (s² + (μ − μ₀)²)/(2λ);对d个坐标求和, KL = ½(ds²/λ + |μ − μ₀|²/λ − d − d ln(s²/λ))。(如第7章那样每个坐标的s不同时,把各坐标的项相加。)
- 重要性权重。 证明重要性加权的训练误差是测试误差的无偏估计,并说明当p = N(0, 1)、q = N(0, 4)时权重的方差是无穷大。 解答。 E_p[w(x)ℓ(x)] = ∫p(q/p)ℓ = E_q[ℓ]。E_p[w²] = ∫q²/p dx ∝ ∫exp(−x²/4 + x²/2)dx = ∫exp(x²/4)dx = ∞: 测试分布的尾部比训练分布重,有效样本量随之崩溃。
Build the film
python -m videos.ai.ai8.compute # the part's numbers, into .cache/ai8
python tools/build.py ai8 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai8 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai8. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
Normal builds now require the two explicit corrected-recipe preparation commands
in Versioned scientific corrections first.
The legacy make/compute commands below populate only the original cache; they
do not create versioned corrected bundles. Missing corrected bundles fail clearly.
Use explicit legacy selection only when reproducing the original results.
python tools/make.py ai8 # computations, then the narrated film in English and Chinese
python -m videos.ai.ai8.compute # the numbers only (Part 6's pages; the novels model for two items)
python tools/build.py ai8 # English
python tools/build.py ai8 --lang zh # Chinese
EXPLAINER_TTS=silent python tools/build.py ai8 -q l --fps 15 # a quick silent preview
Everything is seeded and runs on the CPU, on one thread (AI8_THREADS, default 1), except canary, which continues
training the novels model on two (AI8_TRAIN_THREADS, default 2) for about forty minutes and checkpoints every few
dozen steps (.cache/ai8/canary.ckpt), so a killed run resumes. corrupt and sharp save each finished run as they
go. In all, about an hour of CPU time. memorize and canary need the novels model (python -m explainer.ai.novels,
which make.py runs first if it is missing).