Module contents
Lesson 7 of 19Core 115 min

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 P(1)=0.05\Pr(1) = 0.05. Its entropy is H⁡=0.286\Ent = 0.286 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 P(1)=0.01\Pr(1) = 0.01 it would be over 12 times. The expected-length bound H⁡≤L<H⁡+1\Ent \le L < \Ent + 1 is tight: “+1” is not slack in the analysis, but the cost of rounding each length −log⁡2p(x)-\log_2 p(x) to an integer number of bits.

One can try to fix this by encoding blocks of mm symbols at once, reducing excess to 1/m1/m per symbol. To stay within 0.0140.014 bits of entropy (5%), the bound requires m≥70m \ge 70, a table of 2702^{70} 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 −log⁡2q(x1,…,xn)+2-\log_2 q(x_1, \dots, x_n) + 2 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 −log⁡2-\log_2 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, log⁡\log is base-2 logarithm.

Arithmetic coding: the message is an interval

Let X\mathcal{X} be a finite alphabet with fixed order and qq a sequential model: for each past x<tx_{<t} it gives a distribution q(⋅∣x<t)q(\cdot \mid x_{<t}) over the next symbol. Write F(x∣x<t)=∑y<xq(y∣x<t)F(x \mid x_{<t}) = \sum_{y < x} q(y \mid x_{<t}) for its cumulative distribution function, the mass of symbols preceding xx.

Interval width is message probability: wn=∏tq(xt∣x<t)=q(x1:n)w_n = \prod_t q(x_t \mid x_{<t}) = q(x_{1:n}) by the chain rule. Moreover, intervals of messages of length nn are disjoint and their union is [0,1)[0, 1) (if all probabilities are positive): by induction, splitting I(x1:t−1)I(x_{1:t-1}) 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-nn messages, and the decoder needs to know nn (or an end symbol, paid for within the model).

InteractiveArithmetic coding as zoom
Each row is the current interval expanded to full width and partitioned according to q(⋅∣past)q(\cdot \mid \text{past})
0½1primer bit: 0 en la mitad izquierda, 1 en la derechaanchura 2^−5.6a 0.80b 0.15c1/2x1 = a+0.32a 0.80b 0.15c1/2x2 = a+0.32a 0.80b 0.15c1/2x3 = a+0.32a 0.80b 0.15c1/2x4 = a+0.32a 0.80b 0.15c1/4x5 = a+0.32a 0.80b 0.15c1/4x6 = b+2.74a 0.80b 0.15c9/32x7 = a+0.32a 0.80b 0.15c9/32x8 = a+0.32a 0.80b 0.15c9/32x9 = a+0.32a 0.80b 0.15c9/32x10 = a+0.32a 0.80b 0.15c9/32t = 10Σ 5.63010001 : largest dyadic cell fitting in the interval (6 bits)
  • aa
  • bb
  • cc
  • dyadic point (1/2, 1/4, ...)
  • chosen code
Model
80 %
15 %
ADD SYMBOL (10/12)
Messageaaaaabaaaa
−log⁡2q(x1:t)-\log_2 q(x_{1:t}) (ideal)5.63 bits
Bits already fixed0100
Final code010001 · 6 bits
Bound ⌈−log⁡2q⌉+1\lceil -\log_2 q \rceil + 17 bits
Huffman (per symbol)11 bits (1, 2, 2)
Huffman uses 11 bits (an integer-length code per symbol); arithmetic uses 6, within 0.37 bits of the limit −log⁡2q=5.63-\log_2 q = 5.63.
Build a message of up to 12 symbols with the buttons. Each row is the current interval enlarged to full width and split according to q(⋅∣pasado)q(\cdot \mid \text{pasado}); the funnel zooms toward the chosen symbol's cell. Dashed lines mark the coarsest dyadic points within the interval (1/2, 1/4, ...): when the interval falls to one side, the corresponding bit is decided. Below is the shortest fitting code. Try the fixed model: ‘aaaaaaaaaa’ versus ‘cccccccccc’ (who beats Huffman?); then example ‘aab’, which sets q(a)=0.75q(\mathrm{a}) = 0.75 (why is no bit fixed, even at the end, yet the code has only 4 bits?); finally switch to KT and compare how partitions change.

