Algorithm Search⌘K

Algorithmadvanced

Byte-level BPE

Also called byte-level byte-pair encoding.

Byte-pair encoding run on the UTF-8 bytes of a text instead of its characters, so the base vocabulary has 256 symbols and no input is out of vocabulary.

Time
O(n b) encodeO(n) recoverO(K L) train
Space
O(L + K) trainO(V) vocabulary
Where
K = the number of merges; L = the total length of the distinct training pre-tokens in bytes; V = the vocabulary size (256 + K); b = the length of its longest pre-token in bytes; n = the length of the text to encode in bytes
Properties
deterministicnot exactofflineiterative
Origin
Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, Ilya Sutskever, 2019

Byte-level BPE is byte-pair encoding applied to the UTF-8 bytes of a text, not to its characters. The base vocabulary is the 256 byte values, so every string has an encoding and no token is ever unknown. GPT-2 made the method common, with a pre-tokenizer that keeps merges inside runs of letters, of digits or of other symbols. Because a token can stop in the middle of a character, a model can emit byte sequences that are not valid UTF-8, and Wang, Cho and Gu (2020) give a small dynamic program that recovers as many characters as possible.

In plain words

Computers store text as bytes, and there are only 256 different bytes. A letter such as "a" is one byte, while a Japanese character or an emoji takes three or four.

Byte-level BPE starts from these 256 bytes as its pieces. It then counts which two neighboring pieces appear together most often in a training text, glues them into a new piece, and repeats. Common words soon become single pieces. A rare character still has its bytes, so nothing is ever unknown.

Before counting, the text is cut into chunks such as a word with the space in front of it, a number, or a run of punctuation. Gluing never crosses a chunk border. A piece can hold only part of a character, so a model that writes pieces can write broken text, and a short repair step keeps all the characters that are still whole.

The problem

Training: given texts and a number of merges KK, learn a merge list of length at most KK. Encoding: given a text and the merge list, return a list of tokens whose bytes join to the UTF-8 code of the text. Decoding: join the bytes of a token list and read them as UTF-8. Recovery: given any byte string, find the largest number of whole characters that can be read from it. The vocabulary has V=256+KV = 256 + K tokens; GPT-2 used 50,257, which is 256 bytes, 50,000 merges and one end-of-text token.

The pre-tokenizer of GPT-2 is the regular expression 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+. It splits off English contractions, then takes an optional space with a run of letters, of digits or of other symbols, and runs of whitespace; a run of spaces before a word gives its last space to the word. Every merge stays inside one pre-token.

The algorithm

Training is BPE on bytes:

  1. BBPE-TRAIN(texts, K)
  2. 1C ← counts of the pre-tokens of all texts
  3. 2for each pre-token x in C do S[x] ← the list of the UTF-8 bytes of x
  4. 3merges ← empty list
  5. 4repeat K times
  6. 5P ← counts of adjacent pairs over all S[x], weighted by C(x)
  7. 6if P is empty then stop
  8. 7(a, b) ← the pair with the largest count, ties to the smallest pair
  9. 8in every S[x], replace each occurrence of a b, from the left, by ab
  10. 9append (a, b) to merges
  11. 10return merges

Encoding follows the GPT-2 code: inside each pre-token, merge the pair of lowest rank until no pair has a rank.

  1. BBPE-ENCODE(text, merges)
  2. E1 rank(a, b) ← the position of (a, b) in merges
  3. E2 out ← empty list
  4. E3 for each pre-token x of text do
  5. E4 u ← the list of the UTF-8 bytes of x
  6. E5 while some adjacent pair of u has a rank do
  7. E6 (a, b) ← the adjacent pair of lowest rank
  8. E7 replace each occurrence of a b in u, from the left, by ab
  9. E8 append the tokens of u to out
  10. E9 return out

