Tokenization

A language model never sees letters. GPT-2 reads “strawberry” as 3 tokens, st · raw · berry, so no single r ever reaches the model.

Pick a word, then pick a tokenizer. Count the boxes and look for the letter r. Then we build, piece by piece, the tokenizers that cut text this way: BPE, WordPiece, Unigram and byte-level BPE.

You need to know that text is a string of characters and that a model takes a list of integers. A little Python helps for the code. We build the rest from zero.

Every real split on this page comes from running the tokenizers themselves. GPT-2, GPT-4 (cl100k_base) and GPT-4o (o200k_base) through OpenAI's tiktoken, and BERT, T5 and Llama through Hugging Face tokenizers. The toy BPE runs live in your browser.

Cut one word four ways

The dot · marks a space. GPT-2 and GPT-4 splits are real outputs of tiktoken's gpt2 and cl100k_base encodings; boxes like <F0 9F> are raw bytes. The word tokenizer is illustrative: a dictionary of common English words, so made-up words, numbers and emoji map to [UNK].

Chapter 0

The Vocabulary Problem

Turn text into integers, and see why neither whole words nor single letters work

You type “unbelievable” into a chatbot. The model inside cannot read it. It takes a list of integers and predicts the next integer. So a program must first cut your text into pieces called tokens and give each piece an integer ID. That program is the tokenizer.

The first idea is a dictionary of words: “cat” gets 5, “dog” gets 6. Then a user types “covfefe”. The word has no ID. This is the out-of-vocabulary (OOV) problem. A word tokenizer maps every such word to one catch-all ID, [UNK], and the word is lost.

The second idea is letters. About a hundred characters cover English, and no word is ever missing. But “unbelievable” becomes 12 tokens, and every input gets several times longer. Each extra token costs compute and memory in every layer of the model.

The device runs a real byte-pair encoding (BPE) tokenizer, trained on a 1,045-character text. Each merge fuses two pieces into one new token. With 0 merges it is a character tokenizer. With all 276 merges, every word of the training text is one token.

Slide from letters to words

Yellow is the length of the training text in tokens. Purple is the vocabulary size. The row below cuts a sentence the tokenizer never saw. Drag the merges.

30

Real BPE, run live on a toy 1,045-character English text written for this page (the same engine as Chapter 8). The dot · marks a space.

The two curves move in opposite directions. Fewer tokens need a bigger vocabulary. A subword tokenizer sits in the middle: common words stay whole, rare words split into pieces, and single characters catch the rest. At the far right the word list fails on “zebra”; BPE spells it from single letters and loses nothing.

The failure: symptom, measurement, fix

The symptom is a model that talks nonsense about a new name or a typo. To measure it, count the [UNK] IDs in your tokenized inputs; any count above zero is lost text. The fix is a subword tokenizer whose base alphabet covers every input. Chapter 6 makes that alphabet the 256 byte values.

The road

  1. Characters versus words: count one sentence three ways, and price its length.
  2. The subword idea: spend tokens where text is, and pay for each vocabulary entry.
  3. BPE from scratch: count pairs, merge the top one, repeat.
  4. Encoding and decoding: replay the merges on new text, and measure compression.
  5. WordPiece and Unigram: two other rules for picking pieces.
  6. Byte-level BPE: 256 bytes as the alphabet, and the cost for other languages.
  7. Spaces and special tokens: SentencePiece, byte fallback, and what survives a round trip.
  8. Live tokenizer: train BPE on two texts and type anything.
  9. Field guide: numbers, code, sources and links.
Why is a pure word-level tokenizer a poor choice for a general language model?

Chapter 1

Characters versus Words, by the Numbers

Count one sentence three ways and see why length is the cost that matters

Take one sentence: “The unbelievable cat.” It has 21 characters, with the two spaces and the full stop.

A word tokenizer gives 4 tokens: The, unbelievable, cat and the full stop. A character tokenizer gives 21. The real GPT-2 tokenizer also gives 4, because “·unbelievable”, with its leading space, is one entry in its vocabulary.

