Codes, Compression, and Perplexity

Dive into Deep Learning · §37.2

Codes, Compression, and Perplexity
prefix codes · Kraft’s inequality · arithmetic coding · MDL · entropy rate · AEP · perplexity

Why Does Better Prediction Yield a Shorter File?

Motivation & Core Question

  • Compressing The Time Machine (173{,}428 chars, 27 symbols): Raw ASCII takes 8.00\text{ bpc}, fixed 27-symbol code takes 4.75\text{ bpc}, zlib -9 takes 2.84\text{ bpc}, and a tiny adaptive order-3 character model reaches 2.55\text{ bpc}.
  • Prediction = Compression: Any causal model q(x_i \mid x_{<i}) paired with an arithmetic coder stores n symbols in -\sum_{i=1}^n \log_2 q(x_i \mid x_{<i}) + 2 bits.

Prefix-Free Codes and Binary Coding Trees

Unambiguous Parsing

How can a receiver parse a concatenated bitstream without delimiter characters between symbols?

  • Prefix-free guarantee: A symbol code is prefix-free if no codeword is a prefix of any other codeword. The stream 110010111 under \{0, 10, 110, 111\} parses uniquely and instantaneously as 110|0|10|111.
  • Binary tree geometry: Each codeword of length \ell_i sits at a leaf of depth \ell_i and prunes away all descendants below it, consuming a fraction 2^{-\ell_i} of the full binary tree.
  • Exhausting the tree: Lengths (1, 2, 3, 3) spend \tfrac12 + \tfrac14 + \tfrac18 + \tfrac18 = 1, leaving no unused leaves.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Kraft’s Inequality: The Dyadic Interval Proof

Existence of Prefix Codes

A prefix-free binary code with integer lengths \ell_1, \ldots, \ell_k exists if and only if:

\sum_{i=1}^k 2^{-\ell_i} \le 1

  • Necessity (\Rightarrow): Codeword c of length \ell maps to the dyadic interval [0.c, 0.c + 2^{-\ell}) \subset [0, 1). Prefix-free \iff disjoint intervals \implies total width \le 1.
  • Sufficiency (\Leftarrow): Sort \ell_1 \le \cdots \le \ell_k and pack widths 2^{-\ell_i} left-to-right; each start s_i is an integer multiple of 2^{-\ell_i}.

Optimal Codeword Lengths Match Surprisal

Lagrange Multiplier Derivation

Given symbol probabilities P = (p_1, \ldots, p_k), which codeword lengths minimize the expected length \mathbb{E}[\ell] = \sum_{i=1}^k p_i \ell_i subject to Kraft’s budget \sum_{i=1}^k 2^{-\ell_i} = 1?

  • Continuous relaxation via Lagrange multipliers: Differentiating the Lagrangian \sum_i p_i \ell_i + \lambda(\sum_i 2^{-\ell_i} - 1) with respect to \ell_i sets p_i - \lambda (\ln 2) 2^{-\ell_i} = 0, so 2^{-\ell_i} \propto p_i. Summing over i forces 2^{-\ell_i} = p_i: \ell_i^* = \log_2 \frac{1}{p_i}, \qquad \mathbb{E}[\ell^*] = \sum_{i=1}^k p_i \log_2 \frac{1}{p_i} = H_2(P)
  • Integer rounding (Shannon code): Real codewords require integer lengths. Rounding each ideal length up gives the Shannon lengths \ell_i = \lceil \log_2(1/p_i) \rceil, which automatically satisfy 2^{-\ell_i} \le p_i and pass Kraft’s test (\sum_i 2^{-\ell_i} \le \sum_i p_i = 1).

The Fundamental Entropy Sandwich for Prefix Codes

Shannon’s Source Coding Bounds

With spent Kraft budget Z = \sum_i 2^{-\ell_i} \le 1 and implied distribution q_i = 2^{-\ell_i}/Z, expected length splits into three terms:

