Workbench / Squeeze: the Information Theory Capstone
S11 · B1·11
Mixing Models
Stage 11 of Squeeze, the last, after chapter 11: method 5 mixes order-0, order-1 and order-2 byte models, weighting each by how well it has been predicting in situations like the current one, and the arithmetic coder pays exactly the mixture's cross-entropy (0.8056 bits per byte predicted, 0.8057 coded); Shakespeare falls from 3.53 to 2.85 bits per byte, beating deflate, the server log halves to 0.81, random data stays near 8 bits instead of 9.16, and lzma still wins where structure reaches further than two bytes back.
Stage 11: mixing models
The brief
What you'll build. mixed.py, Squeeze's method 5. Three adaptive models predict each byte: order 0 (no context), order 1 (the previous byte) and order 2 (the previous two bytes). Their predictions are combined as a weighted average, and the weights are learned: after each byte, each model's weight is multiplied by the probability it gave to what actually came, then renormalised (Bayes' rule, with a small floor so no model is ever silenced). There are four sets of weights, chosen by how often the current order-2 context has been seen before (never, 1 to 3 times, 4 to 15, 16 or more), so the mixer learns when to trust the long context. The arithmetic coder of stage 7 codes each byte with the mixture's probabilities.
Why a compressor needs this. Chapter 7 showed that longer contexts predict better until they overfit; chapter 10 blended orders with fixed rules and beat any single order; stage 10 found Squeeze's order-1 model too short-sighted for most real data. Chapter 11 supplies the score that makes learning the weights possible: each model's cross-entropy on the data so far.
Why now. The chapter supplies cross-entropy as code length (so improving the mixture's cross-entropy shrinks the file bit for bit), Bayesian weighting as accumulated evidence, and the warning to judge models on data they haven't seen, which an adaptive coder does automatically: every byte is predicted before the model learns it.
What you'll have at the end. Squeeze with six methods, a table against order-1, deflate and lzma, a check that the file size equals the model's cross-entropy, and the weights the mixer learned.
Theory to own
- Cross-entropy is file size. Why must the coded size of a file equal the sum of over its bytes, to within a few bits? (Chapter: "Cross-entropy"; the exercises' C1.)
- Bayesian weights. Why does multiplying each model's weight by the probability it gave the actual byte favour the model with the lowest cross-entropy so far? (Chapter: "How fast evidence accumulates".)
- Why several weight sets? What does the order-2 model know about a context it has never seen, and why should its weight depend on that? (Chapter 10: "Blending contexts".)
- Why a floor on weights? What would happen to a model whose weight reached zero, if the data later changed? (Chapter: "Divergence as an alarm".)
Build it
Step 1: the mixed model. It plugs into stage 7's coder: table() returns the mixture's frequencies, update() learns.
"""Squeeze, stage 11: method 5, an adaptive coder that mixes order-0, order-1 and order-2 byte models,
weighting each by how well it has been predicting in similar situations."""
import numpy as np
from adaptive import encode, decode
class Table:
"""A frequency table for the arithmetic coder, built from mixed probabilities."""
def __init__(self, probs):
freq = np.floor(probs * (65536 - 256)).astype(np.int64) + 1 # every byte keeps at least 1 of 65,536
self.edges = np.concatenate(([0], np.cumsum(freq)))
self.total = int(self.edges[-1])
def below(self, i):
return int(self.edges[i])
def find(self, target):
return int(np.searchsorted(self.edges, target, side="right")) - 1
class Mixed:
INC, LIMIT = 1.0, 4096.0
def __init__(self):
self.c0 = np.full(256, 0.5)
self.c1 = np.full((256, 256), 0.02)
self.c2 = np.full((65536, 256), 0.02, dtype=np.float32)
self.seen2 = np.zeros(65536, dtype=np.int64) # how often each order-2 context has occurred
self.w = np.full((4, 3), 1 / 3) # mixing weights, one set per experience level
self.h1 = self.h2 = 0
def _predictions(self):
rows = (self.c0, self.c1[self.h1], self.c2[self.h2 * 256 + self.h1])
return np.array([r / r.sum() for r in rows])
def _level(self):
n = self.seen2[self.h2 * 256 + self.h1]
return 0 if n == 0 else 1 if n < 4 else 2 if n < 16 else 3
def table(self):
self.p = self._predictions()
self.lvl = self._level()
return Table(self.w[self.lvl] @ self.p)
def update(self, s):
w = self.w[self.lvl] * self.p[:, s] # Bayes: weight each model by the probability it gave
w /= w.sum()
self.w[self.lvl] = 0.98 * w + 0.02 / 3 # but never let a model's weight vanish
ctx2 = self.h2 * 256 + self.h1
for row in (self.c0, self.c1[self.h1], self.c2[ctx2]):
row[s] += self.INC
if row.sum() > self.LIMIT:
row *= 0.5 # forget slowly, as stage 7 did
self.seen2[ctx2] += 1
self.h2, self.h1 = self.h1, s
def pack(data):
return b"SQZ\x05" + len(data).to_bytes(4, "big") + encode(data, Mixed())
def unpack(blob):
if blob[:4] != b"SQZ\x05":
raise ValueError("not a Squeeze mixed file")
return decode(blob[8:], int.from_bytes(blob[4:8], "big"), Mixed())
Step 2: register it as method 5 in squeeze.py (import mixed and one more entry in METHODS).
Step 3: compare, check and look inside.
import lzma, math, zlib
from pathlib import Path
import numpy as np
import squeeze, mixed, adaptive
print(f"{'file':<16}{'order-1':>9}{'mixed':>9}{'deflate':>9}{'lzma':>9} bits per byte; chosen, round trip")
for name in ("shakespeare.txt", "server.log", "squares.csv", "zeros.bin", "random.bin"):
data = Path(name).read_bytes()
blob = squeeze.pack(data)
ok = squeeze.unpack(blob) == data
o1, mx = len(adaptive.pack(data)), len(mixed.pack(data))
rate = lambda n: f"{8 * n / len(data):>9.3f}"
print(f"{name:<16}{rate(o1)}{rate(mx)}{rate(len(zlib.compress(data, 9)))}{rate(len(lzma.compress(data, preset=9 | lzma.PRESET_EXTREME)))}"
f" {squeeze.METHODS[blob[3]][0]}, {'exact' if ok else 'FAILED'}")
for edge in (b"", b"x", b"ab" * 3, bytes(range(256)), bytes(range(256)) * 300):
assert squeeze.unpack(squeeze.pack(edge)) == edge
print("edge cases: exact")
# The model's own cross-entropy on the log, against the size of the file it produced
data = Path("server.log").read_bytes()
m, bits = mixed.Mixed(), 0.0
for s in data:
t = m.table()
bits -= math.log2((t.below(s + 1) - t.below(s)) / t.total)
m.update(s)
print(f"\nserver.log: the model's cross-entropy {bits / len(data):.4f} bits per byte; the coded body {8 * (len(mixed.pack(data)) - 8) / len(data):.4f}")
print("final mixing weights (order-0, order-1, order-2) by how often the order-2 context had been seen:")
for lvl, label in enumerate(("never", "1 to 3 times", "4 to 15 times", "16 or more")):
print(f" {label:<14}" + " ".join(f"{w:.3f}" for w in m.w[lvl]))
file order-1 mixed deflate lzma bits per byte; chosen, round trip
shakespeare.txt 3.531 2.850 3.118 2.614 mixed, exact
server.log 1.670 0.806 0.862 0.511 mixed, exact
squares.csv 3.232 3.244 3.539 1.620 order-1, exact
zeros.bin 0.008 0.006 0.009 0.007 fixed, exact
random.bin 9.159 8.038 8.003 8.003 store, exact
edge cases: exact
server.log: the model's cross-entropy 0.8056 bits per byte; the coded body 0.8057
final mixing weights (order-0, order-1, order-2) by how often the order-2 context had been seen:
never 0.008 0.985 0.007
1 to 3 times 0.008 0.066 0.926
4 to 15 times 0.007 0.020 0.973
16 or more 0.007 0.024 0.969
Step 4: read the results.
- Shakespeare: 2.850 bits per byte, down from order-1's 3.531 and below deflate's 3.118; lzma (2.614) still finds longer repeats.
- The server log: 0.806 bits per byte, half of order-1's 1.670 and below deflate; lzma's 0.511 comes from whole repeated lines, beyond two bytes of context.
- The table of squares: no gain (3.244 against 3.232): its structure is arithmetic, not short byte patterns, so no context model helps, and lzma (1.620) wins by matching repeated digit strings.
- Random data: order-1 alone paid 9.16 bits per byte learning 65,536 useless probabilities; mixed with order-0, the cost falls to 8.04. When the long contexts know nothing, the mixer listens to the short one: chapter 7's overfitting, contained. The chooser stores it anyway.
- Cross-entropy is the file. The mixture's cross-entropy on the log is 0.8056 bits per byte; the coded body is 0.8057. Every improvement to the model's predictions is an improvement to the file, bit for bit.
- What the mixer learned. When the order-2 context has never been seen, the weights are 0.985 on order-1; once it has been seen even once, order-2 gets 0.93 to 0.97. The weights encode chapter 10's rule (trust a context by its evidence) without anyone writing it down.
Senior and architect lens
- Better models are the only way to better compression. The coder hasn't changed since stage 7; every gain here came from better probabilities. Production compressors that beat lzma (the PAQ family, cmix, and those built on neural language models) mix hundreds of models the same way, at the cost of speed: method 5 took about 20 seconds to pack the plays on the lab machine, in pure Python with NumPy.
- Encoder and decoder must compute identically. The mixture uses floating-point arithmetic; on one machine and one library version it's deterministic, but different hardware or NumPy versions could round differently and the decoder would desynchronise. Production context mixers use integer arithmetic, or pin their numeric environment, for exactly this reason; test decoding on every platform you support.
- Choose models for your data. Squeeze's table shows each kind of data rewarding a different model: context for text and logs, long matches for repeated lines, nothing for random bytes. A general compressor tries several and picks (as Squeeze's chooser does); a specialised one models its data's structure directly.
- Measure in bits, against baselines, on held-out data. Every number in this capstone is a cross-entropy on data the model predicted before seeing it, compared with standard tools; that's the discipline the whole book has been building towards.
Evidence
mixed.py, the updatedsqueeze.py, and your table, every file "exact".- The cross-entropy check: the model's bits against the coded size, for one file.
- A paragraph on the learned weights: which model dominates at each experience level, and why.
Carry forward
This is Squeeze's last stage. Over eleven stages it grew from a meter and a test corpus into a compressor with six methods, an adaptive mixed-order model, checks that catch every damaged file, optional error correction, and measurements against the limits the book derived: entropy, the source coding theorem, capacity and cross-entropy. Ideas for going further: add an order-3 model and a match model (predict the byte that followed the last occurrence of the current context), mix with a small neural network, or replace floating point with integers and test across machines.