Level 3 In-Depth AI · Transformers and Language Models
Tokenization
Before a language model can read text it must chop it into pieces called tokens and turn each piece into a number. How that chopping works explains the model's vocabulary, its price per word, and some of its strangest mistakes.
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 45 minutes to read, an hour to play with a tokenizer
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
Python for AIThe full path from zero — 1 concept before this one
- Python for AI
- Tokenization
Read them roughly in this order. See it on the concept map →
Why it matters
A neural network only understands numbers. Before ChatGPT, Claude or any other language model can read your message, the text must be cut into small pieces and each piece replaced by a whole number. The pieces are called tokens, the program that does the cutting is a tokenizer, and the fixed list of all pieces the model knows is its vocabulary.
Tokenization looks like a boring preprocessing step, but it shapes almost everything you notice about a language model:
- Cost and limits. API prices are quoted per million tokens, and a model's context window, the most text it can look at in one go, is measured in tokens. One English token is roughly four characters, or about three quarters of a word.
- Strange blind spots. Models famously struggled to count the letters in "strawberry". They never see letters. They see the token ids for
str,awandberry. - Fairness between languages. A tokenizer trained mostly on English text needs more tokens for the same sentence in Hindi or Amharic, so those users pay more and fit less into the context window.
- Arithmetic and code. How digits and spaces are grouped affects how well a model can add numbers or indent Python.
Every later chapter in this part starts from token ids: Language Modeling and Next-Token Prediction predicts the next token, embeddings turn each id into a vector, and Build a GPT from Scratch trains a model on them.
The intuition
Imagine you must send a long message by telegraph, paying per code word. You could have one code for every letter. That is a short codebook, but every message becomes very long. You could have one code for every word in the dictionary. Messages are short, but the codebook is enormous and still fails on names, typos and new words like "rizz".
The sensible middle ground is a codebook of common chunks: whole codes for frequent words like "the" and "and", codes for common pieces like "ing", "tion" and "un", and single letters as a fallback for anything unusual. Frequent things get one code; rare things get spelled out from parts. That is exactly what modern tokenizers do. The chunks are called subwords.
Look at the subword rows in the figure. "Token" and "ization" are separate pieces, so the model can reuse "ization" in "civilization" and "organization". The space before "isn" is glued onto the token, so ' hard' (with a space) and 'hard' (without) are different tokens with different ids. The newer GPT-4o tokenizer has a bigger vocabulary and keeps "isn't" whole.
How does a tokenizer decide which chunks deserve their own code? It learns them from a large sample of text with a simple counting algorithm called byte-pair encoding.
Key idea A tokenizer turns text into a list of integers using a fixed vocabulary of subword pieces. Common words become one token; rare words are built from several. The model only ever sees those integers, never letters.
How it works
Three choices of unit
| Unit | Vocabulary size | Sequence length | Unknown words? |
|---|---|---|---|
| Characters (or bytes) | about 100 (256 for bytes) | very long | never |
| Words | hundreds of thousands, still incomplete | short | often |
| Subwords | 30,000 to 200,000 | medium | never, with byte fallback |
Sequence length matters because a Transformer's cost grows with the number of tokens: the Self-Attention and Multi-Head Attention step compares every token with every other one, so doubling the length roughly quadruples that work. Vocabulary size matters because the model needs one learned vector per vocabulary entry at the input and one output score per entry at every step. Subwords balance the two.
Byte-pair encoding, by hand
Byte-pair encoding (BPE) builds a vocabulary bottom-up. Start with single characters. Then repeat: find the pair of neighbouring symbols that occurs most often, fuse it into a new symbol, and add that symbol to the vocabulary. Each fusion is called a merge rule. Stop when the vocabulary reaches the size you want.
Take a tiny training corpus of four words and how often each appears: low 5 times, lower 2 times, newest 6 times and widest 3 times. Write each word as characters plus an end-of-word marker _, so the algorithm can tell "est at the end of a word" from "est in the middle".
l o w _ ×5
l o w e r _ ×2
n e w e s t _ ×6
w i d e s t _ ×3
The starting vocabulary is the 11 distinct symbols: l o w _ e r n s t i d.
Merge 1. Count every adjacent pair, weighting by how often its word appears. The pair e s appears once in newest (×6) and once in widest (×3): 9 times. s t and t _ also score 9. w e scores 2 + 6 = 8, l o and o w score 5 + 2 = 7. Several pairs tie at 9; break the tie by taking the first one found, e s. Fuse it everywhere:
n e w es t _ ×6
w i d es t _ ×3
Merges 2 and 3. Recount. Now es t scores 9, so it becomes est; then est _ scores 9 and becomes est_, meaning "est at the end of a word".
Merges 4 and 5. The best pair is now l o with 7 (5 from low, 2 from lower), giving lo, then lo w gives low.
Merges 6 to 8. n e (6), then ne w (6), then new est_ (6) produce newest_ as a single token, because it is the most frequent word in this corpus.
After eight merges the vocabulary has 11 + 8 = 19 symbols, and the learned list of merges, in order, is the tokenizer:
1. e s → es 2. es t → est 3. est _ → est_ 4. l o → lo
5. lo w → low 6. n e → ne 7. ne w → new 8. new est_ → newest_
To encode a new word, split it into characters and apply the merges in the order they were learned. The word lowest, never seen in training, becomes l o w e s t _ → l o w es t _ → l o w est _ → l o w est_ → lo w est_ → low est_: two tokens, low and est_. It handles unseen words gracefully, which is the whole point. A real tokenizer does tens of thousands of merges on gigabytes of text, so common English words end up as single tokens.
Bytes, not characters
There are about 150,000 characters in Unicode, so starting from characters would leave a huge base vocabulary and still fail on emoji and rare scripts. GPT-2 introduced byte-level BPE: first encode the text as UTF-8 bytes (every character becomes one to four bytes, each a number from 0 to 255), then run BPE on the bytes. The base vocabulary is exactly 256, and any string, in any language, including binary junk, can be encoded. Nothing is ever "unknown".
Two more practical details:
- Pre-splitting. Before BPE runs, the text is split with a regular expression into chunks such as words, numbers and punctuation, and merges are never allowed to cross chunk boundaries. That keeps
dog.from becoming one token anddog!another. It is also why GPT-4's tokenizer splits numbers into groups of at most three digits:12345becomes123+45. - The leading space. Spaces are attached to the following word, so
" cat"is one token. That is why "Hello" at the start of a sentence and " Hello" in the middle have different ids.
Token ids and special tokens
After merging, each token is replaced by its position in the vocabulary, its token id. In GPT-4's tokenizer, "The cat sat on the mat." becomes seven ids:
[791, 8415, 7731, 389, 279, 5634, 13]
The ␣cat ␣sat ␣on ␣the ␣mat .
Vocabularies also contain special tokens that never come from ordinary text: markers for "end of text", "start of a user turn", "start of the assistant's reply" and so on. Chat models rely on them to know where your message stops and theirs begins (see Instruction Tuning and Chat Models).
Other subword algorithms
- WordPiece, used by BERT (vocabulary 30,522), is like BPE but picks the merge that most increases the likelihood of the training data rather than the raw most-frequent pair. Word-internal pieces are written with
##, as intoken ##ization. - Unigram language model tokenization starts with a big vocabulary and prunes the pieces that matter least. It is available in SentencePiece, a library that treats the input as a raw stream (spaces become the symbol
▁) and is used by T5 and many multilingual models.
Real vocabulary sizes, for scale: GPT-2 has 50,257 tokens, GPT-4's cl100k_base about 100,000, GPT-4o's o200k_base about 200,000, Llama 2 has 32,000 and Llama 3 128,256. The trend is towards bigger vocabularies, which shorten sequences, especially for non-English text.
In code
Here is a complete byte-level BPE trainer, encoder and decoder in plain Python. It is the same algorithm as the hand example, but on bytes, with integer ids instead of strings.
from collections import Counter
def get_pair_counts(ids):
return Counter(zip(ids, ids[1:]))
def merge(ids, pair, new_id):
out, i = [], 0
while i < len(ids):
if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
out.append(new_id); i += 2
else:
out.append(ids[i]); i += 1
return out
def train(text, vocab_size):
ids = list(text.encode("utf-8")) # start from raw bytes: 256 base tokens
merges = {} # (a, b) -> new token id
vocab = {i: bytes([i]) for i in range(256)}
for new_id in range(256, vocab_size):
pair = get_pair_counts(ids).most_common(1)[0][0]
ids = merge(ids, pair, new_id)
merges[pair] = new_id
vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
return merges, vocab
def encode(text, merges):
ids = list(text.encode("utf-8"))
while len(ids) >= 2:
# apply the earliest-learned merge that is present, as in training
pair = min(get_pair_counts(ids), key=lambda p: merges.get(p, float("inf")))
if pair not in merges:
break
ids = merge(ids, pair, merges[pair])
return ids
def decode(ids, vocab):
return b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace")
text = ("the cat sat on the mat. the dog sat on the log. "
"then the cat and the dog sat together on the mat. ") * 20
merges, vocab = train(text, vocab_size=256 + 12)
for pair, new_id in list(merges.items())[:6]:
print(new_id, repr(vocab[new_id]))
ids = encode("the cat sat on the hat", merges)
print([vocab[i].decode() for i in ids])
print(len("the cat sat on the hat".encode()), "bytes ->", len(ids), "tokens")
print(decode(ids, vocab))
# 256 b'th'
# 257 b'the'
# 258 b' the'
# 259 b'at'
# 260 b' the '
# 261 b'at '
# ['the', ' ', 'cat ', 'sat on the ', 'h', 'at']
# 22 bytes -> 6 tokens
# the cat sat on the hat
Notice 'sat on the ' became a single token. Our training text repeats that phrase so often that BPE happily glued words together. Real tokenizers prevent this with the regex pre-splitting described above. Karpathy's minbpe adds exactly that step.
To use a real tokenizer, OpenAI's tiktoken library (pip install tiktoken; the first call downloads the vocabulary file) gives you GPT-4o's:
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # the GPT-4o tokenizer
text = "Tokenization is the first step in every language model."
ids = enc.encode(text)
print(len(text), "characters,", len(text.split()), "words,", len(ids), "tokens")
print(ids)
print([enc.decode([i]) for i in ids[:3]])
print(enc.decode(ids) == text)
# 55 characters, 9 words, 11 tokens
# [4421, 2860, 382, 290, 1577, 5983, 306, 1753, 6439, 2359, 13]
# ['Token', 'ization', ' is']
# True
Hugging Face's AutoTokenizer.from_pretrained(...) does the same for open models, and its tokenizers library can train a new BPE vocabulary on your own text in seconds.
Common pitfalls
- Counting letters and reversing words. "How many r's in strawberry?" is hard because GPT-4's tokenizer turns
strawberryintostr+aw+berry, and' strawberry'(with a leading space) into a single token. The model has to have memorised the spelling of each token. Asking it to spell the word out letter by letter first often fixes the answer. - Arithmetic.
12345is123+45and13023is130+23. The digit groups don't line up with place values, which makes column-by-column addition awkward. Some tokenizers, such as those of Llama 1 and 2, split numbers into single digits for this reason. - Surprising token counts. Capitals, rare words, code and non-English text cost more.
hellois one token in GPT-4's tokenizer,HELLOis two. "Привет, как дела?" ("Hi, how are you?" in Russian) takes 18 tokens with GPT-2's English-centric tokenizer, 8 with GPT-4's and 6 with GPT-4o's. - Whitespace. Trailing spaces, tabs versus spaces, and a missing leading space change the tokens and can noticeably change a model's output, especially for code.
- Mixing tokenizers. Token ids are meaningless without the exact vocabulary they came from. Feeding ids from one model's tokenizer into another model produces garbage with no error message.
Watch out Always count tokens with the tokenizer of the model you are actually using. A "1,000-word" document can be 1,300 tokens in English and several times that in other scripts. Budget for context limits and API costs with real counts, not word counts.
A famous oddity: in 2023 people found glitch tokens such as SolidGoldMagikarp in GPT-2/GPT-3's vocabulary. They were common in the tokenizer's training data (a Reddit username) but almost absent from the model's, so their embeddings were barely trained, and prompting with them produced bizarre behaviour.
Where it leads
- The next step is to give each token id a learned vector, an embedding (Word Embeddings), and to model which token comes next (Language Modeling and Next-Token Prediction).
- Build a GPT from Scratch uses the simplest tokenizer of all, one token per character, so you can see that the rest of the model doesn't care how text was cut.
- Tokens are the unit of the context window, of API pricing and of generation speed (The KV Cache and Fast Inference).
- Images and audio get "tokenized" too, into patches or short frames, which is how vision Transformers and Multimodal LLMs reuse the same machinery.
- Researchers are exploring tokenizer-free models that read raw bytes directly, trading longer sequences for the end of tokenization quirks.
A bit of history
Byte-pair encoding began life as a data-compression trick, published by Philip Gage in 1994: repeatedly replace the most common pair of bytes in a file with a single unused byte. In 2015 Rico Sennrich, Barry Haddow and Alexandra Birch adapted it to split rare words into subword units for neural machine translation, solving the "unknown word" problem that plagued word-level models. Google had developed the related WordPiece method for Japanese and Korean voice search (Schuster and Nakajima, 2012), and it went on to power Google's neural translation system and BERT. In 2018 Taku Kudo introduced the unigram method and, with John Richardson, the SentencePiece library. GPT-2 (2019) popularised byte-level BPE, and that design, with ever larger vocabularies, is still used by most large language models today.
Try it
- Run the hand example yourself: change the corpus to
low ×5, lower ×2, lowest ×6, widest ×3and predict the first three merges before running the code. Did the order change compared with the chapter's example, and why?- In the from-scratch code, train with
vocab_size=256 + 50on a few paragraphs of any book from Project Gutenberg. Print the 50 merges. Which English pieces appear first?- Paste the same paragraph in English and in another language into Tiktokenizer and compare the token counts.
Hint for 1:
l oando wnow appear in three words, 5 + 2 + 6 = 13 times, which beatse sat 9. Soloandlowcome first.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Let's build the GPT Tokenizer
Byte-pair encoding built from scratch, and why tokenization causes so many LLM quirks.
Tiktokenizer
Paste text and see exactly how it splits into tokens for several real model tokenizers, with colours and token ids.
minbpe
Minimal, clean code for byte-level BPE as used in GPT tokenizers, with exercises. Companion to the tokenizer video.
Hugging Face LLM Course
Using Transformers, datasets and tokenizers, fine-tuning, and building with open LLMs, with runnable notebooks.
tiktoken
OpenAI's fast BPE tokenizer library. Load the encodings used by GPT models and count tokens in Python.
Neural Machine Translation of Rare Words with Subword Units
The paper that brought byte-pair encoding into NLP, splitting rare words into subword units.
SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing
The tokenizer library behind T5, Llama and many other models. Works on raw text with no pre-splitting into words.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/tokenization.md