\mathbb{E}_P[\ell] = H_2(P) + D_{\textrm{KL}}^{(2)}(P \| Q) + (-\log_2 Z) \ge H_2(P)

  • Shannon sandwich: Choosing \ell_i = \lceil \log_2(1/p_i) \rceil < \log_2(1/p_i) + 1 guarantees H_2(P) \le \mathbb{E}_P[\ell] < H_2(P) + 1.

Shannon vs. Huffman Codes and the 1-Bit Floor

Optimal Symbol Codes

  • Huffman greedy merging: Repeatedly merges the two rarest symbols so Z = 1, cutting expected length on P = (0.6, 0.3, 0.1) from Shannon’s 1.60 bits to 1.40 bits (H_2 = 1.295).
  • The 1-bit symbol wall: Because every symbol codeword has \ell_i \ge 1, no symbol code can beat 1.00 bit/symbol—even when P(\texttt{a}) = 0.9 has H_2(P) = 0.469 bits.

Mismatched Codes: Cross-Entropy Is File Length

Coding Under a Model Q

When we build a Shannon code \ell_i = \lceil \log_2(1/q_i) \rceil from a model Q and apply it to data drawn from P, its expected code length is sandwiched by the cross-entropy \textrm{CE}_2(P, Q) = H_2(P) + D_{\textrm{KL}}^{(2)}(P \| Q):

\textrm{CE}_2(P, Q) \le \mathbb{E}_P[\ell] < \textrm{CE}_2(P, Q) + 1

dyadic, own      lengths [1, 2, 3, 3]  Kraft 1.0000  E[ell] 1.750  CE2 1.750
dyadic, uniform  lengths [2, 2, 2, 2]  Kraft 1.0000  E[ell] 2.000  CE2 2.000
P, own           lengths [1, 2, 4]  Kraft 0.8125  E[ell] 1.600  CE2 1.295
P, code from Q   lengths [3, 1, 2]  Kraft 0.8750  E[ell] 2.300  CE2 1.867

Arithmetic Coding: One Interval per Message

Stream Codes

Arithmetic coding achieves block-coding efficiency without a lookup table by mapping an entire n-symbol message x_{1:n} on the fly to a subinterval of [0, 1) of width w = \prod_{i=1}^n q(x_i \mid x_{<i}):

  • At step i, the encoder subdivides the current interval [lo, hi) in proportion to q(\cdot \mid x_{<i}) and retains the slice of the observed symbol x_i.

The Two-Bit Overhead Bound of Arithmetic Coding

Dyadic Interval Selection

To specify a dyadic interval [m 2^{-\ell}, (m+1)2^{-\ell}) wholly inside [lo, hi) of width w = \prod_{i=1}^n q(x_i \mid x_{<i}), set \ell = \lceil\log_2(1/w)\rceil + 1 (2^{-\ell} \le w/2):

\ell < \sum_{i=1}^n \log_2 \frac{1}{q(x_i \mid x_{<i})} + 2\text{ bits}

  • Amortized rounding: Rounding happens once for the entire message, so per-symbol overhead 2/n \to 0 as n \to \infty.

Arithmetic Coding in Code: 6 Bits vs. 13 Bits

Live Demonstration

On the 10-symbol message aaaaaaaaba (4.69 bits surprisal under q(\texttt{a}) = 0.9), arithmetic coding outputs the 6-bit codeword 011001, whereas symbol-by-symbol Shannon coding spends 13 bits:

final interval [0.3874, 0.4262), width 0.0387
surprisal 4.69 bits, codeword 011001 (6 bits)
symbol-by-symbol Shannon code: 13 bits

Systems Pitfall (53-Bit Float Underflow): Naive IEEE-754 double precision (float64) underflows hi - lo to zero after \sim 100 symbols. Production coders use fixed-width integer registers and stream out leading bits whenever lo and hi agree on their top bit.

