Module contents
Lesson 8 of 19Advanced 110 min

A language model is a compressor

Connect language modeling and lossless compression, compare perplexity and bits per byte, account for model cost, and analyze compression-based similarity.

After this lesson you can

  • Prove the connection between arithmetic-code length and accumulated language-model log loss.
  • Convert between nats per token, perplexity, and bits per byte and explain tokenization effects.
  • Compare compression with a pretrained language model and conventional compressors including model cost.
  • Use normalized compression distance and analyze its limitations.
  • Relate Shannon's guessing game to language entropy estimates.

Before you start

Motivation: an LM’s loss is a code length

In 2006 Marcus Hutter offered a prize for better compression of an English Wikipedia dump. Since 2020 the file has been enwik9, of 10910^9 bytes, the prize fund is €500 000, and the interesting rule is that size counts both the compressed file and its decompression program. Hutter’s wager is that compressing human text to its limit requires understanding it: spending few bits on the next word calls for grammar, world knowledge, and arithmetic.

Seventeen years later, Delétang and coauthors (DeepMind, 2023) turned the idea around in a provocatively titled paper, “Language Modeling Is Compression.” Their central observation is an identity, not an analogy: a language model assigning probabilities q(xt∣x<t)q(x_t \given x_{<t}) coupled to an arithmetic coder is a lossless compressor, and its output length is, within two bits, the sum of surprises −log⁡2q(xt∣x<t)-\log_2 q(x_t \given x_{<t}). That is training cross-entropy times token count. Using text-trained Chinchilla 70B, they compressed ImageNet patches to 43.4% and LibriSpeech audio to 16.4% of original size, ahead of PNG (58.5%) and FLAC (30.3%).

For a number we measured: Qwen2.5-0.5B-Instruct (494 million parameters; Qwen2.5-0.5B below) turns the 357-byte paragraph shown later into 417 bits, about 52 bytes. gzip -9 yields 262 bytes. But the model occupies almost a gigabyte. This lesson turns those figures into theory:

  • Why prediction and compression are the same problem in both directions, with exact bounds.
  • How to measure a model as a compressor (perplexity, bits per byte), and why perplexity misleads across tokenizers.
  • What actual LM compression requires: bitwise determinism, precision, context, and model cost.
  • How a compressor serves as a similarity measure (normalized compression distance), and when it gives absurd results.

Intuition: guessing is compression

Before language models, Claude Shannon measured English information using people. In “Prediction and Entropy of Printed English” (1951), he asked a subject to guess text letter by letter, knowing everything earlier, and recorded attempts per position. A fluent subject gets most letters first try, yielding attempt sequences resembling 1 1 1 5 1 1 2 1 1 1 ....

InteractiveShannon's guessing game
youmodel
?
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
·
Letter 1 of 42.
Frequency of success on attempt i
0.000.25123456789+
  • you (0 letters)
  • order-3 context model (whole phrase)
Your bounds (bits per letter)no data
Model bounds (whole phrase)2.06 to 2.79
Model mean −log₂ q3.35
Without model: log₂ 284.81
Guess the sentence letter by letter (27 letters and the space, without accents). Under each letter are your attempts and the model's, which is the correct letter's rank in its distribution. The histogram compares frequencies qiq_i of success on attempt ii, and readouts give Shannon bounds calculated from them. Try the proverb: once you recognize ‘más vale’, your attempts plummet while the model's do not. Compare the technical sentence, more like its training material.

Attempt counts are a reversible encoding of the text. Imagine an identical twin with the subject’s deterministic brain. Given only counts, the twin reconstructs the sentence: at each position it makes the same guesses in the same order and keeps the one at the indicated rank. Text and attempts carry the same information; the latter is much easier to compress because ones dominate.

Reversibility directly gives a bound. Call the next letter XNX_N, the preceding context XN−1X^{N-1} of N−1N - 1 letters, and attempts RNR_N. Since XNX_N is a function of (XN−1,RN)(X^{N-1}, R_N) and RNR_N a function of (XN−1,XN)(X^{N-1}, X_N),

H⁡(XN∣XN−1)=H⁡(RN∣XN−1)≤H⁡(RN)=−∑iqilog⁡2qi,\Ent(X_N \given X^{N-1}) = \Ent(R_N \given X^{N-1}) \le \Ent(R_N) = -\sum_i q_i \log_2 q_i,

where qi=P(RN=i)q_i = \Pr(R_N = i). Conditional entropy of the next letter, which with N→∞N \to \infty is the language’s entropy rate, does not exceed entropy of the attempt distribution.

The upper bound is the argument above and applies to any predictor, ideal or not: a worse predictor only worsens the attempt distribution. The lower bound is subtler and requires an ideal predictor. Shannon obtains it by observing that, in each context, ordered probabilities p1≥p2≥⋯p_1 \ge p_2 \ge \cdots mix uniform distributions over the first ii letters, with weights i(pi−pi+1)i(p_i - p_{i+1}); entropy is concave and each uniform contributes log⁡2i\log_2 i, so entropy is at least the mean of those logarithms, and averaging over contexts preserves the inequality. The bound is tight when the predictor is uncertain among a few equally probable letters.

With subjects seeing up to 100 context letters, Shannon bounded English entropy at about 0.6 to 1.3 bits per letter, versus log⁡227≈4.75\log_2 27 \approx 4.75 bits for random text over the same alphabet. Later estimates tightened the upper bound. Cover and King (1978) replaced attempts with bets: subjects distribute capital across 27 letters, and logarithmic growth gives a log-score bound around 1.3 bits per letter. Brown and coauthors (IBM, 1992) obtained 1.75 bits per character with a word-trigram model trained on 583 million words. In 2023, LLMZip used LLaMA-7B for a bound around 0.7 bits per character in its limited experiments. Each bound is one predictor’s log loss: better predictors yield lower bounds.

In the interactive, the context model (order 3, trained on about 5 KB of Spanish) pays 2.3–3.4 bits per letter in log loss depending on sentence, with Shannon upper bounds 2.4–2.9. A Spanish speaker easily beats it on the proverb by recognizing the whole sentence after a few letters: no amount of local four-character statistics substitutes for knowing proverbs. A single 50- or 60-letter sentence makes noisy estimates; Shannon averaged over one hundred passages.

From language model to compressor

Formalize the twin. A language model over a finite alphabet X\mathcal{X} (letters, bytes, or tokens) is a sequential probability assignment: for each prefix x<tx_{<t}, a distribution q(⋅∣x<t)q(\cdot \given x_{<t}). By the chain rule it defines a probability over length-nn sequences,

q(xn)=∏t=1nq(xt∣x<t),−log⁡2q(xn)=∑t=1n−log⁡2q(xt∣x<t).q(x^n) = \prod_{t=1}^{n} q(x_t \given x_{<t}), \qquad -\log_2 q(x^n) = \sum_{t=1}^n -\log_2 q(x_t \given x_{<t}).

The arithmetic coder converts that probability into bits. It starts with interval [0,1)[0, 1), divides it at each step into subintervals proportional to q(⋅∣x<t)q(\cdot \given x_{<t}) in a fixed alphabet order, and keeps the actual symbol’s interval. After nn steps the interval for xnx^n has width q(xn)q(x^n), and sending the bits of a short binary number inside suffices.

