Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
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 TT. The output is a vocabulary of pieces (nonempty strings) and a probability p(w)p(w) for each piece ww, with ∑wp(w)=1\sum_w p(w) = 1. The input of encoding is a word xx of nn characters, and the output is a segmentation of xx: a list of pieces whose concatenation is xx.

The model is a unigram language model of pieces: the pieces of a segmentation ss are independent, so (Kudo's Equation 6)

P(s)=∏w∈sp(w),P(x)=∑sP(s),P(s) = \prod_{w \in s} p(w), \qquad P(x) = \sum_{s} P(s),

where the sum runs over all segmentations ss of xx. Encoding returns arg⁡max⁡sP(s)\arg\max_s P(s) (Equation 7). Training maximizes the corpus log likelihood L=∑xfxlog⁡P(x)L = \sum_x f_x \log P(x), where fxf_x is the count of the word xx; all logs on this page are natural logs. Positions in a word are fenceposts 0,…,n0, \ldots, n, and the piece x[i:j]x[i{:}j] covers the characters between positions ii and jj. The pieces x[i:j]x[i{:}j] of the vocabulary are the edges of a word lattice on these positions, and a segmentation is a path from 00 to nn.

The algorithm

Encoding is the Viterbi algorithm on the lattice, in the VITERBI semiring (log probabilities, plus = max, times = +):

  1. VITERBI(x, p)
  2. V1 best[j] ← -∞ for j = 0..n
  3. V2 best[0] ← 0
  4. V3 for j ← 1 to n
  5. V4 for i ← max(0, j - m) to j - 1
  6. V5 if x[i:j] is a piece and best[i] > -∞
  7. V6 if best[i] + log p(x[i:j]) > best[j] then best[j] ← that value; back[j] ← i
  8. V7 follow back[] from n to 0, collecting the pieces x[back[j]:j]
  9. 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 α[j]\alpha[j] is the log of the total probability of the segmentations of x[:j]x[{:}j], and the backward value β[i]\beta[i] is that of x[i:]x[i{:}]. The piece x[i:j]=wx[i{:}j] = w is used with posterior probability exp⁡(α[i]+log⁡p(w)+β[j]−log⁡P(x))\exp(\alpha[i] + \log p(w) + \beta[j] - \log P(x)).

  1. EM-STEP(corpus, p)
  2. E1 C[w] ← 0 for every piece w
  3. E2 for each word x with count f in the corpus
  4. E3 for each piece w, with E[c_w] the expected uses of w in x (forward-backward)
  5. E4 C[w] ← C[w] + f · E[c_w]
  6. E5 Z ← the sum of C[w] over the pieces
  7. E6 return the model p'(w) = C[w] / Z

Training follows the four steps of Kudo's Section 3.2. The loss of a piece ww is L(p)−L(p−w)L(p) - L(p_{-w}), where p−wp_{-w} is pp without ww, renormalized.

  1. TRAIN-UNIGRAM(corpus, T, eta)
  2. T1 seed ← every character, plus the most frequent substrings of the words
  3. T2 p ← the relative frequencies of the seed pieces
  4. T3 loop
  5. T4 run a few EM steps on p
  6. T5 give each character of probability 0 the smallest positive probability, drop other pieces of probability 0, and renormalize
  7. T6 if p has at most T pieces, or only characters, then return p
  8. T7 loss(w) ← L(p) - L(p without w), for each piece w of length 2 or more
  9. T8 k ← max(T, ⌊eta · |p|⌋) - (the number of characters)
  10. T9 keep the k pieces of largest loss
  11. T10 p ← the characters and the kept pieces
  12. T11 renormalize p

Kudo gives η=80\eta = 80 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 P(hugs)=0.0444P(\text{hugs}) = 0.0444, so log⁡P=−3.1145\log P = -3.1145. 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 0.03/0.0444=0.67570.03 / 0.0444 = 0.6757, 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 −110.31-110.31 for the seed frequencies, and −68.21-68.21, −55.62-55.62 and −54.54-54.54 after one, two and three EM steps. With T=10T = 10 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 nn are exactly the segmentations, and the weight of a path is the probability of its segmentation. By induction on jj, 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 P(x)P(x), is the posterior use of that edge. An EM step never lowers LL, 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 TT 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 pp from a finite set of pieces (nonempty strings) to probabilities with ∑wp(w)=1\sum_w p(w) = 1. All logs are natural logs. A word xx has nn characters, and positions are fenceposts 0,1,…,n0, 1, \ldots, n: the piece x[i:j]x[i{:}j] covers the characters after position ii up to position jj. A segmentation of xx is a list of pieces whose concatenation is xx; its probability is P(s)=∏w∈sp(w)P(s) = \prod_{w \in s} p(w), with one factor per use, and P(x)=∑sP(s)P(x) = \sum_s P(s). The lattice has the positions as nodes and an edge i→ji \to j of weight p(x[i:j])p(x[i{:}j]) for each piece x[i:j]x[i{:}j] of the model. A segmentation is a path from 00 to nn, and its probability is the product of the edge weights.

Lemma 1 (paths). The map from segmentations of xx to paths 0→n0 \to n in the lattice is a bijection that keeps the probability.

Proof. A segmentation w1⋯wrw_1 \cdots w_r fixes the cut positions 0=c0<c1<⋯<cr=n0 = c_0 < c_1 < \cdots < c_r = n with wk=x[ck−1:ck]w_k = x[c_{k-1}{:}c_k], and each wkw_k is a piece, so each step is an edge. Conversely a path c0,…,crc_0, \ldots, c_r gives the pieces x[ck−1:ck]x[c_{k-1}{:}c_k], which join to xx. The two maps are inverse, and both products have the same factors. □\square

Theorem 1 (Viterbi). In the VITERBI semiring (log probabilities, plus = max, times = +), line V6 gives best[j]=max⁡slog⁡P(s)\mathrm{best}[j] = \max_s \log P(s) over the segmentations ss of x[:j]x[{:}j], and VITERBI returns a segmentation of xx of the largest probability, or reports that none exists.

Proof. By induction on jj. For j=0j = 0 the only segmentation is empty, with log probability 00 (line V2). For j>0j > 0, the last piece of a segmentation of x[:j]x[{:}j] is some x[i:j]x[i{:}j] in the model, and the rest is a segmentation of x[:i]x[{:}i]; the log probability is the sum of the two parts. Lines V4 to V6 take the max over ii of best[i]+log⁡p(x[i:j])\mathrm{best}[i] + \log p(x[i{:}j]), which by the induction hypothesis is the max over all segmentations. The pointer back[j]\mathrm{back}[j] keeps an ii that reaches the max, so lines V7 and V8 rebuild a best segmentation. If no segmentation exists, best[n]\mathrm{best}[n] stays at the semiring zero, −∞-\infty. □\square

Theorem 2 (forward and backward). In the LOG semiring (plus = log-add, times = +), α[j]=log⁡∑sP(s)\alpha[j] = \log \sum_s P(s) over the segmentations of x[:j]x[{:}j], and β[i]=log⁡∑sP(s)\beta[i] = \log \sum_s P(s) over the segmentations of x[i:]x[i{:}]. So α[n]=β[0]=log⁡P(x)\alpha[n] = \beta[0] = \log P(x).

Proof. The same induction as for Theorem 1, with the sum in place of the max: the segmentations of x[:j]x[{:}j] 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 β\beta runs from the right end. □\square

Theorem 3 (expected counts). For each piece ww, EXPECTED-COUNTS returns E[cw]=∑sP(s∣x) cw(s)E[c_w] = \sum_s P(s \mid x)\, c_w(s), where cw(s)c_w(s) is the number of uses of ww in ss and P(s∣x)=P(s)/P(x)P(s \mid x) = P(s) / P(x).

Proof. Write cw(s)c_w(s) as the number of edges i→ji \to j on the path of ss with x[i:j]=wx[i{:}j] = w. Swap the two sums: E[cw]=∑(i,j):x[i:j]=w∑s∋(i,j)P(s)/P(x)E[c_w] = \sum_{(i, j) : x[i{:}j] = w} \sum_{s \ni (i, j)} P(s) / P(x). A path through the edge i→ji \to j is a path 0→i0 \to i, then the edge, then a path j→nj \to n, and these choices are free, so the inner sum is exp⁡(α[i]) p(w) exp⁡(β[j])\exp(\alpha[i]) \, p(w) \, \exp(\beta[j]) by Theorem 2. The code adds exp⁡(α[i]+log⁡p(w)+β[j]−α[n])\exp(\alpha[i] + \log p(w) + \beta[j] - \alpha[n]) over these edges. □\square

Theorem 4 (EM). Let L(p)=∑xfxlog⁡Pp(x)L(p) = \sum_x f_x \log P_p(x) for a corpus with word counts fxf_x, and let p′p' be the model of EM-STEP. Then L(p′)≥L(p)L(p') \ge L(p).