With initial values (fixed model with q(a)=0.8q(\mathrm{a}) = 0.8, q(b)=0.15q(\mathrm{b}) = 0.15, q(c)=0.05q(\mathrm{c}) = 0.05), message aaaaabaaaa has −log⁡2q=5.63-\log_2 q = 5.63 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 −log⁡20.8=0.32-\log_2 0.8 = 0.32 bits rather than 1: arithmetic coding does not round.

Four things the figure shows:

  1. 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.
  2. Bits are decided when the interval falls on one side of a dyadic point. Initially I=[0,1)I = [0, 1) and no bit is fixed; once the interval fits in [0,12)[0, \tfrac12) the first bit is 0, and so on. The fixed prefix is the part common to both endpoints.
  3. An interval may take time to decide. With q(a)=34q(\mathrm{a}) = \tfrac34 and q(b)=14q(\mathrm{b}) = \tfrac14, message aab occupies [2764,3664)=[0.4219,0.5625)[\tfrac{27}{64}, \tfrac{36}{64}) = [0.4219, 0.5625), containing 12\tfrac12: no bit is certain. Yet cell [716,816)[\tfrac{7}{16}, \tfrac{8}{16}), code 0111, fits inside. The finite implementation calls this E3. (In the figure the ‘aab’ example uses q(a)=0.75q(\mathrm{a}) = 0.75, q(b)=0.2q(\mathrm{b}) = 0.2 and q(c)=0.05q(\mathrm{c}) = 0.05 because the third symbol needs some mass; the interval changes slightly but still contains 12\tfrac12 and the code remains 0111.)
  4. With an adaptive model partitions change from row to row: after many as, the a cell widens. A Huffman code with fixed table cannot do this.

What it costs: the −log⁡q+2-\log q + 2 bound

Proof

Let w=q(x1:n)w = q(x_{1:n}) be the width of I=[l,l+w)I = [l, l + w) and k=⌈−log⁡w⌉+1k = \lceil -\log w \rceil + 1, so 2−k≤w/22^{-k} \le w/2. Multiples of 2−k2^{-k} are separated by 2−k2^{-k}, so interval [ l,  l+2−k ][\,l,\; l + 2^{-k}\,] contains one: m 2−km\,2^{-k} with m=⌈l 2k⌉m = \lceil l\,2^k \rceil, and m 2−k≤l+2−km\,2^{-k} \le l + 2^{-k}. Cell [ m2−k,  (m+1)2−k)[\,m 2^{-k},\; (m+1) 2^{-k}) then satisfies

(m+1) 2−k  ≤  l+2⋅2−k  ≤  l+w,(m+1)\,2^{-k} \;\le\; l + 2 \cdot 2^{-k} \;\le\; l + w ,

so it lies in II, and its code is the kk-bit string writing mm in binary. Since the shortest code cannot be longer, the bound holds.

∎

The extra “+1” relative to Shannon coding, which uses ⌈−log⁡p⌉\lceil -\log p \rceil, 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 pp, with H(p,q)=Ep[−log⁡q(X1:n)]H(p, q) = \E_p[-\log q(X_{1:n})] the cross entropy of sequences,

Ep[∣s(X1:n)∣]  <  H(p,q)+2.\E_p\big[\abs{s(X_{1:n})}\big] \;<\; H(p, q) + 2 .

If pp is an iid source and the model is true, q=p⊗nq = p^{\otimes n}, expected length is less than n H⁡(p)+2n\,\Ent(p) + 2: H⁡(p)+2/n\Ent(p) + 2/n bits per symbol, versus Huffman’s guarantee H⁡(p)+1\Ent(p) + 1. If the model is wrong, q=p~⊗nq = \tilde p^{\otimes n}, the bound becomes n (H⁡(p)+KL⁡(p ∥ p~))+2n\,(\Ent(p) + \KL(p\,\|\,\tilde p)) + 2: 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 ss and nn and computes point x=0.sx = 0.s, inside I(x1:n)I(x_{1:n}). It repeats the encoder’s splitting: at each step, with the decoded past, split the interval according to q(⋅∣x<t)q(\cdot \mid x_{<t}) and choose the piece containing xx. Since length-nn 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:

