Search

Search papers and lessons

Subword Tokenization

Level 3 · 11 min read

Subword tokenization splits text into pieces that are more common than characters and smaller than words, so a model can read any text with a fixed vocabulary.

On this page

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 VV be a finite vocabulary of pieces, and let Σ∗\Sigma^\ast be the set of all strings over the character alphabet. A tokenizer is a function

τ:Σ∗→V∗\tau : \Sigma^\ast \to V^\ast

that maps a string to a sequence of pieces. It must be lossless: concatenating the pieces must give back the original string. Given VV, 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 ∣τ(s)∣|\tau(s)| 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 ∣V∣|V| sets how large the embedding table is, and an embedding table of size ∣V∣×d|V| \times d costs memory for each of the dd dimensions.

Byte pair encoding

Byte pair encoding (BPE) builds VV 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.

Algorithm
Learning BPE merges
  1. 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.
  2. Count every adjacent pair of symbols, weighting each pair by the frequency of its word.
  3. Find the most frequent pair (a,b)(a, b). Add the new symbol abab to the vocabulary and record the merge (a,b)→ab(a, b) \to ab.
  4. Replace every occurrence of a ba\,b in the corpus with abab.
  5. 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

score(a,b)=count⁡(ab)count⁡(a) count⁡(b).\mathrm{score}(a, b) = \frac{\operatorname{count}(ab)}{\operatorname{count}(a)\,\operatorname{count}(b)}.

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 ss has a probability p(s)p(s), and a segmentation s=(s1,…,sk)\mathbf{s} = (s_1, \dots, s_k) of a string has probability ∏ip(si)\prod_{i} p(s_i). The tokenizer picks the segmentation with the highest probability, which is a shortest-path problem solved by dynamic programming:

s^=arg⁡max⁡s∑i=1klog⁡p(si).\hat{\mathbf{s}} = \arg\max_{\mathbf{s}} \sum_{i=1}^{k} \log p(s_i).

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

Example
Learning five BPE merges by hand

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.

  1. The most frequent pairs are e s, s t and t </w>, each appearing 9 times (6 in newest, 3 in widest). Break the tie by taking the first, and merge e s to es.
  2. Now t after es is the most frequent pair: 9 occurrences. Merge es t to est.
  3. Now est </w> appears 9 times. Merge it to est</w>.
  4. The pair l o appears 7 times (5 in low, 2 in lower), tied with o w. Break the tie by taking the first, and merge lo.
  5. Now lo w appears 7 times. Merge it to low.

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.

Example
Why not characters: attention cost

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.

  1. Character sequence length: Lc≈9000L_c \approx 9000.
  2. Subword sequence length: Ls≈2000L_s \approx 2000.
  3. Self-attention compares every pair of positions, so its cost scales with L2L^2.
  4. Character cost: 90002=810000009000^2 = 81000000 comparisons. Subword cost: 20002=40000002000^2 = 4000000 comparisons.
  5. The ratio is 81000000/4000000=20.2581000000 / 4000000 = 20.25.

Interpretation: character-level input would make the attention work about twenty times larger for this essay. The subword vocabulary costs embedding memory, roughly 50000×d50000 \times d parameters for a model with a vocabulary of about 50 thousand pieces, but it saves far more computation on long documents.

Example
Fitting a document into a context window

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.

  1. At 1.33 tokens per word: 3000×1.33≈40003000 \times 1.33 \approx 4000 tokens. This fits in 4096.
  2. At 2 tokens per word: 3000×2=60003000 \times 2 = 6000 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.

1234567800.20.40.60.81characters per tokenattention cost relative to 1 character per token
  • relative attention cost
If each token covers x characters, the sequence has 1/x as many positions, and attention work, which scales with length squared, falls as 1/x^2.
SituationWhat goes wrongBetter choice
Word-level vocabularyUnseen words become an unknown token, and the vocabulary grows hugeSubword pieces, which cover any string
Character-level inputSequences are long, and attention cost grows with length squaredSubword pieces with a moderate vocabulary
Text without spaces, such as Japanese or ChineseSplitting on spaces first does nothing usefulSentencePiece, which treats the raw text, including spaces, as the input
Numbers and arithmeticDigits are grouped into arbitrary pieces, so 1234 and 123 share no structureTokenizers that split numbers into individual digits
A tokenizer trained on one language, used on anotherMore tokens per word, so the same text costs more and fits lessTrain the tokenizer on a mixed corpus that covers the target languages
Byte-level BPEEvery input is representable, but a single emoji can take several tokensAccept 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 r letters 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. hello and hello (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 3000×1.5=45003000 \times 1.5 = 4500 tokens. That is 4500−4096=4044500 - 4096 = 404 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.

Sources