Sub topic 2
How Text Is Split into Tokens
This chapter assumes you can read basic Python, you know that an LLM API takes text in and returns text, and you know from the previous chapter that a token is the unit a model reads and bills. Here we look at where token boundaries come from and why they sometimes look strange.
Why not split by words or by characters
A tokenizer is the component that turns a string into a list of integer IDs before the model sees it. It also turns IDs back into text on the way out. Each model family ships with its own tokenizer, and the model is trained against that exact one.
The two obvious designs both have problems:
- One token per word. The vocabulary would need an entry for every word form in every language, plus names, typos, and code identifiers. Any word not in the list would have no ID.
- One token per character. The vocabulary is tiny, but every text becomes a very long sequence. Long sequences use more of the context window and cost more.
Modern tokenizers use a middle path called subword tokenization. Common words get a single token. Rare words are built from several smaller pieces. Any text can still be represented, because the smallest pieces are single characters or single bytes.
Byte pair encoding
Most current tokenizers are variants of byte pair encoding (BPE). The idea has two phases.
- Training. This happens once, before the model is trained. Start with the smallest symbols. Count which adjacent pair of symbols occurs most often in a large text sample. Merge that pair into a new symbol and record the merge. Repeat until the vocabulary reaches a target size, often 50,000 to 200,000 entries.
- Encoding. To tokenize new text, start from the smallest symbols and apply the recorded merges in the order they were learned.
The result is that frequent strings such as common words and common word endings become single tokens. Unusual strings are broken into several pieces.
A toy BPE you can run
The following program trains a tiny BPE on a small corpus and then tokenizes two new words. Real tokenizers are much larger, but the logic is the same.
from collections import Counter
def apply_merge(symbols, pair):
out = []
i = 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
out.append(symbols[i] + symbols[i + 1])
i += 2
else:
out.append(symbols[i])
i += 1
return out
def train_bpe(corpus, num_merges):
words = Counter(tuple(w) for w in corpus.split())
merges = []
for _ in range(num_merges):
pairs = Counter()
for symbols, freq in words.items():
for pair in zip(symbols, symbols[1:]):
pairs[pair] += freq
if not pairs:
break
best = max(pairs, key=pairs.get)
merges.append(best)
new_words = Counter()
for symbols, freq in words.items():
new_words[tuple(apply_merge(symbols, best))] += freq
words = new_words
return merges
def tokenize(word, merges):
symbols = list(word)
for pair in merges:
symbols = apply_merge(symbols, pair)
return symbols
corpus = ("low low low low low lower lower "
"newest newest newest newest newest newest "
"widest widest widest")
merges = train_bpe(corpus, 4)
print(merges)
print(tokenize("lowest", merges))
print(tokenize("newer", merges))Running it prints:
[('e', 's'), ('es', 't'), ('l', 'o'), ('lo', 'w')]
['low', 'est']
['n', 'e', 'w', 'e', 'r']Three things are worth noticing:
- The word
lowestnever appears in the corpus. It still becomes two sensible pieces,lowandest, because both pieces were learned from other words. - The word
newerfalls back to single characters, because the training text never gave the tokenizer a reason to merge those letters. Text that looks unlike the training data is split into more tokens. - The order of the merge list matters. Applying the same merges in a different order can give a different split.
What a real tokenizer does
The tiktoken library exposes the tokenizers used by several OpenAI models. The cl100k_base encoding is one of them. The program below shows how different strings are split. It prints the raw bytes of each token, because a single token can end in the middle of a multi-byte character.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
samples = [
"hello",
" hello",
"Hello",
"HELLO",
"unbelievably",
"12345678",
"def parse_user_id(x):",
"Здравствуйте",
"😀",
]
for text in samples:
ids = enc.encode(text)
pieces = [enc.decode_single_token_bytes(t) for t in ids]
print(f"{text!r}: {len(ids)} tokens {pieces}")The exact splits depend on the tokenizer version, so run it yourself and read the output. In general you will see these patterns:
- A common English word with a leading space is often one token. The space is usually attached to the start of the word rather than standing alone.
hello,hello,Hello, andHELLOare different strings, so they can have different token IDs and different token counts.- Long numbers are cut into chunks of a few digits.
- Source code splits at identifiers, underscores, and punctuation.
- Text in languages that were rare in the training data, and many emoji, take more tokens per character than common English text does.
Byte-level vocabularies
Many modern tokenizers start from the 256 possible byte values instead of from characters. This is called byte-level BPE. It has one important property: no input is ever "unknown". Any string can be encoded as UTF-8 bytes, and any byte is in the base vocabulary. Older word-level systems used an <unk> token for missing words. Byte-level BPE does not need one.
The trade-off is that a character outside the common range can be spread over several byte-level tokens. That is why decoding a single token from the middle of an emoji can produce a replacement character or an error in some tools. Decode the whole list of IDs together when you want text.
Special tokens
A tokenizer also has a few special tokens. These are reserved strings with their own IDs that mark structure, such as the end of a text or the boundary between chat roles. Chat APIs add some of these for you around each message, so the token count for a chat request is slightly higher than the count of the raw message text.
tiktoken treats special-token text in your input as a possible mistake. By default, enc.encode("<|endoftext|>") raises a ValueError, so that user-supplied text cannot inject control tokens by accident. You opt in explicitly:
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
try:
enc.encode("<|endoftext|>")
except ValueError as error:
print("rejected by default")
print(enc.encode("<|endoftext|>", allowed_special={"<|endoftext|>"}))Consequences you will run into
The table summarizes how the splitting rules show up in practice.
| Observation | Cause | What to do |
|---|---|---|
| Token count is not word count | Words split into subwords, punctuation and spaces count | Use a tokenizer, not `len(text.split())` |
| Same sentence, different counts on two models | Each model family has its own vocabulary and merges | Count with the tokenizer that matches the model |
| Non-English text costs more per character | Fewer merges learned for those scripts | Measure real samples of your own data |
| Capitalization or leading spaces change the count | They are different byte strings | Count the exact string you will send |
| Long numbers and IDs are expensive | Digits are cut into short chunks | Avoid pasting large tables of numbers when you can summarize them |
| A rare word is split into odd pieces | No merge covers it | This is normal and does not mean the model cannot read it |
Tokenization and what the model can do
The model sees token IDs, not letters. This explains some well-known weaknesses:
- Questions such as "how many times does the letter r appear in this word?" are harder than they look, because the word may arrive as one or two tokens and the model never sees its individual letters directly.
- Reversing a string or spelling a rare word letter by letter requires the model to recover character structure that the tokenizer hid.
- Arithmetic on long numbers is affected by how the digits were chunked.
These are tendencies, not absolute limits, and newer models handle many of them better. When a task depends on exact characters, you can often avoid the problem by doing it in code instead of asking the model.
Practical rules
- Never estimate tokens from word counts when the number matters. Encode the text with the right tokenizer.
- Match the tokenizer to the model. A library tokenizer for one family gives only an approximation for another family. For exact numbers, use the provider's token-counting feature or the usage data returned by the API, which later chapters cover.
- Count the final string. Templates, system prompts, and role markers all add tokens.
- Test with your own data. Token density depends on language, formatting, and content type, so a sample of real inputs beats any general ratio.
Exercise
Using the toy BPE above with the four learned merges, what does tokenize("lowest", merges) return, and why does tokenize("newer", merges) return one token per letter? What would you change to make "newer" produce fewer tokens?
Show answer
"lowest" becomes ['low', 'est']. The merges ('es','t'), ('l','o'), and ('lo','w') all apply to its letters, and the result is the two pieces 'low' and 'est'. "newer" ends up as ['n', 'e', 'w', 'e', 'r'] because none of the four merges contains a pair that occurs in "newer": there is no 'es', 'est', 'lo', or 'low' in it. To get fewer tokens, train on a corpus that contains "newer" or similar words (so pairs like ('n','e') or ('e','r') are frequent) and increase num_merges.
Exercise
You count a prompt with a tokenizer for model family A and get 1,200 tokens. You then send the same prompt to a model from family B. Is it safe to assume the request is also 1,200 tokens? Name two other things that can make the real billed input count higher than your count of the raw text.
Show answer
No. Family B has a different vocabulary and merge list, so the same text can split into more or fewer tokens. The billed count can also be higher than the raw-text count because the API adds role markers and special tokens around chat messages, and because system prompts, tool definitions, or template text that you did not include in your count are also sent as input.