intermediate language-modeling 40 min read

Perplexity, Cross-Entropy, and Compression

Held-out log-loss is a file size: an arithmetic coder turns any language model into a compressor within two bits of it — which makes perplexity a branching factor, bits per character its honest unit, and the unknown-word convention a flattering lower bound

Overview & Motivation

Two language models score the same held-out finance text. One reports a perplexity of 1.6651.665, the other 19.2319.23. Which is better? As posed, the question has no answer. The first model is a character 77-gram, so its perplexity is per character. The second is a word trigram, so its perplexity is per word. Put both on one unit and the order flips: the word model spends 0.6370.637 bits per character, and the character model 0.7350.735.

This topic makes that comparison precise by reading a language model three ways, and proving each reading.

  1. A forecaster scored by log-loss. Held-out log-loss estimates a cross-entropy, and the logarithm is the score that rewards a forecaster for reporting what it actually believes.
  2. A branching factor. Perplexity counts the equally likely choices the model behaves as if it faced at each token. The asymptotic equipartition property makes “behaves as if” exact.
  3. A compressor. An arithmetic coder turns any sequential model into a code whose length is within two bits of the model’s −log⁡2Q(text)-\log_2 Q(\text{text}). So held-out cross-entropy is the size of the file the model would write. We run that coder on the whole held-out corpus of the n-gram topic: 154,362154{,}362 characters become one codeword of 98,34598{,}345 bits, 0.690.69 bits above the model’s own figure.

The file-size reading settles two questions the previous topics left open. The subword topic charged −log⁡2p(t)-\log_2 p(t) bits for a piece tt and called it compression, and Theorem 4 makes that exact for a whole file. The n-gram topic reported log-loss per word, and Theorem 5 shows that comparing models across tokenizers needs a unit the tokenizer does not choose: characters, bytes, or words. Proposition 5 shows that the unknown-word convention can only flatter a model. The finance case study then takes everything out of domain, to public EDGAR filings, where a Kneser–Ney model predicts worse than a uniform guess and a stock lzma compressor beats every model on the page.


Cross-entropy and the log score

The n-gram topic’s interpolated Kneser–Ney model scores 2.85512.8551 nats per token on held-out text: the average of −log⁡Q(wi∣ui)-\log Q(w_i \mid u_i) over its 23,05523{,}055 predicted tokens. In bits that is 4.1194.119 per token, and it already sounds like a code length. We start with what that average estimates.

Throughout, a sentence is padded with two <s> symbols in front and one </s> behind, and every word and the final </s> is a predicted token. VV is the n-gram topic’s vocabulary, ∣V∣=3,427\lvert V \rvert = 3{,}427. The normalized string of a sentence is its words joined by single spaces, followed by a sentence-end mark. Its characters are therefore each word’s letters plus one separator after each word, a space or the sentence end. The held-out text has 2,0492{,}049 sentences, 23,05523{,}055 predicted tokens, and 154,362154{,}362 characters. Logarithms are natural (in nats) unless written log⁡2\log_2 (in bits).

Definition 1 (Cross-entropy, log-loss, and perplexity).

For distributions pp and qq on a finite set, the cross-entropy of qq relative to pp is H(p,q)=−∑xp(x)log⁡q(x)H(p, q) = -\sum_x p(x) \log q(x), and H(p)=H(p,p)H(p) = H(p, p) is the entropy. A sequential model QQ scores a text x1…xnx_1 \dots x_n by its negative log-likelihood

NLL=−log⁡Q(x1…xn)=−∑i=1nlog⁡Q(xi∣x1…xi−1).\mathrm{NLL} = -\log Q(x_1 \dots x_n) = -\sum_{i=1}^{n} \log Q(x_i \mid x_1 \dots x_{i-1}).

For a unit occurring nunitn_{\text{unit}} times in the text (the model’s own tokens, characters, or word tokens), the log-loss per unit is NLL/nunit\mathrm{NLL}/n_{\text{unit}}, and the perplexity per unit is PPunit=exp⁡(NLL/nunit)\mathrm{PP}_{\text{unit}} = \exp(\mathrm{NLL}/n_{\text{unit}}). Bits per character (bpc) is NLL/(ncharln⁡2)\mathrm{NLL}/(n_{\text{char}} \ln 2).

Proposition 1 (Cross-entropy is entropy plus divergence).

H(p,q)=H(p)+KL(p ∥ q)≥H(p)H(p, q) = H(p) + \mathrm{KL}(p \,\|\, q) \ge H(p), with equality if and only if q=pq = p.

This is Proposition 1 of formalML’s KL divergence: expand log⁡q=log⁡p−log⁡(p/q)\log q = \log p - \log(p/q) and apply Gibbs’ inequality. We use it as a tool, four times on this page: in Corollary 1, Proposition 2(3), Corollary 2, and Proposition 3.

Corollary 1 (The log score is strictly proper).

For every distribution pp, the expected log-loss Ep[−log⁡q(X)]\mathbb{E}_p[-\log q(X)] is minimized at q=pq = p and nowhere else.

Proof.

Ep[−log⁡q(X)]=H(p,q)=H(p)+KL(p ∥ q)\mathbb{E}_p[-\log q(X)] = H(p, q) = H(p) + \mathrm{KL}(p \,\|\, q). Only the divergence depends on qq, and by Proposition 1 it is zero exactly at q=pq = p.

∎

A forecaster scored by log-loss does best, on average, by reporting its true belief. That is the property strictly proper names (Gneiting and Raftery 2007). Training a language model by minimizing empirical cross-entropy is maximum likelihood, the reading the n-gram topic proved for relative frequencies, and strict propriety is why maximum likelihood rewards a model for reporting its true beliefs. Not every score has it. Under the linear score Ep[q(X)]\mathbb{E}_p[q(X)], putting all mass on the most likely outcome does at least as well as reporting pp itself, and strictly better unless pp is uniform on its support. For more than two outcomes, the logarithm is the only proper score that depends on the forecast only through the probability given to what happened (Bernardo 1979).

