Forward Deployed EngineeringAI EngineeringTokenization

What is a token, and why should an FDE care about tokenization?

Question 15 of 73 · Updated

On this page

Interview-ready answer#

A token is a discrete unit of text or other input that a model's tokenizer maps to an integer ID. It may represent an entire word, part of a word, punctuation, whitespace, or a byte sequence. An LLM processes these IDs as learned embeddings and generates output by predicting successive token IDs, rather than producing words directly.

As a Forward Deployed Engineer, I care about tokenization because tokens determine how much information fits in the context window, influence inference latency and memory, and often form the basis of API pricing and rate limits. Different tokenizers can represent the same text using different numbers of tokens, particularly for multilingual content, code, identifiers, and unusual formatting.

In production, I would use the deployed model's tokenizer or official token-counting interface, budget for the entire serialized request and output, and compare estimated token usage with actual service usage. I would optimize context selection and output length without sacrificing customer task quality.

1. From text to model input#

Input text → Tokenizer → Token IDs → Embedding lookup → Transformer

During generation, the model produces vocabulary-sized logits, a decoding strategy selects a token ID, and the tokenizer's decoder converts generated IDs back into text.

A tokenizer and its vocabulary are part of the model's input/output contract. An arbitrary tokenizer cannot replace the original one without compatibility considerations: token IDs must correspond to the model's learned embedding and output tables.

Intuitive examples#

TextPossible segmentation (illustrative only)
hellohello
unbelievableun · believ · able
order_id_12345order · _id · _ · 123 · 45
hello!hello · !

These are invented segmentations for explanation, not outputs from a particular tokenizer. Actual boundaries depend on the vocabulary, preprocessing and tokenizer configuration. Some tokenizers encode a leading space as part of a token; others handle whitespace differently.

A character, a Unicode code point, a UTF-8 byte, a word and a token are different units. For instance, a single visible emoji may comprise multiple code points and tokens. Counting words or characters therefore cannot guarantee a request fits a model's context.

2. Common tokenization algorithms#

AlgorithmCore ideaPractical consideration
Byte Pair Encoding (BPE)Learn frequent adjacent symbol merges and apply learned merge rulesRepresents common patterns efficiently while allowing rare strings to be decomposed
WordPieceLearn subword units using a vocabulary-selection objective; commonly tokenize with longest-match segmentationEffective for subword representation; unknown-token behavior depends on the implementation
Unigram language modelStart with a large candidate vocabulary and prune it based on a probabilistic segmentation objectiveSupports alternative segmentations and can select a high-probability sequence
Byte-level tokenizationOperate on a byte representation, often combined with BPECan represent arbitrary valid text without requiring a separate vocabulary entry for every Unicode character

SentencePiece is a tokenizer framework that supports algorithms including BPE and Unigram; it is not itself synonymous with Unigram. Byte-level representation and byte-pair merges are related design choices, not mutually exclusive categories.

For an intuitive BPE example, suppose the training corpus contains many occurrences of "low", "lower" and "lowest". Frequent adjacent symbols such as "l" and "o" may be merged, and later merges may produce "low". Rare words can still be represented using smaller learned units. This is a simplified illustration of vocabulary learning, not a recreation of a deployed model's merge table.

3. Why multilingual tokenization matters#

Tokenizer efficiency depends on how the vocabulary represents scripts, words, punctuation and common patterns. Hindi, English, Japanese, Arabic, mixed-language messages and source code can have very different token-to-character ratios.

An FDE deploying a customer support assistant across several languages should measure token distributions on actual customer traffic. Do not assume that English token estimates generalize to every language, or that a language always requires more tokens than English across all models. A tokenizer that fragments a script or technical vocabulary heavily may increase context consumption and cost; model quality must still be evaluated independently.

Preserve meaningful Unicode, whitespace and formatting in code, identifiers and legal documents. Avoid aggressive normalization that changes semantics. For search and indexing, use a documented normalization policy, preserve original text and source offsets, and evaluate the impact on retrieval.

For streaming, do not assume every token maps to a complete visible character or word. Some token byte sequences may need to be combined before UTF-8 decoding. Use the serving SDK's streaming decoder or an appropriate incremental decoder rather than independently decoding arbitrary byte fragments.

4. Token budgets and context limits#

For a conventional model with a shared input-plus-output context window:

Serialized input tokens + reserved output tokens + safety margin ≤ context window

Serialized input includes more than the user's visible message: system instructions, role markers, conversation history, tool schemas, tool results and retrieved evidence can all consume capacity. Provider-specific input and output limits, multimodal accounting and reasoning-token rules may also apply.

