Lecture 20 · Compression I: Entropy, Prefix Codes and Arithmetic Coding

Deep Unsupervised Learning · Lecture 20。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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, P=(0.9,0.05,0.05)P = (0.9, 0.05, 0.05), 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:

  1. Explain why no lossless compressor can shrink every input, and why data with statistical regularities can be compressed.
  2. Tell prefix-free, uniquely decodable and ambiguous codes apart; draw a prefix code as a binary trie; run Huffman’s algorithm by hand.
  3. 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.
  4. Derive the cost of coding with the wrong model: cross-entropy =H(p)+KL(p ∥ q)= H(p) + \mathrm{KL}(p\,\|\,q) — and why this makes maximum likelihood the right objective for compression.
  5. Explain the “+1” problem and the three fixes: blocks, run lengths, arithmetic coding; compute an arithmetic code by hand and bound its length.
  6. 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

AssumedIntroduced hereDeveloped later
Lecture 1 (entropy; the integer arithmetic coder coding.py was used there)prefix codes, Huffman, Kraft–McMillan, Shannon’s theorembits-back coding, ANS, BB-ANS, flows (Lecture 21)
Lecture 2 (maximum likelihood = cross-entropy = code length)arithmetic coding by intervals, its precision, run-length codesLempel–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

XX a symbol (or message) with distribution pp; ℓ(x)\ell(x) the length in bits of the codeword of xx; H(p)=−∑xp(x)log⁡2p(x)H(p) = -\sum_x p(x)\log_2 p(x) the entropy in bits; H(p,q)=−∑xp(x)log⁡2q(x)H(p, q) = -\sum_x p(x)\log_2 q(x) the cross-entropy; KL(p ∥ q)=∑xp(x)log⁡2p(x)q(x)\mathrm{KL}(p\,\|\,q) = \sum_x p(x)\log_2 \frac{p(x)}{q(x)}. “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 p(x)p(x) can encode xx in about −log⁡2p(x)-\log_2 p(x) 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 UU 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 210002^{1000} strings of 1,000 bits but only 1+2+⋯+2999=21000−11 + 2 + \dots + 2^{999} = 2^{1000} - 1 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 2−k2^{-k} of all inputs can shrink by kk 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):

databytesafter zlib
100,000 random bytes100,000100,041 (it grew)
2,000 ShapeWorld images (1 bit per pixel)72,00026,812
2,000 captions (ASCII)144,8898,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:

codeKraft sum ∑2−ℓ\sum 2^{-\ell}prefix-freeuniquely decodable
0 10 110 1111.0000yesyes
0 01 011 01110.9375noyes (needs lookahead)
0 01 101.0000nono: 010 = 0·10 = 01·0
1 01 001 0001 000010.9688yesyes
0 1 001.2500nono

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 ∑xp(x)ℓ(x)\sum_x p(x)\ell(x)? 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
symbolppHuffman codewordlength−log⁡2p-\log_2 p
A0.200022.32
B0.1010033.32
C0.05101044.32
D0.210122.25
E0.361121.47
F0.08101143.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 x,yx, y can be assumed to be siblings at the deepest level (swapping them there never increases the expected length); (iii) merging xx and yy into one symbol zz with p(z)=p(x)+p(y)p(z) = p(x) + p(y) turns any tree for the nn symbols into a tree for n−1n - 1 symbols whose cost is smaller by exactly p(x)+p(y)p(x) + p(y), whatever the tree. So the best tree for nn symbols is the best tree for n−1n - 1 symbols plus the split of zz — which is what Huffman does at every step.


4. The limits: entropy, Kraft–McMillan, Shannon

4.1 Entropy as code length

Shannon’s entropy H(X)=∑xp(x)log⁡21p(x)H(X) = \sum_x p(x)\log_2 \frac{1}{p(x)} is the expected code length when each symbol gets log⁡21p(x)\log_2 \frac{1}{p(x)} bits. When all probabilities are powers of ½ this is exactly achievable: (A,12),(B,14),(C,18),(D,18)(A, \tfrac12), (B, \tfrac14), (C, \tfrac18), (D, \tfrac18) gets codewords 0, 10, 110, 111 with expected length 1.75=H1.75 = H. The theorems below say that in general we can come within 1 bit, and never beat HH.

4.2 The Kraft–McMillan inequality

