Understanding and Mitigating Tokenization Bias in Language Models
Abstract
State-of-the-art language models are autoregressive and operate on subword units known as tokens. Specifically, one must encode the conditioning string into a list of tokens before passing to the language models for next-token prediction. We show that popular encoding schemes, such as maximum prefix encoding (MPE) and byte-pair-encoding (BPE), induce a sampling bias that cannot be mitigated with more training or data. To counter this universal problem, for each encoding scheme above, we propose a novel algorithm to obtain unbiased estimates from any language model trained on tokenized data. Our methods do not require finetuning the model, and the complexity, defined as the number of model runs, scales linearly with the sequence length in the case of MPE. As a result, we show that one can simulate token-free behavior from a tokenized language model. We empirically verify the correctness of our method through a Markov-chain setup, where it accurately recovers the transition probabilities, as opposed to the conventional method of directly prompting tokens into the language model.
align*\useshortskip
1 Introduction
Tokenization is a preprocessing procedure used in many state-of-the-art (SOTA) language models (LMs) such as GPTs (Brown et al., 2020), Llama (Touvron et al., 2023) and Gemini (Gemini, 2023). It divides the input text into smaller subword units while retaining linguistic importance, helping to address vocabulary limitations such as unknown words. Tokenization also shortens (compresses) the input context length (Sennrich et al., 2015; Kudo & Richardson, 2018). Since effective compression allows transformer-based LMs to handle longer context strings, many works (Zouhar et al., 2023; Gallé, 2019; Goldman et al., 2024) have focused on enhancing vocabulary design and encoding algorithms for better performance in downstream tasks. However, the relationship between compression and model performance remains unclear. Some research suggests the impact of compression is not always positive (Schmidt et al., 2024; Dagan et al., 2024; Goyal et al., 2023). Consequently, understanding tokenization’s effect on model performance continues to be an open question.
Tokenization has been criticized for introducing many shortcomings in LMs. These include sensitivity to spelling and morphological structure (Xue et al., 2022), language-based biases (Petrov et al., 2024), subpar performance in specific tasks such as arithmetic (Singh & Strouse, 2024), or new domains (Liu et al., 2023a). One approach to address these issues is through fine-tuning the model with new vocabularies; however, this often complicates the training process and requires domain-specific expertise (Chen et al., 2023; Liu et al., 2023b). Furthermore, the performance gains do not provide a theoretical understanding of whether these limitations truly arise from the tokenization process or result from suboptimal model training. Another direction is to develop token-free LMs (Yu et al., 2024; Nawrot et al., 2022; Tay et al., 2021). While this approach has potential as it eliminates tokenization-related issues, it significantly increases the context length, resulting in performance that still lags behind the SOTA tokenized LMs 111We refer language models that process tokenized texts as tokenized language models (tokenized LMs).(Yu et al., 2024).
In this work we offer new theoretical insights on the behavior of tokenized LMs. We show that they are statistically equivalent to their token-free counterparts. Specifically, we examine the maximum prefix encoding (MPE) scheme employed in the WordPiece tokenization method (Devlin et al., 2018; Song et al., 2020) and find that this process not only results in biased estimates of next token probabilities, but also leads to overall skewed estimates of subsequent character probabilities. In general, this bias persists despite an increase in training data, even within the simple setting of a 1st-order Markov chain. Such bias occurs due to the implicit disparity between the domain of the conditioning context, namely, characters versus tokens. Nevertheless, we will show that it is possible to correct this bias without resorting to finetuning. Once adjusted, it becomes possible to simulate the token-free behavior learned implicitly by the tokenized LM and even (theoretically) mimic the behavior of another tokenized model employing a distinct vocabulary set, all without requiring finetuning. Our specific contributions are as follows:
-
•
We show the presence of a bias in the next-token distribution that arises as a result of the tokenization process.
-
•
We present two novel algorithms to correct this bias for MPE and Byte-Pair-Encoding (BPE) respectively. Due to space limit, the analysis and algorithm for BPE are presented in Appendix H.
-
•
We verify the correctness of our algorithms on learning the transition matrix of a -th order Markov chain.
2 Problem Setup
We begin by establishing the tokenization and language models setup in our paper. We then describe the next-character sampling bias problem due to tokenization.
2.1 Notations and Setup.
String Notations. For any string , we denote its substring from to as , where each is a character of the alphabet . For a given string , we define the prefix function that generates a set containing all possible prefix strings of , represented as . Also, we define a concatenation function that concatenates the given list of strings, e.g given and , we obtain . Finally, we denote the set of all strings that start with a prefix as .
Tokenization Setting. We assume having a predefined vocabulary constructed using any tokenization algorithm such as BPE, with the condition that . We use to denote a token in , i.e. . Importantly, we use the longest prefix matching strategy for tokenization (encoding), denoted as , similar to the approach used in the Wordpiece algorithm (Devlin et al., 2018; Song et al., 2020). Given a sequence of tokens , the function returns the concatenated string resulting from processing each token in the sequence. Finally, the set of all strings that starts with the tokens is defined as .
Tokenized LMs. We assume having access to a tokenized autoregressive LM with parameters that is trained with tokens from and maximum prefix matching. The target distributions on the character domain is denoted as and on the token domain is . For simplicity, unless otherwise stated, we implicitly assume each probability term involves . Using the model, we assume that one can compute for any integer . In this work, we consider LMs trained under the standard setup, where each string in the dataset is first tokenized with the encoding function and vocabulary , and the parameters are optimized to maximize the predictive likelihood of the next token in the tokenized dataset.
2.2 Next-Character Sampling Bias
We first define the (next-character) sampling bias problem that describes the discrepancy between the character level and token level predictions for tokenized LMs.
Definition 2.1.
(Next-Character Sampling Bias) Let the input prompt string has as the corresponding encoding. The next-character sampling bias occurs for this prompt when where where .
In other words, the probability of the next character being “c” may be different from the sum of the probabilities of all tokens that start with “c”. Note that this character-level probability offers a broader perspective compared to the probability of the subsequent token being exactly “c”.
Example. Consider a first order Markov chain with two states as shown in Figure 1 (left). Each string is tokenized with , which leads to a new Markov chain whose states and transition matrix is shown in Figure 1 (right). Details on computing the transition matrix of the new Markov chain is in Appendix F. We first observe that for the prompt and , there is no bias problem after marginalization222For example, we have . However, for the prompt , the sampling bias occurs as , which is not equal to , i.e. the optimally trained LM will always output . In fact, for any context string that ends with token , e.g and (tokens are separated by ), such LM will always output .
Since this applies to any optimally trained LM, increasing the training set size does not mitigate this problem. The reason for this sampling bias is that, during the tokenization process with longest prefix matching, the token must be followed by the token . Else, MPE encoding will merge to create a longer token . We generalize this phenomenon with the definition of invalid encodings.
Definition 2.2.
(Invalid Encodings) The list of tokens (an encoding) is invalid if . Otherwise, it is a valid encoding.
For example, let then and are invalid encodings of . We now show in Proposition 2.3 that the existence of invalid encodings introduces sampling bias, generalizing the observed phenomenon in the Markov chain example to any autoregressive distribution.
Proposition 2.3.
(Token-Induced Zero Probability) Let be a sequence of input tokens. For any invalid encoding , we have and the conditional probability is undefined. In the case is valid, then if is invalid. Furthermore, let , then for any string such that , we have
Proof.
See Appendix C. ∎
Remark 1.
Proposition 2.3 implies that LMs may not function as expected when presented with invalid encodings, because these models will never be exposed to such inputs within the dataset. This directly implies that the practice of evaluating LMs under different encodings (Cao & Rimell, 2021; Chirkova et al., 2023) is suboptimal.
3 Alleviating Sampling Bias
We propose a method to remove the described bias and recover the original token-free autoregressive model, i.e. expressing the implicitly learned using the tokenized LM that outputs the conditional probability . For , this captures the behavior of a token-free model, i.e. sampling the next character instead of a whole token. We assume our LM follows Proposition 2.3 on zero probability events and undefined conditional probability for invalid encodings. Appendix G justifies this assumption and provides its practical implementation.
Our method consists of two stages. In the first stage, the idea is to identify the condition when where . Once identified, we can refactor the conditional probability to match the conditioning events. In the second stage, we compute using the LM output probability, i.e. , through the novel Maximum Prefix Correction (MPC) Algorithm.
3.1 Refactoring
Our method removes the bias by connecting character and token domains through a special subset of tokens , whose elements are not a substring of any other tokens in but itself. For example, given , then . In the Markov example in Section 2, this corresponds to the tokens and . Also, we assume that any string has the first token 333Many current language models begins with a start token in , e.g. in SentencePiece (Kudo & Richardson, 2018).. Consider the input string and its corresponding encoding , Proposition 3.1 shows the sufficient condition for .
Proposition 3.1.
Let , where . Then we have , i.e. for any string where , we have . In the case , then we also have that , i.e. any string where must have the first tokens as and .
Proof.
See Appendix D. ∎
The intuition for Proposition 3.1 is that the subsequent string after cannot change the tokenization for . We now establish one of the main results in Corollary 3.2.
Corollary 3.2.
Following Proposition 3.1, suppose then we have . Similarly, we also have .
Proof.
See Appendix D. ∎
We note that Proposition 3.1 and Corollary 3.2 always hold, regardless of the value of . In general, consider when the last token of is not in , we can refactor as follow:
(1) |
where is the last token in such that and , where . Proof details of this step can be found in the Appendix E. We then use the MPC algorithm to compute each term in the RHS individually.
3.2 Maximum Prefix Correction Algorithm
We present the MPC algorithm in Algorithm 1, that allows us to compute the probabilities and in Equation (1). Note that this algorithm does not require . Details on the algorithmic correctness are shown in Appendix E.
The idea is to marginalize out by considering two complementary events: when the next token has a prefix ( in the Branch Step) versus when the next token is contained within ( in the Pass Step). Formally, MPC computes the following probabilities:
(2) | ||||
(3) |
where and we immediately see that .
We provide an intuitive explanation for the algorithm following the example in Figure 2. Here, we would like to compute the probability . The first possibility is that is a prefix of the next token, so we search for all such tokens (line 3 in the algorithm) and sum up their probability (line 4), i.e. . Figure 2 visualizes this step as branching out the tree by finding all tokens completing the string. Since is not the only string that contains , e.g. , etc. we need to compute the probability for these other scenarios, each of which has (the first token in , line 10 and 12) due to maximum prefix encoding. Then, we want to compute the probability that the subsequent string is (line 13), given the previous and , which is the output of the MPC algorithm but for and . Formally, in the Passing step: . We continue the procedure until meeting the base case, where the string must be a prefix of the next token (usually, when there is only a single character left). Finally, by computing the sum of the branch and pass steps, we obtain the desired conditional probability .
4 Experiments
We validate our method on a 3rd order Markov chain experiment with , where we randomly construct the transition matrix and the vocabulary . We train a LM model using GPT-2 architecture with 6 hidden layers. Since the model is agnostic to the Markov chain order, we average the probability from 100 runs on different context length while fixing the last 3 characters. We compare our method with the baseline estimator , equivalent to one Branch step in the MPC algorithm. Figure 3 shows the results where the baseline method exhibits significant sampling bias due to tokenization. Following Proposition 2.3, one can clarify the zero probability events output from the baseline estimator. Our method, in contrast, accurately estimates the ground truth probability used to generate the data, showing that it is possible to recover the implicitly learned character information from the tokenized LMs.
5 Conclusion
This work identifies the next-character sampling gap between a tokenized model and a token-free one, which persists even for optimally trained models. We present a probabilistic approach to effectively eliminate this bias without requiring additional training. This closes the sampling gap between tokenized and token-free models, suggesting that language models implicitly absorb character-level information despite being trained solely on tokenized text. This result implies that it is theoretically possible to simulate the behavior of another language model trained using different vocabulary without any fine-tuning, since it is possible to transfer from token-free models to tokenized counterparts.
References
- Brown et al. (2020) Brown, T., Mann, B., Ryder, N., Subbiah, M., Kaplan, J. D., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., et al. Language models are few-shot learners. Advances in neural information processing systems, 33:1877–1901, 2020.
- Cao & Rimell (2021) Cao, K. and Rimell, L. You should evaluate your language model on marginal likelihood over tokenisations. In Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing, pp. 2104–2114, 2021.
- Chen et al. (2023) Chen, Y., Marchisio, K., Raileanu, R., Adelani, D., Saito Stenetorp, P. L. E., Riedel, S., and Artetxe, M. Improving language plasticity via pretraining with active forgetting. Advances in Neural Information Processing Systems, 36:31543–31557, 2023.
- Chirkova et al. (2023) Chirkova, N., Kruszewski, G., Rozen, J., and Dymetman, M. Should you marginalize over possible tokenizations? In The 61st Annual Meeting Of The Association For Computational Linguistics, 2023.
- Cleary & Witten (1984) Cleary, J. and Witten, I. Data compression using adaptive coding and partial string matching. IEEE transactions on Communications, 32(4):396–402, 1984.
- Cognetta et al. (2024) Cognetta, M., Zouhar, V., Moon, S., and Okazaki, N. Two counterexamples totextit Tokenization and the Noiseless Channel. arXiv preprint arXiv:2402.14614, 2024.
- Dagan et al. (2024) Dagan, G., Synnaeve, G., and Rozière, B. Getting the most out of your tokenizer for pre-training and domain adaptation. arXiv preprint arXiv:2402.01035, 2024.
- Devlin et al. (2018) Devlin, J., Chang, M.-W., Lee, K., and Toutanova, K. Bert: Pre-training of deep bidirectional transformers for language understanding. arXiv preprint arXiv:1810.04805, 2018.
- Gallé (2019) Gallé, M. Investigating the effectiveness of bpe: The power of shorter sequences. In Proceedings of the 2019 conference on empirical methods in natural language processing and the 9th international joint conference on natural language processing (EMNLP-IJCNLP), pp. 1375–1381, 2019.
- Gemini (2023) Gemini, T. Gemini: a family of highly capable multimodal models. arXiv preprint arXiv:2312.11805, 2023.
- Goldman et al. (2024) Goldman, O., Caciularu, A., Eyal, M., Cao, K., Szpektor, I., and Tsarfaty, R. Unpacking tokenization: Evaluating text compression and its correlation with model performance. arXiv preprint arXiv:2403.06265, 2024.
- Goyal et al. (2023) Goyal, S., Ji, Z., Rawat, A. S., Menon, A. K., Kumar, S., and Nagarajan, V. Think before you speak: Training language models with pause tokens. In The Twelfth International Conference on Learning Representations, 2023.
- guidance ai (2023) guidance ai. Guidance ai, 2023. URL https://github.com/guidance-ai/guidance. GitHub repository.
- Gutierrez-Vasques et al. (2023) Gutierrez-Vasques, X., Bentz, C., and Samardžić, T. Languages through the looking glass of bpe compression. Computational Linguistics, 49(4):943–1001, 2023.
- Kudo & Richardson (2018) Kudo, T. and Richardson, J. Sentencepiece: A simple and language independent subword tokenizer and detokenizer for neural text processing. arXiv preprint arXiv:1808.06226, 2018.
- Liu et al. (2023a) Liu, S., Deng, N., Sabour, S., Jia, Y., Huang, M., and Mihalcea, R. Task-adaptive tokenization: Enhancing long-form text generation efficacy in mental health and beyond. In The 2023 Conference on Empirical Methods in Natural Language Processing, 2023a.
- Liu et al. (2023b) Liu, Y., Lin, P., Wang, M., and Schütze, H. Ofa: A framework of initializing unseen subword embeddings for efficient large-scale multilingual continued pretraining. arXiv preprint arXiv:2311.08849, 2023b.
- Makkuva et al. (2024) Makkuva, A. V., Bondaschi, M., Girish, A., Nagle, A., Jaggi, M., Kim, H., and Gastpar, M. Attention with markov: A framework for principled analysis of transformers via markov chains. arXiv preprint arXiv:2402.04161, 2024.
- Minixhofer et al. (2024) Minixhofer, B., Ponti, E. M., and Vulić, I. Zero-shot tokenizer transfer. arXiv preprint arXiv:2405.07883, 2024.
- Nawrot et al. (2022) Nawrot, P., Chorowski, J., Łańcucki, A., and Ponti, E. M. Efficient transformers with dynamic token pooling. arXiv preprint arXiv:2211.09761, 2022.
- Petrov et al. (2024) Petrov, A., La Malfa, E., Torr, P., and Bibi, A. Language model tokenizers introduce unfairness between languages. Advances in Neural Information Processing Systems, 36, 2024.
- Provilkov et al. (2019) Provilkov, I., Emelianenko, D., and Voita, E. Bpe-dropout: Simple and effective subword regularization. arXiv preprint arXiv:1910.13267, 2019.
- Rajaraman et al. (2024) Rajaraman, N., Jiao, J., and Ramchandran, K. Toward a theory of tokenization in llms. arXiv preprint arXiv:2404.08335, 2024.
- Schmidt et al. (2024) Schmidt, C. W., Reddy, V., Zhang, H., Alameddine, A., Uzan, O., Pinter, Y., and Tanner, C. Tokenization is more than compression. arXiv preprint arXiv:2402.18376, 2024.
- Sennrich et al. (2015) Sennrich, R., Haddow, B., and Birch, A. Neural machine translation of rare words with subword units. arXiv preprint arXiv:1508.07909, 2015.
- Singh & Strouse (2024) Singh, A. K. and Strouse, D. Tokenization counts: the impact of tokenization on arithmetic in frontier llms. arXiv preprint arXiv:2402.14903, 2024.
- Song et al. (2020) Song, X., Salcianu, A., Song, Y., Dopson, D., and Zhou, D. Fast wordpiece tokenization. arXiv preprint arXiv:2012.15524, 2020.
- Tay et al. (2021) Tay, Y., Tran, V. Q., Ruder, S., Gupta, J., Chung, H. W., Bahri, D., Qin, Z., Baumgartner, S., Yu, C., and Metzler, D. Charformer: Fast character transformers via gradient-based subword tokenization. In International Conference on Learning Representations, 2021.
- Touvron et al. (2023) Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M.-A., Lacroix, T., Rozière, B., Goyal, N., Hambro, E., Azhar, F., et al. Llama: Open and efficient foundation language models. arXiv preprint arXiv:2302.13971, 2023.
- Willems et al. (1995) Willems, F. M., Shtarkov, Y. M., and Tjalkens, T. J. The context-tree weighting method: Basic properties. IEEE transactions on information theory, 41(3):653–664, 1995.
- Xue et al. (2022) Xue, L., Barua, A., Constant, N., Al-Rfou, R., Narang, S., Kale, M., Roberts, A., and Raffel, C. Byt5: Towards a token-free future with pre-trained byte-to-byte models. Transactions of the Association for Computational Linguistics, 10:291–306, 2022.
- Yu et al. (2024) Yu, L., Simig, D., Flaherty, C., Aghajanyan, A., Zettlemoyer, L., and Lewis, M. Megabyte: Predicting million-byte sequences with multiscale transformers. Advances in Neural Information Processing Systems, 36, 2024.
- Zouhar et al. (2023) Zouhar, V., Meister, C., Gastaldi, J., Du, L., Sachan, M., and Cotterell, R. Tokenization and the noiseless channel. In Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 5184–5207, 2023.
Appendix A Related Work
Theory of Tokenization. Existing works on tokenization generally support the idea that compressing tokens enhances model performance (Gallé, 2019; Gutierrez-Vasques et al., 2023; Zouhar et al., 2023). However, these emperically findings are in conflicted with other later studies Cognetta et al. (2024); Schmidt et al. (2024). On the theoretical side, Rajaraman et al. (2024) examined tokenization through the lens of unigram models, motivated by the observation made by Makkuva et al. (2024) that transformers struggles to learn 2nd-order Markov chains. We, however, do not observe this phenomenon in our experiment. As such, our work on bias due to tokenization is not affected by their observation.
Tokenization and Perplexity. Our work relates to the statistical evaluation of LMs, where we provide an algorithm to directly evaluate the character-level perplexity , using a tokenized LM. In terms of token-level perplexity evaluation, some recent studies (Cao & Rimell, 2021; Chirkova et al., 2023) have suggested using stochastic tokenization (Provilkov et al., 2019) at test time to evaluate perplexity scores of LMs (). However, these evaluations were done on LMs trained with deterministic tokenization which could be suboptimal as demonstrated by our examination of undefined states in Section 2. As such, by utilizing our approach, one can obtain a much more accurate insights on LMs evaluation.
Related Algorithms. Our algorithm is inspired from the literature of universal compression such as prediction by partial matching (Cleary & Witten, 1984) and context-tree weighting (Willems et al., 1995), which have been applied for text prediction but for much simpler settings without any tokenization involved. Recently, Minixhofer et al. (2024); Liu et al. (2023a) propose tokenization adaptation methods, which still requires a heuristic optimization that complicates the training pipeline. Some recent studies have proposed method to target the problem of language models encountering difficulties generating text near prompt boundaries (Dagan et al., 2024; guidance ai, 2023), which bears some resemblance to our proposed algorithm. These methods, however, are heuristic and only applicable to certain scenarios. On the other hand, our bias removal algorithm is theoretically correct, versatile for various situations, and enables conversion between token-free and tokenized LMs due to its accurate representation of conditional sampling distributions.
Appendix B Supporting Theorems on Maximum Prefix Encoding
This section provides supporting theorems for the proof of the main results. We first remind the readers that the set corresponds to the set of all strings that contain as a prefix. Similarly, the event set corresponds to the set of all strings whose first tokens are . Consider when , it should be noted that the two sets and are not guaranteed to be equivalent. That is because the subsequent characters after can affect the tokenization within the first character. We illustrate this in more detail in the following example.
Example. Consider the Markov chain example in Section 2, where . Then, the string , then and since the first character of is and the first token of is . On the other hand, since its first token is , not .
We introduce the Proposition B.1 that contains two facts regarding the MPE process, visually presented in Figure 4.
Proposition B.1.
Let be a string with the prefix (). Define the minimal superstring to be the prefix of with the fewest tokens that contains as a prefix: . Then, we have the followings:
-
1.
For , . Furthermore, when , we also have .
-
2.
Let be the number of tokens in , then we have .
Proof.
(Result 1.) Proof by contradiction. Let be the counter-example with the fewest number of tokens. Assume that for , . Let be the smallest of such .
Consider and .
-
•
Case 1: .
-
–
Case 1.a: . This leads to a contradiction, since is a prefix of , therefore a longest prefix matching algorithm would always generate the longer token () over the shorter one () when it is available.
-
–
Case 1.b: . This leads to a contradiction, since is a prefix of (Case 1 assumption), therefore a longest prefix matching algorithm would always generate the longer token () over the shorter one () when it is available.
-
–
Case 1.c: . This means that the two tokens are the same, contradicting our initial assumption.
-
–
-
•
Case 2: . In this case, is a superstring of implying that is at most , which contradicts our initial assumption that .
Finally, in the case , this means is a suffix of . Since all the tokens before within has been matched, i.e. for , the last token must also match as the result (else, , leads to contradiction), we have .
(Result 2.) The proof idea is that since contains and any tokens within and has been matched up to , then what is left in must be in the last token in (which is the th token of ). Formally, following Result 1, we have . Since has tokens in total and , this means that must cover the rest of , i.e. . As the result, we must have . ∎
We remind the reader the definition of invalid encoding below.
Definition B.2.
(Invalid Encodings) The list of tokens (an encoding) is invalid if . Otherwise, it is a valid encoding.
Corollary B.3.
if and only if is invalid.
Proof.
We prove each direction as follow.
-
•
If then is invalid: Since , we know that there exist no string such that . As such, for , we do not have , which proves the result.
-
•
If is invalid then : Let and . Let and suppose there exist a string . Re-running the MPE procedure on and in parallel, then every time a token is selected within in , it must also be selected at the same position in as well. Thus, we cannot have , which proves the result.
∎
Appendix C Proof of Proposition 2.3 in the Main Paper
Proposition 2.3 (Token-Induced Zero Probability) Let be a sequence of input tokens. For any invalid encoding , we have and the conditional probability is undefined. In the case is valid, then if is invalid. Furthermore, let , then for any string such that , we have
Proof.
For the first two statements, we have:
-
•
For an invalid where , we have , as implied by Corollary B.3. As such, we have which leads to be an undefined conditional probability .
-
•
For a valid but invalid , we know that , which results in .
For the last statement, we first note the following:
-
1.
Note that where .
-
2.
Consider , we will prove that if .
The proof idea for this is shown in Figure 4 (Example 2, Right). Formally:
-
•
Let be the first position such that then we know that (Proposition B.1 (Result 2)).
-
•
Following Proposition B.1 (Result 2), let , then we know that must be a substring of within another longer token (it cannot be broken down) in . Hence, no string will have a -th token as , so . This completes the proof.
Finally, we note that does not implies , since it can be due to the original distribution on the character domain. A classic example for this is a Markov model with an absorption state. ∎
Appendix D Proof of Proposition 3.1 and Corollary 3.2 in the Main Paper
Proposition 3.1 Let , where . Then we have , i.e. for any string where , we have . In the case , then we also have that , i.e. any string where must have the first tokens as and .
Proof.
We prove each case as follow.
1) General Case: There exists a string where , following directly from our 1st order Markov chain example in the main paper, i.e. the string has as prefix but have the . Also, any string that has the first tokens as must have the first characters as , hence and .
2) : The proof idea is that, since cannot be a part of any token in , it is impossible to merge it by appending additional characters after . Formally, similar to Proposition B.1:
-
•
For any string , let be the number of tokens in the minimal superstring of that contains as a prefix.
-
•
Following Proposition B.1 (Result 2), we know that must be a substring of .
-
•
Due to , then . We also know from Proposition B.1 (Result 1) that for , this means that . This gives us and .
This completes the proof. ∎
Remarks. We briefly note that the condition is the sufficient condition. In general, any token sequence that satisfies will have . One potential strategy is to find the first index such that cannot be merged into another token in .
Proof.
For the first case, we prove through the following equations:
(4) | ||||
(5) | ||||
(6) | ||||
(7) |
where the first equality is due to and the last equality is due to for .
Similarly, for the second case, we have:
(8) | ||||
(9) | ||||
(10) |
which completes the proof. ∎
Appendix E Proof for The Bias Removal Method
E.1 Refactoring
Our goal is to express the quantity using the tokenized LM that outputs the conditional probability . Let where and . Following Proposition 3.1, any string with prefix must have the first tokens as . We now perform the following factorization:
(11) | ||||
(12) | ||||
(13) | ||||
(14) |
where the last inequality is due to Corollary 3.2. Finally, we will use the Maximum Prefix Correction (MPE) Algorithm to compute each term in (14) individually. Note that the algorithm does not require . Here, we explicitly highlight the importance of having , as it bridges between the character and token domain through Equation (14).
E.2 Maximum Prefix Correction Algorithm
Overview. The MPC algorithm computes . Note that we do not require in the MPC algorithm. Using marginalization, we have the following:
(15) | ||||
(16) |
where:
-
•
is the set of tokens that have a prefix .
-
•
is the ones that do not.
and .
Branch Step. Here, is the probability that, given the list of previous tokens , the next token of the string has as a prefix. To compute this term, we obtain for all using one model run, then sum the probabilities corresponds to all tokens whose prefix is .
(17) |
Proof.
To see this, for each summand of in Eq.(16), we have:
(18) | ||||
(19) |
where is due to . This concludes the proof. ∎
Pass Step. Here, is the probability that, given the list of previous tokens , the subsequent string is not a prefix of the next token. Under the MPE, we compute the value as follow:
(20) |
where and . That is, during the passing step, there are two subroutines:
-
1.
Extract the next token within and compute . If , then returns since this is not allowed according to the condition required in .
-
2.
Recursively compute .
Proof.
Following Proposition 2.3 for invalid encodings, we only need to consider such that is valid. Under Proposition B.1 for MPE on , only first token of is allowed (also see Example 2 in Figure 4(Right)). Finally, applying the chain rule of probability, we obtain Equation 20. For the case of non-optimal LM, see Section G.2 for non-optimal LM. This completes the proof. ∎
Base Case. We note that the base case of our algorithm corresponds to the situation where . In this scenario, we only needs to compute (branching step) while .
Complexity Analysis. The complexity of our algorithm (number of inferences on the language model) scales with the length of the the query string, i.e. . Note that the complexity of the summation at the Branching step is relatively cheap compared to the runtime of the language model.
Appendix F Converting Token-Free Language Model to Tokenized Language Model for MPE.
We introduce an algorithm to compute using a token-free language model , despite having no access to any tokenized LM. This approach enables theoretical conversion of a token-free model to a tokenized one. The method involves two stages. First, we refactor the conditional probability similar to the technique presented in Section E. Next, we aggregate the probabilities of all possible strings leading to the desired tokenization. It is important to note that a Markov chain is a special type of autoregressive model, meaning this method can be employed to effortlessly calculate Markov chain transition matrices within the tokenized domain.
F.1 Refactoring
Consider the probability that we would like to expressed using . Let be the last token within such that . We now perform the following factorization:
(21) | ||||
(22) |
where . The second equality is due to Corollary 3.2. Each term can then be computed using the aggregation procedure shown next.
F.2 Aggregation.
In this step, we would like to compute where and , using the token-free representation . Here, we denote and be the length of the longest token in and is the enumeration of all string of length .
Computing involves considering all possible strings with prefix and . Although iterating through every possible string is infeasible, we can restrict our search by only examining strings with length , as any additional string beyond this point will not impact the tokenization of prefix due to being the maximum token length. Formally, we will show that one can express as follows:
(23) |
where and . The first term can be computed using the given token-free LM, i.e. . The second term is an indicator function that checks whether and can be computed deterministically.
Proof.
We have:
(24) | ||||
(25) | ||||
(26) | ||||
(27) |
The rest is to prove the following equality:
(28) |
We first note that the first tokens must be due to our condition that . Since is the length of the longest token in , appending extra characters cannot change the tokenization happened for . In other words, any string with prefix must have the same minimal superstring containing (see Proposition B.1). We then apply this principle to the two cases:
-
•
: In this case, we know that the string must contains the first tokens as , hence
-
•
: In contrast, this case is equivalent to since we are sure that the string do not contains the tokens .
This concludes the proof. ∎
F.3 The Markov Chain Example.
We provide a detail computation of the Markov chain example in the main paper. Recall that in the original chain (in the character domain), we have the following:
(29) | ||||
(30) | ||||
(31) | ||||
(32) |
We also assume the initial probability for and respectively. In the token domain, let first compute , where we do not have to do the refactoring step since we know that . Following the Aggregation step, we have:
(33) | ||||
(34) | ||||
(35) |
where in the first equality, we do not include the case and since and , which are not the token that we are interested in. For other tokens and when , the computation follows the same arguments.
We now consider the case , we can refactor it as:
(36) |
We first compute using the aggregation step:
(37) | ||||
(38) | ||||
(39) |
where we do again include the case and for the same reason above. For we have:
(40) | ||||
(41) | ||||
(42) |
which gives us . Finally, in this specific case, since order of the Markov chain in the character domain is , we do not need to consider the higher order of the Markov chain in the token domain.
Appendix G On Predictive Distribution of Language Models
In practice, LMs often do not follow Proposition 2.3 due to softmax activations. As such, in our MPC algorithm, when and , then may not be (where is the model weights). Eventually, this can potentially increase the complexity of our MPC algorithm during the Passing step.
In this section, we show that given any tokenized LM, we can force its output probabilities to obey Proposition 2.3, without any loss in terms of perplexity score on the token domain. This means that a tokenized LM satisfying Proposition 2.3 will guarantee the correctness of the Passing step in our MPC algorithm.
Finally, before going to the method, we remind the readers that Proposition 3.1 and Corollary 3.2 are factually correct and hold for all . As such, the refactoring step holds regardless.
G.1 Truncate-Renormalization Process
We justify the assumption that our tokenized language model follows Proposition 2.3. The idea is that we can turn a language model that does not follow Proposition 2.3 to the one that does while guaranteeing that the new model will always result in a lower token-level perplexity score.
We first introduce Proposition G.1. In this proposition, we are given a target discrete probability distribution where we know some of the values will not happen, says . Assume that we have another distribution that approximates , then we can produce another distribution that is closer to in terms of KL divergence by setting corresponding probabilities of in to and renormalize it (similar to rejection sampling).
Proposition G.1.
Given a discrete distribution and with for all . Let and , we define where for , and . Then we have:
(43) |
which implies that is closer to than . We refer to the process of producing as truncate-renormalization (TR).
Proof.
Let is the normalizing factor in . Note that and as such . Then:
(44) | ||||
(45) | ||||
(46) | ||||
(47) | ||||
(48) |
which completes the proof. ∎
Applying to our scenario, for any autoregressive language models that does not follow Proposition 2.3 (due to the softmax activations), we can perform the TR process (since we know which encoding is invalid) to obtain a new LM , which is guaranteed to better approximate the ground-truth model . Thus, we are guaranteed that the token-level perplexity score of is always lower than or equal to .
G.2 On Passing Step in Maximum Prefix Correction Algorithm.
Appendix H Algorithms for Byte Pair Encoding
H.1 Overview
We begin by introducing the Byte-Pair Correction (BPC) Algorithm for bias correction in Byte-Pair Encoding, which is more general than the MPC algorithm and also works for case of MPE. We then follow with a detail analysis to show the correctness of the algorithm.
Here, we introduce the definitions of invalid encodings (for BPE) and cover encodings.
Definition H.1.
(Invalid Encodings) The list of tokens (an encoding) is invalid if . Otherwise, it is a valid encoding. We denote a valid as .
Definition H.2.
(Cover Encodings) Given a string , an encoding is said to be covering when all the following conditions satisfied:
-
1.
is valid.
-
2.
.
-
3.
for some , i.e. the last token covers a part of the string .
We denote to be the set of all cover encodings of and is an encoding in .
Having established these two definitions, we will later show that for BPE (and MPE), the probability can be represented using a tokenized LM as follows:
(49) |
and the main goal of the BPC algorithm is to search through all cover encodings of . We can then apply this algorithm and compute any conditional probability through factorization. Figure 5 (Left) illustrates this with examples cover encodings and invalid/valid encodings.
H.2 Byte-Pair Correction Algorithm
For MPE, the MPC algorithm computes by searching all possible valid encodings that cover , where the probability of each encoding are computed using the LMs through greedy search. However, this does not work for the case of BPE. For example, under the BPE encoding rule of Llama 2, the string is tokenized as an individual token while the string is tokenized into 2 tokens and . Note that naive search for all tokens within from left to right that cover is computationally expensive.
The Byte-Pair Correction (BPC) algorithm, shown in Algorithm 2 and visualized in Figure 5 (right), which is an efficient algorithm that can search all valid encodings covering . The idea is that, for each cover encoding , once the starting position of the last token is determined (say ), we are guaranteed the prior tokens is unique and must be . Then one will accept the extracted if it is valid, otherwise reject it. Corollary H.3 provides justification for this procedure. Here, we assume for invalid , see Proposition H.4 and justifications as well as implementation in Appendix G.
Remark. The BPC algorithm can also be applied for the case of MPE. In fact, it is more general than the original MPC algorithm as it only relies on the property of invalid encodings.
H.3 Analysis
Notations. We extend the notation of the vocabulary for the case of BPE. Here, is an ordered list that determines the merging order in the BPE algorithm. Each is a triplet of which corresponds to the merging tokens (left and right) and the new token. For simplicity, when we write , it corresponds to the merged token, i.e. . Finally, the first entries in correspond to the alphabet , where no merging will happen.
Byte-Pair Encoding. We revise the encoding rule for BPE, shown in Algorithm 3. In practice, pre-tokenization is often used, where tokens are separated by whitespace or special characters. In this case, we can adjust our vocabulary by removing tokens with special characters in the middle of the string.
Overview. We begin our analysis with theoretical results on invalid encodings (Corollary H.3 and Proposition H.4), which characterizes the zero probability events for an optimal tokenized LM. This will allow us to prove the representation of , i.e. Proposition H.5, previously shown in Equation (49). Finally, we conclude this section with the proof of correctness of the BPC algorithm, using Proposition H.5 and H.6.
We begin with theoretical results on invalid encodings in the case of BPE.
Corollary H.3.
if and only if is invalid.
Proof.
We prove each direction as follows.
-
•
If then is invalid: Since , we know that there exist no string such that . As such, for , we do not have , which proves the result.
-
•
If is invalid then : Let , we consider two string and that both have prefix . Furthermore, we assume the first tokens of covers exactly , i.e. and similarly, the first tokens of covers exactly , i.e. . Then:
-
1.
Proving invalid leads to is equivalently to proving for any .
-
2.
Re-running the BPE algorithm for and in parallel, we know that there will be no merge between any suffix of and the rest of strings, i.e. and due to the condition above (See Algorithm 3, line 6).
-
3.
Furthermore, for , any time a merge happens within then the same merge must also happen within for and vice versa.
As the result, we have and they must be equal to .
-
1.
∎
Proposition H.4.
(Token-Induced Zero Probability-BPE) Let be a sequence of input tokens. For any invalid encoding , we have and the conditional probability is undefined. In the case is valid, then if is invalid.
Proof.
The proof is the same as the MPE version (Proposition 2.3). ∎
Correctness of BPC Algorithm. We show in Proposition H.5 that computing the string probability is equivalent to marginalizing the probability of all covering tokens of . As such, the main task of computing is to iterate all the valid encodings that cover .
Proposition H.5.
(Prefix Probability Representation) Given a prefix , we have the followings:
-
1.
For any distinct , then .
-
2.
.
As a result, can be expressed as the marginal probability of all covering tokens of
(50) |
Proof.
We prove each point as follows:
-
1.
Proof by contradiction, suppose that , then there exists a string that has two different cover encodings and . This is impossible since each string has only one unique encoding.
-
2.
This follows the definition of cover encodings.
Since each is pair-wise disjoint, we arrive at the final equation. We illustrate this Proposition in Figure 7. ∎
Finally, we prove that BPC extracts all the cover encodings of . Proposition H.6 shows the correctness of line 9 in the algorithm, where suppose that the last token starts from , then must be the encoding before that last token. Since each cover encoding must have a last token cover a suffix within , iterating over all positions from to guarantees that we extract all possible encodings.
Proposition H.6.
Let and is the number of tokens in . Suppose that is a prefix of the for some , i.e. , then .
Proof.
Since , then must be a valid encoding. As a result, we must have . ∎
Refactoring. Unlike the case for MPE, identifying the case when is nontrivial in general for BPE. Nevertheless, the refactoring step aims to reduce the computational complexity, and in general, we can still compute by refactoring.
(51) |
and we use the BPC algorithm to compute and respectively. Note that this is equivalent to assuming is a token within (and consider instead of ). When pretokenization is used, e.g. split by white spaces, we can identify when by using the pretokenization pattern.
H.4 Experiments
The experiment setup for BPE is the same as the one in Section 4, except we use the vocabulary , where the order within is the merging order for the BPE encoding process and the “” separates the merging tokens. The result is shown in Figure 7, where our method can accurately recover the ground truth probability while the baseline fails to. Notice that for the state , the baseline approach can output the correct probability, which is because the merging for the token happens before any mergs where is the left token happens. This experiment also shows the existence of bias within the BPE process and our method can recover the exact ground truth probability.