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.
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
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.
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.
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 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.
Chapter 1
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.
A equals n times n.
Count the tokens n. Multiply n by itself. That is A, the work one attention layer does on this input.
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.
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 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.
Chapter 2
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.
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.
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.
E equals V times d.
Take the vocabulary size V. Multiply by the vector width d. That is E, the parameters spent on looking up tokens.
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 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.
Chapter 3
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.
c of a b equals the sum over words w of f-w times n-w of a b.
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.
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.
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 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.
Chapter 4
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:
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, •.
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.
CR equals C over T.
Count the characters C. Tokenize and count the tokens T. Divide C by T. A higher CR means each token carries more text.
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 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.
Chapter 5
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).
score of a b equals c of a-b over, c of a times c of b.
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.
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.
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).
P of the cut equals the product over i of p of x-i.
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 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.
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.
| Method | Direction | Picks by | Used by (checked) |
|---|---|---|---|
| BPE | merge upward | largest pair count | GPT-2, GPT-4, Llama |
| WordPiece | merge upward | count over product of part counts | BERT |
| Unigram | prune downward | least loss of likelihood | T5, ALBERT |
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.
Chapter 6
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.
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.
V equals two hundred fifty-six plus M plus S.
Start from the 256 byte tokens. Add one token for each merge M. Add the special tokens S. The total is V.
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.
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 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.
Chapter 7
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.
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.
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.
Chapter 8
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.
Warm boxes are learned tokens, blue boxes are single characters, red boxes are characters the training text never had. Type in the box.
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.
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.
Chapter 9
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 number | Meaning | Value here |
|---|---|---|
| Token, ID | a piece of text, and its integer | “·hello” is 23748 in GPT-2 |
| OOV, [UNK] | no ID for the input; text is lost | BERT: 🍓 becomes ID 100 |
| Attention pairs | A = n × n | 21 tokens: 441; 4 tokens: 16 |
| Embedding table | E = V × d | GPT-2 small: 38.6 million of about 124 million |
| Pair count | c(a, b) = Σw fw · nw(a, b) | c(e, s) = 9 in Sennrich's example |
| Compression ratio | CR = C / T, characters per token | toy 4.3; GPT-4 on English 4.8 |
| WordPiece score | c(ab) / (c(a) × c(b)) | i d: 0.33; e s: 0.059 |
| Unigram cut | P(cut) = Πi p(xi) | he · llo: 0.0008 (made up) |
| Byte-level size | V = 256 + M + S | GPT-2: 256 + 50,000 + 1 = 50,257 |
| Vocabulary sizes | as loaded from the real files | BERT 30,522 · T5 32,100 · Llama 32,000 · GPT-4 cl100k about 100k · GPT-4o o200k about 200k |
| Language tax | same sentence, different cost | Hindi 27 vs English 6 tokens (GPT-2) |
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
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.