Algorithm Search⌘K

Algorithmresearch

BPE-dropout

Also called byte-pair encoding dropout.

Apply the BPE merges in order but skip each candidate merge with probability p at training time, which yields random segmentations of each word.

Time
O(n^2) sample
Space
O(n) sampleO(K) table
Where
K = the number of merges in the table; n = the length of the word in characters
Properties
randomizednot exactofflineiterative
Origin
Ivan Provilkov, Dmitrii Emelianenko, Elena Voita, 2020

BPE-dropout is a way to get many different segmentations of the same word from one byte-pair encoding merge table. It segments a word as BPE does, but at each step it drops each possible merge at random with probability pp, so the word stops at a random level of detail. A model is trained on these random segmentations and is then used with plain BPE. It is a form of subword regularization that needs no new tokenizer.

In plain words

Plain BPE always cuts a word the same way. A model then sees "unrelated" as the same few pieces every time and never learns that the pieces of a rare word mean the same as the pieces inside a common one.

BPE-dropout cuts words with the usual list of gluing rules, but at each step it forgets some of the rules for that step, at random. A word sometimes comes out as one piece, sometimes as smaller pieces, and sometimes as single letters. During training, the model sees many cuts of each word and learns how the pieces fit together. When the model is used, the forgetting is turned off, so the cut is the normal one.

The problem

The input is a word ww of nn characters, a merge table (a list of pairs of units, where an earlier pair has a higher priority) and a probability pp. The output is a random segmentation of ww into units, that is, a list of strings that joins back to ww. With p=0p = 0 the output must be the plain BPE segmentation, and with p=1p = 1 it must be the list of characters. Provilkov et al. describe the plain BPE segmentation as: split the word into characters, then merge the adjacent pair of highest priority, and repeat until no pair of the table is left.

The algorithm

Algorithm 1 of Provilkov et al., with the rule of their footnote 1 that each occurrence of a merge is dropped on its own:

  1. BPE-DROPOUT(w, merges, p)
  2. 1u ← the characters of w
  3. 2repeat
  4. 3O ← the positions i where (u_i, u_{i+1}) is a pair of merges
  5. 4remove each position from O, independently, with probability p
  6. 5if O is empty then return u
  7. 6(a, b) ← the pair of highest priority at a position in O
  8. 7join a b at the positions of O that hold (a, b), from the left, skipping overlaps

The run stops as soon as all occurrences of one pass are dropped, even if a later pass could have merged something. Line L7 joins all kept occurrences of the chosen pair, as plain BPE joins all occurrences. For a pair such as (a, a) in "aaa", the two occurrences overlap; line L7 takes the left one when both are kept. The Sennrich et al. code adds an end-of-word symbol to each word before segmenting; this page leaves it out to keep the example short.

Example

Learn 6 merges from the counts low 5, lower 2, newest 6 and widest 3. Plain BPE gives the table (e, s), (es, t), (l, o), (lo, w), (e, w), (ew, est), in this order of priority, and segments "lowest" as low, est.

With p=0.1p = 0.1, the word "low" has one occurrence at the start, (l, o). It is dropped with probability 0.1, and the run returns l, o, w. Otherwise lo, w is formed, and the occurrence (lo, w) is dropped with probability 0.1, which returns lo, w with probability 0.9⋅0.1=0.090.9 \cdot 0.1 = 0.09. The rest, 0.81, gives low.

The word "lowest" has 9 possible outputs. Their exact probabilities, from enumerating every pattern of drops:

segmentation probability
low est 0.807003
lo w est 0.08748
l o w est 0.081
l o w e s t 0.01
l o w es t 0.009
low es t 0.002187
lo w es t 0.00162
lo w e s t 0.0009
low e s t 0.00081

The first pass sees (l, o) and (e, s); both are dropped with probability 0.1⋅0.1=0.010.1 \cdot 0.1 = 0.01, which is the row of single characters. With p=0.5p = 0.5 the plain segmentation low, est has probability 0.171875, and the single characters have 0.25.

Correctness