Proposition 2 (What a perplexity is).

  1. For a text of NN tokens with model probabilities q1,…,qNq_1, \dots, q_N, the perplexity is PP=(∏i1/qi)1/N\mathrm{PP} = \bigl(\prod_{i} 1/q_i\bigr)^{1/N}, the geometric mean of the inverse probabilities, which is at most their arithmetic mean.
  2. A model that is uniform on kk symbols has perplexity exactly kk on every text.
  3. For every distribution pp, 1≤eH(p)≤∣supp p∣1 \le e^{H(p)} \le \lvert \mathrm{supp}\, p \rvert.
  4. Consequently, a perplexity above ∣V∣\lvert V \rvert means the model did worse on that text than the uniform distribution on VV.
Proof.

For (1), exp⁡(−1N∑ilog⁡qi)=(∏iqi−1)1/N\exp\bigl(-\frac1N \sum_i \log q_i\bigr) = \bigl(\prod_i q_i^{-1}\bigr)^{1/N}, and the arithmetic–geometric mean inequality bounds it by 1N∑iqi−1\frac1N \sum_i q_i^{-1}. For (2), every qi=1/kq_i = 1/k. For (3), H(p)≥0H(p) \ge 0, and H(p)≤log⁡∣supp p∣H(p) \le \log \lvert \mathrm{supp}\, p \rvert is Proposition 1 with qq uniform on the support of pp. Statement (4) is (2) with k=∣V∣k = \lvert V \rvert.

∎

On the held-out text, interpolated Kneser–Ney’s 2.85512.8551 nats per token is a perplexity of 17.3817.38: the model is as uncertain as if it chose uniformly among about seventeen words at each token. On the public EDGAR excerpts of the finance case study, the same model scores 8.79638.7963 nats, a perplexity of 6,6106{,}610. That is above ∣V∣=3,427\lvert V \rvert = 3{,}427, whose logarithm is 8.13948.1394, so on that text the model predicts worse than the uniform distribution over its own vocabulary. Modified Kneser–Ney (8.60228.6022) does too. Laplace smoothing, which leans hardest toward uniform, scores 8.13268.1326 and stays just under the line.


Perplexity as a branching factor

Roll a three-sided die weighted 0.60.6, 0.30.3, and 0.10.1 three hundred times. There are 33003^{300} possible sequences, but the die does not visit them evenly. Almost all of its probability falls on a set that holds a fraction 4.8×10−174.8 \times 10^{-17} of the sequences. Each sequence in that set has a probability whose geometric mean per roll is close to e−He^{-H}, so each is about as probable as a run of uniform choices among eH=2.455e^{H} = 2.455 faces per roll, rather than three. This is the precise sense in which perplexity is a branching factor.

Theorem 1 (The asymptotic equipartition property).

Let X1,…,XnX_1, \dots, X_n be independent draws from pp on a finite alphabet, with entropy H=H(p)H = H(p) and σ2=Var(−log⁡p(X1))\sigma^2 = \mathrm{Var}(-\log p(X_1)). For ε>0\varepsilon \gt 0, the typical set is

A={x1…xn:∣−1nlog⁡p(x1…xn)−H∣≤ε}.A = \Bigl\{ x_1 \dots x_n : \bigl\lvert -\tfrac1n \log p(x_1 \dots x_n) - H \bigr\rvert \le \varepsilon \Bigr\}.

Then

P(A)  ≥  1−σ2nε2,∣A∣  ≤  en(H+ε),∣A∣  ≥  P(A) en(H−ε).P(A) \;\ge\; 1 - \frac{\sigma^2}{n\varepsilon^2}, \qquad \lvert A \rvert \;\le\; e^{n(H + \varepsilon)}, \qquad \lvert A \rvert \;\ge\; P(A)\, e^{n(H - \varepsilon)}.

For any model qq with τ2=Var(−log⁡q(X1))\tau^2 = \mathrm{Var}(-\log q(X_1)), likewise P(∣−1nlog⁡q(X1…Xn)−H(p,q)∣≤ε)≥1−τ2/(nε2)P\bigl(\lvert -\tfrac1n \log q(X_1 \dots X_n) - H(p, q) \rvert \le \varepsilon\bigr) \ge 1 - \tau^2/(n\varepsilon^2).

Proof.

−log⁡p(X1…Xn)=∑i−log⁡p(Xi)-\log p(X_1 \dots X_n) = \sum_i -\log p(X_i) is a sum of nn independent terms, each with mean HH and variance σ2\sigma^2. Chebyshev’s inequality bounds the probability that its average leaves [H−ε,H+ε][H - \varepsilon, H + \varepsilon] by σ2/(nε2)\sigma^2/(n\varepsilon^2), which is the first bound and the weak law of large numbers. Every sequence in AA has probability between e−n(H+ε)e^{-n(H + \varepsilon)} and e−n(H−ε)e^{-n(H - \varepsilon)}. Summing the lower bound over AA gives 1≥P(A)≥∣A∣e−n(H+ε)1 \ge P(A) \ge \lvert A \rvert e^{-n(H + \varepsilon)}, the second bound. Summing the upper bound gives P(A)≤∣A∣e−n(H−ε)P(A) \le \lvert A \rvert e^{-n(H - \varepsilon)}, the third. The statement for qq is Chebyshev’s inequality applied to the terms −log⁡q(Xi)-\log q(X_i), whose mean is H(p,q)H(p, q).

∎

