Techniqueadvanced
Subword regularization
Also called stochastic subword segmentation.
Sample a different segmentation of each training sentence from a unigram tokenization model, so the network sees many splits and grows robust.
Subword regularization trains a model on random segmentations of its input instead of one fixed segmentation. Each time a sentence is used in training, its words are split into subword pieces by sampling from a probabilistic tokenizer, so the same word reaches the model as different rows of pieces. Kudo (2018) introduced it with the unigram language model tokenizer and showed gains in machine translation. At test time the model gets the single most probable segmentation, or a few of them.
In plain words
A tokenizer that always cuts a word the same way hides the fact that the word could be cut in other ways. A model trained on one cut never learns that "un" + "related" and "unrel" + "ated" spell the same word, so it is fragile when a rare or misspelled word is cut in an unusual way.
Subword regularization picks a fresh cut for each word every time the model sees it during training. Likely cuts come up often, unlikely ones less often, and a dial sets how adventurous the picks are. The model learns from many cuts of the same text, which acts like extra training data. When the model is used, the picking stops and the best cut is used.
When it applies
It needs a tokenizer that defines a probability for every segmentation of a word, such as the unigram language model, or a random procedure that gives many segmentations, such as BPE-dropout. It needs a model that is trained by many passes over the data, so that each sentence is segmented many times. It helps most when the data is small or the test text differs from the training text. Kudo applies it to both the source and the target side of a translation model, and it needs no change to the model, only to the data it reads.
The template
Let a model give each piece a probability , and let for a segmentation of a word . For a smoothing value , sample with probability
where the sum runs over the candidates . A small makes the law flatter, and a large moves it to the Viterbi segmentation. Kudo uses one sample per sentence per update ( in his Equation 4); over many updates this approximates training on the marginal likelihood over all segmentations.
There are two ways to draw . The first takes the best segmentations and draws one of them:
SAMPLE-NBEST(x, p, a, l)N1 T ← the l best segmentations of x, with their log probabilitiesN2 Z ← the log-add over t in T of a · log P(t)N3 draw r uniform in [0, 1)N4 return the first t of T where the running sum of exp(a · log P(t) - Z) exceeds r
The second draws from all segmentations, exactly, by forward filtering and backward sampling on the word lattice. Positions are fenceposts , and the piece is the edge from to . The forward pass runs in the LOG semiring (log probabilities, plus = log-add, times = +) with the edge weights , natural logs:
SAMPLE-LATTICE(x, p, a)S1 alpha ← the forward values of x with the edge weights a · log p(w)S2 if alpha[n] = -∞ then fail: x has no segmentationS3 pieces ← empty; j ← nS4 while j > 0S5 give each start i of a piece x[i:j] the weight exp(alpha[i] + a · log p(x[i:j]) - alpha[j])S6 draw a start i with these weightsS7 put x[i:j] in front of pieces; j ← iS8 return pieces
The weights of line S5 sum to 1, and the product of the weights along the drawn path telescopes to ; proofs/correctness.md gives the proof. One sample costs as much as one forward pass, linear in the size of the lattice.
Kudo decodes either from the best segmentation (one-best decoding) or from the best, and then keeps the translation with the best score , where is a length penalty tuned on development data (n-best decoding).
Classic examples
The word "hugs". 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 of the unigram page. The word has 7 segmentations. The law for three values of :
| segmentation | a = 1 | a = 0.5 | a = 2 |
|---|---|---|---|
| hug s | 0.6757 | 0.3978 | 0.9399 |
| h ugs | 0.1126 | 0.1624 | 0.0261 |
| hu gs | 0.1126 | 0.1624 | 0.0261 |
| h ug s | 0.0507 | 0.1089 | 0.0053 |
| hu g s | 0.0338 | 0.0890 | 0.0023 |
| h u gs | 0.0113 | 0.0514 | 0.0003 |
| h u g s | 0.0034 | 0.0281 | 0.00002 |
With the law is the posterior , and . With and , the three best are hug s, h ugs and hu gs, with the probabilities 0.75, 0.125 and 0.125: the rest of the law is cut off. In a measurement with 10,000 draws by the lattice sampler at and the seed 0, hug s came up 3,999 times, close to the 3,978 that the law predicts.
Translation. In Kudo's experiments (Section 5.1), the samplers used with , and (the lattice sampler) with on the IWSLT data and on the others. Subword regularization raised BLEU by 1 to 2 points on all language pairs but one (Section 5.2), and by about 2 points on out-of-domain data (Section 5.3). These are measurements on those tasks.
Variations
- BPE-dropout. Provilkov, Emelianenko and Voita (2020) get random segmentations from a BPE merge table by skipping merges at random. It needs no unigram model, and they report better BLEU than Kudo's sampling on their tasks.
- l-best against the lattice. The -best list needs a k-shortest-paths search; Kudo uses the Forward-DP Backward-A* algorithm of Nagata (1994). The lattice sampler needs only the forward values and is exact.
- n-best decoding. Kudo found that n-best decoding helps only for models trained with subword regularization (Section 5.2).
- Other noise. It is a form of data augmentation and is related in spirit to dropout: the noise is in the input, not in the network.
Pitfalls
- Sampling at test time. Inference should use the best segmentation, or n-best decoding; a random segmentation at test time makes the output random.
- Underflow. For a long sentence, underflows in floating point. Work in log space, with log-add for the sums, as the code does through nlslog.
- The l-best list is not the full law. Sampling from the best renormalizes over the list, so segmentations outside the list are never drawn.
- The value of a. With too small, implausible segmentations such as single characters become frequent; with too large, the method is plain Viterbi segmentation.
- The cost per epoch. Segmentation must be done again at each update, so it cannot be cached as for a fixed tokenizer.
Code
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
subword_regularization.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subword-regularization/. The authors are listed in prov/510HA2.jsonl.
"""Sampling of segmentations for subword regularization (Kudo 2018, Section 3.3).
A model is a dict from pieces to natural log probabilities. A segmentation s
of x has the log probability sum of log p(w) over its pieces. Both samplers
draw s with probability proportional to P(s)^a, where a > 0 is the smoothing
value:
sample_lattice over all segmentations, by forward filtering (LOG semiring)
and backward sampling
sample_nbest over the l best segmentations only
exact_distribution enumerates all segmentations, for tests and small examples.
Positions are fenceposts 0..n; the piece x[i:j] is the edge from i to j.
"""
import math
import random
from typing import Dict, List, Tuple
from nlslog import LOG, NEG_INF, log_sum
Model = Dict[str, float]
Seg = Tuple[str, ...]
def _max_len(model: Model) -> int:
return max(len(w) for w in model)
def forward(x: str, model: Model, a: float) -> List[float]:
"""alpha[j] = log of the sum over segmentations s of x[:j] of P(s)^a."""
n, m = len(x), _max_len(model)
alpha = [LOG.zero] * (n + 1)
alpha[0] = LOG.one
for j in range(1, n + 1):
alpha[j] = log_sum(LOG.times(alpha[i], a * model[x[i:j]])
for i in range(max(0, j - m), j) if x[i:j] in model)
return alpha
def sample_lattice(x: str, model: Model, a: float, rng: random.Random) -> Seg:
"""Draw s with probability P(s)^a / Z, by forward filtering and backward sampling."""
n, m = len(x), _max_len(model)
alpha = forward(x, model, a) # @line S1
if alpha[n] == NEG_INF: # @line S2
raise ValueError("the word has no segmentation")
pieces, j = [], n # @line S3
while j > 0: # @line S4
starts = [i for i in range(max(0, j - m), j) if x[i:j] in model]
logw = [alpha[i] + a * model[x[i:j]] - alpha[j] for i in starts] # @line S5
r, acc, pick = rng.random(), 0.0, starts[-1] # @line S6
for i, lw in zip(starts, logw):
acc += math.exp(lw)
if r < acc:
pick = i
break
pieces.append(x[pick:j]) # @line S7
j = pick
return tuple(pieces[::-1]) # @line S8
def nbest(x: str, model: Model, l: int) -> List[Tuple[float, Seg]]:
"""The l best segmentations with their log probabilities, best first (ties by the pieces)."""
n, m = len(x), _max_len(model)
best: List[List[Tuple[float, Seg]]] = [[] for _ in range(n + 1)]
best[0] = [(0.0, ())]
for j in range(1, n + 1):
cands = [(score + model[x[i:j]], seg + (x[i:j],))
for i in range(max(0, j - m), j) if x[i:j] in model
for score, seg in best[i]]
best[j] = sorted(cands, key=lambda t: (-t[0], t[1]))[:l]
return best[n]
def sample_nbest(x: str, model: Model, a: float, l: int, rng: random.Random) -> Seg:
"""Draw one of the l best segmentations with probability proportional to P(s)^a."""
top = nbest(x, model, l) # @line N1
if not top:
raise ValueError("the word has no segmentation")
z = log_sum(a * score for score, _ in top) # @line N2
r, acc = rng.random(), 0.0 # @line N3
for score, seg in top: # @line N4
acc += math.exp(a * score - z)
if r < acc:
return seg
return top[-1][1]
def segmentations(x: str, model: Model) -> List[Seg]:
if not x:
return [()]
return [(x[:j],) + rest for j in range(1, len(x) + 1) if x[:j] in model
for rest in segmentations(x[j:], model)]
def exact_distribution(x: str, model: Model, a: float, l: int = 0) -> Dict[Seg, float]:
"""P(s)^a / Z over all segmentations, or over the l best ones if l > 0."""
segs = [(sum(model[w] for w in s), s) for s in segmentations(x, model)]
if l > 0:
segs = sorted(segs, key=lambda t: (-t[0], t[1]))[:l]
z = log_sum(a * score for score, _ in segs)
return {s: math.exp(a * score - z) for score, s in segs}
test_subword_regularization.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subword-regularization/. The authors are listed in prov/510HA2.jsonl.
import math
import random
from fractions import Fraction
from nlslog import NEG_INF
from subword_regularization import exact_distribution, forward, nbest, sample_lattice, sample_nbest, segmentations
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)}
MODEL = {w: math.log(p) for w, p in PAGE.items()}
def frequencies(draw, n):
counts = {}
for _ in range(n):
s = draw()
counts[s] = counts.get(s, 0) + 1
return counts
def close(counts, exact, n):
assert set(counts) <= set(exact)
for s, q in exact.items():
sd = math.sqrt(q * (1 - q) / n)
assert abs(counts.get(s, 0) / n - q) <= 5 * sd + 1e-9
def test_exact_distribution_with_fractions():
# With a = 1 the law is P(s) / P(x); check it against exact rational arithmetic.
probs = {}
for s in segmentations("hugs", MODEL):
q = Fraction(1)
for w in s:
q *= PAGE[w]
probs[s] = q
total = sum(probs.values())
assert total == Fraction(111, 2500)
d = exact_distribution("hugs", MODEL, 1.0)
for s, q in probs.items():
assert abs(d[s] - float(q / total)) < 1e-12
assert abs(d[("hug", "s")] - 75 / 111) < 1e-12
def test_page_values():
d = exact_distribution("hugs", MODEL, 0.5)
assert round(d[("hug", "s")], 4) == 0.3978 and round(d[("h", "u", "g", "s")], 4) == 0.0281
d = exact_distribution("hugs", MODEL, 2.0)
assert round(d[("hug", "s")], 4) == 0.9399
assert {s: round(q, 4) for s, q in exact_distribution("hugs", MODEL, 1.0, 3).items()} == {
("hug", "s"): 0.75, ("h", "ugs"): 0.125, ("hu", "gs"): 0.125}
def test_lattice_sampling_matches_the_exact_law():
rng = random.Random(0)
n = 3000
for a in [1.0, 0.5, 0.2]:
counts = frequencies(lambda: sample_lattice("hugs", MODEL, a, rng), n)
close(counts, exact_distribution("hugs", MODEL, a), n)
def test_nbest_sampling_matches_the_exact_law():
rng = random.Random(1)
n = 3000
for a, l in [(1.0, 3), (0.5, 5)]:
counts = frequencies(lambda: sample_nbest("hugs", MODEL, a, l, rng), n)
close(counts, exact_distribution("hugs", MODEL, a, l), n)
def test_nbest_against_brute_force():
rng = random.Random(2)
for _ in range(40):
pieces = set("ab") | {"".join(rng.choice("ab") for _ in range(rng.randint(2, 3))) for _ in range(4)}
weights = {w: rng.randint(1, 50) for w in sorted(pieces)}
z = sum(weights.values())
model = {w: math.log(c / z) for w, c in weights.items()}
x = "".join(rng.choice("ab") for _ in range(rng.randint(1, 8)))
scores = sorted((sum(model[w] for w in s) for s in segmentations(x, model)), reverse=True)
got = [score for score, _ in nbest(x, model, 4)]
assert len(got) == min(4, len(scores))
assert all(abs(g - s) < 1e-9 for g, s in zip(got, scores))
def test_random_models_sample_correctly():
rng = random.Random(3)
n = 2000
for _ in range(3):
pieces = set("ab") | {"".join(rng.choice("ab") for _ in range(2)) for _ in range(3)}
weights = {w: rng.randint(1, 9) for w in sorted(pieces)}
z = sum(weights.values())
model = {w: math.log(c / z) for w, c in weights.items()}
x = "".join(rng.choice("ab") for _ in range(5))
a = rng.choice([0.3, 1.0, 1.5])
counts = frequencies(lambda: sample_lattice(x, model, a, rng), n)
close(counts, exact_distribution(x, model, a), n)
def test_log_space_avoids_underflow():
# "a" * 4000 with p(a) = p(aa) = 1/2: the probability of any segmentation is
# at most 2^-2000, which underflows to 0.0 as a plain product.
n = 4000
model = {"a": math.log(0.5), "aa": math.log(0.5)}
plain = 1.0
for _ in range(n // 2):
plain *= 0.5
assert plain == 0.0
alpha = forward("a" * n, model, 1.0)
assert alpha[n] > NEG_INF
s = sample_lattice("a" * n, model, 1.0, random.Random(4))
assert "".join(s) == "a" * n and set(s) <= {"a", "aa"}
Exercises
- Show that with the lattice sampler draws with the posterior probability of the unigram model.
- Show that as grows without bound, puts all its mass on the Viterbi segmentations (spread over them if there are ties).
- For the word "hugs" above, compute the forward values with , shown as , and check that they are 1, 0.316228, 0.416228, 0.701311 and 0.435399.
- Explain why the weights of line S5 sum to 1 at every position with .
- Give a model and a word for which the 2-best sampler can never return the segmentation of largest probability among those with three pieces.
Proof: Forward filtering and backward sampling draws a segmentation with probability proportional to P(s) to the power afull
Notation. A model gives each piece a probability . All logs are natural logs. A word has characters, and positions are fenceposts ; the piece is the edge of the lattice. A segmentation is a path , with . For a smoothing value , the target law is with , the sum over all segmentations of . Note that , so is the path law of the lattice with edge weights .
Lemma 1 (forward values). In the LOG semiring, FORWARD gives , the sum over the segmentations of , and .
Proof. By induction on : the segmentations of split, without overlap, by their last piece , and the weight of each is times the weight of a segmentation of . In log space the product is a sum and the sum over is log-add.
Theorem 1 (the sampler). If , SAMPLE-LATTICE stops after at most steps of line S4 and returns each segmentation of with probability exactly (up to the rounding of floating point).
Proof. Each step of the loop picks a start and sets , so the loop runs at most times and ends at . At position with , line S5 gives the start the weight . By Lemma 1 these weights are nonnegative and sum to , so line S6 draws from a probability distribution, and a start with has weight and is never drawn. Let have the cut positions . The sampler returns when it draws at , then at , and so on, so
because the terms telescope, and .
Theorem 2 (the l-best sampler). NBEST returns the segmentations of largest (fewer if has fewer), and SAMPLE-NBEST returns each of them with probability , the sum over the returned list.
Proof. Let be the best segmentations of . A segmentation in ends with some piece , and its prefix is in : if the prefix were not among the best of , then better prefixes with the same last piece would give better segmentations of . So the candidates formed from and the edges into contain , and sorting keeps it (ties are broken by the pieces). Lines N2 to N4 normalize the weights in log space and draw one by inversion.
The sampling frequencies in the tests are checked against the exact law, which is computed by listing all segmentations. That subword regularization improves a translation model is a measurement, reported by Kudo (2018), not a theorem.
References
- Taku Kudo, Subword regularization, Improving neural network translation models with multiple subword candidates, ACL 2018, pages 66 to 75, Section 2.1 (on-the-fly sampling, Equations 3 and 4), Section 2.2 (one-best and n-best decoding), Section 3.3 (l-best sampling with the smoothing value alpha, and forward filtering backward sampling), Section 4 (the relation to data augmentation), Section 5.1 (the settings l = 64 with alpha = 0.1, and l = infinity with alpha = 0.2 or 0.5) and Section 5.2 (the BLEU gains)
- Ivan Provilkov, Dmitrii Emelianenko and Elena Voita, BPE-dropout, Simple and effective subword regularization, ACL 2020, pages 1882 to 1892, the abstract and Section 4 (subword regularization with the BPE merge table, compared with Kudo's method)
- Taku Kudo and John Richardson, SentencePiece, A simple and language independent subword tokenizer and detokenizer for neural text processing, EMNLP 2018 System Demonstrations, pages 66 to 71, the library that implements the unigram model used for sampling
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 510HA2 Edit this page History Report an error Markdown