The final guided exercise proves this: take ℓ=⌈−log⁡2q(xn)⌉+1\ell = \lceil -\log_2 q(x^n) \rceil + 1 and show there is always a dyadic interval of width 2−ℓ2^{-\ell} inside the interval for xnx^n, and that dyadic intervals for distinct sequences do not overlap, giving a prefix code. The expectation is the same decomposition as the cost of coding with the wrong distribution:

Ep[−log⁡2q(Xn)]=H⁡(p)+KL⁡(p ∥ q),\E_p[-\log_2 q(X^n)] = \Ent(p) + \KL(p \,\|\, q),

Thus compression with an imperfect model costs exactly its KL divergence from the source, in bits. No compressor goes below H⁡(p)\Ent(p) by the source coding theorem.

Connect this to training. LM loss is mean cross-entropy in nats per token, L^=−1n∑tln⁡q(xt∣x<t)\hat{L} = -\tfrac{1}{n}\sum_t \ln q(x_t \given x_{<t}), using the usual softmax cross-entropy loss. Therefore

ℓ(xn)≈n L^ln⁡2 bits.\ell(x^n) \approx \frac{n\,\hat{L}}{\ln 2} \text{ bits}.

Lower validation loss literally shrinks the compressed validation file. This is why LM loss is reported in bits: it is file size, not an arbitrary convention.

Where bits are spent

The sum ∑t−log⁡2q(xt∣x<t)\sum_t -\log_2 q(x_t \given x_{<t}) is not distributed evenly. The next interactive shows each token’s surprise according to Qwen2.5-0.5B, computed once on CPU over several texts.

InteractiveWhere a model spends bits
El 14 de marzo de 2023, la ingeniera Lucía Ferrándiz presentó en Valladolid un prototipo que comprimía los registros de la red eléctrica a la mitad de su tamaño. Nadie en la sala esperaba aquel resultado. La clave, explicó, no estaba en el algoritmo sino en el modelo: cuanto mejor se predice el siguiente dato, menos bits hacen falta para guardarlo.
0 bits16 or more bits per token
Bits per byte of each token: total area is code length
0481216uncompressed: 8gzip: 5.87LM mean: 1.17position in text (bytes, 357 total)
Token 19: ·Ferrq=0.0015q = 0.0015,   −log⁡2q=9.34\;-\log_2 q = 9.34 bitscumulative: 81.281.2 bits, interval width 2−81.22^{-81.2}
01[0.6252, 0.6267)vocabulary in ID order
What the model expected
·Mart0.026
·M0.023
·Fern0.021
  • actual token subinterval
  • subintervals of the most likely alternatives
Tokens / bytes96 / 357
Code length (LM)416.2 bits
Bits per token4.33
Bits per byte: LM1.166
Bits per byte: gzip, xz5.87, 7.71
Bits in costliest 10% (10 tokens)31 %
Each token is colored by surprise −log⁡2q-\log_2 q. Below, token rectangles are as wide as their bytes and as tall as bits per byte, so total area is code length. Select a token to see its arithmetic subinterval (vocabulary-ID order), what the model expected, and accumulated bits. Find where bits concentrate in the new text; then switch to ‘Lorem ipsum’ or Dickens and compare with Don Quixote.

Three regularities stand out in the new paragraph. Word continuations are almost free: after “ prot”, tokens “ot” and “ipo” cost 0.05 bits each; after “ elé”, “ct” and “rica” cost 0.013 and 0.002. Function words are cheap on average but not free: “de” costs 0.6–2.2 bits, while “la” and “en” reach 5 or 6 bits when starting something unexpected. The expensive bits are content choices: the first token of a proper name (“ Vall”, 11.2 bits; “ Ferr”, 9.3), a sentence-opening word or unexpected idea (“ Nad” of “Nadie”, 13.2; “ cuanto”, 13.2), and unanticipated terms (“ bits”, 13.5). The most expensive 10% of tokens account for 31% of bits. Date digits are cheaper than they look: “2023” totals 6.1 bits versus 13.3 for four random digits, because year format is predictable (the “0” after the first “2” is free).

Famous texts tell another story. The beginning of A Tale of Two Cities costs 0.24 bits per byte and “Lorem ipsum” 0.21: after initial tokens the model pays almost nothing. It is remembering, not compressing in a way that reveals its capacity to predict novel text. Don Quixote’s opening costs 1.66 bits per byte, more than the new paragraph, suggesting this small model has not memorized it. The gzip line also matters: on texts of a few hundred bytes it barely compresses (5.87 bits per byte), having had little time to see repetitions. The LM arrives with knowledge already loaded.

From compressor to predictor

The equivalence also works in reverse. A lossless compressor producing prefix codes of lengths ℓ(x)\ell(x) satisfies the Kraft inequality, ∑x2−ℓ(x)≤1\sum_x 2^{-\ell(x)} \le 1, so

qC(x)=2−ℓ(x)q_C(x) = 2^{-\ell(x)}

is a (sub)probability. A good compressor assigns short codes to likely strings, making qCq_C a good model. To predict the next symbol condition: qC(a∣x)=qC(xa)/∑bqC(xb)q_C(a \given x) = q_C(xa)/\sum_b q_C(xb), where qC(xa)q_C(xa) should sum over all continuations of xaxa. That is intractable for a black-box compressor, so the usual approximation (used by Delétang and coauthors) takes the extended text’s length directly:

qC(a∣x)∝2−C(xa),q_C(a \given x) \propto 2^{-C(xa)},

with C(⋅)C(\cdot) the compressed file’s length in bits. The idea is exact in the limit but encounters practical granularity: gzip measures bytes, so adding a letter changes CC by 0 or 8 bits and resulting probabilities are separated by factors of 256. You will implement this in the coding exercise. On “más vale pájaro en mano que ciento volando” repeated three times (134 bytes, 20 distinct byte values, log⁡220≈4.32\log_2 20 \approx 4.32 bits for their uniform distribution), a zlib-derived predictor pays 4.95 bits per byte on the first copy, worse than uniform, and 0.70 on repeats, which it exploits. A bz2-derived predictor averages 12.0 bits per byte: lengths jump almost arbitrarily as bytes are added, and it confidently bets on wrong symbols. LM-to-compressor is practical; compressor-to-predictor is mainly conceptual except for compressors that already are probabilistic models (PPM, CM, or arithmetic coding with a context model).

Metrics: nats, perplexity, and bits per byte

Loss L^\hat{L} is measured in nats per token. Other metrics follow from it, so the conversions matter.

Perplexity has a serious flaw: it is per token, and tokenizers split text differently. A model with long tokens makes fewer predictions, each harder, increasing perplexity even if it compresses better. A tokenizer-independent metric divides bits by something fixed: text bytes.

Models with different tokenizers can only be compared in bits per byte (or per character if they see the same characters), on the same text. The Pile paper (Gao and coauthors, 2020) adopted BPB for precisely this comparison. Bits per character, the classic metric of enwik8 and text8, coincide with BPB on ASCII, not Spanish, where “ñ” or “á” occupy two UTF-8 bytes.

A real example clarifies this. We measured Qwen2.5-0.5B on the same Spanish paragraph and its English translation:

TextTokensBytesBytes per tokenNats per tokenPerplexityBits per byte
Spanish963573.723.00420.21.166
English773254.223.31427.51.133

