Skip to main content

Tokenization: How Text Becomes Numbers (BPE)

Editorial

Introduction

Language Models 101: Predicting the Next Token treated a token as roughly a word. Here it gets its real meaning.

A model reads neither words nor letters. It reads tokens: numbers, each standing for a piece of text from a fixed list, the model's vocabulary. The first thing that happens to your prompt is tokenization: the text is cut into those pieces and each piece becomes its number.

It sounds like plumbing, and it shapes what you pay, what fits in a request, and some odd things models do with spelling.

You'll learn:

  • why models use pieces of words, neither whole words nor single letters;
  • what a token and a vocabulary are, with a real tokenizer's numbers;
  • Byte-Pair Encoding (BPE), the method that builds the vocabulary, run step by step;
  • how to tokenize text yourself in Python;
  • what follows: spelling, cost and other languages.

Why Not Just Words or Characters?

There are two obvious ways to cut text, and both break.

  • Whole words. Every word needs its own entry: every plural, tense, name and typo. A word that was not in the list when it was made cannot be read at all.
  • Single characters. The list is tiny, but every text becomes a long run of pieces. Over the prose of these lessons, GPT-2's tokenizer gives one token for every 3.83 characters, so a model reading characters would take in 3.83 times as many pieces for the same text.

Pieces of words sit between the two. Sennrich, Haddow and Birch made a translation model "capable of open-vocabulary translation by encoding rare and unknown words as sequences of subword units", and GPT-2's paper calls their method "a practical middle ground between character and word level language modeling". Common words become one token, rare ones split into pieces that are used again, and anything can still be written, down to single bytes. That method is Byte-Pair Encoding.

What a Token Is

A token is one entry of the model's fixed vocabulary: a piece of text and its number, the id. Tokenizing a text turns it into a list of ids, and the model only ever sees those numbers.

GPT-2's tokenizer, run on The cat sat., gives four tokens, "The", " cat", " sat" and ".", with ids 464, 3797, 3332, 13 (the code under Tokens in Practice prints them). Two things to notice:

  • A space belongs to the word after it. "cat" is token 9246 and " cat", with its space, is 3797: two different entries for what a reader sees as one word.
  • A token is not a word. Over these lessons' prose GPT-2 used 1.65 tokens for every word (a word here being what stands between two spaces), and 3.83 characters made one token. The ratio depends on the text and on the tokenizer, so measure it on your own text before you plan with it.

Byte-Pair Encoding: How the Vocabulary Is Built

Byte-Pair Encoding began as a way to compress data (Gage, 1994). Sennrich, Haddow and Birch describe the original: it "iteratively replaces the most frequent pair of bytes in a sequence with a single, unused byte." They turned it into a way to build a vocabulary:

  1. Start with single characters, every word ending with an end mark.
  2. Count every pair of symbols that stand side by side, each word weighted by how often it occurs.
  3. Merge the most frequent pair into one new symbol.
  4. Repeat for a chosen number of merges.

Frequent strings get merged early and become one symbol; rare ones never do and stay in pieces. As the paper puts it, "The final symbol vocabulary size is equal to the size of the initial vocabulary, plus the number of merge operations". GPT-2 starts from bytes, since "a byte-level version of BPE only requires a base vocabulary of size 256", and adds 50,000 merges and one end-of-text token: 256 plus 50,000 plus 1 makes its 50,257 tokens.

Three parts. One, the algorithm as Sennrich, Haddow and Birch print it, run on its own dictionary: low five times, lower twice, newest six times and widest three times, each word as single symbols with an end mark. It counts every pair side by side and joins the most frequent: e and s (9 times), then es and t (9), then est and the end mark (9), then l and o (7), then lo and w (7), and 5 more. Two, GPT-2's own tokenizer on real words, a space drawn as a dot: strawberry after a space is one token, id 41236; strawberry with no space is three, st, raw and berry, ids 301, 1831 and 8396; antidisestablishmentarianism after a space is five, ant with its space, idis, establishment, arian and ism. A space is part of the token: cat is 9246 and cat after a space is 3797. GPT-2's vocabulary is its 256 bytes, its 50,000 merges and one end-of-text token, 50,257 in all. Three, why subwords: tokenization after a space as a whole word is one entry, and every new word needs its own; as single characters it is 13 pieces; as GPT-2's tokens it is two, token with its space and ization, and ization is the same token at the end of Tokenization. Frequent strings become one token; rare ones split into pieces used again.

