perf(js): speed up Tiktoken.encode#157
Open
jeet-dhandha wants to merge 1 commit into
Open
Conversation
- key the rank map by latin1 string instead of Array.join(",")
- compile the token and special-token regexes once in the constructor
instead of on every encode() call
- merge byte pairs with cached ranks and neighbour-only updates
Output is unchanged; ~2.4x faster on large inputs.
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.
Tiktoken.encodedoes three things on the hot path that are cheap to avoid. Output is byte-for-byte unchanged.Array.from(bytes).join(",")on every lookup. Mapping each byte to one latin1 code unit (String.fromCharCode) is injective over byte sequences and avoids the intermediate array + comma string. The constructor uses the same helper, so keys stay consistent.encode()compiled the token pattern and the special-token regex on every call. Both depend only on values fixed at construction, so they're compiled once in the constructor.O(n²)per round). Ranks are now cached, and a merge only refreshes the two neighbours it affects — the algorithm tiktoken's reference implementation uses.Correctness
Checked the patched encoder against the current release across
o200k_base,cl100k_base,p50k_base,r50k_baseon a diverse corpus (prose, code, CJK, emoji, whitespace runs, URLs, edge cases) — identical token output on every sample, matchingdecoderound-trips, and identical special-token throw/allow behaviour.Performance
~2.4x faster on large inputs (100KB encode,
o200k_base, Apple M1). No API or memory-model change.