Bring the mental model from Maximum Likelihood; this page will reuse it instead of restarting from zero.
Attention & Transformers
Tokenization & Vocabulary Design
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.

Concept Structure
Tokenization & Vocabulary Design
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Tokenization & Vocabulary DesignConceptual Bridge
What should feel connected as you move through this page.
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.
The next edge should feel earned: use the demo prediction here before following Scaled Dot-Product Attention & Transformer Layers.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
Transformers do not read characters or words. They read tokens: discrete IDs from a fixed vocabulary.
Tokenization is the (often invisible) step that decides what the model's "atoms" are. If your tokenizer splits function_name into 6 tokens, the model must process 6 positions (and at generation time emit 6 tokens) to handle it. If it gets a single token, it can treat it like one object.
There is always a tradeoff:
- Bigger vocabulary: fewer tokens per prompt, but a larger embedding/output table and more brittle edge cases.
- Smaller vocabulary (or bytes): more robust, but longer sequences, larger KV caches, and higher compute for the same text.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let the vocabulary be a set of strings (or byte sequences) . A tokenizer maps an input string into a sequence of tokens (where is the token count):
BPE and unigram tokenization are two different search stories
BPE learns vocabulary entries by merging frequent adjacent symbols. Unigram tokenization instead scores candidate segmentations with token priors and picks the most likely path:
The unigram path can be solved by dynamic programming (a Viterbi-like shortest-path problem over string positions). The BPE merge sequence is learned greedily during tokenizer training, then applied as deterministic merge rules at encoding time.
Vocabulary size affects parameter count
If embeddings and output logits both use a matrix, then token-related parameters scale like:
If you tie input/output embeddings (common in LLMs), this is closer to .
So the tokenizer is not just preprocessing: it changes model size, latency, and what patterns become easy to represent.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
from collections import Counter
import math
def learn_bpe_merges(corpus, num_merges=3):
vocab = {tuple(word): freq for word, freq in corpus.items()}
merges = []
for _ in range(num_merges):
counts = Counter()
for symbols, freq in vocab.items():
for pair in zip(symbols, symbols[1:]):
counts[pair] += freq
if not counts:
break
best = max(counts, key=counts.get)
merges.append(best)
merged_vocab = {}
for symbols, freq in vocab.items():
out, i = [], 0
while i < len(symbols):
if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == best:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
merged_vocab[tuple(out)] = freq
vocab = merged_vocab
return merges, vocab
def unigram_map(x, tok_logp):
n, NEG = len(x), -1e30
dp, back = [NEG] * (n + 1), [None] * (n + 1)
dp[0] = 0.0
buckets = {}
for tok, lp in tok_logp.items():
buckets.setdefault(tok[0], []).append((tok, lp))
for i in range(n):
if dp[i] <= NEG / 2:
continue
for tok, lp in buckets.get(x[i], []):
if x.startswith(tok, i):
j, s = i + len(tok), dp[i] + lp
if s > dp[j]:
dp[j], back[j] = s, (i, tok)
if back[n] is None:
return None
out, j = [], n
while j > 0:
i, tok = back[j]
out.append(tok)
j = i
return out[::-1], dp[n]
merges, vocab = learn_bpe_merges({"low": 5, "lower": 2, "new": 6, "newer": 3}, num_merges=4)
print("bpe merges:", merges)
print("bpe vocab:", vocab)
probs = {"the": 0.08, "there": 0.02, "re": 0.05, "th": 0.06, "e": 0.07, "r": 0.03, "t": 0.02, "h": 0.02}
tok_logp = {t: math.log(p) for t, p in probs.items()}
x = "there"
res = unigram_map(x, tok_logp)
assert res is not None, "No valid segmentation"
seg, score = res
print("x:", x)
print("seg:", seg, "tokens:", len(seg), "logp:", round(score, 3))
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
Use the demo to see how different tokenizer designs change token boundaries, token counts, and what the model treats as a single unit.
Live Concept Demo
Explore Tokenization & Vocabulary Design
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Commit to what Tokenization & Vocabulary Design should make visible before reading the result.
After The First Pass
Turn the concept into an inspected object.
Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.
Mechanism Storyboard
See the idea move before the page explains it
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.

