Sub topic 12
Choosing a Vocabulary Size
Prerequisites and the main trade-off
This chapter assumes you know what tokens are and have basic Python, dictionaries, loops, and frequency counts. You should also know that BPE, WordPiece, and SentencePiece turn text into a sequence of vocabulary entries.
Vocabulary size is the number of entries a tokenizer can use. It includes ordinary tokens and often special tokens such as padding, unknown, beginning-of-sequence, and end-of-sequence markers.
A small vocabulary creates shorter entries, so text becomes longer token sequences. A large vocabulary stores more whole words and frequent subwords, so sequences become shorter. However, a large vocabulary uses more memory and may learn rare entries that generalize poorly.
| Vocabulary choice | Typical benefit | Typical cost |
|---|---|---|
| Small | Lower embedding and output-layer memory | Longer sequences and more computation |
| Medium | Balanced coverage and sequence length | Requires validation |
| Large | Shorter sequences for frequent text | More parameters and rare, brittle tokens |
How vocabulary size affects a model
The embedding table contains one vector per vocabulary entry. If the vocabulary has size V and the embedding width is d, the table has approximately V × d parameters. The output layer can have a similar cost when the model predicts the next token with a full softmax.
Sequence length also matters. Self-attention usually becomes more expensive as the sequence grows. A tokenizer that reduces a sequence from 1,000 tokens to 500 tokens can reduce attention work substantially, depending on the model architecture.
A large vocabulary does not always produce better compression. It may contain many entries seen only a few times during training. Such entries can memorize spelling, names, or formatting without helping the model understand related text.
Measure tokenization instead of guessing
Compare candidate vocabulary sizes on held-out text, not only on the training corpus. Useful measurements include:
- Mean and percentile sequence length.
- Fertility, or average tokens per word.
- The fraction of text represented by unknown tokens.
- Coverage of scripts, languages, numbers, and punctuation.
- The number of very rare vocabulary entries.
- Training and inference speed.
- Downstream task quality.
A fair comparison uses the same normalization rules, pre-tokenization, special tokens, and maximum sequence length. Otherwise, the vocabulary size is not the only changing factor.
def longest_match(text, vocabulary):
tokens = []
position = 0
while position < len(text):
matches = [
token for token in vocabulary
if text.startswith(token, position)
]
if not matches:
tokens.append("<unk>")
position += 1
else:
token = max(matches, key=len)
tokens.append(token)
position += len(token)
return tokens
samples = ["lower", "lowest", "newer", "newest"]
vocabularies = {
8: {"low", "er", "est", "new", "er", "est", "l", "o", "w"},
12: {"low", "lower", "lowe", "new", "newer", "est", "er", "l", "o", "w"},
}
for size, vocabulary in vocabularies.items():
lengths = [len(longest_match(word, vocabulary)) for word in samples]
average = sum(lengths) / len(lengths)
print(f"declared size {size}: average tokens = {average:.2f}")This toy experiment uses longest matching, so it resembles WordPiece encoding but is not a complete implementation of any production tokenizer. In a real experiment, train each tokenizer on the same corpus and report results for several language groups.
Multilingual and domain-specific data
Vocabulary size interacts with the training data. If English dominates a multilingual corpus, a large vocabulary may be filled with English words while other languages receive character-level fragments. Increasing the size alone may worsen fairness across languages.
Balanced sampling, byte-level fallback, or a shared subword vocabulary can improve coverage. Inspect token lengths separately for each language and script. Also test code, scientific notation, dates, URLs, emoji, and user-generated spelling. These forms often expose weaknesses hidden by ordinary prose.
A practical selection process
- Choose several candidate sizes, such as 8,000, 16,000, 32,000, and 64,000.
- Train each tokenizer using identical data and preprocessing.
- Measure compression, unknown handling, memory, and speed.
- Check rare-token counts and per-language sequence lengths.
- Evaluate the downstream model under the same token budget.
- Select the smallest vocabulary that meets quality and latency targets.
Exercise
Why can increasing vocabulary size reduce quality for a multilingual model?
Show answer
Frequent data from one language can consume many vocabulary entries, leaving other languages with longer and less useful fragments. Evaluate coverage and sequence length per language before increasing the size.