SystemYou are an expert NLP engineer. You explain tokenization clearly and give correct, minimal Python examples.
You are an expert NLP engineer. You explain tokenization clearly and give correct, minimal Python examples.
User
What is byte-pair encoding (BPE) and how does tokenizer training work? Include a small code example.
Assistant
Byte-pair encoding (BPE) is a subword tokenization algorithm. It starts from single characters (or bytes) and repeatedly merges the most frequent adjacent pair until the vocabulary reaches a target size. Philip Gage (1994) proposed it for compression; Sennrich et al. (2016) adapted it for neural machine translation, and it is now the basis of most LLM tokenizers (GPT-2/3/4, Llama, Mistral).
Training:
Pre-tokenize text into words, split each word into symbols, append an end-of-word marker.
Count every adjacent symbol pair, weighted by word frequency.
Merge the single most frequent pair everywhere (add it to the vocabulary).
Repeat steps 2-3 for N merges.
Worked example (word frequencies: low x5, lower x2, newest x6, widest x3): the pair ('e', 's') occurs 9 times (newest x6 + widest x3), more than any other pair, so the first learned token is 'es'.
python
from collections import Counter
defget_stats(vocab):
"""Count adjacent symbol pairs, weighted by word frequency."""
pairs = Counter()
for word, freq in vocab.items():
syms = word.split()
for i inrange(len(syms) - 1):
pairs[(syms[i], syms[i + 1])] += freq
return pairs
defmerge_pair(pair, vocab):
"""Merge one pair everywhere it occurs."""return {w.replace(' '.join(pair), ''.join(pair)): f for w, f in vocab.items()}
vocab = {
'l o w </w>': 5,
'l o w e r </w>': 2,
'n e w e s t </w>': 6,
'w i d e s t </w>': 3,
}
for _ inrange(10):
pairs = get_stats(vocab)
ifnot pairs:
break
best = max(pairs, key=pairs.get) # most frequent pair
vocab = merge_pair(best, vocab)
print(best)
Production notes: modern tokenizers use byte-level BPE (base vocabulary = 256 UTF-8 bytes, e.g. GPT-2), so any input is encodable and there are no unknown tokens. Vocabulary size (typically 32k-256k) trades sequence length against embedding-table size. A tokenizer trained on English-only text still runs on other languages (bytes always work) but splits them into many tiny pieces — see the multilingual fertility note.