Sub topic 9
The unigram language model tokeniser
This chapter assumes you have read the chapters on vocabularies and out-of-vocabulary handling and on BPE. It also assumes you are comfortable with Python dictionaries, logarithms, and the idea of a probability distribution over a finite set. SentencePiece, the next chapter's subject, is the library that usually ships this algorithm.
The idea: a vocabulary of pieces with probabilities
BPE and WordPiece build a vocabulary bottom-up. They start from characters and add merged pieces one at a time. The unigram language model tokeniser (Kudo, 2018) works in the opposite direction. It starts with a very large candidate vocabulary and removes pieces until the target size is reached.
Each piece x in the vocabulary has a probability p(x), and the probabilities sum to 1. The model assumes pieces occur independently. If a word is split into pieces x1, x2, ..., xn, the probability of that segmentation is:
P(x1, ..., xn) = p(x1) * p(x2) * ... * p(xn)Most strings can be split in several ways. "hugs" could be hug + s, hu + gs, or h + u + g + s. The tokeniser keeps the segmentation with the highest probability. Because the vocabulary is a set of scored pieces, there is no ordered merge list and no ## convention. The scores do all the work.
Encoding: finding the best segmentation with Viterbi
Trying every segmentation is exponential in word length. The independence assumption lets dynamic programming do it in quadratic time.
Let best[i] be the highest log-probability of any segmentation of the first i characters. For each end position i, try every start position j < i where word[j:i] is in the vocabulary:
best[i] = max over j of ( best[j] + log p(word[j:i]) )Store the winning j as a back-pointer, then walk the pointers from the end to recover the pieces. This is the Viterbi algorithm. Logs are used so that products become sums and tiny probabilities do not underflow.
The code below implements it and also measures how much a piece contributes to the training objective.
import math
def viterbi_segment(word, probs):
n = len(word)
best = [-math.inf] * (n + 1)
back = [0] * (n + 1)
best[0] = 0.0
for end in range(1, n + 1):
for start in range(end):
piece = word[start:end]
if piece in probs and best[start] > -math.inf:
score = best[start] + math.log(probs[piece])
if score > best[end]:
best[end] = score
back[end] = start
if best[n] == -math.inf:
return None, -math.inf
pieces = []
end = n
while end > 0:
start = back[end]
pieces.append(word[start:end])
end = start
return pieces[::-1], best[n]
def corpus_loss(freqs, probs):
total = 0.0
for word, freq in freqs.items():
_, score = viterbi_segment(word, probs)
total -= freq * score
return total
# Toy probabilities, not normalised, for illustration only.
probs = {"h": 0.05, "u": 0.05, "g": 0.05, "s": 0.05,
"hug": 0.15, "hu": 0.10, "ug": 0.10, "gs": 0.04}
freqs = {"hug": 10, "hugs": 5}
print(viterbi_segment("hugs", probs)) # (['hug', 's'], about -4.89)
base = corpus_loss(freqs, probs)
for piece in ["hug", "gs"]:
if len(piece) == 1:
continue
reduced = {k: v for k, v in probs.items() if k != piece}
print(piece, round(corpus_loss(freqs, reduced) - base, 2))The segmentation of "hugs" is hug + s, with probability 0.15 × 0.05 = 0.0075. The alternative hu + gs scores 0.10 × 0.04 = 0.004, which is lower.
The loop at the end shows the key quantity for training. Removing hug raises the corpus loss by about 37, because both words must fall back to weaker splits. Removing gs changes nothing, because no best segmentation uses it. A piece like gs is an obvious candidate for pruning.
Training: EM, then prune, repeat
Training starts from a seed vocabulary. It contains every single character in the corpus, so nothing can be out of vocabulary at the character level. It also contains a large set of the most frequent substrings, usually several times the target size. The algorithm then alternates two steps.
- Estimate probabilities with EM. With the current vocabulary, compute the expected count of each piece over all possible segmentations of the training text, weighted by segmentation probability. Normalise the counts into new probabilities. Repeat a few times. This is the expectation-maximisation (EM) algorithm, and the forward-backward recursion makes the expected counts cheap to compute.
- Prune. For every piece, estimate how much the total corpus log-likelihood would drop if that piece were deleted. This is the idea the
corpus_losscode above shows. Keep the pieces whose removal hurts most, and discard the rest of a fixed fraction of the vocabulary. The original paper keeps 80% per round.
Single characters are never pruned. The loop ends when the vocabulary reaches the target size.
How it differs from BPE and WordPiece
| Property | BPE | WordPiece | Unigram LM |
|---|---|---|---|
| Direction | Bottom-up, adds merges | Bottom-up, adds merges | Top-down, removes pieces |
| Selection criterion | Pair frequency | Likelihood-style pair score | Loss increase when a piece is removed |
| What is stored | Ordered merge list | Vocabulary with `##` marks | Vocabulary with probabilities |
| Encoding | Apply merges in learned order | Greedy longest match | Viterbi search for the highest-probability split |
| Segmentation per string | One, deterministic | One, deterministic | Best one, but alternatives are scored |
WordPiece's encoder is greedy: it takes the longest piece at each position and never reconsiders. Unigram's encoder is globally optimal under its model. It might choose a shorter first piece if that makes the rest of the word cheaper.
Subword regularisation: sampling segmentations
Because every segmentation has a probability, the model can do something BPE cannot do in its standard form. It can sample a segmentation instead of always returning the best one. During training of a downstream model, you can feed a different valid split of the same sentence on each epoch. Kudo called this subword regularisation. It acts as data augmentation and tends to help translation and other tasks with limited data, because the downstream model stops relying on one canonical split.
The same machinery supports an n-best list, which returns the top few segmentations. At inference time you normally turn sampling off, so that the same text always gives the same ids.
Failure modes and gotchas
- The independence assumption is wrong. Pieces in real text are not independent, so the probabilities are a useful scoring device and not a faithful language model. Do not use them to judge how likely a sentence is.
- Seed vocabulary quality matters. If the seed substrings miss an important multi-character unit, pruning cannot create it. Pruning only removes.
- Low-frequency scripts depend on character coverage. Single characters are kept, but a rare character that never appears in training cannot be in the vocabulary. Without a byte fallback it becomes the unknown token.
- Training is slower than BPE per iteration. EM passes over the whole corpus on every round. Practical implementations train on a sample of the data.
- Ties and near-ties. When two segmentations score almost the same, tiny changes in the training data can flip the chosen split. Pin the trained model file for production and do not retrain casually.
Where this goes next
Unigram is an algorithm for choosing and applying a vocabulary. It still needs text to be cut into chunks first, and it does not by itself say how whitespace is handled. SentencePiece answers both questions. It implements unigram and BPE behind one interface that works on raw text, and the next chapter covers it.
Exercise
A unigram vocabulary has these probabilities: "a" = 0.2, "b" = 0.1, "c" = 0.1, "ab" = 0.15, "bc" = 0.12, "abc" = 0.05. Which segmentation of "abc" does the Viterbi search choose, and what is its probability? Would a greedy longest-match encoder choose the same one?
Show answer
The candidates are "abc" at 0.05, "ab"+"c" at 0.15 × 0.1 = 0.015, "a"+"bc" at 0.2 × 0.12 = 0.024, and "a"+"b"+"c" at 0.2 × 0.1 × 0.1 = 0.002. The highest is "abc" with probability 0.05, so Viterbi chooses the single piece. Greedy longest match also picks "abc", because it is the longest vocabulary entry at position 0, so both encoders agree here. They would disagree if "abc" were removed. Greedy would then take "ab"+"c" (0.015), while Viterbi would take "a"+"bc" (0.024).