# How BPE tokenizers work: training merges, byte-level fallback and choosing vocabulary size

Every language model reads text through a tokenizer, and most use byte-pair encoding. This article trains a BPE tokenizer by hand, explains the byte-level trick and pre-tokenization, computes what vocabulary size costs in parameters, and shows why tokenization still shapes cost and quality across languages.

A language model never sees letters or words. It sees integers, each standing for a piece of text called a token. The tokenizer that maps text to tokens decides how long every input is, how much each request costs, how well the model handles rare words and other languages, and how big its embedding tables are. It is trained once, before the model, and then fixed for the model's whole life.

Most modern language models use byte-pair encoding (BPE) or a close relative. The algorithm is simple enough to run by hand, yet its details explain many quirks people notice in models, from odd behaviour on numbers to higher bills for some languages. This article walks through BPE training and encoding with a worked example, explains the byte-level variant used by most large models, and quantifies the vocabulary-size trade-off.

## What happened

### Hugging Face Tokenizers approaches 1.0 (21 September to 20 November 2026)

Hugging Face's Tokenizers library, the Rust-based package behind the fast tokenizers in Transformers, has been publishing release candidates for version 1.0. The first on PyPI, 1.0.0rc1, appeared on 21 September 2026; 1.0.0rc5 followed on 20 November 2026, while the stable line remains at 0.23.3, released on 9 October. The project's "Required for v1" document describes a rebuilt core: a pipeline runtime that loads a `tokenizer.json` file and encodes and decodes with it, with the authoring, saving and training interfaces brought back step by step. It states that the trainers for BPE, Unigram, WordPiece and WordLevel now build pipeline models directly in a separate crate that will stay at 0.x while its API settles. The library's README also describes dedicated wheels for free-threaded Python 3.14.

A tokenizer library rewrite matters because the tokenizer must reproduce the training-time mapping exactly. Any difference between the tokenizer used in training and the one used in serving silently changes the model's inputs.

## The tokenization pipeline

The Tokenizers documentation describes four stages that every encode call goes through:

1. **Normalisation** cleans the raw string, for example Unicode normalisation, lowercasing or stripping accents. Many large-model tokenizers do little or no normalisation, so that the model sees text as written.
2. **Pre-tokenisation** splits text into chunks, usually words, spaces and punctuation, so that merges never cross those boundaries.
3. **The model**, such as BPE, WordPiece or Unigram, turns each chunk into tokens.
4. **Post-processing** adds special tokens, such as a start-of-sequence marker or chat template tokens.

Decoding reverses the process. The library tracks alignments throughout, so each token can be mapped back to the exact span of the original text it came from.

## How BPE learns its vocabulary

BPE was adapted for neural machine translation by Sennrich, Haddow and Birch in 2016. Training starts from single characters and repeatedly merges the most frequent adjacent pair into a new symbol. Each merge is recorded in order. The merge list is the tokenizer.

### A worked example

Take a tiny corpus of word counts, in the style of the original paper: "low" 5 times, "lower" 2 times, "newest" 6 times and "widest" 3 times. Each word is split into characters, with an end-of-word marker `</w>`.

Counting adjacent pairs, weighted by word frequency, the most common pairs are tied at 9: (e, s), (s, t) and (t, `</w>`), each appearing in "newest" 6 times and "widest" 3 times. A tie-breaking rule is needed; the code below picks the lexicographically largest pair. Six rounds of merging produce:

| Round | Merged pair | Count | New symbol |
|---|---|---|---|
| 1 | t + `</w>` | 9 | `t</w>` |
| 2 | s + `t</w>` | 9 | `st</w>` |
| 3 | e + `st</w>` | 9 | `est</w>` |
| 4 | o + w | 7 | `ow` |
| 5 | l + `ow` | 7 | `low` |
| 6 | w + `est</w>` | 6 | `west</w>` |

After these merges, "low" is two symbols (`low`, `</w>`) and "newest" is three (`n`, `e`, `west</w>`). The frequent suffix "est" became a unit, and so did the frequent stem "low".

### Encoding new words

To encode a word, apply the merges in the order they were learned. "lowest", which never appeared in the corpus, becomes `low` + `est</w>`: two tokens built from pieces the tokenizer has seen. "newer" falls apart into `n`, `e`, `w`, `e`, `r`, `</w>`, because no merge involving "er" was learned in six rounds. A real tokenizer runs tens of thousands of merges, so common words become single tokens and rare words split into a few meaningful pieces.

