When a language-model evaluator emits one mean loss per batch, averaging those means gives a one-token batch as much influence as a hundred-token batch. Averaging the batches’ perplexities is worse because exponentiation is nonlinear. Instead, recover each batch’s total negative log-likelihood, pool those totals, divide by the number of scored target tokens, and exponentiate once.
Run the fixture
Use Python 3.12 and its standard library. Save this as perplexity.py and run python3 perplexity.py without optimization so that the assertions run. The fixture supplies synthetic mean losses in natural-log units. No tokenizer or model is needed.
from math import exp, fsum, isclose, isfinite, log
def perplexity(batches):
counts, losses = [], []
for count, mean_nll in batches:
if type(count) is not int or count < 0:
raise ValueError("invalid token count")
if count == 0:
continue
if not isfinite(mean_nll) or mean_nll < 0:
raise ValueError("invalid mean loss")
counts.append(count)
losses.append(count * mean_nll)
if not counts:
raise ValueError("no scored tokens")
return exp(fsum(losses) / sum(counts))
rows = [(1, log(16)), (3, 0), (0, float("nan"))]
score = perplexity(rows)
assert isclose(score, 2)
assert isclose(perplexity([(4, log(2))]), score)
for bad in [[], [(0, 0)], [(-1, 0)], [(1, float("nan"))]]:
try:
perplexity(bad)
except ValueError:
pass
else:
raise AssertionError(bad)
print(f"perplexity={score:.3f}")Expected output
perplexity=2.000The first batch contributes one loss of ln(16). The other contributes three zero losses. The corpus mean is ln(16)/4, which is ln(2). The single-batch assertion represents those same four tokens as one aggregate and checks that regrouping does not change the result. The empty batch contributes no evidence, even though its mean is undefined. An entirely empty evaluation is an error, not a perplexity of one.
Connect it to an evaluator
The count must come from the same mask and target alignment as the reported mean. Do not count padding, ignored labels, context-only tokens in overlapping windows, or a position dropped by the model’s label shift. Check that the loss really is an unweighted per-target mean rather than a sum, an average of sequence means, or an objective with extra terms. Overlapping windows can supply context more than once without scoring the same target more than once.
If results shift when you only change aggregation batch size, log the exact scored-token count and summed loss per batch. If you also changed window placement, predictions themselves may have changed because the context changed. Compare models on the same text with a documented tokenization and context policy. For extremely large losses, report mean negative log-likelihood as well, since exponentiation can overflow.
References and related reading: Hugging Face’s perplexity and context-window documentation and Java Samples AI tutorials.