Part I. For any uniquely decodable binary code with lengths ℓ1,…,ℓn\ell_1, \dots, \ell_n: ∑i2−ℓi≤1.\sum_i 2^{-\ell_i} \le 1. Proof for prefix codes (slides): let L=max⁡iℓiL = \max_i \ell_i and extend the trie to the full binary tree of depth LL. Codeword ii “covers” the 2L−ℓi2^{L - \ell_i} leaves below it; prefix-freeness means no leaf is covered twice; there are 2L2^L leaves. So ∑i2L−ℓi≤2L\sum_i 2^{L - \ell_i} \le 2^L. (McMillan’s extension to all uniquely decodable codes: expand (∑i2−ℓi)k(\sum_i 2^{-\ell_i})^k over all kk-symbol sequences; unique decodability bounds the number of sequences with total length mm by 2m2^m, so (∑i2−ℓi)k≤kL(\sum_i 2^{-\ell_i})^k \le kL; a quantity whose kk-th power grows only linearly in kk is at most 1.)

Part II. Conversely, if ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1, there is a prefix code with exactly these lengths. Proof: sort the lengths; for each in turn take the leftmost free node at depth ℓi\ell_i 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, E[ℓ(X)]≥H(X)\mathbb{E}[\ell(X)] \ge H(X).

Proof. Let qi=2−ℓi/Zq_i = 2^{-\ell_i}/Z with Z=∑j2−ℓj≤1Z = \sum_j 2^{-\ell_j} \le 1. Then E[ℓ]−H=∑ipi(ℓi+log⁡2pi)=∑ipilog⁡2piqi−log⁡2Z=KL(p ∥ q)−log⁡2Z≥0,\mathbb{E}[\ell] - H = \sum_i p_i\big(\ell_i + \log_2 p_i\big) = \sum_i p_i \log_2 \frac{p_i}{q_i} - \log_2 Z = \mathrm{KL}(p\,\|\,q) - \log_2 Z \ge 0, because KL≥0\mathrm{KL} \ge 0 (Gibbs’ inequality) and log⁡2Z≤0\log_2 Z \le 0 (Kraft). Equality needs ℓi=−log⁡2pi\ell_i = -\log_2 p_i exactly.

Converse (within 1 bit). The Shannon code lengths ℓi=⌈−log⁡2pi⌉\ell_i = \lceil -\log_2 p_i \rceil satisfy Kraft (∑2−ℓi≤∑pi=1\sum 2^{-\ell_i} \le \sum p_i = 1), so a prefix code with these lengths exists, and E[ℓ]<∑pi(−log⁡2pi+1)=H+1\mathbb{E}[\ell] < \sum p_i(-\log_2 p_i + 1) = H + 1. Huffman is at least as good, so H≤LHuffman<H+1H \le L_{\text{Huffman}} < H + 1.

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 H+1=3.308H + 1 = 3.308 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:

symbolsDirichlet αmin (Huffman − H)meanmax
21.00.00000.27790.9950
81.00.00550.05380.1679
80.10.02600.36990.9958
641.00.01910.02980.0431
640.050.00650.04950.4693

Always in [0,1)[0, 1). 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:

unitalphabetunits per captionentropy per unit (order 0)Huffman bits / unitHuffman bits / caption
characters2472.43.9283.977288.0
words2417.04.0764.09969.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 qq (lengths −log⁡2q(x)-\log_2 q(x)) but the data come from pp. The expected length is Ep[−log⁡2q(X)]=H(p,q)=H(p)+KL(p ∥ q).\mathbb{E}_p[-\log_2 q(X)] = H(p, q) = H(p) + \mathrm{KL}(p\,\|\,q). The price of the wrong model is exactly the KL divergence, and since KL≥0\mathrm{KL} \ge 0, the true distribution is the best code. This is why maximum likelihood (minimizing the cross-entropy H(p^data,qθ)H(\hat p_{\text{data}}, q_\theta)) 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 H(p)=3.9867H(p) = 3.9867 bits per word:

