TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Byte-Pair Encoding from Scratch

Byte-Pair Encoding from Scratch

Why Subword Tokenizers measured the trade-off: frequent words should be single tokens, rare words should split into frequent pieces, and nothing should ever be unknown. Byte-pair encoding (BPE) gets there with one greedy rule, applied thousands of times: merge the most frequent adjacent pair of symbols. It began as a compression algorithm (Gage 1994), was adapted to subword units for machine translation by Sennrich, Haddow and Birch (2016), and in its byte-level form (GPT-2, 2019) it is the tokenizer of GPT-2, GPT-3, GPT-4, Llama 3 and many other LLMs.

Tokens & Tokenization showed the idea on a toy corpus, and Tokenization and Byte-Pair Encoding stated the algorithm. Here you write a complete trainer and encoder, compact enough to reuse (the lesson Pretraining a Tiny GPT trains a model on a tokenizer built with these functions), extend it to bytes, and check it token for token against GPT-2's real tokenizer.

The algorithm

Training. Start from a word-frequency table, each word split into characters. Repeat MM times:

  1. Count every adjacent pair of symbols, weighted by word frequency: count⁡(a,b)=∑wc(w)⋅#{(a,b) adjacent in w}\operatorname{count}(a, b) = \sum_{w} c(w) \cdot \#\{(a, b) \text{ adjacent in } w\}.
  2. Take the most frequent pair (a∗,b∗)=arg⁡max⁡(a,b)count⁡(a,b)(a^\ast, b^\ast) = \arg\max_{(a, b)} \operatorname{count}(a, b), add the new symbol a∗b∗a^\ast b^\ast to the vocabulary, and record the merge.
  3. Replace every adjacent occurrence of (a∗,b∗)(a^\ast, b^\ast) in the table by a∗b∗a^\ast b^\ast.

The vocabulary ends with ∣base∣+M\lvert \text{base} \rvert + M symbols, and the output of training is the ordered list of merges. MM is the one hyperparameter: GPT-2 used 50,000 merges on top of 256 byte symbols.

Encoding a new word replays the training: split it into characters and, while some adjacent pair appears in the merge list, apply the merge with the lowest rank (the earliest learned). Ranks matter: applying merges in another order gives other tokens.

Two details keep it well defined. Merges never cross word boundaries, because the text is pre-tokenised into words first. And the boundary itself has to be visible, or "s" at the end of "spokes" and "s" at the start of "stroke" are the same symbol. Sennrich's version appended an end-of-word marker </w>; GPT-2 attaches the space in front of a word to the word (Ġbike). The code below follows GPT-2 and writes that space as _.

Training on six words

python · try it yourself
from collections import Counter

def merge_pair(symbols, pair):
    out, i = [], 0
    while i < len(symbols):
        if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
            out.append(symbols[i] + symbols[i + 1])
            i += 2
        else:
            out.append(symbols[i])
            i += 1
    return tuple(out)

def train_bpe(words, num_merges):
    """words: {word: count}. Returns the merges (pairs of symbols) in the order they were learned."""
    table = {tuple(w): c for w, c in words.items()}            # each word starts as its characters
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for symbols, c in table.items():
            for p in zip(symbols, symbols[1:]):
                pairs[p] += c
        if not pairs:
            break
        best = max(pairs, key=lambda p: (pairs[p], p))         # most frequent; ties: larger pair
        merges.append(best)
        table = {merge_pair(s, best): c for s, c in table.items()}
    return merges

def encode(word, merges):
    """Split a word into characters, then apply the learned merges in rank order."""
    rank = {p: i for i, p in enumerate(merges)}
    symbols = tuple(word)
    while len(symbols) > 1:
        candidates = [p for p in zip(symbols, symbols[1:]) if p in rank]
        if not candidates:
            break
        symbols = merge_pair(symbols, min(candidates, key=rank.get))
    return list(symbols)

# word frequencies; "_" marks the space in front of a word, as GPT-2's "Ġ" does
words = {"_spoke": 9, "_spokes": 5, "_poke": 2, "_stroke": 4, "_strokes": 3, "_smoke": 3}
table = {tuple(w): c for w, c in words.items()}
for step, pair in enumerate(train_bpe(words, 8), 1):
    pairs = Counter()
    for s, c in table.items():
        for p in zip(s, s[1:]):
            pairs[p] += c
    table = {merge_pair(s, pair): c for s, c in table.items()}
    print(f"merge {step}: {pair[0]!r} + {pair[1]!r} (count {pairs[pair]:2d}) ->", " ".join("|".join(s) for s in table))