Decoding joins the bytes and reads them as UTF-8, with a replacement character for each bad part. Recovery is the program of Wang, Cho and Gu, in the (max⁡,+)(\max, +) semiring. For bytes d1⋯dnd_1 \cdots d_n, g(i,j)=1g(i, j) = 1 if di⋯djd_i \cdots d_j is the code of one character and 0 otherwise, and f(k)f(k) is the most characters that the first kk bytes can give:

  1. RECOVER(d1 ... dn)
  2. R1 f(0) ← 0
  3. R2 for k ← 1 to n do
  4. R3 f(k) ← max over t = 1 .. min(4, k) of f(k - t) + g(k - t + 1, k)
  5. R4 back(k) ← a t that gives this maximum
  6. R5 walk back from n by back(k) and keep the chunks with g = 1

This is a longest path in a DAG whose nodes are the byte positions 0 to nn and whose edges span 1 to 4 bytes. Byte positions use fencepost spans: d[i..j)d[i..j) holds the bytes i+1i + 1 to jj.

Example

Train on the text "日本 日本 日日". The pre-tokens are "日本", " 日本" and " 日日", once each. In UTF-8, 日 is E6 97 A5, 本 is E6 9C AC, and the space is 20. The first counts of adjacent pairs:

pair count
97 A5 4
E6 97 4
A5 E6 3
20 E6 2
9C AC 2
E6 9C 2

The first two tie, and 97 A5 wins by byte order. It becomes token 256, which is two continuation bytes and not valid UTF-8 by itself. The next merges are E6 with 97 A5, which gives token 257 = 日, then 20 with 日, which gives 258 = " 日", then 9C AC as 259, and E6 with 9C AC, which gives 260 = 本. Three more merges join each pre-token into a single token, and then no pair is left.

With the first five merges, " 日本語" is one pre-token. It encodes as 258, 260, 232, 170, 158: " 日", 本, and the three bytes E8 AA 9E of 語, which never occurred in training. Nothing is unknown, and decoding gives the text back.

If a model emits token 256 and then token 257, the bytes 97 A5 E6 97 A5 decode to two replacement characters followed by 日, and RECOVER keeps the one character 日. The bytes E6 97 E6 97 A5 61 A5 C3 A9 give 3 characters, 日, a and é: the incomplete E6 97 and the stray A5 are dropped.

Correctness

The pre-tokens join to the text, a merge never changes the bytes, and every byte has a token, so decoding an encoding always gives the original text back; this is a theorem for every string. Training merges, at each step, a pair of largest count, which is a heuristic for a short encoding, not an optimum. RECOVER is correct by the usual argument for a longest path: the last chunk of a best split of the first kk bytes has 1 to 4 bytes, and the rest is a best split of a shorter prefix. The proofs are in proofs/correctness.md.

Encoding by lowest rank first is the rule of the GPT-2 code. It is not proved here that it gives the same tokens as replaying the merges in their order: for the hand-made list (x,ab)(x, ab), (a,b)(a, b) and the text xabxab the two differ. On merge lists made by training, the tests found no difference.

Proof: Byte-level BPE encodes every string without loss, and the recovery program keeps the most charactersfull

Notation. A text tt is a string of Unicode scalar values, and utf8(t)\mathrm{utf8}(t) is its UTF-8 byte string. A token is a nonempty byte string. A merge list is a sequence of pairs (a,b)(a, b) of tokens. Spans are fencepost spans: x[i..j)x[i..j) holds the elements i+1i + 1 to jj.

Lemma 1 (pre-tokens cover the text). PRETOKENIZE(tt) returns strings x1,…,xqx_1, \ldots, x_q with x1x2⋯xq=tx_1 x_2 \cdots x_q = t.

Proof. Each pass of the scanner starts at position ii, appends t[i..j)t[i..j) for some j>ij > i, and sets i←ji \leftarrow j. In the contraction branch j=i+∣c∣>ij = i + |c| > i. In the letter, digit and symbol branches the run starts at k≥ik \ge i and holds t[k]t[k], so j≥k+1>ij \ge k + 1 > i. In the whitespace branch the run has length at least 1, and it is shortened by one only when its length is at least 2. So the appended pieces are consecutive, they do not overlap, and the scan ends at i=∣t∣i = |t|. □\square

Lemma 2 (merges keep the bytes). For any list of tokens uu and any pair (a,b)(a, b), the concatenation of MERGE(uu, aa, bb) equals the concatenation of uu.