So almost all the probability sits on the typical set, and every member of it has probability within a factor e±nεe^{\pm n\varepsilon} of e−nHe^{-nH}: per symbol, each typical sequence is about as probable as a uniform choice among eHe^{H} options. That is a statement about each sequence’s probability, not the set’s size. With ε\varepsilon fixed, the theorem pins ∣A∣\lvert A \rvert only between P(A) en(H−ε)P(A)\, e^{n(H - \varepsilon)} and en(H+ε)e^{n(H + \varepsilon)}, and the table below shows it sitting well above enHe^{nH}. Likewise, by the theorem’s last statement, a text drawn from pp has −1nlog⁡q≈H(p,q)-\frac1n \log q \approx H(p, q) with high probability, so the model assigns it about the probability a uniform guesser among eH(p,q)e^{H(p, q)} options per symbol would. Its perplexity is that number of options.

For the die, H=0.8979H = 0.8979 nats. Counting type classes exactly with ε=0.1\varepsilon = 0.1:

rolls nnP(A)P(A)Chebyshev’s floor1nlog⁡∣A∣\frac1n \log \lvert A \rvert
40400.75040.75040.2120.2120.93390.9339
1201200.94840.94840.7370.7370.96190.9619
3003000.99790.99790.8950.8950.97330.9733
1,0001{,}0001.00001.00000.9680.9680.97970.9797

The probability of the typical set climbs to one, and the growth rate of its size stays within ε\varepsilon of HH, as the theorem says. At n=300n = 300 the set has e292.0e^{292.0} members out of 3300≈e329.63^{300} \approx e^{329.6}, against enH=e269.4e^{nH} = e^{269.4}. Formal statements of this kind are often quoted as “about enHe^{nH} sequences.” The table shows what “about” means: within e±nεe^{\pm n\varepsilon}, with ε\varepsilon fixed while nn grows.


From held-out text to cross-entropy

A held-out log-loss is one number computed from one text, so it comes with an uncertainty. For interpolated Kneser–Ney there are two candidate standard errors: 0.02270.0227 if every token is an independent draw, and 0.03200.0320 if every sentence is. The second is right, and the reason is in what the held-out average estimates.

Definition 2 (The sentence source).

Sentences S1,S2,…S_1, S_2, \dots are independent and identically distributed finite token sequences, each ending in </s>. For a model QQ, write Yj=−log⁡Q(Sj)Y_j = -\log Q(S_j) for the negative log-likelihood of sentence jj and Nj=∣Sj∣N_j = \lvert S_j \rvert for its number of predicted tokens. The per-token cross-entropy of QQ against the source is r=E[Y1]/E[N1]r = \mathbb{E}[Y_1]/\mathbb{E}[N_1].

Theorem 2 (Held-out log-loss is a ratio estimator).

If E[N1]\mathbb{E}[N_1] and E[Y1]\mathbb{E}[Y_1] are finite, the held-out per-token log-loss of mm sentences, r^m=∑j≤mYj/∑j≤mNj\hat r_m = \sum_{j \le m} Y_j \big/ \sum_{j \le m} N_j, converges to rr almost surely. If the second moments are also finite, then

m (r^m−r)  ⇒  N ⁣(0,  Var(Y1−rN1)E[N1]2),\sqrt{m}\,(\hat r_m - r) \;\Rightarrow\; \mathcal{N}\!\left(0,\; \frac{\mathrm{Var}(Y_1 - r N_1)}{\mathbb{E}[N_1]^2}\right),

and the variance of r^m\hat r_m is estimated consistently by

se^ 2=∑j≤m(Yj−r^mNj)2m(m−1) Nˉ2,Nˉ=1m∑j≤mNj.\widehat{\mathrm{se}}^{\,2} = \frac{\sum_{j \le m} (Y_j - \hat r_m N_j)^2}{m(m-1)\,\bar N^{2}}, \qquad \bar N = \frac1m \sum_{j \le m} N_j .
Proof.

By the strong law of large numbers (formalStatistics, Law of Large Numbers), the sentence averages Yˉ\bar Y and Nˉ\bar N converge almost surely to E[Y1]\mathbb{E}[Y_1] and E[N1]>0\mathbb{E}[N_1] \gt 0, and r^m=Yˉ/Nˉ\hat r_m = \bar Y / \bar N is a continuous function of the pair away from Nˉ=0\bar N = 0. For the limit law, write r^m−r=(Yˉ−rNˉ)/Nˉ\hat r_m - r = (\bar Y - r \bar N)/\bar N. The numerator is the average of the independent terms Yj−rNjY_j - r N_j, which have mean E[Y1]−r E[N1]=0\mathbb{E}[Y_1] - r\,\mathbb{E}[N_1] = 0. The central limit theorem (formalStatistics, Central Limit Theorem) gives m (Yˉ−rNˉ)⇒N(0,Var(Y1−rN1))\sqrt{m}\,(\bar Y - r \bar N) \Rightarrow \mathcal{N}(0, \mathrm{Var}(Y_1 - r N_1)), and Slutsky’s theorem divides by Nˉ→E[N1]\bar N \to \mathbb{E}[N_1]. Replacing rr by r^m\hat r_m in the sample variance is consistent by the same two laws.

∎

Two things follow. First, the held-out average estimates a ratio of means, not the mean of per-sentence averages, so long sentences count for more. Second, the independent unit is the sentence: tokens in one sentence share a history, so treating them as independent understates the error. On the corpus the sentence-level standard error is 1.411.41 times the naive one.