merges = train_bpe(words, 8)
for w in ["_spoke", "_strokes", "_pokes", "_stoke", "_jokes"]:
    print(f"{w:9s} -> {encode(w, merges)}")
merge 1: 'o' + 'k' (count 26) -> _|s|p|ok|e _|s|p|ok|e|s _|p|ok|e _|s|t|r|ok|e _|s|t|r|ok|e|s _|s|m|ok|e
merge 2: 'ok' + 'e' (count 26) -> _|s|p|oke _|s|p|oke|s _|p|oke _|s|t|r|oke _|s|t|r|oke|s _|s|m|oke
merge 3: '_' + 's' (count 24) -> _s|p|oke _s|p|oke|s _|p|oke _s|t|r|oke _s|t|r|oke|s _s|m|oke
merge 4: 'p' + 'oke' (count 16) -> _s|poke _s|poke|s _|poke _s|t|r|oke _s|t|r|oke|s _s|m|oke
merge 5: '_s' + 'poke' (count 14) -> _spoke _spoke|s _|poke _s|t|r|oke _s|t|r|oke|s _s|m|oke
merge 6: 't' + 'r' (count  7) -> _spoke _spoke|s _|poke _s|tr|oke _s|tr|oke|s _s|m|oke
merge 7: 'tr' + 'oke' (count  7) -> _spoke _spoke|s _|poke _s|troke _s|troke|s _s|m|oke
merge 8: '_s' + 'troke' (count  7) -> _spoke _spoke|s _|poke _stroke _stroke|s _s|m|oke
_spoke    -> ['_spoke']
_strokes  -> ['_stroke', 's']
_pokes    -> ['_', 'poke', 's']
_stoke    -> ['_s', 't', 'oke']
_jokes    -> ['_', 'j', 'oke', 's']
after _spoke (x9) _strokes (x3) _smoke (x3) start: characters _ s p o k e _ s t r o k e s _ s m o k e merge 2: ok + e _ s p oke _ s t r oke s _ s m oke merge 5: _s + poke _spoke _s t r oke s _s m oke merge 8: _s + troke _spoke _stroke s _s m oke

Read the log line by line. "o" + "k" is the most frequent pair (26: it occurs once in every one of the 26 word occurrences), then "ok" + "e". The third merge, "_" + "s", is the start of a word that begins with s. After merge 5 the most frequent word, "_spoke", is a single token, and after merge 8 so is "_stroke". "_smoke" (3 occurrences) never got its own merges and stays _s m oke. At step 6 three pairs tie with count 7 (t r, r oke, _s t); train_bpe breaks ties by taking the larger pair in Python's tuple order, a detail that real implementations decide differently. Ties are why two BPE implementations trained on the same data can disagree.

Encoding new words applies the same merges in rank order. "_pokes" becomes _ poke s: the merge _s + poke cannot apply because there is no "_s" here. "_stoke" reuses the pieces _s and oke. "_jokes" contains "j", which never occurred in training: a character-level BPE has no symbol for it. Real character-level tokenizers map it to [UNK], and the byte-level version below removes the problem.

The code to keep

These three functions are all of BPE. The table table maps a word (as a tuple of current symbols) to its count, so each merge step costs one pass over the distinct words, not over the whole corpus.

Function Input Output
train_bpe(words, num_merges) {word: count}, each word a string whose characters are the base symbols the merges, a list of (a, b) pairs in learned order
encode(word, merges) one pre-tokenised word its list of tokens
merge_pair(symbols, pair) a tuple of symbols and one merge the tuple with every occurrence of the pair merged

Production trainers (Hugging Face tokenizers, SentencePiece) are the same algorithm with incremental bookkeeping: they keep the pair counts and an index from pairs to the words that contain them, and update only the words touched by each merge. That makes training on gigabytes of text a matter of minutes instead of hours.

On real text: vocabulary size against sequence length