Why does the count matter? Inside a transformer, self-attention lets each token look at every other token. Call the number of tokens n. Each of the n tokens compares itself with all n tokens, itself included. Call the number of comparisons A, the attention pairs.

Say it aloud

A equals n times n.

A
A the attention pairs: comparisons in one attention layer, for one head.
n
n the number of tokens in the input.
×
times every token meets every token, so the count is a square.
n
n the same count again: the tokens each one compares against.
In plain words

Count the tokens n. Multiply n by itself. That is A, the work one attention layer does on this input.

With numbers

Characters: n = 21, so A = 441. Words: n = 4, so A = 16. The character version does 441 / 16, about 28 times the attention work for the same sentence.

Count the pairs

The boxes are the tokens. Each yellow cell is one attention pair. Pick a tokenizer and a sentence.

GPT-2 splits are real tiktoken output. The square counts pairs for one head of one layer. A decoder also masks future tokens, which halves the count but keeps the square.

The rest of the network grows in step with n, not with its square. Even there, 21 tokens cost about 5 times as much as 4.

The failure: symptom, measurement, fix

The symptom is a long document that does not fit. GPT-2 reads at most 1,024 tokens. At one character per token that is 1,024 characters. To measure, divide characters by tokens on your own text. GPT-2 packs 4.7 characters per token on an ordinary English paragraph, so its window holds about 4,800 characters. The fix is a tokenizer with enough merges for your kind of text.

The same sentence is 4 tokens one way and 21 tokens another way. About how much more attention work does the 21-token version need?

Chapter 2

The Subword Idea

Spend whole tokens on frequent words, pieces on rare ones, and pay for every entry in the vocabulary

Word frequency has a long tail. In the training text of Chapter 0, “the” appears 42 times in 212 words, and most words appear once. This pattern is Zipf's law: the word at rank r appears about 1/r as often as the most common word.

So spend the vocabulary where the text is. A frequent word earns its own token, because it saves tokens every time it appears. Shared pieces build a rare word. If the pieces are missing too, it falls back to single characters, so nothing is out of vocabulary.

Spend the merge budget

Bar height is how often each word appears. A warm bar is one token; a blue bar shows how many pieces the word still needs. Drag the merges.

12

The same live BPE and toy text as Chapter 0. Each word is cut as it appears inside a sentence, with its leading space.

The first merges go to the most frequent words. Why not merge everything? Each vocabulary entry costs parameters. The model keeps one vector of numbers per token in an embedding table. Call the vocabulary size V and the length of each vector d. Call the table's parameter count E.

Say it aloud

E equals V times d.

E
E the parameters in the embedding table.
V
V the vocabulary size: how many different tokens exist.
×
times one full vector for each token.
d
d the width of the model: numbers in each token's vector.
In plain words

Take the vocabulary size V. Multiply by the vector width d. That is E, the parameters spent on looking up tokens.

With numbers

GPT-2 small: V = 50,257 and d = 768. E = 50,257 × 768 = 38,597,376, about 38.6 million. The whole model has about 124 million parameters, so about a third of it is the token table.

A rare token also trains badly. Its vector gets an update only when the token appears, so a token seen a few times stays close to random.

The failure: symptom, measurement, fix

The symptom is a token the model handles strangely. “·SolidGoldMagikarp” is one GPT-2 token (ID 43453); in 2023 people found that GPT models behaved oddly on it and similar tokens. To measure, count how often each token ID appears in the model's training data; IDs near zero are under-trained. The fix is to train the tokenizer on text like the model's training text, or to use fewer merges.

Why can a subword tokenizer promise that no word is out of vocabulary?

Chapter 3

Byte-Pair Encoding, From Scratch

Train a tokenizer by hand: count adjacent pairs, merge the most frequent, repeat