Proof. MERGE copies each token of uu in order, except that it writes two adjacent tokens aa, bb as the one token aba b, which is the same byte string. □\square

Theorem 1 (lossless, with no unknown token). For every text tt and every merge list, every token of BBPE-ENCODE(tt) has an id, and DECODE(BBPE-ENCODE(tt)) =t= t.

Proof. Line E4 starts each pre-token as its single bytes, and each of the 256 byte values has an id. Line E7 creates only tokens aba b for pairs with a rank, which are merges and have ids. By Lemma 2 the tokens of one pre-token join to utf8(x)\mathrm{utf8}(x), and UTF-8 maps a concatenation of strings to the concatenation of their byte strings, so by Lemma 1 all tokens join to utf8(x1)⋯utf8(xq)=utf8(t)\mathrm{utf8}(x_1) \cdots \mathrm{utf8}(x_q) = \mathrm{utf8}(t). This is valid UTF-8, so decoding gives tt and no replacement character appears. The loop of lines E5 to E7 stops, because each pass replaces at least one pair and so shortens uu. □\square

Theorem 2 (training). BBPE-TRAIN stops after at most KK passes, and in each pass it merges a pair of largest count, counting non-overlapping occurrences from the left and weighting each pre-token by its count. Among pairs of equal count it takes the smallest by byte order.

Proof. Line L4 bounds the passes and line L6 can stop earlier. Line L5 counts the pairs of the current segmentation, and line L7 takes the largest count with ties to the smallest pair. Line L8 applies the merge to every pre-token, so the next count is taken on the segmentation that results. □\square

Nothing here says that the merge list is the best of its length: choosing the most frequent pair is a heuristic. Nor does anything here prove that merging the pair of lowest rank first (line E6) gives the same tokens as replaying every merge in order. For the hand-made list [(x,ab),(a,b)][(x, ab), (a, b)] and the text xabxab the two differ: replay gives xx, abab, and lowest rank first gives xabxab. On lists made by BBPE-TRAIN the tests found no difference.

Theorem 3 (recovery). For a byte string dd of length nn, call a partition a split of dd into consecutive chunks of 1 to 4 bytes, and let g(i,j)=1g(i, j) = 1 if d[i−1..j)d[i - 1..j) is the UTF-8 code of one character and 0 otherwise. Then RECOVER returns the largest number of chunks with g=1g = 1 over all partitions of dd, and a partition that reaches it.

Proof. Let OPT(k)\mathrm{OPT}(k) be that largest number for the prefix d[0..k)d[0..k), with OPT(0)=0\mathrm{OPT}(0) = 0. The last chunk of a partition of d[0..k)d[0..k) is d[k−t..k)d[k - t..k) for some t∈{1,2,3,4}t \in \{1, 2, 3, 4\} with t≤kt \le k, and the rest is a partition of d[0..k−t)d[0..k - t). So OPT(k)=max⁡tOPT(k−t)+g(k−t+1,k)\mathrm{OPT}(k) = \max_t \mathrm{OPT}(k - t) + g(k - t + 1, k). This is the recurrence of line R3, computed in the (max⁡,+)(\max, +) semiring, and line R1 sets the base case. By induction on kk, f(k)=OPT(k)f(k) = \mathrm{OPT}(k). Line R4 stores a tt that reaches the maximum, so the walk of line R5 follows a partition whose score is f(n)f(n), and it keeps the chunks with g=1g = 1. ■\blacksquare

Wang, Cho and Gu state that the design of UTF-8 makes the recovered characters unique. The tests check, by enumerating all partitions of short byte strings, that every best partition keeps the same characters.