We checked the theorem where the answer is known exactly. For twenty random bigram sentence sources, absorbing-chain algebra gives E[Y1]\mathbb{E}[Y_1] and E[N1]\mathbb{E}[N_1] in closed form. The held-out average of 20,00020{,}000 sampled sentences lands within four standard errors of rr every time. For one of those sources, 400400 replications of 300300 sentences each check the interval r^±1.96 se^\hat r \pm 1.96\,\widehat{\mathrm{se}}: it covers rr 373373 times (93.3%93.3\%), within binomial noise of the nominal 95%95\%. On the held-out corpus:

  • interpolated Kneser–Ney scores 2.8551±0.03202.8551 \pm 0.0320 nats per token;
  • modified Kneser–Ney minus interpolated Kneser–Ney, paired sentence by sentence, is −0.0143±0.0006-0.0143 \pm 0.0006, twenty-four standard errors from zero, although the two models’ own intervals overlap;
  • the open-vocabulary code of the next section spends 0.6371±0.00650.6371 \pm 0.0065 bits per character.

Pairing removes the variation the two models share, which is most of it. Formal tests and the bootstrap belong to the later topic on significance testing.

Remark (Shannon–McMillan–Breiman (cited)).

Sentences need not be independent for the held-out average to mean something. For a stationary ergodic source PP on a finite alphabet, −1nlog⁡P(X1…Xn)-\frac1n \log P(X_1 \dots X_n) converges almost surely to the entropy rate (McMillan 1953 in mean, Breiman 1957 almost surely). For a model QQ of finite Markov order with positive conditionals, −1nlog⁡Q(X1…Xn)-\frac1n \log Q(X_1 \dots X_n) is an ergodic average of a function of finitely many coordinates, so Birkhoff’s ergodic theorem sends it to the cross-entropy rate. Algoet and Cover (1988) prove the first statement by sandwiching between exactly such Markov approximations. The companion notebook checks both limits along single paths of length 10510^5 of random ergodic Markov chains, whose rates formalML’s Shannon Entropy computes in closed form.

Corollary 2 (Every model bounds the entropy rate).

For a stationary source PP and any sequential model QQ, E[−log⁡Q(X1…Xn)]≥H(X1,…,Xn)\mathbb{E}[-\log Q(X_1 \dots X_n)] \ge H(X_1, \dots, X_n) for every nn. When the limits exist, the cross-entropy rate is therefore at least the entropy rate, with equality when Q=PQ = P.

Proof.

Apply Proposition 1 to the joint distributions of nn symbols: E[−log⁡Q(X1…Xn)]=H(X1,…,Xn)+KL(Pn ∥ Qn)\mathbb{E}[-\log Q(X_1 \dots X_n)] = H(X_1, \dots, X_n) + \mathrm{KL}(P_n \,\|\, Q_n), where PnP_n and QnQ_n are the two laws of the first nn symbols. Divide by nn and let nn grow.

∎

So any model’s held-out cross-entropy estimates an upper bound on the entropy rate of the source. Brown et al. (1992) bounded English at 1.751.75 bits per character this way. For our generator the lowest figure on this page is modified Kneser–Ney’s open-vocabulary code, at 0.6340.634 bits per character; the interpolated Kneser–Ney code run below gives 0.6370.637. That figure comes from one held-out text, so it estimates the bound rather than certifying it.


Compression is prediction

A binary code gives each symbol xx a codeword c(x)c(x) of ℓ(x)\ell(x) bits. It is prefix-free if no codeword begins another, and uniquely decodable if concatenations of codewords can be split back in only one way. Picture each codeword cc as an interval of [0,1)[0, 1). Read cc as a binary fraction 0.c0.c, and let it name the dyadic interval [0.c, 0.c+2−ℓ)[0.c,\ 0.c + 2^{-\ell}), of length 2−ℓ2^{-\ell}. A codeword that begins another names an interval containing the other’s. So a prefix-free code is a set of disjoint dyadic intervals, and its lengths satisfy

∑x2−ℓ(x)≤1.\sum_x 2^{-\ell(x)} \le 1 .

This is Kraft’s inequality. Conversely, any lengths satisfying it admit a prefix code: lay the intervals left to right in order of increasing length. Both directions, with Shannon’s source-coding theorem H≤E[ℓ]<H+1H \le \mathbb{E}[\ell] \lt H + 1 (in bits), are proved in formalML’s Shannon Entropy. We add the step that extends the converse from prefix codes to every uniquely decodable code.

Definition 3 (Codes).

A binary code on a finite set X\mathcal{X} is a map c:X→{0,1}∗c : \mathcal{X} \to \{0, 1\}^{\ast} with lengths ℓ(x)=∣c(x)∣\ell(x) = \lvert c(x) \rvert. Its extension sends a message x1…xmx_1 \dots x_m to the concatenation c(x1)⋯c(xm)c(x_1) \cdots c(x_m). The code is uniquely decodable if its extension is injective, and prefix-free if no codeword is a proper prefix of another.

