← Math
Math

Log-probabilities and information theory

The dashboard says the new keyboard model is better. Is it?

Measure how much surprise a model assigns to the words people actually type.

Outcome

Measure a model in bits and perplexity, compare two models on the same words, and use entropy, cross-entropy and KL to see how far a model is from real typing.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Surprise Also information
−log₂ p bits: how unexpected an outcome of probability p is.
Cross-entropy
The average surprise, in bits, of a model on what actually happened.
Perplexity
2 raised to the cross-entropy: the number of equally likely choices that would be as surprising.
Entropy
The average surprise of the true distribution itself, the part no model can remove.
KL divergence
Cross-entropy minus entropy: the extra bits paid for predicting with q when the truth is p; not symmetric.

Why this matters

Many language models are trained and compared on log-probabilities: how surprised it is by what actually comes next. Those numbers decide which model ships. Working in logs is not a convenience; it is the only way the per-word numbers add up correctly, and it exposes how one confident mistake can outweigh many good guesses. Multiplying hundreds of probabilities first can round the product to zero even when no individual probability is zero.

This lesson assumes logarithms, averages and probability.

What log-probability measures

The surprise of an observed word is −log₂ p, where p is the probability the model assigned to it. A word the model gave probability 1/2 costs 1 bit of surprise; 1/8 costs 3 bits; 1/1,000 costs about 10. Surprise adds along a sentence because probabilities multiply.

Averaging that surprise gives bits per predicted word. Entropy describes the average surprise of a distribution under itself; cross-entropy uses another model’s probabilities for those outcomes. Their difference, KL divergence, measures the extra average surprise from that model. The evaluation must specify which outcomes and distribution supply the weights.

01Surprise is −log p

Surprise is −log p

A phone keyboard ships its next-word model on the device, and a new model replaces the current one only if it predicts what people type at least 10% better. A dashboard compared the average probability each model gave to the words people actually typed and recommended the candidate. On the release gate it failed.

First verify the dashboard’s scoring on a six-position control trace. The current keyboard model gave those typed words 0.20, 0.05, 0.40, 0.10, 0.25 and 0.02: an average of 3.1553 bits per word.

Math.log2(0) is -Infinity and 2 ** Infinity is Infinity, so one zero probability flows through to an infinite perplexity without an error.

02Perplexity

Perplexity

2^3.1553 = 8.909: on these words the model is as unsure as if it chose among about nine equally likely words each time. For candidate probabilities 0.25, 0.08, 0.45, 0.12, 0.30 and 0.03, the same trace scores 6.845, 23.2% lower, which clears a 10% gate. Perplexities are comparable only on the same words with the same vocabulary. To compare safely, let Δ = candidate bits − current bits. Since PPL = 2^bits, the relative change is (2^Δ − 1) × 100. Compute it as expm1(Δ ln 2) × 100; expm1 evaluates exp(x) − 1 accurately near zero without subtracting two enormous perplexities. Identical bit scores give Δ = 0 and change 0%, even if neither displayed perplexity fits in binary64.

03Average the logs, not the probabilities

Average the logs, not the probabilities

The control trace passes, but that does not explain the failed release comparison. Reduce the averaging discrepancy to two typed positions so every bit gained or lost is visible. Predict which model each line favours.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Probabilities each model gave the two words a user actually typed.
const current = [0.5, 0.02];
const candidate = [0.9, 0.01];

const mean = (ps: number[]) => ps.reduce((sum, p) => sum + p, 0) / ps.length;
const perplexity = (ps: number[]) =>
  2 ** (-ps.reduce((sum, p) => sum + Math.log2(p), 0) / ps.length);

console.log(mean(current).toFixed(3), mean(candidate).toFixed(3)); // the dashboard's comparison
console.log(perplexity(current).toFixed(2), perplexity(candidate).toFixed(2)); // lower is better

The candidate is very sure about one word and nearly rules out the other. Against the current model, its 0.01 costs one extra bit (6.64 against 5.64), while its 0.9 saves only 0.85 bits (0.15 against 1). Perplexity adds those up; the average probability does not.

04One impossible word

One impossible word

If a model gives a typed word probability 0, its surprise is infinite, and so are its cross-entropy and perplexity. That is the right answer: the model claimed something could not happen and it did. A mathematical softmax over finite logits assigns positive probabilities, but finite precision or truncation can still produce zeros. A zero in this evaluation is reported, rather than silently skipped or replaced with an arbitrary small probability. A positive representable probability can also have a finite bit score but a perplexity too large for binary64. For 1e−310 the score is about 1029.7977 bits and the represented perplexity is inf; actual probability zero instead reports inf bits as well. G requires positive current-model probabilities. It computes its decision from finite bit differences: two identical 1e−310 models have inf inf 0.0000 ship at gate 0. A candidate with actual zero always reports infinite change and hold. If the computed positive percentage change itself overflows, its representation is inf and the decision is hold.