Complexity

  • Training. In the word-RAM model with a hash table for the counts, one pass over the distinct pre-tokens counts the pairs and another applies the merge, so a step costs O(L)O(L) and KK steps cost O(KL)O(K L). Implementations that update only the counts near each merge are much faster in practice.
  • Encoding. A pre-token of b′b' bytes needs at most b′−1b' - 1 rounds of lines E5 to E7, each O(b′)O(b'), so a text of nn bytes costs O(nb)O(n b). A priority queue of the pairs brings one pre-token to O(b′log⁡b′)O(b' \log b').
  • Recovery. Each position tries 4 chunks of at most 4 bytes, so RECOVER costs O(n)O(n) time and space.

Properties

  • No unknown token. This is the main point of the method, and it holds for any Unicode string, including emoji and unseen scripts.
  • A small base. The base has 256 symbols. A character-level BPE that covers all of Unicode would need a base of over 130,000 symbols, as the GPT-2 report notes.
  • Longer sequences for rare scripts. A text in a script that the merges do not cover comes out as raw bytes, up to 4 tokens per character. Wang, Cho and Gu note that a byte sequence can be up to 4 times longer than the character sequence.
  • Tokens need not be text. A token can be part of a character, as token 256 in the example. Tools that show tokens use the GPT-2 map from bytes to 256 printable characters, which writes a space as Ġ.

Variants and improvements

  • Merge rules. GPT-2 stops merges across character categories, with an exception for spaces, because plain BPE on bytes learned many versions of words such as dog. Other systems use other pre-tokenization patterns, and each pattern gives a different vocabulary.
  • Byte-level BPE for translation. Wang, Cho and Gu (2020) used byte-level vocabularies of 2K to 32K tokens and the recovery step for decoding.
  • Regularization. BPE-dropout skips merges at random while the model trains, and it applies to byte merges in the same way.
  • Other subword models. WordPiece and unigram language model tokenization start from characters, so they need an unknown token or a byte fallback for unseen characters.

When to use it

Use it when the input can be any text, such as web pages, code, or many languages, and an unknown token is not acceptable. It suits generative models such as a generative pretrained transformer, which must write any string. If the text is in a few known scripts and sequence length matters more, a character-level vocabulary can be shorter per character for those scripts.

Pitfalls

  • Decoding single tokens. Decoding a stream token by token can split a character, and each half becomes a replacement character. Buffer the bytes until a character is complete.
  • The pre-tokenizer is part of the model. A different pattern, or a regex engine without \p{L}, gives other pre-tokens and other tokens than the trained model expects.
  • Merges can be wasted on bytes. Without the pre-tokenizer, merges join words with punctuation and spaces in many variants.
  • Ties. The merge order depends on how ties are broken. Reproduce a vocabulary only with the same rule.

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.

byte_level_bpe.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/byte-level-bpe/. The authors are listed in prov/HZ50C6.jsonl.

"""Byte-level byte-pair encoding, in the style of GPT-2.

The text is first split into pre-tokens by a scanner that follows the GPT-2
pattern (contractions, an optional space and a run of letters, of digits or
of other symbols, and runs of whitespace). Each pre-token becomes the list of
its UTF-8 bytes, and BPE merges are learned and applied on those bytes. Any
string has an encoding, so there is no unknown token.

recover is the dynamic program of Wang, Cho and Gu (2020) that keeps as many
characters as possible from a byte sequence that is not valid UTF-8.
"""

import unicodedata
from typing import Dict, List, Sequence, Tuple

Pair = Tuple[bytes, bytes]
CONTRACTIONS = ("'s", "'t", "'re", "'ve", "'m", "'ll", "'d")


def bytes_to_unicode() -> Dict[int, str]:
    """The GPT-2 map from the 256 byte values to printable characters."""
    keep = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
    codes = keep[:]
    extra = 0
    for b in range(256):
        if b not in keep:
            keep.append(b)
            codes.append(256 + extra)
            extra += 1
    return {b: chr(c) for b, c in zip(keep, codes)}


BYTE_CHAR = bytes_to_unicode()


def show(token: bytes) -> str:
    """Print a token as GPT-2 does, for example b" world" as "Ġworld"."""
    return "".join(BYTE_CHAR[b] for b in token)


def _kind(ch: str) -> str:
    if ch.isspace():
        return "S"
    cat = unicodedata.category(ch)
    if cat[0] == "L":
        return "L"
    if cat[0] == "N":
        return "N"
    return "O"


def pretokenize(text: str) -> List[str]:
    """Split text like the GPT-2 pattern
    's|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+
    """
    out, i, n = [], 0, len(text)
    while i < n:
        hit = next((c for c in CONTRACTIONS if text.startswith(c, i)), None)
        if hit is not None:
            out.append(hit)
            i += len(hit)
            continue
        k = i + 1 if text[i] == " " and i + 1 < n else i
        kind = _kind(text[k])
        if kind != "S":
            j = k
            while j < n and _kind(text[j]) == kind:
                j += 1
            out.append(text[i:j])
            i = j
            continue
        j = i
        while j < n and text[j].isspace():
            j += 1
        if j < n and j - i >= 2:
            j -= 1  # leave the last space for the next word
        out.append(text[i:j])
        i = j
    return out


def _merge(units: Sequence[bytes], a: bytes, b: bytes) -> List[bytes]:
    out, i = [], 0
    while i < len(units):
        if i + 1 < len(units) and units[i] == a and units[i + 1] == b:
            out.append(a + b)
            i += 2
        else:
            out.append(units[i])
            i += 1
    return out


def _count_pair(units: Sequence[bytes], a: bytes, b: bytes) -> int:
    k, i = 0, 0
    while i + 1 < len(units):
        if units[i] == a and units[i + 1] == b:
            k += 1
            i += 2
        else:
            i += 1
    return k


def pair_counts(seg: Dict[str, List[bytes]], freq: Dict[str, int]) -> Dict[Pair, int]:
    """Non-overlapping occurrences of each adjacent pair, weighted by the counts."""
    pairs = set()
    for units in seg.values():
        pairs.update(zip(units, units[1:]))
    out = {}
    for a, b in pairs:
        k = sum(freq[x] * _count_pair(u, a, b) for x, u in seg.items())
        if k:
            out[(a, b)] = k
    return out


def train(texts: Sequence[str], merges: int) -> List[Pair]:
    """Learn up to `merges` byte-pair merges from a list of texts."""
    freq: Dict[str, int] = {}
    for text in texts:  # @line L1
        for x in pretokenize(text):
            freq[x] = freq.get(x, 0) + 1
    seg = {x: [bytes([b]) for b in x.encode("utf-8")] for x in freq}  # @line L2
    done: List[Pair] = []  # @line L3
    for _ in range(merges):  # @line L4
        p = pair_counts(seg, freq)  # @line L5
        if not p:  # @line L6
            break
        a, b = min(p, key=lambda pr: (-p[pr], pr))  # @line L7
        seg = {x: _merge(u, a, b) for x, u in seg.items()}  # @line L8
        done.append((a, b))  # @line L9
    return done  # @line L10


def encode(text: str, merges: Sequence[Pair]) -> List[bytes]:
    """Encode text into byte tokens by applying the merge of lowest rank first."""
    rank = {pr: r for r, pr in enumerate(merges)}  # @line E1
    out: List[bytes] = []  # @line E2
    for x in pretokenize(text):  # @line E3
        u = [bytes([b]) for b in x.encode("utf-8")]  # @line E4
        while any(pr in rank for pr in zip(u, u[1:])):  # @line E5
            a, b = min((pr for pr in zip(u, u[1:]) if pr in rank), key=rank.__getitem__)  # @line E6
            u = _merge(u, a, b)  # @line E7
        out.extend(u)  # @line E8
    return out  # @line E9


def replay(text: str, merges: Sequence[Pair]) -> List[bytes]:
    """Apply every merge in the order learned, to each pre-token."""
    out: List[bytes] = []
    for x in pretokenize(text):
        u = [bytes([b]) for b in x.encode("utf-8")]
        for a, b in merges:
            u = _merge(u, a, b)
        out.extend(u)
    return out


def token_ids(tokens: Sequence[bytes], merges: Sequence[Pair]) -> List[int]:
    """Byte b has id b, and the k-th merge (from 0) has id 256 + k."""
    ids = {bytes([b]): b for b in range(256)}
    for k, (a, b) in enumerate(merges):
        ids.setdefault(a + b, 256 + k)
    return [ids[t] for t in tokens]


def decode(tokens: Sequence[bytes]) -> str:
    """Join the bytes and decode them; bad UTF-8 becomes U+FFFD."""
    return b"".join(tokens).decode("utf-8", errors="replace")


def is_char(chunk: bytes) -> bool:
    """g(i, j) of Wang et al.: 1 if the bytes are one valid UTF-8 character."""
    try:
        return len(chunk.decode("utf-8")) == 1
    except UnicodeDecodeError:
        return False


def recover(data: bytes) -> Tuple[int, str]:
    """Keep the most characters from data; return (count, characters kept).

    The program works in the (max, +) semiring over chunks of 1 to 4 bytes.
    """
    n = len(data)
    f = [0] * (n + 1)  # @line R1
    back = [0] * (n + 1)
    for k in range(1, n + 1):  # @line R2
        best, arg = -1, 0
        for t in range(1, min(4, k) + 1):  # @line R3
            v = f[k - t] + is_char(data[k - t:k])
            if v > best:
                best, arg = v, t
        f[k], back[k] = best, arg  # @line R4
    kept, k = [], n  # @line R5
    while k > 0:
        t = back[k]
        if is_char(data[k - t:k]):
            kept.append(data[k - t:k].decode("utf-8"))
        k -= t
    return f[n], "".join(reversed(kept))
test_byte_level_bpe.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/byte-level-bpe/. The authors are listed in prov/HZ50C6.jsonl.

import itertools
import random

from byte_level_bpe import (
    BYTE_CHAR,
    decode,
    encode,
    is_char,
    pair_counts,
    pretokenize,
    recover,
    replay,
    show,
    token_ids,
    train,
)

CORPUS = ["日本 日本 日日"]


def random_text(rng, n):
    pool = "ab c\n'!7é日本語😀 x"
    return "".join(rng.choice(pool) for _ in range(n))


def test_byte_map():
    assert len(BYTE_CHAR) == 256 and len(set(BYTE_CHAR.values())) == 256
    assert all(not ch.isspace() and ch.isprintable() for ch in BYTE_CHAR.values())
    assert show(b" world") == "Ġworld"
    assert BYTE_CHAR[ord("A")] == "A"


def test_pretokenizer_examples():
    assert pretokenize("Hello world") == ["Hello", " world"]
    assert pretokenize("I've  got 42 apples!\n") == ["I", "'ve", " ", " got", " 42", " apples", "!", "\n"]
    assert pretokenize("a\n\nb") == ["a", "\n", "\n", "b"]
    assert pretokenize("don't stop") == ["don", "'t", " stop"]
    assert pretokenize(" 日本語x²") == [" 日本語x", "²"]
    assert pretokenize("ab  ") == ["ab", "  "]


def test_pretokens_cover_the_text():
    rng = random.Random(1)
    for _ in range(300):
        t = random_text(rng, rng.randint(0, 20))
        assert "".join(pretokenize(t)) == t


def test_page_example():
    assert len(train(CORPUS, 100)) == 8
    merges = train(CORPUS, 5)
    assert merges == [
        (b"\x97", b"\xa5"),
        (b"\xe6", b"\x97\xa5"),
        (b" ", "日".encode()),
        (b"\x9c", b"\xac"),
        (b"\xe6", b"\x9c\xac"),
    ]
    toks = encode(" 日本語", merges)
    assert toks == [" 日".encode(), "本".encode(), b"\xe8", b"\xaa", b"\x9e"]
    assert token_ids(toks, merges) == [258, 260, 232, 170, 158]
    assert not is_char(b"\x97\xa5")
    seg = {x: [bytes([b]) for b in x.encode()] for x in ["日本", " 日本", " 日日"]}
    p = pair_counts(seg, {"日本": 1, " 日本": 1, " 日日": 1})
    assert p[(b"\x97", b"\xa5")] == 4 and p[(b"\xe6", b"\x97")] == 4 and p[(b"\xa5", b"\xe6")] == 3


def test_round_trip_and_no_unknown():
    rng = random.Random(2)
    corpus = [random_text(rng, 40) for _ in range(5)]
    merges = train(corpus, 30)
    for _ in range(300):
        t = random_text(rng, rng.randint(0, 25))
        toks = encode(t, merges)
        assert decode(toks) == t
        assert all(0 <= i < 256 + len(merges) for i in token_ids(toks, merges))


def test_rank_order_equals_replay():
    rng = random.Random(3)
    for _ in range(20):
        corpus = [random_text(rng, 30) for _ in range(4)]
        merges = train(corpus, 25)
        for _ in range(20):
            t = random_text(rng, rng.randint(0, 20))
            assert encode(t, merges) == replay(t, merges)


def test_rank_order_can_differ_on_a_hand_made_list():
    merges = [(b"x", b"ab"), (b"a", b"b")]
    assert replay("xab", merges) == [b"x", b"ab"]
    assert encode("xab", merges) == [b"xab"]


def test_training_takes_the_most_frequent_pair():
    rng = random.Random(4)
    corpus = [random_text(rng, 30) for _ in range(3)]
    merges = train(corpus, 10)
    for k in range(1, len(merges) + 1):
        seen = merges[: k - 1]
        freq = {}
        for t in corpus:
            for x in pretokenize(t):
                freq[x] = freq.get(x, 0) + 1
        seg = {x: replay(x, seen) for x in freq}
        p = pair_counts(seg, freq)
        assert p[merges[k - 1]] == max(p.values())


def brute_force_recover(data):
    best = (0, set())
    n = len(data)
    for cuts in itertools.product([0, 1], repeat=max(n - 1, 0)):
        chunks, start = [], 0
        for i, c in enumerate(cuts, start=1):
            if c:
                chunks.append(data[start:i])
                start = i
        chunks.append(data[start:])
        if n == 0 or any(len(ch) > 4 for ch in chunks):
            continue
        good = [ch for ch in chunks if is_char(ch)]
        text = "".join(ch.decode("utf-8") for ch in good)
        if len(good) > best[0]:
            best = (len(good), {text})
        elif len(good) == best[0]:
            best[1].add(text)
    return best


def test_recover_against_brute_force():
    rng = random.Random(5)
    pieces = [b"a", b"\xc3\xa9", "日".encode(), "😀".encode(), b"\x97", b"\xa5", b"\xe6", b"\xf0\x9f", b"\xff"]
    for _ in range(300):
        data = b"".join(rng.choice(pieces) for _ in range(rng.randint(1, 5)))[:11]
        count, text = recover(data)
        best_count, texts = brute_force_recover(data)
        assert count == best_count
        assert texts == {text} or (best_count == 0 and text == "")


def test_recover_example():
    data = b"\x97\xa5" + "日".encode()
    assert recover(data) == (1, "日")
    assert decode([b"\x97\xa5", "日".encode()]) == "��日"
    assert recover(b"\xe6\x97\xe6\x97\xa5a\xa5\xc3\xa9") == (3, "日aé")
    assert recover(b"") == (0, "")

History

Sennrich, Haddow and Birch (2016) brought byte-pair encoding to neural machine translation, with characters as the base symbols. Radford et al. (2019) moved the base to bytes for GPT-2, so that the model could assign a probability to any Unicode string, and added the rule against merges across character categories. Wang, Cho and Gu (2020) called the method BBPE, tested it in translation, and gave the recovery program for invalid output.

References

  1. Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei and Ilya Sutskever, Language models are unsupervised multitask learners, OpenAI technical report, 2019, Section 2.2, Input Representation (a base vocabulary of 256, no merges across character categories except for spaces), and Section 2.3 (a vocabulary of 50,257)
  2. OpenAI, GPT-2 reference code, encoder.py, bytes_to_unicode, the pre-tokenization pattern, and Encoder.bpe (merge the pair of lowest rank first)
  3. Changhan Wang, Kyunghyun Cho and Jiatao Gu, Neural machine translation with byte-level subwords, AAAI 2020, volume 34(05), pages 9154 to 9160, the sections Encoding Byte-Level Representation and Decoding with Byte-Level Subwords (Equation 1, the recovery program)
  4. Rico Sennrich, Barry Haddow and Alexandra Birch, Neural machine translation of rare words with subword units, ACL 2016, the section on byte pair encoding (the merge learning algorithm over characters)

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
  • a full proof of time.recover
  • 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