⚡️ Speed up method ProphetNetTokenizer._convert_token_to_id by 417%
#884
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.
📄 417% (4.17x) speedup for
ProphetNetTokenizer._convert_token_to_idinsrc/transformers/models/prophetnet/tokenization_prophetnet.py⏱️ Runtime :
2.40 milliseconds→463 microseconds(best of147runs)📝 Explanation and details
The optimization applies dictionary lookup caching to eliminate redundant lookups in the hot path of token-to-ID conversion.
Key changes:
self._unk_token_idin__init__to store the unknown token's ID once, avoiding repeatedself.vocab.get(self.unk_token)calls.get()calls into separate lookup and fallback steps, reducing dictionary operations from 2 to 1 for unknown tokensWhy this speeds up the code:
self.vocab.get(token, self.vocab.get(self.unk_token))which always does 2 dictionary lookups for unknown tokens. The optimized version does only 1 lookup for the token, then returns the pre-cached unknown token IDself._unk_token_id) is much faster than dictionary hash table lookupsPerformance impact based on test results:
This optimization is particularly effective for tokenizers since
_convert_token_to_idis called frequently during text processing, and unknown tokens are common in real-world applications.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ProphetNetTokenizer._convert_token_to_id-misk6l0gand push.