17.5 Information theory problem set, part b: coding and Huffman, mutual information, maximum entropy, rate-distortion
This is where information theory becomes things the system does. Perplexity, bits per byte, NLL accumulator turned the models’ losses into bits per byte, which is literally a compression rate: a model with 2 bits per byte could drive an arithmetic coder that shrinks text to a quarter of its size, and this set proves why no code can beat the entropy. Mutual information, PMI, and PPMI built mutual information and PMI for the word-vector baseline of word2vec skip-gram with negative sampling, and the PPMI-SVD baseline in AI Engineering; here you compute them by hand.
Concepts from other sections (21)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Bits per byte (bpb): , total information divided by the UTF-8 length; comparable across tokenizers. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Entropy: , the average surprise of a distribution. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Mutual information: , the nats that knowing one variable saves about the other. Read more: 17.3 Mutual information, PMI, and PPMI
- Pointwise mutual information (PMI): for a single pair; positive above chance, for unseen pairs. Read more: 17.3 Mutual information, PMI, and PPMI
- Gibbs’ inequality: , with equality if and only if ; coding data from with a code built for always costs extra bits, so cross-entropy is never below entropy. Read more: Chapter 17: Information Theory
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Kraft’s inequality: the codeword lengths of any prefix-free (or uniquely decodable) binary code satisfy , and any lengths that satisfy it can be realized by a prefix-free code. Read more: Chapter 17: Information Theory
- Rate-distortion function: , the fewest bits per symbol needed to describe a source when the reconstruction may have average distortion up to ; it frames lossy compression and the bits-for-error tradeoff of quantization. Read more: Chapter 17: Information Theory
- Prefix code: a code in which no codeword is a prefix of another, so a bit stream decodes left to right without separators; any prefix code is a binary tree with the symbols at its leaves. Read more: Chapter 10: Greedy algorithms in Programming and Algorithms
- KL divergence: , the excess cost of predicting with ; nonnegative and asymmetric. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- greedy decoding: taking the single most likely token at every step; a beam of size 1. Read more: 10.4 Beam search, generic over a step function in AI Engineering
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- Huffman tree: the binary tree Huffman’s algorithm builds, with each character at a leaf; a character’s code is its path from the root, 0 for a left branch and 1 for a right one, so frequent characters sit near the root and get short codes. Read more: 10.1 Huffman coding in Programming and Algorithms
- Complete binary tree: a tree with every level full except possibly the last, which is filled left to right; it is what makes the array layout work. Read more: 18.4 Binary heap in Programming and Algorithms
- PPMI: , a finite, sparse, non-negative matrix suitable for SVD. Read more: 17.3 Mutual information, PMI, and PPMI
- Joint distribution: the table over pairs of values; it determines marginals and conditionals. Read more: 13.10 Probability problem set, part b: joint distributions, covariance, MLE
- Lagrange multiplier: the scalar in at a constrained optimum. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Hessian: the symmetric matrix of second partial derivatives, whose eigenvalues classify a critical point. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- Standard deviation: , the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
Two topics have no section of their own in this book and live only in this set. The first is the maximum-entropy reading of softmax, which is what the temperature knob of the sampler in Sampling and logit processors means. The second is rate-distortion, the theory behind the quantizers of Quantization trading bits for error. The coding problems also supply the theorems behind source coding with Huffman and arithmetic codes, whose greedy construction is treated as an algorithm in Greedy algorithms in Programming and Algorithms.
The set has eleven problems, nineteen exact parts and three proofs (Problems 4, 7, and 9), each with a worked answer folded underneath. It builds on Problem set A for entropy, KL, and Gibbs’ inequality, and on the perplexity and mutual-information sections of this chapter.
Learning objectives
- Build a Huffman code, compute its expected length and Kraft sum, and compare it with the entropy and the Shannon code.
- Prove Kraft’s inequality and the identity .
- Compute mutual information and PMI for a small joint table, in bits.
- Derive softmax at temperature as the maximum-entropy distribution and describe its limits as and .
- Evaluate the rate-distortion function for a binary and a Gaussian source.
The ideas you need
Section titled “The ideas you need”A prefix code assigns each symbol a bit string so that no codeword is the start of another; a stream of codewords then decodes without separators. Write for the length of symbol ‘s codeword and for the expected code length. Kraft’s inequality (Problem 4) says any prefix code’s lengths satisfy , and conversely any lengths satisfying it have a prefix code. Minimizing under that constraint gives and : no code beats the entropy. Lengths must be integers, so the Shannon code rounds up, , and lands within one bit: . The Huffman code is optimal among prefix codes: repeatedly merge the two least likely symbols (or groups) into one node; each symbol’s length is the number of merges it took part in.
Mutual information connects to this through the same KL machinery. is the KL divergence from the joint to the product of its marginals, the expected PMI, where , and also . It is symmetric, non-negative, and zero exactly when and are independent. A single pair’s PMI can be negative (seen together less than chance); only the average must be non-negative.
Maximum entropy explains temperature. Among all distributions with a given expected energy, the one with the most entropy is the Gibbs distribution (Problem 9). With logits and temperature , that is softmax at temperature : . Dividing logits by sharpens the distribution and flattens it. As every and the distribution becomes uniform; as it concentrates on the largest logit, which is greedy decoding (the sampler treats as greedy).
Rate-distortion is the lossy counterpart of the coding theorem. It asks for the fewest bits per symbol, , that reproduce a source within an average distortion . For a fair coin with Hamming distortion (the fraction of flipped bits), for , where is the binary entropy: allowing errors saves exactly the entropy of the error pattern, and at the decoder can guess without receiving anything. For a Gaussian source with variance and squared error, , so : every extra bit divides the error by 4, the “6 dB per bit” rule of quantization.
Four warm-up examples
Section titled “Four warm-up examples”These are siblings of Problems 1, 5, 8, and 10, worked in full before you try the real ones.
For Huffman, take probabilities . Merge the two quarters into one node of , then merge that node with the . The lengths are , bits, and : dyadic probabilities are coded at exactly the entropy. The Kraft sum is .
For mutual information, take and , so , a fair bit. The marginals are uniform, bit, and bit : knowing removes all of ‘s uncertainty.
For temperature, take logits . At , ; at , and , sharper.
For rate-distortion, a fair coin at has , so bits per symbol. A Gaussian at needs bit.
The problems
Section titled “The problems”Each problem carries a tag for the kind of answer it wants ([number], [vector], [bool], [choice], [proof]). Answers are exact and in bits unless stated. Try each one on paper first, then open the answer and compare the derivation. Each answer names the common wrong answer and why it is wrong.
Coding theorems and Huffman
Section titled “Coding theorems and Huffman”Problem 1. A source emits four symbols with probabilities . (a) Give the codeword lengths of a binary Huffman code, in the order of the probabilities. [vector] (b) Give its expected length in bits. [number] (c) Is that expected length equal to the entropy of the source? [bool]
Answer
(a) , (b) bits, (c) true.
- (a) Merge the two s into a node; merge that with the symbol into a node; merge that with the symbol. The symbol took part in one merge, the in two, each in three. A common mistake is : the right multiset listed in the wrong order, which describes a different (bad) code. Another is , the fixed-length code.
- (b) . A common mistake is 2, the fixed-length code’s length.
- (c) . Every probability is a power of (dyadic), so the ideal lengths are integers and Huffman reaches them exactly.
Problem 2. For probabilities : (a) give the expected length in bits of a binary Huffman code; (b) give the Kraft sum of its codeword lengths . [number]
Answer
(a) bits, (b) 1.
- (a) Merge ; the two smallest are now and , merge them to ; merge . Lengths for , and . A common mistake is the entropy : that is the lower bound, which no integer-length code reaches here since the probabilities are not dyadic. Another is 2, the fixed-length code.
- (b) . A Huffman tree is complete (every internal node has two children), so its Kraft sum is exactly 1. A sum below 1 would mean a codeword could be shortened.
Problem 3. For the same probabilities : (a) give the expected length in bits of the Shannon code, whose lengths are . [number] (b) Does a binary prefix code with codeword lengths exist? [bool]
Answer
(a) bits, (b) false.
- (a) , rounded up to . , within one bit of as promised, and worse than Huffman’s 1.9. A common mistake is 1.9, the Huffman length; another is rounding down instead of up, which gives lengths whose Kraft sum exceeds 1, so no prefix code has them.
- (b) The Kraft sum is , so by Kraft’s inequality no prefix code with these lengths exists. Concretely: after
0,10,11use up the whole tree, there is no room left for a length-3 codeword.
Problem 4. Prove the Kraft inequality: the codeword lengths of any binary prefix code satisfy . [proof]
Answer
Proof. Let and picture the complete binary tree of depth , with the root as the empty string and each left/right step appending a 0 or a 1. Codeword is a node at depth . Below it lie exactly of the leaves at depth (all ways to extend it to length ).
By the prefix property no codeword is an ancestor of another, so the sets of leaves below different codewords are disjoint: a leaf below both and would make one of them a prefix of the other. Disjoint subsets of leaves have at most elements in total:
Dividing by gives .
The intuition: a codeword of length “uses up” a fraction of the tree, and prefix-freeness means the used-up parts cannot overlap.
Mutual information
Section titled “Mutual information”Problem 5. and take values in with and . In bits, give (a) the mutual information , (b) the pointwise mutual information , (c) . [number]
Answer
(a) , (b) , (c) bits.
The marginals are , so each .
- (b) . A common mistake is , the log of the joint alone.
- (c) : the pair occurs half as often as chance. A common mistake is 0, which is PPMI (the clipped value), not PMI; another is , a flipped ratio.
- (a) is the expected PMI: . A common mistake is the natural-log value (nats); another is 1, which is , the most could be.
Problem 6. (a) is uniform on and . Give in bits. [number] (b) Is for every joint distribution? [bool]
Answer
(a) 1 bit, (b) true.
- (a) . is a fair bit, so , and is a function of , so . Hence . A common mistake is 2, which is : knowing only tells you the parity, one of the two bits of .
- (b) The definition is unchanged when and swap roles. A common mistake is false, reasoning that KL is not symmetric: true, but here both arguments of the KL ( and ) are themselves symmetric in and .
Problem 7. Prove that , where , and that with equality exactly when and are independent. You may use Gibbs’ inequality (Problem set A, Problem 9). [proof]
Answer
Proof. Split the log, , and sum each term against over the pairs with :
The first sum is . In the second, does not depend on and , so it is with the minus sign in front; the third is likewise. So .
For non-negativity, the definition is exactly , and wherever both marginals are positive, so Gibbs’ inequality (Problem set A, Problem 9) applies: , with equality exactly when for every , which is the definition of independence.
Maximum entropy
Section titled “Maximum entropy”Problem 8. A softmax at temperature turns logits into . Let . (a) Give at . (b) Give at . [number] (c) As , the distribution tends to: (a) the one-hot vector on the largest logit, (b) the uniform distribution, (c) the distribution at . [choice]
Answer
(a) , (b) , (c) (b), the uniform distribution.
- (a) , so and . A common mistake is , ignoring the logits.
- (b) At , , so : a temperature below 1 sharpens. A common mistake is to multiply by instead of dividing, giving and , which flattens.
- (c) As , every , every weight tends to , and . A common mistake is (a): the one-hot limit is , greedy decoding.
Problem 9. Derive, with a Lagrange multiplier for each constraint, that among distributions on with a fixed mean energy , the one with maximum entropy has the form with : a softmax of the logits at temperature . [proof]
Answer
Derivation. Maximize subject to and . With one multiplier per constraint, the Lagrangian is
Setting :
The factor is the same for every , so normalization fixes it: , giving . ( is then whatever value makes the mean energy equal .)
This stationary point is the maximum: is strictly concave on the simplex (its Hessian is , negative definite) and the constraints are linear, so the feasible set is convex and a stationary point of the Lagrangian is the unique global maximum. Every , so the boundary , where is not differentiable, plays no role.
With logits and , : softmax at temperature .
Rate-distortion
Section titled “Rate-distortion”Problem 10. A fair binary source () with Hamming distortion has the rate-distortion function bits per symbol for , where is the binary entropy. Give (a) and (b) . [number]
Answer
(a) , (b) 0 bits.
- (a) , so . Tolerating one flipped bit in eight saves more than half the rate. A common mistake is to report itself; another is , which is .
- (b) , so : at distortion the decoder can output anything (or a fixed guess) and be wrong half the time without receiving a single bit. A common mistake is 1.
Problem 11. A Gaussian source with variance and squared-error distortion has bits per sample for . (a) How many bits per sample are needed to reach ? (b) Each extra bit per sample divides the smallest achievable distortion by what factor? [number]
Answer
(a) 2 bits, (b) 4.
- (a) . A common mistake is 4, dropping the ; another is 16, the ratio itself.
- (b) Inverting, , so multiplies by . A common mistake is 2: one extra bit halves the error’s standard deviation , not the squared error. In decibels, a factor 4 is dB, the rule the quantizers of Quantization follow.
Common mistakes
Section titled “Common mistakes”The wrong answers in this set fall into recognizable patterns, each tied to the problem where it appears.
| Mistake | Symptom | How to avoid it |
|---|---|---|
| Listing code lengths in an order other than the probabilities’ | the right multiset, the wrong code | report each symbol’s merge count in the probabilities’ order (Problem 1(a)) |
| Reporting the entropy where the code length was asked | a non-integer-length code that no prefix code achieves | compute from the Huffman lengths (Problem 2(a)) |
| Rounding down for Shannon lengths | lengths that violate Kraft | use the ceiling (Problem 3(a)) |
| Trusting lengths without checking Kraft | a “prefix code” that cannot exist | compute the Kraft sum first (Problem 3(b)) |
| Mixing nats into a bits answer | mutual information off by | use throughout (Problem 5(a)) |
| Clipping PMI at zero when PMI was asked | PPMI, not PMI | keep the negative value (Problem 5(c)) |
| Confusing with | “knowing X tells everything about Y” when it does not | compute (Problems 5(a), 6(a)) |
| Multiplying logits by instead of dividing | a temperature that sharpens when it should flatten | use (Problem 8(b)) |
| Reading as greedy | the opposite limit | take the limit of , which is 0 (Problem 8(c)) |
| for , or dropping the in the Gaussian rate | bit budgets off by a factor 2 or worse | write out and in full (Problems 10, 11) |
Where this leads
Section titled “Where this leads”This set rests on Problem set A for entropy, KL, the chain rule, and Gibbs’ inequality, and on Perplexity, bits per byte, NLL accumulator, where bits per byte is a code length per byte. mutual_information and pmi_matrix in Mutual information, PMI, and PPMI are Problems 5 to 7 as code. Looking forward in AI Engineering, word2vec skip-gram with negative sampling, and the PPMI-SVD baseline builds PPMI word vectors from positive PMI only; the sampler of Sampling and logit processors divides logits by the temperature, with as greedy; and the quantizers of Quantization trade bits per weight for squared error, about a factor 4 per bit.
Further reading
Section titled “Further reading”- Cover and Thomas, Elements of Information Theory, sections 2.4 to 2.6, 5.1 to 5.8, 10.1 to 10.3, and 12.1.
- MacKay, Information Theory, Inference, and Learning Algorithms (free online), chapters 5 and 8.
- Jaynes, “Information theory and statistical mechanics” (1957).
Summary
Section titled “Summary”- The entropy is the best expected code length: a Huffman code reaches it exactly for dyadic probabilities and stays within one bit of it otherwise (Problems 1, 2), and every prefix code obeys Kraft’s inequality (Problems 3, 4).
- Mutual information is the expected PMI; it is symmetric, zero only for independent variables, and equals (Problems 5 to 7).
- Softmax at temperature is the maximum-entropy distribution with a fixed expected logit; flattens it to uniform and sharpens it to the argmax (Problems 8, 9).
- Rate-distortion gives the fewest bits per symbol for an allowed distortion; for a Gaussian, each extra bit divides the mean squared error by 4 (Problems 10, 11).