The paper prints the whole algorithm as a short Python program, and it runs as printed. Its dictionary holds low five times, lower twice, newest six times and widest three times, with </w> as the end mark:

import re, collections

def get_stats(vocab):
    pairs = collections.defaultdict(int)
    for word, freq in vocab.items():
        symbols = word.split()
        for i in range(len(symbols)-1):
            pairs[symbols[i],symbols[i+1]] += freq
    return pairs

def merge_vocab(pair, v_in):
    v_out = {}
    bigram = re.escape(' '.join(pair))
    p = re.compile(r'(?<!\S)' + bigram + r'(?!\S)')
    for word in v_in:
        w_out = p.sub(''.join(pair), word)
        v_out[w_out] = v_in[word]
    return v_out

vocab = {'l o w </w>' : 5, 'l o w e r </w>' : 2,
         'n e w e s t </w>':6, 'w i d e s t </w>':3}
num_merges = 10
for i in range(num_merges):
    pairs = get_stats(vocab)
    best = max(pairs, key=pairs.get)
    vocab = merge_vocab(best, vocab)
    print(best)

It prints each merge in turn:

('e', 's')
('es', 't')
('est', '</w>')
('l', 'o')
('lo', 'w')
('n', 'e')
('ne', 'w')
('new', 'est</w>')
('low', '</w>')
('w', 'i')

e and s stand side by side 9 times (six in newest, three in widest), more than any other pair, so they merge first. Then es with t, then est with the end mark, all at 9, and only then l with o at 7. When two pairs tie, max takes the first one counted. The paper's own figure merges another small dictionary, and its text gives the result for an unseen word: "In our example, the OOV 'lower' would be segmented into 'low er·'." Applying the figure's four merges to lower gives the same.

See It: Watch BPE Join a Word

GPT-2 learned 50,000 merges this way, in order, and that order is the merge's rank: rank 0 was learned first, from the most frequent pair. To split a word it starts from the word's bytes and, of the pairs that stand side by side, joins the one with the lowest rank, everywhere that pair occurs; then again, until no pair side by side is in its list.

Pick a word and press Merge next. The pieces of the word are across the top, a space drawn as ·. Under them is every pair side by side, lowest rank first, each with its place on a track of ranks; the top one joins, its right piece sliding into the left. Merge all plays every merge left. Every step, rank and id is GPT-2's own, from its tokenizer run by tiktoken.

GPT-2's tokenizer on a word: the pair side by side with the lowest rank joins, again and again, until no pair is one of its merges.

Tokens in Practice

OpenAI's tokenizer library, tiktoken, runs on your machine with no API call. Install it with pip install tiktoken. The first time you ask for an encoding it downloads that encoding's files and keeps them in a folder named data-gym-cache under your system's temporary folder; GPT-2's are two files, of 456,318 and 1,042,301 bytes. Save this as tokens.py and run python3 tokens.py:

import tiktoken

enc = tiktoken.get_encoding("gpt2")  # GPT-2's tokenizer: 50,257 tokens
for text in ["The cat sat.", "cat", " cat", "strawberry", " strawberry"]:
    ids = enc.encode(text)
    print(f"{text!r:15} {ids}  {[enc.decode([i]) for i in ids]}")
print(enc.n_vocab, "tokens in the vocabulary")

Run with tiktoken 0.13.0, it prints:

'The cat sat.'  [464, 3797, 3332, 13]  ['The', ' cat', ' sat', '.']
'cat'           [9246]  ['cat']
' cat'          [3797]  [' cat']
'strawberry'    [301, 1831, 8396]  ['st', 'raw', 'berry']
' strawberry'   [41236]  [' strawberry']
50257 tokens in the vocabulary

