BPE: learn merges, then obey their order
BPE 分词
Train character BPE, count overlapping pairs, and encode unseen words without relearning the rules.
tokenizer-bpeWhy can a tokenizer read a word it never learned?
Suppose a vocabulary contains low and lower, but a reader types lowest. A whole-word dictionary needs an unknown-word rule. A character dictionary can spell the new word, but produces longer sequences. Byte-pair encoding, or BPE, learns a middle ground: keep characters available and combine frequently adjacent symbols into reusable pieces.
The name needs a qualification. Sennrich, Haddow and Birch adapted a compression method to word segmentation in their 2016 paper. Their starting units were characters, not necessarily the 256 possible byte values. The name BPE alone therefore does not establish byte-level coverage. This chapter implements the paper’s character-based idea; it does not reproduce a production LLM tokenizer. The original adaptation states the distinction in section 3.2.
Our small corpus uses the paper’s four-word example: low occurs 5 times, lower 2, newest 6 and widest 3. Initially e s appears in the last two words, so its weighted count is 9. Replacing that pair creates es. The next round counts pairs again, now over the changed sequences. It does not keep using the old character counts.
The useful surprise comes with aaa: the pair aa occurs at two adjacent positions, but the positions overlap. A left-to-right replacement can consume only one of them. Pair frequency and the number of actual replacements are different quantities.
Learn frequencies; apply ranks
Let a training dictionary contain words with positive integer frequencies . Attach a reserved end-of-word marker so the last piece retains boundary information. Our teaching representation uses a separate marker initially:
The marker is not text supplied by the user. It may later merge into a piece such as est</w>. For the current symbol sequences, count each adjacent occurrence, including overlapping occurrences:
Choose a pair with maximum count. Our code breaks ties by lexicographic order of the pair; this makes the demonstration reproducible but is not a universal BPE convention.
Replace non-overlapping occurrences of that pair by its concatenation, then recount. Each actual replacement removes one symbol. If is the frequency-weighted symbol count and is the number of non-overlapping replacements in word , then
For aaa, with the separate boundary marker, the first merge changes 4 symbols to 3 although the winning pair count is 2. This greedy procedure favors frequent pairs; it does not solve a global search over every possible vocabulary. Kudo’s comparison contrasts it with a probabilistic segmentation model.
Save the ordered merge list. At inference, do not estimate a new tokenizer from the input. Among currently adjacent pairs with saved rules, select the earliest learned rule:
Here contains adjacent pairs and contains learned rules. Stop when their intersection is empty. For rules a+b before b+c, abc becomes ab | c; reversing the rules yields a | bc. Longest-piece lookup is a different procedure. The fixed subword-nmt implementation explicitly selects the minimum rank and skips overlapping matches. Its version 0.2 attaches the word marker to the final character initially; our example uses the separate-marker convention, so their exact token lists need not match.
For training merges and initial total length over distinct dictionary words, recounting costs symbol visits. Frequencies are weights, so we need not duplicate every occurrence. For an input of initial symbols, repeatedly scanning for the next merge takes
These are symbol-operation bounds. Python string concatenation and tuple comparison add character-dependent costs. The training dictionary and pair table require symbol slots, plus the saved rules; this simple code is not the efficient incremental data structure used by large tokenizer trainers.
Eight merges, then three new words
Run this complete program with Python 3.12; it needs only the standard library. It trains eight merges, records the frequency and actual length reduction at each step, and encodes three held-out words. No language model is trained. The four-word training fixture comes from Algorithm 1 in the BPE paper; the implementation and held-out checks are written for this encyclopedia.
"""Original character-BPE teaching model; no byte tokenizer or upstream code."""
from collections import Counter
import json
END = "</w>"
def symbols(word):
if not word or any(c.isspace() for c in word) or END in word:
raise ValueError("Supply one nonempty word without the reserved marker")
return tuple(word) + (END,)
def merge(seq, pair):
out, i = [], 0
while i < len(seq):
if tuple(seq[i:i + 2]) == pair:
out.append("".join(pair))
i += 2
else:
out.append(seq[i])
i += 1
return tuple(out)
def train(counts, steps):
if not counts or not isinstance(steps, int) or steps < 0:
raise ValueError("Need a corpus and a nonnegative merge budget")
if any(not isinstance(v, int) or v <= 0 for v in counts.values()):
raise ValueError("Word counts must be positive integers")
corpus = {symbols(w): f for w, f in counts.items()}
alphabet = set("".join(counts))
rules, trace = [], []
for _ in range(steps):
pairs = Counter()
before = sum(len(s) * f for s, f in corpus.items())
for seq, freq in corpus.items():
for pair in zip(seq, seq[1:]):
pairs[pair] += freq
if not pairs:
break
# Lexicographic tie-breaking is our explicit teaching convention.
pair = min(pairs, key=lambda p: (-pairs[p], p))
changed = Counter()
for seq, freq in corpus.items():
changed[merge(seq, pair)] += freq
corpus = dict(changed)
after = sum(len(s) * f for s, f in corpus.items())
rules.append(pair)
trace.append(dict(pair=list(pair), frequency=pairs[pair], before=before,
after=after, reduction=before - after))
return rules, alphabet, trace
def encode(word, rules, alphabet):
seq = symbols(word)
if set(word) - alphabet:
raise ValueError("Unseen character: this model has no byte fallback")
ranks = {p: i for i, p in reversed(list(enumerate(rules)))}
while True:
candidates = [p for p in zip(seq, seq[1:]) if p in ranks]
if not candidates:
return seq
seq = merge(seq, min(candidates, key=ranks.get))
def decode(pieces):
joined = "".join(pieces)
if not joined.endswith(END) or joined.count(END) != 1:
raise ValueError("Need exactly one final word marker")
return joined[:-len(END)]
def demo():
counts = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
rules, alphabet, trace = train(counts, 8)
_, _, overlap = train({"aaa": 1}, 1)
return dict(corpus=counts, trace=trace,
heldout={w: list(encode(w, rules, alphabet))
for w in ["lowest", "newer", "wider"]},
overlap=overlap[0], initial_symbols=trace[0]["before"],
final_symbols=trace[-1]["after"])
if __name__ == "__main__":
print(json.dumps(demo(), ensure_ascii=False, indent=2))
The weighted corpus starts with 95 symbols, including boundaries, and ends with 36 after eight merges. The first three winning pairs have frequency 9; the first pair is e+s under our tie rule. The output exposes every intermediate count, so you can check the reduction without treating the final compression ratio as a language benchmark.
Change the frequency of lower to 20 and train again. The learned order can change. Then hold the rules fixed and repeat lowest in an input list: repetition must not change that word’s encoding. These are different experiments—changing training statistics and changing inference input frequency.
A boundary marker does not supply missing characters
An unseen word composed of known characters can still be segmented, even if none of its longer pieces were learned. An unseen character is a separate problem: this example raises an error. A byte-based tokenizer can start from all byte values, but its byte-to-text mapping, preprocessing and special-token rules must also be specified. Do not infer them from the abbreviation BPE.
Word boundaries are another modeling choice. This program processes one word at a time and rejects whitespace. It cannot learn pieces across words or reconstruct the spacing of a whole document. SentencePiece covers a pipeline that learns directly from raw sentences and handles whitespace explicitly.
More merges can shorten sequences while enlarging the vocabulary and its embedding/output tables. Shorter sequences alone do not establish better prediction, fairer language coverage or lower end-to-end cost. Measure downstream loss and task behavior under matched data and compute conditions. Also fit the tokenizer on the training split: learning its vocabulary from held-out text changes what the evaluation is measuring.
Predict the next replacement
- A dictionary has
ab:7andac:1. What is the first merge under this chapter’s tie rule?
Answer: a+b. Both a+b and b+</w> have count 7; lexicographic tie-breaking puts a+b first. Ignoring word frequencies would lose the 7-to-1 weighting.
- In
aaa, why is the pair count 2 but the reduction only 1?
Answer: The matches occupy positions 1–2 and 2–3. Consuming the first leaves the third a unpaired; the middle character cannot be consumed twice. The boundary-inclusive length falls from 4 to 3.
- With rules
a+bbeforeb+c, could a longest-vocabulary-entry rule always replace the saved merge order?
Answer: No. On abc, the saved order chooses ab | c. The vocabulary also contains bc, and a different tie or lookup direction could choose a | bc. Vocabulary membership alone does not encode merge priority.
- The model can encode
lowestbut rejects雪. Does that contradict open-vocabulary word segmentation?
Answer: No. Novel combinations of covered characters and novel characters are different cases. Expand the character coverage or use a specified byte/unknown fallback, then test the full round trip; adding a word-boundary marker does not solve the missing-character case.
Where the method ends and the pipeline begins
Sennrich and colleagues provide the character adaptation, weighted dictionary training and word-boundary setup. The fixed subword-nmt source makes rank selection and boundary-version differences inspectable. Kudo supplies the comparison with probabilistic subword modeling. Our small checks verify counts, overlap handling and reversible encoding over the covered alphabet; they do not reproduce the papers’ translation results. Continue with Unigram tokenization to replace a deterministic merge history with probabilities over competing segmentations.
Make a prediction, then check
How does a trained BPE tokenizer select the next applicable merge?
Learning objectives
- Derive frequency-weighted pair counts and explain overlapping matches.
- Apply fixed merge ranks to held-out words and verify the word-boundary roundtrip.
- Separate character BPE from byte-level coverage and from probabilistic segmentation.
Prerequisites & connections
Explore related knowledge →References
- Neural Machine Translation of Rare Words with Subword Units
Rico Sennrich; Barry Haddow; Alexandra Birch · 2016 - subword-nmt: BPE application at fixed commit
Rico Sennrich and subword-nmt contributors · 2024 - Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates
Taku Kudo · 2018
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked Sennrich section 3.2/Algorithm 1, Kudo section 3.1 and fixed subword-nmt encode lines 276–338. Six paired equations and four explained exercises; weighted counts, overlap counterexample, ranked application, exhaustive covered-alphabet roundtrips and character versus byte coverage. Original code uses the paper four-word fixture; no translation replication.
- Single AI author checked Sennrich section 3.2/Algorithm 1, Kudo section 3.1 and fixed subword-nmt encode lines 276–338. Six paired equations and four explained exercises; weighted counts, overlap counterexample, ranked application, exhaustive covered-alphabet roundtrips and character versus byte coverage. Original code uses the paper four-word fixture; no translation replication.
- Four computed SVG variants per topic; 10 numeric/geometry tests and 24 responsive cases passed. Eight Chinese-mobile/English-desktop figure screenshots actually viewed. Full article acceptance recorded separately.
Source locations checked:
- Neural Machine Translation of Rare Words with Subword Units · Read section 3.2 and Algorithm 1; viewed PDF page 3. Character merges, word counts and boundaries; no translation benchmark reproduced.
- subword-nmt: BPE application at fixed commit · Read encode lines 276–338 and README usage; rank selection, non-overlapping replacement and 0.1/0.2 boundary conventions. MIT license header inspected; no upstream code executed or copied.
- Subword Regularization: Improving Neural Network Translation Models with Multiple Subword Candidates · Read sections 3.1–3.4; viewed PDF pages 3–4, including equations 6–7, EM, vocabulary pruning and segmentation sampling. No NMT experiments reproduced.
Related topics