TL;DR
A neural network reads numbers, not letters, so text must first be cut into pieces and each piece given an integer id. Subword tokenization cuts text into pieces that are bigger than single characters and smaller than whole words. Common words stay whole, and rare words break into familiar fragments. The result is a fixed-size vocabulary that can represent any string.
Where you'll see it: the first step of every large language model, including the byte-level BPE used by GPT models, the WordPiece used by BERT, and the SentencePiece used by T5 and the original LLaMA.
Intuition
Building words from a kit of parts
Imagine a dictionary with a fixed number of entries. A word-level dictionary is too big, and it still fails on the first word it has never seen, such as a rare surname or a new product name. A character-level dictionary never fails, but it turns every sentence into a long string of letters, and the model has to learn spelling and meaning from scratch.
Subword tokenization sits between the two. Think of a box of building bricks in several sizes. The common words are single large bricks. A rare word is assembled from smaller bricks that you already own. "unhappiness" might come out as un, happi, ness. The model has seen un and ness in thousands of other words, so it can reuse what it knows.
The pieces are not chosen by a linguist. They are learned from a corpus, by counting which character sequences appear together most often. A piece that occurs many times earns a slot in the vocabulary, and a piece that never occurs does not.
flowchart LR A[Raw text] --> B[Split into words or chunks] B --> C[Apply learned merge rules] C --> D[Pieces from the vocabulary] D --> E[Integer ids] E --> F[Embedding lookup in the model]
The output of the tokenizer feeds the embedding table of the model, so each piece gets a learned vector. Everything after that point is ordinary neural network computation, and the Language Model only ever sees sequences of ids.
Why the middle ground works
Most text is made of a small set of very common words and a long tail of rare ones. Word frequencies follow a heavy-tailed distribution, so a few thousand subword pieces cover most of what appears in ordinary writing, and the rare long tail is covered by combinations. The tokenizer spends its vocabulary budget where the frequency is, and the leftover budget handles the tail.
The math
What a tokenizer is
Let be a finite vocabulary of pieces, and let be the set of all strings over the character alphabet. A tokenizer is a function
that maps a string to a sequence of pieces. It must be lossless: concatenating the pieces must give back the original string. Given , a tokenizer is a choice of how to segment each string. Because the vocabulary contains every single character (or, for byte-level methods, every byte), every string has at least one valid segmentation, so the tokenizer never fails. This is what "open vocabulary" means in practice.
Two sequence lengths matter. The number of pieces sets how much work the model does, since the cost of attention in a Transformer (the operation that compares every pair of positions) grows with the square of that length. The vocabulary size sets how large the embedding table is, and an embedding table of size costs memory for each of the dimensions.
Byte pair encoding
Byte pair encoding (BPE) builds by repeatedly merging the most frequent adjacent pair. Words are first split into characters, and a special end-of-word marker </w> is appended, so that est at the end of a word is different from est inside estimate.
- Start with a vocabulary of all characters. Represent each word in the corpus as its characters plus
</w>, and count how often each word occurs. - Count every adjacent pair of symbols, weighting each pair by the frequency of its word.
- Find the most frequent pair . Add the new symbol to the vocabulary and record the merge .
- Replace every occurrence of in the corpus with .
- Repeat steps 2 to 4 until the vocabulary reaches the target size, which is a chosen number of merges.
To tokenize new text, apply the recorded merges in the same order to the characters of each word. The method is greedy and it is not a probabilistic model. Its objective is compression: each merge replaces the most frequent pair, which shortens the corpus the most.
WordPiece
WordPiece, used in BERT, changes the merge rule. Instead of raw frequency, it merges the pair that most increases the likelihood of the training data under a unigram model, which is approximated by the score
A pair scores high when its two halves rarely appear apart, relative to how often they appear together. Frequent but unrelated pieces, such as the common letters on their own, score low. At inference time, WordPiece matches the longest vocabulary piece from the left, and marks continuation pieces with a ## prefix.
Unigram language model segmentation
SentencePiece with the unigram method takes the opposite approach. It starts with a large candidate vocabulary and prunes it. Each piece has a probability , and a segmentation of a string has probability . The tokenizer picks the segmentation with the highest probability, which is a shortest-path problem solved by dynamic programming:
Because segmentation is a distribution rather than a single answer, training can also sample several segmentations of the same word. That is called subword regularisation, and it makes the model less brittle to a particular split.
Worked examples
Take a toy corpus with four words and their counts: low (5), lower (2), newest (6), widest (3). Each word is split into characters, with </w> at the end.
- The most frequent pairs are
e s,s tandt </w>, each appearing 9 times (6 innewest, 3 inwidest). Break the tie by taking the first, and mergee stoes. - Now
tafteresis the most frequent pair: 9 occurrences. Mergees ttoest. - Now
est </w>appears 9 times. Merge it toest</w>. - The pair
l oappears 7 times (5 inlow, 2 inlower), tied witho w. Break the tie by taking the first, and mergelo. - Now
lo wappears 7 times. Merge it tolow.
The final merge list is: es, est, est</w>, lo, low. Tokenizing a word the corpus never contained, lowest, gives:
- Start:
l o w e s t </w> - Apply
es:l o w es t </w> - Apply
est:l o w est </w> - Apply
est</w>:l o w est</w> - Apply
lo:lo w est</w> - Apply
low:low est</w>
Interpretation: lowest was never seen, but it is encoded with two known pieces, low and est</w>, which carry most of its meaning. The model can reuse what it learned from low and from newest.
A 1500-word essay has roughly 9000 characters including spaces, and a subword tokenizer usually produces about 2000 tokens for the same text, which is the common rule of thumb of about three quarters of a word per token.
- Character sequence length: .
- Subword sequence length: .
- Self-attention compares every pair of positions, so its cost scales with .
- Character cost: comparisons. Subword cost: comparisons.
- The ratio is .
Interpretation: character-level input would make the attention work about twenty times larger for this essay. The subword vocabulary costs embedding memory, roughly parameters for a model with a vocabulary of about 50 thousand pieces, but it saves far more computation on long documents.
A model has a context window of 4096 tokens. A 3000-word English essay is about 4000 tokens if the tokenizer produces 1.33 tokens per word, which fits. The same essay in a language the tokenizer was not trained on might produce 2 tokens per word.
- At 1.33 tokens per word: tokens. This fits in 4096.
- At 2 tokens per word: tokens. This does not fit.
Interpretation: the tokenizer decides how much text fits in the window. A tokenizer trained mostly on English is cheap for English and expensive for other languages, which is a real cost to users of those languages.
Tradeoffs and failure modes
Subword tokenization is a compromise, and its failures are the failures of its compromise.
- relative attention cost
| Situation | What goes wrong | Better choice |
|---|---|---|
| Word-level vocabulary | Unseen words become an unknown token, and the vocabulary grows huge | Subword pieces, which cover any string |
| Character-level input | Sequences are long, and attention cost grows with length squared | Subword pieces with a moderate vocabulary |
| Text without spaces, such as Japanese or Chinese | Splitting on spaces first does nothing useful | SentencePiece, which treats the raw text, including spaces, as the input |
| Numbers and arithmetic | Digits are grouped into arbitrary pieces, so 1234 and 123 share no structure | Tokenizers that split numbers into individual digits |
| A tokenizer trained on one language, used on another | More tokens per word, so the same text costs more and fits less | Train the tokenizer on a mixed corpus that covers the target languages |
| Byte-level BPE | Every input is representable, but a single emoji can take several tokens | Accept the longer sequences, or use a larger vocabulary |
Three failure modes come up repeatedly in practice:
- The model does not see letters. Asked how many
rletters a word contains, a model that sees the word as two or three pieces has to infer the answer indirectly. The letters were never separate inputs. - Small changes change the tokens.
helloandhello(with a leading space) are different pieces, so the same text with a different spacing can produce a different sequence. - Pieces can split meaning. A name or a technical term may split into fragments that carry no meaning on their own, which makes the model weaker on that word.
History
Philip Gage described byte pair encoding in 1994 as a data compression method, where it repeatedly replaces the most frequent pair of bytes with an unused byte. Rico Sennrich, Barry Haddow and Alexandra Birch applied the same idea to neural machine translation in 2016, so that a model could translate rare words by building them from smaller parts. Their paper is the usual reference for subword units in neural networks.
WordPiece was developed at Google for a speech and language system in the early 2010s, and it was used in Google's neural machine translation system in 2016. BERT, released in 2018, made it the standard tokenizer for encoder models. GPT-2 in 2019 moved to byte-level BPE, which works on the bytes of the text, so it can represent any input without an unknown token.
Taku Kudo and John Richardson released SentencePiece in 2018. It treats the input as a raw stream of characters, including spaces, which removed the need to split words first. That made the method practical for languages without spaces and for training end-to-end without language-specific preprocessing. It is the tokenizer behind T5 and the original LLaMA models.
Check yourself
QuestionWhy does a word-level vocabulary fail on words that never appeared in training, while a subword vocabulary does not?Show answer
A word-level vocabulary has one entry per word. A word missing from the training data has no entry, so it maps to an unknown token and its meaning is lost. A subword vocabulary contains characters and fragments, and any string can be written as a sequence of those pieces. A new word is therefore assembled from pieces the model has already seen, such as the low and est</w> in lowest.
QuestionUsing the five merges from the worked example, in order, which pieces does the word newest become?Show answer
Start with n e w e s t </w>. Apply es to get n e w es t </w>. Apply est to get n e w est </w>. Apply est</w> to get n e w est</w>. The merges lo and low do not apply, because lo and low do not occur in this word. The final pieces are n, e, w, est</w>.
QuestionWhy does the end-of-word marker matter when learning BPE merges?Show answer
Without the marker, the piece est inside newest and the piece est at the start of estimate would be the same symbol. The marker makes est</w> a different symbol, which only occurs at the end of a word. That lets the tokenizer learn that a word ending in est behaves differently from a word that merely contains those letters.
QuestionA model has a 4096-token context window. Your English document has 3000 words and the tokenizer produces 1.5 tokens per word. Does it fit, and how many tokens are over or under the limit?Show answer
The document has tokens. That is tokens over the limit, so it does not fit. You would need to truncate it, split it into chunks, or use a model with a larger window.