English perplexity is 36% worse, yet the model compresses it better: the tokenizer groups more bytes per token. With one sentence per language the BPB difference is not significant, but the general lesson is that perplexity measures tokenizer as well as model.

InteractiveCompression metric converter
Compressed size of 1.0 GB of text (gzip and xz: rates measured on WikiText-2)
Uncompressed1.0 GBgzip -9345.3 MBxz -9e285.6 MBLM: message145.7 MBLM + model1.1 GB
  • LM-encoded message
  • parameters (16 bits each)
Perplexity for a model with 1.166 bits per byte versus bytes per token
1101001000123456bytes per tokenone token per byte: 2.24your model: 20.2
Model
3.004
3.72
494 million
Bits per parameter
Text
1.0 GB
Bits per token4.334
Perplexity per token20.17
Bits per byte1.166
Raw rate14.6 %
Adjusted rate (including model)113.4 %
Beats xz above7.1 GB
Including the model, the compressed file is larger than the original: the LM pays off only when the text is much larger than its parameters.
Above, text size after gzip, xz, and LM compression, with and without parameters. Below, the perplexity corresponding to these bits per byte for different bytes per token: the curve is 2BPB⋅b2^{\mathrm{BPB}\cdot b}. Switch Spanish to English and inspect changed readings. Reduce text to 1 MB and increase to 10 TB: when does sending the model pay off?

The lower curve illustrates the tokenizer trap. At fixed BPB, PPL=2BPB⋅b\mathrm{PPL} = 2^{\mathrm{BPB}\cdot b} grows exponentially with bytes per token. At 1.166 bits per byte the same compressor would have perplexity 2.2 reading one byte per token and 20.2 with Qwen’s tokenizer. The upper bars anticipate the next section: for 1 GB text the LM message occupies 146 MB, but the 16-bit model adds 988 MB.

[ ]From nats per token to bits per byteBrowser
import math

def metricas(nats_por_token, bytes_por_token):
    bits_token = nats_por_token / math.log(2)
    return {"bits/token": bits_token, "perplejidad": math.exp(nats_por_token),
            "bits/byte": bits_token / bytes_por_token}

# totales medidos con Qwen2.5-0.5B sobre el mismo párrafo (bits, tokens, bytes)
for nombre, bits, tokens, nbytes in [("español", 416.1, 96, 357), ("inglés", 368.1, 77, 325)]:
    L = bits * math.log(2) / tokens
    m = metricas(L, nbytes / tokens)
    print(f"{nombre:8s} L = {L:.3f} nats/token  " + "  ".join(f"{k} = {v:.3f}" for k, v in m.items()))

# el mismo compresor visto con tokenizadores distintos: los bits por byte no cambian, la perplejidad sí
bpb = 416.1 / 357
for b in (1, 2, 3.72, 6):
    print(f"bytes/token = {b:4}:  perplejidad = {2 ** (bpb * b):8.2f}")

# tamaño comprimido de 1 GB con 2.0 nats por token y 4 bytes por token
print(f"\n2.0 nats/token, 4 bytes/token: {metricas(2.0, 4)['bits/byte']:.4f} bits/byte, "
      f"1 GB -> {1e9 * metricas(2.0, 4)['bits/byte'] / 8 / 1e6:.1f} MB")

Implementation from scratch

Witten, Neal and Cleary’s (1987) integer arithmetic coder uses interval [low,high][\text{low}, \text{high}] of 32-bit integers. Each symbol narrows it by cumulative frequencies; when endpoints share the most significant bit, that bit is final and emitted, and the interval doubles. The subtle case straddles the midpoint and narrows without deciding its first bit: double around the center and defer the bit (the pending), later emitting it opposite to the next decided bit. Probabilities are quantized to integer frequencies summing to ≤216\le 2^{16} with minimum 1, so no symbol has zero probability.

The model is an order-2 byte context model with Witten–Bell interpolation, initially empty and learning while compressing: a tiny language model.

[ ]Arithmetic coder and context modelBrowser
import numpy as np, zlib, bz2, time

class ArithmeticCoder:
    """Codificador aritmético entero (Witten, Neal y Cleary, 1987) con registros de PREC bits."""
    PREC = 32
    FULL, HALF, QUARTER = (1 << PREC) - 1, 1 << (PREC - 1), 1 << (PREC - 2)

    def __init__(self):
        self.low, self.high, self.pending, self.bits = 0, self.FULL, 0, []

    def _emit(self, b):
        self.bits.append(b)
        self.bits.extend([1 - b] * self.pending)       # los bits aplazados salen con el signo contrario
        self.pending = 0

    def encode(self, cum_lo, cum_hi, total):
        rng = self.high - self.low + 1
        self.high = self.low + rng * cum_hi // total - 1
        self.low = self.low + rng * cum_lo // total
        while True:
            if self.high < self.HALF:                  # los dos en la mitad inferior: sale un 0
                self._emit(0)
            elif self.low >= self.HALF:                # los dos en la superior: sale un 1
                self._emit(1)
                self.low -= self.HALF; self.high -= self.HALF
            elif self.low >= self.QUARTER and self.high < 3 * self.QUARTER:
                self.pending += 1                      # a caballo del centro: se aplaza el bit
                self.low -= self.QUARTER; self.high -= self.QUARTER
            else:
                break
            self.low, self.high = 2 * self.low, 2 * self.high + 1

    def finish(self):
        self.pending += 1                              # dos bits más fijan un punto del intervalo
        self._emit(0 if self.low < self.QUARTER else 1)
        return self.bits

class ArithmeticDecoder:
    def __init__(self, bits):
        A = ArithmeticCoder
        self.bits, self.i, self.low, self.high, self.value = bits, 0, 0, A.FULL, 0
        for _ in range(A.PREC):
            self.value = 2 * self.value + self._next()

    def _next(self):
        b = self.bits[self.i] if self.i < len(self.bits) else 0
        self.i += 1
        return b

    def decode(self, cum):
        A, total = ArithmeticCoder, int(cum[-1])
        rng = self.high - self.low + 1
        target = ((self.value - self.low + 1) * total - 1) // rng
        s = int(np.searchsorted(cum, target, side="right")) - 1   # el símbolo cuyo tramo contiene target
        self.high = self.low + rng * int(cum[s + 1]) // total - 1
        self.low = self.low + rng * int(cum[s]) // total
        while True:
            if self.high < A.HALF:
                pass
            elif self.low >= A.HALF:
                self.low -= A.HALF; self.high -= A.HALF; self.value -= A.HALF
            elif self.low >= A.QUARTER and self.high < 3 * A.QUARTER:
                self.low -= A.QUARTER; self.high -= A.QUARTER; self.value -= A.QUARTER
            else:
                break
            self.low, self.high = 2 * self.low, 2 * self.high + 1
            self.value = 2 * self.value + self._next()
        return s

def quantize(p, total_bits=16):
    """Probabilidades -> frecuencias enteras >= 1 con suma <= 2^total_bits; devuelve las acumuladas."""
    f = np.floor(p * ((1 << total_bits) - len(p))).astype(np.int64) + 1
    return np.concatenate([[0], np.cumsum(f)])

