Sub topic 13
Pitfalls: multilingual text, numbers, and train/inference mismatch
This chapter covers three failure areas that cause most real tokeniser bugs. It assumes you can read basic Python and know how BPE merges, WordPiece longest-match encoding, and SentencePiece's raw-text model work from the earlier chapters. None of these failures raises an error. The model just gets worse, slower, or more expensive.
Multilingual text
Why other languages cost more tokens
A subword vocabulary is learned from a training corpus. If most of that corpus is English, English words earn whole-word entries. A Greek, Thai, or Tamil word of the same meaning gets cut into short pieces, or into single characters.
The usual measure is fertility, the average number of tokens produced per word. Higher fertility has three effects:
- Fewer words fit in a fixed context window.
- Inference costs more, because cost is usually counted per token.
- The model must learn each word from longer, less regular sequences.
Byte-level BPE sets a floor on this problem. Its base symbols are UTF-8 bytes, and UTF-8 uses a different number of bytes per character depending on the script. You can see this without any tokeniser:
samples = {
"English": "The cat sat on the mat.",
"Greek": "Η γάτα κάθισε στο χαλί.",
"Japanese": "猫はマットの上に座った。",
}
for lang, text in samples.items():
chars = len(text)
nbytes = len(text.encode("utf-8"))
print(f"{lang:10} chars={chars:3} bytes={nbytes:3} bytes/char={nbytes / chars:.2f}")English is 1 byte per character. Greek letters take 2 bytes each, so this Greek sentence is about 1.8 bytes per character. Japanese characters take 3 bytes each. If a script has no learned merges, each character costs two or three tokens before any merging happens.
What controls coverage
Three settings decide how well a vocabulary serves a language:
- Training sample balance. Merges follow frequency. A language with 1% of the corpus rarely wins a merge against a language with 60%. Multilingual systems often rebalance by sampling each language in proportion to its share raised to a power below 1, which upsamples small languages.
- Vocabulary size. A larger vocabulary leaves room for entries from many scripts. The next chapter's topic, vocabulary size trade-offs, covers the cost side.
- Character coverage. SentencePiece's
character_coverageoption sets the fraction of training characters the model must represent directly. The documented defaults are 0.9995 for languages with large character sets such as Japanese and Chinese, and 1.0 for languages with small alphabets. Characters outside the coverage become the unknown token, unless you use byte fallback.
Word boundaries
Whitespace pre-tokenisation assumes words are separated by spaces. Chinese, Japanese, and Thai have no such spaces. A WordPiece tokeniser with a whitespace pre-tokeniser treats an entire sentence as one "word". Greedy longest match then runs over a long string, and a single unmatched position turns the whole sentence into [UNK]. SentencePiece avoids this because it never pre-splits on whitespace.
Numbers
Numbers are a pitfall because merges are driven by frequency. A year such as 2024 may appear often enough to become one token, while 2025 or 2031 may split differently. The model then sees no consistent relation between the digits and the value. Arithmetic, dates, and comparisons suffer. Some tokenisers also produce different splits depending on the digits that precede a number, so the same number can tokenise differently in two sentences.
There are two common fixes, and both work by changing pre-tokenisation:
- Split every digit. The number
1234567becomes seven tokens. This is consistent, but long numbers cost many tokens. Llama-family tokenisers use this approach. - Group digits in fixed chunks. Limiting a run to three digits keeps sequences shorter. Grouping from the left is inconsistent, because
1234567and234567would align differently. Grouping from the right matches how people write thousands separators.
import re
def pretokenize_default(text):
return re.findall(r"\d+|[A-Za-z]+|[^\sA-Za-z\d]+", text)
def pretokenize_digits(text):
return re.findall(r"\d|[A-Za-z]+|[^\sA-Za-z\d]+", text)
def group_right_to_left(number, size=3):
head = len(number) % size
parts = [number[:head]] if head else []
parts += [number[i:i + size] for i in range(head, len(number), size)]
return parts
print(pretokenize_default("Pay 1234567 now"))
print(pretokenize_digits("Pay 1234567 now"))
print(group_right_to_left("1234567"))The first call keeps 1234567 as one pre-token, and BPE then decides how to split it from frequency alone. The second call yields ['Pay', '1', '2', '3', '4', '5', '6', '7', 'now']. The third returns ['1', '234', '567'].
Decimals and units need a decision too. Is 3.14 three pre-tokens (3, ., 14) or one? Pick a rule, test it on dates, prices, and version strings such as v2.10.1, and keep it fixed.
Train/inference mismatch
The model learns from token ids. If inference produces different ids for the same text, the model receives input it never saw. The usual causes follow.
Normalisation differences
Unicode can write the same visible text in different ways. The character é may be one code point or e plus a combining accent. If training used NFC normalisation and inference does not, the two forms tokenise differently.
import unicodedata
def wordpiece_encode(word, vocab, unk="[UNK]"):
tokens = []
start = 0
while start < len(word):
end = len(word)
piece = None
while start < end:
candidate = word[start:end]
if start > 0:
candidate = "##" + candidate
if candidate in vocab:
piece = candidate
break
end -= 1
if piece is None:
return [unk]
tokens.append(piece)
start = end
return tokens
composed = "caf\u00e9"
decomposed = "cafe\u0301"
vocab = {"caf", "##\u00e9"}
print(composed == decomposed)
print(len(composed), len(decomposed))
print(wordpiece_encode(composed, vocab))
print(wordpiece_encode(decomposed, vocab))
print(wordpiece_encode(unicodedata.normalize("NFC", decomposed), vocab))The strings compare as unequal, with lengths 4 and 5. The composed form encodes to ['caf', '##é']. The decomposed form fails at ##e and returns ['[UNK]']. After NFC normalisation, the decomposed input encodes correctly. The fix is to run the same normalisation step at both stages.
Other sources of mismatch
| Mismatch | Symptom | Prevention |
|---|---|---|
| Different tokeniser file or version | Ids shift, and output is garbage or slightly degraded | Ship the tokeniser files with the model and pin the library version |
| Lowercasing at one stage only | Capitalised words become `[UNK]` or split heavily | Store the casing rule in the tokeniser configuration |
| Special tokens added or omitted | The model misses its start or separator markers | Use one encode function with fixed settings for training and serving |
| Leading-space handling | `"hello"` and `" hello"` get different ids in byte-level BPE | Test strings with and without surrounding whitespace |
| Text decoded then re-encoded | Spacing or accents change after a round trip | Check `decode(encode(text))` on real samples |
| Pre-tokeniser regex edited | Merges no longer line up with the learned vocabulary | Treat the regex as part of the trained artifact |
Special tokens in user text
If the tokeniser parses strings such as <|endoftext|> or [SEP] as control tokens, then user input containing that string can inject control markers. Decide whether special-token strings in raw text are parsed or treated as plain characters, and apply the same choice in training and serving. Most libraries have a flag for this, but its default differs between libraries.
A debugging checklist
The order matters. Version and normalisation checks cost minutes and are the most common cause, so run them before any retraining. Retraining is the most expensive fix and is needed only for coverage and number-splitting problems.
A useful habit is to keep a small regression set of 50 to 100 strings covering accents, emoji, long numbers, mixed scripts, and leading and trailing spaces. Save their expected token ids. Run the set whenever the tokeniser, its library, or the serving code changes. A single id difference then shows up as a failed test.
Exercise
A model was trained with text normalised to NFC. At serving time, users paste text from a source that uses decomposed accents, and the application passes it to the tokeniser unchanged. The WordPiece vocabulary contains ##é but not ##e followed by a combining accent. What happens, and what is the fix?
Show answer
Words containing a decomposed accent reach a position where no vocabulary entry matches, so the encoder returns the unknown token for the whole word. The model sees [UNK] instead of the word and performs worse. The fix is to apply the same NFC normalisation, using unicodedata.normalize("NFC", text), before tokenisation at serving time, exactly as in training.
Exercise
You compare two tokenisers on 1,000 words each of English and Thai. Tokeniser A produces 1,200 English tokens and 5,000 Thai tokens. Tokeniser B produces 1,300 English tokens and 2,600 Thai tokens. Compute fertility for each language and say which tokeniser you would choose for a product serving both languages equally, and why.
Show answer
Tokeniser A has fertility 1.2 for English and 5.0 for Thai. Tokeniser B has 1.3 for English and 2.6 for Thai. For an equal mix, A averages 3.1 tokens per word and B averages 1.95. B is the better choice, because its small English penalty (0.1 tokens per word) is far smaller than its Thai saving (2.4 tokens per word). It fits more Thai text in the context window and costs less per request.