Topic 8
Hands-on and wrap-up
Two places where tokenization shows up in everyday engineering:
- Budgeting a prompt. Before calling a model, count tokens with that model's tokenizer to check the prompt fits the context window, leave room for the output, and estimate cost. Counting locally is cheap and avoids a failed request.
- Chunking documents for retrieval. When you split documents into chunks for a retrieval system, you can measure chunk size in tokens of your generation model's tokenizer. That makes it easy to guarantee chunks fit the context window. The cost, as AI Engineering points out, is that switching to a model with a different tokenizer means re-chunking and re-indexing your data.
- System prompt 600
- Retrieved chunks 4,200
- Conversation so far 1,500
- User question 200
- Reserved for the answer 1,500
total 8,000 tokens
A prompt is a token budget. Everything you send, plus the room you leave for the answer, has to fit the model's context window, counted in that model's tokens. Count each part before you send.
Illustrative numbers for an 8,000-token window, not a measurement.
Quick check
Try it right here
These are the real tokenizers GPT models use, running in your browser.
- Start with Guess the count: four rounds where you commit to a number before you see the split.
- Then switch to Explore and try your own text: your name in normal case and in capitals, a sentence in another language you know, a long number with and without commas, an indented code block. Watch how the three tokenizers cut the same text differently.
Tokenizer lab
Real tokenizers · running in your browser
js-tiktoken 1.0.21, checked token for token against Python tiktoken 0.14.0. · is a space, ↵ a newline, ×N a character that needed N byte-level tokens.
Try it on your machine
Install tiktoken (pip install tiktoken) and run:
import tiktoken
text = "Tokenizers turn text into integers."
for name in ["gpt2", "cl100k_base", "o200k_base"]:
enc = tiktoken.get_encoding(name)
ids = enc.encode(text)
pieces = [enc.decode([i]) for i in ids]
print(f"{name}: {len(ids)} tokens")
print(" ids: ", ids)
print(" pieces:", pieces)
assert enc.decode(ids) == text # round-trips losslessly
Output with tiktoken 0.14.0 (the first run downloads each encoding file):
gpt2: 7 tokens
ids: [30642, 11341, 1210, 2420, 656, 37014, 13]
pieces: ['Token', 'izers', ' turn', ' text', ' into', ' integers', '.']
cl100k_base: 7 tokens
ids: [3404, 12509, 2543, 1495, 1139, 26864, 13]
pieces: ['Token', 'izers', ' turn', ' text', ' into', ' integers', '.']
o200k_base: 7 tokens
ids: [4421, 24223, 3716, 2201, 1511, 54912, 13]
pieces: ['Token', 'izers', ' turn', ' text', ' into', ' integers', '.']
Probe the quirks
Before running this, write down your guess for each count.
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
for s in ["strawberry", " strawberry", "2026", "1234567", "HELLO"]:
ids = enc.encode(s)
print(repr(s), len(ids), [enc.decode([i]) for i in ids])
Output with tiktoken 0.14.0
'strawberry' 3 ['st', 'raw', 'berry']
' strawberry' 1 [' strawberry']
'2026' 2 ['202', '6']
'1234567' 3 ['123', '456', '7']
'HELLO' 2 ['HEL', 'LO']
Now try your own text: a paragraph in another language you know, a JSON object, a block of indented code. Guess first, then check.
Running example
One sentence follows you through this whole module. Here is what it looks like after this lesson: just token IDs.
Running example · one sentence, four lessons
“We sat on the river bank and watched the …”
9 tokens. GPT-2 never sees the words, only these IDs. The two “·the” tokens get the same ID, 262.
Measured with gpt2 (transformers 5.20.2 (torch 2.14.1)). · marks a leading space.
Summary
- Models consume integer token IDs, not text. A tokenizer maps text → tokens → IDs and back, and each ID later selects a row in the model's embedding table.
- Subword vocabularies trade off vocabulary size against sequence length: common words become one token, rare words are assembled from smaller pieces, and with a byte-level base nothing is unrepresentable.
- BPE learns an ordered list of merges by repeatedly fusing the most frequent adjacent pair, then encodes new text by replaying those merges in order.
- Token counts depend on language, code, numbers, whitespace, capitalization and the tokenizer. Count with the real tokenizer; do not estimate from words.
- Tokenizers are tied to their models. Never mix them, and never let untrusted text become special tokens.
Next
Next lesson: embeddings, where each token ID becomes a vector and similarity between meanings becomes geometry. The tokenizer lab above stays here whenever you want to check a token count.