WordPiece and Unigram Tokenizers
BPE is one of three subword families in wide use. WordPiece is the tokenizer of BERT and its descendants (DistilBERT, ELECTRA, many sentence encoders). Unigram language-model tokenization, usually through the SentencePiece library, is the tokenizer of T5, mT5, ALBERT, XLNet and XLM-R; Llama 1 and 2 used SentencePiece too, in its BPE mode. You will meet all three when you load pretrained models, and the differences matter: they split the same word differently, mark word boundaries differently, and fail differently on unusual text.
This lesson builds the encoding side of both from scratch (WordPiece's greedy longest match, checked against BERT's real vocabulary, and Unigram's Viterbi segmentation), then the training ideas: WordPiece's merge score and Unigram's EM with pruning.
WordPiece encoding: greedy longest match first
A WordPiece vocabulary contains word-initial pieces ("token", "un") and continuation pieces with a ## prefix ("##ization", "##s"). To encode a word, take the longest prefix that is in the vocabulary, then the longest ## piece for the rest, and so on. If at some position not even a single character matches, the whole word becomes [UNK].
def wordpiece(word, vocab, unk="[UNK]", max_chars=100):
"""Greedy longest-match-first, as in BERT. Non-initial pieces carry the '##' prefix."""
if len(word) > max_chars:
return [unk]
pieces, start = [], 0
while start < len(word):
end = len(word)
while end > start: # try the longest remaining substring first
piece = word[start:end] if start == 0 else "##" + word[start:end]
if piece in vocab:
break
end -= 1
if end == start: # not even one character matched
return [unk] # the WHOLE word becomes [UNK]
pieces.append(piece)
start = end
return pieces
vocab = {"un", "use", "used", "able", "##able", "##s", "##ed", "##e", "##d", "##u", "##n", "##a", "##b", "##l",
"u", "n", "s", "e", "d", "re", "##use", "##us", "spoke", "##spoke", "##r"}
for w in ["unused", "reusable", "reused", "spokes", "unusable", "use", "x-ray"]:
print(f"{w:9s} -> {wordpiece(w, vocab)}")unused -> ['un', '##use', '##d']
reusable -> ['re', '##us', '##able']
reused -> ['re', '##use', '##d']
spokes -> ['spoke', '##s']
unusable -> ['un', '##us', '##able']
use -> ['use']
x-ray -> ['[UNK]']
Two properties show up even in this toy vocabulary. The result is greedy, not morphological: "reusable" becomes re ##us ##able because ##usable is not in the vocabulary and ##us is the longest piece that matches. And the failure mode is coarse: "x-ray" has no piece for "x" (in this vocabulary), so the whole word is lost, not just one character. BERT's real vocabulary contains about a thousand single characters (997 in the uncased vocabulary), each both as a word-initial piece and as a ## piece, so [UNK] is rare for scripts it covers and frequent for those it does not.
Checking against BERT's vocabulary
BERT runs two steps before WordPiece. Its normaliser lower-cases and strips accents (for the uncased model), and its pre-tokeniser splits on whitespace and around every punctuation character. The recorded example takes those two steps from the real tokenizer, applies our wordpiece function with BERT's 30,522-token vocabulary, and compares with Hugging Face's result.
from transformers import AutoTokenizer
def wordpiece(word, vocab, unk="[UNK]", max_chars=100):
if len(word) > max_chars:
return [unk]
pieces, start = [], 0
while start < len(word):
end = len(word)
while end > start:
piece = word[start:end] if start == 0 else "##" + word[start:end]
if piece in vocab:
break
end -= 1
if end == start:
return [unk]
pieces.append(piece)
start = end
return pieces
tok = AutoTokenizer.from_pretrained("google/bert_uncased_L-2_H-128_A-2")
vocab = tok.get_vocab()
print("vocabulary:", len(vocab), "| pieces with ##:", sum(t.startswith("##") for t in vocab),
"| first ids:", [tok.convert_ids_to_tokens(i) for i in (0, 100, 101, 102, 103, 1996)])
backend = tok.backend_tokenizer
for s in ["Tokenization isn't hard, really!", "The derailleur hanger was misaligned.",
"Unbelievably, the e-bike's firmware v2.13 crashed", "Naïve café owners ☕"]:
text = backend.normalizer.normalize_str(s) # lower-case, strip accents
words = [w for w, _ in backend.pre_tokenizer.pre_tokenize_str(text)] # split on spaces and punctuation
ours = [p for w in words for p in wordpiece(w, vocab)]
print(f"{ours == tok.tokenize(s)!s:5s} {ours}")vocabulary: 30522 | pieces with ##: 5828 | first ids: ['[PAD]', '[UNK]', '[CLS]', '[SEP]', '[MASK]', 'the']
True ['token', '##ization', 'isn', "'", 't', 'hard', ',', 'really', '!']
True ['the', 'der', '##ail', '##le', '##ur', 'hang', '##er', 'was', 'mis', '##ali', '##gned', '.']
True ['un', '##bel', '##ie', '##va', '##bly', ',', 'the', 'e', '-', 'bike', "'", 's', 'firm', '##ware', 'v', '##2', '.', '13', 'crashed']
True ['naive', 'cafe', 'owners', '[UNK]']
All four sentences match. The vocabulary has 5,828 continuation pieces, and ids 0 and 100 to 103 are the special tokens [PAD], [UNK], [CLS], [SEP] and [MASK] (ids 1 to 99 are unused slots, [unused0] onwards, which fine-tuning can repurpose). Look at the outputs: "isn't" is three tokens, isn ' t, because the pre-tokeniser splits at the apostrophe; "v2.13" becomes v ##2 . 13; and "Naïve café" lost its accents before WordPiece ever saw it. The coffee emoji ☕ is not in the vocabulary, so it becomes [UNK]. A byte-level BPE would have encoded it as bytes.
WordPiece training: a likelihood score instead of a count
WordPiece is trained like BPE, by merging pairs, but it chooses the pair differently. BPE takes the most frequent pair. WordPiece takes the pair that increases the likelihood of the training data the most under a unigram model of the symbols, which works out to the pair count divided by the product of the parts' counts:
This is (up to a constant) the pointwise mutual information of the pair from Word Embeddings: it prefers pairs whose parts rarely occur apart, even if the pair itself is not frequent. (Google never published its original WordPiece trainer; this score is the one used by Hugging Face's implementation and described in its documentation.)
from collections import Counter
words = {"spoke": 9, "spokes": 5, "poke": 2, "stroke": 4, "strokes": 3, "smoke": 3, "hug": 2, "hugs": 1}
def split(w): # WordPiece style: "##" marks a non-initial piece
return tuple([w[0]] + ["##" + c for c in w[1:]])
def join(a, b):
return a + b[2:] # "s" + "##p" -> "sp", "##o" + "##k" -> "##ok"
def train(words, steps, score):
table = {split(w): c for w, c in words.items()}
learned = []
for _ in range(steps):
pairs, single = Counter(), Counter()
for sym, c in table.items():
for s in sym:
single[s] += c
for p in zip(sym, sym[1:]):
pairs[p] += c
if not pairs:
break
best = max(pairs, key=lambda p: (score(pairs[p], single[p[0]], single[p[1]]), p))
learned.append(f"{join(*best)} ({pairs[best]}/{single[best[0]]}x{single[best[1]]})")
new = {}
for sym, c in table.items():
out, i = [], 0
while i < len(sym):
if i + 1 < len(sym) and (sym[i], sym[i + 1]) == best:
out.append(join(*best)); i += 2
else:
out.append(sym[i]); i += 1
new[tuple(out)] = c
table = new
return learned, table
bpe, _ = train(words, 6, lambda pair, a, b: pair) # BPE: the most frequent pair
wp, table = train(words, 6, lambda pair, a, b: pair / (a * b)) # WordPiece: pair / (count a * count b)
print("BPE merges: ", bpe)
print("WordPiece merges:", wp)
print("after 6 WordPiece merges:", [" ".join(s) for s in table])BPE merges: ['##ok (26/26x26)', '##oke (26/26x26)', 'sp (14/24x14)', 'spoke (14/14x26)', 'st (7/10x7)', 'str (7/7x7)']
WordPiece merges: ['hu (3/3x3)', 'hug (3/3x3)', '##tr (7/7x7)', 'str (7/24x7)', 'sp (14/17x14)', 'sm (3/3x3)']
after 6 WordPiece merges: ['sp ##o ##k ##e', 'sp ##o ##k ##e ##s', 'p ##o ##k ##e', 'str ##o ##k ##e', 'str ##o ##k ##e ##s', 'sm ##o ##k ##e', 'hug', 'hug ##s']
The two criteria disagree from the first step. BPE merges ##ok (26 occurrences), the most frequent pair. WordPiece merges hu first: it occurs only 3 times, but "h" and "##u" never occur without each other, so its score is the highest. Then it builds "hug", "##tr" and "str", all made of parts that always appear together, and leaves the frequent but "promiscuous" ##o ##k ##e unmerged after 6 steps. The counts in brackets are pair / count of count of at the moment of the merge.
Unigram: segmentation as probabilistic inference
The Unigram tokenizer (Kudo 2018) turns the question around. Instead of a merge procedure, it defines a probability model: every piece in the vocabulary has a probability , and a segmentation of a word has probability
where is the set of all segmentations of the word into vocabulary pieces. There can be exponentially many, but the best one is found by Viterbi over positions: the best score of the first characters is the maximum over the pieces ending at of the best score where the piece starts plus . That is the same dynamic program as the tag decoder in Named Entity Recognition, with characters instead of tags.
import math
import numpy as np
counts = {"un": 30, "re": 40, "use": 25, "us": 10, "able": 20, "usable": 4, "una": 2, "reus": 1,
"bl": 3, "le": 8, "ab": 5, "u": 10, "n": 12, "r": 9, "e": 30, "s": 20, "a": 25, "b": 6, "l": 10}
total = sum(counts.values())
logp = {p: math.log(c / total) for p, c in counts.items()} # unigram piece log-probabilities
def viterbi(word, logp):
"""best[i] = best log-prob of word[:i]; one pass over end positions, all pieces ending there."""
best, back = [0.0] + [-math.inf] * len(word), [0] * (len(word) + 1)
for end in range(1, len(word) + 1):
for start in range(max(0, end - 6), end): # pieces are at most 6 characters long
piece = word[start:end]
if piece in logp and best[start] + logp[piece] > best[end]:
best[end], back[end] = best[start] + logp[piece], start
pieces, end = [], len(word)
while end > 0:
pieces.append(word[back[end]:end])
end = back[end]
return pieces[::-1], best[-1]
def all_segmentations(word):
if not word:
return [[]]
return [[word[:i]] + rest for i in range(1, len(word) + 1) if word[:i] in logp
for rest in all_segmentations(word[i:])]
for w in ["unusable", "reusable", "reuse"]:
pieces, lp = viterbi(w, logp)
print(f"{w}: Viterbi {pieces}, log P = {lp:.2f}")
segs = sorted(all_segmentations("unusable"), key=lambda s: -sum(logp[p] for p in s))
print(len(segs), "segmentations of 'unusable'; the top 4:")
probs = np.exp([sum(logp[p] for p in s) for s in segs])
for s, p in zip(segs[:4], probs[:4] / probs.sum()):
print(f" {' '.join(s):16s} share {p:.3f}")
rng = np.random.default_rng(0) # subword regularisation: sample with weights P(s)^alpha
alpha = 0.5
w = probs ** alpha
print("samples, alpha = 0.5:", [" ".join(segs[i]) for i in rng.choice(len(segs), size=4, p=w / w.sum())])unusable: Viterbi ['un', 'usable'], log P = -6.41
reusable: Viterbi ['re', 'usable'], log P = -6.12
reuse: Viterbi ['re', 'use'], log P = -4.29
26 segmentations of 'unusable'; the top 4:
un usable share 0.820
un us able share 0.152
u n usable share 0.012
un u s able share 0.011
samples, alpha = 0.5: ['un us able', 'un usable', 'un usable', 'un usable']
Viterbi picks un usable for "unusable" (log-probability ), out of 26 possible segmentations. Normalising over all of them shows how confident the model is: un usable has 0.820 of the probability, un us able 0.152. Because the model is probabilistic, it can also sample a segmentation instead of taking the best one, with probabilities proportional to . Training a model on sampled segmentations (subword regularisation, Kudo 2018) makes it robust to segmentation noise; BPE-dropout (Provilkov et al. 2020) does the same for BPE by randomly skipping merges.
Unigram training: EM and pruning
Training must learn both the vocabulary and the probabilities, without knowing the true segmentations. Kudo's procedure:
- Start with a large candidate vocabulary: all characters plus frequent substrings (SentencePiece uses a suffix array to find them).
- EM: with the current , compute for each word the posterior of each segmentation (E-step), add up the expected count of each piece, and renormalise the counts into new probabilities (M-step). The loss, the negative log-likelihood , cannot increase.
- Prune: for each piece, compute how much the loss grows if it is removed; drop the 10 to 20 % of pieces that matter least (never single characters, so every word stays representable).
- Repeat 2 and 3 until the vocabulary reaches the target size.
Real trainers compute the E-step with the forward-backward algorithm over each word's lattice. The example below enumerates segmentations instead, which is fine for short words.
import math
from collections import Counter
corpus = {"unusable": 3, "reusable": 2, "reuse": 5, "unable": 4, "use": 6, "usable": 2, "able": 3, "bus": 2}
chars = {c for w in corpus for c in w}
# start: every substring of length <= 4 that occurs in the corpus (a real trainer starts much larger)
cand = Counter(w[i:j] for w, c in corpus.items() for i in range(len(w)) for j in range(i + 1, min(len(w), i + 4) + 1) for _ in range(c))
pieces = {p: c / sum(cand.values()) for p, c in cand.items()}
def segs(word, pieces):
if not word:
return [[]]
return [[word[:i]] + r for i in range(1, len(word) + 1) if word[:i] in pieces for r in segs(word[i:], pieces)]
def em_step(pieces):
"""E: expected piece counts under P(segmentation | word). M: renormalise. Returns new pieces, loss."""
expected, loss = Counter(), 0.0
for w, c in corpus.items():
S = segs(w, pieces)
weights = [math.prod(pieces[p] for p in s) for s in S]
Z = sum(weights) # P(word) = sum over its segmentations
loss -= c * math.log(Z)
for s, wt in zip(S, weights):
for p in s:
expected[p] += c * wt / Z
for ch in chars: # single characters always stay (no word becomes impossible)
expected[ch] = max(expected[ch], 1e-6)
total = sum(expected.values())
return {p: n / total for p, n in expected.items() if n > 1e-9}, loss
def loss_of(pieces):
return -sum(c * math.log(sum(math.prod(pieces[p] for p in s) for s in segs(w, pieces))) for w, c in corpus.items())
print("start:", len(pieces), "pieces")
for it in range(1, 6):
pieces, loss = em_step(pieces)
print(f"EM step {it}: loss {loss:.2f}, pieces {len(pieces)}")
base = loss_of(pieces) # pruning: how much does the loss grow without a piece?
cost = {p: loss_of({q: v for q, v in pieces.items() if q != p}) - base for p in pieces if p not in chars}
print("most useful:", [(p, round(c, 1)) for p, c in sorted(cost.items(), key=lambda x: -x[1])[:4]])
print("least useful:", [(p, round(c, 2)) for p, c in sorted(cost.items(), key=lambda x: x[1])[:4]])
best = {w: " ".join(max(segs(w, pieces), key=lambda s: math.prod(pieces[p] for p in s))) for w in corpus}
print("best segmentations:", best)start: 42 pieces
EM step 1: loss 141.41, pieces 42
EM step 2: loss 97.19, pieces 42
EM step 3: loss 82.90, pieces 40
EM step 4: loss 80.29, pieces 27
EM step 5: loss 80.07, pieces 17
most useful: [('able', 207.2), ('un', 131.6), ('us', 65.1), ('bus', 29.8)]
least useful: [('abl', 0.0), ('re', 4.02), ('unus', 7.54), ('reus', 10.35)]
best segmentations: {'unusable': 'unus able', 'reusable': 'reus able', 'reuse': 're use', 'unable': 'un able', 'use': 'use', 'usable': 'us able', 'able': 'able', 'bus': 'bus'}
The loss falls from 141.41 to 80.07 in five EM steps, and EM already sparsifies: pieces that are never needed lose their expected counts, and the vocabulary shrinks from 42 to 17 by itself. The pruning scores then rank what is left: removing "able" would raise the loss by 207.2, removing "abl" by nothing. Notice what the model learned for "unusable": unus able, not the linguist's un us able. With so little data, a long piece that covers a whole frequent chunk wins; on a real corpus with many words the pieces become more general.
Differences in one table.
| BPE | WordPiece | Unigram | |
|---|---|---|---|
| Training | add the most frequent pair | add the pair with the best likelihood gain | start large, prune by likelihood loss |
| Encoding | apply merges in rank order | greedy longest match | Viterbi over a lattice |
| Output | deterministic | deterministic | best or sampled |
| Unknown text | bytes (byte-level) | [UNK] for the whole word |
character pieces, <unk> or byte fallback |
| Used by | GPT-2/3/4, Llama 3, RoBERTa | BERT, DistilBERT, ELECTRA | T5, mT5, ALBERT, XLNet, XLM-R |
SentencePiece
SentencePiece (Kudo and Richardson 2018) is a library that implements both Unigram and BPE with one important change: no pre-tokenisation. It treats the input as a raw stream of Unicode characters, replaces spaces with the visible symbol ▁ (U+2581), and lets the model learn pieces that include it, so "Hello world" becomes ▁Hello ▁world. Decoding is exact: join the pieces and turn ▁ back into spaces. This matters for languages written without spaces (Chinese, Japanese, Thai), where whitespace pre-tokenisation does not work, and it makes the tokenizer a single self-contained model file. Byte fallback (used by Llama 2) adds the 256 bytes as pieces, so characters outside the vocabulary are encoded as bytes instead of <unk>.
The sentencepiece package is not installed here, so this is shown without running:
import sentencepiece as spm # pip install sentencepiece; not run here
spm.SentencePieceTrainer.train(input="shop.txt", model_prefix="shop", vocab_size=400,
model_type="unigram", # or "bpe"
character_coverage=1.0, byte_fallback=True)
sp = spm.SentencePieceProcessor(model_file="shop.model")
print(sp.encode("The derailleur hanger", out_type=str)) # e.g. ['▁The', '▁de', 'rail', ...]
print(sp.encode("The derailleur hanger", out_type=str, # subword regularisation
enable_sampling=True, alpha=0.1, nbest_size=-1))Pitfalls
- Assuming one tokenizer per architecture. "BERT-like" models use WordPiece, but RoBERTa (same architecture) uses byte-level BPE. Always load the tokenizer that was saved with the checkpoint.
- Ignoring
[UNK]. WordPiece maps a whole word to[UNK]when one character is missing. Measure the[UNK]rate on your data (emoji, rare scripts, special symbols) before fine-tuning. - Forgetting the normaliser. An uncased tokenizer lower-cases and strips accents before WordPiece; cased and uncased checkpoints are not interchangeable.
- Comparing token counts across families. WordPiece, BPE and Unigram vocabularies of the same size give different fertilities on the same text; compare on your own data.
- Sampling at inference. Subword regularisation is a training-time augmentation. At inference, use the Viterbi (best) segmentation.
▁versusĠversus##. Three conventions for word boundaries (SentencePiece: start of word; GPT-2: leading space; WordPiece: continuation). Code that post-processes tokens (for example to rebuild words for NER) has to know which one it is dealing with.
Practice
- Encode "unable" with the toy vocabulary of the first example by hand, and "unbe" too.
- In the WordPiece training example, compute the score of the BPE winner
##o ##kat step 1 and compare it with the score ofh ##u. - In the Unigram example, why does Viterbi need only the best score at each position and not all segmentations?
- A word of length with all characters and all substrings in the vocabulary: how many segmentations does it have?
- Why is "no pre-tokenisation" useful for Japanese, and what does SentencePiece use instead to know where words start?
Answers
- "unable": longest prefix in the vocabulary is "un" ("unable", "unabl", "unab", "una" are not); then from "able":
##ableis in the vocabulary, so['un', '##able']. "unbe": "un", then for "be"##beis not in the vocabulary but##bis, then##efor "e". Result['un', '##b', '##e']. ##o ##k: .h ##u: , about 9 times higher, so WordPiece prefers it although the pair is rarer.- The score of a segmentation is a sum of independent piece scores, so the best segmentation of the first characters extends the best segmentation of some shorter prefix (optimal substructure). Keeping the best score per position, plus a back-pointer, is enough: work for maximum piece length .
- Each of the gaps between characters is either a cut or not, so segmentations. "unusable" has if every substring were a piece; with the toy vocabulary it had 26.
- Japanese has no spaces between words, so splitting on whitespace gives whole sentences. SentencePiece works on the raw character stream and learns pieces from frequency alone; where the original text had spaces it keeps them as
▁inside the pieces, so the boundary information is learned, not imposed.
Test yourself
How does WordPiece encode a word at inference time?
- Apply merges in rank order
- Greedy longest match first, with ## pieces after the first
- Viterbi over piece probabilities
- Split into bytes
What happens in BERT's WordPiece when one character of a word is not in the vocabulary?
- Only that character becomes [UNK]
- The whole word becomes [UNK]
- The character is split into bytes
- The character is dropped
Which pair does WordPiece's training score prefer?
- The most frequent pair
- Pairs whose parts rarely occur apart
- The longest pair
- Pairs of single characters
What makes subword regularisation possible with a Unigram tokenizer?
- Its vocabulary is larger
- It defines a probability for every segmentation, so segmentations can be sampled
- It has no pre-tokenisation
- It uses bytes
What does SentencePiece's '▁' symbol mark?
- A continuation piece
- An unknown character
- A space in the original text, kept inside the piece that follows it
- The end of a sentence