Text as model input
Tokens and vocabulary IDs
A token is one entry in a tokenizer’s finite vocabulary. Encoding converts text into an ordered sequence of token IDs; decoding maps IDs back toward text. Depending on the tokenizer, an entry may represent a word, a word fragment, punctuation, whitespace, a byte sequence, or a structural marker. A token is therefore neither reliably a word nor reliably a character. The tokenizer associated with the selected model defines the mapping.
One string, seven vocabulary entries
| Text piece | Token ID |
|---|---|
2 | 17 |
+ | 489 |
| 220 |
2 | 17 |
= | 284 |
| 220 |
4 | 19 |
Repeated pieces reuse the same IDs, but the numbers themselves are names, not measurements. ID 220 is not semantically “between” IDs 17 and 489. The model uses each ID to retrieve a learned vector and then computes with those vectors; Embeddings and Representation Learning explains that numerical representation. Changing IDs or using another tokenizer changes which learned rows the model receives, so tokenizer compatibility is part of the model interface rather than an interchangeable preprocessing preference. Ishan Anand’s GPT walkthrough provides an implementation-oriented view of this transition from pieces to IDs and vectors.
Characters, code points and bytes
Before inspecting a token boundary, name the text unit. A Unicode code point is a numbered position in the Unicode codespace. A grapheme cluster is a programmatic approximation to a user-perceived character and may contain several code points. UTF-8 then represents Unicode scalar values using one to four bytes. Some programming environments expose UTF-16 code units as yet another length and offset system.
Two representations of é
| Form | Code points | UTF-8 bytes |
|---|---|---|
Composed é | U+00E9 | C3 A9 |
Decomposed é | U+0065 U+0301 | 65 CC 81 |
One visible span, three coordinate systems
A👩💻B
| Character | Code point | UTF-16 span | UTF-8 span | UTF-8 bytes |
|---|---|---|---|---|
| A | U+0041 [0, 1) | [0, 1) | [0, 1) | 41 |
| 👩 | U+1F469 [1, 2) | [1, 3) | [1, 5) | F0 9F 91 A9 |
| ZWJ | U+200D [2, 3) | [3, 4) | [5, 8) | E2 80 8D |
| 💻 | U+1F4BB [3, 4) | [4, 6) | [8, 12) | F0 9F 92 BB |
| B | U+0042 [4, 5) | [6, 7) | [12, 13) | 42 |
Each interval is zero-based and end-exclusive. ZWJ is U+200D, the zero-width joiner. Highlighting the same emoji requires three different index pairs; tokenizer offsets require a separately specified tokenizer.
A tokenizer may preserve this distinction, normalize it away, or split the byte sequences in different places. Consequently, a UI showing one apparent character does not establish a string length, byte length, token count, or safe slicing boundary.
Preprocessing sets boundaries
Tokenizer implementations commonly separate several responsibilities. Normalization transforms text under chosen equivalence rules. Pre-tokenization establishes regions within which the segmentation model may operate. The model then selects vocabulary pieces, and post-processing may insert special tokens. These stages are configurable; they are not universal properties of tokenization.
From source text to vocabulary IDs
- 1. Source textThe application supplies a string.
- 2. NormalizeConfigured rules may change that text.
- 3. Pre-tokenizeEstablish regions; these are not final tokens.
- 4. Select piecesUse fixed trained rules within each region.
- 5. Look up IDsMap pieces to vocabulary entries.
- 6. Post-processOptionally add configured structural tokens.
- 7. Ordered IDsEmbedding lookup happens afterward.
Normalization can discard distinctions an application needs, while lowercasing, accent removal, and whitespace cleanup are separate transformations. Treat every configured transformation as part of the input contract.
Pre-tokenization constrains later choices. In the inspected tiktoken 0.11.0 definition, one numeric expression creates regions of one to three numeric characters; for constructed ASCII input, 1234 first becomes 123|4. Those are preliminary regions, not a claim about the final token IDs: vocabulary merges still decide the pieces inside each region.
Vocabulary design
Vocabulary size, coverage and length
A whole-word vocabulary is compact for frequent known words but needs an entry for every retained form. Unseen names, misspellings, compounds, and inflections then require an unknown marker or another fallback. An unknown token preserves only the fact that some unsupported input occurred; it cannot reconstruct which input was lost. Character and byte representations avoid a huge word inventory, but usually produce longer sequences. Subword tokenization uses reusable fragments between those extremes, without promising that the fragments are linguistic morphemes.
Granularity moves costs rather than removing them
| Unit | Vocabulary pressure | Coverage | Typical sequence effect |
|---|---|---|---|
| Whole word | High across domains and languages | Unsupported forms may become unknown | Short for known words |
| Character | Small alphabet-dependent inventory | Depends on character coverage | Longer sequences |
| UTF-8 byte | 256 ordinary byte values plus controls | Can represent arbitrary valid UTF-8 bytes | Often longer sequences |
| Subword | Learned middle-sized inventory | Depends on base symbols and fallback | Frequent patterns become shorter |
Vocabulary size also affects model parameters because token IDs index an embedding table with roughly vocabulary size times vector width entries. That matters especially for tiny models: a vocabulary suitable for a large multilingual system can dominate a small educational model’s parameter budget. But a smaller inventory may increase sequence work, so neither vocabulary size nor token count alone identifies the cheapest design. Byte-based models remain a live alternative: the 2022 ByT5 study removed the learned subword vocabulary, accepted longer sequences, and reported task-dependent advantages on tested noisy and spelling-sensitive workloads. It was a separately trained architecture, not a replacement tokenizer for an existing checkpoint.
Must-know turning points
Several lines of work contributed different parts of today’s tokenizer interface: compression, open-vocabulary segmentation, neural subword translation, and reproducible raw-text processing.
Four contributions to tokenization
- Byte-pair encoding
Block-oriented data compression repeatedly replaced frequent byte pairs and stored their substitutions; it was not yet a language-model tokenizer.
Philip Gage
A New Algorithm for Data Compression - Statistical word pieces
Statistical word pieces addressed open-ended vocabulary and text without explicit word spaces in Japanese and Korean speech recognition.
Mike Schuster and Kaisuke Nakajima; Google speech-recognition team
Excellent Papers for 2012 — Japanese and Korean Voice Search - Subword translation
BPE was adapted to represent rare names, compounds, and changing word forms with reusable subword units inside a translation model.
Rico Sennrich, Barry Haddow, and Alexandra Birch
Neural Machine Translation of Rare Words with Subword Units - SentencePiece
SentencePiece packaged BPE or Unigram segmentation, normalization rules, and raw-text processing into a reproducible model artifact.
Taku Kudo and John Richardson
SentencePiece: A simple and language independent subword tokenizer and detokenizer for Neural Text Processing
These are connected developments, not a ladder on which each new method eliminated the previous one. Word, character, byte, BPE, WordPiece, and Unigram approaches continue to coexist because their coverage, sequence length, preprocessing, and implementation tradeoffs differ.
Learning and applying BPE
Byte-pair encoding (BPE) separates vocabulary training from request encoding. Training repeatedly merges selected adjacent units and records their priorities. Encoding later applies those fixed priorities to new text; it does not recount the request or retrain the vocabulary.
Counts follow the current segmentation
In the published word-bounded BPE procedure, adjacent-pair counts are weighted by word frequency. Each merge changes the current segmentation, so the next pair is counted from that updated representation. Boundary and tie policies must be specified for a reproducible vocabulary.
Rank priority is not longest match
Applying ranks is not the same as greedily taking the longest vocabulary entry. A tokenizer must be identified by more than its vocabulary list. In the comparison, BPE changes merge priority; WordPiece changes the available prefix pieces; Unigram changes piece probabilities and compares their products across complete segmentations. These controls belong to different algorithms. Anand’s implementation walkthrough demonstrates the repeated-merge intuition in an accessible model reconstruction.
Same text, different segmentation rules
Base pieces: a, b, c, ab, bc. Each algorithm has its own configuration; changing one control affects only that algorithm. No abc piece or later merge is available.
Ranked BPE
a | bc
Start: a | b | c
- Merge bc (rank 1) → a | bc
Stop: no eligible adjacent pair remains. Lower rank wins; ties use the leftmost pair.
WordPiece: longest match
ab | c
ab · ##c
Choose the longest match at each position. Noninitial vocabulary entries use ##; it is a continuation marker, not input text. The fixture includes initial and continuation versions of every listed piece.
Unigram: score full paths
a | bc
P(a)=0.15, P(b)=0.10, P(c)=0.10. Moving the slider redistributes the remaining 0.65 between ab and bc. All five probabilities sum to 1.
Multiply piece probabilities across each complete path; the largest product wins. The table evaluates every path for this short input.
For abc: BPE a | bc; WordPiece ab | c; Unigram a | bc.
| Path | Piece probability product | Score |
|---|---|---|
| Best: a | bc | 0.15 × 0.40 | 0.06 |
| ab | c | 0.25 × 0.10 | 0.025 |
| a | b | c | 0.15 × 0.10 × 0.10 | 0.0015 |
WordPiece, Unigram and SentencePiece
Reusable pieces do not imply one selection algorithm. The original BERT WordPiece encoder works left to right, choosing the longest vocabulary match at each position. Continuation pieces use the ## prefix; its documented example represents unaffable as un, ##aff, ##able. If a remaining span cannot be matched, that implementation emits the unknown token for the whole word.
A Unigram tokenizer instead assigns scores to vocabulary pieces and evaluates complete candidate segmentations. The best segmentation is the highest-scoring path, commonly found with the Viterbi algorithm; the same inventory can admit several alternatives. Kudo’s 2018 subword-regularization work sampled such alternatives during training to create segmentation variation. That does not imply that randomly changing segmentation at inference will improve an already-trained model.
Different names answer different questions
| Name | What it identifies |
|---|---|
| Ranked BPE | Repeated use of learned merge priorities |
| Original BERT WordPiece encoder | Longest matching piece from each position |
| Unigram | A scored choice among complete segmentations |
| SentencePiece | A toolkit and artifact format supporting BPE, Unigram, and configurable text processing |
Google’s 2016 GNMT system adopted speech-derived WordPiece to help with rare-word translation and copying, but the deployed system combined many changes; its overall results cannot be assigned to tokenization alone. SentencePiece later made raw-text preprocessing and reconstruction rules part of a portable tokenizer artifact, improving reproducibility without guaranteeing preservation of distinctions removed by normalization.
Reconstruction and source locations
What decoding preserves
A text round trip, decode(encode(text)), preserves the original string only when the full pipeline is reversible for that input. Normalization may replace the original representation; unsupported input may become an unknown token; decoding may omit special tokens or clean spaces. Even when text round-trips, the reverse encode(decode(ids)) need not reproduce the same IDs because several token sequences can decode to the same text.
Reconstruct bytes before characters
A byte-based token boundary can fall inside a multibyte UTF-8 character. Decode the reconstructed byte stream, not each arbitrary fragment independently. An incremental decoder retains incomplete input between calls and handles any remainder when the stream ends.
A byte fragment can end inside a character
é → UTF-8 C3 A9 → fragments [C3], then [A9]
Independent decoders
[C3] → end of fragment → �
[A9] → decode alone → �
Combined emitted text: ��
Both are U+FFFD under replacement handling.
One stateful decoder
[C3] → buffer C3 → emit nothing
[A9] → complete C3 A9 → emit é
End of stream → flush → empty buffer
Flush the decoder at end of stream: a remaining incomplete sequence must be handled according to the error policy. Strict decoding throws instead of replacing malformed input.
Do not apply that repair where it is unnecessary. Some hosted streaming APIs already deliver decoded text fragments rather than token bytes; those strings should be accumulated according to the API contract. A delivery event is not necessarily one model token. Inference Engineering covers streaming and serving behavior in depth.
Finally, reversible tokenization does not force the model to copy text exactly. Generation selects a new sequence from model predictions. Systems that require exact identifiers, quotations, or source strings must compare the produced value with the required original or bypass generation for that field.
Offsets need a coordinate system
An offset is incomplete without two declarations: the representation it indexes and the unit it counts. Byte offsets, Unicode code-point offsets, UTF-16 code-unit offsets, and token positions are different coordinate systems. Ranges should also state their convention; the examples here use zero-based, end-exclusive intervals.
Name the coordinates
| Coordinate unit | What it counts |
|---|---|
| Unicode code points | Positions in the Unicode codespace sequence |
| UTF-16 code units | Sixteen-bit encoding units |
| UTF-8 bytes | Eight-bit encoding units |
| Token positions | Entries in one tokenizer output |
Normalization creates a second mapping problem: an offset into normalized text may need alignment back to the original. Hugging Face’s internal NormalizedString uses byte-level alignment data, while the Transformers fast-tokenizer interface documents returned offsets as character start/end pairs. Those contracts should not be conflated merely because both expose two integers. Applications that attach extracted values to source material need the same discipline across every transformation; Document Understanding and OCR’s alignment section develops that broader source-location problem.
Conversation structure
Special tokens and chat templates
A special token is a designated vocabulary entry used for structure or control. A chat template converts ordered role/content messages into the token sequence expected by a particular chat checkpoint. It can insert a beginning marker, role headers, turn endings, and—where required—a generation prompt marking the start of an assistant response. Message objects are therefore an application interface, not the representation consumed directly by the model.
Serialization is checkpoint-specific
A pinned Mistral-7B-Instruct-v0.1 configuration formats the conversation user Hi, assistant Hello, user Bye with instruction boundaries and sequence markers. This template does not add a separate assistant prefix. Other checkpoints use different role markers and continuation rules, even when they share a base architecture.
Format the conversation once
↓ apply the checkpoint template once
<s> [INST] Hi [/INST] Hello</s> [INST] Bye [/INST]Tokenize this serialization with additional special-token insertion disabled.
If automatic BOS insertion runs again: <s><s> [INST] Hi [/INST] Hello</s> [INST] Bye [/INST]
Pinned configuration: <s> is BOS ID 1; </s> is EOS ID 2. No full conversation ID sequence is asserted.
Mistral-7B-Instruct-v0.1, revision b54db9339734a22dd2b55531bd8146540729fbb8. This template adds no separate assistant prefix.
Three kinds of ending
| Mechanism | Role |
|---|---|
| End-of-sequence token | A model-vocabulary marker associated with sequence termination |
| End-of-turn or handoff token | A model-family convention marking a conversational boundary |
| Application stop string | A serving configuration that terminates after matching text |
Do not format twice
Apply structural formatting exactly once. If a chat template already inserts the required beginning token and a subsequent tokenization step inserts it again, the model receives a different prefix. Daniel Han’s fine-tuning bug review describes degraded inference when training and serving used different beginning-token counts. The same general rule applies to export: preserve the training serialization at inference. Padding is separate batch filler; if a training loss masks every occurrence of the padding ID, reusing an end-of-sequence ID for padding can also remove end targets from supervision. That conditional training issue belongs to Post-training and Alignment.
Structural markers guide the model’s learned interpretation; they do not authenticate a role or authorize an action. An application must enforce those responsibilities outside the tokenizer.
Language and boundary effects
Language, code and formatting
A tokenizer allocates its finite vocabulary according to training data and design choices. Patterns well represented in that data may receive long reusable pieces; less represented scripts, domain terms, identifiers, and numeric forms may fragment. Consequently, comparable information can occupy different numbers of tokens. The result describes representation length under one tokenizer, not a language’s complexity or a model’s intelligence.
Translated content can occupy different budgets
| Language | Tokens relative to English |
|---|---|
| English | 1.00 |
| French | 1.60 |
| Japanese | 2.30 |
These corpus-specific ratios are not universal conversions. A related metric, token fertility, is the average number of subwords per tokenized word. It requires a stated word-segmentation convention and is not the same denominator as a parallel-sentence token ratio. Neither metric directly measures downstream task quality.
Formatting can be equally surprising. Published cl100k_base regression fixtures show today followed by newline-space taking three tokens, while adding one more newline makes the string two tokens. More input characters produced fewer tokens because the complete pattern admitted a different segmentation. Indentation, punctuation, escaping, and numeric grouping can similarly alter counts—but only text presented to the model matters. Extra syntax in an HTTP envelope does not count unless the service serializes it into model-visible content.
Joining text changes boundaries
Tokenization is generally not additive under string concatenation. Encoding a + b can differ from concatenating encode(a) and encode(b) because the joined text changes pre-tokenization regions or creates adjacent units eligible for a merge. This matters for prompt prefixes, leading spaces, suffixes, partial words, and labels that look indivisible to a human.
Joined encoding is not fragment addition
| Operation | Result |
|---|---|
encode("0") | [15] |
encode("0") + encode("0") | [15, 15] |
encode("00") | [405] |
Both ID sequences can decode to the text 00, so decoding and re-encoding [15,15] need not preserve those original IDs. For counting and caching, always serialize the complete request before encoding rather than summing arbitrary fragments.
Test behavior, not a token-count folk rule
Boundaries can also complicate character-sensitive work, but they are not a complete causal explanation. The 2024 CUTE study found that tested models could often spell tokens yet struggled more with character insertion, deletion, substitution, and swapping. The 2025 CharBench preprint found different relationships for counting and character-position tasks, with word length and requested counts often mattering more than token count alone. These results rule out both extremes: tokenized models are not categorically blind to spelling, and fewer tokens do not universally solve character tasks.
A boundary change is a reason to run a controlled behavior test, not proof that a rewritten prompt is better. Prompting and In-Context Learning covers instructions, demonstrations, ordering, and held-out prompt experiments.
Request accounting
Count the complete request
The relevant input count belongs to the complete representation presented to the model: system instructions, serialized message history, role and boundary markers, retrieved content, and model-visible tool or schema definitions. The HTTP JSON envelope is a transport representation and should not be tokenized as a substitute unless its literal syntax is itself included in model content.
Count the complete model-visible request
Model-visible boundary
↓ serialized together; applicable role / turn markers inserted by template
↓ count this complete representation using the endpoint’s contract
Prompt count P
The HTTP envelope transports the request. Its ordinary field names, headers, and wire syntax remain outside this boundary unless literally exposed as model input. Separately tokenized fragment counts need not add up to the joined count.
What normally belongs in model input
| Material | Count it when |
|---|---|
| User and assistant content | The serialized request retains it |
| System instructions | They are supplied to the invocation |
| Role and turn markers | The selected template inserts them |
| Tools and schemas | The service exposes their definitions to the model |
| HTTP keys and wire syntax | Only when they become model-visible text |
Exact local counting requires the intended tokenizer artifacts, chat-template revision, special-token settings, and complete joined input. Pinning a repository revision does not freeze caller overrides. Adding vocabulary entries also requires resizing compatible model embedding parameters; a tokenizer with attractive counts cannot simply replace the checkpoint’s tokenizer.
Exact and estimated hosted counts
Hosted counters have provider-specific contracts. OpenAI documents its Responses input-count endpoint as returning the exact input count the model will receive, including role and boundary formatting. Claude documents its token-counting result as an estimate that can differ slightly from message-creation usage and may include automatically added material. Use the provider’s stated guarantee rather than generalizing one service’s semantics to another. Noah Hein’s AI Engineering 101 workshop illustrates the practical value of counting documents with the selected model tokenizer before processing them.
Reserve room for generation
A context window is a bound on the token sequence available to one model invocation. For an endpoint with a shared context limit, let be the complete counted prompt, the generated-token allowance reserved by the application, and the supported context capacity. If the endpoint also has a separate maximum output , both bounds must hold:
Reserve output within both limits
Shared context: 7350 + 700 = 8050. 142 tokens remain.
Separate output cap: R = 700; O = 1,000. Fits output cap.
Caching changes no segment’s occupancy. A reservation is an allowance, not a promise that the model emits that many tokens.
A max_new_tokens-style setting caps generated tokens; it does not prove that prompt plus generation fits the shared context. Provider-defined hidden reasoning or formatting tokens may also consume the generated allowance, so reserve according to the actual endpoint contract without counting the same category twice.
Different ways a bounded request can end
| Outcome | Meaning |
|---|---|
| Input rejection | The submitted representation exceeded an accepted limit |
| Input truncation | An application or runtime removed input tokens before execution |
| Natural completion | The runtime reported its normal completion condition |
| Output-cap termination | The returned prefix reached a generated-token bound |
| Context-limit termination | Generation filled the available shared context |
Cached prefixes still occupy context even when caching reduces processing charges. Likewise, fitting the nominal window does not guarantee that every retained fact influences the answer. Controlled long-context experiments have found position-dependent use in several tested models and tasks. Choosing what deserves the finite allowance is context allocation, covered in Context Engineering; architectural reach and effective use are discussed in When longer context helps.
From token usage to charges
Providers bill according to named usage categories rather than one universal token rate. Read the pricing table and usage schema together because input, cached input, and generated output can have different prices and reporting rules.
A dated accounting example
| Category | Usage | Rate per million | Charge |
|---|---|---|---|
| Ordinary input | 1,000 tokens | $3 | $0.003 |
| Output | 200 tokens | $15 | $0.003 |
| Total | $0.006 |
Cached is not absent
Claude reports cache reads, cache creation, and ordinary input separately. Add the documented categories when reconciling total input; cached prefixes still occupy context.
Tokenization therefore affects both capacity and charges: language, formatting, templates, and tool definitions can change counted input. But price per token alone cannot compare models whose tokenizers, output lengths, and task results differ. Token counts also affect computational work without determining elapsed latency; concurrency, batching, hardware, request rate, and output behavior matter. AI Cost and Performance Engineering owns those workload comparisons, while Inference Engineering covers serving behavior and bottlenecks.
Open questions
Can future byte- or patch-based model architectures retain open input coverage while matching subword systems’ practical training and serving efficiency? BLT concentrates expensive processing at uncertain byte regions, but operation counts do not yet establish equivalent wall-clock behavior or broad deployment. Progress would require controlled quality, latency, memory, and robustness comparisons at matched training resources.
How should multilingual tokenizer quality be evaluated when word boundaries, scripts, morphology, and downstream tasks differ? Existing fertility and parallel-corpus ratios reveal representation disparities but do not measure competence. Progress would combine explicit denominators, versioned tokenizers, representative workloads, and task outcomes across languages.
How much of character-level failure is caused by token boundaries rather than data, architecture, prompting, or task formulation? Recent studies find task-dependent relationships and show that models can possess spelling knowledge while failing at manipulation. Stronger causal evidence would hold the model and training data fixed while varying representation and evaluating multiple character operations.
Can provider token accounting become portable without hiding model-specific serialization? Current APIs expose different guarantees and category semantics. Progress would look like versioned, machine-readable contracts that identify tokenizer artifacts, template revisions, model-visible additions, count guarantees, and billing-category relationships.












