Maps to: UC Berkeley CS294-158 Deep Unsupervised Learning (Spring 2024), Lecture 11 · Thu 4/4/2024 · Compression (93 slides), first part (slides 1–46): what compression is and why it belongs in a course on generative models (the Hutter prize, the learned-compression challenge), why no compressor can shrink everything, why structured data compresses, fixed- vs variable-length codes, Morse code, prefix-free codes as binary tries, Huffman codes, Shannon entropy, the Kraft–McMillan inequality (both parts, with proofs), Shannon’s source-coding theorem, Huffman’s optimality, coding with the wrong distribution (KL), higher-order models and the entropy of English, the “+1” problem, run-length coding, arithmetic coding and its finite-precision issues, and arithmetic coding with autoregressive models. The second part (bits-back coding, ANS, flows, Lempel–Ziv) is Lecture 21. Basis: The slides follow Blelloch’s Introduction to Data Compression. These notes keep their order and their examples (the six-symbol Huffman example, , the message “aaba”), prove the theorems, and check every claim in code: Huffman’s algorithm with a trace, the Sardinas–Patterson test for unique decodability, Kraft’s construction, exact arithmetic coding with fractions, a floating-point coder that breaks, and real bit streams produced with the autoregressive models of Lectures 3–4 — down to the exact model of ShapeWorld, whose entropy (17.80 bits per image) is the floor. Code:
code/lecture20/(4 scripts +compress.py; numpy, PyTorch (CPU) for script 04, which reuses the cached models of Lectures 3–4; each script runs in seconds to a few minutes) Reading time: 2.5 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain why no lossless compressor can shrink every input, and why data with statistical regularities can be compressed.
- Tell prefix-free, uniquely decodable and ambiguous codes apart; draw a prefix code as a binary trie; run Huffman’s algorithm by hand.
- State and prove the Kraft–McMillan inequality (both parts) and Shannon’s source-coding theorem; show that Huffman is within 1 bit of the entropy and optimal among symbol codes.
- Derive the cost of coding with the wrong model: cross-entropy — and why this makes maximum likelihood the right objective for compression.
- Explain the “+1” problem and the three fixes: blocks, run lengths, arithmetic coding; compute an arithmetic code by hand and bound its length.
- Use any autoregressive model with an arithmetic coder, and reason about the two-part code (model size + data) behind the Hutter prize.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
Lecture 1 (entropy; the integer arithmetic coder coding.py was used there) | prefix codes, Huffman, Kraft–McMillan, Shannon’s theorem | bits-back coding, ANS, BB-ANS, flows (Lecture 21) |
| Lecture 2 (maximum likelihood = cross-entropy = code length) | arithmetic coding by intervals, its precision, run-length codes | Lempel–Ziv (Lecture 21) |
| Lectures 3–4 (autoregressive image and text models, cached) | coding with autoregressive models, two-part codes |
This lecture is about lossless compression only (the slides: “this lecture: lossless”).
0.3 Map
§1 what and why: compression as understanding, the Hutter prize
§2 no universal compressor; why compression is possible ← code 01, Part 1
§3 codes for symbols: fixed, variable, prefix-free; Huffman ← code 01, Parts 2-3
§4 the limits: entropy, Kraft-McMillan, Shannon, Huffman's optimality ← code 01, Parts 4-5; code 02, Part 1
§5 coding with the wrong model; context and the entropy of English ← code 02, Parts 2-3
§6 the "+1" problem: blocks and run lengths ← code 03, Parts 1-2
§7 arithmetic coding, exactly and in finite precision ← code 03, Parts 3-4
§8 arithmetic coding with autoregressive models; two-part codes ← code 04
§9 summary §10 pitfalls §11 exercises §12 further reading §13 next lecture
0.4 Notation
a symbol (or message) with distribution ; the length in bits of the codeword of ; the entropy in bits; the cross-entropy; . “bits per image” etc. always means the average over a test set.
1. What and why
Compression reduces the number of bits needed to store or send a message (an image, speech, text). Lossless compression must give back exactly the original; lossy compression (JPEG, MP3, video codecs — Lecture 17) may give back something close. Practical reasons: storage, bandwidth, time. The reason in this course: compression and generative modelling are the same problem. A model that assigns probability can encode in about bits (Lecture 1 used this to turn likelihoods into actual files), so a better generative model is a better compressor, and maximum-likelihood training is minimizing code length (Lecture 2).
Two competitions on the slides make the point. The Hutter prize pays for compressing a 1 GB excerpt of Wikipedia, and counts the size of the decompressor too — its premise is that compressing human knowledge well requires understanding it. The Challenge on Learned Image Compression (CLIC) compares learned codecs with JPEG-style ones. We will see both ideas in miniature in §8: models of Lectures 3–4 beat general-purpose compressors on ShapeWorld by a factor of four to seven, and the model’s own size becomes the deciding term when there is little data.
2. No universal compressor; why compression is possible
Proposition (slides): no algorithm compresses every bit string. Two proofs:
- Contradiction. If shrank every input, apply it to its own output again and again; every string would end at length 0, and the empty string cannot decode to all of them.
- Counting. There are strings of 1,000 bits but only strings that are shorter. Two inputs would share a code, and decoding would be ambiguous (pigeonhole). The same count shows more: at most a fraction of all inputs can shrink by bits or more. A compressor is a bet on which inputs are likely.
Why compression is possible is the other side of the bet: real data have statistical regularities. The slides quote a famous text with scrambled letters inside each word that skilled readers still understand — English is so redundant that much of it can be destroyed without losing the message. Random data have no regularities and do not compress.
Experiment (script 01, Part 1, zlib at its strongest setting):
| data | bytes | after zlib |
|---|---|---|
| 100,000 random bytes | 100,000 | 100,041 (it grew) |
| 2,000 ShapeWorld images (1 bit per pixel) | 72,000 | 26,812 |
| 2,000 captions (ASCII) | 144,889 | 8,454 |
A general-purpose compressor knows nothing about shapes, yet finds the regularities of ShapeWorld images (2.7×) and much more of the captions (17×: a tiny vocabulary in a fixed template). On random bytes it pays its small overhead and gains nothing.
3. Codes for symbols
3.1 Fixed and variable length
The simplest code gives every symbol the same number of bits (ASCII: 7 bits per character). It is trivial to decode and does not compress: it cannot exploit that some symbols are more frequent. A variable-length code gives frequent symbols short codewords — but then a bit stream must be split into codewords unambiguously.
Uniquely decodable: every concatenation of codewords can be parsed in only one way. Two ways to get there:
- Separators. Morse code is uniquely decodable because of the gaps: letters are separated by a medium silence. Written as bits (the slides’ version: a dot is “1”, a dash “111”, a gap inside a letter “0”, the separator “000”), the separators are a large overhead.
- Prefix-free codes: no codeword is a prefix of another. Then the decoder can output a symbol the moment its bits are complete — no lookahead, no separators. A prefix-free code is a binary trie: symbols sit at the leaves, the codeword is the path from the root (0 = left, 1 = right), and “no codeword is a prefix of another” is exactly “no symbol sits on the path to another”.
Prefix-freeness is sufficient for unique decodability, not necessary: the code {0, 01, 011, 0111} is uniquely decodable (read it backwards) but needs lookahead. The Sardinas–Patterson test decides unique decodability for any code: start from the “dangling suffixes” left when one codeword is a prefix of another, keep extending them, and the code is ambiguous exactly when a dangling suffix is itself a codeword. Script 01, Part 3:
| code | Kraft sum | prefix-free | uniquely decodable |
|---|---|---|---|
| 0 10 110 111 | 1.0000 | yes | yes |
| 0 01 011 0111 | 0.9375 | no | yes (needs lookahead) |
| 0 01 10 | 1.0000 | no | no: 010 = 0·10 = 01·0 |
| 1 01 001 0001 00001 | 0.9688 | yes | yes |
| 0 1 00 | 1.2500 | no | no |
The Kraft sum (§4.2) separates possible from impossible lengths; whether a particular set of codewords is decodable is a separate question (“0 01 10” has a Kraft sum of exactly 1 and is still ambiguous).
3.2 Huffman’s algorithm
Which prefix code minimizes the expected length ? Huffman (1952): start with one tree per symbol, weighted by its probability; repeatedly merge the two lightest trees into one whose weight is their sum; the final tree is the code. Rare symbols are merged early and end up deep; frequent symbols stay near the root.
The slides’ example (script 01, Part 2):
merge C (0.05) + F (0.08) -> 0.13
merge B (0.10) + CF (0.13) -> 0.23
merge A (0.20) + D (0.21) -> 0.41
merge BCF (0.23) + E (0.36) -> 0.59
merge AD (0.41) + BCFE (0.59) -> 1
| symbol | Huffman codeword | length | ||
|---|---|---|---|---|
| A | 0.20 | 00 | 2 | 2.32 |
| B | 0.10 | 100 | 3 | 3.32 |
| C | 0.05 | 1010 | 4 | 4.32 |
| D | 0.21 | 01 | 2 | 2.25 |
| E | 0.36 | 11 | 2 | 1.47 |
| F | 0.08 | 1011 | 4 | 3.64 |
Expected length 2.36 bits per symbol, against 3 for a fixed-length code and an entropy of 2.308. The message “EADBEECAFEED” becomes 29 bits and decodes back by walking the trie. (Ties between equal weights can be broken either way; different tie-breaks give different codes with the same expected length.)
Why Huffman is optimal (slides; proof sketch by induction on the number of symbols): (i) in an optimal prefix tree every internal node has two children (otherwise remove the useless split); (ii) the two least probable symbols can be assumed to be siblings at the deepest level (swapping them there never increases the expected length); (iii) merging and into one symbol with turns any tree for the symbols into a tree for symbols whose cost is smaller by exactly , whatever the tree. So the best tree for symbols is the best tree for symbols plus the split of — which is what Huffman does at every step.
4. The limits: entropy, Kraft–McMillan, Shannon
4.1 Entropy as code length
Shannon’s entropy is the expected code length when each symbol gets bits. When all probabilities are powers of ½ this is exactly achievable: gets codewords 0, 10, 110, 111 with expected length . The theorems below say that in general we can come within 1 bit, and never beat .
4.2 The Kraft–McMillan inequality
Part I. For any uniquely decodable binary code with lengths : Proof for prefix codes (slides): let and extend the trie to the full binary tree of depth . Codeword “covers” the leaves below it; prefix-freeness means no leaf is covered twice; there are leaves. So . (McMillan’s extension to all uniquely decodable codes: expand over all -symbol sequences; unique decodability bounds the number of sequences with total length by , so ; a quantity whose -th power grows only linearly in is at most 1.)
Part II. Conversely, if , there is a prefix code with exactly these lengths. Proof: sort the lengths; for each in turn take the leftmost free node at depth and block its subtree; Kraft’s sum guarantees the leaves never run out. (The “canonical” construction in compress.canonical_code: each codeword is the previous one plus 1, shifted to the new length.) Consequence: we never need a non-prefix code — any lengths a uniquely decodable code can have, a prefix code can have too.
4.3 Shannon’s source-coding theorem
Theorem (Shannon 1948). For any uniquely decodable code, .
Proof. Let with . Then because (Gibbs’ inequality) and (Kraft). Equality needs exactly.
Converse (within 1 bit). The Shannon code lengths satisfy Kraft (), so a prefix code with these lengths exists, and . Huffman is at least as good, so .
Script 01, Part 4 builds the Shannon code for the slides’ example: lengths 3, 4, 5, 3, 2, 4, Kraft sum 0.656, a canonical prefix code (010, 1000, 10100, 011, 00, 1001), expected length 2.920 — within but worse than Huffman (2.36): rounding each length up separately wastes Kraft budget that Huffman spends.
Script 02, Part 1 checks the sandwich on 2,000 random distributions:
| symbols | Dirichlet α | min (Huffman − H) | mean | max |
|---|---|---|---|---|
| 2 | 1.0 | 0.0000 | 0.2779 | 0.9950 |
| 8 | 1.0 | 0.0055 | 0.0538 | 0.1679 |
| 8 | 0.1 | 0.0260 | 0.3699 | 0.9958 |
| 64 | 1.0 | 0.0191 | 0.0298 | 0.0431 |
| 64 | 0.05 | 0.0065 | 0.0495 | 0.4693 |
Always in . The gap approaches 1 bit only for peaked distributions (small α, or two symbols with one dominant): a codeword cannot be shorter than 1 bit, even when the most likely symbol carries almost no information. Hold that thought for §6.
4.4 Symbol codes and dependencies
Huffman is optimal among codes that treat symbols one at a time with fixed probabilities. Script 01, Part 5 applies it to ShapeWorld captions:
| unit | alphabet | units per caption | entropy per unit (order 0) | Huffman bits / unit | Huffman bits / caption |
|---|---|---|---|---|---|
| characters | 24 | 72.4 | 3.928 | 3.977 | 288.0 |
| words | 24 | 17.0 | 4.076 | 4.099 | 69.7 |
Each code is within a few hundredths of a bit of its own order-0 entropy — and both are far from the exact entropy of a whole caption, 11.97 bits (Lecture 15). The waste is not in the code but in the model: “a” is always followed by a size word, the right shape often repeats the left kind. Symbol codes cannot see dependencies; models can (§5.2).
5. Coding considerations
5.1 Coding with the wrong distribution
Suppose the code is built from a model (lengths ) but the data come from . The expected length is The price of the wrong model is exactly the KL divergence, and since , the true distribution is the best code. This is why maximum likelihood (minimizing the cross-entropy ) is the right training objective for compression: the “log-likelihood objective for learning is aligned with compression” (slides).
Script 02, Part 2 codes the words of the caption language, whose exact word distribution has bits per word:
| model used to build the code | ideal bits / word | Huffman code from | |
|---|---|---|---|
| 3.9867 | 0 | 4.0052 | |
| uniform over the 23 words | 4.5236 | 0.5369 | 4.7240 |
| estimated from 10 captions (add-½) | 4.0331 | 0.0465 | 4.0625 |
| … from 100 captions | 3.9946 | 0.0079 | 4.0234 |
| … from 1,000 captions | 3.9875 | 0.0009 | 4.0052 |
| … from 100,000 captions | 3.9867 | 0.0000 | 4.0052 |
The KL penalty shrinks as the estimate improves; with 1,000 captions the Huffman code is already the same as the true one.
5.2 Higher-order models: conditioning lowers entropy
A message with high entropy needs long codes. The remedy is context: — knowing something never increases uncertainty on average. Autoregressive models do exactly this, coding each symbol with .
The slides’ “entropy of English” — Shannon’s 1951 experiments (about 4.1 bits per letter from letter frequencies alone, roughly 1 bit with long contexts) and the bits per character of practical compressors on the Calgary corpus — has an exact counterpart for our caption language (script 02, Part 3): order- character models (counts with add-½ smoothing) trained on 50,000 captions and tested on 2,000 others:
| context (characters) | 0 | 1 | 2 | 3 | 4 | 6 | 8 | 16 | 32 | exact |
|---|---|---|---|---|---|---|---|---|---|---|
| bits per character | 3.925 | 1.998 | 0.609 | 0.259 | 0.232 | 0.217 | 0.218 | 0.216 | 0.237 | 0.165 |
| bits per caption | 284.8 | 145.0 | 44.2 | 18.8 | 16.8 | 15.8 | 15.8 | 15.7 | 17.2 | 11.97 |
The first few characters of context remove most of the redundancy (spelling inside words, the template between them): 285 → 19 bits per caption. Then progress stops at ~16 bits: the remaining 4 bits are the copy rule — whether the right shape repeats the left kind — which needs a context of ~40 characters, and with long contexts the counts become too sparse to estimate (the order-32 model is worse than order 16). Lecture 4’s character Transformer, which shares statistics across contexts, does much better (§8).
6. The “+1” problem: blocks and run lengths
Huffman’s “+1” is harmless when is large and terrible when it is small. The slides’ example: has bits per symbol, but the best single-symbol code {0, 10, 11} needs — almost double. Good predictive models make this common: a model that is usually confident produces exactly such peaked distributions.
Blocks. Code symbols at once: the block alphabet has symbols with entropy , so Huffman needs bits per block, per symbol (script 03, Part 1):
| block length | 1 | 2 | 3 | 4 | 6 | 8 |
|---|---|---|---|---|---|---|
| block alphabet | 3 | 9 | 27 | 81 | 729 | 6,561 |
| Huffman bits / symbol | 1.1000 | 0.7275 | 0.6269 | 0.5923 | 0.5701 | 0.5755 |
| excess over | 0.5310 | 0.1585 | 0.0579 | 0.0233 | 0.0011 | 0.0065 |
The excess stays below but is not monotone ( is slightly worse than : rounding luck). The price is an exponentially large code table — and blocks only work when the probabilities are fixed in advance.
Run lengths. For long runs of the same symbol (fax pages: mostly white), code the lengths of the runs instead of the symbols — one codeword pays for many symbols. On ShapeWorld images (script 03, Part 2; raster order, Huffman code of run lengths learned on 10,000 training images; 42.5 runs per image):
| code | bits per image |
|---|---|
| raw pixels | 288 |
| run lengths, Huffman-coded | 161.4 |
| every pixel independent, (ideal) | 238.1 |
| exact entropy | 17.80 |
Run lengths beat an independent-pixel model because they capture “background comes in long stretches”; both are far from the entropy because neither knows what a shape is.
7. Arithmetic coding
7.1 The idea: a message is an interval
Arithmetic coding (Rissanen 1976; practical versions in the 1980s) groups all symbols of a message without choosing block sizes or tables. Start with . For each symbol, cut the current interval into pieces proportional to the symbols’ probabilities and keep the piece of the symbol that occurred. After the whole message the interval has width .
The slides’ example, , , message “aaba” (script 03, Part 3, exact fractions):
after 'a': [0.0000, 0.8000) width 0.8000
after 'a': [0.0000, 0.6400) width 0.6400
after 'b': [0.5120, 0.6400) width 0.1280
after 'a': [0.5120, 0.6144) width 0.1024
Sending the interval. The naive choice — the number with the fewest binary digits inside the interval — does not give a prefix code (0.1 is a prefix of 0.11). Instead, send a bit string whose completion interval (all numbers that start with ) lies entirely inside the message’s interval; such codewords are prefix-free over messages. For an interval of width such a codeword exists with at most bits, so with the “+2” paid once per message, not per symbol. For “aaba”: , , and the shortest codeword is 10001 (5 bits): every number starting with 0.10001 lies in . On 2,000 random messages of 1–39 symbols, codeword length minus ranged from 0.020 to 1.986 bits — always below 2.
7.2 Finite precision
Two practical problems (slides): the interval can keep straddling ½, so no bit can be sent until the end; and real arithmetic has finite precision. Script 03, Part 4 runs a naive coder with float64 low and high on the source :
| symbols | float interval width | float decoder correct | integer coder bits | ideal | integer decoder correct |
|---|---|---|---|---|---|
| 10 | 0.0194 | yes | 7 | 5.7 | yes |
| 100 | 0 | yes | 58 | 56.9 | yes |
| 500 | 0 | no (first error at symbol 93) | 293 | 292.8 | yes |
| 1,000 | 0 | no (first error at symbol 87) | 578 | 577.3 | yes |
| 10,000 | 0 | no (first error at symbol 90) | 5,612 | 5,610.7 | yes |
A float64 has 53 significant bits. After ~90 symbols of 0.57 bits each, the interval is narrower than the spacing of floats near low and collapses to width 0; decoding goes wrong from there. (The 100-symbol message decoded by luck.) The integer coder of Lecture 1 (coding.py, after Witten, Neal & Cleary 1987) keeps low and high as 32-bit integers and renormalizes: as soon as both ends agree on the leading bit, that bit is final — it is sent and the interval is doubled; when the interval straddles ½ without shrinking, a “pending” bit is remembered and resolved later. Its output stays within 2 bits of for any length. Probabilities must be integer frequencies, identical in encoder and decoder (freqs_from_probs).
7.3 Arithmetic coding with autoregressive models
Nothing above needs the probabilities to be the same at every step. Use for the first symbol, for the second, … — an autoregressive model — and the final width is . The decoder runs the same model on the symbols it has already decoded, so it sees the same cuts. The better the model’s log-likelihood, the better the compression — exactly, up to the 2 bits.
8. Compressing with the course’s models
8.1 Images (script 04, Part 1)
500 ShapeWorld test images, each arithmetic-coded into its own bit stream with the cached models of Lectures 3–4 (and with the exact model, built from Lecture 1’s tables: , then with the copy rule), then decoded and compared with the original:
| compressor | parameters | real bits / image | ideal bits | model | round trip |
|---|---|---|---|---|---|
| raw pixels | — | 288.0 | |||
| zlib, all 500 images in one file | — | 119.3 | |||
| lzma, all 500 images in one file | — | 111.7 | |||
| FVSBN (Lecture 3) | 83,232 | 52.6 | 51.5 | 51.5 | yes |
| MADE | 591,136 | 33.6 | 32.5 | 32.5 | yes |
| WaveNet + coordinates | 100,705 | 24.6 | 23.5 | 23.5 | yes |
| gated PixelCNN | 176,386 | 23.5 | 22.5 | 22.5 | yes |
| Transformer on 2 × 2 patch tokens (Lecture 4) | 206,864 | 19.9 | 18.8 | 18.8 | yes |
| Transformer on 4 × 4 dictionary tokens | 261,845 | 20.1 | 19.0 | 18.8 | yes |
| Transformer on whole-panel tokens | 324,160 | 20.0 | 18.9 | 18.9 | yes |
| the exact model | — | 18.8 | 17.8 | 17.8 | yes |
Three things to read off:
- The file length is the likelihood. Every model’s stream is about 1 bit longer than its ideal code length — the cost of terminating one bit stream per image — and the ideal length equals the model’s up to ~0.2 bits lost to integer frequencies (largest for the 469-symbol dictionary vocabulary, where every unused symbol still gets frequency 1).
- Better model, smaller file, in exactly the order of Lectures 3–4’s test likelihoods: 52.6 → 23.5 → 19.9 bits, and the exact model reaches the entropy (17.8 ideal, 18.8 with the stream overhead).
- A compressor that knows the distribution beats general-purpose ones by ~6×: lzma needs 111.7 bits per image even with all 500 images in one file.
8.2 Captions (Part 2)
| compressor | bits per caption |
|---|---|
| ASCII (8 bits per character) | 581.7 |
| Huffman on single characters | 288.9 |
| lzma, all 500 captions in one file | 39.4 |
| Lecture 4’s character Transformer + arithmetic coding | 12.9 (round trip exact) |
| exact entropy | 11.97 |
The character Transformer, which looks at the whole caption so far, does what the counting models of §5.2 could not: it uses the copy rule and stays within ~1 bit of the entropy (including the stream overhead).
8.3 The two-part code (Part 3)
The Hutter prize counts the decompressor. In a two-part code (minimum description length), the cost of images is :
| images | lzma (decompressor not counted) | gated PixelCNN, 16-bit weights | the true generator (toy_worlds.py without comments, lzma: 4.0 KB) |
|---|---|---|---|
| 10 | 111.7 | 282,241 | 3,267 |
| 1,000 | 111.7 | 2,846 | 51.3 |
| 100,000 | 111.7 | 51.8 | 19.1 |
| 10,000,000 | 111.7 | 23.8 | 18.8 |
(bits per image including the model). The neural compressor’s 344.5 KB of weights pay for themselves only after 32,017 images; the true generative program — a few kilobytes — after 350. For little data, a small model wins even if it compresses each item worse; for a lot of data, the per-item bits dominate. The shortest description of the data is the best model of it — the bridge between compression and “understanding” on the first slides.
9. Summary
- No compressor shrinks everything (counting): compression is a bet that some inputs are likelier than others. Data with regularities compress (ShapeWorld images 2.7×, captions 17× with zlib); random data do not.
- Prefix codes are binary tries and decode without lookahead; uniquely decodable codes need not be prefix-free, but by Kraft–McMillan ( for every uniquely decodable code, and every such set of lengths has a prefix code) nothing is gained by leaving prefix codes.
- Shannon: no uniquely decodable code beats the entropy on average; Shannon’s lengths come within 1 bit; Huffman (merge the two lightest trees) is the optimal symbol code: 2.36 bits for the slides’ example (), always within .
- Coding with a model costs the cross-entropy : maximum likelihood is minimum code length. Context lowers entropy: order- character models took the caption language from 285 to ~16 bits per caption (exact: 11.97), until the counts ran out.
- The “+1” of symbol codes hurts when is small (1.1 vs 0.569 bits per symbol); blocks and run lengths reduce it; arithmetic coding removes it: a message is an interval of width , coded in at most bits in total. Real coders use integers and renormalization — a float64 coder broke after ~90 symbols.
- Arithmetic coding works with any autoregressive model, so every likelihood model of this course is a compressor: on 500 ShapeWorld images the bit streams were within ~1 bit of each model’s (FVSBN 52.6, gated PixelCNN 23.5, Transformer on patch tokens 19.9, the exact model 18.8 bits per image vs lzma’s 111.7), and a character Transformer coded captions in 12.9 bits (entropy 11.97). Counting the decompressor (a two-part code), a 4 KB generator program beats a 345 KB network until tens of thousands of images.
10. Common pitfalls
- “A good compressor shrinks everything.” It cannot; it shrinks the likely inputs at the expense of the others.
- Confusing “uniquely decodable” with “prefix-free”, or a Kraft sum ≤ 1 with decodability: “0 01 10” has Kraft sum 1 and is ambiguous; Kraft constrains lengths, not codewords.
- Ignoring the “+1” when the entropy per symbol is small: a symbol code can cost nearly twice the entropy.
- Rounding each Shannon length separately and calling it optimal: Shannon’s code is within 1 bit but can be clearly worse than Huffman (2.92 vs 2.36 bits).
- Assuming more context always helps a counting model: with finite data, long contexts are sparse (order 32 was worse than order 16).
- Floating-point arithmetic coding: works for short messages, silently fails after ~53 bits of interval narrowing; decoders must also use the same quantized probabilities as the encoder, bit for bit.
- Comparing a neural compressor with gzip without counting the model: for small data the model’s size dominates (§8).
11. Exercises
Exercise 1 (Kraft’s inequality for prefix codes — derivation). Prove for a prefix code by the leaf-counting argument.
Answer
Let . In the complete binary tree of depth , the codeword of length is a node whose subtree contains leaves. Because no codeword is a prefix of another, no codeword node lies in the subtree of another, so these leaf sets are disjoint. There are leaves in total: ; divide by .
Exercise 2 (Kraft Part II — derivation). Given lengths with , sorted increasingly, show that assigning to each length the leftmost node at that depth not inside an already used subtree always succeeds.
Answer
After assigning codewords (lengths ), the used subtrees cover of the nodes at depth (each earlier codeword blocks of them, disjointly). Since , : at least one node at depth is free, and it is not a prefix of an earlier codeword because earlier ones are not longer. The canonical construction (“previous codeword + 1, shifted”) is this leftmost-free-node rule written in binary arithmetic.
Exercise 3 (Shannon’s bound — derivation). Prove for every uniquely decodable code using Gibbs’ inequality and Kraft.
Answer
See §4.3: with , , . Gibbs’ inequality () follows from Jensen: .
Exercise 4 (the price of the wrong model — derivation). Show , and conclude that the expected Shannon code length built from is between and .
Answer
; take the expectation under . With lengths the expected length lies in . Script 02: a uniform model on caption words costs bits per word more.
Exercise 5 (Huffman by hand). Build the Huffman code for ; give two codes with different length profiles but the same expected length.
Answer
Merges: 0.1 + 0.1 = 0.2; then three trees of weight 0.2 — merging two of the original 0.2s gives lengths (2, 2, 2, 3, 3) with expected length ; merging the new 0.2 with an original one gives lengths (1, 2, 3, 4, 4): . Both are optimal; ties make Huffman codes non-unique. (.)
Exercise 6 (blocks — derivation). For i.i.d. symbols, show that Huffman on blocks of symbols uses bits per symbol.
Answer
The block has entropy (independence). Huffman on the block alphabet has expected length per block, i.e. per symbol. Script 03 (Part 1) shows the bound is not the whole story: the actual excess is not monotone in .
Exercise 7 (arithmetic code length — derivation). Show that an interval contains a dyadic interval with .
Answer
With , . Let , so and . The codeword (the binary digits of ) therefore has length ; with this is the “+2” of §7.1.
Exercise 8 (coding). Change script 03, Part 4 to a source with bits per symbol. After how many symbols does the float coder fail? Explain.
Answer
(Run it.) The interval shrinks by about per symbol on average; float64 resolves about relative to low, so failure comes after roughly symbols (with fluctuations, since individual surprising symbols shrink the interval much more).
12. Further reading
From the slides
- G. Blelloch. Introduction to Data Compression, CMU lecture notes (the slides’ core reading).
- C. Shannon. A Mathematical Theory of Communication, 1948; C. Shannon. Prediction and Entropy of Printed English, 1951.
- D. Huffman. A Method for the Construction of Minimum-Redundancy Codes, 1952.
- J. Rissanen. Generalized Kraft Inequality and Arithmetic Coding, IBM J. Res. Dev. 1976.
- R. Sedgewick, K. Wayne. Algorithms (4th ed.), 2011 — the figures of tries and Huffman’s algorithm.
- The Hutter prize (prize.hutter1.net); the Challenge on Learned Image Compression (compression.cc).
Added by these notes
- I. Witten, R. Neal, J. Cleary. Arithmetic Coding for Data Compression, CACM 1987 — the integer coder of
coding.py. - A. Sardinas, G. Patterson. A Necessary and Sufficient Condition for the Unique Decomposition of Coded Messages, 1953.
- B. McMillan. Two Inequalities Implied by Unique Decipherability, 1956.
- T. Cover, J. Thomas. Elements of Information Theory, ch. 5 (data compression).
- G. Delétang et al. Language Modeling Is Compression, ICLR 2024 — large language models as general-purpose compressors.
13. Next lecture
Lecture 21 finishes the compression lecture with latent-variable models: how to code with a mixture or a VAE when cannot be enumerated — “max-mode” and posterior-sampling codes, bits-back coding (sending the latent costs nothing net), asymmetric numeral systems (a stack-like coder that makes bits-back practical: BB-ANS, Bit-Swap), compression with flows, and dictionary methods (Lempel–Ziv).