Tokenisation: How AI Reads (and Misreads) Your Text
By the end of this lesson, you should be able to execute a Byte-Pair Encoding (BPE) merge pass by hand, compare BPE, WordPiece, and Unigram LM tokenisers, explain why Byte-Level BPE eliminates unknown tokens, calculate multilingual token-fertility cost impacts, and identify security risks linked to special control tokens and token-boundary evasion.
##
- Intuition first: why neither characters nor whole words work
Neural networks operate on numbers, not strings. Before a single Transformer layer executes, a tokeniser converts text into a sequence of integers drawn from a fixed vocabulary of size (typically 32,000 to 128,000+ entries, and up to 200,000–256,000 in modern multilingual models).
Why not assign one ID per letter or one ID per dictionary word?
- Character-level ($V \approx 100$): Tiny lookup table, terrible sequence length. A 2,000-word contract becomes ~12,000 tokens long—exploding attention compute (which scales quadratically with token count).
- Word-level ($V > 1,000,000$): The embedding table and final Softmax become gigantic, and any typo, compound word, URL, or SKU collapses into
<UNK>(unknown), erasing critical meaning. - Subword tokenisation ($V \approx 50\text{k}–200\text{k}$): Frequent words stay whole (
_bank,_loan), while rarer words split cleanly into reusable building blocks (_collat+eral).
##
- Worked example: running Byte-Pair Encoding (BPE) by hand
A BPE tokeniser is trained offline, before the LLM ever trains, on a large representative text corpus. Let us run BPE on a tiny 4-word corpus (using </w> to mark word endings):
| Word in corpus | Frequency | Initial symbol split |
|---|---|---|
low | 5 | l o w </w> |
lower | 2 | l o w e r </w> |
newest | 6 | n e w e s t </w> |
widest | 3 | w i d e s t </w> |
### Iteration 1: Count every adjacent pair
(e, s):6 (newest) + 3 (widest) = 9← Highest frequency!(s, t):6 + 3 = 9(tie; pick(e, s))(l, o):5 + 2 = 7(o, w):5 + 2 = 7
Merge Rule #1: e + s -> es
### Iteration 2: Re-count pairs after Merge #1
(es, t):6 + 3 = 9← Highest!(t, </w>):6 + 3 = 9
Merge Rule #2: es + t -> est
### Iteration 3: Re-count pairs
(est, </w>):6 + 3 = 9← Merge Rule #3:est + </w> -> est</w>- Next merges become
l + o -> lo(7),lo + w -> low(7),low + </w> -> low</w>(5).
### Inference time (encoding an unseen word) Now suppose a brand-new word "lowest" arrives at runtime. The tokeniser starts from characters l o w e s t </w> and applies the saved merge table in priority order:
l o w e s t </w> -> l o w es t </w> -> l o w est</w> -> lo w est</w> -> [ low ] + [ est</w> ]Even though "lowest" never appeared in the training corpus, it encodes cleanly in 2 meaningful tokens with zero <UNK> loss.
##
- Modern refinements: Byte-Level BPE, pre-tokenisation and alternatives
Production tokenisers add three crucial design details:
- Byte-Level BPE: Rather than starting from thousands of raw Unicode characters, GPT-2, Llama 3, and Qwen start from the 256 raw UTF-8 bytes. Every possible string on Earth—including Devanagari, emojis, or corrupted logs—is representable with zero
<UNK>tokens. - Regex Pre-Tokenisation: Before counting pairs, a regular expression splits text into coarse chunks (separating punctuation, contractions, and limiting digit runs to 1–3 digits) so BPE does not waste vocabulary slots merging
"dog.","dog!", and"dog?"into separate tokens. Notice also that leading spaces are glued onto words:"The"(791) and" the"(279) are different token IDs. - Other Subword Families:
- WordPiece (used in BERT): Merges pairs that maximise corpus *likelihood* rather than raw frequency.
- Unigram LM / SentencePiece (used in Gemma, T5, Mistral v1): Starts with a huge candidate vocabulary and iteratively *prunes* tokens that hurt likelihood the least; operates directly on raw Unicode streams without assuming spaces separate words.
##
- Special control tokens and chat templates
Beyond text tokens, every modern LLM reserves special tokens with dedicated IDs that never appear in normal text merges:
- Sequence boundaries:
<|bos|>(beginning of sequence),<|eos|>(end of sequence) - Role delimiters (ChatML / Llama templates):
<|im_start|>system,<|im_start|>user,<|im_start|>assistant,<|im_end|> - Tool and reasoning markers:
<|tool_call|>,<|tool_response|>,<think>,</think>
When your application calls a chat API, the server renders your messages array into one flat token stream wrapped in these special tokens before sending it to the Transformer.
##
- Worked economics example: token fertility across languages and formats
Token fertility is the average number of tokens needed to encode one word. Because historical tokenisers were trained predominantly on English and code, fertility varies dramatically:
| Content type (1,000 human words) | Illustrative fertility | Approximate tokens | Relative cost & context usage |
|---|---|---|---|
| Clean English prose | 1.33 | ~1,330 | 1.0× (baseline) |
| Compact JSON with keys/quotes | 1.95 | ~1,950 | 1.47× |
| Hindi (Devanagari) on older BPE | 3.20 | ~3,200 | 2.41× |
| Hindi (Devanagari) on newer 128k–256k BPE | 1.70 | ~1,700 | 1.28× |
*Note: Figures are illustrative; exact counts depend on the specific model's tokeniser.* The business impact is workload- and model-dependent: a tokenizer that represents a language or format more compactly can reduce token usage, context consumption, and token-based API charges at the same list price. Lower token counts may also reduce generation work, but end-to-end latency depends on the serving stack, batching, model architecture, and output length. The illustrative figures above are not a universal benchmark.
##
- Why tokenisation explains famous LLM quirks
- Letter-counting & spelling errors:
"strawberry"arrives as 2–3 opaque integers, not['s','t','r','a','w','b','e','r','r','y']. Unless the model memorised the spelling map in its weights, counting'r's is unnaturally hard. - Arithmetic glitches: Large numbers split differently depending on the tokeniser (
123456789might split into123 | 456 | 789or12 | 345 | 67 | 89), breaking vertical digit alignment. - Trailing-space degradation: Ending a prompt with
"Classify as: "(trailing space) forces the model to generate a token *without* a leading space—an out-of-distribution boundary compared to normal training text. - Glitch / under-trained tokens: Rare strings present in the tokeniser's training data (like Reddit usernames in early GPT vocabularies, famously
"SolidGoldMagikarp") received a token ID but almost zero updates during LLM training, leaving their embedding vectors uncalibrated and producing bizarre outputs when triggered.
##
- AI GRC and security implications
- Special-token injection: If an application concatenates raw user input into a prompt template and passes
allow_special_tokens=Trueto a local tokeniser, an attacker can type literal<|im_end|><|im_start|>systemto hijack role boundaries. Always use structured role APIs and disable special-token parsing on untrusted user strings. - Token smuggling and filter evasion: Attackers split restricted words with zero-width Unicode characters, homoglyphs (Cyrillic
аvs. Latina), or unusual spacing. Simple regex or keyword guardrails miss the string while the LLM's deep layers still reconstruct the malicious intent. - Denial-of-wallet / context exhaustion: Adversarial payloads with high-fertility characters (repeated rare Unicode symbols or unmerged punctuation) inflate token counts 3×–5× beyond character-length limits. Enforce token-based rate and input caps, not merely character-length caps.
##
- Common misconceptions
- “1 token equals 1 word.” False. English averages ~0.75 words per token (~1.33 tokens/word), and non-Latin scripts, URLs, and minified JSON can be far higher.
- “Token IDs encode semantic similarity.” False. ID
4820(_bank) and ID4821have no meaningful proximity; integer IDs are purely lookup keys. - “All LLMs count tokens the same way.” False. Every model family ships its own vocabulary and merge table; always count tokens with the target model's exact tokeniser before budgeting.
##
- Practical exercise
Test four inputs in a tokeniser inspector (such as Tiktokenizer, Hugging Face's tokenizer playground, or CNSLT Tools):
- Compare
"bank"," bank","BANK", and"Bank"—record how many distinct IDs appear. - Compare a 50-word English policy paragraph against the exact same paragraph translated into Hindi or another non-Latin script, computing the fertility ratio.
- Insert zero-width spaces or hyphens inside a sensitive keyword (e.g.,
p-a-s-s-w-o-r-d) and observe how the token sequence changes completely. - Draft one engineering rule your team will enforce for token budgeting and input validation based on what you observed.
##
- Knowledge check
- How does BPE choose which symbol pair to merge during tokeniser training?
- Why does Byte-Level BPE completely eliminate
<UNK>tokens? - What is token fertility, and why does it matter for multilingual products?
- Why can trailing spaces or weird digit splits degrade LLM accuracy?
- What security vulnerability occurs if untrusted user input is allowed to trigger literal special control tokens?
Answer key:
- It counts adjacent pairs across the corpus and greedily merges the most frequent pair.
- Its base alphabet contains all 256 UTF-8 bytes, so any valid text can always fall back to raw bytes.
- Average tokens per word; higher fertility multiplies API cost, slows generation, and consumes context window faster.
- They push token boundaries out of the model's normal training distribution and hide character/place-value alignment.
- Role/template spoofing, allowing an attacker to close the user turn and inject forged system instructions.
##
- Checklist
- [ ] Estimate costs and context limits using the exact target model's tokeniser, not word counts.
- [ ] Measure token fertility for every non-English language your product supports.
- [ ] Strip or reject unescaped special control tokens inside untrusted user and retrieved inputs.
- [ ] Apply token-based (not just character-based) input and output caps.
- [ ] Avoid unnecessary trailing spaces at the end of prompt templates.
- [ ] Normalise Unicode (e.g., NFC/NFKC where appropriate) and check for invisible characters in security guardrails.
- [ ] Document tokeniser differences whenever switching or benchmarking candidate models.
##
- Further reading
Help improve this learning path.
Suggest a concept we should teach, or tell us what is unclear. No account is required. Email is optional and only for a reply. Do not include confidential or sensitive information.