Type at least 2 letters. Enter opens the first result, Esc closes.

    Information Theory · Lesson 5 · KL divergence, cross-entropy and compression

    Source coding: compression is prediction

    Intermediate 70 min 5 interactive figures 3 videos Colab notebook

    Before this lesson: lesson 01 (surprisal, entropy, the question game), lesson 02 (the chain rule, used for blocks of symbols), lesson 03 (KL divergence, Gibbs' inequality) and lesson 04 (H(p,q)=H(p)+KL(p ∥ q)H(p, q) = H(p) + \mathrm{KL}(p\,\|\,q), bits per byte). Time: about 70 minutes, plus the notebook.


    Why this matters #

    Lesson 01 called entropy "the average number of yes/no questions". This lesson makes that exact: entropy is the smallest average number of bits per symbol that any lossless code can reach. This turns log-loss into a physical quantity.

    • Language models report losses in bits per byte (lesson 04). With arithmetic coding, that number is the size of the compressed text. Delétang et al. (2024) show that large language models are strong general-purpose compressors.
    • Every compressor ends with an entropy coder: zip, gzip and PNG (Huffman coding), JPEG, zstd (Huffman and asymmetric numeral systems), learned image codecs (arithmetic coding with a neural model).
    • Model compression: quantized weights are often entropy-coded, and the entropy of the quantized values is a lower bound on the bits per weight of such a code.
    • Minimum description length (MDL) chooses between models by the total length of model plus data: a principled form of Occam's razor.

    As in the whole track, log⁡\log is the natural log (nats) and log⁡2\log_2 gives bits. In this lesson all code lengths and entropies are in bits. We write KL2(p ∥ q)\mathrm{KL}_2(p\,\|\,q) for the KL divergence in bits (KL\mathrm{KL} in nats divided by ln⁡2\ln 2).

    1. Predict first #

    2. The picture #

    Fixed length vs variable length #

    Four symbols a,b,c,da, b, c, d have probabilities (12,14,18,18)(\frac12, \frac14, \frac18, \frac18). A fixed-length code (00,01,10,1100, 01, 10, 11) needs 2 bits per symbol. Now try a variable-length code: a=0a = 0, b=10b = 10, c=110c = 110, d=111d = 111. On average it needs

    12⋅1+14⋅2+18⋅3+18⋅3=1.75 bits.\tfrac12 \cdot 1 + \tfrac14 \cdot 2 + \tfrac18 \cdot 3 + \tfrac18 \cdot 3 = 1.75 \text{ bits.}

    This is exactly the entropy H=1.75H = 1.75 bits. Look at the lengths: each one equals the surprisal −log⁡2p-\log_2 p of its symbol (−log⁡212=1-\log_2 \frac12 = 1, −log⁡214=2-\log_2 \frac14 = 2, −log⁡218=3-\log_2 \frac18 = 3). This code is the question game of lesson 01: the bits are the answers to "is it aa?", "is it bb?", "is it cc?".

    Prefix-free codes decode instantly #

    A code is prefix-free (also called a prefix code) when no codeword is the beginning of another codeword. Then you can read the bits from left to right and output a symbol as soon as a codeword is complete. You need no separators:

    0110111  →  0∣110∣111  →  a c d.0110111 \;\to\; 0 \mid 110 \mid 111 \;\to\; a\,c\,d .

    Step by step: the first bit 00 is a codeword (aa), so output aa. The next bits 11, 1111 are not codewords, 110110 is (cc). The last three bits 111111 give dd.

    The code tree and the budget #

    Draw each codeword as a path in a binary tree: 00 = go left, 11 = go right. A code is prefix-free exactly when every codeword is a leaf: no codeword lies on the path to another one.

    Now the key picture. Read a codeword cc of length ll as the binary fraction 0.c0.c. All infinite bit strings that start with cc fill an interval of length 2−l2^{-l} in [0,1)[0, 1). For example, 1010 owns [0.102,0.112)=[0.5,0.75)[0.10_2, 0.11_2) = [0.5, 0.75), an interval of length 2−2=142^{-2} = \frac14.

    • Prefix-free means that these intervals do not overlap.
    • The intervals lie inside [0,1)[0, 1), so their lengths add up to at most 1.

    So a code has a budget of 1, and a codeword of length ll costs 2−l2^{-l} of it. Short codewords are expensive: a 1-bit codeword uses half of the budget. How should you spend the budget? Give each symbol a share close to its probability: 2−li≈pi2^{-l_i} \approx p_i, that is, li≈−log⁡2pil_i \approx -\log_2 p_i. This is the whole theory in one line. Section 3 makes it exact.

    Interactive figure: loading…

    Pick a symbol, then click a node of the tree to give that symbol this codeword. The bar below the tree shows the interval of each codeword in [0,1)[0, 1); its length 2−l2^{-l} is the codeword's share of the budget (orange, the code's model). The blue bar shows the probabilities pp for comparison. Watch the Kraft sum and the average length LL against the entropy HH. Try "not prefix-free": two intervals overlap (yellow) and the code cannot be decoded instantly.

    Quick check

    Is the code {0,01,11}\{0, 01, 11\} prefix-free?

    Quick check

    A binary prefix code has lengths (1,2,3,3)(1, 2, 3, 3). Can you add a fifth codeword without changing the other four?

    3. Definitions and main results #

    Setup. A source XX takes values 1,…,K1, \dots, K (K≥2K \ge 2) with probabilities p1,…,pK>0p_1, \dots, p_K > 0.

    • A binary symbol code gives symbol ii a codeword cic_i, a string of bits of length lil_i.
    • The expected length is L=∑ipiliL = \sum_i p_i l_i bits per symbol.
    • A code is uniquely decodable if every concatenation of codewords can be split in only one way.
    • A code is prefix-free if no codeword is a prefix of another. Prefix-free codes are uniquely decodable, and they decode instantly.
    • L∗L^* is the smallest expected length over all prefix codes.
    • A code with ∑i2−li=1\sum_i 2^{-l_i} = 1 is complete.

    3.1 The Kraft inequality #

    Theorem 1 (Kraft inequality). (a) The lengths of every binary prefix code satisfy ∑i=1K2−li≤1\sum_{i=1}^K 2^{-l_i} \le 1. (b) Conversely, if positive integers l1,…,lKl_1, \dots, l_K satisfy ∑i2−li≤1\sum_i 2^{-l_i} \le 1, then there is a prefix code with these lengths.

    Proof of (a), with the tree.

    1. Let lmax⁡=max⁡ilil_{\max} = \max_i l_i. The bit strings of length lmax⁡l_{\max} are the 2lmax⁡2^{l_{\max}} leaves of the full binary tree of depth lmax⁡l_{\max}.
    2. The codeword cic_i has 2lmax⁡−li2^{l_{\max} - l_i} descendants among these leaves: the strings that start with cic_i.
    3. Prefix-free means that these sets of descendants are disjoint. (A string that starts with both cic_i and cjc_j would make one of them a prefix of the other.)
    4. So ∑i2lmax⁡−li≤2lmax⁡\sum_i 2^{l_{\max} - l_i} \le 2^{l_{\max}}. Divide by 2lmax⁡2^{l_{\max}}. ■\blacksquare

    Proof of (b), with intervals.

    1. Sort the lengths: l1≤l2≤⋯≤lKl_1 \le l_2 \le \dots \le l_K. Let Fi=∑j<i2−ljF_i = \sum_{j<i} 2^{-l_j}, so F1=0F_1 = 0. Kraft gives Fi+2−li≤1F_i + 2^{-l_i} \le 1.
    2. Every term 2−lj2^{-l_j} with j<ij < i is a whole multiple of 2−li2^{-l_i}, because lj≤lil_j \le l_i. So FiF_i is a multiple of 2−li2^{-l_i}, and its binary expansion ends after lil_i digits. Let cic_i be these lil_i digits.
    3. The binary fractions that start with cic_i form the interval [Fi,Fi+2−li)[F_i, F_i + 2^{-l_i}). These intervals are laid end to end, so they do not overlap.
    4. If cic_i were a prefix of cjc_j, the interval of cjc_j would lie inside the interval of cic_i. Disjoint intervals rule this out. ■\blacksquare

    Example. Lengths (1,2,3,3)(1, 2, 3, 3) give F=0,0.5,0.75,0.875F = 0, 0.5, 0.75, 0.875. In binary these are 0.02,0.102,0.1102,0.11120.0_2, 0.10_2, 0.110_2, 0.111_2, so the code is 0,10,110,1110, 10, 110, 111.

    McMillan's theorem. Every uniquely decodable code also satisfies the Kraft inequality. So restricting to prefix codes loses nothing: for every uniquely decodable code there is a prefix code with the same lengths.

    Proof of McMillan's theorem

    Let S=∑i2−liS = \sum_i 2^{-l_i} for a uniquely decodable code, and let n≥1n \ge 1.

    1. Expand the power: Sn=∑i1,…,in2−(li1+⋯+lin)S^n = \sum_{i_1, \dots, i_n} 2^{-(l_{i_1} + \dots + l_{i_n})}. Each term belongs to one sequence of nn symbols, and the exponent is the length of its encoded bit string.
    2. Group the terms by this length mm, which lies between nn and n lmax⁡n\,l_{\max}. Let AmA_m be the number of symbol sequences whose encoding has mm bits. Then Sn=∑m=nnlmax⁡Am2−mS^n = \sum_{m=n}^{n l_{\max}} A_m 2^{-m}.
    3. Unique decodability means that different symbol sequences give different bit strings. There are only 2m2^m bit strings of length mm, so Am≤2mA_m \le 2^m.
    4. Hence Sn≤n lmax⁡−n+1≤n lmax⁡S^n \le n\,l_{\max} - n + 1 \le n\,l_{\max} for every nn.
    5. If S>1S > 1, the left side grows exponentially in nn and the right side only linearly, which is impossible for large nn. So S≤1S \le 1. ■\blacksquare

    (MacKay, Information Theory, Inference, and Learning Algorithms, §5.2.)

    3.2 The entropy bound (source coding theorem) #

    Theorem 2 (entropy bound). Every prefix code (indeed every uniquely decodable code) has L≥H(X)L \ge H(X), with equality if and only if pi=2−lip_i = 2^{-l_i} for all ii. There is a prefix code with L<H(X)+1L < H(X) + 1. Hence

    H(X)≤L∗<H(X)+1.H(X) \le L^* < H(X) + 1 .

    Why this is true (intuition). Every code "believes in" a distribution: the shares 2−li2^{-l_i} of the budget. Using a code is like using a model. By Gibbs' inequality (lesson 03), coding with any model other than pp costs extra bits. Integer lengths cost less than 1 extra bit because rounding −log⁡2pi-\log_2 p_i up adds less than 1.

    Proof.

    1. Let Z=∑j2−ljZ = \sum_j 2^{-l_j}. Then Z≤1Z \le 1 by Kraft (or McMillan). Define ri=2−li/Zr_i = 2^{-l_i}/Z. This is a probability distribution: the implicit distribution of the code.
    2. Write li=−log⁡2ri−log⁡2Zl_i = -\log_2 r_i - \log_2 Z. Then
    L−H=∑ipili+∑ipilog⁡2pi=∑ipilog⁡2piri−log⁡2Z=KL2(p ∥ r)−log⁡2Z.\begin{aligned} L - H &= \sum_i p_i l_i + \sum_i p_i \log_2 p_i \\ &= \sum_i p_i \log_2 \frac{p_i}{r_i} - \log_2 Z = \mathrm{KL}_2(p\,\|\,r) - \log_2 Z . \end{aligned}
    1. KL2(p ∥ r)≥0\mathrm{KL}_2(p\,\|\,r) \ge 0 by Gibbs' inequality, and −log⁡2Z≥0-\log_2 Z \ge 0 because Z≤1Z \le 1. So L≥HL \ge H.
    2. Equality needs both terms to be 0: r=pr = p and Z=1Z = 1. That is, pi=2−lip_i = 2^{-l_i} for all ii (dyadic probabilities, powers of 12\frac12).
    3. Upper bound. Take the Shannon lengths li=⌈−log⁡2pi⌉l_i = \lceil -\log_2 p_i \rceil (round up). From li≥−log⁡2pil_i \ge -\log_2 p_i we get 2−li≤pi2^{-l_i} \le p_i, so ∑i2−li≤∑ipi=1\sum_i 2^{-l_i} \le \sum_i p_i = 1, and Theorem 1(b) gives a prefix code with these lengths. From li<−log⁡2pi+1l_i < -\log_2 p_i + 1 we get L<H+1L < H + 1.
    4. L∗L^* is at most the length of this code, and at least HH by step 3. ■\blacksquare

    Blocks of symbols. Code nn independent symbols at once, as one "super-symbol" from an alphabet with KnK^n values. By the chain rule and independence (lesson 02), H(X1,…,Xn)=nH(X)H(X_1, \dots, X_n) = nH(X). Theorem 2 for the block gives nH≤Ln∗<nH+1nH \le L^*_n < nH + 1. Divide by nn:

    H(X)≤Ln∗n<H(X)+1n.H(X) \le \frac{L^*_n}{n} < H(X) + \frac1n .

    The rounding cost of less than 1 bit is now shared by nn symbols. So entropy is the best possible compression rate, and you can get as close to it as you like. This is Shannon's source coding theorem for lossless codes.

    Interactive figure: loading…

    Move the slider to change the coin's probability of heads. The dots are the bits per flip of the best (Huffman) code for blocks of nn flips. They stay between the entropy HH (blue line) and the bound H+1/nH + 1/n (magenta). Notice that the rate does not always go down when nn grows (for p=0.9p = 0.9, n=7n = 7 is a little worse than n=6n = 6); only the bound does. At p=0.5p = 0.5 there is nothing to gain: H=1H = 1 bit already.

    The cost of a wrong code. If the code is complete (Z=1Z = 1), step 2 reads L=H(p)+KL2(p ∥ r)L = H(p) + \mathrm{KL}_2(p\,\|\,r) with ri=2−lir_i = 2^{-l_i}. Every code is a model, and its excess length is the KL divergence from the true distribution to the code's implicit distribution. Section 3.5 comes back to this.

    Quick check

    A source has entropy H(X)=1.3H(X) = 1.3 bits. What do you know about the best average length L10∗/10L^*_{10}/10 (bits per symbol) of a prefix code on blocks of 10 symbols?

    3.3 The Huffman code #

    Shannon lengths prove the bound, but they are not optimal. Huffman's algorithm (1952) finds the best prefix code for a known distribution.

    The idea: the two least likely symbols should get the longest codewords, and these codewords should differ only in the last bit. Merging them reduces the problem to K−1K - 1 symbols.

    Interactive figure: loading…

    Press Next merge to run Huffman's algorithm one step at a time. The two yellow nodes are the two smallest weights; they merge into a new node one level up. At the end, read each codeword along the path from the root (left = 0, right = 1). The table compares each length with the surprisal −log⁡2pi-\log_2 p_i, and the readout compares LL with the entropy HH (blue). Edit the probabilities, or try the preset with ties.

    Ties. For p=(0.4,0.2,0.2,0.1,0.1)p = (0.4, 0.2, 0.2, 0.1, 0.1), the algorithm can break ties in different ways. One choice gives lengths (2,2,2,3,3)(2, 2, 2, 3, 3), another gives (1,2,3,4,4)(1, 2, 3, 4, 4). Both have L=2.2L = 2.2 bits, and H=2.122H = 2.122 bits. Ties can change the tree, even the set of lengths, but never the expected length.

    Theorem 3 (Huffman is optimal). For a known distribution pp, no prefix code has a smaller expected length than the Huffman code. By McMillan's theorem, no uniquely decodable symbol code has either.

    Proof of Theorem 3 (exchange and induction)

    Order the symbols so that pK−1p_{K-1} and pKp_K are the two smallest probabilities.

    1. Swap. In an optimal code, pi>pjp_i > p_j implies li≤ljl_i \le l_j. If not, swap the two codewords: LL changes by (pi−pj)(lj−li)<0(p_i - p_j)(l_j - l_i) < 0, which contradicts optimality.
    2. No lonely nodes. In the tree of an optimal code, every internal node has two children. If a node had only one child, delete that branch's bit from every codeword below it. The code stays prefix-free and gets shorter. So a longest codeword has a sibling, and that sibling is also a codeword of maximal length.
    3. Siblings. By steps 1–2, some optimal code gives symbols K−1K-1 and KK codewords of maximal length. Exchanging codewords among leaves of maximal length does not change LL, so we may assume that K−1K-1 and KK are siblings.
    4. Merge. Merge symbols K−1K-1 and KK into one symbol with probability pK−1+pKp_{K-1} + p_K. This gives a source p′p' with K−1K - 1 symbols. A code C′C' for p′p' becomes a code CC for pp when the merged leaf gets two children. Then L(C)=L(C′)+pK−1+pKL(C) = L(C') + p_{K-1} + p_K, because both symbols pay one extra bit. In the other direction, the optimal code of step 3 merges into a code for p′p' with the same relation. Together: L∗(p)=L∗(p′)+pK−1+pKL^*(p) = L^*(p') + p_{K-1} + p_K.
    5. Induction on KK. Huffman's first step is exactly this merge, and the rest of Huffman builds a code for p′p'. For K=2K = 2, Huffman gives 0,10, 1, which is optimal. If Huffman is optimal for K−1K - 1 symbols, step 4 gives L(Huffman(p))=L∗(p′)+pK−1+pK=L∗(p)L(\text{Huffman}(p)) = L^*(p') + p_{K-1} + p_K = L^*(p). ■\blacksquare

    Consequences: Huffman codes are complete (Kraft sum 1), and H≤LHuffman<H+1H \le L_{\text{Huffman}} < H + 1, because LHuffman=L∗L_{\text{Huffman}} = L^*.

    Weaknesses.

    • The extra bit. Lengths are whole numbers, so every symbol costs at least 1 bit. For a coin with P(heads)=0.99P(\text{heads}) = 0.99, H=0.081H = 0.081 bits, but Huffman needs 1 bit per flip.
    • A fixed distribution. If the probabilities depend on the context (the previous characters) or change over time, you need a new code for each context.
    • Fix 1: blocks. The overhead drops below 1/n1/n bit per symbol, but the alphabet grows like KnK^n.
    • Fix 2: arithmetic coding (next section).
    Quick check

    Build a Huffman code for p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1). What is its expected length?

    3.4 Arithmetic coding #

    Arithmetic coding removes the "extra bit per symbol". It codes a whole sequence x1,…,xnx_1, \dots, x_n as one number in [0,1)[0, 1).

    1. Start with the interval [0,1)[0, 1).
    2. For each symbol xtx_t: split the current interval into pieces, one per possible symbol, with lengths proportional to the model's probabilities q(xt∣x<t)q(x_t \mid x_{<t}). Keep the piece of the symbol that actually comes.
    3. After nn symbols, the interval has width w=q(x1) q(x2∣x1)⋯q(xn∣x<n)=q(x1:n)w = q(x_1) \, q(x_2 \mid x_1) \cdots q(x_n \mid x_{<n}) = q(x_{1:n}), by the chain rule of probability.
    4. Send the shortest binary fraction whose whole dyadic interval lies inside the final interval. This needs at most ⌈−log⁡2w⌉+1<−log⁡2q(x1:n)+2\lceil -\log_2 w \rceil + 1 < -\log_2 q(x_{1:n}) + 2 bits.

    The decoder runs the same model: it splits [0,1)[0, 1) the same way, sees which piece contains the received number, outputs that symbol, and repeats. It must also know nn (or the model has an end-of-message symbol).

    Small example. Model q(a)=0.8q(a) = 0.8, q(b)=0.2q(b) = 0.2; sequence a a b aa\,a\,b\,a.

    step symbol interval width
    0 — [0,1)[0, 1) 1
    1 aa [0,0.8)[0, 0.8) 0.8
    2 aa [0,0.64)[0, 0.64) 0.64
    3 bb [0.512,0.64)[0.512, 0.64) 0.128
    4 aa [0.512,0.6144)[0.512, 0.6144) 0.1024

    −log⁡20.1024=3.29-\log_2 0.1024 = 3.29 bits. The 5-bit fraction 0.100012=0.531250.10001_2 = 0.53125 owns [0.53125,0.5625)[0.53125, 0.5625), which lies inside the final interval, so the codeword is 1000110001: 5 bits, below the bound 3.29+23.29 + 2. For short sequences the "+2" matters; for long ones it does not. For a a a a b a a aa\,a\,a\,a\,b\,a\,a\,a this model needs 6 bits, the uniform model 8 bits, and the model q(a)=0.2q(a) = 0.2 needs 17 bits.

    Interactive figure: loading…

    Add symbols with the buttons and watch the interval shrink. Each row zooms into the piece kept in the row above (yellow); the piece sizes are the model's probabilities q(xt∣x<t)q(x_t \mid x_{<t}). The readout gives the final width w=q(x1:n)w = q(x_{1:n}), the ideal length −log⁡2w-\log_2 w, and the real codeword. Switch the model: a model that predicts the sequence well keeps wide intervals and needs few bits. "Learns from counts" is an adaptive model that updates its probabilities after every symbol.

    Any model works, as long as the decoder can run it too: fixed probabilities, counts that adapt as the data arrive, or a neural network that predicts the next token. Modern entropy coders such as asymmetric numeral systems (ANS) reach the same lengths and run faster.

    3.5 Compression = prediction #

    Put the pieces together.

    • With a model qq, the ideal code length of xx is −log⁡2q(x)-\log_2 q(x) bits. Arithmetic coding reaches it for a whole sequence within 2 bits; Shannon lengths ⌈−log⁡2q⌉\lceil -\log_2 q \rceil reach it within 1 bit per symbol.
    • If the data come from pp, the expected ideal length is the cross-entropy (lesson 04):
    Ep[−log⁡2q(X)]=H(p,q)=H(p)+KL2(p ∥ q) bits.\mathbb{E}_p[-\log_2 q(X)] = H(p, q) = H(p) + \mathrm{KL}_2(p\,\|\,q) \text{ bits.}

    A wrong model costs exactly KL2(p ∥ q)\mathrm{KL}_2(p\,\|\,q) extra bits per symbol. With Shannon lengths for qq: H(p)+KL2(p ∥ q)≤L<H(p)+KL2(p ∥ q)+1H(p) + \mathrm{KL}_2(p\,\|\,q) \le L < H(p) + \mathrm{KL}_2(p\,\|\,q) + 1.

    • Note the direction: the data come from pp, the code is designed for qq, and the cost is KL(p ∥ q)\mathrm{KL}(p\,\|\,q), not KL(q ∥ p)\mathrm{KL}(q\,\|\,p).
    Interactive figure: loading…

    Drag the bar tops of the true distribution pp (blue) and the model qq (orange). The lower chart shows the average code length when the data come from pp and the code is built for qq: the entropy H(p)H(p) (blue), the extra cost KL2(p ∥ q)\mathrm{KL}_2(p\,\|\,q) of the wrong model (aqua), and the rounding cost of whole-number Shannon lengths (yellow). Set q=pq = p: the aqua part disappears.

    Sequences and language models. A language model predicts each token from the earlier ones. By the chain rule of probability, q(x1:n)=∏tq(xt∣x<t)q(x_{1:n}) = \prod_t q(x_t \mid x_{<t}), so

    −log⁡2q(x1:n)=∑t=1n−log⁡2q(xt∣x<t).-\log_2 q(x_{1:n}) = \sum_{t=1}^n -\log_2 q(x_t \mid x_{<t}) .

    The code length of a text is the sum of the per-token losses in bits. So the training loss of a language model, converted to bits, is the length of the text after arithmetic coding with that model. Minimizing cross-entropy is learning to compress. In the other direction, a compressor is a model: a complete code with lengths lil_i "believes" the distribution qi=2−liq_i = 2^{-l_i}.

    Minimum description length (MDL). The decoder must know the model. A fair comparison of two models counts the bits for the model and the bits for the data given the model: L(model)+L(data∣model)L(\text{model}) + L(\text{data} \mid \text{model}). A huge model may code the data in few bits but cost many bits itself. MDL picks the model with the smallest total; it is one precise form of Occam's razor.

    Quick check

    Data come from pp, and you compress them with an ideal code for the model qq. How many extra bits per symbol do you pay, compared with the best code for pp?

    Answers to section 1. (1) 1 bit. Each symbol needs at least one bit, so heads=0\text{heads} = 0, tails=1\text{tails} = 1 is optimal, 0.531 bits above HH. Coding pairs of flips gives 0.645 bits per flip (section 4), blocks of nn flips get within 1/n1/n of 0.469, and arithmetic coding gets within 2 bits of −log⁡2q-\log_2 q of the whole sequence. (2) KL2(p ∥ q)\mathrm{KL}_2(p\,\|\,q) bits per symbol with ideal lengths −log⁡2q-\log_2 q, plus less than 1 bit if the lengths are rounded up to whole numbers. (3) About 250 KB: 2 bits instead of 8 bits per character is a factor of 4, and 106⋅210^6 \cdot 2 bits =250 000= 250\,000 bytes. The decoder needs the same model, so a fair comparison (MDL, section 3.5) adds the size of the model.

    4. Worked example #

    (a) A Huffman code by hand. Five symbols a,b,c,d,ea, b, c, d, e with p=(0.45,0.25,0.17,0.08,0.05)p = (0.45, 0.25, 0.17, 0.08, 0.05).

    step merge the two smallest new node nodes left
    1 ee (0.05) + dd (0.08) dede (0.13) aa 0.45, bb 0.25, cc 0.17, dede 0.13
    2 dede (0.13) + cc (0.17) cdecde (0.30) aa 0.45, cdecde 0.30, bb 0.25
    3 bb (0.25) + cdecde (0.30) bcdebcde (0.55) aa 0.45, bcdebcde 0.55
    4 aa (0.45) + bcdebcde (0.55) root (1) —

    Label the branches: aa gets 0 and bcdebcde gets 1; inside bcdebcde, bb gets 0 and cdecde gets 1; inside cdecde, cc gets 0 and dede gets 1; inside dede, dd gets 0 and ee gets 1. The code is

    a=0,b=10,c=110,d=1110,e=1111.a = 0, \quad b = 10, \quad c = 110, \quad d = 1110, \quad e = 1111 .
    • Expected length: 0.45⋅1+0.25⋅2+0.17⋅3+0.08⋅4+0.05⋅4=0.45+0.5+0.51+0.32+0.2=1.980.45 \cdot 1 + 0.25 \cdot 2 + 0.17 \cdot 3 + 0.08 \cdot 4 + 0.05 \cdot 4 = 0.45 + 0.5 + 0.51 + 0.32 + 0.2 = 1.98 bits.
    • Entropy: the surprisals are 1.152,2,2.556,3.644,4.3221.152, 2, 2.556, 3.644, 4.322 bits, so H=0.45⋅1.152+0.25⋅2+0.17⋅2.556+0.08⋅3.644+0.05⋅4.322=1.961H = 0.45 \cdot 1.152 + 0.25 \cdot 2 + 0.17 \cdot 2.556 + 0.08 \cdot 3.644 + 0.05 \cdot 4.322 = 1.961 bits. Check the theorem: 1.961≤1.98<2.9611.961 \le 1.98 < 2.961 ✓. A fixed-length code would need 3 bits.
    • Kraft sum: 12+14+18+116+116=1\frac12 + \frac14 + \frac18 + \frac1{16} + \frac1{16} = 1: the code is complete.
    • Decoding 01011011100101101110: 0∣10∣110∣1110→a b c d0 \mid 10 \mid 110 \mid 1110 \to a\,b\,c\,d.

    (b) Shannon lengths. ⌈−log⁡2pi⌉=(2,2,3,4,5)\lceil -\log_2 p_i \rceil = (2, 2, 3, 4, 5). The expected length is 0.9+0.5+0.51+0.32+0.25=2.480.9 + 0.5 + 0.51 + 0.32 + 0.25 = 2.48 bits: below H+1=2.961H + 1 = 2.961, as promised, but 0.5 bits worse than Huffman. The Kraft sum is 14+14+18+116+132=0.719\frac14 + \frac14 + \frac18 + \frac1{16} + \frac1{32} = 0.719: 28% of the budget is wasted.

    (c) A wrong model. True p=(12,14,18,18)p = (\frac12, \frac14, \frac18, \frac18) with H(p)=1.75H(p) = 1.75 bits.

    • Use the code for the uniform model uu (all lengths 2): L=2L = 2 bits. The KL in bits is KL2(p ∥ u)=12log⁡21/21/4+14log⁡21/41/4+2⋅18log⁡21/81/4=12+0−14=0.25\mathrm{KL}_2(p\,\|\,u) = \frac12 \log_2 \frac{1/2}{1/4} + \frac14 \log_2 \frac{1/4}{1/4} + 2 \cdot \frac18 \log_2 \frac{1/8}{1/4} = \frac12 + 0 - \frac14 = 0.25, and indeed L=1.75+0.25L = 1.75 + 0.25.
    • The other way round: the code 0,10,110,1110, 10, 110, 111 on uniform data gives L=14(1+2+3+3)=2.25=H(u)+KL2(u ∥ p)=2+0.25L = \frac14(1 + 2 + 3 + 3) = 2.25 = H(u) + \mathrm{KL}_2(u\,\|\,p) = 2 + 0.25.

    Both results are exact, because every length equals −log⁡2-\log_2 of the model probability.

    (d) Blocks. The coin with P(heads)=0.9P(\text{heads}) = 0.9, H=0.469H = 0.469 bits. One flip at a time: 1 bit. Pairs have probabilities 0.81,0.09,0.09,0.010.81, 0.09, 0.09, 0.01. Huffman merges 0.01+0.09=0.100.01 + 0.09 = 0.10, then 0.09+0.10=0.190.09 + 0.10 = 0.19, then 0.19+0.81=10.19 + 0.81 = 1. The lengths are 1,2,3,31, 2, 3, 3, so

    L2=0.81⋅1+0.09⋅2+0.09⋅3+0.01⋅3=1.29 bits per pair=0.645 bits per flip,L_2 = 0.81 \cdot 1 + 0.09 \cdot 2 + 0.09 \cdot 3 + 0.01 \cdot 3 = 1.29 \text{ bits per pair} = 0.645 \text{ bits per flip},

    below the bound H+12=0.969H + \frac12 = 0.969. Blocks of 3, 4, 5, 6 flips give 0.533,0.493,0.480,0.4700.533, 0.493, 0.480, 0.470 bits per flip.

    5. In code #

    NumPy and SciPy check the hand computations above: the entropy, the expected lengths, the Kraft sums, a brute-force search over all valid length vectors, and the cost of a wrong model.

    import itertools
    import numpy as np
    from scipy.stats import entropy
    
    p = np.array([0.45, 0.25, 0.17, 0.08, 0.05])
    huffman = np.array([1, 2, 3, 4, 4])        # lengths of the code built by hand in section 4
    shannon = np.ceil(-np.log2(p))             # Shannon lengths
    print(shannon)                              # [2. 2. 3. 4. 5.]
    print(round(entropy(p, base=2), 4))         # 1.9606  = H in bits
    print(round(p @ huffman, 4), round(p @ shannon, 4))       # 1.98 2.48
    print((2.0 ** -huffman).sum(), (2.0 ** -shannon).sum())   # 1.0 0.71875  (Kraft sums)
    
    # Brute force over all length vectors that satisfy Kraft: nothing beats 1.98.
    grid = np.array(list(itertools.product(range(1, 6), repeat=5)))
    ok = (2.0 ** -grid).sum(axis=1) <= 1
    print(round((grid[ok] @ p).min(), 4))       # 1.98
    
    # Wrong model: ideal lengths -log2 q(x) cost H(p) + KL(p || q) bits per symbol.
    p4, u4 = np.array([1/2, 1/4, 1/8, 1/8]), np.full(4, 1/4)
    print(entropy(p4, base=2) + entropy(p4, u4, base=2))    # 2.0   = 1.75 + 0.25
    print(entropy(u4, base=2) + entropy(u4, p4, base=2))    # 2.25  = 2 + 0.25
    

    scipy.stats.entropy(p, base=2) is H(p)H(p) in bits, and entropy(p, q, base=2) is KL2(p ∥ q)\mathrm{KL}_2(p\,\|\,q). The notebook builds the Huffman code with heapq, encodes and decodes, and compares model-based code lengths with zlib on real text.

    6. Where it shows up #

    • File formats. DEFLATE (zip, gzip, PNG) is LZ77 followed by Huffman coding. Baseline JPEG Huffman-codes the quantized DCT coefficients. zstd uses Huffman coding for literals and an ANS coder for the rest.
    • Language models as compressors. With arithmetic coding, a model's cross-entropy in bits per token is its compressed size per token. Delétang et al. (ICLR 2024) report that Chinchilla 70B, trained on text, compresses ImageNet patches to 43.4% and LibriSpeech audio to 16.4% of the raw size, better than PNG (58.5%) and FLAC (30.3%), when the model size is not counted.
    • Bits per byte (lesson 04) is exactly this compression rate, measured per raw byte so that models with different tokenizers can be compared.
    • Tokenizers. Byte-pair encoding (BPE) started as a compression algorithm (Gage, 1994): it replaces frequent pairs of symbols by new symbols. A tokenizer shortens the sequence the model must predict.
    • Model compression. Deep Compression (Han, Mao and Dally, ICLR 2016) prunes, quantizes by weight sharing, and Huffman-codes the result: 35× smaller for AlexNet, 49× for VGG-16. After quantization, the entropy of the histogram of the quantized weights is a lower bound on the bits per weight of any code that treats the weights as independent draws from that histogram.
    • Learned image compression uses a neural network as the model for arithmetic coding of a quantized latent; this is lossy coding, the topic of lesson 10.
    • ML for science. Error-bounded compressors for simulation output (the SZ family) predict each value from its neighbours, quantize the prediction error, and entropy-code the result. A better predictor gives smaller errors with lower entropy: compression = prediction again.

    7. Common mistakes #

    • "Huffman reaches the entropy." Only for dyadic probabilities (powers of 12\frac12). Otherwise H<L<H+1H < L < H + 1, and the gap can come close to 1 bit: for p=(0.99,0.01)p = (0.99, 0.01), L=1L = 1 bit but H=0.081H = 0.081 bits.
    • "Shannon lengths are optimal." They prove the bound; Huffman can be much better (2.48 vs 1.98 bits above). For p=(0.9999,0.0001)p = (0.9999, 0.0001) the Shannon length of the rare symbol is 14 bits, while 1 bit is enough.
    • "Each Huffman codeword is at most ⌈−log⁡2pi⌉\lceil -\log_2 p_i \rceil long." False symbol by symbol. For p=(13,13,14,112)p = (\frac13, \frac13, \frac14, \frac1{12}), one Huffman code has lengths (1,2,3,3)(1, 2, 3, 3): the symbol with p=14p = \frac14 gets 3 bits, but its Shannon length is 2. Only the average is better.
    • "The entropy bound holds for every symbol." It is a bound on the expected length. A single rare symbol can get a codeword much longer than the average.
    • Wrong direction of the KL. Data from pp, code for qq: the cost is KL(p ∥ q)\mathrm{KL}(p\,\|\,q).
    • Bits vs nats. Code lengths use log⁡2\log_2; ML losses use ln⁡\ln. Divide nats by ln⁡2=0.693\ln 2 = 0.693 to get bits.
    • Forgetting the model. The decoder needs the code or the model. In MDL its size is part of the total length.
    • "A good compressor shrinks every file." There are 2n2^n bit strings of length nn and only 2n−12^n - 1 shorter ones, so no lossless code shortens all of them. Random bits cannot be compressed.

    8. Check yourself #

    1. Is there a binary prefix code with lengths (1,2,2,3)(1, 2, 2, 3)? With (1,2,3,3)(1, 2, 3, 3)?
      AnswerKraft sums: 12+14+14+18=1.125>1\frac12 + \frac14 + \frac14 + \frac18 = 1.125 > 1, so no. 12+14+18+18=1\frac12 + \frac14 + \frac18 + \frac18 = 1, so yes: 0,10,110,1110, 10, 110, 111.
    2. Build a Huffman code for p=(0.25,0.25,0.2,0.15,0.15)p = (0.25, 0.25, 0.2, 0.15, 0.15). Give its expected length and the entropy.
      AnswerMerge 0.15+0.15=0.300.15 + 0.15 = 0.30; then 0.20+0.25=0.450.20 + 0.25 = 0.45; then 0.25+0.30=0.550.25 + 0.30 = 0.55; then 0.45+0.55=10.45 + 0.55 = 1. The lengths are (2,2,2,3,3)(2, 2, 2, 3, 3), for example 00,10,01,110,11100, 10, 01, 110, 111. L=2⋅0.7+3⋅0.3=2.3L = 2 \cdot 0.7 + 3 \cdot 0.3 = 2.3 bits; H=2.285H = 2.285 bits. (MacKay, Example 5.15.)
    3. The data are fair coin flips. An arithmetic coder uses the model q(heads)=14q(\text{heads}) = \frac14, q(tails)=34q(\text{tails}) = \frac34. About how many bits per flip does it spend, and why?
      AnswerH(p,q)=12⋅2+12⋅0.415=1.208H(p, q) = \frac12 \cdot 2 + \frac12 \cdot 0.415 = 1.208 bits =H(p)+KL2(p ∥ q)=1+0.208= H(p) + \mathrm{KL}_2(p\,\|\,q) = 1 + 0.208. The model error costs 0.208 bits per flip.
    4. Why does an optimal prefix code have Kraft sum exactly 1?
      AnswerIf the sum is below 1, the code tree is not full: some internal node has only one child. Deleting that branch's bit from every codeword below it keeps the code prefix-free and lowers LL (all pi>0p_i > 0). So the code was not optimal.
    5. A complete code has lengths (1,2,3,3)(1, 2, 3, 3). Which distribution does it "believe in"? What is its expected length on p=(0.4,0.4,0.1,0.1)p = (0.4, 0.4, 0.1, 0.1), written as entropy plus KL?
      Answerq=(12,14,18,18)q = (\frac12, \frac14, \frac18, \frac18). L=0.4+0.8+0.3+0.3=1.8L = 0.4 + 0.8 + 0.3 + 0.3 = 1.8 bits =H(p)+KL2(p ∥ q)=1.722+0.078= H(p) + \mathrm{KL}_2(p\,\|\,q) = 1.722 + 0.078.
    6. Why can arithmetic coding beat the Huffman code for the coin with P(heads)=0.99P(\text{heads}) = 0.99?
      AnswerHuffman gives every flip its own codeword, so it needs at least 1 bit per flip. Arithmetic coding codes the whole sequence as one interval of width q(x1:n)q(x_{1:n}) and needs fewer than −log⁡2q(x1:n)+2-\log_2 q(x_{1:n}) + 2 bits in total: about 0.081n+20.081n + 2 bits for nn flips on average.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is a prefix-free code?

    2. State the Kraft inequality.

    3. Why does a codeword of length ll use 2−l2^{-l} of the budget?

    4. State the entropy bound for the best expected length L∗L^* of a symbol code.

    5. What are the Shannon code lengths, and what do they prove?

    6. What is the rule of Huffman's algorithm?

    7. Compute the Huffman code lengths for p=(0.4,0.3,0.2,0.1)p = (0.4, 0.3, 0.2, 0.1).

    8. What is the ideal code length of xx under a model qq?

    9. How many extra bits per symbol does a code for qq cost on data from pp?

    10. Why is a language model's loss a compression rate?

    Open the review →

    9. Interview angle #

    • "What does entropy mean operationally?" The smallest expected number of bits per symbol for lossless coding, reached in the limit of long blocks.
    • "Prove the Kraft inequality." Disjoint sets of descendants in the code tree, or disjoint intervals of length 2−li2^{-l_i} in [0,1)[0, 1).
    • "Is Huffman optimal? Then why use arithmetic coding?" Huffman is optimal among symbol codes for a fixed, known pp. But it pays up to 1 bit per symbol and adapts badly. Arithmetic coding gets within 2 bits of −log⁡2q-\log_2 q of the whole message, with any adaptive model.
    • "Why is cross-entropy a compression objective?" The model spends −log⁡2q(x)-\log_2 q(x) bits on xx; the expected excess over the entropy is KL(p ∥ q)\mathrm{KL}(p\,\|\,q).
    • "Can you compress uniformly random bits?" No. Their entropy is 1 bit per bit, and by counting, no lossless code shortens every string.
    • "Your LM has 0.9 bits per byte. What does that mean?" With arithmetic coding, the model would store the text in 0.9 bits per raw byte, about 11% of the original size, not counting the model.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. huffman_code(probs) with heapq; check that the code is prefix-free and complete.
    2. encode and decode for a prefix code, and a round trip on a random message.
    3. Brute force: no length vector that satisfies Kraft beats Huffman on a small example.
    4. block_rate(probs, n): bits per symbol of Huffman codes on blocks, for the coin with P(heads)=0.9P(\text{heads}) = 0.9 and n=1,…,6n = 1, \dots, 6.
    5. Code a text with a unigram model and a bigram (previous-character) model: ideal code lengths compared with zlib.

    11. Watch and read #

    Prefix codes as trees, the entropy bound, and Huffman's algorithm with clear animations.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Symbol codes, the Kraft inequality as a budget, and the bound H ≤ L < H + 1.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The weaknesses of Huffman codes and arithmetic coding with an adaptive model.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play