Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·06

The Source Coding Theorem: Why Entropy Is the Limit

Around chapter 6: how typicality, the coding theorem, arithmetic coding and universal compression fit together; three other ways to see them; what the chapter simplifies (how long "long blocks" must be, why forgetting beats remembering for changing data, and how slowly real dictionary compressors approach the entropy); how Zstandard rounds probabilities to a power-of-two table and what that costs; four debugging drills; and interview questions.

6 topics · ~17 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Law of large numbers (chapter 3) → surprise per symbol concentrates at H → typical sequences: about 2nH, probability about 2−nH each.
  • Counting (chapter 2): log2(npn)≈nh(p) → the same fact for coins.
  • Source coding theorem: achievable at H+ε (index the typical set) + converse (chapter 5's bound for blocks).
  • Counting argument: no compressor shrinks every file → random and compressed data don't compress.
  • Arithmetic coding: interval width = message probability → total surprise + 2 bits → model and coder separate.
  • Adaptive models: learning cost K−12log2n → universal codes → Lempel–Ziv for stationary sources.
  • Next: sources with memory and conditional entropy (chapter 7); errors in compressed streams (chapters 8 and 9); real data (chapter 10); cross-entropy as the cost of a model (chapter 11).

Explain it differently

The library of all books. Imagine a library holding every possible 1,000-letter book. Almost all of it is gibberish. A source like English writes almost only in one small wing, the typical books, and a catalogue of that wing needs far fewer digits per book than a catalogue of the whole library. Compression is cataloguing the wing; the entropy says how big the wing is.

Arithmetic coding as zooming into a map. Start with a map of the whole world. Each symbol zooms in on a region whose size is its probability: likely symbols zoom in a little, unlikely ones a lot. After the message, you're looking at a tiny patch, and the coordinates of that patch, written in binary, are the code. Zooming a little costs few digits; zooming a lot costs many.

Universal compression as learning a language by reading. A compressor that knows nothing at first is like a reader new to a language: the first pages are full of surprises, but soon the common words and phrases are expected. The surprises of the first pages are the learning cost; after that, it reads (and codes) like a native.

Gaps and misconceptions

What the chapter oversimplifies

1. "With long enough blocks", but how long? The theorem promises H+ε for long blocks without saying how long. For Huffman coding of blocks of a 90/10 coin:

Python
import math
from itertools import product
from huff import huffman_lengths
p = 0.1
H = -p * math.log2(p) - (1 - p) * math.log2(1 - p)
print(f"coin with P(1) = {p}: entropy {H:.4f} bits per toss")
for m in (1, 2, 4, 8, 12, 16):
    blocks = {b: p ** sum(b) * (1 - p) ** (m - sum(b)) for b in product((0, 1), repeat=m)}
    L = sum(blocks[b] * l for b, l in huffman_lengths(blocks).items()) / m
    print(f"Huffman on blocks of {m:>2} tosses ({2 ** m:>6} codewords): {L:.4f} per toss (+{100 * (L / H - 1):.1f} %)")
Text
coin with P(1) = 0.1: entropy 0.4690 bits per toss
Huffman on blocks of  1 tosses (     2 codewords): 1.0000 per toss (+113.2 %)
Huffman on blocks of  2 tosses (     4 codewords): 0.6450 per toss (+37.5 %)
Huffman on blocks of  4 tosses (    16 codewords): 0.4926 per toss (+5.0 %)
Huffman on blocks of  8 tosses (   256 codewords): 0.4758 per toss (+1.5 %)
Huffman on blocks of 12 tosses (  4096 codewords): 0.4700 per toss (+0.2 %)
Huffman on blocks of 16 tosses ( 65536 codewords): 0.4717 per toss (+0.6 %)

One toss at a time costs 113 % above the entropy; blocks of 4 cost 5 %, blocks of 8 cost 1.5 % (256 codewords), and blocks of 12 reach 0.2 % with 4,096 codewords. Blocks of 16 are slightly worse (0.6 %) with 65,536 codewords: the rounding doesn't fall steadily. Table size grows exponentially with block length while the gain shrinks, which is why practical coders use arithmetic coding or ANS instead of big blocks: they get the long-block result with no table at all.

2. "Learning costs a fixed number of bits", for a source that doesn't change. For data whose statistics change, remembering everything is the wrong strategy:

Python
import math
parts = [open(f, "rb").read()[:200_000] for f in ("data/shakespeare.txt", "data/server.log", "data/squares.csv")]
data = b"".join(parts)
def adaptive(data, halve_at=None):
    counts, total, bits = [0.5] * 256, 128.0, 0.0
    for b in data:
        bits -= math.log2(counts[b] / total)
        counts[b] += 1; total += 1
        if halve_at and total > halve_at:              # forget: halve every count
            counts = [c / 2 for c in counts]; total /= 2
    return bits / len(data)
print(f"600,000 bytes: 200,000 of the plays, then a server log, then a table of squares")
print(f"adaptive, remembering everything:     {adaptive(data):.3f} bits per byte")
for limit in (100_000, 10_000, 1_000):
    print(f"adaptive, halving counts past {limit:>7,}: {adaptive(data, limit):.3f} bits per byte")
for name, part in zip(("plays", "log", "squares"), parts):
    print(f"  each part alone, remembering everything: {name:<8} {adaptive(part):.3f}")
Text
600,000 bytes: 200,000 of the plays, then a server log, then a table of squares
adaptive, remembering everything:     5.104 bits per byte
adaptive, halving counts past 100,000: 4.485 bits per byte
adaptive, halving counts past  10,000: 4.238 bits per byte
adaptive, halving counts past   1,000: 4.214 bits per byte
  each part alone, remembering everything: plays    4.768
  each part alone, remembering everything: log      4.371
  each part alone, remembering everything: squares  3.564

On a file made of three different parts (the plays, the capstone's server log and its table of squares), an adaptive coder that remembers every count spends 5.10 bits per byte: by the time it reaches the table, its counts are dominated by the plays and the log. Halving all counts whenever the total passes a limit, so old data fades, brings it down to 4.21, slightly better even than coding each part separately with full memory (4.23 on average), because each part has local variation too. The K−12log2n cost assumes a stationary source; real compressors decay their counts (as here), use per-block models, or mix models of different memory lengths.

3. "Lempel–Ziv approaches the entropy", eventually. Ziv and Lempel's theorem is about the limit of infinitely long inputs. On a source whose entropy is known exactly, independent bytes drawn with the plays' frequencies:

Python
import lzma, math, random, zlib
from collections import Counter
text = open("data/shakespeare.txt", "rb").read()
c = Counter(text)
symbols, weights = list(c), list(c.values())
n = sum(weights)
H = sum(-w / n * math.log2(w / n) for w in weights)
random.seed(77)
source = bytes(random.choices(symbols, weights=weights, k=4_000_000))   # independent bytes with the plays' frequencies
print(f"independent bytes with the plays' frequencies: entropy {H:.4f} bits per byte")
for size in (1_000, 10_000, 100_000, 1_000_000, 4_000_000):
    part = source[:size]
    print(f"first {size:>9,} bytes: zlib {8 * len(zlib.compress(part, 9)) / size:.3f}   lzma {8 * len(lzma.compress(part, preset=9)) / size:.3f} bits per byte")
Text
independent bytes with the plays' frequencies: entropy 4.7794 bits per byte
first     1,000 bytes: zlib 5.376   lzma 6.464 bits per byte
first    10,000 bytes: zlib 5.318   lzma 5.168 bits per byte
first   100,000 bytes: zlib 5.418   lzma 4.947 bits per byte
first 1,000,000 bytes: zlib 5.412   lzma 4.914 bits per byte
first 4,000,000 bytes: zlib 5.411   lzma 4.915 bits per byte

The entropy is 4.78 bits per byte. zlib stays at 5.41 however much data it gets: DEFLATE's window is only 32 KB and its Huffman stage codes literals per block, so it never fully exploits the frequencies. lzma, with a larger window and an adaptive arithmetic coder, gets to 4.91, still above the entropy at 4 MB. For independent data there's no repetition to find, and dictionary methods spend effort looking for matches that aren't there; an order-0 arithmetic coder would reach 4.78 at once. "Universal" is a statement about the limit, and real compressors are tuned for real data, which has repetition and context.

Common misconceptions

Misconception What's actually true Where it's shown
"Long blocks get steadily closer to the entropy." Gains shrink and wobble while tables grow exponentially. What the chapter oversimplifies, point 1
"An adaptive coder should remember everything it has seen." For changing data, forgetting cut 5.10 to 4.21 bits per byte. What the chapter oversimplifies, point 2
"Universal compressors reach the entropy of any data." zlib stayed 13 % above it on 4 MB of independent bytes. What the chapter oversimplifies, point 3
"Real coders use exact probabilities." Zstandard rounds them to a table of size 211 or so, at a measurable cost. Code walkthrough
"Any precision works for an arithmetic coder." Too few bits let rare symbols' slices round to zero, and the coder hangs. Drill D1
"The decoder can tweak the model it receives." Encoder and decoder must use identical probabilities, or the output is garbage. Drill D2
"The last few bits don't matter." Without the final bits, the last symbol came out wrong. Drill D3
"A model trained on a sample covers the data." A byte unseen in the sample has no slice at all. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Entropy rate and the Shannon–McMillan–Breiman theorem. For stationary ergodic sources with memory, −1nlog2p(x1…xn) converges to the entropy rate with probability 1, so typicality and the coding theorem hold with the entropy rate in place of H. Chapter 7 computes entropy rates for Markov sources.
  • Redundancy of universal codes. The K−12log2n learning cost is optimal: Rissanen (1984) proved no universal code can do better for most sources in a parametric family, the basis of the minimum description length principle in statistics.
  • Error exponents. The probability that a sequence isn't typical shrinks exponentially in n, at a rate given by a KL divergence (Sanov's theorem). Chapter 11's divergence measures exactly this kind of "how unlikely is the atypical".

Applying it

Code walkthrough

Zstandard's entropy stage (finite-state entropy, an ANS coder) can't use arbitrary probabilities: its tables need counts that add up to a power of two, 2tableLog. Excerpt from lib/compress/fse_compress.c in Zstandard 1.5.7 (github.com/facebook/zstd, tag v1.5.7):

C
size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
                           const unsigned* count, size_t total,
                           unsigned maxSymbolValue, unsigned useLowProbCount)
{
    ...
    {   static U32 const rtbTable[] = {     0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
        short const lowProbCount = useLowProbCount ? -1 : 1;
        U64 const scale = 62 - tableLog;
        U64 const step = ZSTD_div64((U64)1<<62, (U32)total);   /* <== here, one division ! */
        U64 const vStep = 1ULL<<(scale-20);
        int stillToDistribute = 1<<tableLog;
        ...
        U32 lowThreshold = (U32)(total >> tableLog);

        for (s=0; s<=maxSymbolValue; s++) {
            if (count[s] == total) return 0;   /* rle special case */
            if (count[s] == 0) { normalizedCounter[s]=0; continue; }
            if (count[s] <= lowThreshold) {
                normalizedCounter[s] = lowProbCount;
                stillToDistribute--;
            } else {
                short proba = (short)((count[s]*step) >> scale);
                if (proba<8) {
                    U64 restToBeat = vStep * rtbTable[proba];
                    proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
                }
                if (proba > largestP) { largestP=proba; largest=s; }
                normalizedCounter[s] = proba;
                stillToDistribute -= proba;
        }   }
        ...
        else normalizedCounter[largest] += (short)stillToDistribute;
    }
    ...
}

Each count is scaled to the table (count[s]*step >> scale is ⌊count×2tableLog/total⌋, computed with one division for the whole loop). Three rules from this book are visible. A symbol that never appeared gets 0 and can't be coded: the block's own counts are the model, so every symbol in the block is present. A rare symbol that did appear gets at least 1 slot (or a special "low probability" marker, −1), never 0: chapter 3's never-zero rule. A block of one repeated symbol returns early as a run-length case: chapter 5's one-symbol edge case. Small probabilities are rounded up or down with a tuned threshold table (rtbTable), and whatever is left over goes to the most common symbol. Measured with a Python transcription of the core (without the rounding refinements):

Python
import math
from collections import Counter
def normalize(count, table_log):
    """The core of zstd's FSE_normalizeCount (fse_compress.c, v1.5.7), without its rounding refinements:
    scale counts so they add up to 2^table_log, give every present symbol at least 1, the rest to the largest."""
    total, size = sum(count.values()), 1 << table_log
    low = total >> table_log
    norm, left = {}, size
    for s, c in count.items():
        if c == total:
            return "rle"                                   # one symbol fills the block: run-length special case
        p = 1 if c <= low else (c * size) // total
        norm[s] = p
        left -= p
    largest = max(norm, key=norm.get)
    norm[largest] += left
    return norm
count = Counter(open("data/shakespeare.txt", "rb").read())
n = sum(count.values())
H = sum(-c / n * math.log2(c / n) for c in count.values())
print(f"order-0 entropy of the plays: {H:.4f} bits per byte")
for log in (7, 8, 9, 11, 12):
    norm = normalize(count, log)
    cost = sum(-c / n * math.log2(norm[s] / (1 << log)) for s, c in count.items())
    print(f"table of 2^{log:<2} = {1 << log:>4}: smallest probability {min(norm.values())}/{1 << log}; cost {cost:.4f} bits per byte (+{cost - H:.4f})")
print("one symbol only:", normalize(Counter(b"aaaa"), 7))
Text
order-0 entropy of the plays: 4.7794 bits per byte
table of 2^7  =  128: smallest probability 1/128; cost 5.1205 bits per byte (+0.3412)
table of 2^8  =  256: smallest probability 1/256; cost 4.8538 bits per byte (+0.0745)
table of 2^9  =  512: smallest probability 1/512; cost 4.8077 bits per byte (+0.0283)
table of 2^11 = 2048: smallest probability 1/2048; cost 4.7832 bits per byte (+0.0039)
table of 2^12 = 4096: smallest probability 1/4096; cost 4.7809 bits per byte (+0.0016)
one symbol only: rle

Rounding the plays' byte probabilities to a table of 128 costs 0.34 bits per byte above the entropy; 512 costs 0.028, and 2,048 (close to Zstandard's usual table sizes) costs 0.004. Every coder that uses integer arithmetic makes this trade: bigger tables cost memory and cache, smaller ones cost compression, and the loss is a small cross-entropy penalty (chapter 11) from coding with slightly wrong probabilities.