model qq used to build the codeideal bits / word =H+KL= H + \mathrm{KL}KL(p ∥ q)\mathrm{KL}(p\,\|\,q)Huffman code from qq
q=pq = p3.986704.0052
uniform over the 23 words4.52360.53694.7240
estimated from 10 captions (add-½)4.03310.04654.0625
… from 100 captions3.99460.00794.0234
… from 1,000 captions3.98750.00094.0052
… from 100,000 captions3.98670.00004.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: H(X∣C)≤H(X)H(X \mid C) \le H(X) — knowing something never increases uncertainty on average. Autoregressive models do exactly this, coding each symbol with p(xt∣x<t)p(x_t \mid x_{<t}).

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-kk character models (counts with add-½ smoothing) trained on 50,000 captions and tested on 2,000 others:

context kk (characters)01234681632exact
bits per character3.9251.9980.6090.2590.2320.2170.2180.2160.2370.165
bits per caption284.8145.044.218.816.815.815.815.717.211.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 HH is large and terrible when it is small. The slides’ example: P=(0.9,0.05,0.05)P = (0.9, 0.05, 0.05) has H=0.569H = 0.569 bits per symbol, but the best single-symbol code {0, 10, 11} needs 0.9⋅1+0.1⋅2=1.10.9 \cdot 1 + 0.1 \cdot 2 = 1.1 — almost double. Good predictive models make this common: a model that is usually confident produces exactly such peaked distributions.

Blocks. Code kk symbols at once: the block alphabet has 3k3^k symbols with entropy kHkH, so Huffman needs <kH+1< kH + 1 bits per block, <H+1/k< H + 1/k per symbol (script 03, Part 1):

block length kk123468
block alphabet3927817296,561
Huffman bits / symbol1.10000.72750.62690.59230.57010.5755
excess over HH0.53100.15850.05790.02330.00110.0065

The excess stays below 1/k1/k but is not monotone (k=8k = 8 is slightly worse than k=6k = 6: 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):

codebits per image
raw pixels288
run lengths, Huffman-coded161.4
every pixel independent, P(ink)=0.260P(\text{ink}) = 0.260 (ideal)238.1
exact entropy17.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 [0,1)[0, 1). 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 p(x1)p(x2)⋯=p(message)p(x_1)p(x_2)\cdots = p(\text{message}).

The slides’ example, P(a)=0.8P(a) = 0.8, P(b)=0.2P(b) = 0.2, 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 bb whose completion interval [0.b,0.b+2−∣b∣)[0.b, 0.b + 2^{-|b|}) (all numbers that start with 0.b0.b) lies entirely inside the message’s interval; such codewords are prefix-free over messages. For an interval of width ss such a codeword exists with at most ⌈−log⁡2s⌉+1\lceil -\log_2 s \rceil + 1 bits, so ℓ(message)≤−log⁡2p(message)+2,\ell(\text{message}) \le -\log_2 p(\text{message}) + 2, with the “+2” paid once per message, not per symbol. For “aaba”: p=0.1024p = 0.1024, −log⁡2p=3.288-\log_2 p = 3.288, and the shortest codeword is 10001 (5 bits): every number starting with 0.10001 lies in [0.512,0.6144)[0.512, 0.6144). On 2,000 random messages of 1–39 symbols, codeword length minus −log⁡2p-\log_2 p 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 P=(0.9,0.05,0.05)P = (0.9, 0.05, 0.05):

symbolsfloat interval widthfloat decoder correctinteger coder bitsideal −log⁡2p-\log_2 pinteger decoder correct
100.0194yes75.7yes
1000yes5856.9yes
5000no (first error at symbol 93)293292.8yes
1,0000no (first error at symbol 87)578577.3yes
10,0000no (first error at symbol 90)5,6125,610.7yes

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 −log⁡2p(message)-\log_2 p(\text{message}) 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 p(x1)p(x_1) for the first symbol, p(x2∣x1)p(x_2 \mid x_1) for the second, … — an autoregressive model — and the final width is ∏tp(xt∣x<t)=p(message)\prod_t p(x_t \mid x_{<t}) = p(\text{message}). 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: p(left panel)p(\text{left panel}), then p(right panel∣left panel)p(\text{right panel} \mid \text{left panel}) with the copy rule), then decoded and compared with the original:

compressorparametersreal bits / imageideal bitsmodel −log⁡2p-\log_2 pround 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,23252.651.551.5yes
MADE591,13633.632.532.5yes
WaveNet + coordinates100,70524.623.523.5yes
gated PixelCNN176,38623.522.522.5yes
Transformer on 2 × 2 patch tokens (Lecture 4)206,86419.918.818.8yes
Transformer on 4 × 4 dictionary tokens261,84520.119.018.8yes
Transformer on whole-panel tokens324,16020.018.918.9yes
the exact model—18.817.817.8yes

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 −log⁡2p-\log_2 p 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)

