esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

How Do Tokenizers Work?

How BPE, WordPiece and SentencePiece cut text into tokens, what each one does differently, and how to explain it for your AI interview.

In short

A tokeniser cuts text into pieces called tokens and gives each piece a number. BPE and WordPiece differ in how they pick the next pair to join: BPE takes the most common pair, WordPiece the most informative. SentencePiece is a library that runs BPE or Unigram directly on raw text.

11 min readIntermediateVery common · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

A tokeniser cuts text into tokens, pieces that are often parts of words, and gives each one a number. BPE builds its pieces by joining the most common pairs of neighbours, over and over. WordPiece picks pairs that appear together more than chance predicts. SentencePiece works straight on raw text, so it suits languages without spaces. The model never sees letters, only the numbers.

What is a tokeniser, in plain words?

A computer does not read words the way you do. It needs numbers. A tokeniser turns text into numbers in two steps: it cuts the text into pieces, called tokens, then looks each piece up in a fixed list, the vocabulary, to find its number.

Think of a records clerk at an insurer. For a long, common company name she writes a short code she already knows. For a rare name she spells out the parts. A tokeniser works the same way: common chunks get short codes, and rare words are spelled in smaller pieces.

A claims assistant that reads the word reimbursement in thousands of notes may store it as several pieces. So one note can use more tokens than its word count suggests.

Key words

Token
One piece of text the model reads as a unit. It can be a word, part of a word or one character.
Vocabulary
The fixed list of tokens a model knows, each with its own number.
Merge rule
A learned instruction: join this pair of neighbouring pieces into one piece.
Subword
A piece smaller than a whole word, such as a prefix or an ending.

How does BPE build its vocabulary?

BPE learns its vocabulary from a large pile of text. It starts with single characters, so every letter is already a token. Then it repeats one job: count which two neighbouring pieces appear together most, glue them into one new piece, and add that piece to the list.

Hugging Face's documentation puts the first step in one line: "BPE starts with individual characters and iteratively merges the most frequent adjacent pair."

  1. 1

    Start with characters

    Every letter is its own token, so the vocabulary is just the letters.

  2. 2

    Join the most common pair

    Say i and m often sit side by side. Glue them into im, then count again.

  3. 3

    Stop at the target size

    Repeat until the vocabulary reaches the size the team chose. Then apply the same rules to new text.

Here is a small version on a few claim-note words. It learns six merges, and the chart shows how two words split at four stages of the run.

Two claim words, cut one merge at a time (small BPE run)

Start: single characters

c l a i m s

claims: 6 pieces

r e i m b u r s e m e n t

reimbursement: 13 pieces

After merge 1: i + m

c l a im s

claims: 5 pieces

r e im b u r s e m e n t

reimbursement: 12 pieces

After merge 4: claim is one piece

claim s

claims: 2 pieces

r e im b u r s e m e n t

reimbursement: 12 pieces

After merge 5: n + t

claim s

claims: 2 pieces

r e im b u r s e m e nt

reimbursement: 11 pieces

  1. 1Merge 1 glues i and m together, in both words.
  2. 2Merges 2 to 4 join the letters of claim into one piece.
  3. 3Merge 5 joins n and t at the end of reimbursement.
The two claim words at four stages of the small run, side by side. Each box holds one word's pieces, and the arrows show the merges that change them. A real tokeniser learns far more merges from far more text.

How do WordPiece and SentencePiece differ from BPE?

All three split words into subword pieces. They differ in how they choose which pair to join next, and in whether they need words split by spaces first.

  • BPE

    Join the most common pair

    Counts every pair of neighbours and joins the top one. The Transformers library calls it the most popular method.

  • WordPiece

    Join the most useful pair

    Scores each pair by how often it appears together compared with how often each piece appears alone. BERT-family models use it.

  • SentencePiece

    Work on raw text

    Runs BPE or Unigram straight on the text, so languages without spaces, like Japanese, need no word split first.

From claim note to model input

Claim note

Plain text from the claim

Tokeniser

Cut into pieces

Words, or parts of words

Apply merge rules

Joins pairs learned in training

Token IDs

One number per token

The model

Reads the numbers

  1. 1The raw text goes into the tokeniser.
  2. 2Each piece is joined with the merge rules where they apply.
  3. 3Each final piece is swapped for its number in the vocabulary.
  4. 4The model gets only the numbers, never the letters.
A claim note is cut into pieces, the merge rules join the common ones, and each piece becomes a number. The model reads only those numbers.

