-
Notifications
You must be signed in to change notification settings - Fork 9.6k
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
Improve Tokenizer Class: Error Handling, Flexibility #640
Open
zeelsheladiya
wants to merge
3
commits into
meta-llama:main
Choose a base branch
from
zeelsheladiya:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,7 +3,7 @@ | |
|
||
import os | ||
from logging import getLogger | ||
from typing import List | ||
from typing import List, Optional | ||
|
||
from sentencepiece import SentencePieceProcessor | ||
|
||
|
@@ -13,29 +13,32 @@ | |
|
||
class Tokenizer: | ||
"""tokenizing and encoding/decoding text using SentencePiece.""" | ||
def __init__(self, model_path: str): | ||
def __init__(self, model_path: Optional[str] = None): | ||
""" | ||
Initializes the Tokenizer with a SentencePiece model. | ||
|
||
Args: | ||
model_path (str): The path to the SentencePiece model file. | ||
""" | ||
# reload tokenizer | ||
assert os.path.isfile(model_path), model_path | ||
self.sp_model = SentencePieceProcessor(model_file=model_path) | ||
logger.info(f"Reloaded SentencePiece model from {model_path}") | ||
if model_path is not None: | ||
# reload tokenizer if possible | ||
if not os.path.isfile(model_path): | ||
raise FileNotFoundError(f"Model file not found: {model_path}") | ||
self.sp_model = SentencePieceProcessor(model_file=model_path) | ||
logger.info(f"Reloaded SentencePiece model from {model_path}") | ||
|
||
# BOS / EOS token IDs | ||
self.n_words: int = self.sp_model.vocab_size() | ||
self.bos_id: int = self.sp_model.bos_id() | ||
self.eos_id: int = self.sp_model.eos_id() | ||
self.pad_id: int = self.sp_model.pad_id() | ||
logger.info( | ||
f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}" | ||
) | ||
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size() | ||
# BOS / EOS / PAD / UNK token IDs | ||
self.n_words: int = self.sp_model.vocab_size() | ||
self.bos_id: int = self.sp_model.bos_id() | ||
self.eos_id: int = self.sp_model.eos_id() | ||
self.pad_id: int = self.sp_model.pad_id() | ||
self.unk_id: int = self.sp_model.unk_id() | ||
logger.info( | ||
f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}" | ||
) | ||
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size() | ||
|
||
def encode(self, s: str, bos: bool, eos: bool) -> List[int]: | ||
def encode(self, s: str, bos: bool = False, eos: bool = False) -> List[int]: | ||
""" | ||
Encodes a string into a list of token IDs. | ||
|
||
|
@@ -47,8 +50,15 @@ def encode(self, s: str, bos: bool, eos: bool) -> List[int]: | |
Returns: | ||
List[int]: A list of token IDs. | ||
""" | ||
assert type(s) is str | ||
t = self.sp_model.encode(s) | ||
assert isinstance(s, str), "Input 's' must be a string" | ||
try: | ||
t = self.sp_model.encode(s) | ||
except Exception as e: | ||
raise ValueError(f"Error during tokenization: {e}") | ||
Comment on lines
+54
to
+57
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think we need this, the exception itself should be clear enough? |
||
|
||
# Handle unknown tokens | ||
t = [token_id if token_id in range(self.n_words) else self.unk_id for token_id in t] | ||
Comment on lines
+59
to
+60
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would you have an example of an input string that requires this? |
||
|
||
if bos: | ||
t = [self.bos_id] + t | ||
if eos: | ||
|
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 was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why make this optional? How would you initialize the tokenizer without the model file?