[ ]Ideal arithmetic coding with exact fractionsBrowser
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 ⌈−log⁡q⌉+1\lceil -\log q \rceil + 1 always holds (largest excess over −log⁡2q-\log_2 q is 1.95 bits, below 2). Mean length is 9.90 bits versus Huffman’s 12.05, and nH⁡=8.84n\Ent = 8.84: 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 nH⁡≈884n\Ent \approx 884 bits.

Finite implementation: integers, renormalization and pending bits

The previous scheme has a practical problem: required precision grows with the message. An 10610^6-symbol message interval has width of order 2−1062^{-10^6} 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 bb-bit integer variable (here b=32b = 32) and whenever it narrows, enlarge it and emit bits already decided.

The state is [ bajo,alto ][\,\text{bajo}, \text{alto}\,] with bb-bit integers representing enlarged [0,1)[0, 1). To encode a symbol with cumulative frequencies cbajo,caltoc_{\text{bajo}}, c_{\text{alto}} over total TT, split current range r=alto−bajo+1r = \text{alto} - \text{bajo} + 1:

alto←bajo+⌊r calto/T⌋−1,bajo←bajo+⌊r cbajo/T⌋.\text{alto} \leftarrow \text{bajo} + \lfloor r\, c_{\text{alto}} / T \rfloor - 1, \qquad \text{bajo} \leftarrow \text{bajo} + \lfloor r\, c_{\text{bajo}} / T \rfloor .

Then renormalize whenever possible, with three cases:

CaseConditionWhat happens
E1alto<12\text{alto} < \tfrac12The first bit is 0. Emit it and pending bits as 1. Double the interval.
E2bajo≥12\text{bajo} \ge \tfrac12The first bit is 1. Emit it (and pending bits as 0). Subtract 12\tfrac12 and double.
E314≤bajo\tfrac14 \le \text{bajo} and alto<34\text{alto} < \tfrac34The interval contains 12\tfrac12 but is far from the edges. Emit nothing: record a pending bit, subtract 14\tfrac14 and double.

E3 is the case seen with aab. When the interval falls within [14,34)[\tfrac14, \tfrac34) the next bit is not yet known, but whichever it is, the following bit will be its complement: if the interval ends in [12,34)[\tfrac12, \tfrac34), the sequence starts 1010; if it ends in [14,12)[\tfrac14, \tfrac12), 0101. 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 12\tfrac12 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 bb-bit valor window of the code and, when renormalizing, shifts it and reads a new bit.

Limited precision costs very little. After renormalization, r>2b−2r > 2^{b-2}. If frequency totals do not exceed 2162^{16}, partition truncation changes each cell width by a relative factor below 216/230=2−142^{16}/2^{30} = 2^{-14}, and loss is below −log⁡2(1−2−14)<10−4-\log_2(1 - 2^{-14}) < 10^{-4} bits per symbol. The model must, however, provide integer frequencies with a bounded total, none zero.

[ ]The 32-bit integer coder with E1, E2 and E3Browser
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 12\tfrac12 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 kk symbols and the KT estimator explained next (frequencies 2ns+12 n_s + 1, i.e. ns+12n_s + \tfrac12 doubled to make integers), and a round trip on random messages:

[ ]A context model connected to the integer coderBrowser
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 −log⁡2q-\log_2 q 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:

∣s(x1:n)∣  ≈  ∑t=1n−log⁡q(xt∣x<t).\abs{s(x_{1:n})} \;\approx\; \sum_{t=1}^{n} -\log q(x_t \mid x_{<t}) .

Each symbol costs what surprised the model, and the code sums surprises. If pp is the true source, mean excess over optimum −log⁡p(X1:n)-\log p(X_{1:n}) is KL⁡(p1:n ∥ q1:n)\KL(p_{1:n}\,\|\,q_{1:n}), and by the KL chain rule it decomposes token by token:

Ep[−log⁡q(X1:n)+log⁡p(X1:n)]=∑t=1nEp[KL⁡(p(⋅∣X<t) ∥ q(⋅∣X<t))].\E_p\big[-\log q(X_{1:n}) + \log p(X_{1:n})\big] = \sum_{t=1}^{n} \E_{p}\Big[\KL\big(p(\cdot \mid X_{<t})\,\|\,q(\cdot \mid X_{<t})\big)\Big].

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 θ\theta

