How Tokenizers Work in LLMs
Every time you send a prompt to a large language model, the very first thing that happens has nothing to do with neural networks. Your text is chopped into tokens (small chunks of characters) and each chunk is mapped to an integer. The model never sees letters or words, only a sequence of IDs like [791, 4062, 14198, 39935].
This step is called tokenization, and while it is easy to ignore, it explains a surprising amount of LLM behaviour: why pricing is per token, why models struggle to count letters, and why the same sentence can be “cheaper” in English than in Romanian.
Why not just use characters or words?
There are two obvious ways to turn text into numbers, and both have problems.
Characters. A character-level vocabulary is tiny (a few hundred symbols) and never meets an unknown input. But sequences become very long: a 1,000-word essay is roughly 6,000 characters. Transformer attention cost grows with sequence length, and each position carries very little meaning on its own, so the model has to spend capacity re-learning how letters form words.
Words. A word-level vocabulary produces short sequences with meaningful units, but it explodes in size. English alone has hundreds of thousands of word forms (run, runs, running, runner…), and any word not seen during training.
Subwords sit in the middle. Common words get a single token (the, model), while rare words are built from reusable pieces (token + ization). The vocabulary stays manageable, sequences stay short, and nothing is ever truly unknown.
Byte Pair Encoding (BPE)
Most modern LLMs such as the GPT family, Llama 3, Mistral and others use a variant of Byte Pair Encoding. The idea comes from a 1990s compression algorithm and is refreshingly simple.
Training the tokenizer:
- Start with a base vocabulary of individual symbols. In byte-level BPE these are the 256 possible byte values, so any UTF-8 text can be represented.
- Count every pair of adjacent symbols in the training corpus.
- Merge the most frequent pair into a new symbol and add it to the vocabulary.
- Repeat until the vocabulary reaches the target size.
A tiny example. Suppose the corpus contains these words with their frequencies:
low (5) lower (2) newest (6) widest (3)
Split into characters, the most frequent adjacent pairs are e s and s t. Each appears 9 times across newest and widest. Merge e s first:
n e w es t w i d es t
Now es t is the most frequent pair, so it becomes est. Then l o becomes lo, then lo w becomes low, and so on. After enough merges, frequent words become single tokens while rare words remain split into familiar pieces.
Encoding new text replays the learned merges, in order, on the input. The result is deterministic: the same string always produces the same tokens.
WordPiece and Unigram
BPE is not the only approach.
WordPiece, used by BERT, looks similar but chooses merges differently. Instead of the most frequent pair, it picks the pair that most increases the likelihood of the training data. Roughly, pairs whose parts appear together more often than chance would predict. Continuation pieces are marked with ##, so tokenization might become token ##ization.
Unigram, usually used through Google’s SentencePiece library (T5, ALBERT and others), works in the opposite direction. It starts with a large candidate vocabulary and repeatedly removes the pieces that contribute least to a probabilistic model of the corpus. At encoding time it picks the most likely segmentation, and it can even sample alternative segmentations during training as a form of regularisation.
SentencePiece also treats the input as a raw stream, including spaces (represented as ▁), which makes it language-agnostic. This is useful for languages like Japanese or Chinese that don’t separate words with spaces.
| Algorithm | Builds vocab by | Used in | Space handling |
|---|---|---|---|
| Byte-level BPE | Merging most frequent pairs | GPT-2/3/4, Llama 3 | Space attached to the following token |
| WordPiece | Merging highest-likelihood pairs | BERT, DistilBERT | Pre-split on whitespace, ## for continuations |
| Unigram (SentencePiece) | Pruning a large candidate set | T5, ALBERT, XLNet | Space encoded as ▁ |
Vocabulary size is a trade-off
Tokenizer vocabularies have grown over time: GPT-2 used about 50k tokens, cl100k_base (GPT-4) about 100k, and o200k_base (GPT-4o) about 200k. Llama 2 used 32k, while Llama 3 jumped to roughly 128k.
A larger vocabulary means more text fits in each token, so sequences are shorter, inference is cheaper and more content fits in the context window. The costs are a bigger embedding matrix and output layer, and rare tokens that the model sees too seldom to learn well.
A smaller vocabulary keeps those layers compact but produces longer sequences. The sweet spot depends on the languages and domains (code, math, multilingual text) the model needs to handle.
Seeing it in practice
OpenAI’s tiktoken library lets you inspect exactly how text is split:
import tiktoken
enc = tiktoken.get_encoding("o200k_base")
text = "Tokenizers quietly shape how LLMs see text."
ids = enc.encode(text)
print(len(ids)) # number of tokens
print([enc.decode([i]) for i in ids]) # the individual pieces
Try a few inputs and patterns appear quickly: common English words are one token each, leading spaces are usually part of the token (" see" rather than "see"), and rare names or long numbers break into several pieces.
Quirks that come from tokenization
Many “strange” LLM behaviours are really tokenizer behaviours.
- Counting letters is hard. Ask how many
rs are in strawberry and the model sees something likestr+aw+berry— not individual letters. It has to recall spelling from training rather than simply looking. - Arithmetic is uneven. Older tokenizers split numbers by frequency, so
1234might be one token while1235is two, and digits don’t line up by place value. Newer ones chunk digits more predictably — groups of up to three (12345→123+45) or even one token per digit, as in Llama 2. - Whitespace matters.
"Hello"and" Hello"are different tokens. Trailing spaces in a prompt can subtly change what the model predicts next. - Not all languages cost the same. Tokenizers trained mostly on English compress English best. The same sentence in Romanian, Hindi or Thai can take noticeably more tokens, which means higher cost and less effective context.
- Code depends on the training data. Indentation, brackets and common identifiers compress well only if the tokenizer saw plenty of code while it was being trained.
Takeaways
Tokenization is the translation layer between human text and the model. Subword algorithms like BPE, WordPiece and Unigram balance vocabulary size against sequence length, and the choices baked into a tokenizer ripple outward into cost, context limits, multilingual fairness and even the model’s ability to spell.