Lesson 6 of 12 · How It Works
Tokens and Context Windows
What tokens are, why models read text in pieces, how byte-pair encoding builds a vocabulary and what a context window is. Try a live tokenizer in your browser.
- 8 min read
- Beginner
- Reviewed
- What a token is, and why models use tokens instead of words or letters
- How a tokenizer learns its pieces, using byte-pair encoding
- Quick rules for estimating tokens from words and characters
- What a context window is, and what happens when it fills up
Models read tokens
A language model never sees letters or words. Before your text reaches the model, a tokenizer cuts it into pieces called tokens and replaces each piece with a number.
Type anything into the box below and watch how it is split. Try a long or unusual word, a number, a name, or another language.
Some things to notice:
- Common words such as
theormagicare a single token, usually including the space before them. - Rare or long words are split into familiar chunks.
- Long numbers are broken into groups of digits, which is one reason exact arithmetic is hard for models.
- Many languages other than English need more tokens for the same meaning, so they use up limits faster and cost more.
Why not just use words or letters?
| Choice | Problem |
|---|---|
| One token per letter | Text becomes very long, so the model must take many more steps and sees less at once. |
| One token per word | The vocabulary would need millions of entries and still could not handle new words, names or typos. |
| Pieces of words | A vocabulary of about 100,000 to 200,000 pieces can spell anything, while common words stay short. |
Tokens are the compromise.
How a tokenizer learns its pieces
Most tokenizers are built with byte-pair encoding (BPE). The idea: start with single characters, then repeatedly glue together the pair of neighbours that appears most often in a large amount of text.
The program below runs five merges on a tiny "training text" containing four words.
# How often each word appears in our tiny "training text"
words = {"low": 5, "lower": 2, "newest": 6, "widest": 3}
# Start: every word is split into single characters
pieces = {}
for word in words:
pieces[word] = list(word)
def count_pairs():
pairs = {}
for word in words:
parts = pieces[word]
for i in range(len(parts) - 1):
pair = (parts[i], parts[i + 1])
pairs[pair] = pairs.get(pair, 0) + words[word]
return pairs
def merge(pair):
for word in words:
parts = pieces[word]
merged = []
i = 0
while i < len(parts):
if i < len(parts) - 1 and parts[i] == pair[0] and parts[i + 1] == pair[1]:
merged.append(parts[i] + parts[i + 1])
i += 2
else:
merged.append(parts[i])
i += 1
pieces[word] = merged
for step in range(1, 6):
pairs = count_pairs()
best = max(pairs, key=pairs.get)
merge(best)
print(f"Merge {step}: '{best[0]}' + '{best[1]}' -> '{best[0] + best[1]}'")
print()
for word in words:
print(word, "->", pieces[word])The ending est became one token because it appears in two frequent words, and low became one token because it is common. A real tokenizer does exactly this on billions of words, tens of thousands of times.
Estimating tokens
You will often need a rough count, for example to estimate cost. For ordinary English text:
- 1 token is about 4 characters.
- 1 token is about three quarters of a word, so 100 words is about 130 tokens.
The context window
Context windows have grown fast, from a few thousand tokens in early models to hundreds of thousands, and in some models a million or more. That is enough for several books. But the window is still a hard limit.
What happens in a long conversation when the window fills up? It depends on the app. Some stop and ask you to start a new chat; many quietly drop or summarise the oldest messages, so the model "forgets" the start of the conversation. The program below shows the dropping approach.
window = 1000 # tokens the model can see at once
# Each message with an estimated size in tokens, oldest first
messages = [
("You: Plan a 3-day trip to Rome", 12),
("AI: Day 1: Colosseum and Forum ...", 420),
("You: Make day 2 more relaxed", 9),
("AI: Day 2: a slow morning in Trastevere ...", 380),
("You: Add restaurant ideas", 6),
("AI: Here are restaurants for each day ...", 350),
]
# Keep the newest messages that fit, working backwards
kept = []
used = 0
for text, tokens in reversed(messages):
if used + tokens > window:
break
kept.insert(0, text)
used += tokens
print(f"Tokens used: {used} of {window}")
print("The model can still see:")
for text in kept:
print(" ", text)
print("Forgotten:", len(messages) - len(kept), "messages")The original request, "a 3-day trip to Rome", has fallen out of the window. If you now ask "make it 4 days", the model no longer sees the first day's plan.
Common mistakes
Estimate whether a whole novel fits into each model's context window.
characters = 300000 # length of a novel in characters
windows = {"small model": 32000, "large model": 200000}
# 1. Estimate tokens: about 4 characters per token (use // 4)
# 2. Print: Estimated tokens: ...
# 3. For each model print "name: fits" or "name: does not fit"
What counts towards a model's context window?
Summary
- Models read and write tokens: pieces of text such as words, parts of words and punctuation.
- Tokenizers are built with byte-pair encoding, merging frequent pairs of characters into bigger pieces.
- In English, 1 token is about 4 characters or 0.75 words.
- The context window is how many tokens a model can consider at once, including its own answer.
- When a conversation outgrows the window, older parts are dropped or summarised, and the model forgets them.
Next: the difference between training a model and using it.
Finished reading? Tick it off to track your progress.