If the source is iid Bernoulli with known parameter θ\theta, model q=pθq = p_\theta is optimal. But θ\theta is almost never known. Two obvious approaches fail. Estimating θ\theta from the data and sending it before the message requires a first pass and paying parameter bits. Using θ^=kt/t\hat\theta = k_t/t (frequency observed so far) is disastrous: the first time a new symbol appears, θ^=0\hat\theta = 0 assigns it zero probability and the message cannot be encoded.

The working approach is mixing: use as model the data probability averaged over all θ\theta with prior distribution ww,

qw(x1:n)=∫01θk(1−θ)n−k w(θ) ⁣dθ,q_w(x_{1:n}) = \int_0^1 \theta^{k}(1-\theta)^{n-k}\, w(\theta)\dd\theta ,

where kk counts ones in x1:nx_{1:n}. 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 B(α,β)=Γ(α)Γ(β)/Γ(α+β)B(\alpha, \beta) = \Gamma(\alpha)\Gamma(\beta)/\Gamma(\alpha+\beta) and density w(θ)=θa−1(1−θ)a−1/B(a,a)w(\theta) = \theta^{a-1}(1-\theta)^{a-1}/B(a,a),

qw(x1:n)=1B(a,a)∫01θk+a−1(1−θ)n−k+a−1 ⁣dθ=B(k+a,  n−k+a)B(a,a),q_w(x_{1:n}) = \frac{1}{B(a, a)} \int_0^1 \theta^{k + a - 1}(1-\theta)^{n-k+a-1}\dd\theta = \frac{B(k + a,\; n - k + a)}{B(a, a)} ,

which depends only on (n,k)(n, k). For a=1a = 1, B(1,1)=1B(1,1) = 1 and B(k+1,n−k+1)=k! (n−k)!/(n+1)!B(k+1, n-k+1) = k!\,(n-k)!/(n+1)!. For a=12a = \tfrac12, B(12,12)=Γ(12)2=πB(\tfrac12,\tfrac12) = \Gamma(\tfrac12)^2 = \pi and B(k+12,n−k+12)=Γ(k+12)Γ(n−k+12)/n!B(k+\tfrac12, n-k+\tfrac12) = \Gamma(k+\tfrac12)\Gamma(n-k+\tfrac12)/n!. The predictive is the ratio of the probabilities of x1:t1x_{1:t}1 and x1:tx_{1:t}:

B(kt+1+a,  t−kt+a)B(kt+a,  t−kt+a)=Γ(kt+a+1) Γ(t+2a)Γ(kt+a) Γ(t+2a+1)=kt+at+2a,\frac{B(k_t + 1 + a,\; t - k_t + a)}{B(k_t + a,\; t - k_t + a)} = \frac{\Gamma(k_t + a + 1)\,\Gamma(t + 2a)}{\Gamma(k_t + a)\,\Gamma(t + 2a + 1)} = \frac{k_t + a}{t + 2a},

using Γ(z+1)=z Γ(z)\Gamma(z + 1) = z\,\Gamma(z).

∎

Read it as a counting rule: Laplace says “add one imaginary case of each symbol” (ktk_t ones appeared in tt: (kt+1)/(t+2)(k_t + 1)/(t + 2)) and KT says “add half a case” ((kt+12)/(t+1)(k_t + \tfrac12)/(t+1)). After tt consecutive zeros, KT assigns the first one probability 1/2t+1\tfrac{1/2}{t+1} and Laplace 1t+2\tfrac{1}{t+2}: Laplace still reserves almost twice as much mass for what has never occurred (ratio 2(t+1)/(t+2)2(t+1)/(t+2)), and pays for that at each zero.

Regret: the cost of learning

The natural measure of not knowing θ\theta is regret: how many extra bits the code spends relative to the best model in the family, chosen afterward with data in view,

Rn(q; x1:n)=−log⁡q(x1:n)−min⁡θ(−log⁡pθ(x1:n))=log⁡pθ^(x1:n)q(x1:n),θ^=k/n,R_n(q;\, x_{1:n}) = -\log q(x_{1:n}) - \min_{\theta}\big(-\log p_\theta(x_{1:n})\big) = \log \frac{p_{\hat\theta}(x_{1:n})}{q(x_{1:n})}, \qquad \hat\theta = k/n,