BPE began as a data compression method by Philip Gage in 1994. Sennrich, Haddow and Birch used it in 2016 to build subword vocabularies for translation. The rule fits in one line: find the most frequent pair of adjacent symbols, and merge it into one new symbol. Repeat until the budget is spent.

The training text is the example in Sennrich's paper: “low” 5 times, “lower” 2 times, “newest” 6 times and “widest” 3 times. Split each word into characters. Add an end-of-word marker • so the tokenizer knows where a word stops. The text is now 95 symbols: 79 letters and 16 markers.

Which pair do we merge? Call the number of times word w appears fw. Call the number of times symbol b directly follows symbol a inside word w nw(a, b). The pair count c(a, b) adds these up over the whole text.

Say it aloud

c of a b equals the sum over words w of f-w times n-w of a b.

c(a, b)
c of a b the pair count: how often a sits directly before b in the whole text.
Σw
the sum over words w add one term for each different word.
fw
f-w how many times word w appears: 5 for “low”.
·
times each copy of the word adds its pairs again.
nw(a, b)
n-w of a b how many times the pair a b occurs inside one copy of word w.
In plain words

For each word, count the places where b directly follows a. Multiply by the word's frequency f-w. Add over all words. The pair with the largest c(a, b) is the next merge.

With numbers

Pair e s: “newest” gives 6 × 1 and “widest” gives 3 × 1, so c(e, s) = 9. Pair l o: 5 + 2 = 7. Three pairs tie at 9 (e s, s t and t •). Our rule takes the pair it met first, e s.

Train BPE one merge at a time

The bars are the top pair counts; the pink one wins. Press Next merge and watch “newest” and “widest” share the piece “est•”.

The four words and counts are the worked example in Sennrich et al. (2016), Algorithm 1. The page computes every count live; ties go to the pair met first, scanning the words in order.

pythonfrom collections import Counter

def pair_counts(words):                 # words: {tuple of symbols: frequency}
    c = Counter()
    for sym, f in words.items():
        for a, b in zip(sym, sym[1:]):
            c[(a, b)] += f                   # c(a, b) = sum of f_w * n_w(a, b)
    return c

def merge(words, pair):
    out = {}
    for sym, f in words.items():
        new, i = [], 0
        while i < len(sym):
            if sym[i:i+2] == pair:
                new.append(sym[i] + sym[i+1]); i += 2
            else:
                new.append(sym[i]); i += 1
        out[tuple(new)] = f
    return out

words = {tuple(w) + ("•",): f for w, f in
         [("low", 5), ("lower", 2), ("newest", 6), ("widest", 3)]}
merges = []
for _ in range(12):                       # the budget: 12 merges
    c = pair_counts(words)
    best = max(c, key=c.get)                 # ties: the pair met first
    words = merge(words, best); merges.append(best)
# merges[:5] == [('e','s'), ('es','t'), ('est','•'), ('l','o'), ('lo','w')]

After 12 merges each of the four words is one token, and the text is 22 tokens. The ordered merge list is the whole tokenizer. Its length is the one setting you choose.

The failure: symptom, measurement, fix

The pair count runs over all text at once. If most of the text is English, English pairs win almost every merge, and other languages stay cut into many small tokens. To measure, tokenize the same sentences in each language and compare the counts. One fix is Parity-aware BPE, where the language that compresses worst picks each merge; Session 1 of CS 8803 builds it.

What decides which pair BPE merges at each training step?

Chapter 4

Encoding and Decoding New Text

Cut a word that training never saw by replaying the merges in order, then measure the compression

Training produced an ordered list of 12 merges:

  1. e+s
  2. es+t
  3. est+•
  4. l+o
  5. lo+w
  6. n+e
  7. ne+w
  8. new+est•
  9. low+•
  10. w+i
  11. wi+d
  12. wid+est•

To encode a new word, start from its characters and apply the merges in training order. Each merge fuses every place its pair appears. A merge whose pair is absent does nothing.

