About this notebook
Companion to Module 2: LLMs for builders. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
Models do not read characters or words; they read tokens, and every limit and price an agent builder meets is counted in them: the context window, the output cap, the bill. This notebook builds the tokenizer most models use, byte-pair encoding (BPE), from scratch:
- turn text into bytes, the alphabet every tokenizer starts from;
- learn merges: repeatedly fuse the most frequent adjacent pair into a new token;
- encode and decode, and check the round trip on text the tokenizer never saw;
- measure how vocabulary size trades off against compression;
- count what an agent’s prompts, tool schemas and tool outputs cost in tokens.
Which model answers here?
None. This notebook trains a tokenizer on a 6 KB text file in a fraction of a second and makes no model calls, so it runs the same with or without an API key.
from agentlab.nbsetup import setup
nb = setup("02a_bpe_tokenizer")LLM backend
offline policy model (deterministic, rule-based, no API key used)
1. Text is bytes
A tokenizer needs a fixed starting alphabet. Characters are a poor choice: Unicode has over 150,000 of them, and a model would meet characters it has never seen. Bytes are better: UTF-8 writes every character as one to four bytes, so 256 starting symbols cover every possible string, including emoji and scripts the training data never contained.
for s in ["agent", "café", "東京", "🤖"]:
b = s.encode("utf-8")
print(f"{s!r:8} {len(s)} character(s) -> {len(b)} byte(s): {list(b)}")'agent' 5 character(s) -> 5 byte(s): [97, 103, 101, 110, 116] 'café' 4 character(s) -> 5 byte(s): [99, 97, 102, 195, 169] '東京' 2 character(s) -> 6 byte(s): [230, 157, 177, 228, 186, 172] '🤖' 1 character(s) -> 4 byte(s): [240, 159, 164, 150]
Bytes alone make sequences long: one token per byte means a 1,000-word prompt is about 6,000 tokens, and attention cost grows with the square of the length. BPE starts from bytes and then learns longer tokens for the byte sequences that occur often.
2. One merge at a time
The training step is simple: count every adjacent pair of tokens, take the most frequent pair, and give it a new id. Replace every occurrence of the pair with that id, and repeat.
from collections import Counter
def pair_counts(ids):
return Counter(zip(ids, ids[1:]))
def merge(ids, pair, new_id):
out, i = [], 0
while i < len(ids):
if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
out.append(new_id)
i += 2
else:
out.append(ids[i])
i += 1
return out
toy = "low lower lowest slow slower"
ids = list(toy.encode("utf-8"))
vocab = {i: bytes([i]) for i in range(256)}
for step in range(5):
counts = pair_counts(ids)
pair = max(counts, key=counts.get)
new_id = 256 + step
vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
ids = merge(ids, pair, new_id)
print(f"merge {step + 1}: {vocab[pair[0]]!r} + {vocab[pair[1]]!r} -> {vocab[new_id]!r}"
f" ({counts[pair]} times; sequence now {len(ids)} tokens)")merge 1: b'l' + b'o' -> b'lo' (5 times; sequence now 23 tokens) merge 2: b'lo' + b'w' -> b'low' (5 times; sequence now 18 tokens) merge 3: b'low' + b'e' -> b'lowe' (3 times; sequence now 15 tokens) merge 4: b'low' + b' ' -> b'low ' (2 times; sequence now 13 tokens) merge 5: b'lowe' + b'r' -> b'lower' (2 times; sequence now 11 tokens)
After five merges, low and lower are single tokens and the 28-byte string is 11 tokens.
Two details matter once the text is real:
- Pre-tokenization. Merge 4 glued a space onto
low: the token now spans a word boundary. On real text this fills the vocabulary with fragments of common phrases. Real tokenizers first split text with a regular expression into words, numbers and punctuation, each with its leading space, and only merge inside those pieces. - Ties. When two pairs are equally frequent the choice must still be deterministic, or two training runs give different tokenizers. Here, as in the CS336 reference, the pair with the larger bytes wins.
3. Train on a corpus
The training text is a 6 KB file of notes on building agents. Pre-tokenize it, count each distinct word once with its frequency (so the loop runs over about 430 distinct words instead of 6,000 bytes), and merge until the vocabulary reaches the size we ask for.
import re
from agentlab.config import fixtures_dir
text = (fixtures_dir() / "text" / "field_notes.txt").read_text()
PRETOKENIZE = re.compile(
r"""'(?:s|t|re|ve|m|ll|d)| ?[A-Za-z]+| ?[0-9]{1,3}| ?[^\sA-Za-z0-9]+|\s+(?!\S)|\s+"""
)
print(PRETOKENIZE.findall("The agent's 3 tools returned 1234 results!"))
def train_bpe(text, vocab_size):
words = Counter(tuple(w.encode("utf-8")) for w in PRETOKENIZE.findall(text))
vocab = {i: bytes([i]) for i in range(256)}
merges = []
while len(vocab) < vocab_size:
counts = Counter()
for word, freq in words.items():
for pair in zip(word, word[1:]):
counts[pair] += freq
if not counts:
break
pair = max(counts, key=lambda p: (counts[p], vocab[p[0]], vocab[p[1]]))
new_id = len(vocab)
vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
merges.append(pair)
words = Counter({tuple(merge(list(w), pair, new_id)): f for w, f in words.items()})
return merges, vocab
merges, vocab = train_bpe(text, vocab_size=512)
print(f"{len(text):,} characters, {len(set(PRETOKENIZE.findall(text)))} distinct words, "
f"{len(merges)} merges learned")
print("first 12 merges:", [vocab[256 + i].decode() for i in range(12)])
print("last 8 merges: ", [vocab[i].decode() for i in range(len(vocab) - 8, len(vocab))])
learned = {b.decode(): i - 256 for i, b in vocab.items() if i >= 256}
for w in [" the", " model", " agent", " tool", " sandbox", " Paris"]:
print(f"{w!r:11} merge {learned[w] + 1}" if w in learned else f"{w!r:11} not a token")['The', ' agent', "'s", ' 3', ' tools', ' ', ' returned', ' 123', '4', ' results', '!'] 6,256 characters, 428 distinct words, 256 merges learned first 12 merges: [' t', ' a', 'he', ' the', ' i', ' w', 're', 'er', 'st', 'ha', ' c', 'nd'] last 8 merges: [' bu', ' ask', ' arguments', ' Every', ' ea', 'wo', 'vi', 'umber'] ' the' merge 4 ' model' merge 42 ' agent' merge 47 ' tool' merge 35 ' sandbox' not a token ' Paris' not a token
The first merges are the most frequent pairs in English (" t", "he", " the"). Later
ones are whole words and word pieces that are common in this text: " model", " agent"
and " tool" become single tokens, while a word the notes never use stays in pieces. A
tokenizer is shaped by its training data, which is why the same sentence costs a different
number of tokens with different models, and why code, JSON and languages other than English
often cost more than you would guess.
4. Encode and decode
Encoding a new string replays the merges in the order they were learned: within each pre-token, repeatedly apply the earliest-learned merge that is present. Decoding is just concatenating the bytes of each token.
ranks = {pair: k for k, pair in enumerate(merges)}
def encode(s):
out = []
for word in PRETOKENIZE.findall(s):
ids = list(word.encode("utf-8"))
while len(ids) > 1:
pairs = zip(ids, ids[1:])
rank, i = min((ranks.get(p, 1 << 30), i) for i, p in enumerate(pairs))
if rank == 1 << 30:
break
ids[i:i + 2] = [256 + rank]
out += ids
return out
def decode(ids):
return b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace")
examples = ["The agent calls a tool.", "Tokenizers mangle 12345678.", "naïve café 東京 🤖"]
for s in examples:
ids = encode(s)
assert decode(ids) == s
pieces = [vocab[i].decode("utf-8", errors="replace") for i in ids]
print(f"{len(s.encode()):3} bytes -> {len(ids):3} tokens: " + "|".join(pieces))23 bytes -> 7 tokens: The| agent| call|s| a| tool|. 27 bytes -> 22 tokens: T|o|k|en|i|z|er|s| m|an|g|le| |1|2|3|4|5|6|7|8|. 24 bytes -> 21 tokens: n|a|�|�|ve| ca|f|�|�| |�|�|�|�|�|�| |�|�|�|�
The round trip is exact for every string, including characters the tokenizer never saw in
training: they simply stay as single bytes (each � above is one byte of a multi-byte
character, printed on its own).
The number is worth a second look. The notes contain no digits, so no digit merges were learned and each digit is one token. But even with merges, the pre-tokenizer has already cut the number into groups of three, and no merge can cross those cuts:
print(PRETOKENIZE.findall("12345678 and 1234"))['123', '456', '78', ' and', ' 123', '4']
Production tokenizers do the same (GPT-4’s splits numbers into groups of one to three
digits), so a model sees 12345678 as chunks whose boundaries have nothing to do with place
value. That is one reason models are unreliable at long arithmetic, and why agents get a
calculator tool.
agentlab.tiny.bpe.BPETokenizer is the same algorithm packaged for later notebooks. Check
that it learns exactly the same merges:
from agentlab.tiny.bpe import BPETokenizer
tok = BPETokenizer.train(text, vocab_size=512)
assert tok.merges == merges
print(tok.show("Return the error to the model as the result of the call."))R|et|urn| the| error| to| the| model| as| the| result| of| the| call|.
5. Vocabulary size against compression
More merges mean longer tokens and shorter sequences, but a bigger embedding table and more rare tokens the model sees too seldom to learn well. Production tokenizers settle around 50,000 to 250,000 tokens. With 6 KB of training text we can only go to about a thousand, but the trend is visible. We hold out the last fifth of the file, and also measure on a piece of JSON (a tool definition from Notebook 1), which looks nothing like the training text.
import json
from agentlab.tools import tool
def get_weather(city: str) -> str:
"""Current weather for a city."""
return "..."
tool_json = json.dumps(tool(get_weather).tool_definition)
split = int(len(text) * 0.8)
train_text, held_out = text[:split], text[split:]
sizes = [256, 300, 400, 500, 600, 800, 1000]
bpt_prose, bpt_json = [], []
for v in sizes:
t = BPETokenizer.train(train_text, v)
bpt_prose.append(len(held_out.encode()) / len(t.encode(held_out)))
bpt_json.append(len(tool_json.encode()) / len(t.encode(tool_json)))
for v, a, b in zip(sizes, bpt_prose, bpt_json):
print(f"vocab {v:5}: {a:.2f} bytes/token on held-out prose, {b:.2f} on JSON")vocab 256: 1.00 bytes/token on held-out prose, 1.00 on JSON vocab 300: 1.47 bytes/token on held-out prose, 1.14 on JSON vocab 400: 2.00 bytes/token on held-out prose, 1.29 on JSON vocab 500: 2.33 bytes/token on held-out prose, 1.37 on JSON vocab 600: 2.61 bytes/token on held-out prose, 1.43 on JSON vocab 800: 2.84 bytes/token on held-out prose, 1.51 on JSON vocab 1000: 3.02 bytes/token on held-out prose, 1.54 on JSON
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.plot(sizes, bpt_prose, "o-", color="#2c5f9e", label="held-out prose")
ax.plot(sizes, bpt_json, "s--", color="#b5523b", label="tool definition (JSON)")
ax.set_xlabel("vocabulary size (tokens)")
ax.set_ylabel("bytes per token")
ax.set_ylim(0.8, max(bpt_prose) * 1.15)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, loc="upper left")
plt.show()
Bytes per token as the vocabulary grows. Compression improves quickly and then flattens, and it improves much less on JSON, which the tokenizer never saw in training.
Compression on held-out prose levels off as the new merges become words that occur once or twice. Compression on JSON stays poor: braces, quotes and key names were rare in the training text. Large production tokenizers are trained on a mix that includes code and JSON, and reach about 4 bytes per token on English prose, a figure worth remembering.
6. Tokens are the agent’s budget
The usage tables in this course estimate tokens as one per 4 bytes
(agentlab.llm.pricing.estimate_tokens). Compare that rule of thumb with our small
tokenizer on three things every agent sends: instructions, tool definitions, and a tool
output.
from agentlab.llm.pricing import estimate_tokens, reference_cost
big = BPETokenizer.train(text, 1000)
system_prompt = ("You are a careful assistant. Use the tools when you need facts you do "
"not have. If a tool fails, read the error and try again.")
rows = [{"city": c, "temp_c": 20 + i, "sky": "clear"} for i, c in enumerate(["Paris"] * 40)]
samples = {
"system prompt": system_prompt,
"tool definition": tool_json,
"tool output (40 rows)": json.dumps(rows),
}
print(f"{'':24} {'bytes':>6} {'BPE-1000':>9} {'bytes/4':>8}")
for name, s in samples.items():
print(f"{name:24} {len(s.encode()):6} {len(big.encode(s)):9} {estimate_tokens(s):8}")bytes BPE-1000 bytes/4 system prompt 126 43 32 tool definition 203 131 51 tool output (40 rows) 1960 1640 490
Two things to take away. First, structured data is expensive: the 40-row tool output costs far more tokens than the instructions, and an agent sends it again on every later step (Notebook 1, section 5). Trimming tool outputs is one of the cheapest optimisations there is. Second, our 1,000-token vocabulary is much less efficient than a real one; the bytes/4 column is closer to what a production tokenizer would charge.
What would a long run cost? Using the formula from Module 1, a run of
s0, d = 2_000, 800
for K in [5, 10, 30, 60]:
total = K * s0 + K * (K - 1) * d // 2
usd = reference_cost(total, 0)
print(f"{K:3} steps: {total:>9,} input tokens, about USD {usd:.2f} (USD 1 per million)")5 steps: 18,000 input tokens, about USD 0.02 (USD 1 per million) 10 steps: 56,000 input tokens, about USD 0.06 (USD 1 per million) 30 steps: 408,000 input tokens, about USD 0.41 (USD 1 per million) 60 steps: 1,536,000 input tokens, about USD 1.54 (USD 1 per million)
Try this
- Train on
text * 3and ontext.lower(). Which merges change, and why does lowercasing help compression on this corpus but hurt a model that must reproduce names exactly?- Remove the
[0-9]{1,3}rule fromPRETOKENIZE(so digits join the punctuation rule) and encode"12345678"again. What do you get?- Add a few hundred lines of JSON to the training text and re-run section 5. How much does the JSON curve improve, and what happens to the prose curve?
This notebook made no model calls, so the usage table is empty.
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 0 (none) | 0 | 0 | USD 0.0000 |