On this page
Your API bill is priced in tokens, your context window is measured in tokens, and the model itself sees nothing else. Yet most engineers first meet the tokenizer on the day it hurts them: a non-English prompt that consumes fifteen times as many tokens as its English translation,[1] or a dependency bump after which a healthy model speaks nonsense while every tensor shape still checks out.
Before a language model sees a single word of rain falls softly, its tokenizer slices the text into integer IDs. Each integer is a model-local row address in a learned embedding table . If ID 5 meant falls during training and a swapped tokenizer assigns ID 5 to soft, every shape assertion passes while the model silently reads the wrong learned vectors. Three subword algorithms power modern tokenizers: Byte-Pair Encoding (BPE), WordPiece, and Unigram LM (with SentencePiece packaging BPE and Unigram alongside normalization and reversible whitespace encoding).
![Four token pieces rain (ID 2), ·falls (ID 5), ·soft (ID 1), and ly (ID 6) index directly into an 8-by-3 embedding matrix W_E. Curved arrows trace each token ID to its corresponding highlighted row in W_E (leaving rows 0, 3, 4, and 7 unused) and gather those four rows in sequence order into the 4-by-3 model input tensor E[ids].](https://assets.leetllm.com/v1/021fff835bdc/fundamentals/tokenization-bpe-wordpiece-sentencepiece/illustrations/_generated/tokenization_pipeline_dark.png)
Why subwords win: words vs. characters vs. subwords
Every tokenizer first picks its granularity, and both extremes break in opposite ways:
- Whole words explode vocabulary memory (, untied FP16 input and output tables cost before layer 0) and collapse unseen words, typos, or code identifiers (
deserialize_payload) into<UNK>. - Raw characters or bytes eliminate
<UNK>(only 256 byte values cover all UTF-8), yet stretchrain falls softlyfrom 4 subwords to 17 characters, inflating dense attention grids from cells per head to cells ( more pairs). - Subwords keep common strings whole (
rain,falls), decompose rare words into reusable pieces (soft+ly), and lock vocabulary size before model training begins.
![Granularity comparison on "rain falls softly" (17 characters): characters take 17 positions (289 dense attention cells), subwords take 4 pieces (16 cells), and whole words take 3 pieces (9 cells, risking [UNK] on unseen words).](https://assets.leetllm.com/v1/b4ec96dd6e44/fundamentals/tokenization-bpe-wordpiece-sentencepiece/illustrations/_generated/token_granularity_tradeoff_dark.png)
Keep three components distinct: the vocabulary (pieces and integer IDs), the segmentation algorithm (how text maps to pieces), and the complete tokenizer (normalization, pre-tokenization boundaries, special tokens, and decoding). Tokenizer training happens once before model training; inference replays frozen rules.
Byte Pair Encoding (BPE): bottom-up frequency merges
Originally a 1994 compression trick by Philip Gage[2] and adapted to neural translation by Sennrich et al.,[3] BPE grows a vocabulary greedily from the bottom up: start from base characters (or 256 raw UTF-8 bytes in GPT-2's byte-level BPE[4]), count adjacent pairs weighted by word frequency, merge the top pair into a new symbol, recount, and repeat until reaching . At inference time, BPE replays the frozen ordered merge table without recounting prompt frequencies.
rain (), rainy (), and rail () shrink weighted positions from 30 down to 11. rail stops at rai l because rai n was the learned merge.Production BPE runs a regex pre-tokenizer first (GPT-2, tiktoken, Llama 3[4][5][6]) so merges do not waste vocabulary gluing letters to punctuation (failed., failed!, failed\n). Because UTF-8 characters span 1 to 4 bytes, byte-level BPE guarantees zero <UNK> on arbitrary Unicode, though streaming decoders must buffer incomplete multi-byte characters before calling .decode("utf-8") so CJK or emoji output never turns into replacement characters.[7]
from collections import Counter
def merge_pair(pieces: tuple[str, ...], pair: tuple[str, str]) -> tuple[str, ...]:
out, i = [], 0
while i < len(pieces):
if i + 1 < len(pieces) and pieces[i:i + 2] == pair:
out.append(pair[0] + pair[1])
i += 2
else:
out.append(pieces[i])
i += 1
return tuple(out)
state = {tuple("rain"): 3, tuple("rainy"): 2, tuple("rail"): 2}
merges = []
for step in range(3):
counts = Counter()
for pieces, freq in state.items():
for pair in zip(pieces, pieces[1:]):
counts[pair] += freq
winner, top = counts.most_common(1)[0]
state = {merge_pair(p, winner): f for p, f in state.items()}
merges.append(winner)
print(f"merge {step + 1}: {winner} -> {''.join(winner)} (count={top})")
def encode(word: str) -> list[str]:
p = tuple(word)
for m in merges:
p = merge_pair(p, m)
return list(p)
print("replay:", {w: encode(w) for w in ("rain", "rainy", "rail", "airy")})
raw_bytes = list("関数✨".encode("utf-8"))
print(f"UTF-8 bytes ({len(raw_bytes)}): round-trip={bytes(raw_bytes).decode('utf-8')!r}")merge 1: ('r', 'a') -> ra (count=7)
merge 2: ('ra', 'i') -> rai (count=7)
merge 3: ('rai', 'n') -> rain (count=5)
replay: {'rain': ['rain'], 'rainy': ['rain', 'y'], 'rail': ['rai', 'l'], 'airy': ['a', 'i', 'r', 'y']}
UTF-8 bytes (9): round-trip='関数✨'Why can't an inference BPE tokenizer learn new merges on the fly from the user's prompt?
Answer
The checkpoint's embedding rows and output head correspond to fixed learned merge IDs. Inventing new merges at inference creates pieces with no trained embedding row and alters the segmentation distribution the model expects.
WordPiece, SentencePiece, and Unigram LM
WordPiece (introduced for Japanese/Korean ASR and popularized by BERT[8][9]) selects merges by likelihood intuition rather than raw frequency (often illustrated with the association proxy [10]) and marks word continuations with ##. At inference, BERT-style WordPiece runs greedy longest-match-first without backtracking: if a longer prefix (rainb) hits a dead end (##ow missing), the whole word collapses to [UNK] even when rain + ##bow is in the vocabulary.[11]
![Aligned character spans for "rainbow" (r a i n b o w) under fixed vocabulary {rainb, rain, ##bow}. On the top greedy WordPiece track, longest-match commits to rainb (indices 0..4), leaves unmatched tail ow (no ##ow in vocabulary), and collapses the whole word to [UNK]. On the bottom valid-split track, rain (0..3) plus ##bow (4..6) covers all seven characters cleanly, but WordPiece never backtracks to find it.](https://assets.leetllm.com/v1/5dcaf27c3158/fundamentals/tokenization-bpe-wordpiece-sentencepiece/illustrations/_generated/code_tokenization_dark.png)
SentencePiece[12] is a toolkit that trains directly on raw Unicode streams (essential for scripts without spaces like Japanese, Chinese, and Thai) by encoding spaces explicitly as ▁ (U+2581) so detokenization is straightforward ("".join(tokens).removeprefix("▁").replace("▁", " ")).[13] SentencePiece supports both BPE (used in Llama 2[14]) and the Unigram Language Model,[15] which works top-down: start from an oversized seed vocabulary, fit piece probabilities via EM to maximize , prune the lowest-loss pieces, and decode at inference with Viterbi dynamic programming to select the globally highest-probability complete path (avoiding WordPiece's greedy dead end and optionally enabling training-time subword regularization by sampling alternative segmentations ).
![Top: Unigram Viterbi segmentation DAG over the 5-character metaspace sequence ▁rain with boundary nodes 0 to 5. Three complete paths connect node 0 to node 5: the top green arc [▁rain] (P=0.30, cost 1.204), the blue 2-piece path [▁] (1.897) + [rain] (2.303) totaling 4.200, and the red 3-piece path [▁] (1.897) + [ra] (3.912) + [in] (3.507) totaling 9.316. Bottom: horizontal total-cost bars on a shared 0 to 10 scale confirm Viterbi selects [▁rain] at cost 1.204.](https://assets.leetllm.com/v1/275c7a8218bc/fundamentals/tokenization-bpe-wordpiece-sentencepiece/illustrations/_generated/sentencepiece_unigram_dark.png)
import numpy as np
def wordpiece(word: str, vocab: set[str]) -> list[str]:
out, i = [], 0
while i < len(word):
match = next(
(((("##" if i else "") + word[i:e]), e)
for e in range(len(word), i, -1)
if (("##" if i else "") + word[i:e]) in vocab),
None,
)
if match is None:
return ["[UNK]"]
piece, i = match
out.append(piece)
return out
print("WordPiece greedy trap on 'rainbow':", wordpiece("rainbow", {"rainb", "rain", "##bow"}))
probs = {"▁rain": 0.30, "▁": 0.15, "rain": 0.10, "ra": 0.02, "in": 0.03, "sun": 0.20, "cloud": 0.20}
logp = {k: float(np.log(v)) for k, v in probs.items()}
text = "▁rain"
best = [(0.0, -1, "")] + [(-np.inf, -1, "")] * len(text)
for s in range(len(text)):
for e in range(s + 1, len(text) + 1):
piece = text[s:e]
if piece in logp and best[s][0] + logp[piece] > best[e][0]:
best[e] = (best[s][0] + logp[piece], s, piece)
pieces, cur = [], len(text)
while cur > 0:
_, cur, p = best[cur]
pieces.append(p)
pieces.reverse()
print("Unigram Viterbi on '▁rain':", pieces, "score:", round(best[len(text)][0], 3))WordPiece greedy trap on 'rainbow': ['[UNK]']
Unigram Viterbi on '▁rain': ['▁rain'] score: -1.204| Algorithm | Training | Inference | Whitespace | Fallback |
|---|---|---|---|---|
| BPE | Bottom-up frequency merges | Ordered merge replay | Regex pre-tokenizer | Byte-level BPE (0 <UNK>) |
| WordPiece | Likelihood-motivated merges | Greedy longest-match | Basic tokenizer + ## | [UNK] on dead end |
| SentencePiece BPE / Unigram | Raw stream merges or top-down EM pruning | Merge replay or Viterbi | Explicit ▁ (U+2581) | Optional byte fallback or <unk> |
Vocabulary economics, Unicode normalization, and production hazards
Choosing vocabulary size (32K in Llama 2,[14] 50,257 in GPT-2,[4] 128K in Llama 3,[5] 200K in o200k_base,[16] 256K in Gemma 2[17]) trades static embedding memory ( for untied FP16 tables: 500 MiB at 32K vs. 2,000 MiB at 128K for ) against shorter sequences. Increasing English compression from Llama 2's 3.17 chars/token to Llama 3's 3.94 chars/token trims sequence length and KV cache by 19.5% and dense attention cells by 35.3%.[5]

Five production failure modes repeatedly masquerade as model bugs until you inspect the token IDs:
- Unicode normalization (
NFCvs.NFKC): Composedcafé(\u00E9) and decomposedcafe\u0301look identical on screen yet emit different token IDs unless normalized withNFC. Compatibility normalization (NFKC, or SentencePiece'snmt_nfkc[18]) additionally folds ligatures likefileintofile, silently rewriting code identifiers and losing exact round-trip reconstruction.[19] - Checkpoint/tokenizer drift: Swapping a tokenizer without remapping both input embeddings and an untied output head breaks every row lookup even when matches. Pin tokenizer files, merge rules, normalizers, and special-token maps by hash alongside the checkpoint, and guard deploys with golden text-to-ID test strings.
- Multilingual fertility tax: Across parallel FLORES-200 translations, low-resource scripts like Shan cost up to as many tokens as English on
cl100k_base, filling context windows and multiplying latency and cost.[1] - Numeric and code splitting: Llama 2 splits digits individually[14] while Llama 3 groups 1 to 3 digits via
\p{N}{1,3}.[6] Code-aware encoders compress indentation (16 spaces -> 1 token) and familiar identifiers while fragmenting opaque SHA-256 digests and UUIDs heavily. - Glitch tokens: Pieces present in the tokenizer corpus yet absent during model training (like
SolidGoldMagikarp) have under-trained embeddings and trigger erratic outputs.[7]

import unicodedata
import numpy as np
# 1. NFC vs NFKC normalization
print("NFC cafe equal:", unicodedata.normalize("NFC", "café") == unicodedata.normalize("NFC", "cafe\u0301"))
print("NFC vs NFKC on 'file':", unicodedata.normalize("NFC", "file"), "vs", unicodedata.normalize("NFKC", "file"))
# 2. Swapping token IDs without moving embedding rows breaks lookup
ids_a = {"prompt": 0, "cache": 1, "failed": 2}
ids_b = {"failed": 0, "prompt": 1, "cache": 2}
rows_a = np.array([[1.0, 0.0], [0.0, 1.0], [-1.0, -1.0]])
rows_b = np.zeros_like(rows_a)
for piece, new_id in ids_b.items():
rows_b[new_id] = rows_a[ids_a[piece]]
msg = ["prompt", "cache"]
print("Original rows:", rows_a[[ids_a[p] for p in msg]].tolist())
print("Swapped IDs, unmoved table:", rows_a[[ids_b[p] for p in msg]].tolist())
print("Swapped IDs, remapped table:", rows_b[[ids_b[p] for p in msg]].tolist())NFC cafe equal: True
NFC vs NFKC on 'file': file vs file
Original rows: [[1.0, 0.0], [0.0, 1.0]]
Swapped IDs, unmoved table: [[0.0, 1.0], [-1.0, -1.0]]
Swapped IDs, remapped table: [[1.0, 0.0], [0.0, 1.0]]Pinning known strings on a real encoder (cl100k_base) guards normalization, indentation, numbers, and special-token handling at once. When calling hosted APIs whose tokenizer you do not control, use the provider's official token-counting endpoint (such as OpenAI's POST /v1/responses/input_tokens or Anthropic's count_tokens) rather than assuming a local tiktoken table matches every newer model family.[20][21]
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
golden = {
"rain falls softly": [30193, 17503, 57150],
"caf\u00e9": [936, 59958],
"cafe\u0301": [936, 1897, 54939],
" return x": [262, 471, 865],
"1234567": [4513, 10961, 22],
"<|endoftext|>": [27, 91, 8862, 728, 428, 91, 29],
}
for text, expected in golden.items():
assert enc.encode(text, disallowed_special=()) == expected, text
print("tokenizer matches", len(golden), "known strings")
print("reserved:", enc.encode("<|endoftext|>", allowed_special="all"))tokenizer matches 6 known strings
reserved: [100257]| Symptom | Likely tokenizer cause | First check |
|---|---|---|
| Gibberish right after deploy | IDs select the wrong embedding/output rows | Compare golden text-to-ID tests; pin checkpoint and tokenizer by hash |
| Bill spikes for non-English traffic | High token fertility on target script | Measure token counts across parallel translations |
| Multi-digit arithmetic degrades | Digit splitting shifts place alignment | Inspect the pre-tokenizer regex on sample numbers |
| Context fills fast on logs/code | Hashes, UUIDs, or base64 fragment heavily | Measure real prompts with the model's exact encoder |
| Replacement glyphs in streamed UTF-8 | Decoding split multi-byte tokens one by one | Buffer bytes and decode incrementally |