Tokenization & BPE
The model never sees characters, only merged byte pairs. How BPE learns its vocabulary, how it encodes new text, and where token counts surprise you.
Jump to a section
The model never sees characters
GPT-2's vocabulary has 50,257 entries: 256 single bytes, 50,000 learned merges, and one end-of-text marker. Every input is converted to a sequence of those IDs before the model sees it, and every output is produced one ID at a time. A common word is usually one ID; a rare one is several.
That choice decides how much text fits in a context window, how much compute each request takes, and what a token-priced API charges. Two inputs with the same word count can differ widely in tokens.
Byte-pair encoding (BPE) is how that vocabulary is built. It sits between two simpler options. A word-level vocabulary gives short sequences but has to be enormous, and any word missing from it becomes an unknown token. A character or byte vocabulary is tiny and covers everything, but sequences get several times longer, and attention cost grows with length. BPE starts from characters or bytes and learns which longer pieces are worth a vocabulary slot.
Learning merges from a corpus
Training BPE to a target vocabulary size is a greedy loop:
- Start the vocabulary with every base symbol: the characters in the corpus, or all 256 bytes for byte-level BPE.
- Count every adjacent pair of symbols across the corpus.
- Merge the most frequent pair into a new symbol , add it to the vocabulary, and record the merge.
- Repeat steps 2 and 3 until the vocabulary has entries.
Frequent sequences get absorbed early. In English text a pair like t h is a typical early merge, and later rounds build longer pieces and whole common words. Rare words never accumulate enough counts and stay split into pieces. The output of training is the ordered list of merges, and that order matters as much as the vocabulary itself.
Sennrich et al. brought the method to neural machine translation in 2015, applied within words and with an end-of-word marker so a piece at the end of a word stays distinct from the same piece in the middle. The original BPE was a data-compression algorithm that replaced frequent byte pairs with unused byte values; the NLP version keeps the merge loop and turns each merged symbol into a vocabulary entry.
Encoding replays the merges in order
To tokenize new text, split it into base symbols and apply the learned merges by priority: of all the adjacent pairs that have a merge rule, merge the one learned earliest, and repeat until no rule applies. Nothing in this procedure looks for English words or the longest match.
Take l o w e r. If the learned order is e r first and l o second, encoding gives l o w er, then lo w er. A tokenizer whose order was l o, then lo w, then e r produces low er from the same five letters. Same word, same alphabet, different pieces, because the priorities came from different corpora.
Apply a learned merge order
The same word changes token boundaries as ranked merges are applied.
Exact inputs and equations appear with the figure.
Preparing the scientific figure…
A fixed illustrative merge sequence; vocabulary learning requires a corpus.
Authored analytic exampleExperiment with related Studio inputs
Read each box as the current token sequence. Merge e + r first, then l + o, using an already learned merge order.
An illustrative sequence for one word. Merge priorities are learned from a corpus, not inferred from this single example.
Read the related Studio connections
l o w e r -> l o w er : merge e + r l o w er -> lo w er : merge l + o
A merge that looks useful inside one word can have low priority in the full corpus, so the pieces do not always align with morphemes. In the small example in the code below, w e is the most frequent pair, and "newest" comes out as n e we s t.
Bytes as the base alphabet
If the base alphabet is characters, any character absent from training has no symbol. Byte-level BPE starts from the 256 possible byte values instead, so every UTF-8 string, including emoji and rare scripts, can be encoded with no unknown token. The cost is that a character outside the merges may take two to four tokens, one per byte.
Byte-level BPE needs a guard of its own. The GPT-2 report describes how naive merging produced many variants of one word glued to punctuation, such as dog., dog! and dog?, each taking a vocabulary slot. Its fix was to prevent merges across character categories, with an exception for spaces. Many later tokenizers do something similar with a pre-tokenization step that splits text before BPE runs.
WordPiece, used by BERT, looks similar and encodes differently. The BERT tokenizer splits a word by greedy longest-match-first lookup in its vocabulary, not by replaying ranked merges, and it emits an unknown token when no split exists.
Vocabulary size is a trade
A larger vocabulary means fewer tokens per text. Llama 2 used a 32K vocabulary; Llama 3 moved to 128K, built from 100K tiktoken tokens plus 28K added for non-English languages. The Llama 3 paper reports that compression on a sample of English rose from 3.17 to 3.94 characters per token, so the same context window holds about 24% more English text.
The price is embedding rows. Llama 3 8B has a vocabulary of 128,256 and a width of 4,096, so its input embedding table alone is million parameters, and its separate output projection is the same size. Together they are about 1.05 billion parameters, roughly an eighth of the model.
In code
A small merge-learning example, plus an encoder that replays merges by rank. It joins strings with spaces and permits merges across word boundaries; production tokenizers also define normalization, pre-tokenization, special tokens and unknown-character handling.
1from collections import Counter
2
3def get_pairs(tokens: list[str]) -> Counter:
4 return Counter(zip(tokens, tokens[1:]))
5
6def merge_pair(tokens: list[str], pair: tuple[str, str]) -> list[str]:
7 merged, i = [], 0
8 while i < len(tokens): # apply the merge in one pass
9 if i < len(tokens) - 1 and (tokens[i], tokens[i + 1]) == pair:
10 merged.append(tokens[i] + tokens[i + 1])
11 i += 2
12 else:
13 merged.append(tokens[i])
14 i += 1
15 return merged
16
17def train_bpe(corpus: list[str], num_merges: int) -> list[tuple[str, str]]:
18 tokens = list(" ".join(corpus)) # char-level start
19 merges: list[tuple[str, str]] = []
20 for _ in range(num_merges):
21 pairs = get_pairs(tokens)
22 if not pairs:
23 break
24 best = pairs.most_common(1)[0][0] # most frequent adjacent pair
25 merges.append(best)
26 tokens = merge_pair(tokens, best)
27 return merges
28
29def encode(word: str, merges: list[tuple[str, str]]) -> list[str]:
30 rank = {pair: i for i, pair in enumerate(merges)}
31 tokens = list(word)
32 while True:
33 candidates = [p for p in zip(tokens, tokens[1:]) if p in rank]
34 if not candidates:
35 return tokens
36 tokens = merge_pair(tokens, min(candidates, key=rank.__getitem__))
37
38merges = train_bpe(["lower", "lowest", "newer"], num_merges=5)
39print(merges) # tie-breaking follows first occurrence in this example
40assert merges[0] == ("w", "e") # occurs in all three words
41assert encode("lower", merges) == ["lower"]
42assert encode("newest", merges) == ["n", "e", "we", "s", "t"]
43assert encode("lower", [("e", "r"), ("l", "o")]) == ["lo", "w", "er"]Where token counts surprise you
Whitespace and case. Byte encoding, whitespace handling, special tokens and pre-tokenization all change the IDs. A leading space or a capital letter can turn one token into a different one or into two, so a token count cannot be inferred from a word count.
Mismatched tokenizers. IDs are only meaningful with the vocabulary that produced them. Use the same tokenizer on both sides of a model interface; token strings that look identical are not proof that their IDs come from the same vocabulary.
Untested round trips. For a reproducible check, name the tokenizer and its revision, inspect the actual IDs, decode them back, and verify the round trip on punctuation and non-ASCII text.
Sources and further reading
- Sennrich et al., Neural Machine Translation of Rare Words with Subword Units: subword BPE training.
- Google Research BERT tokenizer implementation: WordPiece longest-match-first lookup and unknown-token handling.
- Llama Team, The Llama 3 Herd of Models (2024): the 128K vocabulary and its compression rate against Llama 2.
Keep going
Ask your own question about Tokenization & BPE, or start a guided session on it: six short pages, from the big picture to code you can run.