Sub topic 2
Tokenization: turning text into subword tokens
This chapter assumes you can read basic Python and know that a language model predicts the next token from the tokens before it. Here you will see what a token is, why models use subwords, and how byte-pair encoding (BPE) builds a vocabulary.
Why not use words or characters?
A model needs a fixed list of symbols it can score at every step. That list is the vocabulary. Each symbol gets an integer token ID, and the model works only with those IDs.
Two simple choices both have problems:
- Whole words. The vocabulary must hold every word form, such as "run", "running", and "runner". Any word not in the list, like a new name or a typo, becomes an unknown symbol.
- Single characters. There are no unknown symbols, but sequences become very long. Attention cost grows with sequence length, and each character carries little meaning.
Subword tokenization sits between the two. Common words stay whole, and rare words split into smaller pieces that the vocabulary already contains.
| Unit | Vocabulary size | Sequence length | Unknown words |
|---|---|---|---|
| Words | Very large | Short | Frequent |
| Characters | Tiny | Very long | None |
| Subwords | Moderate (often 30,000 to 200,000) | Moderate | Rare or none |
Byte-pair encoding
BPE builds the vocabulary from a training corpus in a loop:
- Start with each character as its own token.
- Count every adjacent pair of tokens.
- Merge the most frequent pair into one new token.
- Repeat until the vocabulary reaches the target size.
The list of merges, in order, is saved. To tokenize new text, the tokenizer starts from characters and applies the saved merges in the same order.
One merge step in code
The code below performs a single merge on the string low lower lowest.
from collections import Counter
def most_frequent_pair(tokens):
pairs = Counter(zip(tokens, tokens[1:]))
return pairs.most_common(1)[0][0]
def merge(tokens, pair, new_token):
out, i = [], 0
while i < len(tokens):
if i < len(tokens) - 1 and (tokens[i], tokens[i + 1]) == pair:
out.append(new_token)
i += 2
else:
out.append(tokens[i])
i += 1
return out
tokens = list('low lower lowest')
pair = most_frequent_pair(tokens)
tokens = merge(tokens, pair, ''.join(pair))
print(pair, tokens)The pair ('l', 'o') appears three times, and so does ('o', 'w'). most_common returns the one it counted first, which is ('l', 'o'). The output list then starts with lo in place of l, o at each of the three words. Running the loop again would merge lo with w into low, and so on.
Practical consequences
Real tokenizers add details that affect how the model behaves.
- Spaces are often part of tokens. A token like " the" (with a leading space) differs from "the" at the start of a text. The same word can have different IDs depending on position.
- Byte-level fallback. Many tokenizers start from raw bytes instead of characters, so any input, including emoji and rare scripts, can be encoded.
- Special tokens. Reserved tokens mark things like the end of a text or the boundaries of chat messages.
- Uneven cost across languages. A vocabulary trained mostly on English splits other languages into more pieces. The same sentence then uses more tokens, which uses more of the context window and costs more.
- Arithmetic and spelling. The model sees token IDs, not letters. Counting the letters in a word or comparing long numbers is harder because a token may hide its characters.
Tokenization is fixed before model training. The model never changes it, so a model must always be used with the tokenizer it was trained with.
Exercise
A tokenizer's vocabulary was built from English text. A user sends the same sentence in English and in a language that was rare in the training data. Which version will likely use more tokens, and why?
Show answer
The rare-language version. Few merges for that language were learned, so words stay split into short pieces or bytes, which produces more tokens for the same meaning.
Exercise
In the code above, what would tokens look like after a second merge step if the most frequent pair were ('lo', 'w')?
Show answer
Each lo, w sequence becomes low, giving ['low', ' ', 'low', 'e', 'r', ' ', 'low', 'e', 's', 't'].