Foundations to Frontier
Tests

WordPiece, Unigram and SentencePiece

Besides BPE, two subword algorithms dominate. WordPiece (used by BERT) also grows a vocabulary by merging pairs, but chooses the pair that most increases the likelihood of the training data: the pair whose parts co-occur far more often than chance. Unigram LM tokenisation (Kudo, 2018) works the other way round: it starts from a large set of candidate pieces, fits a probability to each with EM, prunes the least useful, and segments new text by the most probable split. SentencePiece is a library that implements BPE and Unigram on raw text, treating spaces as ordinary symbols (▁), so tokenisation is language-independent and exactly reversible. This page covers the three methods, Viterbi segmentation, subword regularisation, and practical differences. In the exercises you implement the WordPiece score, Unigram Viterbi segmentation and SentencePiece-style spaces, then compare tokenisers at the same 200-piece vocabulary on words with known stem|suffix boundaries. BPE and Unigram compressed about equally (1.72 and 1.76 tokens per word), and Unigram's splits matched real morpheme boundaries best (F1 0.55 against 0.51). WordPiece-style likelihood merges spent the small budget on rare pairs (4.83 tokens per word).

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Three recipes for word pieces

BPE glues the most frequent pairs. WordPiece glues pairs that stick together more than you would expect by chance. Unigram starts with far too many pieces and throws away the least useful ones until the vocabulary is the right size, then splits each word in its most probable way. SentencePiece is a toolkit that runs these recipes straight on raw text, treating spaces as just another symbol. The demo shows BPE merges; the others build similar pieces in different ways.

Language lab
Merges learned: we, lo, ne, r</w>. Corpus now: lo·we·r</w> lo·we·s·t·</w> ne·we·r</w> ne·we·s·t·</w> … Frequent pairs fuse into subwords such as "est" and "er".
Why engineers care

BERT-family models (WordPiece), T5, LLaMA-1/2 and many multilingual models (SentencePiece Unigram or BPE) differ in tokenizer; knowing which one a model uses matters when fine-tuning, counting tokens or comparing models.

📝 Quick check (Level 0)
0/3 answered
  1. 1. WordPiece merges pairs that…
  2. 2. Unigram tokenisation starts from…
  3. 3. SentencePiece treats spaces as…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • WordPiece: score(a, b) = c(ab) / (c(a) c(b)). Merging the best pair maximises the gain in unigram likelihood of the corpus. BERT marks non-initial pieces with ## (“un”, “##launch”, “##able”) and segments greedily by longest match.
  • Unigram LM: the probability of a segmentation is the product of its piece probabilities. Training:
    1. start from all frequent substrings;
    2. run EM to estimate piece probabilities (expected counts by forward–backward over all segmentations);
    3. drop the pieces whose removal costs least likelihood, keeping single characters;
    4. repeat until the target size.
  • Segmentation: a word of n characters has 2^(n−1) segmentations (2048 for 12 letters); Viterbi finds the best in O(n · max piece length).
  • Subword regularisation: sample segmentations from the Unigram model during training, so the model sees “un + launch + able” and “unl + aunch + able”, which improves robustness.
  • SentencePiece: works on raw Unicode, replaces spaces by ▁ and includes them in pieces, so decoding is exact concatenation. It can fall back to bytes for unknown characters.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Segmentations of a 12-letter word:
  2. 2. BERT marks continuation pieces with…
  3. 3. Subword regularisation…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Subword tokenisers in code

Exercise 1.

  • Compute WordPiece merge scores: rare parts that co-occur score highest.
  • Segment a word by Viterbi under a Unigram model.
  • Pre-tokenise SentencePiece-style with ▁ for spaces.

Practice.

  • SentencePiece trains BPE or Unigram models (model_type) from raw text in one command, with byte fallback and character coverage settings for many scripts.
  • Hugging Face tokenizers provides BPE, WordPiece and Unigram models with the same API.
  • Use enable_sampling (SentencePiece) or BPE-dropout for subword regularisation when training models from scratch.
  • Do not mix tokenizers: a model’s embeddings are tied to its own pieces.
import sentencepiece as spm
spm.SentencePieceTrainer.train(input="corpus.txt", model_prefix="sp", vocab_size=8000,
                               model_type="unigram", character_coverage=0.9995, byte_fallback=True)
sp = spm.SentencePieceProcessor(model_file="sp.model")
print(sp.encode("unlaunchable rockets", out_type=str))           # e.g. ['▁un', 'launch', 'able', '▁rocket', 's']
print(sp.encode("unlaunchable", out_type=str, enable_sampling=True, alpha=0.1))
🐍 Exercise 1: WordPiece scores, Unigram segmentation, SentencePiece spaces
Compute WordPiece merge scores, Viterbi-segment words under a Unigram model and pre-tokenise text with ▁.
📝 Quick check (Level 2)
0/3 answered
  1. 1. SentencePiece model types include…
  2. 2. Subword sampling in SentencePiece is enabled by…
  3. 3. A model's embeddings are tied to…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