Each pass that does not stop joins at least one pair, and a join keeps the characters, so the run stops after at most n−1n - 1 joins and returns a segmentation of ww into characters and joined pairs of the table. With p=0p = 0 nothing is dropped, so each pass merges the pair of highest priority at all its occurrences, which is plain BPE; with p=1p = 1 the first pass stops. The law of the output is a sum over the patterns of drops at the first pass, which the code evaluates exactly with rational numbers; the tests check the sampled frequencies against it. These are theorems, proved in proofs/correctness.md. That the random segmentations help a model is a measurement, not a theorem.

Proof: BPE-dropout stops, returns a segmentation of the word, and has the law that the enumeration computesfull

Notation. The merge table is a list of pairs of strings; the rank of a pair is its position in the list, and a lower rank means a higher priority. A segmentation of a word ww is a list of nonempty strings whose concatenation is ww. For a segmentation u=u1⋯uru = u_1 \cdots u_r, an occurrence is an index ii with 1≤i<r1 \le i < r such that (ui,ui+1)(u_i, u_{i+1}) is in the table. JOIN(uu, SS) joins uiu_i and ui+1u_{i+1} for the indices ii of a set SS, taken from the left, and skips an index that is next to one already joined.

Lemma 1 (one step). If uu is a segmentation of ww and SS is a nonempty set of occurrences, then JOIN(uu, SS) is a segmentation of ww with at least one unit less than uu, and each of its units is a unit of uu or the join aba b of a pair (a,b)(a, b) of the table.

Proof. JOIN copies the units in order and writes two adjacent units as one string with the same characters, so the concatenation is still ww. The smallest index of SS is always joined, so the length drops by at least one. A joined unit is uiui+1u_i u_{i+1} for an occurrence ii, which is the join of a pair in the table. □\square

Theorem 1 (termination and output). For every word ww of nn characters, every p∈[0,1]p \in [0, 1] and every sequence of random draws, BPE-DROPOUT stops after at most n−1n - 1 joins and returns a segmentation of ww whose units are characters of ww or joins of pairs in the table. With p=0p = 0 it returns the segmentation that merges the pair of highest priority at all its occurrences until no pair is left, which is how Section 2.1 of Provilkov et al. describes the BPE segmentation. With p=1p = 1 it returns the characters of ww.

Proof. Line L1 starts with the characters of ww, a segmentation with nn units. Each pass that does not stop at line L5 applies line L7 to a nonempty set, and by Lemma 1 it keeps a segmentation and removes at least one unit. A segmentation has at least one unit, so there are at most n−1n - 1 such passes. With p=0p = 0, line L4 keeps every occurrence, so line L6 takes the pair of highest priority among all occurrences and line L7 joins all its occurrences, which is the BPE rule. With p=1p = 1, line L4 removes every occurrence, so the first pass stops at line L5 with the characters. □\square

Theorem 2 (the law). Let D(u)D(u) be the law of the output when the loop starts from the segmentation uu, and let O(u)O(u) be the set of occurrences of uu. Then

