Algorithm Search⌘K

Algorithmcore

WordPiece

Also called WordPiece tokenization.

Learn subword units by merging the pair that most raises a unigram likelihood, then encode each word by greedy longest match with

Time
O(n^3) encode_wordO(K L m) train
Space
O(L) trainO(V m) vocabulary
Where
K = the number of merges; L = the total length of the distinct training words; V = the vocabulary size (number of types); m = the length of the longest training word; n = the length of one word in characters
Properties
deterministicnot exactofflineiterative
Origin
Mike Schuster, Kaisuke Nakajima, 2012

WordPiece is a subword tokenization method in two parts: a training step that builds a vocabulary of word pieces by merging adjacent units, and an encoder that splits each word into the longest pieces of that vocabulary from left to right. Training is like byte-pair encoding, but it picks the merge that most raises the likelihood of a unigram language model of the units, not the most frequent pair. The encoder is the greedy rule of maximum matching segmentation applied to pieces, with the prefix "##" on every piece that does not start a word and the token [UNK] for a word it cannot cover. Fast WordPiece tokenization gives the same output as this encoder in linear time.

In plain words

Start with the single letters of every word in a training text. Then glue two neighboring pieces into a new piece, again and again. At each step, choose the glue that makes the text most probable under a simple model that counts how often each piece appears. A pair of pieces that almost always appear together is a good choice, even if it is not the most common pair. Stop when the list of pieces has the size you want.

To cut a new word, take the longest piece from the list that starts at the first letter. Then take the longest piece that fits after it, and so on. Pieces inside a word carry a mark, so the word can be put back together. If some position has no piece at all, the whole word becomes one unknown token.

The problem

The training input is a map CC from distinct words to counts, and a number of merges KK. Each word w=w1⋯wnw = w_1 \cdots w_n starts as the units w1,##w2,…,##wnw_1, \#\#w_2, \ldots, \#\#w_n. A merge of the adjacent units aa and bb makes the unit abab: the text of aa followed by the text of bb without its "##". The output is a vocabulary VV of units and the list of merges.

The criterion is the log likelihood of the corpus under a unigram model whose probabilities are the maximum likelihood estimates c(x)/Nc(x)/N, where c(x)c(x) counts the occurrences of unit xx and N=∑xc(x)N = \sum_x c(x):

L=∑xc(x)log⁡c(x)N=∑xF(c(x))−F(N),F(x)=xlog⁡x, F(0)=0(log⁡ base e).\mathcal{L} = \sum_x c(x) \log \frac{c(x)}{N} = \sum_x F(c(x)) - F(N), \qquad F(x) = x \log x,\ F(0) = 0 \qquad (\log \text{ base } e).

Merging kk occurrences of (a,b)(a, b) changes only c(a)c(a), c(b)c(b), c(ab)c(ab) and NN, so the gain has a closed form with eight terms when a≠ba \ne b:

g(a,b)=F(cab+k)−F(cab)+F(ca−k)−F(ca)+F(cb−k)−F(cb)−F(N−k)+F(N).g(a, b) = F(c_{ab} + k) - F(c_{ab}) + F(c_a - k) - F(c_a) + F(c_b - k) - F(c_b) - F(N - k) + F(N).

When a=ba = b, the two middle differences become F(ca−2k)−F(ca)F(c_a - 2k) - F(c_a). Choosing the largest gain at each step is a greedy heuristic: it gives the best single step, and nothing is proved about the final vocabulary.

The encoding input is a word ww of nn characters and the vocabulary VV. The output is the list of pieces that greedy longest match first gives, or [UNK].

The algorithm