Any Autoregressive Language Model Is a Compressor

Adaptive & Pretrained Models

Because arithmetic coding requires only next-symbol probabilities q(\cdot \mid x_{<i}), any causal predictor (from an n-gram table to a Transformer LLM) becomes a lossless compressor:

  • Adaptive order-m counting model: Predicts character x_i from the preceding m-character context s = x_{i-m:i} using Laplace-smoothed running counts (k = 27): q(x \mid s) = \frac{c(s, x) + 1/2}{c(s) + k/2}
  • Zero parameter transmission overhead: Counts are updated after coding each character, so the decoder updates identical counts in lockstep without receiving a header table.

Any Autoregressive Language Model Is a Compressor (cont.)

Adaptive & Pretrained Models

fname = d2l.download(d2l.DATA_URL + 'timemachine.txt',
                     sha1_hash='090b5e7e70c295757f55df93cb0a180b9691891a')
with open(fname) as f:
    text = re.sub('[^A-Za-z]+', ' ', f.read()).lower()   # 26 letters, space

def adaptive_bits(text, m, k):
    """Bits per character of the adaptive order-m model with half counts."""
    counts, totals, bits = {}, {}, 0.0
    for i, ch in enumerate(text):
        s = text[max(0, i - m):i]                # the context
        c = counts.setdefault(s, {})
        bits -= math.log2((c.get(ch, 0) + 0.5) / (totals.get(s, 0) + k / 2))
        c[ch] = c.get(ch, 0) + 1                 # learn after coding
        totals[s] = totals.get(s, 0) + 1
    return bits / len(text)

Compressing The Time Machine: Context Trade-Off

Empirical Compression Benchmark

Evaluating adaptive context lengths m \in \{0, 1, 2, 3, 4\} on The Time Machine (173{,}428 chars) reveals a bias-variance / warmup trade-off:

173428 characters over 27 symbols, letter-frequency entropy 4.078 bits
order 0: 4.08 bits/char = 2.83 nats/char, perplexity 2^bits = 16.91
order 1: 3.29 bits/char = 2.28 nats/char, perplexity 2^bits = 9.81
order 2: 2.75 bits/char = 1.90 nats/char, perplexity 2^bits = 6.70
order 3: 2.55 bits/char = 1.77 nats/char, perplexity 2^bits = 5.84
order 4: 2.78 bits/char = 1.92 nats/char, perplexity 2^bits = 6.85
zlib -9: 2.84 bits/char
order 0 minus the letter-frequency entropy: 0.0011 bits/char, 183 bits in all
  • Why order 3 wins (2.55 bpc vs. zlib 2.84 bpc): Three characters capture English morphemes while occurring often enough to populate counts quickly; order 4 (27^4 \approx 530{,}000 contexts) wastes more bits warming up rare contexts than the 4th character saves.

Pretrained LLMs as Universal Compressors

Parametric vs. Adaptive Trade-Off

  • Frozen 70B LLM + arithmetic coder (Delétang et al., 2023): Compresses raw ImageNet patches to 43.4\% (beating PNG’s 58.5\%) and LibriSpeech audio to 16.4\% (beating FLAC’s 30.3\%).
  • Two-part MDL catch: If the receiver does not already hold the 140\text{ GB} weights (2 bytes/param), transmitting the model inflates a 1\text{ GB} dataset to >14{,}000\%.

Minimum Description Length (MDL) and BIC

Occam’s Razor in Bits

Minimum Description Length (MDL) selects the model \mathcal{M} minimizing total two-part file size:

\hat{\mathcal{M}} = \operatorname{argmin}_{\mathcal{M}}\big[L(\mathcal{M}) + L(\mathcal{D} \mid \mathcal{M})\big]

  • BIC rule (\tfrac12\log_2 n bits/param): Empirical parameter uncertainty scales as 1/\sqrt{n}, so a \sqrt{n}-grid costs \approx 5 bits at n = 1{,}000.
  • Adaptive prequential advantage: Pays only for contexts that actually appear in the text stream.