class ContextModel:
    """Modelo de bytes de orden K con interpolación de Witten-Bell; aprende sobre la marcha."""
    def __init__(self, K=2):
        self.K, self.tables = K, {}

    def predict(self, hist):
        p = np.full(256, 1 / 256)
        for k in range(min(self.K, len(hist)) + 1):
            t = self.tables.get(hist[len(hist) - k:])
            if t is None:
                break
            C, T = t.sum(), np.count_nonzero(t)
            p = (t + T * p) / (C + T)                  # mezcla con el orden inferior
        return p

    def update(self, hist, c):
        for k in range(min(self.K, len(hist)) + 1):
            h = hist[len(hist) - k:]
            if h not in self.tables:
                self.tables[h] = np.zeros(256)
            self.tables[h][c] += 1

def compress(data, K=2):
    m, enc, ideal, ideal_q = ContextModel(K), ArithmeticCoder(), 0.0, 0.0
    for i, c in enumerate(data):
        hist = data[max(0, i - K):i]
        p = m.predict(hist)
        cum = quantize(p)
        enc.encode(int(cum[c]), int(cum[c + 1]), int(cum[-1]))
        ideal -= np.log2(p[c])
        ideal_q -= np.log2((cum[c + 1] - cum[c]) / cum[-1])
        m.update(hist, c)
    return enc.finish(), ideal, ideal_q

def decompress(bits, n, K=2):
    m, dec, out = ContextModel(K), ArithmeticDecoder(bits), bytearray()
    for i in range(n):
        hist = bytes(out[max(0, i - K):i])
        c = dec.decode(quantize(m.predict(hist)))      # mismas predicciones que el compresor
        out.append(c)
        m.update(hist, c)
    return bytes(out)

texto = ("Cuando llega el otoño, la ciudad cambia de ritmo. Las tardes se acortan, los parques se llenan de hojas "
         "secas y en las calles del centro vuelve a oler a castañas asadas. Los niños regresan al colegio con mochilas "
         "nuevas y los adultos se quejan del tráfico, que parece crecer cada año un poco más. En los mercados aparecen "
         "las primeras setas, las granadas y los membrillos, y los vendedores anuncian a voces el precio de la fruta de "
         "temporada. Mi abuela decía que para cocinar bien hacen falta tres cosas: paciencia, buenos ingredientes y "
         "alguien con quien compartir la mesa. Su cocido tardaba toda la mañana en estar listo. Ponía los garbanzos en "
         "remojo la noche anterior, y al día siguiente los cocía a fuego lento con un trozo de tocino, una punta de "
         "jamón, chorizo, morcilla, zanahorias y un repollo entero. Primero se servía la sopa, después los garbanzos "
         "con la verdura y por último la carne. Nadie se levantaba de la mesa antes de las cinco de la tarde.")
data = texto.encode("utf-8")
n = len(data)
t0 = time.perf_counter()
bits, ideal, ideal_q = compress(data)
back = decompress(bits, n)
print(f"¿idéntico tras descomprimir? {back == data}   ({time.perf_counter() - t0:.2f} s)")
print(f"{n} bytes -> {len(bits)} bits = {len(bits) / n:.3f} bits/byte")
print(f"Σ −log2 q con q real: {ideal:.1f} bits;  con q cuantizada: {ideal_q:.1f};  código - Σ (cuantizada): {len(bits) - ideal_q:.2f} bits")
for nombre, c in [("zlib -9", zlib.compress(data, 9)), ("bz2 -9", bz2.compress(data, 9))]:
    print(f"{nombre:8s} {8 * len(c) / n:.3f} bits/byte")

The 974 bytes become 3941 bits (4.05 bits per byte), and quantized model surprise sums to 3940.1: the code is less than one bit longer, within the theorem’s 2 bits (finite arithmetic also incurs tiny per-step rounding error, negligible with 32-bit registers). Quantization costs nothing here, even saving a few bits relative to actual qq: the code pays the log loss of the model actually used, the quantized one. The decoder recovers exact text because it reproduces the same predictions, using the same model updated with the same symbols in the same order. This tiny initially ignorant model already beats zlib and bz2 on a kilobyte of Spanish: short text favors models over Lempel–Ziv dictionaries, which need repeated material.

Compress with a real LM

Replacing the context model with a pretrained transformer leaves the algorithm unchanged but adds four engineering problems.

Bitwise determinism. The decoder must obtain exactly the same integer frequency tables as the encoder. If one frequency differs by one, subinterval boundaries move, the decoder may choose another token, and contexts diverge: the rest becomes garbage. Floating-point differences of 10−510^{-5} that are unimportant in training are fatal here, and appear when summation order changes: another batch size, sequence length, nondeterministic GPU kernels, library version, or card.

Precision. Qwen’s vocabulary has 151 936 tokens, more than 2162^{16}, so frequencies require more bits (we use 2302^{30} and 62-bit registers, free with Python integers). Avoid FP16: less stable arithmetic makes two executions likelier to disagree.

Context. A transformer sees at most its context window. Longer texts use a sliding window whose size and stride are part of the file format: the decoder must use exactly the same values.

Cost. Each token costs one model pass, about 2N2N operations for NN parameters, both compressing and decompressing. gzip processes tens or hundreds of megabytes per second; Qwen2.5-0.5B on CPU, incrementally with KV cache, measured about 9 tokens per second with 4 threads, or about 35 bytes per second.

The next cell compresses the paragraph with Qwen2.5-0.5B on the available device (usual device placement: cuda if a GPU is available) in float32. Both sides calculate predictions incrementally with KV cache, using the same code, inside torch.inference_mode(), which cuts the autograd graph because gradients are unnecessary. Model revision is fixed: a compressed file can only be opened with identical weights bit for bit.

[ ]Compress text with an LM and arithmetic codingLocal GPU
import gzip, bz2, lzma, time
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

# --- el codificador aritmético entero de antes, con registros de 62 bits (el vocabulario no cabe en 16) ---
PREC, TOTAL_BITS = 62, 30
FULL, HALF, QUARTER = (1 << PREC) - 1, 1 << (PREC - 1), 1 << (PREC - 2)

class Encoder:
    def __init__(self):
        self.low, self.high, self.pending, self.bits = 0, FULL, 0, []
    def _emit(self, b):
        self.bits.append(b); self.bits.extend([1 - b] * self.pending); self.pending = 0
    def encode(self, lo, hi, total):
        rng = self.high - self.low + 1
        self.high = self.low + rng * hi // total - 1
        self.low = self.low + rng * lo // total
        while True:
            if self.high < HALF: self._emit(0)
            elif self.low >= HALF: self._emit(1); self.low -= HALF; self.high -= HALF
            elif self.low >= QUARTER and self.high < 3 * QUARTER: self.pending += 1; self.low -= QUARTER; self.high -= QUARTER
            else: break
            self.low, self.high = 2 * self.low, 2 * self.high + 1
    def finish(self):
        self.pending += 1; self._emit(0 if self.low < QUARTER else 1)
        return self.bits

class Decoder:
    def __init__(self, bits):
        self.bits, self.i, self.low, self.high, self.value = bits, 0, 0, FULL, 0
        for _ in range(PREC): self.value = 2 * self.value + self._next()
    def _next(self):
        b = self.bits[self.i] if self.i < len(self.bits) else 0
        self.i += 1
        return b
    def decode(self, cum):
        total, rng = int(cum[-1]), self.high - self.low + 1
        target = ((self.value - self.low + 1) * total - 1) // rng
        s = int(np.searchsorted(cum, target, side="right")) - 1
        self.high = self.low + rng * int(cum[s + 1]) // total - 1
        self.low = self.low + rng * int(cum[s]) // total
        while True:
            if self.high < HALF: pass
            elif self.low >= HALF: self.low -= HALF; self.high -= HALF; self.value -= HALF
            elif self.low >= QUARTER and self.high < 3 * QUARTER: self.low -= QUARTER; self.high -= QUARTER; self.value -= QUARTER
            else: break
            self.low, self.high = 2 * self.low, 2 * self.high + 1
            self.value = 2 * self.value + self._next()
        return s

