Bring the mental model from Maximum Likelihood; this page will reuse it instead of restarting from zero.
Tokenization & Vocabulary Design
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.
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.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
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) V. A tokenizer maps an input string x into a sequence of tokens (where n 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 p(t) 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 ∣V∣×d matrix, then token-related parameters scale like:
If you tie input/output embeddings (common in LLMs), this is closer to ∣V∣d.
So the tokenizer is not just preprocessing: it changes model size, latency, and what patterns become easy to represent.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
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))
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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.
Choose what to inspect in Tokenization & Vocabulary Design. This shared fallback is an observation guide, not evidence of learning.
Use the demo to see how different tokenizer designs change token boundaries, token counts, and what the model treats as a single unit.
Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.
Concept: Tokenization & Vocabulary Design
What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?
Object contextAttention & Transformers
concept:attention-transformers/tokenization-vocabularyTokenization & Vocabulary Design
What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?
Start with the prediction checkpoint, then compare the reveal to the mental model.
Take this moveStudy modes
Keep the object fixed; change the lens.Route back through the notebook
Carry the same object through intuition, math, code, and demo.
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.
After The First Pass
Turn the concept into an inspected object.
The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the 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.
What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?
concept:attention-transformers/tokenization-vocabularysources: sennrich-2015-bpe, kudo-2018-sentencepiece
Open the closest source note before trusting the local explanation.
2 selected-object sources shown first; 2 references total.
Audit the claim boundary, then ask from the same selected object.
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.
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 SentencePi...
Checks 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, v...
Primary SentencePiece source. Describes a language-independent tokenizer/detokenizer that manages vocabulary-id mapping and implements BPE plus unigram language-model subword segmentation.
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 SentencePi...
Checks 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, v...
Claim Review
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.
What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?
concept:attention-transformers/tokenization-vocabularysources: sennrich-2015-bpe, kudo-2018-sentencepiece
Treat every claim as provisional until source support and a local witness agree.
1 structured claim check on this concept.
Run the prediction or practice transfer before asking for a grounded review.
Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 2 references and 3 local witnesses are available for inspection.
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-inde...
Checks 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, d...
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-07Practice notebook
Use the idea, then test it somewhere new
How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.
What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?
concept:attention-transformers/tokenization-vocabularysources: sennrich-2015-bpe, kudo-2018-sentencepiece
Use one state from Tokenization & Vocabulary Design to explain what changes, why it changes, and which assumption the explanation needs.
No learner move yet; no learning state is inferred.
Write first, use only the help you need, then try a new case without it.
Use one state from Tokenization & Vocabulary Design to explain what changes, why it changes, and which assumption the explanation needs.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Write an attempt before asking the companion.
0 of 3 progressive hints opened.
This draft and any AI response do not establish mastery; a later unassisted case can.
- ObjectConceptTokenization & Vocabulary Design
- PredictBefore revealTokenization & Vocabulary Design prediction
- WitnessCompare codeTokenization & Vocabulary Design code witness 1
- RoomAsk groundedChecking local snapshot
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?
These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.
Source ids sennrich-2015-bpe, kudo-2018-sentencepiece must support the exact object, not just the surrounding topic.
Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.
Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.
The learner can state the mechanism in their own words
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 Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids sennrich-2015-bpe, kudo-2018-sentencepiece must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Tokenization & Vocabulary Design" feel predictable rather than familiar." | assumption: Source ids sennrich-2015-bpe, kudo-2018-sentencepiece must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: sennrich-2015-bpe, kudo-2018-sentencepiece" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. 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. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Tokenization & Vocabulary Design" feel predictable rather than familiar. - Assumption to keep visible: Source ids sennrich-2015-bpe, kudo-2018-sentencepiece must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words
concept/concept-notebook/attention-transformers/tokenization-vocabulary
concept:attention-transformers/tokenization-vocabulary