Universal Source Coding
Coding when the source distribution is unknown; redundancy as relative entropy; minimax redundancy equals the capacity of the channel from parameter to source (Gallager–Ryabko); universal codes for binary sequences via two-stage descriptions and Bayesian mixtures, the Laplace and Krichevsky–Trofimov estimators; arithmetic coding and the probability integral transform; the sliding-window (LZ77) and tree-structured (LZ78) Lempel–Ziv algorithms; Kac's recurrence lemma, an Elias-style integer code, and the optimality of LZ77; the distinct-parsing phrase bound, Ziv's inequality, and the optimality of LZ78
Motivation: the telecom doesn’t know who is typing
Every compression result so far assumed the engineer knows the source distribution . Huffman needs to merge the two least likely symbols. Shannon–Fano–Elias needs to build the CDF. The wrong-code theorem showed that guessing instead of costs bits per symbol.
On a real telegraph line the company serves thousands of operators, in different languages, on different topics, and it cannot interview each one before the message arrives. There are three escalating versions of this ignorance:
| What the engineer knows | Approach | Section |
|---|---|---|
| The source is one of a known family , unknown | A single code that is good for every member: minimax redundancy | Universal codes and channel capacity |
| Nothing, but the data can be read once, in order | Learn the distribution on the fly and feed the estimate to an arithmetic coder | Universal coding for binary sequences, Arithmetic coding |
| No distribution at all, just an individual sequence (a book, a song) | Adaptive dictionaries: Lempel–Ziv | Lempel–Ziv coding |
IntuitionWhy “two passes” isn’t the answer
One fix is to read the whole message, estimate , build a Huffman code, then go back and encode, sending the code table too. This works for small files but fails for a live line: the operator is still typing when the first pulses must leave. We want one-pass (online) coders that learn as they go, and still converge to the entropy.
WarningIndividual-sequence compression needs a benchmark
“Compress this particular sequence as well as possible” is meaningless without restricting the class of compressors. For any sequence there is a function that maps that sequence to one bit and leaves every other one alone. It is perfectly overfitted. So for individual sequences we compare against benchmarks such as the best Bernoulli or -th-order Markov code chosen in hindsight. The ultimate benchmark, Kolmogorov complexity, comes in Chapter 14.
Universal codes and channel capacity
Setup. is drawn from one of distributions , , and we don’t know which. Throughout this section we ignore the integer constraint on codeword lengths, which costs at most one bit (Shannon codes).
If were known, lengths would give the best possible expected length:
DefinitionRedundancy
A code with lengths implicitly assumes the distribution . Its redundancy against source is the excess over the ideal:
| Component | Detail |
|---|---|
| Signature | |
| Domain | The true source and the coding distribution the codebook was built for. |
| Codomain | Extra bits per symbol paid for not knowing . |
DefinitionMinimax redundancy
The worst-case redundancy of the best single code:
IntuitionThe center of an information ball
Picture the distributions as points. asks for the point whose farthest source is as close as possible, measured in relative entropy. It is the center of the smallest “relative entropy ball” enclosing every candidate source, and is that ball’s radius (the information radius of the family).
flowchart LR P1["p_1"] --- Q["q*: center of the ball"] P2["p_2"] --- Q PM["p_m"] --- Q
The channel from parameter to source
To find , view the unknown parameter as the input of a channel and the source symbol as its output. Row of the transition matrix is :
flowchart LR T["theta: which source"] -->|"row theta of the matrix is p_theta"| X["X: source symbol"]
An input distribution induces the output distribution , and the channel’s capacity is
NoteChannel capacity
Capacity is the subject of Chapter 7 (see channel-capacity). For this note only the definition is needed.
TheoremMinimax redundancy is capacity (Gallager; Ryabko)
The capacity of the channel with rows is
The minimizing is the output distribution induced by the capacity-achieving input distribution : .
ProofA centroid identity, then the minimax theorem
Write for , , and .
Step 1: Mutual information is an average distance to the centroid.
Step 2: Replace the centroid by any . Insert in the log and split:
In the second sum, , so it equals . Hence
Step 3: The centroid is the closest point on average. Since , with equality iff ,
So .
Step 4: Swap max and min. The objective is convex in (convexity of relative entropy) and linear, hence concave, in . Both range over compact convex sets (probability simplices). The minimax theorem of game theory says that for such , . So
Step 5: The inner maximum puts all weight on the worst source. A linear function of over the simplex is maximized at a vertex, so . Hence , and the saddle point gives .
∎
IntuitionThe parallel-axis theorem of information
Step 2 is the information-theoretic version of the parallel-axis theorem in mechanics: the average squared distance to any point equals the average distance to the centroid plus the distance from the centroid to that point. Here “squared distance” is relative entropy and the centroid is the mixture .
ImportantThe price of not knowing is a capacity
The cost of universality is the number of bits per symbol the source symbol reveals about which source produced it. If the candidate sources are very different, identifies easily, the channel has high capacity, and a single code must pay a lot. If they are similar, the channel is noisy and universality is cheap.
ExampleTwo sources that look like an erasure channel
and
The best universal coding distribution is the midpoint , with
Seen as a channel, symbol 2 is an “erasure” (it says nothing about ), and symbols 1 and 3 reveal exactly. This is the binary erasure channel, with capacity at uniform input, whose output distribution is exactly . Not knowing the source costs bits per symbol above the entropy.
RemarkRedundancy is the gambler’s lost doubling rate
In the horse-race picture, a gambler betting when the truth is loses doublings per race. The minimax code is the bet that guarantees the smallest worst-case loss over every horse race in the family.
Universal coding for binary sequences
The problem. Encode a binary string with no probabilistic assumption at all. The benchmark is hindsight: if the string has ones, the Bernoulli() Shannon code would spend bits. How close can a code that doesn’t know in advance get?
LemmaBinomial coefficient bounds (Wozencraft–Reiffen)
For ,
(Proved as Lemma 17.5.1 in the book.)
Two-stage description (offline)
AlgorithmCount, then index
After reading the whole string:
- Send , using bits.
- Send the index of among the strings with ones, using bits.
TheoremTwo-stage length
DerivationPlug in the upper binomial bound
Use and
since . Add the pieces: the from the count and the from the index leave .
IntuitionHalf a log per parameter
The overhead over the hindsight-optimal is about bits for the whole string, so per symbol. Describing one real parameter () to the precision the data can actually support costs about bits.
WarningThe bound blows up at or
The last term is unbounded there. The actual length is then about bits, while , so the redundancy is rather than .
Mixture coding (online)
The problem. The two-stage code must see all of before sending anything. We want the same performance in one pass.
DefinitionUniform (Bayes) mixture of Bernoulli sources
Pretend the bias was drawn uniformly from . A specific sequence with ones then has probability
TheoremClosed form of the mixture
ProofIntegration by parts gives a recursion
Step 1: Integrate by parts with , . The boundary term vanishes (for ), leaving
Step 2: Base case. .
Step 3: Check the closed form satisfies the recursion. , so . ✓
∎
IntuitionThe mixture is the two-stage code
is the uniform probability of the count , and is the uniform probability of the index among strings with that count. So
exactly the two-stage length without the ceilings. The mixture achieves the same redundancy for every sequence, and it can be run online.
TheoremMixture code length
For every with ,
The Laplace estimator
TheoremSequential form of the mixture
Let be the number of ones among the first symbols. Then
ProofRatio of two mixture probabilities
and , which leaves .
∎
IntuitionAdd one imaginary success and one imaginary failure
This is Laplace’s rule of succession (see conditional-probability-and-independence): the Bayesian posterior mean of under a uniform prior. It never predicts probability 0, so it never pays the infinite penalty of an “impossible” symbol. Feeding it to an arithmetic coder (Arithmetic coding) achieves sequentially, with finite-precision arithmetic.
ImportantHorizon-free
The predictor doesn’t depend on . The coder needn’t know how long the message will be, which is exactly what a live telegraph line requires.
The Krichevsky–Trofimov estimator
WarningThe uniform prior underweights the extremes
At or , , so the redundancy is , not . A uniform prior puts too little mass on near 0 and 1.
DefinitionDirichlet mixture
Weight by the Beta density , which piles up near 0 and 1:
TheoremUniformly bounded redundancy
For all , including and ,
and the sequential predictor is
NoteProof deferred
The book says the bound “can be shown” and analyzes the mixture in detail with universal portfolios (§16.7). The predictor adds half an imaginary success and half an imaginary failure, which is enough probability for all-zeros and all-ones strings.
| Estimator | Prior on | Next-symbol probability | Worst-case redundancy |
|---|---|---|---|
| Laplace | Uniform | (at ) | |
| Krichevsky–Trofimov | Beta | uniformly |
Arithmetic coding
The problem. Huffman codes have integer codeword lengths, which can waste up to one bit per symbol. Coding blocks of symbols dilutes this to , but the codebook grows exponentially in . We want a code whose lengths are effectively fractional, that works incrementally symbol by symbol, and that can use a distribution learned on the fly (such as Laplace or KT).
The probability integral transform
Lemma is uniform
If has a continuous distribution function , then is uniform on .
ProofInvert the CDF
, and for ,
∎
NoteOn
The proof as written assumes is strictly increasing so that exists. For a continuous but flat-in-places the result still holds, using the generalized inverse.
From sequences to numbers. Put “0.” in front of a sequence over an alphabet of size and read it as a base- real number . Its CDF is
ImportantCompression as “uniformizing”
If the distribution on infinite sequences has no atoms, then is uniform on , so its binary digits are i.i.d. fair bits. They are incompressible, and they determine the source sequence. The probability transform is a perfect compressor: it turns any atomless source into fair coin flips, the reverse of generation.
FormulaCDF of a binary sequence
For any binary process,
Each one in the sequence adds the probability of the branch where that position was a zero instead.
ExampleBernoulli, sequence 110101
With :
Each term reuses the prefix probability computed for the previous one, so the work is linear in .
From intervals to codewords
IntuitionA sequence is a subinterval
The prefix corresponds to all infinite sequences starting with it. Under the probability transform, that set becomes an interval of length exactly . Any number in the interval identifies (given ). Shannon–Fano–Elias coding picks one with about bits.
AlgorithmArithmetic coding
- Start with the interval .
- For each new symbol, shrink the current interval to the sub-piece for that symbol, in proportion to its conditional probability given the past.
- Whenever the top and bottom of the interval agree in their leading bits, those bits can no longer change. Output them, and rescale the interval to keep the arithmetic at fixed precision.
- At the end, send enough bits to pin down a point inside the final interval.
The decoder runs the same subdivision and reads symbols off as the transmitted bits narrow down the interval. (Bell, Cleary and Witten give the fixed-precision details.)
ExampleTernary source, sequence ACAA
, , , so the symbol pieces are , , .
| After | Interval | Width |
|---|---|---|
| — | 1 | |
A | 0.4 | |
AC | 0.08 | |
ACA | 0.032 | |
ACAA | 0.0128 |
The final width is . Encode the midpoint with bits.
TheoremArithmetic coding length
For any and any (possibly learned) distribution on sequences, arithmetic coding encodes in at most bits. With for an i.i.d. source, the expected length is within 2 bits of for the whole block.
RemarkNot optimal for a fixed block, but incremental
For any fixed , a Huffman code on -blocks could do slightly better on average. But arithmetic coding needs no codebook, extends to any block length, and lets change with every symbol. Combined with the Laplace or KT predictor, it gives a universal one-pass coder for binary sources.
Lempel–Ziv coding
IntuitionTelegraph codebooks were dictionary compression
When telegrams were charged per word, large companies printed private codebooks that mapped frequent phrases to short code words. Indian greetings telegrams worked the same way: “25” meant Merry Christmas, and “26” meant May Heaven’s choicest blessings be showered on the newly married couple. The sender paid for a number; the destination office printed the sentence. These dictionaries were fixed and agreed in advance.
Ziv and Lempel’s idea (1977, 1978) was an adaptive dictionary that both ends build from the message itself as it passes. A phrase that has already appeared is replaced by a pointer to where it appeared. Nothing about the source distribution is needed.
| Version | Also called | Dictionary | Used in |
|---|---|---|---|
| LZ77 | sliding-window LZ, LZ1 | Every substring in a window of past symbols | gzip, pkzip |
| LZ78 | tree-structured LZ, LZ2 | The phrases parsed so far, arranged as a tree | Unix compress, modems, GIF (via LZW) |
Sliding-window Lempel–Ziv (LZ77)
DefinitionParsing
A parsing of divides the string into phrases separated by commas.
AlgorithmLZ77 (Storer–Szymanski variant), window
Suppose everything up to time has been encoded.
- Find the largest such that, for some with , the length- string starting at equals the length- string starting at .
- If a match exists, emit : a flag, the match’s position (counted back from the end of the window), and its length .
- Otherwise emit , the raw character .
- Advance by the phrase length and repeat.
WarningMatches may overlap the phrase being encoded
The match must start in the window but may run past it into the new
phrase. Copying from just behind the cursor reproduces runs: in the example
below, ABBABB is copied from a match three symbols back. In theory such a
match is unbounded; in practice the maximum phrase length is capped.
Example, string ABBABBABBBAABABA
Parsing: A, B, B, ABBABB, BA, A, BA, BA
Pointers: (0,A), (0,B), (1,1,1), (1,3,6), (1,4,2), (1,1,1), (1,3,2), (1,2,2)
The fourth phrase copies 6 symbols from a match starting 3 back, a self-overlapping copy. Encoding a one-symbol match as can cost more than sending the raw character; practical coders send short matches raw (Problem 13.8).
IntuitionThe dictionary is the recent past
The implicit dictionary is every substring of the last symbols plus all single characters. Each step sends a pointer to the longest dictionary entry that matches what comes next. Frequent strings are likely to be found recently and long, so they cost little.
Tree-structured Lempel–Ziv (LZ78)
AlgorithmLZ78 incremental parsing
Repeatedly cut off the shortest phrase not seen before. Since it is the shortest new phrase, all its prefixes have already appeared, in particular the phrase minus its last symbol. Encode each phrase as (index of that prefix phrase, last symbol), with index 0 for the empty prefix.
ExampleString ABBABBABBBAABABAA…
| # | Phrase | Prefix phrase | Code |
|---|---|---|---|
| 1 | A | empty | (0, A) |
| 2 | B | empty | (0, B) |
| 3 | BA | 2 (B) | (2, A) |
| 4 | BB | 2 (B) | (2, B) |
| 5 | AB | 1 (A) | (1, B) |
| 6 | BBA | 4 (BB) | (4, A) |
| 7 | ABA | 5 (AB) | (5, A) |
| 8 | BAA | 3 (BA) | (3, A) |
flowchart TD
R(("root")) -->|A| P1["1: A"]
R -->|B| P2["2: B"]
P1 -->|B| P5["5: AB"]
P5 -->|A| P7["7: ABA"]
P2 -->|A| P3["3: BA"]
P2 -->|B| P4["4: BB"]
P3 -->|A| P8["8: BAA"]
P4 -->|A| P6["6: BBA"]
RemarkLZW
Sending a raw character with every phrase wastes bits. Welch’s variant treats
the last character of each phrase as the first character of the next, so
each phrase is sent as a single index. LZW is the basis of Unix compress,
modem compression, and GIF.
Optimality of Lempel–Ziv algorithms
Both versions are universal: for any stationary ergodic source, their compression rate converges to the entropy rate , though they never estimate the source distribution. The two proofs work very differently.
| LZ77 | LZ78 | |
|---|---|---|
| Key idea | Frequent strings recur soon, so pointers are short | A string with many distinct phrases can’t be very probable |
| Key lemma | Kac’s recurrence lemma | Ziv’s inequality |
| Proved here | A simplified “infinite past” version | The actual algorithm |
LZ77 via recurrence times
The simplified algorithm. Assume a stationary ergodic process , and that encoder and decoder both see the infinite past. To send the block , send only how far back it last occurred:
The decoder looks back symbols and copies. The cost is the cost of describing the integer .
LemmaA prefix code for the positive integers
There is a prefix-free code for the integers in which has length .
ProofSend the length of the length
Step 1: A crude code. = zeros, then in binary. The binary form of starts with a 1, so the decoder counts zeros, learns how many digits follow, and reads them. Length . It’s prefix-free, but the unary length prefix doubles the cost.
Step 2: Encode the length with , not in unary. Send the number of binary digits of using , which costs about bits, then send in binary, about bits. The total is less than .
∎
IntuitionWhy the overhead must grow at all
With no upper limit on known in advance, the receiver must be told where the number ends. The term is the price of that punctuation, negligible next to .
LemmaKac’s lemma
Let be stationary ergodic on a countable alphabet, and . Let
be the conditional probability that the most recent earlier occurrence of was steps back. Then
IntuitionWaiting time is reciprocal frequency
For an i.i.d. process the look-back time is geometric with parameter , with mean . Kac says the same holds for any stationary ergodic process. The heuristic: in a sample of length , appears about times, so the average gap between appearances is .
ProofDecompose by the last occurrence before 0 and the first at or after 0
Step 1: A partition. For , let
“the last before time 0 is at , and the first at or after time 0 is at ”. These events are disjoint. By ergodicity, occurs both before and after 0 almost surely, so .
Step 2: Add up.
Step 3: Stationarity. Shift time by : the conditional probability is a gap of ending at an occurrence of , i.e. , and . So
Step 4: Count pairs. For each there are exactly pairs with , , . So .
∎
RemarkAn amusing consequence
Averaging over the symbol, , the number of symbols with positive probability, regardless of the distribution.
CorollaryRecurrence of blocks
Apply Kac to the block process , which is also stationary ergodic:
TheoremRecurrence-time coding achieves the entropy rate
Let be the description length of . Then
ProofLower bound from source coding, upper bound from Jensen and Kac
Lower bound. This is a prefix code for the block, so (for a stationary source the block average of entropies is at least the rate).
Step 1: Main term. Condition on the block, then apply Jensen (log is concave) and Kac:
Step 2: The term vanishes. By Jensen again and Step 1,
For large , , so this is at most .
∎
IntuitionPoint to the past instead of describing the present
A typical block has probability about , so by Kac it last occurred about steps ago. Writing down that distance takes about bits. Matching the past is as good as knowing the distribution.
WarningNot a practical algorithm
With entropy rate and a 200-bit block, you’d look back on average bits. The practical finite-window LZ77 is also asymptotically optimal by similar ideas (Wyner–Ziv), but the book doesn’t give that proof. Ziv and Lempel’s original paper showed the finite-window version beats any finite-state compressor on every individual sequence.
LZ78 via distinct parsings
LZ78 emits pairs (pointer, last bit), each pointer using bits, so its length is
We show at most.
DefinitionDistinct parsing
A parsing is distinct if no two phrases are identical. For example,
0,111,1 is a distinct parsing of 01111; 0,11,11 is not. LZ78 always
produces a distinct parsing.
IntuitionThe two ingredients
- Not many phrases. There are only binary strings of length , so a distinct parsing can’t have too many short phrases. The count is at most about .
- Many distinct phrases means low probability. For an i.i.d. source on , (maximized when all four are equal). can reach , and can reach 1. A sequence built from many distinct pieces can’t be very likely. Ziv’s inequality extends this to phrases and Markov sources.
So strings with few phrases compress well (and may be likely), and strings with many phrases compress badly but must be unlikely. On average, the two balance at the entropy rate.
LemmaFew phrases in a distinct parsing (Lempel–Ziv)
The number of phrases in any distinct parsing of a binary string of length satisfies
ProofUse the shortest phrases possible
Step 1: Total length of all strings up to length .
Step 2: The count is largest when phrases are short. If , the most phrases come from using every string of length once:
Step 3: In between. For , write . The extra symbols form at most phrases of length , so
Step 4: Relate to . From , . From , , which for gives
Substitute into Step 3.
∎
LemmaGeometric maximizes entropy at fixed mean
A nonnegative integer random variable with mean has
ProofRelative entropy to the geometric
The book cites the maximum entropy theorem (Theorem 12.1.1). A direct argument: let with , the geometric with mean . Then , so
∎
Markov approximations. Let be a binary stationary ergodic process with law . For fixed , its -th-order Markov approximation is
with the initial state part of the specification. By the ergodic theorem,
and as (monotone conditional entropies).
Bookkeeping. Parse into distinct phrases . Let be the bits just before phrase (its state), and let count the phrases of length with preceding state . Then
LemmaZiv’s inequality
For any distinct parsing of ,
The right side doesn’t depend on at all.
ProofGroup phrases by (length, state), then Jensen
Step 1: Factor by phrases. By the Markov property, , so
Step 2: Jensen within each group. Write each inner sum as times an average, and use concavity of :
Step 3: Distinctness caps the inner sum. Within a group, the phrases are distinct strings of the same length , all conditioned on the same state . They are disjoint outcomes of one conditional distribution, so . Hence each group contributes at most .
∎
IntuitionProbability bounded by pure combinatorics
The left side is a probability under the source. The right side depends only on how the string happened to parse. Distinctness is the whole engine: different strings competing for at most one unit of probability can’t each get more than about .
TheoremPhrase count is controlled by the entropy rate
For a binary stationary ergodic process, with probability 1,
ProofTurn Ziv’s inequality into an entropy of phrase statistics
Step 1: Normalize the counts. With ,
where has , and . Ziv’s inequality becomes
Step 2: Bound . . The state is bits, so . By the geometric lemma with ,
so .
Step 3: Every correction term vanishes. By the phrase-count lemma, . Since as , . So .
Step 4: Ergodic limit, then . With probability 1,
This holds for every , and the right side tends to .
∎
TheoremLZ78 is asymptotically optimal
For a binary stationary ergodic process,
ProofAdd the last-bit term
. The first term has by the theorem above, and by the phrase-count lemma.
∎
RemarkWhat the proof didn’t use
The phrase-count bound and Ziv’s inequality hold for any distinct parsing, not just LZ78’s incremental one. The argument extends to many parsing variants, including multiple context-dependent trees. And the code never looked at : it is a universal code that reaches the entropy rate of whatever stationary ergodic source happens to be on the line.
Quick reference
| Object | Statement | Reads as |
|---|---|---|
| Redundancy | Extra bits for coding with . | |
| Minimax redundancy | Radius of the smallest information ball. | |
| Gallager–Ryabko | ; | The price of not knowing is a channel capacity. |
| Centroid identity | Parallel-axis theorem for relative entropy. | |
| Erasure example | Midpoint distribution is the universal code. | |
| Two-stage / mixture | Half a log per parameter. | |
| Uniform mixture | Count, then index. | |
| Laplace | One pseudo-success, one pseudo-failure. | |
| KT | ; uniform | Fixes the all-zeros/all-ones case. |
| Probability transform | uniform | Optimal compression produces fair bits. |
| Binary CDF | Computed incrementally. | |
| Arithmetic coding | bits | Shrinking intervals, any , one pass. |
| LZ77 | pointer into a window | gzip. |
| LZ78 | (prefix index, last symbol) | compress, GIF. |
| Integer code | Send the length of the length. | |
| Kac | Waiting time is reciprocal frequency. | |
| LZ77 (infinite past) | Point to where it last occurred. | |
| Phrase count | Few distinct short strings. | |
| Ziv’s inequality | Many distinct phrases means low probability. | |
| LZ78 | a.s. | Universal. |
Facts to keep to hand
- Every universal-coding cost is a relative entropy. Coding with against source costs . The best single for a family is the centroid of the capacity-achieving mixture, and its worst-case cost is the capacity of the channel from parameter to symbol.
- Mixtures learn. A Bayesian mixture over the family is a predictor (Laplace, KT), and an arithmetic coder turns any predictor into a code of length . Learning the parameter costs about bits in total.
- Arithmetic coding separates modelling from coding. The coder is fixed; all the intelligence is in . The same split appears in the gambler-twin compressor.
- Lempel–Ziv needs no model at all. LZ77 works because recent strings recur after about steps (Kac); LZ78 because distinct phrases can’t all be likely (Ziv). Both reach the entropy rate of any stationary ergodic source.
- Asymptotic optimality is not finite- optimality. Overheads such as , and vanish only per symbol and slowly. The idealized infinite-past LZ77 is wildly impractical.
References
- Cover & Thomas, Elements of Information Theory — Chapter 13