Read it yourself

Using the code above: what happens to a symbol that appears once in a block of 100,000 bytes with tableLog 11? What does normalizedCounter get, and what fraction of the table does it claim compared with its real share? Why does the function give the leftover slots to the largest symbol rather than spreading them?

Debugging drills

D1. A coder that never finishes

To save memory on a small device, a developer changes the chapter's arithmetic coder from 32-bit to 16-bit ranges. It works on short test files, then hangs on a 300 kB file.

Python
import signal
from collections import Counter
import ac16                                   # the chapter's coder with 16-bit ranges instead of 32-bit
text = open("data/shakespeare.txt", "rb").read()[:300_000]
counts = Counter(text)
print("symbols:", len(counts), "| total count:", f"{sum(counts.values()):,}", "| range: 16 bits")
def give_up(*_):
    raise TimeoutError("no answer after 10 seconds")
signal.signal(signal.SIGALRM, give_up)
signal.alarm(10)
try:
    code = ac16.encode(text, counts)
    print("encoded:", len(code), "bits")
except TimeoutError as e:
    print("encode:", e)
Text
symbols: 62 | total count: 300,000 | range: 16 bits
encode: no answer after 10 seconds

D2. A decoder that "improves" the model

A decoder adds 1 to every count it receives, to be safe against zeros. Every file decodes to garbage.

