Arithmetic coding and universal compression
Arithmetic coding turns a sequential probability model into a compressor using at most −log₂ q(x₁,…,xₙ) + 2 bits. Study adaptive Laplace, Krichevsky–Trofimov and context models that learn while compressing, and universal Lempel–Ziv coding, which reaches the entropy rate without knowing the source.
After this lesson you can
- Explain arithmetic coding as interval refinement and bound its length by −log₂ q(xⁿ) + 2.
- Implement an integer arithmetic coder with renormalization and verify a lossless round trip.
- Use Laplace and KT estimators in adaptive models and compute regret against the best fixed model.
- Implement LZ78 and explain its universality for stationary ergodic sources.
- Identify the modeling and coding parts of a compressor.
Before you start
Motivation: model and coder as separate pieces
A source emits independent zeros and ones with . Its entropy is bits per symbol. The best symbol-by-symbol prefix code, Huffman, cannot give any symbol less than one bit: it spends 1 bit per symbol, 3.5 times the minimum. With it would be over 12 times. The expected-length bound is tight: “+1” is not slack in the analysis, but the cost of rounding each length to an integer number of bits.
One can try to fix this by encoding blocks of symbols at once, reducing excess to per symbol. To stay within bits of entropy (5%), the bound requires , a table of words. There is a second, more serious practical defect: Huffman needs known probabilities, or a preliminary pass to count them and send the table, and does not adapt if the source changes halfway through the file.
Arithmetic coding removes both limitations with one idea: instead of giving each symbol a codeword, it gives one code to the whole message, building it symbol by symbol using probabilities assigned by a model at that moment. The result costs at most bits for the whole message: rounding is paid once, not once per symbol.
This separates any compressor into two independent pieces:
- The model looks at what has been read and distributes probability among possible symbols. All learning happens here.
- The coder converts those probabilities into bits at of the probability of the observed outcome. This is a solved problem, and arithmetic coding solves it nearly optimally.
The lesson covers both pieces. First the coder, in theory (nested intervals) and practice (32-bit integers with renormalization). Then models that learn while compressing: Laplace and Krichevsky–Trofimov estimators, and their learning cost, half a logarithm of message size per parameter. Finally Lempel and Ziv compress without an explicit model yet reach the entropy of any stationary ergodic source. Unless otherwise stated, is base-2 logarithm.
Arithmetic coding: the message is an interval
Let be a finite alphabet with fixed order and a sequential model: for each past it gives a distribution over the next symbol. Write for its cumulative distribution function, the mass of symbols preceding .
Interval width is message probability: by the chain rule. Moreover, intervals of messages of length are disjoint and their union is (if all probabilities are positive): by induction, splitting into pieces is a partition. An improbable message has a tiny interval; a probable one a wide interval. All that remains is to name the interval with few bits.
Distinct equal-length messages have disjoint intervals and thus disjoint cells, and two disjoint dyadic cells cannot contain one another: no code is a prefix of another. This is a prefix code on length- messages, and the decoder needs to know (or an end symbol, paid for within the model).
With initial values (fixed model with , , ), message aaaaabaaaa has bits and encodes in 6 bits; Huffman, giving a 1 bit and b and c 2 each, spends 11. The saving comes from each a costing bits rather than 1: arithmetic coding does not round.
Four things the figure shows:
- Zoom never loses information. Each row contains all that matters from previous rows: it is the same interval, enlarged. Thus, as we will see, the integer implementation can renormalize.
- Bits are decided when the interval falls on one side of a dyadic point. Initially and no bit is fixed; once the interval fits in the first bit is 0, and so on. The fixed prefix is the part common to both endpoints.
- An interval may take time to decide. With and , message
aaboccupies , containing : no bit is certain. Yet cell , code0111, fits inside. The finite implementation calls this E3. (In the figure the ‘aab’ example uses , and because the third symbol needs some mass; the interval changes slightly but still contains and the code remains0111.) - With an adaptive model partitions change from row to row: after many
as, theacell widens. A Huffman code with fixed table cannot do this.
What it costs: the bound
Proof
Let be the width of and , so . Multiples of are separated by , so interval contains one: with , and . Cell then satisfies
so it lies in , and its code is the -bit string writing in binary. Since the shortest code cannot be longer, the bound holds.
∎The extra “+1” relative to Shannon coding, which uses , arises because an entire cell must fit inside the interval, not just a point. The bound is for the whole message. Taking expectations over any source , with the cross entropy of sequences,
If is an iid source and the model is true, , expected length is less than : bits per symbol, versus Huffman’s guarantee . If the model is wrong, , the bound becomes : the extra cost is exactly the divergence of coding with the wrong model, paid per symbol without Huffman’s additional “+1”. A model assigning zero probability to an occurring symbol gives infinite length: that message cannot be encoded.
Decoding repeats the subdivision
The decoder receives and and computes point , inside . It repeats the encoder’s splitting: at each step, with the decoded past, split the interval according to and choose the piece containing . Since length- message intervals partition the space, the choice is unique and matches the original message. The decoder needs exactly the same model, with exactly the same probabilities: the model runs identically on both sides. This causes the hardest errors to debug, and we return to it.
This is the ideal version with exact fractions. Here is the full code, with the lesson example and counts against Huffman on 600 random messages:
from fractions import Fraction
from math import ceil, log2
import heapq, random
def intervalo(mensaje, modelo):
"""Intervalo [bajo, bajo + ancho) del mensaje. modelo(pasado) -> [(simbolo, prob), ...] en orden de alfabeto."""
bajo, ancho = Fraction(0), Fraction(1)
for t, x in enumerate(mensaje):
acum = Fraction(0)
for s, p in modelo(mensaje[:t]):
if s == x:
bajo, ancho = bajo + ancho * acum, ancho * p
break
acum += p
return bajo, ancho
def codigo_corto(bajo, ancho):
"""Cadena binaria más corta cuya celda diádica [0.s, 0.s + 2^-k) cabe en [bajo, bajo + ancho)."""
alto = bajo + ancho
k = 0
while True:
m = ceil(bajo * 2**k) # primer múltiplo de 2^-k que no baja de 'bajo'
if Fraction(m + 1, 2**k) <= alto:
return format(m, f"0{k}b") if k else ""
k += 1
def decodificar(bits, n, modelo):
"""Repite las particiones del modelo y elige, en cada paso, la celda que contiene el punto 0.bits."""
x = Fraction(int(bits, 2), 2**len(bits)) if bits else Fraction(0)
bajo, ancho, salida = Fraction(0), Fraction(1), []
for _ in range(n):
acum = bajo
for s, p in modelo(salida):
if acum <= x < acum + ancho * p:
salida.append(s)
bajo, ancho = acum, ancho * p
break
acum += ancho * p
return "".join(salida)
fijo = lambda probs: (lambda pasado: list(probs.items()))
# el ejemplo de la lección: p(a) = 3/4, p(b) = 1/4 y el mensaje aab
M = fijo({"a": Fraction(3, 4), "b": Fraction(1, 4)})
bajo, ancho = intervalo("aab", M)
codigo = codigo_corto(bajo, ancho)
print(f"aab: intervalo [{bajo}, {bajo + ancho}), ancho {ancho}, -log2 q = {-log2(ancho):.3f}")
print(f"código más corto: {codigo!r} ({len(codigo)} bits); cota ceil(-log2 q) + 1 = {ceil(-log2(ancho)) + 1}")
print("decodificado:", decodificar(codigo, 3, M))
def longitudes_huffman(probs):
cola = [(float(p), i, [s]) for i, (s, p) in enumerate(probs.items())]
heapq.heapify(cola)
largo, contador = {s: 0 for s in probs}, len(cola)
while len(cola) > 1:
p1, _, g1 = heapq.heappop(cola)
p2, _, g2 = heapq.heappop(cola)
for s in g1 + g2:
largo[s] += 1
contador += 1
heapq.heappush(cola, (p1 + p2, contador, g1 + g2))
return largo
# 600 mensajes de 10 símbolos de una fuente iid con p = (0.8, 0.15, 0.05)
P = {"a": Fraction(4, 5), "b": Fraction(3, 20), "c": Fraction(1, 20)}
MP = fijo(P)
huff = longitudes_huffman(P)
H = -sum(float(p) * log2(float(p)) for p in P.values())
rng = random.Random(0)
n, N = 10, 600
largos, huffs, peor_exceso = [], [], -9.0
for _ in range(N):
msg = "".join(rng.choices("abc", [0.8, 0.15, 0.05], k=n))
bajo, ancho = intervalo(msg, MP)
cod = codigo_corto(bajo, ancho)
assert decodificar(cod, n, MP) == msg
assert len(cod) <= ceil(-log2(ancho)) + 1
largos.append(len(cod)); huffs.append(sum(huff[s] for s in msg))
peor_exceso = max(peor_exceso, len(cod) + log2(ancho))
print(f"Huffman: longitudes {huff}")
print(f"media de {N} mensajes de {n} símbolos: aritmético {sum(largos) / N:.2f} bits, Huffman {sum(huffs) / N:.2f} bits, n*H = {n * H:.2f}, n*H + 2 = {n * H + 2:.2f}")
print(f"mayor exceso del código sobre -log2 q: {peor_exceso:.3f} bits (la cota dice < 2)")The round trip is exact on all 600 messages and bound always holds (largest excess over is 1.95 bits, below 2). Mean length is 9.90 bits versus Huffman’s 12.05, and : mean excess just over 1 bit is rounding of the entire message, not each symbol. With 1000 symbols that rounding would be around 0.1% of bits.
Finite implementation: integers, renormalization and pending bits
The previous scheme has a practical problem: required precision grows with the message. An -symbol message interval has width of order and endpoints are rationals with millions of digits. The zoom observation saves it: each row contains the same as previous ones, enlarged. Maintain the current interval in an -bit integer variable (here ) and whenever it narrows, enlarge it and emit bits already decided.
The state is with -bit integers representing enlarged . To encode a symbol with cumulative frequencies over total , split current range :
Then renormalize whenever possible, with three cases:
| Case | Condition | What happens |
|---|---|---|
| E1 | The first bit is 0. Emit it and pending bits as 1. Double the interval. | |
| E2 | The first bit is 1. Emit it (and pending bits as 0). Subtract and double. | |
| E3 | and | The interval contains but is far from the edges. Emit nothing: record a pending bit, subtract and double. |
E3 is the case seen with aab. When the interval falls within the next bit is not yet known, but whichever it is, the following bit will be its complement: if the interval ends in , the sequence starts ; if it ends in , . Thus pending bits accumulate and are resolved together when the next decided bit is emitted (E1 or E2). Without E3, a very narrow interval straddling could not be enlarged and the range would run out.
At the end, enough bits must be written to identify a point in the final interval: one plus pending bits. This costs at most 2 bits above ideal. The decoder does the same with input: it keeps an -bit valor window of the code and, when renormalizing, shifts it and reads a new bit.
Limited precision costs very little. After renormalization, . If frequency totals do not exceed , partition truncation changes each cell width by a relative factor below , and loss is below bits per symbol. The model must, however, provide integer frequencies with a bounded total, none zero.
PREC = 32
TOP = 1 << PREC
HALF, QUARTER = TOP >> 1, TOP >> 2
class Codificador:
def __init__(self):
self.bajo, self.alto = 0, TOP - 1 # intervalo [bajo, alto], inclusivo
self.pendientes = 0 # bits de E3 todavía sin decidir
self.bits = []
def _emitir(self, b):
self.bits.append(b)
self.bits.extend([1 - b] * self.pendientes) # los pendientes son el complemento
self.pendientes = 0
def codificar(self, c_bajo, c_alto, total):
r = self.alto - self.bajo + 1
self.alto = self.bajo + r * c_alto // total - 1
self.bajo = self.bajo + r * c_bajo // total
while True:
if self.alto < HALF: # E1
self._emitir(0)
elif self.bajo >= HALF: # E2
self._emitir(1)
self.bajo -= HALF; self.alto -= HALF
elif self.bajo >= QUARTER and self.alto < 3 * QUARTER: # E3
self.pendientes += 1
self.bajo -= QUARTER; self.alto -= QUARTER
else:
break
self.bajo = 2 * self.bajo
self.alto = 2 * self.alto + 1
def terminar(self):
self.pendientes += 1
self._emitir(0 if self.bajo < QUARTER else 1)
return self.bits
class Decodificador:
def __init__(self, bits):
self.bits, self.pos = bits, 0
self.bajo, self.alto = 0, TOP - 1
self.valor = 0
for _ in range(PREC):
self.valor = 2 * self.valor + self._leer()
def _leer(self):
b = self.bits[self.pos] if self.pos < len(self.bits) else 0 # pasado el final, ceros
self.pos += 1
return b
def objetivo(self, total):
"""Frecuencia acumulada a la que apunta el código: dice en qué símbolo estamos."""
r = self.alto - self.bajo + 1
return ((self.valor - self.bajo + 1) * total - 1) // r
def avanzar(self, c_bajo, c_alto, total):
r = self.alto - self.bajo + 1
self.alto = self.bajo + r * c_alto // total - 1
self.bajo = self.bajo + r * c_bajo // total
while True:
if self.alto < HALF:
pass
elif self.bajo >= HALF:
self.bajo -= HALF; self.alto -= HALF; self.valor -= HALF
elif self.bajo >= QUARTER and self.alto < 3 * QUARTER:
self.bajo -= QUARTER; self.alto -= QUARTER; self.valor -= QUARTER
else:
break
self.bajo = 2 * self.bajo
self.alto = 2 * self.alto + 1
self.valor = 2 * self.valor + self._leer()
# el mismo mensaje aab con frecuencias enteras: a = [0, 3), b = [3, 4), total 4
c = Codificador()
for lo, hi in [(0, 3), (0, 3), (3, 4)]:
c.codificar(lo, hi, 4)
bits = c.terminar()
print("código entero de aab:", "".join(map(str, bits)), f"({len(bits)} bits; el ideal exacto era 0111)")
d = Decodificador(bits)
salida = ""
for _ in range(3):
t = d.objetivo(4)
lo, hi, s = (0, 3, "a") if t < 3 else (3, 4, "b")
d.avanzar(lo, hi, 4)
salida += s
print("decodificado:", salida)The integer code matches the ideal, 0111, and the path is predicted: during encoding no bit is emitted because the interval straddles and E3 accumulates two pending bits; at the end the termination bit is emitted and the two pending bits resolve as its complement. Generally termination policy (“one plus pending bits”) does not seek the shortest cell and may spend one more bit than ideal code: those two bits are the full termination cost.
What remains is connecting a model. The contract is minimal: a model exposes its alphabet, a frecuencias() function returning positive integers for the next symbol, and an actualizar(s) function. The coder knows nothing else. Here is the simplest contextual model, with the previous symbols and the KT estimator explained next (frequencies , i.e. doubled to make integers), and a round trip on random messages:
import math, random
class ModeloContexto:
"""Estimador KT (a2 = 1) o de Laplace (a2 = 2) con el contexto de los últimos 'orden' símbolos.
Frecuencias enteras 2 n_s + a2, es decir, el doble de (n_s + a)."""
def __init__(self, alfabeto, orden=0, a2=1):
self.alfabeto, self.orden, self.a2 = list(alfabeto), orden, a2
self.cuentas, self.ctx = {}, ""
def _c(self):
return self.cuentas.setdefault(self.ctx, [0] * len(self.alfabeto))
def frecuencias(self):
return [2 * c + self.a2 for c in self._c()]
def probs(self):
f = self.frecuencias(); T = sum(f)
return [x / T for x in f]
def actualizar(self, s):
self._c()[self.alfabeto.index(s)] += 1
if self.orden:
self.ctx = (self.ctx + s)[-self.orden:]
def comprimir(mensaje, modelo):
cod, ideal = Codificador(), 0.0
for s in mensaje:
f = modelo.frecuencias()
i, T = modelo.alfabeto.index(s), sum(f)
bajo = sum(f[:i])
cod.codificar(bajo, bajo + f[i], T)
ideal -= math.log2(f[i] / T)
modelo.actualizar(s)
return cod.terminar(), ideal
def descomprimir(bits, n, modelo):
dec, salida = Decodificador(bits), []
for _ in range(n):
f = modelo.frecuencias()
T = sum(f)
objetivo, acum = dec.objetivo(T), 0
for i, x in enumerate(f):
if objetivo < acum + x:
break
acum += x
dec.avanzar(acum, acum + x, T)
modelo.actualizar(modelo.alfabeto[i])
salida.append(modelo.alfabeto[i])
return "".join(salida)
random.seed(1)
exceso = []
for _ in range(300):
n = random.randint(0, 400)
pesos = [random.random() ** 3 for _ in "abc"]
texto = "".join(random.choices("abc", pesos, k=n))
for orden in (0, 1, 2):
bits, ideal = comprimir(texto, ModeloContexto("abc", orden))
assert descomprimir(bits, n, ModeloContexto("abc", orden)) == texto
exceso.append(len(bits) - ideal)
print(f"ida y vuelta correcta en {len(exceso)} mensajes de 0 a 400 símbolos")
print(f"exceso sobre -log2 q: mínimo {min(exceso):.3f}, medio {sum(exceso) / len(exceso):.3f}, máximo {max(exceso):.3f} bits")Round trips are verified on 900 messages (three context orders and messages up to 400 symbols), and excess over ideal always stays below the 2 termination bits (minimum 0.04, mean 1.08, maximum 1.98): finite-precision loss is negligible. The coder does not know which of the three models it uses.
Sequential models: predicting is compressing
The coder only needs a model to distribute probability over next symbols given the past. This has a name.
The equivalence between a predictor and a distribution over sequences is immediate, but has a deep consequence. By the bound above, code length is, within 2 bits, the predictor’s cumulative log loss:
Each symbol costs what surprised the model, and the code sums surprises. If is the true source, mean excess over optimum is , and by the KL chain rule it decomposes token by token:
Improving a compressor means improving a predictor, and an arithmetic compressor with a predictor exactly measures its log loss. This idea closes the next lesson, with language models as predictors. Meanwhile retain the division of labor: the coder is fixed, and everything one can do to compress better means making better predictions.
The problem: we do not know
If the source is iid Bernoulli with known parameter , model is optimal. But is almost never known. Two obvious approaches fail. Estimating from the data and sending it before the message requires a first pass and paying parameter bits. Using (frequency observed so far) is disastrous: the first time a new symbol appears, assigns it zero probability and the message cannot be encoded.
The working approach is mixing: use as model the data probability averaged over all with prior distribution ,
where counts ones in . It is a probability over sequences (consistent because it mixes consistent probabilities), and its predictive is the Bayesian model’s posterior predictive: a sequential model ready for the coder. With conjugate Beta prior the predictive has closed form and updates with two counters, in constant time per symbol.
Proof
With and density ,
which depends only on . For , and . For , and . The predictive is the ratio of the probabilities of and :
using .
∎Read it as a counting rule: Laplace says “add one imaginary case of each symbol” ( ones appeared in : ) and KT says “add half a case” (). After consecutive zeros, KT assigns the first one probability and Laplace : Laplace still reserves almost twice as much mass for what has never occurred (ratio ), and pays for that at each zero.
Regret: the cost of learning
The natural measure of not knowing is regret: how many extra bits the code spends relative to the best model in the family, chosen afterward with data in view,
with , binary entropy of the observed frequency. This is excess over an oracle that already saw all data, usually measured in the worst case over sequences.
Proof
(1) The formula follows from . To bound it use , which follows from . Then for all , and for , and give exactly .
(2) On the all-zero sequence, , and since the best model encodes it with 0 bits, . Asymptotic gives . For general , the bound follows from an analogous inequality on gamma-function ratios (Krichevsky and Trofimov, 1981); we check it numerically for every below.
∎The figure assembles everything. It generates a sequence with bias and plots each code’s regret over time.
Three readings of the figure:
- Learning one parameter costs bits. Neither Laplace nor KT has a linear cost: after symbols the bits paid grow only logarithmically and excess per symbol is . That is the information needed to estimate with the precision data permit ( is determined to error of order , and distinguishing values costs bits). In a model with parameters the cost is ; lesson 18 proves no universal code generally improves it.
- Laplace is U-shaped and KT is flat. With near Laplace wins by about bits, but near extremes pays nearly double: versus . (Laplace wins while , i.e. for between roughly and .) KT was designed to be uniformly good, and per-sequence regret is nearly constant in the interior.
- Regret is measured against a class. With the best iid model is and costs 1 bit per symbol; KT achieves it nearly losslessly, but a context model (which symbol came before) would cost near 0. Low regret does not mean the code is good, but good for that model class.
How much better can a universal code do? The minimum possible worst case over all codes is Shtarkov’s minimax regret, , equal to : 3.72 bits with and 5.33 with (verified below). KT’s worst case lies within half a bit of that optimum, and KT has a decisive advantage: it is sequential, needing no advance knowledge of . This is one reason it is the default estimator in compression.
from math import lgamma, comb, log, log2, pi
import random
def bits_kt(n, k): # -log2 q_KT(x), para cualquier secuencia con k unos
return -(lgamma(k + .5) + lgamma(n - k + .5) - log(pi) - lgamma(n + 1)) / log(2)
def bits_laplace(n, k): # -log2 q_L(x) = log2((n + 1) C(n, k))
return log2(n + 1) + log2(comb(n, k))
def bits_ml(n, k): # n h2(k/n): el mejor theta en retrospectiva
return 0.0 if k in (0, n) else -(k * log2(k / n) + (n - k) * log2((n - k) / n))
def secuencial(bits, a): # producto de las predictivas (k_t + a)/(t + 2a), en bits
cuentas, total = [0, 0], 0.0
for t, x in enumerate(bits):
total -= log2((cuentas[x] + a) / (t + 2 * a))
cuentas[x] += 1
return total
# 1) el producto secuencial es la forma cerrada, y no depende del orden
random.seed(0)
x = [1 if random.random() < 0.2 else 0 for _ in range(60)]
y = x[:]; random.shuffle(y)
k = sum(x)
print(f"n = 60, k = {k}: KT {secuencial(x, .5):.6f} = {secuencial(y, .5):.6f} (barajada) = {bits_kt(60, k):.6f} (cerrada)")
print(f" Laplace {secuencial(x, 1):.6f} = {secuencial(y, 1):.6f} = {bits_laplace(60, k):.6f}")
# 2) la cota de KT, 1/2 log2 n + 1, en todos los (n, k) con n <= 400
peor = max(bits_kt(n, k) - bits_ml(n, k) - (0.5 * log2(n) + 1) for n in range(1, 401) for k in range(n + 1))
print(f"max sobre n <= 400 y todo k de regret_KT - (1/2 log2 n + 1) = {peor:.4f} (<= 0: la cota se cumple)")
# 3) regret en los dos extremos de θ
print(" n KT(0^n) Lap(0^n) log2(n+1) KT(k=n/2) Lap(k=n/2) 1/2 log2(pi n/2)")
for n in (10, 100, 1000, 10000):
r = lambda f, k: f(n, k) - bits_ml(n, k)
print(f"{n:6d} {r(bits_kt, 0):7.3f} {r(bits_laplace, 0):8.3f} {log2(n + 1):9.3f} {r(bits_kt, n // 2):9.3f} {r(bits_laplace, n // 2):10.3f} {0.5 * log2(pi * n / 2):14.3f}")
# 4) el regret minimax de Shtarkov (n h2 en cada k): log2 de la suma de máximas verosimilitudes
def minimax(n):
s = 0.0
for k in range(n + 1):
lp = lgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1)
if 0 < k < n:
lp += k * log(k / n) + (n - k) * log((n - k) / n)
s += 2.718281828459045 ** lp
return log2(s)
print("minimax:", {n: round(minimax(n), 3) for n in (100, 1000)}, "frente a 1/2 log2(pi n/2) =", {n: round(0.5 * log2(pi * n / 2), 3) for n in (100, 1000)})Context models and model mixtures
An iid model is poor for text, code or images. The natural improvement is conditioning on context: predict the next symbol from the previous . Learning a KT table for each possible context gives an order- model with parameters, each with learning cost of order . The tradeoff is concrete: long context predicts better but has very little data per context; short context learns fast but predicts worse. Best order depends on how much data there is.
Theory’s answer is again mixing. Two method families do this systematically:
- PPM (prediction by partial matching, Cleary and Witten, 1984) uses the longest previously seen context and, when the symbol never occurred there, “escapes” to a shorter context, reserving an escape probability that is itself a modeling decision.
- Context-tree weighting (CTW, Willems, Shtarkov and Tjalkens, 1995) computes the exact Bayesian mixture of all bounded-depth tree models recursively over the context tree, in time linear in times depth. “Choosing” the tree (how many contexts to distinguish) costs about a couple of bits per leaf, and parameters the usual per leaf.
Smoothed -gram models (module 17) are exactly context models of this kind, and a transformer is a context model with a huge window and much more sophisticated information allocation. The structure is the same: a predictor connected to this coder.
To see the effect on real text, the next cell compresses a roughly 1900-character paragraph using KT models of orders 0 through 3, Laplace of order 1, and the Bayesian mixture of orders 0 through 3 (weights proportional to each model’s cumulative likelihood). All use the same integer coder:
import math
TEXTO = (
"Comprimir es predecir. Un compresor sin pérdida divide su trabajo en dos partes que conviene no mezclar. "
"La primera es un modelo, que mira lo ya leído y reparte una probabilidad entre los símbolos que pueden venir después. "
"La segunda es un codificador, que recibe esas probabilidades y escribe bits, tantos como la sorpresa de cada símbolo. "
"Cuanto mejor predice el modelo, menos bits gasta el codificador, y si el modelo se equivoca, el codificador no puede arreglarlo. "
"La codificación aritmética es el codificador ideal para cualquier modelo: no redondea las longitudes a un número entero de bits "
"y no necesita construir una tabla de códigos para cada bloque de símbolos. "
"Basta con que el modelo diga, en cada paso, cuánta probabilidad da a cada símbolo posible. "
"El decodificador repite exactamente los mismos cálculos, y por eso recupera el mensaje sin perder ni un solo carácter. "
"Los modelos adaptativos aprenden mientras comprimen: empiezan sin saber nada, cuentan lo que van viendo y mejoran con cada símbolo. "
"El precio de aprender es pequeño, medio logaritmo del tamaño del mensaje por cada parámetro que se estima. "
"Los compresores por diccionario, como los de la familia de Lempel y Ziv, siguen otro camino: no calculan probabilidades, "
"sino que sustituyen las cadenas que ya han aparecido por una referencia corta. "
"Aun así, sin conocer la fuente, alcanzan en el límite la entropía de cualquier fuente estacionaria y ergódica. "
"Un fichero cifrado no se puede comprimir, porque un buen cifrado produce bytes que parecen aleatorios, "
"y no hay ningún modelo que prediga mejor que el azar. Por eso se comprime primero y se cifra después. "
"Un modelo de lenguaje es, en este sentido, un compresor: la pérdida de entropía cruzada que se minimiza al entrenarlo "
"es el número de bits que un codificador aritmético necesitaría para escribir el texto de entrenamiento. "
)
alfabeto = sorted(set(TEXTO))
print(f"{len(TEXTO)} caracteres ({len(TEXTO.encode('utf-8'))} bytes en UTF-8), alfabeto de {len(alfabeto)} símbolos")
class Mezcla:
"""Mezcla bayesiana de modelos KT de órdenes distintos. Frecuencias enteras cuantizadas a 2^16."""
def __init__(self, alfabeto, ordenes=(0, 1, 2, 3)):
self.alfabeto = list(alfabeto)
self.modelos = [ModeloContexto(alfabeto, k) for k in ordenes]
self.logw = [0.0] * len(ordenes) # log de la verosimilitud acumulada de cada modelo
def frecuencias(self):
mx = max(self.logw)
w = [math.exp(l - mx) for l in self.logw]
self.P = [m.probs() for m in self.modelos]
n = len(self.alfabeto)
mezcla = [sum(w[j] * self.P[j][i] for j in range(len(w))) / sum(w) for i in range(n)]
return [1 + int(p * (65536 - n)) for p in mezcla] # enteros >= 1
def actualizar(self, s):
i = self.alfabeto.index(s)
for j, m in enumerate(self.modelos):
self.logw[j] += math.log(self.P[j][i])
m.actualizar(s)
resultados = {}
for nombre, modelo in [("KT orden 0", ModeloContexto(alfabeto, 0)), ("KT orden 1", ModeloContexto(alfabeto, 1)),
("KT orden 2", ModeloContexto(alfabeto, 2)), ("KT orden 3", ModeloContexto(alfabeto, 3)),
("Laplace orden 1", ModeloContexto(alfabeto, 1, a2=2)), ("mezcla de órdenes 0 a 3", Mezcla(alfabeto))]:
bits, ideal = comprimir(TEXTO, modelo)
resultados[nombre] = len(bits)
print(f"{nombre:25s} {len(bits):6d} bits = {len(bits) / 8:7.1f} bytes {len(bits) / len(TEXTO):.3f} bits por carácter")
mejor = min(v for k, v in resultados.items() if k.startswith("KT"))
print(f"la mezcla paga {resultados['mezcla de órdenes 0 a 3'] - mejor} bits sobre el mejor orden (cota teórica: log2 4 = 2, más cuantización)")Three observations. First, on such short text order 1 wins (894 bytes, 3.85 bits per character, versus order 0’s 1004), and orders 2 and 3 worsen (987 and 1093 bytes): long context does not predict worse, but each new context must be learned from scratch and 1900 characters are insufficient. This is per parameter, multiplied by many parameters. Second, Laplace loses to KT with large alphabets (935 bytes versus 894 at order 1): reserving “one imaginary case” of each of 42 symbols in each context spends too much mass on what does not occur. Third, the order mixture is within 3 bits of the best (7157 versus 7154), without knowing which: that “which” costs at most bits (the Bayesian mixture’s share with 4 models), plus integer probability quantization. This is mixtures’ general guarantee: a mixture of models with equal initial weights is never more than bits from the best for any sequence (because ). The same mechanism with a continuum indexed by yields KT’s .
Lempel–Ziv: compressing without knowing the source
Until now compression meant modeling: a predictor with a family of parameters and a price for learning them. Lempel and Ziv’s algorithm does something different, powerful enough to underlie gzip, zip, GIF and PNG: it calculates no probabilities but replaces previously seen strings with references. Without knowing the source, it asymptotically reaches entropy of any stationary ergodic source.
With and and string ABAABABAABAB: first phrase is A (new), second B (new), then A already exists so third is AA; next B exists, fourth is BA; then B, BA exist and fifth is BAA; sixth is BAB. Six phrases, encoded as . The dictionary is a tree: each phrase is a node whose parent is its prefix phrase, a trie (prefix tree) over the alphabet, and finding the longest known phrase traverses it. A hash table (chaining) on pairs does this in constant time per symbol.
ABAABABAABAB). How far from entropy is LZ78 at ? And order-1 KT? Lower to (pure noise): what does it converge to? With the periodic source of entropy 0, how long does LZ78 take to fall below bits per symbol?Why it is universal
LZ78 code length with phrases is plus a term of order . Everything reduces to how many phrases the sequence has. A very regular sequence splits into a few long phrases, a random one into many short phrases.
The full proof (Ziv and Lempel, 1978; Cover and Thomas, chapter 13) is long. Here is the skeleton, including the step containing the idea.
Proof
(Sketch.) 1. Few phrases. Since phrases are distinct, at most have length , and filling short-length slots forces .
2. Ziv’s inequality. Let be any order- Markov source and the number of length- phrases starting in state (the previous symbols). Such phrases are distinct, so their probabilities under sum to at most 1 and their product is at most (the product of positive numbers with sum is ). Multiplying over all phrases:
where is entropy of a phrase’s (length, state) distribution .
3. The correction term is small. Mean phrase length is , and maximum entropy with that mean is ; state contributes at most . With this gives .
4. Conclusion. for every order- Markov , particularly the best. For a stationary ergodic source, the best order- achieves a rate tending to as . Taking then gives the stated upper bound. The lower bound in expectation is the source coding theorem: expected length of any prefix code for is at least , since for a stationary source decreases toward entropy rate.
∎Notice what has not been assumed: any source distribution. LZ78 is one algorithm that works asymptotically for every stationary ergodic source. Note also step 3, which gives the cost of this generality: relative error decays like , extremely slowly. The figure and next cell show it: with entropy is and, with symbols, LZ78 still spends bits per symbol, while order-1 KT, which knows the source is order-1 Markov, spends (slightly below entropy because this sample has fewer transitions than average). A compressor knowing the model class learns much faster. LZ universality is not free: it guarantees asymptotic performance without prior knowledge.
LZ77 (1977) is the family’s other member. Instead of a growing dictionary it uses a sliding window over the past: each phrase is a copy of a window substring plus one symbol. It has the same asymptotic guarantee and underlies DEFLATE (with Huffman coding on pairs), the gzip and zlib format. LZW, Welch’s variant that emits no extra symbol, is used by GIF.
import math
import numpy as np
def lz78(x):
"""Devuelve la lista de frases como pares (índice del prefijo, símbolo). Si la última queda a medias, es (índice, None)."""
arbol, frases, nodo = {}, [], 0
for s in x:
hijo = arbol.get((nodo, s))
if hijo is None:
arbol[(nodo, s)] = len(frases) + 1 # nueva frase: nodo del trie
frases.append((nodo, s))
nodo = 0
else:
nodo = hijo
if nodo:
frases.append((nodo, None))
return frases
def deslz78(frases):
dic, salida = [()], []
for padre, s in frases:
f = dic[padre] + (() if s is None else (s,))
dic.append(f)
salida.extend(f)
return salida
def bits_lz78(frases):
"""Código formal: la frase j necesita ceil(log2 j) bits de puntero y 1 bit de símbolo (alfabeto binario)."""
return sum(math.ceil(math.log2(j)) + 1 for j in range(1, len(frases) + 1))
ej = [0 if ch == "A" else 1 for ch in "ABAABABAABAB"]
fr = lz78(ej)
print("ABAABABAABAB ->", fr, f"({len(fr)} frases)")
assert deslz78(fr) == ej
# cadena de Markov simétrica de 2 estados: se queda con probabilidad a; tasa de entropía h2(a)
def markov(n, a, rng):
cambia = rng.random(n) >= a
cambia[0] = False
return ((rng.integers(0, 2) + np.cumsum(cambia)) % 2).astype(int)
def h2(p):
return -p * math.log2(p) - (1 - p) * math.log2(1 - p)
def coste_kt1(x):
"""Bits del codificador aritmético con KT de orden 1 (cuenta cada par anterior-siguiente)."""
c, total, prev = [[0, 0], [0, 0]], 0.0, int(x[0])
total += 1.0 # el primer símbolo, sin contexto: 1 bit
for s in x[1:]:
s = int(s)
total -= math.log2((c[prev][s] + 0.5) / (sum(c[prev]) + 1))
c[prev][s] += 1
prev = s
return total
a = 0.9
rng = np.random.default_rng(0)
x = markov(1 << 16, a, rng)
print(f"fuente de Markov con a = {a}: tasa de entropía h2(a) = {h2(a):.4f} bits por símbolo")
print(" n frases LZ78 (bits/símbolo) KT orden 1 modelo verdadero")
for e in range(10, 17, 2):
n = 1 << e
xs = x[:n]
fr = lz78(xs.tolist())
assert deslz78(fr) == xs.tolist()
misma = np.sum(xs[1:] == xs[:-1])
verdadero = -(misma * math.log2(a) + (n - 1 - misma) * math.log2(1 - a)) / n
print(f"{n:8d} {len(fr):7d} {bits_lz78(fr) / n:17.3f} {coste_kt1(xs) / n:10.3f} {verdadero:15.3f}")The cell reproduces the figure with numbers: LZ78 falls with but at a snail’s pace (from at to at , always far from ), and both arithmetic codes hug entropy from the beginning. In exchange, LZ78 does not need to know the source is Markov: replace it with an order-5 source or text and the algorithm is the same.
ANS: the fast modern alternative
Arithmetic coding has an engineering drawback: each symbol requires integer multiplication and division and a renormalization loop, and is inherently sequential. Asymmetric numeral systems (ANS, Jarek Duda, 2013) obtain the same compression efficiency with cheaper operations: the coder state is a single integer containing all information encoded so far, and adding symbol of probability transforms state with , making the state grow by bits. Its table variant (tANS) avoids division and is used by Zstandard (under the name FSE) to encode match lengths and distances; rANS better exploits vector instructions. In exchange it works as a stack (the last symbol encoded is the first decoded), so encoding runs backward. The same division of labor applies: the model computes and a coder, here ANS, converts probabilities to bits. Only speed changes. Source: Duda, 2013.
The library version
Python includes three compressors in its standard library. Each combines a different model and coder, which this lesson lets us interpret:
| Module | Algorithm | Implicit model | Coder |
|---|---|---|---|
zlib (DEFLATE) | LZ77 with 32 KB window | recent repetitions | Huffman, with per-block tables |
bz2 | Burrows–Wheeler transform, move-to-front | long context sorted by similarity | Huffman |
lzma | LZ77 with large window | repetitions and adaptive context | adaptive binary range coder |
The next cell compresses the same paragraph with all three, comparing them with the previous cell’s order-1 model, repeated text, random bytes and text “encrypted” with a pseudorandom stream (toy encryption: XOR with a random-number-generator sequence, sufficient for the experiment):
import zlib, bz2, lzma
import numpy as np
datos = TEXTO.encode("utf-8")
n = len(datos)
rng = np.random.default_rng(0)
cifrado = bytes(np.frombuffer(datos, dtype=np.uint8) ^ rng.integers(0, 256, size=n, dtype=np.uint8))
aleatorio = rng.integers(0, 256, size=n, dtype=np.uint8).tobytes()
def tamanos(b):
return len(zlib.compress(b, 9)), len(bz2.compress(b, 9)), len(lzma.compress(b, preset=9))
print(f"{'entrada':34s}{'bytes':>7s}{'zlib':>7s}{'bz2':>7s}{'lzma':>7s}")
for nombre, b in [("párrafo", datos), ("párrafo repetido 4 veces", datos * 4), ("bytes aleatorios", aleatorio), ("párrafo cifrado (XOR con flujo)", cifrado)]:
z, bz, lz = tamanos(b)
print(f"{nombre:34s}{len(b):7d}{z:7d}{bz:7d}{lz:7d}")
kt1 = lambda t: len(comprimir(t, ModeloContexto(alfabeto, 1))[0]) / 8
print(f"modelo aritmético KT de orden 1 (sin cabecera ni alfabeto): párrafo {kt1(TEXTO):.1f} bytes, repetido 4 veces {kt1(TEXTO * 4):.1f} bytes")Three observations. With a short paragraph (1889 bytes), order-1 arithmetic model (894 bytes, excluding header and alphabet the decoder must know) beats bz2 (912), zlib (922) and lzma (1040), whose headers weigh heavily in such a small file. With the paragraph repeated four times dictionary compressors win (zlib 981 bytes, lzma 1072): a long repetition is one reference, whereas a model looking only at the previous character cannot see repetitions (order 1 spends 3125 bytes: it learns something but is far behind). With random or encrypted data, all fail and produce a file larger than input (for random bytes, 1900, 2312 and 1952 bytes for 1889; encrypted text is nearly the same): there is no exploitable structure and headers and escape codes add bytes.
Common mistakes
Exercises
ABAABABAABAB.More than one answer may be correct.
float32 on a GPU to compress. The file is decompressed on another computer using the same network and weights but a CPU. Sometimes it works, sometimes it does not. What explains this?Step 1 of 4. What is integral equal to?
logprob_kt(bits), which receives a list of 0s and 1s and returns by multiplying sequential predictives , where is the number of symbols seen and how many equal the incoming symbol. Sum logarithms (do not multiply probabilities): with the product underflows. Then check that the result does not depend on order.import math
def logprob_kt(bits):
"""log2 de la probabilidad KT de la secuencia binaria bits."""
# tu código
return 0.0