WordPiece as likelihood gain. Under a unigram model, merging a and b into ab changes the corpus log-likelihood by roughly c(ab) log(c(ab) / (c(a) c(b))) plus normalisation terms. The ratio c(ab)/(c(a)c(b)) is a pointwise-mutual-information-like score, so WordPiece favours pairs that belong together rather than pairs that are merely frequent. On small corpora this ratio is noisy for rare symbols.

Unigram as model selection. Unigram fits a latent-variable model (the segmentation is hidden) by EM and prunes by likelihood loss. It ends with a probabilistic tokenizer: every segmentation has a score, which enables sampling and principled comparison. Bostrom and Durrett (2020) found Unigram segmentations align better with morphology than BPE and give slightly better pretrained models.

Reversibility. Tokenisers that discard spaces or normalise text cannot reproduce the input exactly. SentencePiece’s ▁ convention makes encode–decode lossless for any language, including those without spaces.

📝 Quick check (Level 3)
0/3 answered
  1. 1. WordPiece's score resembles…
  2. 2. Unigram training uses…
  3. 3. Unigram segmentations tend to align with…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Which subword algorithm best recovers real word structure at a fixed vocabulary size?

History.

  • M. Schuster and K. Nakajima, “Japanese and Korean voice search” (ICASSP 2012), introducing WordPiece.
  • T. Kudo, “Subword regularization” (ACL 2018), introducing the Unigram model.
  • T. Kudo and J. Richardson, “SentencePiece” (EMNLP 2018).
  • K. Bostrom and G. Durrett, “Byte pair encoding is suboptimal for language model pretraining” (Findings of EMNLP 2020).

Exercise 2.

  • Data: stem + suffix words (about 400 stems, 10 suffixes, Zipfian); 5000 training and 2000 test tokens. The true boundary is between stem and suffix.
  • Tokenisers, all with a 200-piece vocabulary:
    • BPE (frequency merges);
    • WordPiece-style (merges maximising c(ab)/(c(a)c(b)), pairs seen at least 3 times);
    • simplified Unigram LM (EM with forward–backward and pruning, Viterbi segmentation).
  • Metrics: tokens per test word; precision, recall and F1 of predicted internal boundaries against the true stem|suffix boundary.
tokeniser tokens per word boundary precision boundary recall boundary F1
BPE 1.720 0.481 0.537 0.508
WordPiece-style 4.825 0.165 0.977 0.282
Unigram 1.758 0.509 0.599 0.550
  • Unigram aligns best with morphology at the same vocabulary size and almost the same compression as BPE.
  • WordPiece-style merges failed to compress here: the likelihood ratio rewards pairs of individually rare symbols, so on this small corpus the 180-merge budget went on rare pairs. It split words into many pieces, which finds every true boundary (recall 0.98) but adds many false ones. At 800 pieces it still needed 2.55 tokens per word against 1.25 for BPE. Real WordPiece is trained on huge corpora where counts are less noisy, so treat this as a small-data effect.
  • Larger vocabularies trade recall for precision: at 800 pieces, Unigram had precision 0.85 but recall 0.34, as frequent whole words stop being split.
  • Seeds: seed 1 gave boundary F1 0.47 (BPE), 0.284 (WordPiece-style) and 0.526 (Unigram), the same order.
🐍 Exercise 2 (research): which subword algorithm best recovers real word structure at a fixed vocabulary size?
Train BPE, WordPiece-style and Unigram tokenisers with the same vocabulary size and compare compression and morpheme-boundary F1.

Subword tokenisers in AI, robotics and aerospace

  • Multilingual and technical text: SentencePiece’s language independence suits mixed-language operations logs and documents.
  • Robust models: subword regularisation helps models tolerate spelling variants and noisy transcripts.
  • Design lesson: tokenisers with the same vocabulary size can split words very differently; check segmentations on your own data.

References

  1. M. Schuster and K. Nakajima (2012). “Japanese and Korean voice search.” Proc. ICASSP.
  2. T. Kudo (2018). “Subword regularization: improving neural network translation models with multiple subword candidates.” Proc. ACL.
  3. T. Kudo and J. Richardson (2018). “SentencePiece: a simple and language independent subword tokenizer and detokenizer for neural text processing.” Proc. EMNLP (demo).
  4. K. Bostrom and G. Durrett (2020). “Byte pair encoding is suboptimal for language model pretraining.” Findings of EMNLP.