When a language model says a request uses 1,200 tokens, that number is not a count of words. A token may be a character, a word fragment, a leading space plus a word, or one byte of a multi-byte character. The exact boundary depends on the tokenizer and its vocabulary.
That boundary affects almost everything downstream: how much text fits in context, how much training data a model sees, how an unfamiliar identifier is represented, and how much a request costs when a provider prices by token. Tokenization is not merely preprocessing. It is the model’s first decision about what units are available to learn.
Learning objectives
You will implement three tokenizers, compare them on 60 support tickets, learn byte-pair merges from the training split, and inspect behavior on code-like identifiers, URLs, accented text, emoji, and Japanese. The example lives in content/foundations/tokenization-and-bpe.examples, uses no network or paid API, and writes its transcript to outputs/demo.txt.
The goal is not to reproduce a commercial tokenizer. It is to build a mental model that lets you measure a tokenizer rather than guess from a token-counting slogan.
Prerequisites
You need Python 3.11 or later and basic familiarity with strings, lists, dictionaries, and UTF-8. The example uses NumPy only for reporting. You do not need a language model or a tokenizer package.
Three useful baselines
A character tokenizer maps every character to an id. It has a small conceptual vocabulary for a restricted alphabet and never has an unknown token if it stores the original bytes, but sequences become long. A word tokenizer creates short sequences and readable units, but its vocabulary grows quickly and unseen words become <unk>.
Subword tokenization sits between them. It starts from small units and learns pieces that recur: ing, tion, a leading-space word, or a common code fragment. An unseen word can still be assembled from known pieces. The price is that a token boundary can be less intuitive than a word boundary, and different tokenizers may count the same request very differently.
The comparison is a compression trade-off, not a ranking. A larger vocabulary can shorten common text but costs memory and may leave more rare terms unresolved. A smaller vocabulary has more steps per sentence but can represent new text from basic units.
Bytes, characters, and Unicode
Characters and bytes are not interchangeable. UTF-8 represents common ASCII characters with one byte, but é uses two bytes and the rocket emoji uses four. Japanese text also uses multiple bytes per character. A byte-level tokenizer can represent every valid UTF-8 string without an unknown token, but a single visible character may consume several model tokens if its bytes have not been merged.
This is one reason token counts are language- and domain-dependent. A tokenizer trained mostly on English may split another language into smaller pieces. The result is not a property of the language alone; it is a property of the interaction between text, encoding, training corpus, and vocabulary.
Toy problem / implementation
The bundled corpus contains 60 labelled tickets. The first 45 are the tokenizer’s training text; the final 15 are held out for the unknown-word report. The implementation has four stages:
- Convert text to a sequence of UTF-8 bytes.
- Start with each byte as a token.
- Count adjacent pairs across the training corpus.
- Merge the most frequent pair, append it to the vocabulary, and repeat.
The central loop is intentionally plain:
def most_common_pair(sequences):
counts = Counter()
for sequence in sequences:
counts.update(zip(sequence, sequence[1:]))
return counts.most_common(1)[0] if counts else None
After selecting a pair, the tokenizer scans each sequence and replaces non-overlapping occurrences with the new token id. It records the merge table so encoding and decoding remain deterministic. If the requested 800 merges exceed the corpus’s useful pairs, training stops early rather than inventing a merge.
The production version of this idea has more engineering: normalization policy, special tokens, pre-tokenization rules, efficient data structures, and a stable serialization format. Those details are why maintained libraries matter. The small implementation exists so the learning mechanism remains visible.
Run it yourself
From the repository root:
cd content/foundations/tokenization-and-bpe.examples
./verify.sh
The verifier runs 31 tests and the deterministic demo. The recorded environment is Python 3.13.13 with NumPy 2.4.5. Tests cover round trips, merge determinism, Unicode bytes, unknown words, and held-out behavior.
On the sentence Invoice 4471 is missing from the billing history., the character tokenizer emits 49 tokens, the word tokenizer emits 9, and the learned BPE tokenizer emits 20. Those numbers come from the bundled run, not a copied example.
What the corpus measures
Across all 60 tickets, the character representation uses 2,911 tokens. BPE with 50 requested merges uses 1,954; 100 uses 1,668; 200 uses 1,386; and the corpus reaches its useful limit at 522 vocabulary entries and 1,254 tokens. The final two requested budgets, 400 and 800, therefore produce the same result.
The chart has an important caveat: the curve is local to 60 short tickets. It does not establish an optimal vocabulary size. A larger and more varied corpus would support more useful merges, and a production tokenizer’s quality depends on the distribution it must serve.
The word tokenizer has a different failure mode. It emits 575 tokens across the corpus, but 14.1 percent are unknown on all tickets and 56.6 percent are unknown on the held-out split. Short sequences are not useful if the model cannot distinguish the words inside them. BPE remains lossless for the test strings because its byte fallback can represent every byte.
Inspecting surprising strings
The demo uses strings that look short to a human but expose different costs. getUserAccountBalanceByCustomerId is one word to a whitespace tokenizer, but 23 BPE pieces in this small vocabulary. A hex colour has punctuation and digits. A URL has separators and a host name. Emoji and Japanese characters occupy multiple UTF-8 bytes. A leading space can become part of a learned token, so billing and billing need not have identical segmentation.
The merge table explains why. If the occurs often, the space may be merged with the. If ing is frequent, it may become one token. If a novel identifier appears once, its bytes remain separate. The tokenizer is reflecting frequency, not linguistic truth.
A token is not a semantic unit
It is tempting to say that a token represents a meaning, but the tokenizer has no meaning model. It only applies a deterministic segmentation policy learned or specified before the language model is trained. The embedding and later transformer layers can learn that billing, bill, and invoice are related, but the tokenizer’s decision to split billing as bill plus ing is a frequency and vocabulary decision.
This distinction matters when inspecting model behavior. A model may fail on a newly invented product name because the name is represented by a long, awkward sequence. It may also perform well on a rare word if its pieces are useful and the surrounding context is clear. Token boundaries create opportunities and costs; they do not determine the final prediction by themselves.
The same caution applies to token arithmetic. A prompt that is 1,000 characters long can be cheap or expensive depending on its language and contents. Repeated English prose may compress into familiar pieces. A minified JSON document, a stack trace, or a string of identifiers can consume many more tokens. When designing a context budget, measure the distribution of real requests and include the worst meaningful cases, not only a friendly paragraph.
For multilingual products, evaluate each supported language separately. Record median and high-percentile token counts, unknown or fallback behavior, and the fraction of the context occupied by system instructions, retrieved passages, conversation history, and the user request. A tokenizer choice can change which language gets truncated first. That is a product and fairness concern, not merely a performance detail.
Keep the tokenizer version beside every stored embedding and evaluation result. Changing segmentation changes input ids, vector geometry, and sometimes retrieval ranking. Reproducibility begins before the model sees its first hidden state.
That small metadata habit prevents surprisingly expensive debugging later.
It also makes future tokenizer migrations independently auditable.
Real-world application: context and domain vocabulary
Before choosing a model for a support assistant, measure the actual request distribution. Sample representative tickets, include long threads and attachments’ extracted text, and count tokens with the exact deployed tokenizer. Compare languages, code snippets, identifiers, tables, and error messages separately.
For a domain with many rare product codes, a general tokenizer may spend an inefficient number of tokens. That does not automatically justify training a new tokenizer: changing the vocabulary changes the input representation expected by the model and normally requires retraining or a compatible model. Often the safer intervention is to shorten retrieved context, normalize repetitive boilerplate, or choose a model whose tokenizer already fits the domain.
Token counts also belong in operational telemetry. Log counts without logging sensitive text, enforce request limits, and distinguish user-visible characters from model tokens. A context-window failure should be handled before the model call, with a clear fallback such as summarization or a smaller retrieval set.
Failure modes and debugging
- Counting words instead of tokens. Use the deployed tokenizer, not a whitespace split.
- Training and inference mismatch. Persist the vocabulary, merge table, normalization, and special-token policy together.
- Unicode corruption. Test round trips with accented, emoji, and non-Latin text. Never silently decode arbitrary byte fragments as replacement characters when inspecting token pieces.
- Unknown-token optimism. Measure unknown rates on held-out domain text, not only the training corpus.
- Special-token collisions. Reserve control tokens explicitly and prevent user text from being interpreted as one.
- Assuming more merges always help. Stop when the corpus has no repeated pairs and validate on held-out text.
Limitations / when not to use
This BPE implementation omits the normalization and performance engineering of production libraries. Its merge counts are educational, not a recommendation for a model vocabulary. It cannot tell you how a commercial model tokenizes a prompt unless you use that model’s official tokenizer or counting tool.
Do not train a custom tokenizer merely to reduce a local token count. The model’s embedding table and learned input statistics are coupled to the vocabulary. For many applications, retrieval chunking, prompt structure, caching, or model selection are lower-risk improvements.
Exercises
- Train BPE on only the billing tickets and measure what happens to access and bug tickets.
- Add a normalization experiment for lowercasing and compare exact round trips.
- Plot unknown-token rate against requested merge count on the held-out split.
- Add a special
<email>token and test whether it improves or harms address fidelity.
Next in this path
The next article is Embeddings: Turning Meaning Into Geometry. Tokenization creates the discrete input sequence; embeddings give those ids continuous vectors that can carry useful geometric relationships.
Sources
The research dossier is tokenization-and-bpe. Sennrich, Haddow, and Birch, Neural Machine Translation of Rare Words with Subword Units, establishes the subword-unit approach. Kudo and Richardson document SentencePiece. UTF-8 behavior follows RFC 3629. The implementation and token-counting caveats are cross-checked against the Hugging Face tokenizer summary, tiktoken repository, and Anthropic token-counting documentation.
Research and code were last verified on 2026-08-05. The measured counts belong to the bundled 60-ticket corpus and should be regenerated when the corpus or tokenizer changes.