Consider a hypothetical model with a 32,768-token window. If the base serialized input contains 6,300 tokens, the output reserve is 4,096 and the safety margin is 1,024, the remaining nominal context budget is 21,348 tokens. Additional content must fit after serialization; tokenizing separately concatenated fragments can give a different total because of token boundaries and formatting.

Python example: enforce a conservative token budget#

The following helper operates on already-measured token counts; it does not implement a tokenizer or claim to reproduce any provider's billing rules.

PYTHON
def remaining_context(window: int, serialized_input: int, output_reserve: int, safety_margin: int = 0) -> int: if window <= 0 or min(serialized_input, output_reserve, safety_margin) < 0: raise ValueError('Invalid token budget') remaining = window - serialized_input - output_reserve - safety_margin if remaining < 0: raise ValueError('Request exceeds context budget') return remaining print(remaining_context(32768, 6300, 4096, 1024)) # 21348

Inputs are assumed to be integers. Use the deployed model's tokenizer or provider counting interface to obtain the serialized input count, then recount the assembled request before sending. Apply separate provider limits as additional constraints.

Local verification: 12,246 checks passed: 12,240 combinations of positive window sizes and nonnegative input, output and margin counts, five invalid-parameter cases, and the explicit 32,768-token example. Tests checked both successful budgets and overflow rejection. No model-specific tokenizer was installed locally, so actual model token boundaries were not tested.

5. Token usage, inference cost and performance#

For a service that charges separately for input and output tokens, a simplified estimate is:

Request cost = (input tokens × input rate + output tokens × output rate) / 1,000,000

Here the rates are currency per million tokens. For hypothetical rates of $2 per million input tokens and $8 per million output tokens, a request with 10,000 input tokens and 1,000 output tokens costs $0.028 under that simplified pricing model. These are illustrative rates, not current provider prices. Cached input, reasoning, tools, multimodal inputs and other services may have different accounting.

Tokens also affect latency. More prompt tokens generally increase prefill work, while more generated tokens require additional autoregressive decoding steps. In conventional full-attention models, longer sequences also increase attention computation and KV cache memory. Actual latency depends on hardware, architecture, batching, caching and concurrency; cost and latency are not interchangeable metrics.

Tokens per minute may be part of a service's rate limit. Measure both request and token usage, manage concurrency, and implement bounded retries with backoff for retryable failures. Check the provider's actual quota-accounting behavior.

6. Practical FDE deployment scenario#

Imagine an enterprise assistant that answers customer policy questions in English and Hindi. The team estimates prompt size using character counts and appends the entire chat history plus several retrieved documents on each request. Some requests exceed the context limit, while others are expensive or slow.

I would first measure the exact serialized input and actual output usage across language and task segments. Then I would introduce a token-aware context budget, rank and deduplicate authorized evidence, retain relevant conversation state, and reserve generation capacity. I would also compare model and tokenizer choices on representative multilingual questions rather than optimize token efficiency alone.

Track p50/p95 input tokens, output tokens, context-limit errors, time to first token, total latency, cost per successful task, and answer correctness by language. Compare the baseline and optimized configuration on the same held-out questions. If token reduction removes critical evidence or disproportionately harms one language, revise the approach.

This is a hypothetical engineering scenario, not a measured customer result.

7. Common mistakes and trade-offs#

  • Treating a token as a word or assuming a fixed characters-per-token ratio.
  • Counting the visible prompt while forgetting system instructions, tool definitions and chat serialization.
  • Using a tokenizer from a different model and assuming the counts are interchangeable.
  • Truncating text by bytes or characters and breaking Unicode, citations or important instructions.
  • Cutting output limits so aggressively that answers or structured responses become incomplete.
  • Optimizing cost per request without checking the cost per correct, completed customer task.
  • Logging raw prompts unnecessarily. Prefer usage statistics and authorized, redacted diagnostic samples.

For RAG, token-aware chunking should respect the embedding model's tokenizer and input constraints, while context assembly must respect the generator's tokenizer and limits. They may differ. Prefix caching may reduce repeated computation or billing where supported, but it does not by itself create extra context capacity.

Likely interviewer follow-ups#

  • Why do two models report different token counts for the same text? Their vocabularies, normalization, segmentation and chat templates may differ.
  • Can you estimate tokens using words? Only as a rough heuristic calibrated to a particular workload; use the exact tokenizer for hard limits.
  • Does a larger vocabulary always improve efficiency? No. It can reduce fragmentation for some text, but embedding/output dimensions, training choices and language coverage introduce trade-offs.
  • How would you reduce token cost without hurting quality? Remove redundant context, retrieve relevant evidence, control output length, use caching where appropriate, and evaluate task quality against the original configuration.
  • What is the difference between tokenization and embeddings? Tokenization maps input to discrete IDs; embeddings map those IDs into learned continuous vectors used by the model.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.