Tokenization
How text becomes tokens, BPE/WordPiece trade-offs, and why token counts drive cost and context limits.
In plain words
The model doesn't read letters or words. It reads little chunks of text that it has seen very often, and each chunk has a number.
Think of it like…
A Scrabble bag whose tiles are not just letters but common chunks: "ing", "the", "tion". Everyday words come out as one tile; a rare name has to be spelled out with several small tiles. You are billed per tile placed.
Where you’ve seen it
A support-bot team budgets for 1,500-word tickets at about 2,000 tokens each. After launching in Indian languages, the same-length tickets average 5,500 tokens because the tokenizer splits non-Latin scripts into many more pieces, so cost per ticket nearly triples and the context fills sooner. They fix it by measuring tokens with the provider's tokenizer before pricing each market.
Words you’ll hear
- BPE
- Byte-pair encoding: builds a vocabulary by merging the most frequent adjacent pairs of symbols.
- Vocabulary size
- Number of distinct tokens; larger vocabularies shorten sequences but enlarge the embedding table.
- Token id
- The integer the model receives; the text itself never enters the network.
- Special tokens
- Reserved ids for boundaries such as end-of-sequence or chat role markers.
Visual diagram
Theory & deep dive
How BPE builds a vocabulary
Training starts with every byte (or character) as its own token. The algorithm counts adjacent pairs across a large corpus, merges the most frequent pair into a new token, and repeats until the vocabulary reaches its target size. The ordered list of merges is the tokenizer: to encode new text, apply the same merges in the same order. Byte-level BPE guarantees any string can be encoded, even emoji or unseen scripts, because the worst case is single bytes.
Alternatives exist. WordPiece (used by BERT) picks merges by likelihood and marks continuation pieces with ##; Unigram (used with SentencePiece) starts from a large vocabulary and prunes it. Production chat models mostly use byte-level BPE variants, often with a regex pre-split so merges don't cross word or digit boundaries.
English prose averages roughly 1.3 tokens per word, code and JSON are denser in punctuation, and scripts under-represented in the training corpus can reach 3 to 5 tokens per word. Always measure with the real tokenizer instead of using a fixed ratio.
Consequences you can see in practice
Because the model sees chunks, character-level tasks are indirect: counting the letters in "strawberry" or reversing a string requires the model to infer spelling from tokens it never saw split. Numbers may tokenize inconsistently ("1234" as one piece, "1,234" as three), which affects arithmetic. Trailing spaces, different casing or an extra newline change the token sequence and therefore the output.
Vocabulary size is a trade-off. A bigger vocabulary compresses text into fewer tokens, which saves context and compute per sentence, but the embedding and output layers grow with it and rare tokens get little training signal. Tokenizers are also not interchangeable: a prompt measured with one provider's tokenizer can differ by 10 to 30 percent under another's, so use the matching counter (for example tiktoken for OpenAI models, or the provider's count-tokens endpoint).
enc = tiktoken.get_encoding("o200k_base"); n = len(enc.encode(prompt)) gives the exact input token count for models that use that encoding, so you can reject or truncate oversize prompts before paying for them.
How it works, step by step
Step 1 of 41. Normalise and pre-split
Apply any Unicode normalisation and split text into coarse pieces (words, digits, punctuation) so merges stay sensible.
- Deterministic
- same text, same split
When to use it & trade-offs
What it is
Tokenization converts text into the integer ids a language model actually reads. Modern tokenizers use subword schemes such as byte-pair encoding (BPE): start from single bytes or characters, repeatedly merge the most frequent adjacent pair, and stop at a fixed vocabulary size (often 32,000 to 200,000 entries). Common words become one token, rare words split into pieces, and anything can be represented, because the fallback is raw bytes.
Why it matters: Tokens, not words or characters, are what you pay for, what fills the context window, and what the model predicts one at a time. The same sentence can cost twice as many tokens in Hindi as in English, a JSON blob full of punctuation costs more than prose, and a tokenizer quirk explains why models miscount letters in a word. Engineers who understand tokens estimate cost, budget context and debug odd behaviour correctly.
When to reach for it
- Counting tokens before sending prompts to control cost
- Choosing chunk sizes for retrieval in tokens, not characters
- Explaining model quirks on spelling, digits and rare words
When to avoid or be careful
- Estimating cost from word counts or fixed ratios
- Assuming one tokenizer's counts apply to another model
- Relying on the model to count or reverse characters exactly
Tokenization schemes
Strengths: Handles any text; good compression on common words and code.
Watch out: Weaker on underrepresented scripts; odd splits for numbers.
Strengths: Language-agnostic training; flexible vocabularies.
Watch out: Different tooling and token boundaries per model.
Strengths: No unknown tokens; simple.
Watch out: Very long sequences, so slower and costlier attention.
Interview signals & numbers to know
When this topic comes up
- “Why is my bill higher in Hindi?”
- “The model can't count letters in a word”
- “How big a document fits in the context window?”
- BPE and vocabulary size
- Chunking for RAG
Benchmarks & rules of thumb
- ≈ 1.3
- tokens per English word on average
- 32K – 200K
- typical vocabulary sizes
- ≈ 4 characters
- per token in English prose (rule of thumb)
Common mistakes & follow-ups
Common interview mistakes
- Budgeting context by characters or words and hitting the limit on code or non-English input.
- Counting tokens with the wrong tokenizer and being off by 10 to 30 percent.
- Trimming a prompt by whitespace and silently changing the tokens (and the model's behaviour).
Likely interviewer follow-ups
- How does BPE build its vocabulary?
- Why do some languages cost more tokens for the same meaning?
- Why do models struggle with counting letters?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Tokenization with generative AI interview Q&A and hands-on practice.