What Is Tokenization in LLMs?
Tokenization converts text into an ordered sequence of units called tokens, such as whole words, word fragments, punctuation, or byte sequences. The tokenizer maps those units to integer IDs so a large language model can process them. The same text can produce different token counts with different tokenizers, which affects context limits and, on many APIs, cost.
A large language model (LLM) receives the tokenizer's output as input. For example, the sentence The cat is sitting on a chair. might contain eight tokens under a word-and-punctuation rule. A subword tokenizer could split sitting into two pieces and produce nine. Neither count tells you what a particular deployed model will use. You need its tokenizer and, for a chat request, the rules that turn messages into a model input sequence.
| Unit | Illustrative split | Engineering trade-off |
|---|---|---|
| Word and punctuation | sitting | . | Common words take one position each, but a fixed word vocabulary may map unseen words to an unknown token. |
| Character | s | i | t | t | i | n | g | . | Units are small, so sequences are often longer. A fixed inventory of characters can still miss unseen code points. |
| Subword | sit | ting | . | Frequent strings can occupy one position, while rarer strings can be composed from smaller pieces. |
| Byte | 73 | 69 | 74 | 74 | 69 | 6E | 67 | 2E in hexadecimal | All UTF-8 text can be represented using 256 possible byte values, but one token per byte can make sequences long. |
These categories can overlap. A byte-level subword tokenizer starts from bytes and learns merged pieces. One learned piece may represent a whole word, while another may represent part of a UTF-8 character. This lets the tokenizer represent text it never saw during training without maintaining a separate vocabulary entry for every possible word. Subwords typically make the vocabulary smaller than a word-level vocabulary targeting comparable coverage, at the cost of using more positions for some words.
How Do Tokens Become Token IDs in an LLM?
A trained tokenizer has a vocabulary that assigns each token entry an integer ID. Consider an illustrative vocabulary in which "The" maps to 10, " cat" to 11, " is" to 12, " sit" to 13, and "ting" to 14. Under this toy tokenizer, The cat is sitting becomes [10, 11, 12, 13, 14]. The leading spaces inside some quotes are part of the piece. A bare "cat" and " cat" can have different IDs.

The IDs are lookup keys, so numeric distance between IDs has no semantic meaning. Given a learned embedding matrix E of shape [vocab_size, hidden_size], the sequence above selects five rows: E[10] through E[14]. If hidden_size = 768, the resulting tensor for this sequence has shape [5, 768] before a batch dimension is added. Repeating an ID selects the same input embedding row. The Transformer then uses positional information and attention to compute representations that depend on where each occurrence appears and what surrounds it.
A deployed model and tokenizer are paired. Even if another tokenizer assigns a different ID to a visually identical piece, you cannot substitute that ID and expect to retrieve the intended embedding. A vocabulary can also reserve IDs for control functions such as end of sequence, padding, or chat role boundaries. Whether any of these are added depends on the model, tokenizer settings, and request formatting. In a padded batch, an attention mask commonly tells the model which positions are padding.
For an autoregressive LLM, generation goes in the other direction. At each step, the model returns next-token scores over its output vocabulary, and the decoding strategy selects an ID. To display text, the tokenizer's decoder reconstructs text from the sequence of selected IDs. Decoding IDs one at a time and joining the resulting strings may fail for byte-based pieces that only form valid UTF-8 when decoded together.
How Does BPE Tokenization Learn Subwords?
Byte Pair Encoding (BPE) learns pieces by repeatedly merging adjacent symbols. It helps to separate tokenizer training from encoding. During training, the algorithm counts pairs in a corpus and records an ordered list of merges. During encoding, it applies those learned merge priorities to a new input. It does not relearn pair frequencies from each new sentence.

