fix(Tokenizers): avoid quadratic regex matching for added tokens without whitespace padding - #386
Open
shubhransh-gupta wants to merge 1 commit into
Open
Conversation
…out whitespace padding
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.
Fixes #383.
Summary
In
PreTrainedTokenizer,addedTokensRegexwas constructed by wrapping every added token in a capturing group(\(token))even when neitherlstripnorrstripwas requested.For tokenizers with large added token vocabularies (e.g. Google Gemma-3 with 6,415 added tokens), this caused an$O(N^2)$ quadratic slowdown in Foundation's ICU regular expression engine due to capturing group table allocations, slowing down single newline
\nencoding from ~0.02 ms to ~29 ms (~1.1s for a 40-line prompt on device).Changes
$0.prefixand$0.suffixare bothfalse, compile the token using a non-capturing group(?:\(token))instead of(\(token)).lstriporrstripstill retain their capturing group sosplit(by: NSRegularExpression)continues to isolate and strip surrounding whitespace as expected.unwrappedAddedTokensis empty.addedTokensRegexPerformanceAndCorrectnessinTests/TokenizersTests/TokenizerTests.swift.Verification
swift testacross all targets (50/50 tests passing).swift-format lint --strict --recursive Sources Tests(clean, 0 warnings).