The Minimum Unit of LLMs: Token Principles and Testing Practices
For test engineers, understanding tokens is crucial because they directly determine context capacity, invocation costs, and behavior boundaries in long-text scenarios. This article explores what tokens are, compares different tokenization strategies, and explains how the BPE algorithm forms vocabularies. Furthermore, it provides practical testing methodologies, including context boundary testing, cost estimation, and handling language-specific differences, followed by a summary of common misconceptions and a comprehensive test checklist.
1. Why Test Engineers Need to Understand Tokens
The input and output of Large Language Models (LLMs) are measured in tokens. The token count directly determines three things: how much context a single request can accommodate, the cost of a single invocation, and the model’s behavior boundaries in long-text scenarios. If you only estimate by character count during testing, systematic deviations will occur in both boundary testing and cost accounting.
2. What is a Token?
A token is the minimal semantic unit processed by an LLM. Its granularity lies between a character and a word; it is neither equivalent to a single character nor to a complete word.
Taking the sentence “我喜欢学习人工智能” (I like learning artificial intelligence) as an example, the results of three splitting methods are as follows:
| Splitting Method | Result | Unit Count |
|---|---|---|
| By Character | 我/喜/欢/学/习/人/工/智/能 | 9 |
| By Word | 我/喜欢/学习/人工智能 | 4 |
| By Token (Illustrative) | 我/喜欢/学习/人工/智能 | 5 |
“人工智能” (artificial intelligence) is split into “人工” and “智能” because these two sub-segments appear frequently in the corpus and can be combined to form other words like “人工呼吸” (artificial respiration) and “智能手机” (smartphone). The splitting result is determined by the tokenizer’s vocabulary. The same sentence may yield different token counts in different models.
3. Trade-offs of Three Splitting Strategies
The splitting strategy dictates the sequence length, vocabulary size, and the ability to handle new words, requiring a trade-off among the three.
- By Character: Simple to implement with almost no out-of-vocabulary (OOV) word issues. The downside is that the sequence becomes very long, the semantic capacity of a single character is weak, and the same content requires more computational steps.
- By Word: Semantically complete with shorter sequences. The downside is that the vocabulary will inflate to hundreds of thousands of entries, making it difficult to cover rare and new words.
- By Subword: Strikes a balance between sequence length and vocabulary size. When encountering an unseen new word, it can be broken down into known fragments. The downside is that the splitting rules must be learned from the corpus, and different models will yield different splitting results.
Currently, mainstream LLMs generally adopt subword splitting. This approach uses a limited vocabulary to cover almost all words while maintaining a relatively short sequence length.
4. BPE: How Vocabularies are Formed
BPE (Byte Pair Encoding) is a common subword algorithm. Its core idea is to repeatedly merge high-frequency adjacent fragments. The training process is divided into four steps:
- Split the corpus into minimal units, such as characters.
- Count the occurrence frequency of all adjacent unit pairs.
- Merge the most frequent adjacent pair into a new unit and add it to the vocabulary.
- Repeat steps 2 and 3 until the vocabulary reaches the target size.
Below is a demonstration of the first three merges using the words low, lower, and lowest. An end-of-word marker </w> is added to the end of each word, with frequencies of 5, 2, and 6 respectively.
from collections import Counterdef merge_word(symbols, pair):"""Merge the specified adjacent pair in a word's symbol sequence into a new symbol."""out, i = [], 0while i < len(symbols):if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:out.append(symbols[i] + symbols[i + 1])i += 2else:out.append(symbols[i])i += 1return outdef train_bpe(word_freqs, num_merges):"""word_freqs: {symbol tuple: frequency}, returns learned merge rules in order."""corpus = dict(word_freqs)merges = []for _ in range(num_merges):pairs = Counter()for symbols, freq in corpus.items():for pair in zip(symbols, symbols[1:]):pairs[pair] += freqif not pairs:breakbest = max(pairs, key=pairs.get)merges.append(best)corpus = {merge_word(s, best): f for s, f in corpus.items()}return mergescorpus = {("l", "o", "w", "</w>"): 5,("l", "o", "w", "e", "r", "</w>"): 2,("l", "o", "w", "e", "s", "t", "</w>"): 6,}for pair in train_bpe(corpus, 3):print(pair)# ('l', 'o')# ('lo', 'w')# ('low', 'e')
During the first merge, both l+o and o+w have a frequency of 13. The code selects l+o based on the statistical order. The second merge produces low, and the third merge produces lowe. As merging continues, lowe may further combine with r or st.
Once training is complete, the splitting of new text will be executed sequentially according to the learned merge order. Therefore, the vocabulary content and the merge order jointly determine how many tokens a piece of text will be split into.
5. Tokens and Test Design
5.1 Context Boundary Testing
The context length a model can handle is limited. Input, conversation history, system prompts, and the space reserved for output share the same window. When testing, you should first calculate the available input budget, then design test cases around this budget:
def check_context_limit(prompt_tokens, max_context, reserved_output):"""Verify if the input token count is within the available budget."""budget = max_context - reserved_outputassert prompt_tokens <= budget, (f"Input has {prompt_tokens} tokens, exceeding the available budget of {budget} tokens")
It is recommended to cover three types of boundaries: exactly equal to the budget, one token more than the budget, and far exceeding the budget. The error messages and truncation behavior when the limit is exceeded also need to be verified, rather than just checking whether the request fails.
5.2 Cost Testing
Invocation fees are typically related to the number of input and output tokens. The following estimation formula can be used as a testing benchmark:
Cost per request ≈ Input token count × Input unit price + Output token count × Output unit price
The specific unit price is subject to the rules published by the service provider. In the test code, the unit price should be made a configuration item to avoid hardcoding it in test cases.
def estimate_cost(input_tokens, output_tokens, price_in, price_out):"""Unit price is calculated per token and injected via configuration."""return input_tokens * price_in + output_tokens * price_out
Cost testing should also focus on amplification factors, such as retries, repeated accounting of historical messages in multi-turn conversations, and the metering results after an interruption in streaming output.
5.3 Differences in Languages and Content Types
The token count does not correspond linearly to the character count. Texts with the same character count—such as Chinese, English, code, URLs, number strings, and emojis—usually have different token densities. Test samples should be prepared in groups according to content type, counting tokens separately and verifying whether the budget calculation matches the actual usage.
6. Common Misconceptions
- Using character count instead of token count. Character count is only a rough estimate; boundary testing must use the tokenization results corresponding to the specific model.
- Assuming token counts from different models are directly comparable. Vocabularies differ, so the token count for the same piece of text will vary.
- Ignoring the consumption of non-user inputs. System prompts, conversation templates, and historical messages all occupy context space.
- Only testing the input limit, not the output limit. When output exceeds the reserved space, the truncation method and prompt messages also need to be verified.
7. Test Checklist
- Count tokens using the model’s corresponding tokenizer, rather than estimating by character count.
- Design context budget test cases covering three scenarios: equal to, exceeding by one, and far exceeding the budget.
- Count and verify the input, output, historical messages, and system prompts separately, and check their sum.
- Design samples grouped by Chinese, English, code, special characters, and number strings.
- Use configurable unit prices for cost calculations, and cover scenarios involving retries and streaming interruptions.
