Source Coding and Compression

On this page

The first two articles turned uncertainty into information. Now we ask: how do potentially fractional information costs become a binary file that can be decoded exactly?

We will allocate code space, derive the entropy bound, encode a whole message, and examine long sequences. All logarithms are base 2. Unless stated otherwise, the alphabet is finite, the probability model is known, and the cost of transmitting that model is excluded.

Prefix codes: how much space does a codeword occupy?

Binary codewords must remain distinguishable when concatenated. In a prefix code, no codeword is a prefix of another. For example, , , , can be decoded as soon as each codeword ends, without separators.

Imagine all infinite binary strings as a branching tree. Prefix 0 covers half of them; 10 covers one quarter. Each additional specified bit halves the occupied space. A codeword of length therefore occupies a fraction . Prefix-free regions cannot overlap, so:

This is Kraft’s inequality. For given integer lengths, it is also sufficient for a binary prefix code to exist. It guarantees that a code can be constructed, not that arbitrary codewords with those lengths will be prefix-free.

Preparing the visual
Lengths allocate space; Kraft limits total capacity

Compare three length assignments: spare capacity, full capacity, and overflow. Every block has width 2 to the negative codeword length. The dashed line marks capacity 1; feasible states also show actual prefix codewords.

The diagram packs shorter codewords first. A length- codeword can also represent a dyadic interval . Aligning these intervals to the binary grid without overlap constructs a prefix code. When occupancy is below 1, capacity remains unused. Code lengths are not unconditionally zero-sum: a codeword can be shortened without changing others if enough spare capacity remains; otherwise, space must be freed elsewhere.

Why does entropy bound average code length?

For a uniquely decodable binary symbol code, let . The Kraft–McMillan inequality still gives . Normalize the code-space allocations into a distribution:

Then . The cross-entropy and KL identity from the previous article separates the gap into two nonnegative terms:

The first term measures mismatch between and the normalized allocation . The second reflects unused code space: implies . This explains the average lower bound. The code must satisfy the decoding assumptions; an arbitrary one-to-one file mapping cannot be treated the same way while ignoring externally supplied lengths or boundaries.

For positive-probability symbols, choosing yields a Shannon prefix code with:

For blocks of independent, identically distributed symbols, gives:

Every block still has an integer code length. Rounding overhead per original symbol becomes smaller. This expected-length result follows directly from block coding, without first invoking a typical set.

A fair die: why 2.667 questions for 2.585 bits?

A yes/no strategy forms a binary decision tree, with a root-to-leaf path for each prefix codeword. A fair die has entropy bits. An optimal tree has two leaves at depth 2 and four at depth 3:

The worst case still needs 3 questions. Entropy, average questions, and worst-case questions measure different things. Coding independent outcomes in blocks spreads the integer-length overhead over multiple symbols.

Huffman: read the codewords directly from the tree

Huffman coding repeatedly merges the two currently least probable nodes. Label each pair of branches 0 and 1; the path from root to leaf gives the codeword. For specified symbol probabilities, it minimizes expected length among binary prefix codes. Ties can produce different, equally optimal trees.

0 1 0 1 0 1 A B C D

Read the branch bits along each path: , , , . Shallower leaves have shorter codewords.

Here , so:

Every positive probability has the form , so code length equals self-information and bits.

In general, Huffman guarantees average redundancy bit per symbol. It does not guarantee that each individual length differs from its self-information by less than one bit. For two outcomes with probabilities , a symbol-by-symbol Huffman code still assigns one bit to each outcome, while entropy is approximately 0.469 bits.

Block Huffman coding narrows this gap, but its codebook grows rapidly with block length. Arithmetic coding represents the whole message differently.

Arithmetic coding: multiply probabilities, add information

Start with and subdivide it according to the model probabilities. Keep the part corresponding to the next symbol, then subdivide that part again. If the current interval is and the symbol occupies cumulative probability range , the next interval is:

Its width is multiplied by the symbol’s model probability. With conditional probabilities, a message produces:

Below, the message is fixed as ABA. Only changes, with at every position. All three stages remain visible on the same scale.

Preparing the visual
Turn a message into a narrowing interval

Keep ABA fixed and vary the model probability of A. Three stages share a 0–1 scale: widths multiply while negative logarithms add. A complete dyadic cell inside the final interval supplies an actual integer-length bitstring.

At , the intervals are , , and . Final width is , giving about bits of ideal information.

To emit actual bits, one clear termination method selects a complete dyadic cell inside the final interval and sends its -bit prefix. For example, 011 represents , entirely inside the ABA interval. A decoder using the same subdivisions can identify the message. This example also assumes a known length of 3; a real format needs a shared length or termination rule.

