Simple Algorithm
Deep Learning · Emergence · 26 min

Language Modeling as Compression

Cross-entropy, bits per byte and arithmetic coding with a language model.

Whenever a language model assigns probability pp to a text, it implicitly promises to store that text in −log⁡2p-\log_2p bits, and arithmetic coding keeps the promise to within two bits. That one fact turns cross-entropy into file size, makes bits per byte the honest way to compare models with different tokenizers, and lets a model trained mostly on text compress images and audio. It also raises the question every compressor must answer: who pays for the decompressor?

What you’ll learn

  • Relate cross-entropy to code length, and derive arithmetic coding's interval-narrowing construction and its bound of fewer than two bits above −log⁡2q(x)-\log_2q(\mathbf x).
  • Convert a per-token loss into bits per byte, and explain why bits per byte, unlike perplexity, does not depend on the tokenizer.
  • Place language models among estimates of the entropy of English, from Shannon's 1951 prediction experiments to modern models.
  • Explain why a compressor's own size must be counted, and compare two-part, Bayesian-mixture and prequential codes with the results of Delétang et al. (2024) and Blier and Ollivier (2018).
  • Assess what compression does and does not tell you about generalization and capability.

A log-loss is a code length

A lossless code maps every possible message to a binary codeword that can be decoded unambiguously. Shannon's source coding theorem, proved in the Artificial Intelligence course's lesson Information Theory for AI, says what such codes can achieve: for messages drawn from pp, the expected codeword length is at least the entropy H(p)H(p) in bits, and a code designed for a model qq instead of pp costs the cross-entropy H(p)+DKL(p ∥ q)H(p)+\KL(p\,\|\,q), the extra term being the price of the model's mistakes. For a text, the ideal code length under a language model qq is

ℓq(x)=−log⁡2q(x1,…,xn)=∑t=1n−log⁡2q(xt∣x<t)=n ℓˉln⁡2 bits\ell_q(\mathbf x)=-\log_2q(x_1,\dots,x_n)=\sum_{t=1}^{n}-\log_2q(x_t\mid x_{<t})=\frac{n\,\bar\ell}{\ln2}\ \text{bits}
The chain rule makes the code length a sum over tokens, and the sum is the training loss: nn tokens at a mean loss of ℓˉ\bar\ell nats cost nℓˉ/ln⁡2n\bar\ell/\ln2 bits. Minimizing next-token cross-entropy and minimizing file size are the same optimization.

Two questions remain. Can a real code achieve −log⁡2q(x)-\log_2q(\mathbf x), when codewords have whole numbers of bits and language models put probabilities near 11 on many tokens? A Huffman code, which gives each token its own codeword, spends at least one bit per token even on a token of probability 0.990.99, whose ideal cost is 0.01450.0145 bits. And what does it cost to send qq itself? Arithmetic coding answers the first question; the last step of this lesson takes up the second.

Arithmetic coding

Arithmetic coding, developed in the late 1970s and made practical by Witten, Neal and Cleary (1987), encodes a whole text as one number in [0,1)[0,1). Start from the interval [0,1)[0,1). For each token, divide the current interval into one slice per vocabulary entry, in a fixed order, with widths proportional to the model's conditional probabilities, and keep the slice of the token that actually occurs:

