Sub topic 12
Choosing a vocabulary size
This chapter assumes you have read the earlier chapters on BPE, WordPiece and SentencePiece. You should know that BPE builds its vocabulary by merging frequent pairs, that WordPiece stores continuation pieces with a ## prefix, and that SentencePiece can train either a BPE or a unigram model. Basic Python is enough for the code.
Every subword tokeniser needs a target vocabulary size, and the algorithm does not choose it for you. The number sets a trade-off between sequence length, model size, and how well each token is trained. This chapter covers what the number counts, what a larger or smaller value costs, and a procedure for choosing one.
What the number counts
The same name, "vocabulary size", means slightly different things in each tool.
| Tokeniser | What the vocabulary contains | Relationship to the setting |
|---|---|---|
| Character-initialised BPE | Base characters, plus one new symbol per merge | size = alphabet + number of merges (+ special tokens) |
| Byte-level BPE (GPT-2 style) | 256 byte symbols, plus merges, plus special tokens | GPT-2: 256 + 50,000 merges + 1 end-of-text token = 50,257 |
| WordPiece (BERT style) | Whole words, `##` pieces, single characters, special tokens | You set the target total. BERT-base uses 30,522 |
| SentencePiece | Pieces, plus `<unk>`, `<s>`, `</s>` and any user-defined symbols | `vocab_size` is the total, including those special entries |
Two consequences follow. When you compare published numbers, check whether special tokens and the 256 byte symbols are counted. In SentencePiece, a vocab_size of 8000 does not give you 8000 learned pieces. Some of the entries are reserved.
Sequence length falls as the vocabulary grows
More merges mean that more frequent strings become single tokens, so the same text needs fewer tokens. The script below reuses the BPE trainer from the BPE chapter. It trains with different numbers of merges and counts the tokens needed to write out the training corpus.
from collections import Counter
def get_pair_counts(words):
pairs = Counter()
for symbols, freq in words.items():
for a, b in zip(symbols, symbols[1:]):
pairs[(a, b)] += freq
return pairs
def merge_pair(words, pair):
merged = Counter()
for symbols, freq in words.items():
out = []
i = 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
merged[tuple(out)] += freq
return merged
corpus = ("low " * 5 + "lower " * 2 + "newest " * 6 + "widest " * 3).split()
base = Counter(tuple(w) + ("</w>",) for w in corpus)
alphabet = {s for symbols in base for s in symbols}
def train(num_merges):
words = base
n_done = 0
for _ in range(num_merges):
pairs = get_pair_counts(words)
if not pairs:
break
best = max(pairs, key=pairs.get)
words = merge_pair(words, best)
n_done += 1
total_tokens = sum(len(s) * f for s, f in words.items())
return len(alphabet) + n_done, total_tokens
print("merges vocab tokens tokens/word")
for n in [0, 3, 6, 10, 15, 20]:
vocab, tokens = train(n)
print(f"{n:6d} {vocab:5d} {tokens:6d} {tokens / len(corpus):.2f}")With zero merges the vocabulary is the 11 base symbols and the corpus takes 95 tokens. Once every word has become a single token, the corpus takes 16 tokens, one per word, and the pair counter is empty, so training stops early. Real corpora never reach that point. The useful observation is the shape of the curve. The early merges save the most tokens, and later merges each save fewer, because they cover rarer strings.
What a larger vocabulary costs
Model size and compute
The embedding matrix has one row per token, so it has V × d parameters for vocabulary size V and hidden size d. If the output projection is not tied to the embedding, it adds another V × d. The softmax over the vocabulary also runs once per predicted token, so its cost grows linearly with V.
def embedding_params(vocab_size, hidden_size, tied=True):
per_matrix = vocab_size * hidden_size
return per_matrix if tied else 2 * per_matrix
for v in (32_000, 128_000):
print(v, embedding_params(v, 4096), embedding_params(v, 4096, tied=False))For a hidden size of 4096, a 32,000-token vocabulary gives 131,072,000 embedding parameters. A 128,000-token vocabulary gives 524,288,000. For a small model this is a large share of the total. For a very large model it is a small share, which is one reason newer large models have moved to bigger vocabularies.
Undertrained tokens
Token frequencies follow a heavy-tailed distribution. A large vocabulary adds many tokens that appear only a handful of times in the training data. Their embeddings receive few gradient updates and stay close to their random initialisation. At inference, an input that contains one of these tokens can make the model behave erratically. Practitioners sometimes call such tokens "glitch tokens". They also arise when a tokeniser is trained on data that differs from the model's training data, for example a tokeniser that saw a scraped forum dump that the model never trained on.
What a smaller vocabulary costs
A small vocabulary produces long sequences. This has three effects:
- Attention cost. Self-attention cost grows roughly with the square of sequence length, so longer sequences cost more per document.
- Context budget. A fixed context window holds less text. A 4,096-token window covers less of a document if each word takes three tokens instead of one and a half.
- Harder learning. The model must learn to compose meaning across many small pieces. Words that a larger vocabulary holds as one token have to be assembled from several.
Multilingual coverage
A shared vocabulary is divided among all languages in the training data. If the training sample is mostly English, English gets long, merged tokens and other languages get short fragments or individual bytes. The effect is that the same sentence costs many more tokens in a language with less representation. This matters for cost, because many APIs bill per token, and for quality, because the context window holds less text.
Two things help. Increase the vocabulary size so that more languages can earn whole-word tokens. Balance the training sample so that each language contributes enough text. XLM-R's SentencePiece vocabulary of about 250,000 entries reflects this reasoning, where many English-only models use 30,000 to 50,000.
A procedure for choosing
- Fix the data. Collect a training sample that matches the text the model will see, in the proportions you want each language or domain represented.
- Train candidates. Train tokenisers at several sizes, for example 16k, 32k, 64k and 128k, on the same sample with the same algorithm.
- Measure on held-out text. For each language or domain, compute tokens per word, or bytes per token. This is often called fertility when expressed as tokens per word. Use text the tokeniser did not train on.
- Look at the tail. Count how many vocabulary entries occur fewer than, say, 100 times in the training corpus. A large number suggests the vocabulary is too big for the data.
- Price the model. Compute the embedding and output parameters at each size relative to the model's total.
- Find the knee. Choose the point where extra vocabulary stops reducing tokens per word by a meaningful amount.
- Round for hardware. Pad the final embedding table to a multiple of 64 or 128 so matrix multiplications use hardware efficiently. nanoGPT, for example, pads GPT-2's 50,257 to 50,304. The padding rows are never produced by the tokeniser.
Practical errors
- Setting the size too high for the corpus. SentencePiece raises an error such as "Vocabulary size too high" when the corpus cannot support the requested number of pieces. Reduce
vocab_size, add training data, or sethard_vocab_limit=Falsefor unigram models, which lets the trainer stop at a smaller vocabulary. - Comparing sizes across tokenisers without checking the counting rules. The table near the start shows that special tokens and bytes may or may not be included.
- Changing the vocabulary after training. The embedding rows are tied to specific token ids. A different vocabulary needs a new model or a careful embedding transfer, so settle the size before pretraining.
- Judging only by English. A size that looks fine on English text can hide poor fertility in other languages. Measure each language you care about.
- Training the tokeniser on unrepresentative text. This produces the undertrained tokens described above.
Summary of the trade-off
| Choice | Sequence length | Embedding and softmax cost | Rare-token training | Multilingual coverage |
|---|---|---|---|---|
| Smaller vocabulary | Longer | Lower | Better, since tokens are frequent | Weaker for low-resource languages |
| Larger vocabulary | Shorter | Higher | Worse, since many tokens are rare | Stronger, if the data is balanced |
Exercise
A team trains a SentencePiece unigram tokeniser with vocab_size=64000 on 5 MB of text and gets an error that the vocabulary size is too high. Give two ways to fix this and say what each one changes.
Show answer
Reduce vocabsize to a value the corpus can support, or add more training text. Reducing the size gives a smaller vocabulary and longer sequences. Adding data keeps the target size but increases the number of distinct substrings available. For a unigram model, setting hardvocab_limit=False also lets the trainer accept a smaller vocabulary than requested.
Exercise
A model has hidden size 2048 and untied input and output matrices. How many embedding-related parameters does a 50,000-token vocabulary add, and how many does a 100,000-token vocabulary add?
Show answer
Each matrix has V × 2048 parameters, and there are two of them. For 50,000 that is 2 × 50,000 × 2048 = 204,800,000. For 100,000 it is 409,600,000.
Exercise
You compare two tokenisers on held-out text. Tokeniser A (32k vocabulary) needs 1.4 tokens per word in English and 3.8 in Swahili. Tokeniser B (128k vocabulary, balanced training sample) needs 1.3 in English and 1.9 in Swahili. Which is better for a Swahili application, and what are the costs of choosing it?
Show answer
Tokeniser B is better for Swahili, since it needs about half as many tokens per word, so contexts hold more text and API costs are lower. The costs are a larger embedding and output layer, a more expensive softmax, and more rare tokens that may be undertrained. Check the frequency of the rarest entries before committing.