Train a miniature BPE tokenizer on three copies of low and two copies of lower. Start from individual letters and treat each word as a separate pre-tokenized segment. This example uses letters to make the steps visible; a byte-level variant can start from bytes instead. Set a budget of two merge steps and break the initial tie in favour of (l, o).
- Count adjacent pairs. In the starting sequences
l o wandl o w e r, the pairs(l, o)and(o, w)each appear five times. The pairs(w, e)and(e, r)each appear twice. - Merge
l + o. The new symbol islo. The sequences becomelo wandlo w e r, with the same original frequencies of three and two. - Recount and merge
lo + w. The pair(lo, w)now appears five times and wins the next step. The resulting sequences arelowandlow e r. The example stops here because the merge budget is exhausted.
The merges are applied in learned priority order among the pairs available at each step. When this tiny tokenizer later encounters lower, the two rules yield low | e | r. There is no learned rule for e + r, so the suffix stays split. A different corpus, tie-breaking rule, or merge budget could produce another segmentation. BPE optimises for pair frequency during this procedure, so its pieces need not match syllables or grammatical units.
Real tokenizers can also normalise text and pre-tokenize it before applying the subword algorithm. Normalisation may change the input, for example by mapping canonically equivalent Unicode sequences to a common form. Pre-tokenization controls where merges are allowed and may preserve a leading space with a word-like span. A tokenizer whose base alphabet cannot represent a symbol needs an unknown-token policy, byte fallback, or another coverage mechanism. Starting from UTF-8 bytes gives byte-level BPE coverage of arbitrary Unicode text encoded as valid UTF-8.
Worked Example: How Many Tokens Are in a Sentence?
Take The cat is sitting on a chair. For comparison, define a word-and-punctuation rule that uses spaces as separators and emits a separate token for the period. It yields The | cat | is | sitting | on | a | chair | ., which is eight tokens. This rule discards the separators. It cannot tell you whether the source had one space or two between words unless that information is stored separately.
Extend the earlier toy subword vocabulary with " on": 15, " a": 16, " chair": 17, and ".": 18. Assume the toy tokenizer chooses the pieces shown below. This example illustrates ID lookup and space preservation. The pieces were not learned using the low and lower training example.
Text: The cat is sitting on a chair.
Pieces: ["The", " cat", " is", " sit", "ting", " on", " a", " chair", "."]
IDs: [10, 11, 12, 13, 14, 15, 16, 17, 18]
Count: 9
Count the IDs, not the distinct vocabulary entries or the number of spaces. In this toy scheme, The cat contains two tokens, and The cat cat contains three even though the ID for " cat" repeats. The count is a sequence length. If a request formatter appends one end marker to the nine-token sentence, the resulting sequence has ten positions. That difference matters when comparing raw text counts with model input counts.
How Do You Count Tokens in Python?
Install transformers with python -m pip install transformers. The example loads the GPT-2 tokenizer and downloads its tokenizer files on first use if they are absent from the local cache. It does not load model weights. Inspect the IDs and pieces side by side, then decode the full sequence to check how the original text is reconstructed.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
samples = [
"The cat is sitting on a chair.",
"cat",
" cat",
"नमस्ते",
"SELECT id FROM orders;",
]
for text in samples:
ids = tokenizer.encode(text, add_special_tokens=False)
pieces = tokenizer.convert_ids_to_tokens(ids)
decoded = tokenizer.decode(ids, clean_up_tokenization_spaces=False)
print(f"\nInput: {text!r}")
print(f"Characters (Python len): {len(text)}")
print(f"UTF-8 bytes: {len(text.encode('utf-8'))}")
print(f"Tokens: {len(ids)}")
for token_id, piece in zip(ids, pieces):
print(f" {token_id:5d} {piece!r}")
assert decoded == text
GPT-2's tokenizer may display Ġ in a vocabulary piece to represent a space byte. That symbol is part of the tokenizer's internal display convention. It does not appear in the decoded sentence unless it was actually present in the input. The Hindi example shows why characters, bytes, and tokens are separate measurements. Python's len(text) counts Unicode code points, while what a reader sees as one written unit may combine several code points. UTF-8 can also use multiple bytes for one code point.
For a local chat model, use its documented chat template to tokenize the complete messages if one is available. With a configured Hugging Face chat template, tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True) can produce IDs for a conversation ready for generation. Follow the model's instructions for whether a generation prompt is needed. For a hosted API, use the provider's model-specific counter if supplied, then compare estimates with the usage data returned by real calls. The GPT-2 example cannot serve as an exact counter for an unrelated API model.
How Do Tokens Affect Context Limits and API Costs?
A context window limits how many token positions a model can work with at once. For a decoder-only deployment with a shared input and output limit, budget for the formatted input plus the requested output allowance. The service may also impose a separate output cap. System instructions, message history, retrieved passages, tool descriptions, and formatting can all contribute to the input. Counting only the latest user message can substantially understate the total.
Suppose a model has a shared limit of 8,192 tokens. Your formatted input contains 550 tokens of instructions and framing, 750 tokens of user turns and conversation history, and 6,000 tokens of retrieved text. That is 7,300 input tokens, leaving 892 positions. If you request up to 1,200 output tokens, the budget exceeds the window by 308. You could reduce the input by at least 308 tokens or lower the output allowance to 892 or less, subject to any separate cap. Do not assume a provider will safely shorten an oversized request for you.
For an API with separate input and output rates quoted per million tokens, the basic formula is cost = (input_tokens × input_rate + output_tokens × output_rate) / 1,000,000. Use actual billed counts for completed calls. The output allowance is a planning ceiling; the model may stop well before it reaches that ceiling.
For arithmetic practice, use hypothetical rates of ₹20 per million input tokens and ₹80 per million output tokens. A call billed for 2,400 input tokens costs ₹0.048 for the input. Another 600 output tokens cost ₹0.048, giving ₹0.096 for the call. At 10,000 calls with identical usage, the total would be ₹960 before any taxes or other charges. Real pricing may distinguish cached input, reasoning tokens, tool charges, or other usage categories. Use the provider's billing definitions rather than assuming visible answer text captures all billed output.
How Can You Reduce Token Usage Without Losing Important Context?
Start by measuring which parts of the request consume the budget. Log counts for instructions, conversation history, retrieval, and generated output where your stack exposes them. For counts that must add up exactly, measure the final formatted request. Tokenizing components separately can give a different total because separators or formatting change piece boundaries. Test on representative inputs, including Indian-language text, mixed-language messages, code, and identifiers if your application receives them. A fixed characters-per-token rule can hide large differences between these cases.
In a retrieval-augmented generation (RAG) system, split documents using the tokenizer relevant to each limit. The embedding model and the generator may use different tokenizers. A chunk that fits the embedding model can still consume more generator context than expected once you add citations and neighbouring passages. Remove duplicated retrieved text first, preserve source boundaries and references, and reserve output space before deciding how many passages to include.
For a support chatbot, retain the user's current issue and details that the next answer must respect, such as exact error messages. Replace older resolved turns with a compact summary if your evaluation shows they can be compressed safely. For a coding assistant, preserve indentation and identifiers when they matter to the task. Compare the shortened request with the original on a test set: measure token savings alongside answer accuracy, citation quality, or whether the generated code passes tests. A lower count is useful only if the application still produces acceptable results.
Key Takeaways
- Tokenization turns text into an ordered sequence of token IDs. A token can represent anything from a byte fragment to a whole word.
- BPE learns merge priorities from adjacent-pair counts and reuses those rules at inference time.
- Token IDs index the model's vocabulary and input embeddings. Their numbers do not encode meaning or similarity.
- Vocabulary pieces can include spaces, and characters, bytes, and tokens measure different things.
- Count the fully formatted input, including any chat overhead, and leave room for generation within the applicable context limit.
- Use reported usage and model-specific pricing to estimate API cost. Measure task quality before removing context to save tokens.
Frequently Asked Questions
Is one token the same as one word?
No. A token may contain a full word, a word fragment, punctuation, whitespace, or bytes that form only part of a character. A familiar word might take one token while a technical identifier takes several. Run the target model's tokenizer on representative text rather than treating the word count as the token count.
Why can Hindi and English have different token counts for the same message?
A tokenizer learns pieces from its training corpus. If it learned longer reusable pieces for one language or writing style, equivalent text in another language may be split into more pieces. Script, spelling, spacing, and the particular tokenizer all matter. Test both languages on the deployed model before setting limits for a multilingual application.
Can two LLMs assign different IDs to the same token?
Yes. An ID has meaning only inside the vocabulary used by that model and tokenizer. Two tokenizers can assign different IDs to the same piece, or they can split the original text in different ways. To move a prompt between models, pass the original text and encode it again with the destination tokenizer.
Does BPE handle words that never appeared during training?
Usually, if the word can be represented by the tokenizer's base symbols. BPE can combine known pieces and leave unfamiliar parts as smaller units. Byte-level BPE can represent valid UTF-8 text through its byte inventory. A tokenizer with a limited character alphabet and no fallback may still emit an unknown token for an unsupported symbol.
Why does my API report more input tokens than my local counter?
Your local counter may be encoding only the visible prompt. The API may also count message boundaries, role markers, prior messages, tool schemas, or other request components that reach the model. Confirm that the counter matches the deployed model and its request format, then use the API's usage data to reconcile the difference.