rumblr Work in progressWIP

● The AI Primer · Lesson 9 · Part 1: how a language model works

Tokenization

how text becomes the integers a model actually reads

This lesson covers How text becomes the pieces a language model reads, and why language models miscount letters

Members · open during launch 27 min9 figures and diagrams8 interactive

What this is

What is tokenization?

Tokenization is how an AI language model turns text into numbers. A tokenizer cuts the text into pieces, called tokens, from a fixed list and gives each piece a number. A common word is one piece; a rarer one, such as unbelievable, might be three (un, believ, able). Those numbers are all the language model ever sees of your words.

Why it matters: Every price, rate limit and context window is counted in tokens, and the same message in Hindi or Japanese can take several times as many tokens as in English. Tokens also explain why a language model that writes essays can miscount the letters in strawberry.

At a glance

Key takeaways

  1. BPE learns a kit of subword pieces from text: start from characters or bytes and repeatedly merge the most frequent neighbouring pair.
  2. Byte-level BPE starts from the 256 byte values, so it can encode any text with no unknown token.
  3. Cost, latency and context limits are counted in tokens. English is about 4 characters (0.75 words) per token; code and non-English text need more tokens.
  4. The model sees token ids, not letters, which is why it can miscount the letters in a word.

How it works, from scratch

A language model works on numbers, not text. Before it reads a prompt, the prompt has to be cut into pieces and each piece swapped for a number, and how that cut is made decides what a call costs and what the model can know about spelling.

Chapter 1

Tokens: pieces from a fixed kit

Think of a box of Lego with a fixed set of bricks. Common shapes have a ready-made brick, and anything unusual is assembled from smaller ones, so you can build anything, though some builds take many more bricks than others. A tokenizer is that kit for text: a fixed vocabulary of pieces, called tokens, each with a number, its token id. Real kits typically hold 32,000 to 200,000 pieces.

With a kit that contains the, un, believ and able, "the" takes 1 brick and "unbelievable" takes 3: un + believ + able. The model never sees the letters, only a short list of ids such as [262, 403, 11009, 540].

There are three ways to stock the kit, and "unbelievable" shows what each one costs:

Approach Kit size "unbelievable" Problem
Whole words huge (every form of every word, every name) 1 piece, if it's in the kit words not in the kit become <unk>; typos break
Single bytes 256 12 pieces sequences 4-5× longer, and attention cost grows with length squared
Subwords 32k to 200k ~3 pieces the middle ground every modern LLM uses

Whichever kit is used, the text stops at the tokenizer:

Figure 1 · Diagram

Reading it: text enters on the left and never reaches the model as text. The tokenizer cuts it into pieces from its kit and swaps each piece for its number. Those numbers pick rows from the embedding table (see What happens when you send a prompt), and only those vectors reach the model, so whatever the model knows about spelling it had to learn from the ids alone. (The ids shown are illustrative.)

In code: trained_tokenizer builds this lesson's toy kit, and ByteBPE.encode turns any text into its list of ids. View source

Type a sentence and compare how the three kits cut it. Count the pieces in each row, and watch what the whole-word kit does with a word it has never seen.

Chapter 2

Byte Pair Encoding (BPE): learning the kit from data

A subword kit is learned from a sample of text, not written by hand. Byte Pair Encoding (BPE) learns it the way a court stenographer invents shorthand. Whatever pair of letters they write most often gets its own squiggle. Then the most common pair including that squiggle gets one too, and so on, until they have as many squiggles as they can remember. BPE does the same with symbols: start from single letters, find the neighbouring pair that occurs most often, glue it into one new symbol, write that down as a merge rule, and repeat.

Here are the first three rounds on the training text "low lower lowest":

Step Most frequent pair New token Text becomes
Start none none l o w · l o w e r · l o w e s t
1 l + o (3 times) lo lo w · lo w e r · lo w e s t
2 lo + w (3 times) low low · low e r · low e s t
3 low + e (2 times) lowe low · lowe r · lowe s t

At step 1, l+o and o+w are tied at 3; ties go to the pair seen first.

Figure 2 · Diagram