The next example pre-tokenises the repair-shop text of the previous lesson into words with their leading space and punctuation, trains with different numbers of merges and encodes the held-out paragraph.

python · try it yourself
import re
from collections import Counter

def merge_pair(symbols, pair):
    out, i = [], 0
    while i < len(symbols):
        if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
            out.append(symbols[i] + symbols[i + 1])
            i += 2
        else:
            out.append(symbols[i])
            i += 1
    return tuple(out)

def train_bpe(words, num_merges):
    """words: {word: count}. Returns the merges (pairs of symbols) in the order they were learned."""
    table = {tuple(w): c for w, c in words.items()}            # each word starts as its characters
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for symbols, c in table.items():
            for p in zip(symbols, symbols[1:]):
                pairs[p] += c
        if not pairs:
            break
        best = max(pairs, key=lambda p: (pairs[p], p))         # most frequent; ties: larger pair
        merges.append(best)
        table = {merge_pair(s, best): c for s, c in table.items()}
    return merges

def encode(word, merges):
    """Split a word into characters, then apply the learned merges in rank order."""
    rank = {p: i for i, p in enumerate(merges)}
    symbols = tuple(word)
    while len(symbols) > 1:
        candidates = [p for p in zip(symbols, symbols[1:]) if p in rank]
        if not candidates:
            break
        symbols = merge_pair(symbols, min(candidates, key=rank.get))
    return list(symbols)
train_text = """The repair shop on Harbour Street opens at eight. Mira unlocks the door, switches on the
compressor and reads the notes from yesterday. A courier bike needs new brake pads, a child's bike
has a bent wheel, and an electric cargo bike reports a battery fault. She starts with the brakes,
because the courier is waiting. Old pads come out, new pads go in, and she adjusts the cables until
the levers feel firm. The bent wheel takes longer. She removes the tyre, mounts the rim on the truing
stand and tightens the spokes a quarter turn at a time, listening to the tone of each one. By noon
the wheel spins straight again. The cargo bike is the hardest job of the day. Its display shows error
code 17, which the manual describes as a communication fault between the battery and the motor
controller. Mira cleans the connectors, checks the voltage with a multimeter and updates the firmware.
The error disappears. In the afternoon two customers bring punctures, and a student asks how to
replace a chain. Mira shows him how to find the master link, how to measure wear with a chain gauge
and why a stretched chain wears out the cassette. Before closing she sweeps the floor, orders spare
spokes and writes tomorrow's notes: recheck the cargo bike, call the courier, and order more pads."""
test_text = """On Thursday a tourist rents a tandem and returns it with a squeaking crankset. Mira
disassembles the bottom bracket, regreases the bearings and reinstalls everything. The squeak is gone,
but the derailleur hanger is misaligned, so she straightens it with an alignment gauge."""

def pretokenize(text):                             # words and punctuation, a space becomes "_" in front
    return [m.replace(" ", "_") for m in re.findall(r" ?\w+| ?[^\w\s]+", text.replace("\n", " "))]

words = Counter(pretokenize(train_text))
test_words = pretokenize(test_text)
print("word types:", len(words), "| first pieces:", pretokenize(train_text)[:6])
base = sorted({ch for w in words for ch in w})
print("base symbols:", len(base))
for n in (0, 50, 100, 200, 400):
    merges = train_bpe(words, n)
    toks = [t for w in test_words for t in encode(w, merges)]
    print(f"{n:3d} merges: vocabulary {len(base) + len(merges):3d}, held-out fertility {len(toks) / len(test_words):.2f}")
merges = train_bpe(words, 200)
print("merges 1-8:", ["".join(p) for p in merges[:8]])
for w in ["_derailleur", "_bearings", "_regreases", "_spokes", "_chain"]:
    print(f"{w:12s} -> {encode(w, merges)}")
print("unknown characters in held-out text:", sorted({ch for w in test_words for ch in w} - set(base)))
word types: 146 | first pieces: ['The', '_repair', '_shop', '_on', '_Harbour', '_Street']
base symbols: 39
  0 merges: vocabulary  39, held-out fertility 5.59
 50 merges: vocabulary  89, held-out fertility 3.82
