Tokens
How a tokenizer splits text into tokens, how byte-pair encoding learns its vocabulary, and how tokens affect cost, limits and letter-level mistakes.
On this page
A token is the unit of text that a language model reads and writes. A tokenizer cuts text into tokens taken from a fixed vocabulary, and the model only ever sees the numeric ID of each token, never the individual letters. This matters because context limits and prices are counted in tokens, because some kinds of text use many more tokens than others, and because tasks that depend on single characters are harder for a model than its fluent writing suggests.
If a model received raw letters, every sentence would be a very long sequence and the model would have to relearn common words from scratch. If it received whole words, the vocabulary would need an entry for every name, typo and number. Tokens sit between the two: frequent text becomes short sequences, and any text can still be built from smaller pieces. The previous lesson, What Is an LLM, described a model that predicts the next piece of text, and those pieces are tokens.
How text becomes token IDs
The tokenizer holds a list of pieces called the vocabulary. It splits the input into pieces from that list and replaces each piece with its position in the list. The model works on this sequence of numbers.
Common short words such as "tired" are a single token, while a long or rare word is split into several pieces. The leading space usually belongs to the token that follows it (shown as ␣ in the figure), so " tired" and "tired" are different tokens with different IDs.
How a tokenizer learns its vocabulary
Most current tokenizers use a method called byte-pair encoding, which builds the vocabulary from a large sample of text. It starts with every word split into single characters. It then counts every pair of neighbouring pieces across the whole sample, merges the most frequent pair into one new piece, and adds that piece to the vocabulary. It repeats this until the vocabulary reaches the size the designers want.
The trace below runs the method on six words: tea (twice), team, teams, steam and seat.
split every word into lettersrepeat k times: count each pair of neighbouring pieces best = the most frequent pair glue best together everywhere add best to the vocabulary- tea ×20t1e2ateam0t1e2a3mteams0t1e2a3m4ssteam0s1t2e3a4mseat0s1e2a3t
- tokens
- 24
1Every word starts as single letters, which gives 24 tokens in total.
- tea ×20t1e2ateam0t1e2a3mteams0t1e2a3m4ssteam0s1t2e3a4mseat0s1e2a3t
- e a
- 6
- t e
- 5
- a m
- 3
2Count the pairs. The pair
e aappears 6 times, once in every word occurrence, andt eappears 5 times becauseseatdoes not contain it. The paire awins. - tea ×20t1eateam0t1ea2mteams0t1ea2m3ssteam0s1t2ea3mseat0s1ea2t
- vocabulary +
- ea
- tokens
- 18
3Merge
e aintoeain all 6 places, which reduces the total from 24 to 18 tokens. - tea ×20teateam0tea1mteams0tea1m2ssteam0s1tea2mseat0s1ea2t
- vocabulary +
- tea
- t ea
- 5
- tokens
- 13
4The pair
t eanow appears 5 times, which is the most, so it becomes the pieceteaand the total drops to 13 tokens. - tea ×20teateam0teamteams0team1ssteam0s1teamseat0s1ea2t
- vocabulary +
- team
- tea m
- 3
- tokens
- 10
5The pair
tea mappears 3 times, so it becomes the pieceteamand the total drops to 10 tokens. - tea ×20teateam0teamteams0team1ssteam0s1teamseat0s1ea2t
- merges
- 3
- tokens
- 10
- letters
- 24
6Three merges were learned:
ea,teaandteam. The frequent words are one token each. The wordseatis still three pieces, because its pairss eaandea teach appeared only once and never won a round.
Real tokenizers run this on enormous amounts of text, usually on raw bytes instead of letters so that any writing system can be represented, and they perform tens of thousands of merges. To tokenize new text, the tokenizer applies the learned merges in the order it learned them.
function learnMerges(words, numMerges) {
let pieces = words.map((w) => w.split("")); // start from single letters
const merges = [];
for (let m = 0; m < numMerges; m++) {
const counts = new Map(); // count every pair of neighbouring pieces
for (const word of pieces) {
for (let i = 0; i + 1 < word.length; i++) {
const pair = word[i] + "|" + word[i + 1];
counts.set(pair, (counts.get(pair) || 0) + 1);
}
}
let best = null; // most frequent pair; the first one seen wins a tie
for (const [pair, c] of counts) if (best === null || c > counts.get(best)) best = pair;
if (best === null) break; // every word is already one piece
const [a, b] = best.split("|");
merges.push(a + b);
pieces = pieces.map((word) => {
const out = [];
for (let i = 0; i < word.length; i++) {
if (word[i] === a && word[i + 1] === b) { out.push(a + b); i++; }
else out.push(word[i]);
}
return out;
});
}
return { merges, pieces };
}
learnMerges(["tea", "tea", "team", "teams", "steam", "seat"], 3).merges;
// ["ea", "tea", "team"]def learn_merges(words, num_merges):
pieces = [list(w) for w in words] # start from single letters
merges = []
for _ in range(num_merges):
counts = {} # count every pair of neighbouring pieces
for word in pieces:
for a, b in zip(word, word[1:]):
counts[(a, b)] = counts.get((a, b), 0) + 1
if not counts:
break # every word is already one piece
best = max(counts, key=counts.get) # the first one seen wins a tie
merges.append(best[0] + best[1])
new_pieces = []
for word in pieces:
out, i = [], 0
while i < len(word):
if i + 1 < len(word) and (word[i], word[i + 1]) == best:
out.append(word[i] + word[i + 1])
i += 2
else:
out.append(word[i])
i += 1
new_pieces.append(out)
pieces = new_pieces
return merges, pieces
learn_merges(["tea", "tea", "team", "teams", "steam", "seat"], 3)[0]
# ['ea', 'tea', 'team']Each merge scans all the text once, so k merges over n characters cost O(k · n) in this simple version. Production tokenizers use better bookkeeping to get the same vocabulary faster.
Why tokenization differs between texts
Common and rare text
The merges reflect whatever was frequent in the sample the tokenizer learned from. English prose and popular programming languages therefore pack into few tokens. Languages that were rare in the sample, unusual names, long identifiers and random strings such as hashes break into many small pieces. The same message can cost several times as many tokens in one language as in another, and it also uses up more of the context limit.
Numbers
A number such as 2847 might be one token, or "284" followed by "7", or four separate digits, depending on the tokenizer. When the chunks do not line up with place value, the model cannot easily match units with units, which is one reason long arithmetic is unreliable unless the model uses a calculator or code.
Letters inside words
The model receives the ID for "␣tired", not the letters t, i, r, e, d. It can often spell a word because it has seen the spelling in many places, but counting or reversing letters asks it to recover information that was never directly shown to it. This is why a model can write a fluent paragraph and still miscount the letters in a single word.
How tokens count toward limits and cost
The context limit applies to everything the model handles in one request: your instructions, any documents you attach, the earlier messages of the conversation, and the reply the model writes. Input and output tokens both count against the limit. If a request fills most of the limit with input, little room remains for the answer, and a reply that hits the limit is cut off in the middle of a sentence.
Providers usually charge per token, and often charge a different rate for input tokens and output tokens. In a chat application the whole conversation so far is sent again with each new message, so the input grows with every turn and a long conversation costs more per message than a short one. For this reason, trimming old messages or summarising them is a cost decision as well as a limit decision.
Counts also include text you did not type, such as a system prompt, tool descriptions and the formatting that marks where each message starts and ends. A request that looks short can therefore be larger than the text you wrote suggests.
Pitfalls and nuances
What this changes in practice
Measure inputs in tokens when you budget for cost or context, and measure them on the kind of text you will really send, because a sample in one language or format does not predict another. Put work that depends on exact characters, such as counting, sorting letters, exact string comparison and long arithmetic, into code instead of asking the model to do it in its head. When you must have the model do it, make it write the characters out step by step so that each one becomes its own token. The embeddings lesson covers how each token ID is turned into a vector the model can compute with.
This prompt sometimes gets a confident wrong count. Rewrite it so the model works with letters instead of tokens.
Show a sample answer
Writing one letter per line makes each letter its own token in the output, so counting becomes a matter of looking back at separate tokens instead of looking inside a chunk. You can also check every line yourself. When a wrong answer would matter, ask the model to write code for the count instead.
Check yourself
In the six-word example, why did seat stay as three pieces?
The same paragraph, translated into a language that was rare in the tokenizer's training sample, will usually use...
Why can a model write fluent sentences but miscount the letters in a word?
What to practise next
Build a tokenizer yourself in Knitting Pattern Shorthand, which learns merges, and Sign Shop Letter Blocks, which cuts text into known pieces. After that, Attention and Transformers shows how the model combines token vectors so that each token can use information from the others.