Python
from collections import Counter
from ac import encode, decode
text = open("data/shakespeare.txt", "rb").read()[:2000]
enc_counts = Counter(text)
code = encode(text, enc_counts)
dec_counts = {b: c + 1 for b, c in enc_counts.items()}      # the decoder smooths the counts it was sent
back = bytes(decode(code, dec_counts, len(text)))
print(repr(text[:40]))
print(repr(back[:40]))
Text
b'First Citizen:\nBefore we proceed any fur'
b"Feth smsefya eoao: or!It ;oire a'l:\nlrN "

D3. The last letter changes

A coder that skips the final bits produces files two bits shorter, and the last letter of "to be, or not to be, that is the question" decodes as "i".

Python
from collections import Counter
import ac, ac_noflush
text = b"to be, or not to be, that is the question"
c = Counter(text)
for name, mod in (("with the final bits", ac), ("without them", ac_noflush)):
    code = mod.encode(text, c)
    print(f"{name:<20} {len(code):>3} bits -> {bytes(mod.decode(code, c, len(text)))!r}")
Text
with the final bits  141 bits -> b'to be, or not to be, that is the question'
without them         139 bits -> b'to be, or not to be, that is the questioi'

D4. A shared model that misses a letter

Two services agree a model in advance: the byte counts of a 100 kB sample. Coding the rest of the plays fails on a capital Z.