100 merges: vocabulary 139, held-out fertility 3.43
200 merges: vocabulary 239, held-out fertility 3.12
400 merges: vocabulary 439, held-out fertility 2.92
merges 1-8: ['he', '_t', '_a', '_the', '_c', 'er', 're', '_s']
_derailleur  -> ['_d', 'er', 'a', 'i', 'll', 'e', 'ur']
_bearings    -> ['_b', 'ear', 'ing', 's']
_regreases   -> ['_re', 'g', 're', 'as', 'es']
_spokes      -> ['_spokes']
_chain       -> ['_chain']
unknown characters in held-out text: []

With 0 merges the tokenizer is character-level: 5.59 tokens per pre-tokenised word on the held-out text. Every merge adds one symbol to the vocabulary and shortens sequences: 3.82 tokens per word after 50 merges, 3.12 after 200, 2.92 after 400. The returns diminish, and on a text this small the later merges only memorise whole training words ("_spokes" and "_chain" are single tokens). The held-out words show the subword behaviour: "_bearings" becomes _b ear ing s, reusing the frequent pieces "ear" and "ing", while "_derailleur" falls apart into 7 pieces. The first merges are the most frequent English pairs: "he", "_t", "_a", then "_the".

Byte-level BPE

Character-level BPE still has an unknown-symbol problem: Unicode has about 150,000 characters, and a base vocabulary of all of them is too large while a smaller one misses some. GPT-2's answer: run BPE over the UTF-8 bytes of the text. The base vocabulary is exactly 256 symbols, any string can be encoded, and frequent multi-byte characters (an "é" is 2 bytes, a Chinese character 3) get merged like any other pair.

