Tokenizers: how text becomes numbers
A language model never sees letters or words. Before your prompt reaches it, a tokenizer cuts the text into pieces called tokens and swaps each piece for a number. Module 01 showed what tokens are; this module shows how a tokenizer is built, what it stores, how it turns your prompt into numbers, and the special tokens that turn a conversation into one long sequence.
- Sam When I type a prompt, what does the model actually see?
- Priya Numbers. Before your text reaches the model, a tokenizer cuts it into pieces called tokens and swaps each piece for its number in a fixed vocabulary. The model never sees letters or words, only those IDs.
- Priya Think of a court stenographer building shorthand. First they give a symbol to the most common pair of letters, then to the most common pair of those, until frequent words each have one symbol. A tokenizer is that shorthand, built by counting pairs in a huge pile of text.
- Sam And the steps when I send a prompt?
- Priya Four. Split the text into rough chunks: words, spaces, punctuation. Apply the learned merges to each chunk. Look up each piece's ID in the vocabulary. Then the model turns each ID into a vector by looking up a row in its embedding table.
- Sam How is a tokenizer trained?
- Priya With byte-pair encoding. Take a corpus, split every word into characters, and count every neighbouring pair, weighted by how often each word appears. Merge the most frequent pair into a new token, save that rule, and repeat. In the Hugging Face example, u and g appear twenty times, so u-g becomes a token first. Then u-n, then h plus u-g, and "hug" is a single token.
- Sam When does it stop?
- Priya At a target vocabulary size. gpt-oss stops at 201,088 tokens; Llama 3 at 128 thousand. Modern tokenizers start from the 256 byte values instead of letters, so any text in any language can be encoded and nothing is ever unknown.
- Priya Your turn. When tokenizing new text, in what order are the merges applied?
- Priya In the order they were learned. The merge list is ordered, and that order decides how text splits.
- Sam What's actually stored on disk?
- Priya The vocabulary, mapping each token to its ID, and the ordered list of merges, plus the splitting pattern and the special tokens. Hugging Face puts it in a tokenizer dot json file; tiktoken stores each token's bytes with its rank.
- Sam And special tokens?
- Priya A chat is flattened into one sequence by a chat template. In OpenAI's harmony format each message becomes start, the role, message, the content, end, and the sequence finishes with start assistant, so the model knows it's its turn. Special tokens have their own IDs, and two are stop signals: call, when the model wants a tool, and return, when its answer is finished.
- Sam What can I try on the page?
- Priya A BPE trainer. Type a few words with counts, press merge, and watch the most frequent pair become a new token and the vocabulary grow. Then tokenize a word with the merges you learned and see its IDs.
- Sam Why does any of this matter at work?
- Priya Cost and limits are counted in tokens. Other languages usually take more tokens for the same meaning; Meta says Llama 3's larger vocabulary uses up to fifteen percent fewer tokens than Llama 2's. Models struggle to count letters because they never see letters. And special tokens are a security boundary: never paste user text into a template string, or a user could forge a system message. Use the library's chat template function.
- Sam Which tokenizers will I meet?
- Priya tiktoken, OpenAI's open-source library, with encodings like o200k base. gpt-oss's o200k harmony. Llama 3's 128 thousand token vocabulary. Hugging Face's tokenizers library for most open models. And for Claude or Gemini, use the provider's token-counting API.
- Sam The memory hook?
- Priya Merge the most common pair, then number the pieces.
- Sam Common mistakes?
- Priya Pasting user text into a template string. Assuming one token is one word. Counting with the wrong tokenizer. Asking the model to count letters. And using the wrong chat template for an open model.
- Sam And the lab?
- Priya Count tokens for a paragraph with two tiktoken encodings, then in two other languages. Print the pieces of a long number and an email address. Train a tiny tokenizer on your own documents, and read the special tokens a chat template adds.
1. The idea
The whole journey from text to the model, in four steps:
- Normalise and split. The text is split into rough chunks (words, spaces, punctuation, digits) by a fixed pattern, so pieces never cross, say, a word and the punctuation after it.
- Apply the merges. Each chunk starts as single bytes; the tokenizer joins neighbouring pieces using merge rules it learned in training, in the order it learned them.
- Look up the IDs. Each final piece is replaced by its number in the vocabulary, for example
" order"→ one ID. - Hand over to the model. The model turns each ID into a vector of numbers by looking up one row of its embedding table (Module 01b).
| Term | Meaning |
|---|---|
| Token | A piece of text the model reads or writes: a word, part of a word, a space plus a word, a digit group or a single byte. |
| Vocabulary | The fixed list of every token the model knows, each with an ID. gpt-oss uses 201,088 tokens; Llama 3 uses 128K. |
| Token ID | The token's position in the vocabulary: the only thing the model actually receives. |
| BPE (byte-pair encoding) | The most common way to build a vocabulary: start from bytes and repeatedly merge the most frequent neighbouring pair. |
| Special token | A reserved token, never produced from ordinary text, that marks structure: the start of a message, who is speaking, a tool call, the end. |
2. How it works
Training a BPE tokenizer
Training happens once, before the model itself is trained, on a large sample of the text the model will learn from. This tiny version uses the Hugging Face course's example corpus: five words and how often each appears.
Real tokenizers do exactly this on billions of words, and stop when the vocabulary reaches its target size: about 200,000 for recent OpenAI models, 128K for Llama 3. Most modern tokenizers use byte-level BPE: the starting vocabulary is the 256 possible byte values, not letters, so any text in any language, emoji or file can be encoded and nothing is ever "unknown". Frequent English words end up as one token; rare words, names and many non-English words take several.
Tokenizing your text
When you send a prompt, nothing is learned: the tokenizer splits the text, then applies the stored merges in the order they were learned.
What a tokenizer looks like on disk
A tokenizer is a small set of files that ships with the model weights. The model's weights only make sense with the exact tokenizer they were trained with.
Special tokens and chat templates
A chat is not sent as a list of messages. It is flattened into one sequence by a chat template, which wraps each message in special tokens. Here is the real format of OpenAI's open-weight gpt-oss models, called harmony, with the documented token IDs:
3. Try it yourself: train a tokenizer
Type a few words with how often they appear (word:count) or just a sentence. Press Merge next pair to run one training step, or Train to a vocabulary size. Then type a word to tokenize with the merges you've learned.
4. Why it matters at work
| Effect | Why it happens | What to do |
|---|---|---|
| Cost and limits are counted in tokens | Prices, context windows and rate limits all count tokens, not words or characters (Modules 02, 04). | Count with the model's own tokenizer or the provider's token-counting API, not a rule of thumb. |
| Other languages cost more | A vocabulary learned mostly from English has fewer merges for other scripts, so the same meaning takes more tokens. Bigger vocabularies help: Meta reports Llama 3's 128K tokenizer uses up to 15% fewer tokens than Llama 2's. | Measure token counts for your users' languages before estimating cost. |
| Models struggle to count letters | "strawberry" may be two or three tokens; the model never sees its letters one by one. | For exact character work (counting, reversing, checking spelling), use code or a tool. |
| Numbers and code split oddly | Long numbers are cut into digit groups; indentation and rare identifiers take many tokens. | Expect higher counts for code and data; prefer compact formats when cost matters. |
| The tokenizer is fixed per model | The embedding table has one row per token; change the tokenizer and the weights no longer line up. | Never mix one model's tokenizer with another model's weights. |
| Special tokens are a security boundary | If user text could produce <|start|> as a real special token, a user could forge a system message. Tokenizers keep them apart: tiktoken refuses to encode special-token text unless you explicitly allow it. | Never build prompts by pasting user text into a template string; use the library's chat-template function. |
See it in code
import tiktoken # OpenAI's open-source BPE tokenizer
enc = tiktoken.get_encoding("o200k_base")
ids = enc.encode("Where is my order A-1042?")
print(ids) # a short list of integers
print([enc.decode([i]) for i in ids]) # the text of each token
assert enc.decode(ids) == "Where is my order A-1042?" # lossless round trip
enc = tiktoken.encoding_for_model("gpt-4o") # the encoding a model uses
5. Tokenizers you'll meet
Checked 1 November 2026.
| Tool or model | What it is | Notes |
|---|---|---|
| tiktoken | OpenAI's fast BPE tokenizer library (Python, Rust core) | Encodings such as o200k_base (GPT-4o family); reversible and lossless; averages about four bytes per token |
| gpt-oss (OpenAI, open-weight) | o200k_harmony, a BPE tokenizer with 201,088 tokens | Requires the harmony chat format; available through tiktoken and the openai-harmony package |
| Llama 3 (Meta, open-weight) | A 128K-token vocabulary | Up to 15% fewer tokens than Llama 2's tokenizer |
| Hugging Face tokenizers | A Rust library for training and running BPE, WordPiece and Unigram tokenizers | Most open models ship a tokenizer.json it can load; Transformers' apply_chat_template applies each model's chat template |
| Claude, Gemini | Proprietary tokenizers | Use the provider's token-counting API for exact counts |
6. Remember it
How this hook works: what “Merge the most common pair, then number the pieces” means
What the slogan means, phrase by phrase
- “Merge the most common pair”
- BPE training: count neighbouring pairs across the corpus, merge the most frequent into a new token, repeat until the vocabulary is big enough.
- “then number the pieces”
- Every token has an ID; the model only ever sees those IDs.
Why this picture fits: it's exactly how a stenographer's shorthand grows, one most-common combination at a time.
The story → the concept
| Stenographer | Tokenizer |
|---|---|
| Letters of the alphabet | The 256 starting bytes |
| A new shorthand symbol | A merge rule and a new token |
| The shorthand dictionary | The vocabulary and merges files |
| Marks for "new speaker" | Special tokens and the chat template |
The trap it saves you from
Thinking the model reads words. It reads IDs for pieces, which explains its odd failures with spelling, counting letters and long numbers.
7. Common mistakes
8. Hands-on lab (roadmap week 1)
- Count tokens for one paragraph with tiktoken's
cl100k_baseando200k_base. Which is smaller, and why might that be? - Try other languages: translate the paragraph into two languages you know and compare token counts.
- Inspect the pieces: print each token's text for a sentence with a long number, an email address and some code.
- Train a tiny tokenizer with the Hugging Face
tokenizerslibrary on a few pages of your own documents, and look at its first 20 merges. - See a chat template: with Transformers, call
apply_chat_template(messages, tokenize=False)for an open model and read the special tokens it adds.
9. Self-check quiz
What does each step of BPE training do?
What does the model actually receive from the tokenizer?
Why do most modern tokenizers start from the 256 byte values?
When tokenizing new text, how are the merges applied?
What are special tokens like <|start|> and <|call|> for?
Why can't you swap in a different tokenizer for a trained model?
10. Go deeper
| Resource | Time | Why |
|---|---|---|
| Byte-Pair Encoding tokenization (Hugging Face LLM course) | 20 min | The algorithm with code; the worked example in this module comes from here. |
| tiktoken (OpenAI) | 10 min | A production tokenizer, its encodings and an educational BPE you can step through. |
| Chat templates (Hugging Face Transformers) | 15 min | How conversations become token sequences, and why the template must match. |
| The harmony response format (OpenAI Cookbook) | 15 min | A real chat format with roles, channels, tool calls and token IDs. |
| Introducing Meta Llama 3 (Meta) | 10 min | Why a bigger vocabulary means fewer tokens. |