Chapter 17: Information Theory
Information theory answers two fundamental questions. What is the minimum number of bits needed to represent data? That is source coding. And what is the maximum rate at which data can be sent reliably over a noisy channel? That is channel coding. Both answers are given by entropy. Claude Shannon’s 1948 paper “A Mathematical Theory of Communication” posed and answered both, and in doing so connected probability theory to practical engineering: every compression and error-correction scheme in use today is bounded by his theorems.
Concepts from other sections (17)
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.
- Entropy: , the average surprise of a distribution. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- KL divergence: , the excess cost of predicting with ; nonnegative and asymmetric. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Perplexity: , the geometric mean of ; the effective number of choices per token. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- 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
- k3 estimator: with , an unbiased, nonnegative per-sample estimate of . 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
- PPMI: , a finite, sparse, non-negative matrix suitable for SVD. Read more: 17.3 Mutual information, PMI, and PPMI
- Context distribution smoothing: raising context counts to and renormalizing over contexts, which lowers PMI for rare contexts. Read more: 17.3 Mutual information, PMI, and PPMI
- Bayes’ rule: , which inverts a conditional using the base rate. Read more: 13.9 Probability problem set, part a: axioms, Bayes, random variables, Box-Muller
- Chain rule: . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Huffman coding: an optimal prefix code built greedily by repeatedly merging the two least frequent symbols or subtrees with a min-heap, so the rarest symbols get the longest codewords; it takes for symbols. Read more: Chapter 10: Greedy algorithms in Programming and Algorithms
- ELBO: the evidence lower bound, reconstruction likelihood minus KL to the prior, maximized to train a VAE. Read more: Chapter 2: Deep Learning in AI Engineering
- InfoNCE: a softmax cross-entropy that picks the matching item from a batch of candidates; CLIP applies it in both directions. Read more: 14.5 Contrastive image-text: CLIP and SigLIP in AI Engineering
- Representation learning: learning the features themselves, not just a decision rule over given features. Read more: Chapter 2: Deep Learning in AI Engineering
- Bloom filter: a bit array with hashes per key that never misses an inserted key and has a tunable false-positive rate. Read more: 12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences
For a book on mathematics for computing, the reason to study the subject now is more specific. Entropy, cross-entropy, and KL divergence are the language of machine learning. The training loss of a language model is a cross-entropy, its evaluation metric is a perplexity or a number of bits per byte, its sampler’s temperature is a maximum-entropy knob, and its post-training keeps a policy close to a reference with a KL penalty. This chapter builds those quantities from the idea of surprise and turns them into code that the training and evaluation loops in AI Engineering call.
The chapter moves from definitions to measurement to association. It opens with entropy, cross-entropy, KL, Jensen-Shannon, and the k3 estimator, with careful attention to zero conventions and numerical stability. It then turns per-token losses into perplexity and bits per byte, correctly, over batched and sharded evaluation. Next it builds mutual information and PMI, the count-based route to word vectors. Two problem sets close the chapter: the first fixes the core definitions and identities on paper, and the second covers coding and Huffman, mutual information, maximum entropy and temperature, and rate-distortion, the last two of which appear only there.
Learning objectives
- Define entropy, cross-entropy, KL divergence, and mutual information, and compute each by hand.
- Prove the chain rule for entropy, Gibbs’ inequality, and Kraft’s inequality.
- Implement entropy, KL, and the k3 estimator so they stay exact at zero probabilities and stable on log-probabilities.
- Report perplexity and bits per byte from batched evaluation that does not depend on batch size or order.
- Build PMI and PPMI matrices with context distribution smoothing.
- Explain softmax temperature as maximum entropy, and rate-distortion as the bits-for-error tradeoff behind quantization.
Before you begin
Section titled “Before you begin”You need discrete probability: distributions, expectation, conditioning, and Bayes’ rule, as covered in Probability and Statistics. The implementation sections use the stable log_softmax and compensated sums of Stable numerics: logsumexp, softmax, and compensated sums, the units of information from Exponents, logarithms, and units of information, and, for PPMI word vectors, the SVD of Linear Algebra.
In this chapter
Section titled “In this chapter”- Entropy, cross-entropy, KL, JS, and the k3 estimator builds the core quantities from surprise, proves that cross-entropy is the data’s entropy plus KL, and implements them with exact zero conventions and a sample-based KL estimator for post-training.
- Perplexity, bits per byte, NLL accumulator turns per-token losses into perplexity and tokenizer-independent bits per byte, with an accumulator whose answer does not depend on how the corpus is batched or sharded.
- Mutual information, PMI, and PPMI defines mutual information as a KL divergence and builds the smoothed PPMI matrix that is the count-based baseline for word2vec.
- Information theory problem set, part a works entropy, the chain rule, cross-entropy, KL, and k3 by hand, with two proofs.
- Information theory problem set, part b covers Huffman coding and Kraft’s inequality, mutual information, softmax as a maximum-entropy distribution, and rate-distortion.
The wider landscape
Section titled “The wider landscape”The sections above cover the parts of information theory the rest of the system calls. The subject is broader, and it helps to see the whole map once.
Entropy and information content. The information content of an outcome is bits: rare events carry more information. Shannon entropy is the average information per symbol; joint entropy extends it to pairs; and conditional entropy is the remaining uncertainty about given . Three theorems organize these. Maximum entropy: , with equality if and only if is uniform, because a uniform distribution is the one you cannot predict at all. The chain rule: , so joint entropy decomposes into conditional pieces. And conditioning reduces entropy: , since knowing something cannot make you more uncertain on average. As an example, a source emitting with probabilities has bits: on average each symbol carries 1.75 bits, and no lossless code can use fewer than 1.75 bits per symbol on average. Entropy shows up across machine learning as the cross-entropy loss, as information gain in decision-tree splitting, and in maximum-entropy models.
Source coding. The source coding theorem says the average length of an optimal uniquely decodable code satisfies , and Kraft’s inequality, , constrains the lengths of any such code. Huffman coding is the optimal prefix-free code for known symbol probabilities, built greedily; it is the classic example in Greedy algorithms in Programming and Algorithms. Arithmetic coding approaches the entropy more closely on long sequences by encoding the entire message as a single number in , and a trained language model can drive an arithmetic coder, which is why bits per byte is a compression rate. Lempel-Ziv (LZ77, LZ78) is dictionary-based and universal, adapting to the source’s statistics, and underlies gzip and PNG; zstd and JPEG rest on the same principles. Kolmogorov complexity connects these ideas to algorithmic information theory. Good exercises are to implement Huffman coding from scratch and compare compression ratios on English text against random bytes.
Mutual information and KL divergence. Mutual information is the information shared between and . KL divergence is a “distance” from to that is not symmetric, and cross-entropy is the expected number of bits when you use a code built for on data from . Gibbs’ inequality, with equality if and only if , says that using the wrong distribution always costs extra bits. The data processing inequality, for any function , says that processing data cannot create information. In machine learning, cross-entropy is the standard classification loss, KL divergence is the objective in variational inference (VAEs and the ELBO), and mutual information drives feature selection, contrastive learning (InfoNCE), and representation learning; Deep Learning and Statistical Learning in AI Engineering use these constantly.
Channel coding. A binary symmetric channel flips each bit with probability and has capacity . In general, channel capacity is , the maximum reliable transmission rate. Shannon’s noisy channel coding theorem, the central result of the field, says that for any rate there exist codes with arbitrarily low error probability: reliable communication is possible over a noisy channel, up to a calculable limit. Hamming codes are the simplest concrete example; the code adds 3 parity bits to 4 data bits and corrects any single error, and in general a code with minimum Hamming distance corrects errors. Their generator and parity-check matrices are linear algebra over GF(2). Reed-Solomon codes, built from polynomial evaluation over finite fields, protect CDs, QR codes, and deep-space links, and LDPC and turbo codes approach capacity with iterative decoding. These ideas appear in TCP checksums, ECC memory, RAID, and 5G NR, and the hash-based reasoning of Probabilistic structures such as Bloom filters is a close cousin. Good exercises are a Hamming encoder and decoder and a simulation of bit error rate over a binary symmetric channel.
Rate-distortion. When perfect reconstruction is not needed, the rate-distortion function gives the fewest bits per symbol at average distortion . It governs JPEG quality settings, video codec bitrate selection, and audio compression (MP3, AAC), and in machine learning it frames quantization and model compression (pruning, distillation). Problem set B works the binary and Gaussian cases.
Information-theoretic security. Perfect secrecy means : the ciphertext reveals nothing about the message. The one-time pad achieves it, and Shannon showed that any perfectly secret scheme needs a key at least as long as the message. Entropy also measures password strength and underlies randomness extraction and quantum key distribution.
For reference, the main formulas collected in one place:
| Concept | Key formula | Application |
|---|---|---|
| Entropy | measuring uncertainty, compression limits | |
| KL divergence | loss functions, variational inference | |
| Mutual information | feature selection, contrastive learning | |
| Channel capacity | communication system design limits | |
| Huffman coding | greedy prefix-free code | optimal symbol-by-symbol compression |
| Hamming distance | minimum codeword distance | corrects errors |
Key terms
Section titled “Key terms”- Joint entropy: , the uncertainty of a pair of random variables taken together; it is at most , with equality when they are independent.
- Conditional entropy: , the uncertainty that remains about once is known; conditioning never increases entropy on average, so .
- Chain rule for entropy: ; the joint entropy of a sequence is the sum of each symbol’s entropy given the ones before it, which is how an autoregressive language model’s loss adds up.
- Source coding theorem: the average length of an optimal uniquely decodable code satisfies , so entropy is the limit of lossless compression.
- 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.
- Arithmetic coding: a compression method that encodes a whole message as a single number in , narrowing the interval by each symbol’s probability; it approaches the entropy on long sequences, and driven by a language model it turns bits per byte into a compression rate.
- Lempel-Ziv compression (LZ77): a family of universal, dictionary-based compressors that replace repeated strings with references to earlier occurrences, adapting to the source without knowing its statistics; it underlies gzip and PNG.
- 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.
- Data processing inequality: for any function ; processing data, deterministically or randomly, cannot create information about the source.
- Channel capacity: , the highest rate in bits per channel use at which data can be sent reliably over a noisy channel.
- Binary symmetric channel: a channel that flips each transmitted bit independently with probability ; its capacity is , where is the binary entropy.
- Noisy-channel coding theorem: Shannon’s result that for any rate below the channel capacity there exist codes with arbitrarily small error probability, and above capacity there are none; it sets the limit every error-correcting code is measured against.
- Hamming distance: the number of positions in which two equal-length codewords differ; a code whose minimum distance is can correct errors.
- Hamming code: a linear error-correcting code over GF(2); the code adds 3 parity bits to 4 data bits and corrects any single-bit error, as in ECC memory.
- 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.
- Perfect secrecy: a cipher has it when , so the ciphertext reveals nothing about the message; the one-time pad achieves it, and Shannon showed it requires a key at least as long as the message.
Further reading
Section titled “Further reading”- A Student’s Guide to Coding and Information Theory: an accessible treatment with worked examples, a good first companion to this chapter.
- David MacKay, Information Theory, Inference, and Learning Algorithms, free online: deeper theory and close connections to machine learning.
- Thomas Cover and Joy Thomas, Elements of Information Theory: the standard graduate reference.
- Claude Shannon, “A Mathematical Theory of Communication” (1948): the original paper, still readable.