def quantize(p):
    f = np.floor(p * ((1 << TOTAL_BITS) - len(p))).astype(np.int64) + 1
    return np.concatenate([[0], np.cumsum(f)])

# --- el modelo: revisión fija, float32, modo evaluación ---
REPO, REV = "Qwen/Qwen2.5-0.5B-Instruct", "7ae557604adf67be50417f59c2c2f167def9a775"
device = "cuda" if torch.cuda.is_available() else "cpu"
tok = AutoTokenizer.from_pretrained(REPO, revision=REV)
model = AutoModelForCausalLM.from_pretrained(REPO, revision=REV, dtype=torch.float32).to(device).eval()
BOS = tok.convert_tokens_to_ids("<|endoftext|>")

class Predictor:
    """q(· | x_<t) paso a paso con la caché KV. Codificador y decodificador usan exactamente este código."""
    def __init__(self):
        self.past = None
        self.p = self._step(BOS)
    @torch.inference_mode()
    def _step(self, x):
        out = model(torch.tensor([[x]], device=device), past_key_values=self.past, use_cache=True)
        self.past = out.past_key_values
        return torch.softmax(out.logits[0, -1].double(), dim=-1).cpu().numpy()
    def advance(self, x):
        self.p = self._step(x)

def lm_compress(text):
    ids = tok(text, add_special_tokens=False)["input_ids"]
    q, enc, ideal = Predictor(), Encoder(), 0.0
    for t in ids:
        cum = quantize(q.p)
        enc.encode(int(cum[t]), int(cum[t + 1]), int(cum[-1]))
        ideal -= np.log2(q.p[t])
        q.advance(t)
    return enc.finish(), len(ids), ideal

def lm_decompress(bits, n_tokens):
    q, dec, ids = Predictor(), Decoder(bits), []
    for _ in range(n_tokens):
        t = dec.decode(quantize(q.p))
        ids.append(t)
        q.advance(t)
    return tok.decode(ids)

texto = ("El 14 de marzo de 2023, la ingeniera Lucía Ferrándiz presentó en Valladolid un prototipo que comprimía "
         "los registros de la red eléctrica a la mitad de su tamaño. Nadie en la sala esperaba aquel resultado. "
         "La clave, explicó, no estaba en el algoritmo sino en el modelo: cuanto mejor se predice el siguiente dato, "
         "menos bits hacen falta para guardarlo.")
raw = texto.encode("utf-8")
t0 = time.perf_counter()
bits, n_tok, ideal = lm_compress(texto)
t1 = time.perf_counter()
back = lm_decompress(bits, n_tok)
t2 = time.perf_counter()
print("¿idéntico?", back == texto, f"  ({n_tok} tokens, {len(raw)} bytes, {device})")
print(f"código: {len(bits)} bits = {len(bits) / len(raw):.3f} bits/byte;  Σ −log2 q = {ideal:.1f} bits")
for nombre, c in [("gzip -9", gzip.compress(raw, 9)), ("bz2 -9", bz2.compress(raw, 9)), ("xz -9e", lzma.compress(raw, preset=9 | lzma.PRESET_EXTREME))]:
    print(f"{nombre:8s} {8 * len(c) / len(raw):.3f} bits/byte")
print(f"tiempo: {t1 - t0:.1f} s codificar, {t2 - t1:.1f} s decodificar")

# --- el coste del modelo: lo que el receptor necesita además del mensaje ---
sd = model.state_dict()
ingenuo = sum(v.numel() * v.element_size() for v in sd.values())
unicos = {v.data_ptr(): v.numel() * v.element_size() for v in sd.values()}   # pesos compartidos, una vez
model_bytes = sum(unicos.values())
print(f"state_dict: {len(sd)} tensores; sumando todos {ingenuo / 1e9:.2f} GB, sin duplicar los compartidos {model_bytes / 1e9:.2f} GB")
print(f"tasa ajustada para este texto: {(len(bits) / 8 + model_bytes) / len(raw):.2e}")

# --- ¿dan lo mismo una pasada completa y la generación paso a paso? ---
with torch.inference_mode():
    ids = tok(texto, add_special_tokens=False)["input_ids"]
    full = torch.softmax(model(torch.tensor([[BOS] + ids], device=device)).logits[0, :-1].double(), -1).cpu().numpy()
q, paso = Predictor(), []
for t in ids:
    paso.append(q.p); q.advance(t)
