Workbench / Squeeze: the Information Theory Capstone
S5 · B1·05
The Huffman Coder
Stage 5 of Squeeze, after chapter 5: a canonical Huffman coder for bytes, with a 128-byte table of codeword lengths in the header, written with stage 2's bit writer and decoded bit by bit; every corpus file restored exactly, Shakespeare at 4.82 bits per byte just above stage 4's target, and the zeros file showing Huffman's one-bit floor at 25,136 bytes where the fixed-length code needed 11.
Stage 5: the Huffman coder
The brief
What you'll build. huffman.py, Squeeze's method 2: count the file's bytes, build Huffman codeword lengths, turn them into canonical codes, and write a header of 256 four-bit lengths followed by every byte's codeword. The decoder rebuilds the identical code from the lengths and reads codewords bit by bit.
Why a compressor needs this. Stages 3 and 4 built a model and a target; this is the first coder that uses probabilities. Its result tells you how much of the order-0 target a real code reaches, and where whole-number codeword lengths fall short.
Why now. Chapter 5 gives every piece: prefix codes, Huffman's algorithm, canonical codes from lengths, and the limits (at least one digit per symbol, lengths that can grow long).
What you'll have at the end. huffman.py, a results table with a new column, and edge cases that pass.
Theory to own
- Why lengths are enough. Why can the header carry only lengths, not codewords? (Chapter: "Canonical Huffman codes"; companion, code walkthrough.)
- The table's cost. 256 lengths at 4 bits each is 128 bytes. When does that matter? (Exercises, senior S2.)
- The one-bit floor. What will Huffman do with
zeros.bin, and why is it worse than stage 2's fixed-length code there? (Chapter: "Where Huffman falls short".) - Length limits. This coder refuses codewords longer than 15 bits instead of limiting them. When could that happen? (Companion, point 3.)
Build it
Step 1: the coder. lengths_for is the chapter's Huffman builder, with a 1-bit code for a single symbol; canonical assigns codes from lengths; pack writes the header and codes with the bit writer; unpack reads the lengths, rebuilds the code, and decodes, refusing data where no codeword matches within 15 bits.
"""Squeeze, stage 5: a canonical Huffman coder for bytes. Format: b'SQZ', method 2, length (4 bytes), 256 lengths (4 bits each), codes."""
import heapq, itertools
from collections import Counter
from bits import BitWriter, BitReader
def lengths_for(data):
freq = Counter(data)
if len(freq) == 1:
return {next(iter(freq)): 1}
tie = itertools.count()
heap = [(w, next(tie), {s: 0}) for s, w in freq.items()]
heapq.heapify(heap)
while len(heap) > 1:
w1, _, a = heapq.heappop(heap)
w2, _, b = heapq.heappop(heap)
heapq.heappush(heap, (w1 + w2, next(tie), {s: d + 1 for s, d in (a | b).items()}))
return heap[0][2]
def canonical(lengths):
code, prev, out = 0, 0, {}
for s, l in sorted(lengths.items(), key=lambda kv: (kv[1], kv[0])):
code <<= l - prev
out[s], code, prev = (code, l), code + 1, l
return out # symbol -> (code value, length)
def pack(data):
if not data:
return b"SQZ\x02" + bytes(4)
lengths = lengths_for(data)
if max(lengths.values()) > 15:
raise ValueError("a codeword longer than 15 bits: this simple coder doesn't limit lengths")
code = canonical(lengths)
w = BitWriter()
for b in range(256):
w.write(lengths.get(b, 0), 4)
for b in data:
w.write(*code[b])
return b"SQZ\x02" + len(data).to_bytes(4, "big") + w.getvalue()
def unpack(blob):
if blob[:4] != b"SQZ\x02":
raise ValueError("not a Squeeze Huffman file")
n = int.from_bytes(blob[4:8], "big")
if n == 0:
return b""
r = BitReader(blob[8:])
lengths = {b: l for b in range(256) if (l := r.read(4))}
decode = {(c, l): s for s, (c, l) in canonical(lengths).items()}
out = bytearray()
for _ in range(n):
c, l = 0, 0
while (c, l) not in decode:
c, l = (c << 1) | r.read(1), l + 1
if l > 15:
raise ValueError("corrupt data: no codeword matches")
out.append(decode[(c, l)])
return bytes(out)
Step 2: run it on the corpus and the edge cases.
import time
from pathlib import Path
import fixed, huffman
from report import report
print(f"{'file':<16}{'bytes':>10}{'fixed':>10}{'huffman':>10}{'b/B':>7}{'order-0 target':>16} round trip")
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
data = Path(name).read_bytes()
blob = huffman.pack(data)
ok = huffman.unpack(blob) == data
target = report(name, data)["order 0"][2]
print(f"{name:<16}{len(data):>10,}{len(fixed.pack(data)):>10,}{len(blob):>10,}{8 * len(blob) / len(data):>7.3f}{target:>16.3f} {'exact' if ok else 'FAILED'}")
for edge in (b"", b"x", b"ab" * 3, bytes(range(256))):
assert huffman.unpack(huffman.pack(edge)) == edge
print("edge cases (empty, one byte, two symbols, all 256 values): exact")
file bytes fixed huffman b/B order-0 target round trip
shakespeare.txt 1,115,394 976,045 671,747 4.818 4.781 exact
zeros.bin 200,000 11 25,136 1.005 0.000 exact
random.bin 200,000 200,266 200,136 8.005 8.032 exact
squares.csv 200,000 100,022 89,987 3.599 3.558 exact
server.log 200,000 125,035 110,286 4.411 4.367 exact
edge cases (empty, one byte, two symbols, all 256 values): exact
Step 3: read the table.
- shakespeare.txt: 671,747 bytes, 4.818 bits per byte, just above stage 4's order-0 target of 4.781: the chapter's 0.038-bit gap, plus 136 bytes of header. A third smaller than the fixed-length code.
- zeros.bin: 25,136 bytes, 1 bit per byte: every zero byte costs one whole binary digit, though it carries nothing. Stage 2's fixed-length code needed 11 bytes. That's the one-bit floor.
- random.bin: no gain, as expected; slightly below stage 4's target only because this header (128 bytes of lengths) is more compact than the report's estimate of a table of counts.
- squares.csv and server.log: 3.60 and 4.41 bits per byte, just above their order-0 targets, and far from lzma (1.61 and 0.51): the structure in these files isn't in byte frequencies.
Senior and architect lens
- No single method wins everywhere. Huffman beats fixed-length on four files and loses badly on one. A real compressor tries its methods and keeps the smallest result, recording the method in the header (Squeeze's method byte exists for this). Stage 6 adds that choice, including "store as is".
- Decoding speed is a design goal. Bit-by-bit decoding in Python takes a few seconds per megabyte; real decoders use lookup tables on several bits at once, which is why codeword lengths are capped. If decode speed matters to your users, measure it alongside size.
- Fail loudly on corrupt input. The decoder raises an error when no codeword matches within 15 bits, rather than looping or inventing bytes. Robust decoders treat every input as possibly hostile: check lengths in the header (they must satisfy Kraft), the declared size, and running out of bits.
Evidence
huffman.py, the results table from your own run, all "exact".- The edge cases passing.
- A paragraph on
zeros.bin: why Huffman loses there, and what would fix it.
Carry forward
Stage 6, after chapter 6, adds two things the source coding theorem motivates: coding blocks of bytes to escape the one-bit floor (or an arithmetic coder that removes it), and a method chooser that tries every method, including storing the data unchanged, and keeps the smallest. It also checks the theorem's other half: that random data can't be compressed by any of them.