The supplied formatter prints finite magnitudes below 10²¹ in fixed notation with four fractional digits, rounding the exact represented binary64 value with halfway ties to even (for example, 0.03125 becomes 0.0312 and 0.09375 becomes 0.0938), and magnitudes at least 10²¹ in scientific notation with four fractional digits and an explicit unpadded exponent sign (for example 1.0000e+300). It prints inf only for positive infinity, and normalizes formatted −0.0000 to 0.0000. NaN or negative infinity is an invalid-result diagnostic, never an inf substitute. Log sums start at zero in input order; mean bits, separate logarithms and expm1 use binary64 operations. G compares the unformatted computed change inclusively with the negative gate; K compares the computed KL inclusively with its limit. Equal distributions with exact zero KL pass a zero limit. Native logarithm and exponential libraries can differ in their last bits, so a displayed rounded value cannot establish an exact mathematical boundary decision.

05Entropy, cross-entropy and KL

Entropy, cross-entropy and KL

After “see you” people type tomorrow, later and soon with frequencies 0.5, 0.25, 0.15 and others 0.10. Some uncertainty is unavoidable: the entropy of those frequencies is 1.7427 bits. A model that predicts 0.45, 0.30, 0.15, 0.10 costs 1.7530 bits, its cross-entropy. Compute H(p) = −Σ p log₂p and H(p,q) = −Σ p log₂q, weighting by what users actually type. Subtracting gives Σ p log₂(p/q) = 0.0102 bits, the directed KL divergence. Zero-frequency words contribute no term; a positive-frequency word assigned zero by the model has infinite cost. These are dimensionless bits per predicted word, not an accuracy percentage. For positive terms, compute log₂p − log₂q directly rather than forming p/q. With p = 1 and q = 1e−310 the ratio overflows, but both logs and their difference are finite, about 1029.7977 bits. Keep the separate p = 0 and q = 0 rules. The lab accepts 1..10,000 parsed binary64 probabilities per list; positive probabilities must remain positive when parsed. Distribution inputs use the working binary64 representation, so a tiny term alongside 1 may round away when summed.

Two models against real typing after “see you”
Model predictionCross-entropyKL
0.45, 0.30, 0.15, 0.101.75300.0102
0.10, 0.20, 0.30, 0.402.63420.8914
The model gives 0 to a word people do type. What is the KL divergence?

06Gate the keyboard model

Gate the keyboard model

Repair the dashboard’s per-position score before trusting its release gate. Then measure relative perplexity change on paired evaluation positions. The final audit compares an entire conditional prediction with observed typing frequencies, including words the model rules out.

A keyboard model release

Bits and perplexity, the model-swap gate, then drift from real typing.

  1. easy · M-LOGPROB-V4-1 Bits and perplexity
  2. medium · M-LOGPROB-V4-2 The model-swap gate
  3. hard · M-LOGPROB-V4-3 Drift from real typing
In the frontend A model-comparison panel in Next.js and Svelte Optional

An internal dashboard can take the log-probabilities an evaluation job wrote, compute perplexity from them, and compute change from the difference in mean negative log-probabilities. These snippets receive natural-log values, so their expm1 argument is a difference in nats; the lab’s bit scores require the ln2 factor. Their infinity display can mean representational overflow or an actual impossible word, as explained above.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// An internal model-comparison panel: perplexity from log-probabilities, never from averaged probabilities.
type Evaluation = { name: string; logprobs: number[] }; // natural-log probabilities of the typed words

const surprise = (logprobs: number[]) =>
  -logprobs.reduce((sum, lp) => sum + lp, 0) / logprobs.length;
const display = (value: number, digits = 2) =>
  value === Infinity
    ? "∞"
    : !Number.isFinite(value)
      ? "invalid"
      : Math.abs(value) >= 1e21
        ? value.toExponential(digits)
        : value.toFixed(digits);

export function ModelPanel({
  current,
  candidate,
  gate
}: {
  current: Evaluation;
  candidate: Evaluation;
  gate: number;
}) {
  const [oldNats, newNats] = [surprise(current.logprobs), surprise(candidate.logprobs)];
  const [a, b] = [Math.exp(oldNats), Math.exp(newNats)];
  const change = newNats === Infinity ? Infinity : Math.expm1(newNats - oldNats) * 100;

  return (
    <p>
      {current.name} {display(a)} → {candidate.name} {display(b)} ({display(change, 1)}
      %): {change <= -gate ? "ready to ship" : "hold"}
    </p>
  );
}

Check this idea later
A model has perplexity 4 on a test set. What does that mean?
Is KL(p ‖ q) the same as KL(q ‖ p)?
Sources

Values above were computed at 60 digits and run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The keyboard models and frequencies are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.