Training, with the unigram likelihood gain:

  1. WORDPIECE-TRAIN(C, K) ▷ C maps words to counts
  2. 1for each word w in C do S[w] ← [w1, ##w2, ..., ##wn]
  3. 2V ← set of all units in S
  4. 3repeat K times
  5. 4c ← unit counts, P ← pair counts (both weighted by C)
  6. 5if P is empty then stop
  7. 6for each pair (a, b) in P do g(a, b) ← closed-form gain with k = P(a, b)
  8. 7(a, b) ← pair with the largest g, ties to the smallest pair
  9. 8in every S[w], replace each occurrence of a b, from the left, by ab
  10. 9V ← V ∪ {ab}, append (a, b) to the merge list
  11. 10return V and the merge list

Encoding of one word, as in the BERT code:

  1. WORDPIECE-ENCODE(w, V, maxlen)
  2. E1 if |w| > maxlen then return [UNK]
  3. E2 out ← empty list, start ← 0
  4. E3 while start < |w| do
  5. E4 end ← |w|, piece ← none
  6. E5 while start < end do
  7. E6 sub ← w[start..end), with "##" in front if start > 0
  8. E7 if sub ∈ V then piece ← sub, and leave this loop
  9. E8 end ← end - 1
  10. E9 if piece = none then return [UNK]
  11. E10 append piece to out, start ← end
  12. E11 return out

Line L8 scans each word from the left and skips past each replaced pair, so a run such as ##a ##a ##a\#\#a\ \#\#a\ \#\#a gives one merge, not two. The pair count kk of line L4 counts the same non-overlapping occurrences, so the gain of line L6 matches the merge of line L8. The encoder of lines E5 to E8 tries the end positions from the right, so the first hit is the longest piece. Positions are 0-based, and w[i..j)w[i..j) is the span (i,j)(i, j) in fencepost indices: it holds the characters i+1i + 1 to jj.

Example

Take the counts hug 2, pug 2, pun 2, bun 10 and hugs 10. The first segmentation has N=88N = 88 units, with c(##u)=26c(\#\#u) = 26, c(##g)=14c(\#\#g) = 14, c(h)=12c(h) = 12, c(##n)=12c(\#\#n) = 12, c(##s)=10c(\#\#s) = 10, c(b)=10c(b) = 10, c(p)=4c(p) = 4, and L=−161.1137\mathcal{L} = -161.1137 nats. The pairs of the first step:

pair count kk gain gg (nats)
##g ##s 10 22.7807
##u ##g 14 20.6132
h ##u 12 17.1062
##u ##n 12 17.1062
b ##u 10 13.8333
p ##u 4 5.1095

The most frequent pair is ##u ##g, which BPE would merge first. WordPiece merges ##g ##s, because every ##s follows a ##g, so the merge removes the unit ##s and makes the model sharper. The next four merges are ##u ##n, h ##u, b ##un and hu ##gs. In the second step, h ##u and ##u ##n tie at 15.5424, and the tie goes to ##u ##n because "##u" sorts before "h". In the fourth step, b ##un and hu ##gs tie at 20.4682, and the tie goes to b ##un. After five merges, VV has 12 units: ##g, ##gs, ##n, ##s, ##u, ##un, b, bun, h, hu, hugs and p.

Encoding "bugs" tries bugs, bug, bu and b, and takes b. At position 1 it tries ##ugs, ##ug and ##u, and takes ##u. At position 2 it takes ##gs at once. The result is b, ##u, ##gs after 8 lookups. The word "gun" gives [UNK], because no unit is a word-initial g. The word "hun" gives hu, ##n, while replaying the merges in order gives h, ##un: the encoder does not reproduce the training segmentation.

Correctness

Training takes, at each step, the merge with the largest exact gain in the unigram log likelihood: the closed form above counts every unit that the merge changes and no other, because each replacement removes one aa and one bb and adds one abab. The encoder returns, at each position, the longest piece of VV that starts there, and its pieces join back into the word. Both proofs, with the loop invariants and the count of lookups, are in proofs/correctness.md. Neither result says that the vocabulary is the best of its size: the greedy choice is a heuristic.

Proof: WordPiece training takes the merge of largest likelihood gain, and the encoder returns the greedy longest-match piecesfull

Notation. The corpus is a map CC from distinct words to positive counts. A segmentation SS gives each word ww a list of units whose concatenation, after the prefix "##" is removed from every unit but the first, is ww. The unit count is c(x)=∑wC(w)⋅#{t:S(w)t=x}c(x) = \sum_w C(w) \cdot \#\{t : S(w)_t = x\} and N=∑xc(x)N = \sum_x c(x). All logs are natural logs. Write F(x)=xlog⁡xF(x) = x \log x with F(0)=0F(0) = 0. The unigram log likelihood of the corpus with maximum likelihood probabilities c(x)/Nc(x)/N is

L(S)=∑xc(x)log⁡c(x)N=∑xF(c(x))−F(N)(log⁡ base e).\mathcal{L}(S) = \sum_x c(x) \log \frac{c(x)}{N} = \sum_x F(c(x)) - F(N) \qquad (\log \text{ base } e).

The second form holds because ∑xc(x)log⁡N=Nlog⁡N\sum_x c(x) \log N = N \log N, and units with c(x)=0c(x) = 0 add F(0)=0F(0) = 0 to both sides.

Lemma 1 (the pair count). Let kk be the number of occurrences of (a,b)(a, b) that MERGE replaces, counted with the word counts, and let abab be the joined unit. After the merge, c(ab)c(ab) grows by kk, NN drops by kk, and c(a)c(a) and c(b)c(b) each drop by kk if a≠ba \ne b, while c(a)c(a) drops by 2k2k if a=ba = b. No other count changes.

Proof. Each replacement removes one unit aa and one unit bb at two adjacent places and puts one unit abab there. The replaced occurrences do not overlap, because the scan in MERGE moves two places after each replacement, so the kk replacements remove 2k2k distinct unit occurrences. If a=ba = b these are 2k2k copies of aa. The joined unit abab is longer than aa and than bb, so abab is neither of them, and its count grows by exactly kk. The number of units drops by one per replacement. □\square

Lemma 2 (the closed form of the gain). With kk, aa, bb as in Lemma 1, the change L(S′)−L(S)\mathcal{L}(S') - \mathcal{L}(S) is

g=F(cab+k)−F(cab)+F(ca−k)−F(ca)+F(cb−k)−F(cb)−F(N−k)+F(N)g = F(c_{ab} + k) - F(c_{ab}) + F(c_a - k) - F(c_a) + F(c_b - k) - F(c_b) - F(N - k) + F(N)

when a≠ba \ne b, and the same with F(ca−2k)−F(ca)F(c_a - 2k) - F(c_a) in place of the two middle differences when a=ba = b. This is what merge_gain returns.

Proof. Apply the second form of L\mathcal{L} before and after the merge. By Lemma 1 every term F(c(x))F(c(x)) with x∉{a,b,ab}x \notin \{a, b, ab\} is the same in both sums and cancels. The remaining terms are the ones written. □\square

Theorem 1 (training). WORDPIECE-TRAIN stops after at most KK passes. In each pass, the pair it merges has the largest likelihood gain among all adjacent pairs of the current segmentation, and among pairs with the same gain it is the smallest in string order. The returned vocabulary holds every initial unit and every merged unit.

Proof. The loop of line L3 runs at most KK times, and line L5 can stop it earlier. Each pass computes the counts of line L4 from the current segmentation. Line L6 gives each pair present in the corpus the value gg of Lemma 2, which by that lemma is the exact change of L\mathcal{L}. Line L7 takes the pair with the largest gg, with ties broken by the pair itself. Line L8 applies the merge to every word, so the next pass starts from the segmentation that the gain was computed for. Line L2 puts every initial unit into VV and line L9 adds each merged unit. □\square

Theorem 1 says that each merge is the best single step for the likelihood. It does not say that the KK merges together give the largest likelihood among all vocabularies of that size. No such claim is made: a greedy sequence of best single steps need not be a best sequence, and for the related objective of compression the search for the best merge sequence is NP-hard.

Theorem 2 (encoder). For a word ww of n≤n \le max_chars characters and a vocabulary VV, WORDPIECE-ENCODE returns [UNK] if some step finds no piece. Otherwise it returns u1,…,uru_1, \ldots, u_r with these properties: u1=w[0…p1)u_1 = w[0 \ldots p_1) and ut=## w[pt−1…pt)u_t = \#\#\, w[p_{t-1} \ldots p_t) for t≥2t \ge 2; each ut∈Vu_t \in V; pr=np_r = n; and each ptp_t is the largest j>pt−1j > p_{t-1} for which the piece that starts at pt−1p_{t-1} and ends at jj is in VV. It stops after at most n(n+1)/2n(n + 1)/2 tests of line E7.

Proof. Inner loop: at the test of line E5, every end jj with end <j≤n< j \le n has been tried and its piece is not in VV. This holds at line E4, where end =n= n and the range is empty. Line E8 lowers end by 1 only after line E7 has failed for it, which keeps the invariant. If line E7 succeeds, the piece of length end −- start is in VV and every longer one is not, so it is the longest. If the loop ends with end == start, no piece starts at this position, and line E9 returns [UNK].

Outer loop: at the test of line E3, out holds u1,…,utu_1, \ldots, u_t with the stated form and start =pt= p_t. Line E10 appends the longest piece at ptp_t and sets start to its end. The prefix "##" is added by line E6 exactly when start >0> 0, which is the case for t≥1t \ge 1. Since each piece has length at least 1, start grows by at least 1 in each pass, so the outer loop runs at most nn times and ends with start =n= n.

Count: at position start =p= p, line E7 runs at most n−pn - p times. The sum over p=0,…,n−1p = 0, \ldots, n - 1 is at most n+(n−1)+⋯+1=n(n+1)/2n + (n - 1) + \cdots + 1 = n(n + 1)/2. ■\blacksquare

Complexity

  • Training. In the word-RAM model, one step recounts the units and the pairs of all distinct words. A word of length ll has at most l−1l - 1 pairs, and counting the non-overlapping occurrences of one pair costs O(l)O(l), so a step costs O(Lm)O(L m) for distinct words of total length LL and maximum length mm. KK steps cost O(KLm)O(K L m). Schuster and Nakajima list faster schemes: test only pairs that occur, and update only the counts that a merge changes.
  • Encoding. For a word of nn characters, line E7 runs at most n(n+1)/2n(n + 1)/2 times. Building and hashing a piece of length up to nn costs O(n)O(n), so the BERT code costs O(n3)O(n^3) character steps in the worst case, as for the vocabulary {a, ##a} and the word ana^n. With pieces of length at most mm and a trie, the cost is O(nm)O(n m), and fast WordPiece reaches O(n)O(n).
  • Space. O(L)O(L) for the segmentations and the counts, and O(Vm)O(V m) for a vocabulary of VV pieces.

Properties

  • Open vocabulary up to the alphabet. Every character of the training text is a unit, so any word made only of training characters has an encoding. A word with an unseen character becomes [UNK] as a whole.
  • Not frequency order. The merge order differs from the BPE order, as the example shows.
  • Gains can be negative. In the fifth step of the example the pair hu ##g has the gain −0.0434-0.0434. A fixed target size can therefore lower the likelihood near the end; Schuster and Nakajima also stop when the gain falls below a threshold.
  • Greedy encoding. The encoder is a function of VV only, not of the merge order or of the counts. Hugging Face describes WordPiece models that save only the final vocabulary, not the merges.
  • Deterministic. The same word always gets the same pieces, which is what subword regularization changes.

Variants and improvements

  • Frequency ratio score. The Hugging Face course trains with the score freq(ab)/(freq(a) freq(b))\text{freq}(ab) / (\text{freq}(a)\,\text{freq}(b)). This is a different heuristic from the likelihood gain above. Google never released its training code, so the exact original criterion is known only from the paper.
  • Word-start marks. Schuster and Nakajima, and Wu et al. (2016), mark the start of a word with "_" instead of marking the inner pieces with "##".
  • Linear-time encoding. LinMaxMatch adds failure links and failure pops to the trie of VV in the style of Aho-Corasick; see fast WordPiece tokenization.
  • Unigram tokenization. Unigram language model tokenization keeps the likelihood but drops the greedy merges: it prunes a large vocabulary and segments with the Viterbi algorithm.

When to use it

Use WordPiece when you must match a model trained with it, such as BERT: the vocabulary, the "##" convention, the lowercasing and the [UNK] rule must be the same as at training time. For a new model, byte-level BPE avoids [UNK] entirely, and the unigram method gives several segmentations for regularization.

Pitfalls

  • [UNK] eats the whole word. One unknown character, such as a rare symbol or emoji, turns the full word into [UNK], not only that character. This is an out-of-vocabulary failure at the character level.
  • Two conventions for the mark. "##" on inner pieces (BERT) and "_" on word starts (Schuster and Nakajima, GNMT) are not interchangeable. Mixing them breaks detokenization.
  • The encoder is not the merge replay. A word such as "hun" in the example gets different pieces from the two rules. Train and encode with the same rule if the pieces must agree.
  • Pre-tokenization comes first. The encoder works on single words. The BERT code first splits on whitespace and punctuation (and, for the uncased model, lowercases and strips accents). A different split gives different pieces.
  • Length limit. The BERT code returns [UNK] for a word of more than 200 characters, so a long URL or a long number loses all its content.

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.

wordpiece.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wordpiece/. The authors are listed in prov/N8960R.jsonl.

"""WordPiece: vocabulary learning by likelihood gain, and greedy longest-match encoding.

train_wordpiece learns merges. Each word starts as its characters, and every
character after the first carries the prefix "##". At each step the merge of
the adjacent pair (a, b) that raises the log likelihood of the corpus most is
applied, where the likelihood is that of a unigram model over the current
units with maximum likelihood probabilities c(x) / N. Logs are natural logs,
so the likelihood is in nats.

encode_word is the encoder of BERT: from left to right, take the longest
vocabulary piece that starts at the current position (with "##" after the
first piece), and give [UNK] for the whole word when no piece fits.
"""

import math
from typing import Dict, Iterable, List, Mapping, Sequence, Set, Tuple

PREFIX = "##"
UNK = "[UNK]"

Pair = Tuple[str, str]


def initial_units(word: str) -> List[str]:
    """Return the first segmentation of a nonempty word: w1, ##w2, ..., ##wn."""
    if not word:
        raise ValueError("a word must not be empty")
    return [word[0]] + [PREFIX + ch for ch in word[1:]]


def join_units(a: str, b: str) -> str:
    """Return the unit made from a followed by b. b is never word-initial."""
    if not b.startswith(PREFIX):
        raise ValueError("the right unit of a pair must start with ##")
    return a + b[len(PREFIX):]


def count_pair(units: Sequence[str], a: str, b: str) -> int:
    """Return the number of non-overlapping occurrences of (a, b), taken from the left."""
    k, i = 0, 0
    while i + 1 < len(units):
        if units[i] == a and units[i + 1] == b:
            k, i = k + 1, i + 2
        else:
            i += 1
    return k


def merge_units(units: Sequence[str], a: str, b: str) -> List[str]:
    """Replace each non-overlapping occurrence of (a, b), taken from the left, by one unit."""
    out, i, ab = [], 0, join_units(a, b)
    while i < len(units):
        if i + 1 < len(units) and units[i] == a and units[i + 1] == b:
            out.append(ab)
            i += 2
        else:
            out.append(units[i])
            i += 1
    return out


def unit_counts(seg: Mapping[str, Sequence[str]], freq: Mapping[str, int]) -> Dict[str, int]:
    """Return c(x): the number of times unit x occurs in the corpus."""
    c: Dict[str, int] = {}
    for w, units in seg.items():
        for x in units:
            c[x] = c.get(x, 0) + freq[w]
    return c


def pair_counts(seg: Mapping[str, Sequence[str]], freq: Mapping[str, int]) -> Dict[Pair, int]:
    """Return k(a, b): the number of merges that (a, b) would make in the corpus."""
    p: Dict[Pair, int] = {}
    for w, units in seg.items():
        for pair in set(zip(units, units[1:])):
            k = count_pair(units, pair[0], pair[1])
            p[pair] = p.get(pair, 0) + k * freq[w]
    return p


def xlogx(x: int) -> float:
    """Return x ln x, with 0 ln 0 = 0."""
    return 0.0 if x == 0 else x * math.log(x)


def log_likelihood(c: Mapping[str, int]) -> float:
    """Return the unigram log likelihood sum_x c(x) ln(c(x) / N) in nats."""
    n = sum(c.values())
    return math.fsum(xlogx(v) for v in c.values()) - xlogx(n)


def merge_gain(c: Mapping[str, int], a: str, b: str, k: int) -> float:
    """Return the change in log likelihood when k occurrences of (a, b) become ab.

    Only c(a), c(b), c(ab) and N change, so the gain is a sum of six or eight
    terms of the form x ln x. When a = b, c(a) drops by 2k.
    """
    ab = join_units(a, b)
    n = sum(c.values())
    ca, cab = c.get(a, 0), c.get(ab, 0)
    g = xlogx(cab + k) - xlogx(cab) - (xlogx(n - k) - xlogx(n))
    if a == b:
        return g + xlogx(ca - 2 * k) - xlogx(ca)
    cb = c.get(b, 0)
    return g + xlogx(ca - k) - xlogx(ca) + xlogx(cb - k) - xlogx(cb)


def train_wordpiece(freq: Mapping[str, int], merges: int) -> Tuple[Set[str], List[Pair]]:
    """Learn at most `merges` merges from a map of word counts.

    Return the vocabulary (all initial units and all merged units) and the
    list of merges in the order they were made. Ties in the gain go to the
    smallest pair in string order, so the result is deterministic. Gains are
    compared to 9 decimals, so that rounding in the logarithms cannot break
    an exact tie.
    Cost per merge: O(L) for the counts, where L is the total word length.
    """
    seg = {w: initial_units(w) for w in freq}  # @line L1
    vocab = {x for units in seg.values() for x in units}  # @line L2
    done: List[Pair] = []
    for _ in range(merges):  # @line L3
        c, p = unit_counts(seg, freq), pair_counts(seg, freq)  # @line L4
        if not p:  # @line L5
            break
        gain = {pair: merge_gain(c, pair[0], pair[1], k) for pair, k in p.items()}  # @line L6
        a, b = min(gain, key=lambda pair: (-round(gain[pair], 9), pair))  # @line L7
        seg = {w: merge_units(units, a, b) for w, units in seg.items()}  # @line L8
        vocab.add(join_units(a, b))  # @line L9
        done.append((a, b))
    return vocab, done  # @line L10


def segment_with_merges(word: str, merges: Iterable[Pair]) -> List[str]:
    """Apply the learned merges to one word in training order."""
    units = initial_units(word)
    for a, b in merges:
        units = merge_units(units, a, b)
    return units


def encode_word(word: str, vocab: Set[str], max_chars: int = 200) -> List[str]:
    """Encode one word by greedy longest match first, as BERT does.

    Return [UNK] when the word is longer than max_chars or when some position
    has no matching piece. Cost: at most n(n + 1) / 2 set lookups for a word
    of n characters.
    """
    if len(word) > max_chars:  # @line E1
        return [UNK]
    out, start = [], 0  # @line E2
    while start < len(word):  # @line E3
        end, piece = len(word), None  # @line E4
        while start < end:  # @line E5
            sub = word[start:end] if start == 0 else PREFIX + word[start:end]  # @line E6
            if sub in vocab:  # @line E7
                piece = sub
                break
            end -= 1  # @line E8
        if piece is None:  # @line E9
            return [UNK]
        out.append(piece)  # @line E10
        start = end
    return out  # @line E11


def encode(words: Iterable[str], vocab: Set[str], max_chars: int = 200) -> List[str]:
    """Encode a list of pre-tokenized words and join the pieces."""
    out: List[str] = []
    for w in words:
        out.extend(encode_word(w, vocab, max_chars))
    return out
test_wordpiece.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wordpiece/. The authors are listed in prov/N8960R.jsonl.

import math
import random

import pytest

from wordpiece import (
    UNK,
    count_pair,
    encode,
    encode_word,
    initial_units,
    join_units,
    log_likelihood,
    merge_gain,
    merge_units,
    pair_counts,
    segment_with_merges,
    train_wordpiece,
    unit_counts,
)

FREQ = {"hug": 2, "pug": 2, "pun": 2, "bun": 10, "hugs": 10}


def recount_gain(seg, freq, a, b):
    """The gain by brute force: apply the merge and recount everything."""
    before = log_likelihood(unit_counts(seg, freq))
    after_seg = {w: merge_units(u, a, b) for w, u in seg.items()}
    return log_likelihood(unit_counts(after_seg, freq)) - before


def greedy_by_brute_force(word, vocab):
    """Greedy longest match first, written as a search over all piece lengths."""
    out, i = [], 0
    while i < len(word):
        cands = [j for j in range(i + 1, len(word) + 1) if (word[i:j] if i == 0 else "##" + word[i:j]) in vocab]
        if not cands:
            return [UNK]
        j = max(cands)
        out.append(word[i:j] if i == 0 else "##" + word[i:j])
        i = j
    return out


def test_initial_units_and_join():
    assert initial_units("hugs") == ["h", "##u", "##g", "##s"]
    assert join_units("h", "##u") == "hu"
    assert join_units("##u", "##g") == "##ug"
    with pytest.raises(ValueError):
        join_units("h", "u")
    with pytest.raises(ValueError):
        initial_units("")


def test_pair_count_does_not_overlap():
    units = ["a"] + ["##a"] * 5
    assert count_pair(units, "##a", "##a") == 2
    assert merge_units(units, "##a", "##a") == ["a", "##aa", "##aa", "##a"]
    assert count_pair(units, "a", "##a") == 1


def test_first_step_gains_of_the_page():
    seg = {w: initial_units(w) for w in FREQ}
    c, p = unit_counts(seg, FREQ), pair_counts(seg, FREQ)
    assert sum(c.values()) == 88
    assert p[("##u", "##g")] == 14 and p[("##g", "##s")] == 10
    assert log_likelihood(c) == pytest.approx(-161.1137, abs=1e-4)
    assert merge_gain(c, "##g", "##s", 10) == pytest.approx(22.7807, abs=1e-4)
    assert merge_gain(c, "##u", "##g", 14) == pytest.approx(20.6132, abs=1e-4)


def test_closed_form_gain_equals_recount():
    rng = random.Random(7)
    for _ in range(60):
        words = {"".join(rng.choice("aab") for _ in range(rng.randint(1, 6))) for _ in range(5)}
        freq = {w: rng.randint(1, 9) for w in words}
        seg = {w: initial_units(w) for w in freq}
        for _ in range(3):
            c, p = unit_counts(seg, freq), pair_counts(seg, freq)
            for (a, b), k in p.items():
                assert merge_gain(c, a, b, k) == pytest.approx(recount_gain(seg, freq, a, b), abs=1e-9)
            if not p:
                break
            a, b = min(p)
            seg = {w: merge_units(u, a, b) for w, u in seg.items()}


def test_training_picks_the_best_gain_each_step():
    vocab, merges = train_wordpiece(FREQ, 5)
    assert merges == [("##g", "##s"), ("##u", "##n"), ("h", "##u"), ("b", "##un"), ("hu", "##gs")]
    seg = {w: initial_units(w) for w in FREQ}
    for a, b in merges:
        p = pair_counts(seg, FREQ)
        gains = {pair: recount_gain(seg, FREQ, *pair) for pair in p}
        assert gains[(a, b)] == pytest.approx(max(gains.values()), abs=1e-9)
        seg = {w: merge_units(u, a, b) for w, u in seg.items()}
    assert {"hugs", "bun", "hu", "##un", "##gs"} <= vocab


def test_the_gain_differs_from_the_pair_count():
    seg = {w: initial_units(w) for w in FREQ}
    p = pair_counts(seg, FREQ)
    assert max(p, key=p.get) == ("##u", "##g")
    assert train_wordpiece(FREQ, 1)[1] == [("##g", "##s")]


def test_training_stops_when_no_pair_is_left():
    vocab, merges = train_wordpiece({"ab": 3}, 10)
    assert merges == [("a", "##b")]
    assert vocab == {"a", "##b", "ab"}


def test_encoder_examples():
    vocab, merges = train_wordpiece(FREQ, 5)
    assert encode_word("hugs", vocab) == ["hugs"]
    assert encode_word("hug", vocab) == ["hu", "##g"]
    assert encode_word("bugs", vocab) == ["b", "##u", "##gs"]
    assert encode_word("gun", vocab) == [UNK]
    assert encode_word("unaffable", {"un", "##aff", "##able", "##a"}) == ["un", "##aff", "##able"]
    assert encode(["hugs", "gun", "bun"], vocab) == ["hugs", UNK, "bun"]


def test_long_word_is_unknown():
    vocab = {"a", "##a"}
    assert encode_word("a" * 200, vocab) == ["a"] + ["##a"] * 199
    assert encode_word("a" * 201, vocab) == [UNK]
    assert encode_word("aaa", vocab, max_chars=2) == [UNK]


def test_encoder_against_brute_force():
    rng = random.Random(11)
    for _ in range(300):
        vocab = {"".join(rng.choice("abc") for _ in range(rng.randint(1, 3))) for _ in range(5)}
        vocab |= {"##" + "".join(rng.choice("abc") for _ in range(rng.randint(1, 3))) for _ in range(6)}
        word = "".join(rng.choice("abc") for _ in range(rng.randint(1, 8)))
        assert encode_word(word, vocab) == greedy_by_brute_force(word, vocab)


def test_greedy_is_not_the_merge_order():
    # The encoder and the merge replay can differ: greedy longest match is a different rule.
    vocab, merges = train_wordpiece(FREQ, 5)
    differ = 0
    rng = random.Random(3)
    for _ in range(200):
        w = "".join(rng.choice("hugsbpn") for _ in range(rng.randint(1, 6)))
        if UNK not in encode_word(w, vocab) and encode_word(w, vocab) != segment_with_merges(w, merges):
            differ += 1
    assert differ > 0


def test_pieces_concatenate_to_the_word():
    vocab, _ = train_wordpiece(FREQ, 5)
    rng = random.Random(5)
    for _ in range(200):
        w = "".join(rng.choice("hugsbpn") for _ in range(rng.randint(1, 7)))
        pieces = encode_word(w, vocab)
        if pieces != [UNK]:
            assert "".join(x[2:] if i else x for i, x in enumerate(pieces)) == w
            assert all(x in vocab for x in pieces)

History

Schuster and Nakajima (2012) introduced word pieces for Japanese and Korean voice search. They grew an inventory of up to 200,000 units by adding, at each step, the pair whose combination most increased the likelihood of a language model on the training data. Wu et al. (2016) used the same wordpiece model for Google's neural machine translation system, with 8,000 to 32,000 wordpieces. Devlin et al. (2019) used a WordPiece vocabulary of 30,000 tokens for BERT, and the BERT code made the "##" prefix and greedy longest-match encoding the common form. Song et al. (2021) gave the linear-time encoder.

References

  1. Mike Schuster and Kaisuke Nakajima, Japanese and Korean voice search, ICASSP 2012, pages 5149 to 5152, Section 3, Segmentation and word inventory (page 5150, the four-step building algorithm and its speedups)
  2. Yonghui Wu et al., Google's neural machine translation system, Bridging the gap between human and machine translation, arXiv 1609.08144, 2016 (preprint), Section 4.1, Wordpiece Model
  3. Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova, BERT, Pre-training of deep bidirectional transformers for language understanding, NAACL 2019, pages 4171 to 4186, Section 3, Input/Output Representations (a WordPiece vocabulary of 30,000 tokens)
  4. Google Research, BERT reference code, tokenization.py, class WordpieceTokenizer (greedy longest-match-first, max_input_chars_per_word = 200)
  5. Xinying Song, Alex Salcianu, Yang Song, Dave Dopson and Denny Zhou, Fast WordPiece tokenization, EMNLP 2021, pages 2089 to 2103, Sections 1 and 2 (MaxMatch in WordPiece and its O(n^2) or O(nm) cost)
  6. Hugging Face, LLM Course, Chapter 6, WordPiece tokenization, the training score freq(ab) / (freq(a) freq(b)), and the remark that Google did not release its training code

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.encode_word
  • a full proof of time.train
  • a full proof of space.train
  • a full proof of space.vocabulary
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