Squeeze: the Information Theory CapstoneSqueeze
0 / 0

Workbench / Squeeze: the Information Theory Capstone

S4 · B1·04

The Entropy Report

Stage 4 of Squeeze, after chapter 4: for every corpus file, the entropy of the order-0 and order-1 models in bits per byte, the cost of sending each model's table, and the total, set beside lzma's result; the target the coders of the next stages aim at, and a clear answer to stage 3's puzzle about random data.

6 topics · ~6 min read
Updated Suggest a correction

Stage 4: the entropy report

The brief

What you'll build. report.py, which computes, for any file, the total surprise of its bytes under the order-0 and order-1 models of stage 3 (the bits an ideal coder would spend on the data), the bits needed to send each model's table of counts, and their sum, in bits per byte. Set beside stage 1's lzma figure, it says what each model could achieve and what it can't.

Why a compressor needs this. Chapter 4 says no code can average fewer binary digits per symbol than the entropy of the model it's built on. Before building coders (stages 5 to 7), you need to know the target, and the target must include everything the decoder needs: the data's code and the model. Stage 3 showed what happens when the model's cost is ignored: random data appeared to compress.

Why now. Chapter 4 gives exactly the pieces: entropy as average surprise, entropy computed from counts, the floor it sets, and the warning that an entropy figure belongs to a model.

What you'll have at the end. report.py and a table of targets for every corpus file, model by model.

Theory to own

  1. Total surprise as a target. Why is ∑−log2p(byte) over a file the length of the best code for that file under the model? (Chapter: "Entropy, questions and codes".)
  2. Paying for the model. Why must the bits to send the counts be added, and why does the order-1 table cost so much more than the order-0 table? (Chapter: "Bytes, letters and words"; exercises, harder 12.)
  3. Bias. The data bits are computed from the file's own counts, so they're the plug-in figure. Is the true cost of a model that has to be learned higher or lower? (Chapter: "Estimating entropy from a sample".)
  4. Beating the target. lzma beats both models' totals on every text file. Does that contradict chapter 4? (Chapter: "Limits and trade-offs"; companion, point 1.)

Build it

Step 1: the report. The data cost is each byte's surprise under the model, summed. The model cost sends, for each non-zero count, its key (a byte, or a pair of bytes) and the count itself in enough bits for the file's length: a simple, honest description, though not the most compact one.

Python
"""Squeeze, stage 4: an entropy report. What could a code built on each model achieve, counting the model's own cost?"""
import math
from collections import Counter

def order0_bits(data):
    n, c = len(data), Counter(data)
    return sum(-k * math.log2(k / n) for k in c.values())              # total surprise, in bits

def order1_bits(data):
    pairs, before = Counter(zip(data, data[1:])), Counter(data[:-1])
    first = 8                                                         # the first byte, sent plainly
    return first + sum(-k * math.log2(k / before[a]) for (a, b), k in pairs.items())

def model_cost(counts, n, key_bits):
    """Bits to send a table of non-zero counts: each entry's key, and its count in enough bits for n."""
    return len(counts) * (key_bits + max(1, n.bit_length()))

def report(name, data):
    n = len(data)
    c0, c1 = Counter(data), Counter(zip(data, data[1:]))
    rows = {"order 0": (order0_bits(data), model_cost(c0, n, 8)),
            "order 1": (order1_bits(data), model_cost(c1, n, 16))}
    return {k: (bits / n, cost / n, (bits + cost) / n) for k, (bits, cost) in rows.items()}

Step 2: run it on the corpus.

Python
import json, lzma
from pathlib import Path
from report import report
base = {r["file"]: r for r in json.loads(Path("baseline.json").read_text())}
print(f"{'file':<16}{'model':>8}{'data b/B':>10}{'model b/B':>11}{'total b/B':>11}{'lzma b/B':>10}")
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
    data = Path(name).read_bytes()
    lz = 8 * base[name]["lzma"] / len(data)
    for model, (d, m, t) in report(name, data).items():
        print(f"{name if model == 'order 0' else '':<16}{model:>8}{d:>10.3f}{m:>11.3f}{t:>11.3f}{(f'{lz:.3f}' if model == 'order 0' else ''):>10}")
Text
file               model  data b/B  model b/B  total b/B  lzma b/B
shakespeare.txt  order 0     4.779      0.002      4.781     2.611
                 order 1     3.538      0.047      3.585          
zeros.bin        order 0     0.000      0.000      0.000     0.007
                 order 1     0.000      0.000      0.000          
random.bin       order 0     7.999      0.033      8.032     8.003
                 order 1     7.740     10.599     18.339          
squares.csv      order 0     3.556      0.002      3.558     1.610
                 order 1     3.380      0.023      3.403          
server.log       order 0     4.364      0.003      4.367     0.509
                 order 1     1.663      0.028      1.691

Step 3: read the targets.

  • shakespeare.txt: order-0 costs 4.78 bits per byte including its tiny table; order-1 3.59, and its table of pairs adds only 0.05 because the file is long. Both are far above lzma's 2.61: lzma's model uses longer contexts and repeated strings.
  • zeros.bin: both models cost essentially nothing: one symbol, one pair.
  • random.bin: order-0 costs 8.03 bits per byte with its table, slightly more than storing the bytes as they are. Order-1's data bits look smaller (7.74), but its table of about 65,000 pairs costs 10.6 bits per byte, for a total of 18.3: stage 3's apparent saving was an illusion, and the report shows exactly why.
  • squares.csv and server.log: order-1 helps (3.40 and 1.69), but lzma does far better (1.61 and 0.51), because their structure spans whole lines, not single pairs of bytes.

Senior and architect lens

  • Always count the model. In compression, the decoder must rebuild the model, so its description is part of the output. The same discipline applies to any model: its complexity is part of its cost (the minimum description length principle, a formal version of Occam's razor).
  • Targets before code. The report is cheap to compute and says, before you write a coder, what each design can reach. Stage 5's Huffman coder will land just above the order-0 line; stage 7's context coder just above order-1. If a coder lands below its line, it has a bug.
  • Know when a better model is needed. No coder can make an order-0 or order-1 model match lzma on these files; only a richer model can. Stages 7 and 11 add context and adaptivity for that reason.

Evidence

  • report.py and your table, matching the one above.
  • A paragraph on the random file explaining the order-1 row.
  • Your answers to the four theory questions.

Carry forward

Stage 5, after chapter 5, builds Squeeze's first variable-length coder: a Huffman code for the order-0 model, sent with its table in the file's header, decoded and checked byte for byte. Its size will be compared with this report's order-0 total.