Take “newer”, which training never saw: n e w e r •. Merges 1 to 5 find nothing. Merge 6 gives ne w e r •. Merge 7 gives new e r •. No later merge fits. The result is 4 tokens: new, e, r, •.

Replay the merges

The twelve chips are the merges in order. Pink fits and fires; grey finds no pair. Pick a word and press Step.

The merges are the twelve learned in Chapter 3, computed live. “lowest” is never in the training text, yet it reuses “low” and “est•”.

Order matters because a merge can only use symbols that earlier merges built. Merge 8 needs “est•”, which exists only after merge 3. Decoding runs the other way: look up the string of each ID, join the strings, and turn each • back into a space. It needs no search.

How much did training shrink the text? Call the number of characters C and the number of tokens T. The compression ratio CR is characters per token.

Say it aloud

CR equals C over T.

CR
C-R the compression ratio: characters carried by one token, on average.
C
C the number of characters in the text, spaces included.
T
T the number of tokens the tokenizer makes from that text.
In plain words

Count the characters C. Tokenize and count the tokens T. Divide C by T. A higher CR means each token carries more text.

With numbers

The toy text has C = 95 (each • stands for a space). Before training T = 95, so CR = 1.0. After 12 merges T = 22, so CR = 95 / 22 = 4.3. A real check: a 222-character English paragraph is 46 tokens in GPT-4's tokenizer, so CR = 4.8.

The failure: symptom, measurement, fix

The symptom is fluent nonsense after someone swaps a tokenizer file. The model learned one ID per piece; a different tokenizer sends different IDs. To measure, encode a fixed test string with both tokenizers and compare the ID lists. The fix is to load the tokenizer saved with the model checkpoint, and to check that decode(encode(text)) equals the text.

Why must a BPE encoder apply the merges in the order training learned them?

Chapter 5

WordPiece and Unigram

Change the rule that picks pieces: score pairs by how tightly they stick, or prune a big vocabulary from the top

WordPiece (Schuster and Nakajima, 2012), the tokenizer of BERT, also merges pairs. It takes the pair whose parts appear together much more often than apart. Call the count of the joined pair c(ab), and the counts of its parts c(a) and c(b).

Say it aloud

score of a b equals c of a-b over, c of a times c of b.

score(a, b)
score of a b how tightly a and b stick together. WordPiece merges the top pair.
c(ab)
c of a-b the pair count from Chapter 3: a directly before b.
c(a)
c of a how often symbol a appears anywhere.
×
times the product grows when both parts are common, which lowers the score.
c(b)
c of b how often symbol b appears anywhere.
In plain words

Count the pair, c(ab). Divide by the product of the part counts, c(a) times c(b). A pair whose parts seldom appear apart gets a high score.

With numbers

On the Chapter 3 text, i d has c(id) = 3, c(i) = 3 and c(d) = 3. Its score is 3 / 9 = 0.33. For e s it is 9 / (17 × 9) = 0.059. BPE merges e s first; WordPiece merges i d first, because i and d never appear apart.

Rank the first merge two ways

Each bar is one adjacent pair in the four-word text. Pink is the pair each rule merges first.

The page counts Sennrich's four words live. Google never published WordPiece training code; this score follows Hugging Face's description of it.

BERT marks a piece inside a word with ##. Its 30,522-entry vocabulary cuts “embeddings” into em · ##bed · ##ding · ##s. To encode, it takes the longest piece that matches from the left, then repeats.

Unigram (Kudo, 2018) goes the other way. It starts from many candidate pieces and removes those whose loss hurts the training text least, until the vocabulary fits. A word can be cut many ways. Call a cut’s pieces x1 to xm, each with probability p(xi).

Say it aloud

P of the cut equals the product over i of p of x-i.

P(cut)
P of the cut how likely this way of cutting the word is.
Πi
the product over i multiply one factor for each piece, i from 1 to m.
p(xi)
p of x-i the probability of piece number i, learned in training.
In plain words

Look up the probability p of each piece x-i in the cut. Multiply them. The tokenizer keeps the cut with the largest product.

