Tokenization as a Compression Contract
A tokenizer is a versioned, reversible byte-to-ID protocol whose merge choices allocate context and cost unevenly across inputs.
- Authorship
- InterviewsVector
- Published / updated
- 2026-08-25 / 2026-08-25
- Review status
- Artifact tests passing · primary sources recorded
Original InterviewsVector material. Code examples are covered by repository tests and primary references are recorded. No named human reviewer is claimed.
The decision in one pass
Treat tokenization as a compression and compatibility contract, not a harmless text-cleaning prelude. A concrete tokenizer release binds byte encoding, Unicode normalization, vocabulary IDs, ordered merge rules, special tokens, unknown handling, and byte fallback. Those choices determine exact round-trip behavior and the number of model positions consumed by each input. Compression is evidence-specific: a vocabulary that shortens one corpus may fragment another language, identifier style, or newly emerging term. Version the complete policy, retain byte-level fixtures, and measure token distributions over real traffic before changing it.
Why this matters
Tokenizer drift can reinterpret stored token IDs, invalidate caches, change truncation, move latency and cost, and create uneven product behavior without changing model weights. Engineers need a release contract that proves reversibility and makes compression consequences observable by cohort.
You will be able to
- Trace deterministic tokenization from Unicode code points through UTF-8 bytes, merges, IDs, and decoding.
- Explain why vocabulary and merge order are compression choices rather than semantic truth.
- Separate exact round-trip guarantees from corpus-specific sequence-length observations.
- Build a content-addressed audit binding normalization, vocabulary, merges, fallback, provenance, and input bytes.
- Design multilingual, code, adversarial, and migration tests for a tokenizer release.
Prerequisite contract
Your Vector Loop for this lab
- 01
Model
Name bytes, normalization, vocabulary, merge ranks, fallback, IDs, context window, and owners.
- 02
Derive
Derive encoding as ordered pair replacement and decoding as an exact byte reconstruction requirement.
- 03
Build
Capture a bounded input and run it through a content-addressed tokenizer contract.
- 04
Stress
Probe multilingual text, combining marks, code, unseen bytes, merge reorderings, truncation, and stale IDs.
- 05
Operate
Monitor bytes per token, fallback rate, tail sequence length, truncation, and version mix by cohort.
- 06
Defend
State which inputs round-trip, where compression was measured, and what semantic quality was not established.
Start with bytes and an explicit normalization decision
A model never receives the user's string directly. The tokenizer first commits to a character-to-byte path. UTF-8 gives a deterministic encoding, but Unicode permits visually similar strings with different code-point and byte sequences. Normalization can intentionally collapse some distinctions; omitting normalization preserves them. Either is a protocol choice that must be named, versioned, and reproduced by every writer and reader.
- 01Capture the original stringRetain a bounded, access-controlled test fixture and its exact UTF-8 bytes; display equivalence is not byte equivalence.
- 02Apply the declared normalizationUse one named algorithm and version, or explicitly preserve code points without normalization.
- 03Require a reversible terminal alphabetA byte fallback can cover every valid UTF-8 byte without silently mapping unseen content to one lossy unknown token.
Read BPE merges as an ordered compression program
bytes → ranked adjacent-pair merges → token pieces → token IDs
At each step, the eligible adjacent pair with the best bound rank is merged. Rank order is behavior: the same vocabulary with a different merge table can segment the same bytes differently.
A token piece is not necessarily a word, morpheme, or stable semantic unit. It is a byte sequence selected by the training algorithm and corpus. Frequent patterns can receive short representations, while rare scripts, names, source code, or changed traffic may remain close to byte-level. The learned inventory is an allocation of finite vocabulary capacity.
| Contract element | What it controls | Drift symptom |
|---|---|---|
| normalization | which byte sequence enters merging | visually similar strings diverge or collapse |
| merge rank | which adjacent pair combines first | different boundaries and token counts |
| token ID | model embedding lookup | old stored IDs acquire new meaning |
| byte fallback | coverage of unseen pieces | lossy unknowns or severe fragmentation |
| special-token policy | control/data boundary | prompt structure is reinterpreted |
Measure compression as a traffic distribution
observed bytes per token = UTF-8 input bytes ÷ emitted model tokens
This ratio describes one bounded sample under one tokenizer. It is not a language-wide constant and does not measure meaning, fluency, or downstream quality.
Token count flows into context occupancy, truncation, batch shapes, KV-cache growth, and usage-based pricing. Report medians and tails by language, product surface, code versus prose, and input age. A global average can hide a cohort whose prompts consume twice as many positions and are truncated much earlier.
Predict the policy effect before revealing the result
The laboratory holds inputs and policy identities fixed while changing illustrative merge coverage or byte fallback. Predict both the token-count direction and whether the original UTF-8 bytes survive. The grade is about this fixture only; it does not rank production tokenizers.
Tokenizer compression contract lab
Compare fixed illustrative merge and byte-fallback policies, then predict the compression and exact round-trip effect before revealing the graded result.
Predict compression without sacrificing round-trip safety
Compare two independently authored illustrative merge tables. Each policy takes the longest matching merge at the current byte position and represents every unmatched UTF-8 byte as its own fallback token. Commit to the count and round-trip effect before revealing either encoding.
- Source text
- “interview vector”
- UTF-8 length
- 16 bytes
- Fallback
- one token per unmatched byte
These compact policies are teaching fixtures, not a benchmark or a claim about a production tokenizer.
Fixed merge tables
Spaces shown as [space] are part of the merge. Entries are tried longest-first; neither table is derived from the other.
| Policy | Merge entries |
|---|---|
| Atlas policy | interview · [space]vector · model · cache · miss |
| Delta policy | inter · view · [space]vector · model · [space]caf · cache[space]miss |
The emitted tokens and count comparison remain hidden until you check a prediction.
Make a prediction, then check it against the current evidence.
Bind the tokenizer and evidence contents
The reference artifact freezes concrete token and merge records, validates unique IDs and contiguous ranks, binds scope and release owners, and captures source version, observation time, text, and exact input bytes. Its public boundary reconstructs every record and digest, so constructor bypass, mutable collections, stale contracts, malformed timestamps, and oversized evidence fail before encoding.
1def format_example() -> str:2 report = audit_tokenization(ILLUSTRATIVE_CONTRACT, ILLUSTRATIVE_EVIDENCE)3 return "\n".join(4 (5 "example=illustrative_only",6 f"contract_id={report.contract_content_id}",7 f"evidence_id={report.evidence_content_id}",8 f"tokens={','.join(report.token_ids)}",9 f"compression={report.input_bytes}_bytes/{len(report.token_ids)}_tokens",10 f"fallback_tokens={report.fallback_tokens}",11 f"round_trip={report.round_trip}",12 f"claim={report.compression_claim}",13 f"decision={report.decision}",14 )15 )Expected output
example=illustrative_only
contract_id=tokenizer-contract@sha256:bef3dd116eb77f4817d0154efeded07f31a55bd6406cf12bc8c5183a02f10542
evidence_id=tokenization-evidence@sha256:a3115aa0672c1e2262e320b68deb6a6614ac559007dd934ebf116cf45b6423f1
tokens=piece-ba,piece-nana,byte-21
compression=7_bytes/3_tokens
fallback_tokens=1
round_trip=EXACT_UTF8_BYTES
claim=OBSERVED_FOR_THIS_EVIDENCE_ONLY
decision=PASSVerify: python3 -m unittest discover courses/ai-engineering/reference-impl/tokenization_contract
Operate tokenizer changes as protocol migrations
| Probe | Required evidence | Release response |
|---|---|---|
| exact round-trip | bytes before and after encode/decode | block on any unexplained mismatch |
| stored IDs | old and new ID interpretation | retain the old reader or re-encode explicitly |
| multilingual tails | p50/p95/p99 token expansion by cohort | review fairness, limits, and cost |
| prompt boundaries | special-token collision fixtures | block control/data ambiguity |
| context impact | truncation and cache deltas on traffic replay | capacity-plan before rollout |
A safe rollout expands readers before writers: deploy code able to identify and decode both tokenizer versions, shadow-tokenize sampled traffic, compare exact bytes and length distributions, then move writers by cohort. Retain version tags and rollback until old stored IDs, caches, and queued jobs have expired or migrated.
Operate at three altitudes
Production lens
- — Attach tokenizer content identity to requests, caches, stored token IDs, embeddings, training examples, and evaluation runs.
- — Monitor sequence length, byte fallback, truncation, invalid UTF-8, and special-token handling by meaningful traffic cohort.
- — Shadow-tokenize before rollout and retain mixed-version readers until every persisted or in-flight ID has an explicit version.
- — Treat normalization, vocabulary, merge, unknown, and fallback changes as separately reviewable protocol changes.
Staff lens
- — Assign one owner for the byte-to-ID boundary across training, serving, caching, billing, and observability.
- — Require release evidence for reversibility, cohort tails, model compatibility, capacity impact, and rollback—not one aggregate compression score.
- — Design artifact formats so vocabulary bytes, merge ranks, special-token rules, and source provenance are content-addressed and reproducible.
Interview defense
Why should an AI engineer treat tokenization as a compression contract rather than simple preprocessing?
A tokenizer is a versioned byte-to-ID protocol. Its normalization, vocabulary, merge order, special tokens, and fallback policy determine reversibility and how many model positions each input consumes. That affects context, truncation, cache memory, latency, and cost, often unevenly across languages and code. I would bind the full policy and exact input bytes, prove decode round-trip, measure token-count distributions by cohort, and roll out with mixed-version readers and explicit IDs. A good ratio on one corpus is not a universal quality claim.
Expect the interviewer to press on
- — Why can two visually identical strings tokenize differently?
- — What makes changing token IDs dangerous even if the vocabulary size stays fixed?
- — How would you evaluate a new tokenizer on production traffic?
Misconceptions to remove
“A token is a word or a stable semantic unit.”
A token is an ID for a byte or character piece under one learned and versioned policy; boundaries need not align with words or meaning.
“Byte fallback makes every tokenizer equally good for every language.”
Fallback can preserve coverage and round-trip while still producing long, costly sequences for underrepresented inputs.
“A lower token count proves a better tokenizer.”
It is one efficiency observation. Reversibility, control-token safety, model compatibility, cohort behavior, and downstream evaluation remain separate gates.
Check your model
1. Why must merge rank be included in a tokenizer identity?
Eligible pairs can overlap. Rank order determines which pairs merge first and can change final boundaries and IDs even when the piece inventory is unchanged.
2. What does exact byte round-trip establish?
It establishes that encoding then decoding preserved the captured byte sequence under that contract; it does not establish efficient segmentation or model quality.
3. Why report token expansion by cohort instead of one average?
Averages hide tail and group-specific fragmentation that changes truncation, latency, capacity, cost, and access to usable context.
Prove the mechanism
Add a second evidence corpus containing composed and decomposed Unicode, source code, emoji, and two scripts. Report exact round-trip and token-count distributions without changing the illustrative policy.
Add a production constraint
Design a reversible dual-tokenizer rollout for persisted prompts and cached prefixes. Specify identity propagation, shadow evidence, cutover gates, rollback, and the condition for removing the old reader.
Artifact: Tokenizer compression audit
courses/ai-engineering/reference-impl/tokenization_contract/tokenization_contract.py
Download reference implementationPrimary references and next links
References
- 1. Neural Machine Translation of Rare Words with Subword Units
Sennrich, Haddow, and Birch. Primary paper applying byte pair encoding to open-vocabulary neural machine translation.
- 2. SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing
Kudo and Richardson. Primary paper describing training and segmentation directly from raw sentences.
- 3. Japanese and Korean Voice Search
Schuster and Nakajima. Primary publication associated with the WordPiece segmentation approach.
Continue through the graph
- KV-cache capacity planning →
Connect token counts to persistent inference memory.
- Dataset lineage →
Carry provenance discipline into tokenizer evaluation corpora.
- AI/ML interview questions →
Practice concise model-internals explanations.
Glossary: byte pair encoding · vocabulary · merge rank · Unicode normalization · byte fallback · round-trip