Google's 2016 translation paper calls its sub-word units wordpieces. It says this splitting balances the flexibility of character-level models with the efficiency of word-level ones.

  • “encoding rare and unknown words as sequences of subword units”

    Sennrich, Haddow and Birch (arXiv 2015, ACL 2016)

  • “we divide words into a limited set of common sub-word units ("wordpieces") for both input and output.”

    Wu et al., Google (arXiv 2016)

Byte-level BPE starts from the 256 possible byte values, so any text can be spelled out and no special unknown token is needed. OpenAI's library describes itself as "tiktoken is a fast BPE tokeniser for use with OpenAI's models."

What does a merge trace look like in code?

This small BPE learner counts the pairs in a few claim-note words, joins the most common one, and repeats six times. Then it prints how three words split.

Python
# A small BPE learner: six merges on a few claim-note words, then three splits.
from collections import Counter

words = Counter({"claim": 6, "claims": 4, "claimant": 3, "payment": 5, "payout": 2, "reimbursement": 2})
splits = {w: list(w) for w in words}

def pair_counts():
    counts = Counter()
    for w, n in words.items():
        parts = splits[w]
        for pair in zip(parts, parts[1:]):
            counts[pair] += n
    return counts

for step in range(1, 7):
    counts = pair_counts()
    best = max(sorted(counts), key=lambda p: counts[p])
    for w in words:
        out, parts, i = [], splits[w], 0
        while i < len(parts):
            if i + 1 < len(parts) and (parts[i], parts[i + 1]) == best:
                out.append(parts[i] + parts[i + 1])
                i += 2
            else:
                out.append(parts[i])
                i += 1
        splits[w] = out
    print(f"merge {step}: {best[0]} + {best[1]} -> {best[0] + best[1]}")

print(splits["claims"], splits["payout"], splits["reimbursement"])

Output

merge 1: i + m -> im
merge 2: a + im -> aim
merge 3: c + l -> cl
merge 4: cl + aim -> claim
merge 5: n + t -> nt
merge 6: a + y -> ay
['claim', 's'] ['p', 'ay', 'o', 'u', 't'] ['r', 'e', 'im', 'b', 'u', 'r', 's', 'e', 'm', 'e', 'nt']

Read the output from the top. The first merge joins i and m, because that pair shows up most often. By the end, claims is two tokens, claim and s, while the rare word reimbursement is split into eleven pieces. A real tokeniser learns from far more text, so its common pieces are bigger.

How would you check a tokeniser before you pick a model for a claims assistant?

  1. 1

    Use real notes

    Take a few hundred real claim notes, with their policy codes and names, as they really come in.

  2. 2

    Count with the model's own tokeniser

    Run the notes through the tokeniser the model ships with. A count from a different tokeniser is only a guess.

  3. 3

    Look at the hard parts

    Check how claim numbers, policy codes and medical terms split. Long codes tend to become more pieces.

Tip

Say that you compare models on the same notes, each with its own tokeniser. Token counts from one tokeniser do not carry over to another.

What does the interviewer want to hear?

A strong answer covers

  • A plain definition: a tokeniser cuts text into tokens and maps each one to a number.
  • How BPE joins the most common neighbouring pairs, starting from characters.
  • How WordPiece differs: it scores pairs by how informative they are.
  • Why SentencePiece suits languages without spaces.
  • The tokeniser belongs to the model, so it cannot be swapped alone.
  • Counting tokens on a few hundred real notes from the team.

Common traps

  • Trap"Tokens are just words."

    BetterA word can be one token or several. Rare words split into pieces.

  • Trap"Pick the tokeniser with the fewest tokens."

    BetterThe tokeniser comes with the model. Compare models on your own notes, each with its own tokeniser.

  • Trap"Unknown words crash the model."

    BetterSubword tokenisers build unseen words from known pieces, and byte-level ones can spell out any text.

Can you spot the right way to count tokens?

Spot the count

A claims team wants to know how many tokens a note uses. Which line gives the count the model works with?

Quick check

A bank's support bot runs on one model. Its team wants fewer tokens per chat, so they plan to swap in a tokeniser they like better. What should you tell them?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q003What is a token, and why not whole words?11 min
  2. Q005Why do token counts differ across languages and models?10 min
  3. Q006What is an embedding?11 min
  4. Q008What is a context window?11 min
  5. Q009What happens when input is longer than the window?12 min

Learn it in depth

Last updated on 26 November 2026

Building a tool that counts tokens or picks a model?

I design and build AI products and agents, including the interface and the system behind them. Book a short call and tell me what your model and documents look like.