With numbers

With made-up probabilities: “hello” as one piece has P = 0.002. he · llo has P = 0.04 × 0.02 = 0.0008. The whole piece wins. Remove “hello” from the vocabulary and he · llo becomes the best cut.

Prune a piece

Each bar is one way to cut “hello”; pink is the likeliest. Switch pieces off to prune them.

Illustrative: twelve made-up piece probabilities. Bar length follows the log of the probability.

The Viterbi algorithm finds the best cut without listing them all. In training, Unigram can also sample a random cut, which Kudo calls subword regularization.

MethodDirectionPicks byUsed by (checked)
BPEmerge upwardlargest pair countGPT-2, GPT-4, Llama
WordPiecemerge upwardcount over product of part countsBERT
Unigramprune downwardleast loss of likelihoodT5, ALBERT

The failure: symptom, measurement, fix

BERT has no piece for “🍓”, so it becomes [UNK]. To measure, count ID 100, the [UNK] of bert-base-uncased. The fix is a base alphabet that covers everything: the next chapter.

How does Unigram differ from BPE?

Chapter 6

Byte-Level BPE

Make the base alphabet the 256 byte values, so no input is ever out of vocabulary

Subwords fall back to characters. But Unicode holds far more than a hundred characters: emoji, Chinese, Devanagari, maths signs. Put them all in the base and the vocabulary bloats. Leave them out and they become [UNK], as BERT does with 🍓.

GPT-2 (Radford et al., 2019) runs BPE on bytes instead. UTF-8, the common text encoding, writes each character as 1 to 4 bytes, and a byte has 256 possible values. With all 256 in the base vocabulary, any text in any script has a tokenization.

Follow text down to bytes

Top row: characters. Middle: their UTF-8 bytes. Bottom: GPT-2's tokens. Pick a text.

Bytes are computed live with your browser's UTF-8 encoder. GPT-2 tokens are real tiktoken output; a token that holds only part of a character is shown as its bytes.

How big is such a vocabulary? It starts with 256 byte tokens. Call the number of merges M and the number of hand-added special tokens S. Call the vocabulary size V.

Say it aloud

V equals two hundred fifty-six plus M plus S.

V
V the vocabulary size: the number of token IDs.
256
two hundred fifty-six one token for each possible byte value, 0 to 255.
M
M the number of merges; each one adds one token.
S
S the special tokens added by hand, such as end of text.
In plain words

Start from the 256 byte tokens. Add one token for each merge M. Add the special tokens S. The total is V.

With numbers

GPT-2: 256 + 50,000 merges + 1 special token (<|endoftext|>) = 50,257. That is the vocabulary size in the hero.

Bytes make coverage universal, but not fair. A Devanagari character is 3 bytes, and a tokenizer trained mostly on English has few merges for those bytes.

Pay the language tax

One sentence, “The weather is nice today”, in three languages. Bar length is its token count. Switch the tokenizer.

Token counts are real tiktoken output for gpt2, cl100k_base and o200k_base. The French and Hindi sentences are this page's own translations.

GPT-2 needs 27 tokens for the Hindi sentence and 6 for the English one: 4.5 times the price and 4.5 times the context. GPT-4o's tokenizer, with about 200,000 entries, needs 5. Parity-aware BPE attacks the same gap at training time (CS 8803, Session 1).

The failure: symptom, measurement, fix

The symptom is bad arithmetic on long numbers. To measure, tokenize numbers: GPT-2 cuts 1234567 into 123 · 45 · 67 and GPT-4 into 123 · 456 · 7, so one digit position lands in different tokens. One fix is in the Llama tokenizer: it splits every number into single digits.

What does byte-level BPE fix that character-level BPE does not?

Chapter 7

SentencePiece, Spaces and Special Tokens

Treat the space as a symbol, check what survives a round trip, and reserve IDs for structure

Older tokenizers split text on spaces first, then cut each word. That loses how many spaces there were. It also fails for Chinese and Japanese, which do not put spaces between words.

