Squeeze: the Information Theory CapstoneSqueeze
0 / 0

Workbench / Squeeze: the Information Theory Capstone

S7 · B1·07

A Model with Memory

Stage 7 of Squeeze, after chapter 7: an adaptive order-1 arithmetic coder (method 4) that predicts each byte from the one before it, learning 256 tables of counts as it goes, with nothing sent in advance; Shakespeare drops from 666,539 to 492,328 bytes and the server log by more than half, both at or below stage 4's order-1 targets, while random data shows exactly what learning 65,536 probabilities costs.

6 topics · ~9 min read
Updated Suggest a correction

Stage 7: a model with memory

The brief

What you'll build. adaptive.py, Squeeze's method 4. For each previous byte, the model keeps a table of counts for the next byte (a Fenwick tree, so running totals are fast), starting every count at 1 and adding 32 each time a byte is seen. When a table's total passes 216, its counts are halved, which keeps the totals small enough for the coder and lets old statistics fade. The arithmetic coder asks the model for each byte's slice given the previous byte, then updates the model; the decoder makes exactly the same updates, so no table is ever sent.

Why a compressor needs this. Chapter 7's chain rule says a file's information is the sum of each symbol's conditional surprise given what came before, and the conditional entropy is never more than the order-0 entropy. Stage 4 measured how much one byte of context should save; this stage collects it.

Why now. The chapter supplies conditional entropy, the chain rule as a recipe for coding, entropy rates for sources with memory, and the warning about models with too many contexts for the data. Chapter 6 supplied adaptive coding and its learning cost.

What you'll have at the end. adaptive.py, the updated squeeze.py (five methods now), and a table setting the order-1 coder against the order-0 one, stage 4's targets and lzma.

Theory to own

  1. The chain rule as a coder. Why does coding each byte with P(byte∣previous byte) cost about nH(Xn∣Xn−1) bits in total? (Chapter: "The chain rule"; "Sources with memory".)
  2. Learning instead of sending. Stage 4 charged order-1 a table of up to 65,536 counts. Where does that cost go when the model is adaptive? (Chapter 6: "Learning the probabilities".)
  3. Forgetting. Why halve the counts, and why might that make the coder beat stage 4's target? (Chapter 6's companion, point 2.)
  4. Too many contexts. What will this model do on random.bin, and why? (Chapter: Experiment 2; exercises, T5.)

Build it

Step 1: the model and coder. The coder is chapter 6's, with one change: instead of a fixed table of counts, it asks model.table() for the current context's counts before each byte and calls model.update after.

Python
"""Squeeze, stage 7: adaptive models with memory, and an arithmetic coder that asks a model for each byte's slice."""
TOP, HALF, QUARTER = (1 << 32) - 1, 1 << 31, 1 << 30

