Skip to content

added cached tokenizer #35218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/transformers/tokenization_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,10 +457,27 @@ def vocab_size(self) -> int:
@property
def added_tokens_encoder(self) -> Dict[str, int]:
"""
Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
optimisation in `self._added_tokens_encoder` for the slow tokenizers.
Returns the sorted mapping from string to index. The cache is dynamically invalidated if `_added_tokens_decoder`
has changed since the last computation.
"""
return {k.content: v for v, k in sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return {k.content: v for v, k in sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])}
return self._added_tokens_encoder

this would not work as you probably need the content to be sorted, which is why we have the non-sorted _added_tokens_encoder. We can actually sort it (define it as OrderedDict) as we deprecated python <= 3.9!

# Check if cache exists and is valid
if not hasattr(self, "_cached_added_tokens_encoder") or self._is_decoder_modified():
# Recompute and cache the added tokens encoder
self._cached_added_tokens_encoder = {
k.content: v for v, k in sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])
}
# Store the current state of `_added_tokens_decoder` for future validity checks
self._cached_decoder_state = self._added_tokens_decoder.copy()
return self._cached_added_tokens_encoder

def _is_decoder_modified(self) -> bool:
"""
Check if `_added_tokens_decoder` has been modified since the last computation.
Returns:
bool: True if modified, False otherwise.
"""
# Compare the current state with the cached state
return not hasattr(self, "_cached_decoder_state") or self._cached_decoder_state != self._added_tokens_decoder

@property
def added_tokens_decoder(self) -> Dict[int, AddedToken]:
Expand Down
Loading