Byte Pair Encoding (BPE) & Subword Tokenization Explained Visually
How LLMs convert raw text, code, and emojis into integer token IDs — why word-level and character-level vocabularies fail, and how Byte-Level BPE compresses frequent roots with zero <UNK> tokens.
Byte Pair Encoding (BPE) is a subword tokenization algorithm that converts raw text into integer token IDs by repeatedly merging the most frequent adjacent character pairs.
Neural networks only accept numbers—character-level tokens make sequences too long, while word-level vocabularies explode on typos and rare words. BPE hits the sweet spot.
Tokenization is the hidden lens through which every LLM sees the world — explaining why LLMs struggle to count the 'r's in 'strawberry' and why JSON costs 2× more!
Knowing how BPE merges work lets you diagnose subtle bugs: trailing whitespace splits (' apple' vs 'apple'), digit chunking ('1234'), and multilingual token inflation that silently triples API bills.
Understanding vocabulary size tradeoffs (32K vs 128K in LLaMA 3) explains how modern LLMs cut sequence lengths by 15–20% while keeping embedding table VRAM manageable.
Top Generative AI interview coding prompt: 'Implement BPE pair-frequency counting and one BPE merge step from scratch in Python — and explain why GPT-2/4 uses Byte-Level BPE!'
If a Byte-Level BPE tokenizer starts with all 256 raw UTF-8 bytes and performs 50,000 merge operations, what is its base vocabulary size (excluding special tokens)?
- Explain why word-level vocabularies fail on rare/new words and character-level sequences explode O(N²) attention cost
- Trace Byte Pair Encoding (BPE) pair-frequency counting and greedy iterative merging step-by-step
- Explain how Byte-Level BPE (GPT-4 / LLaMA 3) guarantees zero <UNK> tokens on any UTF-8 byte sequence
- Implement BPE pair-frequency counting and merge steps from scratch in Python
Imagine packing a suitcase of LEGO bricks where you can either carry individual 1×1 studs (characters — tiny vocabulary, way too many pieces!) or pre-glued entire castles (whole words — gigantic warehouse, breaks the instant you want a slightly new tower!). Subword BPE pre-glues just the most frequently repeated building blocks ('un', 'believ', 'able', 'def ') so common words take 1 token while brand-new words snap together cleanly from familiar roots!
1. Word vs. Character vs. Subword BPE: The Vocabulary Sweet Spot
Self-Attention scales quadratically O(T²) with token count T, while the final Softmax head scales linearly O(V) with vocabulary size V. Subword tokenization hits the exact sweet spot between both extremes!
Why Byte-Level BPE Won
- Word-Level: Fails on typos, compound words, and code identifiers (
get_user_by_id) → floods output with<UNK>. - Character-Level: Makes sequences ~5× longer → makes Self-Attention 25× slower!
- Byte-Level BPE (GPT-2/4, LLaMA 3, Qwen): Operates directly on raw UTF-8 bytes (
0..255). Even an unseen emoji or rare Unicode symbol safely falls back to its 1–4 UTF-8 bytes — literally 0%<UNK>rate!
2. How BPE Trains: Counting Adjacent Pairs & Greedy Merging
Click Merge 0 → Merge 1 → Merge 2 below to watch BPE count adjacent pairs and compress 'the_there_then' from 14 characters down to 8 tokens!
The 3-Line BPE Training Loop
- Split corpus into UTF-8 byte sequences (after regex pre-tokenization so merges don't cross spaces/punctuation awkwardly).
- Count the frequency of every adjacent pair across the entire corpus.
- Find the most frequent pair , mint a new token ID , replace every occurrence of with , and record the merge rule . Repeat times!
Crucial Inference Detail: At inference time, BPE applies learned merge rules in exact training priority order (earliest learned merge first), NOT left-to-right!
V = 256 + M_merges + N_special
Every possible byte 0x00..0xFF guarantees any text or emoji is encodable.
256 + 50,000 + 1 = 50,257 tokens; LLaMA 3 scales to 128,256 tokens to compress code and multilingual text far more efficiently!Interactive BPE Pair-Merge Stepper
3. Token Fertility, Numbers & Why LLMs Misspell Words
Because the LLM never sees raw letters — only integer IDs like [496, 675, 15717] for 'strawberry' — asking it to count letters inside a single fused token is like asking you to count brush strokes inside a printed Chinese character from memory!
Production Gotchas Every AI Engineer Hits
- Leading Spaces Matter:
"apple"and" apple"get different token IDs! Never leave trailing spaces at the end of a prompt prefix. - Multilingual Cost Tax: Older English-centric 32K tokenizers split Hindi, Arabic, or Thai into 4–8× more tokens than English. Expanding to 128K–256K vocabs (LLaMA 3, Gemma 2) dramatically cuts multilingual latency!
- Number Splitting: Modern tokenizers (GPT-4 / LLaMA 3) cap numeric merges at 3-digit chunks (
000..999) so arithmetic aligns cleanly!
Worked Example: Running One Exact BPE Merge Step by Hand
Token list: ['a', 'b', 'a', 'b', 'c', 'a', 'b']. Find the top pair and apply 1 merge.
('a','b'): 3, ('b','a'): 1, ('b','c'): 1, ('c','a'): 1.
Why does Byte-Level BPE NEVER produce an <UNK> (unknown) token on any valid string?
Given sequence ['x', 'x', 'x'] and merge rule ('x', 'x') → 'xx', what is the exact result when merging left-to-right?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
BPE merges pairs purely by raw frequency. WordPiece merges pairs that maximize likelihood gain (count(ab) / (count(a)·count(b))). Unigram starts with a huge vocabulary and prunes tokens that least hurt corpus likelihood.
'neural_nets' compress from 11 bytes down to 5 subword tokens!Byte Pair Encoding (BPE) Iterative Compression Animator
Watch BPE greedily merge frequent adjacent pairs step-by-step, shrinking sequence length while growing the learned subword vocabulary.
<UNK> tokens while balancing O(T²) sequence length against O(V) embedding memory.OpenAI tiktoken (cl100k / o200k)
High-speed Rust Byte-Level BPE powering GPT-4 and GPT-4o (200K vocab cutting multilingual tokens in half).
LLaMA 3 & Gemma 2 Tokenizers
128K–256K vocabularies optimized for Python, SQL, math digits, and non-English scripts.
Cost & Latency Estimation
Pre-counting exact tokens with tiktoken before sending API requests prevents context-overflow errors.
from collections import Counter
# 1. From-Scratch BPE Pair Frequency & Single Merge Step
def get_pair_frequencies(tokens: list[str]) -> Counter:
return Counter(zip(tokens, tokens[1:]))
def bpe_merge_step(tokens: list[str], pair: tuple[str, str], merged: str) -> list[str]:
out: list[str] = []
i = 0
while i < len(tokens):
if i + 1 < len(tokens) and (tokens[i], tokens[i + 1]) == pair:
out.append(merged)
i += 2 # consume both tokens cleanly (handles 'xxx' -> ['xx', 'x'])
else:
out.append(tokens[i])
i += 1
return out
# Demo
seq = list("the_there_then")
top_pair, _ = get_pair_frequencies(seq).most_common(1)[0] # ('t', 'h')
print(bpe_merge_step(seq, top_pair, "".join(top_pair)))
# ['th', 'e', '_', 'th', 'e', 'r', 'e', '_', 'th', 'e', 'n']
str.replace() naively on a joined string during BPE merging.list[str] of tokens with an index pointer i += 2 so merges never accidentally cross existing token boundaries!' cat'); a trailing space forces a broken extra space token!V?('a', 'a') → 'aa' left-to-right on ['a', 'a', 'a']?V excessively huge (e.g., 2,000,000)?