Reading it: training is a loop around two boxes. "Count adjacent pairs" looks at every neighbouring pair of symbols in the corpus; "Merge" glues the winner into one new symbol everywhere and appends that rule to an ordered list. The loop exits when the vocabulary reaches its target size. What comes out is the vocabulary and the merge rules in the order they were learned, and encoding depends on that order.

"Most often" has a precise meaning. Each round picks the pair with the largest count:

The formula and its symbols

Symbols

Symbol Meaning here In the example
two symbols that sit side by side l and o
one distinct word of the training text "lower"
"add up the following over every distinct word" low, lower, lowest
how many times word occurs in the text 1 each
how many times is immediately followed by inside 1 in each word
the pair's total, the number BPE ranks by 3

In words: "for each distinct word, count how often the pair appears inside it, multiply by how often the word occurs, and add everything up."

With the numbers: count(l, o) = 1·1 (low) + 1·1 (lower) + 1·1 (lowest) = 3; count(e, r) = 1·1 (lower) = 1.

In Python
# f_w: how often each distinct word occurs
f = {"low": 1, "lower": 1, "lowest": 1}
# n_w(a, b): a immediately followed by b inside w
def n(w, a, b):
    return sum(1 for i in range(len(w) - 1) if w[i] == a and w[i + 1] == b)
def count(a, b):
    # Σ_w f_w · n_w(a, b)
    return sum(f_w * n(w, a, b) for w, f_w in f.items())
count("l", "o"), count("e", "r")  # → (3, 1)

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

Because the most frequent pairs are merged first, frequent strings end up as single tokens and rare ones stay in pieces. That is why token counts differ from word counts, and why a tokenizer trained mostly on English is cheap for English and expensive for most other text.

In code: train_char_bpe runs the count-and-merge loop and returns one MergeStep per round, holding the winning pair, its count, the new token and the text after the merge (one row of the table above). View source

Run the training one round at a time on "low lower lowest", or on text of your own, and watch the rule list grow.

Chapter 3

Encoding new text: replay the merges in order

Training hands over an ordered list of merge rules. To cut new text, the tokenizer starts from its letters and applies the rules in the order they were learned. At each step it looks at the pairs present, merges the pair whose rule was learned earliest, everywhere it occurs, and looks again, until no pair left is a rule. Training and encoding agree because both use the rules in the same order.

Encode "lowest" with the three merges learned above: l o w e s t → (merge 1) lo w e s t → (merge 2) low e s t → (merge 3) lowe s t. Result: 3 tokens. A word that never appeared in training still gets cut: "slow" → s low, while "newer" matches no merge and stays as letters.

Figure 3 · Diagram

Reading it: follow the word from left to right. Each box applies one merge rule, in the order the rules were learned, to every place it fits, and the word shrinks from 6 symbols to 3. It stops when none of the remaining neighbouring pairs is in the rule list.

Since the rules are applied in a fixed order, the same text always gives the same ids. Prompt caching and cost estimates rely on that.

In code: encode_char_bpe replays the merges on one word. View source

Type a word and follow the rules applied in order. Then change how many rules the tokenizer knows and watch the number of tokens change.

Chapter 4

Byte-level BPE: nothing is ever unknown

A kit whose smallest pieces are letters has a gap: a character that is not in it, an emoji, say, or a Chinese character the training text never contained, has no id, and a real tokenizer can only replace it with an "unknown" token, losing it. (The toy letter tokenizer in this lesson passes such characters through instead, to keep the code short.) Byte-level BPE closes the gap by starting one layer lower. Every file on a computer, whatever it holds, is a sequence of bytes: numbers from 0 to 255. If the smallest bricks in the kit are those 256 byte values, no text is ever unbuildable: emoji, Chinese, source code or garbage all come apart into bytes.

UTF-8 is the standard way to store text as bytes. In it "a" is one byte, 97; "é" is two bytes, 195 169; and "🙂" is four bytes, 240 159 153 130. An untrained byte-level tokenizer turns "é🙂" into 6 tokens, one per byte. After training on English, " password" is one token, id 291, because it was frequent.

Figure 4 · Diagram