D(u)=∑S⊆O(u)(1−p)∣S∣ p∣O(u)∣−∣S∣⋅{the point mass at uif S=∅,D(STEP(u,S))otherwise,D(u) = \sum_{S \subseteq O(u)} (1 - p)^{|S|} \, p^{|O(u)| - |S|} \cdot \begin{cases} \text{the point mass at } u & \text{if } S = \emptyset, \\ D(\mathrm{STEP}(u, S)) & \text{otherwise,} \end{cases}

where STEP(uu, SS) is JOIN(uu, S′S') for the set S′S' of indices in SS that hold the pair of lowest rank among those in SS. DISTRIBUTION computes this sum exactly.

Proof. In one pass, line L4 keeps each occurrence on its own with probability 1−p1 - p, as footnote 1 of Provilkov et al. asks, so the kept set equals SS with probability (1−p)∣S∣p∣O(u)∣−∣S∣(1 - p)^{|S|} p^{|O(u)| - |S|}. These events cover all cases and do not overlap. If SS is empty, the output is uu. Otherwise lines L6 and L7 give STEP(uu, SS), and the later passes use fresh draws, so given SS the output has law D(STEP(u,S))D(\mathrm{STEP}(u, S)). The law of total probability gives the sum. The recursion ends, because STEP shortens uu (Lemma 1), and DISTRIBUTION evaluates the sum term by term in exact rational arithmetic, keeping a table of the laws it has found. ■\blacksquare

The law is not a product over the merges. A pass that keeps no occurrence ends the run, so a single drop at the first pass of a short word returns its characters, even when later merges could apply. The example on the page shows this for the word low.

Complexity

In the word-RAM model with a hash table for the ranks, one pass costs O(n)O(n) to list the occurrences, draw the drops and join, and there are at most nn passes, so one sample costs O(n2)O(n^2) time and O(n)O(n) space. Plain BPE has the same bound. The rank table takes O(K)O(K) space. A sample is drawn every time a word is seen in training, so this cost is paid in each epoch, unlike plain BPE, whose output can be cached.

Properties

  • The same vocabulary. No new unit is created: every output unit is a character or a unit of the BPE table, so the model and its vocabulary stay as for BPE. Provilkov et al. keep the vocabulary of plain BPE; a unit that appears only through dropout then becomes an unknown token, which is rare (Section 4.2).
  • A tunable level of detail. The value of pp moves the output between the BPE segmentation and the characters.
  • Not a product law. The probability of a segmentation is not a product of one factor per merge. One dropped pass can end the run, as the row l, o, w, e, s, t shows.
  • Measured gains. Provilkov et al. report gains of up to 2.3 BLEU over BPE and up to 0.9 BLEU over the subword regularization of Kudo (2018), on their translation tasks. They usually use p=0.1p = 0.1, and p=0.6p = 0.6 for Chinese and Japanese (Table 1).

Variants and improvements

  • Unigram sampling. Kudo's subword regularization samples from a unigram language model of the pieces. It needs that model, while BPE-dropout needs only the merge table.
  • Byte level. The same drops apply to the merges of byte-level BPE.
  • Choice of p. A larger pp gives finer pieces. A language with many characters, where BPE units are long, may need a larger pp, as Table 1 of the paper shows.

When to use it

Use it when you train a model on text segmented by BPE and want the effect of subword regularization without changing the tokenizer, for example in machine translation with a transformer. Turn it off (p=0p = 0) at test time. It is a kind of data augmentation: it changes the input, not the model.

Pitfalls

  • Dropout at test time. Inference must use p=0p = 0. Random segmentations at test time make the output random and usually worse.
  • Per occurrence, not per pair. Dropping a pair type for the whole word at once is a different law. Footnote 1 of the paper drops each occurrence on its own.
  • Stopping early. A pass that keeps no occurrence ends the run. An implementation that skips such a pass and goes on with the next one gives a different, coarser law.
  • Vocabulary. Units that only dropout produces may be missing from a vocabulary built from plain BPE output, and become unknown tokens.

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.

bpe_dropout.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bpe-dropout/. The authors are listed in prov/ZZH1HW.jsonl.

"""BPE-dropout of Provilkov, Emelianenko and Voita (2020).

The merge table is the one of ordinary byte-pair encoding. To segment a word,
start from its characters and repeat: list every position where a pair of the
table occurs, drop each position on its own with probability p, and apply the
surviving merge of highest priority (lowest rank) at its surviving positions.
Stop when no position survives. With p = 0 this is plain BPE, and with p = 1
it returns the characters.

segment draws one segmentation with a random.Random. distribution gives the
exact probability of every segmentation, as Fractions, by enumeration.
"""

import random
from fractions import Fraction
from typing import Dict, List, Sequence, Tuple

Pair = Tuple[str, str]
Seg = Tuple[str, ...]


def _merge_at(units: Sequence[str], positions: Sequence[int]) -> List[str]:
    """Join units[i] and units[i + 1] for each i in positions, from the left,
    skipping a position that overlaps the previous join."""
    take, last = set(), -2
    for i in sorted(positions):
        if i > last + 1:
            take.add(i)
            last = i
    out, i = [], 0
    while i < len(units):
        if i in take:
            out.append(units[i] + units[i + 1])
            i += 2
        else:
            out.append(units[i])
            i += 1
    return out


def _positions(units: Sequence[str], a: str, b: str) -> List[int]:
    return [i for i in range(len(units) - 1) if units[i] == a and units[i + 1] == b]


def train_bpe(freq: Dict[str, int], merges: int) -> List[Pair]:
    """Plain BPE: merge the most frequent pair, ties to the smallest pair."""
    seg = {w: list(w) for w in freq}
    out: List[Pair] = []
    for _ in range(merges):
        counts: Dict[Pair, int] = {}
        for w, u in seg.items():
            for pair in set(zip(u, u[1:])):
                k = len(u) - len(_merge_at(u, _positions(u, *pair)))  # non-overlapping count
                counts[pair] = counts.get(pair, 0) + freq[w] * k
        if not counts:
            break
        a, b = min(counts, key=lambda pr: (-counts[pr], pr))
        seg = {w: _merge_at(u, _positions(u, a, b)) for w, u in seg.items()}
        out.append((a, b))
    return out


def _occurrences(units: Sequence[str], rank: Dict[Pair, int]) -> List[int]:
    return [i for i in range(len(units) - 1) if (units[i], units[i + 1]) in rank]


def _step(units: Sequence[str], kept: Sequence[int], rank: Dict[Pair, int]) -> List[str]:
    best = min(((units[i], units[i + 1]) for i in kept), key=rank.__getitem__)
    return _merge_at(units, [i for i in kept if (units[i], units[i + 1]) == best])


def segment(word: str, merges: Sequence[Pair], p: float, rng: random.Random) -> Seg:
    """Draw one BPE-dropout segmentation of word (Algorithm 1 of the paper)."""
    rank = {pair: r for r, pair in enumerate(merges)}
    u = list(word)  # @line L1
    while True:  # @line L2
        occ = _occurrences(u, rank)  # @line L3
        kept = [i for i in occ if rng.random() >= p]  # @line L4
        if not kept:  # @line L5
            return tuple(u)
        a, b = min(((u[i], u[i + 1]) for i in kept), key=rank.__getitem__)  # @line L6
        u = _merge_at(u, [i for i in kept if (u[i], u[i + 1]) == (a, b)])  # @line L7


def bpe(word: str, merges: Sequence[Pair]) -> Seg:
    """Plain BPE segmentation: merge the pair of highest priority until none is left."""
    rank = {pair: r for r, pair in enumerate(merges)}
    u = list(word)
    while True:
        occ = _occurrences(u, rank)
        if not occ:
            return tuple(u)
        u = _step(u, occ, rank)


def distribution(word: str, merges: Sequence[Pair], p: Fraction) -> Dict[Seg, Fraction]:
    """The exact law of segment(word, merges, p), by enumerating the drops."""
    rank = {pair: r for r, pair in enumerate(merges)}
    memo: Dict[Seg, Dict[Seg, Fraction]] = {}

    def law(u: Seg) -> Dict[Seg, Fraction]:
        if u in memo:
            return memo[u]
        occ = _occurrences(u, rank)
        out: Dict[Seg, Fraction] = {}
        for mask in range(1 << len(occ)):
            kept = [occ[j] for j in range(len(occ)) if mask >> j & 1]
            weight = (1 - p) ** len(kept) * p ** (len(occ) - len(kept))
            if weight == 0:
                continue
            if not kept:
                out[u] = out.get(u, Fraction(0)) + weight
                continue
            for seg, q in law(tuple(_step(u, kept, rank))).items():
                out[seg] = out.get(seg, Fraction(0)) + weight * q
        memo[u] = out
        return out

    return law(tuple(word))
test_bpe_dropout.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bpe-dropout/. The authors are listed in prov/ZZH1HW.jsonl.

import random
from fractions import Fraction

from bpe_dropout import bpe, distribution, segment, train_bpe

FREQ = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
MERGES = [("e", "s"), ("es", "t"), ("l", "o"), ("lo", "w"), ("e", "w"), ("ew", "est")]


def test_training_gives_the_page_merges():
    assert train_bpe(FREQ, 6) == MERGES
    assert bpe("lowest", MERGES) == ("low", "est")


def test_p_zero_is_bpe_and_p_one_is_characters():
    rng = random.Random(0)
    for w in ["lowest", "newer", "widest", "slow", "esteem"]:
        assert segment(w, MERGES, 0.0, rng) == bpe(w, MERGES)
        assert segment(w, MERGES, 1.0, rng) == tuple(w)
        assert distribution(w, MERGES, Fraction(0)) == {bpe(w, MERGES): 1}
        assert distribution(w, MERGES, Fraction(1)) == {tuple(w): 1}


def test_page_distribution_of_low():
    d = distribution("low", MERGES, Fraction(1, 10))
    assert d == {("low",): Fraction(81, 100), ("l", "o", "w"): Fraction(1, 10), ("lo", "w"): Fraction(9, 100)}


def test_page_distribution_of_lowest():
    d = distribution("lowest", MERGES, Fraction(1, 10))
    assert len(d) == 9 and sum(d.values()) == 1
    assert d[("low", "est")] == Fraction(807003, 1000000)
    assert d[("lo", "w", "est")] == Fraction(2187, 25000)
    assert d[("l", "o", "w", "est")] == Fraction(81, 1000)
    assert d[tuple("lowest")] == Fraction(1, 100)


def test_samples_follow_the_exact_law():
    rng = random.Random(42)
    n = 20000
    for w, p in [("lowest", 0.1), ("lowest", 0.5), ("newest", 0.3)]:
        exact = distribution(w, MERGES, Fraction(p).limit_denominator(100))
        counts = {}
        for _ in range(n):
            s = segment(w, MERGES, p, rng)
            counts[s] = counts.get(s, 0) + 1
        assert set(counts) <= set(exact)
        for s, q in exact.items():
            q = float(q)
            sd = (q * (1 - q) / n) ** 0.5
            assert abs(counts.get(s, 0) / n - q) <= 5 * sd + 1e-9


def test_overlapping_occurrences():
    merges = [("a", "a")]
    d = distribution("aaa", merges, Fraction(1, 2))
    # Both positions survive (1/4): merge the left one. Only the left (1/4) or
    # only the right (1/4) survives: merge it. None survives (1/4): stop.
    assert d == {("aa", "a"): Fraction(1, 2), ("a", "aa"): Fraction(1, 4), ("a", "a", "a"): Fraction(1, 4)}


def test_every_sample_is_a_segmentation_with_known_units():
    rng = random.Random(7)
    units = set("abc")
    corpus = {"".join(rng.choice("abc") for _ in range(rng.randint(2, 7))): rng.randint(1, 5) for _ in range(8)}
    merges = train_bpe(corpus, 10)
    units |= {a + b for a, b in merges}
    for _ in range(500):
        w = "".join(rng.choice("abc") for _ in range(rng.randint(1, 8)))
        s = segment(w, merges, rng.random(), rng)
        assert "".join(s) == w and set(s) <= units


def test_exact_law_sums_to_one_on_random_words():
    rng = random.Random(9)
    corpus = {"".join(rng.choice("ab") for _ in range(rng.randint(2, 6))): rng.randint(1, 5) for _ in range(6)}
    merges = train_bpe(corpus, 6)
    for _ in range(30):
        w = "".join(rng.choice("ab") for _ in range(rng.randint(1, 6)))
        p = Fraction(rng.randint(0, 10), 10)
        d = distribution(w, merges, p)
        assert sum(d.values()) == 1
        assert all("".join(s) == w for s in d)

History

Kudo (2018) introduced subword regularization with a unigram language model, and noted that plain BPE gives only one segmentation per word. Provilkov, Emelianenko and Voita (2020) showed that the BPE merge table already allows many segmentations: dropping merges at random, in the spirit of dropout in neural networks, gives them without a second model.

References

  1. Ivan Provilkov, Dmitrii Emelianenko and Elena Voita, BPE-dropout, Simple and effective subword regularization, ACL 2020, pages 1882 to 1892, Section 2.1 (BPE segmentation), Section 3 and Algorithm 1 with footnote 1 (page 1884), Table 1 (the values of p), Section 4.2 (vocabularies), and the abstract (the BLEU gains)
  2. Taku Kudo, Subword regularization, Improving neural network translation models with multiple subword candidates, ACL 2018, pages 66 to 75, the method that BPE-dropout is compared with (a unigram language model with sampling)
  3. Rico Sennrich, Barry Haddow and Alexandra Birch, Neural machine translation of rare words with subword units, ACL 2016, the merge table and the segmentation procedure of BPE

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.sample
  • a full proof of space.sample
  • a full proof of space.table
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
  • a scene preset for the example