Language Modeling as Compression
Cross-entropy, bits per byte and arithmetic coding with a language model.
Whenever a language model assigns probability to a text, it implicitly promises to store that text in 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 .
- 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 , the expected codeword length is at least the entropy in bits, and a code designed for a model instead of costs the cross-entropy , the extra term being the price of the model's mistakes. For a text, the ideal code length under a language model is
Two questions remain. Can a real code achieve , when codewords have whole numbers of bits and language models put probabilities near 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 , whose ideal cost is bits. And what does it cost to send 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 . Start from the interval . 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:
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.
Let be the midpoint truncated to bits. Truncation loses less than , and was chosen so that :
Every binary string that begins with the codeword is a number in , and that whole dyadic interval lies inside the text's interval:
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.
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 , , after a or a ): 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 tokens, bytes and a mean loss of nats per token:
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 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.)
A model's validation loss is nats per token, and its tokenizer produces tokens per byte of this text. What is its loss in bits per byte?
Show the answer
0.94 bits/byte
. In bits per token the loss is , and four bytes share each token. A per-token perplexity of looks very different from 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 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:
| Predictor | Text | Bits per character |
|---|---|---|
| uniform over letters and space | any | 4.75 |
| single-letter frequencies (Shannon, 1951) | English, letters and space | 4.03 |
| human guessing with 100 letters of context (Shannon, 1951) | literary English | 0.6 to 1.3 |
| human gambling (Cover & King, 1978) | English | about 1.3 |
| GPT-2 1.5B, zero-shot (Radford et al., 2019) | text8, from Wikipedia | 0.98 |
| LLaMA-7B (Valmeekam et al., 2023, preprint) | 1 MB of text8 | 0.71 |
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 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.
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.
Two-part code. Send the parameters, then the data coded with them. A network of parameters stored in 16 bits costs bits before a single token is sent:
Mixture code. Put a prior on a countable set of models, so that plays the role of the cost of describing , 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:
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:
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:
| Code | MNIST: bits for the labels | MNIST test accuracy | CIFAR-10: bits for the labels | CIFAR-10 test accuracy |
|---|---|---|---|---|
| uniform | 199 k | 10% | 166 k | 10% |
| two-part, float32 weights | over 8.6 M | 98.4% | over 428 M | 92.9% |
| variational | 22.2 k | 98.2% | 89.0 k | 66.5% |
| prequential | 4.10 k | 99.5% | 45.3 k | 93.3% |
Key takeaways
- Under a model a text costs 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, , 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.
A language model assigns probability to a document that ends with an end-of-text token. How long is its arithmetic codeword under this lesson's construction?
- 37 bits
- 38 bits
- 39 bits
- About 2 bits per token of the document
Show the answer
C. 39 bits
bits: one bit of rounding up and one bit of margin, never more than 2 bits above the ideal , however long the document.
On the same text, model A reports perplexity with a tokenizer that produces tokens per byte, and model B reports perplexity with a larger vocabulary that produces tokens per byte. Which model assigns the text the shorter code?
- A, because its perplexity is lower
- B, at about bits per byte against A's
- Neither: both are at about one bit per byte
- It cannot be decided without the vocabulary sizes
Show the answer
B. B, at about bits per byte against A's
Bits per byte is tokens per byte times bits per token: for A and for B. Each of B's tokens is harder to predict, but there are fewer of them.
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?
- The adjusted rate counts the model's 140 GB of 16-bit parameters as part of the compressed output
- Arithmetic coding adds two bits per token
- Its 2,048-token context forces the data into short chunks
- 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.
In a prequential (online) code for a neural network, what takes the place of transmitting the trained parameters?
- The parameters are quantized to a few bits each and sent
- Only the final layer is transmitted
- A Bayesian posterior over the parameters is transmitted instead
- 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).