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 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 coupled to an arithmetic coder is a lossless compressor, and its output length is, within two bits, the sum of surprises . 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 ....
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 , the preceding context of letters, and attempts . Since is a function of and a function of ,
where . Conditional entropy of the next letter, which with 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 mix uniform distributions over the first letters, with weights ; entropy is concave and each uniform contributes , 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 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 (letters, bytes, or tokens) is a sequential probability assignment: for each prefix , a distribution . By the chain rule it defines a probability over length- sequences,
The arithmetic coder converts that probability into bits. It starts with interval , divides it at each step into subintervals proportional to in a fixed alphabet order, and keeps the actual symbol’s interval. After steps the interval for has width , and sending the bits of a short binary number inside suffices.
The final guided exercise proves this: take and show there is always a dyadic interval of width inside the interval for , 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:
Thus compression with an imperfect model costs exactly its KL divergence from the source, in bits. No compressor goes below by the source coding theorem.
Connect this to training. LM loss is mean cross-entropy in nats per token, , using the usual softmax cross-entropy loss. Therefore
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 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.
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 satisfies the Kraft inequality, , so
is a (sub)probability. A good compressor assigns short codes to likely strings, making a good model. To predict the next symbol condition: , where should sum over all continuations of . 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:
with 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 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, 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 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:
| Text | Tokens | Bytes | Bytes per token | Nats per token | Perplexity | Bits per byte |
|---|---|---|---|---|---|---|
| Spanish | 96 | 357 | 3.72 | 3.004 | 20.2 | 1.166 |
| English | 77 | 325 | 4.22 | 3.314 | 27.5 | 1.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.
The lower curve illustrates the tokenizer trap. At fixed BPB, 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.
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 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 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.
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 : 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 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 , so frequencies require more bits (we use 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 operations for 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.
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)}")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 , 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
Predictoris 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:
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 bytes and compresses at bits per byte versus a classical compressor at , the LM pays off beyond
With Qwen2.5-0.5B in 16 bits ( GB), and the measured for xz on WikiText-2 test, 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 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 is a compressor, estimates bits needed to describe when is already known. If and 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 (), monotonic (), symmetric (), and distributive. Real compressors satisfy these only approximately; idempotence fails dramatically when the string exceeds what the compressor remembers.
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 bytes. If , when compressing the compressor has forgotten the start of upon reaching , so and 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: 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 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 -NN concatenates each class’s training text, , and assigns to the class most reducing its compression cost, . By this lesson’s equivalence, , the log likelihood of under a model trained on class : a generative Bayesian classifier using the compressor as language model. The cell compares it with -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.
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. -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. -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 ; 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 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 , no compressor averages below 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 operations (at 4 bytes per token and 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
Step 1 of 4. Why are intervals of distinct length- sequences disjoint and of width ?
predictor_from_compressor(compress, context, alphabet), converting an arbitrary compressor (a bytes-to-bytes function) into a distribution over the next byte: for each byte of alphabet, returned as dictionary {a: probabilidad}. Also implement log_loss_bits(compress, text, alphabet), mean over the bytes of text. Ensure numerical stability: on long texts 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.0Summary
- 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: , and mean length is times cross-entropy, namely . Compressor to predictor: , exact in theory and coarse for byte-granularity compressors.
- Metrics: and . 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.