[GH-ISSUE #268] [tokenizer] O(n^2) BPE merge loop: an unbroken CJK run is ~10 s per 8K chars (1266x slower than needed) #140

Closed
opened 2026-11-04 01:40:22 +07:00 by bsakaguchi · 3 comments
Owner

Originally created by @cha0yang on GitHub (Sep 30, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/268

tools/strata_tokenizer.py is a pure-Python BPE whose merge loop is O(n^2) in the length of a
pre-token, and the pre-tokenizer hands it a very long pre-token whenever a stretch of text has
no punctuation or whitespace. For CJK that stretch is also byte-mapped first, so the length it
scans is 3x the number of characters. A run of Han characters without punctuation therefore costs
seconds, and the cost grows quadratically.

I hit this as "the engine hangs on long prompts": server.py:736 encodes the whole prompt before
the engine is told anything, so the GPU sits idle, nothing appears in the engine log, and the
request just never returns. It is not the engine — it is the tokenizer.

Root cause

tools/strata_tokenizer.py:140 (_bpe):

parts = list(word)
while len(parts) > 1:
    best, best_rank = None, None
    for i in range(len(parts) - 1):          # <-- full rescan after every single merge
        r = self.ranks.get((parts[i], parts[i + 1]))
        if r is not None and (best_rank is None or r < best_rank):
            best, best_rank = i, r
    if best is None:
        break
    parts[best:best + 2] = [parts[best] + parts[best + 1]]

Every merge rescans the entire list, so a word of length n costs O(n^2). _encode_plain then makes
the input 3x longer for non-ASCII, because it byte-maps each character to 1-3 byte-chars before
calling _bpe:

mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8"))

So 8000 Han characters (no punctuation -> one pre-token -> 24000 byte-chars) is 256,007,999 dict
lookups, measured with cProfile.

Measurements

Engine 0.1.29, this box, pack swift-iq3_xxs, Tokenizer(tokens, merges, types) built exactly as
server.py builds it, encode(..., parse_special=True).

input pre-tokens chars _bpe sees time
8000 chars of Chinese prose with punctuation 615 (avg 13) 13-19 0.024 s
8000 chars of English many short short 0.005 s
8000 Han chars, no punctuation 1 24000 9.75 s
8000 Han chars on one line (mixed) 1 ~22000 9.72 s

Quadratic in the length of the unbroken run:

Han chars, no punctuation _bpe
500 0.0364 s
1000 0.1488 s (x4.1)
2000 0.6011 s (x4.0)
4000 2.4169 s (x4.0)
8000 9.7526 s (x4.0)

Extrapolating: 32K Han chars ~160 s, 53K ~7 min.

Note the asymmetry, which is probably why nobody has reported it: English is fine (3x slower than
it could be) and normal Chinese prose is fine (12x slower, but 0.024 s at 8K)
. Only a long
unbroken CJK run blows up. Pasting a long Chinese document that lost its line breaks, a
comma-free log line, or a long Chinese string inside tool output all trigger it.

A drop-in fix, no new dependencies

Replace the rescan with a min-heap over adjacent pairs plus a doubly-linked list of live positions,
and version-stamp heap entries so stale ones can be dropped. Same output, O(n log n):

import heapq

def bpe(self, word):
    """Merge by lowest rank first, same result as the O(n^2) scan."""
    word = list(word)
    n = len(word)
    if n < 2:
        return word
    nxt = list(range(1, n + 1))          # nxt[i] = next live index (n = end)
    prv = list(range(-1, n - 1))
    ver = [0] * n                        # bumped on merge -> stale heap entries are detectable
    live = [True] * n
    h = []
    for i in range(n - 1):
        r = self.ranks.get((word[i], word[i + 1]))
        if r is not None:
            heapq.heappush(h, (r, i, 0))
    while h:
        r, i, v = heapq.heappop(h)
        if not live[i] or ver[i] != v:
            continue
        j = nxt[i]
        if j >= n or not live[j] or prv[j] != i:
            continue
        if self.ranks.get((word[i], word[j])) != r:   # pair changed under us
            continue
        word[i] = word[i] + word[j]
        live[j] = False
        nxt[i] = nxt[j]
        if nxt[j] < n:
            prv[nxt[j]] = i
        ver[i] += 1
        k = prv[i]
        if k >= 0:
            r2 = self.ranks.get((word[k], word[i]))
            if r2 is not None:
                heapq.heappush(h, (r2, k, ver[k]))
        if nxt[i] < n:
            r2 = self.ranks.get((word[i], word[nxt[i]]))
            if r2 is not None:
                heapq.heappush(h, (r2, i, ver[i]))
    out, head = [], next(x for x in range(n) if prv[x] == -1)
    while head < n:
        out.append(word[head])
        head = nxt[head]
    return out

Verified against the current implementation on 1500 random strings over
"中国古代四大发明abc,。\n" (including the byte-mapped form, which is what actually reaches
_bpe): 0 differences. On the worst case above:

Han chars current this patch speedup
500 0.0364 s 0.00042 s 86x
1000 0.1488 s 0.00085 s 175x
2000 0.6011 s 0.00177 s 339x
4000 2.4169 s 0.00372 s 650x
8000 9.7526 s 0.00770 s 1266x

It is slower than the current code on already-short pre-tokens (the heap setup costs more than a
15-element scan), so if that matters the two can be dispatched on len(word) — but the shorter path
only gets used in the region that is already fast.

For reference

I worked around it on my side with a thin wrapper over the Rust tokenizers crate loaded from the
model's official tokenizer.json, which is also bit-identical on a corpus of mixed text and takes
8K CJK from 9.95 s to 0.003 s. That adds a dependency, which is why I would prefer the heap version
upstream. Happy to send either as a PR — thanks, the rest of the engine has been excellent.

Originally created by @cha0yang on GitHub (Sep 30, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/268 `tools/strata_tokenizer.py` is a pure-Python BPE whose merge loop is O(n^2) in the length of a pre-token, and the pre-tokenizer hands it a very long pre-token whenever a stretch of text has no punctuation or whitespace. For CJK that stretch is also *byte-mapped first*, so the length it scans is 3x the number of characters. A run of Han characters without punctuation therefore costs seconds, and the cost grows quadratically. I hit this as "the engine hangs on long prompts": `server.py:736` encodes the whole prompt before the engine is told anything, so the GPU sits idle, nothing appears in the engine log, and the request just never returns. It is not the engine — it is the tokenizer. ## Root cause `tools/strata_tokenizer.py:140` (`_bpe`): ```python parts = list(word) while len(parts) > 1: best, best_rank = None, None for i in range(len(parts) - 1): # <-- full rescan after every single merge r = self.ranks.get((parts[i], parts[i + 1])) if r is not None and (best_rank is None or r < best_rank): best, best_rank = i, r if best is None: break parts[best:best + 2] = [parts[best] + parts[best + 1]] ``` Every merge rescans the entire list, so a word of length n costs O(n^2). `_encode_plain` then makes the input 3x longer for non-ASCII, because it byte-maps each character to 1-3 byte-chars before calling `_bpe`: ```python mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8")) ``` So 8000 Han characters (no punctuation -> one pre-token -> 24000 byte-chars) is 256,007,999 dict lookups, measured with cProfile. ## Measurements Engine 0.1.29, this box, pack `swift-iq3_xxs`, `Tokenizer(tokens, merges, types)` built exactly as `server.py` builds it, `encode(..., parse_special=True)`. | input | pre-tokens | chars `_bpe` sees | time | |---|---|---|---| | 8000 chars of Chinese prose with punctuation | 615 (avg 13) | 13-19 | **0.024 s** | | 8000 chars of English | many short | short | **0.005 s** | | 8000 Han chars, no punctuation | **1** | **24000** | **9.75 s** | | 8000 Han chars on one line (mixed) | 1 | ~22000 | **9.72 s** | Quadratic in the length of the unbroken run: | Han chars, no punctuation | `_bpe` | |---|---| | 500 | 0.0364 s | | 1000 | 0.1488 s (x4.1) | | 2000 | 0.6011 s (x4.0) | | 4000 | 2.4169 s (x4.0) | | 8000 | 9.7526 s (x4.0) | Extrapolating: 32K Han chars ~160 s, 53K ~7 min. Note the asymmetry, which is probably why nobody has reported it: **English is fine (3x slower than it could be) and normal Chinese prose is fine (12x slower, but 0.024 s at 8K)**. Only a long unbroken CJK run blows up. Pasting a long Chinese document that lost its line breaks, a comma-free log line, or a long Chinese string inside tool output all trigger it. ## A drop-in fix, no new dependencies Replace the rescan with a min-heap over adjacent pairs plus a doubly-linked list of live positions, and version-stamp heap entries so stale ones can be dropped. Same output, O(n log n): ```python import heapq def bpe(self, word): """Merge by lowest rank first, same result as the O(n^2) scan.""" word = list(word) n = len(word) if n < 2: return word nxt = list(range(1, n + 1)) # nxt[i] = next live index (n = end) prv = list(range(-1, n - 1)) ver = [0] * n # bumped on merge -> stale heap entries are detectable live = [True] * n h = [] for i in range(n - 1): r = self.ranks.get((word[i], word[i + 1])) if r is not None: heapq.heappush(h, (r, i, 0)) while h: r, i, v = heapq.heappop(h) if not live[i] or ver[i] != v: continue j = nxt[i] if j >= n or not live[j] or prv[j] != i: continue if self.ranks.get((word[i], word[j])) != r: # pair changed under us continue word[i] = word[i] + word[j] live[j] = False nxt[i] = nxt[j] if nxt[j] < n: prv[nxt[j]] = i ver[i] += 1 k = prv[i] if k >= 0: r2 = self.ranks.get((word[k], word[i])) if r2 is not None: heapq.heappush(h, (r2, k, ver[k])) if nxt[i] < n: r2 = self.ranks.get((word[i], word[nxt[i]])) if r2 is not None: heapq.heappush(h, (r2, i, ver[i])) out, head = [], next(x for x in range(n) if prv[x] == -1) while head < n: out.append(word[head]) head = nxt[head] return out ``` Verified against the current implementation on 1500 random strings over `"中国古代四大发明abc,。\n"` (including the byte-mapped form, which is what actually reaches `_bpe`): **0 differences**. On the worst case above: | Han chars | current | this patch | speedup | |---|---|---|---| | 500 | 0.0364 s | 0.00042 s | 86x | | 1000 | 0.1488 s | 0.00085 s | 175x | | 2000 | 0.6011 s | 0.00177 s | 339x | | 4000 | 2.4169 s | 0.00372 s | 650x | | 8000 | 9.7526 s | 0.00770 s | **1266x** | It is slower than the current code on already-short pre-tokens (the heap setup costs more than a 15-element scan), so if that matters the two can be dispatched on `len(word)` — but the shorter path only gets used in the region that is already fast. ## For reference I worked around it on my side with a thin wrapper over the Rust `tokenizers` crate loaded from the model's official `tokenizer.json`, which is also bit-identical on a corpus of mixed text and takes 8K CJK from 9.95 s to 0.003 s. That adds a dependency, which is why I would prefer the heap version upstream. Happy to send either as a PR — thanks, the rest of the engine has been excellent.
Author
Owner

@cha0yang commented on GitHub (Sep 30, 2026):

Correction to the "For reference" paragraph, now that I have actually switched to the heap version
above: the Rust workaround was not bit-identical after all. The official tokenizer.json
applies NFC, so it folds a decomposed Hangul jamo sequence into a composed syllable, while the GGUF
merges do not — and the round trip through it loses characters:

"각 한국어"    (7 chars: U+1100 U+1161 U+11A8 SP U+D55C U+AD6D U+C5B4)

  Python (GGUF merges)       10 tokens  ->  round trip exact, 7 chars
  Rust (hf_tokenizer.json)    2 tokens  ->  round trip 5 chars, lossy: "각 한국어"

My first check was 9 strings of plain text, code and emoji, and it passed. A wider corpus (Hangul,
combining marks) is what caught it. So the dependency-free heap version is strictly better here, not
merely lighter: identical to the current implementation on 4000 random strings (both
parse_special modes) and on a mixed corpus of prose, code, Hangul, emoji and combining marks, and
it has no NFC divergence.

It is also fast enough that the Rust path is not worth keeping:

input current O(n^2) heap speedup
8K Chinese prose with punctuation 0.0255 s 0.0088 s 2.9x
8K unbroken CJK 9.6928 s 0.0088 s 1096x
8K space-free Latin (long URL, minified blob) 1.3737 s 0.0054 s 253x
8K English / code unchanged unchanged 1.0x

The "space-free Latin" row is worth a look on its own, by the way — it is not only CJK that trips
the rescan. Anything that arrives as one long pre-token does, and a pasted URL or a minified JSON
blob is exactly that.

I have the heap version in production locally now and the long-prompt symptom is gone: an 8K
unbroken-CJK prompt goes from ~10 s of tokenization before the engine is even told anything to
nothing measurable.

<!-- gh-comment-id:5916193833 --> @cha0yang commented on GitHub (Sep 30, 2026): Correction to the "For reference" paragraph, now that I have actually switched to the heap version above: the Rust workaround was **not** bit-identical after all. The official `tokenizer.json` applies NFC, so it folds a decomposed Hangul jamo sequence into a composed syllable, while the GGUF merges do not — and the round trip through it loses characters: ``` "각 한국어" (7 chars: U+1100 U+1161 U+11A8 SP U+D55C U+AD6D U+C5B4) Python (GGUF merges) 10 tokens -> round trip exact, 7 chars Rust (hf_tokenizer.json) 2 tokens -> round trip 5 chars, lossy: "각 한국어" ``` My first check was 9 strings of plain text, code and emoji, and it passed. A wider corpus (Hangul, combining marks) is what caught it. So the dependency-free heap version is strictly better here, not merely lighter: identical to the current implementation on 4000 random strings (both `parse_special` modes) and on a mixed corpus of prose, code, Hangul, emoji and combining marks, and it has no NFC divergence. It is also fast enough that the Rust path is not worth keeping: | input | current O(n^2) | heap | speedup | |---|---|---|---| | 8K Chinese prose with punctuation | 0.0255 s | 0.0088 s | 2.9x | | 8K unbroken CJK | 9.6928 s | 0.0088 s | 1096x | | 8K space-free Latin (long URL, minified blob) | 1.3737 s | 0.0054 s | 253x | | 8K English / code | unchanged | unchanged | 1.0x | The "space-free Latin" row is worth a look on its own, by the way — it is not only CJK that trips the rescan. Anything that arrives as one long pre-token does, and a pasted URL or a minified JSON blob is exactly that. I have the heap version in production locally now and the long-prompt symptom is gone: an 8K unbroken-CJK prompt goes from ~10 s of tokenization before the engine is even told anything to nothing measurable.
Author
Owner

@Niko1221 commented on GitHub (Sep 30, 2026):

Confirmed, thanks for the analysis. 0.1.31 uses your heap + linked-list merge for long words (same merge order, checked token for token against the current code), and short words keep the existing loop.

<!-- gh-comment-id:5917510568 --> @Niko1221 commented on GitHub (Sep 30, 2026): Confirmed, thanks for the analysis. 0.1.31 uses your heap + linked-list merge for long words (same merge order, checked token for token against the current code), and short words keep the existing loop.
Author
Owner

@Niko1221 commented on GitHub (Oct 1, 2026):

Fixed in 0.1.31 with your heap + linked-list merge for long words (same merge order, checked id for id against the old code): 2,000 CJK characters 1.6 s -> 5 ms here. Thanks!

<!-- gh-comment-id:5925208849 --> @Niko1221 commented on GitHub (Oct 1, 2026): Fixed in [0.1.31](https://github.com/Niko1221/Strata/releases/tag/v0.1.31) with your heap + linked-list merge for long words (same merge order, checked id for id against the old code): 2,000 CJK characters 1.6 s -> 5 ms here. Thanks!
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#140
No description provided.