Self-Information, Log Bases, and Perplexity in Language Models
Machine LearningModel answerLast updated
Define the information content of a token, explain how the log base sets its unit, link it to cross-entropy and perplexity, and spot common mistakes when reading or comparing these numbers.
You are reviewing the evaluation of a language model with a colleague, and the conversation turns to surprisal, the information content of a predicted token. Answer the following.
- Definition. Give the formula for the surprisal of an event with probability (p). Explain why the logarithm is the natural choice, and say what surprisal means for a token inside a language model.
- Units. Surprisal comes in different units, much as length comes in meters or feet. What decides which unit you get? List the common units and show how to convert between them.
- Connections. How does surprisal relate to entropy, cross-entropy, the training loss, and perplexity? Include a short numeric example that moves between nats, bits and perplexity.
- Pitfalls. Which mistakes commonly occur when people compute, average, compare or interpret surprisal and perplexity values?
Aim for an answer that is short and exact, and include at least one worked number.
Hints
Hint 1
Start from the requirement that independent events should have additive information, and see what function of probability that forces.
Hint 2
The unit is purely a matter of which logarithm base you use. Work out how 1/8 looks in base 2 versus base e, then find the factor that converts between them.
Hint 3
Per-token average surprisal on a corpus estimates cross-entropy, and perplexity is that average exponentiated in the same base. Then think about what changes if two models split the same text into different numbers of tokens.
Hint 4
For pitfalls, consider base mismatches, tokenizer differences, how you average across sentences, subword versus word-level scores, padding/BOS/EOS handling, and zero probabilities.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Definition
For an event (x) with probability (p(x)), the surprisal (self-information) is
[ I(x) = -\log_b p(x) = \log_b \frac{1}{p(x)} ]
Why a logarithm:
- A certain event ((p=1)) carries zero information.
- Rarer events are more surprising: (I) grows as (p) shrinks and diverges as (p \to 0).
- It is non-negative for discrete probabilities.
- It is additive for independent events: (I(x,y) = I(x) + I(y)), because the log turns products of probabilities into sums. This additivity is the axiomatic reason the log is used.
In a language model, surprisal is conditional:
[ I(w_t) = -\log_b q(w_t \mid w_{<t}) ]
It depends on the token, the context and the model together. It is not a fixed property of the word.
2. Units
The log base sets the unit. The quantity is the same; only the scale changes.
| Base | Unit | Comment |
|---|---|---|
| 2 | bit (shannon) | Standard in coding and compression |
| (e) | nat | What deep-learning frameworks compute |
| 10 | hartley (ban) | Rare, mostly historical |
Conversions follow from (\log_b p = \ln p / \ln b):
- 1 nat ≈ 1.443 bits
- 1 bit ≈ 0.693 nats
- 1 hartley ≈ 3.322 bits
Example: (p = 1/8) gives 3 bits, equal to three fair coin flips, or (\ln 8 \approx 2.079) nats. In bits, surprisal is also the ideal code length: an arithmetic coder spends about 3 bits on that token.
3. Entropy, cross-entropy, loss, perplexity
- Entropy is expected surprisal under the true distribution: (H(p) = \mathbb{E}_p[-\log p(x)]).
- Cross-entropy is expected surprisal when data come from (p) but are scored by model (q): [ H(p,q) = H(p) + D_{KL}(p,|,q) \ge H(p) ] Minimizing it is the same as minimizing KL divergence and the same as maximum likelihood.
- Training loss / evaluation estimate. Since (p) is unknown, we average over (N) held-out tokens: [ \hat H = \frac1N \sum_t -\log q(w_t \mid w_{<t}) ] This is the mean negative log-likelihood, i.e. the mean per-token surprisal.
- Perplexity exponentiates it in the matching base: [ \mathrm{PPL} = b^{\hat H} = \Big(\prod_t q(w_t\mid w_{<t})\Big)^{-1/N} ] It has no unit ((2^{\text{bits}} = e^{\text{nats}})), it is the geometric mean of inverse probabilities, and it reads as an effective branching factor: PPL 20 means the model is as unsure as a uniform choice among 20 tokens.
Numeric example. A mean loss of 3.0 nats gives PPL (= e^{3} \approx 20.1). In bits, (3.0/\ln 2 \approx 4.33) bits per token, and (2^{4.33} \approx 20.1). Same model quality, two units, one perplexity.
import math
import torch.nn.functional as F
def surprisal_stats(logits, targets, ignore_index=-100):
logp = F.log_softmax(logits, dim=-1) # nats, numerically stable
mask = targets != ignore_index
nats = -logp[mask].gather(1, targets[mask].unsqueeze(1)).squeeze(1)
mean_nats = nats.mean().item()
return {
"surprisal_bits": (nats / math.log(2)).tolist(),
"cross_entropy_nats": mean_nats,
"bits_per_token": mean_nats / math.log(2),
"perplexity": math.exp(mean_nats),
}
Complexity is linear in the number of scored tokens, plus the softmax over the vocabulary at each position.
4. Common pitfalls
- Mixing bases. Framework losses are in nats, while papers often quote bits (bits per character or byte). A raw 2.0 in nats and 2.0 in bits differ by about 1.44x. Exponentiating with the wrong base gives the wrong perplexity.
- Comparing perplexity across tokenizers. Per-token numbers depend on how text is segmented. A larger vocabulary means fewer, harder tokens and a higher per-token surprisal for equally good prediction. Total surprisal over a text is comparable; per-token averages are not. Normalize per character, per word, or per UTF-8 byte (bits per byte).
- Averaging the wrong quantity. Corpus perplexity is (\exp) of the mean NLL over all tokens, not the mean of per-sentence perplexities. Because exp is convex the two differ, and the latter overweights short sentences.
- Word surprisal from subwords. By the chain rule, a word's surprisal is the sum of its subword surprisals, not the mean. Leading-space and end-of-word conventions also matter.
- Inconsistent token counting. Padding must be masked out. BOS is not a prediction and is excluded, while EOS is predicted and usually counted. Context length and stride in sliding-window evaluation also change the result, so report them.
- Zero probabilities. (p=0) means infinite surprisal, so one unseen event can make cross-entropy infinite. N-gram models need smoothing; softmax models avoid exact zeros, but always work with log-probabilities (log-softmax) rather than taking the log of a probability to avoid underflow.
- Treating surprisal as a property of the word. It changes with context and with the model, and a low value means the model found the token predictable, not that the token is common or semantically simple.
Summary
Surprisal is (-\log_b q(\text{token}\mid\text{context})). The base fixes the unit (bits, nats, hartleys). Its mean over a corpus is cross-entropy, which equals the training loss, and exponentiating that mean gives the unitless perplexity. Most reporting errors come from unit mismatches, tokenizer-dependent averaging and inconsistent token counting.