Skip to content
Skip to lesson
Back to Topics
LearnCore LLM FoundationsBPE, WordPiece, and SentencePiece
MediumNLP Fundamentals10 min read

BPE, WordPiece, and SentencePiece

See why a word like unexpectedly should split into reusable pieces, and why a new tokenizer can still point an old checkpoint at the wrong vector.

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 WE∈RV×dW_E \in \mathbb{R}^{V \times d}. 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].
Token IDs index rows of the embedding table WEW_E; swapping IDs without remapping rows points the model at the wrong learned vectors. A centered dot marks a leading space.

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 (V=106,d=4096V = 10^6, d = 4096, untied FP16 input and output tables cost 2×106×4096×2≈16.38 GB2 \times 10^6 \times 4096 \times 2 \approx 16.38\text{ GB} 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 stretch rain falls softly from 4 subwords to 17 characters, inflating dense O(L2d)O(L^2 d) attention grids from 42=164^2 = 16 cells per head to 172=28917^2 = 289 cells (18.1×18.1\times more pairs).
  • Subwords keep common strings whole (rain, falls), decompose rare words into reusable pieces ( soft + ly), and lock vocabulary size VV 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).
Subwords balance vocabulary size against quadratic dense attention cost: 4 pieces (16 cells) vs. 17 characters (289 cells) on the same sentence.

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 VV. At inference time, BPE replays the frozen ordered merge table without recounting prompt frequencies.

Three BPE merges on rain (×3\times 3), rainy (×2\times 2), and rail (×2\times 2) 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]

bpe-train-replay-and-utf8.py
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}")
Output
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='関数✨'

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 count(ab)/(count(a) count(b))\text{count}(ab) / (\text{count}(a)\,\text{count}(b))[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.
Greedy WordPiece commits to `rainb` and returns `[UNK]` for `rainbow` without backtracking to the valid `rain` + `##bow` split.

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 L=∑slog⁡∑x∈S(s)∏iP(xi)\mathcal{L} = \sum_s \log \sum_{\mathbf{x} \in \mathcal{S}(s)} \prod_i P(x_i), 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 qα(x∣s)∝∏P(xi)αq_\alpha(\mathbf{x} \mid s) \propto \prod P(x_i)^\alpha).

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.
Unigram Viterbi scores complete paths by summed negative log-probabilities and selects `['▁rain']` (cost 1.204) over two- and three-piece splits.
wordpiece-dead-end-and-unigram-viterbi.py
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))
Output
WordPiece greedy trap on 'rainbow': ['[UNK]']
Unigram Viterbi on '▁rain': ['▁rain'] score: -1.204
AlgorithmTrainingInferenceWhitespaceFallback
BPEBottom-up frequency mergesOrdered merge replayRegex pre-tokenizerByte-level BPE (0 <UNK>)
WordPieceLikelihood-motivated mergesGreedy longest-matchBasic tokenizer + ##[UNK] on dead end
SentencePiece BPE / UnigramRaw stream merges or top-down EM pruningMerge replay or ViterbiExplicit ▁ (U+2581)Optional byte fallback or <unk>

Vocabulary economics, Unicode normalization, and production hazards

Choosing vocabulary size VV (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 (2Vdmodelb2 V d_{\text{model}} b for untied FP16 tables: 500 MiB at 32K vs. 2,000 MiB at 128K for d=4096d = 4096) 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 N2N^2 attention cells by 35.3%.[5]

Top: untied FP16 table memory at hidden dimension 4096 grows linearly across 8k (125 MiB), 32k (500 MiB), and 128k (2,000 MiB) vocabulary rows. Bottom: increasing English compression from 3.17 to 3.94 characters per token lowers token and KV positions to 80.5% and dense N-squared score cells to 64.7%.
Larger vocabularies raise embedding-table memory linearly (top) while shortening sequence length and quadratically cutting dense attention cells (bottom).[5]

Five production failure modes repeatedly masquerade as model bugs until you inspect the token IDs:

  1. Unicode normalization (NFC vs. NFKC): Composed café (\u00E9) and decomposed cafe\u0301 look identical on screen yet emit different token IDs unless normalized with NFC. Compatibility normalization (NFKC, or SentencePiece's nmt_nfkc[18]) additionally folds ligatures like file into file, silently rewriting code identifiers and losing exact round-trip reconstruction.[19]
  2. Checkpoint/tokenizer drift: Swapping a tokenizer without remapping both input embeddings WEW_E and an untied output head WheadW_{\text{head}} breaks every row lookup even when VV 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.
  3. Multilingual fertility tax: Across parallel FLORES-200 translations, low-resource scripts like Shan cost up to 15×15\times as many tokens as English on cl100k_base, filling context windows and multiplying latency and cost.[1]
  4. 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.
  5. Glitch tokens: Pieces present in the tokenizer corpus yet absent during model training (like SolidGoldMagikarp) have under-trained embeddings and trigger erratic outputs.[7]
Composed café (4 code points, 5 UTF-8 bytes) and decomposed cafe plus U+0301 (5 code points, 6 bytes) both map to composed café under NFC and NFKC. The ligature file (3 code points, 5 bytes) remains file under NFC and expands to four ASCII letters under NFKC.
`NFC` unifies composed and decomposed `café` while keeping ligatures distinct; `NFKC` additionally folds `file` into `file`.
normalization-and-id-remap.py
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())
Output
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]