Two practical tricks come with it.

  • A printable alias for every byte. Merges are stored in a text file, so GPT-2 maps each byte to a visible Unicode character: printable ASCII and Latin-1 bytes map to themselves, and the 68 others (control characters, space, a few Latin-1 gaps) map to code points from 256 upward. Space (byte 32) becomes Ġ and newline (byte 10) becomes Ċ; that is where the Ġ in GPT-2 tokens comes from.
  • Pre-tokenisation with a regex. Before BPE, GPT-2 splits text with a pattern that separates English contractions ('s, 't, 're, …), runs of letters with an optional leading space, runs of digits, runs of other symbols, and whitespace. Merges therefore never join a letter and a digit, or a word and the punctuation after it. The pattern uses Unicode property classes \p{L} (any letter) and \p{N} (any number), which Python's built-in re does not support; the third-party regex module does, and it loads in the browser's Python too. (Without it, [^\W\d_] is a reasonable stand-in for \p{L} and \d for \p{N}.)
python · try it yourself
import regex                                       # third-party "regex": supports \p{L} (letters), \p{N} (numbers)
from collections import Counter

def merge_pair(symbols, pair):
    out, i = [], 0
    while i < len(symbols):
        if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
            out.append(symbols[i] + symbols[i + 1])
            i += 2
        else:
            out.append(symbols[i])
            i += 1
    return tuple(out)

def train_bpe(words, num_merges):
    """words: {word: count}. Returns the merges (pairs of symbols) in the order they were learned."""
    table = {tuple(w): c for w, c in words.items()}            # each word starts as its characters
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for symbols, c in table.items():
            for p in zip(symbols, symbols[1:]):
                pairs[p] += c
        if not pairs:
            break
        best = max(pairs, key=lambda p: (pairs[p], p))         # most frequent; ties: larger pair
        merges.append(best)
        table = {merge_pair(s, best): c for s, c in table.items()}
    return merges

def encode(word, merges):
    """Split a word into characters, then apply the learned merges in rank order."""
    rank = {p: i for i, p in enumerate(merges)}
    symbols = tuple(word)
    while len(symbols) > 1:
        candidates = [p for p in zip(symbols, symbols[1:]) if p in rank]
        if not candidates:
            break
        symbols = merge_pair(symbols, min(candidates, key=rank.get))
    return list(symbols)
train_text = """The repair shop on Harbour Street opens at eight. Mira unlocks the door, switches on the
compressor and reads the notes from yesterday. A courier bike needs new brake pads, a child's bike
has a bent wheel, and an electric cargo bike reports a battery fault. She starts with the brakes,
because the courier is waiting. Old pads come out, new pads go in, and she adjusts the cables until
the levers feel firm. The bent wheel takes longer. She removes the tyre, mounts the rim on the truing
stand and tightens the spokes a quarter turn at a time, listening to the tone of each one. By noon
the wheel spins straight again. The cargo bike is the hardest job of the day. Its display shows error
code 17, which the manual describes as a communication fault between the battery and the motor
controller. Mira cleans the connectors, checks the voltage with a multimeter and updates the firmware.
The error disappears. In the afternoon two customers bring punctures, and a student asks how to
replace a chain. Mira shows him how to find the master link, how to measure wear with a chain gauge
and why a stretched chain wears out the cassette. Before closing she sweeps the floor, orders spare
spokes and writes tomorrow's notes: recheck the cargo bike, call the courier, and order more pads."""
test_text = """On Thursday a tourist rents a tandem and returns it with a squeaking crankset. Mira
disassembles the bottom bracket, regreases the bearings and reinstalls everything. The squeak is gone,
but the derailleur hanger is misaligned, so she straightens it with an alignment gauge."""

def bytes_to_unicode():
    """GPT-2's table: each byte 0-255 -> a printable character (so merges can be stored as text)."""
    keep = [*range(ord("!"), ord("~") + 1), *range(ord("¡"), ord("¬") + 1), *range(ord("®"), ord("ÿ") + 1)]
    table, extra = {b: chr(b) for b in keep}, 0
    for b in range(256):
        if b not in table:
            table[b] = chr(256 + extra)            # space (32) -> "Ġ", newline (10) -> "Ċ"
            extra += 1
    return table

B2U = bytes_to_unicode()
U2B = {u: b for b, u in B2U.items()}
PAT = regex.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")

def pieces(text):                                  # pre-tokenise, then map each piece's UTF-8 bytes
    return ["".join(B2U[b] for b in p.encode("utf-8")) for p in PAT.findall(text)]

def decode(tokens):
    return bytes(U2B[ch] for t in tokens for ch in t).decode("utf-8", errors="replace")

print("pieces:", PAT.findall("Mira's bike, 17 km/h!"))
print("mapped:", pieces("Mira's bike, 17 km/h!"))
merges = train_bpe(Counter(pieces(train_text)), 300)
for s in ["The cargo bike's battery", "Cảm ơn!", "naïve 😀"]:
    toks = [t for p in pieces(s) for t in encode(p, merges)]
    print(f"{s!r}: {len(toks)} tokens {toks}")
    print("   round trip ok:", decode(toks) == s)
pieces: ['Mira', "'s", ' bike', ',', ' 17', ' km', '/', 'h', '!']
mapped: ['Mira', "'s", 'Ġbike', ',', 'Ġ17', 'Ġkm', '/', 'h', '!']
"The cargo bike's battery": 5 tokens ['The', 'Ġcargo', 'Ġbike', "'s", 'Ġbattery']
   round trip ok: True
'Cảm ơn!': 10 tokens ['C', 'á', 'º', '£', 'm', 'Ġ', 'Æ', '¡', 'n', '!']
   round trip ok: True
'naïve 😀': 11 tokens ['n', 'a', 'Ã', '¯', 'v', 'e', 'Ġ', 'ð', 'Ł', 'ĺ', 'Ģ']
   round trip ok: True

The English sentence becomes 5 tokens because its words were in the training text. "Cảm ơn!" and "naïve 😀" contain bytes that this tiny tokenizer never merged, so they fall back to single bytes, shown through the alias table: 10 and 11 tokens, but never an unknown token, and decoding the bytes gives back the exact input. The emoji is 4 bytes and becomes 4 tokens (ð Ł ĺ Ģ). A byte-level tokenizer can split a character in the middle, so a single token may not be valid UTF-8 on its own; decoders have to buffer bytes until a character is complete (this matters when streaming tokens to a user).

The real thing: GPT-2's merges with our encoder

GPT-2's tokenizer ships as two files, vocab.json (token →\to id) and merges.txt (the 50,000 merges in rank order). If our encode is right, feeding it GPT-2's merges and the same pre-tokenisation must reproduce GPT-2's tokens exactly. The recorded example loads the tokenizer of sshleifer/tiny-gpt2, which is GPT-2's original tokenizer.

python · try it yourself
import json, regex
from transformers import AutoTokenizer
from collections import Counter

def merge_pair(symbols, pair):
    out, i = [], 0
    while i < len(symbols):
        if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
            out.append(symbols[i] + symbols[i + 1])
            i += 2
        else:
            out.append(symbols[i])
            i += 1
    return tuple(out)

def train_bpe(words, num_merges):
    """words: {word: count}. Returns the merges (pairs of symbols) in the order they were learned."""
    table = {tuple(w): c for w, c in words.items()}            # each word starts as its characters
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for symbols, c in table.items():
            for p in zip(symbols, symbols[1:]):
                pairs[p] += c
        if not pairs:
            break
        best = max(pairs, key=lambda p: (pairs[p], p))         # most frequent; ties: larger pair
        merges.append(best)
        table = {merge_pair(s, best): c for s, c in table.items()}
    return merges

def encode(word, merges):
    """Split a word into characters, then apply the learned merges in rank order."""
    rank = {p: i for i, p in enumerate(merges)}
    symbols = tuple(word)
    while len(symbols) > 1:
        candidates = [p for p in zip(symbols, symbols[1:]) if p in rank]
        if not candidates:
            break
        symbols = merge_pair(symbols, min(candidates, key=rank.get))
    return list(symbols)

tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")      # GPT-2's tokenizer, same as tiktoken "gpt2"
model = json.loads(tok.backend_tokenizer.to_str())["model"]
merges = [tuple(m.split(" ")) if isinstance(m, str) else tuple(m) for m in model["merges"]]
print("type:", model["type"], "| vocabulary:", len(tok), "| merges:", len(merges))
print("first merges:", merges[:6])
print("256 byte tokens + merges + <|endoftext|> =", 256 + len(merges) + 1)

keep = [*range(ord("!"), ord("~") + 1), *range(ord("¡"), ord("¬") + 1), *range(ord("®"), ord("ÿ") + 1)]
B2U, extra = {b: chr(b) for b in keep}, 0
for b in range(256):
    if b not in B2U:
        B2U[b] = chr(256 + extra)
        extra += 1
PAT = regex.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")

def gpt2_encode(text):                             # our encode() with GPT-2's merges
    out = []
    for p in PAT.findall(text):
        out += encode("".join(B2U[b] for b in p.encode("utf-8")), merges)
    return out

for s in ["Tokenization isn't hard, really!", "The derailleur hanger is misaligned.",
          "Cảm ơn bạn 😀", "  def f(x):\n\treturn x**2"]:
    ours = gpt2_encode(s)
    print(f"{len(ours):2d} tokens, same as Hugging Face: {ours == tok.tokenize(s)} {ours[:8]}")
print("ids:", tok.convert_tokens_to_ids(gpt2_encode("hello world")))
type: BPE | vocabulary: 50257 | merges: 50000
first merges: [('Ġ', 't'), ('Ġ', 'a'), ('h', 'e'), ('i', 'n'), ('r', 'e'), ('o', 'n')]
256 byte tokens + merges + <|endoftext|> = 50257
 8 tokens, same as Hugging Face: True ['Token', 'ization', 'Ġisn', "'t", 'Ġhard', ',', 'Ġreally', '!']
10 tokens, same as Hugging Face: True ['The', 'Ġderail', 'le', 'ur', 'Ġh', 'anger', 'Ġis', 'Ġmis']
16 tokens, same as Hugging Face: True ['C', 'á', 'º', '£', 'm', 'Ġ', 'Æ', '¡']
12 tokens, same as Hugging Face: True ['Ġ', 'Ġdef', 'Ġf', '(', 'x', '):', 'Ċ', 'ĉ']
ids: [31373, 995]

Every sentence matches Hugging Face's fast tokenizer token for token, including the Vietnamese text, the emoji and code with spaces and a tab. The vocabulary arithmetic checks out too: 256 byte tokens, 50,000 merges and the one special token <|endoftext|> give 50,257. The first merges, Ġ t and Ġ a, are the beginnings of " the" and " a". "hello world" gets the ids 31373 and 995.

OpenAI's tiktoken library implements the same encodings in Rust. It downloads its BPE files on first use, so it is shown without running:

python
import tiktoken                                    # needs network access on first use; not run here

enc = tiktoken.get_encoding("gpt2")
print(enc.encode("hello world"))                   # [31373, 995], the same ids as above
enc4 = tiktoken.get_encoding("cl100k_base")        # GPT-4's encoding, about 100k tokens
print(len(enc4.encode("Tokenization isn't hard, really!")))

To train a production BPE tokenizer on your own data, use Hugging Face tokenizers (models.BPE, trainers.BpeTrainer, pre_tokenizers.ByteLevel). Tokenizers in Practice covers the special tokens, padding and offsets that come with a production tokenizer.

Pitfalls

  • Applying merges in the wrong order. Encoding must apply the lowest-rank merge first, repeatedly. Merging by frequency within the new word, or left to right, gives segmentations that training would never have produced, and the model has never seen them.
  • Forgetting the boundary marker. Without </w> or a leading-space symbol, pieces from the end and the start of words are confused, and decoding cannot restore spaces.
  • Different pre-tokenisation at training and encoding time. The merges are only valid for the pre-tokeniser they were trained with; GPT-2's merges with a different regex give different tokens.
  • Decoding single tokens. With byte-level BPE, one token may be part of a multi-byte character. Decode whole sequences, or buffer bytes when streaming.
  • Training the tokenizer on the test set. A tokenizer is fitted preprocessing: fit it on training text, or merges will memorise test words and shorten their sequences.
  • Too few merges for the target language. A vocabulary trained on English leaves other scripts at the byte level (see the multilingual counts in the previous lesson).

Practice

  1. In the six-word table, compute the count of the pair ("_", "s") before any merge, and check it against merge 3 (count 24).
  2. Encode "_spokes" by hand with the 8 merges of the first example. Which merges apply, in which order?
  3. Why does train_bpe stop early (fewer merges than requested) on a small corpus?
  4. Write a decode(tokens) for the character-level version where _ stands for a space.
  5. A byte-level tokenizer must encode the 3-byte character "感". What is the largest and smallest number of tokens it can take, and when?
Answers
  1. Words starting with "_s": "_spoke" 9, "_spokes" 5, "_stroke" 4, "_strokes" 3, "_smoke" 3; total 9+5+4+3+3=249 + 5 + 4 + 3 + 3 = 24. ("_poke" starts with "_p".)
  2. Start _ s p o k e s. The lowest-rank applicable merge each time: o k (rank 1), ok e (2), _ s (3), p oke (4), _s poke (5), giving _spoke s; no further merge applies (_spoke s is not a learned pair). Result: ['_spoke', 's'].
  3. When every word has become a single symbol, there are no adjacent pairs left to count, and the loop breaks. With 146 word types, that happens long before thousands of merges.
  4. "".join(tokens).replace("_", " "), assuming the text itself contains no underscores (GPT-2 avoids that ambiguity because Ġ is an alias of the space byte, and decoding goes through the byte table).
  5. At most 3 tokens (one per byte, when no merge covers its bytes); at least 1 (if merges for its two byte pairs exist, as for frequent Chinese characters in a tokenizer trained on Chinese). With a leading space in GPT-2 style it can also merge into one token with the space.

Test yourself

What does BPE training output, besides the vocabulary?

  1. A probability for every token
  2. The ordered list of merges
  3. A trained neural network
  4. A list of stop words

How does BPE encode a new word?

  1. Longest match from the left in the vocabulary
  2. Split into characters (or bytes), then repeatedly apply the learned merge with the lowest rank among the adjacent pairs
  3. Pick the segmentation with the highest probability
  4. Merge the most frequent pair in the new word

Why does byte-level BPE never produce an unknown token?

  1. It has a huge vocabulary
  2. Its 256 base symbols are all byte values, and any string is a sequence of UTF-8 bytes
  3. It removes unknown characters
  4. It lower-cases the text

GPT-2's vocabulary has 50,257 tokens. Where does that number come from?

  1. 216−15,2792^{16} - 15{,}279
  2. 256 byte tokens + 50,000 merges + 1 special token
  3. 50,000 words + 257 punctuation marks
  4. It was chosen at random

Why does GPT-2 map bytes to characters like 'Ġ' (space) and 'Ċ' (newline)?

  1. To compress the text
  2. So that every byte has a printable character and the merges can be stored as text
  3. Because spaces are not allowed in tokens
  4. To mark the end of a word