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. You don't need to know how the network itself works yet. Here we look at the step before the network: how raw text becomes the integer IDs the model consumes.
Why a model can't read raw text
A neural network does arithmetic on numbers. Text has to be converted to numbers first, and the conversion has to be reversible, so the model's output can be turned back into text. The conversion has two stages:
- Tokenization splits a string into pieces called tokens.
- Vocabulary lookup maps each token to an integer token ID.
The model never sees characters or words, only the IDs. Later chapters turn each ID into a vector (an embedding). The choice of token pieces shapes everything downstream, including cost, context length, and some odd failure modes.
Three ways to split text
| Unit | Example split of "unbelievably" | Vocabulary size | Main problem |
|---|---|---|---|
| Characters | u, n, b, e, l, i, e, v, a, b, l, y | Tiny (hundreds) | Sequences get very long, and each token carries little meaning |
| Whole words | unbelievably | Huge (hundreds of thousands) | Unseen words, typos, and names fall outside the vocabulary |
| Subwords | un, believ, ably | Middle (tens of thousands to a few hundred thousand) | Splits are less intuitive, but any text can be represented |
Modern LLMs use subword tokenization. Common words become a single token. Rare words are built from several smaller pieces. Any string can still be represented, because the pieces can always fall back to single characters or bytes.
Byte-pair encoding
Byte-pair encoding (BPE) is the most widely used subword algorithm. It learns its vocabulary from a text corpus:
- Start with a vocabulary of single symbols (characters or bytes).
- Count every adjacent pair of symbols in the corpus.
- Merge the most frequent pair into a new symbol and add it to the vocabulary.
- Repeat until the vocabulary reaches the target size.
Frequent sequences such as "the" or " and" end up as single tokens, because they were merged early. The ordered list of merges is the trained tokenizer.
One merge step
The functions below perform a single merge. They find the most frequent adjacent pair and replace every occurrence with one new token.
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') occurs three times, so it is merged into lo. The pairs ('o', 'w') and ('l', 'o') tie at three occurrences. Counter.most_common(1) returns the one it saw first, which is ('l', 'o'). Real implementations need a deterministic tie-breaking rule for the same reason. Otherwise two training runs could produce different tokenizers.
Training several merges and encoding new text
Training repeats the step. Encoding then replays the learned merges, in the same order, on new text.
from collections import Counter
def most_frequent_pair(tokens):
pairs = Counter(zip(tokens, tokens[1:]))
return pairs.most_common(1)[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
def train_bpe(text, num_merges):
tokens, merges = list(text), []
for _ in range(num_merges):
if len(tokens) < 2:
break
pair, count = most_frequent_pair(tokens)
if count < 2:
break # no pair repeats, so merging teaches nothing
tokens = merge(tokens, pair, ''.join(pair))
merges.append(pair)
return merges, tokens
def encode(text, merges):
tokens = list(text)
for pair in merges: # apply merges in the order they were learned
tokens = merge(tokens, pair, ''.join(pair))
return tokens
merges, tokens = train_bpe('low lower lowest', 3)
print(merges)
print(tokens)
print(encode('lower', merges))The three merges are ('l', 'o'), ('lo', 'w'), and (' ', 'low'). The training text becomes ['low', ' low', 'e', 'r', ' low', 'e', 's', 't']. The new word lower encodes as ['low', 'e', 'r']. The tokenizer never saw lower as a unit during encoding, but it still produced a sensible split from the pieces it knows.
Notice that the third merge includes a leading space. That is deliberate and matters in practice, as the next sections show.
From tokens to IDs
After training, the vocabulary is a table that assigns each token string a unique integer. Encoding text produces a list of IDs, and decoding reverses it.
vocab = {'low': 0, ' low': 1, 'e': 2, 'r': 3, 's': 4, 't': 5}
inverse = {i: tok for tok, i in vocab.items()}
pieces = ['low', ' low', 'e', 'r']
ids = [vocab[p] for p in pieces]
print(ids)
print(''.join(inverse[i] for i in ids))The IDs are arbitrary labels. ID 5 isn't "bigger" or "more similar" to ID 4 than to ID 0. Any similarity between tokens has to be learned later, in the embedding table.
Details that affect behavior
Byte-level fallback
Many production tokenizers run BPE on bytes of UTF-8 text instead of Unicode characters. The base vocabulary then has exactly 256 entries, and every possible string can be encoded. Nothing is ever "unknown". Emoji, rare scripts, and corrupted text all decompose into bytes. The cost is that a rare character may take several tokens.
Whitespace is part of the token
In many tokenizers, " low" (with a leading space) and "low" are different tokens with different IDs. The same word at the start of a line and in the middle of a sentence can therefore tokenize differently. This is why a prompt that ends with a trailing space can behave oddly. The model expects the space to be attached to the front of the next token, so a lone trailing space is a rare, unusual input.
Pre-tokenization
Before BPE runs, most tokenizers first split text with a regular expression into chunks, for example separating words, numbers, and punctuation. Merges then happen only inside a chunk. This stops the algorithm from creating tokens that span unrelated pieces, such as the end of one word and the start of the next.
Special tokens
The vocabulary also holds reserved tokens that never come from merging. Examples are an end-of-text marker, or markers that delimit chat roles. The model learns to emit the end-of-text token to signal that generation should stop.
Vocabulary size is a trade-off
| Larger vocabulary | Smaller vocabulary |
|---|---|
| Fewer tokens per text, so more text fits in the context window | More tokens per text, so context fills faster |
| Bigger embedding table and output layer | Smaller embedding table and output layer |
| Rare tokens get few training examples | Each token is seen more often |
Typical vocabularies run from about 32,000 to a few hundred thousand tokens.
Consequences you will notice
- Cost and limits are measured in tokens. English prose averages roughly four characters per token, but this varies. Code, non-English text, and unusual formatting often use more tokens for the same meaning.
- Counting words or letters is hard for a model. It sees
strawberryas one or a few tokens, not as individual letters. Questions about spelling or letter counts ask about structure the model doesn't see directly. - Numbers split unevenly. A long number may be broken into arbitrary chunks, which makes digit-level arithmetic harder.
- Languages differ in efficiency. A tokenizer trained mostly on English text splits other languages into more, smaller pieces. The same sentence then costs more and leaves less room in the context window.
- Under-trained tokens exist. A token can enter the vocabulary because it was frequent in the tokenizer's training data, yet appear rarely in the model's training data. Its embedding is then poorly learned, and inputs containing it can produce erratic output.
Check your understanding
Exercise
Starting from the characters of "aaabdaaabac", which pair does BPE merge first, and what does the sequence look like after that one merge?
Show answer
The pair ('a', 'a') occurs 4 times, more than any other pair, so it merges first into "aa". The sequence becomes: aa, a, b, d, aa, a, b, a, c. Scanning left to right, the first "aaa" yields "aa" followed by "a", because merging consumes two symbols at a time and does not overlap.
Exercise
Why does a byte-level BPE tokenizer never meet an "unknown" input, and what does it pay for that guarantee?
Show answer
Its base vocabulary contains all 256 possible byte values, and any text is a sequence of UTF-8 bytes. Every string can therefore be encoded, even if no merge applies. The cost is that rare characters or scripts that have few learned merges break into several byte tokens, which uses more of the context window and may be harder for the model to handle.
Exercise
A team replaces the tokenizer of a trained model with one that has a different vocabulary, keeping the model weights. Explain what goes wrong.
Show answer
The model's embedding table and output layer are tied to the original token IDs. A new tokenizer assigns different IDs to the same text, so each ID retrieves the embedding of an unrelated token. The model receives meaningless input and its predicted IDs decode to the wrong strings, so the output is nonsense even though nothing raises an error.