Tokenization and Vocabularies
Models process token identifiers
A tokenizer maps text to a sequence of token IDs and often maps those IDs back to text. Tokens can represent words, word pieces, characters, or bytes. A model's tokenizer is part of its interface; token IDs from one vocabulary do not carry the same meaning in another.
An illustrative split of “unhelpful” is [un, help, ful]. A real tokenizer may split it differently. Numbers, punctuation, whitespace, code, emoji, and non-English writing can produce surprising token counts. Do not budget context by assuming one word equals one token.
flowchart LR A[Text and message template] --> B[Tokenizer] B --> C[Token IDs] C --> D[Embedding lookup] D --> E[Transformer]
Byte-pair encoding starts with smaller units and learns frequent merges. WordPiece and Unigram use different vocabulary-building procedures. These algorithms determine segmentation; they do not themselves give a token semantic understanding.
Trace a toy tokenizer
vocabulary = {"hello": 0, " ": 1, "world": 2, "!": 3}
pieces = ["hello", " ", "world", "!"]
ids = [vocabulary[piece] for piece in pieces]
reverse = {value: key for key, value in vocabulary.items()}
print(ids) # [0, 1, 2, 3]
print("".join(reverse[value] for value in ids)) # hello world!This is a lookup illustration, not an implementation of BPE. Run it in the Python compiler, then ask how it would handle a word outside the vocabulary. Real systems handle unfamiliar text using smaller units, bytes, unknown tokens, or other tokenizer-specific mechanisms.
Special tokens and chat templates
Models can use special IDs for sequence boundaries, roles, or other controls. A chat template turns a list of messages into the sequence a model was trained to expect. Applying the wrong template can reduce quality even if the text looks reasonable to a person.
Token count affects cost, context capacity, and latency. Input accounting may include message formatting, tool schemas, retrieved text, and special tokens. Count with the tokenizer and endpoint behavior appropriate to the selected model.
Checkpoint with answers
Can you truncate an arbitrary byte sequence and always get valid text? No. Multibyte characters and tokenization boundaries require careful handling.
Why can an LLM struggle with character counting? Its processing units need not align with characters. Use deterministic code when an exact count is required.
What should an application store to reproduce token accounting? Model and tokenizer version, message template, and the full rendered request structure.