Algorithm Search⌘K

Algorithmresearch

Fast WordPiece tokenization

Also called LinMaxMatch.

Linear-time greedy longest-match WordPiece encoding with a trie extended by failure links and failure pops, in the style of Aho-Corasick.

Time
O(n) encode_wordO(M m) precompute
Space
O(n) encode_wordO(M m) trie_with_pops
Where
M = the total length of all tokens; m = the length of the longest token; n = the length of the word in characters
Properties
deterministicexactofflineiterative
Origin
Xinying Song, Alex Salcianu, Yang Song, Dave Dopson, Denny Zhou, 2021

Fast WordPiece tokenization computes the same pieces as the greedy longest-match-first encoder of WordPiece, but in time linear in the length of the word. It puts the vocabulary in a trie and adds to each node a failure link and a list of failure pops, much as Aho-Corasick adds failure links to a trie of patterns. The single-word algorithm is called LinMaxMatch. Song et al. (2021) also give an end-to-end version that splits the text into words in the same pass.

In plain words

The usual WordPiece encoder tries the longest piece at a position, then a shorter one, then a shorter one, and only then moves on. On a bad word it reads the same letters many times.

The fast encoder reads each letter once. It walks down a tree of all pieces, one letter at a time. When the next letter has no branch, it does not go back. Each place in the tree already knows two things, worked out once for the whole vocabulary: which pieces the slow encoder would output from the letters read so far, and at which place in the tree to go on. So the encoder outputs those pieces, jumps there, and tries the same letter again. A letter can be tried again only a few times in total, so the work grows like the length of the word.

The problem