class Fenwick:
    """Counts for 256 symbols with fast running totals (a binary indexed tree)."""
    def __init__(self, start=1):
        self.t = [0] * 257
        for i in range(256):
            self.add(i, start)
        self.total = 256 * start
    def add(self, i, d):
        i += 1
        while i <= 256:
            self.t[i] += d; i += i & -i
        if hasattr(self, "total"):
            self.total += d
    def below(self, i):                    # sum of counts of symbols 0 .. i-1
        s = 0
        while i > 0:
            s += self.t[i]; i -= i & -i
        return s
    def find(self, target):                # the symbol whose slice contains target
        pos, rem, step = 0, target, 256
        while step:
            if pos + step <= 256 and self.t[pos + step] <= rem:
                pos += step; rem -= self.t[pos]
            step >>= 1
        return pos
    def halve(self):
        counts = [self.below(i + 1) - self.below(i) for i in range(256)]
        self.__init__(0)
        for i, c in enumerate(counts):
            self.add(i, max(1, c // 2))

class Order1:
    """P(byte | previous byte), learned as it goes: +32 per occurrence on a base of 1, halved when a context's total passes 2^16."""
    INC, LIMIT = 32, 1 << 16
    def __init__(self):
        self.tables, self.prev = {}, 0
    def table(self):
        t = self.tables.get(self.prev)
        if t is None:
            t = self.tables[self.prev] = Fenwick()
        return t
    def update(self, sym):
        t = self.table()
        t.add(sym, self.INC)
        if t.total > self.LIMIT:
            t.halve()
        self.prev = sym

def encode(data, model):
    low, high, pending, out = 0, TOP, 0, []
    def emit(bit):
        nonlocal pending
        out.append(bit); out.extend([bit ^ 1] * pending); pending = 0
    for s in data:
        t = model.table()
        start, total, width = t.below(s), t.total, t.below(s + 1) - t.below(s)
        span = high - low + 1
        high = low + span * (start + width) // total - 1
        low = low + span * start // total
        while True:
            if high < HALF:
                emit(0)
            elif low >= HALF:
                emit(1); low -= HALF; high -= HALF
            elif low >= QUARTER and high < HALF + QUARTER:
                pending += 1; low -= QUARTER; high -= QUARTER
            else:
                break
            low, high = 2 * low, 2 * high + 1
        model.update(s)
    pending += 1
    emit(0 if low < QUARTER else 1)
    out += [0] * (-len(out) % 8)
    return bytes(int("".join(map(str, out[i:i + 8])), 2) for i in range(0, len(out), 8))

def decode(blob, n, model):
    bits = (b >> (7 - k) & 1 for b in blob for k in range(8))
    nxt = lambda: next(bits, 0)
    low, high, value = 0, TOP, 0
    for _ in range(32):
        value = 2 * value + nxt()
    out = bytearray()
    for _ in range(n):
        t = model.table()
        span = high - low + 1
        target = ((value - low + 1) * t.total - 1) // span
        s = t.find(target)
        start, width = t.below(s), t.below(s + 1) - t.below(s)
        high = low + span * (start + width) // t.total - 1
        low = low + span * start // t.total
        while True:
            if high < HALF:
                pass
            elif low >= HALF:
                low -= HALF; high -= HALF; value -= HALF
            elif low >= QUARTER and high < HALF + QUARTER:
                low -= QUARTER; high -= QUARTER; value -= QUARTER
            else:
                break
            low, high, value = 2 * low, 2 * high + 1, 2 * value + nxt()
        out.append(s)
        model.update(s)
    return bytes(out)

def pack(data):
    return b"SQZ\x04" + len(data).to_bytes(4, "big") + encode(data, Order1())

def unpack(blob):
    if blob[:4] != b"SQZ\x04":
        raise ValueError("not a Squeeze order-1 file")
    return decode(blob[8:], int.from_bytes(blob[4:8], "big"), Order1())

Step 2: register it as method 4 in squeeze.py (import adaptive and one more entry in METHODS), so the chooser tries it too.

Step 3: run it.

Python
import lzma
from pathlib import Path
import squeeze
from report import report
print(f"{'file':<16}{'order-0':>9}{'order-1':>9}{'b/B':>7}{'order-1 target':>16}{'lzma b/B':>10}  chosen, round trip")
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
    data = Path(name).read_bytes()
    o0, o1 = len(squeeze.METHODS[3][1](data)), len(squeeze.METHODS[4][1](data))
    blob = squeeze.pack(data)
    ok = squeeze.unpack(blob) == data
    target = report(name, data)["order 1"][0]
    print(f"{name:<16}{o0:>9,}{o1:>9,}{8 * o1 / len(data):>7.3f}{target:>16.3f}{8 * len(lzma.compress(data, preset=9)) / len(data):>10.3f}"
          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")
Text
file              order-0  order-1    b/B  order-1 target  lzma b/B  chosen, round trip
shakespeare.txt   666,539  492,328  3.531           3.538     2.611  order-1, exact
zeros.bin              43      211  0.008           0.000     0.007  fixed, exact
random.bin        200,532  228,965  9.159           7.740     8.003  store, exact
squares.csv        88,968   80,809  3.232           3.380     1.610  order-1, exact
server.log        109,180   41,760  1.670           1.663     0.509  order-1, exact
edge cases: exact

Step 4: read the table.

  • shakespeare.txt: 492,328 bytes, 3.53 bits per byte, a quarter smaller than order-0 and slightly below stage 4's order-1 data cost (3.538), with no table sent: adaptation (counts that fade) tracks local statistics, and the learning cost is small for 1.1 MB.
  • server.log: 1.67 bits per byte, under half of order-0, right on its target. The previous byte predicts much of a log line.
  • squares.csv: 3.23, again below its target; digits of squares depend on their neighbours a little, and on local position more.
  • zeros.bin: 211 bytes, mostly the cost of learning that the zero context only ever sees zero; the fixed-length code still wins.
  • random.bin: 9.16 bits per byte, worse than storing it. With 256 contexts and 256 possible next bytes, the model has 65,536 probabilities to learn from only 200,000 bytes, and each costs learning bits for nothing: chapter 7's overfitting, paid in bits. The chooser stores it.

lzma is still far ahead on the log and the table (0.51 and 1.61): their structure spans whole lines, which one byte of context can't see.

Senior and architect lens

  • Context is where compression comes from. Order-0 to order-1 bought 26 % on text and 62 % on logs; no coder improvement could. The next gains need longer contexts, which means more tables to learn: the trade-off chapter 7 measured.
  • Adaptive models need careful symmetry. Encoder and decoder must update identically, in the same order, with the same rounding and the same halving rule; any difference (a different increment, halving at a different moment) corrupts everything after it, silently. Test the round trip on many files and edge cases, as run.py does.
  • Know when a model will lose. On data with no structure, a richer model only adds learning cost. The chooser's store fallback contains the damage; better compressors also mix models of different orders, so the short-context model takes over where the long one has learned nothing (stage 11).

Evidence

  • adaptive.py, the updated squeeze.py, and your table, every file "exact".
  • The timing of a full pack and unpack of shakespeare.txt on your machine.
  • A paragraph on random.bin: why the order-1 coder is worse than storing it, in terms of learning cost.

Carry forward

Stage 8, after chapter 8, turns from compressing to protecting: Squeeze files get a checksum, so damage is detected rather than silently decoded into garbage, and you'll measure what one flipped bit does to a file from each method.