The Guessing Game
How many bits does a text really hold, and what does guessing the next letter have to do with it?
The part opens with Shannon's 1951 experiment: hide a sentence, have someone guess it letter by letter, and write down how many guesses each letter took. From letter counts in thirty novels it builds probability and the chain rule, shows that Shannon's requirements leave only log2(1/p) as a measure of surprise, and defines entropy as the average surprise: 4.08 bits for single letters, 3.33 given the previous one. Codes come next: Kraft's inequality on the binary tree, Huffman's code and why it is optimal, typical sequences and the source coding theorem. The part turns when the code is built from the wrong model: the price is the KL divergence, and an arithmetic coder turns any predictor into a compressor that wastes at most two bits on the whole text. Learning by counting, Laplace's rule and the softmax gradient show how a model is fitted, and mutual information measures what the past tells the future. It ends on the scoreboard, bits per character on one passage, where gzip, a counting model, GPT-2 and Qwen3 are ranked by the same number.
What you need. Logarithms, sums and a little programming. No probability is assumed.
- Mathematics and history
- probability, surprise, entropy, Kraft, Huffman, typical sets, cross-entropy, KL, arithmetic coding, maximum likelihood, mutual information
- Models, data
- counting models, gzip/xz/bzip2, GPT-2, Qwen3
What you will be able to do
Undergraduate
- Compute the surprise of an outcome and the entropy of a distribution in bits, and say what each measures.
- Build a Huffman code for a small alphabet and decode a message with it.
- Explain why a model that predicts the next letter better compresses the text further.
Master's
- Prove Kraft's inequality on the binary tree and derive L >= H from it with Jensen's inequality.
- Derive H(p, q) = H(p) + KL(p || q) and Gibbs' inequality, and tell forward from reverse KL by what each fit covers.
- Derive the gradient of the softmax cross-entropy with respect to the logits.
Research
- State the asymptotic equipartition property, bound the size of the typical set, and prove the source coding theorem from it.
- Prove the data-processing inequality from the chain rule for mutual information, and say what an estimate of mutual information at long distances does and does not establish.
Engineering
- Convert between bits per token, bits per character, bits per byte and perplexity, and compare two models only in a unit that does not depend on the tokenizer.
- Run an arithmetic coder with integer registers, and account for a compressed size that must include the model.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 25 min · Master's 51 min · Research 58 min · Engineering 36 min.
- 0Shannon's guessing gameUndergraduate4 min
- 1Probability, and the chain ruleUndergraduate3 min
- 2How surprised to beUndergraduate3 min
- 3Entropy, and why it is uniqueUndergraduate4 min
- 4Prefix codes and the Kraft-McMillan inequalityMaster's4 min
- 5The best code: Huffman, and why it is optimalMaster's4 min
- 6Typical sequences and the source coding theoremResearch4 min
- 7Cross-entropy and KL: the price of a wrong modelMaster's4 min
- 8Arithmetic coding: prediction is compressionEngineering5 min
- 9Learning by counting, and Laplace's ruleUndergraduate5 min
- 10Shannon's 1951 experimentUndergraduate2 min
- 11Learning: likelihood, softmax, and the gradientMaster's3 min
- 12Mutual information: what the past tells the futureResearch3 min
- 13What it takes to guess wellUndergraduate2 min
- 14Bits per character, bits per tokenEngineering2 min
- 15The scoreboard: language modeling is compressionEngineering4 min
- Recap, problems, and where this comes backAll 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.
Shannon's guessing gameUndergraduate4 min
In 1951, Claude Shannon played a game with English. He took a sentence, hid it, and asked a person to guess it, one letter at a time. A wrong guess, and they guessed again, until they got it. Under each letter, he wrote down how many guesses it took.
The guesses pile up at a few places, mostly where a new word begins. That is where the information is.
From counts like these, Shannon estimated that English carries about one bit per letter, a bit being the answer to one yes-or-no question: between 0.6 and 1.3, when a letter guessed blindly could carry 4.75. Most of what we write is predictable.
Shannon didn't start from nothing. Telegraphers knew that common letters deserve short codes: Morse gives e a single dot. In 1928 Ralph Hartley, at Bell Labs, measured information by the logarithm of the number of possible messages. In 1948 Shannon made it a theory: entropy, the bit, and the limits of compression. The guessing game, Huffman's code and arithmetic coding followed. Half a century later, the same game became how machines learn language: a network guessing the next word, in 2003, then GPT-2, and today's models.
Seventy-five years on, Shannon's game is exactly what large language models are trained to play. Give one the start of a sentence, and it returns a probability for every possible next word. GPT-2, from 2019, with a hundred and twenty-four million parameters, the adjustable numbers inside it, gives the word Paris 6 percent. Qwen3, a 2025 model with four billion, gives the word Paris 35 percent.
Strictly, a model guesses the next token. A token is the chunk of text it guesses at one time: a word, a piece of a word, or a punctuation mark. Here is a line of a 1930 novel, cut the way GPT-2 cuts it.
Which raises the question this whole series is about. What do you have to know, to guess well?
Over thirty-one parts, we'll build the answer from the ground up: foundations, learning from data, transformers, generation and perception, agency and reasoning, and finally, looking inside, and whether we can trust it.
Part one starts where Shannon did. What information is, and why it's measured in bits; the best codes, and Shannon's limit; the price of a wrong model; a code that turns any guesser into a compressor; how a model learns to guess; and how far guessing has come. Guessing well and compressing well, we'll see, are the same thing.
And we'll keep score. Here is a page of The Maltese Falcon, from 1930. Its Project Gutenberg edition appeared in January 2026. We hold it out of the models we train here. For pretrained models, earlier copies may have been in their training data. As plain text, it takes about eight bits per character. The series explains how the numbers on this board come down: from eight, to below one.
1Probability, and the chain ruleUndergraduate3 min
Before we can score a guess, we need a way to write one down.
Take 30 novels, from Pride and Prejudice to The Great Gatsby, and count every symbol: Shannon's alphabet of twenty-six letters and the space, capitals and punctuation dropped. That's 22.8 million symbols. The most common is the space, about one symbol in 5. Then e, one in 10.
Sorted, the familiar order appears: space, e, t, a, o, n. The rarest, z, turns up about once in 1,900 symbols.
This is a probability distribution: a number for each possibility, none negative, adding up to one. Stack the bars end to end, and they fill a bar of length one, a sliver per symbol, as wide as its probability. A guess, written down, shares one unit of belief among the possibilities.
But we rarely guess from nothing. Once you know the previous letter, the odds change. Here is the whole table: each row is a previous symbol, each square how likely the next one is. This is conditional probability: B given A is the probability of both, divided by that of A.
In our books, q appears 18,496 times, and all but 27 are followed by u. So u given q is 0.9985. After a space, though, almost anything can come next: a new word is starting.
Multiply that definition out, and you get a rule for whole strings. The probability of two symbols is the probability of the first, times the probability of the second given the first. For three, treat the first two as a single event, and substitute.
And so on, one symbol at a time. A whole text's probability is a product of next-symbol guesses, each knowing everything before it. This is the chain rule, and it is exact: no assumption made. It's why a machine that only guesses the next symbol can score, or write, a whole text.
Here's the chain rule as a picture. Someone has written, he said, and we want the chance that the next three letters are t, h, e. The first bar shares the whole unit of belief among the 27 next symbols, given the last three: i, d, space. t gets a sliver 0.155 wide.
Now zoom into that sliver and share it out again, by the probabilities after d, space, t. h takes 61 percent of it. Zoom again: after space, t, h, e takes 70 percent. The final sliver's width is the product, 0.0666: the probability of the whole string.
Keep this picture in mind: nested slivers, each one a guess. In chapter eight, it becomes a way to compress text.
2How surprised to beUndergraduate3 min
If you were sure something would happen, seeing it happen tells you nothing. u after q: no news. A coin landing heads tells you a little. A letter e, a bit more. And a z, which turns up about once in 1,900 symbols, tells you a lot. The less likely it was, the more you learn.
Let's turn that into mathematics. Call the surprise of an event with probability p, s of p. Ask a few modest things. It depends only on p. It goes down as p goes up, and a certain event is no surprise at all. For independent events, where one tells you nothing about the other, probabilities multiply and surprises should add: heads on a coin and a five on a die, together, as surprising as the two added up. And small changes in p make small changes in s.
Remarkably, those rules leave only one choice. Measure probabilities in halvings: write p as two to the minus x, and let g of x be its surprise. Rule three says g turns sums into sums. So g of n is n times g of one, for every whole number, and for every fraction. Continuity fills in the rest: g of x is x times g of one.
Put the probability back in, and the surprise must be a constant times the log of one over p. The constant just picks a unit. Let a fair coin flip carry exactly one, and call it a bit: an event of probability p carries log, base two, of one over p, bits.
Here's that function. A coin: one bit. A face of a die: 2.58 bits. The letter e: 3.32 bits. The letter z: 10.9. And u, right after q: 0.002 bits, almost nothing. As p heads to zero, the surprise grows without limit.
And because logs turn products into sums, the chain rule turns into something lovely. A whole text's surprise is the sum of its symbols' surprises, each given everything before it. Here is Shannon's sentence again, each letter's surprise a bar, judged by a model that knows only the previous 5 letters.
The tall bars are where the text surprised the model: . Altogether, bits for symbols: bits per symbol, . Remember that number; it's how we'll keep score.
3Entropy, and why it is uniqueUndergraduate4 min
Surprise is about one event. Before it happens, we can ask: on average, how surprised should we expect to be? Weight each surprise by how often it happens, and add up. That average is the entropy, H of p.
There's a nice picture of it. Take the unit bar from chapter one, a sliver per symbol, as wide as its probability, common to rare. Raise each sliver to the height of its surprise: common symbols wide and low, rare ones thin and tall. The entropy is the total area: for English letters, 4.08 bits.
The simplest case is a coin. Fair, it has one bit of entropy. Bias it, and it gets easier to guess: heads ninety percent of the time, 0.47 bits. Always heads: no entropy at all. Entropy is largest when the outcomes are equally likely.
We built entropy out of surprise; Shannon went the other way. In 1948 he asked what any measure of uncertainty should satisfy. It should change continuously with the probabilities. With n equally likely outcomes, more outcomes, more uncertainty. And a choice broken into two successive choices should cost the first choice, plus the second, weighted by how often you face it. His example: a half, a third, a sixth is a fair coin, then, half the time, two thirds against one third.
Our letters work the same way. First choose space, vowel or consonant: 1.48 bits. Then choose which one: 2.20 bits among the vowels, 3.85 among the consonants. Weighted and added, that's 4.08 bits: the entropy of the letters, exactly.
And he proved nothing else meets them. Call A of n the uncertainty of n equal choices. Choosing among s to the m equal outcomes is m choices among s in a row, so by the third requirement, A of s to the m is m times A of s. Squeeze any number between powers of another, and the second forces A of n to be a constant times log n. Now take probabilities that are fractions, n i over N: choose one of N equal outcomes in two steps, the block, then the outcome inside it. Solve for H, and out comes minus K, sum of p log p; continuity covers the rest.
Up to a unit, entropy is the only consistent measure of uncertainty. That's why every part of this series measures information this way.
In general, with K outcomes, the entropy is at most log two of K. The proof is one inequality. The log bends downward, so the average of logs is at most the log of the average: Jensen's inequality. Entropy is an average of logs. Swap in the log of the average, and the average of one over p is just the number of outcomes. So H is at most log K, with equality only when every outcome is equally likely. The gap measures structure a guesser can exploit. Shannon's redundancy is that gap divided by log two of K.
Entropy also works when we know something. Each previous letter gives the next one its own distribution, and entropy. Draw a column for each previous letter, as wide as that letter is common, as tall as the entropy of what follows. After q, almost nothing: 0.02 bits. After a space, a new word begins: 4.11 bits.
The total area is the conditional entropy: 3.33 bits given the previous letter, down from 4.08 with no context. On average, knowing more never makes you more uncertain; chapter seven proves it.
4Prefix codes and the Kraft-McMillan inequalityMaster's4 min
Surprise is measured in bits. So let's spend some bits. The simplest way to send letters as bits is a fixed-length code. Two to the five is thirty-two, enough for twenty-seven symbols, so each gets a five-bit number. The falcon, 10 symbols, costs 50 bits. But that's wasteful: e is 192 times more common than z, and both cost five bits.
So give common symbols short codewords, as Morse code gives e a single dot. But careful. If e is zero, t is one, and a is zero one, then zero one could be e, t, or a. The fix is a prefix-free code: no codeword starts another. Then the codewords are the leaves of a binary tree: zero goes left, one goes right, and to decode, you walk down from the top to a leaf.
Watch it decode. Right, right, left: c. Back to the top. Left: a. Right, left: b. Right five times: f. No separators needed.
Prefix-free codes obey a budget, and the tree shows why. Grow the tree down to the longest codeword: 5 levels, 32 leaves at the bottom. A codeword of length l sits l levels down, and everything below it is off limits, so it uses up two to the l max minus l of the bottom leaves. No codeword starts another, so these shares never overlap: together, at most 32. Divide by two to the l max: two to the minus length, summed over the codewords, is at most one. That's Kraft's inequality, from Leon Kraft's 1949 master's thesis.
The budget is also enough. Hand me any lengths whose powers of a half add up to at most one, and a prefix code with those lengths exists: give out codewords shortest first, each at the leftmost free node of its depth. For example, round each letter's surprise up to whole bits. The powers of a half add up to 0.70, so here is a prefix code with those lengths. We'll meet it again next chapter.
Could a code that isn't prefix-free do better? This one isn't: zero starts zero one. Yet it decodes, because every codeword begins with a zero, and a zero always means a new codeword. Its sum is 15 over 16. This one, with sum 5 over 4, can't be decoded: zero one is a b, or c. In 1956 Brockway McMillan showed the budget binds every decodable code. Raise the sum to a power k and multiply out: each term is a message of k codewords. Group the messages by their length in bits. If the code decodes, different messages never give the same bits, so at most two to the m are m bits long, and the sum is at most k times the longest length.
A sum above one, raised to the k, grows exponentially; k times a constant grows in a straight line. For the bad code, five fourths to the k overtakes two k at k equals 16: the bound breaks, so it can't be decodable. So prefix codes lose nothing: any lengths a decodable code can have, a prefix code can have too.
5The best code: Huffman, and why it is optimalMaster's4 min
Now we can prove a speed limit. Let L be the average codeword length, and H the entropy. Write their difference as one sum. Jensen's inequality, exactly as in chapter three, moves the log outside. The probabilities cancel, and Kraft's inequality says what's left is at most log one: zero. So the average length is never less than the entropy, and equals it only if each symbol gets exactly log one over p bits: its surprise.
Codeword lengths must be whole numbers, so round the surprises up: those lengths fit Kraft's budget, and cost less than one extra bit per symbol. For our letters, 4.62 bits.
Which code gets closest? In 1951 David Huffman, a graduate student in Robert Fano's class at MIT, could sit the final exam, or write a paper on finding the most efficient code. He chose the paper. His answer: join the two least likely symbols, here z and q, under a new node whose probability is their sum. Then again with the two least likely of what's left, 26 times, until one tree holds everything.
Read off the codewords: the space gets 2 bits, e gets 4, and z gets 10. On average, 4.127 bits per symbol, just 0.043 above the entropy. The falcon now costs 43 bits instead of 50.
Huffman proved that no prefix code does better, with a few exchanges. First: if a likelier symbol had a longer codeword than a rarer one, swapping them would shorten the average. Give e the 10 bits of z, and z the 4 bits of e, and each letter costs 0.60 bits more. So in a best code, likelier symbols never get longer codewords. Second: a deepest codeword with no sibling could move up a level. So the deepest codewords come in pairs. By the first exchange, the two rarest symbols can be such a pair: in Huffman's code, z and q, differing only in the last bit.
Now merge those two rarest symbols into one, whose probability is their sum. Any code for the smaller alphabet becomes one for the original by splitting that leaf, and the average goes up by exactly the merged probability, whatever the rest. So the best code for the original is the best for the smaller problem, plus that split. That's Huffman's first merge, and the same argument covers every merge after it: his tree is optimal. We checked. Add up the weights of the merges: 4.127, Huffman's average. Search every possible shape of code tree for the letters: the best is the same. And on 400 random alphabets, Huffman's code matched the exhaustive search every time.
6Typical sequences and the source coding theoremResearch4 min
Why long messages compress so well. Last chapter, whole bits wasted up to one per symbol, and long blocks were the cure. Here is why. Draw letters independently, with the books' frequencies, crude but exact to reason about, and measure the surprise per letter. For one letter, it's all over the place, from 2.4 bits to 10.9. Ten letters: the spread narrows. A hundred, a thousand, ten thousand: it piles up at 4.08 bits, the entropy, its spread shrinking from 1.2 bits to 0.01.
It's the law of large numbers: a text's surprise is a sum over its letters, and the average of many independent surprises settles at their mean, the entropy. Shannon proved it in 1948; McMillan and Breiman extended it to sources with memory, like real text. Its name: the asymptotic equipartition property.
Call a sequence typical if its surprise per symbol is within a small epsilon of the entropy. Then each has probability close to two to the minus n H. By equipartition, together they hold nearly all the probability. Count them: their probabilities can't add past one, so there are at most two to the n H plus epsilon; and since they hold nearly everything, at least about two to the n H. Almost every sequence you'll see is one of these, all about equally likely.
Here is the typical set, drawn. Take a simpler source: a coin that writes a space with the books' frequency, 0.191. Lay out all two to the n sequences in a row, equally wide, from the most likely, with no spaces, to the least. Below, the same sequences, each as wide as its probability; the typical ones in gold. With 4 symbols, they are 25 percent of the sequences, holding 40 percent of the probability. Now make the sequences longer.
In the top row, the gold shrinks to a sliver, then to nothing you can see; in the bottom row it spreads until it fills almost everything. By symbols, the typical sequences are two to the minus of all sequences, and carry . And the most likely sequence, all non-spaces, isn't typical at all: you'll essentially never see it.
That gives the source coding theorem. To compress n symbols: if the sequence is typical, send a zero, then its number in a list of the typical set: about n H bits. If not, send a one and the sequence itself. That's rare, so on average you pay about H bits per symbol. And no code does better: a shorter list would miss most typical sequences, and almost all the probability. Even last chapter's rounded code, used on whole blocks, closes in on the entropy: 0.882 bits per symbol with blocks of 4, 0.7041 with blocks of 1000, against 0.7036.
Now English: twenty-seven to the n strings of n letters. Under letter frequencies alone, the typical ones are a fraction two to the minus 0.67 n: for a page of 2,000 letters, two to the minus 1,341. At one bit per letter, real text is a far smaller corner. A language model's job is to find that corner, and to write, it draws from it: how, in Part 5.
7Cross-entropy and KL: the price of a wrong modelMaster's4 min
What happens when your guesses are wrong? Codes and guesses are the same thing: a code that spends l bits on a symbol bets that it has probability two to the minus l. What if the bets are wrong? Say the data come from p, but the code was built for a model q. Each symbol costs log of one over q bits, and on average we pay the cross-entropy: the sum of p times log one over q.
As a picture: with the right probabilities, the area is the entropy, 4.08 bits. Now use a model that has e and z the wrong way round. Every e, one symbol in 10, now costs 10.9 bits. The area grows to 4.84.
Split the log in two, and the cross-entropy separates into two prices. First, the entropy of p: the world's own randomness, which no code can remove. Second, the price of being wrong: the Kullback–Leibler divergence of q from p, from 1951. Swapping e and z costs bits per symbol. The letter frequencies of our thirty books, used on the Falcon passage, .
Is being wrong always a cost? Yes, by chapter three's argument. The log bends downward: the average of logs is at most the log of the average. Minus the divergence is an average, weighted by p, of the log of q over p. Move the log outside. Inside, the p's cancel, and what's left is the total of q, which is one. The log of one is zero.
So the divergence is never negative, and zero only when q equals p, where Jensen's inequality is an equality. The truth is the best code. The inequality is named after Josiah Willard Gibbs, who used it in statistical mechanics. It also pays a debt from chapter three: the drop in entropy from knowing X is a divergence too, so it can't be negative. Knowing more never hurts, on average. That drop, the mutual information, gets its own chapter.
Here is why this matters for AI. Autoregressive language models are pretrained with this next-token loss: the average of log one over q, for each token of real text, given the tokens before it. Usually with the natural log, ln, so it's counted in nats: one nat is about 1.44 bits. It's the cross-entropy between the world's text and the model. Training can only shrink the divergence; the entropy of language itself is a floor no model can go below.
One more property, which will matter a lot later: the divergence is not symmetric. Say the truth p has two peaks, and our model q can only be a bell curve: one smooth hump, set by its center and its width. Which bell curve is best? It depends on which way round we measure. Minimizing the divergence of q from p, the training loss we just met,
The other way round, q is punished for putting probability where p has none, so Each fit is bad by the other's measure: the wide curve scores bits the second way, the narrow one bits the first. Covering everything, or committing to one thing: that choice comes back in variational autoencoders, in Part 20, and in distillation and reinforcement learning from human feedback, in Part 27.
8Arithmetic coding: prediction is compressionEngineering5 min
The best code for a good guesser. Huffman's code has one flaw: every symbol costs at least one whole bit. u after q carries 0.002 bits, and still costs a full bit. A model that really knows English is surprised by about a bit per symbol, or less; a symbol code can't go below one. Long blocks would fix it, but blocks of a hundred letters need a table of twenty-seven to the hundred entries. Instead, code the whole message as one number, one guess at a time.
Arithmetic coding, worked out by Jorma Rissanen and Richard Pasco in 1976. We've seen its heart: the nested slivers of the chain rule. Split the unit interval by the model's guesses for the first letter: t takes a sliver 0.155 wide. Write its two ends in binary. They agree on their first 2 digits, so every number in the sliver starts that way: those bits are decided.
Then zoom in and split again: h, e, space, f, a, l, c, o, n. Each letter narrows the interval by its probability, and more leading digits of its ends come to agree, ready to send. A likely letter barely narrows it, and costs a fraction of a bit. An unlikely one, like the c in falcon, which the model gave 0.8 percent, costs 7.0 bits.
After ten letters, the interval has width two to the minus 27.66: the probability of the whole message. To finish, find the shortest binary fraction whose every continuation lies inside the interval. Here, it takes 29 bits. Compare: 50 for the fixed code, 43 for Huffman, 29 for arithmetic coding, against an information content of 27.66.
Why within two bits? Let P be the message's probability, the width of its interval. Choose a length l: log of one over P, rounded up, plus one. A run of l bits names a little interval of width two to the minus l, at most half of P. These tile the line, so the first one starting at or after the low end finishes before the high end: it lies inside, and its l bits pin the message down. And l is less than the information content plus two.
Decoding runs the same steps, with an identical copy of the model. The bits name a number. It falls in the t sliver of the first split: the first letter is t. Zoom in: the h sliver, then e, and so on, until the message is back, exactly.
A real coder keeps the interval as two whole numbers, low and high: 16 bits here, 32 in practice. The first letter narrows it. Both ends agree on their leading bit: send it, and double the half holding the interval: a zoom. If the interval straddles the middle, the next bit isn't known yet: the coder zooms about the middle anyway, and the waiting bit comes out, flipped, after the next decided one. Narrow and zoom, and the bits stream out.
At the end, a couple of bits close it off: 28 bits for the falcon, one fewer than the exact coder's 29. Whole numbers, and nothing longer than the registers, ever.
This is the hinge of the whole part. Give arithmetic coding any model that predicts, and you get a compressor spending about log of one over q bits per symbol: the text's length times the model's cross-entropy. A complete prefix code over a fixed set of messages gives normalized probabilities: two to the minus each code length. Other uniquely decodable codes give weights with total at most one; normalization and consistency between prefixes are needed to turn them into next-symbol probabilities. This is the connection between prediction and compression. In chapter fifteen, a language model becomes a compressor.
9Learning by counting, and Laplace's ruleUndergraduate5 min
So far, our models have only counted. How far can counting go? In 1948, Shannon let counting models write. Every symbol equally likely: noise. The right letter frequencies: still noise, with the right texture. Pick each letter by what followed the previous one in our books, and syllables appear. Two letters of context: short words. Four: mostly real words. Six: phrases, mariners would be by many. Count whole words instead, and it almost scans.
The rule behind all of these is simple. The probability of the next symbol, given a context, is how often it followed that context in the books, divided by how often the context appeared. It's the most natural estimate, and chapter eleven shows it's the best one, for the books themselves.
So let's score them. For each amount of context, from none to fourteen letters, measure the bits per letter. First on the books it counted. More context, fewer bits, down to 0.27 bits per letter at 14 letters. Our numbers for no context and one letter, 4.08 and 3.33, land next to Shannon's 1951 estimates from printed tables, 4.03 and 3.32.
But on new text, the Falcon passage, the story is different. More context helps at first: among the orders we tried, the lowest loss on this passage is at letters of context, bits per letter. This order is selected after scoring the passage, not on validation text. Beyond that, it gets worse:
The reason: contexts multiply. Of the Falcon passage's five-letter contexts, 99 percent appear somewhere in the books; of its 14-letter contexts, only 27 percent. There are about ten to the 20 possible 14-letter contexts, and the books hold 16.7 million. An unseen context gives the model nothing to go on, and a letter never seen after it would get probability zero: infinite surprise.
The patch is older than computers. In 1814 Pierre-Simon Laplace asked: if something happened s times in n tries, how likely is it next time? Suppose that, before looking, every chance between zero and one was equally plausible. Weigh each by how well it explains what you saw, and the answer is s plus one, over n plus two. His example was the sunrise: five thousand years, 1,826,213 days, give odds of 1,826,214 to one that the sun rises tomorrow. For our 27 symbols: add one to every count, and nothing gets probability zero. Add alpha instead of one, chosen on held-out text, and you have the smoothing that keeps our curves finite.
How much does alpha matter? Here is every alpha from a ten-thousandth to ten, at four context lengths, on the Falcon passage. : common one-letter contexts have abundant examples. With letters of context, percent of the passage's letters follow a context where the books never showed that letter, and most contexts were seen only a few times. Adding one to every count drowns the evidence: Laplace's rule costs bits per letter more than the alpha chosen on held-out text, . Good smoothing is about what you haven't seen; Part 7 answers it properly.
This is the first appearance of the central problem of machine learning. A model can fit the data it learned from almost perfectly, and still guess badly on new data; how well it does there is called generalization. Counting has a deeper limit: every context is an island. It can't tell that the dog barked and the hound barked are alike, so it can't share what it learned. Better smoothing comes in Part 7, generalization in Part 8, and models that share what they learn, with vectors and networks, in Parts 3 and 9.
10Shannon's 1951 experimentUndergraduate2 min
Back to Shannon's guessing game, now that we have the tools to read it.
Here's Shannon's key observation. Give the receiver an identical twin of the guesser: same knowledge, same habits. The sender plays the game on the text and sends only the guess counts. The receiver asks the twin, and when the count says third guess, takes its third guess. Out comes the text, exactly.
So the guess counts carry all the text's information. The text's entropy is at most theirs, which is at most the entropy of how often each guess number turns up: an upper bound on the information in English.
Let's play with the last chapter's counting model as the guesser, on 11,994 letters of the Falcon passage. It gets the letter first time 58 percent of the time, second time 13 percent, with a long tail.
From those frequencies, the rank entropy is 2.37 bits per letter: an estimate of the upper bound. Shannon's lower-bound expression gives 1.36, but its proof assumes an ideal guesser, ranking letters by their true conditional probabilities. Our counting program is not ideal, so that lower endpoint is illustrative, not a certified bound.
Shannon's own subjects did far better. With a hundred letters of context, he put printed English between 0.6 and 1.3 bits per letter, against a rank entropy of 2.4 for our counting guesser with six. Its lower endpoint is only illustrative, and Shannon also cautioned about sampling error and imperfect human guessing. The difference is knowledge: of words and grammar, idioms, the story, and how the world works.
Later estimates, with people betting on the next letter, landed at about 1.3 bits. To guess like a person, a machine has to know what a person knows.
11Learning: likelihood, softmax, and the gradientMaster's3 min
So far our models were counted. Now let's see how a model learns. Learning starts from a principle stated by Ronald Fisher in 1922: choose the model under which the data you saw were most likely. The likelihood is the product of the model's probabilities for every observation. Minus its log, per observation, is the average surprise. Group the observations by value: the cross-entropy between the data's own frequencies, p hat, and the model. That's the data's entropy plus the model's divergence from the data.
So maximum likelihood, minimum cross-entropy, and minimum divergence from the data are one and the same goal. It's the loss from chapter seven, seen from the other side.
If the model may be any distribution at all, the divergence is smallest, zero, when the model equals the data's frequencies. So chapter nine's counting models were maximum likelihood models, and that's why they overfit: they fit the books perfectly, and nothing pulled them toward anything more general.
Counting doesn't generalize. Neural networks do. A neural network is a stack of simple steps: multiply by a table of numbers, bend the result, repeat, with all the numbers tuned until its guesses are good. For each possible next token, its last step computes a score, a logit: any real number, positive or negative. To make probabilities, exponentiate: e to the z is always positive, and each step of one up multiplies it by about 2.7. Then divide by the total. That's the softmax: bigger score, bigger probability, and never zero.
To learn, the network needs to know which way to nudge each score. That's what a derivative measures: how much the output moves when you nudge one input, holding the others still. Write the surprise of the right answer, y, in terms of the scores. Differentiate with respect to the score z k. The first term gives minus one if k is y. The second is the softmax itself. So the derivative is q k minus one, for the right answer, and q k, for every wrong one.
In words: the model's guess, minus the truth. For our shared-logit toy model, averaging gives q minus p hat. With varying contexts, average each example's q minus its one-hot answer. To update network parameters, backpropagate these logit derivatives through the network. Following it downhill, one small step at a time, is gradient descent, and it returns in Parts 4, 9 and 11.
12Mutual information: what the past tells the futureResearch3 min
In chapter seven, knowing X lowered the entropy of Y, on average. That drop is the mutual information. It's the bits that knowing one thing saves you when you guess the other, and it's symmetric. It's also a divergence, of the joint distribution from independence, so it's never negative. In our books, the next letter carries 4.08 bits; knowing the letter before it, 3.33. So neighbouring letters share 0.75 bits. Two letters back share 1.36, though the second one on its own shares only 0.27: together, letters say more than apart.
Now process what you know. Suppose Z is computed from Y, by any function at all, even a noisy one. The chain rule splits what Y and Z together say about X in two ways: first Y, then whatever Z adds, which is nothing. Or first Z, then whatever Y adds. Compare the two, and Z can never tell you more about X than Y did. No amount of processing creates information.
Let's watch it happen in our books. Keep only the kind of the previous letter: space, vowel or consonant. Of the 0.75 bits, 0.35 survive. Or garble it: replace a share of the letters with random ones. The more noise, the less it tells, down to nothing. Do both, and you lose more: each curve stays under the one before. A law for learning machines too: whatever a network computes from its context can't know more about the next token than the context itself.
How far back does that reach? Measure pairs of letters at distance d across our books. These are finite-sample estimates, with an approximate bias correction. The neighbouring letter estimate is bits. At our largest measured distance, letters, the corrected estimate is about millionths of a bit; one shuffled version of the same letters gives about millionths of a bit. The shuffled control is a reference realization, not an uncertainty interval. Both axes are logarithmic. Nonpositive estimates cannot appear on them; their signed values are retained, including the control shown at the right.
A fit is a summary, not a law. Bias correction is approximate, especially for overlapping pairs from text. Corrected estimates can fluctuate below zero, even though true mutual information is nonnegative. Our measurement stops at this distance. It does not establish what happens beyond it, or prove that memory helps at every distance. Long context remains a question for models to test: attention, in Part 13.
13What it takes to guess wellUndergraduate2 min
Let's look at what a strong model knows that a weaker one doesn't. Here is a paragraph of the Falcon passage, in tokens, each colored by how surprised GPT-2, from 2019, was by it: dark when expected, bright when not. And the same paragraph under Qwen3, from 2025. The paragraph is : bits instead of .
Look where they differ. And the telephone: GPT-2 pays bits for it, Qwen3 , with the earlier paragraphs present, including the telephone bell. On this paragraph alone, Qwen3 pays bits; with the preceding paragraphs, . This comparison shows that context helps this prediction. It does not isolate which earlier sentence matters.
Facts work the same way. Ask for the city of the Eiffel Tower, the author of Pride and Prejudice, or the chemical symbol for gold, and the model that knows the answer pays far fewer bits when the answer comes. Arithmetic is harder:
So here's the ladder. Letter frequencies get you bits. Spelling, a few letters of context, gets you . Better prediction can benefit from words and grammar, facts, and what has happened so far in the story. These are interpretations of the measured gains, not capabilities proved by a compression score alone. Shannon's people give us a historical comparison near one bit per letter. Training rewards whatever reduces the bits paid for each guess, including useful structure and context.
14Bits per character, bits per tokenEngineering2 min
Before the final scores, a word about units. Language models don't read letters. Each cuts text into tokens with its own vocabulary. Here is a paragraph of the Falcon passage as GPT-2 cuts it, and as Qwen3 does. Over the whole passage, GPT-2 needs 5,458 tokens, 3.92 characters each on average; Qwen3, with a bigger vocabulary, 5,217.
A model's loss is reported per token, so its size depends on how much text a token holds. What matters is the total: tokens times bits per token, which is characters times bits per character. Here are our models on the passage; for the counting model, every token is a character. Perplexity, two to the bits per token, has the same problem: tokens differ. So compare per character, or per byte: that's why the scoreboard counts bits per character.
The field measures it this way too. In 2024, researchers at the Hong Kong University of Science and Technology and Tencent studied thirty-one public language models across twelve benchmarks. They measured compression on fresh web pages, code and papers in bits per character, since token sizes differ. General-purpose models were tested across the benchmarks; specialized code and math models only in their domains. Compression corpora were matched to those domains. The overall comparison reported a correlation of minus 0.93: an observed association in this study, not a guarantee for every model or task.
15The scoreboard: language modeling is compressionEngineering4 min
Time to keep score. Here's the board, for the Falcon passage as printed: capitals, punctuation, everything. Plain text spends about eight bits per character. The passage uses only 61 different symbols, so a blind guess among them costs 5.93 bits. Letter frequencies, counted in our thirty books, bring it to 4.55, and one character of context, to 3.58.
Next, the compressors on your computer. . They know nothing about English in advance, and learn only from the passage, as they go. Among the counting orders we tested, the lowest loss on this passage uses the previous characters and gets . Alpha was selected on validation text, but this context length was selected after scoring the passage; it is an exploratory best, not a blind held-out winner.
And then, the neural language models. GPT-2, the smallest version, from 2019: 1.17 bits. Its largest version, 1.01. Qwen3, from 2025: the 0.6 billion parameter model already matches the largest GPT-2, and four billion parameters bring it to 0.87 bits per character. For comparison, Shannon's estimate for people, on letters alone, was 0.6 to 1.3.
The jump from counting, at 2.3 bits, to under one, is what this series is about: what these models learned, and how.
Arithmetic coding turns any predictor into a compressor, so we built one. GPT-2 small reads the start of the Falcon passage a token at a time, feeding chapter eight's 32-bit coder. The known-length payload packs into bytes, including padding: bits more than GPT-2's own surprise. This excludes the model and file framing. On the same characters, xz needs bytes: times as many.
There's a catch: the decompressor needs the model, and the model is big. GPT-2 small's whole-passage size is estimated from log loss at kilobytes, not a full-passage round trip. Its weights, at two bytes per parameter, add megabytes: together the estimated two-part size is times the passage. In 2024, a DeepMind paper titled Language Modeling Is Compression put a 70-billion-parameter model on a gigabyte of Wikipedia: 8.3 percent of the original size, against 32 for gzip and 23 for xz; fourteen thousand percent, counting its weights. Trained on text, it also beat PNG and FLAC on its tested image patches and audio samples. The Hutter Prize, started in 2006, counts both the compressor and the self-extracting archive. Its official table, checked on October thirty-first, 2026, lists Vladimir Ivanov's July twenty-fourth, 2026 entry at 100.4 megabytes total, or about 0.80 bits per input byte. Prediction is compression, and the predictor's size is part of the bill.
And the board isn't finished: better counting in Part 7, a neural network in Part 9, a network with memory in Part 10, and our own small transformer in Part 13, all trained on these books and scored on this page.
Recap, problems, and where this comes backAll tracks2 min
Let's take stock. Guesses are probability distributions; the chain rule scores a whole text. Surprise had to be a logarithm, and entropy is the only consistent measure of uncertainty. Kraft's budget bounds uniquely decodable codes; Huffman is optimal for symbol codes, and long blocks can approach the entropy on average. A wrong model costs the cross-entropy. Arithmetic coding made predicting and compressing one thing, and GPT-2 compressed a known-length prefix of our passage . Counting taught generalization by failing at it, and mutual information showed how far back text remembers.
Almost everything here comes back. The chain rule is how language models generate text, and how reasoning models think out loud. Cross-entropy is the loss we'll minimize for the rest of the series. The divergence's two directions return in variational autoencoders and in alignment. Drawing typical text from a model is Part 5. And compression returns with scaling, and at the very end, when we ask what these models can be trusted with.
Here are six problems to try, from the grouping rule to Laplace's rule of succession. Pause here and work through them; full solutions are in this part's notes.
Next time: the other road to intelligence, the one that came first. Alan Turing's question; machines that search, uniformly, or guided toward a goal; programs that play games and prove theorems; the expert systems; and the winters that followed. The symbolic era.
This part followed the first chapters of Cover and Thomas's Elements of Information Theory, and MacKay's Information Theory, Inference, and Learning Algorithms, both of which go much further. The papers are all worth reading, starting with Shannon's two. Thanks for watching, and see you in Part 2.
Where it goes next. Cross-entropy is the loss minimized for the rest of the series, and its gradient q - y is derived again by backpropagation in Part 4. Sampling text from a model returns in Part 5, the two directions of the KL divergence in Parts 20 and 27, and the scoreboard gains rows in Part 7 and closes the series in Part 31.
Key results
The part's results in one place, for revision.
Try it
Lab 1 · Prediction is compression: an arithmetic coder under three models
Draw 3,000 symbols from a skewed 27-symbol source, encode them with the series' arithmetic coder under the true model, a wrong model and a model that learns by counting, decode them back, and compare every code length with the text's information content, with H(p) and with H(p) + KL(p || q).
python -m videos.ai.labs 1
needs numpy, scipy, matplotlib · download lab01.py ·
source on GitHubsource entropy H(p) 3.9694 bits per symbol
true model: coder output 11882 bits = 3.9607 per symbol (theory 3.9694)
true model: information content 11880.2 bits; the coder spends +1.81 more
wrong model: coder output 13107 bits = 4.3690 per symbol (theory 4.3716)
wrong model: information content 13106.6 bits; the coder spends +0.45 more
counting: coder output 11965 bits = 3.9883 per symbol
counting: information content 11964.7 bits; the coder spends +0.26 more
counting: closed form 11964.7 bits = log2 multinomial + log2 C(N+K-1, K-1)
counting: price of learning 0.0282 bits per symbol
Whatever the model, the coder's output is the text's surprise under that model plus at most two bits: a better predictor is a shorter file, a wrong one pays the KL divergence on every symbol, and counting pays only a logarithmic fee for not knowing the source.
The code (102 lines; it asserts its own result)
"""Lab 1: compress a sampled text with the film's arithmetic coder under three models, and count the bits."""
import numpy as np
from scipy.special import gammaln
from videos.coursekit import labs
from videos.ai.ai1 import coder # the finite-precision arithmetic coder of chapter 8 (plain Python integers)
TITLE = "Prediction is compression: an arithmetic coder under three models"
GOAL = ("Draw 3,000 symbols from a skewed 27-symbol source, encode them with the series' arithmetic coder under the "
"true model, a wrong model and a model that learns by counting, decode them back, and compare every code "
"length with the text's information content, with H(p) and with H(p) + KL(p || q).")
TASKS = [
"Lower the coder's precision from 32 bits to 16 (and FREQ_BITS to 12). How many extra bits does the text cost?",
"Replace add-one counting by add-alpha with alpha = 0.1 and alpha = 5. Which learns this source fastest?",
"Make the source a Markov chain (the next symbol depends on the last) and give the counting model one symbol of "
"context. How far below H of the single-symbol frequencies does the code length fall?",
]
K, N, FREQ_BITS = 27, 3000, 16
LOG2 = np.log(2.0)
def zipf(s):
p = 1.0 / np.arange(1, K + 1) ** s
return p / p.sum()
def compress(text, table_for):
"""Encode ``text`` with the cumulative table ``table_for(i, history)`` at each position; decode it back.
Returns (code length in bits, information content in bits under the integer tables, running lengths)."""
enc, info, running = coder.Encoder(32), 0.0, []
for i, s in enumerate(text):
cdf = table_for(i, text[:i])
enc.encode(int(cdf[s]), int(cdf[s + 1]), int(cdf[-1]))
info += np.log2(cdf[-1] / (cdf[s + 1] - cdf[s]))
running.append(len(enc.bits) + enc.pending)
bits = enc.finish()
dec, out = coder.Decoder(bits, 32), []
for i in range(len(text)):
cdf = table_for(i, np.array(out, dtype=int))
s = dec.find(cdf)
dec.consume(int(cdf[s]), int(cdf[s + 1]), int(cdf[-1]))
out.append(s)
assert np.array_equal(out, text), "the decoder must return the text exactly"
return len(bits), info, np.array(running)
def run(seed=0):
rng = np.random.default_rng(seed)
p, q = zipf(1.0), zipf(0.3) # the source, and a model that is too flat
text = rng.choice(K, size=N, p=p)
H = -(p * np.log2(p)).sum()
kl = (p * np.log2(p / q)).sum()
cdf_p, cdf_q = coder.quantize(p, FREQ_BITS), coder.quantize(q, FREQ_BITS)
res = {"true model": compress(text, lambda i, h: cdf_p),
"wrong model": compress(text, lambda i, h: cdf_q),
"counting": compress(text, lambda i, h: np.concatenate([[0], np.cumsum(np.bincount(h, minlength=K) + 1)]))}
lab = labs.Lab()
lab.row("source entropy H(p)", f"{H:.4f} bits per symbol")
theory = {"true model": H, "wrong model": H + kl}
for name, (bits, info, _) in res.items():
tail = f" (theory {theory[name]:.4f})" if name in theory else ""
lab.row(f"{name}: coder output", f"{bits} bits = {bits / N:.4f} per symbol{tail}")
lab.row(f"{name}: information content", f"{info:.1f} bits; the coder spends {bits - info:+.2f} more")
n_k = np.bincount(text, minlength=K)
multinomial = (gammaln(N + 1) - gammaln(n_k + 1).sum()) / LOG2
mixture = (gammaln(N + K) - gammaln(N + 1) - gammaln(K)) / LOG2 # log2 of C(N + K - 1, K - 1)
lab.row("counting: closed form", f"{multinomial + mixture:.1f} bits = log2 multinomial + log2 C(N+K-1, K-1)")
lab.row("counting: price of learning", f"{(res['counting'][1] - res['true model'][1]) / N:.4f} bits per symbol")
lab.note = ("Whatever the model, the coder's output is the text's surprise under that model plus at most two bits: a "
"better predictor is a shorter file, a wrong one pays the KL divergence on every symbol, and counting "
"pays only a logarithmic fee for not knowing the source.")
for name, (bits, info, _) in res.items():
assert -0.01 < bits - info < 2.5, f"{name}: within two bits of the information content"
sd_p = np.sqrt((p * np.log2(p) ** 2).sum() - H ** 2) # the spread of one symbol's surprise
sd_q = np.sqrt((p * np.log2(q) ** 2).sum() - (H + kl) ** 2)
assert abs(res["true model"][1] / N - H) < 4 * sd_p / np.sqrt(N) + 0.01, "the true model codes at H"
assert abs(res["wrong model"][1] / N - (H + kl)) < 4 * sd_q / np.sqrt(N) + 0.01, "a wrong model codes at H + KL"
assert abs(res["counting"][1] - (multinomial + mixture)) < 1e-6, "Laplace's rule is a uniform mixture over sources"
assert res["true model"][0] < res["counting"][0] < res["wrong model"][0]
fig, ax = labs.figure(2, size=(11, 4.2))
t = np.arange(1, N + 1)
for (name, (_, _, running)), color in zip(res.items(), (labs.GREEN, labs.RED, labs.BLUE)):
ax[0].plot(t, running / t, color=color, label=name)
ax[0].axhline(H, color=labs.MUTED, ls="--", lw=1, label="H(p)")
ax[0].axhline(H + kl, color=labs.MUTED, ls=":", lw=1, label="H(p) + KL(p || q)")
ax[0].set(title="Bits sent per symbol so far", xlabel="symbols encoded", ylabel="bits per symbol", xscale="log",
ylim=(H - 0.6, H + kl + 1.0))
ax[0].legend()
names = list(res)
ax[1].bar(np.arange(3) - 0.2, [res[k][1] / N for k in names], 0.4, color=labs.GOLD, label="information content")
ax[1].bar(np.arange(3) + 0.2, [res[k][0] / N for k in names], 0.4, color=labs.BLUE, label="coder output")
ax[1].axhline(H, color=labs.MUTED, ls="--", lw=1)
ax[1].text(2.45, H, " H(p)", color=labs.MUTED, va="bottom", ha="right", fontsize=9)
ax[1].set(title="The whole text: surprise against file size", ylabel="bits per symbol", ylim=(H - 0.6, H + kl + 0.5))
ax[1].set_xticks(range(3), names)
ax[1].legend(loc="upper left")
lab.fig = fig
return lab
Now change it
- Lower the coder's precision from 32 bits to 16 (and FREQ_BITS to 12). How many extra bits does the text cost?
- Replace add-one counting by add-alpha with alpha = 0.1 and alpha = 5. Which learns this source fastest?
- Make the source a Markov chain (the next symbol depends on the last) and give the counting model one symbol of context. How far below H of the single-symbol frequencies does the code length fall?
Problems, with solutions
Try each problem before opening its solution.
1. The grouping rule. From H = −Σ pᵢ log₂ pᵢ, show H(p₁, p₂, p₃, …) = H(p₁ + p₂, p₃, …) + (p₁ + p₂) H(p₁/(p₁ + p₂), p₂/(p₁ + p₂)).
Solution
Write s = p₁ + p₂. The two sides share every term from p₃ on. What is left on the left is −p₁ log p₁ − p₂ log p₂; on the right, −s log s + s H(p₁/s, p₂/s) = −s log s − p₁ log(p₁/s) − p₂ log(p₂/s) = −s log s − p₁ log p₁ − p₂ log p₂ + (p₁ + p₂) log s, which is the same.
2. A budget overspent. Can a prefix code have codeword lengths 1, 2, 3, 3, 3? Can any uniquely decodable code?
Solution
Σ 2^(−l) = 1/2 + 1/4 + 3/8 = 9/8 > 1. Kraft's inequality rules out a prefix code, and McMillan's extends the verdict to every uniquely decodable code: with these lengths, some message would always have two readings.
3. Two optimal codes. Build a Huffman code for (0.4, 0.2, 0.2, 0.1, 0.1). Find two optimal codes with different lengths, and compare their average with H.
Solution
Label the symbols a, b, c, d, e in the given probability order. Merge d + e into de of weight 0.2, then de + c into dec of weight 0.4. The remaining weights are a: 0.4, b: 0.2, dec: 0.4. Merging b with a gives lengths (2, 2, 2, 3, 3); merging b with dec instead gives (1, 2, 3, 4, 4). Finish by joining the last two nodes. Both average 2.2 bits (0.8 + 0.8 + 0.6, and 0.4 + 0.4 + 0.6 + 0.8), both are optimal, and H = 0.4 × 1.322 + 0.4 × 2.322 + 0.2 × 3.322 = 2.122 bits: within 0.08 bits of the bound. The first code has the smaller spread of lengths, which matters for buffering, not for the average.
4. Typical, but not likely. A coin lands heads with probability 0.1; toss it 100 times. About how many typical sequences are there, how likely is each, and how does that compare with the likeliest single sequence?
Solution
H = h(0.1) = 0.469 bits. The leading-exponential AEP estimates are 2^(nH) = 2^46.9 ≈ 1.3 × 10¹⁴ sequences and 2^(−nH) ≈ 7.7 × 10⁻¹⁵ probability per sequence, a roughly 2^(−53) share of all 2¹⁰⁰ strings at this exponential scale. These are not exact counts or probabilities at n = 100: a finite-n typical set requires a specified tolerance ε, and its total probability must then be calculated. For comparison, a sequence with exactly ten heads has probability 0.1¹⁰ × 0.9⁹⁰, while the single likeliest sequence, all tails, has probability 0.9¹⁰⁰ ≈ 2.7 × 10⁻⁵. Its surprise per toss is −log₂ 0.9 = 0.152 bits; it lies outside the weak typical set whenever ε < 0.469 − 0.152 ≈ 0.317. A large relative probability for one sequence does not make its absolute probability large.
5. KL is not symmetric. For p = (½, ½) and q = (¼, ¾), compute D_KL(p‖q) and D_KL(q‖p).
Solution
D_KL(p‖q) = ½ log₂(½/¼) + ½ log₂(½/¾) = 0.5 − 0.2925 = 0.2075 bits. D_KL(q‖p) = ¼ log₂(¼/½) + ¾ log₂(¾/½) = −0.25 + 0.4387 = 0.1887 bits. Coding p's data with q's code wastes more than the other way round.
6. Laplace's rule. Derive (s + 1)/(n + 2) from ∫₀¹ θᵃ(1 − θ)ᵇ dθ = a! b!/(a + b + 1)!.
Solution
With every chance θ equally likely beforehand, after s successes in n trials the weight of θ is proportional to θˢ(1 − θ)ⁿ⁻ˢ, and the chance of a success next is the average of θ under that weight: ∫ θˢ⁺¹(1 − θ)ⁿ⁻ˢ dθ / ∫ θˢ(1 − θ)ⁿ⁻ˢ dθ = [(s + 1)!(n − s)!/(n + 2)!] / [s!(n − s)!/(n + 1)!] = (s + 1)/(n + 2).
Notes and sources
Glossary
| English | 中文 |
|---|---|
| Shannon's three requirements; the grouping rule | 香农的三条要求;分组法则 |
| uniqueness of entropy (Shannon's Theorem 2) | 熵的唯一性(香农定理2) |
| Hartley's measure of information | 哈特利的信息度量 |
| uniquely decodable code | 唯一可解码的码 |
| Kraft–McMillan inequality | 克拉夫特–麦克米兰不等式 |
| canonical code | 规范码 |
| exchange argument; sibling (leaves) | 交换论证;兄弟(叶子) |
| optimal code | 最优码 |
| typical set, typical sequence | 典型集,典型序列 |
| asymptotic equipartition property (AEP) | 渐近均分性(AEP) |
| law of large numbers | 大数定律 |
| block code | 分组编码 |
| finite precision; register | 有限精度;寄存器 |
| zoom (renormalization); pending bit | 放大(重新归一化);待定比特 |
| Laplace's rule of succession; the sunrise problem | 拉普拉斯接续法则;日出问题 |
| prior | 先验 |
| add-one (Laplace) smoothing | 加一(拉普拉斯)平滑 |
| data-processing inequality | 数据处理不等式 |
| chain rule for mutual information | 互信息的链式法则 |
| tokenizer, vocabulary | 分词器,词表 |
| bits per token, bits per byte | 每词元比特数,每字节比特数 |
| perplexity | 困惑度 |
| two-part code; adjusted compression rate | 两段式编码;调整后的压缩率 |
| Hutter Prize; context mixing | 赫特奖;上下文混合 |
| round trip (encode, then decode) | 往返(先编码,再解码) |
Sources
Books: T. M. Cover & J. A. Thomas, Elements of Information Theory, 2nd ed. (2006), ch. 2, 3, 5, 13; D. J. C. MacKay, Information Theory, Inference, and Learning Algorithms (2003), ch. 2, 4–6; C. M. Bishop & H. Bishop, Deep Learning: Foundations and Concepts (2024), ch. 2.
Papers: R. V. L. Hartley, Transmission of Information (1928); C. E. Shannon, A Mathematical Theory of Communication (1948; Theorem 2, the uniqueness of entropy; Theorem 3, the AEP) and Prediction and Entropy of Printed English (1951); L. G. Kraft (MIT thesis, 1949); D. A. Huffman, A Method for the Construction of Minimum-Redundancy Codes (1952), and G. Stix, Profile: David A. Huffman, Scientific American (1991); A. A. Sardinas & G. W. Patterson (1953); B. McMillan, The Basic Theorems of Information Theory (1953) and Two Inequalities Implied by Unique Decipherability (1956); L. Breiman, The Individual Ergodic Theorem of Information Theory (1957); S. Kullback & R. A. Leibler, On Information and Sufficiency (1951); P.-S. Laplace, Essai philosophique sur les probabilités (1814); R. A. Fisher, On the Mathematical Foundations of Theoretical Statistics (1922); J. Rissanen, Generalized Kraft Inequality and Arithmetic Coding (1976); R. Pasco (Stanford thesis, 1976); I. H. Witten, R. M. Neal & J. G. Cleary, Arithmetic Coding for Data Compression (1987); T. M. Cover & R. C. King, A Convergent Gambling Estimate of the Entropy of English (1978); H. W. Lin & M. Tegmark, Critical Behavior in Physics and Probabilistic Formal Languages (2017); G. Delétang et al., Language Modeling Is Compression (ICLR 2024; Table 1 for enwik9); Y. Huang, J. Zhang, Z. Shan & J. He, Compression Represents Intelligence Linearly (COLM 2024); the Hutter Prize, hutter1.net (records table, consulted October 2026); A. Radford et al., Language Models are Unsupervised Multitask Learners (2019); Qwen Team, Qwen3 Technical Report (2025).
Data: Project Gutenberg (thirty novels, listed in compute.BOOKS; The Maltese Falcon, eBook #77600, released
1 January 2026).
About this partfrom its README
Part 1 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). It starts where Claude Shannon did, with a game: guess the next letter of an English text. From that game it builds information theory as a working tool: probability and the chain rule, surprise and entropy (and why entropy is the only consistent measure of uncertainty), codes and the limits of compression, cross-entropy and the KL divergence, arithmetic coding, learning by counting and by gradient descent, mutual information, and the series' scoreboard, where large language models turn out to be the best compressors of text we have. A hook, fifteen chapters and an outro:
- Shannon's guessing game. Shannon's 1951 experiment, played on his own sentence by a counting program; how we got here (Morse code, Hartley 1928, Shannon 1948 and 1951, Huffman, arithmetic coding, Bengio 2003, GPT-2, Qwen3); GPT-2 (2019) and Qwen3-4B (2025) playing the same game on the next token; tokens; the series map; the objectives; the scoreboard and its passage.
- 1. Probability and the chain rule. Letter frequencies of 22.8 million symbols from thirty novels; a distribution as one unit of belief shared out; the 27 × 27 table of P(next | previous) and the mosaic of joint probabilities, P(u | q) = 0.9985; the chain rule, derived, and drawn as nested slivers (“he said” → the).
- 2. How surprised to be. Shannon's requirements for surprise and the derivation that they leave only log₂(1/p) (g(x + y) = g(x) + g(y), integers, fractions, continuity); the surprise of Shannon's sentence, letter by letter: 182 bits for 101 symbols.
- 3. Entropy, and why it is unique. The average surprise, term by term; entropy as an area (slivers of width p and height log₂ 1/p): 4.08 bits for letters; the coin; Shannon's three requirements (1948) and the grouping rule, checked on his example and on the letters (space / vowel / consonant: 1.48 + 0.307 × 2.20 + 0.502 × 3.85 = 4.08); his Theorem 2, sketched (A(sᵐ) = m A(s), A(n) = K log n, blocks of equal outcomes); H ≤ log₂ K by Jensen on the entropy dome (log₂ 27 = 4.75; the gap is absolute redundancy, and dividing it by log₂ 27 gives Shannon's redundancy); conditional entropy as a mosaic: 3.33 bits given the previous letter.
- 4. Prefix codes and the Kraft–McMillan inequality. Fixed-length codes; prefix-free codes as trees, decoding; Kraft's inequality proved on the full binary tree (codewords claim 16 + 8 + 4 + 2 + 1 + 1 of 32 leaves); the converse (the canonical code: Shannon's lengths for the letters sum to 0.70); McMillan (1956): a decodable code that is not prefix-free ({0, 01, 011, 0111}, sum 15/16), one that cannot be decoded ({0, 1, 01}, sum 5/4), the k-th power argument, and (5/4)ᵏ overtaking 2k at k = 16.
- 5. The best code: Huffman, and why it is optimal. L ≥ H by Jensen and Kraft; Shannon's rounded code (4.62 bits); Huffman's 1951 term paper and his algorithm, merge by merge on the 27 letters (4.127 bits, the falcon in 43 bits instead of 50); optimality by exchange arguments (swapping e's and z's codewords costs 0.596 bits per letter; the deepest leaves come in pairs; z and q are siblings) and induction (L = L′ + p_x + p_y); checked: the merged weights sum to L, an exhaustive search over tree shapes finds the same 4.127, and 400 random alphabets (211 also against every length assignment) all agree.
- 6. Typical sequences and the source coding theorem. Letters drawn independently: the surprise per letter of 4,000 sampled texts concentrates at H as n goes 1 → 10,000 (spread 1.2 → 0.012 bits); the asymptotic equipartition property (Shannon 1948; McMillan 1953; Breiman 1957); the typical set and its size, derived; the typical set shrinking inside sequence space, exactly, for a coin with the books' space frequency (n = 4: 25% of the sequences, 40% of the probability; n = 1000: 2⁻¹⁷³ of the sequences, all but one part in 87 million of the probability; the likeliest sequence is never typical); the source coding theorem, with Shannon's code on blocks closing in on H (0.882 → 0.7041 bits against 0.7036); real text as a vanishing corner of all strings.
- 7. Cross-entropy and KL. A code as a set of bets (Huffman's lengths against the true p); coding with the wrong model as an area; H(p, q) = H(p) + D_KL(p‖q); Gibbs' inequality by Jensen (and H(Y | X) ≤ H(Y)); next-token cross-entropy for autoregressive pretraining, nats; forward against reverse KL, fitted by gradient descent to a two-peaked density, with the fits sliding (the wide fit scores 1.30 bits the other way, the narrow one 10.1).
- 8. Arithmetic coding. Huffman's whole bits (and the 27¹⁰⁰-entry table blocks would need); the chain-rule slivers continued for the falcon, the binary
expansions of the interval's ends agreeing digit by digit; the 29-bit codeword (information content 27.66 bits);
the two-bit bound, proved; decoding; finite precision: the integer coder's own record, with 16-bit registers,
narrowing and zooming (with pending bits) through the falcon (28 bits); prediction ⇔ compression. (
arithintalso runs the whole passage through a 32-bit coder: 41,089 bits against an information content of 41,087.6 with 24-bit counts, 1,192 extra bits with 8-bit counts; the numbers are in the cache, not in the film.) - 9. Learning by counting, and Laplace's rule. Shannon's 1948 approximations, regenerated from the books; the counting rule; bits per letter against context length on the books (down to 0.27 at 14 letters) and on the Falcon passage (lowest observed test loss 2.02 at 5 letters, selected on this same passage; worse than letter frequencies at 14); unseen contexts; Laplace's rule of succession (1814, the sunrise) derived from Euler's beta integral, add-one and add-α smoothing, swept over α at four context lengths (Laplace is best for one letter of context, and 0.35 bits worse at eight); generalization.
- 10. Shannon's 1951 experiment. The identical-twin argument (guess counts are a code); our counting guesser's guess counts on 11,994 letters (first guess 58%); Shannon's upper and lower bounds (2.37 and 1.36 bits); his subjects (0.6–1.3 bits with 100 letters of context); Cover and King's 1978 estimate.
- 11. Likelihood, softmax and the gradient. Maximum likelihood = minimum cross-entropy = minimum divergence; counting is maximum likelihood; the softmax, step by step; ∂(−ln q_y)/∂z_k = q_k − [k = y], derived: the model's guess minus the truth, the signal gradient descent follows.
- 12. Mutual information. I(X; Y) = H(X) − H(X | Y), symmetric, a divergence; neighbouring letters share 0.75 bits, two letters back 1.36 (the second alone 0.27); the data-processing inequality from the chain rule, checked on the books (the kind of the previous letter keeps 0.35 bits; noise drains the rest); the mutual information between letters d apart through 1,000 letters, with a matched shuffled control and finite-sample bias correction. A descriptive log-log fit summarizes the positive tail estimates; it does not establish a power law or extrapolate beyond the measured distances. Signed estimates and nonpositive control values remain in the data.
- 13. What it takes to guess well. One paragraph's per-token surprise under GPT-2 and Qwen3-4B (Bull Durham tobacco; the telephone, 12.8 bits without the earlier paragraphs and 3.5 with them); knowledge probes; the ladder of knowledge.
- 14. Bits per character, bits per token. Two tokenizers on the same paragraph and passage (GPT-2: 5,458 tokens, 3.92 characters each; Qwen3: 5,217); total bits = tokens × bits per token = characters × bits per character; per token, the counting model looks better than GPT-2 (2.32 bits, perplexity 5.0, against 4.57 and 23.8), per character it is twice as bad; perplexity; bits per byte; Huang et al. (2024): bits per character on fresh text against the relevant benchmark scores in a study of 31 models across twelve benchmarks (specialized models evaluated only in their domains); the overall comparison reports Pearson −0.93.
- 15. The scoreboard: language modeling is compression. Bits per character on the passage as printed: plain text 8, uniform over its 61 symbols 5.93, letter frequencies 4.55, one character of context 3.58, gzip 3.31, xz 3.20, bzip2 2.92, the best counting model 2.32, GPT-2 small 1.17, GPT-2 XL 1.01, Qwen3-0.6B 1.02, Qwen3-4B 0.87; people 0.6–1.3 (letters only); the gap from counting to under one bit is the series. GPT-2 small as a real compressor, round trip: the first 4,331 characters in 688 bytes (xz: 2,180), decoded back exactly by a second run of the model with known output length. This is a packed payload, excluding model/framing; its padding-inclusive overhead is 4.7 bits over the model's surprise. Whole-passage coded sizes are estimates from log loss, not additional completed round trips. The catch, the model's size (248 MB for GPT-2 small: 11,572 times the passage); Delétang et al. (ICLR 2024) on enwik9 (Chinchilla 70B 8.3% against gzip 32.3% and LZMA2 23.0%, 14,008% counting its weights); the Hutter Prize (2006; record of 24 July 2026: 100,424,672 bytes for enwik9, compressor and self-extracting archive included, about 0.80 bits per input byte; official table checked 31 October 2026). The rows later parts fill.
- Recap in eight computed pictures, where each idea comes back, six problems, Part 2's teaser, references.
Every number the narration states is computed in compute.py (or cited), and the narration is written
over the data: it branches where a sentence depends on a result. Schematics are labeled schematic, made-up
examples illustrative.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Probability and the chain rule.
- Surprise; entropy's axioms (Shannon's uniqueness theorem, sketched).
- Gibbs' inequality via Jensen.
- Kraft–McMillan, proved on the binary tree.
- Huffman optimality by an exchange argument.
- The AEP and typical sets: the source coding theorem.
- Cross-entropy and KL: asymmetry, forward vs reverse KL (mode-covering vs mode-seeking). Comes back in VI, distillation and RLHF.
- Arithmetic coding with its 2-bit overhead and finite precision.
- Counting models and Laplace smoothing.
- Shannon 1951.
- Maximum likelihood = minimum KL; the softmax gradient p − y.
- Mutual information and the data-processing inequality.
- Bits per character vs per token.
- The scoreboard.
Frontier: "language modeling is compression" (Delétang et al. 2024); LLMs as compressors vs gzip/xz. Visuals: the typical set shrinking inside sequence space; the arithmetic coder's interval zooming; forward vs reverse KL fits sliding over a bimodal p.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
1. 分组法则。 由 H = −Σ pᵢ log₂ pᵢ 证明:H(p₁, p₂, p₃, …) = H(p₁ + p₂, p₃, …) + (p₁ + p₂) H(p₁/(p₁ + p₂), p₂/(p₁ + p₂))。
解答
记 s = p₁ + p₂。两边从p₃起的各项相同。左边剩下 −p₁ log p₁ − p₂ log p₂;右边是 −s log s + s H(p₁/s, p₂/s) = −s log s − p₁ log(p₁/s) − p₂ log(p₂/s) = −s log s − p₁ log p₁ − p₂ log p₂ + (p₁ + p₂) log s, 两者相等。
2. 超支的预算。 能否有一个前缀码,码字长度为1, 2, 3, 3, 3?能否有任何一个唯一可解码的码?
解答
Σ 2^(−l) = 1/2 + 1/4 + 3/8 = 9/8 > 1。克拉夫特不等式排除了前缀码,麦克米兰不等式把这个结论推广到一切唯一可解码的码: 用这些长度,总有某条消息会有两种读法。
3. 两个最优码。 为 (0.4, 0.2, 0.2, 0.1, 0.1) 构造霍夫曼编码。找出两个码长不同的最优码,并把它们的平均码长与H比较。
解答
按题目中的概率顺序,把符号记作a、b、c、d、e。先把d和e合并成权重为0.2的de,再把de和c合并成权重为0.4的dec。 剩下的权重是a:0.4,b:0.2,dec:0.4。把b和a合并,得到码长 (2, 2, 2, 3, 3);改为把b和dec合并,就得到 (1, 2, 3, 4, 4)。 最后把剩下的两个节点合并。两者的平均码长都是2.2比特(0.8 + 0.8 + 0.6,以及 0.4 + 0.4 + 0.6 + 0.8),都是最优的;而 H = 0.4 × 1.322 + 0.4 × 2.322 + 0.2 × 3.322 = 2.122 比特,相差不到0.08比特。 第一个码的码长更整齐,这影响缓冲,不影响平均码长。
4. 典型,却不是最可能的。 一枚硬币正面朝上的概率是0.1,抛100次。典型序列大约有多少个?每个的概率是多少?和最可能的那一个序列相比如何?
解答
H = h(0.1) = 0.469比特。AEP给出的主导指数近似,是 2^(nH) = 2^46.9 ≈ 1.3 × 10¹⁴ 个序列, 每个序列的概率约为 2^(−nH) ≈ 7.7 × 10⁻¹⁵;在这一指数尺度上,约占全部 2¹⁰⁰ 个字符串的 2^(−53)。 这不是 n = 100 时的精确计数或概率:有限长度的典型集需要指定容差 ε,再计算其总概率。作为比较,恰有10次正面的一个序列, 概率为 0.1¹⁰ × 0.9⁹⁰;单个最可能的序列是全部反面,概率 0.9¹⁰⁰ ≈ 2.7 × 10⁻⁵。它每次抛掷的意外度为 −log₂ 0.9 = 0.152比特;只要 ε < 0.469 − 0.152 ≈ 0.317,它就不在弱典型集内。一个序列的相对概率很大,并不意味着绝对概率也大。
5. KL散度不对称。 对 p = (½, ½) 和 q = (¼, ¾),计算 D_KL(p‖q) 和 D_KL(q‖p)。
解答
D_KL(p‖q) = ½ log₂(½/¼) + ½ log₂(½/¾) = 0.5 − 0.2925 = 0.2075比特。D_KL(q‖p) = ¼ log₂(¼/½) + ¾ log₂(¾/½) = −0.25 + 0.4387 = 0.1887比特。用q的编码去编p的数据,比反过来浪费得多。
6. 拉普拉斯法则。 由 ∫₀¹ θᵃ(1 − θ)ᵇ dθ = a! b!/(a + b + 1)! 推出 (s + 1)/(n + 2)。
解答
事先认为每个机会θ都同样可能;在n次试验中成功了s次之后,θ的权重正比于 θˢ(1 − θ)ⁿ⁻ˢ,而下一次成功的概率是θ在这个权重下的平均: ∫ θˢ⁺¹(1 − θ)ⁿ⁻ˢ dθ / ∫ θˢ(1 − θ)ⁿ⁻ˢ dθ = [(s + 1)!(n − s)!/(n + 2)!] / [s!(n − s)!/(n + 1)!] = (s + 1)/(n + 2)。
Build the film
python -m videos.ai.ai1.compute # the part's numbers, into .cache/ai1
python tools/build.py ai1 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai1 Hook # one chapter, silent, with a contact sheet
Scenes: videos/ai/ai1. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python tools/make.py ai1 # everything: the computations, then the narrated cut in English and Chinese
python -m videos.ai.ai1.compute # or just the numbers
python tools/build.py ai1 -q l # a preview
python tools/build.py ai1 --lang zh # the Chinese cut
compute.py downloads 31 Gutenberg books (~40 MB) and, for lms, probes and context, GPT-2, GPT-2 XL and
Qwen3-0.6B/1.7B/4B-Base (~19 GB); about 15 minutes on 4 cores, cached in .cache/ai1. The items added for the
expanded part are small: groups, kraft, units, compress and dpi take seconds; huffopt (400 exhaustive
searches) about 15 s; typical a second; smoothing and arithint under a minute; lmzip (GPT-2 small encodes and
decodes 1,023 tokens, one at a time, on one core) about 3 minutes. Every random choice is seeded (compute.rng), and
each item is saved the moment it finishes, so an interrupted run resumes; lms keeps each model's result as it goes.
coder.py is the finite-precision arithmetic coder (Witten, Neal & Cleary 1987) used by arithint and lmzip.