TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Why Subword Tokenizers

Why Subword Tokenizers

A language model sees integers, not text, so something has to cut text into units and number them. The choice looks like plumbing, but it fixes three numbers that shape the whole model: the vocabulary size VV (the rows of the embedding table and the width of the output softmax), the sequence length nn of a given text (attention costs grow with n2n^2, and the context window is counted in tokens), and the out-of-vocabulary (OOV) rate, the share of text the model cannot represent at all.

Tokens & Tokenization introduced characters, words and BPE as a user of LLMs, and Tokenization and Byte-Pair Encoding gave the algorithm. This lesson measures the trade-offs on an original text, looks at the costs that surprise people in production (other languages, numbers, code), and sets up the next three lessons, which build BPE, WordPiece and Unigram tokenizers from scratch.

Words, characters and bytes on one text

The text is an original description of a day in a bike repair shop (228 words for "training") and a short held-out paragraph about another repair. A word tokenizer gets its vocabulary from the training part; characters and bytes need none.

python · try it yourself
import re
from collections import Counter
train_text = """The repair shop on Harbour Street opens at eight. Mira unlocks the door, switches on the
compressor and reads the notes from yesterday. A courier bike needs new brake pads, a child's bike
has a bent wheel, and an electric cargo bike reports a battery fault. She starts with the brakes,
because the courier is waiting. Old pads come out, new pads go in, and she adjusts the cables until
the levers feel firm. The bent wheel takes longer. She removes the tyre, mounts the rim on the truing
stand and tightens the spokes a quarter turn at a time, listening to the tone of each one. By noon
the wheel spins straight again. The cargo bike is the hardest job of the day. Its display shows error
code 17, which the manual describes as a communication fault between the battery and the motor
controller. Mira cleans the connectors, checks the voltage with a multimeter and updates the firmware.
The error disappears. In the afternoon two customers bring punctures, and a student asks how to
replace a chain. Mira shows him how to find the master link, how to measure wear with a chain gauge
and why a stretched chain wears out the cassette. Before closing she sweeps the floor, orders spare
spokes and writes tomorrow's notes: recheck the cargo bike, call the courier, and order more pads."""
test_text = """On Thursday a tourist rents a tandem and returns it with a squeaking crankset. Mira
disassembles the bottom bracket, regreases the bearings and reinstalls everything. The squeak is gone,
but the derailleur hanger is misaligned, so she straightens it with an alignment gauge."""

def words(t):
    return re.findall(r"\w+|[^\w\s]", t.lower())

train_w, test_w = words(train_text), words(test_text)
vocab = set(train_w)
oov = [w for w in test_w if w not in vocab]
print(f"words: training vocabulary {len(vocab)}, test tokens {len(test_w)}, OOV {len(oov)} ({len(oov) / len(test_w):.0%})")
print("  unseen:", sorted(set(oov))[:12], "...")
chars = set(train_text)
print(f"characters: vocabulary {len(chars)}, test length {len(test_text)}, OOV {sum(c not in chars for c in test_text)}")
b = test_text.encode("utf-8")
print(f"bytes: vocabulary 256, test length {len(b)}, OOV 0")
print(f"sequence length relative to words: characters {len(test_text) / len(test_w):.1f}x, bytes {len(b) / len(test_w):.1f}x")

counts = Counter(train_w)
print("most common:", counts.most_common(6))
print("types seen once:", sum(c == 1 for c in counts.values()), "of", len(counts))
seen, growth = set(), []
for i, w in enumerate(train_w, 1):          # Heaps' law: the vocabulary keeps growing
    seen.add(w)
    if i % 50 == 0:
        growth.append(len(seen))
print("vocabulary size after every 50 tokens:", growth)
words: training vocabulary 141, test tokens 49, OOV 25 (51%)
  unseen: ['alignment', 'bearings', 'bottom', 'bracket', 'but', 'crankset', 'derailleur', 'disassembles', 'everything', 'gone', 'hanger', 'it'] ...
characters: vocabulary 40, test length 274, OOV 0
bytes: vocabulary 256, test length 274, OOV 0
sequence length relative to words: characters 5.6x, bytes 5.6x
most common: [('the', 31), ('.', 15), (',', 15), ('a', 12), ('and', 10), ('bike', 5)]
types seen once: 109 of 141
vocabulary size after every 50 tokens: [38, 63, 91, 115, 138]