Start with the picture, metaphor, or geometric mechanism.
Before reading further, choose the kind of change Tokenization & Vocabulary Design should make visible.
Visual Inquiry
Make the image answer a mathematical question
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.
Which visible object should carry the first intuition?
Pick the cue that should make Tokenization & Vocabulary Design easier to reason about before the page gives the answer.
Source Grounding
Canonical references for the mechanism on this page.
Primary BPE subword source. Sec. 3.2 initializes a character-symbol vocabulary, repeatedly counts adjacent symbol pairs, merges the most frequent pair, and grows the final symbol vocabulary by merge operations.
Open sourcePrimary SentencePiece source. Describes a language-independent tokenizer/detokenizer that manages vocabulary-id mapping and implements BPE plus unigram language-model subword segmentation.
Open sourceClaim Review
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.
Claims without a substantive review badge still need exact source-support review.
sennrich-2015-bpe, kudo-2018-sentencepiece
Use equation, code, and demo objects to check whether the source support is operational.
Sennrich Sec. 3.2 initializes character symbols, counts adjacent pairs, repeatedly merges the most frequent pair, and grows final vocab by merge count. Kudo/Richardson describe SentencePiece as language-independent tokenization/detokenization with subword sequences, vocab-id mapping, and BPE plus unigram LM segmentation. The first two equations, first code witness, and demo BPE/unigram portions are toy witnesses.
Sources: Neural Machine Translation of Rare Words with Subword Units, SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text ProcessingChecks high-level subword vocab, BPE merges, and SentencePiece BPE/unigram mechanics only; not exact LLM tokenizer files, byte fallback, Unicode normalization edges, merge-rank details, vocab-size scaling, downstream capability/cost claims, or the demo's byte/Unicode/cost panes.A bounded review summary is present; still check caveats and exact source scope.Checked Sennrich Sec. 3.2 and Kudo/Richardson: Sennrich supports BPE as character-symbol vocabulary plus adjacent-pair counts and repeated most-frequent-pair merges; Kudo/Richardson supports SentencePiece as language-independent tokenizer/detokenizer with vocabulary-id conversion and BPE/unigram LM segmentation. Local math/code and BPE/unigram demo portions are toy witnesses only.
Reviewer: codex+oracle; reviewed 2026-05-07Source support candidates
paper 2015Neural Machine Translation of Rare Words with Subword UnitsPrimary BPE subword source. Sec. 3.2 initializes a character-symbol vocabulary, repeatedly counts adjacent symbol pairs, merges the most frequent pair, and grows the final symbol vocabulary by merge operations.
paper 2018SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text ProcessingPrimary SentencePiece source. Describes a language-independent tokenizer/detokenizer that manages vocabulary-id mapping and implements BPE plus unigram language-model subword segmentation.
Practice Loop
Try the idea before it explains itself
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.
Before touching the demo, predict one visible change that should happen in Tokenization & Vocabulary Design.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
Research Room
Attach the question to an exact object
Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.Open the draft below to save one note and next action in this browser.
Tokenization & Vocabulary Design
What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays locally in this browser for concept:attention-transformers/tokenization-vocabulary.
- Source ids to inspect: sennrich-2015-bpe, kudo-2018-sentencepiece
- Definition, prerequisite, and contrast concept links
- The equation or code witness that makes the concept operational
- One demo state that shows the invariant instead of a slogan
- The learner can state the mechanism in their own words
- The learner can name the prerequisite that would repair confusion
- The learner can predict how the mechanism changes under one perturbation
I am working in Continuous Function's research reading room. Object: concept - Tokenization & Vocabulary Design Object key: concept:attention-transformers/tokenization-vocabulary Context: Attention & Transformers Anchor id: concept/concept-notebook/attention-transformers/tokenization-vocabulary Open question: What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math? Evidence to inspect: - Source ids to inspect: sennrich-2015-bpe, kudo-2018-sentencepiece - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.
concept/concept-notebook/attention-transformers/tokenization-vocabulary
concept:attention-transformers/tokenization-vocabulary