Concept notebookChecking saved investigationReading browser-local route memory before showing a continuation.

Tokenization & Vocabulary Design

How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.

published · difficulty 3/5 · 14 min read

01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

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.
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Let the vocabulary be a set of strings (or byte sequences) V\mathcal VV. A tokenizer maps an input string xxx into a sequence of tokens (where nnn is the token count):

x=concat(t1,,tn),tiV.x = \mathrm{concat}(t_1,\dots,t_n), \qquad t_i \in \mathcal V.x=concat(t1,,tn),tiV.

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)p(t)p(t) and picks the most likely path:

(a,b)=argmax(a,b)  count(ab)abab,t^1:n=argmaxt:  concat(t)=x  i=1nlogp(ti).(a,b)^* = \arg\max_{(a,b)}\;\mathrm{count}(ab) \Rightarrow a\,b \to ab, \qquad \hat t_{1:n} = \arg\max_{t:\;\mathrm{concat}(t)=x}\;\sum_{i=1}^n \log p(t_i).(a,b)=arg(a,b)maxcount(ab)abab,t^1:n=argt:concat(t)=xmaxi=1nlogp(ti).

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|\mathcal V|\times dV×d matrix, then token-related parameters scale like:

paramstoken2Vd.\mathrm{params}_{\mathrm{token}} \approx 2\,|\mathcal V|\,d.paramstoken2Vd.

If you tie input/output embeddings (common in LLMs), this is closer to Vd|\mathcal V|\,dVd.

So the tokenizer is not just preprocessing: it changes model size, latency, and what patterns become easy to represent.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
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))
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

Live Concept Demo

Explore Tokenization & Vocabulary Design

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Scaled Dot-Product Attention & Transformer Layers

Choose what to inspect in Tokenization & Vocabulary Design. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Use the demo to see how different tokenizer designs change token boundaries, token counts, and what the model treats as a single unit.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Tokenization & Vocabulary Design

What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?

BeforeMaximum LikelihoodNow4/4 sections readyTryManipulate one control and predict the visible change.NextScaled Dot-Product Attention & Transformer Layers
Object contextAttention & Transformers
ConceptLearner lens

Tokenization & Vocabulary Design

What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inMaximum Likelihood

Bring the mental model from Maximum Likelihood; this page will reuse it instead of restarting from zero.

Work hereTokenization & Vocabulary Design

How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.

Carry outScaled Dot-Product Attention & Transformer Layers

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.
ConceptTokenization & Vocabulary DesignAttention & Transformers

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.

Demo notes open01 / Intuition
Editorial tokenizer illustration of text fragments becoming token blocks, merge paths, and vocabulary entries.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

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.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

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.

Object - ConceptTokenization & Vocabulary DesignQuestion

What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?

concept:attention-transformers/tokenization-vocabulary
Boundary

sources: sennrich-2015-bpe, kudo-2018-sentencepiece

Check

Open the closest source note before trusting the local explanation.

Evidence

2 selected-object sources shown first; 2 references total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · paper · 2015Neural Machine Translation of Rare Words with Subword UnitsSennrich, Haddow, and Birch
Located CF editorial boundary

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.

Used here as

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...

Caveat

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...

Open source
selected object source · paper · 2018SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text ProcessingKudo and Richardson
Located CF editorial boundary

Primary SentencePiece source. Describes a language-independent tokenizer/detokenizer that manages vocabulary-id mapping and implements BPE plus unigram language-model subword segmentation.

Used here as

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...

Caveat

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...

Open source

Claim Review

How text becomes token IDs: segmentation, BPE/unigram tokenizers, and the tradeoffs that shape cost and capability.

Object - ConceptTokenization & Vocabulary DesignQuestion

What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?

concept:attention-transformers/tokenization-vocabulary
Boundary

sources: sennrich-2015-bpe, kudo-2018-sentencepiece

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

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.

Subword tokenizers map text to vocabulary items: BPE builds units by repeatedly merging the most frequent adjacent symbols; SentencePiece supports BPE and unigram language-model subword segmentation.
Used here as

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...

Local witness
Equation 1
x=concat(t1,,tn),tiV.x = \mathrm{concat}(t_1,\dots,t_n), \qquad t_i \in \mathcal V.
Equation 2
(a,b)=argmax(a,b)  count(ab)abab,t^1:n=argmaxt:  concat(t)=x  i=1nlogp(ti).(a,b)^* = \arg\max_{(a,b)}\;\mathrm{count}(ab) \Rightarrow a\,b \to ab, \qquad \hat t_{1:n} = \arg\max_{t:\;\mathrm{concat}(t)=x}\;\sum_{i=1}^n \log p(t_i).
Caveat

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...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. 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-07

Practice 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.

AttemptNo learning claim inferred
Object - ConceptTokenization & Vocabulary DesignQuestion

What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?

concept:attention-transformers/tokenization-vocabulary
Boundary

sources: sennrich-2015-bpe, kudo-2018-sentencepiece

Check

Use one state from Tokenization & Vocabulary Design to explain what changes, why it changes, and which assumption the explanation needs.

Evidence

No learner move yet; no learning state is inferred.

Next move

Write first, use only the help you need, then try a new case without it.

Explain

Use one state from Tokenization & Vocabulary Design to explain what changes, why it changes, and which assumption the explanation needs.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded object roomClose
Selected object routeAsk from this object; carry one invariant back.sources: sennrich-2015-bpe, kudo-2018-sentencepiece
  1. ObjectConceptTokenization & Vocabulary Design
  2. PredictBefore revealTokenization & Vocabulary Design prediction
  3. WitnessCompare codeTokenization & Vocabulary Design code witness 1
  4. RoomAsk groundedChecking local snapshot
ConceptTokenization & Vocabulary DesignAttention & Transformers

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.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptAttention & Transformers

Tokenization & Vocabulary Design

Anchored question

What is the smallest example that makes Tokenization & Vocabulary Design click without losing the math?

Source boundaryInspect source ids: sennrich-2015-bpe, kudo-2018-sentencepieceStable content-object key attached
Role lenses for this object

These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

Learner evidence requestAsk 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.

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.

Next action

The learner can state the mechanism in their own words

Evidence4 checks
PredictionChecking carried observation
ActionReady for one action
AILearner handoff ready
Open source object
01PredictionChecking browser-local route memory
02EvidenceChecking for a carried observation
03BoundaryInspect source ids: sennrich-2015-bpe, kudo-2018-sentencepiece
04Next moveSave one next action
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:attention-transformers/tokenization-vocabulary.

No local draft saved.
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
Object-attached AI handoff

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