paso = np.array(paso)
dif = np.abs(np.log(full) - np.log(paso)).max()
distintas = sum(not np.array_equal(quantize(a), quantize(b)) for a, b in zip(full, paso))
print(f"máx |Δ log q| entre pasada completa y paso a paso: {dif:.1e};  tablas cuantizadas distintas: {distintas} de {len(ids)}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In one CPU run text was recovered exactly and code length was 417 bits (1.168 bits per byte) versus 416.1 summed surprise: less than one excess bit. gzip needs 5.87 bits per byte, bz2 6.54, and xz 7.71 (on such short texts headers and lack of repetition matter more than algorithm). The last two lines matter:

  • Counting model size with its state_dict, summing tensors gives 2.52 GB, but Qwen2.5-0.5B shares embeddings with its output layer, so that matrix appears twice with the same storage. Counting each storage once gives 1.98 GB in float32. This text’s adjusted rate is about 5.5 million: its “compressed file” is millions of times larger than the original.
  • A full sequence pass and incremental generation yield log probabilities differing by up to 10−410^{-4}, and all 96 quantized frequency tables differ. A compressor encoding with a full pass (natural for efficiency) and decoding incrementally (the only possible order) would fail. Hence Predictor is the same object on both sides.

Model size counts

For Hutter the decoder is part of the file. Delétang and coauthors formalize this with adjusted compression rate:

tasa ajustada=bytes del mensaje comprimido+bytes de los paraˊmetrosbytes del texto original.\text{tasa ajustada} = \frac{\text{bytes del mensaje comprimido} + \text{bytes de los parámetros}}{\text{bytes del texto original}}.

Under it, large models cease to be competitive compressors except on enormous amounts of text: in their analysis of enwik9, billion-parameter models exceed 100% adjusted rate and only small models trained on the data themselves are competitive. If a model occupies MM bytes and compresses at rLMr_{\text{LM}} bits per byte versus a classical compressor at r0r_0, the LM pays off beyond

D⋆=M(r0−rLM)/8 bytes.D^\star = \frac{M}{(r_0 - r_{\text{LM}})/8} \text{ bytes}.

With Qwen2.5-0.5B in 16 bits (M≈0.99M \approx 0.99 GB), rLM=1.17r_{\text{LM}} = 1.17 and the r0=2.29r_0 = 2.29 measured for xz on WikiText-2 test, D⋆≈7D^\star \approx 7 GB. This is an order-of-magnitude estimate: 1.17 is the LM rate on our paragraph, not WikiText-2; a clean comparison would measure both compressors on the same corpus.

This is a two-part code instance of minimum description length: first describe the model, then data with that model, choosing the model minimizing their sum. An alternative avoids parameter cost by sending the program that trains it instead. Encoder and decoder start from the same random model and seed, code each chunk with the current model, and then train on it; the decoder does likewise with decoded data. Total cost is the sum of losses over training, the area under the learning curve: prequential MDL, used by Blier and Ollivier (2018) to measure deep-network description length. The earlier adaptive context model is a tiny example.

Compression as a capacity measure

If loss and compression are the same, familiar LLM curves are compression curves. A scaling law L(N,D)L(N, D) says validation bits per token as a function of parameters and training data: the compression rate of a compressor family. Compression is a surprisingly useful capacity measure: Huang and coauthors (2024) measured bits per character of around thirty open LLMs on recent text and found mean benchmark performance on knowledge, programming, and mathematical reasoning depended nearly linearly on that compression rate.

It has two advantages: no labels are needed, and it is hard to inflate without truly improving prediction. But ordinary evaluation traps remain. Chief among them is contamination: text in the training corpus compresses exceptionally well through memorization, like Dickens in the interactive. Those studies therefore use text published after model data cutoffs. Conceptually, compressing one distribution well does not guarantee a specific ability absent from that distribution.

Compression also describes transfer across modalities. Chinchilla 70B’s 43.4% on ImageNet reads pixels as bytes with a text-only model: a general byte-sequence predictor learned regularities useful beyond its domain. Again this is a raw rate, and including the model makes it uncompetitive with PNG.

Compressors as similarity measures

If CC is a compressor, C(xy)−C(x)C(xy) - C(x) estimates bits needed to describe yy when xx is already known. If xx and yy share much, compressing together costs little more than one alone. The theoretical idea is information distance based on uncomputable Kolmogorov complexity; Cilibrasi and Vitányi (2005) proposed replacing complexity with a real compressor.

Cilibrasi and Vitányi’s guarantees require a normal compressor: idempotent (C(xx)≈C(x)C(xx) \approx C(x)), monotonic (C(xy)≥C(x)C(xy) \ge C(x)), symmetric (C(xy)≈C(yx)C(xy) \approx C(yx)), and distributive. Real compressors satisfy these only approximately; idempotence fails dramatically when the string exceeds what the compressor remembers.

InteractiveClassify with a compressor
es Spanishpt Portugueseit Italianfr Frenchen Englishde Germanes₂ Spanish, another text
The bluer the cell, the more similar the texts (off-diagonal scale 0.00 to 1.00). Blue marks the Romance-language group if the tree separates it.
Compressor
Parameters
700 B
32 KB
NCD(es, pt)…
NCD(es, es₂)…
NCD(es, de)…
Mean NCD(x, x)…
Romance group separated…
Seven fragments: the same paragraph translated into six languages and another Spanish text with different content (es₂). The matrix gives pairwise NCD ordered by an average-linkage dendrogram; the diagonal is NCD(x,x)\mathrm{NCD}(x, x), which should be near 0. With deflate (zlib and gzip) and long fragments, Romance languages cluster and German is distant. Switch to LZ77 and shrink its window below fragment length: the diagonal approaches 1 and the tree loses meaning. Try the context model, a small LM, too.

The figure shows two distinct things. First, what NCD measures: shared substrings, not “language” abstractly. Spanish and Portuguese versions of the same paragraph are closer than two Spanish texts on different subjects, because translations share names, cognates, and structure; NCD sees content and vocabulary together. Second, when it breaks. LZ77 can refer only to the last WW bytes. If ∣x∣>W\abs{x} > W, when compressing xyxy the compressor has forgotten the start of xx upon reaching yy, so C(xy)≈C(x)+C(y)C(xy) \approx C(x) + C(y) and NCD≈1\mathrm{NCD} \approx 1 for any pair, even a text with itself. deflate has a 32 KB window: on longer text zlib NCD is noise. bzip2 uses 100–900 KB blocks, and xz uses an 8 MiB default-level dictionary and 64 MiB with -9. Cebrián, Alfonseca and Ortega (2005) systematically documented these failures.

Classification with gzip

In 2023 Jiang and coauthors published a remarkably simple text classifier: kk nearest neighbors with gzip NCD, no parameters or training, competitive with BERT on several datasets, especially with little data or out of distribution. Criticism followed. Ken Schutte noted that code using k=2k = 2 resolved ties by choosing the correct label if among the two neighbors, effectively measuring top-2 accuracy against other methods’ top-1, and some datasets repeated examples across training and test. Correcting evaluation substantially reduces scores. The methodological lesson is general: clean splits, the same metric, and attention to leakage.

A compressor classifier better founded than kk-NN concatenates each class’s training text, DcD_c, and assigns xx to the class most reducing its compression cost, arg min⁡c [C(Dc x)−C(Dc)]\argmin_c \,[C(D_c\,x) - C(D_c)]. By this lesson’s equivalence, C(Dc x)−C(Dc)≈−log⁡2qc(x)C(D_c\,x) - C(D_c) \approx -\log_2 q_c(x), the log likelihood of xx under a model trained on class cc: a generative Bayesian classifier using the compressor as language model. The cell compares it with kk-NN on a small six-language corpus. Splitting is by content: because texts are translations, sentences 1 through 5 of each language train and the rest test, so no test sentence appears in training in any language.

[ ]Classification by compression distanceBrowser
import re, zlib, bz2, random

TEXTOS = {
    "es": "Cuando llega el otoño, la ciudad cambia de ritmo. Las tardes se acortan, los parques se llenan de hojas secas y en las calles del centro vuelve a oler a castañas asadas. Los niños regresan al colegio con mochilas nuevas y los adultos se quejan del tráfico, que parece crecer cada año un poco más. En los mercados aparecen las primeras setas, las granadas y los membrillos, y los vendedores anuncian a voces el precio de la fruta de temporada. Mi abuela decía que para cocinar bien hacen falta tres cosas: paciencia, buenos ingredientes y alguien con quien compartir la mesa. Su cocido tardaba toda la mañana en estar listo. Ponía los garbanzos en remojo la noche anterior, y al día siguiente los cocía a fuego lento con un trozo de tocino, una punta de jamón, chorizo, morcilla, zanahorias y un repollo entero. Primero se servía la sopa, después los garbanzos con la verdura y por último la carne. Nadie se levantaba de la mesa antes de las cinco de la tarde. La ciencia avanza a base de preguntas pequeñas, y cada respuesta abre otras.",
    "pt": "Quando chega o outono, a cidade muda de ritmo. As tardes ficam mais curtas, os jardins enchem-se de folhas secas e nas ruas do centro volta a cheirar a castanhas assadas. As crianças regressam à escola com mochilas novas e os adultos queixam-se do trânsito, que parece crescer um pouco mais todos os anos. Nos mercados aparecem os primeiros cogumelos, as romãs e os marmelos, e os vendedores anunciam em voz alta o preço da fruta da época. A minha avó dizia que para cozinhar bem são precisas três coisas: paciência, bons ingredientes e alguém com quem partilhar a mesa. O cozido dela demorava a manhã inteira. Punha o grão de molho na noite anterior e no dia seguinte cozia-o em lume brando com um pedaço de toucinho, chouriço, morcela, cenouras e uma couve inteira. Primeiro servia-se a sopa, depois o grão com os legumes e por fim a carne. Ninguém se levantava da mesa antes das cinco da tarde. A ciência avança à custa de perguntas pequenas, e cada resposta abre outras.",
    "it": "Quando arriva l'autunno, la città cambia ritmo. I pomeriggi si accorciano, i parchi si riempiono di foglie secche e nelle strade del centro torna il profumo delle castagne arrostite. I bambini tornano a scuola con zaini nuovi e gli adulti si lamentano del traffico, che sembra crescere ogni anno un po' di più. Nei mercati compaiono i primi funghi, le melagrane e le mele cotogne, e i venditori annunciano a gran voce il prezzo della frutta di stagione. Mia nonna diceva che per cucinare bene servono tre cose: pazienza, buoni ingredienti e qualcuno con cui condividere la tavola. Il suo bollito richiedeva tutta la mattina. Metteva i ceci in ammollo la sera prima e il giorno dopo li cuoceva a fuoco lento con un pezzo di lardo, salsiccia, carote e un cavolo intero. Prima si serviva il brodo, poi i ceci con le verdure e infine la carne. Nessuno si alzava da tavola prima delle cinque del pomeriggio. La scienza avanza grazie a domande piccole, e ogni risposta ne apre altre.",
    "fr": "Quand l'automne arrive, la ville change de rythme. Les après-midi raccourcissent, les parcs se remplissent de feuilles mortes et dans les rues du centre on sent de nouveau l'odeur des marrons grillés. Les enfants retournent à l'école avec des cartables neufs et les adultes se plaignent de la circulation, qui semble augmenter un peu plus chaque année. Sur les marchés apparaissent les premiers champignons, les grenades et les coings, et les marchands annoncent à voix haute le prix des fruits de saison. Ma grand-mère disait que pour bien cuisiner il faut trois choses : de la patience, de bons ingrédients et quelqu'un avec qui partager la table. Son pot-au-feu demandait toute la matinée. Elle faisait tremper les pois chiches la veille et le lendemain elle les cuisait à feu doux avec un morceau de lard, des saucisses, des carottes et un chou entier. On servait d'abord le bouillon, puis les légumes et enfin la viande. Personne ne quittait la table avant cinq heures. La science avance grâce à de petites questions.",
    "en": "When autumn arrives, the city changes its rhythm. The afternoons grow shorter, the parks fill with dry leaves and the streets of the centre smell of roasted chestnuts again. Children go back to school with new backpacks and adults complain about the traffic, which seems to grow a little more every year. The first mushrooms, pomegranates and quinces appear in the markets, and the sellers shout out the price of the seasonal fruit. My grandmother used to say that cooking well takes three things: patience, good ingredients and someone to share the table with. Her stew took the whole morning. She soaked the chickpeas the night before and the next day she cooked them over a low heat with a piece of bacon, sausages, carrots and a whole cabbage. First came the soup, then the chickpeas with the vegetables and finally the meat. Nobody left the table before five in the afternoon. Science moves forward through small questions, and every answer opens new ones, which is why results are published with all their details.",
    "de": "Wenn der Herbst kommt, ändert die Stadt ihren Rhythmus. Die Nachmittage werden kürzer, die Parks füllen sich mit trockenem Laub und in den Straßen der Innenstadt riecht es wieder nach gerösteten Kastanien. Die Kinder gehen mit neuen Rucksäcken zurück in die Schule und die Erwachsenen klagen über den Verkehr, der jedes Jahr ein wenig zuzunehmen scheint. Auf den Märkten erscheinen die ersten Pilze, Granatäpfel und Quitten, und die Verkäufer rufen laut den Preis des Obstes der Saison aus. Meine Großmutter sagte immer, dass man zum guten Kochen drei Dinge braucht: Geduld, gute Zutaten und jemanden, mit dem man den Tisch teilen kann. Ihr Eintopf brauchte den ganzen Vormittag. Sie weichte die Kichererbsen am Vorabend ein und kochte sie am nächsten Tag bei schwacher Hitze mit einem Stück Speck, Würsten, Karotten und einem ganzen Kohl. Zuerst gab es die Suppe, dann die Kichererbsen mit dem Gemüse und zuletzt das Fleisch. Niemand stand vor fünf Uhr vom Tisch auf.",
}
COMP = {"zlib": lambda b: len(zlib.compress(b, 9)), "bz2": lambda b: len(bz2.compress(b, 1))}

def ncd(C, x, y, cx=None, cy=None):
    cx = C(x) if cx is None else cx
    cy = C(y) if cy is None else cy
    return (C(x + b" " + y) - min(cx, cy)) / max(cx, cy)

# frases: el texto de cada idioma partido por puntos (la frase i dice lo mismo en todos los idiomas)
frases = [(idioma, i, s.encode()) for idioma, t in TEXTOS.items()
          for i, s in enumerate(x for x in re.split(r"(?<=[.:])\s+", t) if len(x) > 20)]
train = [f for f in frases if f[1] < 5]
test = [f for f in frases if f[1] >= 5]
print(f"{len(train)} frases de entrenamiento, {len(test)} de prueba, {len(TEXTOS)} idiomas (azar: {1 / len(TEXTOS):.2f})")

def knn(C, train, test, k=1):
    c_tr = [C(s) for _, _, s in train]
    aciertos = 0
    for idioma, _, x in test:
        cx = C(x)
        vecinos = sorted((ncd(C, x, s, cx, c_tr[j]), l) for j, (l, _, s) in enumerate(train))[:k]
        votos = {}
        for _, l in vecinos:
            votos[l] = votos.get(l, 0) + 1
        aciertos += max(votos, key=votos.get) == idioma
    return aciertos / len(test)

def por_clase(C, train, test):
    """argmin_c C(D_c x) - C(D_c): un clasificador bayesiano con el compresor como modelo."""
    docs = {l: b" ".join(s for ll, _, s in train if ll == l) for l in TEXTOS}
    c_docs = {l: C(d) for l, d in docs.items()}
    return sum(min(docs, key=lambda l: C(docs[l] + b" " + x) - c_docs[l]) == idioma
               for idioma, _, x in test) / len(test)

for nombre, C in COMP.items():
    print(f"{nombre:5s} k-NN (k=1) {knn(C, train, test):.2f}   k-NN (k=3) {knn(C, train, test, 3):.2f}   "
          f"por clase {por_clase(C, train, test):.2f}")

for m in (25, 50, 100):                               # frases de prueba recortadas a m bytes
    corto = [(l, i, s[:m]) for l, i, s in test]
    print(f"prueba recortada a {m:3d} bytes:  " + "   ".join(
        f"{n} k-NN {knn(C, train, corto):.2f} / por clase {por_clase(C, train, corto):.2f}" for n, C in COMP.items()))

rng = random.Random(0)                                # NCD(x, x) debería ser casi 0
for n in (20_000, 40_000):
    x = bytes(rng.choice(b"abcdefghijklmnopqrstuvwxyz ") for _ in range(n))
    print(f"NCD(x, x) con |x| = {n // 1000} KB:  " + "   ".join(f"{nom} {ncd(C, x, x):.3f}" for nom, C in COMP.items()))

Results are instructive. kk-NN on individual sentences gets about 40% right (chance 17%): for 50–150-byte sentences format headers and little shared material dominate distance. The class classifier compresses each sentence with all text of its language before it and exceeds 80% with both compressors: the compressor acts as a language model once given conditioning data. Truncating test sentences worsens everything, and at 25 bytes neither method is reliable. kk-NN with zlib can fall below chance (0.11 at 50 bytes): 14 of 35 test sentences have the same 46-byte Portuguese sentence as nearest neighbor, the shortest training example. On such short fragments NCD mainly measures lengths and headers, not content. The last line illustrates the window: at 20 KB zlib gives NCD(x,x)=0.02\mathrm{NCD}(x, x) = 0.02; at 40 KB, beyond its 32 KB window, it gives 1.008, as if a text and itself shared nothing. bz2 avoids that problem at this scale, but its NCD(x,x)=0.37\mathrm{NCD}(x, x) = 0.37 shows it is not idempotent either: Burrows–Wheeler transform does not exploit an exact copy like an LZ reference.

Frontier and limits of the analogy

LLMZip (Valmeekam and coauthors, 2023) coupled LLaMA-7B with arithmetic coding and a sliding window, beating reference compressors such as ZPAQ and paq8h in its experiments and providing the English entropy bound mentioned above. Delétang and coauthors showed transfer to images and audio by reading raw bytes and analyzed how adjusted rate implies an optimal model size for each data volume: bigger is not a better compressor if the model must be sent. LM compression has also been proposed for LLM contexts themselves (prompts, retrieved documents) and for studying memorization: text compressed far below its class’s expected rate was probably in training.

Keep the analogy’s limits in mind:

  • It does not beat entropy. No model compresses noise. If source entropy rate is hh, no compressor averages below hh bits per symbol; an LM may approach that bound more closely for sources resembling training.
  • It is impractical at scale. Compressing one gigabyte with a 7 000-million-parameter model costs about 3.5×10183.5 \times 10^{18} operations (at 4 bytes per token and 2N2N operations per token), and the same to decompress; the file opens only with the same model, software, and practically the same hardware type.
  • Compression is not understanding, though correlated. Compression measures mean log likelihood over a specific distribution; a rare ability weighs little in the average.

Common mistakes

Exercises

NumericFrom nats per token to bits per byte
A model has loss 2.0 nats per token and its tokenizer averages 4 bytes per token. How many bits per byte does it spend as a compressor?
NumericPerplexity of a loss
What perplexity corresponds to loss 2.0 nats per token?
NumericShannon's upper bound
In a guessing game, a subject succeeds on the first attempt 80% of the time, second 10%, third 5%, and fourth 5%. Calculate Shannon's upper bound on entropy per letter in bits.
NumericWhen does sending the model pay off?
A 125-million-parameter model stored in 16 bits compresses text to 0.9 bits per byte; xz achieves 2.285 bits per byte. Above how many gigabytes (10910^9 bytes) of text is the LM message plus model smaller than xz?
ProofArithmetic-code length
Prove: With infinite precision and known length nn, arithmetic coding guided by model qq satisfies −log⁡2q(xn)<ℓ(xn)<−log⁡2q(xn)+2-\log_2 q(x^n) < \ell(x^n) < -\log_2 q(x^n) + 2 and is a prefix code. Expected length consequently differs by less than 2 bits from nn times cross-entropy, and minimizing expected loss minimizes expected length up to those 2 bits.
0
Order the alphabet and associate each xnx^n with interval I(xn)=[F(xn),F(xn)+q(xn))I(x^n) = [F(x^n), F(x^n) + q(x^n)) from subdividing [0,1)[0, 1) step by step according to q(⋅∣x<t)q(\cdot \given x_{<t}). The code for xnx^n is the first ℓ=⌈−log⁡2q(xn)⌉+1\ell = \lceil -\log_2 q(x^n)\rceil + 1 bits of k 2−ℓk\,2^{-\ell}, with k=⌈F(xn) 2ℓ⌉k = \lceil F(x^n)\,2^{\ell}\rceil.

Step 1 of 4. Why are intervals I(xn)I(x^n) of distinct length-nn sequences disjoint and of width q(xn)q(x^n)?

QuizWhich compresses better?
On the same evaluation text, model A has perplexity 12 with 3 bytes per token, and model B perplexity 20 with 4.5 bytes per token. Which compresses better?
QuizWhy determinism matters
You encode text with an LM on a GPU using a full sequence pass and decode on the same GPU one token at a time with KV cache. What is most likely?
QuizA text far from itself
You compute NCD(x,x)\mathrm{NCD}(x, x) with zlib for text xx of 40 KB and get 1.01. What happened?
CodeFrom compressor to predictor
Implement predictor_from_compressor(compress, context, alphabet), converting an arbitrary compressor (a bytes-to-bytes function) into a distribution over the next byte: q(a∣x)∝2−8 ∣compress(xa)∣q(a \given x) \propto 2^{-8\,\lvert\mathrm{compress}(x a)\rvert} for each byte aa of alphabet, returned as dictionary {a: probabilidad}. Also implement log_loss_bits(compress, text, alphabet), mean −log⁡2q(xt∣x<t)-\log_2 q(x_t \given x_{<t}) over the bytes of text. Ensure numerical stability: on long texts 2−8C2^{-8C} underflows in floating point.
import math

def predictor_from_compressor(compress, context, alphabet):
  """q(a | context) proporcional a 2^(-8 * len(compress(context + a))), para cada byte a de alphabet."""
  # tu código: longitudes, pesos (resta el mínimo antes de exponenciar) y normalización
  return {a: 1 / len(alphabet) for a in alphabet}

def log_loss_bits(compress, text, alphabet):
  """Media de -log2 q(x_t | x_<t) sobre los bytes de text, en bits por byte."""
  # tu código
  return 0.0
Shift+Enter to run

Summary

Key idea
A language model with arithmetic coding is a lossless compressor whose file measures accumulated log loss plus less than 2 bits: training with cross-entropy compresses, and better prediction is the only way to compress better.
  • Shannon (1951) measured English information with a guessing game: attempt counts reversibly encode the text, and their entropy bounds language entropy rate at about 0.6–1.3 bits per letter.
  • LM to compressor: −log⁡2q(xn)<ℓ(xn)<−log⁡2q(xn)+2-\log_2 q(x^n) < \ell(x^n) < -\log_2 q(x^n) + 2, and mean length is nn times cross-entropy, namely H⁡(p)+KL⁡(p ∥ q)\Ent(p) + \KL(p \,\|\, q). Compressor to predictor: qC(a∣x)∝2−C(xa)q_C(a \given x) \propto 2^{-C(xa)}, exact in theory and coarse for byte-granularity compressors.
  • Metrics: PPL=eL^\mathrm{PPL} = e^{\hat{L}} and BPB=L^/(bln⁡2)\mathrm{BPB} = \hat{L}/(b\ln 2). Perplexity depends on tokenizer; bits per byte on the same text do not.
  • Real compression requires encoder and decoder to calculate bit-identical frequency tables: identical incremental code, stable precision, weight revision, and context.
  • The model counts: adjusted rate includes parameters, and an LM pays off only on much larger text. This is two-part MDL; prequential coding avoids sending weights by training at both ends.
  • NCD uses a compressor for similarity. It measures shared substrings, needs texts shorter than the compressor’s window, and classifying by concatenated class text is a Bayesian classifier using the compressor as language model.