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
- Solves
- Tokenization
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 from distinct words to counts, and a number of merges . Each word starts as the units . A merge of the adjacent units and makes the unit : the text of followed by the text of without its "##". The output is a vocabulary 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 , where counts the occurrences of unit and :
Merging occurrences of changes only , , and , so the gain has a closed form with eight terms when :
When , the two middle differences become . 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 of characters and the vocabulary . The output is the list of pieces that greedy longest match first gives, or [UNK].
The algorithm
Training, with the unigram likelihood gain:
WORDPIECE-TRAIN(C, K) ▷ C maps words to counts- 1
for each word w in C do S[w] ← [w1, ##w2, ..., ##wn] - 2
V ← set of all units in S - 3
repeat K times - 4
c ← unit counts, P ← pair counts (both weighted by C) - 5
if P is empty then stop - 6
for each pair (a, b) in P do g(a, b) ← closed-form gain with k = P(a, b) - 7
(a, b) ← pair with the largest g, ties to the smallest pair - 8
in every S[w], replace each occurrence of a b, from the left, by ab - 9
V ← V ∪ {ab}, append (a, b) to the merge list - 10
return V and the merge list
Encoding of one word, as in the BERT code:
WORDPIECE-ENCODE(w, V, maxlen)E1 if |w| > maxlen then return [UNK]E2 out ← empty list, start ← 0E3 while start < |w| doE4 end ← |w|, piece ← noneE5 while start < end doE6 sub ← w[start..end), with "##" in front if start > 0E7 if sub ∈ V then piece ← sub, and leave this loopE8 end ← end - 1E9 if piece = none then return [UNK]E10 append piece to out, start ← endE11 return out
Line L8 scans each word from the left and skips past each replaced pair, so a run such as gives one merge, not two. The pair count 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 is the span in fencepost indices: it holds the characters to .
Example
Take the counts hug 2, pug 2, pun 2, bun 10 and hugs 10. The first segmentation has units, with , , , , , , , and nats. The pairs of the first step:
| pair | count | gain (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, 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 and one and adds one . The encoder returns, at each position, the longest piece of 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 from distinct words to positive counts. A segmentation gives each word a list of units whose concatenation, after the prefix "##" is removed from every unit but the first, is . The unit count is and . All logs are natural logs. Write with . The unigram log likelihood of the corpus with maximum likelihood probabilities is
The second form holds because , and units with add to both sides.
Lemma 1 (the pair count). Let be the number of occurrences of that MERGE replaces, counted with the word counts, and let be the joined unit. After the merge, grows by , drops by , and and each drop by if , while drops by if . No other count changes.
Proof. Each replacement removes one unit and one unit at two adjacent places and puts one unit there. The replaced occurrences do not overlap, because the scan in MERGE moves two places after each replacement, so the replacements remove distinct unit occurrences. If these are copies of . The joined unit is longer than and than , so is neither of them, and its count grows by exactly . The number of units drops by one per replacement.
Lemma 2 (the closed form of the gain). With , , as in Lemma 1, the change is
when , and the same with in place of the two middle differences when . This is what merge_gain returns.
Proof. Apply the second form of before and after the merge. By Lemma 1 every term with is the same in both sums and cancels. The remaining terms are the ones written.
Theorem 1 (training). WORDPIECE-TRAIN stops after at most 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 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 of Lemma 2, which by that lemma is the exact change of . Line L7 takes the pair with the largest , 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 and line L9 adds each merged unit.
Theorem 1 says that each merge is the best single step for the likelihood. It does not say that the 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 of max_chars characters and a vocabulary , WORDPIECE-ENCODE returns [UNK] if some step finds no piece. Otherwise it returns with these properties: and for ; each ; ; and each is the largest for which the piece that starts at and ends at is in . It stops after at most tests of line E7.
Proof. Inner loop: at the test of line E5, every end with end has been tried and its piece is not in . This holds at line E4, where end 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 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 with the stated form and start . Line E10 appends the longest piece at and sets start to its end. The prefix "##" is added by line E6 exactly when start , which is the case for . Since each piece has length at least 1, start grows by at least 1 in each pass, so the outer loop runs at most times and ends with start .
Count: at position start , line E7 runs at most times. The sum over is at most .
Complexity
- Training. In the word-RAM model, one step recounts the units and the pairs of all distinct words. A word of length has at most pairs, and counting the non-overlapping occurrences of one pair costs , so a step costs for distinct words of total length and maximum length . steps cost . 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 characters, line E7 runs at most times. Building and hashing a piece of length up to costs , so the BERT code costs character steps in the worst case, as for the vocabulary {a, ##a} and the word . With pieces of length at most and a trie, the cost is , and fast WordPiece reaches .
- Space. for the segmentations and the counts, and for a vocabulary of 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 . 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 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 . 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 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.
# 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
- 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)
- 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
- 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)
- Google Research, BERT reference code, tokenization.py, class WordpieceTokenizer (greedy longest-match-first, max_input_chars_per_word = 200)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag N8960R Edit this page History Report an error Markdown