17.2 Perplexity, bits per byte, NLL accumulator
The tracer bigram reports one number, nll: the mean negative log-likelihood of one text, in nats per token. As soon as a language-model system grows past that first model, the number breaks in two ways.
Concepts from other sections (7)
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.
- Log-likelihood: , the log probability of the observed counts under a distribution . Read more: 13.3 MLE, Laplace, absolute discounting
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator
- Model zoo: the manifest-driven report that scores every model family in its own unit, one row per entry. Read more: 12.7 The evaluation harness and the model zoo in AI Engineering
- Byte-level: the base alphabet is the 256 bytes (through the byte map), so every text encodes and there is no unknown token. Read more: 7.2 Byte-level BPE in AI Engineering
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Pairwise summation: recursive halving of a sum, with error growing like . Read more: 15.2 Stable numerics: logsumexp, softmax, and compensated sums
- Bytes per token (): total UTF-8 bytes of the val texts over their tokens; converts loss per token into bits per byte. Read more: 5.7 Tokenize and pack to llm.c .bin in Data Engineering
First, tokenizers arrive: the byte tokenizer, byte-level BPE with 4096 merges, and the Unigram LM tokenizer in AI Engineering. A BPE model and a byte model scoring the same text report nats per their token, and a BPE token is three or four bytes, so their perplexities are not comparable. Tokenizer metrics and the tokenizer ablation in Capstone: TinyStories, owned end to end need a per-byte number. Second, evaluation stops fitting in one call: the The evaluation harness and the model zoo scores tokens in padded batches, possibly on several workers. Averaging batch means, counting padding, or letting float rounding drift all change the reported number while every individual line of code looks right.
This section turns per-token losses into perplexity and bits per byte, correctly, one batch at a time. It derives both metrics from the total NLL, shows why batched evaluation needs totals, masks and compensated sums, works every number by hand, and then walks through the reference implementation, ppl.py (contract: ppl.pyi). It uses bits_per_byte from Exponents, logarithms, and units of information, reads the mean NLL as the cross-entropy of Entropy, cross-entropy, KL, JS, and the k3 estimator, and runs the compensated sums of Stable numerics: logsumexp, softmax, and compensated sums as a stream.
Learning objectives
- Compute perplexity, bits per token and bits per byte from a total NLL, a token count and a byte count.
- Explain why bits per byte, not perplexity, compares models with different tokenizers.
- Explain why a corpus mean must come from totals, and why masks must select rather than multiply.
- Implement Neumaier’s compensated summation and explain how it makes any batch split give the same answer.
Notation
Section titled “Notation”These symbols are used throughout the section.
| Symbol | Meaning | Type / shape |
|---|---|---|
| the tokens of an evaluation text | int64[n] | |
| the probability the model gave the true token | float in | |
| that token’s negative log-likelihood, in nats | float | |
| the total NLL of the text, in nats | float | |
| the number of scored tokens | int | |
| the number of UTF-8 bytes the scored tokens cover | int | |
| the mean NLL per token (the cross-entropy) | float | |
| perplexity | float | |
| bits per byte | float | |
| , | a running sum and its compensation (the low bits it lost) | float64 |
From NLL to perplexity
Section titled “From NLL to perplexity”The model gives the text probability , each prediction conditioned on what came before. Its log is . The mean is the cross-entropy between the text and the model, in nats per token. Perplexity undoes the log:
the geometric mean of . If the model spreads its mass evenly over tokens every time, then , , and exactly: perplexity is the effective number of tokens the model is choosing between. A perfect model scores 1. A model that gives a real token probability 0 has and , the zero problem of MLE, Laplace, absolute discounting. In float64, overflows once . An untrained model can get there, so the function returns instead of raising.
The units follow from units of information: one bit is nats, so bits per token is , and .
Bits per byte: a tokenizer-free measure
Section titled “Bits per byte: a tokenizer-free measure”Perplexity is a per-token quantity, and that is exactly its weakness when tokenizers differ. Think of instead as the length, in nats, of the shortest code for the whole text under the model: an arithmetic coder driven by the model spends for each token. That total does not care how the text was cut into tokens; only the model’s skill at predicting it matters. Dividing by the number of tokens brings the tokenizer back in. Dividing by the number of bytes does not, because every tokenizer sees the same bytes:
A BPE model whose tokens average 4 bytes and a byte model can have per-token perplexities that differ by a factor of hundreds while their bits per byte say which one actually predicts the text better. That is why the model zoo reports bpb for every model.
One mean, many batches
Section titled “One mean, many batches”The definitions are simple; computing them over a large corpus is where errors creep in. The corpus mean is with and summed over every batch. The average of batch means, , weights each batch equally, so a short last batch or heavily padded batches pull it away from ; the two agree only when every batch has the same token count. So the accumulator keeps the two totals, never a running mean.
Padding brings a second trap. Padded batches have slots with no real token, whose loss is garbage: a loss against a pad id, , or NaN. A mask marks the slots that count. Multiplying by the mask looks equivalent and is not, because and . Selecting the masked values (x[mask]) never touches them. The token count is the number of selected slots, not the batch size.
Summing numbers
Section titled “Summing 10710^7107 numbers”The last trap is floating point itself. Adding a small number to a large float64 total rounds away its low bits: near 1.0 the spacing is , so exactly. Over tokens the lost bits add up to changes in the last digits of a reported perplexity, and, worse, the answer depends on batch size and order.
Two tools fix it. Within a batch, math.fsum returns the exactly rounded sum of the batch, after widening float32 losses to float64 (summing float32 values in float32 loses about seven digits). Across batches, Neumaier’s compensated summation keeps a second float . For each batch total ,
and the total is . When , is computed exactly, and is exactly the part of that dropped. This is the same idea as Kahan’s sum in Stable numerics, run as a stream. Merging adds another accumulator’s and then its , so shards scored on different workers combine without losing their low bits.
Working it by hand
Section titled “Working it by hand”Score the cat sat. as four BPE tokens with the model probabilities below. The text is 12 UTF-8 bytes.
| token | the | cat | sat | . | total |
|---|---|---|---|---|---|
| bytes | 3 | 4 | 4 | 1 | |
| 1/4 | 1/2 | 1/8 | 1/2 | ||
| nats |
The mean is nats per token, which is 1.75 bits per token. The perplexity is : the model is as unsure as a fair choice among about 3.4 tokens. Bits per byte is .
Now compare a byte model on the same text. Suppose a byte-level model spends 0.7 bits on each of the 12 bytes, 8.4 bits in all. Its perplexity per (byte) token is , which looks better than 3.36. Its bits per byte, 0.7, is worse than 0.5833. The BPE model predicts this text better, and only bpb says so.
Next, batching. Score the same four tokens as two batches, [the] and [ cat, sat, ., PAD] with mask [1, 1, 1, 0] and NaN in the pad slot. The batch means are and . Their average is , which is wrong. The totals give over tokens, or , the same as one batch.
Finally, compensation. Start at , and add ten times. With plain addition, rounds to 1 every time, so the total stays 1. With Neumaier, each step has and , so after ten steps and , the right answer.
These numbers are the first two test cases any implementation should pass.
Designing the interface
Section titled “Designing the interface”The module exposes one function and one accumulator class:
def perplexity(nll_sum: float, n_tokens: int) -> float # exp(nll_sum / n_tokens); inf on overflowclass NLLAccumulator: def __init__(self) -> None def add(self, nll: ArrayLike, mask: ArrayLike | None = None, n_bytes: int = 0) -> None def merge(self, other: "NLLAccumulator") -> None def result(self) -> dict[str, float] # {"nll_sum", "n_tokens", "n_bytes", "nll_mean", "ppl", "bits_per_token", "bpb"}result calls bits_per_byte from the units-of-information section for bpb; with no bytes added, bpb is NaN. A counted NaN or negative loss is a ValueError; a counted is allowed and makes ppl infinite.
Building it step by step
Section titled “Building it step by step”The design follows from six observations.
- Every reported number is a function of three totals. Mean NLL, perplexity, bits per token and bits per byte are all computed from , and . So the state of an evaluation is exactly those three numbers, and
result()derives everything else at the end. A running mean is not a valid state: it cannot be combined correctly with a batch of a different size. - Totals combine by addition, so batches and shards combine by addition.
addadds one batch’s contribution andmergeadds another accumulator’s. Any split of the corpus gives the same totals, which is the property that makes a number reported from batched or sharded evaluation trustworthy. - Only real tokens enter the totals. A mask decides which slots are real, and the safe way to apply it is selection,
x[keep], because the values in pad slots are arbitrary (NaN, ) and arithmetic with them, even times 0, can poison the sum. is then the number of selected entries. - The sum must not depend on how it was split. In floating point, addition is not associative, so step 2 holds exactly only if rounding is controlled. There are two levels:
math.fsummakes each batch’s total the correctly rounded exact sum, and Neumaier’s compensated addition carries the rounding error of adding batch totals into a second float. With both, the result matches one big exact sum to within a couple of ulps, whatever the split and order. - Bad input should fail where it enters, and is not bad input. A counted NaN or negative loss means a bug upstream (a loss computed against the wrong target, a sign error), so
addraises. A counted is a legitimate result: the model gave a real token probability 0. It must flow through toppl = inf, which means the compensated sum needs an infinity path, since in the compensation step would be NaN. - Perplexity is , computed so it cannot crash a report.
math.expraises on overflow; an untrained model’s mean can exceed 709.78 nats, so overflow returns .
Start with the free function:
def perplexity(nll_sum: float, n_tokens: int) -> float: if n_tokens < 1: raise ValueError( f"perplexity needs at least one token, got n_tokens = {n_tokens}" ) # NaN fails "nll_sum < 0" silently, so it needs its own test. if math.isnan(nll_sum) or nll_sum < 0: raise ValueError( f"nll_sum must be a non-negative number of nats, got {nll_sum!r}" ) try: return math.exp(nll_sum / n_tokens) # an infinite total gives exp(inf) = inf except OverflowError: # a mean above ln(DBL_MAX) = 709.78 nats return math.infThe accumulator’s state is the three totals of step 1, with split into a sum and its compensation:
class NLLAccumulator: def __init__(self) -> None: self._sum = 0.0 # Neumaier: the total is _sum + _comp self._comp = 0.0 self.n_tokens = 0 self.n_bytes = 0
def _accumulate(self, x: float) -> None: """Neumaier's compensated add of one float into the running total.""" # Once anything is infinite the total is infinite; skip the error term, # where inf - inf would produce nan. if math.isinf(x) or math.isinf(self._sum): self._sum += x return t = self._sum + x # Subtract the larger operand from t first: that difference is exact, # so the bracket is exactly the part of the smaller operand t lost. if abs(self._sum) >= abs(x): self._comp += (self._sum - t) + x # the low bits of x that t lost else: self._comp += (x - t) + self._sum self._sum = tThe branch on magnitudes is what distinguishes Neumaier from Kahan. Kahan’s version assumes the running sum is the larger operand, and loses the correction when a single batch total is larger than everything summed so far, for example the first big batch after a few tiny ones.
add validates, selects, and accumulates:
def add( self, nll: ArrayLike, mask: ArrayLike | None = None, n_bytes: int = 0 ) -> None: x = np.asarray(nll, dtype=np.float64) # widen float32 losses before summing if mask is None: keep = np.ones(x.shape, dtype=bool) else: keep = np.asarray(mask) if keep.shape != x.shape: # no broadcasting: a wrong mask is a bug raise ValueError( f"mask shape {keep.shape} differs from nll shape {x.shape}" ) keep = keep.astype(bool) # accepts 0/1 integer masks if n_bytes < 0: raise ValueError(f"n_bytes must be >= 0, got {n_bytes}") # Select, never multiply: padding may hold NaN, and NaN * 0 is NaN. vals = x[keep] # Validate only what is counted: garbage in pad slots is expected. if np.isnan(vals).any() or (vals < 0).any(): raise ValueError("a counted NLL is negative or NaN") self._accumulate(math.fsum(vals.tolist())) # exact within the batch self.n_tokens += int(vals.size) # real tokens, not slots self.n_bytes += int(n_bytes)Validation happens before any state changes, so a rejected batch leaves the accumulator exactly as it was.
merge and result complete the class:
def merge(self, other: NLLAccumulator) -> None: # Add the other side's sum and then its compensation: dropping # other._comp would throw away the low bits it carefully kept. self._accumulate(other._sum) self._accumulate(other._comp) self.n_tokens += other.n_tokens self.n_bytes += other.n_bytes # other is read, never modified
def result(self) -> dict[str, float]: if self.n_tokens == 0: raise ValueError("no tokens were counted") # The compensation is meaningless next to an infinite sum (and could be nan). total = self._sum + self._comp if math.isfinite(self._sum) else self._sum mean = total / self.n_tokens return { "nll_sum": float(total), "n_tokens": float(self.n_tokens), "n_bytes": float(self.n_bytes), "nll_mean": float(mean), "ppl": perplexity(total, self.n_tokens), "bits_per_token": float(mean / math.log(2.0)), # Same total, divided by bytes: M00.1's S / (B ln 2). No bytes: NaN, not 0. "bpb": bits_per_byte(total, self.n_bytes) if self.n_bytes > 0 else math.nan, }The full solution is ppl.py.
Why this design
Section titled “Why this design”add is for a batch of slots: one selection, one validation pass, and fsum, which is linear with a small constant (Shewchuk’s partials list stays short for same-sign values). The state is four numbers, so merge is , and sharded evaluation costs nothing extra to combine.
Using both fsum and Neumaier is deliberate. fsum alone across the whole corpus would require holding every loss, or every partial, for the whole run. Neumaier alone inside a batch would work but is a Python loop over elements. Exact per batch plus compensated across batches gets near-exact totals with constant state. np.sum is not enough: NumPy uses pairwise summation, which is good (error ulps) but still depends on the batch shape, so the same corpus split differently gives different last digits. The goal here is a number that does not depend on batching.
A running mean with the update is numerically fine, but it cannot be merged across shards without also carrying , at which point it is the totals again, with extra rounding. And raising on NaN, rather than skipping it, matters because skipping would silently report a perplexity over fewer tokens than the caller thinks were scored. Raising puts the bug next to its cause.
One tradeoff is accepted: vals.tolist() copies the batch into Python floats for fsum, which is slower than a vectorized sum. Evaluation is dominated by the model’s forward pass, so exactness wins.
What can go wrong
Section titled “What can go wrong”A correct implementation must reproduce the hand-worked sentence (, 1.75 bits per token, , bpb 0.5833) and give the one-batch numbers from two batches with a NaN pad, because the mean of means is wrong. A uniform model over choices must have perplexity , up to . Perplexity must return for 800 nats per token and for an infinite total, which is what untrained models in the zoo produce, and perplexity must reject zero tokens and a negative or NaN total, which usually signal sign bugs upstream.
Masked positions may hold anything, NaN, or negative values, and 0/1 integer masks must work, because the zoo’s padded batches depend on it. Bad batches must fail loudly: a mismatched mask shape, a counted NaN or negative loss, or negative bytes are rejected, while a counted is allowed. Empty totals behave distinctly: no tokens raises, and no bytes gives NaN bpb, so a results table shows “missing” rather than “perfect”.
The streaming properties are the heart of the design. Random splits added in reverse order must match one batch to , so the number does not depend on batch size. must come out within 2 ulps, guarding against drift over tokens. float32 losses must sum to within , because losses arrive as float32. Merged shards must equal one accumulator, low bits included, with other unchanged; this is what sharded evaluation in Platform workflows: TrainRun and EvalSuite in Systems Engineering relies on. Bits per byte must rank tokenizers correctly: the byte model has lower perplexity and higher bpb. And three long golden cases are checked against totals computed to 50 digits, independent of float64 rounding.
The mistakes that break these checks are few and recognizable:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| averaging batch means | the reported loss changes with the batch size and the last batch’s length | stores totals , , and divides only in result() |
| multiplying by the mask | NaN in a pad slot turns the total into NaN; pad slots are counted as tokens | selects with x[keep] and counts vals.size |
| plain float64 addition across batches | -sized contributions vanish into a large total; the result depends on order | Neumaier’s compensated add in _accumulate |
| summing float32 losses in float32 | seven digits of a -token batch lost | np.asarray(nll, dtype=np.float64), then math.fsum |
math.exp of a huge mean | OverflowError in the middle of a zoo report | perplexity catches OverflowError and returns math.inf |
| bits per byte divided by tokens, or left in nats | a bpb that is really bits per token, or off by | passes the nats total and the byte count to bits_per_byte |
| a merge that drops the other side’s compensation or bytes | sharded and single runs disagree in the last digits, or bpb is wrong after merging | merge accumulates other._sum and other._comp and adds both counts |
| accepting a counted NaN, or reporting on zero tokens | NaN or a ZeroDivisionError reaches the report | add validates the selected values; result raises on zero tokens |
Warning: Averaging batch means is the bug that survives code review, because every line looks right. If a reported loss changes when you change the batch size, look here first.
Where this leads
Section titled “Where this leads”This section draws on three earlier ones: bits_per_byte from Exponents, logarithms, and units of information converts the nats total to bits per byte; Entropy, cross-entropy, KL, JS, and the k3 estimator explains why the mean NLL is the cross-entropy of the text under the model; and Stable numerics supplies Kahan’s compensated sum, here run as a stream across batches.
In AI Engineering, the accumulator is used everywhere a model is scored. Tokenizer metrics report bytes per token and the bpb of a reference model per tokenizer. The Kneser-Ney n-gram model, Bengio’s neural probabilistic language model and the RNN language model each report validation perplexity and bpb through an accumulator. The model zoo scores every family with one accumulator per model and prints bpb. Quantization is allowed a fixed bpb increase, and the TinyStories capstone reports its training curve and ablations in bpb.
Three production systems are worth reading alongside this code. The EleutherAI lm-evaluation-harness (lm_eval/api/metrics.py) provides bits_per_byte, byte_perplexity and word_perplexity aggregations over documents, weighted by length. llama.cpp’s perplexity tool (tools/perplexity/perplexity.cpp) uses strided windows that score only the second half of each context, so every token has enough history. CPython’s math.fsum (Modules/mathmodule.c, math_fsum) implements Shewchuk’s exact partial sums, correctly rounded whatever the order.
Further reading
Section titled “Further reading”- Cover and Thomas, Elements of Information Theory (2nd ed.), chapters 2 and 5.
- Gao et al., “The Pile” (2020), section 4 (bits per byte).
- Higham, Accuracy and Stability of Numerical Algorithms, chapter 4.
Key terms
Section titled “Key terms”- Negative log-likelihood (NLL): , the surprise of the true token under the model, in nats.
- Perplexity: , the geometric mean of ; the effective number of choices per token.
- Bits per byte (bpb): , total information divided by the UTF-8 length; comparable across tokenizers.
- Compensated summation: keeping a second float that accumulates the rounding error of each addition (Kahan, Neumaier).
- Mask selection: choosing counted entries with
x[mask]instead of multiplying by the mask.
Summary
Section titled “Summary”- Perplexity is to the mean NLL per token: the geometric mean of , so a model that is uniform over choices scores exactly .
- Bits per byte divides the same total by the text’s UTF-8 length instead of its token count, which makes it the one number that compares models with different tokenizers.
- A corpus mean is the total over all tokens divided by the token count, never the average of batch means, and padding is selected out, not multiplied by zero.
- Summing each batch exactly and carrying the rounding error across batches makes any split of the corpus give the same answer to float64 rounding.
- A counted is a legitimate result and flows through to infinite perplexity; a counted NaN or negative loss is a bug and raises.
Review questions
Section titled “Review questions”- Two batches have means 2 and 1 nats with 1 and 3 tokens. What is the corpus mean, and what does the mean of means report?
Answer
The corpus mean is $(2 \cdot 1 + 1 \cdot 3)/4 = 1.25$ nats. The mean of means is $(2 + 1)/2 = 1.5$, because it gives the one-token batch the same weight as the three-token batch. Only totals give the right answer, which is why the accumulator stores $S$ and $n$. - Why does
addselect withx[keep]instead of computing(x * keep).sum()andkeep.sum()?Answer
Pad slots can hold NaN or $\infty$, and $\mathrm{NaN} \cdot 0$ and $\infty \cdot 0$ are both NaN, so one pad slot would make the total NaN. Selection never reads those values into arithmetic. It also makes the validation apply only to counted slots. - Why does
_accumulatetake a separate path when either operand is infinite?Answer
With $x = \infty$, $t = \infty$ and the correction $(x - t) + s$ is $\infty - \infty = \mathrm{NaN}$, which would then turn the reported total into NaN. An infinite total is a legitimate result (a counted token with probability 0), so the code just adds and skips the error term; `result` likewise ignores the compensation when the sum is infinite. - A byte model and a BPE model report per-token perplexities 1.62 and 3.36 on the same text. Which predicts the text better, and how does the accumulator tell?
Answer
Per-token perplexity cannot tell, because the tokens are different sizes. The accumulator also tracks $B$, the UTF-8 bytes covered, and reports $\mathrm{bpb} = S/(B \ln 2)$. In the worked example the BPE model has 0.583 bpb and the byte model 0.7, so the BPE model is better. - What goes wrong if
mergeadds onlyother._sum?Answer
The other shard's compensation holds the low bits its own additions lost. Dropping it makes a sharded run differ from a single run in the last digits, which is exactly the batch-dependence the design exists to remove.