Squeeze: the Information Theory CapstoneSqueeze
0 / 0

Workbench / Squeeze: the Information Theory Capstone

S3 · B1·03

The Probability Model

Stage 3 of Squeeze, after chapter 3: an order-0 model (how often each byte appears) and an order-1 model (how often each byte follows each other byte), both smoothed so no possible byte gets probability zero and both checked to add up to 1; and what each would cost per byte on the corpus, including the warning in random.bin that a model fitted to the data it codes is too optimistic.

6 topics · ~6 min read
Updated Suggest a correction

Stage 3: the probability model

The brief

What you'll build. model.py, with two probability models Squeeze's coders will use from stage 5 on. Order0 gives each byte a probability from how often it appears; Order1 gives each byte a probability given the byte before it. Both add a half to every count (the Krichevsky–Trofimov estimator), so every one of the 256 byte values has a probability above zero, and a check function proves each distribution is positive and adds to 1.

Why a compressor needs this. Chapter 1 said a symbol of probability p carries −log2p bits, and chapter 5 will build codes whose codeword lengths match those surprises. A code can only be as good as the probabilities behind it. Separating the model (what's likely) from the coder (how to turn likelihoods into bits) is how every modern compressor is designed.

Why now. Chapter 3 gives exactly what the model needs: distributions that add to 1, conditional probabilities, estimates from counts, and the rule that a possible symbol must never get probability zero.

What you'll have at the end. model.py, a run over the corpus showing what each model would cost per byte if every byte cost exactly its surprise, and an answer to the question the random file raises.

Theory to own

  1. Never zero. What would happen to a coder built on a model that gives some byte probability 0, when that byte appears? (Chapter: "Frequencies, and the zero problem"; companion, interview Q3.)
  2. Conditional distributions. Why must the 256 probabilities P(b∣a) add to 1 for each previous byte a, and what does it mean if they don't? (Chapter: "Conditional probability"; companion, drill D2.)
  3. Average surprise as cost. If each byte costs −log2P(b) bits, why is the average cost over a long file close to the expected surprise? (Chapter: "The law of large numbers".)
  4. Fitting to what you code. These models are built from the counts of the whole file, then used to measure the same file. What does the decoder need, that it doesn't have, to use them? (Chapter: "Estimating probabilities from data"; exercises, P3.)

Build it

Step 1: the models.

Python
"""Squeeze, stage 3: probability models built from counts, that never give a possible byte zero probability."""
from collections import Counter

class Order0:
    """P(byte) from counts of the whole input, plus `add` for every one of the 256 byte values."""
    def __init__(self, data, add=0.5):
        self.counts, self.n, self.add = Counter(data), len(data), add
    def p(self, b):
        return (self.counts[b] + self.add) / (self.n + 256 * self.add)

class Order1:
    """P(byte | previous byte): one Order0-style table per previous byte."""
    def __init__(self, data, add=0.5):
        self.add = add
        self.pairs = Counter(zip(data, data[1:]))
        self.before = Counter(data[:-1])
    def p(self, b, prev):
        return (self.pairs[(prev, b)] + self.add) / (self.before[prev] + 256 * self.add)

def check(model_p, contexts=(None,)):
    """Every distribution must be positive everywhere and add up to 1 (within rounding)."""
    for ctx in contexts:
        ps = [model_p(b) if ctx is None else model_p(b, ctx) for b in range(256)]
        assert min(ps) > 0, "a possible byte has probability 0"
        assert abs(sum(ps) - 1) < 1e-9, f"probabilities add up to {sum(ps)}"

Step 2: measure the corpus. For each file, build both models, check them, and compute the average surprise per byte: the cost per byte of an ideal coder using the model (chapter 6 shows arithmetic coding reaches it).

Python
import math
from pathlib import Path
from model import Order0, Order1, check
print(f"{'file':<16}{'symbols':>8}{'top byte':>10}{'P(top)':>8}{'order 0':>9}{'order 1':>9}  (bits per byte if each byte cost its surprise)")
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
    data = Path(name).read_bytes()
    m0, m1 = Order0(data), Order1(data)
    check(m0.p)
    check(m1.p, contexts=sorted(set(data))[:5])
    top, _ = m0.counts.most_common(1)[0]
    bits0 = -sum(math.log2(m0.p(b)) for b in data) / len(data)
    bits1 = (-math.log2(m0.p(data[0])) - sum(math.log2(m1.p(b, a)) for a, b in zip(data, data[1:]))) / len(data)
    print(f"{name:<16}{len(m0.counts):>8}{repr(bytes([top]))[1:]:>10}{m0.p(top):>8.3f}{bits0:>9.3f}{bits1:>9.3f}")
print("every model checked: positive for all 256 bytes, and adds up to 1")
Text
file             symbols  top byte  P(top)  order 0  order 1  (bits per byte if each byte cost its surprise)
shakespeare.txt       65       ' '   0.152    4.779    3.547
zeros.bin              1    '\x00'   0.999    0.001    0.001
random.bin           256    '\x0f'   0.004    7.999    7.754
squares.csv           12       '1'   0.133    3.557    3.391
server.log            25       '2'   0.114    4.364    1.686
every model checked: positive for all 256 bytes, and adds up to 1

Step 3: read the table.

  • shakespeare.txt: the space is the commonest byte (15 %). Order-0 costs 4.78 bits per byte against stage 2's fixed 7; knowing the previous byte brings it to 3.55. lzma's 2.61 (stage 1) is still ahead: it uses much longer contexts.
  • zeros.bin: one symbol with probability 0.999 (the half-counts of 255 unused bytes take the rest): 0.001 bits per byte.
  • random.bin: order-0 costs 7.999 bits per byte, as it should. Order-1 claims 7.754: better than random data allows. That's the warning. The order-1 model has 65,536 pairs of counts, estimated from only 200,000 bytes, so it has "learned" the accidental pattern of this particular file, and its cost is measured on the same bytes it learned from. A decoder doesn't have those counts; sending them would cost far more than the 0.25 bits per byte the model seems to save.
  • squares.csv: 12 symbols; order-1 helps only a little (3.56 to 3.39), since which digit follows which is close to random here.
  • server.log: order-1 halves the cost (4.36 to 1.69): the log's bytes are very predictable from the one before (timestamps, fixed words).

Senior and architect lens

  • Model and coder are separate jobs. Swapping a better model into the same coder is how compressors improve (zip to bzip2 to lzma to context-mixing compressors changed models far more than coders). Keep the interface small: p(byte, context).
  • A model's cost includes describing it. The random file shows the trap every machine-learning team meets: a model evaluated on its own training data looks better than it is. Compression keeps you honest, because the decoder must be able to rebuild the model from what it's sent. From stage 5, Squeeze will either send the counts in the header or learn them as it goes (adaptive coding, stage 11), and the table will be measured on what's really sent.
  • Invariants as tests. check encodes the two rules of chapter 3 (positive, adds to 1). Cheap invariant checks on probability tables catch the commonest model bugs (wrong denominators, missing smoothing) before they become corrupted files.

Evidence

  • model.py and the table from your own run, matching the one above.
  • A paragraph explaining why order-1 seems to beat 8 bits per byte on random data, and why that number is not achievable.
  • Your answers to the four theory questions.

Carry forward

Stage 4, after chapter 4, turns these models into an entropy report: for each file, the entropy of the order-0 and order-1 models, how many bits describing each model would cost, and so how much each could really save. That report is the target the coders of stages 5 to 7 aim at.