Measure tokenizer compression and fertility on a text sample

Why it matters Tokenizer fertility explains why the same text costs very different numbers of tokens in different languages, which matters for low-resource languages.

Before picking a tokenizer for a new language, measure how many tokens it needs. Fewer tokens per word means cheaper training, cheaper inference and more text per context window.

Write tokenizer_stats(texts, tokenize). texts is a list of strings; tokenize(word) returns the list of tokens for one word. Split each text on whitespace into words, tokenize every word, and return a dict:
- "chars_per_token": total characters of all words / total tokens
- "fertility": total tokens / total words
- "split_rate": fraction of words that became more than one token
Round each value to 4 decimals. If there are no words, return all zeros.

Signaturedef tokenizer_stats(texts, tokenize)

Example

with tokenize splitting a word into chunks of 3 characters, tokenizer_stats(["a cat", "elephant"], tokenize) is {"chars_per_token": 2.4, "fertility": 1.6667, "split_rate": 0.3333}.

Understand the idea

A tokenizer trained mostly on English often chops words from other languages into many small pieces. Then the same sentence costs more tokens, so it is slower, more expensive and fits less into the context window. Fertility is a quick health check, like measuring how many coins a vending machine needs for the same price.

Example: words "a", "cat" and "elephant" with a toy tokenizer that cuts every 3 characters. "a" and "cat" stay one token each; "elephant" becomes "ele", "pha", "nt". Totals: 12 characters, 5 tokens, 3 words. Chars per token = 12 / 5 = 2.4, fertility = 5 / 3 = 1.67, and 1 of 3 words was split.

Rule: chars_per_token = chars / tokens; fertility = tokens / words; split_rate = words with more than 1 token / words.

Teams extending an LLM to a new language compare these numbers before and after adding tokens to the vocabulary.

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

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

  • Sample 1: exampletokenizer_stats(['a cat', 'elephant'], chunk3)
  • Sample 2: long wordstokenizer_stats(['internationalization is long'], chunk3)
  • Test 3: char leveltokenizer_stats(['ab c'], list)
  • Test 4: emptytokenizer_stats([' '], chunk3)