Sub topic 1
Why language models need subword units
A language model works on numbers, not text. Before any model sees a sentence, a tokeniser cuts it into pieces called tokens and maps each piece to an integer id. This chapter explains why the best pieces are usually neither whole words nor single characters, but subwords: units between the two, such as un, believ and ably.
Prerequisites
This chapter assumes you have:
- Basic Python, including dictionaries, tuples and loops.
- A rough idea of a token as the input unit of a language model.
- Basic counting and frequency statistics, such as "how often does this word appear in a corpus".
You do not need any neural network background beyond knowing that a model looks up a vector for each token id.
What a tokeniser does
A tokeniser has two jobs. It splits text into tokens, and it maps each token to an id using a fixed table called the vocabulary. The model then replaces each id with a learned vector, so the vocabulary size sets the number of rows in the model's embedding matrix.
The vocabulary is fixed before the language model is trained. If a piece of text contains something the vocabulary cannot express, the model never sees it properly. This is why the choice of unit matters.
Three granularities
There are three obvious ways to cut text.
- Word-level: one token per word, found by splitting on spaces and punctuation.
- Character-level: one token per character.
- Subword-level: pieces learned from data. Common words stay whole, and rare words split into reusable fragments.
| Unit | Vocabulary size | Sequence length | Unseen words | Main weakness |
|---|---|---|---|---|
| Words | Very large (hundreds of thousands) | Short | Cannot be represented | Out-of-vocabulary words, huge embedding table |
| Characters | Tiny (tens to thousands) | Very long | Always representable | Slow, and each token carries little meaning |
| Subwords | Moderate (often 30,000 to 100,000) | Close to word count | Spelled out from smaller pieces | Needs a training step, and splits can look odd |
Problems with word-level tokens
Word frequencies follow a heavy-tailed pattern known as Zipf's law. A few words such as "the" are extremely common, and most distinct words are rare. A word-level vocabulary has to make a hard choice:
- Keep every word seen in training. The vocabulary grows without bound, and most rows of the embedding table are trained on only a handful of examples.
- Cut the vocabulary at the top N words. Every other word becomes a single unknown token, usually written
[UNK]. The model loses the information in names, technical terms, typos and new coinage.
Word-level tokens also hide structure. "play", "plays", "played" and "playing" get four unrelated ids, so the model must learn from scratch that they share a meaning. Languages with rich morphology, such as Finnish or Turkish, produce thousands of forms per verb. They make this problem far worse than English does.
Problems with character-level tokens
Characters solve the unseen-word problem, because any word is a sequence of known characters. The cost is length. English averages roughly five to six characters per word including the space, so a character-level sequence is about five times longer than a word-level one.
Self-attention, the core operation in Transformer models, compares every position with every other position, so its cost grows with the square of the sequence length. A sequence five times longer costs about 25 times more attention computation. A fixed context window of, say, 2,048 tokens also covers far less text. And a single character such as t carries almost no meaning, so the model must spend layers assembling letters into words before it can do anything useful.
The subword compromise
Subword tokenisers keep frequent words as single tokens and break rare words into pieces that appear in many other words. The word "unbelievably" can become un, believ, ably, and each of those pieces is common enough to have a well-trained vector. A word the tokeniser has never seen can still be built from known pieces, and in the worst case from single characters.
A worked example
The following code is a toy, not a real tokeniser. It shows the three granularities on one sentence. The vocabulary is written by hand. A real tokeniser learns it from a corpus, which later chapters cover.
import string
def toy_segment(word, vocab):
"""Greedy longest-match split of one word using a hand-made vocabulary."""
pieces = []
start = 0
while start < len(word):
for end in range(len(word), start, -1):
if word[start:end] in vocab:
pieces.append(word[start:end])
start = end
break
else:
raise ValueError(f"cannot encode {word[start:]!r}")
return pieces
# Single letters guarantee that every lowercase word can be encoded.
vocab = {"un", "believ", "ably", "happy"} | set(string.ascii_lowercase)
sentence = "unbelievably unhappy"
words = sentence.split()
chars = list(sentence)
subwords = [piece for w in words for piece in toy_segment(w, vocab)]
print(len(words), len(chars), len(subwords))
print(subwords)The output is:
2 20 5
['un', 'believ', 'ably', 'un', 'happy']Words give 2 tokens, characters give 20 (the space counts), and subwords give 5. The subword split also reuses un across two words, so whatever the model learns about un carries over.
Now compare what happens to an unseen word under a word-level vocabulary:
train = "the cat sat on the mat the cat ate the rat".split()
test = "the cat sat on the sofa".split()
word_vocab = set(train)
unknown = [w for w in test if w not in word_vocab]
print(len(word_vocab), unknown)This prints 7 ['sofa']. The word-level model has 7 known words and has no way to represent "sofa". Replaced by [UNK], it looks identical to every other missing word. The subword approach would instead spell it out from pieces, which is what the next chapters formalise.
The cost model
Three quantities pull against each other, and the choice of unit sets all three.
- Embedding and output size. The embedding matrix has V rows of d dimensions, so with V = 50,000 and d = 768 it holds 38.4 million parameters. A word-level V of 500,000 at the same d would hold 384 million. The final layer that predicts the next token also scores V candidates at every step, so a large V slows both training and generation.
- Sequence length. Fewer, larger tokens mean shorter sequences, cheaper attention and more text per context window.
- Statistical strength. Each token needs enough training examples for its vector to be good. Whole rare words fail this test. Subword pieces pass it because they are shared.
The following diagram shows where the three units sit.
Edge cases and common errors
- Tokens are not words. A token count is not a word count. For English, subword tokenisers typically produce somewhat more tokens than words, often around 1.3 to 1.5 per word. The ratio varies by language and domain, and code and non-English text can be much worse.
- The vocabulary is frozen. After training, the tokeniser's vocabulary cannot grow without changing the model's embedding table. New slang or product names will be split into smaller pieces, not added as new tokens.
- Odd splits are normal. Pieces such as
believare not dictionary morphemes. They are whatever fragments a statistical procedure found useful, so do not expect linguistically clean boundaries. - A tokeniser must match its model. A model trained with one vocabulary reads ids as meaning specific pieces. Using a different tokeniser at inference time yields valid-looking ids that mean the wrong things.
- Unknown tokens still exist. If the base units are characters from a fixed alphabet, a character outside that alphabet, such as a rare emoji or script, can still become
[UNK]. Later chapters show how byte-level approaches remove this gap.
How this chapter fits the rest
This chapter fixed the problem: choose a unit that keeps the vocabulary manageable, keeps sequences short, and still handles words never seen before. The next chapters cover how vocabularies and unknown tokens are managed, how text is normalised before splitting, and then the learning procedures themselves.
Exercise
A word-level model uses a vocabulary of 200,000 words with 512-dimensional embeddings. A subword model uses 32,000 pieces with the same embedding size. How many embedding parameters does each model have, and what is the main cost the subword model pays in return?
Show answer
The word-level model has 200,000 × 512 = 102,400,000 embedding parameters. The subword model has 32,000 × 512 = 16,384,000. The subword model pays with longer sequences: the same text splits into more tokens than words, so attention costs more and each context window covers less text.
Exercise
Using the toy vocabulary from the worked example (un, believ, ably, happy and the letters a to z), what does toy_segment("unhappy", vocab) return, and what would it return for the word "bunhappy"?
Show answer
For "unhappy" it returns ['un', 'happy']. For "bunhappy", no multi-letter piece matches at position 0, so it takes the single letter 'b', then continues with 'un' and 'happy', giving ['b', 'un', 'happy']. The single-letter fallback is what lets the tokeniser handle words it has not seen.