WordPiece and SentencePiece
Overview
WordPiece and SentencePiece are subword tokenization algorithms that break words into smaller pieces to balance vocabulary size and coverage. They solve the out-of-vocabulary (OOV) problem while keeping the vocabulary tractable.
Why subword? Character-level is too granular (long sequences), word-level has infinite vocabulary. Subword is the Goldilocks zone.

[!intuition] Core Intuition
Imagine you're learning English and encounter "unbreakable". If you know "un-", "break", and "-able", you can guess the meaning even if you've never seen the full word. Subword tokenization teaches the model this compositional skill.
The key insight: Frequent words stay whole ("the", "and"), rare words get split into meaningful pieces ("playing" → "play" + "##ing"). The model learns morphology implicitly.
[!definition] WordPiece (Google/BERT)
WordPiece is a likelihood-based (PMI-weighted) subword algorithm developed for BERT. Crucially, it is not raw-frequency based—it chooses merges by which pair most increases the corpus likelihood under a unigram model.
Algorithm (Training):
- Initialize vocabulary with all characters + special tokens (
[UNK],[CLS],[SEP],[MASK]) - Repeat until vocabulary reaches target size (e.g., 30K):
- For every pair of consecutive tokens in the corpus, calculate the likelihood increase if we merge them
- The pair that increases the likelihood most becomes a new token
- Add it to vocabulary with
##prefix if it's not word-initial
Why likelihood, not frequency? We want the tokenization that makes the training corpus most probable under a unigram language model (each token independent, no context). Under a unigram model the corpus log-likelihood is:
Note there is no context term —each token contributes independently. Merging a pair changes , and WordPiece picks the merge with the largest gain (which turns out to be PMI-weighted, see below).
Contrast with BPE: BPE merges the pair with the highest raw count; WordPiece merges the pair that maximizes likelihood gain. That gain rewards pairs that co-occur more than chance, not merely often.
Tokenization (Inference):
- Greedy longest-match: Start from the beginning of each word, take the longest subword in vocabulary, repeat
- Use
##to mark non-initial pieces:"playing"→["play", "##ing"]
Key properties:
- Always starts with words separated by whitespace
- Never crosses word boundaries
- Requires pre-tokenized input (space-separated)
[!definition] SentencePiece (Google/T5)
SentencePiece is a language-agnostic, unsupervised text tokenizer that treats the input as a raw stream.
Why "language-agnostic"? Many languages (Chinese, Japanese, Thai) don't use spaces. SentencePiece works directly on raw text, treating whitespace as a special token ▁ (U+2581).
Algorithm choices:
- BPE mode (Byte-Pair Encoding): Merge most frequent pairs iteratively
- Unigram mode (default): Start with large vocabulary, prune tokens that minimize likelihood loss
Important: SentencePiece unigram does not use the ## prefix. All tokens are plain substrings; word boundaries are recovered purely from the ▁ marker.
Unigram derivation from first principles:
Assume each token is sampled independently (unigram assumption):
Log-likelihood:
Training objective: Find vocabulary and token probabilities that maximize across the corpus.
EM algorithm:
- E-step: For each word, enumerate all possible segmentations, compute each segmentation's probability using current , and derive expected (soft) counts of each token via forward-backward
- M-step: Update = (expected count of ) / (total expected counts)
- Prune: Remove tokens that hurt least, repeat until target vocabulary size
Why this works: Frequent subwords get high , so they're preferred in segmentations. Rare subwords get pruned.
Key properties:
- Reversible:
tokens → original textexactly (because▁encodes spaces) - No pre-tokenization needed
- Handles any language
[!formula] Likelihood-Based Merging (WordPiece)
For a merge candidate :
Derivation:
Before merge: segments appear as two tokens
After merge: they appear as one token
Likelihood gain:
This is the pointwise mutual information (PMI) weighted by frequency. This is exactly why WordPiece is not frequency-based: a pair can be frequent yet have low PMI (if and are independently common), so it won't be merged first.
Why maximize this? High PMI means and co-occur more than chance → they form a meaningful unit.
[!example] Worked Example 1: WordPiece Tokenization
Input: "unhappiness"
Vocabulary: ["un", "##happ", "##i", "##ness", "happiness"]
Step-by-step greedy longest-match:
- Start at position 0
- Try
"unhappiness"→ not in vocab - Try
"unhappine"→ not in vocab - Try
"unhapi"→ not in vocab - Try
"unhapp"→ not in vocab - Try
"unhap"→ not in vocab - Try
"unha"→ not in vocab - Try
"unh"→ not in vocab - Try
"un"→ found! ✓ - Move to position 2, now process
"happiness" - Try
"happiness"→ found! ✓
Output: ["un", "happiness"]
Why this step? Greedy longest-match ensures we use the largest chunks possible, reducing sequence length.
[!example] Worked Example 2: SentencePiece with Spaces
Input: "Hello world"
SentencePiece vocabulary: ["▁", "▁H", "ello", "▁w", "orld"]
Tokenization:
"Hello world"→ treat space as▁→"▁Hello▁world"- Segment:
["▁H", "ello", "▁w", "orld"]
Detokenization:
["▁H", "ello", "▁w", "orld"]→"▁Hello▁world"→ replace▁with space →"Hello world"
Why ▁? It makes tokenization reversible. You can always reconstruct the original text exactly, including leading/trailing spaces.
[!example] Worked Example 3: SentencePiece Unigram E-step
Corpus: a single word "dogs" observed with count 1 (kept small for clarity).
Vocabulary (plain substrings, NO ## prefix): ["d", "o", "g", "s", "do", "dog", "gs", "dogs"]
Current token probabilities (from a previous M-step):
| token | |
|---|---|
| dog | 0.40 |
| s | 0.20 |
| do | 0.10 |
| gs | 0.05 |
| g | 0.10 |
| d | 0.05 |
| o | 0.05 |
| dogs | 0.05 |
E-step — enumerate segmentations of "dogs" and score each:
["dog", "s"]→ Why this step? Product of independent token probs (unigram assumption).["do", "g", "s"]→["d", "o", "gs"]→["dogs"]→["d", "o", "g", "s"]→
Normalize (sum ):
| segmentation | posterior weight |
|---|---|
[dog, s] |
|
[dogs] |
|
| others | remaining |
Expected (soft) counts of each token = sum of posterior weights of segmentations that contain it:
- (from seg 1 and 5)
- ≈ tiny
Why forward-backward? For long words the number of segmentations is exponential; forward-backward computes these expected counts in linear time without enumerating them all. The M-step then re-normalizes these expected counts into new , and low-count tokens (like do, gs) get pruned in later rounds.
Key takeaway: This is soft, probabilistic assignment across all segmentations — very different from WordPiece's hard greedy merge, and it uses plain substrings, not ##-prefixed pieces.
[!mistake] Common Mistake 1: Confusing BPE and WordPiece
Wrong idea: "WordPiece and BPE are the same because both merge frequent pairs."
Why it feels right: Both are greedy merge algorithms on pairs.
The fix:
- BPE merges the pair with highest frequency (simple count)
- WordPiece merges the pair with highest likelihood increase (PMI weighted)
Example: Suppose ("e", "r") appears 100 times, ("er", "s") appears 50 times. BPE merges ("e", "r") first. But if ("er", "s") has very high PMI (they're almost always together), WordPiece might merge ("er", "s") first because it increases likelihood more.
Formula difference:
BPE:
WordPiece:
[!mistake] Common Mistake 2: Thinking SentencePiece Can't Handle Spaces
Wrong idea: "SentencePiece is for languages without spaces, so it breaks on English."
Why it feels right: The documentation emphasizes "language-agnostic" and Chinese examples.
The fix: SentencePiece handles spaces better than WordPiece because it encodes them explicitly as ▁. You can perfectly reconstruct the original text, including multiple spaces or leading spaces.
Example:
- Input:
" Hello world "(note multiple spaces) - WordPiece: Pre-tokenization normalizes spaces → information loss
- SentencePiece: encodes each space as its own
▁, fully reversible
[!mistake] Common Mistake 3: Mixing ## into SentencePiece
Wrong idea: "SentencePiece unigram tokens use ## for non-initial pieces, like WordPiece."
Why it feels right: Both are subword tokenizers from Google, so people assume the notation is shared.
The fix: ## is a WordPiece-only convention. SentencePiece tokens are plain substrings; word/space information is carried entirely by the ▁ marker. So a SentencePiece vocabulary looks like ["▁the", "▁dog", "s"], never ["the", "##s"].
[!recall]- Explain to a 12-year-old
Imagine you're making a dictionary for texting. You want it to be small (so it fits on your phone), but you also want to be able to write any word.
WordPiece is like: "Let's keep whole words for common stuff like 'the' and 'cat'. But if someone texts 'supercalifragilisticexpialidocious', we'll break it into pieces we've seen before: 'super', 'cali', 'fragi', etc."
The trick: We don't just pick pieces that show up a lot — we pick pieces that belong together. If "play" and "ing" appear next to each other much more than you'd expect by luck, we glue them into "playing". (This "more than luck" idea is called PMI.)
SentencePiece is even smarter: instead of breaking words first, it treats spaces as just another character (we write it as ▁). This works for Chinese (no spaces) and English (lots of spaces) the same way. And you can always go backwards — turn the pieces back into the exact original message.
[!mnemonic] Memory Hook
WordPiece: Word-boundary aware (never crosses spaces, uses ##)
SentencePiece: Sentence-level raw (treats spaces as ▁, no ##, no pre-tokenization)
PMI = "Pair Must Integrate" → WordPiece merges pairs that belong together (high mutual information, NOT just high frequency)
Unigram = "You Need Independence Guess Repeatedly And Modify" → EM algorithm iterates on independent token probabilities
Connections
- Byte-Pair Encoding (BPE): WordPiece uses likelihood/PMI instead of raw frequency
- Tokenization Fundamentals: Subword as the middle ground between character and word
- BERT Architecture: Uses WordPiece with 30K vocabulary
- T5 and mT5: Use SentencePiece unigram for 100+ languages
- Out-of-Vocabulary Problem: Subword tokenization eliminates OOV
- Morphology and Compositionality: Subwords capture morphemes implicitly
- Pointwise Mutual Information: The math behind WordPiece merging
- Expectation Maximization: Powers SentencePiece unigram training
Flashcards
Is WordPiece frequency-based or likelihood-based?
What is the key difference between WordPiece and BPE merge criteria?
Does WordPiece's unigram objective condition on context?
What special token does SentencePiece use to encode spaces?
▁ (U+2581), making tokenization reversible.Does SentencePiece unigram use the ## prefix?
## is WordPiece-only. SentencePiece tokens are plain substrings; spaces are marked by ▁.Why does WordPiece use the ## prefix?
What is the unigram assumption in SentencePiece?
How does WordPiece tokenization work at inference time?
What is the formula for likelihood increase when merging tokens and in WordPiece?
In SentencePiece's unigram E-step, how are token counts computed?
Can you perfectly reconstruct the original text from SentencePiece tokens?
▁, making tokenization reversible with no information loss.Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, jab hum language model bana rahe hote hain, to sabse pehle text ko tukdo (tokens) me todna padta hai. Ab problem yeh hai — agar hum har word ko poora ek token banaye to vocabulary infinite ho jayegi (kyunki naye naye words aate rehte hain, aur "unbreakable" jaise rare words model ne kabhi dekhe nahi honge — yeh OOV problem hai). Aur agar har character ko token banaye to sequence bahut lambi ho jaati hai aur model slow. Iska beautiful solution hai subword tokenization — yeh Goldilocks zone hai, na bahut chota na bahut bada. Common words jaise "the", "and" poore rehte hain, aur rare words tut jaate hain meaningful pieces me, jaise "playing" ban jaata hai "play" + "##ing". Isse model ko morphology yaani words ki structure apne aap samajh aa jaati hai.
Ab WordPiece (jo BERT use karta hai) ka core trick yeh hai ki yeh pairs ko sirf frequency (kitni baar aaye) dekh ke merge nahi karta — balki dekhta hai ki kaunsa merge corpus ki likelihood sabse zyada badhata hai unigram model ke under. Matlab yeh un pairs ko reward karta hai jo chance se zyada saath-saath aate hain (PMI-weighted), sirf jo often aate hain unhe nahi. SentencePiece (T5 me use hota hai) ek step aur aage jaata hai — yeh language-agnostic hai, kyunki Chinese, Japanese, Thai jaisi languages me spaces hote hi nahi. Yeh raw text ko directly leta hai aur whitespace ko bhi ek special symbol ▁ ki tarah treat karta hai, jisse baad me word boundaries wapas nikal sakein.
Yeh cheez isliye important hai kyunki aaj ke saare bade language models — BERT, GPT, T5 — inhi tokenization techniques pe khade hain. Agar tokenization achhi na ho to model ki poori performance girti hai. Yeh samajhna ki model text ko kaise "dekhta" hai, tumhe puri AI-ML pipeline ka foundation deta hai. Ek baar yeh clear ho gaya, to tum samajh paoge ki model kaise naye words ko handle karta hai, kaise vocabulary size control hoti hai, aur kaise ek hi tokenizer alag-alag languages pe kaam kar sakta hai — jo real-world multilingual applications ke liye bahut crucial hai.