Theorem 3 (McMillan's inequality).

Every uniquely decodable code satisfies ∑x2−ℓ(x)≤1\sum_x 2^{-\ell(x)} \le 1.

Proof.

Let K=∑x2−ℓ(x)K = \sum_x 2^{-\ell(x)} and let ℓmax⁡\ell_{\max} be the longest codeword length. For each m≥1m \ge 1, multiply out the mm-th power:

Km=∑x1,…,xm2−(ℓ(x1)+⋯+ℓ(xm))=∑j=1mℓmax⁡Aj 2−j,K^m = \sum_{x_1, \dots, x_m} 2^{-(\ell(x_1) + \cdots + \ell(x_m))} = \sum_{j=1}^{m \ell_{\max}} A_j\, 2^{-j},

where AjA_j counts the messages of mm symbols whose concatenated codeword has exactly jj bits. Unique decodability makes those concatenations distinct strings of jj bits, and there are only 2j2^j such strings, so Aj≤2jA_j \le 2^j and Km≤m ℓmax⁡K^m \le m\,\ell_{\max}. If K>1K \gt 1, the left side grows exponentially in mm and the right side linearly, which is impossible for large mm. So K≤1K \le 1.

∎

Prefix codes therefore lose nothing: any lengths a uniquely decodable code achieves, a prefix code achieves too. The companion notebook checks the theorem exhaustively. Of the 1,3651{,}365 binary codes with three or four codewords of at most three bits, 587587 are uniquely decodable by the Sardinas–Patterson test, and 214214 of those are not prefix-free; {0,01,11}\{0, 01, 11\} is one. None violates Kraft’s inequality, and none of the 182182 codes that violate it is uniquely decodable. A brute-force count of the parsings of every bit-string up to ten bits agrees with Sardinas–Patterson on all 1,3651{,}365 codes.

Proposition 3 (Coding with the wrong model costs its divergence).

For a model qq, the Shannon code has lengths ℓq(x)=⌈−log⁡2q(x)⌉\ell_q(x) = \lceil -\log_2 q(x) \rceil. It is realized by a prefix code, and when symbols are drawn from pp,

H2(p)+KL2(p ∥ q)  ≤  Ep[ℓq]  <  H2(p)+KL2(p ∥ q)+1,H_2(p) + \mathrm{KL}_2(p \,\|\, q) \;\le\; \mathbb{E}_p[\ell_q] \;\lt\; H_2(p) + \mathrm{KL}_2(p \,\|\, q) + 1,

where the subscript 22 marks quantities in bits.

Proof.

∑x2−ℓq(x)≤∑xq(x)=1\sum_x 2^{-\ell_q(x)} \le \sum_x q(x) = 1, so Kraft’s inequality gives a prefix code with these lengths. Since −log⁡2q(x)≤ℓq(x)<−log⁡2q(x)+1-\log_2 q(x) \le \ell_q(x) \lt -\log_2 q(x) + 1, taking expectations under pp places Ep[ℓq]\mathbb{E}_p[\ell_q] in [H2(p,q), H2(p,q)+1)[H_2(p, q),\, H_2(p, q) + 1), and Proposition 1 writes H2(p,q)=H2(p)+KL2(p ∥ q)H_2(p, q) = H_2(p) + \mathrm{KL}_2(p \,\|\, q).

∎

The bits a model wastes per symbol, beyond the source’s entropy, are its divergence from the source. For p=(12,14,18,18)p = (\tfrac12, \tfrac14, \tfrac18, \tfrac18) coded with the uniform model, the code spends 22 bits per symbol: the entropy’s 1.751.75 plus a divergence of 0.250.25. The rounding up to whole bits costs up to one more bit per symbol. Over a text of thousands of symbols that is thousands of bits, and the next theorem removes it.

Theorem 4 (Arithmetic coding).

Let QQ be a sequential model and x=x1…xnx = x_1 \dots x_n a message. Start from the interval [0,1)[0, 1). At step ii, divide the current interval into consecutive slices, one per possible next symbol, the slice for symbol ss having a fraction Q(s∣x1…xi−1)Q(s \mid x_1 \dots x_{i-1}) of the interval’s width, and keep the slice for xix_i. The final interval [a,a+Q(x))[a, a + Q(x)) has width Q(x)Q(x). Let L=⌈−log⁡2Q(x)⌉+1L = \lceil -\log_2 Q(x) \rceil + 1 and b=⌈a 2L⌉b = \lceil a\, 2^{L} \rceil, and let the codeword be the LL-bit binary expansion of bb. Then:

  1. the dyadic interval [b/2L, (b+1)/2L)[b/2^{L},\, (b + 1)/2^{L}) lies inside [a,a+Q(x))[a, a + Q(x));
  2. over any prefix-free set of messages (for example, all messages with a fixed number of symbols), these codewords form a prefix code;
  3. the shortest codeword whose dyadic interval fits has a length Lmin⁡L_{\min} with −log⁡2Q(x)≤Lmin⁡≤⌈−log⁡2Q(x)⌉+1-\log_2 Q(x) \le L_{\min} \le \lceil -\log_2 Q(x) \rceil + 1.
Proof.

(1) By the choice of LL, 2−L≤Q(x)/22^{-L} \le Q(x)/2. By the choice of bb, a≤b/2L<a+2−La \le b/2^{L} \lt a + 2^{-L}, so (b+1)/2L<a+2⋅2−L≤a+Q(x)(b + 1)/2^{L} \lt a + 2 \cdot 2^{-L} \le a + Q(x). (2) The slices of an interval are disjoint, so by induction on the symbols, two messages that differ at some position have disjoint final intervals as long as neither is a prefix of the other. Their dyadic subintervals are then disjoint too. A codeword that began another would name a dyadic interval containing the other’s, so neither codeword begins the other. (3) The upper bound is (1). For the lower bound, a dyadic interval of length 2−L2^{-L} inside an interval of width Q(x)Q(x) needs 2−L≤Q(x)2^{-L} \le Q(x).

∎

So the whole message costs at most two bits more than −log⁡2Q(x)-\log_2 Q(x), not one bit more per symbol. Our coder replaces each probability qq with an integer frequency f=⌊q (240−∣A∣)⌋+1f = \lfloor q\,(2^{40} - \lvert \mathcal{A} \rvert) \rfloor + 1, so every symbol of the alphabet A\mathcal{A} keeps a nonzero slice. It then carries the interval as exact big-integer fractions: with TT the total frequency and cum(s)\mathrm{cum}(s) the frequency of the symbols before ss,

A←A T+W cum(xi),W←W f(xi),D←D T,A \leftarrow A\,T + W\,\mathrm{cum}(x_i), \qquad W \leftarrow W\,f(x_i), \qquad D \leftarrow D\,T,

so that the interval is [A/D, (A+W)/D)[A/D,\ (A + W)/D) at every step. The bounds of Theorem 4 then hold exactly for the integer model. On 200200 random sequential models and messages, decoding recovers every message and the two-sided bound holds in exact integer arithmetic. Over all 243243 messages of five symbols from a three-symbol model, the codewords are prefix-free with Kraft sum at most one.

To code real text, the model needs a way to write down words it has never seen.

Definition 4 (The open-vocabulary word code).

The open-vocabulary form of a word model codes a word in VV as one symbol. It codes any other word as <unk> followed by its letters and an end mark, which are spelled by a speller: a character trigram Kneser–Ney model fit to the 1,8771{,}877 word types that occur exactly once in training, the stand-ins for unseen words that Good–Turing reasoning suggests. The word history sees <unk>, as in the n-gram topic.

The speller can also spell words that are in VV. That wastes a little code space, so the code is slightly deficient, but it never fails. Under interpolated Kneser–Ney, the entire held-out text — 24,76824{,}768 symbols, counting the letters of spelled words — becomes one codeword of 98,34598{,}345 bits. The model’s own −log⁡2Q-\log_2 Q is 98,344.3198{,}344.31, so the codeword is 0.690.69 bits longer. Quantizing to integer frequencies costs less than 0.010.01 bits in all, and decoding reproduces all 2,0492{,}049 sentences exactly. That is 0.63710.6371 bits per character. As in Theorem 4(2), the decoder is told the number of symbols; sending the count 24,76824{,}768 as well would add about 1515 bits. Coding each symbol separately with its Shannon code would take 114,900114{,}900 bits, 16.8%16.8\% more. The subword topic’s reading of a unigram model as a code, −log⁡2p(t)-\log_2 p(t) bits per piece, is now exact to within two bits for a whole file.

Proposition 4 (A compressor is a model).

If CC is a uniquely decodable code on a set of texts, then qC(x)=2−ℓ(x)q_C(x) = 2^{-\ell(x)} satisfies ∑xqC(x)≤1\sum_x q_C(x) \le 1, so the length of every compressed file is the negative log-probability, in bits, of the text under a sub-probability model. Conversely, Theorem 4 turns every sequential model into a code within two bits of its negative log-probability.

Proof.

The first statement is Theorem 3, since ℓ(x)=−log⁡2qC(x)\ell(x) = -\log_2 q_C(x). The second is Theorem 4.

∎

So compressors and language models can be ranked on one scale, bits per character. “Given the training text” means the coder may use the training corpus. For zlib that is a genuine conditional code, a 3232 KiB preset dictionary the decoder also holds. For bz2 and lzma it is the extra length ∣C(train+test)∣−∣C(train)∣\lvert C(\text{train} + \text{test}) \rvert - \lvert C(\text{train}) \rvert, an approximation to one.

bits per characterheld out, aloneheld out, given training textEDGAR, aloneEDGAR, given training text
zlib, level 91.47631.47631.37631.37633.26613.26613.02693.0269
bz2, level 91.04041.04040.67710.67713.12443.12443.55423.5542
lzma, preset 9e1.26171.26170.95590.95593.42013.42012.9080\mathbf{2.9080}
interpolated Kneser–Ney, arithmetic-coded (codeword length)—0.6371\mathbf{0.6371}—5.66075.6607

The last row is the length of the actual codeword, like the compressors’ rows. Elsewhere the page reports the model’s own −log⁡2Q-\log_2 Q per character, which on EDGAR is 5.66055.6605: the 29,71329{,}713-bit codeword is 1.041.04 bits longer than the model’s 29,711.9629{,}711.96. In domain, the Kneser–Ney code beats every general-purpose compressor that sees the same training text. bz2 needs 6.3%6.3\% more bits, because its block sort finds the corpus’s long templated phrases. On the EDGAR excerpts the order reverses, and lzma beats every model on the page. lzma wins by adapting to the text it is coding, and Theorem 4 allows that too: Q(xi∣x1…xi−1)Q(x_i \mid x_1 \dots x_{i-1}) may be learned from the symbols already coded, as long as the decoder can learn it the same way. This is prequential coding (Dawid 1984; formalML’s Minimum Description Length), and adaptive models like PPM (Cleary and Witten 1984) were built on it.


Choosing the unit

One model, one text, two perplexities. On the 1,9031{,}903 held-out sentences made only of in-vocabulary words, interpolated Kneser–Ney (with <unk> removed and the rest renormalized) has a perplexity of 15.7115.71 per word token and 1.5131.513 per character. Nothing about the model changed between the two numbers, only the count we divided by.

Theorem 5 (Tokenization invariance).

Let PP be a distribution on strings, each ending in an end mark, and let τ\tau be an injective tokenizer from strings to token sequences. The token model Qτ(t)=P(τ−1(t))Q_\tau(t) = P(\tau^{-1}(t)) satisfies log⁡Qτ(τ(s))=log⁡P(s)\log Q_\tau(\tau(s)) = \log P(s) for every string ss. Consequently, for a text TT and any two units AA and BB occurring nAn_A and nBn_B times in it,

nAlog⁡PPA  =  nBlog⁡PPB  =  −log⁡P(T),n_A \log \mathrm{PP}_A \;=\; n_B \log \mathrm{PP}_B \;=\; -\log P(T),

and every unit whose count does not depend on the model (characters, bytes, word tokens) ranks any set of models identically.

Proof.

The chain rule over tokens multiplies the conditionals of the single distribution QτQ_\tau, the image of PP under τ\tau. Because τ\tau is injective, the string ss corresponds to the one token sequence τ(s)\tau(s), so Qτ(τ(s))=P(s)Q_\tau(\tau(s)) = P(s). The unit identity is NLL=nunit⋅(NLL/nunit)\mathrm{NLL} = n_{\text{unit}} \cdot (\mathrm{NLL}/n_{\text{unit}}) for each unit. A unit whose count is the same for every model divides every model’s total by one constant, which preserves the order.

∎

The theorem is close to bookkeeping, and its force is in what it rules out. A per-token perplexity divides a model’s total by the number of tokens its own tokenizer produced. Two models with different tokenizers divide by different numbers, so their per-token perplexities measure model quality and token length together.

The construction behind it shows that a word model really is a character model. Let Q′Q' be the word model with <unk> removed and renormalized, a proper distribution on sentences of in-vocabulary words. After a context uu, the words beginning with a partial word π\pi form a contiguous block of the sorted vocabulary, with total probability

M(π)=∑w begins with πQ′(w∣u).M(\pi) = \sum_{w \text{ begins with } \pi} Q'(w \mid u).

The next letter cc then has probability M(πc)/M(π)M(\pi c)/M(\pi). Write s(u)s(u) for the probability Q′Q' gives </s> after the context uu. The character after a complete word ww is its separator, with

P(sentence end∣w)=Q′(w∣u)M(w) s(u′),P(space∣w)=Q′(w∣u)M(w) (1−s(u′)),P(\text{sentence end} \mid w) = \frac{Q'(w \mid u)}{M(w)}\, s(u'), \qquad P(\text{space} \mid w) = \frac{Q'(w \mid u)}{M(w)}\,\bigl(1 - s(u')\bigr),