Reading it: encoding runs left to right. A regular expression (a text-matching pattern) first cuts the text into chunks, each keeping its leading space; merges never cross a chunk boundary. Each chunk becomes raw bytes (ids 0-255). The tokenizer then applies whichever learned merge came earliest among the pairs present, until none applies. The ids shown are what the toy tokenizer trained for this lesson produces: "Reset" is two tokens (Re set), " password" is one. Decoding is the reverse lookup: every id maps to a fixed byte string, and joining them restores the original bytes, so a byte-level tokenizer gets back any text it was given.

This is BPE with bytes in place of letters: ids 0-255 stand for the bytes and 256, 257, ... for the merges. GPT-2, GPT-4's cl100k_base, Llama 3 and most current LLMs tokenize this way. The more merges a tokenizer learns, the more text each token covers:

Figure 5 · Chart

250 300 350 400 450 500 vocabulary size (256 bytes + learned merges) 1.0 1.5 2.0 2.5 3.0 characters per token (held-out English) More merges compress text, with diminishing returns

Compression climbs steeply from 1.0 to 2.0 characters per token in the first 44 merges, then flattens near 3.1 by 500 entries

Reading it: the x-axis is vocabulary size: 256 raw bytes plus the number of merges learned. The y-axis is compression, how many characters of held-out English each token covers on average. At 256 (no merges) every byte is a token, so the value is 1. The first few dozen merges capture the most frequent pairs (" t", "he", " the") and the curve climbs steeply; later merges capture rarer strings and the curve flattens. (Our toy corpus runs out of repeated strings near 500; real corpora keep going.) Production tokenizers sit far to the right, at 50k to 200k entries, and reach about 4 characters per token on English. Bigger kits mean shorter sequences but a larger embedding table and output layer.

Figure 6 · Interactive · computed from the lesson's code

Byte-level BPE tokenizer

Try it: this is the toy tokenizer from the diagram, with its 144 learned merges. Drag the merges down to 0 and every byte is its own token. Drag them back up and watch frequent pieces such as " the" and " password" fuse, one merge at a time, while characters per token climbs as in the chart. Then type a word the corpus never saw, an accent or an emoji, and see it stay in small pieces.

So a byte-level tokenizer never meets an unknown token, whatever the input. It pays in length instead: text in a script it rarely saw falls back to near-byte pieces and costs many more tokens.

In code: ByteBPE.train learns the byte merges, ByteBPE.encode and ByteBPE.decode make the round trip, and compression_curve measures tokenizers of growing size for the chart. View source

Type any text and read it down the ladder: chunks, characters, bytes, tokens. Try an accent or an emoji and see which bytes stay apart.

Chapter 5

Other ways to learn a kit: WordPiece and Unigram

BPE is not the only way to learn a kit. WordPiece also merges pairs, but where BPE glues the most common pair, WordPiece glues the most inseparable one: two pieces that rarely appear apart, like "Q" and "u" in English. Unigram works the other way round: it starts with a huge kit and keeps throwing out the pieces it would miss least.

On "low lower lowest", BPE's first merge is l+o. WordPiece's first merge is s+t: "s" and "t" each appear once, and always together.

Figure 7 · Diagram

Reading it: the two top rows grow a vocabulary bottom-up and differ only in how they rank candidate pairs. The bottom row prunes top-down. All three end with a fixed kit and a rule for cutting new text into pieces from it.

WordPiece ranks pairs by

The formula and its symbols

Symbols

Symbol Meaning here In the example
how often is immediately followed by count(st) = 1
how often appears at all count(s) = 1
how often appears at all count(t) = 1
fraction bar divide: pairs are rewarded when their parts rarely appear apart

In words: "how often the two appear together, divided by how often each appears at all."

With the numbers: score(s, t) = 1 / (1 · 1) = 1.0; score(l, o) = 3 / (3 · 3) = 0.33, so WordPiece merges s+t first.

In Python
f = {"low": 1, "lower": 1, "lowest": 1}
# how often a symbol, or a pair written together, appears
def count(piece):
    return sum(f_w * w.count(piece) for w, f_w in f.items())