The input is a vocabulary VV of tokens, where a token that does not start a word carries the prefix ♯\sharp = "##", and a word ww of nn characters. The output is the list that greedy longest match first (MAXMATCH) gives: the longest token that is a prefix of ww, then the longest token "##"yy such that yy follows it in ww, and so on, or [UNK] if some position has no token. The BERT code does this with up to nn dictionary lookups per position. With a trie and tokens of at most mm characters it costs O(nm)O(n m), and on the vocabulary {a, ##a, amba^m b} and the word ana^n that bound is reached: each position walks mm edges toward amba^m b and then backs up.

The algorithm

The trie holds every token and the string "##". Its root is rr, the node of "##" is r♯r_\sharp, χv\chi_v is the string of node vv, and δ(u,c)\delta(u, c) is the child of uu along character cc. For a node vv, the failure pops F(v)F(v) are the tokens that MAXMATCH would emit from χv\chi_v, longest first, until the rest, written as "##" followed by the unread characters, is again a node of the trie; that node is the failure link f(v)f(v). If MAXMATCH gets stuck first, f(v)f(v) is none. The links are filled in breadth-first order (Algorithm 2 of the paper):

  1. PRECOMPUTE(V)
  2. P1 build the trie of V ∪ {##}; r ← root, r♯ ← node of ##
  3. P2 f(v) ← none and F(v) ← [] for every node v
  4. P3 queue ← [r, r♯]
  5. P4 while queue is not empty do
  6. P5 u ← dequeue(queue)
  7. P6 for each edge from u to v with label c do
  8. P7 if v = r♯ then skip to the next edge
  9. P8 if χv ∈ V then f(v) ← r♯, F(v) ← [χv]
  10. P9 else
  11. P10 z ← f(u), Z ← []
  12. P11 while z ≠ none and δ(z, c) = none do
  13. P12 Z ← Z + F(z), z ← f(z)
  14. P13 if z ≠ none then f(v) ← δ(z, c), F(v) ← F(u) + Z
  15. P14 enqueue v
  16. P15 return the trie with f and F

Encoding one word walks the trie and follows a failure link whenever the next character has no edge (Algorithm 1 of the paper):

  1. LINMAXMATCH(w) ▷ uses the trie from PRECOMPUTE
  2. 1s ← w followed by the end mark ␣, which is in no token
  3. 2u ← r, tokens ← empty list, i ← 0
  4. 3while i < |s| do
  5. 4while δ(u, s[i]) = none do
  6. 5if f(u) = none then leave both loops
  7. 6append the list F(u) to tokens
  8. 7u ← f(u)
  9. 8u ← δ(u, s[i]), i ← i + 1
  10. 9if i < |w| or u ∉ {r, r♯} then return [UNK]
  11. 10if u = r♯ and tokens is empty then return MAXMATCH("##")
  12. 11return tokens

The end mark of line L1 has no edge anywhere, so at the end of the word the loop pops every pending token. A successful run stops at r♯r_\sharp, where all characters are covered, or at rr for the empty word. Line L10 handles the word "##", whose path from the root also ends at r♯r_\sharp. Positions are 0-based, and w[i..j)w[i..j) is the span (i,j)(i, j) in fencepost indices.

Example

This is the example of Song et al. Let VV = {a, abcdx, ##b, ##c, ##cdy, ##dz}. PRECOMPUTE gives:

node χv\chi_v F(v)F(v) f(v)f(v)
a [a] ##
ab [a] ##b
abc [a, ##b] ##c
abcd [a, ##b] ##cd
abcdx [abcdx] ##
##b [##b] ##
##c [##c] ##
##cd [##c] ##d
##cdy [##cdy] ##
##d [] none
##dz [##dz] ##

The root, "#" and "##" have empty pops and no link. For the node abcd, MAXMATCH would emit a and then ##b, and the rest "##cd" is a node, so the encoder can go on from there without reading c and d again.

On the word abcdz the encoder walks a, ab, abc, abcd. The letter z has no edge from abcd, so it emits a, ##b and moves to ##cd. There is still no edge for z, so it emits ##c and moves to ##d, where z leads to ##dz. The end mark has no edge, so it emits ##dz and moves to ##, whose link is none. The result is a, ##b, ##c, ##dz after 5 steps along edges and 3 failure steps. The word abcz stops at abc with i = 3 < 4, and abcd stops at ##d, which has no link, so both give [UNK], as MAXMATCH does.

Correctness

PRECOMPUTE fills ff and FF as defined, by induction in breadth-first order: when a node v=δ(u,c)v = \delta(u, c) is not a token, MAXMATCH on χv\chi_v emits the pops of uu and then follows the chain of links from f(u)f(u) until some node has an edge for cc, which is what lines P10 to P13 do. LINMAXMATCH keeps the invariant that its tokens are a prefix of the MAXMATCH output and that the current node spells the unmatched rest. When the next character has no edge, no token can reach past it, so the next MAXMATCH tokens are exactly the failure pops. The equality is a theorem for every word that does not start with "##", and for every word when the one-character token "#" is not in VV. For VV = {#, ###c} and the word "##c", MAXMATCH gives #, ###c and LINMAXMATCH gives [UNK]; BERT splits off "#" as punctuation, so such words do not reach its encoder. The proofs are in proofs/correctness.md.

Proof: LinMaxMatch gives the tokens of greedy longest match first, with at most 2n trie stepsfull

Notation. VV is the vocabulary, ♯\sharp is the suffix indicator "##", and no token is ♯\sharp itself or holds the end mark ␣. The trie holds every prefix of every string in V∪{♯}V \cup \{\sharp\}; χv\chi_v is the string of node vv, rr is the root and r♯r_\sharp is the node of ♯\sharp. A node whose string starts with ♯\sharp lies in the ♯\sharp subtree; its content is χv\chi_v without the leading ♯\sharp. For any other node the content is χv\chi_v. The level of vv is the length of its content.

A string xx is read in one of two contexts. In the word-start context, a candidate for xx is any token that is a prefix of xx. In the suffix context, x=♯yx = \sharp y and a candidate is a token ♯y′\sharp y' with y′y' a nonempty prefix of yy. Strings in the ♯\sharp subtree are read in the suffix context, all others in the word-start context.

Pops. For a node v∉{r,r♯}v \notin \{r, r_\sharp\}, set x0=χvx_0 = \chi_v and repeat: let ptp_t be the longest candidate for xt−1x_{t-1}; if there is none, the pops fail; else xtx_t is ♯\sharp followed by the content of xt−1x_{t-1} after ptp_t, read in the suffix context. Stop at the first t≥1t \ge 1 for which xtx_t is a trie node. The content gets shorter at each step, and xt=♯x_t = \sharp is the node r♯r_\sharp, so exactly one of the two endings happens. This is Definition 1 of Song et al.: if the pops stop at t=kt = k, then F(v)=[p1,…,pk]F(v) = [p_1, \ldots, p_k] and f(v)f(v) is the node of xkx_k; if they fail, $f(v) = $ none and F(v)=[]F(v) = []. For rr and r♯r_\sharp both are empty.

Lemma 0 (extension). Let yy be a string that is not a trie node, read in some context, and let cc be a character. Then ycy c is not a trie node, and yy and ycy c have the same longest candidate (or both have none).

Proof. The trie is closed under prefixes, so ycy c is not a node. A candidate for ycy c that is not a prefix of yy is ycy c itself, which would make ycy c a node. □\square

Lemma 1 (PRECOMPUTE). After PRECOMPUTE, f(v)f(v) and F(v)F(v) are as defined by the pops, for every node vv.

Proof. Line P7 skips r♯r_\sharp as a child, so a node of the ♯\sharp subtree is reached only from r♯r_\sharp, and the queue of line P3 holds rr and r♯r_\sharp, both at level 0. Each other child has the level of its parent plus one, so the search takes the nodes in order of level. Every failure link points to a node of smaller level, because the content of xkx_k is a proper suffix of the content of χv\chi_v. So when vv gets its values (while its parent uu is dequeued), ff and FF are final for uu and for every node that line P11 can reach from f(u)f(u). Use induction on this order. The values of rr and r♯r_\sharp stay empty, which is right.

Let v=δ(u,c)v = \delta(u, c), so χv=χuc\chi_v = \chi_u c, read in the same context as χu\chi_u. If χv∈V\chi_v \in V, the longest candidate for χv\chi_v is χv\chi_v itself, x1=♯x_1 = \sharp is a node, and the pops give F(v)=[χv]F(v) = [\chi_v] and f(v)=r♯f(v) = r_\sharp, as line P8 sets.

Otherwise χv∉V\chi_v \notin V, so its longest candidate is that of χu\chi_u. If u∈{r,r♯}u \in \{r, r_\sharp\}, then χu\chi_u has no candidate (its content is empty), so the pops of vv fail; line P10 sets zz = none and line P13 leaves vv empty, which is right. Else let the pops of uu give y1,y2,…y_1, y_2, \ldots. The strings yty_t before the stop are not nodes, so by Lemma 0 the pops of χv\chi_v take the same tokens and give the remainders ytcy_t c, which are not nodes either. If the pops of uu fail, those of vv fail at the same step, and line P10 sets z=f(u)=z = f(u) = none. If they stop at yk=χf(u)y_k = \chi_{f(u)}, the pops of vv have taken F(u)F(u) and reached χzc\chi_z c with z=f(u)z = f(u). If δ(z,c)\delta(z, c) exists, this is a node and the pops stop with F(v)=F(u)F(v) = F(u) and f(v)=δ(z,c)f(v) = \delta(z, c). If not, χzc\chi_z c is not a node, and the same argument applied to zz (whose values are final) shows that the pops go on with F(z)F(z) and reach χf(z)c\chi_{f(z)} c, or fail if f(z)=f(z) = none. Lines P11 and P12 follow exactly this chain and collect ZZ, and line P13 sets f(v)=δ(z,c)f(v) = \delta(z, c) and F(v)=F(u)+ZF(v) = F(u) + Z, or leaves vv empty when the chain ends at none. □\square

Theorem 1 (output). Let ww be a word without ␣. Assume that ww does not start with ♯\sharp, or that the one-character token "#" is not in VV. Then LINMAXMATCH(ww) equals the output of greedy longest match first (MAXMATCH) on ww, where MAXMATCH returns [UNK] when some position has no token.

Proof. Let s=ws = w␣. MAXMATCH emits tokens t1,t2,…t_1, t_2, \ldots that cover w[0..j1),w[j1..j2),…w[0..j_1), w[j_1..j_2), \ldots, with the usual span convention: w[i..j)w[i..j) holds the characters i+1i + 1 to jj. Call the pending text at a moment of the loop w[0..i)w[0..i) if no token has been emitted, and ♯ w[j..i)\sharp\, w[j..i) if the tokens emitted so far end at jj.

Invariant: at each test of line L4, the tokens list is a prefix t1,…,tqt_1, \ldots, t_q of the MAXMATCH output, and χu\chi_u equals the pending text. It holds at line L2 with q=0q = 0 and u=ru = r. When line L8 runs, δ(u,s[i])\delta(u, s[i]) exists, the pending text grows by s[i]s[i] and uu moves along the same edge.

Suppose line L4 finds no edge for s[i]s[i]. Any token that starts where the pending text starts and is longer than it would have the pending text followed by s[i]s[i] as a prefix, so that string would be a node. Hence the next MAXMATCH token is the longest candidate for the pending text, which is p1p_1 of the pops of uu, and the following tokens are p2,…p_2, \ldots by Lemma 0, as long as the remainders are not nodes. The candidates are the same in both contexts: for q>0q > 0 the pending text is read in the suffix context in both, and for q=0q = 0 the two contexts differ only when χu\chi_u starts with ♯\sharp and "#" ∈V\in V, which the assumption excludes. So by Lemma 1, line L6 appends the next MAXMATCH tokens, and line L7 moves to the node of the new pending text. If f(u)=f(u) = none, the pops fail, so MAXMATCH reaches a position with no token, and its output is [UNK].

Termination: ␣ is in no token, so line L4 finds no edge for it, and each failure step lowers the level (Theorem 2), so the loop exits through line L5, where f(u)=f(u) = none. If u∉{r,r♯}u \notin \{r, r_\sharp\}, the pops of uu fail and MAXMATCH gives [UNK], as shown above. If u∈{r,r♯}u \in \{r, r_\sharp\} and i<∣w∣i < |w|, the pending text has empty content, or it is "##" at the word start with "#" ∉V\notin V; no token extends it by s[i]s[i], so no token starts at that position and MAXMATCH gives [UNK]. Line L9 returns [UNK] in both cases. Otherwise i=∣w∣i = |w| and χu\chi_u is the empty pending text, ♯\sharp after a token or the empty word at rr, and the tokens list is the full MAXMATCH output. The single exception is u=r♯u = r_\sharp with no token: then ww is "##" itself, which line L10 hands to MAXMATCH. □\square

The assumption is needed. With V={#,###c}V = \{\#, \#\#\#c\}, MAXMATCH turns "##c" into #, ###c, while line L5 stops at r♯r_\sharp, whose failure link is none, and gives [UNK]. BERT splits "#" off as punctuation before WordPiece, so such words do not reach the encoder there.

Theorem 2 (linear time). On a word of nn characters, line L8 runs at most nn times and line L7 runs at most nn times. The tokens appended by line L6 number at most nn.

Proof. Line L8 consumes one character of ww each time, and never ␣. A step of line L8 raises the level by 1, except the step from the node "#" to r♯r_\sharp, which lowers it from 1 to 0. A step of line L7 lowers the level by at least 1, because the content of f(u)f(u) is a proper suffix of the content of uu. The level is never negative, so the number of runs of line L7 is at most the number of runs of line L8. Each appended token covers characters of ww that no other appended token covers, so there are at most nn of them. ■\blacksquare

Complexity

  • Encoding. In the word-RAM model, line L8 runs at most nn times. Define the level of a node as the length of its string without a leading "##". Each step along an edge raises the level by one (except the single step from "#" to "##"), and each failure step lowers it, so line L7 also runs at most nn times. At most nn tokens are appended. The total is O(n)O(n), with no factor of mm. This is a theorem.
  • Precomputation. The breadth-first search visits O(M)O(M) nodes. Song et al. bound the link computation by O(M)O(M) in the style of Aho-Corasick, and copying the pop lists, each of at most mm tokens, costs O(Mm)O(M m) time and space in a direct implementation.

Properties

  • Exact. The output is that of the BERT encoder, under the condition above, so a model trained with the slow encoder can switch to this one.
  • Each character once. The input is read once from left to right, and failure steps never move the read position back.
  • Measurements. Song et al. ran C++ code on a Linux desktop with a six-core Intel Xeon at 3.60 GHz and 64 GB of memory, with the BERT-Base Multilingual Cased vocabulary and 1,000 sentences from multilingual Wikipedia. The mean time per word was 82 ns, against 274 ns for Hugging Face Tokenizers (Rust) and 246 ns for TensorFlow Text, about 3 times faster. For end-to-end tokenization of text the means were 1,629 ns, 13,397 ns and 8,247 ns, so 8.2 and 5.1 times faster. These are measurements, not bounds.

Variants and improvements

  • End-to-end WordPiece. Section 4 of the paper adds the pre-tokenization of BERT to the same automaton: whitespace and punctuation get their own nodes, so one pass splits the text into words and words into pieces.
  • A transducer view. The trie with failure links and pops is a finite-state transducer whose failure steps emit tokens; Song et al. describe this view in Section 3.6.
  • Compact tries. The paper stores the trie as a double-array trie for speed.

When to use it

Use it to serve a model that was trained with WordPiece, such as BERT, when tokenization time matters, as in high-volume inference. It changes nothing in the model or in the vocabulary. If the vocabulary has no long tokens, the plain encoder with a trie costs O(nm)O(n m) with a small mm, and the gain is smaller.

Pitfalls

  • The end mark. The mark must not occur in any token or word. Without it, pending tokens at the end of the word are never popped.
  • The node of "##". It must never be enqueued as the child of "#" (line P7), and its own link must stay none. Otherwise a word that starts with "##" walks into suffix nodes with the wrong pops.
  • Pop lists are long. Storing F(v)F(v) as a full list at each node costs O(Mm)O(M m) space. If memory is tight, store each list once and let nodes with the same list share it.
  • [UNK] is decided at the end. A word can emit several pops and still end as [UNK], so tokens must not be streamed out before the word ends.

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.

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

"""Fast WordPiece tokenization: LinMaxMatch of Song et al. (2021).

The vocabulary is put in a trie. Each node v gets a failure link f(v) and a
list of failure pops F(v): the tokens that greedy longest match first emits
when the match cannot go on from v. With these, one left-to-right pass over a
word gives the same tokens as the greedy encoder of BERT, in time linear in
the length of the word.

Nodes are integers. Node 0 is the root r, and SUFFIX_ROOT is the node of the
suffix indicator "##". A missing link is None.
"""

from collections import deque
from typing import Dict, List, Optional, Sequence, Set, Tuple

PREFIX = "##"
UNK = "[UNK]"
END = " "  # the end mark appended to a word; no token may contain it


class Trie:
    """The trie of a vocabulary, with failure links and failure pops."""

    def __init__(self, vocab: Set[str]):
        for tok in vocab:
            if not tok or tok == PREFIX or END in tok:
                raise ValueError("a token must be nonempty, not the bare prefix, and free of the end mark")
        self.vocab = set(vocab)
        self.children: List[Dict[str, int]] = [{}]
        self.string: List[str] = [""]
        for tok in sorted(self.vocab | {PREFIX}):
            self._insert(tok)
        self.root = 0
        self.suffix_root = self.node_of(PREFIX)
        n = len(self.children)
        self.fail: List[Optional[int]] = [None] * n
        self.pops: List[List[str]] = [[] for _ in range(n)]

    def _insert(self, tok: str) -> None:
        u = 0
        for ch in tok:
            nxt = self.children[u].get(ch)
            if nxt is None:
                nxt = len(self.children)
                self.children[u][ch] = nxt
                self.children.append({})
                self.string.append(self.string[u] + ch)
            u = nxt

    def node_of(self, s: str) -> Optional[int]:
        """Return the node whose string is s, or None."""
        u: Optional[int] = 0
        for ch in s:
            u = self.children[u].get(ch)
            if u is None:
                return None
        return u

    def delta(self, u: int, ch: str) -> Optional[int]:
        return self.children[u].get(ch)


def precompute(vocab: Set[str]) -> Trie:
    """Algorithm 2 of Song et al.: fill f and F by a breadth-first search."""
    t = Trie(vocab)  # @line P1
    assert all(f is None for f in t.fail) and not any(t.pops)  # @line P2
    r, rs = t.root, t.suffix_root
    queue = deque([r, rs])  # @line P3
    while queue:  # @line P4
        u = queue.popleft()  # @line P5
        for c, v in t.children[u].items():  # @line P6
            if v == rs:  # @line P7
                continue
            if t.string[v] in t.vocab:  # @line P8
                t.fail[v], t.pops[v] = rs, [t.string[v]]
            else:  # @line P9
                z, zpops = t.fail[u], []  # @line P10
                while z is not None and t.delta(z, c) is None:  # @line P11
                    zpops, z = zpops + t.pops[z], t.fail[z]  # @line P12
                if z is not None:  # @line P13
                    t.fail[v], t.pops[v] = t.delta(z, c), t.pops[u] + zpops
            queue.append(v)  # @line P14
    return t  # @line P15


def max_match(word: str, vocab: Set[str]) -> List[str]:
    """The original greedy longest-match-first encoder, with no length limit."""
    out, start = [], 0
    while start < len(word):
        end, piece = len(word), None
        while start < end:
            sub = word[start:end] if start == 0 else PREFIX + word[start:end]
            if sub in vocab:
                piece = sub
                break
            end -= 1
        if piece is None:
            return [UNK]
        out.append(piece)
        start = end
    return out


def lin_max_match(word: str, t: Trie, stats: Optional[Dict[str, int]] = None) -> List[str]:
    """Algorithm 1 of Song et al.: the tokens of one word in one pass.

    If stats is a dict, it gets the number of goto steps ("goto") and of
    failure steps ("fail") of the pass.
    """
    if END in word:
        raise ValueError("the word must not contain the end mark")
    s = word + END  # @line L1
    u, tokens, i = t.root, [], 0  # @line L2
    goto = fail = 0
    stuck = False
    while i < len(s) and not stuck:  # @line L3
        while t.delta(u, s[i]) is None:  # @line L4
            if t.fail[u] is None:  # @line L5
                stuck = True
                break
            tokens.extend(t.pops[u])  # @line L6
            u = t.fail[u]  # @line L7
            fail += 1
        if not stuck:
            u, i = t.delta(u, s[i]), i + 1  # @line L8
            goto += 1
    if stats is not None:
        stats["goto"], stats["fail"] = goto, fail
    if i < len(word) or u not in (t.root, t.suffix_root):  # @line L9
        return [UNK]
    if u == t.suffix_root and not tokens:  # @line L10
        return max_match(PREFIX, t.vocab)
    return tokens  # @line L11


def tokenize(words: Sequence[str], vocab: Set[str]) -> List[str]:
    """Build the trie once and encode a list of words."""
    t = precompute(vocab)
    out: List[str] = []
    for w in words:
        out.extend(lin_max_match(w, t))
    return out


def failure_table(t: Trie) -> Dict[str, Tuple[List[str], Optional[str]]]:
    """Map each node string to (F(v), string of f(v)), for checks and display."""
    return {
        t.string[v]: (list(t.pops[v]), None if t.fail[v] is None else t.string[t.fail[v]])
        for v in range(len(t.children))
    }
test_fast_wordpiece_tokenization.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-wordpiece-tokenization/. The authors are listed in prov/PZXMS8.jsonl.

import random

import pytest

from fast_wordpiece_tokenization import (
    UNK,
    failure_table,
    lin_max_match,
    max_match,
    precompute,
    tokenize,
)

PAPER_VOCAB = {"a", "abcdx", "##b", "##c", "##cdy", "##dz"}


def brute_force_greedy(word, vocab):
    """Greedy longest match first, written as a search over all piece ends."""
    out, i = [], 0
    while i < len(word):
        ends = [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 ends:
            return [UNK]
        j = max(ends)
        out.append(word[i:j] if i == 0 else "##" + word[i:j])
        i = j
    return out


def test_failure_table_of_the_paper():
    table = failure_table(precompute(PAPER_VOCAB))
    expected = {
        "": ([], None),
        "#": ([], None),
        "##": ([], None),
        "a": (["a"], "##"),
        "ab": (["a"], "##b"),
        "abc": (["a", "##b"], "##c"),
        "abcd": (["a", "##b"], "##cd"),
        "abcdx": (["abcdx"], "##"),
        "##b": (["##b"], "##"),
        "##c": (["##c"], "##"),
        "##cd": (["##c"], "##d"),
        "##cdy": (["##cdy"], "##"),
        "##d": ([], None),
        "##dz": (["##dz"], "##"),
    }
    assert table == expected


def test_paper_examples():
    t = precompute(PAPER_VOCAB)
    stats = {}
    assert lin_max_match("abcdz", t, stats) == ["a", "##b", "##c", "##dz"]
    assert stats == {"goto": 5, "fail": 3}
    assert lin_max_match("abcz", t) == [UNK]
    assert lin_max_match("abcd", t) == [UNK]
    assert lin_max_match("abcdx", t) == ["abcdx"]
    assert lin_max_match("##bc", t) == ["##b", "##c"]
    assert lin_max_match("", t) == []


def test_bare_suffix_indicator_falls_back():
    t = precompute({"#", "a"})
    assert lin_max_match("##", t) == max_match("##", {"#", "a"}) == [UNK]
    t2 = precompute({"#", "###"})
    assert lin_max_match("##", t2) == max_match("##", {"#", "###"}) == ["#", "###"]


def test_bad_tokens_are_rejected():
    with pytest.raises(ValueError):
        precompute({"##"})
    with pytest.raises(ValueError):
        precompute({"a b"})
    with pytest.raises(ValueError):
        lin_max_match("a b", precompute({"a"}))


def test_against_brute_force_on_random_vocabularies():
    rng = random.Random(2021)
    for _ in range(400):
        vocab = {"".join(rng.choice("abc") for _ in range(rng.randint(1, 4))) for _ in range(rng.randint(1, 6))}
        vocab |= {"##" + "".join(rng.choice("abc") for _ in range(rng.randint(1, 4))) for _ in range(rng.randint(0, 7))}
        t = precompute(vocab)
        for _ in range(15):
            word = "".join(rng.choice("abc") for _ in range(rng.randint(1, 10)))
            assert lin_max_match(word, t) == brute_force_greedy(word, vocab)


def random_hash_vocab(rng):
    vocab = {"".join(rng.choice("ab#") for _ in range(rng.randint(1, 4))) for _ in range(6)}
    vocab |= {"##" + "".join(rng.choice("ab#") for _ in range(rng.randint(1, 3))) for _ in range(6)}
    vocab.discard("##")
    return vocab


def test_words_with_the_hash_character():
    # Words that do not start with ##: equal output for every vocabulary.
    rng = random.Random(5)
    for _ in range(300):
        vocab = random_hash_vocab(rng)
        t = precompute(vocab)
        for _ in range(10):
            word = "".join(rng.choice("ab#") for _ in range(rng.randint(1, 8)))
            if not word.startswith("##"):
                assert lin_max_match(word, t) == brute_force_greedy(word, vocab)


def test_words_that_start_with_the_prefix():
    # Words that start with ##: equal output when "#" is not a token.
    rng = random.Random(6)
    for _ in range(300):
        vocab = random_hash_vocab(rng)
        vocab.discard("#")
        t = precompute(vocab)
        for _ in range(10):
            word = "##" + "".join(rng.choice("ab#") for _ in range(rng.randint(0, 6)))
            assert lin_max_match(word, t) == brute_force_greedy(word, vocab)


def test_the_one_corner_case():
    # With "#" in V, a word that starts with ## can differ from the original encoder.
    vocab = {"#", "###c"}
    assert max_match("##c", vocab) == ["#", "###c"]
    assert lin_max_match("##c", precompute(vocab)) == [UNK]


def test_steps_are_linear():
    # The worst case of the original encoder: vocabulary {a, ##a, a^m b}.
    for m in (5, 20, 60):
        vocab = {"a", "##a", "a" * m + "b"}
        t = precompute(vocab)
        word = "a" * m
        stats = {}
        assert lin_max_match(word, t, stats) == ["a"] + ["##a"] * (m - 1)
        assert stats["goto"] + stats["fail"] <= 2 * len(word) + 2
    rng = random.Random(9)
    for _ in range(200):
        vocab = {"".join(rng.choice("ab") for _ in range(rng.randint(1, 6))) for _ in range(6)}
        vocab |= {"##" + "".join(rng.choice("ab") for _ in range(rng.randint(1, 6))) for _ in range(8)}
        t = precompute(vocab)
        word = "".join(rng.choice("ab") for _ in range(rng.randint(1, 30)))
        stats = {}
        lin_max_match(word, t, stats)
        assert stats["goto"] <= len(word)
        assert stats["fail"] <= stats["goto"] + 1


def test_tokenize_many_words():
    assert tokenize(["abcdz", "abcz", "a"], PAPER_VOCAB) == ["a", "##b", "##c", "##dz", UNK, "a"]

History

Greedy longest match first came with WordPiece in BERT, where each position costs a series of dictionary lookups. Song et al. (2021) observed that the failure links of Aho and Corasick (1975) carry over if each link also carries the tokens to emit, and called the result LinMaxMatch. Their end-to-end version folds the pre-tokenization into the same pass.

References

  1. Xinying Song, Alex Salcianu, Yang Song, Dave Dopson and Denny Zhou, Fast WordPiece tokenization, EMNLP 2021, pages 2089 to 2103, Section 3 (Definition 1, Algorithms 1 and 2, the example of Figure 1 and Table 2, the complexity in Section 3.5), Section 4 (end-to-end WordPiece), Section 5 (setup and Table 3, page 2097)
  2. Alfred V. Aho and Margaret J. Corasick, Efficient string matching, an aid to bibliographic search, Communications of the ACM 18(6) (1975), 333-340, Algorithms 2 and 3 (the goto and failure functions)
  3. Google Research, BERT reference code, tokenization.py, class WordpieceTokenizer (the original greedy longest-match-first encoder)

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/PZXMS8/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
  • a scene preset for the example