Change "gpt2" to "o200k_base" to see a newer vocabulary. tiktoken's table of models gives o200k_base for GPT-4o, GPT-4.1 and GPT-5, and cl100k_base for GPT-4; its source numbers o200k_base's end-of-text token 199,999, so that vocabulary holds about 200,000 tokens. Its pieces and ids differ from GPT-2's, so the numbers above will change.

Claude uses its own tokenizer, and Anthropic counts its tokens for you: its API takes a request at /v1/messages/count_tokens and returns the number of input tokens for the model you name. Its documentation adds that "the actual number of input tokens used when creating a message might differ by a small amount", and that Claude 4.7 and later models use a newer tokenizer: "The same input text produces approximately 30 percent more tokens than on earlier models." Count with the model you will use. Anatomy of an LLM API Call (Messages, Roles, Params) shows the token counts every answer comes back with.

Why This Matters: Spelling, Cost and Languages

Spelling. GPT-2 cuts "strawberry" with no space before it into "st", "raw" and "berry" (ids 301, 1831, 8396). After a space, as it stands in a sentence, " strawberry" is one token, id 41236. Either way the letters are inside the tokens, and the model reads ids. A 2024 study set out from that very failure, many models miscounting the r's in strawberry, and found more than a hidden spelling: "models are capable of recognizing the letters but not counting them", with "most models being unable to correctly count words in which letters appear more than twice." For work on letters, give the model a tool that counts: in Python, "strawberry".count("r") is 3.

Three parts. What you see: strawberry as ten letters, three of them r. What GPT-2's tokenizer gets, run: with no space before it, strawberry is three tokens, st, raw and berry, ids 301, 1831 and 8396, holding 0, 1 and 2 of the r's; after a space, as in a sentence, it is one token, id 41236, holding all 3. The model reads the ids, not the letters, and asked how many r's, a model can answer 2. What a 2024 study of letter counting found (Fu and colleagues): models recognize the letters but miss the count, most often where a letter appears more than twice. For letters, use a tool: in Python, "strawberry".count("r") gives 3. Tokens shape the bill: with GPT-2's tokenizer over the lessons' text, measured, 3.83 characters a token. The model reads ids; for letters, give it a tool.

Cost and room. Prices and context windows are counted in tokens, not words: Understanding API Pricing (Token Math) and Tokens, Context Windows & Why They Matter work it out. Measure the ratio on your own text with your model's tokenizer.

Other languages. A tokenizer can cut one language into far more pieces than another. Petrov and colleagues measured that "The same text translated into different languages can have drastically different tokenization lengths, with differences up to 15 times in some cases." More tokens means more cost, more time and less room in the window.

Rare words and typos. GPT-2 cuts antidisestablishmentarianism, after a space, into five tokens, and a typo splits a word it knows: " strawberry" is one token, " strawbery" is two, " straw" and "bery".

Mental-Model Corrections

  • Don't ask a model for letter-level work on trust. Counting letters, reversing a string and exact character edits go against how the text reaches it. Give it a tool that runs code.
  • Estimate, then measure. A ratio of characters to tokens is a plan; the token counts your provider returns are the bill.
  • Token counts belong to a tokenizer. OpenAI's count is not Claude's, and Claude's newer models count the same text differently from older ones.
  • Token and word are close, not the same. Thinking in words is fine for a first guess; spelling, prices and other languages are where the difference shows.

Try It Yourself

Six questions on tokens and BPE, each answered by the runs above.

Check tokens and BPE

1 / 6

Multiple choice

In GPT-2, "cat" is token 9246. What is " cat", with a space before it?

Key Takeaways

  • A model reads tokens: numbers for pieces of text from a fixed vocabulary. Tokenizing is the first step of every prompt.
  • Pieces of words sit between whole words and single characters; Byte-Pair Encoding builds the vocabulary by merging the most frequent pair, again and again.
  • GPT-2's vocabulary is 256 bytes, 50,000 merges and one end token: 50,257 tokens. A space belongs to the word after it.
  • Tokens explain real behaviour: letters hidden inside tokens, bills and windows counted in tokens, and other languages split into more pieces.
  • For work on letters, reach for a tool.

Next: Embeddings: Meaning as Vectors, where these numbers get meaning.