Tokens & Tokenization
Neural networks work with numbers, not letters. Before an LLM sees your prompt, a tokenizer cuts the text into tokens and replaces each with an integer token ID. Tokens are the unit of everything in LLM land: context limits, speed and price are all measured in tokens.
Option 1: characters
The simplest tokenizer uses one token per character. The vocabulary is tiny, but the sequences become very long, and the model must learn spelling from scratch.
text = "low lower lowest"
vocab = sorted(set(text))
stoi = {ch: i for i, ch in enumerate(vocab)}
ids = [stoi[ch] for ch in text]
print("vocab:", vocab)
print("ids: ", ids)
print(len(text), "characters ->", len(ids), "tokens")
decoded = "".join(vocab[i] for i in ids)
print("round trip ok:", decoded == text)vocab: [' ', 'e', 'l', 'o', 'r', 's', 't', 'w']
ids: [2, 3, 7, 0, 2, 3, 7, 1, 4, 0, 2, 3, 7, 1, 5, 6]
16 characters -> 16 tokens
round trip ok: True
Option 2: whole words
A word tokenizer gives short sequences, but the vocabulary explodes (every name, typo and new word needs its own entry) and unseen words become a useless "unknown" token:
corpus = "the model reads the text and the model writes text"
vocab = ["<unk>"] + sorted(set(corpus.split()))
stoi = {w: i for i, w in enumerate(vocab)}
def encode(sentence):
return [stoi.get(w, 0) for w in sentence.split()]
print(vocab)
print(encode("the model writes text"))
print(encode("the model summarises text")) # 'summarises' is unknown['<unk>', 'and', 'model', 'reads', 'text', 'the', 'writes']
[5, 2, 6, 4]
[5, 2, 0, 4]
Option 3: subwords with Byte-Pair Encoding
Modern LLMs use subword tokenizers, most often a variant of Byte-Pair Encoding (BPE). Training starts from single characters and repeatedly merges the most frequent adjacent pair into a new token. Common words end up as one token, rare words are split into familiar pieces, and nothing is ever "unknown".
from collections import Counter
words = ["low", "low", "low", "lower", "lower", "lowest", "newest", "newest", "widest"]
# Each word starts as a tuple of characters plus an end-of-word marker
corpus = Counter(tuple(w) + ("_",) for w in words)
def most_frequent_pair(corpus):
pairs = Counter()
for symbols, count in corpus.items():
for a, b in zip(symbols, symbols[1:]):
pairs[(a, b)] += count
# highest count wins; ties broken alphabetically so the result is stable
return min(pairs, key=lambda p: (-pairs[p], p))
def merge(corpus, pair):
merged = Counter()
for symbols, count in corpus.items():
out, i = [], 0
while i < len(symbols):
if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
merged[tuple(out)] += count
return merged
merges = []
for step in range(6):
pair = most_frequent_pair(corpus)
merges.append(pair)
corpus = merge(corpus, pair)
print(f"merge {step + 1}: {pair[0]!r} + {pair[1]!r}")
for symbols in corpus:
print(" ".join(symbols))merge 1: 'l' + 'o'
merge 2: 'lo' + 'w'
merge 3: 'e' + 's'
merge 4: 'es' + 't'
merge 5: 'est' + '_'
merge 6: 'low' + '_'
low_
low e r _
low est_
n e w est_
w i d est_
After only six merges, the word low and the suffix est (with its end-of-word marker, est_) have become single tokens. Real tokenizers run tens of thousands of merges over huge corpora and usually work on bytes rather than characters, so any text — emoji, Chinese, source code — can be encoded.
Applying learned merges
To tokenize new text, a BPE tokenizer replays the merges in the order they were learned. A word it never saw is still split into known pieces:
# the six merges learned above, in order
merges = [("l", "o"), ("lo", "w"), ("e", "s"), ("es", "t"), ("est", "_"), ("low", "_")]
def bpe_tokenize(word):
symbols = list(word) + ["_"]
for a, b in merges:
i = 0
while i < len(symbols) - 1:
if symbols[i] == a and symbols[i + 1] == b:
symbols[i:i + 2] = [a + b]
else:
i += 1
return symbols
for word in ["lowest", "slowest", "low", "newer", "best"]:
print(f"{word:8} -> {bpe_tokenize(word)}")lowest -> ['low', 'est_']
slowest -> ['s', 'low', 'est_']
low -> ['low_']
newer -> ['n', 'e', 'w', 'e', 'r', '_']
best -> ['b', 'est_']
slowest and best were never in the training words, yet they reuse the learned pieces. newer matches none of the six merges, so it falls back to single characters — a bigger vocabulary (more merges) would cover it.
Why tokens matter to you
| Effect | Why |
|---|---|
| Limits | Context windows and max_tokens are counted in tokens, not characters or words |
| Cost and speed | APIs bill per input and output token; generating each token takes time |
| Languages | English text often averages roughly 4 characters per token; many other languages and code need more tokens for the same content |
| Odd mistakes | The model sees "strawberry" as a few chunks, not letters, which is one reason letter-counting and spelling tasks can trip it up |
| Numbers | Long numbers are split into chunks, which makes digit-level arithmetic harder |
Tip: Each model family has its own tokenizer, so the same text can have different token counts on different models. Use the provider's token-counting tool when you need exact numbers; for rough planning, characters ÷ 4 is a common rule of thumb for English.
Go further: Byte-Pair Encoding from Scratch trains a BPE tokenizer, measures vocabulary size against sequence length and checks the encoder against GPT-2's merges.
Test yourself
What does Byte-Pair Encoding repeatedly do during training?
- Deletes the rarest characters
- Merges the most frequent adjacent pair of symbols into a new token
- Splits every word into single bytes
- Sorts words alphabetically
Why do modern LLMs prefer subword tokens over whole-word tokens?
- Subwords make the model forget spelling
- They keep the vocabulary manageable and can represent any word, even unseen ones
- Whole words cannot be converted to numbers
- Subwords are always one character long
Context limits and API billing are measured in…
- characters
- sentences
- tokens
- kilobytes