Training Tokenizers: Algorithms and Corpus
Summary
Training a tokenizer involves building a dictionary of tokens from a text corpus using statistical algorithms (BPE, WordPiece, Unigram), which determines the granularity of tokenization and the final efficiency of the model.
Why Train a Tokenizer Separately
A tokenizer is not part of the model weights: its dictionary is fixed before training and does not change thereafter. The quality of the dictionary affects:
- average sequence length in tokens for the same text;
- proportion of rare words split into subwords;
- robustness to typos, word forms, and language mixing;
- final inference cost, as it is counted by tokens.
Dictionary Construction Algorithms
| Algorithm | Principle | Application |
|---|---|---|
| BPE | Iterative merging of the most frequent character pairs | GPT, Llama, most LLMs |
| WordPiece | Merging based on maximum likelihood in the corpus | BERT and encoder models |
| Unigram | Removing the least probable subwords from an overabundant dictionary | T5, SentencePiece |
| Byte-level BPE | Operating at the byte level, without OOV | GPT-2 and descendants |
The byte-level variant eliminates the problem of unknown characters: any input can be represented as a sequence of bytes, which is critical for multilingual and multimodal models.
Corpus Preparation
Order of operations:
- Unicode normalization (usually NFKC).
- Removal of control characters and broken encoding.
- Optional language and document length filtering.
- Deduplication at the line and document level.
- Balancing languages and domains.
Corpus imbalance directly translates into the dictionary: a language with less text representation gets more subwords per word and is more expensive in tokens.
Dictionary Size
Dictionary size is a compromise:
- small dictionary (16–32k) — short embeddings, but long sequences;
- large dictionary (100–256k) — compact sequences, but bloated embedding matrix and softmax.
from tokenizers import Tokenizer, models, trainers
tok = Tokenizer(models.BPE(unk_token=None))
trainer = trainers.BpeTrainer(
vocab_size=64000,
special_tokens=["<pad>", "<s>", "<e>", "<unk>"]
min_frequency=2,
)
tok.train_from_iterator(corpus_iter, trainer=trainer)
Quality Check
Metrics after training:
- average number of tokens per word in the target domain;
- proportion of
<unk>tokens (for byte-level — zero); - coverage of frequent n-grams;
- stability on test languages.
flowchart LR
A[Corpus] --> B[Normalization]
B --> C[BPE/Unigram Algorithm]
C --> D[Dictionary]
D --> E[Validation Evaluation]
E -->|poor coverage| C
E -->|ok| F[Fix Tokenizer]
Typical Mistakes
- Training the dictionary on a corpus different from the target domain.
- Over-aggressive normalization, losing significant characters.
- Changing the dictionary after model training starts — leads to incompatibility of weights and inputs.
- Ignoring special tokens for chat-template.
Related materials: tokenization, token, token-healing, tokenizer-vocabulary.