Manuscript Offprint
arXiv:2610.19139Online Tokenization with Optimal Delay in Linear Time
Abstract
Tokenization is an essential preprocessing step in almost all large language models (LLMs). One of the most popular frameworks is BPE tokenization, which consists of special token segmentation, pretokenization, and byte-pair encoding (BPE). However, existing algorithms are sequential, with each stage only processing complete output from the previous stage. In order to reduce latency and memory footprints, recent works (Jiang and Gong, ICML 2026) (Li, Yang and Mamouras, ASPLOS 2026) (Mamouras, Li and Yang, PLDI 2026) have initiated the study of online algorithms for subroutines such as pretokenization and BPE with a goal of streaming input to output as the input arrives online. However, the search for efficient online tokenization remains open.
In this work, we formalize and resolve online tokenization. We introduce the notion of delay for online tokenization which characterizes the extent to which the algorithm output lags behind the (possibly computationally intractable) optimum. We give a near-linear time algorithm with optimal delay (up to constant factors). We complement this algorithm with a conditional lower bound: unless , there is no polynomial time algorithm that beats the delay of our algorithm by more than a constant factor.
We implement a practical variant for tokenizers from OpenAI's tiktoken and HuggingFace's tokenizers. We obtain a latency advantage (measured as time to first token) over tiktoken (as well as the recent gigatoken tokenizer) and our implementation maintains approximately constant memory usage independent of input size. Our implementation also achieves a improvement in throughput over tiktoken and over tokenizers.
*Supported by NSF HDR TRIPODS Phase II grant 2217058 (EnCORE Institute). This work was completed as part of an internship at Morgan Stanley Machine Learning Research.
1 Introduction
In many natural language processing (NLP) applications, including powerful and popular large language models (LLMs), raw text undergoes tokenization before being provided as model input. Tokenization defines a vocabulary containing as many common words and sequences as possible, which help compress raw text into tokens, balancing expressivity and computational efficiency.
Byte-Pair Encoding (BPE) is a popular method for tokenization proposed by Gage [Gag94] that has been widely adopted in LLMs [SHB16]. Indeed, BPE Tokenization is both the subject of intense recent theoretical study [Bv23; JG26; MLY26] and the basis for popular practical tokenizers, including OpenAI's tiktoken and HuggingFace's tokenizers [Ope26a; Hug26].
Concretely, tokenization consists of a three step process: Special Token, Pretokenization, and BPE. As observed in Jiang and Gong [JG26], existing implementations of tokenization are inherently offline and sequential: we take in the full input, apply segmentation to the full input, then apply pretokenization on each segment, and then apply BPE to each pretoken. While completed segments and pretokens can be passed on to the next stage, one should in principle be able to apply pretokenization to a segment as it forms and similarly apply BPE to a pretoken as it forms. Following this observation, Jiang and Gong [JG26] raise the question of online tokenization: can we process each stage as the input arrives in an online setting?
While offline tokenization is now well understood both theoretically and empirically, the question of efficient online tokenization remains wide open. Online algorithms are desirable for many reasons. First, we can drastically reduce the memory footprint of our algorithm by avoiding holding the entire input or output in memory, a shortcoming of all existing end-to-end tokenization algorithms. Second, streaming can reduce latency of tokenization, drastically reducing the time to first token. Indeed, streaming and online algorithms are a fundamental and well-studied paradigm both in theory and in practice, with efficient algorithms being developed in many applications including counting [Mor78], selection and sorting [MP80], heavy hitters [MG82], frequency moments [AMS96], and cardinality estimation [FM85; DF03; Fla+07].
Motivated by latency and memory constraints, online algorithms have been developed for individual steps of tokenization: Li, Yang, and Mamouras [LYM26] studies the problem of online pretokenization and Berglund and van der Merwe [Bv23], Jiang and Gong [JG26], and Mamouras, Li, and Yang [MLY26] study online BPE algorithms. However, none of these works provide an online algorithm for the full tokenization pipeline. Indeed, Jiang and Gong [JG26] raise the design of end-to-end online tokenization as a crucial direction for future research. Our work is thus guided by the following question:
Is there an efficient algorithm for online tokenization?
- Special Token (Seg): Given a list of special tokens and a string , split the string by occurrences of special tokens (see Definition 4.1) into segments. For example, if and the input string is , we have
We use to denote segment boundaries.
- Pretokenization (Split): Given a regular expression (regex) and a string , split each segment of into pretokens by repeatedly finding the longest match of in (see Definition 4.2). For example, if and ,
As we see in our example, matches cannot extend across segment boundaries.
- BPE (Merge): Given a merge list M and a list of pretokens x, apply BPE to each pretoken of x, by repeatedly applying merges in order of priority left to right (see Definition 4.4). For example, if and ,
Tokenization, given special tokens , regex R, and merge list M, is defined
Note that each token in the output corresponds to a unique string denoted raw( ) where . For example, using the same and as above,
That is, merges cannot merge across pretoken boundaries, and the merged pretokens are concatenated. In the offline setting, efficient algorithms are now well known. For example, Seg and Split have classical linear time algorithms [Rep98]. The naive algorithm for Merge runs in time, which is already efficient when is small. When is large, there are well known time heap-based algorithms (see e.g. the tiktoken implementation [Ope26a]).
We now define online Seg, Split, Merge, and Tok. First, for two strings in an alphabet , if is a prefix of , we show it by . Consider a function where are alphabets (e.g. characters and tokens). In our context, could be any of the Seg, Split, Merge, or Tok functions. We say that is a stable prefix with respect to if for any . It is easy to show that stable prefixes are totally ordered (see Claim 4.8). The maximum stable prefix is then denoted by . We define online tokenization (analogously each of the three sub-routines) as . In particular, given that input is all we have observed so far, online tokenization outputs , the longest possible prefix of tokens that can be safely emitted, regardless of what characters appear in the future. This is exactly the definition that allows us to stream input characters and output tokens.
Surprisingly, our first result establishes that online tokenization, unlike its offline counterpart, is NP-Hard. Given that it is unlikely that even a polynomial (let alone linear time) algorithm for online tokenization exists, a natural relaxation is to design efficient approximation algorithms. We introduce a natural approximation of online tokenization which we call delay (see Definition 4.9). An online tokenization with delay k produces on input , output z satisfying:
In particular, an algorithm with small delay produces a stable prefix that might not be the maximum stable prefix, but would have been the maximum stable prefix not too long ago. A trivial algorithm achieves delay n: output the empty string . So we focus on answering the following question:
What is the minimum delay k with efficient algorithms for online tokenization?
1.2 Our Contributions
We give optimal algorithms for online tokenization, tightly characterizing when efficient online tokenization is possible, resolving the main open question of Jiang and Gong [JG26]. First, our lower bound rules out the existence of efficient algorithms with small delay. For any list of special tokens , let be the longest special token and be the sum of the lengths of the special tokens. For any merge list , let and denote the length of the longest token.
Note are constants independent of , so we omit them from bounds for clarity. While (and therefore ) is also a constant (since the BPE dictionary is independent of the input string), since can be quite large in practice (around 100,000 for CL100K in tiktoken), we will account for in space and run-time, keeping consistent with prior work [JG26].
Theorem 1.1 (Hardness of Online Tokenization). Unless , there is no algorithm for exact (zero-delay) online tokenization with preprocessing and total time , even when . Furthermore, the lower bounds hold for algorithms with delay.
A natural attempt at an online tokenization algorithm is to compose online algorithms for special token, pretokenization, and BPE. We show that this idea of composition does in fact yield an efficient online tokenization algorithm with non-trivial delay.
The performance of this algorithm, which we call composition, is parameterized by the following quantity which depends on the pretokenization regular expression. Given a regular language , we define the lookback of the regular language, denoted , to be the smallest integer (or if no such number exists) such that every string of length has a strict prefix such that , and (see Definition 4.3), i.e. is in the language and is shorter than by at most . For example, if , we have . On the other hand, if , .
Theorem 1.2 (Online Tokenization via Composition). Let be a set of special tokens, a total regular expression over , and a merge list. Then, there is an time and space algorithm for online tokenization with delay.
Remark 1.3. As part of our algorithm for Theorem 1.2, we design a simple, novel linear time algorithm for online pretokenization (see Lemma 4.17). In contrast, the previous algorithm of Li, Yang, and Mamouras [LYM26] incurs preprocessing time and space . In particular, we achieve online pretokenization without delay in linear time for all regular expressions under the longest-match convention, whereas the previous algorithm was only efficient when is small.
Remark 1.4. While we have efficient algorithms for online BPE [JG26] and pretokenization via Lemma 4.17, Theorem 1.1 still establishes that online tokenization (with no delay) is NP-hard. Our algorithm for online pretokenization has 0 delay. Known algorithms for online BPE [JG26] have delay (see proof of Lemma 4.18) which suffices for our purposes. We leave as an interesting open question whether zero delay is achievable for online BPE.
While our first algorithm does not achieve optimal delay, we show that its space is optimal (up to word size). In particular, bits is necessary for online tokenization.
Theorem 1.5 (Space Lower Bound). For every integer , there exists where and online tokenization requires bits in space.
While our algorithm requires space, we note that is a constant independent of the input , while can be arbitrarily large (see e.g. above). We note that Theorem 4.24 shows that bits of space are necessary for online BPE, and therefore online tokenization, essentially showing that our space usage is optimal (up to a factor and word size).
Finally, we discuss delay-optimal algorithms for online tokenization. Note that Theorem 1.2 incurs delay and thus incurs additional delay over the lower bound of Theorem 1.1. We show that this is not an artifact of our analysis: composition alone will always incur delay on some instances.
Theorem 1.6 (Composition Delay Bound). For every integer there exists alphabet , a total regular expression over , merge list and some input where and
Thus, if we want to obtain a delay-optimal algorithm, it cannot be from composition alone. Using these insights, our main result establishes an algorithm that achieves near linear time, optimal space, and optimal delay.
Note that the size of is a constant independent of all other parameters. We focus on and parameters here as is typically not a bottleneck in practice, and we set in the construction of Theorem 1.1
Theorem 1.7 (Online Tokenization with Constant Delay). Let be a set of special tokens, a total regular expression over , and a merge list. There is an online tokenization algorithm with preprocessing time , total time and space with delay.
In particular, we characterize (up to constant factors) for what delay efficient online tokenization is possible. When delay is , there is a near linear time algorithm. On the other hand, when delay is , there is no polynomial time algorithm (unless ).
1.3 Implementation and Experiments
We implement a practical variant and obtain an efficient tokenizer that streams an input file of characters to an output file of tokens. We evaluate our tokenizer against tiktoken and tokenizers as a drop-in replacement on code (Github), English, and Chinese datasets. See Section 6 for experimental setup, dataset composition, as well as implementation details and optimizations. Our code is available at https://github.com/morganstanley/MSML/tree/main/papers/Online-Tokenization_with_Optimal_Delay_in_Near_Linear_Time. Our experiments reveal that our implementation exhibits a significant advantage over all evaluated baselines with respect to latency and memory consumption. We also describe some simple optimizations that lead to significant throughput advantages over tiktoken and tokenizers.
1.4 Latency Benchmark
We measure latency as time to first token (TTFT). Since tiktoken and gigatoken do not natively support TTFT measurement, we make minimal changes to their code base to allow TTFT measurement, which is measured as the time from when the input is provided to the tokenizer to the time that the first token is formed. Table 1 shows that our tokenizer achieves TTFT advantage over the best of tiktoken and gigatoken for every encoding and dataset, exhibiting the significant latency advantage of online tokenization.
Table 1: Time to first token (TTFT) speedup of our tokenizer over the better of tiktoken and gigatoken on each corpus.
| Encoding | Github | English | Chinese |
|---|---|---|---|
| r50k | 21.7× | 17.8× | 14.3× |
| p50k | 19.2× | 20.3× | 13.8× |
| c1100k | 34.8× | 11.1× | 7.9× |
| o200k | 17.8× | 11.8× | 12.5× |
1.5 Memory Benchmark
We measure peak RSS (Resident Set Size) as input size increases. Our implementation exhibits approximately constant peak RSS over the range of input sizes, while existing tokenizers retain the full input or output in memory. See Figure 2 for Github, Figure 3 for English, and Figure 4 for Chinese. Our tokenizer reports lower memory usage than gigatoken across all encodings, datasets, and input sizes. Compared to tiktoken, our tokenizer reports higher memory usage on small inputs due to initialization overhead but lower memory usage on large inputs. The crossover point is between 2 and 32 MiB-sized inputs depending on the encoding and dataset.
1.6 Throughput Benchmark
Finally, Table 2 exhibits the throughput comparison of our tokenizer against tiktoken and tokenizers baselines. Depending on the encoding and dataset, our tokenizer exhibits a throughput advantage of over tiktoken and over tokenizers.
Our main optimization replaces the default regular expression of each encoding with a simplified regular expression that allows for faster matching, coupled with a simple, efficient cleanup step that ensures equivalence with the reference regular expression. The optimizations of our streaming algorithms (e.g. simplified regular expressions) are provably verified in Section 6. Due to their simplicity, the optimizations are portable across different encodings, achieving consistent speedups for all evaluated tokenizers that fall within the framework considered in this work. See Section 6 for implementation details and practical optimizations.
Table 2: Throughput speedup of our tokenizer over tiktoken (top) and tokenizers (bottom).
| Encoding | Github | English | Chinese |
|---|---|---|---|
| r50k | |||
| p50k | |||
| cl100k | |||
| o200k | |||
| GPT2 | |||
| Mistral | |||
| Llama4 | |||
| Qwen-3 |
Recent Work Recently, the gigatoken tokenizer presents a parallelized tokenizer that achieves significant throughput speedups over previous tokenizers [Rød26]. While gigatoken achieves high throughput, our implementation, due to its practical streaming design, achieves lower measured TTFT and approximately constant peak RSS over the tested input sizes. We remark that some optimizations of gigatoken are compatible with online tokenization, and observe that a combination of the two can achieve improved throughput for some encodings and datasets, especially on the Chinese dataset (see Section 7.3.1 for details). Verma and Ying [VY26] give an online BPE algorithm with total time , improving upon the of Jiang and Gong [JG26]. This immediately implies a runtime improvement saving a log t factor to our composition algorithm (Theorem 1.2).
2 Technical Overview
We now describe the main ideas behind our algorithms.
Efficient Online Pretokenization We begin with Theorem 1.2. Our algorithm is a simple composition of online segmentation, pretokenization, and BPE. Thus, in order for composition to be efficient, we need efficient implementations of each online component. Given the efficient online BPE algorithm [JG26], it suffices for us to design a linear time online pretokenization algorithm with zero delay.
Some gigatoken optimizations, such as more aggressive caching of observed pretokens can introduce additional memory usage that grows with the number and size of distinct pretokens encountered.
Lemma 2.1 (Online Pretokenization (Informal Lemma 4.17)). There is an algorithm that computes online pretokenization in time and space.
Given a string , let denote the longest prefix of that matches . For simplicity, suppose can be recognized by a DFA of size poly(||) (in Lemma 4.17 we describe how to handle NFAs). Let denote the set of states and the accepting states of . For a string , let denote the state computed if we begin at state and read , and let last be the length of the longest prefix such that ; i.e. reading from ends up at an accepting state. A state is dead if there is no such that .
Consider the following simple algorithm: initialize the variable state to start and on input update state . Whenever state , we know that the current prefix . That is, is a prefix of the longest prefix of that matches , so we can emit and set last . Whenever state dead, we know that the last accepting prefix (denoted ) is maximal and therefore . Since we have already emitted , we can emit , and restart the algorithm on input .
We now analyze the performance of this simple algorithm. On each input , our algorithm needs to maintain (1) to check whether is accepting or is dead and (2) last = last(start, ) to track the longest accepting prefix so far. By restarting the algorithm at , naively scanning the input again requires time. Since every accepting path through the DFA reaches an accepting state once every steps we have (Lemma 4.20). Thus, our algorithm backtracks by at most steps on every output, yielding a running time of . If we could instead recompute and last(start, ) efficiently, then we would have an efficient algorithm for online pretokenization.
Li, Yang, and Mamouras [LYM26] address this by precomputing , last for all possible strings of length , resulting in preprocessing time and space that is exponential in . In this work, we instead give a simple data structure cQueue that supports exactly the required operations.
Lemma 2.2. There is a data structure cQueue supporting the following operations on a string w:
-
(Push) Append a character c to w i.e. update .
-
(Pop) Pop a prefix of w, i.e. return and update for some .
-
(Query) Given a state q, compute and last .
Furthermore, the data structure supports the operations in amortized time.
Now, to implement the online pretokenization algorithm efficiently, it suffices to observe that the string which we want to query only undergoes queue updates. In particular, we push on each input, and whenever , we pop up to . Thus, by supporting the required operations in amortized time, we obtain a total time algorithm for online pretokenization.
Composition Delay Bound We now argue that composition already achieves non-trivial delay . Composition always outputs a stable prefix (and this in fact holds for composition of any two functions see Claim 4.19). If for any continuation , and for any continuation , then for any continuation , since for some .
To bound the delay, it suffices to bound where is the output of our algorithm (see Claim 4.21). Let . In Lemma 4.16, we show where is the length of the longest special token. Now, let . As discussed in the pretokenization algorithm, there are two cases when we can safely emit a stable prefix of Split: either and we can emit the accepted prefix, or and we can emit and rewind to the last accept. Since the DFA must reach a state every steps, outputs all but the last
An accepting state can be dead, for example, if every transition leads to a dead state.
characters of (see Lemma 4.20), and . Finally, let be the output of our algorithm.
We use the key property of BPE which states that for all inputs x,
Combining all three bounds we can upper bound the delay by
Limitations of Composition While composition produces a stable prefix with non-trivial delay, it falls short of an optimal delay algorithm for online tokenization. While the additive term is an input-independent constant (and usually not a large one in practice), the additive term can be arbitrarily large. Theorem 1.6 shows that this delay is inherent to composition.
Consider the following simple example of a tokenizer: and ; and an input . On the one hand, and indeed , since two possible continuations produce and with a longest common prefix of . On the other hand, since no pretoken contains , then regardless of the pretokenization, no merge ever occurs. For our specific example, we in fact have for any input . Concretely, we argue the delay is greater than as the algorithm outputs and
From the above example, we observe that composition will always produce an output where , where is the longest accepting prefix in the pretokenization. However, a zero-delay online tokenization algorithm might produce output that is strictly longer than , i.e. . This is because different continuations may produce different pretokenization outputs, but they nevertheless can produce the same tokenization at the end.
Optimal Delay Algorithm We are now ready to describe our algorithm with optimal delay. Suppose our algorithm proceeds inductively, beginning with an empty output which is a stable prefix of all possible outputs. Consider some stable prefix of the online tokenization output, i.e. which we have computed so far. Since , any stable prefix must be a prefix of . Let be the token following in , i.e. . Then, is not a maximum stable prefix if and only if : is the only candidate token to extend to a longer stable prefix. It thus suffices to decide whether , equivalently, whether for all we have .
Recall that last = last(start, x) is the index of the last accepting state in the pretokenization DFA. Denote so that and
Let out be the index of the last output character so that . Let and , let be the index such that . Note that .
We now describe our optimal delay tokenization algorithm. Let be the current input of length and be the output so far (stable by assumption). In the appendix, we will describe how to use offline tokenization to reduce to the case. Thus, without loss of generality, assume . First, if , then we already have that has delay . Thus, assume .
Now, since , we have
While known online BPE algorithms do not provably compute Merge , the algorithms nevertheless guarantee that the above bound holds (Lemma 4.18)
Note that a different continuation xy may have different outcome Split(xy) = .
From Equation (1), we can conclude that is independent of , where denotes the first token in Merge( ) for any . In fact, can be computed with online BPE applied to a suffix of the current input. Of course, if , then we have so that we can safely emit and proceed inductively. On the other hand, if , the fact that already tells us that is a maximum stable prefix, since there is a continuation such that
To implement the above algorithm efficiently, we need a few additional data structures. First, we need to compute , the next token in , denoted by where is the pretoken in with last . Second, we need to compute , the next token in the event that a future continuation extends the current pretoken match. To support these operations efficiently, we implement two useful data structures. Note that both data structures support pushing string characters and to denote the beginning of a new pretoken (pushing does not contribute to the length of the maintained string).
The first data structure incBPE allows us to compute efficiently.
Lemma 2.3 (Incremental BPE). Given a BPE merge list M with longest token length t, there is a data structure incBPE that maintains implicitly an append-only history string h, an index , and explicitly string under the following operations:
-
(Push) append c to . Note that we can push to denote a pretoken split.
-
(Pop) if , increment I by 1.
-
(First Token) if Merge( ) Merge( ), compute . Otherwise return .
The data structure has preprocessing, space , worst-case update time and query time .
The second data structure bpeQ allows us to compute efficiently.
Lemma 2.4 (BPE Queue). Given a BPE merge list M, there is a data structure bpeQ supporting the following operations on a string w:
-
(Push) Append a character c to w i.e. update .
-
(Pop) Pop , i.e. return and update .
-
(First Token) If , then compute . Otherwise, return .
Furthermore, the data structure has preprocessing, space, and supports updates and queries in amortized time .
Furthermore, Lemma 5.4 gives a data structure cutQ that allows us to efficiently compute last(q) satisfying last(q-1) ≤ out < last(q). We note that last(q) is monotonically increasing: since we are always looking for the longest match, additional characters can only extend a pretoken.
We now sketch our final algorithm on input (see Theorem 1.7 for the full algorithm and Figure 1 for an illustration of the data structures in our algorithm). As before, we will assume . Initialize data structures incBPE and bpeQ. Denote data structure queries by incBPE. and bpeQ. .
Sketch of OptimalDelayTokenization( )
-
Push onto bpeQ. Ensure incBPE maintains .
-
While incBPE. (i.e. first token queries agree), output incBPE. and pop incBPE. from incBPE and bpeQ.
-
If incBPE = and out < i: add , push to incBPE, and return to Step 2.
(When incBPE is empty, we have processed the current pretoken , so increment q and proceed to the next pretoken.)
Our algorithm maintains the following invariants (see Figure 1):
-
if out < i, q satisfies last(q - 1) ≤ out < last(q).
-
incBPE maintains .
-
bpeQ maintains .
Observe that whenever , incBPE is guaranteed to produce the correct output. We only need push operations in Step 1, since last(q) is monotonically increasing. We will show in the proof of Theorem 1.7 that every query to incBPE is valid. Following the above discussion, the displayed algorithm obtains a delay bound of . The running time follows from the near linear running time of both data structures.

