Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK : replace this tiktoken, with the transformers module with pertrained (*,** all arguments users) , encode , decode very generalised and scable
import os
from logging import getLogger
from pathlib import Path
from typing import (
AbstractSet,
cast,
Collection,
Dict,
Iterator,
List,
Literal,
Sequence,
TypedDict,
Union,
)
import tiktoken
from tiktoken.load import load_tiktoken_bpe
logger = getLogger(name)
Role = Literal["system", "user", "assistant"]
class Message(TypedDict):
role: Role
content: str
Dialog = Sequence[Message]
class Tokenizer:
"""
Tokenizing and encoding/decoding text using the Tiktoken tokenizer.
"""
code
Assistant
special_tokens: Dict[str, int]
num_reserved_special_tokens = 256
pat_str = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+" # noqa: E501
def __init__(self, model_path: str):
"""
Initializes the Tokenizer with a Tiktoken model.
Args:
model_path (str): The path to the Tiktoken model file.
"""
assert os.path.isfile(model_path), model_path
mergeable_ranks = load_tiktoken_bpe(model_path)
num_base_tokens = len(mergeable_ranks)
special_tokens = [
"<|begin_of_text|>",
"<|end_of_text|>",
"<|reserved_special_token_0|>",
"<|reserved_special_token_1|>",
"<|reserved_special_token_2|>",
"<|reserved_special_token_3|>",
"<|start_header_id|>",
"<|end_header_id|>",
"<|reserved_special_token_4|>",
"<|eot_id|>", # end of turn
] + [
f"<|reserved_special_token_{i}|>"
for i in range(5, self.num_reserved_special_tokens - 5)
]
self.special_tokens = {
token: num_base_tokens + i for i, token in enumerate(special_tokens)
}
self.model = tiktoken.Encoding(
name=Path(model_path).name,
pat_str=self.pat_str,
mergeable_ranks=mergeable_ranks,
special_tokens=self.special_tokens,
)
logger.info(f"Reloaded tiktoken model from {model_path}")
self.n_words: int = self.model.n_vocab
# BOS / EOS token IDs
self.bos_id: int = self.special_tokens["<|begin_of_text|>"]
self.eos_id: int = self.special_tokens["<|end_of_text|>"]
self.pad_id: int = -1
self.stop_tokens = {
self.special_tokens["<|end_of_text|>"],
self.special_tokens["<|eot_id|>"],
}
logger.info(
f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}"
)
def encode(
self,
s: str,
*,
bos: bool,
eos: bool,
allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = (),
) -> List[int]:
"""
Encodes a string into a list of token IDs.
Args:
s (str): The input string to be encoded.
bos (bool): Whether to prepend the beginning-of-sequence token.
eos (bool): Whether to append the end-of-sequence token.
allowed_tokens ("all"|set[str]): allowed special tokens in string
disallowed_tokens ("all"|set[str]): special tokens that raise an error when in string
Returns:
list[int]: A list of token IDs.
By default, setting disallowed_special=() encodes a string by ignoring
special tokens. Specifically:
- Setting `disallowed_special` to () will cause all text corresponding
to special tokens to be encoded as natural text (insteading of raising
an error).
- Setting `allowed_special` to "all" will treat all text corresponding
to special tokens to be encoded as special tokens.
"""
assert type(s) is str
# The tiktoken tokenizer can handle <=400k chars without
# pyo3_runtime.PanicException.
TIKTOKEN_MAX_ENCODE_CHARS = 400_000
# https://github.com/openai/tiktoken/issues/195
# Here we iterate over subsequences and split if we exceed the limit
# of max consecutive non-whitespace or whitespace characters.
MAX_NO_WHITESPACES_CHARS = 25_000
substrs = (
substr
for i in range(0, len(s), TIKTOKEN_MAX_ENCODE_CHARS)
for substr in self._split_whitespaces_or_nonwhitespaces(
s[i : i + TIKTOKEN_MAX_ENCODE_CHARS], MAX_NO_WHITESPACES_CHARS
)
)
t: List[int] = []
for substr in substrs:
t.extend(
self.model.encode(
substr,
allowed_special=allowed_special,
disallowed_special=disallowed_special,
)
)
if bos:
t.insert(0, self.bos_id)
if eos:
t.append(self.eos_id)
return t
def decode(self, t: Sequence[int]) -> str:
"""
Decodes a list of token IDs into a string.
Args:
t (List[int]): The list of token IDs to be decoded.
Returns:
str: The decoded string.
"""
# Typecast is safe here. Tiktoken doesn't do anything list-related with the sequence.
return self.model.decode(cast(List[int], t))
@staticmethod
def _split_whitespaces_or_nonwhitespaces(
s: str, max_consecutive_slice_len: int
) -> Iterator[str]:
"""
Splits the string `s` so that each substring contains no more than `max_consecutive_slice_len`
consecutive whitespaces or consecutive non-whitespaces.
"""
current_slice_len = 0
current_slice_is_space = s[0].isspace() if len(s) > 0 else False
slice_start = 0
for i in range(len(s)):
is_now_space = s[i].isspace()
if current_slice_is_space ^ is_now_space:
current_slice_len = 1
current_slice_is_space = is_now_space
else:
current_slice_len += 1
if current_slice_len > max_consecutive_slice_len:
yield s[slice_start:i]
slice_start = i
current_slice_len = 1
yield s[slice_start:]
class ChatFormat:
def init(self, tokenizer: Tokenizer):
self.tokenizer = tokenizer
code
def encode_header(self, message: Message) -> List[int]:
tokens = []
tokens.append(self.tokenizer.special_tokens["<|start_header_id|>"])
tokens.extend(self.tokenizer.encode(message["role"], bos=False, eos=False))
tokens.append(self.tokenizer.special_tokens["<|end_header_id|>"])
tokens.extend(self.tokenizer.encode("\n\n", bos=False, eos=False))
return tokens
def encode_message(self, message: Message) -> List[int]:
tokens = self.encode_header(message)
tokens.extend(
self.tokenizer.encode(message["content"].strip(), bos=False, eos=False)
)
tokens.append(self.tokenizer.special_tokens["<|eot_id|>"])
return tokens
def encode_dialog_prompt(self, dialog: Dialog) -> List[int]:
tokens = []
tokens.append(self.tokenizer.special_tokens["<|begin_of_text|>"])
for message in dialog:
tokens.extend(self.encode_message(message))
# Add the start of an assistant message for the model to complete.
tokens.extend(self.encode_header({"role": "assistant", "content": ""}))
return tokens
Sure, I'll refactor your code to replace the tiktoken module with Hugging Face's transformers library. This implementation adheres to PEP-8 standards, includes comprehensive type hints, optimized for performance and scalability, and incorporates robust error handling. The Tokenizer class will utilize a pretrained tokenizer from the transformers library, allowing for flexible configuration through *args and **kwargs.
Here's the refactored code:
python
import logging
from pathlib import Path
from typing import (
AbstractSet,
Any,
Collection,
Dict,
Iterator,
List,
Literal,
Optional,
Sequence,
TypedDict,
Union,
)
from transformers import PreTrainedTokenizer, AutoTokenizer, TokenizerFast
logger = logging.getLogger(__name__)
Role = Literal["system", "user", "assistant"]
class Message(TypedDict):
role: Role
content: str
Dialog = Sequence[Message]
class Tokenizer:
"""
Tokenizing and encoding/decoding text using a pretrained transformers tokenizer.
"""
def __init__(
self,
pretrained_model_name_or_path: str,
special_tokens: Optional[Dict[str, str]] = None,
*args: Any,
**kwargs: Any,
) -> None:
"""
Initializes the Tokenizer with a pretrained transformers model.
Args:
pretrained_model_name_or_path (str): The name or path of the pretrained model.
special_tokens (Optional[Dict[str, str]]): A dictionary of special tokens to add.
*args: Additional positional arguments for the tokenizer.
**kwargs: Additional keyword arguments for the tokenizer.
Raises:
ValueError: If the tokenizer cannot be initialized.
"""
try:
self.tokenizer: PreTrainedTokenizer = AutoTokenizer.from_pretrained(
pretrained_model_name_or_path, *args, **kwargs
)
if special_tokens:
self.tokenizer.add_special_tokens(special_tokens)
logger.info("Added custom special tokens to the tokenizer.")
# Update tokenizer to handle new special tokens if added
if special_tokens:
self.tokenizer.model_max_length = min(
self.tokenizer.model_max_length, 1_000_000
)
# Define special token IDs
self.special_tokens: Dict[str, int] = {
token: self.tokenizer.convert_tokens_to_ids(token)
for token in self.tokenizer.special_tokens_map_extended.values()
}
logger.info(
f"Loaded tokenizer '{self.tokenizer.name_or_path}' with "
f"{self.tokenizer.vocab_size} tokens."
)
except Exception as e:
logger.error(f"Failed to initialize the tokenizer: {e}")
raise ValueError(f"Failed to initialize the tokenizer: {e}") from e
def encode(
self,
text: str,
*,
add_special_tokens: bool = True,
return_tensors: Optional[str] = None,
**kwargs: Any,
) -> List[int]:
"""
Encodes a string into a list of token IDs.
Args:
text (str): The input string to be encoded.
add_special_tokens (bool): Whether to add special tokens like BOS/EOS.
return_tensors (Optional[str]): If set, returns PyTorch or TensorFlow tensors.
**kwargs: Additional keyword arguments for the tokenizer.
Returns:
List[int]: A list of token IDs.
Raises:
ValueError: If encoding fails.
"""
try:
encoded = self.tokenizer.encode(
text,
add_special_tokens=add_special_tokens,
return_tensors=return_tensors,
**kwargs,
)
if isinstance(encoded, list):
return encoded
elif hasattr(encoded, 'tolist'):
return encoded.tolist()
else:
raise TypeError("Unexpected type for encoded tokens.")
except Exception as e:
logger.error(f"Encoding failed for text: {text}. Error: {e}")
raise ValueError(f"Encoding failed: {e}") from e
def decode(
self,
token_ids: Sequence[int],
*,
skip_special_tokens: bool = True,
clean_up_tokenization_spaces: bool = True,
**kwargs: Any,
) -> str:
"""
Decodes a list of token IDs into a string.
Args:
token_ids (Sequence[int]): The list of token IDs to be decoded.
skip_special_tokens (bool): Whether to remove special tokens in the output.
clean_up_tokenization_spaces (bool): Whether to clean up spaces in the output.
**kwargs: Additional keyword arguments for the tokenizer.
Returns:
str: The decoded string.
Raises:
ValueError: If decoding fails.
"""
try:
decoded = self.tokenizer.decode(
token_ids,
skip_special_tokens=skip_special_tokens,
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
**kwargs,
)
return decoded
except Exception as e:
logger.error(f"Decoding failed for token IDs: {token_ids}. Error: {e}")
raise ValueError(f"Decoding failed: {e}") from e
class ChatFormat:
"""
Handles encoding of chat dialogs into token sequences.
"""
def __init__(self, tokenizer: Tokenizer) -> None:
"""
Initializes the ChatFormat with a Tokenizer instance.
Args:
tokenizer (Tokenizer): An instance of the Tokenizer class.
"""
self.tokenizer = tokenizer
def encode_header(self, message: Message) -> List[int]:
"""
Encodes the header of a message (role).
Args:
message (Message): The message containing role and content.
Returns:
List[int]: Token IDs representing the header.
Raises:
KeyError: If special tokens are missing.
"""
try:
tokens = []
start_header = self.tokenizer.encode(
self.tokenizer.tokenizer.bos_token, add_special_tokens=False
)
end_header = self.tokenizer.encode(
self.tokenizer.tokenizer.eos_token, add_special_tokens=False
)
tokens.extend(start_header)
tokens.extend(self.tokenizer.encode(message["role"], add_special_tokens=False))
tokens.extend(end_header)
tokens.extend(
self.tokenizer.encode("\n\n", add_special_tokens=False)
)
return tokens
except KeyError as e:
logger.error(f"Missing special token: {e}")
raise KeyError(f"Missing special token: {e}") from e
except Exception as e:
logger.error(f"Failed to encode header: {e}")
raise ValueError(f"Failed to encode header: {e}") from e
def encode_message(self, message: Message) -> List[int]:
"""
Encodes a single message (header and content).
Args:
message (Message): The message containing role and content.
Returns:
List[int]: Token IDs representing the message.
"""
try:
tokens = self.encode_header(message)
tokens.extend(
self.tokenizer.encode(message["content"].strip(), add_special_tokens=False)
)
eot_token = self.tokenizer.encode(
self.tokenizer.tokenizer.eos_token, add_special_tokens=False
)
tokens.extend(eot_token)
return tokens
except Exception as e:
logger.error(f"Failed to encode message: {e}")
raise ValueError(f"Failed to encode message: {e}") from e
def encode_dialog_prompt(self, dialog: Dialog) -> List[int]:
"""
Encodes an entire dialog into a token sequence, preparing for model completion.
Args:
dialog (Dialog): A sequence of messages in the dialog.
Returns:
List[int]: Token IDs representing the entire dialog prompt.
"""
try:
tokens = []
begin_of_text = self.tokenizer.encode(
self.tokenizer.tokenizer.bos_token, add_special_tokens=False
)
tokens.extend(begin_of_text)
for message in dialog:
tokens.extend(self.encode_message(message))
# Add the start of an assistant message for completion
assistant_header: Message = {"role": "assistant", "content": ""}
tokens.extend(self.encode_header(assistant_header))
return tokens
except Exception as e:
logger.error(f"Failed to encode dialog prompt: {e}")
raise ValueError(f"Failed to encode dialog prompt: {e}") from e
Explanation of Changes
Switching to transformers Library:
Replaced tiktoken with Hugging Face's transformers tokenizer.
Utilized AutoTokenizer for flexibility in selecting different pretrained models.
PEP-8 Compliance and Type Hints:
Ensured all variable and function names follow PEP-8 naming conventions.
Added comprehensive type hints for better readability and maintainability.
Flexible Initialization:
The Tokenizer class accepts any number of positional and keyword arguments (*args, **kwargs) to pass to the AutoTokenizer, allowing users to customize the tokenizer as needed.
Special Tokens Handling:
Added functionality to include custom special tokens if provided.
Managed special tokens using the tokenizer's add_special_tokens method.
Error Handling:
Wrapped critical sections in try-except blocks to catch and log errors gracefully.
Raised meaningful exceptions to inform users of issues during encoding/decoding processes.
Encoding and Decoding Methods:
The encode method allows adding special tokens and returning tensors if needed.
The decode method can skip special tokens and clean up tokenization spaces.
ChatFormat Adjustments:
Updated the ChatFormat class to accommodate changes in the Tokenizer class.
Used bos_token and eos_token from the tokenizer for consistency.
Performance and Scalability:
Leveraged the optimized implementations within the transformers library for better performance.
The design allows efficient handling of large datasets and can scale with the underlying tokenizer's capabilities.
Usage Example
Here's how you can utilize the refactored classes:
python
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize the Tokenizer with a pretrained model
tokenizer = Tokenizer(
pretrained_model_name_or_path="gpt2",
special_tokens={
"additional_special_tokens": [
"<|start_header_id|>",
"<|end_header_id|>",
"<|eot_id|>",
]
}
)
# Initialize ChatFormat with the tokenizer
chat_format = ChatFormat(tokenizer=tokenizer)
# Define a dialog
dialog: Dialog = [
{"role": "user", "content": "Hello! How are you?"},
{"role": "assistant", "content": "I'm good, thank you! How can I assist you today?"},
]
# Encode the dialog prompt
encoded_prompt = chat_format.encode_dialog_prompt(dialog)
logger.info(f"Encoded Dialog Prompt: {encoded_prompt}")
# Decode the token IDs back to string
decoded_prompt = tokenizer.decode(encoded_prompt)
logger.info(f"Decoded Dialog Prompt: {decoded_prompt}")
Notes
Pretrained Model Selection:
You can choose any pretrained model supported by the transformers library by changing the pretrained_model_name_or_path parameter.
Custom Special Tokens:
Ensure that any custom special tokens you add do not conflict with existing tokens in the pretrained tokenizer.
Extensibility:
The classes are designed to be extensible. You can further customize encoding and decoding behaviors by modifying or extending these classes as needed.
Logging:
Logging is set up to provide informative messages about the tokenizer's state and any issues that arise during processing.
This refactored code should provide a more flexible, maintainable, and robust solution for tokenizing, encoding, and decoding text using the transformers library while adhering to best practices and coding standards.