Convert language model loss to bits per byte

Why it matters Bits per byte is how tokenizer-independent comparisons of language models are usually reported.

Per-token loss cannot be compared across models with different tokenizers. Bits per byte normalises by the raw text size instead.

Write bits_per_byte(total_nll, n_tokens, n_bytes). total_nll is the summed negative log-likelihood in nats over a text with n_tokens tokens and n_bytes UTF-8 bytes. Return a dict with "bpb" = total_nll / (n_bytes * ln 2), "token_loss" = total_nll / n_tokens and "token_ppl" = exp(token_loss).

Signaturedef bits_per_byte(total_nll, n_tokens, n_bytes)

Example

bits_per_byte(693.1471805599453, 500, 1000) is {"bpb": 1.0, "token_loss": 1.3863, "token_ppl": 4.0} (token_loss is ln 4).

Understand the idea

A model with a big vocabulary uses fewer tokens per sentence, so each token carries more information and its per-token loss looks worse, even if the model is just as good. Bits per byte asks a tokenizer-free question: how many bits does the model need, on average, to encode each byte of text? It is like comparing cars by fuel per kilometre instead of fuel per trip.

Example: a 1000-byte text, total loss 693.15 nats. In bits that is 693.15 / ln 2 = 1000 bits, so 1.0 bit per byte. If the text was 500 tokens, the token loss is 1.386 nats (ln 4) and perplexity 4.

Rule: bpb = total_nll / (n_bytes * ln 2); token_loss = total_nll / n_tokens; ppl = e^token_loss.

The same total NLL gives the same bpb whatever the tokenizer, which is why compression-style evaluations of LLMs report bits per byte.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplebits_per_byte(693.1471805599453, 500, 1000)
  • Sample 2: coarser tokenizerbits_per_byte(1200.0, 250, 1000)
  • Test 3: finer tokenizerbits_per_byte(1200.0, 600, 1000)