Attention & Transformers

BPE vs. Unigram Tokenization

Compare ordered BPE merges with unigram path search on the same string, then predict which tokenizer uses fewer tokens and why.

status: reviewimportance: importantdifficulty 3/5math: undergraduateread: 14mlive demo

Concept Structure

BPE vs. Unigram Tokenization

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.

1prerequisites
2next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseCompare ordered BPE merges with unigram path search on the same string, then predict which tokenizer uses fewer tokens and why.

This Attention & Transformers concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to Raw Text to Packed Causal-LM Examples (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources4 cited
Codeattached
Demolive
Reviewed2026-07-03
Updatedpage 2026-07-03

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptBPE vs. Unigram TokenizationAttention & Transformers
4 sources attachedLocal snapshot ready
concept:attention-transformers/bpe-vs-unigram-tokenization
01

01

Intuition

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

Section prompt

BPE and unigram tokenizers can both produce subword tokens, but they answer different questions.

BPE asks: "Given the merge rules I learned, what happens if I replay those rules on this string?" The order matters. A merge that happens early can create a larger symbol that a later rule can use.

Unigram tokenization asks: "Among all segmentations allowed by my candidate vocabulary, which path has the best score?" It does not replay one ordered merge list. It searches over possible token paths and chooses the segmentation with the highest product of token probabilities, or equivalently the lowest sum of negative log probabilities.

That distinction matters when a string has several plausible pieces. A BPE tokenizer may keep the split created by its historical merge order, while a unigram tokenizer may prefer a different segmentation because one whole piece has a better score.

This page uses a deliberately tiny example so the split is inspectable. It is a teaching model, not a production tokenizer.

Source spine: Sennrich, Haddow, and Birch, Neural Machine Translation of Rare Words with Subword Units; Kudo and Richardson, SentencePiece; Hugging Face course notes on BPE and Unigram tokenization.

02

02

Math

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

Section prompt

For BPE, start with characters and apply the learned merge rules in order:

s(0)=characters(x)s^{(0)} = \text{characters}(x) s(k+1)=merge(s(k),ak,bk).s^{(k+1)} = \operatorname{merge}\left(s^{(k)}, a_k, b_k\right).

Here (ak,bk)(a_k,b_k) is the kk-th learned merge pair. Encoding is deterministic once the vocabulary, merge list, pre-tokenization, and normalization are fixed.

For unigram tokenization, assume a candidate vocabulary V\mathcal V and token probabilities p(t)p(t) for each tVt \in \mathcal V. A segmentation is a sequence of tokens t1:mt_{1:m} whose concatenation is the input string xx:

t1t2tm=x.t_1 \Vert t_2 \Vert \cdots \Vert t_m = x.

The best unigram segmentation is

t^1:m=argmaxt1:m:concat(t1:m)=xi=1mlogp(ti).\hat t_{1:m} = \arg\max_{t_{1:m}: \operatorname{concat}(t_{1:m})=x} \sum_{i=1}^{m} \log p(t_i).

Equivalently, using costs c(t)=logp(t)c(t)=-\log p(t), it minimizes total path cost:

t^1:m=argmint1:m:concat(t1:m)=xi=1mc(ti).\hat t_{1:m} = \arg\min_{t_{1:m}: \operatorname{concat}(t_{1:m})=x} \sum_{i=1}^{m} c(t_i).

A dynamic program computes this by scanning positions in the string:

D[j]=min0i<j,  xi:jVD[i]+c(xi:j).D[j]= \min_{0 \le i < j,\; x_{i:j}\in\mathcal V} D[i]+c(x_{i:j}).

The backpointer that achieved the minimum tells us the final segmentation.

SentencePiece-style unigram training starts with many candidate pieces and prunes pieces whose removal hurts likelihood least. The demo below does not train that model. It shows the inference-time choice once a small scored vocabulary is already given.

03

03

Code

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

Section prompt

This small script compares ordered BPE merges with unigram path search on the same word.

from math import inf

word = "unhugs"
merges = [("u", "g"), ("u", "n"), ("h", "ug"), ("p", "un")]
cost = {
    "un": 1.10, "hugs": 1.35, "hug": 1.25, "s": 1.80,
    "u": 3.20, "n": 3.20, "h": 3.20, "g": 3.20, "ug": 2.10,
}

def apply_merge(parts, pair):
    out, i = [], 0
    while i < len(parts):
        if i + 1 < len(parts) and (parts[i], parts[i + 1]) == pair:
            out.append(parts[i] + parts[i + 1])
            i += 2
        else:
            out.append(parts[i])
            i += 1
    return out

def bpe_encode(text):
    parts = list(text)
    for pair in merges:
        parts = apply_merge(parts, pair)
    return parts

def unigram_encode(text):
    dp = [(inf, -1) for _ in range(len(text) + 1)]
    dp[0] = (0.0, 0)
    for end in range(1, len(text) + 1):
        for start in range(end):
            token = text[start:end]
            if token in cost and dp[start][0] + cost[token] < dp[end][0]:
                dp[end] = (dp[start][0] + cost[token], start)
    tokens, pos = [], len(text)
    while pos:
        start = dp[pos][1]
        tokens.append(text[start:pos])
        pos = start
    return list(reversed(tokens)), dp[-1][0]

print("BPE:", bpe_encode(word))
print("Unigram:", unigram_encode(word))

BPE returns ["un", "hug", "s"] because those pieces are created by the ordered merge list. The unigram path search returns ["un", "hugs"] because that two-piece path has lower total cost in the given scored vocabulary.

04

04

Interactive Demo

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

Section prompt

Prediction check: inspect the same input string and the candidate unigram pieces, then predict which tokenizer uses fewer tokens and which unigram segmentation has the lowest path cost before revealing the ordered BPE replay and the Viterbi-style path search.

The lab hides the final BPE segmentation, path costs, winning unigram path, token counts, and explanation until you commit. The goal is to feel the difference between a deterministic merge history and a scored segmentation search.

Live Concept Demo

Explore BPE vs. Unigram Tokenization

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 BPE vs. Unigram Tokenization 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

Compare ordered BPE merges with unigram path search on the same string, then predict which tokenizer uses fewer tokens and why.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change BPE vs. Unigram Tokenization should make visible.

Visual Inquiry

Make the image answer a mathematical question

Compare ordered BPE merges with unigram path search on the same string, then predict which tokenizer uses fewer tokens and why.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make BPE vs. Unigram Tokenization easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

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

Primary source for BPE as open-vocabulary subword modeling through repeated frequent symbol-pair merges.

Open source
paper · 2018SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text ProcessingKudo and Richardson

Primary source for SentencePiece, raw-sentence subword model training, and the BPE/unigram tokenizer-family distinction.

Open source
course-notes · 2026Hugging Face LLM Course: Byte-Pair Encoding tokenizationHugging Face

Course source for the tiny hug/pug/pun/bun/hugs BPE merge walkthrough that anchors the BPE side of the demo.

Open source
course-notes · 2026Hugging Face LLM Course: Unigram tokenizationHugging Face

Course source for unigram segmentation as a scored path search, including Viterbi-style best-path computation and pruning intuition.

Open source

Claim Review

Compare ordered BPE merges with unigram path search on the same string, then predict which tokenizer uses fewer tokens and why.

Status1 substantive review recorded

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

Sources4 references

sennrich-2016-bpe-subword, kudo-richardson-2018-sentencepiece, hf-llm-course-bpe, hf-llm-course-unigram

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Practice Loop

Try the idea before it explains itself

Compare ordered BPE merges with unigram path search on the same string, then predict which tokenizer uses fewer tokens and why.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in BPE vs. Unigram Tokenization.

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 research drawerClose
ConceptBPE vs. Unigram TokenizationAttention & Transformers
Runnable code comparisonBPE vs. Unigram Tokenization runnable code 1word = "unhugs"Prediction before revealBPE vs. Unigram Tokenization interactive demoManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes BPE vs. Unigram Tokenization click without losing the math?Local snapshot ready

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

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

conceptAttention & Transformers

BPE vs. Unigram Tokenization

Attached question

What is the smallest example that makes BPE vs. Unigram Tokenization 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 in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code 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 - BPE vs. Unigram Tokenization Selected item key: recorded for copy. Context: Attention & Transformers Page anchor: recorded for copy. Open question: What is the smallest example that makes BPE vs. Unigram Tokenization click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code 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.

View it in context
concept/concept-notebook/attention-transformers/bpe-vs-unigram-tokenization concept:attention-transformers/bpe-vs-unigram-tokenization