Arithmetic coding still emits an integer number of bits. It accumulates information across symbols and pays a finite termination overhead for the whole message. With ideal precision and known block length, this construction can achieve . Finite-precision implementations also account for renormalization, quantized probabilities, and headers. See the Stanford arithmetic coding notes.

Entropy rate: what remains uncertain after using context?

Independent symbols have joint entropy . With dependence, start from the chain rule:

When the limit exists, the entropy rate is:

For a stationary source on a finite alphabet, this limit exists and equals the limiting conditional entropy with increasingly long histories. The sample-path AEP below generally also requires ergodicity.

For a concrete example, start with a fair bit . At each later position, independently flip the previous bit with probability , or retain it with probability . Every marginal remains fair, with entropy 1 bit. Given the previous bit, uncertainty is only :

At , the rate is approximately 0.469 bits per symbol. Compression can exploit this contextual redundancy even though single-symbol marginal frequencies remain uniform.

Give the same sequence to two predictors

Both fixed samples have the same total zero/one frequencies. The independent model always assigns probability to the next bit. With the previous bit known, the context model assigns to staying and to flipping. Change and reveal bits to compare cumulative ideal lengths.

Preparing the visual
Half zeros, half ones. Why different code lengths?

Reveal two balanced fixed samples bit by bit. Compare cumulative ideal lengths from a fair independent model and a Markov model with flip probability r, whose entropy rate is h₂(r).

With flips among the first bits, the context model assigns

The first bit costs 1 bit. Every later stay or flip costs its conditional self-information. At , every step costs 1 bit. At , stays are cheap and unexpected flips expensive. Context does not shorten every message: a sample with frequent flips can cost more under a model that considers flips rare. Averaging over that source model, rather than one fixed sample, gives .

AEP: how can a small set carry most of the probability?

For an IID source, average sequence information is an average of IID random variables. The law of large numbers yields the asymptotic equipartition property (AEP):

For fixed tolerance , the typical set consists of sequences whose average information is within . Its total probability tends to 1, while each typical sequence satisfies:

Distinguish two fractions: the fraction of all possible sequences, and the probability of sampling one under the source distribution. The following example fixes and , using exact binomial probabilities rather than random simulation.

Preparing the visual
Few sequences can carry most of the probability

Fix P(1)=0.2 and tolerance 0.12 bits, then vary sequence length. The histogram shows average-information probabilities; blue marks typical sequences. Below, compare source probability with the fraction of all binary sequences.

A particular sequence with ones has probability . There are such sequences. Their combined probability is therefore , whereas counting them adds only . This explains why the two fractions differ so much.

If typical-set probability is at least , the bounds on individual probabilities imply:

“About sequences” describes an exponential-rate approximation, not an exact count at finite . With a fixed tolerance, coverage need not increase monotonically at every successive block length. For a uniform source, all sequences can be typical; a tiny fraction of all sequences is a feature of this nonuniform example, not a universal AEP requirement.

Indexing typical sequences explains asymptotic fixed-rate coding with small error probability. Strictly lossless compression must also recover atypical sequences, for example with an escape flag and a fallback code; they cannot simply be discarded. See the Stanford AEP notes.

A language model supplies probabilities; an entropy coder emits bits

A language model provides . An entropy coder, such as arithmetic coding, turns those probabilities into a reversible bitstream. Ideal rate on a particular sample is:

This is empirical negative log-likelihood; taking expectation under the true source gives the corresponding cross-entropy. Loss computed with natural logarithms must be divided by to obtain bits. With consistent units and data representation, lower prediction loss usually means lower ideal coding cost. The average entropy bound does not require every individual message to exceed the source’s average entropy.

A real compressor must also account for the model, vocabulary, length or end marker, headers, and numerical precision. Both ends must reproduce identical probabilities. The ideal relationship becomes more representative when model cost can be amortized over enough data. Language Modeling Is Compression studies this connection and compression with language models.

BPE shortens token sequences by merging common adjacent symbols, while also changing vocabulary, probabilities, and modeling difficulty. Across tokenizers, compare a common unit such as bits per byte. Fewer tokens or lower per-token loss alone does not establish better text compression. See Tokens and Sampling.

MethodHow length is allocatedMain constraint
Symbol-by-symbol HuffmanAn integer codeword for each symbolAverage redundancy below 1 bit per symbol; blocks can reduce it further
Arithmetic / range codingAccumulate message probability through interval subdivisionFinal bit length remains integer; model, precision, and termination must agree
ANSEntropy coding through an integer stateAlso depends on a probability model and finite precision; organizes state and output differently

Next: Channel Capacity and Coding adds noise and studies reliable communication. Applications to language models continue in Information Theory in LLMs.

References