Proof. This is the EM inequality for the hidden segmentation. Let Q(q)=∑xfx∑sPp(s∣x)log⁡Pq(s)Q(q) = \sum_x f_x \sum_s P_p(s \mid x) \log P_q(s). For each word, Jensen's inequality on the concave log gives log⁡Pq(x)−log⁡Pp(x)=log⁡∑sPp(s∣x)Pq(s)Pp(s)≥∑sPp(s∣x)log⁡Pq(s)Pp(s)\log P_q(x) - \log P_p(x) = \log \sum_s P_p(s \mid x) \frac{P_q(s)}{P_p(s)} \ge \sum_s P_p(s \mid x) \log \frac{P_q(s)}{P_p(s)}, so L(q)−L(p)≥Q(q)−Q(p)L(q) - L(p) \ge Q(q) - Q(p). Now Q(q)=∑wCwlog⁡q(w)Q(q) = \sum_w C_w \log q(w) with Cw=∑xfxEp[cw]C_w = \sum_x f_x E_p[c_w], by Theorem 3. Over the probability vectors qq on the pieces, ∑wCwlog⁡q(w)\sum_w C_w \log q(w) is largest at q(w)=Cw/∑vCvq(w) = C_w / \sum_v C_v (Gibbs' inequality), which is what lines E1 to E6 compute. So Q(p′)≥Q(p)Q(p') \ge Q(p) and L(p′)≥L(p)L(p') \ge L(p). A piece with Cw=0C_w = 0 gets q(w)=0q(w) = 0, that is −∞-\infty in log space. □\square