compressorbits per caption
ASCII (8 bits per character)581.7
Huffman on single characters288.9
lzma, all 500 captions in one file39.4
Lecture 4’s character Transformer + arithmetic coding12.9 (round trip exact)
exact entropy11.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 NN images is bits(model)+N⋅bits per image\text{bits}(\text{model}) + N \cdot \text{bits per image}:

images NNlzma (decompressor not counted)gated PixelCNN, 16-bit weightsthe true generator (toy_worlds.py without comments, lzma: 4.0 KB)
10111.7282,2413,267
1,000111.72,84651.3
100,000111.751.819.1
10,000,000111.723.818.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

  1. 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.
  2. Prefix codes are binary tries and decode without lookahead; uniquely decodable codes need not be prefix-free, but by Kraft–McMillan (∑2−ℓi≤1\sum 2^{-\ell_i} \le 1 for every uniquely decodable code, and every such set of lengths has a prefix code) nothing is gained by leaving prefix codes.
  3. Shannon: no uniquely decodable code beats the entropy on average; Shannon’s lengths ⌈−log⁡2p⌉\lceil -\log_2 p \rceil come within 1 bit; Huffman (merge the two lightest trees) is the optimal symbol code: 2.36 bits for the slides’ example (H=2.308H = 2.308), always within [H,H+1)[H, H + 1).
  4. Coding with a model qq costs the cross-entropy H(p)+KL(p ∥ q)H(p) + \mathrm{KL}(p\,\|\,q): maximum likelihood is minimum code length. Context lowers entropy: order-kk character models took the caption language from 285 to ~16 bits per caption (exact: 11.97), until the counts ran out.
  5. The “+1” of symbol codes hurts when HH 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 p(message)p(\text{message}), coded in at most −log⁡2p+2-\log_2 p + 2 bits in total. Real coders use integers and renormalization — a float64 coder broke after ~90 symbols.
  6. 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 −log⁡2p-\log_2 p (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

  1. “A good compressor shrinks everything.” It cannot; it shrinks the likely inputs at the expense of the others.
  2. 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.
  3. Ignoring the “+1” when the entropy per symbol is small: a symbol code can cost nearly twice the entropy.
  4. 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).
  5. Assuming more context always helps a counting model: with finite data, long contexts are sparse (order 32 was worse than order 16).
  6. 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.
  7. 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 ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1 for a prefix code by the leaf-counting argument.

Answer

Let L=max⁡iℓiL = \max_i \ell_i. In the complete binary tree of depth LL, the codeword of length ℓi\ell_i is a node whose subtree contains 2L−ℓi2^{L - \ell_i} 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 2L2^L leaves in total: ∑i2L−ℓi≤2L\sum_i 2^{L - \ell_i} \le 2^L; divide by 2L2^L.

Exercise 2 (Kraft Part II — derivation). Given lengths with ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \le 1, 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 1,…,k−11, \dots, k - 1 (lengths ≤ℓk\le \ell_k), the used subtrees cover ∑i<k2ℓk−ℓi\sum_{i < k} 2^{\ell_k - \ell_i} of the 2ℓk2^{\ell_k} nodes at depth ℓk\ell_k (each earlier codeword blocks 2ℓk−ℓi2^{\ell_k - \ell_i} of them, disjointly). Since ∑i≤k2−ℓi≤1\sum_{i \le k} 2^{-\ell_i} \le 1, ∑i<k2ℓk−ℓi≤2ℓk−1\sum_{i < k} 2^{\ell_k - \ell_i} \le 2^{\ell_k} - 1: at least one node at depth ℓk\ell_k 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 E[ℓ(X)]≥H(X)\mathbb{E}[\ell(X)] \ge H(X) for every uniquely decodable code using Gibbs’ inequality and Kraft.

Answer