Python
from collections import Counter
from ac import encode
text = open("data/shakespeare.txt", "rb").read()
model = Counter(text[:100_000])                       # counts from a sample, shared with the decoder in advance
try:
    encode(text[100_000:], model)
except KeyError as e:
    print("KeyError:", e, "=", bytes([e.args[0]]))
Text
KeyError: 90 = b'Z'

Career-oriented

Interview prep

Mid level

Q1. What does Shannon's source coding theorem say, and why can't any compressor shrink all files?

How to get there. Entropy as the limit; the counting argument.

Q2. How does arithmetic coding work, and why is it better than Huffman for skewed data?

How to get there. Interval narrowing, cost per symbol.

Senior level

Q3. You're choosing an entropy coder for a new binary format: Huffman, arithmetic coding or ANS. What do you consider?

How to get there. Compression, speed, adaptivity, robustness.

Q4. Why does adding a pre-trained dictionary help compress small messages, and what are the risks?

How to get there. Learning cost per message; shared models.

Staff level

Q5. Leadership asks why the storage team's compression ratio hasn't improved in two years despite trying faster and newer compressors. How do you explain the limit, and where would gains come from?

How to get there. Entropy of the model, not the coder.

Q6. A team proposes encrypting data before compressing it, "for security". What do you say?

How to get there. What encryption does to the data's statistics.