SentencePiece (Kudo and Richardson, 2018) is a library that skips the split. It treats raw text as one stream, writes each space as the visible marker ▁, and runs BPE or Unigram on everything. The space becomes part of a token: ▁world.

GPT-2 does the same thing its own way: a word carries its leading space. “hello” is ID 31373 and “·hello” is ID 23748. So a prompt that ends in a space changes which token is likely next.

Run the round trip

Top row: tokens. Middle: their IDs. Bottom: the text you get back by decoding. Pick a tokenizer and an input.

Real output of bert-base-uncased, google-t5/t5-small and the Llama tokenizer (32,000 entries) in Hugging Face tokenizers. “Hello  world” has two spaces.

Llama gives back “Hello  world” with both spaces. It writes 🍓 as four byte tokens, <0xF0> <0x9F> <0x8D> <0x93>. That is byte fallback: a SentencePiece option that spells a character missing from the vocabulary as its UTF-8 bytes. T5 is also SentencePiece, but its settings drop the second space and map 🍓 to its unknown token. So SentencePiece is lossless only when its settings make it so.

Every vocabulary also holds special tokens that no merge produced. GPT-2 has <|endoftext|> (ID 50256). BERT has [CLS] (101), [SEP] (102), [PAD] (0) and [UNK] (100). Chat models add markers for each turn. They get fixed IDs, and the model learns their meaning in training.

The failure: symptom, measurement, fix

One symptom is code whose indentation breaks after a tokenize and decode step. Another is a user message that ends a chat early because it contains the text of a special token. To measure, assert decode(encode(x)) == x on test strings with double spaces, tabs and emoji. The fix is a lossless tokenizer, and refusing special-token text in user input; tiktoken raises an error on “<|endoftext|>” unless you allow it.

Llama returns “🍓” exactly after encoding and decoding, but T5 does not. Why?

Chapter 8

Live Tokenizer

Train BPE on English prose or on Python code, type anything, and watch the budget and the data change the count

This tokenizer trains in your browser. Choose its training text and its merge budget, then type. Every number below is computed live.

Type and tokenize

Warm boxes are learned tokens, blue boxes are single characters, red boxes are characters the training text never had. Type in the box.

100

Toy BPE on toy texts written for this page, with a GPT-2 style rule that keeps a leading space on each word. Real tokenizers learn tens of thousands of merges from billions of characters.

  1. Set the merges to 0. Every character is a token, and the count is the length of your text.
  2. Raise the merges. Frequent pairs fuse first, then whole common words. The count falls and the compression ratio rises.
  3. Press Rare word. Words the training text never had fall back to characters. A character it never had, like “é”, turns red: this toy has no byte base.
  4. Press Python line, then switch the training text. The Python-trained tokenizer cuts code into few tokens and English into many; the English one does the reverse.

The last step is the lesson of this chapter. A tokenizer is only as good as the match between its training text and your text. That is why a code model wants a tokenizer trained on code, and why Chapter 6's Hindi sentence cost 27 GPT-2 tokens.

A tokenizer trained only on Python code tokenizes an English sentence. What do you expect?

Chapter 9

Field Guide

Keep the terms, the numbers, the checklist and the code in one place

A tokenizer turns text into integer IDs. Subword tokenizers keep common words whole and split rare ones, with a base alphabet that catches everything. BPE learns an ordered merge list from pair counts and replays it to encode. WordPiece and Unigram change how pieces are picked. Byte-level BPE makes the base 256 bytes. The tokenizer decides the length, the cost and what the model can see.

