Understanding Tokens in LLMs: How Text Tokenization Works and Why It Matters

    This article explains what tokens are in the context of language models, how subword tokenization splits text into token IDs, and why token count is a core constraint for context windows, billing, and latency. It also covers practical estimation rules, optimization strategies, and common misconceptions to help developers manage token usage effectively.

    1. What Exactly Is a Token

    In the context of language models, a token is the smallest unit of text that the model processes. It is not a character, and it is not necessarily a word. Instead, it is a “frequent fragment” identified by a tokenizer based on statistics from large-scale corpora. The model never reads raw strings; it only reads a sequence of tokens and the integer ID assigned to each one. As a result, any text must pass through tokenization before it enters the model.

    The original material gives a clear example: the English sentence Tokenization is the process of converting text into tokens. is split into

    1. ["Token", "ization", " is", " the", " process", " of",
    2. " converting", " text", " into", " tokens", "."]

    Three details are worth noting. First, Tokenization is split into Token and ization, which shows that split boundaries are determined by statistical frequency rather than linguistic morphology. Second, fragments like is and the include the leading space, so spaces themselves consume tokens. Third, the sentence-final punctuation is a standalone token. The whole sentence contains 11 tokens.

    2. How Tokenization Happens

    mainstream approaches belong to the subword tokenization family. The core idea is to strike a balance between character-level and word-level splitting: common words are kept intact, while rare words are broken into smaller fragments. This controls vocabulary size and avoids the out-of-vocabulary problem. There are two common implementation paths: one builds the vocabulary by repeatedly merging frequent adjacent fragments, and the other selects split paths based on statistical probability. Both produce a mapping table of “fragment to integer ID.”

    Several engineering conclusions follow from this:

    • Token length is not linearly related to text length; it depends on how “common” the text is. Standard expressions and common vocabulary achieve higher compression.
    • The same meaning in different languages consumes tokens very differently. In English, a common word is usually about 1 token, while a common Chinese character often takes 1 to 2 tokens.
    • Structured or high-entropy content such as code, JSON, regular expressions, and Base64 compresses poorly, so token consumption is noticeably higher than for natural language.
    • The vocabulary is fixed, so new words, spelling variants, and rare proper nouns get split into more fragments.

    The following illustrative code shows the basic “encode then decode” flow (refer to the official documentation of your platform for specific interfaces):

    1. ids = encode(text) # text -> sequence of token IDs
    2. n = len(ids) # number of tokens
    3. restored = decode(ids) # sequence of IDs -> text

    3. Why Token Count Is the Core Constraint

    Tokens are the metric developers care about most because they determine three things at once.

    First, the context window. There is an upper limit on the total number of tokens a model can accept in a single request, and input and output share this budget. Once the limit is exceeded, the usual options are truncation or an error, so long-document processing requires a chunking strategy.

    Second, billing. The industry generally measures input tokens and output tokens separately, and output is usually priced higher than input. This means “making the model write more” is more expensive than “making the model read more,” and redundant prompts translate directly into higher bills.

    Third, latency and throughput. More tokens mean more computation for prefill and decoding, which increases time to first token and overall duration. In batch scenarios, total token volume often reflects real load better than the number of requests.

    4. Estimation and Optimization in Practice

    When no tokenizer is available, you can estimate quickly with rules of thumb: for English, use “word count × 1.3”; for Chinese, use “character count × 1.5”; for code and structured data, use “character count ÷ 3” as a conservative estimate. In engineering, leave a 10% to 20% buffer to avoid boundary overflow.

    A more reliable approach is to incorporate token counting into the development workflow:

    1. Wrap tokenization and counting logic on the application side, and validate the budget before sending a request.
    2. Version-control prompts, separating the stable parts from dynamic variables.
    3. Use retrieval augmentation instead of injecting everything, placing only relevant fragments into the context.
    4. Summarize long text before reasoning, trading one extra call for significant savings across subsequent calls.
    5. Enable response caching and result reuse to reduce token consumption for high-frequency repeated requests to zero.
    6. Compress conversation history, keeping conclusions and discarding the process to control growth in multi-turn scenarios.
    7. Set an explicit output limit to prevent runaway generation from driving up costs.

    5. Common Misconceptions

    The first is equating tokens with character count, which causes budgets to diverge severely from reality. The second is ignoring that spaces, line breaks, and indentation are also billed, which is especially easy to lose control of when concatenating templates. The third is assuming “free input” exists; in fact, system prompts, tool definitions, and historical messages all count toward input. The fourth is assuming different models tokenize identically; in reality, the same text can differ by several times in token count under different vocabularies, so you must recalculate when migrating across models.

    6. Conclusion

    The key to understanding tokens is to view them as a metering contract between the model and engineering: upstream determines how text is split, and downstream determines cost, latency, and feasibility. To implement related capabilities on Baidu AI Cloud, you can use the platform’s general tokenization and counting tools, and combine them with general cloud products such as object storage, message queues, logging services, and monitoring alerts to build an observable, cost-controlled, and traceable invocation pipeline, achieving a stable balance between quality and overhead.