Foundation Keywords
Before diving into tokenization, these are the core concepts you need. Each entry includes a definition, historical context, worked examples, and how it connects to modern LLMs.
A character is a single symbol in a writing system — a letter, digit, punctuation mark, emoji, or whitespace. It is an abstract concept; the way a character is stored as numbers is determined by an encoding.
ASCII maps 128 characters — English letters, digits, punctuation, and control codes — to integers 0–127. Each character fits in 7 bits. It was the dominant encoding for early computers and the internet.
Unicode is a universal standard that assigns a unique code point (a number) to every character in every human writing system. Unicode 15 (2022) defines over 149,000 characters across 161 scripts.
UTF-8 encodes every Unicode code point as 1–4 bytes. It is backward-compatible with ASCII (the first 128 code points use exactly 1 byte each) and is by far the most common encoding on the web and in modern software.
é → 0xC3 0xA9 (2 bytes)
你 → 0xE4 0xBD 0xA0 (3 bytes)
😀 → 0xF0 0x9F 0x98 0x80 (4 bytes)
UTF-16 uses 2 or 4 bytes per character and is used internally by Windows, Java, and JavaScript. UTF-32 uses a fixed 4 bytes for every character — simple but memory-heavy.
UTF-16: 48 00 69 00 20 00 60 4F (8 bytes)
UTF-32: 16 bytes total
A code point is the abstract integer assigned to each character in the Unicode standard, written as U+XXXX. There are 1,114,112 possible code points (U+0000 to U+10FFFF).
U+00E9 → é (e with acute)
U+4F60 → 你 (you, in Chinese)
U+1F600 → 😀 (grinning face)
A token is the smallest chunk of text an LLM processes. Tokens can be whole words, subwords, characters, or bytes — depending on the tokenizer. Every token is mapped to an integer ID from the model's vocabulary.
BERT (WP): ["Token", "##ization"]
char-level: ["T","o","k","e","n","i","z","a","t","i","o","n"]
A model's vocabulary (or vocab) is the fixed list of all tokens it recognises, each assigned a unique integer ID. During inference, every input token must map to a vocab ID; during generation, the model picks the next ID from this same list.
GPT-2: 50,257 tokens
GPT-4 / CL3: ~100,000 tokens
LLaMA-3: 128,256 tokens
Each token in the vocabulary is assigned a unique integer, its Token ID. This is the actual input to a neural network — not the text itself. The tokenizer converts text → IDs (encoding) and converts IDs → text (decoding).
↓ tokenize
[15496, 995]
"I love AI"
↓ tokenize
[40, 1842, 9552]
Special tokens are reserved tokens that convey structural meaning rather than text content. They tell the model where a sequence starts, ends, is padded, or where a different speaker begins.
[SEP] – sentence separator (BERT)
[PAD] – padding to equal length
[UNK] – unknown / out-of-vocab
<s> – start of sequence
</s> – end of sequence
<|im_start|> – speaker turn (ChatML)
The context window (or context length) is the maximum number of tokens — input + output — that a model can process in a single call. Tokens beyond this limit are silently dropped.
GPT-4: 128,000 tokens (~96,000 words)
Claude 3: 200,000 tokens (~150,000 words)
Gemini 1.5: 1,000,000 tokens
An embedding converts a token ID into a dense vector of floating-point numbers (e.g., 768 or 4096 dimensions). These numbers encode semantic meaning: similar words cluster together in vector space.
"queen" → [0.31, -0.13, 0.86, 0.12, ...]
"apple" → [-0.44, 0.72, -0.21, 0.63, ...]
The embedding matrix is a parameter table of shape vocab_size × d_model. Given a token ID, the model simply looks up the corresponding row. These weights are learned during training.
50,257 tokens × 768 dims
= 38.6 million parameters
LLaMA-3 (70B) embedding matrix:
128,256 tokens × 8,192 dims
= ~1.05 billion parameters
Word2Vec trains shallow neural networks to predict a word from its neighbours (CBOW) or predict neighbours from a word (Skip-gram). The internal weights become word embeddings that capture semantic relationships.
≈ vec("queen") ✓
vec("Paris") − vec("France") + vec("Italy")
≈ vec("Rome") ✓
Semantic similarity is quantified as the angle between two embedding vectors — specifically, cosine similarity. A score of 1.0 means identical meaning, 0 means unrelated, −1 means opposite.
sim("cat", "dog") = 0.76 (related)
sim("cat", "democracy")= 0.04 (unrelated)
sim("hot", "cold") = 0.31 (antonyms — closer than you'd think!)
A corpus is the body of text used to train a tokenizer or language model. The tokenizer vocabulary is built to reflect the most frequent substrings in the corpus — so the corpus composition directly shapes what gets a token.
GPT-3: Common Crawl + Books + Wikipedia (570 GB)
LLaMA-3: ~15 trillion tokens of curated web text
BERT: Wikipedia + BookCorpus (16 GB)
Normalisation is the first stage of the tokenization pipeline. It transforms raw text into a consistent form — lowercasing, removing accents, applying Unicode normal forms (NFC, NFD, NFKC, NFKD) — before splitting into tokens.
NFD: "Héllo" (decomposed: e + combining accent)
NFC: "Héllo" (recomposed: single U+00E9)
NFKC: "Hello" (compatibility: drops accent)
BERT uses: NFD + lowercase + strip accents
Attention is the core mechanism of transformer models. Each token "attends to" other tokens to build context. The attention mask is a binary tensor (1 = real token, 0 = padding) that prevents the model from attending to padding tokens.
IDs: [ 464, 3797, 3332, 0, 0]
Mask: [ 1, 1, 1, 0, 0]
An out-of-vocabulary word is one that the tokenizer cannot represent as a single token from its vocab. Word-level tokenizers replace it with a special [UNK] token. Subword tokenizers handle OOV by decomposing the word into smaller known pieces.
Word-level: [UNK] ← information lost
WordPiece: ["Chat", "##GP", "##T"]
Byte-level BPE: ["Ch","at","G","PT"] or bytes
← no information lost
Padding extends short sequences to a fixed length by appending [PAD] tokens. Truncation cuts long sequences to fit within the model's max length. Both are necessary for batching multiple inputs together in a single tensor.
"Hello" → [ 15496, 50256, 50256, 50256, 50256, 50256]
"Hello world" → [15496, 995, 50256, 50256, 50256, 50256]
padding=True, truncation=True with the Hugging Face tokenizer. Never manually truncate — the tokenizer handles edge cases correctly.- Explain what a token is and why LLMs use tokens instead of raw words
- Describe the full tokenization pipeline: normalisation → pre-tokenisation → model → post-processing
- Compare the 5 major tokenization algorithms (Word, Character, BPE, WordPiece, SentencePiece/Unigram)
- Read and interpret tokenizer output including token IDs, attention masks and special tokens
- Estimate token counts and understand the cost, context-window and quality implications in the workplace
- Apply practical strategies to reduce token usage when working with LLM APIs
| # | Section | Format | Time |
|---|---|---|---|
| 1 | Welcome & scene-setting | Discussion + warm-up | 10 min |
| 2 | What is a token? | Lecture + visual | 20 min |
| 3 | Full tokenization pipeline HF | Lecture + code walkthrough | 30 min |
| 4 | Why it matters at work | Case studies | 25 min |
| 5 | Common pitfalls & tips | Facilitated discussion | 15 min |
| 6 | Knowledge check quiz | Individual | 15 min |
| 7 | Debrief & close | Q&A | 5 min |
- Projector / shared screen for live code demos
- Access to platform.openai.com/tokenizer (no login needed)
- Access to Google Colab for optional Hugging Face code demos
- Printed quick-reference cards (one per learner)
- Whiteboard or flip chart for BPE step-through exercise
- Printed or digital 10-question quiz
Every modern tokenizer executes exactly four steps before the model ever sees your text. Understanding each step helps you debug unexpected outputs and write better prompts.
Cleans the text before any splitting occurs. Operations include: lowercasing, Unicode normalisation (NFC / NFKC), accent removal, and whitespace stripping.
BERT example: "Héllò hôw are ü?" → "hello how are u?"
GPT-2: preserves case and formatting — produces richer but more complex token sequences.
Why it matters: Inconsistent text (e.g. "Résumé" vs "Resume") produces different tokens for the same meaning — wasting context window and increasing cost.
Splits text into rough "words" before the subword algorithm runs. Different tokenizers split differently:
| Tokenizer | Pre-tokenisation rule | Example |
|---|---|---|
| BERT (WordPiece) | Split on whitespace + punctuation | "Hello," → ["Hello", ","] |
| GPT-2 (BPE) | Split on whitespace, keep spaces as Ġ prefix | "Ġhow", "Ġare" |
| T5 (SentencePiece) | Treat raw bytes, space = ▁ symbol | "▁Hello", "▁world" |
The core tokenization step. Takes pre-tokenised words and applies the learned merge rules (BPE), likelihood scores (WordPiece / Unigram), or language-agnostic byte-stream rules (SentencePiece) to produce subword tokens.
Output: a sequence of subword strings. e.g. "tokenization" → ["token", "ization"]
BPE in one sentence: Start with characters; repeatedly merge the most frequent adjacent pair into a new token until vocabulary size is reached.
Adds model-specific special tokens and produces final model inputs. This is also where padding and truncation happen.
| Special token | Meaning | Model |
|---|---|---|
| [CLS] | Classification / start of sequence | BERT |
| [SEP] | Separator between sequences | BERT |
| [PAD] | Padding to uniform length | Most models |
| [UNK] | Unknown token (out-of-vocab) | Most models |
| <s> / </s> | Start / end of sequence | RoBERTa, T5 |
| <|endoftext|> | End of document | GPT-2, GPT-4 |
| <|im_start|> | Chat message boundary | GPT-4, Mistral |
Padding & Truncation: When batching multiple inputs, all sequences must be the same length. Padding adds [PAD] tokens to shorter sequences. Truncation removes tokens from sequences that exceed the model's context window. Attention masks (1 = real token, 0 = padding) tell the model which tokens to ignore.
This is exactly what happens under the hood when you call a tokenizer:
Facilitator note: Show this live in Google Colab or run it on a shared screen. The jump from human-readable words to a list of numbers is the "aha" moment for most non-technical learners.
Select a type above
BPE starts with individual characters and repeatedly merges the most frequent adjacent pair. Here's the algorithm on the corpus: "hug"(×10), "pug"(×5), "pun"(×12), "bun"(×4), "hugs"(×5)
This continues until the vocabulary reaches the target size (e.g. 50,000 tokens for GPT-2). The resulting merge rules are saved and applied to any new text at inference time.
Byte-level BPE (GPT-2, Claude): Instead of starting with Unicode characters, it starts with all 256 bytes. This guarantees that any character — including emojis, rare symbols, and multi-script text — can be encoded without [UNK] tokens.
| Model family | Tokenizer | Vocab size | Notes |
|---|---|---|---|
| GPT-2 / GPT-3 / GPT-4 | Byte-level BPE | ~50K / ~100K | Uses tiktoken library; no [UNK] |
| Claude (Anthropic) | BPE variant | ~100K | Similar to GPT-4 tokenizer |
| BERT / RoBERTa / DistilBERT | WordPiece | ~30K | [CLS], [SEP], [MASK] special tokens |
| LLaMA 2 / Gemma | SentencePiece (BPE) | ~32K | Uses ▁ for spaces |
| LLaMA 3 | SentencePiece (BPE) | ~128K | Expanded vocab for better multilingual coverage |
| T5 / mT5 | SentencePiece (Unigram) | ~32K | Fully language-agnostic |
| Mistral / Mixtral | SentencePiece (BPE) | ~32K | Shares Llama 2 tokenizer |
Sentence: "The quick brown fox jumps over the lazy dog."
The AutoTokenizer class automatically selects the correct tokenizer for any model. It's the recommended starting point for all tokenization tasks.
Training a domain-specific tokenizer for your own corpus (e.g. legal, medical, technical):
When to build a custom tokenizer: Your corpus uses domain-specific jargon (medical codes, legal terms, product SKUs) that common tokenizers fragment inefficiently. A custom tokenizer reduces token counts and improves model accuracy for your domain.
Type any text to see a simulated BPE tokenization with token IDs.
Approximate tokens to express "Good morning, how are you?" across languages: