IT·06
The Source Coding Theorem: Why Entropy Is the Limit
Shannon's first theorem, proved and measured: typical sequences, the few that carry almost all the probability, about 2^(nH) of them; why that means a source can be compressed to H bits per symbol and no further; why no compressor can shrink random data, by counting; arithmetic coding, which reaches the entropy without Huffman's whole-bit rounding, built and run on Shakespeare and on a 1-in-100 coin; and universal compression, which learns the probabilities as it goes for a small, predictable price.
Start here
What this chapter answers
Why exactly can't a compressor beat the entropy, and why can it get as close as it likes? What does a long message from a source "usually" look like? Why does no compressor shrink every file, and why does random data never shrink? How does arithmetic coding spend fractions of a bit per symbol? And how can a compressor do well on data whose probabilities nobody told it?
The theorem in one picture
Toss a coin that lands heads 90 % of the time, 1,000 times. There are possible sequences, but you'll almost certainly see one with between about 70 and 130 tails. Every such sequence has roughly the same probability, about , because , and there are only about of them. So a code needs to name only those, which takes about 469 bits, not 1,000. The rare sequences outside the typical set can be given long codewords: they almost never happen, so they hardly affect the average. That's the whole idea of the theorem.
Typical sequences
What long messages look like
Take independent symbols from a source with entropy . By the law of large numbers (chapter 3), each symbol appears close to its expected number of times: about times for symbol . A sequence with exactly those counts has probability
The surprise of the whole sequence is bits: per symbol, the average surprise, just as the law of large numbers says an average should be. Sequences whose counts are close to the expected ones are called typical.
"Equipartition" because the probability is shared almost equally among the typical sequences. It's a strange picture: the single most likely sequence (all heads, for the 90/10 coin) isn't typical, and neither are most sequences (most of the have about 500 tails). The typical set is a tiny fraction of all sequences that holds almost all of the probability. The lab counts it.
Counting with binomial coefficients
For a coin, the typical sequences with tails number (chapter 2). With , Stirling's approximation gives
the binary entropy times . That's the counting side of the same fact: the number of sequences with the typical proportion of tails is about . It's also why chapter 2's exercise C2 found that a set of 1,000 ids from a million carries bits: about .
The source coding theorem
The theorem has two halves, and both matter. The first says compression to is possible: there's no further hidden cost. The second says it's a limit: any claim to do better on average, for a source of known statistics, is wrong. The proof's code (send the index of a typical sequence) is hopeless in practice, since the list of typical sequences is astronomically long; the rest of the chapter is about practical codes that get there.
Why random data can't be compressed
The theorem has a blunt corollary. A source of uniformly random bytes has entropy 8 bits per byte, so nothing compresses its output on average. But there's an even simpler argument, which doesn't need probabilities at all.
So every compressor is a bet: it shortens the files it expects (text, images, logs, with their low entropy) at the cost of lengthening others slightly. Random data, and data that's already compressed or encrypted, is exactly the kind it can't win on. The lab checks all 65,536 two-byte files: zlib makes every one of them bigger, because its fixed header costs more than any saving.
Arithmetic coding
Coding a whole message as one number
Huffman's weakness is the whole-number codeword per symbol. Arithmetic coding gives up codewords altogether and codes the entire message as one number between 0 and 1.
Start with the interval . Split it into slices, one per symbol, with widths equal to the symbols' probabilities (chapter 3's companion did exactly this to make random choices). The first symbol picks its slice. Split that slice the same way, and the second symbol picks a slice of it. After symbols the interval has width equal to the probability of the whole message, . Any number inside it identifies the message (given its length), and a number inside an interval of width can be written in about binary digits. That's the message's total surprise, plus at most 2 bits for the whole message, not per symbol.
Making it work with integers
Real coders can't use infinitely precise fractions. They keep the interval as two integers (32 bits each in the lab's coder) and, whenever the interval falls entirely in the lower or upper half, they output the bit that says which half and double the interval, so it never gets too small to split. An interval straddling the middle is handled by remembering "pending" bits until it's resolved. The decoder mirrors every step, reading bits into a window and finding which slice the current value falls in. Witten, Neal and Cleary's 1987 paper gave the version the lab uses; the rounding it introduces costs a tiny fraction of a bit per symbol.
The lab's coder reaches the entropy almost exactly. For 100,000 tosses of a coin that lands 1 with probability 0.01, the entropy is 8,238 bits in all and the arithmetic code is 8,239 bits long, while Huffman would need 100,000 (one digit per toss). For Shakespeare's bytes with order-0 counts, the code is 1 bit above the order-0 entropy for the whole 1.1 MB file, against Huffman's 0.038 bits per byte. The remaining cost is the model: sending the counts, or learning them.
Modelling and coding, separated
Arithmetic coding doesn't care where the probabilities come from: they can change from symbol to symbol. That separates compression into two jobs. A model predicts the next symbol's probabilities, using anything the decoder also knows (the symbols so far, context, a dictionary). A coder turns those probabilities into bits, at a cost of per symbol. Every modern high-compression format works this way, and improving compression means improving the model. Asymmetric numeral systems (ANS) do the coder's job with the same efficiency and less arithmetic, which is why recent formats prefer them.
Universal compression
Learning the probabilities
So far the probabilities were known. In practice they're learned. An adaptive coder starts with smoothed counts (chapter 3) and updates them after each symbol; the decoder makes the same updates, so no table is sent. Learning costs something: early symbols are coded with poor estimates. For a source with symbols and symbols coded, the extra cost is about bits in total, so it vanishes per symbol as grows. The lab measures 1,821 extra bits for adaptive coding of Shakespeare's bytes, against 2,561 predicted for 256 possible symbols (the plays use only 65, which is why learning was cheaper).
Lempel–Ziv: the past as a dictionary
Lempel and Ziv took a different route. LZ77 (1977) replaces a string that occurred earlier with a pointer: "copy 12 bytes from 340 bytes back". LZ78 (1978) builds a dictionary of phrases as it goes, each new phrase being an old one plus one symbol. Neither has any probabilities, yet Ziv and Lempel proved that, for any stationary source, their compressed size per symbol approaches the source's entropy rate as the input grows. They're universal: good for every source without knowing which one it is. DEFLATE (ZIP, gzip, PNG) combines LZ77 with Huffman coding; lzma combines LZ77-style matching with an adaptive arithmetic coder, which is why it did so well in chapter 1.
Lab: the theorem measured
Experiment 1: typical sequences
import math
p = 0.1 # a coin that lands 1 with probability 0.1
H = -p * math.log2(p) - (1 - p) * math.log2(1 - p)
def log2C(n, k):
return (math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)) / math.log(2)
n = 1000
print(f"entropy {H:.4f} bits per toss; n = {n}: nH = {n * H:.1f}")
for k in (0, 50, 100, 150, 300):
print(f" a sequence with {k:>3} ones has probability 2^{k * math.log2(p) + (n - k) * math.log2(1 - p):7.1f}; there are 2^{log2C(n, k):5.1f} such sequences")
print("typical sequences: those whose number of ones is within 3 standard deviations of np")
for n in (100, 1000, 10_000, 100_000, 1_000_000):
sd = math.sqrt(n * p * (1 - p))
lo, hi = math.ceil(n * p - 3 * sd), math.floor(n * p + 3 * sd)
prob = sum(math.exp(log2C(n, k) * math.log(2) + k * math.log(p) + (n - k) * math.log(1 - p)) for k in range(lo, hi + 1))
m = max(log2C(n, k) for k in range(lo, hi + 1))
count = m + math.log2(sum(2 ** (log2C(n, k) - m) for k in range(lo, hi + 1)))
print(f" n = {n:>7,}: they hold {prob:.4f} of the probability; there are 2^{count:,.1f} of them = 2^({count / n:.4f} n)")
entropy 0.4690 bits per toss; n = 1000: nH = 469.0
a sequence with 0 ones has probability 2^ -152.0; there are 2^ 0.0 such sequences
a sequence with 50 ones has probability 2^ -310.5; there are 2^282.3 such sequences
a sequence with 100 ones has probability 2^ -469.0; there are 2^464.4 such sequences
a sequence with 150 ones has probability 2^ -627.5; there are 2^605.0 such sequences
a sequence with 300 ones has probability 2^-1103.0; there are 2^876.1 such sequences
typical sequences: those whose number of ones is within 3 standard deviations of np
n = 100: they hold 0.9980 of the probability; there are 2^67.2 of them = 2^(0.6722 n)
n = 1,000: they hold 0.9973 of the probability; there are 2^547.4 of them = 2^(0.5474 n)
n = 10,000: they hold 0.9974 of the probability; there are 2^4,962.8 of them = 2^(0.4963 n)
n = 100,000: they hold 0.9973 of the probability; there are 2^47,785.7 of them = 2^(0.4779 n)
n = 1,000,000: they hold 0.9973 of the probability; there are 2^471,832.7 of them = 2^(0.4718 n)
For 1,000 tosses of the 90/10 coin, the single likeliest sequence (no ones) has probability , but there's only one of it. Sequences with 100 ones each have probability , exactly , and there are about of them: together they hold about 4 % of the probability, more than any other single count, and the counts near 100 hold nearly all of it. Sequences within 3 standard deviations of the expected count hold 99.7 % of the probability at every length, and their number, per symbol, falls towards the entropy as grows: at , at 100,000, at a million, approaching .
Experiment 2: nothing shrinks every file
import lzma, zlib
grew = same = shrank = 0
for i in range(65_536):
data = i.to_bytes(2, "big")
z = len(zlib.compress(data, 9))
shrank += z < 2; same += z == 2; grew += z > 2
print(f"all 65,536 two-byte files through zlib: {shrank} shrank, {same} stayed the same, {grew:,} grew")
n = 20
print(f"files of exactly {n} bits: 2^{n} = {2 ** n:,}; files of fewer bits, all lengths together: {2 ** n - 1:,}")
all 65,536 two-byte files through zlib: 0 shrank, 0 stayed the same, 65,536 grew
files of exactly 20 bits: 2^20 = 1,048,576; files of fewer bits, all lengths together: 1,048,575
Every one of the 65,536 possible two-byte files gets bigger under zlib, because its header and checksum cost more than anything it could save on two bytes. The second line is the counting argument: there are 1,048,576 files of exactly 20 bits and only 1,048,575 shorter ones, so no lossless method can shorten them all.
Experiment 3: arithmetic coding reaches the entropy
"""A small arithmetic coder (after Witten, Neal and Cleary, 1987): 32-bit integer ranges, static counts."""
from bisect import bisect_right
from itertools import accumulate
TOP, HALF, QUARTER = (1 << 32) - 1, 1 << 31, 1 << 30
def encode(symbols, counts):
"""counts: {symbol: count > 0}. Returns the code as a string of '0'/'1'."""
keys = sorted(counts)
start = dict(zip(keys, [0] + list(accumulate(counts[k] for k in keys)))) # start of each symbol's slice
total = sum(counts.values())
low, high, pending, out = 0, TOP, 0, []
def emit(bit):
nonlocal pending
out.append(bit); out.extend([bit ^ 1] * pending); pending = 0
for s in symbols:
span = high - low + 1
high = low + span * (start[s] + counts[s]) // total - 1 # narrow [low, high] to the symbol's slice
low = low + span * start[s] // total
while True:
if high < HALF:
emit(0)
elif low >= HALF:
emit(1); low -= HALF; high -= HALF
elif low >= QUARTER and high < HALF + QUARTER: # straddling the middle: defer the bit
pending += 1; low -= QUARTER; high -= QUARTER
else:
break
low, high = 2 * low, 2 * high + 1
pending += 1
emit(0 if low < QUARTER else 1) # two final bits pin a point inside [low, high]
return "".join(map(str, out))
def decode(bits, counts, n):
keys = sorted(counts)
starts = [0] + list(accumulate(counts[k] for k in keys))
total = starts[-1]
it = iter(bits)
nxt = lambda: int(next(it, "0"))
low, high, value = 0, TOP, 0
for _ in range(32):
value = 2 * value + nxt()
out = []
for _ in range(n):
span = high - low + 1
target = ((value - low + 1) * total - 1) // span
i = bisect_right(starts, target) - 1
s = keys[i]
out.append(s)
high = low + span * starts[i + 1] // total - 1
low = low + span * starts[i] // total
while True:
if high < HALF:
pass
elif low >= HALF:
low -= HALF; high -= HALF; value -= HALF
elif low >= QUARTER and high < HALF + QUARTER:
low -= QUARTER; high -= QUARTER; value -= QUARTER
else:
break
low, high, value = 2 * low, 2 * high + 1, 2 * value + nxt()
return out
import math, random
from collections import Counter
from ac import encode, decode
random.seed(1976)
bits = [1 if random.random() < 0.01 else 0 for _ in range(100_000)]
c = Counter(bits)
H = sum(-k / len(bits) * math.log2(k / len(bits)) for k in c.values())
code = encode(bits, c)
assert decode(code, c, len(bits)) == bits
print(f"100,000 bits, 1 with probability 0.01: entropy {H * len(bits):,.0f} bits in all;"
f" arithmetic code {len(code):,} bits ({len(code) / len(bits):.4f} per symbol); Huffman would need 100,000")
text = open("data/shakespeare.txt", "rb").read()
c = Counter(text)
H = sum(-k * math.log2(k / len(text)) for k in c.values())
code = encode(text, c)
assert bytes(decode(code, c, len(text))) == text
print(f"Shakespeare's {len(text):,} bytes: order-0 entropy {H:,.0f} bits; arithmetic code {len(code):,} bits"
f" ({len(code) / len(text):.4f} per byte; {len(code) - H:.1f} bits above the entropy); Huffman 4.8170 per byte")
100,000 bits, 1 with probability 0.01: entropy 8,238 bits in all; arithmetic code 8,239 bits (0.0824 per symbol); Huffman would need 100,000
Shakespeare's 1,115,394 bytes: order-0 entropy 5,330,862 bits; arithmetic code 5,330,863 bits (4.7794 per byte; 1.0 bits above the entropy); Huffman 4.8170 per byte
For the 1-in-100 coin, the arithmetic code (8,239 bits) is within 1 bit of the entropy of the whole sequence (8,238): 0.082 bits per toss, where Huffman can't go below 1. For Shakespeare's bytes with their order-0 counts, it's 1 bit above the entropy for the whole file, 4.7794 bits per byte against Huffman's 4.8170. Both round trips are exact. Arithmetic coding has removed the coder from the list of things that limit compression; only the model remains.
Experiment 4: the price of learning
import math
from collections import Counter
data = open("data/shakespeare.txt", "rb").read()
n = len(data)
c = Counter(data)
static = sum(-k * math.log2(k / n) for k in c.values())
def adaptive(add, K=256):
counts, seen, bits = [0] * K, 0, 0.0
for b in data:
bits -= math.log2((counts[b] + add) / (seen + add * K))
counts[b] += 1; seen += 1
return bits
kt = adaptive(0.5)
print(f"static order-0 code with the counts known in advance: {static:,.0f} bits (+ a table to send them)")
print(f"adaptive order-0 code (add a half), no table needed: {kt:,.0f} bits; the cost of learning: {kt - static:,.0f} bits")
print(f"theory for learning K = 256 probabilities: about (K - 1)/2 x log2 n = {255 / 2 * math.log2(n):,.0f} bits")
static order-0 code with the counts known in advance: 5,330,862 bits (+ a table to send them)
adaptive order-0 code (add a half), no table needed: 5,332,683 bits; the cost of learning: 1,821 bits
theory for learning K = 256 probabilities: about (K - 1)/2 x log2 n = 2,561 bits
Learning the byte probabilities as it goes, an adaptive coder spends 1,821 bits more than one that was given the final counts in advance: about 228 bytes on a 1.1 MB file, less than the table the static coder would have to send. The theory's predicts 2,561 bits for 256 possible bytes; the plays use only 65 of them, so the real cost is lower. Learning costs a fixed number of bits, not a fixed fraction, so for long inputs it's negligible: that's what makes universal compression possible.
Worked examples
Typical sequences by hand
An arithmetic code by intervals
The cost of learning
Exercises
Practice
- For 100 tosses of a fair coin, how many sequences are there, how many are typical (about 50 heads), and what's the probability of each?
- A source has entropy 2.3 bits per symbol. About how many bits does an ideal code need for 10,000 symbols?
- Why can't a compressor guarantee to save at least one byte on every 1 KB file?
- In arithmetic coding, what's the width of the interval for the message A B A with P(A) = 0.6 and P(B) = 0.4? About how many digits does it need?
- Huffman codes a source with P = 0.95 and 0.05 at 1 digit per symbol. What does arithmetic coding approach?
- An adaptive coder learns a 256-symbol source over 10 million symbols. Estimate the learning cost in bytes.
- Name the two halves of the source coding theorem.
Answers
- sequences; about , roughly , have exactly 50 heads (and nearby counts add more, approaching in total, since for a fair coin nearly every sequence is typical); each has probability .
- About 23,000 bits.
- By counting: there are files of 1 KB and fewer files of all shorter lengths together, so a lossless compressor can't shorten them all.
- ; about , so about 4 to 5 digits.
- bits per symbol.
- bits, about 370 bytes.
- Compression to bits per symbol is achievable; no lossless code averages fewer than .
Harder
- Show that the most likely single sequence of a 90/10 coin (all heads) isn't typical for large , and explain why that doesn't contradict "typical sequences hold almost all the probability".
- Prove that, averaged over all files of bits equally, any lossless compressor's output averages at least bits (Hint: there are only outputs of length ).
- Explain why arithmetic coding's extra cost is "at most about 2 bits per message" rather than per symbol, and why real coders lose a little more.
- A file contains English text followed by the same text again. Which compresses it better, an order-0 arithmetic coder or LZ77, and why?
- Why is the source coding theorem's proof code (index into the typical set) impractical, and what do practical codes do instead?
Answers
- All heads has probability , and , so its surprise per symbol is far from : not typical. It's the likeliest single sequence, but it's one sequence; the typical set has about members, each much less likely, and together they hold almost all the probability. Likeliest and typical are different questions.
- To give inputs different outputs with the smallest total length, use all strings of each length in turn. The strings of length cover half the inputs, of length a quarter, and so on; the average length is , which works out to , at least . So even the best possible compressor saves at most 2 bits on average over all files: for random data, compression is essentially impossible.
- The final interval has width , the message's probability, and some binary fraction with digits lies inside any interval of width : so at most about 2 digits beyond the total surprise, once for the message. Real coders lose a little more because they round the interval to finite precision at every step (each rounding shaves a tiny bit of width), and because they must also say where the message ends (its length, or an end symbol).
- LZ77: when it reaches the second copy, it replaces the whole thing with a few pointers ("copy everything from bytes back"), costing almost nothing. An order-0 coder sees the same letter frequencies twice and codes the second half at the same cost as the first: it can't see repetition, only frequencies.
- The list of typical sequences has about entries, astronomically many for any useful , so the encoder can't store it or search it. Practical codes get the same result symbol by symbol: arithmetic coding narrows an interval by each symbol's probability, so the final width is the message's probability and its length is the message's surprise, with no list at all.
Challenge
- Show that the number of binary sequences of length with exactly ones satisfies . (Hint: for the upper bound, expand with the binomial theorem and keep one term.)
Discussion
Upper bound: by the binomial theorem, , and that sum is at least its single term ; and (take ), so . Lower bound: of the terms in the sum, the one with is the largest (a standard check: the ratio of consecutive terms crosses 1 there), so it's at least the average, . So . Taking logarithms, : the number of sequences with the typical proportion of ones is up to a factor that's tiny on a logarithmic scale. This is the method of types, the cleanest route to the source coding theorem for binary sources.
In real life
Misconceptions and limits
The model to keep
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "The most likely sequence is the typical one." | All heads is likeliest but not typical; typical ones are each less likely and far more numerous. | Typical sequences; harder exercise 8 |
| "A clever enough compressor can shrink any file." | No: there are fewer shorter files than files. | Why random data can't be compressed; Experiment 2 |
| "Compressing twice compresses more." | Compressed output is near-random; a second pass gains nothing (chapter 4's exercises measured it). | Why random data can't be compressed |
| "Huffman is as good as it gets." | Arithmetic coding reached 0.082 bits per toss where Huffman needs 1. | Experiment 3 |
| "Arithmetic coding loses a little on every symbol." | It loses about 2 bits per message, plus tiny rounding. | Making it work with integers |
| "A compressor needs to be told the statistics." | Adaptive and Lempel–Ziv methods learn them for a small fixed cost. | Universal compression; Experiment 4 |
| "Entropy is the limit for any file." | It's the limit for a source model; a better model has lower entropy. | Modelling and coding, separated |
| "The theorem's proof shows how to build compressors." | Its code is a list of sequences; practical codes get there symbol by symbol. | Harder exercise 12 |
Limits and trade-offs
- The theorem is about averages and long messages. For short messages, the fixed costs (headers, learning, the final bits of an arithmetic code) dominate; for a particular file, the entropy of the "true source" isn't defined.
- Sources with memory need a model of the memory. The theorem extends to stationary ergodic sources with entropy rate in place of (McMillan, Breiman), but the compressor has to capture the dependence; chapter 7 measures how much it's worth.
- Arithmetic coding is slower than Huffman, and its errors spread: one wrong bit derails everything after it. ANS reduces the speed cost; chapters 8 and 9 deal with errors.
Revision sheet
Key ideas
- Typical sequences: probability ; about of them; together almost all the probability (law of large numbers).
- .
- Source coding theorem: achievable at per symbol; impossible below .
- Counting: files of bits, shorter files: no compressor shrinks all; random data doesn't compress.
- Arithmetic coding: interval width = message probability; length ≈ total surprise + 2 bits; model and coder separate.
- Adaptive coding: learning costs about bits in total.
- Lempel–Ziv: LZ77 (pointers to earlier copies), LZ78 (growing dictionary); universal for stationary sources.
- ANS: arithmetic-coding efficiency at Huffman speed.
Glossary
- Typical sequence: a sequence whose surprise per symbol is close to the source's entropy; long sequences are almost always typical.
- Typical set: the set of typical sequences of a given length; about members holding almost all the probability.
- Asymptotic equipartition property: the fact that long sequences from a source have probability close to , shared almost equally among about typical sequences.
- Source coding theorem: Shannon's result that a source can be losslessly compressed to its entropy per symbol, and no further.
- Counting argument (compression): the proof that no lossless compressor shortens every file, because there are fewer shorter files than files.
- Arithmetic coding: coding a whole message as a number inside an interval whose width is the message's probability, so it costs about its total surprise.
- Model (compression): the part of a compressor that predicts the probabilities of the next symbol.
- Coder (compression): the part of a compressor that turns predicted probabilities into bits.
- Adaptive coding: coding with probabilities learned from the symbols seen so far, updated identically by encoder and decoder.
- Universal compression: compression that approaches the entropy of any source in a broad class without being told which source it is.
- Lempel–Ziv compression: dictionary methods (LZ77, LZ78) that replace repeated strings with references to earlier occurrences.
- Asymmetric numeral systems (ANS): a family of entropy coders with arithmetic coding's efficiency and table-driven speed.