Sub topic 2
Vocabularies and the out-of-vocabulary problem
This chapter assumes you can read basic Python (dictionaries, Counter, list comprehensions). It also assumes you know a token is the unit a language model reads, and that you can count and compare frequencies. It covers what a vocabulary is, how a fixed vocabulary breaks on new text, and why that problem motivates the subword methods in the next chapters.
What a vocabulary is
A vocabulary is a fixed table that maps each token string to an integer id. A model never sees strings. It sees ids, and each id selects a row of the embedding matrix, which is a table of learned vectors. The vocabulary also works in reverse: the output layer produces one score per id, and the table turns the winning id back into text.
Three facts about this table shape everything that follows:
- It is fixed before training. You build it from a training corpus, then freeze it. Adding a token later means changing the embedding matrix and the output layer, which usually means retraining or at least extending the model.
- Its size is a cost. The embedding matrix has |V| × d parameters, where |V| is the vocabulary size and d is the vector width. A 100,000-token vocabulary with d = 768 holds 76.8 million parameters, about 307 MB in 32-bit floats. The output layer pays a similar cost, and the softmax (the step that turns scores into probabilities) runs over all |V| ids at every prediction.
- It contains more than words. Practical vocabularies reserve ids for special tokens such as padding and unknown. The chapter on special tokens covers these in detail. This chapter only needs
[PAD]and[UNK].
Where the problem comes from
Suppose you build the vocabulary from whole words. Words follow a long-tailed distribution, often described by Zipf's law. A few words ("the", "of") account for a large share of all text. Most distinct words are rare, and many occur once.
Two terms matter here:
- A token is one occurrence of a word in running text.
- A type is one distinct word.
"the cat saw the dog" has five tokens and four types.
A second regularity, Heaps' law, says the number of types keeps growing as you read more text. It grows roughly as N^β for N tokens, with β often between 0.4 and 0.6 for English. The growth never stops, because new names, typos, numbers, and inflected forms keep appearing. Languages with rich morphology, such as Finnish or Turkish, produce many more types per token. One verb can have thousands of surface forms.
A fixed vocabulary cannot list every type. A word that is not in the table is out of vocabulary (OOV). A model must still produce an id for it, so the usual rule is to map it to a single [UNK] token.
Measuring it in code
The script below builds a word-level vocabulary from a tiny corpus, encodes unseen text, and reports the OOV rate. It then shows a second strategy, falling back to characters, which keeps more information than [UNK].
from collections import Counter
train_text = "the cat sat on the mat the dog sat on the log"
test_text = "the dog sat on the mat while the cats watched"
def build_vocab(text, min_freq=1, specials=("[PAD]", "[UNK]")):
counts = Counter(text.split())
words = [w for w, c in counts.most_common() if c >= min_freq]
return {tok: i for i, tok in enumerate(list(specials) + words)}
def encode(text, vocab, unk="[UNK]"):
return [vocab.get(w, vocab[unk]) for w in text.split()]
vocab = build_vocab(train_text)
ids = encode(test_text, vocab)
oov = sum(1 for i in ids if i == vocab["[UNK]"])
print(len(vocab), ids)
print(f"OOV rate: {oov / len(ids):.2%}")
# Strategy 2: fall back to characters for unknown words.
char_vocab = set(train_text.replace(" ", ""))
def encode_fallback(text, word_vocab, chars, unk="[UNK]"):
out = []
for w in text.split():
if w in word_vocab:
out.append(w)
else:
out.extend(c if c in chars else unk for c in w)
return out
print(encode_fallback("the cats watched", vocab, char_vocab))Running it prints:
9 [2, 7, 3, 4, 2, 6, 1, 2, 1, 1]
OOV rate: 30.00%
['the', 'c', 'a', 't', 's', '[UNK]', 'a', 't', 'c', 'h', 'e', 'd']Read the output carefully:
- The vocabulary has 9 entries: 2 specials and 7 word types.
- Id 1 is
[UNK]. Three of the ten test tokens map to it: "while", "cats", and "watched". The model cannot tell these three words apart. - In the fallback encoding, "cats" becomes four known characters, so its spelling survives. "watched" still loses its "w", because "w" never appeared in the training text. Character fallback is only as complete as the character set.
Why `[UNK]` hurts
Replacing a word with [UNK] has several costs.
- Lost information. "Dr. Okonkwo", "Dr. Smith", and "Dr. Xu" may all become "Dr. [UNK]". The model cannot copy the name to its output or reason about it.
- Shared, noisy embedding. Every OOV word shares one vector. That vector is trained on a mixture of unrelated rare words, so it carries little meaning.
- Poor generation. A model that has only seen
[UNK]in its targets can learn to emit[UNK]. Output with literal[UNK]in it is a known failure of older word-level translation and summarisation systems. - Missed morphology. "watched" is not related to "watch" or "watches" in a word-level table. Each form is a separate row, and a form never seen in training gets nothing.
Ways to handle OOV words
Each strategy trades vocabulary size against sequence length and information loss.
| Strategy | How it works | Main cost |
|---|---|---|
| Single `[UNK]` | Map every missing word to one id | Loses the word entirely |
| Bigger word vocabulary | List more words, for example 500,000 | Large embedding and softmax cost, and new words still appear |
| Character-level model | Use characters as the only tokens | No OOV for known scripts, but sequences are 4 to 6 times longer for English |
| Character fallback (as above) | Spell unknown words out | Mixed sequences, and unseen characters still become `[UNK]` |
| Subword units | Split rare words into frequent pieces | Needs a training algorithm; this is the subject of the following chapters |
| Byte-level units | Use the 256 byte values as the base alphabet | Never OOV, but non-Latin text costs more tokens |
Subword methods sit between the word and character extremes. Frequent words stay whole, so sequences stay short. Rare words are built from reusable pieces, so almost nothing is unknown. The later chapters on BPE, WordPiece, and the unigram model are different ways to choose those pieces.
Choices when building a vocabulary
Even a plain word-level vocabulary involves decisions that change the OOV rate.
- Frequency cutoff. The
min_freqargument above drops words seen fewer than a set number of times. A higher cutoff gives a smaller table and more[UNK]. Words dropped this way are the ones the model could barely learn anyway. - Size cap. Alternatively, keep the top N words by count. The two rules produce different tables and different OOV rates.
- Case and normalisation. Keeping "The" and "the" separate doubles many entries. Lowercasing merges them but loses the distinction between "Apple" and "apple". The next chapter covers these choices.
- Training data. The vocabulary reflects the corpus that built it. A table built from news will have a high OOV rate on medical text or source code.
Measuring OOV honestly
Report the OOV rate on text the vocabulary has never seen, and say which unit you counted.
- Token OOV rate is OOV tokens divided by all tokens. In the example it is 3 of 10, or 30%. It reflects how often a model hits
[UNK]while reading. - Type OOV rate is OOV types divided by all distinct types. It is usually much higher than the token rate, because the missing words are the rare ones that appear once.
A system can show a token OOV rate of 2% and a type OOV rate of 30% on the same text. The 2% looks harmless, but the missing words are often the content words that carry the meaning: names, technical terms, and rare inflections. Report both, and check which kinds of words fall into [UNK].
Common errors
- Treating
[UNK]as harmless because it is rare. Check what the missing words are before judging the rate. - Mixing vocabularies. A model trained with one id table and run with another gives wrong embeddings without raising any error. Ids are only meaningful relative to the table that produced them.
- Forgetting the specials. In the script,
[PAD]takes id 0 and[UNK]takes id 1, so word ids start at 2. Leaving them out shifts every id. - Assuming a bigger table fixes it. Growing the word vocabulary lowers the OOV rate slowly, because of the long tail, while parameters and softmax cost grow linearly.
Exercise
A word-level vocabulary is evaluated on a test document with 1,000 tokens and 400 distinct word types. After encoding, 30 tokens map to [UNK], and those 30 tokens come from 24 distinct word types. Compute the token OOV rate and the type OOV rate, and explain why they differ so much.
Show answer
Token OOV rate = 30 / 1,000 = 3%. Type OOV rate = 24 / 400 = 6%. They differ because OOV words are rare ones, so each missing type contributes only a few tokens, while every type counts equally in the type rate. Here the missing words occur about 1.25 times each, while the average type occurs 2.5 times. The 3% token rate understates how many different words the model cannot see.
Exercise
A team builds a 50,000-word vocabulary with embedding width d = 512. How many embedding parameters does it add, and why does doubling the vocabulary to 100,000 words not remove OOV words?
Show answer
50,000 × 512 = 25,600,000 parameters (25.6 million). Doubling to 100,000 words doubles this to 51.2 million. It does not remove OOV words because the number of distinct types keeps growing with the amount of text (Heaps' law): names, typos, numbers, and inflected forms keep appearing. The extra entries only cover rarer words, so the OOV rate falls slowly while the memory and softmax costs rise in proportion.