where u′u' is the context after ww. After a space the next word cannot be </s>, so the first letter is normalized by 1−s(u)1 - s(u) instead of 11. Each word’s factors telescope to Q′(w∣u)Q'(w \mid u), and the separators carry the decisions to stop. On all 1,9031{,}903 sentences, the character factorization and the word factorization agree to 10−910^{-9}. The character view also shows where a model spends its bits. In halvorsen reported revenue …, the first letter of halvorsen costs 4.804.80 bits and the next eight cost almost nothing. The first letter of reported costs 4.984.98.

Now compare models built on different tokenizers. Each row is a Kneser–Ney model of the order shown, scored on the same held-out text:

modeltokens per characternats per tokenperplexity per tokenbits per characterperplexity per word token
character 3-gram1.00001.00001.71461.71465.5555.5552.47372.473796,77296{,}772
character 5-gram1.00001.00000.69130.69131.9961.9960.99740.9974102.4102.4
character 7-gram1.00001.00000.50950.50951.665\mathbf{1.665}0.73510.735130.3130.31
BPE, ∣V∣=100\lvert V \rvert = 100, 5-gram0.65750.65750.76280.76282.1442.1440.72360.723628.7328.73
BPE, ∣V∣=400\lvert V \rvert = 400, 5-gram0.44330.44331.03981.03982.8292.8290.66500.665021.8921.89
BPE, ∣V∣=1,870\lvert V \rvert = 1{,}870, 5-gram0.29500.29501.52351.52354.5884.5880.64830.648320.2620.26
word trigram, open vocabulary0.14940.14942.95672.956719.2319.230.6371\mathbf{0.6371}19.2319.23
word trigram, <unk> as one event — not a code0.14940.14942.85512.855117.3817.38(0.61520.6152)17.3817.38