with min⁡θ(−log⁡pθ(x1:n))=n h2(k/n)\min_\theta(-\log p_\theta(x_{1:n})) = n\,h_2(k/n), 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 −log⁡qL=log⁡((n+1)(nk))-\log q_L = \log\big((n+1)\binom nk\big). To bound it use (nk)≤2n h2(k/n)\binom{n}{k} \le 2^{n\,h_2(k/n)}, which follows from 1=∑j(nj)(k/n)j(1−k/n)n−j≥(nk)(k/n)k(1−k/n)n−k=(nk) 2−n h2(k/n)1 = \sum_j \binom{n}{j} (k/n)^j (1 - k/n)^{n-j} \ge \binom{n}{k} (k/n)^k (1-k/n)^{n-k} = \binom{n}{k}\,2^{-n\,h_2(k/n)}. Then Rn(qL)≤log⁡(n+1)R_n(q_L) \le \log(n+1) for all kk, and for k=0k = 0, (n0)=1\binom{n}{0} = 1 and h2(0)=0h_2(0) = 0 give exactly log⁡(n+1)\log(n+1).

(2) On the all-zero sequence, qKT(0n)=∏t=1n2t−12t=(2nn)/4n≥12nq_{KT}(0^n) = \prod_{t=1}^{n} \frac{2t-1}{2t} = \binom{2n}{n}/4^n \ge \frac{1}{2\sqrt n}, and since the best model encodes it with 0 bits, Rn=−log⁡qKT(0n)≤12log⁡n+1R_n = -\log q_{KT}(0^n) \le \tfrac12\log n + 1. Asymptotic (2nn)/4n∼1/πn\binom{2n}{n}/4^n \sim 1/\sqrt{\pi n} gives 12log⁡n+12log⁡π\tfrac12\log n + \tfrac12\log \pi. For general kk, the bound follows from an analogous inequality on gamma-function ratios (Krichevsky and Trofimov, 1981); we check it numerically for every n≤400n \le 400 below.

∎

The figure assembles everything. It generates a sequence with bias θ\theta and plots each code’s regret over time.

InteractiveLearning while compressing
Sequence regret: extra bits relative to the best hindsight θ\theta
02468110100t (log scale)
  • KT
  • Laplace
  • KT bound: 12log⁡2t+1\tfrac12\log_2 t + 1
  • log⁡2(t+1)\log_2(t+1)
Expected regret at horizon n=500n = 500 versus true bias θ\theta
024681000.250.50.751true bias θ½ log₂ n + 1
Sequence
0.03
500
Ones among n=500n = 500 symbols13
Bits with KT91.8
Bits with Laplace92.8
Bits with known θ\theta87.2
Best hindsight θ\theta, n h2(k/n)n\,h_2(k/n)87.0
Regret KT4.81
Regret Laplace5.80
12log⁡2n\tfrac12\log_2 n4.48
Near the edge, Laplace assigns mass to an almost impossible event and pays 5.8 extra bits (on all zeros it reaches log⁡2(n+1)=9.0\log_2(n+1) = 9.0). KT pays 4.8 and never exceeds 12log⁡2n+1=5.5\tfrac12\log_2 n + 1 = 5.5.
Top: Laplace (orange) and KT (blue) regret after tt symbols of a sequence with bias θ\theta, with tt on a logarithmic scale, so 12log⁡2t\tfrac12 \log_2 t and log⁡2t\log_2 t are straight lines and the second has double the slope. Bottom: exact binomial expected regret at horizon nn for each possible θ\theta. Start with θ=0.03\theta = 0.03 (mostly zeros) and move bias toward 1/21/2: when does Laplace win? Choose ‘Zeros’: which line does each follow? Finally sequence 0101…0101\ldots is entirely predictable, but regret barely rises: why?

