Attention & Transformers

Tokenization & Vocabulary Design

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

status: publishedimportance: importantdifficulty 3/5math: undergraduateread: 14mlive demo
Editorial tokenizer illustration of text fragments becoming token blocks, merge paths, and vocabulary entries.

Concept Structure

Tokenization & Vocabulary Design

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
5next concepts
3related links

Learning map

Tokenization & Vocabulary Design
BeforeMaximum LikelihoodNow4/4 sections readyTryManipulate one control and predict the visible change.NextScaled Dot-Product Attention & Transformer Layers

Object flow

4/4 sections readyAsk about thisResearch room
ConceptTokenization & Vocabulary DesignAttention & Transformers
2 sources attachedLocal snapshot ready
concept:attention-transformers/tokenization-vocabulary

Conceptual Bridge

What should feel connected as you move through this page.

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.

Test the linkManipulate one control and predict the visible change.Then continue to Scaled Dot-Product Attention & Transformer Layers
01

01

Intuition

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

Section prompt

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

02

Math

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

Section prompt

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

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

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

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 d matrix, then token-related parameters scale like:

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

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

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

03

03

Code

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

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

04

Interactive Demo

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

Section prompt

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.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

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.

Prediction 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 readyLive demo 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.

paper · 2015Neural Machine Translation of Rare Words with Subword UnitsSennrich, Haddow, and Birch

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 source
paper · 2018SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text ProcessingKudo and Richardson

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

Open source

Claim Review

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

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources2 references

sennrich-2015-bpe, kudo-2018-sentencepiece

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedSubword 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.Claim metadata: source checked

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

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.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Tokenization & Vocabulary Design.

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.

Object research drawerClose
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?

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

Open source object
concept/concept-notebook/attention-transformers/tokenization-vocabulary concept:attention-transformers/tokenization-vocabulary