Entropy Rate of Stationary Sources with Memory

Fundamental Limit for Sequences

For a stationary stochastic process X_1, X_2, \ldots with memory, the fundamental compression floor per symbol is the entropy rate:

H_{\textrm{rate}} = \lim_{n \to \infty} \frac{1}{n} H(X_1, \ldots, X_n) = \lim_{n \to \infty} H(X_n \mid X_{<n})

  • Monotone decrease with context: By the chain rule H(X_{1:n}) = \sum_{i=1}^n H(X_i \mid X_{<i}) and the fact that conditioning never increases entropy, H(X_n \mid X_{<n}) and its Cesàro average \frac{1}{n}H(X_{1:n}) decrease monotonically to H_{\textrm{rate}}.
  • Sticky Markov chain example: Let X_n \in \{\texttt{a}, \texttt{b}\} stay in its current state with probability 0.9 and switch with probability 0.1. By symmetry, the marginal is uniform (H(X_1) = 1\text{ bit}), but given X_{n-1} the transition entropy is H_{\textrm{rate}} = H(X_n \mid X_{n-1}) = H_2(0.9, 0.1) = 0.469\text{ bits/symbol}.

Achieving and Bounding the Entropy Rate

English Compression Ladder

  • Fundamental floor: No uniquely decodable block code can average fewer than H_{\textrm{rate}} bits/symbol, while arithmetic coding under the true conditional model achieves \frac{1}{n}H(X_{1:n}) + \frac{2}{n} \to H_{\textrm{rate}}.
  • English progression (\textrm{PPL} = 2^{\textrm{bpc}}): Drops from uniform 4.75\text{ bpc} (\textrm{PPL} = 27) to unigram 4.08\text{ bpc}, zlib 2.84\text{ bpc}, order-3 2.55\text{ bpc} (\textrm{PPL} = 5.84), neural LM 1.73\text{ bpc}, and Shannon’s human bounds of 0.6\text{–}1.3\text{ bpc} (\textrm{PPL} \approx 1.5\text{–}2.5).

The Asymptotic Equipartition Property (AEP)

Typical Sequences

For i.i.d. draws X_1, \ldots, X_n \sim P with binary entropy H = H_2(P), the weak law of large numbers implies -\frac{1}{n}\log_2 P(X_{1:n}) = -\frac{1}{n}\sum_{i=1}^n \log_2 P(X_i) \xrightarrow{P} H. The typical set at tolerance \delta > 0 is:

A_\delta = \left\{x_{1:n} : \left|-\frac{1}{n}\log_2 P(x_{1:n}) - H\right| < \delta\right\}

  • 1. Concentration (P(A_\delta) \to 1): Almost all probability mass concentrates inside A_\delta as n \to \infty.
  • 2. Equipartition of probability: Every typical sequence x_{1:n} \in A_\delta has probability 2^{-n(H+\delta)} < P(x_{1:n}) < 2^{-n(H-\delta)}.
  • 3. Exponential cardinality (|A_\delta| \approx 2^{nH}): Summing the probability bounds over A_\delta gives (1-\eta)2^{n(H-\delta)} \le |A_\delta| \le 2^{n(H+\delta)}, proving that indexing A_\delta takes n(H+\delta) bits while any fixed-length code of rate R < H fails with probability \to 1.

Typical Sequences Are Not the Most Probable Ones

Geometry of the Typical Set

For n = 200 i.i.d. \textrm{Bernoulli}(0.3) bits (H = 0.881\text{ bits}, nH = 176.3\text{ bits}, \delta = 0.1), exact binomial summation counts the typical set (44 \le j \le 76 ones):

H = 0.881 bits/symbol, nH = 176.3 bits
typical: 2^188.8 of 2^200 strings, 44 <= j <= 76
probability they carry: 0.9893
bounds: 0.989 * 2^156.3 <= |A| <= 2^196.3