def score(a, b):
    # count(ab) / (count(a) · count(b))
    return count(a + b) / (count(a) * count(b))
score("s", "t"), round(score("l", "o"), 2)  # → (1.0, 0.33)

BERT marks continuation pieces with ## ("un", "##believ", "##able"). SentencePiece is a library that runs BPE or Unigram directly on raw text, writing spaces as the visible symbol ▁.

Each model family is trained with its own kit, so two families cut the same text into different pieces and count it as a different number of tokens. Count with the tokenizer of the model you will call.

In code: wordpiece_scores scores every neighbouring pair. View source

Switch between the two rankings of the same pairs and see where BPE and WordPiece disagree.

Chapter 6

Tokens are the unit of cost, speed and memory

That count is what you pay for. Providers bill by the token, and they run two meters, like a taxi with a pricier meter for the return trip: one for the tokens you send in and one for the tokens the model writes back. Output tokens usually cost several times more than input tokens.

Take a prompt of 2,000 tokens with a 500-token answer, at example prices of $3 per million input tokens and $15 per million output tokens: 0.006 + 0.0075 = $0.0135. A million such calls cost $13,500.

Figure 8 · Diagram

Reading it: two meters run on every call. Input tokens are counted once on the way in; they also have to fit in the model's context window (the dotted arrow). Output tokens are counted on the way out, and each one also takes a full step of generation, so they drive latency as well as cost.

The bill for one call is

The formula and its symbols

Symbols

Symbol Meaning here In the example
input tokens in the call 2,000
output tokens generated 500
one million, because prices are quoted per million tokens 1,000,000
price per million input tokens, in dollars 3
price per million output tokens, in dollars 15

In words: "input tokens in millions times the input price, plus output tokens in millions times the output price."

With the numbers: 2,000/1,000,000 × 3 + 500/1,000,000 × 15 = 0.006 + 0.0075 = $0.0135.

In Python
T_in, T_out = 2_000, 500
# dollars per million tokens
p_in, p_out = 3, 15
round(T_in / 10**6 * p_in + T_out / 10**6 * p_out, 4)  # → 0.0135

To estimate a token count without a tokenizer, use the rule of thumb for English prose: about 4 characters per token, or 0.75 words per token, so 1,000 tokens ≈ 750 words. Count with the real tokenizer for anything that matters, because the rule holds only for English prose. The same English-trained tokenizer needs far more tokens for other kinds of text:

Figure 9 · Chart

English prose German Python code JSON Hindi Emoji 0.0 0.5 1.0 1.5 2.0 2.5 characters per token (higher = cheaper) Same tokenizer, very different cost by content

English prose gets 2.6 characters per token; German, code and JSON 1.2 to 1.4; Hindi and emoji under 0.4

Reading it: each bar is one kind of text encoded by the same English-trained toy tokenizer; taller bars mean each token carries more text, so the content is cheaper. English prose scores highest because the merges were learned from English. Code and JSON score lower because symbols and unusual identifiers were rarely merged. German shares the alphabet but not the words. Hindi and emoji fall below one character per token: each character is 3-4 UTF-8 bytes and few of those byte pairs were ever merged, the worst case of byte-level fallback.

So the same request can differ several-fold in cost, latency and context used, depending on its language and content.

In code: estimate_cost prices a call, estimate_tokens and tokens_to_words apply the rule of thumb, and chars_per_token computes each bar: the length of the text divided by the number of ids ByteBPE.encode returns for it. View source

Drag the token counts and the prices, and watch what one call costs and what a million of them cost.

Chapter 7

Quirks the tokenizer explains

The model receives ids, not letters, so whatever sits inside a token is hidden from it, as if it read through frosted glass that shows which bricks are there but not the letters printed on them. The toy tokenizer trained above shows three cases:

Text Tokens What it explains
" cat" vs "cat" [303] vs [99, 268] (c at) a leading space makes a different token; the model must learn they mean the same
" 1234" vs " 12345" [' 1234'] vs [' 1234', '5'] digits split by length and context, so place values don't line up: one reason arithmetic is hard
" strawberry" [' straw', 'berry'] 2 ids, not 10 letters: "how many r's?" is hard