Figure 1: Illustration of delay algorithm. Characters up to out are output in . last, last(2), ..., last(5), i are endpoints of pretokens if the current input terminates. Square brackets describe the substring of the input maintained by each data structure. Here, we have .
Hardness of Exact Online Tokenization Our algorithm does not achieve exact online tokenization (zero delay), and we give a lower bound ruling out any polynomial algorithm unless . We will reduce 3-SAT to online tokenization. Consider 3-SAT on variables. First, we construct an alphabet , regular expression , and merge list depending only on . We will ensure that the alphabet size, the size of a DFA recognizing the regular expression, and the length of the merge list all have size . Then, we give a reduction from any -variable 3-SAT instance to input strings of length such that there is a specific alphabet character that appears in if and only if is unsatisfiable (see Theorem 1.1 for details and proof with delay).
The high level idea of our approach is as follows. For each of the possible width 3 clauses , define a symbol . Define . Define the alphabet
For every assignment , we encode as . For a clause , let s.t. denote the encodings of all assignments that falsify and build the regular expression .
To define the tokenization, fix and where is the alternation of all , is the alternation of all encodings, and is the alternation of all characters added to ensure is total. The merge rules will be chosen so that within any pretoken, is merged if and only if the suffix of the pretoken beginning with has even length. Observe that this occurs if and only if occurs in the pretoken (since , both have odd length suffixes beginning with ). Then, given a 3-SAT instance , construct the input .
If is satisfiable (say by ), we will argue that the continuation corresponding to the satisfying assignment has no match with any , and thus matches , in which case is merged and does not appear in . On the other hand, when is unsatisfiable, we argue that any match involving matches corresponding to some unsatisfied clause, so that is never merged and always appears in .
Organization. In Section 3, we define the necessary preliminaries. In Section 4, we establish the hardness of online tokenization with zero delay, and obtain an efficient algorithm via composition. In Section 5, we give our efficient optimal delay algorithm. In Section 6, we present our experimental setup and in Section 7 our results. We provide omitted proofs in Section A.
3 Preliminaries
Let denote an alphabet, the set of length strings over , and the set of (any length) strings over . Let . Let denote the empty string and concatenation. Let denote the length of a string. Let or denote the substring of starting at the -th index and ending at the -th index (inclusive and indexed at 1). We let and where . and are defined analogously. Let denote the prefix of obtained by deleting the last characters and the suffix containing the last characters. We say if is a prefix of . We use to mean that contains as a prefix, not that is a suffix of . We use to denote .
Regular Expressions The regular languages over an alphabet consist of the smallest collection of languages that satisfy the following rules:
-
-
(Concatenation) If , then .
-
(Alternation) If , then .
-
(Star) If , then .
When convenient, we use to denote . A regular expression is total if every non-empty has a non-empty prefix matched by (possibly including itself). Note that this implies . Throughout this work, we consider only total regular expressions.
Regular languages are closed under complement, union and finite intersection. For our theoretical results, a match of regular expression R in x is the longest prefix of x that matches R, or equivalently the longest prefix of x in . Since we assume R is total, this is a non-empty prefix.
For a total regular expression and non-empty input , define the longest match of in , denoted as where . When the context is clear, we simply write . We note that for any regular expression , there is a non-deterministic finite automata (NFA) that recognizes exactly of size (see e.g. Aho et al. [Aho+06]). In Section 6, we will separately discuss examples of regular expressions used in practice, which use regular expressions with priority rules and lookahead.
Given a DFA or an NFA , let be its states. Let be the accepting states, and dead be the set of states that have no non-trivial path to a state in . Note that a dead state can be a state, since we do not count the trivial transition on the empty string . For our purposes of simulating a regular expression with a DFA, if a state is dead and in , it is a maximal match. Let start denote the start state. For a state and word , denotes the state computed if we start on and read . last denotes the maximum where , or if no such exists. For an NFA, we let be a set of states and be the set of states reachable if starting at any and reading and last the maximum where , or if no such exists.
For a merge list , we use merge list and BPE encoding interchangeably. For a given token , let denote the expansion of , i.e. the raw string such that . For a sequence of tokens , let denote the concatenation of . Let the length of a token or a sequence of tokens be defined .
4 Online Tokenization
We begin by defining tokenization in the standard offline batch setting.
Definition 4.1 (Special Tokens). Let be a finite alphabet and a finite set of special tokens. For each string , is a single special character corresponding to . Given a string , the segmenting of by is given by
The output consists of symbols with strings between. Each string is called a special token if it is for , and a segment otherwise. Let and .
Definition 4.2 (Pretokenization). Let be a finite alphabet and a total regular expression over . Then, the pretokenization of with respect to is
Given a list of segments and special tokens , define Split( ) to be Split applied to each segment with the results concatenated. Note that Split is not applied to special tokens and trailing is removed. The output of Split on a single segment consists of symbols with strings between; we call these strings pretokens. Thus, on a list of segments and special tokens, Split produces a list of pretokens and special tokens.
We formally define bounded lookback, a quantity which will characterize both the delay and space usage of our algorithms.
Definition 4.3 (Lookback). A regular language L has -lookback if for any with ,
with the convention . That is, every word in the regular language of length greater than has a strict prefix in the language that is shorter by at most . We let denote the minimum such that has -lookback. has unbounded lookback if for any finite .
Lookback ensures that if we do not find an accepting prefix within characters, the current match (if any) cannot extend by reading more characters of the input.
Definition 4.4 (Byte-Pair Encoding). Let be positive integers. Let be a finite alphabet. Let be a trained Byte-Pair Encoding (BPE) list of merges with corresponding dictionary (i.e. a list of ordered pairs for and ). Let denote the full BPE dictionary. We assume the given merge list is canonical: for every dictionary token , as in Jiang and Gong [JG26, Section 3.3].
Let be a merge. Given a string , the BPE of with respect to is
For a string , the BPE of with respect to is
Given a list of pretokens and special tokens , we define Merge(y; M) to be Merge applied to each pretoken with the results concatenated. Note that on a special token, Merge outputs the special token identically. We call each element in the output list (i.e. number) a token.
We note that a BPE encoding is determined by its list of merges M alone. For succinctness, we use M alone to denote a BPE. We define the longest token.
Definition 4.5 (Longest Token). Define to be the length of the longest token. When the context is clear, we write .
Throughout, we use the symbol to denote hard boundaries in the input string through which no merges can occur. The tokenization problem is then a composition of the above three subroutines.
Definition 4.6 (Tokenization). We define the Tokenization problem as follows. Let be a finite alphabet. Let be a set of special tokens, a total regular expression over , and a BPE encoding. Given a string , the tokenization of is
In running times, we use to denote and to denote . We now define tokenization in the online setting. We begin with the notion of a stable output prefix.
Definition 4.7 (Stable). Let be a set of special tokens, a regular expression over , and a BPE encoding. A list of tokens is stable with respect to a string if is a prefix of Tok( ; , , ) for every string . That is, Tok outputs as a prefix for every continuation of . Let denote the set of stable prefixes with respect to . When the context is clear, we use to denote the set of stable prefixes.
We show that any two stable prefixes are comparable, and therefore the maximal/maximum stable prefix is unique. For two lists , we define the partial order if is a prefix of .
Claim 4.8. If are stable with respect to , then or . In particular, has a unique greatest element under , and every stable prefix is a prefix of .
Proof. We begin with the following fact: if and , then or . Assume without loss of generality . Since both are prefixes of and , we have .
Define . Then, since , we have so that either or . Thus, is in fact a total order, so that there exists a unique greatest element .
Thus, we may define the following Online Tokenization problem. A string is incrementally updated if it is updated only by appending new characters. An algorithm outputs y incrementally if it outputs by appending to the previous output.
Definition 4.9 (Online Tokenization). Let be a set of special tokens, a total regular expression over , and a BPE encoding. Online tokenization, given an incrementally updated string , incrementally outputs . An algorithm for online tokenization with delay incrementally outputs such that
Exact online tokenization is the problem of online tokenization with delay 0.
We argue that given an incrementally updated string , also updates incrementally, and thus (at least in principle) an algorithm could maintain the output efficiently.
Claim 4.10. If , then . Consequently, .
Proof. Let be a stable prefix. Then, for any . Write for some . Then, for any since is a continuation of . Hence, , as desired.
4.1 Exact Online Tokenization
We begin with a conditional lower bound showing that it is likely hard to design an efficient algorithm for online tokenization without delay.
Theorem 1.1 (Hardness of Online Tokenization). Unless , there is no algorithm for exact (zero-delay) online tokenization with preprocessing and total time , even when . Furthermore, the lower bounds hold for algorithms with delay.
Proof of Theorem 1.1. We begin with the lower bound against algorithms for exact online tokenization with zero delay. Suppose we have some algorithm running in time . We will construct a reduction from 3-SAT on variables. We construct the following tokenization instance. There are possible clauses of width 3 on variables. Let be the set of all such clauses. Define . The alphabet consists of
Let . For every bit-string , define
For each clause , let be the set of assignments on variables that falsify . Observe that can be recognized by a DFA of size : there is 1 assignment to the three variables in that falsifies , and the remaining variables are unconstrained. Similarly, is the set of all assignments and can be recognized by a DFA of size . Consider the regular expression
where we abuse notation and use to denote the regular expression that recognizes . Let recognize the alternation of all for . Then, the full regular expression is
Note that is the alternation of all single characters, and ensures that is total. Observe also that all rules that match strings of length > 1 have distinct starting characters, so that any longest match automatically chooses the match of highest priority. In particular, longest match already prioritizes matches of length > 1 over single character matches. Thus, can be recognized by a DFA of size .
The merge rules are described below in order of priority:
Note that . Thus, in the preprocessing phase, the assumed algorithm for online pretokenization given requires time.
Consider now a 3-CNF formula on variables and clauses. Construct the input
Note that . We claim that decides whether is satisfiable.
Claim 4.11. For any 3-CNF formula , we have the following:
-
(Completeness) If , then .
-
(Soundness) If , then .
Thus, if an algorithm computed online tokenization (without delay) in time, we would have an algorithm that determines satisfiability of size formulas in time. In particular, since 3-SAT is NP-complete, we would have , a contradiction. It remains to prove Claim 4.11.
Proof of Claim 4.11. First, we argue . This follows simply as are not involved in any merge rules, and thus are output regardless of the choice of continuation. Next, note that since every pretoken that contains more than one character ends with either or , which does not occur in . Thus, Split splits into single characters, and no merges occur.
Suppose is satisfiable. Let be a satisfying assignment so . Consider the continuation . Then, we claim that no substring of matches for any . Suppose for contradiction some substring of matches for some . Since there is only one in the input, the match must take the form for some . We thus have for some clause , a contradiction since is a satisfying assignment.
Since does not match any substring of , we have
Thus, , establishing equality.
On the other hand, suppose is unsatisfiable. Our goal is to show that for any continuation , . Observe that appears in a pretoken only when followed by a , a string in and a . Thus, it suffices to only consider continuations of the form where and . Otherwise, no rule matches a pretoken of length > 1 containing , so is emitted as its own token. Since
is not satisfiable, we have , or for some . Take the smallest such with and since gets matched first, we have
Thus, we have , as desired.
Extension to Delay. Now, we describe how to modify the lower bound against algorithms with small delay. We add a character to the alphabet so that
The special token set is identical. Note that in the previous construction, . The merge rules now begin with
Then, we have for every , the merge rule . The remaining merge rules are as essentially identical, replacing with .
Observe that now as long as , we have . For example, if we choose , then . As argued above, we have , , and . We reduce instead from 3-SAT on variables (assuming without loss of generality that is even). Consider the fixed string
For every assignment on variables, define
For every possible clause of width 3 on variables, we let denote the assignments on variables that falsify , and we write . By our choice of , can be recognized by a DFA of size since we may replace the at most states for recognizing for any with a path of length at most that recognizes . We let be the alternation of all for . Then, if we let , we define the full regular expression analogously as . Following similar arguments as before, and noting that once again all pretoken matching strings of length > 1 have distinct starting characters, R can be recognized by a DFA of size , so that the total preprocessing time of the assumed online tokenization algorithm is .
For a 3-CNF formula on variables and clauses, we construct the input
Note that . We claim that decides whether is satisfiable, even with delay.
Claim 4.12. Let . For any 3-CNF formula , we have the following:
-
(Completeness) If , then for all with , .
-
(Soundness) If , then for all with , .
Proof of Claim 4.12. As before, we have since no participates in any merge rule and for any , we have , since contains no , .
Suppose is satisfiable, so that there exists an assignment with . Fix any of length at least . Then, for some . Consider the extension . Following similar arguments to Claim 4.11, we have
Thus, , establishing equality.
Suppose . Again, fix for some . Since every pretoken of length > 1 involving follows with , , a string in , and , it suffices to consider extensions of the form where and . Otherwise, the pretoken does not match , so that is not merged and output as single characters. Since is unsatisfiable, there exists a clause in such that . Following similar arguments to Claim 4.11, we have
Thus, .
Suppose for contradiction that we have an algorithm with delay . Let be the algorithm's output on , and let be its delay. Hence
Since , , and , we have for sufficiently large . By Claim 4.12, determines whether is satisfiable. Thus also determines whether is satisfiable. Since the input has length , we decide whether is satisfiable in time, contradicting the assumption .
4.2 Online Tokenization via Composition
Given Theorem 1.1, our goal is to design fast algorithms with minimal delay. In particular, we would like to design algorithms running in almost linear time (e.g. ). We begin with a simple algorithm that composes online segmentation, pretokenization, and BPE merging.
We first define online segmentation, pretokenization, and BPE merging. Note that Claim 4.8 and Claim 4.10 do not use anything specific about the tokenization process, and can be shown for any function that takes an (incremental) list as input and outputs an (incremental) list. Thus, again in principle, we can hope for efficient online segmentation, pretokenization, and BPE merging. Since pretokenization takes a list of lists as an input and outputs a list of strings, we say a list of strings is updated incrementally if it is updated by either appending characters to the current last string, or starting a new string. Similarly, an algorithm outputs a list of strings incrementally by either appending characters to the current last string, or starting a new string. We let , , and denote the set of stable prefixes with respect to , , respectively, where is a string input to segment with , and is a list of strings input to pretokenization or BPE.
Definition 4.13 (Online Segmentation). Let be a set of special tokens. Online Segmentation, given an incrementally updated string , incrementally outputs .
Definition 4.14 (Online Pretokenization). Let be a total regular expression over . Online Pretokenization, given an incrementally updated list of strings , incrementally outputs .
Definition 4.15 (Online Byte-Pair Encoding). Let be a BPE encoding. Online BPE, given an incrementally updated list of strings , incrementally outputs .
As before, we omit , , when convenient. We observe that for a list , . Indeed, any continuation of has the first segments identical to and the -th segment is a continuation of . Similarly, .
We give a linear time algorithm for online tokenization.
Theorem 1.2 (Online Tokenization via Composition). Let be a set of special tokens, a total regular expression over , and a merge list. Then, there is an time and space algorithm for online tokenization with delay.
Accounting only for on large inputs, our algorithm runs in time and space with delay.
Proof of Theorem 1.2. As subroutines, we require algorithms Segment, Pretokenize, BPEMerge with the following guarantees.
Lemma 4.16 (Online Segmentation). There is an algorithm Segment that computes online segmentation in time and space. Furthermore, for any , .
Lemma 4.17 (Online Pretokenization (Formal Lemma 2.1)). There is an algorithm Pretokenize that computes online pretokenization in time and space. Furthermore, for any list of segments , outputs all but the last characters of .
Lemma 4.18 (Online BPE [JG26]). There is an algorithm BPEMerge that in total time and space incrementally outputs y satisfying
for some .
First, we argue that the above suffices to prove Theorem 1.2. Our algorithm simply outputs
Note that each of the three algorithms are online (i.e. handles incremental input and incremental output) so that the algorithm is well defined. The running time and space bounds follow trivially, so it suffices to prove correctness. Let be the current input and the desired output. First, we prove that our algorithm is sound: it outputs a stable prefix.
Claim 4.19. For any , R, M and input string x,
Proof. Throughout, we omit for clarity. Let , and denote the outputs of our algorithm. Fix any continuation . Then, by correctness of Segment, so that for some . By correctness of Pretokenize, . Then, for some . By correctness of BPEMerge, we have . Thus, is a stable prefix.
Next, we prove completeness: our algorithm outputs the maximum stable prefix with delay . We require the following lemma, which states that any accepted word must reach an accepting state every characters.
Lemma 4.20. Let be a DFA recognizing . For , let denote whether is in an accepting state after reading . Let last denote the last accepting state when reading (possibly including ). If last, then for all .
Proof. Suppose for contradiction for some continuation . Let . Since is total, we have last so that . Set . By Definition 4.3, for any , there exists some such that and . Let be the largest such that so that . Then, last , a contradiction.
Let . Let where and (possibly empty) contains no special token. We can assume this without loss of generality, as if ends on a special token, then is empty. Note that we can thus assume is a special token.
Since only holds back characters of if a suffix of is a prefix of a special token in , we conclude that since and therefore is not a prefix of any special token . Then, we write
where . If is empty, then so that
In other words, since is a special token, we have
so that the algorithm has delay , since implies .
Thus, assume is not empty. Let where and . Lemma 4.17 guarantees that .
Then, our algorithm outputs
where . Recall that we proved above
We have the following claim.
Claim 4.21. Suppose and , and . Then, .
Proof of Claim 4.21. Note , so , are prefixes of . Thus, if , we have the desired claim.
Our algorithm outputs . From Lemma 4.18 we have
Thus, Claim 4.21 implies the desired delay bound. It remains to prove the required lemmas.
Lemma 4.16 (Online Segmentation). There is an algorithm Segment that computes online segmentation in time and space. Furthermore, for any , .
Proof of Lemma 4.16. Consider a trie that recognizes strings in . This trie has size . Regard the trie as a deterministic automaton with an additional rejecting sink. Missing child transitions lead to the sink, which loops on every character. Accepting nodes correspond to special tokens. The function last(start, w) returns the length of the longest accepting prefix of w, or if none exists.
We note some properties of . The input consists of the characters in the committed output and (possibly empty) buffer such that . We note that is a (non-maximal) trie prefix. Otherwise, if it is not a trie prefix, it is not (and cannot be extended to a special token), so that we can commit at least one character of to output. If it is a maximal trie prefix, it is a special token (and cannot be extended to a longer one), so we can commit as a special token. Thus, we have
For some partition where we may assume without loss of generality that (possibly empty) is not a special token, we have
Note that each is either a special token (corresponding to a trie match) or a segment of alphabet characters. Only the latter is provided as input to pretokenization and BPE in later stages.
In the first case, since contains a special token as a prefix, any continuation of contains a special token after , so the prefix contains after . In the latter case, we do not know if will extend to a special token. In particular, we cannot yet commit any character of , since if is extended to a match (e.g. ) then ends with .
We now give a simple algorithm. Intuitively, buffer will maintain the uncommitted suffix of the input. Initialize state ← start to the root of T, last ← ⊥, and buffer ← ε. Recall that δ denotes the transition function and last the last acceptance. In the following, reset means state ← start, last ← ⊥, buffer ← ε. Our algorithm never outputs two consecutive ∥; this can be checked by examining the last output. On input , do the following:
SimpleMatch( )
-
Update state and push to buffer.
-
While buffer is not a trie prefix:
(a) If last = ⊥, output buffer₁ and update buffer ← buffer₁.
(Prefix of special token unmatched. Flush first character.)
(b) If last ≠ ⊥, output and pop .
(Backtrack to the last special token. Restore state.)
(c) Update state and last .
- If state ∈ P and buffer is a maximal trie prefix, output . Reset.
(Found maximal special token.)
- Else if state ∈ P set last ← |buffer|. If last ≠ ⊥, output ∥.
(Found special token, not maximal.)
Observe that if we make the assumption that is prefix-free (as is often the case in practice), the algorithm and ensuing analysis can be simplified by ignoring Step 4. The space of the algorithm is , since buffer contains exactly the uncommitted input . The time of the state cases is , in the maximal case and otherwise. We bound the time of Step 2. We observe that each iteration of the while loop takes time (e.g. to recompute state, last). Furthermore, there are at most iterations since in each iteration, the size of buffer decreases by at least 1. Thus, the overall time per update is . With a slightly tighter analysis, we can achieve total time, by observing that every step that requires time produces at least one character of output, so there are at most such steps.
We now prove correctness, inducting on with the following hypothesis. Let u be the uncommitted input after processing .
-
buffer contains the uncommitted input.
-
state = and last = last(start, buffer).
-
The output is (satisfying Equation (2)).
The base case is trivial. On input , either extends as a prefix of a special token, or it does not. In the former case, if is a maximal special token, our algorithm has and buffer is maximal, so we output and reset, satisfying the inductive hypothesis. Otherwise, is not a maximal special token. If it is a special token, we output since , push to buffer and update , last, again satisfying the inductive hypothesis. Otherwise, our algorithm pushes to buffer and updates , again satisfying the inductive hypothesis.
If does not extend u, our algorithm enters the case where buffer is not a trie prefix. Whenever buffer is not a trie prefix, we pop some prefix of it (either one character or a prefix of buffer that is a special token). Eventually, buffer (which is possibly empty) must be a trie prefix. If this prefix is maximal, we output it, leaving buffer empty and satisfying the first condition. If not, we retain buffer, again satisfying the first condition, as this is the uncommitted input. It is easily verified that whenever buffer is updated, state and last are recomputed appropriately, satisfying the second condition. In each iteration, we output any prefix of buffer that is a special token (that cannot be extended), and also outputting if the buffer contains a trie prefix after exiting the while loop, maintaining the correctness of the output as desired.
Lemma 4.17 (Online Pretokenization (Formal Lemma 2.1)). There is an algorithm Pretokenize that computes online pretokenization in time and space. Furthermore, for any list of segments , Split outputs all but the last characters of .
We note that in the offline setting, there is a linear time pretokenization algorithm (called maximal munch tokenization) of Reps [Rep98]. In the worst case, their algorithm requires linear space. We design an algorithm parameterized by . Consider a DFA that recognizes exactly with starting state start.
Observe that a simple modification of Lemma 4.16 gives an algorithm for online pretokenization that runs in time and space: Simulate . On each accepting state, emit the current match; otherwise buffer the current input in memory. On each dead state, backtrack to the last accepting state, emit a , and simulate on the buffer in memory from the starting state. Lemma 4.20 guarantees that a dead state must be encountered within characters of the last accept, so that we backtrack at most characters, resulting in time. While in practice is not large, in the worst case this can lead to a quadratic time algorithm (e.g. when is sufficiently large). To guarantee linear time in general, we require the following useful data structure:
Lemma 2.2. There is a data structure cQueue supporting the following operations on a string w:
-
(Push) Append a character c to w i.e. update w ← wc.
-
(Pop) Pop a prefix of w, i.e. return and update for some .
-
(Query) Given a state q, compute and last(q, w).
Furthermore, the data structure supports the operations in amortized time.
The data structure is initialized with two empty stacks: the push stack and the pop stack.
push(c) for character :
-
Compute and last for all .
-
Let be the top element of the push stack ( if empty). Compute and push
last .
pop(p) for integer :
-
If the pop stack has elements, pop elements from the pop stack.
-
If the pop stack has elements:
(a) Pop k elements from the pop stack. Let the push stack contain (with on top).
(b) If , empty both stacks.
(c) If , reverse the elements of the push stack onto the pop stack, so that the pop stack contains (with on top). For each in decreasing order, compute:
(For comparison purposes, if last(q, w) = ⊥, then ⊥ = -∞.)
Then, pop p - k elements from the pop stack.
query(q) for state :
-
Let the pop stack contain (with on top) and the push stack contain (with on top).
-
Compute:
We prove that the data structure satisfies the desired guarantees.
Proof of Lemma 2.2. We maintain the following invariant: every element maintains and last for the string obtained by concatenating all characters beneath it and itself. This consists of prefixes of the string on the push stack and suffixes of the string on the pop stack. Formally,
Claim 4.22 (Below Consistency). Let the pop stack contain (with on top) and the push stack contain (with on top). Our algorithm maintains for every :
-
and last for all ,
-
and last for all .
Proof of Claim 4.22. Note that for any word , we have by the definition of a DFA for all ,
Similarly, for all ,
(4)
The above equality follows as either the DFA reaches an accepting state in the second half of the computation when scanning (in which case the second case triggers) or it does not, in which case it suffices to find an accepting state in the first half when scanning (which is handled by the first case).
We now argue that the invariant is maintained on the push and pop stacks. This follows directly from Equation (3) and Equation (4) and the update rule of push and pop.
Given Claim 4.22, we observe that Equation (3) and Equation (4) ensure that query returns the correct values. We now argue that our data structure has the desired performance. Consider a single element: it is pushed onto the push stack once, moved from the push to pop stack (at most) once, and popped from the pop stack (at most) once. It then suffices to argue that each operation requires time. For push, the computation of the transitions and last can be computed in time given and last . When moving from the push stack to the pop stack, we compute and last in time and then query and last in time. Popping an element of the pop stack requires time, completing the proof.
Using the given data structure, run the following algorithm. We begin by initializing an empty cQueue (Lemma 2.2) and state ← start. Then, for each character in the input, do the following.
FastPretokenization( )
-
Push cQueue.push( ) and update state ← .
-
If state ∈ P, output cQueue.pop(|cQueue|). (Found a match, so emit the current buffer and reset cQueue.)
-
While state ∈ dead: (The unresolved suffix cannot continue the current match, so || at the last P.)
(a) If cQueue = , output ||, set state ← start and exit.
(b) Query , last(start) ← cQueue.query(start).
(c) Output || and cQueue.pop(last(start)).
(d) Update state ← .
We prove that our algorithm satisfies the desired properties.
Proof of Lemma 4.17. We begin by analyzing the correctness of our algorithm. We proceed by induction, and argue that for all , after witnessing , the algorithm maintains the following:
A The output is Split . The output Split consists of a string consisting of pretokens and separators . We let denote the output before the last separator in Split . Thus, we observe that the output has one of the following forms
-
for , for some indicating the current “live” pretoken,
-
, in which case we write .
B cQueue maintains .
C state maintains .
We call the above induction the outer induction, which inducts over each input provided incrementally to the algorithm. The base case is trivial. If , we have so the initial output is , cQueue is empty, and state start = .
We now proceed to the inductive case. Consider input . To prove the outer induction above, we will use an inner induction over the while loop within FastPretokenization. To prove the output of the -th iteration of the outer induction has Properties A, B, C, we assume the output of the -th iteration starting with satisfies Properties A, B, C after processing . Note that since we can only incrementally extend the output of Split . We now claim that after the -th iteration of the while loop, the following hold:
- The current output is where
for with the convention .
-
cQueue maintains . Furthermore, state maintains .
-
If state dead, then the output is Split .
-
state if and only if .
First, we claim that if the inner induction claim holds and the while loop terminates, then the outer induction holds. Towards Item A, we observe that the while loop only terminates when state dead and thus Item 3 ensures that whenever state dead, the output is Split as desired. Towards Item B and Item C, we set and after the termination of the while loop so that Item 2 ensures the desired properties. Thus, it suffices to prove (1) the inner induction holds and (2) that the algorithm does indeed terminate after each input.
Base Case. We begin with the base case. By convention, we say that the 0-th iteration of the while loop ends after Step 2, i.e. immediately before the first iteration of the while loop. When input arrives, the output is by Claim 4.10.
If state , then the algorithm does not output or modify cQueue in Step 2. Furthermore, since
we have , satisfying the first, second, and fourth conditions.
If state , then we have
In particular, since for any continuation y,
we have so that
where represents the first match of (see Definition 4.2). Thus, the first, second, and fourth conditions are satisfied with .
It remains to check the third condition. Suppose state dead, we claim the output is Split . Since state dead, there is some continuation where
If state , then above we had ,
so that .
If state , after Step 2 the output is Split since we output
We claim this is Split as
have a maximum common prefix of . Thus, in both cases we have that the output is .
Inductive Case. Now, let . We check that all conditions are maintained through each iteration of the while loop. From the second condition, we have cQueue maintains so that we compute
Let denote state at the end of the previous iteration. If , the fourth condition implies that and the second implies cQueue maintains . Furthermore, since (otherwise this iteration would never have run), then for every continuation
so that . Our algorithm outputs exactly in the -th iteration. Furthermore, , so the while loop terminates, completing the inductive step.
Thus, in the following assume , so that and . By induction, we output . We argue . Since , we have for any continuation ,
Since , we have
The algorithm pops and outputs , satisfying the first and second conditions. If , we have , satisfying the fourth condition.
We verify the third condition. Suppose state ∉ dead, so there is some continuation where
Then, we have
so that the maximum common prefix is at most , as desired.
Termination Condition. We now argue that the while loop terminates. Above we have argued that whenever state , the while loop terminates in the next iteration. On the other hand, whenever state , we have , and the first condition ensures that since is total so that last(start, ) > 0, as every non-empty string has a non-empty prefix that matches the regular expression.
Performance. Finally, we bound the amortized running time of our algorithm. From Lemma 2.2, it suffices to argue that the running time of our algorithm is dominated by operations of cQueue (up to constant factors). To do so, we can simply charge the check of and outputting in each iteration of the while loop to query from cQueue. To bound the space, we use Lemma 4.20. Suppose maintains more than elements e.g. . Recall is the last output index, corresponding to the last index where on the current attempted match. Then, we have since we pop from cQueue and output whenever an accepting state is encountered. In particular, Lemma 4.20 ensures that , so that we enter the while loop and output . Since is total, on the new match we have , so that the algorithm outputs and pops (at least) from cQueue. Thus, whenever , the algorithm pops at least one element from cQueue in each iteration, ensuring that the size of the string maintained by cQueue does not grow. Thus, cQueue requires space at most .
Extension to NFA So far, we have assumed that is a DFA. However, given a regex , a DFA might have size , while an NFA is promised to have size . We thus describe how to extend our algorithm to handle NFAs. It suffices to describe how to modify the data structure given by Lemma 2.2 to handle queries on NFAs. Note that we only ever query the data structure with the start state. In addition, in the algorithm of Lemma 4.17, we modify to be a subset of states and in the first step, modify the update rule . We say a subset is dead if .
We modify Lemma 2.2 as follows. For each state , we maintain which is now a subset of states. For any , we have the identities (analogous to Equation (3) and Equation (4)):
Above, max of an empty set or is . Given , and last , last note that , last can be computed in time. Thus, the amortized time of each operation of the cQueue data structure is still , as desired.
The analyses of correctness and performance follow identically. Note that all of the modifications described incur a poly(|R|) = O(1) blowup in runtime. This concludes the proof of Lemma 4.17.
Finally, for online BPE we use the algorithm of Jiang and Gong [JG26].
Lemma 4.18 (Online BPE [JG26]). There is an algorithm BPEMerge that in total time and space incrementally outputs y satisfying
for some .
Proof of Lemma 4.18. We take the algorithm of Jiang and Gong [JG26] (see their eager output algorithm and accompanying analysis). Their algorithm has time and space . While they do not explicitly analyze the delay of their algorithm (indeed it does not compute zero-delay online BPE, see Claim 4.25), we show that their algorithm has delay at most .
Let denote the depth of the Aho and Corasick [AC75] automaton state after reading . The [JG26] algorithm outputs the longest common prefix of for . Every input in this common-prefix computation extends so that is a prefix of their output. In particular, on input tokenizes all but a length suffix of .
Lemma 4.23 (Theorem 2 of Berglund and van der Merwe [Bv23]). For any merge list and input , we have
where and .
The bound on is tight up to constant factors (see Theorem 4.24 for details). We remark that while may vary on input , it is always upper bounded by . By Lemma 4.23, the output emits all but at most characters. Alternatively, we can also use the algorithm of Mamouras, Li, and Yang [MLY26], which obtains similar guarantees.
This concludes the proof of Theorem 1.2.
4.3 Space Lower Bounds and Limitations of Composition
We give a lower bound showing that the space usage of Theorem 1.2 is optimal.
Theorem 1.5 (Space Lower Bound). For every integer , there exists where and online tokenization requires bits in space.
Proof. Fix the alphabet . Fix a function . Let ,
and .
First, we claim that . Consider any string of the form . Then, the only proper prefixes that are in are which are length shorter than the original string. Thus, we have . To prove the upper bound, we observe that all singletons are in the language, and the longest word in the language is length .
We now show that online tokenization requires space. Consider the following inputs, where is a string . Upon seeing this, there are (at least) two possibilities. The input ends, in which case, Split partitions into single characters, so that . On the other hand, if the next character is a so that the entire string becomes one pretoken, we apply the merge rules to the consecutive and pairs, so the output is . In particular, since the two outputs have no common prefix we have . When the next character is a and the input ends, the algorithm must output a string in . Note that the output is purely a function of the internal state of the algorithm, since the final character is constant across all possible inputs. Since there are such strings, the algorithm requires space, as desired.
Using similar ideas, we show that our space dependence on m and the bound in Lemma 4.23 are both optimal.
Theorem 4.24 (BPE Space Bound). For every pair of functions with , there exists where the size of the merge list and and online BPE merging (and therefore online tokenization) requires bits of space. Furthermore, there exists some where
Proof of Theorem 4.24. We give an instance of BPE, which can easily be extended to a tokenization instance by setting and . Let . Let . We build the list of merges as follows, in order of priority. For we define
so that with we have and . Next, define the following rules, where the priority order is given first by row and then left-to-right in each row:
Analogously, we define and , placing each immediately after its corresponding A-rule in the above priority order.
We now describe the inputs. For any , we can build the input
Where . For , we define if and otherwise and if and otherwise. Then, consider the (empty) continuation and continuation . We have
Thus, . Note . As in Theorem 1.5, after viewing , the output is , but the algorithm must produce distinct outputs after receiving the continuation . Then, the number of bits of space is at least .
Next, we can extend the example of Theorem 4.24 to show that the Online BPE (eager output) algorithm of Jiang and Gong [JG26] in fact incurs delay . Since in our application, delay suffices (and is optimal), we leave as an open question to develop an online BPE algorithm with zero delay.
Claim 4.25. For every function , there exists where and the online BPE algorithm of Jiang and Gong [JG26] incurs delay .
We begin by recapping the Aho and Corasick [AC75] automaton, a crucial ingredient in describing the Jiang and Gong [JG26] algorithm. For any node in the trie, define fail() to be the longest proper suffix of that is a trie prefix. Note fail() could be the root corresponding to . We use strings to denote their corresponding nodes in the trie. Aho and Corasick [AC75] give an efficient linear time algorithm for computing fail() for all and the Aho-Corasick automaton, denoted , which has states and transitions:
That is, transition to the child if it exists, otherwise find the longest suffix of (possibly empty) that is a prefix of the trie. The depth of a state is the depth of the node in the trie.
Proof of Claim 4.25. Let and for so that . Consider the input so that . Indeed, we have .
Note that the depth of the Aho-Corasick automaton on the trie consisting of the strings corresponding to all tokens after scanning is . Thus, the Jiang and Gong [JG26] algorithm outputs the longest common prefix of . In particular,
so the longest common prefix is , the empty output. This fails the requirement for the algorithm to have delay , thus establishing that the delay is .
So far, we have given an algorithm that is essentially optimal in both time and space. However, the worst-case delay of the algorithm is still . On the other hand, Theorem 1.1 does not rule out efficient algorithms with delay , which can be much smaller than b. Below, we show that this is an artifact of composition: naively composing online algorithms for Segment, Split, and Merge cannot achieve online tokenization with delay less than lookback.
Theorem 1.6 (Composition Delay Bound). For every integer there exists alphabet , a total regular expression over , merge list and some input where and
Proof of Theorem 1.6. Let . For any function , we provide an example where composition of segmenting, pretokenization, and merging alone achieve delay at least . Let , and . Observe that the lookback is since the only strict prefix of that is matched by the regular expression is , so the lookback is at least . To upper bound the lookback, note singletons are accepted and the longest pretoken has length .
Consider the input . Note since no pretoken contains as a substring and no merge ever occurs. However, since it must be a common prefix of
Thus, . In particular, the delay is at least , as desired.
While the above example is not hard for tokenization (in fact, for any ), it shows that any algorithm achieving delay against arbitrary pretokenization splitting and BPE merging cannot naively compose algorithms for segmenting, pretokenization, and BPE merging.
5 Improved Delay Beyond Composition
We show that a more careful algorithm can achieve delay independent of . Theorem 1.1 establishes that this delay is optimal for polynomial time algorithms. We begin with some notation and useful properties. Recall that for any string , is the first token in Merge( ).
Claim 5.1 (Theorem 2 of Berglund and van der Merwe [Bv23]). Let be a merge list with pairs and the length of the longest token. For any two input strings , if , then .
Throughout this section, we will view BPE as the following process on an input string x. Every pair of adjacent characters initially has a cut between them, that is, every character begins as a single token. Pretokenization fixes certain cuts in place (i.e. the cuts that represent cuts between pretokens denoted by ). For example, the list of pretokens
can be viewed as list of characters with cuts
where represents fixed cuts given by the pretokenization phase and represents unfixed cuts (or simply cuts) that can be removed by the BPE merge process. BPE merge on each pretoken then removes cuts, i.e. every merge removes a cut between two adjacent tokens. Following the above example, the merge rule removes cuts so that the output is
corresponding to the output string "AabbbAA".
An ordered pair of tokens is consistent, denoted , if
We show that consistency extends to sequences of tokens.
Claim 5.2. Let be a sequence of tokens. Then
We say is a consistent sequence of tokens if they satisfy the left hand side. Consequently, for any token and consistent sequence of tokens , we have is consistent iff .
Following the above convention of viewing BPE as a process of removing cuts between characters, a sequence of tokens can be viewed as the raw string with the cuts surviving the BPE merge process exactly denoting the cuts in the final output.
where denotes the surviving cut between token and .
Proof of Claim 5.2. Suppose is consistent. Consider the interval for any with endpoint cuts . Observe that for two strings containing this interval, if after applying merge , neither endpoint cut is merged, then the cuts internal to the interval are identical after applying merge . Then, consider the strings and . Since is consistent, the endpoint cuts are never merged. The same statement holds trivially over the string . Thus, since the cuts internal to the interval are identical, we have that .
Conversely, suppose every pair is consistent. If every cut between is not merged, then we have by the above argument. Thus, assume some cut between is merged. Let be the highest priority rule that removes a boundary cut, and among the boundary cuts removed by , let be the one of minimum index. We claim that at the instant is removed, neither endpoint cut nor has been removed. Indeed, by the choice of , no rule of higher priority than removes a boundary cut, and every rule of lower priority is applied only after ; so it suffices to rule out that itself removes an endpoint cut before . For , this holds by the minimality of . For , note that minimality does not apply, since ; instead, if also removes , then it does so only after removing , as lies to the left of . Consequently, the cuts internal to the interval are identical to those in the Merge process on alone, so is removed there as well. This contradicts .
We now present our algorithm.
Theorem 1.7 (Online Tokenization with Constant Delay). Let be a set of special tokens, a total regular expression over , and a merge list. There is an online tokenization algorithm with preprocessing time , total time and space with delay.
Proof of Theorem 1.7. We present an algorithm that computes (Merge ○ Split)₹ with delay . Following similar arguments to Theorem 1.2, we can obtain an online tokenization algorithm with delay , since outputs all but the last characters of the input. We begin with the following useful data structures.
BPE Queue On any string w, let be the first token in Merge(w). As before, we use when the merge list M is clear.
Lemma 2.4 (BPE Queue). Given a BPE merge list M, there is a data structure bpeQ supporting the following operations on a string w:
-
(Push) Append a character c to w i.e. update .
-
(Pop) Pop , i.e. return and update .
-
(First Token) If , then compute . Otherwise, return .
Furthermore, the data structure has preprocessing, space, and supports updates and queries in amortized time .
Note that queries are only required to be correct when is sufficiently large ( mt).
Proof of Lemma 2.4. We require a modification of the incremental algorithm of Jiang and Gong [JG26].
Lemma 5.3. Given BPE merge list M, there is an algorithm with preprocessing and space that given any string , computes for all in time.
Note that Jiang and Gong [JG26] give an algorithm that computes in time the last token of every prefix of . In contrast, we compute the first token of every suffix of . Since the data structure essentially follows from Jiang and Gong [JG26], we defer the proof to Section A.
Finally, we can use a standard trick to convert the batch algorithm into an algorithm with efficient amortized update and query time. We maintain two queues U and V such that the maintained string w satisfies . Initially, both . We maintain the invariant that:
If , then and is computed for all .
On a push, we push the character to V. On a pop, we pop the character from U if it is not empty. Otherwise, V is not empty and we remove a character from V. After each operation, if and , then we have , in which case we let and apply the algorithm of Lemma 5.3 to U.
We check that the invariant is always maintained. Consider the first time , at this time we have and is empty. Our algorithm detects this, and moves to , applying the batch algorithm to , maintaining the invariant. Subsequently, anytime and , we again transfer to and apply the batch algorithm. Note that always and is always computed, since whenever we add elements to , we recompute on the whole object , while popping elements from ensures that is still computed on the remaining elements. Each application of the batch algorithm requires time and ends with . Since we do not apply the algorithm again until , or after operations, the amortized time is .
Finally, correctness follows since whenever , the invariant guarantees . Claim 5.1 then ensures that .
Incremental BPE We also extend the incremental BPE algorithm of Jiang and Gong [JG26].
Lemma 2.3 (Incremental BPE). Given a BPE merge list M with longest token length t, there is a data structure incBPE that maintains implicitly an append-only history string h, an index , and explicitly string under the following operations:
-
(Push) append c to h ← hc. Note that we can push || to denote a pretoken split.
-
(Pop) if , increment I by 1.
-
(First Token) if Merge( ) Merge( ), compute . Otherwise return .
The data structure has preprocessing, space , worst-case update time and query time .
Popping is allowed only when . First token queries are only required to return when , i.e. when is a token boundary in the tokenization of the full implicit hidden string .
Proof of Lemma 2.3. Jiang and Gong [JG26] give an algorithm with preprocessing and space (see Section 5 and 6 of [JG26] and Section A for details) worst-case update time supporting push operations and last token queries after any number of push operations. For example, given a string , they can compute the last token of every prefix of , i.e. the last token of for all , denoted .
We describe how to augment their data structure with first token queries, as pops can trivially be maintained with a separate counter for , initialized at 0. Note that Jiang and Gong [JG26] provide queries for all . Let denote the total number of characters pushed onto , including those that have been popped. Consider the tree whose nodes are indices and node has parent . Intuitively, node points to its parent, the last character of the token immediately preceding . Thus, if we wanted to compute the BPE output of , it suffices to follow the path from to the root of the tree .
Let be the number of characters popped so . Note that naturally correspond to indices in the input string. We abuse notation and let also denote the nodes in the tree corresponding to the indices . Our data structure maintains , and induced forest of on the nodes corresponding to indices , which we denote . Note that for any push, we only need to query from the Jiang and Gong [JG26] data structure, and add this node to (either to its parent if it is in the tree, or as the root of a new tree otherwise). We maintain using standard data structures (for example, an Euler Tour and efficient order queries using [DS87; Ben+02]) so that one can efficiently insert and delete nodes, and support queries of the form is a descendant of , and if so, what is the next vertex on that path? This allows us to support first token queries, as we can query whether is a descendant of . If so, report as the child of on the path form to (note that this could be itself), otherwise return . Finding the child of can be performed with binary search in time. Overall, this requires space , since we also use the data structure of Jiang and Gong [JG26].
Next, we give an efficient data structure for computing pretokens. Recall from the proof of Lemma 4.17, for an incrementally updated string : where or in which case . Here, indicates the start of the current “live” pretoken in .
Lemma 5.4. Given a total regular expression , there is a data structure cutQ that maintains implicitly an append-only string (of length ), and index . Denote
-
Split(x) = z₁ || ... || zₗ where zₙ = xₙ(j-1)+1 ... xₙ(j) for 1 ≤ j ≤ ℓ.
-
Split where .
Then, cutQ supports the following operations:
-
(Push) append c to .
-
(Pop) increment out by 1.
-
(Cut) if out = i, return i, otherwise return where .
-
(Base) return .
Furthermore, the data structure requires preprocessing, amortized update and query time and space.
Proof of Lemma 5.4. We will maintain a linked list that intuitively contains pretokens in Split where . We will also maintain a data structure that contains for some subset of , the tuple and . For the analysis, denote . Let be the state space of the DFA recognizing . We will ensure that contains at most tuples by ensuring that for every , we keep only where . This operation, which can be computed in time, is denoted trim(). At initialization, both . Upon receiving , run the following algorithm.
cutQ.push( )
-
For , update . trim( ).
-
Let .
-
If , let . Remove all from with .
(a) If , set .
(b) If , remove all where and insert to .
- Otherwise, if , add to and to .
(Totality ensures ).
- Remove from if .
cutQ.pop()
-
Increment out out + 1.
-
Remove any where .
We claim that the following hold after each update (push or pop):
-
If out = i, . Otherwise, where .
-
contains for every such that exists, a tuple , and no other tuples.
Before proving the invariants, we see that this efficiently supports the desired queries. Cut queries can be supported in time by examining the first element of (or returning if is empty). Base queries can be supported by computing in time. If the set is empty, we set . We claim that , since
When the set is empty, we have , as desired. It remains to prove that the above invariants hold, which we do so by induction. In the base case, before any operations, the invariants are trivially satisfied.
Consider a push operation of . There are two cases: either does not extend any existing pretoken, or it does.
In the former case, we have
Observe that since every , so we add to and to . This satisfies the first property.
Towards the second property, consider some and the minimum such that . We claim . Suppose , which covers all but the new singleton pretoken. Note that for any , if , then . Thus, at the start of the push, the same must have been the minimum with state . Thus, we have by induction. If , it must have been deleted by since and Step 3 does not run. This cannot happen, since is the minimum over all with . The unique is the new singleton pretoken, which we insert into .
Conversely, consider a tuple . Any tuple in is for some (since all pretokens from before the push survive). Suppose for contradiction that there is some with and . Take the minimum such . By the inductive hypothesis, was in before the push, so that is in , implying that is removed by trim(). This concludes the proof of the second property.
In the latter case, for some base, we have
By the choice of , it is the earliest old pretoken extended by . Since , its previous state is not dead as reading provides a nonempty accepting continuation. We claim that is present in before the push. Otherwise, the second invariant gives an earlier with . Then , so would extend the earlier pretoken , contradicting the choice of . Consequently, , and no earlier old pretoken start belongs to . Thus .
Towards the first property, we see that if , then satisfies the invariant. Similarly, if , we have , as desired.
Towards the second property, again consider some dead and the minimum such that . We claim . If not, following similar arguments as the previous case, it must have been removed either by trim( ) or Step 3. We have already argued that trim( ) will not remove the tuple, so we may focus on Step 3. Here, we only remove tuples where . Since all pretokens have , this cannot happen either.
Conversely, consider . If corresponds to a pretoken in Split, a similar argument to above proves that is the minimum among all tuples with state . However, it may now be the case that corresponds to some pretoken with . In this case, we have , so that Step 3 removes , as desired.
Finally, consider a pop operation. Note that out that does not affect the second invariant at all, so this remains satisfied. We remove all with out, so that the first interval in has out, as desired.
Performance It remains to bound the performance. Preprocessing is constant, since we just need to build the DFA and initialize . All queries require time, since we ensure has at most size . Each push and pop operation requires time for all operations that do not involve , again because . To bound the amortized update time, note that each iteration adds at most one interval, and each interval is removed at most once. Finally, we note that the space is .
We now use Lemma 2.4, Lemma 2.3, and Lemma 5.4 to prove Theorem 1.7, i.e. give an online tokenization algorithm with constant delay. We begin by describing the data structures our algorithm will use. We initialize cut, out 0. We ensure that out maintains the last index in the output and cut to maintain the end of the pretoken containing out in , i.e. the current pretoken being output if the input were to immediately terminate.
We maintain a raw string buffer buffer that supports push and pop. We initialize empty bpeQ and incBPE data structures. We initialize cutQ with out 0 (the same out as the counter). Whenever out is incremented, we accordingly pop from cutQ. When a data structure is used as an input, this denotes reading the string maintained by the structures. When pop is supplied with an integer argument p, we pop p items. When push is supplied with a string, we push the string character by character. For each character in the input, do the following:
OptimalDelayTokenization( )
-
Push to bpeQ, cutQ, and buffer.
-
If cutQ.cut > cut:
(The current pretoken containing out extends.) Push incBPE.push(buffer.pop(cutQ.cut - cut)). Update cut ← cutQ.cut.
- While cutQ.base > out: (Cannot extend the current pretoken containing out. Process dead pretokens, and find the next live pretoken. Compare to Step 3 of FastPretokenization.)
(a) Push incBPE.push( || ). (b) While incBPE ≠ ε: Output φ ← incBPE.φ. Update bpeQ.pop(|φ|), incBPE.pop(|φ|), and out ↔ |φ|. (Compute BPE on the current dead pretoken with incBPE.)
(c) Push incBPE.push(buffer.pop(cutQ.cut - cut)). (d) Update cut ← cutQ.cut. (Move the next pretoken to incBPE.)
-
While incBPE.φ = bpeQ.φ ≠ ⊥: (a) Output φ ← incBPE.φ. (b) Update bpeQ.pop(|φ|), incBPE.pop(|φ|), and out ↔ |φ|. (When incBPE and bpeQ agree, incBPE.φ extends the stable prefix.)
-
If incBPE = ε and out < i: (Load the next pretoken into incBPE.)
(a) Push incBPE.push( || buffer.pop(cutQ.cut - cut)). (b) Update cut ← cutQ.cut and go to Step 4.
When out < i, write Split( ) = Q where with and . Above, are the pretokens in if the input were to immediately terminate. We use to denote the concatenation of pretokens , so that is indeed the longest accepting prefix in for each . Define and for each , so that . Index the pretokens so that ; thus contains the first un-emitted character. When out = i, no such is needed.
We now make the following claim at after processing each input :
-
buffer maintains .
-
bpeQ maintains .
-
incBPE explicitly maintains . Consequently, out cut.
-
The output y of the algorithm satisfies .
-
If out < i, then and . If out = i, then .
-
out .
Trivially, the conditions are satisfied at initialization. Observe that cut, out are monotonically non-decreasing. To prove the first three properties, note that (1) is always pushed onto buffer, bpeQ, (2) we always push and pop cutQ.cut – cut elements from buffer to incBPE and increment cut by the same amount, and (3) we always increment out by , which is popped from bpeQ and incBPE. Similarly, the fourth property follows as every output is accompanied by a corresponding increment to out.
Next, we argue the fifth property. If out = i, the third property and cut ≤ i give cut = i. Otherwise, holds by definition. We argue cut = . After Step 2 and Step 3, cut = by correctness of Lemma 5.4, since we query cutQ.cut after any pushes and pops (i.e. increments to out). In Step 4, we increment out, but as long as incBPE , we still have out < cut = by the third property, in which case does not change and cut does not need to be updated. On the other hand, whenever incBPE = , in Step 5 we recompute cut cutQ.cut = by the correctness of Lemma 5.4.
Finally, we argue out cutQ.base = b(i). In Step 3, we already have cutQ.base = b(i). Thus, as long as the while loop terminates (which we will show later), we must have out b(i).
We are now ready to prove correctness, and proceed with the inductive claim that the output y satisfies
We argue inductively over individual token emissions within each input iteration. Thus, before considering the next emission, we may assume that the output already produced is a stable prefix.
We first justify first-token queries to incBPE. Consider a query with out < cut, and let be the string maintained by incBPE. Let be the position such that incBPE implicit hidden history is , possibly followed by a trailing separator at cut. We denote .
Observe that both and out are token boundaries in the tokenization of the current input: is either a pretoken boundary or a boundary of the already-emitted stable output, and out is the end of that output. The block lies within a single pretoken of the current Tok() tokenization: it is loaded within one pretoken, and later longest-match extensions can only preserve or join existing pretokens. Thus and out are surviving token boundaries within that pretoken, so Claim 5.2 gives Merge() = Merge() Merge(). Since the implicit hidden history of incBPE is ... , we have Merge() Merge() and Lemma 2.3 applies. In particular, since the first token query condition is satisfied,
Beginning with soundness, it is clear that if we do not output any tokens after reading , then the output is a stable prefix by induction as
Suppose a token is output in Step 3 (i.e. cutQ.base > out). By the correctness of Lemma 5.4, we have cutQ.base = b(i) so that . Following the proof of Lemma 4.17, write
where for some , we have , , and for . Following our above notation, we have . Then, observe
Consider an iteration of Step 3. Since out < b(i), the current pretoken ends at cut ≤ b(i), so this pretoken is output by Split_ and is unchanged under every continuation. By (5), the query returns , the next token of the current pretoken. Since the already-emitted output is stable, this is also the next token under every continuation. Thus each emission preserves soundness, and the argument applies again after updating out.
Upon exiting Step 3, we have out = b(i), and the emitted prefix is the following stable prefix:
Now suppose a token is emitted in Step 4. Write , where . By (5) . Also, bpeQ maintains and so .
Fix any continuation . If no pretoken extends, or the first pretoken that extends occurs strictly after , then is unchanged. The next token is therefore .
Otherwise, let , with , be the first pretoken that extends. Because its longer match was unavailable before reading , the new match ends strictly after position . Consequently, this pretoken has raw string for some nonempty prefix . The remaining suffix of may form further pretokens.
By the inductive stability of the emitted output, the boundary at out survives within this extended pretoken. In particular, we have
By Claim 5.1,
Thus is the next token for every continuation and emitting it preserves soundness.
Finally, we prove completeness, i.e. (Merge ○ Split) . As in the proof of soundness, we note that after exiting Step 3, we have out . We may assume without loss of generality that out , as otherwise Claim 4.21 already bounds the delay by 3mt.
Thus . At termination, Step 5 ensures that incBPE is nonempty, since out < i. Define
The first equality is justified by (5). Both queries are non-bottom, so termination of Step 4 implies . Since , there is a live pretoken with
Choose a nonempty continuation such that . Note that all pretokens preceding are dead, while is accepted as a single pretoken under the continuation .
For the empty continuation, the next token after the already-emitted output is . For continuation z, the boundary at out survives by soundness. The next token is
where the first equality follows from Claim 5.1. Hence, if P denotes the already emitted output,
Because , these two tokenizations have longest common prefix exactly . Together with soundness, this proves
In particular,
as required.
Termination Condition. It remains to prove that the algorithm terminates on each iteration. Step 3 terminates since out increases in every iteration of the while loop. In particular, since out < b(i), we have out < r(0) so that incBPE is not empty. Step 4 terminates as each iteration pops at least 1 character from both incBPE and bpeQ, so the loop must terminate when |bpeQ| < 3mt. Step 5 must terminate whenever Step 4 terminates with a mismatch, in which case incBPE ≠ ε. Otherwise, we increment cut until eventually out = i, and the algorithm terminates.
Performance Finally, we bound the space and runtime of our algorithm. To bound the space, we observe that similar to Lemma 4.17, we can bound the space of cutQ by . This follows as
The first inequality follows from the fact that if out < - 3mt, then bpeQ and incBPE share a prefix of length at least 3mt, so that Step 4 will output a token. The second inequality follows from the definition of . Similarly, the space of bpeQ and incBPE is . The space of buffer is as .
To bound the time, our algorithm does work per input in addition to various calls to the data structures. Combining Lemma 2.3, Lemma 2.4, and Lemma 5.4 gives an algorithm with preprocessing and total time. This concludes the proof of Theorem 1.7.
6 Experimental Setup
We compare our end-to-end tokenizer on a selection of encodings from tiktoken [Ope26a] and tokenizers [Hug26]. Our code can be found at https://github.com/morganstanley/MSML/tree/main/papers/Online_Tokenization_with_Optimal_Delay_in_Near_Linear_Time.
We test our tokenizer on similar datasets as Jiang and Gong [JG26]. In particular, we use the following three datasets:
-
English and Chinese - We utilized the first Parquet shard from the standard training split of the Wikipedia dataset (20231101 dump) [Wik23]. The filtered dataset is obtained by a strided sampling strategy. For English, we keep documents 0, 5, 10, and 16 in every block of 21 documents. For Chinese, we keep documents 0 and 6 in every block of 13 documents.
-
Github - We extracted data from the RedPajama GitHub subset [Tog23], specifically using the file with the filename "filtered_08cdfa755e6d4d89b673d5bd1acee5f6.sampled.json1". The filtered dataset contains every 17th document.
All experiments were conducted on an Intel Xeon Platinum 8462Y+, comprising 32 cores. All computations were performed exclusively on the CPU and executed on a single core. The system was otherwise idle during benchmarking, with no other user processes competing for CPU resources.
6.1 Applications: R50K, CL100K, and O200K
We study the full R50K, CL100K, O200K reference patterns below. The three patterns: R50K (used by both R50K and P50K encodings), CL100K, and O200K are given below:
R50K = r'' (? : [sdmt] | 11 | ve | re) | ?\p{L}+ | ?\p{N}+ | ?[^s\p{L}\p{N}]+ | \s+(?!\S) | \s+;
CL100K = concat! ( r'' (?i : [sdmt] | 11 | ve | re) | [^-r\n\p{L}\p{N}]?+\p{L}++ | \p{N}{1,3}+ | ", r" ?[^s\p{L}\p{N}]++[\r\n]+| \s++$ | \s[\r\n] | \s+(?!\S) | \s" );
We note that we do not explicitly compare our tokenizer against Jiang and Gong [JG26], since their code supports only BPE, whereas our goal is to benchmark the full end-to-end tokenization pipeline.
0200K = concat!( r"[^r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}][\p{Ll}\p{Lm}\p{Lo}\p{M}]", r"+(?:'s|'t'|re|'ve|m'|ll|'d)?", r"[^r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]", r(?i:'s|'t'|re|'ve|m'|ll|'d)?", r|\p{N}{1,3}", r| ?[^s\p{L}\p{N}]+[\r\n/]", r|\s[\r\n]+", r|\s+(?!S)", r|\s+" );
Each regex is an alternation of several cases. We explain some of the illustrative cases below (focusing on R50K and CL100K, the interested reader is encouraged to investigate in detail with a tool such as https://regex101.com).
-
r"(?i:[sdmt]|ll|ve|re)" matches common apostrophed suffixes such as "ll".
-
r" ?\p{L}+" matches consecutive letters with optional leading whitespace, e.g. " hello".
-
r" ?\p{N}+" matches consecutive digits with optional leading whitespace, e.g. " 123". We note that CL100K caps the length of a run of digits at 3.
-
r" ?[^s\p{L}\p{N}]+" matches consecutive symbols with optional leading whitespace e.g. " !?!?".
-
r"\s+(?!S)" matches consecutive white space such that the next character is a space or end of input.
-
r"\s+ as a special character to denote EOF.
-
r"\s*[\r\n]" matches consecutive whitespace ending in a newline.
-
r"\s+" and r"\s" matches consecutive whitespace and single whitespace respectively.
In these reference patterns, matching is computed in order of priority, then length. In particular, given a regular expression the first match of in , denoted is defined as where
.
That is, instead of just taking the longest prefix that matches any rule, we take the highest priority rule that has any match with a prefix of x, and the longest match under that rule. We observe that given the left-to-right priority of the alternation rules in the regex pattern, a string is accepted by a rule if (1) it matches the pattern of that rule and (2) it has no prefix that matches any higher priority rule. Note that (online) pretokenization (Definition 4.2) is defined identically, replacing F with .
Beyond left-to-right priorities, practical patterns also implement the lookahead operations. In particular, CL100K and O200K contain the rule r"\s+(?!S)" which matches runs of whitespace that are followed by whitespace or end of input (but not runs of whitespace followed by a non-whitespace character). In this case, a DFA may need to scan ahead by one character to accept a prefix. For example, if , the DFA must scan "\t\t\t" before accepting "\t\t". We note that even with the priority rules and lookahead operation the CL100K and O200K examples can still be represented with simple DFAs (see Section A). In our examples, the DFA needs to scan ahead by at most one character.
With both priority and lookahead, let be the prefix of matched by incorporating all priority and lookahead rules. Define .
In view of priority and lookahead, we give a generalized definition of lookback (Definition 4.3).
Definition 6.1. A regular expression has -generalized-lookback if for any and , .
First, one can see that when has no priority rules (i.e. just one rule) and no lookahead, is only non-zero when , in which case is exactly the longest match among strict prefixes, so that .
For the reference patterns considered here, we adapt the simple backtracking algorithm of Lemma 4.16 to compute pretokenization on a pattern with priority rules and one character lookahead. When is finite, a similar proof can show that the structure of the DFAs ensure that each restart reprocesses only characters. Charging each restart to progress through the input gives total time. We use this approach in practice because it is simple and avoids the overhead of the more general data structure in Lemma 4.17. We further justify this choice by showing that in most practical cases, is small.
Claim 6.2. The R50K pattern satisfies .
Proof of Claim 6.2. Appending a character can extend an existing run of letters, digits, or symbols by at 1. For runs of letters and numbers, appending a character cannot lead to a match with a higher priority rule. On the other hand, an initial apostrophe could be extended to a contraction e.g. " 's", which extends the match by at most 1. Finally, note that a character can extend the match to a contraction, for example,
For a run of whitespace, appending a non-whitespace character can shorten the first match by one character because of the lookahead rule, or extend the match to a higher priority rule by at most one character. Appending a whitespace character on the other hand, can extend the match by at most one character. This exhausts all the cases.
Claim 6.3. The CL100K and O200K patterns have unbounded .
Proof of Claim 6.3. It suffices to produce a single accepted string where any proper prefix that is also accepted is much shorter.
Consider CL100K. For any , consider and to be any letter so that matches the pattern Item 7 and . On the other hand, matches the pattern Item 6 and . This establishes a gap of size .
For O200K, we consider a similar string and . Note that is accepted by the (7) (i.e. the fifth rule of O200K, but any length > 1 prefix of is not accepted: the first rule it matches, either (5) or (8), is lower priority than (7), which is matched by the prefix " ". Thus, as well.
However, given that CL100K and O200K only have unbounded lookback on relatively rare outputs (basically files that are all whitespace), all three patterns have lookback that are typically much smaller than input size on normal text.
6.2 Optimization
We now describe some optimizations in our code to improve the practical efficiency of our algorithm.
Chunk Size We read input in fixed-size chunks to amortize input overhead, observing that chunks of 64KiB (or larger) are most efficient in practice. The read chunk size controls input batching. For each chunk, the unresolved suffix may contain a candidate pretoken that is retained until it is resolved by reading the next chunk.
Pretokenization Algorithm We remark that in practice, the simple backtracking algorithm for online pretokenization that requires time is more efficient than the time algorithm given by Lemma 4.17. In particular, the overhead of the linear-time algorithm depends on the size of the regular expression, which is typically larger than the overhead incurred by backtracking (since in practice is often very small, see e.g. Claim 6.2).
BPE Algorithm. To favor throughput, our implementation invokes the incremental (but not online) BPE algorithm of Jiang and Gong [JG26], which only merges after a pretoken boundary is resolved. This is consistent with Jiang and Gong [JG26], which observe that the online BPE algorithm is slower in practice. The implementation therefore differs here from the theoretical composition algorithm, which emits accepted prefixes of candidate pretokens to an online BPE merging algorithm. The practical implementation can consequently (in the worst case) retain an arbitrarily long unfinished pretoken and defer applying BPE to merge this pretoken until the pretoken is complete. Its worst-case memory and latency can therefore depend on pretoken length, even for patterns with bounded lookback. We note that for the implemented regular expressions, this scenario typically does not occur on natural language, evidenced by the memory and latency advantages of our implementation.
Linear Buffering Suppose that we have read in a chunk into a buffer, and our online tokenization algorithm has decided that some small prefix of the chunk can be stably tokenized and emitted as output. We now need to remove this prefix on the chunk and recurse the tokenizer on the remaining suffix. Naively draining the buffer (e.g. std::String::drain) after each token is emitted requires linear time, since we shift the entire array of characters forwards. Since tokens are typically much shorter than a chunk, this requires time that is quadratic in the chunk size. Instead, whenever we emit a token, we simply advance a counter on the buffer to mark which characters have been successfully processed. At the arrival of a new chunk, we keep the last trailing token (typically quite short) and drain the processed prefix in time linear in the chunk size.
DFA Implementation A key optimization of our code is a faster implementation of the regular expression matching required by pretokenization. Indeed, regex parsing is the dominant cost of tokenization (see OpenAI [Ope26b]). Instead of directly implementing the pretokenization patterns (e.g. R50K, CL100K) as a DFA, we use a combination of (1) a simpler pattern that can be efficiently implemented as a DFA, and (2) an auxiliary ApplyFixup function that ensures our algorithm exhibits identical behavior to a DFA directly implemented on the original pattern.
We note that the choice of DFA implementation (either the lazy DFA or dense DFA in regex_automata) once the pattern is fixed does not lead to any significant differences in performance. Furthermore, since we work exclusively with total regular expressions, we use anchored DFAs, which ensure that the first character is matched (removing the overhead caused by searching for alternative starting characters). In Section 6.3, we present theoretical and empirical evidence that our alternative implementation is in fact equivalent to a direct implementation of the DFA.
Segmenting Finally, we optimize the special token segmenting. Since special tokens typically start with the same character (e.g. <) and this character is relatively rare in natural text, we use memchr [Bur26], an optimized library for string search in Rust to efficiently find instances of the starting characters.
6.3 Data Validation: DFA Optimization
For tiktoken, we provide theoretical and empirical evidence that our DFA optimizations preserve the same pretoken matching and splitting as the reference patterns. We consider the R50K, CL100K, and O200K, beginning with their simplified forms.
R50K_SIMP = r" (?:[sdmt]|11|ve|re) | ?\p{L}+ | ?\p{N}+ | ?[^s\p{L}\p{N}]+|\s+";
CL100K_SIMP = concat!( r" (?i:[sdmt]|11|ve|re) | [^-r\n\p{L}\p{N}]? \p{L}+ | \p{N}{1,3}|", r" ?[^s\p{L}\p{N}]+[\r\n]|\s[\r\n]|[^S\r\n]+" );
Similarly to R50K, the simplified O200K pattern is identical to the reference O200K pattern with the r"\s+(?!\S)" rule removed. The ApplyFixup function is described as follows. Every time the DFA finds a resolved match in the substring (in the language of Lemma 4.17, this corresponds to outputting ), we call the ApplyFixup function on the candidate pretoken. Note that if we reach the end of the current chunk in buffer and the DFA is not in an or dead state, we simply suspend the DFA computation until the arrival of the next chunk and do not call ApplyFixup.
ApplyFixup()
-
Input: remaining input and candidate boundary .
-
extend: if is a newline, is all whitespace, and the remaining suffix of through EOF is all horizontal whitespace, then extend the pretoken to the end of the buffer (equivalently return ). (extend is only applied for the CL100K pattern.)
-
trim: if and is whitespace, and next character is not whitespace, then return .
(for the CL100K and O200K patterns, we check if is horizontal whitespace.)
- Otherwise, return .
We now show that the simplified patterns along with ApplyFixup as described above is equivalent to the original pattern.
Proof of Equivalence Observe the following crucial property of Split: any algorithm that successfully computes immediately gives an algorithm that computes Split. The proof is essentially immediate from the definition of pretokenization (see Definition 4.2). Recall that given a string and a total expression , is the first match of in starting at the first character. Note .
Claim 6.4 (Local Reduction). Let be a total regular expression. Suppose there is a function such that for all . Then, and for computes Split() for all .
Thus, it suffices to argue that the first match is identical for all strings. Before doing so, we formally describe our algorithm FastMatch(). For regular expression (e.g. R50K), let denote the simplified pattern.
FastMatch()
-
Input: string .
-
If , return .
-
Compute .
-
Output ApplyFixup().
Proposition 6.5. For all and pattern in R50K, CL100K, and O200K, we have
Proof of Proposition 6.5. We analyze each pattern separately, beginning with R50K.
R50K. Note that the first four rules are identical in the original and simplified patterns. None of these patterns trigger the trim subroutine of ApplyFixup, since the last character is not a whitespace. Therefore, the returned match is identical, if original pattern first matches one of these rules.
Suppose the fifth rule r"\s+(?!\S)" matches in the original pattern. Let be the maximal initial run of whitespace. If reaches EOF, both the original and simplified patterns match all of , and trim does not trigger because there is no following character. Otherwise, is followed by a non-whitespace character. For the fifth rule to match, , and the original pattern matches without its final character. The simplified pattern matches all of , and trim removes its final character, yielding the same match.
Finally, suppose the sixth rule matches in the original pattern. Since the fifth rule did not match, the initial whitespace run consists of a single character followed by a non-whitespace character. This whitespace cannot be a literal space, since one of the preceding letter, number, or symbol rules would then match. The simplified pattern matches the same single whitespace character, and trim does not trigger because the candidate has length one.
CL100K. Consider now CL100K. The first rule is identical in the original and simplified pattern. For the second, third, and fourth rules, we claim that removing the possessive quantifier "+" does not change the match. First, a general characterization of when possessive quantifiers change the output of a match.
Claim 6.6. Let be disjoint sets of literals in . Consider a regular expression , defined by and , defined by . If and , then for all .
Proof of Claim 6.6. We begin with a brief refresher on possessive quantifiers (see e.g. Oracle [Ora24] and Regular-Expressions.info [Reg25]). Given a pattern r"A++B", a possessive quantifier tries to (1) find the longest match satisfying r"A+", and (2) the longest match of r"B" in the remaining string. If no such match exists, then the possessive quantifier reports that no match is found. In contrast, if no such match exists, the greedy quantifier given by r"A+B" backtracks to the next longest prefix matching r"A+", and attempts to match r"B" from there. As an example, r".++x" would fail to match "abcx", since (1) matches the whole string leaving no characters for (2), whereas r".+x" would find a match by backtracking one character.
Suppose for contradiction that for some . Let be the longest prefix match of in . Then, there is no match for in . On the other hand, there is a prefix such that contains a match for . In particular, a prefix of is a suffix of , a contradiction since and are over disjoint sets of literals.
Claim 6.6 applies to the possessive symbol run followed by the disjoint newline class in the fourth rule. In the second rule, the optional possessive prefix excludes letters, so giving back its character cannot enable the following letter match. The bounded digit pattern in the third rule and the remaining possessive quantifiers in these three rules occur at the ends of their rules, where no subsequent sub-pattern can require backtracking. Thus removing the possessive modifiers preserves the matches of the second, third, and fourth rules.
Consider the fifth rule (6). In this case, the simplified pattern matches (7) or the final case of all horizontal whitespace. In the former case, we trigger extend since the match ends with a newline, is all whitespace, and the remaining string is all whitespace, so we extend the pretoken to the whole string. In the latter case, the entire input string is all horizontal whitespace followed by EOF, so that neither extend or trim trigger, and we return the full matched string, as desired.
For the sixth rule, observe that the sixth rule occurs in the simplified string, and since we did not match the fifth rule, extend will not trigger since the remaining string is not all whitespace. Since is not horizontal whitespace, trim does not trigger either.
Consider the seventh rule, i.e. a run of whitespace with no newlines (since the sixth rule did not match) such that the following character is a horizontal whitespace (but there is some non-whitespace character afterwards since the fifth rule did not match). In this case, we match the last rule of the simplified pattern (which matches all runs of horizontal whitespace). Since we matched also the trailing horizontal whitespace trim will remove this to produce an identical match to the original pattern.
In the final rule, we have a single whitespace character; a similar argument follows as in the last rule of R50K.
O200K. As with R50K, the simplified pattern and the original pattern are identical for the first five rules, so we may assume that the first match does not involve the first five rules. The fifth rule did not match, hence the run contains no newline. In particular, we may assume that the first match is all horizontal whitespace.
Suppose the original pattern matches the sixth rule ". Let be the maximal initial run of horizontal whitespace. If reaches EOF, both patterns match all of , does not trigger. Otherwise, is followed by a non-whitespace character. The sixth rule can match only if , in which case it matches without its final character. The simplified pattern matches all of , and removes its final character, yielding the same match.
Finally, suppose the original pattern matches the seventh rule. Since the sixth rule did not match, the initial run consists of a single horizontal whitespace character followed by a non-whitespace character. The simplified pattern matches this same character, and trim does not trigger because the candidate has length one. This concludes the proof.
Next, we verify the correctness of our algorithm empirically by enforcing equal output with reference tokenizers on test datasets.
Empirical Validation: Equivalence on Datasets Finally, we ensure that our algorithm's output is byte-identical to tiktoken and tokenizers on the three given datasets (English, Chinese, and Github). We also empirically verify that our implementation is byte-identical to tiktoken and tokenizers on a large number of short strings.
7 Experimental Results
We now present the results of our empirical evaluations.
7.1 Time to First Token
Next, we measure the time to first token (TTFT), a key metric in streaming and online applications. For each tiktoken encoding and dataset, we ignore encoder construction time, and measure the time from when the input is provided to the encoder to when the first token is formed. Note that we measure the time to when the first token is formed, not when it is output, since both tiktoken and gigatoken do not output any tokens until all tokens are formed. For our tokenizer, we provide the input as a file, so that input-reading time is included. For tiktoken and gigatoken, we provide the string as input in memory, thus excluding input-reading time. We note that tiktoken and gigatoken do not natively provide support for TTFT profiling: we make minimal changes to their code to allow for this measurement, as the alternative simpler method of measuring TTFT as the total time of encoding excessively advantages our algorithm (see code for details). TTFT results are provided in Table 3.
7.2 Memory
Next, we examine the memory required by each tokenizer. For each encoding and dataset, we measure the peak RSS (Resident Set Size) required by tokenization for input sizes of 1, 2, 4, 8, 16, 32, 64, 128 MiB. We invoke tiktoken, tokenizers and gigatoken through their public APIs, which produce the output as an array in memory. Recall that our algorithm streams an input file of characters to an output file of tokens. The peak RSS is plotted against input size on a log-log scale. Across the evaluated datasets of size 1–128 MiB, our implementation exhibits approximately constant peak RSS, while existing tokenizers show memory growth with input size. Note that on small inputs, our algorithm will incur large RSS relative to tiktoken but still smaller than gigatoken due to initialization costs.
7.3 Throughput Comparison
Finally, we measure throughput. The size of each dataset is approximately 128 MiB. For every dataset and every tiktoken encoding, we compare the throughput between tiktoken and our tokenizer. For every dataset and every tokenizers model, we compare the throughput between tokenizers and our tokenizer.
Table 3: Time to first token (TTFT) of all comparison of all tokenizers on tiktoken encodings measured in milliseconds (ms). We report the median TTFT over 30 runs for each row with upper and lower quartiles in the parentheses.
| Encoding | Dataset | tiktoken | gigatoken | Ours | Speedup |
|---|---|---|---|---|---|
| r50k | Github | 10.91 (10.89-16.77) | 10.70 (10.67-10.74) | 0.49 (0.45-0.56) | 21.7× |
| r50k | English | 10.95 (10.94-10.99) | 10.86 (10.85-10.89) | 0.61 (0.51-0.84) | 17.8× |
| r50k | Chinese | 11.04 (11.00-11.11) | 50.24 (46.48-172.62) | 0.77 (0.72-0.85) | 14.3× |
| p50k | Github | 10.88 (10.86-10.91) | 10.70 (10.68-10.72) | 0.56 (0.49-0.61) | 19.2× |
| p50k | English | 10.95 (10.93-10.99) | 10.83 (10.81-10.86) | 0.53 (0.47-0.68) | 20.3× |
| p50k | Chinese | 11.01 (10.99-11.04) | 46.63 (31.03-64.26) | 0.80 (0.72-0.87) | 13.8× |
| c1100k | Github | 19.93 (19.91-19.96) | 18.21 (18.19-18.23) | 0.52 (0.47-0.56) | 34.8× |
| c1100k | English | 6.44 (6.41-6.46) | 6.96 (6.92-7.00) | 0.58 (0.50-0.70) | 11.1× |
| c1100k | Chinese | 6.51 (6.50-6.54) | 236.34 (233.10-238.22) | 0.82 (0.77-0.86) | 7.9× |
| o200k | Github | 10.62 (10.61-10.67) | 18.78 (18.73-18.82) | 0.60 (0.56-0.66) | 17.8× |
| o200k | English | 10.95 (10.92-10.97) | 7.03 (6.96-7.05) | 0.60 (0.51-0.72) | 11.8× |
| o200k | Chinese | 10.99 (10.98-11.02) | 235.69 (94.11-239.96) | 0.88 (0.78-0.90) | 12.5× |
For both tiktoken and tokenizers, input is provided as a string in memory, while output is given as an array in memory. For our algorithm, input is provided as a file path and output is streamed to a temporary file. For the throughput benchmarking, output is streamed to a temporary file (tmpfs) backed by memory instead of an actual file on disk. In particular, the cost of reading and writing the input and output file is factored into the throughput of our algorithm. Note that encoder construction time is not timed. We measure performance of the encoding function itself. Table 4 shows the throughput comparison on tiktoken encodings and Table 5 shows the throughput comparison on tokenizers encodings. Our algorithm significantly outperforms tiktoken, achieving throughput speedups of depending on the encoding and dataset. We achieve a more dramatic speedup over tokenizers, with speedup factors between .
7.3.1 Comparison with gigatoken
Recently, the release of the gigatoken tokenizer presents a parallelized tokenizer that achieves significant throughput speedups over previous tokenizers [Rød26]. At a high level, gigatoken uses the following ideas to dramatically speed up tokenization:
-
Parallelism - Rød [Rød26] attempts to process a batch of files or a single file in parallel. In order to break up a single file, one can attempt certain heuristics to split up a large file based on known priors for pretokenization. For example, examining the tiktoken patterns, if we find a space between two words (a fairly common occurrence), we can safely split a file at this space.
-
Optimized Pretokenization - Using SIMD and many other tricks, Rød [Rød26] drastically reduces the workload of pretokenization, which is typically deferred to a regex engine.
-
Caching - In order to avoid repeatedly merging the same pretoken, Rød [Rød26] maintains a cached mapping from pretokens to tokens. While some form of caching is already implemented in tiktoken, Rød [Rød26] uses a heavily optimized cache to improve performance.
r50k / github: peak RSS vs input size Median with p25-p75 error bars

(a) r50k peak RSS vs. input size
p50k / github: peak RSS vs input size Median with p25-p75 error bars

(b) p50k peak RSS vs. input size
cl100k / github: peak RSS vs input size Median with p25-p75 error bars
o200k / github: peak RSS vs input size Median with p25-p75 error bars

(c) cl100k peak RSS vs. input size

(d) o200k peak RSS vs. input size
Figure 2: Peak RSS vs. input size on Github datasets. The blue line is tiktoken, the green line is gigatoken, while the red line is our algorithm.
To make a fair comparison with gigatoken in the streaming and online settings which are inherently sequential, we compare with the serial implementation of gigatoken (the package already provides such an option by setting parallel=False). Furthermore, we note that given the above tricks to split a single file or a batch of files, one can easily obtain a parallel algorithm by applying an optimized serial tokenizer to each part of the resulting split. Regarding the optimized pretokenization and caching, we observe that many optimizations remain compatible with an online framework, particularly composition: one can replace our DFA-based pretokenization algorithm with the SIMD-optimized pretokenization, and one can incorporate an optimized pretoken caching policy into any online BPE algorithm. We note that our original algorithm, identically to tiktoken, maintains a cache of all pretokens that map directly to tokens, and thus maintains a cache of approximately size . The cache of gigatoken instead caches all observed pretokens, thus resulting in a cache that grows with input size in the worst case. In particular, after incorporating the more aggressive caching policy which caches all pretokens, online tokenization will no longer maintain a constant memory footprint independent of input size.
In Table 6, we compare the throughput of tiktoken, gigatoken, and two implementations of our algorithm with optimized pretokenization and caching from Rød [Rød26]. Both our algorithm and gigatoken are provided with a file path as input and supports two output types: an array in memory, and a written output file (for the benchmark, we use a temporary file backed by RAM to avoid blocking on disk). Since gigatoken does not support streaming, we write the array to file after output. On array output, we attain similar performance to gigatoken, producing lower throughput on English and code datasets, while producing higher throughput on Chinese. The more aggressive caching policy can use increasing memory as r50k / english: peak RSS vs input size Median with p25-p75 error bars

(a) r50k peak RSS vs. input size
p50k / english: peak RSS vs input size Median with p25-p75 error bars

(b) p50k peak RSS vs. input size
c1100k / english: peak RSS vs input size Median with p25-p75 error bars
o200k / english: peak RSS vs input size Median with p25-p75 error bars

(c) c1100k peak RSS vs. input size

(d) o200k peak RSS vs. input size
Figure 3: Peak RSS vs. input size on English datasets. The blue line is tiktoken, the green line is gigatoken, while the red line is our algorithm.
additional distinct pretokens are encountered. Our DFA-based implementation voids this growing pretoken cache, but its input buffer can still grow with an unfinished pretoken (as discussed earlier).
Statement on AI Usage
For our theoretical results, generative AI was particularly useful in designing the reduction behind Theorem 1.1. For our empirical results, essentially all of our code was implemented by AI. The code was reviewed and manually verified. For our DFA algorithm, the main empirical contribution of this work, the code was written by AI but we manually prove the correctness of the key optimization (DFA simplification, see Section 6). We take responsibility for the final content of this work, including text, claims or artifacts produced with the aid of generative AI.
References
[AC75] Alfred V. Aho and Margaret J. Corasick. "Efficient string matching: an aid to bibliographic search". In: Communications of the ACM 18.6 (1975), pp. 333–340. DOI: 10.1145/360825.360855 (cit. on pp. 26, 28).
[Aho+06] Alfred V. Aho et al. Compilers: Principles, Techniques, and Tools. 2nd. Pearson/Addison-Wesley, 2006 (cit. on p. 10).
r50k / chinese: peak RSS vs input size Median with p25-p75 error bars

(a) r50k peak RSS vs. input size
p50k / chinese: peak RSS vs input size Median with p25-p75 error bars

(b) p50k peak RSS vs. input size
cl100k / chinese: peak RSS vs input size Median with p25-p75 error bars
o200k / chinese: peak RSS vs input size Median with p25-p75 error bars

(c) cl100k peak RSS vs. input size

(d) o200k peak RSS vs. input size
Figure 4: Peak RSS vs. input size on Chinese datasets. The blue line is tiktoken, the green line is gigatoken, while the red line is our algorithm.
[AMS96] Noga Alon, Yossi Matias, and Mario Szegedy. “The Space Complexity of Approximating the Frequency Moments”. In: Proceedings of the 28th Annual ACM Symposium on Theory of Computing (STOC). 1996, pp. 20–29 (cit. on p. 1).
[Ben+02] Michael A Bender et al. “Two simplified algorithms for maintaining order in a list”. In: European symposium on algorithms. Springer. 2002, pp. 152–164 (cit. on p. 32).
[Bur26] BurntSushi. memchr 2.8.2. https://docs.rs/memchr/latest/memchr/. Docs.rs documentation. Accessed 26 June 2026. 2026 (cit. on p. 41).
[Bv23] Martin Berglund and Brink van der Merwe. “Formalizing BPE tokenization”. In: arXiv preprint arXiv:2309.08715 (2023) (cit. on pp. 1, 26, 29).
[DF03] Marianne Durand and Philippe Flajolet. “Loglog Counting of Large Cardinalities”. In: Proceedings of the 11th Annual European Symposium on Algorithms (ESA). 2003, pp. 605–617 (cit. on p. 1).
[DPV19] Davide Della Giustina, Nicola Prezza, and Rossano Venturini. “A new linear-time algorithm for centroid decomposition”. In: International Symposium on String Processing and Information Retrieval. Springer. 2019, pp. 274–282 (cit. on p. 50).
[DS87] Paul Dietz and Daniel Sleator. “Two algorithms for maintaining order in a list”. In: Proceedings of the nineteenth annual ACM symposium on Theory of computing. 1987, pp. 365–372 (cit. on p. 32).
Table 4: Throughput comparison of our tokenizer on tiktoken encodings measured in MiB/s. tiktoken is provided with a string as input and gives an array as output, both in memory. Our algorithm is provided with a file path as input and writes output to file. We report the median throughput over 10 runs for each row with upper and lower quartiles in the parentheses.
| Encoding | Dataset | tiktoken | Ours | Speedup |
|---|---|---|---|---|
| r50k | Github | 11.3 (11.3-11.3) | 43.6 (43.5-43.7) | 3.9× |
| r50k | English | 17.8 (17.7-17.8) | 47.7 (47.4-48.3) | 2.7× |
| r50k | Chinese | 15.0 (14.9-15.0) | 38.0 (38.0-38.1) | 2.5× |
| p50k | Github | 10.8 (10.8-10.8) | 45.0 (44.7-45.2) | 4.2× |
| p50k | English | 18.0 (17.9-18.0) | 49.2 (48.8-49.4) | 2.7× |
| p50k | Chinese | 15.0 (14.9-15.0) | 36.6 (36.5-36.7) | 2.4× |
| c1100k | Github | 11.1 (11.1-11.1) | 48.4 (48.1-48.6) | 4.4× |
| c1100k | English | 15.5 (15.4-15.6) | 45.3 (44.3-46.4) | 2.9× |
| c1100k | Chinese | 13.6 (13.6-13.6) | 37.6 (37.5-37.6) | 2.8× |
| o200k | Github | 7.8 (7.7-7.8) | 54.8 (54.7-55.0) | 7.0× |
| o200k | English | 8.7 (8.7-8.7) | 41.5 (41.3-41.7) | 4.8× |
| o200k | Chinese | 9.9 (9.9-9.9) | 36.5 (36.2-36.9) | 3.7× |
[Fla+07] Philippe Flajolet et al. “HyperLogLog: The Analysis of a Near-Optimal Cardinality Estimation Algorithm”. In: Proceedings of the 2007 International Conference on Analysis of Algorithms (AofA). Vol. AH. DMTCS Proceedings. 2007, pp. 127–146 (cit. on p. 1).
[FM85] Philippe Flajolet and G. Nigel Martin. “Probabilistic Counting Algorithms for Data Base Applications”. In: Journal of Computer and System Sciences 31.2 (1985), pp. 182–209 (cit. on p. 1).
[Gag94] Philip Gage. “A new algorithm for data compression”. In: The C Users Journal 12.2 (1994), pp. 23–38 (cit. on p. 1).
[Hug26] HuggingFace. Tokenizers: Fast state-of-the-art tokenizers optimized for research and production. https://github.com/huggingface/tokenizers. 2026 (cit. on pp. 1, 38).
[JG26] Shenghu Jiang and Ruihao Gong. “Incremental BPE Tokenization”. In: Proceedings of the 43rd International Conference on Machine Learning (ICML). 2026. arXiv: 2605.30813. URL: https://arxiv.org/abs/2605.30813 (cit. on pp. 1–3, 5, 11, 17, 26, 28, 31, 32, 38, 41, 50, 51).
[LYM26] Angela W Li, Yudi Yang, and Konstantinos Mamouras. “Static Analysis for Efficient Streaming Tokenization”. In: Proceedings of the 31st ACM International Conference on Architectural Support for Programming Languages and Operating Systems, Volume 2. 2026, pp. 1880–1896 (cit. on pp. 1, 3, 6).
[MG82] J. Misra and David Gries. “Finding Repeated Elements”. In: Science of Computer Programming 2.2 (1982), pp. 143–152 (cit. on p. 1).
[MLY26] Konstantinos Mamouras, Angela W Li, and Yudi Yang. “An Efficient Algorithm for Streaming BPE Tokenization”. In: Proceedings of the ACM on Programming Languages 10.PLDI (2026), pp. 2085–2108 (cit. on pp. 1, 26).
[Mor78] Robert Morris. “Counting Large Numbers of Events in Small Registers”. In: Communications of the ACM 21.10 (1978), pp. 840–842 (cit. on p. 1).
[MP80] J. Ian Munro and Mike S. Paterson. "Selection and Sorting with Limited Storage". In: Theoretical Computer Science 12.3 (1980), pp. 315–323 (cit. on p. 1).
[Ope26a] OpenAI. tiktoken. https://github.com/openai/tiktoken. Accessed: 2026-06-15. 2026 (cit. on pp. 1, 2, 38).
[Ope26b] OpenAI. tiktoken: src/lib.rs. https://github.com/openai/tiktoken/blob/main/src/lib.rs. Accessed: 2026-07-07. GitHub, 2026 (cit. on p. 41).
[Ora24] Oracle. Quantifiers. https://docs.oracle.com/javase/tutorial/essential/regex/quant.html. Accessed: 2026-06-29. 2024 (cit. on p. 43).
[Reg25] Regular-Expressions.info. Possessive Quantifiers. https://www.regular-expressions.info/possessive.html. Accessed: 2026-06-29. 2025 (cit. on p. 43).
[Rep98] Thomas Reps. “Maximal-Munch” Tokenization in Linear Time”. In: ACM Transactions on Programming Languages and Systems 20.2 (1998), pp. 259–273. DOI: 10.1145/276393.276394 (cit. on pp. 2, 20).
[Rød26] Marcel Rød. Gigatoken: SIMD and Cache Hierarchies for 1000x Faster Byte-Pair Encoding Tokenization on Modern CPUs. 2026. URL: https://github.com/marcelroed/gigatoken (cit. on pp. 5, 45, 46).
[SHB16] Rico Sennrich, Barry Haddow, and Alexandra Birch. “Neural machine translation of rare words with subword units”. In: Proceedings of the 54th annual meeting of the association for computational linguistics (volume 1: long papers). 2016, pp. 1715–1725 (cit. on p. 1).
[Tog23] Together Computer. RedPajama-Data-1T dataset. Hugging Face dataset repository. Apr. 2023. URL: https://huggingface.co/datasets/togethercomputer/RedPajama-Data-1T (cit. on p. 38).
[VY26] Harshit Verma and Rex Ying. "Component-Weighted Centroid Search for Exact Incremental BPE". In: arXiv preprint arXiv:2609.40016 (2026) (cit. on p. 5).
[Wik23] Wikimedia Foundation. Wikipedia dataset. Hugging Face dataset repository. Nov. 2023. URL: https://huggingface.co/datasets/wikimedia/wikipedia (cit. on p. 38).
A Omitted Proofs
We prove Lemma 5.3.
Proof of Lemma 5.3. We use the incremental BPE algorithm of Jiang and Gong [JG26]. Their algorithm computes the last token of every prefix, whereas we require the first token of every suffix. The algorithm and proof are almost identical, with some minor modifications to handle left-to-right tie-breaking in the computation of first token rather than last token .
We recap the algorithm of Jiang and Gong [JG26]. In preprocessing, they compute the following data structures:
-
A successor forest where nodes are tokens and edges where is produced by the merge rule . We call the predecessor and successor of . We replace this with a predecessor forest where the nodes are tokens and edges . This requires time.
-
For each token , compute the suffix-successor tree of , which is the induced subgraph of containing tokens where is a suffix of . On each of these trees, compute a centroid decomposition (using e.g. Della Giustina, Prezza, and Venturini [DPV19]). Instead, we replace this with a prefix-predecessor tree, i.e. the induced subgraph of the predecessor forest consisting of tokens where . There are tokens, each with at most prefixes, so this requires time.
-
Jiang and Gong [JG26] use an Aho–Corasick automaton to report the longest suffix of that is a token. Instead, we scan right-to-left using an automaton on reversed token strings to report the longest prefix of that is a token. This requires preprocessing.
We then process the input string right-to-left. Assume that is computed for . We have an analogue of Jiang and Gong [JG26] Prefix Last Token condition (see Definition 4.1), which we call the Suffix First Token condition. That is, satisfies the Suffix First Token condition if it is an atomic token (i.e. ) or satisfies the following:
-
(Reachability) is in the subtree of the predecessor forest rooted at . This ensures that is formed in the suffix .
-
(Priority Dominance) If , let be the unique child of that lies on the path to . Then, the rule producing has priority at least as high as the rule producing . This ensures that is produced before is consumed. Note that here we require priority to be at least as high, instead of strictly higher as in Jiang and Gong [JG26], due to left-to-right tie-breaking.
Let be the longest token such that . Then . Analogously to Jiang and Gong [JG26], one can show that on the prefix-predecessor tree of , a vertex is on the path from to iff it satisfies the Suffix First Token condition, which can be checked in time. The idea then is to start from the root and follow the path of children satisfying the Suffix First Token (SFT) condition. Since we have constructed a centroid decomposition, we begin from the centroid. We first test the centroid's SFT condition. If it is valid, we search for a child satisfying the condition. We identify the valid child by binary search, with children ordered by the left endpoints of their disjoint valid intervals, as in Jiang and Gong [JG26], with predecessors and successors interchanged. Here children refer to the original prefix-predecessor tree. If the centroid is valid but has no valid child, return it. Otherwise, either the centroid has a valid child, in which case we remove the centroid and continue at the centroid of the remaining component containing the valid child, or the centroid is invalid, in which case we remove it and continue at the centroid of the remaining component containing its original-tree parent, as in Jiang and Gong [JG26]. This proceeds for at most steps, and searching for the right child requires time, leading to time.
We provide the reference and simplified DFA illustrations for R50K, CL100K, and O200K.

Figure 5: R50K reference pattern as a delayed-accept DFA. X denotes non-whitespace characters as in Figure 6; = space, = other whitespace, = end of input. The non-whitespace part is an ordinary DFA (boundary unconditional at run/contraction end); the whitespace part , ) is a delayed DFA. includes the last ws char; trims it (imposed by the rule ). Peeling fires only from , i.e. when the run of whitespace is at least 2 characters long.

Figure 6: R50K simplified pattern. X denotes non-whitespace characters such as letters, digits, and symbols. In each case, the run continues on the same class X; = literal space, = other whitespace ( s ). W accepts the maximal s run unconditionally (no lookahead).
Table 5: Throughput comparison of our tokenizer on tokenizers models measured in MiB/s. tokenizers is provided with a string as input and gives an array as output, both in memory. Our algorithm is provided with a file path as input and writes output to file. We report the median throughput over 10 runs for each row with upper and lower quartiles in the parentheses.
| Model | Dataset | tokenizers | Ours | Speedup |
|---|---|---|---|---|
| GPT2 | Github | 1.2 (1.2-1.2) | 45.7 (45.5-45.8) | 38.1× |
| GPT2 | English | 1.4 (1.4-1.4) | 50.4 (50.0-51.3) | 36.0× |
| GPT2 | Chinese | 1.2 (1.2-1.2) | 38.6 (38.4-38.6) | 32.2× |
| RoBERTa | Github | 1.1 (1.1-1.2) | 40.7 (37.5-41.0) | 37.0× |
| RoBERTa | English | 1.3 (1.3-1.3) | 46.2 (45.7-46.4) | 35.5× |
| RoBERTa | Chinese | 1.2 (1.2-1.2) | 35.0 (34.7-35.2) | 29.2× |
| StarCoder | Github | 1.4 (1.4-1.4) | 51.3 (50.8-51.5) | 36.6× |
| StarCoder | English | 1.3 (1.3-1.4) | 35.8 (35.7-35.8) | 27.5× |
| StarCoder | Chinese | 1.5 (1.4-1.5) | 32.1 (32.0-32.2) | 21.4× |
| Mistral | Github | 1.7 (1.6-1.7) | 55.8 (55.4-56.3) | 32.8× |
| Mistral | English | 1.7 (1.7-1.7) | 47.4 (47.1-47.6) | 27.9× |
| Mistral | Chinese | 1.7 (1.7-1.7) | 39.3 (39.3-39.4) | 23.1× |
| Llama4 | Github | 1.8 (1.8-1.8) | 56.3 (56.2-56.7) | 31.3× |
| Llama4 | English | 1.7 (1.7-1.7) | 41.1 (40.9-41.4) | 24.2× |
| Llama4 | Chinese | 1.7 (1.7-1.7) | 33.7 (33.5-33.9) | 19.8× |
| Qwen-3 | Github | 1.6 (1.6-1.6) | 30.8 (30.6-31.0) | 19.2× |
| Qwen-3 | English | 1.5 (1.5-1.5) | 29.6 (29.5-30.1) | 19.7× |
| Qwen-3 | Chinese | 1.7 (1.7-1.7) | 26.8 (26.6-26.9) | 15.8× |
| gpt-oss | Github | 1.9 (1.9-1.9) | 56.6 (56.4-57.1) | 29.8× |
| gpt-oss | English | 1.8 (1.8-1.8) | 44.4 (44.2-44.7) | 24.7× |
| gpt-oss | Chinese | 1.9 (1.9-1.9) | 36.8 (36.6-37.0) | 19.4× |
Table 6: Throughput comparison of optimized tokenizer on tiktoken encodings (MiB/s). gigatoken and our algorithm are provided with a file path as input. The array (A) column reports throughput when output is collected as array in memory, the stream (S) column reports when output is written to a temporary file. We report the median of 10 runs (quartiles omitted for space).
| Encoding | Dataset | gigatoken (A) | gigatoken (S) | Ours (A) | Ours (S) |
|---|---|---|---|---|---|
| r50k | Github | 178.3 | 26.9 | 185.5 | 117.5 |
| r50k | English | 331.1 | 44.6 | 298.7 | 181.9 |
| r50k | Chinese | 39.9 | 13.1 | 45.3 | 37.8 |
| p50k | Github | 188.7 | 32.2 | 191.5 | 126.8 |
| p50k | English | 329.2 | 44.6 | 297.6 | 180.0 |
| p50k | Chinese | 39.8 | 13.0 | 45.9 | 37.8 |
| c1100k | Github | 172.2 | 40.4 | 159.7 | 119.7 |
| c1100k | English | 278.3 | 44.2 | 248.3 | 158.4 |
| c1100k | Chinese | 27.8 | 13.5 | 43.7 | 36.5 |
| o200k | Github | 253.4 | 43.3 | 236.6 | 155.9 |
| o200k | English | 240.9 | 43.6 | 216.0 | 140.8 |
| o200k | Chinese | 24.0 | 15.0 | 41.2 | 36.4 |

Figure 7: CL100K reference pattern. G denotes the DFA to compute the first rule. Next, L denotes the DFA to compute runs of letters with leading horizontal whitespace or punctuation (e.g. ). denotes the DFA to compute runs of digits. Pu and PN denote the DFA to compute runs of symbols followed by newlines. Priority: contraction, word, digit, punct, ws. Wh and denote the first and subsequent horizontal whitespace respectively. Wnl denotes vertical whitespace/newline. From Wnl we always keep the last whitespace. From , we trim the last character when a non-whitespace is encountered.

Figure 8: O200K reference pattern. Words are case split, with upper case characters first, followed by lower case characters with an optional contraction suffix . Digits have run length . Symbols can have a leading space, followed by an arbitrary number of newlines. Horizontal whitespace followed by letters reaches the first two cases, while followed by any other non-whitespace character immediately outputs the single space. Remaining runs of whitespace either must end with a newline or leave a trailing space before the next whitespace character.

Figure 9: O200K simplified pattern. Most of the DFA (except whitespace handling) is identical to Figure 8. For whitespace, any run of whitespace that contains vertical whitespace/newline must end on vertical whitespace/newline. Otherwise, a run that contains only horizontal whitespace is matched as a single run.