at=at−1+wt−1 Ft(xt),wt=wt−1 q(xt∣x<t),Ft(v)=∑u≺vq(u∣x<t)a_t=a_{t-1}+w_{t-1}\,F_t(x_t),\qquad w_t=w_{t-1}\,q(x_t\mid x_{<t}),\qquad F_t(v)=\sum_{u\prec v}q(u\mid x_{<t})
ata_t is the left end and wtw_t the width after tt tokens, starting from a0=0a_0=0 and w0=1w_0=1; Ft(v)F_t(v) is the probability of all tokens ordered before vv. After the whole text the width is wn=∏tq(xt∣x<t)=q(x)w_n=\prod_tq(x_t\mid x_{<t})=q(\mathbf x): likely texts keep wide intervals, and wide intervals need few bits to pin down.
DerivationProof
  1. [an, an+wn) ∩ [an′, an′+wn′)=∅for x≠x′[a_n,\,a_n+w_n)\ \cap\ [a_n',\,a_n'+w_n')=\varnothing\qquad\text{for }\mathbf x\ne\mathbf x'

    Distinct texts get disjoint final intervals: at the first token where two texts differ they fall into different slices, and later steps only shrink each interval inside its slice.

  2. an+wn2−2−k<z≤an+wn2,2−k≤wn2a_n+\tfrac{w_n}{2}-2^{-k}<z\le a_n+\tfrac{w_n}{2},\qquad2^{-k}\le\tfrac{w_n}{2}

    Let zz be the midpoint truncated to kk bits. Truncation loses less than 2−k2^{-k}, and kk was chosen so that 2−k≤wn/22^{-k}\le w_n/2:

  3. an<zandz+2−k≤an+wn⟹[z, z+2−k)⊂[an, an+wn)a_n<z\quad\text{and}\quad z+2^{-k}\le a_n+w_n\quad\Longrightarrow\quad[z,\,z+2^{-k})\subset[a_n,\,a_n+w_n)

    Every binary string that begins with the codeword is a number in [z,z+2−k)[z,z+2^{-k}), and that whole dyadic interval lies inside the text's interval:

  4. k=⌈−log⁡2q(x)⌉+1 < −log⁡2q(x)+2k=\lceil-\log_2q(\mathbf x)\rceil+1\ <\ -\log_2q(\mathbf x)+2

    If one codeword were a prefix of another, the longer one's dyadic interval would lie inside the shorter one's, and the two texts' intervals would overlap, which the first step rules out. The decoder rebuilds the slices with the same model and reads off, position by position, the token whose slice contains the codeword.

python
import math
from fractions import Fraction

def encode(seq, model):
    """model(prefix) -> {symbol: Fraction probability}, in a fixed symbol order."""
    low, width = Fraction(0), Fraction(1)
    for t, s in enumerate(seq):
        cum = Fraction(0)
        for sym, p in model(seq[:t]).items():
            if sym == s:                                 # narrow to this symbol's slice
                low, width = low + width * cum, width * p
                break
            cum += p
    k = math.ceil(-math.log2(width)) + 1                 # codeword length in bits
    z = math.floor((low + width / 2) * pow(2, k))        # midpoint, truncated to k bits
    return format(z, '0%db' % k)                         # [z, z + 1) / 2^k lies inside [low, low + width)

On the example above it returns 010. Extend the example's model to longer strings (back to 0.50.5, 0.30.3, 0.20.2 after a bb or a cc): the codewords of all 27 strings of three symbols are prefix-free, and so are those of all 81 strings of four, each 1 to 2 bits above the ideal length. Pooling the two lengths breaks this, because a three-symbol string's interval contains those of its extensions; an end-of-text symbol, as in the proposition, makes the codewords of all lengths prefix-free. Practical coders use fixed-precision integers and emit leading bits as soon as they are settled, at a small cost in length. The decoder must reproduce the model's probabilities exactly, bit for bit, a real constraint for neural compressors whose floating-point results can differ across hardware.

Bits per byte, and the entropy of English

Divide the code length of a text by its length in UTF-8 bytes and you get its bits per byte (BPB). With LTL_T tokens, LBL_B bytes and a mean loss of ℓˉ\bar\ell nats per token:

BPB=1LB∑t=1LT−log⁡2q(xt∣x<t)=LTLB⋅ℓˉln⁡2\mathrm{BPB}=\frac{1}{L_B}\sum_{t=1}^{L_T}-\log_2q(x_t\mid x_{<t})=\frac{L_T}{L_B}\cdot\frac{\bar\ell}{\ln2}
The Pile made it its main metric because it does not depend on the tokenization scheme (Gao et al., 2020); for GPT-2's tokenizer, LT/LB=0.293L_T/L_B=0.293 across the Pile. On the Pile's test set, bits per byte fell from 1.23 for the smallest GPT-2 to 0.72 for the largest GPT-3.

Why is bits per byte free of the tokenizer when perplexity is not? A tokenizer is a fixed, invertible map from bytes to tokens, so the probability a model gives to a token sequence is also a probability for the bytes it spells, and −log⁡2-\log_2 of it is a code length for those bytes. Models with different tokenizers can therefore be compared by the bits they need for the same bytes, while per-token quantities divide that total by different token counts. (Strictly, a model also gives some probability to other token sequences that spell the same bytes; scoring only the tokenizer's own segmentation is still a valid code, slightly longer than necessary.)

Predict before you look

A model's validation loss is 2.62.6 nats per token, and its tokenizer produces 0.250.25 tokens per byte of this text. What is its loss in bits per byte?

Show the answer

0.94 bits/byte

BPB=0.25×2.6/ln⁡2≈0.94\mathrm{BPB}=0.25\times2.6/\ln2\approx0.94. In bits per token the loss is 2.6/ln⁡2≈3.752.6/\ln2\approx3.75, and four bytes share each token. A per-token perplexity of e2.6≈13.5e^{2.6}\approx13.5 looks very different from 20.94≈1.92^{0.94}\approx1.9 per byte, although both describe the same code.

How much information is in English? Shannon (1951) had people guess the next letter of English text, letters and space only, with up to 100 preceding letters visible, and turned the statistics of their guesses into bounds on the entropy. With 100 letters of context the bounds were 0.6 and 1.3 bits per letter, "of the order of one bit per letter" with a redundancy of "roughly 75%" in his words, where a uniformly random choice among the 27 symbols would cost log⁡227≈4.75\log_227\approx4.75 bits. A model's cross-entropy on text from a source bounds the source's entropy rate from above, since cross-entropy is entropy plus a KL divergence, so every better language model gives a tighter upper bound:

PredictorTextBits per character
uniform over letters and spaceany4.75
single-letter frequencies (Shannon, 1951)English, letters and space4.03
human guessing with 100 letters of context (Shannon, 1951)literary English0.6 to 1.3
human gambling (Cover & King, 1978)Englishabout 1.3
GPT-2 1.5B, zero-shot (Radford et al., 2019)text8, from Wikipedia0.98
LLaMA-7B (Valmeekam et al., 2023, preprint)1 MB of text80.71
The texts and alphabets differ, so the rows are not a strict ranking, and a single text gives an estimate, not the expectation the bound is about. LLaMA's training data probably included Wikipedia, the source of text8, so its authors call the 0.71 optimistic. GPT-2's largest model also reached 0.93 bits per byte on enwik8, raw Wikipedia markup, without being trained on it.

Who pays for the decompressor?

A compressor's real output is the compressed file plus whatever the receiver needs to decode it. For gzip that is a small program; for a language model it is the model. Delétang et al. (2024) made the accounting explicit. Used with arithmetic coding on 2,048-byte chunks, Chinchilla 70B compressed 1 GB of enwik9, the first 10910^9 bytes of an English Wikipedia dump, to 8.3% of its size, against 32.3% for gzip and 23.0% for LZMA2 run on the whole file. It also beat PNG on ImageNet image patches and FLAC on LibriSpeech audio, although it was trained mostly on text. Counting its parameters changes everything: at two bytes per parameter the model takes 140 GB, and its adjusted rate on enwik9 is 14,008%.

With small transformers trained on enwik8 they found that each dataset size has its own optimal model size, the larger the data the more parameters it can afford, so for compression, scaling the model has a ceiling set by the data. They also found that tokenization, itself a kind of pre-compression, did not in general improve compression rates, although it lets more information fit into the context.

Predict before you look

A model with 1 billion parameters, stored in 16-bit precision, compresses a 10 GB corpus to 10% of its raw size. What is its adjusted compression rate, counting the model as part of the output, in percent?

Show the answer

30 %

The compressed data take 1 GB and the model 2 GB, so the receiver needs 3 GB for 10 GB of text: 30%. Doubling the corpus to 20 GB at the same raw rate would bring this to 20%; the model's fixed cost is amortized only over large data.

DerivationThree ways to pay for a model
  1. L2-part(x)=L(θ)+(−log⁡2pθ(x))L_{\text{2-part}}(\mathbf x)=L(\boldsymbol\theta)+\big(-\log_2p_{\boldsymbol\theta}(\mathbf x)\big)

    Two-part code. Send the parameters, then the data coded with them. A network of NN parameters stored in 16 bits costs 16N16N bits before a single token is sent:

  2. pmix(x)=∑θπ(θ) pθ(x) ≥ π(θ⋆) pθ⋆(x)⟹−log⁡2pmix(x)≤−log⁡2π(θ⋆)−log⁡2pθ⋆(x)p_{\text{mix}}(\mathbf x)=\sum_{\boldsymbol\theta}\pi(\boldsymbol\theta)\,p_{\boldsymbol\theta}(\mathbf x)\ \ge\ \pi(\boldsymbol\theta^\star)\,p_{\boldsymbol\theta^\star}(\mathbf x)\quad\Longrightarrow\quad-\log_2p_{\text{mix}}(\mathbf x)\le-\log_2\pi(\boldsymbol\theta^\star)-\log_2p_{\boldsymbol\theta^\star}(\mathbf x)

    Mixture code. Put a prior π\pi on a countable set of models, so that −log⁡2π(θ)-\log_2\pi(\boldsymbol\theta) plays the role of the cost of describing θ\boldsymbol\theta, and code with the mixture. A sum of nonnegative terms is at least each of its terms, so the mixture is never longer than the best two-part code built on the same prior:

  3. −log⁡2pmix(x1:n)=∑t=1n−log⁡2pmix(xt∣x<t),pmix(xt∣x<t)=∑θπ(θ∣x<t) pθ(xt∣x<t)-\log_2p_{\text{mix}}(x_{1:n})=\sum_{t=1}^{n}-\log_2p_{\text{mix}}(x_t\mid x_{<t}),\qquad p_{\text{mix}}(x_t\mid x_{<t})=\sum_{\boldsymbol\theta}\pi(\boldsymbol\theta\mid x_{<t})\,p_{\boldsymbol\theta}(x_t\mid x_{<t})

    Prequential code. By the chain rule, the mixture code is itself a sum of online losses: each item is coded with the posterior predictive distribution given everything before it, the prequential view of Dawid (1984). No parameter is ever sent; the decoder recomputes each predictive distribution from what it has already decoded:

  4. Lpreq=Lfirst block+∑s−log⁡2pθ^(x1:ts)(xts+1:ts+1)L_{\text{preq}}=L_{\text{first block}}+\sum_{s}-\log_2p_{\hat{\boldsymbol\theta}(x_{1:t_s})}\big(x_{t_s+1:t_{s+1}}\big)

    Neural prequential code (Blier & Ollivier, 2018). Replace the posterior predictive with training. Code the first block with a fixed default model, train on it, code the next block with the trained network, retrain on everything decoded so far, and so on. With a shared random seed the decoder reproduces every training run, so the code is valid, and its length is the area under the model's learning curve:

CodeMNIST: bits for the labelsMNIST test accuracyCIFAR-10: bits for the labelsCIFAR-10 test accuracy
uniform199 k10%166 k10%
two-part, float32 weightsover 8.6 M98.4%over 428 M92.9%
variational22.2 k98.2%89.0 k66.5%
prequential4.10 k99.5%45.3 k93.3%
Code lengths of the training labels given the images, including the cost of the model (Blier & Ollivier, 2018). The uniform code spends log⁡210\log_210 bits per label. Sending float32 weights costs far more than the labels themselves; variational codes, built to minimize a description length, were surprisingly poor, and on CIFAR-10 the best one came from a small model with low accuracy; prequential codes compressed the labels to 2% (MNIST) and 27% (CIFAR-10) of the uniform cost, with models that also generalized well. The variational and prequential rows report the model with the shortest code, not the best accuracy; the two-part row counts only the weights of a published network, so it is a lower bound. The numbers are the paper's Table 1; its text and its Table 2 give the variational code as 24.1 k at 95.5% on MNIST and 61.6% on CIFAR-10.

Key takeaways

  • Under a model qq a text costs −log⁡2q(x)=∑t−log⁡2q(xt∣x<t)-\log_2q(\mathbf x)=\sum_t-\log_2q(x_t\mid x_{<t}) bits: the training loss is a file size. Arithmetic coding achieves it to within 2 bits for the whole text by narrowing an interval by each token's probability.
  • Bits per byte, (LT/LB) ℓˉ/ln⁡2(L_T/L_B)\,\bar\ell/\ln2, is the code length per byte of text and does not depend on the tokenizer; perplexity does, and a lower perplexity can mean a longer code.
  • Shannon bounded the entropy of English between 0.6 and 1.3 bits per letter with 100 letters of context; language models give upper bounds directly, below one bit per character on Wikipedia benchmarks.
  • A compressor must pay for itself. Two-part codes pay for the parameters, a Bayesian mixture is never longer than the two-part code built on the same prior, and a prequential code pays only the cumulative online loss, which compressed MNIST's labels to 2% of the uniform cost.
  • Compression ties to generalization through prequential and description-length arguments, and it tracks benchmark scores across language models; that is a correlation under particular accounting choices, not proof that compression is capability.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A language model assigns probability 2−37.22^{-37.2} to a document that ends with an end-of-text token. How long is its arithmetic codeword under this lesson's construction?

  1. 37 bits
  2. 38 bits
  3. 39 bits
  4. About 2 bits per token of the document
Show the answer

C. 39 bits

k=⌈37.2⌉+1=39k=\lceil37.2\rceil+1=39 bits: one bit of rounding up and one bit of margin, never more than 2 bits above the ideal 37.237.2, however long the document.

Question 2

On the same text, model A reports perplexity 1212 with a tokenizer that produces 0.300.30 tokens per byte, and model B reports perplexity 2020 with a larger vocabulary that produces 0.240.24 tokens per byte. Which model assigns the text the shorter code?

  1. A, because its perplexity is lower
  2. B, at about 1.041.04 bits per byte against A's 1.081.08
  3. Neither: both are at about one bit per byte
  4. It cannot be decided without the vocabulary sizes
Show the answer

B. B, at about 1.041.04 bits per byte against A's 1.081.08

Bits per byte is tokens per byte times bits per token: 0.30×log⁡212≈1.080.30\times\log_212\approx1.08 for A and 0.24×log⁡220≈1.040.24\times\log_220\approx1.04 for B. Each of B's tokens is harder to predict, but there are fewer of them.

Question 3

Delétang et al. (2024) report that Chinchilla 70B compresses 1 GB of enwik9 to 8.3% of its size, yet its "adjusted" compression rate on the same data exceeds 14,000%. Why?

  1. The adjusted rate counts the model's 140 GB of 16-bit parameters as part of the compressed output
  2. Arithmetic coding adds two bits per token
  3. Its 2,048-token context forces the data into short chunks
  4. The adjusted rate is measured on images and audio, which the model was not trained on
Show the answer

A. The adjusted rate counts the model's 140 GB of 16-bit parameters as part of the compressed output

Seventy billion parameters at two bytes each are 140 GB, 140 times the 1 GB of data: 14,000 percentage points on top of the 8.3%. A large model pays for itself only on data far larger than its own description.

Question 4

In a prequential (online) code for a neural network, what takes the place of transmitting the trained parameters?

  1. The parameters are quantized to a few bits each and sent
  2. Only the final layer is transmitted
  3. A Bayesian posterior over the parameters is transmitted instead
  4. The decoder retrains the same model with the same seed on the data decoded so far, and each new block is paid for at its online log-loss
Show the answer

D. The decoder retrains the same model with the same seed on the data decoded so far, and each new block is paid for at its online log-loss

Encoder and decoder run the same deterministic training on the same prefix, so they agree on the model that encodes the next block. The code length is the sum of the online losses, the area under the learning curve; no parameter is ever sent.

Further reading

  • C. E. Shannon, "Prediction and entropy of printed English," Bell System Technical Journal 30 (1951).
  • I. H. Witten, R. M. Neal & J. G. Cleary, "Arithmetic coding for data compression," Communications of the ACM 30 (1987).
  • G. Delétang et al., "Language modeling is compression," ICLR (2024).
  • L. Blier & Y. Ollivier, "The description length of deep learning models," NeurIPS (2018).
  • T. M. Cover & J. A. Thomas, Elements of Information Theory, 2nd ed. (Wiley, 2006).