Topic 6 of 6 · 6 min read
Training a tokenizer with real libraries
Goal: Train a small BPE tokenizer with a library and measure its compression ratio on held-out text.
Train a tokenizer on text that looks like your model's data, save it as one file, and measure characters per token on held-out text; and never swap the tokenizer of a pretrained model, because its embeddings are tied to the old ids. Libraries do the heavy lifting, so your job is choosing the corpus, the pre-tokenizer and the size.
Check yourself · 1 of 3
Why should compression be measured on held-out text?
Why it matters
The tokenizer decides sequence length, cost and which languages and code are cheap. A bad tokenizer cannot be repaired after pretraining. It is also tiny to train compared with a model, so test candidates early.
The three libraries
- Hugging Face tokenizers: assemble a model (BPE), a pre-tokenizer, a trainer and a decoder. Fast, and the saved JSON loads in Transformers.
- SentencePiece: trains on raw text, treats spaces as part of the text, and offers BPE and Unigram. Common in multilingual models.
- tiktoken: mainly for loading and running OpenAI-style encodings quickly, rather than training new ones.
A minimal training script
from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tok.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer(
vocab_size=8000,
special_tokens=["<|endoftext|>"],
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
)
tok.train(["train.txt"], trainer)
tok.save("tokenizer.json")
held_out = open("held_out.txt", encoding="utf-8").read()
n_tokens = len(tok.encode(held_out).ids)
print("chars per token:", len(held_out) / n_tokens)
Initial alphabet: seeding with all 256 byte symbols keeps byte-level fallback complete even if a rare byte is missing from the training file.
Measuring it
Compute characters per token on text the tokenizer has not seen, split by domain: prose, code, each language you care about. A single average hides the weak spots. Also check round trips: decode(encode(text)) must equal the text.
Why you cannot swap a pretrained model's tokenizer
A pretrained model's embedding row 4,187 holds what the model learned about whatever token 4,187 was. A new tokenizer assigns different strings to those ids, so every row now describes the wrong text and the output layer predicts the wrong things. To change the tokenizer you must retrain, or at least re-learn the embeddings with a lot of continued training, and expect a quality hit. Adding a few new tokens and resizing the embeddings is a smaller change, but the new rows start untrained.
Before and after
Weak: "Our code is slow, so load a different tokenizer into the model." Fixed: "Measure tokens per file with the model's own tokenizer. If code is costly, either accept the cost, chunk differently, or train a new model with a code-aware tokenizer."
What goes wrong
- Training on a tiny or unrepresentative file, so merges reflect that file only.
- Testing on the training text, which overstates compression.
- Forgetting to save and version the tokenizer file with the model weights.
Examples
Compression by domain
| Held-out set | Characters | Tokens | Chars per token |
|---|---|---|---|
| English prose | 100,000 | 24,000 | 4.2 |
| Python code | 100,000 | 38,000 | 2.6 |
| Arabic news | 100,000 | 52,000 | 1.9 |
The average looks fine, but code and Arabic cost much more per character. If your product serves both, retrain with a corpus that includes them.
The swapped tokenizer
A team loads a pretrained model but replaces its tokenizer with a new one to get shorter code sequences. Generation turns into gibberish. Token id 812 used to mean def. In the new vocabulary it means ing, but the model still treats the row as def. The fix is to keep the original tokenizer or retrain the model.
Key points
- Train the tokenizer on text that matches the model's real data, then save it as a single versioned file.
- Hugging Face tokenizers, SentencePiece and tiktoken cover training and fast loading; pick by language mix and model family.
- Measure characters per token on held-out text, split by domain, not one average.
- Check that decode(encode(text)) returns the original text.
- A pretrained model's embeddings are tied to its tokenizer's ids, so swapping the tokenizer breaks it unless you retrain.
Common mistakes
- Measuring compression on the same text the tokenizer was trained on.
- Averaging compression over all text and missing the poor results for code or other languages.
- Swapping the tokenizer of a pretrained model without retraining its embeddings.
- Not saving the tokenizer file next to the model weights, so serving uses a different one.
Check yourself · 2 of 3
You load a pretrained model but plug in a different tokenizer with a different vocabulary. What happens?
Check yourself · 3 of 3
After training a tokenizer, which check confirms it can recover the original text?
Practice items, not counted towards your mastery.
Start here
- Byte-Pair Encoding tokenization (Hugging Face LLM course) (opens in a new tab)CourseFree
Walks through BPE training and encoding step by step on a tiny corpus, including the byte-level trick that removes unknown tokens.
- Andrej Karpathy: minbpe and the GPT tokenizer lecture (opens in a new tab)ToolFree
Short, readable Python for training, encoding and decoding BPE; the best code to step through next to the merge algorithm.
- Hugging Face LLM Course: The Tokenizers library (opens in a new tab)CourseFree
Hands-on chapters on training a tokenizer from an old one and on the BPE, WordPiece and Unigram algorithms.
More for this topic
- Hugging Face Tokenizers documentation (opens in a new tab)DocsFree
Reference for the models, trainers, pre-tokenizers and decoders you assemble into a tokenizer.
- SentencePiece (Google) (opens in a new tab)ToolFree
A tokenizer trainer that works on raw text without pre-splitting, with BPE and Unigram modes.