Every log-loss is a code length: the cross-entropy a model pays is the data's own entropy, which no model can remove, plus a KL divergence, which is the part training removes.
Fig. 1 draws that line over every bet a model could make on the root page's three words. The target is a soft one, sat 0.8 and dog 0.2 illustrative (section 3).
The same split holds for real models. GPT-2 and Qwen2.5-0.5B read the same 10,376-byte Darwin passage at 1.003 and 0.850 bits per byte (measured, section 6). Nobody knows the passage's floor, but it is the same for both models, so the whole 0.153 bits per byte between them is a difference in KL.
This one line (derived in section 3) is why minimising cross-entropy is maximum likelihood, why a language model's loss levels off above zero, and why the answer to "is 2.0 a good loss?" is "compared with what entropy?". The same few quantities explain why perplexity cannot be compared across tokenizers while bits per byte can, why maximum likelihood spreads probability while an RLHF-style KL penalty narrows it, and why contrastive losses such as CLIP's want huge batches.
You need: distributions, expectations and likelihood (Probability for ML); the tiny next-token model of the Topic: math root (scores for cat, dog, sat; softmax bet ; true word sat; loss nats).
| term | formula | what it is | example |
|---|---|---|---|
| surprise | bits to name one outcome you gave probability | sat at 0.090: 3.473 bits | |
| entropy | expected surprise; the shortest average code | the bet: 1.201 bits; weather: 1.5 | |
| cross-entropy | code built for , data from ; the training loss | weather, wrong forecast: 1.75 bits | |
| KL divergence | the extra bits; ; not symmetric | bits | |
| conditional entropy | what is left once is known; the loss floor | 0.722 bits | |
| mutual information | bits shared; KL from independence | signals agreeing 80%: 0.278 bits | |
| perplexity | the loss as a number of equally likely choices; tokenizer-dependent | GPT-2 on Darwin: 30.2 | |
| bits per byte | total bits / bytes | the loss as a compression rate; tokenizer-free | GPT-2 on Darwin: 1.003 |
| InfoNCE | -way softmax cross-entropy | , never above | CLIP's ceiling: 10.4 nats |
Running examples: the tiny model's bet; the weather (sun 1/2, cloud 1/4, rain 1/4, and a forecaster who swaps sun and cloud); a four-letter source A, B, C, D with probabilities 1/2, 1/4, 1/8, 1/8; real text, a 10,376-byte passage of Darwin's Origin of Species (chapter III, public domain) scored by four small open models and five compressors (Real text, measured). gives bits, gives nats, and 1 nat bits; is the average weighting each outcome by ; . Every number is recomputed by src/recompute.py.
The tiny model gave the true word "sat" probability 0.090, and the loss came out as 2.408. That number is a surprise (also called self-information): nats, or bits, as surprised as you would be by three and a half fair coins all landing heads.
A certain outcome surprises you not at all; and for two independent outcomes the probability multiplies, , while the surprise should add. Only turns products into sums (details below), and the base only sets the unit: base 2 gives bits, base gives nats, and 1 nat bits, 1 bit nats. PyTorch, JAX and NumPy use , so a loss printed during training is in nats: 2.0 nats is 2.885 bits, and its perplexity is , not . Per-token surprise is also the first thing to read in a loss spike: a token with loss 10 nats is one the model gave about , and a few of those can dominate a batch's average.
Shannon put the additivity requirement on the average (his third axiom: "if a choice be broken down into two successive choices, the original should be the weighted sum of the individual values of ") and proved that is the only form satisfying it, the constant "merely" choosing the unit (Shannon 1948, Theorem 2 and Appendix 2).
His example: choose among at once, or first between two halves and then, half the time, between and . The final probabilities agree (), so . In bits: left ; right . The is there because the second choice happens only half the time.
Each halving of the probability adds exactly one bit
| word | (model's bet) | nats | bits |
|---|---|---|---|
| cat | 0.665 | 0.408 | 0.588 |
| dog | 0.245 | 1.408 | 2.031 |
| sat (the truth) | 0.090 | 2.408 | 3.473 |
Surprise to scale (10 bits is the full width), and the tiny model's three surprises. The nats column goes up by exactly 1 per row because the scores drop by 1 each and .
Weather that is sun half the time and cloud or rain a quarter each surprises you by 1, 2 and 2 bits, so on average by bits. The tiny model's bet: bits (0.832 nats), below the 1.585 bits () of a uniform bet over three words. A coin that lands heads 90% of the time: bits; the rare tail is very surprising (3.32 bits) but rare.
Entropy is steep near certainty and flat near a fair coin
The binary entropy of a coin with heads probability : 0 at the ends, 1 bit at . Going from 99% to 95% certain adds more (0.081 to 0.286 bits) than going from 70% to 60% (0.881 to 0.971).
Fig. 2 lifts every bet over three words to its entropy.
Three readings of one number: the average surprise; the shortest possible average length of a message saying which outcome happened (section 2); and the spread of the distribution. for outcomes, 0 exactly when one outcome is certain and exactly when all are equally likely (because for the uniform , section 3). It depends only on the probabilities, not on the names or values of the outcomes, which is why it measures uncertainty and not the size of an error. Choosing a Gaussian or a softmax is choosing the maximum-entropy, least committal distribution that matches what you know (details below).
Among distributions on the real line with variance , the Gaussian has the largest (differential) entropy, , 1.419 nats at ; among distributions over classes with a given expected score, the softmax has the largest (Cover and Thomas, ch. 12).
For a density , the differential entropy is . It is not the limit of the discrete entropy (that limit is infinite: pinning a real number down exactly takes infinitely many bits), it can be negative (a Gaussian with has nats), and it changes if you rescale . Differences of differential entropies, such as KL divergences and mutual information, are finite, non-negative and unchanged by rescaling, which is why ML on continuous data works with them rather than with .
Huffman pays 0.134 bits per word for rounding to whole bits
Tell a friend the weather each day in 0s and 1s with sun = 0, cloud = 10, rain = 11. No codeword is the start of another (a prefix code), so 0100110 splits one way only: sun, cloud, sun, rain, sun. The average length is bits per day, exactly the entropy, because each codeword is exactly bits long.
Lengths are a budget. A codeword of length uses up a fraction of all bit strings, and a prefix code with lengths exists if and only if
(the Kraft inequality, MacKay, ITILA, §5.2). A 1-bit word spends half the budget, so short words can go to only a few outcomes, and they should go to the frequent ones. Read as the probability the code assumes: a code is a probability distribution in disguise, and a distribution is a code. The average length is then , the cross-entropy , and section 3 proves . So no prefix code beats the entropy on average, and it meets it exactly when . MacKay's equation 5.23: "the average length is ", which "exceeds the entropy by the relative entropy ". That equation is the bridge from codes to losses.
The ideal lengths for the bet are 0.588, 2.031 and 3.473 bits. Huffman's algorithm finds the best whole-number lengths: merge the two least likely items, repeat, then read the codewords off the branches.
Huffman's guarantee is (MacKay, Theorem 5.1, eq. 5.19). Coding longer blocks shrinks the "+1", and arithmetic coding removes it: it codes a whole message as one number and spends, in total, within two bits of the message's surprise (MacKay §6.2). So the length of a compressed file is the model's total surprise, to within two bits; section 7 animates it.
On real text: the Darwin passage uses 58 distinct byte values with an entropy, ignoring all context, of 4.269 bits per byte; a Huffman code on those counts spends 4.295, against 8 raw. Going lower needs context, which is a language model (section 7). The code-length reading is also why tokenizers are compressors (a BPE merge table shortens frequent strings, Tokenizers), and why minimum-description-length arguments treat a model plus its residual code as one message.
The cruder rule "round each ideal length up" (a Shannon code, lengths 1, 3, 4) gives 1.760 bits on the bet. Huffman on pairs of words (9 outcomes) costs 1.2145 bits per word, on triples 1.2107, on blocks of four 1.2094, closing in on 1.2009.
The theorem, in MacKay's words (§4.4): "N i.i.d. random variables each with entropy H(X) can be compressed into more than N H(X) bits with negligible risk of information loss, as N → ∞; conversely if they are compressed into fewer than N H(X) bits it is virtually certain that information will be lost." Shannon's original is Theorem 9 of the 1948 paper, stated for transmitting over a channel. Entropy limits the average, not every message, and reaching it needs long blocks or a method such as arithmetic coding that does not spend whole bits per symbol.
Sixteen symbols drawn from = (A 1/2, B 1/4, C 1/8, D 1/8), in exactly those proportions, go through two codes: the code built for (A 0, B 10, C 110, D 111) and a code built for a wrong guess = (A 1/8, B 1/2, C 1/4, D 1/8) (A 110, B 0, C 10, D 111). Predict before Fig. 3 plays: the wrong code is shorter on B, so does it lose overall, and by how much per symbol?
Frequencies from one distribution and code lengths from the other give the cross-entropy , 2.375 bits here. The difference from the entropy, 0.625 bits per symbol, is the Kullback-Leibler divergence (or relative entropy) . Every probability here is a power of one half, so the equality is exact.
The identity is one line: split and average under . The weather agrees: a forecaster who swaps sun and cloud builds cloud 0, sun 10, rain 11, and the real weather costs 1.75 bits a day, . The ratio is the likelihood ratio; the sum runs over outcomes with , and if for any of them the divergence is infinite.
With examples , use the empirical distribution (each example gets ) as and the model as . A one-hot target multiplies every term of by 0 except the true label, leaving the negative log-likelihood
Minimising it maximises : cross-entropy minimisation is maximum-likelihood estimation (the Probability page arrives at the same loss from the likelihood side), and because does not depend on , it is exactly minimising ; the loss can never go below the data's own entropy. For the tiny model with the one-hot target sat, and all 2.408 nats are KL. In nats, a correct-class probability of 0.7 costs 0.357 (0.515 bits), 0.99 costs 0.010, and 0.01 costs 4.61: the loss grows without bound, so a few confidently wrong examples can dominate a batch.
Soft targets (a teacher's probabilities, label smoothing) keep the full sum, and its minimum is , not 0. Say the data after "the cat" were sat 0.8, dog 0.2 illustrative: against the tiny model nats, of which is the target's own entropy and 1.707 is removable. Cross-entropy and KL have the same gradient in the model (they differ by ), "prediction minus target" on the scores (derived on the Calculus and optimisation for ML, section 2), but not the same value: report KL for "distance from the target", cross-entropy for "compressed length".
BCEWithLogitsLoss and CrossEntropyLoss take logits so they can compute the log of a softmax stably. Cross-entropy is also a proper scoring rule: its expected value is minimised only by reporting the true probabilities, which pushes a model towards calibration, not just correct rankings (Evaluation metrics). Cross-entropy among the other losses, with label smoothing and focal loss, is on Loss functions., with equality only when (Gibbs' inequality): on average you cannot beat the truth's own code. MacKay calls it "probably the most important inequality in this book" (§2.6, eq. 2.46); every "" on this page (entropy below , conditioning reduces entropy, mutual information is non-negative, data processing, the ELBO) comes from it. It is not symmetric: a fair coin against a model gives bits but ; the stream above gives 0.625 one way and 0.5 the other; the weather gives 0.25 both ways only because is with two outcomes swapped. With no symmetry and no triangle inequality it is not a metric, despite the name "KL distance" (MacKay: it "is not strictly a distance"). Section 4 shows the direction changes the answer. Try your own pairs in the Entropy and KL lab.
log_softmax directly as with the maximum subtracted (Numerical computing).Jensen: for a convex function (curving upwards, like ), ; the chord between two points of a bowl lies above the curve, and equality needs constant. The same proof as MacKay's solution to exercise 2.26:
Forward KL spreads over both humps; reverse KL picks one
A grid of 801 points from to 8; gradients by central differences on , step size 0.1, 200 steps; src/recompute.py gives the same end points.
The truth has two humps, ; the model is one Gaussian with mean and standard deviation . Both fits start at and run gradient descent, the top on the forward KL , the bottom on the reverse KL . Predict before it plays: which one ends up sitting in the valley between the humps?
Forward, , averages over the truth: wherever the data has mass and the model has almost none, is huge, so the model must put some probability everywhere the data goes, mode-covering (mean-seeking, zero-avoiding). The fit converges to , which is moment matching: the mean and variance of , . The price is 18.6% of its mass in the valley , where the truth has 0.6%; forward KL 0.555 nats, reverse 1.267.
Reverse, , averages over the model: mass the model puts where the truth has none is punished, and truth the model ignores costs nothing because it is never averaged over. So it picks one hump, mode-seeking (zero-forcing): , reverse KL 0.692 nats, almost exactly because on its hump (the hump holds half of ). Its forward KL is 10.23 nats: it ignores half the data. Started at it lands on the left hump; the reverse objective has a local minimum at each.
Sampling at temperature divides the scores by before the softmax, . On the tiny model, is the bet itself, 1.201 bits; sharpens it to (0.867, 0.117, 0.016), 0.636 bits; flattens it to (0.506, 0.307, 0.186), 1.472 bits. Predict before you drag: can any temperature push the entropy above 1.585 bits, or reorder the three words?
No: dividing by keeps the order of the scores, so the most likely word stays the most likely, and the entropy rises monotonically from 0 (as , all mass on the top score: greedy decoding) to (as , uniform). The rate has a closed form derived:
(write with and differentiate). At the variance of the scores under the bet is 0.424, so the entropy climbs 0.424 nats per unit of temperature there. Temperature is the one dial that sets how uncertain the sampler is without changing what it prefers; truncation samplers (top-k, top-p, min-p) change the support instead, and their effects on real next-token distributions are on Sampling and Decoding. In RL fine-tuning, the entropy of the policy's own next-token distribution is the quantity watched for entropy collapse (RL for LLMs).
Temperature only moves the entropy, between 0 (greedy) and log K (uniform), never the order
Scores ; the slider is logarithmic from to 10. The curve is the entropy of in bits against (log axis), with the dashed ceiling . "Effective choices" is , the perplexity of the sampling distribution itself: 2.30 words at .
A teacher's soft probabilities carry more bits than a one-hot label: the relative sizes of the wrong answers. Distillation trains the student on cross-entropy against the teacher's distribution at a raised temperature, which is the teacher's entropy (fixed) plus the forward KL from teacher to student (removable), exactly the split of section 3. Raising raises the teacher's entropy and so how much of that wrong-answer structure the target exposes. The gradient on the student's logits is , and at high temperature the difference itself shrinks like , so the soft term's gradients scale as and are multiplied back by (Hinton, Vinyals and Dean 2015, §2). On-policy distillation instead scores the student's own samples: MiniLLM minimises the reverse KL from student to teacher, with the mode-seeking behaviour of section 4, and GKD allows a family of divergences between the two. The recipes, the measured teacher-student runs and when each direction wins are on Distillation and Small Language Models.
GPT-2 (124M) read the 10,376-byte Darwin passage and paid a total of 7,212.5 nats (10,405 bits). That total is the size of the file it would compress the passage to (section 2). Divide the same total by different units:
Perplexity is the number of equally likely options that would be as confusing as the model: 1 is perfect, a uniform guess over tokens is , and the tiny model on sat is , worse than a uniform guess over its 3 words. But it divides the total surprise by the number of tokens before exponentiating, so a tokenizer with fewer, longer tokens raises it without the model knowing anything less. Bits per byte (BPB) divides by something no tokenizer can change: GPT-2 cuts the passage into 2,117 tokens, 4.901 bytes per token; 3.407 nats per token is 4.915 bits per token; so bits per byte, an eighth of the raw size.
One model, one text, one compressed length: "perplexity" from 2 to 907
| unit | count | nats per unit | "perplexity" |
|---|---|---|---|
| GPT-2 tokens | 2,117 | 3.407 | 30.2 |
| whitespace words | 1,777 | 4.059 | 57.9 |
| pairs of tokens (a coarser tokenizer, built exactly by the chain rule) | 1,059 | 6.811 | 907.5 |
| bytes | 10,376 | 0.695 | 2.00 |
Measured (src/data/score.py). The pair row is exact, not hypothetical: a tokenizer whose tokens are pairs of GPT-2 tokens gives each pair the product of the two conditional probabilities, so the total is unchanged and the count halves.
Three things the table shows. Across texts, perplexity misleads: GPT-2's perplexity on the C code is far lower than on Darwin, yet it compresses the code worse, because 979 of its 3,331 tokens there are pure whitespace at 1.14 nats each against 2.51 for the rest (Qwen2.5's tokenizer needs only 284 such tokens); cheap tokens dilute the per-token loss without shortening the file. Across tokenizers, perplexity understates or overstates: on the French passage Qwen2.5 uses 1,670 tokens where SmolLM2 uses 2,131, so its perplexity advantage (13.3 against 16.6, a ratio of 1.24) is smaller than its compression advantage (1.048 against 1.450 bits per byte, a ratio of 1.38). Within one tokenizer, perplexity is fine: GPT-2 against OPT-125m ranks the same way under both measures on all three texts, and the remaining differences between models are model differences (Qwen2.5 is 0.5B parameters, the others 124M to 135M), which bits per byte measures cleanly. The rule: perplexity only within one tokenizer and one evaluation set; bits per byte or per character, saying which, across tokenizers. Pretraining reports and scaling laws use bits per byte or nats per token within one tokenizer; per-token perplexity under three tokenizers, token by token, is drawn on Evaluation metrics.
Four models, three texts: perplexity against bits per byte
Four small open models on three public-domain texts, float32 on CPU, sliding window (src/data/score.py). GPT-2 and OPT-125m share one tokenizer (OPT's paper, §2.3: "the GPT-2 byte level BPE tokenizer"), so only their perplexities compare. On C code GPT-2 scores perplexity 8.2 yet 1.51 bits per byte, against 30.2 and 1.00 on Darwin. Token by token in Real text, measured.
Bits per character (BPC) divides by characters instead of bytes; it is the traditional unit on character-level benchmarks such as enwik8, the first bytes of the 3 March 2006 English Wikipedia dump (Large Text Compression Benchmark). For plain English the two nearly coincide: the Darwin passage has 10,371 characters and 10,376 bytes (an "æ" takes 2 bytes in UTF-8 and a curly apostrophe 3), so GPT-2's 1.0028 bits per byte is 1.0033 bits per character. In accented French they part: the Hugo passage is 5,773 characters but 5,953 bytes, and Qwen2.5's 1.048 bits per byte is bits per character.
Illustrative (from the old page): one 4,000-byte text; tokenizer A gives 1,000 tokens at 2.0 nats each, tokenizer B 1,250 tokens at 1.6 nats. Both total 2,000 nats. Perplexity: A , B , so B looks much better; bits per byte: both . Real ratio: the Pile paper prefers bits per byte "due to its invariance to different tokenization schemes" and measures 0.29335 GPT-2 tokens per byte over the Pile, so 2.0 nats per token there is bits per byte (Gao et al. 2020).
A language model predicts each token given the ones before it, and the chain rule of entropy (section 8) says the uncertainty of a whole text is exactly the sum of those conditional uncertainties:
That is the shape of the loss: the model pays at each position, and the per-token average over a long text estimates the entropy rate, the uncertainty per symbol once all the past is known. That rate is the floor of section 3; a loss that levels off is the KL shrinking towards a floor that is not zero. Context is worth a lot: Shannon measured, for a 26-letter alphabet, bits per letter with no context, with letter frequencies and with pairs, and from people guessing the next letter with 100 letters of context (27 symbols, counting the space) bounded the entropy between about 0.6 and 1.3 bits per letter, "of the order of one bit per letter" ("Prediction and Entropy of Printed English", 1951). Longer context lowers loss because it lowers the conditional entropy a model can reach.
Chinchilla's fit puts a number on the floor: in , the constant , which the paper calls "the entropy of natural text" (Hoffmann et al. 2022, §D.2), is fitted as 1.69 nats per token (2.44 bits; perplexity 5.4) on its own data and tokenizer; a refit of the same form by Besiroglu et al. (2024) gives 1.82 (2.63 bits). Both are extrapolations of a fitted curve to infinite model and data, not measurements, and both are per token under one tokenizer (Chinchilla page). Read the terms as this page's split: and are the KL that more parameters and more data remove; is the entropy, which nothing removes. The floor of a classifier is the same idea, : zero only when every input has exactly one correct label.
The final interval's width is the product of the probabilities, so its bits are the total surprise
Start with . For each symbol, split the current interval in proportion to the model's probabilities and keep the slice of the symbol that occurred; at the end, send just enough bits to name a number inside the final slice. Here the tiny model's bet, used as a fixed predictor, encodes "sat cat cat":
The 4.65 bits are , the three surprises added up; a real coder adds at most about two bits for the whole message (MacKay §6.2). A language model plugs in at each step instead of a fixed bet, and the decoder runs the same model to rebuild the same intervals. So a model's total loss on a text, in bits, is the size of the file it would compress that text to.
The models reach about 1 bit per byte or less; the best general-purpose compressor, brotli, needs 2.57, and brotli already ships a built-in dictionary of 122,784 bytes of common words and phrases (RFC 7932, Appendix A), a tiny frozen prior, the same idea as a pretrained model. Classical compressors learn only from the text in front of them, so they improve with length: on the whole 953,697-byte book bzip2 reaches 1.92 bits per byte and xz 2.09, still about twice what the models achieve on a 10 KB excerpt (Real text, measured plots it against length).
"Language Modeling Is Compression" (Delétang et al., ICLR 2024) feeds models' predictions to an arithmetic coder on 1 GB of text (enwik9), image patches (ImageNet) and audio (LibriSpeech), each in 2,048-byte chunks. Table 1, raw rates (compressed over raw size): Chinchilla 70B compresses enwik9 to 8.3% (0.66 bits per byte), against 32.3% for gzip on the whole file (2.58 bits per byte); on images and audio, which it was not trained on, it reaches 48.0% and 21.0%, against PNG's 58.5% (whole file) and FLAC's 30.3% (in chunks).
Four small language models need about 1 bit per byte or less; the best general compressor needs 2.57
Bits per byte on the 10,376-byte Darwin passage (lower is better). Compressors are real runs (src/data/comp.py: Apple gzip 487.0.1, bzip2 1.0.8, xz 5.8.2, zstd 1.5.7, brotli 1.1.0, each at its strongest setting); models are total loss in bits over bytes. Order-0 Huffman codes each byte on its own, with no context.
Counting the model. The decoder needs the model too. Delétang et al.'s "adjusted" rate adds the parameters to the compressed size: Chinchilla 70B's enwik9 rate becomes 14,008.3%, and their Figure 2 shows an optimal model size for each dataset size, past which a bigger model compresses worse once its own size is counted. Here, GPT-2's about 124 million parameters are roughly 250 MB in 16-bit floats, some 24,000 times the 10 KB passage it compresses so well derived. Prediction and compression are the same thing; whether a model is a practical compressor depends on how much data it is amortised over (see also Pretraining for loss curves against data).
Two fair binary signals and agree 80% of the time: , . Each alone has 1 bit. The pair has the joint entropy bits. Once is known, is 0.8 likely to match it, so what is left is the conditional entropy bits. The 0.278 bits that knowing saves is the mutual information.
The chain rule says the uncertainty of the pair is the uncertainty of one plus what is left of the other (section 7 applies it to a whole text), so also .
The shared 0.278 bits is counted once in the joint
The bits of the two signals to scale (the top two bars are 1 bit each on their own width; the bottom bar's full width is 1.722 bits).
Fig. 4 builds the same number from the table of the two signals.
The KL form says mutual information is how far the joint is from independence, , which is what Fig. 4 adds up cell by cell. Because it is a KL, , so conditioning never increases entropy on average, , with equality exactly at independence. A single value can still raise it (a usually reliable test coming back strange can make you less sure); only the average must fall. Mutual information is symmetric, , and, unlike correlation, unchanged by any invertible transform of either variable.
A message (a fair bit) is copied with a 10% chance of a flip to give , and copied again the same way to give . bits; differs from when exactly one flip happens, , so bits. Each copy loses information and none gains it. In general, for a Markov chain ( computed from alone, ):
MacKay: "data processing can only destroy information" (§8.3, exercise 8.9). The layers of a network form such a chain, so a hidden layer cannot carry more information about the label than the input does. Training does not add information; it makes the useful information easier to extract by a simple final layer, which Shannon information does not measure. The same quantity ranks features (information gain in trees is exactly mutual information, section 1), and the information bottleneck asks for a representation that keeps as little as possible about the input while keeping as much as possible about the label (Tishby, Pereira and Bialek 1999).
Read the tiny model as a contrastive scorer: cat is the positive (the candidate that truly goes with the anchor), dog and sat the negatives, scores 2, 1, 0. Picking the positive with a softmax costs nats, and that loss certifies nats of mutual information between anchor and positive. With sat as the positive the loss is 2.408 and the bound is negative: it certifies nothing.
The InfoNCE loss is an -way classification whose classes are the candidates in the batch (one positive, negatives, usually the other batch items), scored by a learned critic , often a scaled cosine similarity (van den Oord et al. 2018, §2.3; proved exactly by Poole et al. 2019, details below). A loss is never negative, so the bound can never exceed : with 4 candidates even a perfect critic certifies at most nats. Poole et al. (§2.3, with for ): " is upper bounded by , meaning that this bound will be loose when ". Predict before you choose a correlation: with a perfect critic and 16 candidates, what does InfoNCE report for a true 5.41 nats?
With weak dependence () every batch size gets close to the truth, from below. With strong dependence (5.41 nats) the estimate rides the ceiling until is in the hundreds: 2.73 nats at , 5.20 at 1,024. The ceiling is not a quirk of InfoNCE: McAllester and Stratos (2020) prove that "any distribution-free high-confidence lower bound on mutual information estimated from N samples cannot be larger than O(ln N)". CLIP trains with 32,768 image-text pairs per batch, so each direction is a 32,768-way classification with a ceiling of nats (15 bits) (Radford et al. 2021). Reading any reported "mutual information" estimate: check the batch size first; a value near is the ceiling talking. InfoNCE as a training method (SimCLR, MoCo, SimCSE, temperature, collapse) is on Contrastive and self-supervised learning; the CLIP page trains a toy one.
A small batch does not just add noise; it caps what the loss can certify
Two correlated Gaussians, , , whose mutual information is known, . The optimal critic ; for each , 2,048 anchors in batches of (two batches at ); seeded random numbers (mulberry32, seed 7) identical here and in src/recompute.py.
The CPC derivation used an approximation; Poole et al. 2019 (eq. 10 and footnote 2) prove the bound exactly and show the best critic is the log density ratio plus any function of alone (it cancels inside the softmax). CLIP's loss is symmetric (image to text and text to image), and its temperature, which divides the similarities before the softmax, is learned as a log-parameterised scalar initialised to 0.07 and clipped so the logits are never scaled by more than 100 (Radford et al. 2021, §2.3 and §2.5).
, positive scored 2.0, three negatives 0.0: the positive's probability is , the loss nats, and nats (1.51 bits).Take the tiny model as a policy: reference = (cat 0.665, dog 0.245, sat 0.090), reward 1 for sat and 0 otherwise illustrative. Fine-tuning with a reward model usually maximises reward minus a KL to the reference:
This is equation 3 of the DPO paper; InstructGPT puts the same term into the reward per sample as (Ouyang et al. 2022, eq. 2), whose average over is exactly . The ideal fine-tuned model is the reference reweighted by : small lets rewards dominate and concentrate the policy on the best response, large barely moves it, and nothing gets probability the reference does not give, because the KL is reverse (section 4). DPO runs the closed form backwards: solve it for the reward, (DPO eq. 5), substitute into a preference model where only reward differences matter, and cancels, leaving a loss on the policy alone (DPO page; the family is compared on Alignment: SFT, RLHF, DPO Family, RLVR and the RL algorithms on RL for LLMs).
What a KL budget guarantees: Pinsker's inequality, (KL in nats), bounds the total variation, the largest possible change in the probability of any event. So a KL penalty becomes a guarantee about behaviour: no event's probability can move by more than . On the tiny policy at , sat moved by 0.122, within .
The optimum reweights the reference by ereward/β; cat and dog keep their ratio at every β
Exact optimum on the tiny policy for each (src/recompute.py). At : , ; expected reward rises from 0.090 to 0.212 at a KL of 0.068 nats, and the objective equals .
The KL over all possible responses cannot be summed, so it is estimated from samples with . John Schulman's note ("Approximating KL Divergence", 7 March 2020) compares (unbiased, but negative for some samples, high variance), (always positive, low variance, biased) and (unbiased and always positive, because ). GRPO uses (DeepSeekMath, eq. 4); the DeepSeekMath page explains why differentiating inside the loss does not give the gradient of the KL it estimates.
For a latent-variable model with an encoder , the log-evidence splits into the evidence lower bound plus a reverse KL to the true posterior; since the KL is the first term is a lower bound, and raising it by changing lowers that KL by exactly the same amount (Kingma and Welling 2013, eq. 3, write it as a reconstruction term minus ). The Gaussian KL term in closed form (0.818 nats for ), VAEs and diffusion as a chain of KL terms are derived on Variational inference and generative-model maths.
Count which byte follows each context of bytes in the 10,376-byte Darwin passage, plug the frequencies into the formula, and the conditional entropy seems to fall to 0.18 bits per byte at , far below the 0.85 that a 0.5B-parameter language model achieves. Predict before you look: have the counts learned English better than the model?
No. With about ten thousand positions, most 7-byte contexts occur once, so the "next byte" is always certain in the sample. On the whole book the same estimate falls more slowly (0.81 bits at ) and would keep falling with longer contexts. Shannon's 1951 lower bound of about 0.6 bits per letter is the sanity check: a count-based estimate below it on a short sample is the estimator, not the text. The obvious estimator, count, divide by and compute (the plug-in or maximum-likelihood estimator), is biased downwards: outcomes not yet seen count as impossible, and the seen ones look more concentrated than they are. For possible outcomes and samples,
(Paninski 2003, eq. 4.6, completing Miller's 1955 result; valid when is large compared with .) The Miller-Madow correction adds back, with the number of outcomes actually seen; the same bias as a case of estimator bias and variance in general, with an exact table on the tiny model's three words, is section 2 of Statistics for ML.
Counting looks like it beats the models after a few bytes of context; it is memorising
Plug-in estimate of , the entropy of the next byte given the previous , counted on all of Origin of Species and on the passage alone, against two real models on the passage. Bytes, not Shannon's 27 letters, so the levels are not comparable with his.
Mutual information inherits the bias, with a twist. In the joint has many more cells () than the marginals, so it is underestimated the most, and the plug-in mutual information comes out too high, by about nats (the Miller-Madow terms combined; derived here, not quoted). Independent variables look dependent:
High dimensions: bounds instead of counts. For images, sentences or embeddings every sample is unique, so methods switch to variational bounds learned by a network, InfoNCE (section 9) and others that trade bias against variance (Poole et al. 2019: "the existing variational lower bounds degrade when the MI is large, exhibiting either high bias or high variance"), all under the limit of section 9.
At N = m samples the plug-in entropy is half a nat low; the correction helps but cannot invent unseen outcomes
A uniform distribution over 100 outcomes (true entropy nats), sampled times, 200 repetitions per , seeded (mulberry32, seed 11) identically here and in src/recompute.py. At the plug-in averages 4.04 nats, 0.56 below the truth (the formula predicts 0.50); at it is 1.54 below.
Pick any convex with . The f-divergence of from averages of the likelihood ratio under , , and Jensen gives every time (Nowozin, Cseke and Tomioka 2016 (f-GAN), eq. 2 and Table 1).
| name | weather from , nats | notes | |
|---|---|---|---|
| KL | 0.173 | 0.25 bits; section 3 | |
| reverse KL | 0.173 | equal here only because is with two outcomes swapped | |
| Pearson | 0.375 | blows up where is small | |
| squared Hellinger | 0.086 | symmetric; some books halve it | |
| total variation | 0.250 | ; symmetric, a true metric, at most 1 | |
| Jensen-Shannon | 0.042 | symmetric, at most |
Weather: = (0.5, 0.25, 0.25), = (0.25, 0.5, 0.25), recomputed in src/recompute.py from the generators. f-GAN's Table 1 defines Jensen-Shannon with the but lists the generator without it, which gives twice the value (0.085 here); the generator above includes the .
Jensen-Shannon, with , is how far each distribution is from their average. It is always finite, symmetric and at most nats (1 bit), reached when and do not overlap (, : ). The cap is also a weakness: once two distributions stop overlapping, JS stays at however far apart they move, so it gives no gradient telling them to come closer.
GANs. The original GAN objective at the best discriminator equals (Goodfellow et al. 2014, as restated in f-GAN's Table 1), so the generator minimises JS; f-GAN minimises any f-divergence through its variational lower bound (eq. 4), with the convex conjugate and the discriminator playing .
Near agreement they all look alike: , with the Fisher information (Schulman, "Approximating KL Divergence", 2020); for KL, . This is why trust regions measured in KL (TRPO, PPO's KL variants) behave like Fisher-weighted step limits, the connection the root's "Curvature is read three ways" box makes. Pinsker's inequality (section 10) on the weather: .
Go deeper: the Further reading tab lists the root page's tabs, the sibling pages, and the textbooks chapter by chapter.
Edit two distributions over the same outcomes: , the truth, and , the model or the code. Everything on the Reading tab's sections 1 to 4 and 12 is computed live: entropies, both cross-entropies, both KL divergences, their symmetric relatives, and the codes each distribution implies. The sliders set weights; each distribution is normalised to sum to 1.
Formulas: Reading sections 1 (entropy), 3 (cross-entropy and KL), 12 (Jensen-Shannon, total variation, , squared Hellinger), 2 (Huffman). All computed by the same functions that src/check_js.mjs checks against src/recompute.py.
Left: and per outcome. Right: each outcome's term of , . Single terms can be negative (where gives more than ); the sum never is.
Four small open language models and five general-purpose compressors on the same three public-domain texts. The question each view answers: does perplexity rank models the way their compression does? Reading section 6 explains the units; section 7 the compressors.
src/inputs/): Darwin, On the Origin of Species, chapter III, first 8 paragraphs (Project Gutenberg #1228; 10,376 bytes, 10,371 characters); Hugo, Les Misérables, tome 1, first 15 paragraphs (Project Gutenberg #17489; 5,953 bytes, 5,773 characters); SQLite src/util.c lines 1300 to 1560 (commit 4d577df of 24 September 2026; SQLite is in the public domain; 6,680 bytes). Paragraphs unwrapped to one line each; em-dashes replaced by two hyphens (a house rule of this knowledge base) before measuring.src/data/score.py).-9), bzip2 1.0.8 (-9), xz 5.8.2 (-9e), zstd 1.5.7 (-19), brotli 1.1.0 (-q 11), whole file in one call, headers included (src/data/comp.py).src/recompute.py asserts both): by construction.Compressors learn as they go; models arrive knowing
Bits per byte on the first 500, 1,000, 2,000, 4,000, 8,000 and all 10,376 bytes of the Darwin passage. For a compressor, each point is a separate run on that prefix (headers included, which is why the first points are high). For a model, it is the running total of its bits up to that byte, divided by the bytes. On the whole 953,697-byte book: .
Reading times for knowledge base pages are each page's own stated time where it gives one, otherwise estimated from the length of its Reading tab (about 230 words a minute). Times for outside resources are for the part recommended, checked on 5 October 2026. Every link opens in a new tab.
Edit two distributions; see both entropies, both cross-entropies, both KLs, Jensen-Shannon, total variation, and the Huffman codes each implies. 10 to 15 min of play.
Four small open models and five compressors on English, French and C: tokens, perplexity, bits per byte, the first 40 tokens as each model scored them. About 10 min.
The map of the topic and one prediction of a tiny next-token model through one training step; its section 3, "The same object in different hats", reads cross-entropy four ways. Note its letters: it writes the model as and the target as . 13 min, plus 4 in closed details.
Fourteen landmark equations decoded symbol by symbol, including the next-token log-likelihood, InfoNCE, the KL-regularised RLHF objective, the DPO loss and GRPO's per-token KL estimator. Open the root page and choose "Notation decoder". About 14 min for all fourteen cards.
Losses with analytic against numerical gradients, the log-sum-exp trick, the softmax cross-entropy gradient . On the root page, "Gradient lab". About 28 min.
Where cross-entropy comes from as a likelihood: a Bernoulli model gives binary cross-entropy, a categorical one softmax cross-entropy; MLE, MAP, Bayes. 32 min, plus 16 in closed details.
The ELBO of section 10 in depth: VAEs, the reparameterisation trick, diffusion as a chain of KL terms. 23 min, plus 18 in closed details.
Estimators, bias and variance, the bootstrap: the general version of section 11's estimator bias. 33 min, plus 6 in closed details.
Convexity and Jensen's inequality, Lagrange multipliers (the maximum-entropy derivations), Hessians and the Fisher information. 32 min, plus 11 in closed details.
Why log_softmax and log-sum-exp exist: the floating-point side of section 3's "zero probability" box. 40 min, plus 9 in closed details.
Deriving the cross-entropy gradient through a whole network. 32 min, plus 22 in closed details.
Vectors to SVD; the embeddings that contrastive losses compare. 45 min, plus 13 in closed details.
Cross-entropy among the other losses, with focal loss and label smoothing. 31 min, plus 5 in closed details.
Perplexity token by token under three tokenizers (real log-probabilities), and proper scoring rules. 27 min, plus 7 in closed details.
InfoNCE on a real batch, temperature, alignment and uniformity. About 31 min.
A trained toy CLIP and a live 8-pair batch with a temperature slider. About 27 min.
Where the KL penalty of section 10 sits in practice, and the DPO family compared. 33 min, plus 4 in closed details.
The full derivation from the closed-form optimum to the DPO loss, run on a toy. About 24 min.
KL-regularised policy optimisation in LLM training. 53 min, plus 13 in closed details.
GRPO's KL estimator and why differentiating it is not the KL gradient. About 25 min.
Entropy bonuses (SAC), trust regions measured in KL (TRPO, PPO). 45 min, plus 9 in closed details.
The fitted loss floor of section 7 and why the fit was redone. About 23 min.
Loss curves and what moves them. 30 min, plus 4 in closed details.
Why tokenizers differ in bytes per token, the root of section 6. 46 min, plus 15 in closed details.
Temperature and truncation change the entropy of the next-token distribution; real distributions to play with. 22 min, plus 4 in closed details.
Cross-entropy and KL against a teacher's soft probabilities. 25 min, plus 8 in closed details.
Entropy, cross-entropy, KL and mutual information drawn as codes. When: first, for pictures, before sections 2 to 8. 45 min to 1 h.
Ch. 2 (entropy, Gibbs' inequality, Jensen; §2.6, §2.7), ch. 4 (the source coding theorem, §4.4), ch. 5 (symbol codes, Kraft, Huffman, eq. 5.23 on the wrong code), ch. 6 (arithmetic coding), ch. 8 (mutual information, data processing), ch. 33 (variational methods and the KL direction). When: the backbone text for this page. 8 to 12 h for ch. 2, 4, 5, 6, 8; 2 h more for ch. 33.
The standard reference: ch. 2 (entropy, relative entropy, mutual information, data processing), ch. 5 (data compression, Huffman), ch. 12 (maximum entropy). When: for proofs and exact statements. Reference; about 6 h for ch. 2 and 5.
Part I: the three requirements and Theorem 2 (why ), Theorem 9 (the coding theorem). When: once sections 1 and 2 are comfortable. 1 h 30 min for Part I.
The first language model evaluation: humans predicting the next letter, entropy bounds with 100 letters of context. 40 min.
Models as arithmetic-coding compressors; raw against adjusted rates; read Table 1 rather than the abstract (section 7). 1 h.
InfoNCE and its bound (CPC §2.3), then the family of bounds and their bias-variance trade-off (Poole §2). 1 h 30 min together.
Why no estimator certifies much more than . 45 min for the introduction and main theorem.
The plug-in bias (eq. 4.6), Miller-Madow, and why no estimator is unbiased for all distributions. 1 h for sections 1 to 4.
The f-divergence family (eq. 2, Table 1) and the variational bound behind GAN training (eq. 4). 45 min.
The estimators of section 10. 15 min.
The two derivations of section 10 in their original form. 1 h together.