Sub topic 3
Normalisation and pre-tokenisation before subword splitting
This chapter assumes you know basic Python, what a token is as a language model's input unit, and how BPE learns merges from word counts (covered in the earlier chapters). It covers the two stages that run before a subword model sees any text. These stages decide what the model can learn.
Where the two stages sit
A tokeniser is a pipeline. The subword algorithm (BPE, WordPiece, or unigram) is only one stage in it.
- Normalisation rewrites the string into a canonical form. It maps different spellings of the same text to one spelling.
- Pre-tokenisation cuts the normalised string into word-like chunks. The subword model then runs on each chunk separately.
- Post-processing adds special tokens such as
[CLS]. A later chapter covers it.
Both early stages are fixed rules. They are not learned. Because they run before training and before every encoding call, an error in either one spreads into the whole vocabulary.
Normalisation
Unicode lets one visible character have several code point sequences. The letter "é" can be one code point (U+00E9) or two (e followed by U+0301, a combining accent). They render the same, but they compare as different strings.
import unicodedata
a = "caf\u00e9" # precomposed é
b = "cafe\u0301" # e + combining acute accent
print(a == b, len(a), len(b)) # False 4 5
print(unicodedata.normalize("NFC", b) == a) # TrueIf the tokeniser does not normalise, these two strings get different token ids. The model would treat the same word as two unrelated words.
Unicode defines four normalisation forms:
| Form | What it does | Example effect |
|---|---|---|
| NFC | Decompose, then recompose into precomposed characters | `e` + U+0301 becomes `é` |
| NFD | Decompose into base character plus combining marks | `é` becomes `e` + U+0301 |
| NFKC | Like NFC, plus "compatibility" mappings | `fi` becomes `fi`, fullwidth `H` becomes `H` |
| NFKD | Like NFD, plus compatibility mappings | Same mappings as NFKC, left decomposed |
The "K" forms merge characters that look different but mean the same thing. This shrinks the vocabulary. It also discards information, for example the difference between ² and 2.
Common normalisation steps
Tokenisers combine a few of these steps:
- Unicode normalisation (NFC or NFKC are the usual choices).
- Lowercasing. This is used by "uncased" models.
- Accent stripping. Apply NFD, drop the combining marks (Unicode category
Mn), then recompose. - Whitespace cleanup. Collapse runs of spaces, tabs, and newlines, and remove control characters.
import re
import unicodedata
def normalise(text, lowercase=True, strip_accents=True):
text = unicodedata.normalize("NFKC", text)
if lowercase:
text = text.lower()
if strip_accents:
decomposed = unicodedata.normalize("NFD", text)
text = "".join(c for c in decomposed if unicodedata.category(c) != "Mn")
text = unicodedata.normalize("NFC", text)
return re.sub(r"\s+", " ", text).strip()
print(normalise("Cafe\u0301 fine Déjà vu")) # cafe fine deja vuThe input contains a fullwidth C, a decomposed é, a ligature fi, accented letters, and a double space. All of these are mapped to plain forms.
Normalisation is lossy
Once you lowercase and strip accents, you cannot recover the original. résumé and resume collapse into one string, and so do US and us. For a retrieval model that is fine, and it may even help. For named-entity recognition or for generating text, losing case is a real cost. This is why modern generative models usually skip lowercasing and accent stripping. They keep case and rely on a large vocabulary instead.
Pre-tokenisation
A subword algorithm needs a unit to work on. For BPE training, the unit is a word: the trainer counts words, represents each as a sequence of symbols, and merges pairs inside words. Pre-tokenisation decides what counts as a word.
The simplest rule is to split on whitespace. It has a flaw. Punctuation stays attached to words, so dog., dog,, and dog! become three different words.
import re
from collections import Counter
text = normalise("The dog. The dog, the dog!")
by_space = Counter(text.split())
by_regex = Counter(re.findall(r"\w+|[^\w\s]", text))
print(dict(by_space)) # {'the': 3, 'dog.': 1, 'dog,': 1, 'dog!': 1}
print(dict(by_regex)) # {'the': 3, 'dog': 3, '.': 1, ',': 1, '!': 1}With whitespace splitting, the count for dog is spread over three entries. With the regex, dog has a count of 3, and each punctuation mark becomes its own unit. The BPE trainer receives these counts as its input, so better counts mean better merges.
Pre-tokenisation sets a hard boundary
BPE and WordPiece never merge across pre-token boundaries. If the pre-tokeniser separates dog from ., then no learned token can ever contain both. This has three consequences:
- Merges stay linguistically sensible. You will not get a token that is half of one word and half of the next.
- Training is faster. Pair counting runs over a small set of unique words with frequencies, not over the whole corpus as one long string.
- Phrases are never single tokens. A pre-tokeniser that splits on spaces rules out a token like
of the, however frequent it is.
A GPT-2 style splitter
GPT-2 uses a regular expression that keeps the leading space attached to the following word. The space is then part of the word, so " world" and "world" are different pre-tokens. That makes the original text recoverable, because the spaces are kept.
import re
PATTERN = re.compile(r" ?[^\W\d_]+| ?\d+| ?[^\s\w]+|\s+(?!\S)|\s+")
def pretokenise(text):
return PATTERN.findall(text)
print(pretokenise("Hello, world 42!")) # ['Hello', ',', ' world', ' 42', '!']
print(pretokenise("a b")) # ['a', ' ', ' b']The alternatives in the pattern match, in order: a run of letters, a run of digits, a run of other symbols (each with an optional leading space), and then whitespace. The \s+(?!\S) alternative leaves one space for the next word, so "a b" becomes 'a', ' ', ' b'. The original GPT-2 pattern uses the third-party regex module so it can write \p{L} and \p{N} for any-language letters and numbers. The version above uses the standard re module and approximates this.
Digits and other special cases
A pre-tokeniser can force choices that the subword model would not make on its own:
- Digits. Some tokenisers split every digit into its own pre-token (
2024becomes2,0,2,4). This gives the model a consistent view of numbers. Others keep digit runs whole, and BPE then learns tokens like202that depend on how often they appeared. - CJK characters. Chinese, Japanese, and Korean text has no spaces between words. BERT's pre-tokeniser puts spaces around each CJK character, so every character becomes its own pre-token.
- Contractions. The GPT-2 regex has a special case for
's,'t,'re, and similar. The simplified pattern above does not, soDon'tsplits intoDon,',t.
What SentencePiece does differently
SentencePiece tries to avoid language-specific pre-tokenisation. It takes raw text, applies its own normalisation, and replaces each space with the visible marker ▁ (U+2581). The space then becomes an ordinary character in the sequence, so the model can learn pieces such as ▁the. Decoding is the reverse: join the pieces and turn ▁ back into a space.
Two details matter in practice:
- The default normalisation rule is
nmt_nfkc, a variant of NFKC. You can choose another rule, or none, with thenormalization_rule_nametraining option. - By default SentencePiece still keeps pieces from crossing whitespace boundaries (
split_by_whitespace=True). So it does apply a minimal split. What it avoids is language-specific rules about punctuation or word shape. Setting that option to false allows pieces that span several words.
The later SentencePiece chapter works through this in code.
Common errors
- Different normalisation at training and inference. The tokeniser trained on lowercase text is applied to cased text, or the reverse. Always save and load the whole pipeline, not only the vocabulary file.
- Forgetting that normalisation changes length. NFKC can turn one character into several (
fibecomesfi) and a lowercase step can change the length of some characters. Character offsets in the normalised string no longer match the original. Tools that need spans, such as named-entity recognition, must track an offset mapping. - Expecting a perfect round trip. After lowercasing, accent stripping, or whitespace collapsing, decoding cannot restore the original text.
- Pre-tokenising differently for training and encoding. If the trainer split on whitespace but the encoder uses a regex, the encoder produces words the vocabulary never saw, and you get more unknown tokens or odd splits.
- Treating every Unicode form as equal. Text from different sources (web pages, PDFs, keyboards on different systems) often mixes NFC and NFD. Normalise before counting.
Summary of the design choices
| Choice | Effect on the vocabulary | Cost |
|---|---|---|
| Lowercase and strip accents | Smaller vocabulary, fewer rare words | Loses case and accent information |
| NFKC instead of NFC | Merges look-alike characters | Loses distinctions such as `²` versus `2` |
| Whitespace-only pre-tokenisation | Simple and language-independent | Punctuation fused to words, diluted counts |
| Regex pre-tokenisation | Clean word and punctuation units | Language-specific rules to maintain |
| Split digits individually | Consistent number handling | Longer sequences for numbers |
Exercise
A BPE trainer is fed a corpus pre-tokenised only by whitespace. The corpus often contains the words "model." and "model," with punctuation attached. Name two problems this causes, and one change to the pipeline that fixes them.
Show answer
First, the counts for "model" are split across "model.", "model,", and "model", so each entry has a lower frequency and merges for the word are learned less reliably. Second, the vocabulary can fill with variants that carry punctuation, such as pieces ending in "." or ",", which waste vocabulary slots. The fix is a pre-tokeniser that separates punctuation from letters, for example the regex \w+|[^\w\s], and using the same pre-tokeniser at training and inference.
Exercise
The strings "caf\u00e9" and "cafe\u0301" look identical but a tokeniser gives them different ids. Which normalisation form fixes this, and what does it do to the second string?
Show answer
NFC (NFKC also works). It recomposes "e" followed by the combining acute accent U+0301 into the single code point U+00E9, so both strings become the same four-character string.