pin-known-token-ids.py
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"))
Output
tokenizer matches 6 known strings
reserved: [100257]
SymptomLikely tokenizer causeFirst check
Gibberish right after deployIDs select the wrong embedding/output rowsCompare golden text-to-ID tests; pin checkpoint and tokenizer by hash
Bill spikes for non-English trafficHigh token fertility on target scriptMeasure token counts across parallel translations
Multi-digit arithmetic degradesDigit splitting shifts place alignmentInspect the pre-tokenizer regex on sample numbers
Context fills fast on logs/codeHashes, UUIDs, or base64 fragment heavilyMeasure real prompts with the model's exact encoder
Replacement glyphs in streamed UTF-8Decoding split multi-byte tokens one by oneBuffer bytes and decode incrementally
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A migration changes rain from ID 5 to 7 and falls from ID 7 to 5. The team swaps the corresponding input embedding rows and leaves the untied output head in its original order. Both systems start from the same prompt. The old system gives falls the unique highest score for the first generated token. With greedy decoding, which output row wins in the new system on that step, and which piece does it emit?
2.A BPE tokenizer has three merge rules, applied in this order: (a, i), then (r, a), then (ai, n). How does it encode rain?
3.A byte-level BPE tokenizer has learned no merges that apply to the string aé✨🙂. These four characters use 1, 2, 3, and 4 UTF-8 bytes. How many tokens does it produce, and are any of them unknown tokens?
4.A team is designing the normalizer for a new tokenizer. Composed café (é as U+00E9) and decomposed café (e plus U+0301) must become the same text, so exact-prefix caching treats them alike. The word file, written with the fi ligature (U+FB01), must stay different from file, because the two can be different identifiers. Which normalization form meets both needs?
5.The only pieces a BERT-style WordPiece tokenizer can match are sun, sunr, ##rise, and ##ay. It encodes sunrise and sunray as separate words. What does it return for each word?
6.In a SentencePiece Unigram model, ▁ marks a space. The vocabulary includes ▁rain (0.02), ▁ (0.15), rain (0.20), ▁ra (0.40), and in (0.01). The only complete paths for ▁rain are ▁rain, ▁ + rain, and ▁ra + in. Which path does deterministic encoding choose, and why?
7.A SentencePiece model encodes blue sky✨ with two spaces between blue and sky. It uses default whitespace cleanup and the space marker ▁. Its vocabulary covers both words and the marker, but no piece covers ✨ and byte fallback is off. What can a decoder recover from the token IDs alone?
8.A tokenizer proposal raises the vocabulary from 16,384 to 49,152 for a model with hidden size 2,048, FP16 weights, and an untied output head. On the same corpus, the overall rate rises from 4 to 5 characters per token. How much additional memory do the vocabulary weights need, and by what percentage does the token count fall?
9.BPE training starts from single characters on these words and frequencies: low x3, lot x2, not x1, note x1. After the first merge is applied, which pair is merged next, and what is its count?
10.A team plans to replace a checkpoint's tokenizer A with tokenizer B. Which check directly tests whether each piece of text still selects the embedding row the model learned for it?

10 questions remaining.

References

Language Model Tokenizers Introduce Unfairness Between Languages.

Petrov, A., La Malfa, E., Torr, P. H. S., & Bibi, A. · 2023 · NeurIPS 2023

https://arxiv.org/abs/2305.15425

A New Algorithm for Data Compression.

Gage, P. · 1994

https://dl.acm.org/doi/10.5555/177910.177914

Neural Machine Translation of Rare Words with Subword Units.

Sennrich, R., Haddow, B., & Birch, A. · 2016 · ACL 2016

https://arxiv.org/abs/1508.07909

Language Models are Unsupervised Multitask Learners.

Radford, A., et al. · 2019

https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

Llama 3 Tokenizer Implementation

Meta · 2024 · Official source code

https://github.com/meta-llama/llama3/blob/main/llama/tokenizer.py

Fishing for Magikarp: Automatically Detecting Under-trained Tokens in Large Language Models

Land, S. & Bartolo, M. · 2024 · arXiv preprint

https://arxiv.org/abs/2405.05417

Japanese and Korean Voice Search.

Schuster, M. & Nakajima, K. · 2012

https://research.google/pubs/japanese-and-korean-voice-search/

BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.

Devlin, J., et al. · 2019 · NAACL 2019

https://arxiv.org/abs/1810.04805

WordPiece tokenization: training reconstruction and greedy encoding

Hugging Face · 2026

https://huggingface.co/learn/llm-course/en/chapter6/6

BERT Tokenization Implementation

Google Research · 2026

https://github.com/google-research/bert/blob/master/tokenization.py

SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing.

Kudo, T. & Richardson, J. · 2018 · EMNLP 2018

https://arxiv.org/abs/1808.06226

SentencePiece model specification: coverage, segmentation, and normalization options

Google · 2026

https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto

Llama 2: Open Foundation and Fine-Tuned Chat Models.

Touvron, H., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2307.09288

Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates.

Kudo, T. · 2018 · ACL 2018

https://arxiv.org/abs/1804.10959

tiktoken 0.14.0 model-to-encoding table

OpenAI · 2026

https://github.com/openai/tiktoken/blob/0.14.0/tiktoken/model.py

Gemma 2: Improving Open Language Models at a Practical Size

Gemma Team, Google DeepMind · 2024

https://storage.googleapis.com/deepmind-media/gemma/gemma-2-report.pdf

Text Normalization in SentencePiece

Google · 2026

https://github.com/google/sentencepiece/blob/master/doc/normalization.md

Unicode Standard Annex 15: Unicode Normalization Forms

Unicode Consortium · 2026

https://unicode.org/reports/tr15/

Counting tokens

OpenAI · 2026

https://developers.openai.com/api/docs/guides/token-counting

Token counting

Anthropic · 2026

https://platform.claude.com/docs/en/build-with-claude/token-counting

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.