Theorem 5 (termination of TRAIN). TRAIN stops, and its result has at most max⁡(T,A)\max(T, A) pieces, where TT is the target size and AA 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 00 that are not single characters. If the loop does not stop at line T6, the model has more than TT pieces and at least one piece of length 2 or more. Line T8 sets the new size to max⁡(T,⌊ηN⌋)\max(T, \lfloor \eta N \rfloor), which is less than the current size NN because N>TN > T and η<1\eta < 1, 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 N0N_0 rounds for a seed of N0N_0 pieces. At the stop, either the size is at most TT or only characters are left. □\square

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 TT of the largest likelihood, and the page does not claim that it does.

Complexity

Let mm be the length of the longest piece and VV the vocabulary size. With the pieces in a trie, the edges that start at one position are found in O(m)O(m) steps, so the lattice of a word has O(nm)O(n m) edges, and Viterbi, forward and backward each take O(nm)O(n m) time in the word-RAM model, with O(n)O(n) space for the tables. The code here looks up each substring in a hash table, which adds a factor mm for hashing. One EM step over a corpus of total length NN takes O(Nm)O(N m) time, plus O(V)O(V) to normalize. The exact losses of line T7 need one likelihood per piece, O(VNm)O(V N m) 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 kk 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 P(s)aP(s)^a for a smoothing value aa, either from the ll best or exactly by forward filtering and backward sampling (Kudo's Section 3.3).
  • n-best decoding. Kudo's Section 2.2 translates the nn 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, T=12T = 12 keeps all five words and the 7 characters, and T=10T = 10 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.

nlslog.pyI0RawGitHub
# 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

  1. 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
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.em_step
  • a full proof of time.encode
  • a full proof of time.exact_losses
  • a full proof of space.encode
  • a full proof of space.model
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example