Information Theory for ML & LLMs (Entropy, Cross-Entropy & KL)
Play the 20-Questions bit game to FEEL Entropy, see why Cross-Entropy trains every LLM, decode Perplexity, and master Forward vs. Reverse KL in RLHF
An AI researcher says: 'Our new language model achieved Perplexity = 8 on test articles (down from 25!).' What does Perplexity = 8 actually mean in plain English?
- Feel Shannon Entropy H(P) concretely as 'the minimum average yes/no questions (bits) needed to guess a random outcome'.
- Understand Cross-Entropy = True Entropy + KL Divergence so you know EXACTLY what PyTorch CrossEntropyLoss is minimizing!
- Translate LLM Perplexity (e.g., PPL = 10) instantly into plain English ('as uncertain as a 10-sided die per word').
- Distinguish Forward KL (mean-seeking, pretraining) vs. Reverse KL (mode-seeking, RLHF/VAEs) and Mutual Information.
Forget dry telecommunications formulas — think of 20 Questions! Every yes/no question you ask (0 or 1) is literally 1 bit of information. If you want to transmit a message using as few yes/no questions as possible, give short codes to common outcomes and long codes to rare outcomes! That simple compression game turns out to be the exact mathematical engine behind every Deep Learning classifier and Large Language Model!
1. Surprise & Shannon Entropy — Play the Bit-Compression Game!
Suppose you live in sunny California where the weather is 50% Sunny, 25% Cloudy, 12.5% Rainy, 12.5% Snowy, and you text your friend today's weather using ONLY 0s and 1s.
- Naive code: Give all 4 weathers a 2-bit code (
00, 01, 10, 11) → always costs 2.00 bits/day. - Smart Shannon code: Give common Sunny a tiny 1-bit code (
0), Cloudy (10), Rainy (110), Snowy (111)! Now your average text length drops to !
Play with all 3 coding strategies live below — you will FEEL Entropy, Cross-Entropy, and KL Divergence in 10 seconds!
Entropy = The Irreducible Speed Limit of Compression
- Zero Uncertainty (): bits (why text your friend if it's Sunny 100% of days?!).
- Maximum Uncertainty (Uniform over outcomes): bits (a fair coin peaks at 1.0 bit!).
You text a friend today's weather using only 0s and 1s (yes/no questions!). Switch between the 3 coding strategies below and watch **Average Bits (= Cross-Entropy)** and **Wasted Bits (= KL Divergence)**!
Wastes 2 bits even on super-common Sunny days (50%)!
A 4-sided die is completely FAIR (each face has probability 1/4). What is its Shannon Entropy H(P) in bits? Compare it to the 1.75-bit skewed weather above!
2. Cross-Entropy = Entropy + KL (The Master Loss of AI!)
You just saw it live in the weather game: when you used a wrong model (the Backwards code!), you spent 2.625 bits/day instead of the 1.750 Entropy floor — wasting +0.875 extra bits! That total 2.625 IS Cross-Entropy, and that wasted +0.875 penalty IS KL Divergence!
Click every colored chip of the single most important equation in Deep Learning & LLMs below!
Why minimizing PyTorch CrossEntropyLoss automatically drives your model Q_θ straight onto truth P!
Average surprise of your model Q_θ on real data from P: −Σ P(x) log Q_θ(x). On one-hot labels, this simplifies to −log Q_θ(correct class)!
Pause & Check: Your LLM predicts probability 0.25 (1/4) for the true next word in a sentence. Using base-2 logs, what is the Cross-Entropy loss (in bits) and Perplexity on this single token?
3. Forward vs. Reverse KL (Pretraining vs. RLHF!) & Mutual Info
Careful: KL Divergence is NOT symmetric! Imagine trying to drape ONE small blanket (Q) over TWO sleeping dogs (P, bimodal). You have two totally different strategies:
- Forward KL
D_KL(P ‖ Q)(Mean-Seeking): Never leave ANY part of either dog uncovered — so you stretch the blanket wide across BOTH dogs (even covering the empty floor in between!). That's MLE / Pretraining! - Reverse KL
D_KL(Q ‖ P)(Mode-Seeking): Never put blanket on empty floor — so you tuck the blanket tightly around ONE dog cleanly! That's Variational Inference & RLHF (keeping an LLM crisp and coherent instead of generating weird half-blended gibberish!).
Bonus Superpower: Mutual Information
Remember in Chapter 6 how correlation completely missed ? Mutual Information measures the KL distance between the real joint world and a fake independent world : It catches EVERY nonlinear pattern ( if and only if and are truly independent!), powering Decision Tree Information Gain and CLIP Contrastive Learning!
A Decision Tree node is 50/50 Spam/Ham (H(Y) = 1.0 bit). Splitting on the word 'FREE' creates two equal child nodes with entropies 0.2 bits and 0.4 bits. Compute the Information Gain I(Y; Split)!
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because independent surprises MUST ADD! If two independent 1-in-2 events happen together, the combined chance is . Using −log₂: ! 1 − p does NOT add cleanly across independent events — logarithm is the unique smooth function that turns multiplication into addition!
Align Your Model Q to the True Distribution P to Zero Out KL Divergence
LLM Pretraining & Perplexity Benchmarks
Every frontier LLM trains on next-token Cross-Entropy and tracks validation Perplexity = exp(CE) as its north-star quality metric.
RLHF / DPO KL Anchor Penalty
Subtracting β · D_KL(π_θ ‖ π_ref) during post-training stops the model from reward-hacking into bizarre gibberish.
VAE Evidence Lower Bound (ELBO)
VAEs balance pixel reconstruction quality against D_KL(q(z|x) ‖ N(0, I)) so the latent space stays smooth and sampleable.
Decision Trees & CLIP InfoNCE
Trees greedily maximize Information Gain (Mutual Information), while CLIP maximizes a lower bound on Mutual Information between images and captions.
import numpy as np
P = np.array([0.7, 0.2, 0.1])
Q = np.array([0.4, 0.4, 0.2])
h_p = float(-np.sum(P * np.log2(P)))
ce = float(-np.sum(P * np.log2(Q)))
kl_fwd = float(np.sum(P * np.log2(P / Q)))
kl_rev = float(np.sum(Q * np.log2(Q / P)))
print(f"H(P)={h_p:.3f}b | CE={ce:.3f}b | H(P)+KL={h_p + kl_fwd:.3f}b")
print(f"Asymmetry: KL(P||Q)={kl_fwd:.3f}b != KL(Q||P)={kl_rev:.3f}b")
# LLM Perplexity from natural-log token probabilities
token_logprobs = np.array([-0.5, -1.2, -0.3, -2.0])
print(f"LLM Perplexity: {np.exp(-token_logprobs.mean()):.3f}")