The BPE vocabularies are the subword topic’s tokenizer, and 1,8701{,}870 pieces is the minimum of its two-part description length. Per-token perplexity calls the character 77-gram the best model by a wide margin. In bits per character it ranks fifth of seven, and the open word trigram ranks first. Bits per character and perplexity per word token order the models identically, as Theorem 5 requires. Per-token perplexity rewards short tokens: a token that carries less of the text is easier to predict. The models also see different amounts of context — 66 characters for the 77-gram, about 1313 for both the word trigram and the largest BPE model — so the table compares models as built, not tokenizers in isolation.

The last row is not a code at all, which is the next point.

Proposition 5 (The unknown-word convention can only flatter).

Let a closed-vocabulary model give the symbol <unk> probability qunk(u)q_{\mathrm{unk}}(u) after a context uu, and let an open completion spell each out-of-vocabulary word ww with probability S(w∣⋅)S(w \mid \cdot), where ∑wS(w∣⋅)≤1\sum_w S(w \mid \cdot) \le 1. Then

−log⁡Qopen(text)=−log⁡Qclosed(text)−∑OOV wordslog⁡S(w∣⋅)  ≥  −log⁡Qclosed(text).-\log Q_{\text{open}}(\text{text}) = -\log Q_{\text{closed}}(\text{text}) - \sum_{\text{OOV words}} \log S(w \mid \cdot) \;\ge\; -\log Q_{\text{closed}}(\text{text}).

The closed score is not the length of any code for the text, because it gives one probability to infinitely many different strings.

Proof.

The open model’s probability of the text is the closed model’s probability times one spelling factor for each out-of-vocabulary word, and each factor is at most one. Two texts that differ only in their unknown words receive the same closed probability. There are infinitely many unknown words, so each text with one has infinitely many such siblings, all with the same positive closed probability, and the closed probabilities summed over texts diverge. By Theorem 3, the lengths of any uniquely decodable code satisfy ∑2−ℓ≤1\sum 2^{-\ell} \le 1, so no such code has lengths −log⁡2Qclosed-\log_2 Q_{\text{closed}}. (A sum below one would not have ruled out a code: by Proposition 4, compressors are sub-probability models.)

∎

How much the convention flatters depends on how many words it hides. Send every word seen at most kk times in training to <unk>, refit interpolated Kneser–Ney, and train the speller on the training occurrences of those words:

