Algorithmadvanced
Unigram language model tokenization
Also called unigram tokenizer, Kudo unigram segmentation.
Kudo's subword method. Fit a unigram model over pieces by EM, prune pieces that least lower the likelihood, and segment by Viterbi.
- Solves
- Tokenization
- Time
- O(N m) em_stepO(n m) encodeO(V N m) exact_losses
- Space
- O(n) encodeO(V m) model
- Where
- N = the total length of the corpus in characters; V = the vocabulary size (number of pieces); m = the length of the longest piece; n = the length of the word in characters
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Taku Kudo, 2018
Unigram language model tokenization splits a word into subword pieces by giving each piece of a fixed vocabulary a probability and choosing the split whose pieces have the largest product of probabilities. Taku Kudo introduced it in 2018, together with a training method: start from a large set of candidate pieces, fit the probabilities by expectation maximization, and drop the pieces whose loss hurts the model least, until the vocabulary has the size wanted. Unlike byte-pair encoding, the model gives a probability to every split, which is what subword regularization samples from.
In plain words
Every piece in the vocabulary has a score that says how common it is. To cut a word, look at every way to write it as a row of known pieces, multiply the scores along each row, and keep the row with the best total. A table filled from left to right finds that row without listing every row.
To learn the scores, start with a large pile of candidate pieces. Guess the scores, then count how often each piece would be used if the words were cut with the current scores, weighting each possible cut by how likely it is. Turn the counts into new scores and repeat. Then throw away the pieces the corpus can best do without, keep every single letter so that every word can still be cut, and repeat until the pile is small enough.
The problem
The input of training is a corpus of words with their counts and a target size . The output is a vocabulary of pieces (nonempty strings) and a probability for each piece , with . The input of encoding is a word of characters, and the output is a segmentation of : a list of pieces whose concatenation is .
The model is a unigram language model of pieces: the pieces of a segmentation are independent, so (Kudo's Equation 6)
where the sum runs over all segmentations of . Encoding returns (Equation 7). Training maximizes the corpus log likelihood , where is the count of the word ; all logs on this page are natural logs. Positions in a word are fenceposts , and the piece covers the characters between positions and . The pieces of the vocabulary are the edges of a word lattice on these positions, and a segmentation is a path from to .
The algorithm
Encoding is the Viterbi algorithm on the lattice, in the VITERBI semiring (log probabilities, plus = max, times = +):
VITERBI(x, p)V1 best[j] ← -∞ for j = 0..nV2 best[0] ← 0V3 for j ← 1 to nV4 for i ← max(0, j - m) to j - 1V5 if x[i:j] is a piece and best[i] > -∞V6 if best[i] + log p(x[i:j]) > best[j] then best[j] ← that value; back[j] ← iV7 follow back[] from n to 0, collecting the pieces x[back[j]:j]V8 return best[n] and the pieces in left-to-right order
One EM step uses the forward-backward algorithm on the same lattice, in the LOG semiring (log probabilities, plus = log-add, times = +). The forward value is the log of the total probability of the segmentations of , and the backward value is that of . The piece is used with posterior probability .
EM-STEP(corpus, p)E1 C[w] ← 0 for every piece wE2 for each word x with count f in the corpusE3 for each piece w, with E[c_w] the expected uses of w in x (forward-backward)E4 C[w] ← C[w] + f · E[c_w]E5 Z ← the sum of C[w] over the piecesE6 return the model p'(w) = C[w] / Z
Training follows the four steps of Kudo's Section 3.2. The loss of a piece is , where is without , renormalized.
TRAIN-UNIGRAM(corpus, T, eta)T1 seed ← every character, plus the most frequent substrings of the wordsT2 p ← the relative frequencies of the seed piecesT3 loopT4 run a few EM steps on pT5 give each character of probability 0 the smallest positive probability, drop other pieces of probability 0, and renormalizeT6 if p has at most T pieces, or only characters, then return pT7 loss(w) ← L(p) - L(p without w), for each piece w of length 2 or moreT8 k ← max(T, ⌊eta · |p|⌋) - (the number of characters)T9 keep the k pieces of largest lossT10 p ← the characters and the kept piecesT11 renormalize p
Kudo gives percent of the pieces per round as an example value, and keeps the single characters to avoid unknown words. Line T5 is a choice of this page: plain EM can give a character probability 0 when longer pieces always cover it, and such a character would no longer help a new word. The seed of line T1 comes from frequent substrings; Kudo suggests the enhanced suffix array to list them in linear time, and does not let a piece cross a word boundary. The code here counts the substrings up to a fixed length directly.
Example
Take the model h 0.1, u 0.1, g 0.1, s 0.15, hu 0.1, ug 0.15, hug 0.2, gs 0.05 and ugs 0.05, and the word "hugs". Every split of "hugs" except the whole word is possible, which gives 7 segmentations:
| segmentation | probability | posterior |
|---|---|---|
| hug s | 0.03 | 0.6757 |
| h ugs | 0.005 | 0.1126 |
| hu gs | 0.005 | 0.1126 |
| h ug s | 0.00225 | 0.0507 |
| hu g s | 0.0015 | 0.0338 |
| h u gs | 0.0005 | 0.0113 |
| h u g s | 0.00015 | 0.0034 |
The total is , so . The forward values at positions 0 to 4 are 1, 0.1, 0.11, 0.226 and 0.0444, and the backward values are 0.0444, 0.079, 0.065, 0.15 and 1 (shown as probabilities, not logs). Viterbi returns hug, s with probability 0.03. The expected number of uses of hug is , and that of s is 0.7635, because s is in four of the seven segmentations.
For training, take the corpus hug 10, pug 5, pun 12, bun 4 and hugs 5. The seed holds the 7 characters and the 12 longer substrings, 19 pieces in all. The corpus log likelihood is for the seed frequencies, and , and after one, two and three EM steps. With training ends with the pieces hug, pun, pug and s and the 6 other characters. A new word "pugs" is then encoded as pug, s, and "bugs" as b, u, g, s.
Correctness
The lattice paths from 0 to are exactly the segmentations, and the weight of a path is the probability of its segmentation. By induction on , VITERBI finds the best path to each position, and the forward and backward passes find the total weight to and from each position; their product at an edge, over , is the posterior use of that edge. An EM step never lowers , by Jensen's inequality and Gibbs' inequality. Training stops, because each round removes at least one piece, and it keeps every character. These are theorems, proved in proofs/correctness.md. The pruning rule is a heuristic: it does not promise the vocabulary of size with the largest likelihood.
Proof: The unigram lattice recursions give the best segmentation, the total probability and the expected counts, and an EM step never lowers the likelihoodfull
Notation. A model is a map from a finite set of pieces (nonempty strings) to probabilities with . All logs are natural logs. A word has characters, and positions are fenceposts : the piece covers the characters after position up to position . A segmentation of is a list of pieces whose concatenation is ; its probability is , with one factor per use, and . The lattice has the positions as nodes and an edge of weight for each piece of the model. A segmentation is a path from to , and its probability is the product of the edge weights.
Lemma 1 (paths). The map from segmentations of to paths in the lattice is a bijection that keeps the probability.
Proof. A segmentation fixes the cut positions with , and each is a piece, so each step is an edge. Conversely a path gives the pieces , which join to . The two maps are inverse, and both products have the same factors.
Theorem 1 (Viterbi). In the VITERBI semiring (log probabilities, plus = max, times = +), line V6 gives over the segmentations of , and VITERBI returns a segmentation of of the largest probability, or reports that none exists.
Proof. By induction on . For the only segmentation is empty, with log probability (line V2). For , the last piece of a segmentation of is some in the model, and the rest is a segmentation of ; the log probability is the sum of the two parts. Lines V4 to V6 take the max over of , which by the induction hypothesis is the max over all segmentations. The pointer keeps an that reaches the max, so lines V7 and V8 rebuild a best segmentation. If no segmentation exists, stays at the semiring zero, .
Theorem 2 (forward and backward). In the LOG semiring (plus = log-add, times = +), over the segmentations of , and over the segmentations of . So .
Proof. The same induction as for Theorem 1, with the sum in place of the max: the segmentations of split, without overlap, by their last piece, and the probability factors into the last piece times the rest. The LOG semiring computes the log of these sums. The argument for runs from the right end.
Theorem 3 (expected counts). For each piece , EXPECTED-COUNTS returns , where is the number of uses of in and .
Proof. Write as the number of edges on the path of with . Swap the two sums: . A path through the edge is a path , then the edge, then a path , and these choices are free, so the inner sum is by Theorem 2. The code adds over these edges.
Theorem 4 (EM). Let for a corpus with word counts , and let be the model of EM-STEP. Then .
Proof. This is the EM inequality for the hidden segmentation. Let . For each word, Jensen's inequality on the concave log gives , so . Now with , by Theorem 3. Over the probability vectors on the pieces, is largest at (Gibbs' inequality), which is what lines E1 to E6 compute. So and . A piece with gets , that is in log space.
Theorem 5 (termination of TRAIN). TRAIN stops, and its result has at most pieces, where is the target size and is the number of characters of the corpus, and it holds every character of the corpus.
Proof. The seed holds every character (SEED-VOCABULARY adds them first), and lines T5 and T10 never remove a character: FLOOR-CHARACTERS removes only pieces of probability that are not single characters. If the loop does not stop at line T6, the model has more than pieces and at least one piece of length 2 or more. Line T8 sets the new size to , which is less than the current size because and , and lines T9 and T10 keep at most that many pieces. So the size drops at every round, and the loop stops after at most rounds for a seed of pieces. At the stop, either the size is at most or only characters are left.
The pruning rule itself, keeping the pieces whose removal lowers the likelihood the most, is a heuristic: it does not find the vocabulary of size of the largest likelihood, and the page does not claim that it does.
Complexity
Let be the length of the longest piece and the vocabulary size. With the pieces in a trie, the edges that start at one position are found in steps, so the lattice of a word has edges, and Viterbi, forward and backward each take time in the word-RAM model, with space for the tables. The code here looks up each substring in a hash table, which adds a factor for hashing. One EM step over a corpus of total length takes time, plus to normalize. The exact losses of line T7 need one likelihood per piece, in all, so a trainer for a large corpus needs a cheaper estimate of the loss.
Properties
- A probability for every segmentation. The model scores all segmentations, so it gives the best one, the best, or a random one, from the same lattice.
- Characters always kept. Every word over the alphabet of the training corpus has a segmentation.
- Top-down training. BPE and WordPiece grow a vocabulary by merges; the unigram method shrinks a large seed.
- No context. The pieces are independent given the word, which is a strong assumption (a heuristic) that makes the lattice algorithms exact.
Variants and improvements
- Sampling. Subword regularization samples a segmentation with probability proportional to for a smoothing value , either from the best or exactly by forward filtering and backward sampling (Kudo's Section 3.3).
- n-best decoding. Kudo's Section 2.2 translates the best segmentations and keeps the best translation.
- SentencePiece. The library of Kudo and Richardson trains the model on raw text with the space as an ordinary symbol, so no word splitter is needed.
When to use it
Use it when you want a subword vocabulary with probabilities, either to sample segmentations in training or to score them. If one fixed segmentation from a merge table is enough, byte-pair encoding is simpler.
Pitfalls
- Underflow. The product of many piece probabilities underflows in floating point. Work with log probabilities and add them with log-add, as the code does through nlslog.
- Whole words win on small corpora. Maximum likelihood favors long pieces. In a measurement on the corpus of the example, keeps all five words and the 7 characters, and still keeps hug, pun and pug.
- Negative loss. Removing a piece renormalizes the others, so the loss of a piece that is almost never used can be slightly negative.
- Ties. Two segmentations can have the same probability, as h ugs and hu gs do above. Viterbi then returns the one it meets first.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
unigram_language_model_tokenization.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unigram-language-model-tokenization/. The authors are listed in prov/9PE3NB.jsonl.
"""Unigram language model tokenization of Kudo (2018).
A model is a dict from pieces (nonempty strings) to natural log probabilities.
A segmentation of a word x of n characters is a list of pieces whose
concatenation is x. Positions are fenceposts 0..n, and the piece x[i:j] is the
edge from position i to position j of the lattice.
viterbi the most probable segmentation, in the VITERBI semiring (max, +)
forward the log of the total probability of x, in the LOG semiring
expected_counts the expected number of uses of each piece (forward-backward)
em_step one EM step on a corpus of word counts
piece_loss the drop of the corpus log likelihood when one piece is removed
train seed, then EM and pruning until the vocabulary is small enough
Every log is the natural log. Log-space sums use nlslog.
"""
import math
from typing import Dict, List, Optional, Tuple
from nlslog import LOG, NEG_INF, VITERBI, log_sum, safe_log
Model = Dict[str, float]
def _max_len(model: Model) -> int:
return max((len(w) for w in model), default=0)
def viterbi(x: str, model: Model) -> Tuple[float, Optional[List[str]]]:
"""Return (log P of the best segmentation, its pieces); (NEG_INF, None) if none."""
n, m = len(x), _max_len(model)
best = [VITERBI.zero] * (n + 1) # @line V1
back = [0] * (n + 1)
best[0] = VITERBI.one # @line V2
for j in range(1, n + 1): # @line V3
for i in range(max(0, j - m), j): # @line V4
w = x[i:j]
if w in model and best[i] != NEG_INF: # @line V5
s = VITERBI.times(best[i], model[w])
if s > best[j]: # @line V6
best[j], back[j] = s, i
if best[n] == NEG_INF:
return NEG_INF, None
pieces, j = [], n # @line V7
while j > 0:
pieces.append(x[back[j]:j])
j = back[j]
return best[n], pieces[::-1] # @line V8
def forward(x: str, model: Model) -> List[float]:
"""alpha[j] = log of the total probability of the segmentations of x[:j]."""
n, m = len(x), _max_len(model)
alpha = [LOG.zero] * (n + 1)
alpha[0] = LOG.one
for j in range(1, n + 1):
terms = [LOG.times(alpha[i], model[x[i:j]]) for i in range(max(0, j - m), j) if x[i:j] in model]
alpha[j] = log_sum(terms)
return alpha
def backward(x: str, model: Model) -> List[float]:
"""beta[i] = log of the total probability of the segmentations of x[i:]."""
n, m = len(x), _max_len(model)
beta = [LOG.zero] * (n + 1)
beta[n] = LOG.one
for i in range(n - 1, -1, -1):
terms = [LOG.times(model[x[i:j]], beta[j]) for j in range(i + 1, min(n, i + m) + 1) if x[i:j] in model]
beta[i] = log_sum(terms)
return beta
def log_prob(x: str, model: Model) -> float:
"""log P(x), the log of the sum over all segmentations of the product of piece probabilities."""
return forward(x, model)[len(x)]
def expected_counts(x: str, model: Model) -> Dict[str, float]:
"""The expected number of uses of each piece in a segmentation of x drawn from P(seg | x)."""
n, m = len(x), _max_len(model)
alpha, beta = forward(x, model), backward(x, model)
z = alpha[n]
if z == NEG_INF:
raise ValueError("the word has no segmentation")
out: Dict[str, float] = {}
for i in range(n):
for j in range(i + 1, min(n, i + m) + 1):
w = x[i:j]
if w in model:
lp = alpha[i] + model[w] + beta[j] - z
if lp != NEG_INF:
out[w] = out.get(w, 0.0) + math.exp(lp)
return out
def corpus_log_likelihood(corpus: Dict[str, int], model: Model) -> float:
"""The sum over the words of count * log P(word)."""
return math.fsum(c * log_prob(x, model) for x, c in corpus.items())
def em_step(corpus: Dict[str, int], model: Model) -> Model:
"""One EM step: p(w) = (expected count of w) / (sum of the expected counts)."""
total: Dict[str, float] = {} # @line E1
for x, c in corpus.items(): # @line E2
for w, e in expected_counts(x, model).items(): # @line E3
total[w] = total.get(w, 0.0) + c * e # @line E4
z = math.fsum(total.values()) # @line E5
return {w: safe_log(total.get(w, 0.0) / z) for w in model} # @line E6
def remove_piece(model: Model, w: str) -> Model:
"""The model without w, renormalized so that the probabilities sum to 1."""
rest = {v: lp for v, lp in model.items() if v != w}
z = log_sum(rest.values())
return {v: lp - z for v, lp in rest.items()}
def piece_loss(corpus: Dict[str, int], model: Model, w: str) -> float:
"""loss(w) = L(model) - L(model without w), with L the corpus log likelihood."""
return corpus_log_likelihood(corpus, model) - corpus_log_likelihood(corpus, remove_piece(model, w))
def seed_vocabulary(corpus: Dict[str, int], size: int, max_piece: int) -> Dict[str, int]:
"""Every character of the corpus, plus the most frequent substrings of length 2..max_piece
inside the words (ties to the shorter, then smaller string), up to size pieces in all."""
freq: Dict[str, int] = {}
for x, c in corpus.items():
for i in range(len(x)):
for j in range(i + 1, min(len(x), i + max_piece) + 1):
freq[x[i:j]] = freq.get(x[i:j], 0) + c
chars = {w: f for w, f in freq.items() if len(w) == 1}
longer = sorted((w for w in freq if len(w) > 1), key=lambda w: (-freq[w], len(w), w))
seed = dict(chars)
for w in longer[: max(0, size - len(chars))]:
seed[w] = freq[w]
return seed
def floor_characters(model: Model) -> Model:
"""Give each character of probability 0 the smallest positive probability of the
model, then renormalize. EM can drive a character to 0 when longer pieces always
cover it; the floor keeps every word over the alphabet segmentable (a choice of
this page, not a step of Kudo's paper)."""
low = min(lp for lp in model.values() if lp != NEG_INF)
out = {w: (low if lp == NEG_INF and len(w) == 1 else lp) for w, lp in model.items()}
out = {w: lp for w, lp in out.items() if lp != NEG_INF}
z = log_sum(out.values())
return {w: lp - z for w, lp in out.items()}
def train(corpus: Dict[str, int], target: int, seed_size: int = 100, max_piece: int = 8,
eta: float = 0.8, em_iters: int = 2) -> Model:
"""Kudo's vocabulary learning: EM, then keep the eta share of pieces with the largest loss."""
seed = seed_vocabulary(corpus, seed_size, max_piece) # @line T1
z = sum(seed.values())
model = {w: safe_log(f / z) for w, f in seed.items()} # @line T2
while True: # @line T3
for _ in range(em_iters): # @line T4
model = em_step(corpus, model)
model = floor_characters(model) # @line T5
chars = [w for w in model if len(w) == 1]
if len(model) <= target or len(chars) == len(model): # @line T6
return model
loss = {w: piece_loss(corpus, model, w) for w in model if len(w) > 1} # @line T7
keep = max(target, int(eta * len(model))) - len(chars) # @line T8
kept = sorted(loss, key=lambda w: (-loss[w], w))[: max(0, keep)] # @line T9
model = {w: model[w] for w in chars + kept} # @line T10
z = log_sum(model.values())
model = {w: lp - z for w, lp in model.items()} # @line T11
def segmentations(x: str, model: Model) -> List[List[str]]:
"""All segmentations of x into pieces of the model (for tests and small examples)."""
if not x:
return [[]]
out = []
for j in range(1, len(x) + 1):
if x[:j] in model:
out.extend([[x[:j]] + rest for rest in segmentations(x[j:], model)])
return out
test_unigram_language_model_tokenization.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unigram-language-model-tokenization/. The authors are listed in prov/9PE3NB.jsonl.
import math
import random
from fractions import Fraction
from nlslog import NEG_INF
from unigram_language_model_tokenization import (
backward,
corpus_log_likelihood,
em_step,
expected_counts,
forward,
log_prob,
piece_loss,
remove_piece,
seed_vocabulary,
segmentations,
train,
viterbi,
)
PAGE = {"h": Fraction(1, 10), "u": Fraction(1, 10), "g": Fraction(1, 10), "s": Fraction(15, 100),
"hu": Fraction(1, 10), "ug": Fraction(15, 100), "hug": Fraction(2, 10), "gs": Fraction(5, 100),
"ugs": Fraction(5, 100)}
CORPUS = {"hug": 10, "pug": 5, "pun": 12, "bun": 4, "hugs": 5}
def as_model(probs):
return {w: math.log(p) for w, p in probs.items()}
def exact(x, probs):
"""Brute force with Fractions: {segmentation: probability}."""
out = {}
for s in segmentations(x, probs):
q = Fraction(1)
for w in s:
q *= probs[w]
out[tuple(s)] = q
return out
def random_probs(rng, alphabet, k):
pieces = set(alphabet)
while len(pieces) < len(alphabet) + k:
pieces.add("".join(rng.choice(alphabet) for _ in range(rng.randint(2, 4))))
weights = {w: Fraction(rng.randint(1, 20)) for w in sorted(pieces)}
z = sum(weights.values())
return {w: q / z for w, q in weights.items()}
def test_page_example():
probs = exact("hugs", PAGE)
assert len(probs) == 7
assert sum(probs.values()) == Fraction(111, 2500)
m = as_model(PAGE)
assert abs(log_prob("hugs", m) - math.log(Fraction(111, 2500))) < 1e-12
score, pieces = viterbi("hugs", m)
assert pieces == ["hug", "s"] and abs(score - math.log(Fraction(3, 100))) < 1e-12
alpha = [math.exp(a) for a in forward("hugs", m)]
beta = [math.exp(b) for b in backward("hugs", m)]
for got, want in zip(alpha, [1, 0.1, 0.11, 0.226, 0.0444]):
assert abs(got - want) < 1e-12
for got, want in zip(beta, [0.0444, 0.079, 0.065, 0.15, 1]):
assert abs(got - want) < 1e-12
assert abs(expected_counts("hugs", m)["hug"] - 75 / 111) < 1e-12
def test_viterbi_forward_and_counts_match_brute_force():
rng = random.Random(1)
for _ in range(60):
probs = random_probs(rng, "abc", rng.randint(1, 8))
m = as_model(probs)
x = "".join(rng.choice("abc") for _ in range(rng.randint(1, 9)))
table = exact(x, probs)
total = sum(table.values())
assert abs(log_prob(x, m) - math.log(total)) < 1e-9
best = max(table.values())
score, pieces = viterbi(x, m)
assert abs(score - math.log(best)) < 1e-9 and table[tuple(pieces)] == best
counts = expected_counts(x, m)
for w in probs:
want = sum(q * s.count(w) for s, q in table.items()) / total
assert abs(counts.get(w, 0.0) - float(want)) < 1e-9
def test_no_segmentation():
m = as_model({"a": Fraction(1, 2), "bc": Fraction(1, 2)})
assert viterbi("ab", m) == (NEG_INF, None)
assert log_prob("ab", m) == NEG_INF
assert viterbi("", m) == (0.0, [])
def test_em_never_lowers_the_likelihood():
rng = random.Random(2)
for _ in range(5):
corpus = {"".join(rng.choice("ab") for _ in range(rng.randint(1, 6))): rng.randint(1, 5) for _ in range(6)}
m = as_model(random_probs(rng, "ab", 6))
last = corpus_log_likelihood(corpus, m)
for _ in range(8):
m = em_step(corpus, m)
now = corpus_log_likelihood(corpus, m)
assert now >= last - 1e-9
last = now
assert abs(math.fsum(math.exp(lp) for lp in m.values()) - 1) < 1e-9
def test_page_em_trace():
seed = seed_vocabulary(CORPUS, 100, 8)
assert len(seed) == 19 and sum(len(w) == 1 for w in seed) == 7
z = sum(seed.values())
m = {w: math.log(f / z) for w, f in seed.items()}
trace = [corpus_log_likelihood(CORPUS, m)]
for _ in range(3):
m = em_step(CORPUS, m)
trace.append(corpus_log_likelihood(CORPUS, m))
assert [round(v, 2) for v in trace] == [-110.31, -68.21, -55.62, -54.54]
def test_loss_is_the_drop_in_likelihood():
m = as_model(PAGE)
corpus = {"hugs": 1}
rest = remove_piece(m, "hug")
assert abs(math.fsum(math.exp(lp) for lp in rest.values()) - 1) < 1e-12
q = Fraction(1) / (1 - PAGE["hug"])
without = sum(exact("hugs", {w: p * q for w, p in PAGE.items() if w != "hug"}).values())
want = math.log(Fraction(111, 2500)) - math.log(without)
assert abs(piece_loss(corpus, m, "hug") - want) < 1e-12
def test_training_keeps_characters_and_reaches_the_target():
m = train(CORPUS, 10)
assert len(m) <= 10
assert set("hugpnbs") <= set(m)
assert abs(math.fsum(math.exp(lp) for lp in m.values()) - 1) < 1e-9
assert viterbi("pugs", m)[1] == ["pug", "s"]
assert viterbi("bugs", m)[1] == ["b", "u", "g", "s"]
assert all(lp > NEG_INF for lp in m.values())
assert set(m) == set("hugpnbs") | {"hug", "pun", "pug"}
assert abs(expected_counts("hugs", as_model(PAGE))["s"] - 0.0339 / 0.0444) < 1e-12
assert set(train(CORPUS, 12)) == set("hugpnbs") | set(CORPUS)
def test_log_space_avoids_underflow():
# "a" * 3000 with p(a) = p(aa) = 1/2. P(x) satisfies Z(n) = (Z(n-1) + Z(n-2)) / 2.
n = 3000
probs = {"a": Fraction(1, 2), "aa": Fraction(1, 2)}
z_prev, z = Fraction(1), Fraction(1, 2)
for _ in range(n - 1):
z_prev, z = z, (z + z_prev) / 2
want = math.log(z.numerator) - math.log(z.denominator)
plain = 1.0
for _ in range(n):
plain *= 0.5
assert plain == 0.0 # the product of one segmentation underflows
got = log_prob("a" * n, as_model(probs))
assert got > NEG_INF and abs(got - want) < 1e-9 * abs(want)
score, pieces = viterbi("a" * n, as_model(probs))
assert pieces == ["aa"] * (n // 2) and abs(score - (n // 2) * math.log(0.5)) < 1e-9
History
Kudo (2018) proposed the unigram model of pieces to get many segmentations with probabilities for subword regularization, and compared it with byte-pair encoding, which gives one segmentation. The same year, Kudo and Richardson released SentencePiece, which implements both models.
References
- Taku Kudo, Subword regularization, Improving neural network translation models with multiple subword candidates, ACL 2018, pages 66 to 75, Section 3.2, Unigram language model (Equations 6 and 7, the EM objective and the four-step vocabulary algorithm with eta = 80, page 68), the seed vocabulary paragraph (page 69), and Section 3.3, Subword sampling
- Taku Kudo and John Richardson, SentencePiece, A simple and language independent subword tokenizer and detokenizer for neural text processing, EMNLP 2018 System Demonstrations, the library that ships the unigram model as one of its two segmentation algorithms
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 9PE3NB Edit this page History Report an error Markdown