The numbers show the classic dilemma:

  • Words give the shortest sequences, but half of the held-out tokens (51 %) were never seen: "crankset", "derailleur", "bearings", and even "but" and "it". The vocabulary also keeps growing with no sign of stopping (38, 63, 91, 115, 138 types after every 50 tokens: Heaps' law, V(N)≈kNβV(N) \approx k N^{\beta} with β\beta around 0.4 to 0.6 for English), and 109 of the 141 types occur only once (Zipf's law: a few words are very frequent, most are rare). A real word vocabulary needs hundreds of thousands of entries and still meets unknown words, typos and names every day.
  • Characters have no OOV problem here and a tiny vocabulary, but each word becomes 5.6 tokens (counting the spaces). The model has to spend layers assembling characters into words before it can do anything with meaning.
  • Bytes (UTF-8) are the extreme: a fixed vocabulary of 256 that can represent any string, with no OOV ever, and for English text the same length as characters.

The cost in numbers

Plug these ratios into a model with d=768d = 768. The embedding table costs V⋅dV \cdot d parameters (and the same again for the output layer if it is not tied); attention costs grow with n2n^2 per layer; and a context window of CC tokens holds CC divided by the tokens per word.

python · try it yourself
# 1,000 English words under each choice, d_model = 768, tokens per word as measured above
d, n_words = 768, 1000
options = {   # name: (vocabulary size, tokens per word)
    "words": (100_000, 1.0), "WordPiece (BERT)": (30_522, 1.22), "byte BPE (GPT-2)": (50_257, 1.25),
    "characters": (100, 5.6), "bytes": (256, 5.6),
}
for name, (V, fert) in options.items():
    n = round(n_words * fert)
    print(f"{name:17s} V = {V:7,d} | embedding {V * d / 1e6:5.2f} M params | {n:4d} tokens |",
          f"attention x{(n / n_words) ** 2:5.2f} | context of 4,096 tokens = {4096 / fert:4.0f} words")
words             V = 100,000 | embedding 76.80 M params | 1000 tokens | attention x 1.00 | context of 4,096 tokens = 4096 words
WordPiece (BERT)  V =  30,522 | embedding 23.44 M params | 1220 tokens | attention x 1.49 | context of 4,096 tokens = 3357 words
byte BPE (GPT-2)  V =  50,257 | embedding 38.60 M params | 1250 tokens | attention x 1.56 | context of 4,096 tokens = 3277 words
characters        V =     100 | embedding  0.08 M params | 5600 tokens | attention x31.36 | context of 4,096 tokens =  731 words
bytes             V =     256 | embedding  0.20 M params | 5600 tokens | attention x31.36 | context of 4,096 tokens =  731 words

Subword vocabularies sit in the middle: 23 to 39 million embedding parameters instead of 77 million, sequences only 22 to 25 % longer than words, about 1.5 times the attention cost of words instead of 31 times for characters, and (as the next sections show) no OOV words. That compromise is why every current LM uses subwords. Byte-level models exist (ByT5, and architectures that group bytes into patches), but they pay for their simplicity with longer sequences or extra machinery.

Subwords: fertility and unseen words

The idea of a subword tokenizer is to keep frequent words whole and split rare words into frequent pieces. Two numbers describe it on a text: the vocabulary size, and the fertility, the average number of tokens per word:

fertility=number of tokensnumber of words\text{fertility} = \frac{\text{number of tokens}}{\text{number of words}}

The recorded example runs two real tokenizers, GPT-2's byte-level BPE (50,257 tokens) and BERT's uncased WordPiece (30,522 tokens), on the same text.

