Why models do not read characters
A neural network needs fixed-size numeric inputs, so text must be chopped into units. Characters give a tiny vocabulary but very long sequences: a 1,000-word document is roughly 6,000 characters, and attention cost grows with the square of that. Whole words give short sequences but an open vocabulary - names, typos, code identifiers and morphology mean you either miss words or carry an enormous embedding table.
Subword tokenization sits between the two. Frequent words get a single token, rare words get split into meaningful pieces, and the vocabulary stays a manageable 32,000 to 200,000 entries. "Unbelievable" might become "Un" + "believ" + "able"; "tokenization" becomes "token" + "ization". The model never sees letters, only these IDs - which is why questions about spelling, character counting and rhyming are genuinely hard for it.
How BPE is trained
Byte-pair encoding was adapted from a 1994 compression algorithm by Sennrich, Haddow and Birch in 2016 for machine translation. Training starts with the text split into individual bytes - 256 possible symbols, so nothing is ever out of vocabulary. Count every adjacent pair across the corpus, merge the most frequent pair into a new symbol, record the merge, and repeat until the vocabulary reaches its target size.
Each merge is a rule, and the ordered list of rules is the tokenizer. Encoding new text replays those merges in the order they were learned. Because merges are ranked, the process is deterministic: the same string always produces the same IDs. A toy corpus of "low", "lower", "lowest", "newer", "wider" first merges "e" + "r" into "er" because it appears in three words, then "l" + "o" into "lo", and so on until the budget is spent.
GPT-2's byte-level variant (Radford et al., 2019) is the design nearly everyone copied. It operates on UTF-8 bytes rather than Unicode characters, which means emoji, Chinese, Arabic and malformed byte sequences all encode without a special unknown token, and the vocabulary is exactly 256 byte symbols plus 50,000 learned merges plus one end-of-text marker: 50,257.
Pre-tokenisation and the regex
Real tokenizers do not run BPE over the raw string. They first split it with a regular expression so merges never cross word boundaries, whitespace runs or punctuation in odd ways. GPT-2 used a pattern that separates contractions, letter runs, digit runs, punctuation and trailing spaces; GPT-4 and Llama 3 use refinements that keep contractions together and cap digit runs at three.
That regex is part of the model's behaviour, not an implementation detail. It explains why the same text can cost different numbers of tokens under different models, why leading spaces attach to the following word, and why "1234567" may split as "123" + "456" + "7" - a pattern that badly hurts arithmetic. When you port a prompt between model families, token counts and sometimes accuracy shift because the segmentation changed.
What the vocabulary actually contains
The first 256 entries of a byte-level vocabulary are single bytes, which is why the tokenizer can encode arbitrary binary data, emoji and scripts it never saw in training. Everything after that is a merge, and merges look like fragments rather than words: " the", "ing", "tion", "\n\n", "() {", "://". Leading spaces are part of the token because the regex attaches them, so "the" and " the" are two different IDs and swapping them changes the model's input.
Token length is uneven in a way that matters. A common word is one token; a rare surname might be four; a base64 blob or a random UUID might approach one token per two characters. Emoji are frequently several tokens each, and flags or family emoji built from zero-width joiners can consume a dozen. When a system prompt says "be concise", it is optimising a budget whose unit is this irregular.
Each token owns one row in the embedding matrix and one row in the output projection. That is the entire mechanism by which a token "means" anything at initialisation: a random vector that training gradually shapes. Tokens that appear rarely get few gradient updates, which is the mechanical reason rare tokens are handled worse than common ones, and why a vocabulary too large for the available data quietly wastes capacity.
What a token actually costs
- English prose: roughly 4 characters per token, or about 0.75 tokens per word. A 1,000-word article is around 750 tokens.
- Python and JavaScript: often 3-3.5 characters per token, because indentation, brackets and camelCase identifiers fragment.
- Minified JSON or base64: closer to 2 characters per token, since the text is high-entropy and shares few repeated substrings.
- Chinese, Japanese and Korean: commonly 1-2 characters per token in older 32K vocabularies, improving to near parity in 128K vocabularies trained with more multilingual data.
- Numbers: split into 1-3 digit chunks, so a long ID may consume a dozen tokens and digit-level arithmetic becomes error-prone.
- Whitespace and newlines: separate tokens, which is why deeply indented code and Markdown tables are disproportionately expensive.
Vocabulary size is a real design decision
The embedding table and the output projection both scale with vocabulary: V x d parameters each, and often they are tied. A 128,256-token vocabulary at d_model = 4,096 is 525M parameters per matrix - a substantial share of an 8B model. Doubling the vocabulary doubles that cost and softens the gradient each rare token receives, since it appears less often during training.
The benefit is compression. A larger, better-trained vocabulary packs the same text into fewer tokens, and every downstream cost - context used, attention compute, key-value cache, latency - is charged per token. Llama 2's 32K SentencePiece vocabulary averages about 3.2 characters per token on English; Llama 3's 128K tiktoken-style vocabulary reaches roughly 4.4, and vendor comparisons report up to 15% fewer tokens for the same English text. That is a direct saving in GPU hours at training time and in dollars at inference time.
The trade-off is not free in quality either. Very large vocabularies make each token a rarer training signal, and multilingual coverage needs deliberate sampling: a vocabulary dominated by English data tokenizes Hindi or Swahili inefficiently no matter how large it is. This is measured with fertility - tokens per word - per language, and it is why a model can be fluent in English and expensive in Vietnamese.
The arithmetic you should be able to do
Embedding parameters: V x d_model. Total tokens: characters / compression ratio. Cost: tokens / 1,000,000 x price per million. Context headroom: window - prompt tokens - reserved output tokens.
Example: a 12,000-character support ticket at 3.8 characters per token is about 3,160 tokens. Sent 40,000 times a month that is 126M input tokens - at $0.50 per million, roughly $63; at $3.00 per million, roughly $379. The tokenizer's compression ratio sits directly in that multiplication, which is why vendors advertise it.
Also budget for the output and for retries. A chat template adds tokens for role markers and turn separators, tool definitions are re-sent on every call, and a reasoning model may emit thousands of hidden tokens you never display but still pay for.
Tokenization and prompt engineering
Many prompt problems are tokenizer problems in disguise. Truncating a prompt by characters cuts mid-token or mid-word; truncating by tokens with the model's own tokenizer does not. Few-shot examples that differ in whitespace from production inputs can teach the model a spurious pattern, because "Answer:" and "Answer: " are different continuations. Few-shot examples are also the largest line item in most prompts: five examples at 200 tokens each cost 1,000 tokens on every single request, so caching them pays for itself quickly.
Structured output deserves its own care. JSON schema text is token-dense - braces, quotes and long keys fragment badly - and a 40-field schema can consume 1,500 tokens before the user says anything. Constrained decoding with a grammar or JSON mode removes the need to describe the format in prose, which often saves more tokens than the description itself cost.
For retrieval, size chunks in tokens rather than characters and leave room for the answer. A 32K window with 8K reserved for output and 2K for the system prompt and tool definitions leaves 22K for retrieved content - about 15 chunks of 1,400 tokens, not the 30 that a character-based estimate would suggest. Getting this arithmetic wrong is the most common cause of a RAG system that works in testing and silently drops context in production.
Common failure modes
- Character-level tasks: counting letters, reversing words and rhyming fail because the model never sees individual characters.
- Number handling: digit chunking makes long multiplication, date arithmetic and checksum work unreliable without a calculator tool.
- Trailing whitespace: a space before a word changes its token, so prompts assembled by concatenation can behave differently from hand-written ones.
- Glitch tokens: rare merge artefacts such as " SolidGoldMagikarp" were undertrained and produced erratic outputs in early GPT-2/GPT-3 models.
- Tokenizer drift: fine-tuning with a mismatched or extended vocabulary silently misaligns embeddings and destroys quality.
- Token smuggling: instructions hidden across unusual token boundaries can slip past filters that inspect text rather than tokens.
- Counting characters to estimate cost: always count tokens with the actual tokenizer for the actual model.
Practical guidance
Use the model's own tokenizer library - tiktoken for OpenAI-style vocabularies, Hugging Face tokenizers or SentencePiece for open weights - and count before you send. Cache the count per message, and reject or truncate at a budget you chose rather than at the provider's hard limit, because an error at 3 a.m. is worse than a slightly shortened prompt.
For long documents, chunk on semantic boundaries and keep the tokenizer in mind: splitting mid-token wastes a token at each boundary and can garble the text the model reads. When comparing models, measure cost per finished task rather than price per token, since a model with worse tokenization can be cheaper per token and more expensive per page.
If you train your own tokenizer, fit it on a sample that matches production traffic - including code, tables, and every language you intend to serve - then verify fertility per language before committing. Retraining a tokenizer after pretraining has started is not practical, so this is one of the few genuinely irreversible decisions in the pipeline.
How vocabulary sizes have moved
Early neural machine translation used vocabularies of 30,000-50,000 subword units, sized to fit an embedding table that had to be trained on modest data. BERT shipped 30,522 WordPiece entries; GPT-2 shipped 50,257 byte-level merges; GPT-3 reused that vocabulary unchanged, which is why token counts for GPT-3-era models are still quoted in 50K-vocabulary units.
Open-weight models then split in two directions. Llama 1 and 2 stayed at 32,000 with a SentencePiece implementation, while Mistral and many Chinese labs moved to 100,000-152,000. Qwen2.5 uses 151,643 entries; Llama 3 uses 128,256; GPT-4o's o200k_base uses 200,019; Gemini models report vocabularies in the 256,000 range. The motivation is not prestige - each doubling of vocabulary buys a materially shorter sequence on multilingual text, and shorter sequences mean cheaper attention, cheaper key-value cache and lower latency.
The countervailing pressure is data. A 200K vocabulary trained mostly on English leaves tens of thousands of tokens starved of gradient signal, and those rows stay close to their random initialisation. That is one origin of the odd behaviours attributed to rare tokens. The practical lesson for anyone training a small model: a 32K vocabulary trained well on your domain will usually beat a 128K vocabulary trained badly, and you can measure the difference directly with fertility and downstream loss.
The alternatives
WordPiece, used by BERT, greedily builds tokens by likelihood rather than raw frequency and marks word continuations with "##". SentencePiece's Unigram model starts from a large candidate set and prunes it probabilistically, which handles languages without spaces more gracefully and is reversible - decoding concatenated tokens restores the original text exactly, whitespace included.
Character-level and pure byte-level models avoid tokenization entirely and have repeatedly been tried, most visibly with byte-level state-space models. They fix the character blindness and the multilingual unfairness, but sequences become 3-4x longer for the same content, and that multiplies attention cost and latency. Until that arithmetic changes, subword BPE remains the pragmatic default - an unglamorous compression layer that quietly sets the price of everything above it.