See §4.3: with qi=2−ℓi/Zq_i = 2^{-\ell_i}/Z, Z=∑j2−ℓj≤1Z = \sum_j 2^{-\ell_j} \le 1, E[ℓ]−H=KL(p ∥ q)−log⁡2Z≥0\mathbb{E}[\ell] - H = \mathrm{KL}(p\,\|\,q) - \log_2 Z \ge 0. Gibbs’ inequality (KL≥0\mathrm{KL} \ge 0) follows from Jensen: −KL=∑pilog⁡2(qi/pi)≤log⁡2∑pi(qi/pi)=log⁡2∑qi=0-\mathrm{KL} = \sum p_i \log_2(q_i/p_i) \le \log_2 \sum p_i (q_i/p_i) = \log_2 \sum q_i = 0.

Exercise 4 (the price of the wrong model — derivation). Show Ep[−log⁡2q(X)]=H(p)+KL(p ∥ q)\mathbb{E}_p[-\log_2 q(X)] = H(p) + \mathrm{KL}(p\,\|\,q), and conclude that the expected Shannon code length built from qq is between H(p)+KLH(p) + \mathrm{KL} and H(p)+KL+1H(p) + \mathrm{KL} + 1.

Answer

−log⁡2q=−log⁡2p+log⁡2(p/q)-\log_2 q = -\log_2 p + \log_2(p/q); take the expectation under pp. With lengths ⌈−log⁡2q(x)⌉∈[−log⁡2q,−log⁡2q+1)\lceil -\log_2 q(x) \rceil \in [-\log_2 q, -\log_2 q + 1) the expected length lies in [H+KL,H+KL+1)[H + \mathrm{KL}, H + \mathrm{KL} + 1). Script 02: a uniform model on caption words costs KL=0.537\mathrm{KL} = 0.537 bits per word more.

Exercise 5 (Huffman by hand). Build the Huffman code for P=(0.4,0.2,0.2,0.1,0.1)P = (0.4, 0.2, 0.2, 0.1, 0.1); 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 0.4⋅2+0.2⋅2⋅2+0.1⋅3⋅2=2.20.4 \cdot 2 + 0.2 \cdot 2 \cdot 2 + 0.1 \cdot 3 \cdot 2 = 2.2; merging the new 0.2 with an original one gives lengths (1, 2, 3, 4, 4): 0.4+0.4+0.6+0.4+0.4=2.20.4 + 0.4 + 0.6 + 0.4 + 0.4 = 2.2. Both are optimal; ties make Huffman codes non-unique. (H=2.122H = 2.122.)

Exercise 6 (blocks — derivation). For i.i.d. symbols, show that Huffman on blocks of kk symbols uses <H+1/k< H + 1/k bits per symbol.

Answer

The block (X1,…,Xk)(X_1, \dots, X_k) has entropy kHkH (independence). Huffman on the block alphabet has expected length <kH+1< kH + 1 per block, i.e. <H+1/k< H + 1/k per symbol. Script 03 (Part 1) shows the bound is not the whole story: the actual excess is not monotone in kk.

Exercise 7 (arithmetic code length — derivation). Show that an interval [ℓ,ℓ+s)[\ell, \ell + s) contains a dyadic interval [m2−k,(m+1)2−k)[m 2^{-k}, (m + 1)2^{-k}) with k=⌈−log⁡2s⌉+1k = \lceil -\log_2 s \rceil + 1.

Answer

With k=⌈−log⁡2s⌉+1k = \lceil -\log_2 s\rceil + 1, 2−k≤s/22^{-k} \le s/2. Let m=⌈ℓ 2k⌉m = \lceil \ell\, 2^k \rceil, so m2−k<ℓ+2−km 2^{-k} < \ell + 2^{-k} and (m+1)2−k<ℓ+2⋅2−k≤ℓ+s(m + 1)2^{-k} < \ell + 2 \cdot 2^{-k} \le \ell + s. The codeword (the kk binary digits of mm) therefore has length ≤−log⁡2s+2\le -\log_2 s + 2; with s=p(message)s = p(\text{message}) this is the “+2” of §7.1.

Exercise 8 (coding). Change script 03, Part 4 to a source with H=0.1H = 0.1 bits per symbol. After how many symbols does the float coder fail? Explain.

Answer

(Run it.) The interval shrinks by about 2−H2^{-H} per symbol on average; float64 resolves about 2−532^{-53} relative to low, so failure comes after roughly 53/H≈53053/H \approx 530 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 p(x)=∑zp(z)p(x∣z)p(x) = \sum_z p(z)p(x \mid z) 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).

← 返回课程目录