Algorithm Search⌘K

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 ww a probability p(w)p(w), and let P(s)=∏w∈sp(w)P(s) = \prod_{w \in s} p(w) for a segmentation ss of a word xx. For a smoothing value a>0a > 0, sample ss with probability

Q(s)=P(s)a∑tP(t)a,Q(s) = \frac{P(s)^a}{\sum_t P(t)^a},

where the sum runs over the candidates tt. A small aa makes the law flatter, and a large aa moves it to the Viterbi segmentation. Kudo uses one sample per sentence per update (k=1k = 1 in his Equation 4); over many updates this approximates training on the marginal likelihood over all segmentations.

There are two ways to draw ss. The first takes the ll best segmentations and draws one of them:

  1. SAMPLE-NBEST(x, p, a, l)
  2. N1 T ← the l best segmentations of x, with their log probabilities
  3. N2 Z ← the log-add over t in T of a · log P(t)
  4. N3 draw r uniform in [0, 1)
  5. 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 0,…,n0, \ldots, n, and the piece x[i:j]x[i{:}j] is the edge from ii to jj. The forward pass runs in the LOG semiring (log probabilities, plus = log-add, times = +) with the edge weights alog⁡p(w)a \log p(w), natural logs:

  1. SAMPLE-LATTICE(x, p, a)
  2. S1 alpha ← the forward values of x with the edge weights a · log p(w)
  3. S2 if alpha[n] = -∞ then fail: x has no segmentation
  4. S3 pieces ← empty; j ← n
  5. S4 while j > 0
  6. S5 give each start i of a piece x[i:j] the weight exp(alpha[i] + a · log p(x[i:j]) - alpha[j])
  7. S6 draw a start i with these weights
  8. S7 put x[i:j] in front of pieces; j ← i
  9. S8 return pieces

The weights of line S5 sum to 1, and the product of the weights along the drawn path telescopes to P(s)a/∑tP(t)aP(s)^a / \sum_t P(t)^a; 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 nn best, and then keeps the translation yy with the best score log⁡P(y∣x)/∣y∣λ\log P(y \mid x) / |y|^{\lambda}, where λ\lambda 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 QQ for three values of aa:

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 a=1a = 1 the law is the posterior P(s)/P(x)P(s) / P(x), and P(hugs)=0.0444P(\text{hugs}) = 0.0444. With l=3l = 3 and a=1a = 1, 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 a=0.5a = 0.5 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 l=64l = 64 with a=0.1a = 0.1, and l=∞l = \infty (the lattice sampler) with a=0.2a = 0.2 on the IWSLT data and 0.50.5 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 ll-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, P(s)P(s) 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 ll best renormalizes over the list, so segmentations outside the list are never drawn.
  • The value of a. With aa too small, implausible segmentations such as single characters become frequent; with aa 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.

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
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

  1. Show that with a=1a = 1 the lattice sampler draws ss with the posterior probability P(s)/P(x)P(s) / P(x) of the unigram model.
  2. Show that as aa grows without bound, QQ puts all its mass on the Viterbi segmentations (spread over them if there are ties).
  3. For the word "hugs" above, compute the forward values with a=0.5a = 0.5, shown as exp⁡(α[j])\exp(\alpha[j]), and check that they are 1, 0.316228, 0.416228, 0.701311 and 0.435399.
  4. Explain why the weights of line S5 sum to 1 at every position jj with α[j]>−∞\alpha[j] > -\infty.
  5. 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 ww a probability p(w)>0p(w) > 0. All logs are natural logs. A word xx has nn characters, and positions are fenceposts 0,…,n0, \ldots, n; the piece x[i:j]x[i{:}j] is the edge i→ji \to j of the lattice. A segmentation ss is a path 0→n0 \to n, with P(s)=∏w∈sp(w)P(s) = \prod_{w \in s} p(w). For a smoothing value a>0a > 0, the target law is Q(s)=P(s)a/ZQ(s) = P(s)^a / Z with Z=∑sP(s)aZ = \sum_s P(s)^a, the sum over all segmentations of xx. Note that P(s)a=∏w∈sp(w)aP(s)^a = \prod_{w \in s} p(w)^a, so QQ is the path law of the lattice with edge weights p(w)ap(w)^a.

Lemma 1 (forward values). In the LOG semiring, FORWARD gives α[j]=ln⁡∑sP(s)a\alpha[j] = \ln \sum_{s} P(s)^a, the sum over the segmentations ss of x[:j]x[{:}j], and α[0]=0\alpha[0] = 0.

Proof. By induction on jj: the segmentations of x[:j]x[{:}j] split, without overlap, by their last piece x[i:j]x[i{:}j], and the weight of each is p(x[i:j])ap(x[i{:}j])^a times the weight of a segmentation of x[:i]x[{:}i]. In log space the product is a sum and the sum over ii is log-add. □\square

Theorem 1 (the sampler). If Z>0Z > 0, SAMPLE-LATTICE stops after at most nn steps of line S4 and returns each segmentation ss of xx with probability exactly Q(s)Q(s) (up to the rounding of floating point).

Proof. Each step of the loop picks a start i<ji < j and sets j←ij \leftarrow i, so the loop runs at most nn times and ends at 00. At position jj with α[j]>−∞\alpha[j] > -\infty, line S5 gives the start ii the weight exp⁡(α[i]+aln⁡p(x[i:j])−α[j])\exp(\alpha[i] + a \ln p(x[i{:}j]) - \alpha[j]). By Lemma 1 these weights are nonnegative and sum to 11, so line S6 draws ii from a probability distribution, and a start with α[i]=−∞\alpha[i] = -\infty has weight 00 and is never drawn. Let ss have the cut positions 0=c0<c1<⋯<cr=n0 = c_0 < c_1 < \cdots < c_r = n. The sampler returns ss when it draws cr−1c_{r-1} at crc_r, then cr−2c_{r-2} at cr−1c_{r-1}, and so on, so

Pr⁡[s]=∏k=1rexp⁡(α[ck−1]+aln⁡p(x[ck−1:ck])−α[ck])=exp⁡(α[0]−α[n])∏k=1rp(x[ck−1:ck])a=P(s)aZ,\Pr[s] = \prod_{k=1}^{r} \exp\big(\alpha[c_{k-1}] + a \ln p(x[c_{k-1}{:}c_k]) - \alpha[c_k]\big) = \exp\big(\alpha[0] - \alpha[n]\big) \prod_{k=1}^{r} p(x[c_{k-1}{:}c_k])^a = \frac{P(s)^a}{Z},

because the α\alpha terms telescope, α[0]=0\alpha[0] = 0 and α[n]=ln⁡Z\alpha[n] = \ln Z. □\square

Theorem 2 (the l-best sampler). NBEST returns the ll segmentations of largest P(s)P(s) (fewer if xx has fewer), and SAMPLE-NBEST returns each of them with probability P(s)a/∑tP(t)aP(s)^a / \sum_{t} P(t)^a, the sum over the returned list.

Proof. Let BjB_j be the ll best segmentations of x[:j]x[{:}j]. A segmentation in BjB_j ends with some piece x[i:j]x[i{:}j], and its prefix is in BiB_i: if the prefix were not among the ll best of x[:i]x[{:}i], then ll better prefixes with the same last piece would give ll better segmentations of x[:j]x[{:}j]. So the candidates formed from BiB_i and the edges into jj contain BjB_j, and sorting keeps it (ties are broken by the pieces). Lines N2 to N4 normalize the weights P(s)aP(s)^a in log space and draw one by inversion. □\square

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

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

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/510HA2/proof-correctness.yaml
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
  • three classic examples