Three readings of the figure:

  • Learning one parameter costs 12log⁡n\tfrac12 \log n bits. Neither Laplace nor KT has a linear cost: after nn symbols the bits paid grow only logarithmically and excess per symbol is 12nlog⁡n→0\tfrac{1}{2n}\log n \to 0. That 12log⁡n\tfrac12\log n is the information needed to estimate θ\theta with the precision nn data permit (θ\theta is determined to error of order 1/n1/\sqrt{n}, and distinguishing n\sqrt n values costs 12log⁡n\tfrac12\log n bits). In a model with dd parameters the cost is d2log⁡n\tfrac d2 \log n; lesson 18 proves no universal code generally improves it.
  • Laplace is U-shaped and KT is flat. With θ\theta near 12\tfrac12 Laplace wins by about log⁡π2=0.65\log\frac{\pi}{2} = 0.65 bits, but near extremes pays nearly double: log⁡(n+1)\log(n+1) versus 12log⁡n+0.83\tfrac12\log n + 0.83. (Laplace wins while θ(1−θ)>1/π2\theta(1-\theta) > 1/\pi^2, i.e. for θ\theta between roughly 0.110.11 and 0.890.89.) KT was designed to be uniformly good, and per-sequence regret is nearly constant 12log⁡πn2\tfrac12\log\frac{\pi n}{2} in the interior.
  • Regret is measured against a class. With 0101…0101\ldots the best iid model is θ=12\theta = \tfrac12 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, log⁡∑k(nk)(k/n)k(1−k/n)n−k\log \sum_k \binom nk (k/n)^k (1 - k/n)^{n-k}, equal to 12log⁡πn2+o(1)\tfrac12\log\frac{\pi n}{2} + o(1): 3.72 bits with n=100n = 100 and 5.33 with n=1000n = 1000 (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 nn. This is one reason it is the default estimator in compression.

[ ]Laplace and KT: exchangeability, regret and the KT boundBrowser
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 kk. Learning a KT table for each possible context gives an order-kk model with ∣X∣k(∣X∣−1)\abs{\mathcal{X}}^k(\abs{\mathcal{X}} - 1) parameters, each with learning cost of order 12log⁡n\tfrac12 \log n. 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 nn times depth. “Choosing” the tree (how many contexts to distinguish) costs about a couple of bits per leaf, and parameters the usual 12log⁡n\tfrac12\log n per leaf.

Smoothed nn-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 q(⋅∣x<t)q(\cdot \mid x_{<t}) 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:

[ ]Context order and Bayesian mixture on textBrowser
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 12log⁡n\tfrac12\log n 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 log⁡24=2\log_2 4 = 2 bits (the Bayesian mixture’s share with 4 models), plus integer probability quantization. This is mixtures’ general guarantee: a mixture of MM models with equal initial weights is never more than log⁡2M\log_2 M bits from the best for any sequence (because ∑j1Mqj≥1Mmax⁡jqj\sum_j \tfrac1M q_j \ge \tfrac1M \max_j q_j). The same mechanism with a continuum indexed by θ\theta yields KT’s 12log⁡n\tfrac12\log n.

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 A=0A = 0 and B=1B = 1 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 (0,A)(0,B)(1,A)(2,A)(4,A)(4,B)(0,A)(0,B)(1,A)(2,A)(4,A)(4,B). 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 (nodo,sıˊmbolo)(\text{nodo}, \text{símbolo}) does this in constant time per symbol.

InteractiveThe LZ78 dictionary grows
13 / 13 phrases
Phrase parsing: each phrase is the longest known one plus a new symbol
1A2AA3AAA4AAB5B6BB7BBB8BBBB9BBBBB10BBBBBB11BBBBBBB12BBA13AAAAAAAA
output: (0, A) (1, A) (2, A) (2, B) (0, B) (5, B) (6, B) (7, B) (8, B) (9, B) (10, B) (6, A) (3, A)
Dictionary as a tree: node ii is phrase ii, and each edge shows its added symbol
AAABBBBBBBBAA012345678910111213
Bits per symbol versus nn (log scale): how long until entropy is reached?
0.00.20.40.60.81.01.22^72^92^112^132^15length nentropy 0.469
  • LZ78 (formal code)
  • order-1 KT
  • true model
  • entropy rate
Source
0.90
2^13 = 8192
Phrases in first 4813
Source entropy0.469
Phrases c(n)c(n), n=8192n = 8192598
LZ78 (bits per symbol)0.678
clog⁡2c / nc\log_2 c\,/\,n0.674
True model (arithmetic)0.458
Order-1 KT (learns)0.460
At n=8192n = 8192, LZ78 uses 0.68 bits per symbol versus entropy 0.469: 0.21 extra. Order-1 KT assumes a Markov source and uses 0.460, nearly entropy. LZ78 assumes nothing and therefore learns more slowly.
Top: the first source symbols split into phrases (number is phrase index) and the dictionary tree growing with the player; output is pairs (i,s)(i, s). Below: bits per symbol of the formal LZ78 code (phrase jj spends ⌈log⁡2j⌉\lceil \log_2 j \rceil pointer bits and 1 symbol bit) versus length nn, compared with the entropy rate of a Markov chain of persistence aa, arithmetic coding with the true model, and order-1 KT that learns. Play to see parsing from the start (or choose ‘Exercise’ for ABAABABAABAB). How far from entropy is LZ78 at n=215n = 2^{15}? And order-1 KT? Lower aa to 0.50.5 (pure noise): what does it converge to? With the periodic source of entropy 0, how long does LZ78 take to fall below 0.30.3 bits per symbol?

Why it is universal

LZ78 code length with cc phrases is ∑j≤c(⌈log⁡j⌉+log⁡∣X∣)≈clog⁡c\sum_{j \le c} (\lceil \log j \rceil + \log\abs{\mathcal{X}}) \approx c \log c plus a term of order cc. 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 ∣X∣l\abs{\mathcal{X}}^l have length ll, and filling short-length slots forces c(n)=O(n/log⁡n)c(n) = \bigO(n / \log n).

2. Ziv’s inequality. Let QQ be any order-kk Markov source and clsc_{ls} the number of length-ll phrases starting in state ss (the previous kk symbols). Such phrases are distinct, so their probabilities under Q(⋅∣s)Q(\cdot \mid s) sum to at most 1 and their product is at most (1/cls)cls(1/c_{ls})^{c_{ls}} (the product of mm positive numbers with sum ≤1\le 1 is ≤m−m\le m^{-m}). Multiplying over all phrases:

−log⁡Q(x1:n∣s1)  ≥  ∑l,sclslog⁡cls  =  clog⁡c−c H(L,S),-\log Q(x_{1:n} \mid s_1) \;\ge\; \sum_{l, s} c_{ls} \log c_{ls} \;=\; c \log c - c\,H(L, S),

where H(L,S)H(L, S) is entropy of a phrase’s (length, state) distribution cls/cc_{ls}/c.

3. The correction term is small. Mean phrase length is n/cn/c, and maximum entropy with that mean is O(log⁡(n/c))\bigO(\log(n/c)); state contributes at most klog⁡∣X∣k \log\abs{\mathcal{X}}. With c=O(n/log⁡n)c = \bigO(n/\log n) this gives c H(L,S)=O(nlog⁡log⁡n/log⁡n)=o(n)c\,H(L,S) = \bigO(n \log\log n / \log n) = o(n).

4. Conclusion. ℓLZ≈clog⁡c≤−log⁡Q(x1:n∣s1)+o(n)\ell_{LZ} \approx c \log c \le -\log Q(x_{1:n} \mid s_1) + o(n) for every order-kk Markov QQ, particularly the best. For a stationary ergodic source, the best order-kk QQ achieves a rate tending to H⁡(X)\Ent(\mathcal{X}) as k→∞k \to \infty. Taking n→∞n \to \infty then k→∞k \to \infty gives the stated upper bound. The lower bound in expectation is the source coding theorem: expected length of any prefix code for X1:nX_{1:n} is at least H⁡(X1:n)≥n H⁡(X)\Ent(X_{1:n}) \ge n\,\Ent(\mathcal{X}), since for a stationary source H⁡(X1:n)/n\Ent(X_{1:n})/n 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 log⁡log⁡n/log⁡n\log\log n / \log n, extremely slowly. The figure and next cell show it: with a=0.9a = 0.9 entropy is 0.4690.469 and, with n=216n = 2^{16} symbols, LZ78 still spends 0.620.62 bits per symbol, while order-1 KT, which knows the source is order-1 Markov, spends 0.4650.465 (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 (distancia,longitud)(\text{distancia}, \text{longitud}) 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.

[ ]LZ78 from scratch and convergence to entropy rateBrowser
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 nn but at a snail’s pace (from 0.750.75 at n=210n = 2^{10} to 0.620.62 at 2162^{16}, always far from 0.4690.469), 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 ss of probability psp_s transforms state x↦x′x \mapsto x' with x′≈x/psx' \approx x / p_s, making the state grow by −log⁡ps-\log p_s 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 psp_s 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:

ModuleAlgorithmImplicit modelCoder
zlib (DEFLATE)LZ77 with 32 KB windowrecent repetitionsHuffman, with per-block tables
bz2Burrows–Wheeler transform, move-to-frontlong context sorted by similarityHuffman
lzmaLZ77 with large windowrepetitions and adaptive contextadaptive 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):

[ ]zlib, bz2 and lzma versus the arithmetic model and encrypted dataBrowser
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

NumericSurprise of a message
With fixed model q(a)=34q(a) = \tfrac34, q(b)=14q(b) = \tfrac14, calculate −log⁡2q(aab)-\log_2 q(aab) in bits.
NumericThe ceiling for a biased source
An iid binary source with P(1)=0.05\Pr(1) = 0.05 is encoded using arithmetic coding and the true model. What is the upper bound in bits on expected length for n=1000n = 1000 symbols? (For comparison, symbol-by-symbol Huffman spends 1000.)
NumericA hundred zeros with KT
How many bits (−log⁡2qKT-\log_2 q_{KT}) does KT code spend on a sequence of n=100n = 100 zeros? Round to two decimal places.
NumericLZ78 phrases
Count the phrases in the LZ78 parsing of ABAABABAABAB.
QuizEncryption and compression
Why does an encrypted file not compress, and why compress before encrypting?
QuizWhat regret says
Which statements about Laplace and KT regret on binary sequences of length nn are true?

More than one answer may be correct.

QuizProbabilities that do not match
A compressor uses a neural network as its model, running in 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?
QuizWhat Lempel–Ziv guarantees
Which statement about LZ78 is true?
ProofLaplace is the uniform Bayesian predictive
Prove: The mixture q(x1:n)=∫01θk(1−θ)n−k ⁣dθq(x_{1:n}) = \int_0^1 \theta^k (1-\theta)^{n-k}\dd\theta of Bernoulli distributions with uniform prior assigns every binary sequence with kk ones probability 1/((n+1)(nk))1/\big((n+1)\binom{n}{k}\big), and its predictive is q(1∣x1:t)=(kt+1)/(t+2)q(1 \mid x_{1:t}) = (k_t + 1)/(t + 2).
0
Use the beta function, ∫01θα−1(1−θ)β−1 ⁣dθ=Γ(α)Γ(β)/Γ(α+β)\int_0^1 \theta^{\alpha-1}(1-\theta)^{\beta-1}\dd\theta = \Gamma(\alpha)\Gamma(\beta)/\Gamma(\alpha + \beta), and Γ(m+1)=m!\Gamma(m+1) = m! for integers.

Step 1 of 4. What is integral ∫01θk(1−θ)n−k ⁣dθ\int_0^1 \theta^k(1-\theta)^{n-k}\dd\theta equal to?

CodeKT probability without order
Implement logprob_kt(bits), which receives a list of 0s and 1s and returns log⁡2qKT(x1:n)\log_2 q_{KT}(x_{1:n}) by multiplying sequential predictives (cs+12)/(t+1)(c_s + \tfrac12)/(t + 1), where tt is the number of symbols seen and csc_s how many equal the incoming symbol. Sum logarithms (do not multiply probabilities): with n=5000n = 5000 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
Shift+Enter to run

Summary

Key idea
A compressor has two pieces: a model predicting q(xt∣x<t)q(x_t \mid x_{<t}) and a coder converting probabilities to bits. Arithmetic coding is nearly ideal: it represents a message as an interval of width q(x1:n)q(x_{1:n}) and spends at most −log⁡2q(x1:n)+2-\log_2 q(x_{1:n}) + 2 bits for the entire message, without Huffman’s per-symbol rounding, and is implemented using integers, renormalization and pending bits. Adaptive models learn while compressing: Laplace and Krichevsky–Trofimov are Bayesian mixtures over θ\theta whose learning cost is order 12log⁡2n\tfrac12\log_2 n per parameter, and KT is bounded by 12log⁡2n+1\tfrac12\log_2 n + 1 for every sequence. Lempel–Ziv reaches the entropy rate of any stationary ergodic source without knowing it, but slowly. Better prediction means better compression, and code length is the predictor’s log loss.