Separating Probability Mass from String Counts

Visualizing AEP Concentration

Why does the typical set live around j = np = 60 ones rather than at j = 0 or j = 100?

  • Most probable string (j = 0, all zeros): Has individual probability 0.7^{200} = 2^{-103}, but there is only \binom{200}{0} = 1 such string, so it is completely atypical (0.515\text{ bits/symbol} \notin H \pm \delta).
  • Most numerous strings (j = 100 ones): \binom{200}{100} = 2^{195.9} strings exist, but each has tiny probability 2^{-225}, totaling 2^{-29}.
  • Typical band (j \approx 60): Product \binom{n}{j} p^j (1-p)^{n-j} peaks where 2^{172.2} strings each carry \approx 2^{-176.3}.

Perplexity Is an Exponentiated Code Length

Language Model Evaluation

Language models report held-out cross-entropy loss \textrm{CE} = -\frac{1}{n}\sum_{i=1}^n \log q(x_i \mid x_{<i}) through its exponential, the perplexity:

\textrm{PPL} = \exp(\textrm{CE}) = 2^{\textrm{CE}_2} = \left(\prod_{i=1}^n q(x_i \mid x_{<i})\right)^{-1/n}

  • Base invariance: Because e^{\textrm{CE}} = 2^{\textrm{CE}/\ln 2} = b^{\textrm{CE}_b}, perplexity is identical regardless of whether loss is computed in nats or bits.
  • Effective branching factor: A model that spreads probability uniformly over k plausible next tokens at every step has \textrm{CE}_2 = \log_2 k bits and \textrm{PPL} = k; a perfect deterministic predictor has \textrm{PPL} = 1.
  • Interpretability on The Time Machine: Order-3 context reduces next-character uncertainty from 27 possibilities to an effective branching factor of 5.84 (roughly a six-sided die roll per character).

The Expected Perplexity Floor: 2 to the Rate

Gibbs + Jensen Derivation

How low can expected perplexity go on sequences drawn from a stationary source with entropy rate H_{\textrm{rate}} bits/token?

Proposition (Perplexity Floor): For any stationary source P and any autoregressive model q, \mathbb{E}[\textrm{CE}] \ge H_{\textrm{rate}} \ln 2 and \mathbb{E}[\textrm{PPL}] = \mathbb{E}[e^{\textrm{CE}}] \ge 2^{H_{\textrm{rate}}}.

  • Step 1 (Pointwise Gibbs’ inequality): Conditioned on prefix x_{<i}, expected model loss is at least the true conditional entropy: \mathbb{E}[-\log q(X_i \mid X_{<i})] \ge \mathbb{E}[-\log p(X_i \mid X_{<i})].
  • Step 2 (Chain rule & stationarity): Averaging over i = 1, \ldots, n yields \mathbb{E}[\textrm{CE}] \ge \frac{\ln 2}{n}H(X_{1:n}) \ge H_{\textrm{rate}} \ln 2.
  • Step 3 (Jensen’s inequality for convex e^x): \mathbb{E}[\textrm{PPL}] = \mathbb{E}[e^{\textrm{CE}}] \ge e^{\mathbb{E}[\textrm{CE}]} \ge e^{H_{\textrm{rate}}\ln 2} = 2^{H_{\textrm{rate}}}. \blacksquare (Caution: The bound applies to the expectation \mathbb{E}[\textrm{PPL}]; a single lucky 10-character string of all \texttt{a}’s under P(\texttt{a})=0.9 scores below 2^H = 1.38 with probability 0.9^{10} = 35\%.)

Comparing Perplexity Across Different Tokenizers

Systems Pitfall: Token Granularity

Because perplexity is defined per token, models with different vocabularies must be compared via bits per character (bpc) or bits per byte (bpb):

