Understanding Tokens in LLMs: The Basic Unit of Text Processing

    This article explains what tokens are and why they are the fundamental unit large language models use to process text. It covers how subword tokenization works, why token counts vary across languages, code, and symbols, and how the context window constrains both input and output. It also shows how tokens affect cost, latency, and output quality, and closes with a practical checklist for capacity planning and cost control.

    1. What a Token Actually Is

    A token is not “a character” or “a word.” It is the smallest processing unit produced when text is split during preprocessing. The model never reads raw characters directly. Instead, it first maps the input string to a sequence of integer IDs, then passes those IDs to the rest of the network. So this is what a piece of text really looks like to the model:

    1. Raw text: "Tokenization is fun."
    2. Split result: ["Token", "ization", " is", " fun", "."]
    3. ID sequence: [30642, 1459, 318, 1257, 13]

    Three details here are easy to overlook:

    First, leading spaces are preserved in the split result. A space is usually bound to the word that follows it as a single unit, which is why the token count and the word count are not the same.

    Second, the IDs are what the model actually consumes. The strings are just an intermediate artifact meant for humans to read.

    Third, tokenization is deterministic. The same text and the same vocabulary always produce the same split. This matters a lot for caching and for reproducing experiments.

    2. How Splitting Works: From Vocabulary to Subwords

    Early approaches split on spaces, which made the vocabulary explode as soon as morphological variants or spelling variations appeared. Splitting by character avoided that, but produced sequences that were too long and carried too little meaning per unit. The mainstream modern approach is subword tokenization, which can be summarized in three steps:

    1. Build a vocabulary of finite size, keeping frequent fragments as whole units.
    2. For fragments not in the vocabulary, recursively break them into smaller pieces that do exist in the vocabulary.
    3. For anything still uncovered, fall back to a byte-level representation, so that no input can ever fail to tokenize.

    The byte-level fallback is the key design decision. It means emoji, rare characters, and binary garbage can all be encoded reliably. The cost is that such content consumes noticeably more tokens.

    A minimal illustrative implementation (for explaining the idea only, not production code):

    1. def encode(text, vocab):
    2. # Try a whole-string match first, then fall back character by character
    3. if text in vocab:
    4. return [vocab[text]]
    5. ids = []
    6. for ch in text:
    7. if ch in vocab:
    8. ids.append(vocab[ch])
    9. else:
    10. ids.append(BYTE_FALLBACK[ord(ch) % 256])
    11. return ids

    3. Why Token Counts Vary So Much

    For the same amount of “information,” token consumption can differ by several times. This is the most common source of misestimation in engineering work.

    • English: common words are usually one token, while long words and technical terms get split into two or three pieces.
    • Chinese: common characters are usually one token, but rare characters, traditional forms, and full-width punctuation may take more.
    • Numbers and symbols: long digit strings are often cut into several segments, so dates, amounts, and version numbers cost more than intuition suggests.
    • Code: indentation, brackets, and camelCase get split, so an identifier like getUserProfileById is usually not a single token.
    • Mixed languages: switching between languages tends to produce extra fragments at the boundaries.

    A rough but useful rule of thumb: English text costs about 1.2 to 1.5 tokens per word; Chinese text costs roughly the same order of magnitude as its character count, rising with punctuation and technical-term density. Production systems should rely on actual tokenization results, and use these rules of thumb only for capacity planning.

    4. Tokens and the Context Window

    The maximum number of tokens a model can process in one pass is called the context window, and it constrains input and output at the same time. The budget for a single request is therefore roughly:

    1. Total budget = system prompt + conversation history + retrieved snippets + user input + reserved output

    The most common failure in practice is not “the model cannot answer.” It is “the input was silently truncated.” As conversation history and retrieved content keep accumulating, early critical information can be pushed out of the window, which shows up as the model suddenly “forgetting” the original constraints. Practical mitigations include:

    • Summarize and compress history instead of concatenating all of it;
    • Limit the number of retrieved snippets and the length of each one;
    • Explicitly reserve space for the output so generation is not cut off midway;
    • Log token usage at the application layer and alert on abnormal growth.

    5. How Tokens Affect Cost, Latency, and Quality

    Tokens are the common unit for billing and performance, so understanding them lets you optimize three things at once.

    On cost, input and output are usually priced separately, and repeatedly resending a long context is the main source of waste. Caching and reusing stable system prompts and knowledge snippets can significantly cut repeated overhead.

    On latency, output is generated one token at a time, so output length has the most direct effect on the wait after the first token arrives. Asking the model to give the conclusion first and then expand on it feels better than making it build up to the point at length.

    On quality, the token budget is a scarce resource. Irrelevant content crowding the window dilutes attention and causes key information to be missed. Trimming prompts and deduplicating retrieved snippets often pays off more than switching to a larger model.

    6. Practical Checklist

    1. Before launch, measure the token distribution on real corpus data rather than estimating from sample text.
    2. Set a length limit on user input, and warn or split the input before the limit is exceeded.
    3. Monitor the input-to-output token ratio per request to spot abnormal calls.
    4. Structured output (such as a fixed field format) makes length easier to predict and reduces the risk of exceeding the budget.
    5. For long documents, split into segments and then aggregate, instead of stuffing everything in at once.
    6. Bring token usage into your observability stack, connect it with logging and alerting, and close the loop on capacity and cost.

    7. Conclusion

    A token is the only “official currency” text has before it enters the model. It determines what content can be seen, how much of it can be seen, and how much a call costs and how long it takes. Designing systems that treat tokens as first-class citizens — explicit budget allocation, continuous usage monitoring, proactive context compression — is the foundation of stable, controllable, and economical LLM applications. In related work at Baidu AI Cloud, this same approach is the starting point for capacity planning and cost governance.