Tokens
The atomic processing unit of every language model. Before attention, before embeddings, before generation — there are tokens. This is where machine understanding of language begins.
Tokens: How the Wise Scholar Reads and Speaks
The Wise Scholar does not read letter-by-letter (which would exhaust memory in quadratic $O(N^2)$ self-attention steps) nor with whole infinite words (which would require an infinite dictionary). Instead, the scholar perceives language as a stream of standardized concept blocks (Tokens). Each block has a permanent catalog index (Token ID) pointing to a row in the scholar's memory matrix.
Explore Live Tokenization in Real Time
See how modern state-of-the-art tokenizers slice words, code, emojis, and non-Latin scripts into subword tokens, assign integer IDs, and impact context window budgets.
OverviewWhat tokens are and why they exist
"If you type the word 'unbelievable' into an AI chatbot, how does the machine actually 'read' it? Does it read the letters one-by-one, u-n-b-e-l-i-e-v-a-b-l-e, or does it see it as a single solid word?"
We know computers only process binary and numbers. But how do we cut human sentences into discrete mathematical chunks without losing the structure and spaces?
'unbelievable' into three clean standardized pieces from its pre-trained dictionary: ['un', '##believ', '##able']. It maps these to standard numbers (Token IDs). To the model, your word is simply three integers: [2891, 10245, 3098]!
A token is the smallest discrete unit of text that a language model processes. It is not a word, not a character, not a sentence — it is a model-specific piece chosen by a tokenizer algorithm trained on text data.
💡 The fundamental insight: Neural networks cannot process raw strings. They need numbers. Tokenization is the deterministic bridge: text → discrete pieces → integer IDs → embedding vectors → model math.
What a token can be
A whole common word ("the", "is"), a word fragment ("##ing", "un"), a punctuation mark, a space, a number, or even a single Unicode byte as fallback.
What a token is NOT
A word (one word can be many tokens). A character (one character can be fractionally a token). A meaning-bearing unit (meaning comes from embeddings, not IDs).
SubtopicsAll 12 token subtopics — your complete study list
Each subtopic below is a fully elaborated learning page with interactive demos, code, Feynman challenges, and mini-projects. Study them in the order shown for best results.
PipelineThe complete tokenization pipeline — visualized
Every tokenizer — regardless of model — transforms raw text through these five stages before handing integers to the neural network.
flowchart LR
A["📝 Raw Text\n'Hello World!'"] --> B["🔧 Normalize\nlowercase, unicode"]
B --> C["✂️ Pre-tokenize\nsplit on spaces/punct"]
C --> D["🔬 Subword model\nBPE / WordPiece / SP"]
D --> E["🏷️ Post-process\nadd [CLS] [SEP]"]
E --> F["🔢 Encode\ntoken→integer ID"]
F --> G["📦 Model Input\n[101, 7592, 2088, 102]"]
style A fill:#1a1e2e,stroke:#252a40,color:#b0b8d8
style G fill:#1a1e2e,stroke:#3b82f6,color:#93c5fd
Stage 1 — Normalize
Lowercase, Unicode normalization (NFC/NFKC), accent stripping, whitespace handling. Varies per tokenizer.
Stage 2 — Pre-tokenize
Split into candidate words by whitespace, punctuation, or regex. Creates inputs for the subword model.
Stage 3 — Subword model
Apply BPE merges, WordPiece MaxMatch, or SentencePiece Unigram to produce final token strings.
Stage 4 — Post-process
Add model-specific special tokens: [CLS] at start, [SEP] at end (BERT), or <|endoftext|> (GPT).
Core ConceptsThe five things you must be able to explain
🔤 Token
A model-defined text piece. May be a word, subword, punctuation, or byte. Produced by the tokenizer. Has no inherent meaning — meaning comes from embeddings.
🔢 Token ID
An integer that is the row index into the embedding matrix. ID 500 is NOT "more meaningful" than ID 20. It's just a different vocabulary address.
📖 Vocabulary
The complete fixed set of token entries. Built once from corpus during tokenizer training. Cannot be changed without retraining the model's embedding layer.
🧩 Subword
A token that is a piece of a word. "tokenization" → ["token", "##ization"]. Enables finite vocabulary to cover any text without [UNK].
🏷️ Special Token
Reserved vocabulary entries that add structure: [CLS] marks classification input, [SEP] separates sequences, [PAD] aligns batches, [MASK] enables MLM training.
⚙️ Tokenizer
A deterministic pre-processor (no neural weights). Takes raw text, applies all 5 pipeline stages, returns integer ID sequences. Model-specific and fixed.
Learning PathRecommended study order for tokens
CodeEssential tokenizer operations in Python
These are the operations you'll use in every LLM project. Run them, inspect them, understand every line before moving to embeddings.
from transformers import AutoTokenizer
# ── Load a tokenizer ──────────────────────────────────
tok = AutoTokenizer.from_pretrained("bert-base-uncased")
# ── Encode text → token IDs ───────────────────────────
text = "The tokenizer is surprisingly useful."
ids = tok.encode(text)
print("IDs:", ids)
# → [101, 1996, 19204, 17629, 2003, 14477, 6937, 1012, 102]
# ── See the token strings ─────────────────────────────
tokens = tok.tokenize(text)
print("Tokens:", tokens)
# → ['the', 'token', '##izer', 'is', 'surprisingly', 'useful', '.']
# Note: 'tokenizer' → ['token', '##izer'] (two tokens, one word!)
# ── Decode IDs back to text ───────────────────────────
decoded = tok.decode(ids, skip_special_tokens=True)
print("Decoded:", decoded)
# ── Vocabulary size ───────────────────────────────────
print("Vocab size:", tok.vocab_size) # → 30522
# ── Special token IDs ─────────────────────────────────
print(tok.special_tokens_map)
# → {'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]',
# 'cls_token': '[CLS]', 'mask_token': '[MASK]'}
# ── Token count vs word count ─────────────────────────
words = len(text.split())
n_toks = len(tok.tokenize(text))
print(f"Words: {words}, Tokens: {n_toks}, Ratio: {n_toks/words:.2f}x")
# → Words: 5, Tokens: 7, Ratio: 1.40x
"bert-base-uncased" with "gpt2" or "t5-small" and compare the tokenizations. The same text produces different tokens with different tokenizers.CompareTokenizer algorithms side by side
| Algorithm | Core idea | Selection criterion | Pre-tokenization | Marker style | Used by |
|---|---|---|---|---|---|
| BPE | Merge most frequent adjacent pair | Frequency count | Yes (whitespace/regex) | Ġ word-start (GPT-2) | GPT-2, GPT-3/4, LLaMA |
| WordPiece | Merge pair that maximizes corpus likelihood | Likelihood ratio | Yes (whitespace) | ## continuation | BERT, DistilBERT, ELECTRA |
| SentencePiece+BPE | BPE on raw character stream | Frequency count | No (raw text) | ▁ word-start | T5, mT5, ALBERT, LLaMA |
| Unigram LM | Probabilistic segmentation model | Likelihood of segmentation | No (raw text) | ▁ word-start | mBART, XLNet (via SP) |
| Byte-level BPE | BPE on UTF-8 bytes (no [UNK] possible) | Frequency count | Byte fallback | Ġ word-start | GPT-2, RoBERTa, tiktoken |
FeynmanCan you explain tokens to a non-expert?
Imagine a post office that can only handle standardized parcel boxes — not freeform packages. When you bring in a letter (raw text), the sorting machine (tokenizer) must first cut it into pieces that fit the standard boxes.
Short, common words like "the" get their own single box. Long, rare words like "tokenization" get cut into smaller boxes: token + ##ization. Every piece is labeled with a barcode (token ID). The boxes then travel on a conveyor belt (the model) that only reads barcodes — never the content of the boxes directly.
The model learns what each barcode means through training (embedding lookup). The post office (tokenizer) just handles the logistics. That's why tokenization does not understand meaning — it just produces standardized parcels.
⚠️ The 5 Most Common Misconceptions
❌ "1 token = 1 word"
False. "tokenization" = 2 tokens. "GPT-4" = 3–4 tokens. Punctuation is usually its own token. The ratio varies by word and tokenizer.
❌ "Models think in letters"
False. Models process token chunks, not individual characters. This is why older models struggle with letter-counting tasks ("how many r's in 'strawberry'?").
❌ "Higher token ID = more important"
False. IDs are arbitrary vocabulary indices. Token ID 500 has no inherent relationship to ID 499. Semantic value comes from the embedding vector, not the ID number.
❌ "Tokenizers are interchangeable"
False. BERT tokenizer + GPT-2 model = broken. Each model was trained with a specific tokenizer, and its embedding matrix rows correspond to that exact vocabulary.
ProjectCapstone: Build a token analysis toolkit
🛠️ Token Analysis Toolkit — remaining milestones
- Pipeline tracer: Take a sentence through all 5 stages — show intermediate output at each stage. Make each stage inspectable.
- Tokenizer comparator: Same text, side-by-side output of BERT/GPT-2/T5. Highlight differences in segmentation boundaries.
- Cost estimator: Given a prompt and a pricing API (e.g., GPT-4o at $5/million input tokens), estimate the cost and context window usage percentage.
SummaryWhat you must be able to recall and explain
- Definition: A token is a model-defined text piece — the atomic unit a language model processes.
- Not words, not chars: Tokens are subword units chosen by an algorithm trained on corpus statistics.
- Token IDs: Integer row indices into the embedding matrix. No semantic ordering.
- Vocabulary: Fixed set of all known tokens. Built once, cannot change without retraining.
- Subwords solve two problems: word-level fails on rare words; character-level produces too-long sequences.
- BPE (MUST): Iteratively merges most-frequent adjacent pair. Used by GPT-2, GPT-4, LLaMA.
- WordPiece (GOOD): Likelihood-based selection + MaxMatch greedy segmentation. Used by BERT.
- SentencePiece (GOOD): Raw-text, no pre-tokenization needed. Language-agnostic. ▁ marker.
- Pipeline (MUST): 5 stages: normalize → pre-tokenize → subword → post-process → encode. Model-specific.
- Special tokens: [CLS], [SEP], [PAD], [MASK], <|endoftext|> — structural, not content.
- Context windows: Measured in tokens, not words. ~1.3 tokens/word for English. 3–8x for non-Latin scripts.
- Next: Token IDs → Embedding lookup → Vectors → Attention → Transformer.
reliable-agent-lab/environments/service_simulator.py and continue building. You don't need to finish the whole cluster — read until the blocker is resolved.