python · try it yourself
import re
from transformers import AutoTokenizer
train_text = """The repair shop on Harbour Street opens at eight. Mira unlocks the door, switches on the
compressor and reads the notes from yesterday. A courier bike needs new brake pads, a child's bike
has a bent wheel, and an electric cargo bike reports a battery fault. She starts with the brakes,
because the courier is waiting. Old pads come out, new pads go in, and she adjusts the cables until
the levers feel firm. The bent wheel takes longer. She removes the tyre, mounts the rim on the truing
stand and tightens the spokes a quarter turn at a time, listening to the tone of each one. By noon
the wheel spins straight again. The cargo bike is the hardest job of the day. Its display shows error
code 17, which the manual describes as a communication fault between the battery and the motor
controller. Mira cleans the connectors, checks the voltage with a multimeter and updates the firmware.
The error disappears. In the afternoon two customers bring punctures, and a student asks how to
replace a chain. Mira shows him how to find the master link, how to measure wear with a chain gauge
and why a stretched chain wears out the cassette. Before closing she sweeps the floor, orders spare
spokes and writes tomorrow's notes: recheck the cargo bike, call the courier, and order more pads."""
test_text = """On Thursday a tourist rents a tandem and returns it with a squeaking crankset. Mira
disassembles the bottom bracket, regreases the bearings and reinstalls everything. The squeak is gone,
but the derailleur hanger is misaligned, so she straightens it with an alignment gauge."""
thanks = {"English": "Thank you very much", "German": "Vielen Dank", "French": "Merci beaucoup",
          "Vietnamese": "Cảm ơn bạn rất nhiều", "Russian": "Большое спасибо", "Greek": "Ευχαριστώ πολύ",
          "Hindi": "बहुत धन्यवाद", "Chinese": "非常感谢", "Japanese": "どうもありがとうございます"}

gpt2 = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")                 # byte-level BPE, 50,257 tokens
bert = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")   # WordPiece, 30,522, lower-cased
n_words = len(train_text.split())
for name, tok in [("GPT-2", gpt2), ("BERT", bert)]:
    n = len(tok(train_text, add_special_tokens=False).input_ids)
    print(f"{name}: {n} tokens for {n_words} words of the repair-shop text, fertility {n / n_words:.2f}")
print("unseen test words:", {w: gpt2.tokenize(" " + w) for w in ["crankset", "derailleur", "regreases"]})

print("tokens for 'thank you very much' (GPT-2 / BERT):")
for lang, s in thanks.items():
    line = f"  {lang:10s} {len(gpt2(s).input_ids):3d} / {len(bert(s, add_special_tokens=False).input_ids):3d}"
    print(line, bert.tokenize(s)[:6]) if lang in ("Vietnamese", "Hindi", "Japanese") else print(line)

for s in ["1234567", "3.14159", "2026-11-22", "error code 17"]:
    print(f"{s!r:15s} GPT-2 {gpt2.tokenize(s)}")
code = "def area(r):\n        return 3.14159 * r ** 2\n"
toks = gpt2.tokenize(code)
print("code:", len(toks), "GPT-2 tokens, of which", toks.count("Ġ"), "are a single space;", toks[5:14])
GPT-2: 284 tokens for 228 words of the repair-shop text, fertility 1.25
BERT: 278 tokens for 228 words of the repair-shop text, fertility 1.22
unseen test words: {'crankset': ['Ġcr', 'anks', 'et'], 'derailleur': ['Ġderail', 'le', 'ur'], 'regreases': ['Ġreg', 're', 'ases']}
tokens for 'thank you very much' (GPT-2 / BERT):
  English      4 /   4
  German       5 /   4
  French       5 /   5
  Vietnamese  25 /   6 ['cam', 'on', 'ban', 'rat', 'nh', '##ieu']
  Russian     19 /  14
  Greek       19 /  13
  Hindi       21 /   9 ['ब', '##ह', '##त', 'ध', '##न', '##य']
  Chinese     10 /   4
  Japanese    16 /  13 ['と', '##う', '##も', '##あ', '##り', '##か']
'1234567'       GPT-2 ['123', '45', '67']
'3.14159'       GPT-2 ['3', '.', '14', '159']
'2026-11-22'    GPT-2 ['20', '26', '-', '11', '-', '22']
'error code 17' GPT-2 ['error', 'Ġcode', 'Ġ17']
code: 23 GPT-2 tokens, of which 7 are a single space; ['Ċ', 'Ġ', 'Ġ', 'Ġ', 'Ġ', 'Ġ', 'Ġ', 'Ġ', 'Ġreturn']

On the English text both have a fertility of about 1.2 (1.25 for GPT-2, 1.22 for BERT): most words are single tokens. Unseen words are no longer a problem; they are split into known pieces: "crankset" becomes cr anks et, "derailleur" derail le ur. The Ġ is GPT-2's visible stand-in for a leading space (byte 32 is mapped to a printable character; Byte-Pair Encoding from Scratch explains the mapping). The pieces are not morphemes: "regreases" becomes reg re ases, not re grease s. Frequency decides the splits, not linguistics.

The multilingual tax

The same phrase, "thank you very much", costs very different amounts in different languages. Part of the cost is already in the encoding: byte-level tokenizers start from UTF-8, which uses 1 byte for ASCII, 2 for most accented Latin letters, Cyrillic and Greek (many Vietnamese letters, such as "ả" and "ễ", take 3), 3 for Devanagari, Chinese and Japanese, and 4 for emoji.

python · try it yourself
import unicodedata
thanks = {"English": "Thank you very much", "German": "Vielen Dank", "French": "Merci beaucoup",
          "Vietnamese": "Cảm ơn bạn rất nhiều", "Russian": "Большое спасибо", "Greek": "Ευχαριστώ πολύ",
          "Hindi": "बहुत धन्यवाद", "Chinese": "非常感谢", "Japanese": "どうもありがとうございます"}

for lang, s in thanks.items():
    b = s.encode("utf-8")
    print(f"{lang:10s} {len(s):3d} characters {len(b):3d} UTF-8 bytes ({len(b) / len(s):.2f} per character)")
for ch in ["e", "é", "ơ", "б", "ध", "感", "😀"]:
    print(repr(ch), unicodedata.name(ch).lower(), "->", list(ch.encode("utf-8")))
English     19 characters  19 UTF-8 bytes (1.00 per character)
German      11 characters  11 UTF-8 bytes (1.00 per character)
French      14 characters  14 UTF-8 bytes (1.00 per character)
Vietnamese  20 characters  29 UTF-8 bytes (1.45 per character)
Russian     15 characters  29 UTF-8 bytes (1.93 per character)
Greek       14 characters  27 UTF-8 bytes (1.93 per character)
Hindi       12 characters  34 UTF-8 bytes (2.83 per character)
Chinese      4 characters  12 UTF-8 bytes (3.00 per character)
Japanese    13 characters  39 UTF-8 bytes (3.00 per character)
'e' latin small letter e -> [101]
'é' latin small letter e with acute -> [195, 169]
'ơ' latin small letter o with horn -> [198, 161]
'б' cyrillic small letter be -> [208, 177]
'ध' devanagari letter dha -> [224, 164, 167]
'感' cjk unified ideograph-611f -> [230, 132, 159]
'😀' grinning face -> [240, 159, 152, 128]

In the GPT-2 counts of the recorded example, English needs 4 tokens and Vietnamese 25, Hindi 21, Russian and Greek 19. GPT-2's vocabulary was trained on mostly English web text, so for other scripts it has few merges and falls back towards single bytes. The consequence for users: the same content costs several times as many tokens in Hindi or Vietnamese, which means a higher bill, a shorter effective context and slower generation, and usually worse quality too. Petrov et al. (2023, arXiv:2305.15425) found that the same text can differ by up to 15 times in token count between languages. Multilingual models fix this by training the tokenizer on balanced multilingual data with a larger vocabulary (mBERT has about 120,000 tokens, XLM-R and mT5 about 250,000).

BERT's counts look cheaper, but look at what it did. Its uncased tokenizer strips accents: Vietnamese "Cảm ơn bạn rất nhiều" becomes cam on ban rat nh ##ieu, which is a different and ambiguous text, the Hindi vowel signs are dropped (ब ##ह ##त for "बहुत"), and Japanese "ど" becomes "と". The normalisation that helps English accuracy is lossy elsewhere. Check what a tokenizer's normaliser does before using it on a language (Text Normalisation shows the Unicode side).

Numbers and code

Numbers. GPT-2 cuts "1234567" into 123 45 67 and "3.14159" into 3 . 14 159: the chunks depend on which digit strings happened to be frequent, so the same digit gets different tokens in different numbers, and arithmetic becomes harder to learn. Newer tokenizers split digits deliberately: one token per digit (Llama 1 and 2), or groups of up to three digits (the GPT-4 tokenizer cl100k_base, Llama 3).

Code. The second line of the Python snippet is indented by 8 spaces. GPT-2 has no tokens for runs of spaces, so it spends 7 single-space Ġ tokens on them, with the eighth space attached to Ġreturn: 23 tokens for two short lines. Tokenizers built for code add tokens for runs of spaces and tabs, which can cut code token counts substantially. When you estimate the cost of a code assistant, measure with the model's own tokenizer.

How to choose