```python
from collections import Counter

def train_bpe(word_counts, num_merges):
    vocab = {tuple(w) + ("</w>",): c for w, c in word_counts.items()}
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for sym, c in vocab.items():
            for a, b in zip(sym, sym[1:]):
                pairs[(a, b)] += c
        best = max(pairs.items(), key=lambda kv: (kv[1], kv[0]))[0]
        merges.append(best)
        new = {}
        for sym, c in vocab.items():
            out, i = [], 0
            while i < len(sym):
                if i < len(sym) - 1 and (sym[i], sym[i + 1]) == best:
                    out.append(sym[i] + sym[i + 1]); i += 2
                else:
                    out.append(sym[i]); i += 1
            new[tuple(out)] = c
        vocab = new
    return merges

def encode(word, merges):
    sym = list(word) + ["</w>"]
    for a, b in merges:
        out, i = [], 0
        while i < len(sym):
            if i < len(sym) - 1 and sym[i] == a and sym[i + 1] == b:
                out.append(a + b); i += 2
            else:
                out.append(sym[i]); i += 1
        sym = out
    return sym

merges = train_bpe({"low": 5, "lower": 2, "newest": 6, "widest": 3}, 6)
print(encode("lowest", merges))   # ['low', 'est</w>']
print(encode("newer", merges))    # ['n', 'e', 'w', 'e', 'r', '</w>']
```

A useful analogy is shorthand. A stenographer starts by writing every letter, notices that some letter combinations appear constantly, and invents a symbol for each one. After enough practice, common words take one stroke and unusual words take several. The list of invented symbols, in the order they were invented, is the shorthand system.

## Byte-level BPE and pre-tokenisation

### Never an unknown token

Character-level BPE has a gap: a character never seen in training, such as a rare emoji or script, has no symbol. Byte-level BPE, introduced with GPT-2, closes it by starting from bytes instead of characters. Any text in UTF-8 is a sequence of bytes, and there are only 256 possible byte values, so a byte-level tokenizer can encode any input. The Tokenizers documentation notes that the ByteLevel pre-tokeniser maps each byte to a visible character and therefore needs only 256 initial symbols.

The cost is that characters outside basic ASCII start as several bytes. "café" is 5 bytes because é takes 2; "日本" is 6 bytes because each character takes 3. Merges learned on enough text in those languages recombine the bytes into whole characters or words, but scripts that were rare in the tokenizer's training data stay split into more tokens.

### Pre-tokenisation rules shape behaviour

Before BPE runs, a pre-tokeniser splits text into chunks, usually with a regular expression. Merges never cross chunk boundaries. This step has visible effects. If the pattern splits digits into single characters or groups of up to three, numbers become regular sequences of short tokens instead of arbitrary multi-digit chunks that differ from one number to the next. If spaces are attached to the following word, "hello" at the start of a sentence and " hello" in the middle are different tokens. These choices are fixed when the tokenizer is trained and the model learns around them.

### Other model types

BPE is not the only option. WordPiece, used in BERT, builds words greedily from the longest matching pieces. Unigram, used through SentencePiece in several model families, starts from a large candidate vocabulary and prunes it to maximise the likelihood of the training text, then picks the most probable segmentation at encoding time. SentencePiece also treats the input as a raw stream, including spaces, which suits languages written without spaces.

## Choosing vocabulary size

The number of merges sets the vocabulary size V. A larger V means each token covers more text, so sequences are shorter. It also means larger embedding and output tables, and rarer tokens that each get fewer training examples.

### The parameter cost

The input embedding table has V × d parameters, where d is the model's hidden size. If the output layer is not tied to the input embeddings, it adds another V × d. With d = 4,096:

| Vocabulary size | Embedding parameters | With untied output layer |
|---|---|---|
| 32,000 | 131 million | 262 million |
| 128,000 | 524 million | 1.05 billion |
| 256,000 | 1.05 billion | 2.10 billion |

For a model with tens of billions of parameters, a billion parameters in embeddings is affordable. For a small model of one or two billion parameters, the same vocabulary can consume a large share of the budget. The output layer also computes a score for every vocabulary entry at every generated token, so its cost grows with V.

### The sequence-length benefit

The benefit is compression. Fewer tokens per document means less attention computation, a smaller KV cache, more text in the same context window and, for API users, lower bills, since most providers price by token. The gain is largest for languages and domains that a small vocabulary handles poorly, such as code, non-Latin scripts and morphologically rich languages like Turkish or Finnish, where one word can carry many suffixes.

A simple way to compare tokenizers is fertility: the average number of tokens per word, or per character, on a sample of your own text. Measure it per language and per domain before choosing a model for a multilingual product, because the same request can cost noticeably different amounts in different languages.

## What it means in practice

Tokenization is a frozen decision with lasting consequences. You cannot change a trained model's tokenizer without retraining at least its embeddings, so the choice made before pre-training affects cost, context use and quality in every language for the model's lifetime. When comparing models, token counts are not comparable across tokenizers: a model with a 128,000-token context and an efficient tokenizer may hold more text than one with a larger nominal window.

For engineers, most tokenizer bugs come from mismatches. A chat template applied twice, a missing start token, a different normalisation or a different library version can each change the token sequence without any error message. The model still answers, only worse. Pinning the exact tokenizer file with each model version and testing round trips is cheap insurance.