\textrm{bpc} = \frac{n_{\textrm{tok}}}{n_{\textrm{char}}}\log_2 \textrm{PPL}

  • Coarse subwords vs. fine chars (10^6 chars): Model A (2 \times 10^5 tokens, \textrm{PPL} = 32) achieves 1.00\text{ bpc}, beating Model B (5 \times 10^5 tokens, \textrm{PPL} = 8, 1.50\text{ bpc}) by 33\% despite 4\times higher token PPL.

Concept Check: Prefix Codes, AEP, and Perplexity

Check Your Understanding

Test your grasp of source coding and language model evaluation:

  1. Shannon vs. Huffman lengths: For P = (0.6, 0.3, 0.1) (H_2(P) = 1.295 bits), what codeword lengths and expected code length does Shannon’s rule produce compared to Huffman’s algorithm?
  2. Typical set indexing vs. arithmetic coding: For n = 200 draws of \textrm{Bernoulli}(0.3) (nH = 176.3 bits), indexing the \delta = 0.1 typical set (2^{188.8} strings) costs 189 bits. How does arithmetic coding compare in expected length and failure rate?
  3. Uniform vocabulary baseline: A freshly initialized LLM assigns uniform probability 1/50{,}000 to every token in its vocabulary. What are its perplexity and its loss in bits per token and nats per token?

Answers:

  1. Symbol codes: Shannon rounds surprisals (0.74, 1.74, 3.32) up to (1, 2, 4) for \mathbb{E}[\ell] = 1.60\text{ bits} (Z = 0.8125). Huffman merges the two rarest symbols to get (1, 2, 2) for \mathbb{E}[\ell] = 1.40\text{ bits} (Z = 1).
  2. AEP vs. arithmetic coding: Indexing A_{0.1} spends 189\text{ bits} (12.7 bits above nH) and fails on the 1.1\% of messages outside A_{0.1}; arithmetic coding is strictly lossless on all messages and averages under nH + 2 = 178.3\text{ bits}.
  3. Uniform LLM: \textrm{PPL} = 50{,}000 (the branching factor); loss is \log_2 50{,}000 \approx 15.61\text{ bits/token} or \ln 50{,}000 \approx 10.82\text{ nats/token}.

Summary: Source Coding and Compression Metrics

Key Takeaways

Concept / Method Mathematical Formula / Bound Per-Symbol Overhead Deep Learning / Compression Role
Kraft’s Inequality \sum_{i=1}^k 2^{-\ell_i} \le 1 Exact tree / dyadic budget Necessary & sufficient for prefix / uniquely decodable codes
Shannon Symbol Code \ell_i = \lceil \log_2(1/q_i) \rceil \textrm{CE}_2(P, Q) \le \mathbb{E}_P[\ell] < \textrm{CE}_2 + 1 Links cross-entropy and KL divergence to codeword length
Arithmetic Coding Subinterval of width w = \prod_i q(x_i \mid x_{<i}) < \frac{2}{n} bits/symbol (\le 2 bits total) Turns any autoregressive LLM into a universal compressor
MDL Principle \min_{\mathcal{M}}[L(\mathcal{M}) + L(\mathcal{D} \mid \mathcal{M})] \approx \frac{1}{2}\log_2 n bits per parameter (BIC) Penalizes context/parameter overfitting directly in bits
Entropy Rate H_{\textrm{rate}} = \lim_{n\to\infty} H(X_n \mid X_{<n}) Irreducible floor for stationary sequences Fundamental compression limit of language (\approx 1 bpc)
Perplexity & BPC \textrm{PPL} = e^{\textrm{CE}} = 2^{\textrm{CE}_2}, \textrm{bpc} = \frac{n_{\textrm{tok}}}{n_{\textrm{char}}}\log_2 \textrm{PPL} \mathbb{E}[\textrm{PPL}] \ge 2^{H_{\textrm{rate}}} Evaluates LLMs; \textrm{bpc} normalizes across tokenizers