Unit VV Tokens per English word OOV Typical use
Words 10510^5 to 10610^6 1 yes classic NLP, bag of words, n-gram LMs
Characters about 100 (English) to 1.5⋅1051.5 \cdot 10^5 (all of Unicode) 5 to 6 rare characters spelling, OCR post-processing, small char models
Bytes 256 5 to 6 (more for other scripts) never byte-level models, the base of byte-level BPE
Subwords (BPE, WordPiece, Unigram) 3⋅1043 \cdot 10^4 to 2.5⋅1052.5 \cdot 10^5 1.1 to 1.5 for English, more elsewhere never with a byte fallback every modern LM

Subword tokenizers come in three families. BPE merges the most frequent pair of symbols, again and again (next lesson). WordPiece merges the pair that most increases the likelihood of the training data, and Unigram starts from a large vocabulary and prunes it under a probabilistic model (WordPiece and Unigram Tokenizers). All three are fitted on a training corpus, like any other preprocessing step, and the tokenizer is then frozen together with the model.

Pitfalls

  • Comparing models by token-level metrics across tokenizers. Perplexity per token and "tokens per second" are not comparable between tokenizers; normalise per word or per byte.
  • Estimating cost with the wrong tokenizer. Counting words, or using GPT-2's tokenizer for a model with a different vocabulary, can be off by a factor of 2 or more for non-English text and code. Count with the deployed model's tokenizer (see Cost and Latency).
  • A tokenizer trained on the wrong data. A vocabulary fitted on English news fragments medical terms, code or another language into many pieces. Train or choose a tokenizer on data like yours.
  • Lossy normalisation. Lower-casing and accent stripping change the text, and the model cannot recover what was removed.
  • Changing the tokenizer after training. The embedding rows are tied to token ids. A different tokenizer means a different model (adding a few tokens is possible, see Tokenizers in Practice).

Practice

  1. A model has a context window of 8,192 tokens. How many English words fit with GPT-2's fertility of 1.25, and how many Vietnamese "thank you very much" phrases fit, using the recorded GPT-2 count?
  2. Why does a byte-level tokenizer never produce an unknown token, and why can a character-level tokenizer still produce one?
  3. From the first example: what fraction of the training types are hapax legomena (seen once)? What does that imply for a word-level model trained on this text?
  4. You are building a support bot for customers who write in Hindi and English. Name two measurements to make before choosing a tokenizer or a model.
  5. Using V⋅dV \cdot d, how many parameters does a 250,000-token vocabulary cost at d=1024d = 1024 with untied input and output embeddings?
Answers
  1. 8192/1.25≈65548192 / 1.25 \approx 6554 words. Vietnamese: 8192/25≈3278192 / 25 \approx 327 phrases of 5 words, about 1,640 words, so the same window holds about 4 times fewer Vietnamese words.
  2. Every string has a UTF-8 encoding, and every byte value 0 to 255 is in the vocabulary. A character vocabulary contains only the characters seen in training; a new emoji, a rare CJK character or a symbol is unknown (unless the tokenizer falls back to bytes).
  3. 109/141≈0.77109 / 141 \approx 0.77. Most word types have a single example, so a word-level model cannot learn good embeddings for them, and every new text brings more of them.
  4. Fertility per language on real customer messages (tokens per word, or tokens per character), and task quality on Hindi and English test sets. Also check that normalisation keeps the Hindi text intact (the decode round trip) and the cost per conversation in each language.
  5. 250,000⋅1024=256250{,}000 \cdot 1024 = 256 million per table, 512 million for input and output together, often more than the rest of a small model.

Test yourself

On the repair-shop text, what OOV rate did the word tokenizer have on the held-out paragraph?

  1. 0 %
  2. About 5 %
  3. 51 %
  4. 100 %

What is fertility in tokenization?

  1. The number of merges learned
  2. The average number of tokens per word
  3. The vocabulary size
  4. The share of unknown tokens

Why does 'thank you very much' cost 25 GPT-2 tokens in Vietnamese but 4 in English?

  1. Vietnamese words are longer
  2. GPT-2's BPE was trained mostly on English, so it has few merges for Vietnamese characters and falls back towards bytes, and accented letters take 2 or more UTF-8 bytes
  3. Vietnamese uses no spaces
  4. GPT-2 cannot encode Vietnamese

What happened to Vietnamese text in BERT's uncased tokenizer?

  1. It became [UNK]
  2. Accents were stripped ('cam on ban rat ...'), a lossy change
  3. It was split into bytes
  4. Nothing

Roughly how much larger is the attention score matrix for character tokens than for word tokens on English text, with 5.6 characters per word?

  1. 5.6 times
  2. About 11 times
  3. About 31 times
  4. The same