The [BPE tokenisation simulation](/ai-simulations/tokenisation-bpe) lets you watch merges happen on your own text, and the [tokenizer vocabulary simulation](/ai-simulations/train-tokenizer-vocabulary) shows how vocabulary size trades against sequence length. For training your own, see the [tokenizer training](/tools/tokenizer-training) page.

## What to do now

1. **Measure fertility on your data.** Tokenise a representative sample in each language and domain you serve and compare tokens per word across candidate models.
2. **Budget by tokens, not characters.** Convert expected text volumes into tokens with the actual tokenizer before estimating cost or context use.
3. **Pin the tokenizer file.** Store the exact `tokenizer.json` or equivalent with each model version, and record the library version used to load it.
4. **Test round trips.** Check that decode(encode(text)) returns the original text for samples with unusual characters, emoji, code and whitespace.
5. **Check special tokens and templates.** Inspect the final token IDs of a few formatted prompts to confirm start tokens and chat templates are applied exactly once.
6. **Train a domain tokenizer only for new models.** If you pre-train from scratch on specialised text, such as code or a single language, train the tokenizer on that data; do not swap the tokenizer of an existing model.
7. **Mind small models' embedding budgets.** For models under a few billion parameters, compute the share of parameters in embeddings before choosing a very large vocabulary.
8. **Watch the Tokenizers 1.0 transition.** If you depend on building or training tokenizers in Python, test the release candidates and follow the project's notes on which interfaces are available.

## Risks and open questions

**Unequal costs across languages.** Byte-level tokenizers trained mostly on English split other scripts into more tokens, so users of those languages pay more and fit less text into the same context.

**Silent mismatches.** Tokenizer differences between training and serving rarely raise errors. They show up as unexplained drops in quality.

**Library transitions carry risk.** A rewrite such as the Tokenizers 1.0 effort aims to keep the same outputs, but every upgrade should be checked against stored token sequences.

**Tokenization limits some skills.** Tasks that depend on characters, such as spelling, counting letters or some arithmetic, are harder when the model sees multi-character tokens.

**Watch next:** the stable Tokenizers 1.0 release and its training interfaces, and research on tokenizer-free or byte-level models that could remove the fixed vocabulary altogether.

## Frequently asked questions

### What is byte-pair encoding?

It is a method that builds a vocabulary by repeatedly merging the most frequent adjacent pair of symbols in a training corpus, starting from characters or bytes. The ordered list of merges is then applied to new text to split it into tokens.

### Why do some words become several tokens?

Only frequent sequences get their own merges. Rare words, names, typos and words from languages that were rare in the tokenizer's training data split into smaller pieces that the vocabulary does contain.

### What does byte-level mean?

The tokenizer starts from the 256 possible byte values instead of characters. Because any UTF-8 text is a sequence of bytes, it can encode any input without an unknown token, at the cost of more tokens for characters that take several bytes.

### Is a bigger vocabulary always better?

No. It shortens sequences but adds embedding parameters and output computation, and rare tokens get fewer training examples. The right size depends on model size, languages and domains.

### Can I change a model's tokenizer?

Not without retraining. The model's embeddings and output layer are tied to specific token IDs, so a new tokenizer requires at least retraining those layers and usually further training of the whole model.

## Summary

A tokenizer turns text into the integer sequence a model reads. BPE learns it by repeatedly merging the most frequent adjacent pair, and encodes new text by replaying those merges, so common words become single tokens and rare ones split into known pieces. Byte-level BPE starts from 256 bytes, so it never meets an unknown symbol, while pre-tokenisation rules decide how spaces, digits and punctuation are handled. Vocabulary size trades embedding parameters, from 131 million at 32,000 entries to over a billion at 256,000 with a hidden size of 4,096, against shorter sequences and lower costs. Measure tokens on your own text, pin tokenizer files with model versions, and test round trips. For more, see the [BPE](/tools/bpe) and [SentencePiece](/tools/sentencepiece) pages and the [inside an LLM topic](/topics/generative-ai-llms/inside-an-llm).

## Sources

- [arXiv: Neural Machine Translation of Rare Words with Subword Units](https://arxiv.org/abs/1508.07909)
- [OpenAI: Language Models are Unsupervised Multitask Learners (GPT-2)](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf)
- [arXiv: SentencePiece: A simple and language independent subword tokenizer and detokenizer](https://arxiv.org/abs/1808.06226)
- [arXiv: Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates](https://arxiv.org/abs/1804.10959)
- [Hugging Face: Tokenizers, the tokenization pipeline](https://huggingface.co/docs/tokenizers/pipeline)
- [Hugging Face: Tokenizers components](https://huggingface.co/docs/tokenizers/components)
- [GitHub: Tokenizers, Required for v1](https://github.com/huggingface/tokenizers/blob/main/REQUIRED_FOR_V1.md)
- [PyPI: tokenizers release history](https://pypi.org/project/tokenizers/#history)