Term or numberMeaningValue here
Token, IDa piece of text, and its integer“·hello” is 23748 in GPT-2
OOV, [UNK]no ID for the input; text is lostBERT: 🍓 becomes ID 100
Attention pairsA = n × n21 tokens: 441; 4 tokens: 16
Embedding tableE = V × dGPT-2 small: 38.6 million of about 124 million
Pair countc(a, b) = Σw fw · nw(a, b)c(e, s) = 9 in Sennrich's example
Compression ratioCR = C / T, characters per tokentoy 4.3; GPT-4 on English 4.8
WordPiece scorec(ab) / (c(a) × c(b))i d: 0.33; e s: 0.059
Unigram cutP(cut) = Πi p(xi)he · llo: 0.0008 (made up)
Byte-level sizeV = 256 + M + SGPT-2: 256 + 50,000 + 1 = 50,257
Vocabulary sizesas loaded from the real filesBERT 30,522 · T5 32,100 · Llama 32,000 · GPT-4 cl100k about 100k · GPT-4o o200k about 200k
Language taxsame sentence, different costHindi 27 vs English 6 tokens (GPT-2)

Checklist before you train or ship

  1. Count [UNK] IDs on real inputs. The target is 0.
  2. Check decode(encode(x)) == x on double spaces, tabs, emoji and every script you serve.
  3. Measure characters per token for each language and domain you serve.
  4. Load the tokenizer saved with the checkpoint, never a look-alike.
  5. Refuse special-token text in user input.
  6. Look at how numbers are cut before you trust arithmetic.

The core, in code

pythonfrom collections import Counter

def train_bpe(word_freqs, n_merges):        # word_freqs: {"low": 5, ...}
    words = {tuple(w) + ("•",): f for w, f in word_freqs.items()}
    merges = []
    for _ in range(n_merges):
        c = Counter()
        for sym, f in words.items():
            for pair in zip(sym, sym[1:]):
                c[pair] += f
        if not c: break
        best = max(c, key=c.get)
        merges.append(best)
        words = {apply(sym, best): f for sym, f in words.items()}
    return merges

def apply(sym, pair):                         # fuse every a, b into ab
    out, i = [], 0
    while i < len(sym):
        if sym[i:i+2] == pair: out.append(sym[i] + sym[i+1]); i += 2
        else: out.append(sym[i]); i += 1
    return tuple(out)

def encode(word, merges):                     # replay in training order
    sym = tuple(word) + ("•",)
    for pair in merges:
        sym = apply(sym, pair)
    return list(sym)

def decode(tokens):
    return "".join(tokens).replace("•", " ")

merges = train_bpe({"low": 5, "lower": 2, "newest": 6, "widest": 3}, 12)
print(encode("newer", merges))                # ['new', 'e', 'r', '•']

import tiktoken                                 # the real thing
enc = tiktoken.get_encoding("gpt2")
print(enc.n_vocab, enc.encode("strawberry"))  # 50257, three IDs: st, raw, berry

Keep going

Sources

  1. Philip Gage, “A New Algorithm for Data Compression”, The C Users Journal, 1994.
  2. Sennrich, Haddow and Birch, “Neural Machine Translation of Rare Words with Subword Units”, ACL 2016. arXiv:1508.07909
  3. Schuster and Nakajima, “Japanese and Korean Voice Search”, ICASSP 2012 (WordPiece).
  4. Taku Kudo, “Subword Regularization”, ACL 2018. arXiv:1804.10959
  5. Kudo and Richardson, “SentencePiece”, EMNLP 2018 demo. arXiv:1808.06226
  6. Radford et al., “Language Models are Unsupervised Multitask Learners” (GPT-2), 2019.
  7. Foroutan et al., “Parity-Aware Byte-Pair Encoding”, 2025. arXiv:2508.04796
  8. OpenAI tiktoken and Hugging Face tokenizers: every real split on this page.
The takeaway. A tokenizer is a learned shorthand applied in a fixed order, with a base alphabet as the safety net. It sets the length, the price and what the model can see.

Teach it back: open Present or Teach and train BPE on “low, lower, newest, widest” out loud. Then go back to the strawberry and predict each tokenizer's count before you press it.

Tokenization: BPE, WordPiece and SentencePiece
Sennrich et al., 2016 · Back to Gleams