Figure 10 · Diagram

Reading it: the question is about letters, but the letters were discarded before the model saw anything. It has to have memorized how straw and berry are spelled from seeing them in text, which is why spelling and letter-counting questions trip up models that handle much harder reasoning.

Some newer tokenizers split digits into fixed groups of up to 3 to reduce the arithmetic problem.

In code: ByteBPE.tokens shows the pieces of any string, and the demo prints these cases. View source

Type a word and pick a letter to count. Compare what you see on the left with what reaches the model on the right.

Test yourself

7 questions

Answer each one out loud or on paper before you open it.

Question 1Why subwords instead of whole words or characters?Think it through, then reveal

Words give a huge vocabulary and unknown words; characters make sequences several times longer, and attention cost grows with the square of length. Subwords keep common strings short and still encode anything.

Question 2How does BPE training proceed, step by step, on "low lower lowest"?Think it through, then reveal

Split into letters, count neighbouring pairs, and merge the most frequent: l+o (3), then lo+w (3), then low+e (2). Record each merge; to encode, replay the merges in the order learned.

Question 3Why can a byte-level BPE tokenizer never produce an unknown token?Think it through, then reveal

Its base vocabulary is all 256 byte values, and every string is a sequence of UTF-8 bytes, so in the worst case text falls back to single bytes.

Question 4What does WordPiece do differently from BPE?Think it through, then reveal

It merges the pair with the highest count(ab) / (count(a)·count(b)), which favours pairs whose parts rarely appear apart, instead of the most frequent pair.

Question 5Your users write in Hindi. What changes in your estimates?Think it through, then reveal

Expect noticeably more tokens for the same content: higher cost and latency, and less text per context window. Measure with the actual tokenizer.

Question 6Why are LLMs bad at counting letters and at long arithmetic?Think it through, then reveal

They see token ids, not characters, and numbers split into chunks that don't line up with place value.

Question 7What does a call with 2,000 input and 500 output tokens cost at $3/$15 per million?Think it through, then reveal

0.006 + 0.0075 = $0.0135. And 1,000 tokens is about 750 English words.

Primary sources

The papers behind this lesson

Sennrich, Haddow & Birch (2015), Neural Machine Translation of Rare Words with Subword Units.

Brought byte pair encoding, a 1990s compression trick, to language models as a way to build open-vocabulary subword units.

Read on rumblr →The paper
Radford et al. (2019), Language Models are Unsupervised Multitask Learners (GPT-2).

Introduced byte-level BPE with a pre-tokenization regex, the design most LLM tokenizers still follow.

The paper
Kudo & Richardson (2018), SentencePiece.

A language-independent tokenizer library that works on raw text and encodes spaces as the symbol ▁.

The paper
Kudo (2018), Subword Regularization.

Introduced the Unigram language-model tokenizer that prunes a large vocabulary down instead of merging up.

The paper

Researcher's shelf

Further reading

  • Sennrich et al., Neural Machine Translation of Rare Words with Subword Units (the BPE paper, 2015): https://arxiv.org/abs/1508.07909
  • Andrej Karpathy, Let's build the GPT Tokenizer (video): https://www.youtube.com/watch?v=zduSFxRajkE
  • Karpathy's minbpe (minimal, clean byte-level BPE): https://github.com/karpathy/minbpe
  • OpenAI tiktoken (fast BPE used by GPT models): https://github.com/openai/tiktoken
  • Hugging Face LLM course, BPE chapter: https://huggingface.co/learn/llm-course/chapter6/5
  • Hugging Face LLM course, WordPiece chapter: https://huggingface.co/learn/llm-course/chapter6/6
  • Hugging Face LLM course, Unigram chapter: https://huggingface.co/learn/llm-course/chapter6/7
  • Kudo & Richardson, SentencePiece (2018): https://arxiv.org/abs/1808.06226
  • Kudo, Subword Regularization (the Unigram LM, 2018): https://arxiv.org/abs/1804.10959
  • Petrov et al., Language Model Tokenizers Introduce Unfairness Between Languages (2023): https://arxiv.org/abs/2305.15425

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.