kk∣Vk∣\lvert V_k \rvertout-of-vocabulary tokensperplexity per token, closedbits per character, openEDGAR, closed perplexityEDGAR, open bpc
00 (the n-gram topic’s VV)3,4273{,}4270.67%0.67\%17.3817.380.63710.63716,6106{,}6105.66055.6605
111,5501{,}5509.13%9.13\%7.997.990.74830.7483176.2176.24.85984.8598
4487987913.14%13.14\%5.365.360.79540.7954138.1138.14.86704.8670
161648348316.37%16.37\%4.354.350.88270.882793.2493.244.42444.4244
646421721727.35%27.35\%3.693.691.25941.259429.4229.423.91033.9103
all words2291.11%91.11\%1.33\mathbf{1.33}2.53392.53391.211.213.67603.6760

In domain, every step down in vocabulary lowers the closed perplexity and lengthens the honest code. A model that knows no words at all, and predicts only <unk> or </s>, reports a perplexity of 1.331.33. On EDGAR the honest code instead falls from 5.665.66 to 3.683.68 bits per character as the cutoff rises, though not at every step. Out of domain, the word model’s vocabulary is worth less than a speller trained on more words.


Coding a sentence, choosing a unit

The laboratory makes the last two sections visible. In panel A, pick a sentence and a smoother, then step through the symbols. Each row is the current interval, stretched to full width and cut into the slices of the likeliest next symbols. The chosen slice becomes the next row. The ticker below shows the bits of the codeword that are already settled. Under interpolated Kneser–Ney the in-domain sentence’s codeword is 1616 bits, and Laplace smoothing’s is 6060. In the second sentence, the unknown word nonroyaltys (the subword topic’s running example) costs 35.935.9 of the 64.564.5 bits the model gives the sentence, whose codeword is 6565 bits: 14.614.6 for <unk> and 21.321.3 for its letters. On the EDGAR sentence the smoothers trade places. Panel B ranks the table’s models by the unit you choose, and its slider moves the unknown-word cutoff: the closed perplexity falls toward one while the honest code grows.

A · Arithmetic-code a sentence — each symbol keeps its slice of the interval

halvorsen reported revenue of million for the second quarter (61 characters)

thehalvorsen4.85 bits
−log₂ Q so far
4.851 bits
codeword bits already settled
4
final codeword (whole sentence)
16 bits vs −log₂ Q = 14.71
symbol by symbol (Shannon codes)
23 bits
0101101111111001

Rows show the last 6 symbols. Hollow slices are the likeliest alternatives, placed where they sit in the interval; shaded rows are the speller at work on an unknown word. The whole held-out text under interpolated KN is one codeword of 98,345 bits (0.6371 bits per character).


B · Pick a unit — the same eight models, ranked by perplexity per token
#1 character 7-gram1.665#2 character 5-gram1.996#3 BPE |V| = 100, 5-gram2.144#4 BPE |V| = 400, 5-gram2.829#5 BPE |V| = 1,870, 5-gram4.588#6 character 3-gram5.555#7 word trigram, ⟨unk⟩ closed17.375 (not a code)#8 word trigram, open19.235

Lower is better (log scale). Per-token perplexity divides by each model's own token count; bits per character and perplexity per word token divide every model by the same count, so they always agree. The open word model's bits per character is its arithmetic code: 98,345 bits for 154,362 characters.

k = 0k = 1k = 4k = 16k = 64k = all12510200.01.02.0closed perplexity per token (log)open bits per character
vocabulary |V_k|
3,427
tokens sent to ⟨unk⟩
0.67%
closed perplexity per token
17.38
honest code, bits per character
0.6371

A perplexity above |V| = 3,427 is worse than a uniform guess over the vocabulary. The codeword lengths are exact (big-integer arithmetic coding); "closed" scores count every unknown word as one event and are not code lengths.


Finance case study: out of domain, the zip file wins


Where this goes next

  • Neural language models. They are trained by minimizing exactly the cross-entropy of Corollary 1, and reported in perplexity per token of their own tokenizer, which Theorem 5 says to convert before comparing.
  • Scaling laws. Loss-versus-compute curves are fit in nats per token. Theorem 5 says such curves are comparable only within one tokenizer; across tokenizers, a tokenizer-free unit is needed. The fits themselves are empirical.
  • Adaptive prediction. lzma’s EDGAR win is a model that learns from the text it is coding. Cache models, neural models with long contexts, and in-context learning are increasingly capable versions of the same idea.
  • Calibration and testing. Strict propriety says the log score rewards honest probabilities on average; the calibration topic asks whether a model’s probabilities are honest event by event. Differences like −0.0143±0.0006-0.0143 \pm 0.0006 are the raw material of the significance-testing topic.

Honest caveats


Implementation

The companion notebook (notebookPath) imports perplexity_cross_entropy.py, which owns every number on this page and imports the n-gram topic’s smoothers, the subword topic’s BPE, and the shared finance corpus. Running it as a script executes a harness of 2323 assertion-based tests in under twenty seconds on a laptop CPU. The tests cover:

  • Proposition 1 against SciPy’s entropy and divergence, Corollary 1, Proposition 2, and the out-of-domain comparison with the uniform model.
  • Theorem 1 exactly, by summing over type classes, on random sources, for the model version as well.
  • Theorem 2 against exact targets from absorbing-chain algebra, the coverage of its intervals, and the corpus standard errors; the Shannon–McMillan–Breiman limits on Markov chains; Corollary 2 by exact enumeration.
  • Kraft’s inequality both ways, Theorem 3 exhaustively with Sardinas–Patterson cross-checked by brute force, and Proposition 3 on random pairs.
  • Theorem 4 on random models, and on the whole held-out and EDGAR texts, decoded back exactly.
  • The vectorized models against the n-gram topic’s scalar recursions, Theorem 5’s character factorization on every in-vocabulary sentence, the unit table, Proposition 5 and the cutoff table, and the finance case study.

The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.

References & Further Reading