InterviewKata
AI engineering · Module 01a · Level 1: How AI works

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.

A 4-minute conversation: Sam asks, Priya explains
0:00 / 4:21

1. The idea

A court stenographer can't write every word in full, so they build shorthand. First they give a symbol to the most common pair of letters, then to the most common pair of those, until frequent words and word-endings each have a single symbol. Rare words are still written, just with more symbols. A tokenizer is that shorthand, built by counting pairs in a huge pile of text, and each symbol gets a number.

The whole journey from text to the model, in four steps:

  1. 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.
  2. 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.
  3. Look up the IDs. Each final piece is replaced by its number in the vocabulary, for example " order" → one ID.
  4. 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).
TermMeaning
TokenA 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.
VocabularyThe fixed list of every token the model knows, each with an ID. gpt-oss uses 201,088 tokens; Llama 3 uses 128K.
Token IDThe 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 tokenA 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:

Why the template matters so muchChat models are still models that continue a sequence of tokens; the template is how they know who is speaking and when to answer. Hugging Face's documentation warns that with the wrong control tokens, models perform "drastically worse", and gpt-oss "should only be used with the harmony format". When you call a provider's API, it applies the template for you; when you run an open model yourself, you must use its template.

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.

WordCountCurrent pieces
Vocabulary (ID: token)
Merge rules, in order

4. Why it matters at work

EffectWhy it happensWhat to do
Cost and limits are counted in tokensPrices, 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 moreA 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 oddlyLong 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 modelThe 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 boundaryIf 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
The honest caveatsEach provider has its own tokenizer, and some (including Anthropic and Google) don't publish theirs: use their token-counting endpoints for exact numbers. The "about four characters per token" rule only holds for typical English. And tokenization isn't neutral: research and vendor reports consistently show non-English text costing more tokens, which affects price and how much fits in the context window.

5. Tokenizers you'll meet

Checked 1 November 2026.

Tool or modelWhat it isNotes
tiktokenOpenAI'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 tokensRequires the harmony chat format; available through tiktoken and the openai-harmony package
Llama 3 (Meta, open-weight)A 128K-token vocabularyUp to 15% fewer tokens than Llama 2's tokenizer
Hugging Face tokenizersA Rust library for training and running BPE, WordPiece and Unigram tokenizersMost open models ship a tokenizer.json it can load; Transformers' apply_chat_template applies each model's chat template
Claude, GeminiProprietary tokenizersUse the provider's token-counting API for exact counts

6. Remember it

Memory hook: "Merge the most common pair, then number the pieces"Training counts pairs and merges the most frequent, again and again; using it applies those merges in order and swaps each piece for its ID.
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

StenographerTokenizer
Letters of the alphabetThe 256 starting bytes
A new shorthand symbolA merge rule and a new token
The shorthand dictionaryThe 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

Pasting user text into a template stringBuild prompts with the library's chat-template function, so user text can never become a special token.
One token = one wordA token is often part of a word, and non-English text can take several tokens per word. Count, don't guess.
Counting with the wrong tokenizerDifferent models split the same text differently. Use the model's own tokenizer or the provider's counter.
Asking the model to count lettersIt sees tokens, not letters. Use code for exact character work.
Using the wrong chat templateAn open model with another model's template answers badly or not at all. Use the template shipped with the model.

8. Hands-on lab (roadmap week 1)

  1. Count tokens for one paragraph with tiktoken's cl100k_base and o200k_base. Which is smaller, and why might that be?
  2. Try other languages: translate the paragraph into two languages you know and compare token counts.
  3. Inspect the pieces: print each token's text for a sentence with a long number, an email address and some code.
  4. Train a tiny tokenizer with the Hugging Face tokenizers library on a few pages of your own documents, and look at its first 20 merges.
  5. 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?

Each merge adds one token; training stops at the target vocabulary size.

What does the model actually receive from the tokenizer?

The IDs are then turned into vectors by looking up rows in the embedding table.

Why do most modern tokenizers start from the 256 byte values?

Rare text just takes more tokens; it never becomes an "unknown" token.

When tokenizing new text, how are the merges applied?

The merge list is ordered; the order decides how text splits.

What are special tokens like <|start|> and <|call|> for?

The chat template uses them to flatten a conversation into one token sequence.

Why can't you swap in a different tokenizer for a trained model?

Token ID 1,234 must mean the same piece the model learned during training.

10. Go deeper

ResourceTimeWhy
Byte-Pair Encoding tokenization (Hugging Face LLM course)20 minThe algorithm with code; the worked example in this module comes from here.
tiktoken (OpenAI)10 minA production tokenizer, its encodings and an educational BPE you can step through.
Chat templates (Hugging Face Transformers)15 minHow conversations become token sequences, and why the template must match.
The harmony response format (OpenAI Cookbook)15 minA real chat format with roles, channels, tool calls and token IDs.
Introducing Meta Llama 3 (Meta)10 minWhy a bigger vocabulary means fewer tokens.