Unigram tokenization: sum the paths before choosing one
Unigram 分词模型
Compute segmentation marginals, Viterbi paths, expected counts and a complete small-vocabulary EM update.
tokenizer-unigramOne string, two explanations
Take the teaching vocabulary a, b, ab, with piece probabilities 0.4, 0.3 and 0.3. The string ab has two segmentations: one piece ab, or two pieces a | b. The first has score 0.3; the second has score . Which number describes the observed string: 0.3 or 0.42?
For maximum-path decoding, choose the first path. For a marginal training objective, add both paths and obtain 0.42. For sampling a segmentation of this particular string, normalize the scores: the one-piece path has probability . Those are three different operations on the same candidate set.
Kudo’s 2018 paper learns a Unigram subword model and uses competing segmentations for subword regularization. “Unigram” means that a path’s piece scores factor independently. It does not mean choosing one character at a time, nor that pieces are conditionally independent after requiring them to concatenate to a specified string. The competing paths must all spell that string.
A lattice turns exponential enumeration into shared work
Let be a finite vocabulary of nonempty pieces with probabilities summing to one. A segmentation has product score
For an observed string , let be all segmentations whose concatenation equals . Define its marginal weight and the posterior of a segmentation:
The paper writes the string marginal as . Here makes the normalization being used explicit: this small model does not include an end-of-sequence or length distribution that would turn it into a generative model over all finite strings. The posterior over this string’s finite segmentation set is nevertheless normalized. Training below optimizes the specified sum of log marginal weights, not a complete natural-language probability model.
Maximum-path decoding uses addition of log probabilities and maximization, usually called Viterbi decoding:
Draw positions along a string of characters. An edge from to exists when the substring is a vocabulary piece. Every complete path spells the string. A forward value sums the weights of paths ending at ; a backward value sums those beginning at :
Both and equal . Prefixes shared by many paths are computed once. With the lattice already built, these sums take time and space for edges; enumerating every path can grow exponentially.
An edge’s posterior mass is the product of its prefix mass, piece probability and suffix mass, divided by the total. Sum those masses for every occurrence of a piece to get its expected count:
For ab, the expected counts are for a, for b, and for ab. They sum to , the expected number of pieces, not one. Weighting by piece lengths instead gives 2, the string’s fixed character length.
For corpus frequencies , an EM step first computes these expectations under the old parameters. Maximizing the expected complete-path log score subject to probabilities summing to one gives the normalized expected-count update:
This follows by differentiating with a Lagrange multiplier for : the stationary point is proportional to . The objective is . A full-vocabulary EM step should not decrease it in exact arithmetic. Vocabulary pruning is a different operation: the paper starts from a larger candidate vocabulary, estimates the loss caused by removing pieces, and retains individual characters to avoid losing coverage. Our implementation fixes the vocabulary and does not claim to reproduce that trainer. The original method describes both stages.
For subword regularization, a positive exponent changes the posterior used for sampling:
Smaller flattens the distribution over valid paths; larger favors the maximum-scoring paths. Do not renormalize individual before computing this expression: paths have different lengths, so that would introduce an extra length-dependent factor. The program uses backward weights followed by forward sampling; this is the reverse traversal counterpart of the paper’s forward-filtering/backward-sampling explanation.
Learn three probabilities and audit every path
This standard-library Python 3.12 program builds the lattice explicitly, computes both sum and maximum scores, performs twenty fixed-vocabulary EM updates, and draws 2,000 segmentations with seed 7. The nine training records represented by the four frequency entries are authored teaching data, not a translation corpus.
"""Exact small-lattice unigram segmentation and fixed-vocabulary EM."""
import json
import math
import random
def validate(prob):
if not prob or any(not x or not math.isfinite(p) or p <= 0 for x, p in prob.items()):
raise ValueError("Nonempty pieces need finite positive probabilities")
if not math.isclose(sum(prob.values()), 1.0, abs_tol=1e-12):
raise ValueError("Piece probabilities must sum to one")
def lattice(text, prob, alpha=1.0):
validate(prob)
if not math.isfinite(alpha) or alpha <= 0:
raise ValueError("Need a finite positive sampling exponent")
edges = [[] for _ in range(len(text) + 1)]
for i in range(len(text)):
for piece, p in prob.items():
if text.startswith(piece, i):
edges[i].append((i + len(piece), piece, p ** alpha))
return edges
def forward_backward(text, prob, alpha=1.0):
edges = lattice(text, prob, alpha)
n = len(text)
f, b = [0.0] * (n + 1), [0.0] * (n + 1)
f[0], b[n] = 1.0, 1.0
for i in range(n):
for j, _, weight in edges[i]:
f[j] += f[i] * weight
for i in range(n - 1, -1, -1):
b[i] = sum(weight * b[j] for j, _, weight in edges[i])
if f[n] <= 0:
raise ValueError("No path, or probability underflow: use log space for long text")
return edges, f, b
def viterbi(text, prob):
edges = lattice(text, prob)
best = [(-math.inf, ()) for _ in range(len(text) + 1)]
best[0] = (0.0, ())
for i, row in enumerate(edges):
for j, piece, p in row:
score = best[i][0] + math.log(p)
if score > best[j][0]:
best[j] = (score, best[i][1] + (piece,))
if not math.isfinite(best[-1][0]):
raise ValueError("No complete segmentation")
return best[-1]
def expected_counts(text, prob):
edges, f, b = forward_backward(text, prob)
counts = dict.fromkeys(prob, 0.0)
for i, row in enumerate(edges):
for j, piece, weight in row:
counts[piece] += f[i] * weight * b[j] / f[-1]
return counts, math.log(f[-1])
def em_step(corpus, prob):
if not corpus or any(not x or not isinstance(w, int) or w <= 0 for x, w in corpus.items()):
raise ValueError("Need nonempty strings and positive integer counts")
total = dict.fromkeys(prob, 0.0)
for text, freq in corpus.items():
counts, _ = expected_counts(text, prob)
for piece in prob:
total[piece] += freq * counts[piece]
# This teaching EM keeps all pieces active; unused candidates must be removed explicitly.
if min(total.values()) <= 0:
raise ValueError("A vocabulary piece never occurs in this corpus")
mass = sum(total.values())
return {piece: count / mass for piece, count in total.items()}
def sample(text, prob, rng, alpha=1.0):
edges, _, b = forward_backward(text, prob, alpha)
i, pieces = 0, []
while i < len(text):
options = [(j, piece, weight * b[j]) for j, piece, weight in edges[i] if b[j] > 0]
threshold = rng.random() * sum(w for _, _, w in options)
selected = options[-1]
for choice in options:
threshold -= choice[2]
if threshold < 0:
selected = choice
break
i, piece, _ = selected
pieces.append(piece)
return tuple(pieces)
def demo():
p = {"a": .4, "b": .3, "ab": .3}
counts, log_z = expected_counts("ab", p)
trained = p.copy()
corpus = {"ab": 4, "a": 2, "b": 1, "aba": 2}
losses = []
for step in range(21):
losses.append(-sum(f * expected_counts(x, trained)[1] for x, f in corpus.items()))
if step < 20:
trained = em_step(corpus, trained)
rng = random.Random(7)
draws = [sample("ab", p, rng) for _ in range(2000)]
return dict(probabilities=p, marginal=math.exp(log_z),
best=list(viterbi("ab", p)[1]), expected=counts,
posterior_ab=.3 / math.exp(log_z),
sample_ab_fraction=draws.count(("ab",)) / len(draws),
temperature_posteriors={str(a): .3 ** a / (.3 ** a + .12 ** a)
for a in [.5, 1., 2.]},
corpus=corpus, training_nll=losses, trained=trained)
if __name__ == "__main__":
print(json.dumps(demo(), ensure_ascii=False, indent=2))
The initial ab marginal is 0.42 and its Viterbi segmentation is ['ab']. The sample fraction for that path is 0.6965, close to but not exactly its theoretical . The exact posterior at exponents 0.5, 1 and 2 is approximately 0.612574, 0.714286 and 0.862069 respectively. Sampling noise must not be mistaken for a changed definition.
After twenty EM updates, the probabilities are approximately 0.400001, 0.142858 and 0.457141 for a, b and ab. The corpus negative log marginal decreases to about 9.600931. It is a frequency-weighted total, not a per-character or per-token average. Tests enumerate all segmentations of short binary strings independently and compare both the marginal and maximum path; another check verifies the expected counts directly from that enumeration.
The simple lattice constructor tries every vocabulary piece at every character position. With maximum piece length , this costs up to character comparisons; a trie can share prefix work. The sum/count routines use storage. Our readable Viterbi implementation copies path tuples instead of storing backpointers, adding up to work and stored path elements in the worst case. A backpointer implementation avoids that overhead. Raw probability products can underflow on long strings; production implementations need stable log-space sums or scaling.
The longest piece is not automatically the winner
Change the piece probabilities to a:0.45, b:0.45, ab:0.10. Now a | b scores 0.2025 and beats the longer piece’s 0.10. Unigram decoding follows learned scores, not a longest-match rule. Likewise, preserving all single training characters does not cover characters never seen during training.
The model does not understand syntax merely because its segmentations are probabilistic. Its independence assumption ignores neighboring-piece preferences in the path score; a downstream language model handles a different prediction problem. Sampling tokenizations during model training changes the representation the model encounters, but does not by itself prove improved quality on a particular language or task.
The toy EM rejects vocabulary pieces with zero expected occurrence rather than silently keeping or deleting them. Real vocabulary construction, pruning, character fallback and normalization require additional policies. SentencePiece’s system paper places these decisions in a tokenizer pipeline; the SentencePiece chapter trains a real packaged model. Our calculation isolates the probability mechanism so every path can be checked.
Use the sum and the maximum for different questions
- Why is the Viterbi score 0.30 but the marginal weight 0.42 for the initial
abexample?
Answer: Viterbi selects the better of the scores 0.30 and 0.12. The marginal adds both because either hidden segmentation can explain the observed string. A best-path score does not include alternative paths.
- If the entire corpus is one occurrence of
ab, what is one EM update from the initial probabilities?
Answer: Expected counts are , whose total is . Normalizing gives , and . Dividing by one string instead of the expected number of pieces would fail to normalize.
- Can increasing the sampling exponent force the longest segmentation piece to win?
Answer: No. It favors higher path scores. With probabilities 0.45, 0.45 and 0.10, the two-piece path already has higher score, so increasing the exponent favors that path. At a tied maximum, the limiting mass need not concentrate on a single path.
- A developer replaces the sum over paths by the Viterbi maximum during EM. Is this the same marginal objective computed faster?
Answer: No. It discards posterior mass and changes the training procedure to a hard-path approximation. Forward/backward shares work without discarding paths; it gives exact sums for the finite lattice, subject to numerical precision.
Separate the tokenizer model from the translation experiment
Kudo, sections 3.1–3.4, supplies the Unigram factorization, Viterbi objective, vocabulary-learning outline and tempered sampling. The SentencePiece paper explains how such a model is trained and used alongside normalization and ID management. The calculations here verify a fixed three-piece model and a tiny EM objective. They do not reproduce vocabulary pruning at corpus scale or the papers’ machine-translation comparisons. Compare BPE when you want to see how a saved merge order replaces a probability lattice.
Make a prediction, then check
For ab, path scores are 0.30 and 0.12. What is the posterior of the one-piece path?
Learning objectives
- Distinguish a piece probability, a path score and a posterior over segmentations.
- Derive forward/backward expected counts and check a fixed-vocabulary EM step.
- Compare maximum-path decoding with tempered sampling and explain pruning constraints.
Prerequisites & connections
Explore related knowledge →References
- Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates
Taku Kudo · 2018 - SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing
Taku Kudo; John Richardson · 2018
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked Kudo sections 3.1–3.4/equations 6–7 and the SentencePiece pipeline. Seven paired equations and four explained exercises; independent exhaustive paths check marginal, Viterbi and expected counts; fixed-vocabulary EM hand update and monotonicity; tempered sampling. No EOS/length model, full vocabulary pruning or NMT reproduction.
- Single AI author checked Kudo sections 3.1–3.4/equations 6–7 and the SentencePiece pipeline. Seven paired equations and four explained exercises; independent exhaustive paths check marginal, Viterbi and expected counts; fixed-vocabulary EM hand update and monotonicity; tempered sampling. No EOS/length model, full vocabulary pruning or NMT reproduction.
- Four computed SVG variants per topic; 10 numeric/geometry tests and 24 responsive cases passed. Eight Chinese-mobile/English-desktop figure screenshots actually viewed. Full article acceptance recorded separately.
Source locations checked:
- Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates · Read sections 3.1–3.4; viewed PDF pages 3–4, including equations 6–7, EM, vocabulary pruning and segmentation sampling. No NMT experiments reproduced.
- SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing · Read section 2 and sections 3.1–3.4; viewed PDF pages 2–3. Normalized-text roundtrip, whitespace, IDs and the NFKC limitation in footnote 3; no throughput reproduction.
Related topics