perf(js): replace quadratic BPE merge algorithm with optimal heap-based algorithm#156
Open
uriva wants to merge 1 commit into
Open
perf(js): replace quadratic BPE merge algorithm with optimal heap-based algorithm#156uriva wants to merge 1 commit into
uriva wants to merge 1 commit into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
There is a performance bottleneck where the pure JS BPE merge algorithm (bytePairMerge) in js-tiktoken runs in quadratic time O(N^2) in the number of characters for long continuous words without spaces (such as repeating a character 3000 times). This causes severe performance degradation, taking almost 10 seconds for just 3000 characters and hanging test suites / downstream LLM agents under Deno/Node.\n\nThis PR fixes the issue by replacing the O(N^2) implementation with a correct, optimal heap-based O(N log N) algorithm (using duplicate pushing/lazy deletion to handle priority increases), speeding up encoding of pathological strings by over 270x (from 9 seconds to 32ms for 3000 characters). This also closes the loop on previous attempts like PR #101 and fixes decoding/matching errors on non-latin and emoji sequences.