import os
import logging
from pathlib import Path
from typing import (
AbstractSet,
Collection,
Dict,
Iterator,
List,
Literal,
Sequence,
TypedDict,
Union,
Optional,
)
from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast, AutoTokenizer
from transformers.tokenization_utils import BatchEncoding
logger = logging.getLogger(name)
Role = Literal["system", "user", "assistant"]
class Message(TypedDict):
role: Role
content: str
Assistant
Dialog = Sequence[Message]
class Tokenizer:
"""
Tokenizing and encoding/decoding text using the Hugging Face Transformers tokenizer.
"""
code
def __init__(self, model_name_or_path: str):
"""
Initializes the Tokenizer with a Transformers model.
Args:
model_name_or_path (str): The name or path to the Hugging Face Transformers model.
"""
# if not isinstance(model_name_or_path, str):
# raise TypeError("model_name_or_path must be a string.")
# if not os.path.isdir(model_name_or_path) and not os.path.isfile(model_name_or_path):
# raise ValueError(f"Invalid model path or name: {model_name_or_path}")
try:
self.tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(
pretrained_model_name_or_path=model_name_or_path, use_fast=True
)
if not isinstance(self.tokenizer, PreTrainedTokenizerFast):
self.tokenizer = PreTrainedTokenizerFast.from_pretrained(pretrained_model_name_or_path=model_name_or_path)
logger.info(f"Loaded tokenizer from {model_name_or_path}")
except Exception as e:
logger.error(f"Failed to load tokenizer from {model_name_or_path}: {e}")
raise
self.bos_token_id: Optional[int] = self.tokenizer.bos_token_id
self.eos_token_id: Optional[int] = self.tokenizer.eos_token_id
self.pad_token_id: Optional[int] = self.tokenizer.pad_token_id
self.stop_tokens = set(filter(None, [self.eos_token_id]))
logger.info(
f"Tokenizer initialized with BOS ID: {self.bos_token_id}, "
f"EOS ID: {self.eos_token_id}, PAD ID: {self.pad_token_id}"
)
def encode(
self,
text: str,
add_bos: bool = False,
add_eos: bool = False,
allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = (),
max_length: Optional[int] = None,
truncation: bool = True,
) -> List[int]:
"""
Encodes a string into a list of token IDs.
Args:
text (str): The input string to be encoded.
add_bos (bool): Whether to prepend the beginning-of-sequence token.
add_eos (bool): Whether to append the end-of-sequence token.
allowed_special ("all" | set[str]): Allowed special tokens in string.
disallowed_special ("all" | Collection[str]): Special tokens that raise an error when present in string.
max_length (Optional[int]): Maximum length of the encoded sequence.
truncation (bool): Whether to truncate the sequence to max_length.
Returns:
List[int]: A list of token IDs.
"""
if not isinstance(text, str):
raise TypeError("Input text must be a string.")
try:
encoding: BatchEncoding = self.tokenizer.encode_plus(
text,
add_special_tokens=False,
return_attention_mask=False,
return_token_type_ids=False,
max_length=max_length,
truncation=truncation,
# allow_special_tokens=True,
)
tokens = encoding['input_ids']
except Exception as e:
logger.error(f"Encoding failed for text: {text[:50]}... Error: {e}")
raise
if add_bos and self.bos_token_id is not None:
tokens.insert(0, self.bos_token_id)
if add_eos and self.eos_token_id is not None:
tokens.append(self.eos_token_id)
return tokens
def decode(self, tokens: Sequence[int], skip_special_tokens: bool = True) -> str:
"""
Decodes a list of token IDs into a string.
Args:
tokens (Sequence[int]): The list of token IDs to be decoded.
skip_special_tokens (bool): Whether to skip special tokens during decoding.
Returns:
str: The decoded string.
"""
if not all(isinstance(token, int) for token in tokens):
raise TypeError("All tokens must be integers.")
try:
decoded_text: str = self.tokenizer.decode(
tokens, skip_special_tokens=skip_special_tokens
)
return decoded_text
except Exception as e:
logger.error(f"Decoding failed for tokens: {tokens[:10]}... Error: {e}")
raise
class ChatFormat:
"""
Formats chat dialogs into token sequences suitable for model input.
"""
code
def __init__(self, tokenizer: Tokenizer):
if not isinstance(tokenizer, Tokenizer):
raise TypeError("tokenizer must be an instance of Tokenizer.")
self.tokenizer = tokenizer
def encode_header(self, message: Message) -> List[int]:
"""
Encodes the header of a message (e.g., role).
Args:
message (Message): The message containing role and content.
Returns:
List[int]: Token IDs representing the encoded header.
"""
tokens = []
start_header = "<|start_header_id|>"
end_header = "<|end_header_id|>"
start_header_id = self.tokenizer.tokenizer.convert_tokens_to_ids(start_header)
end_header_id = self.tokenizer.tokenizer.convert_tokens_to_ids(end_header)
if start_header_id is None or end_header_id is None:
logger.error("Special tokens for headers are not defined in the tokenizer.")
raise ValueError("Missing special header tokens in tokenizer.")
tokens.append(start_header_id)
role_encoded = self.tokenizer.encode(message["role"], add_bos=False, add_eos=False)
tokens.extend(role_encoded)
tokens.append(end_header_id)
newline_encoded = self.tokenizer.encode("\n\n", add_bos=False, add_eos=False)
tokens.extend(newline_encoded)
return tokens
def encode_message(self, message: Message) -> List[int]:
"""
Encodes a single message into token IDs.
Args:
message (Message): The message to encode.
Returns:
List[int]: Token IDs representing the encoded message.
"""
tokens = self.encode_header(message)
content_encoded = self.tokenizer.encode(message["content"].strip(), add_bos=False, add_eos=False)
tokens.extend(content_encoded)
eot_token = "<|eot_id|>"
eot_id = self.tokenizer.tokenizer.convert_tokens_to_ids(eot_token)
if eot_id is None:
logger.error(f"Special token {eot_token} is not defined in the tokenizer.")
raise ValueError("Missing end-of-turn token in tokenizer.")
tokens.append(eot_id)
return tokens
def encode_dialog_prompt(self, dialog: Dialog) -> List[int]:
"""
Encodes an entire dialog into a prompt suitable for model input.
Args:
dialog (Dialog): A sequence of messages forming the dialog.
Returns:
List[int]: Token IDs representing the encoded dialog prompt.
"""
tokens = []
begin_of_text = "<|begin_of_text|>"
begin_of_text_id = self.tokenizer.tokenizer.convert_tokens_to_ids(begin_of_text)
if begin_of_text_id is None:
logger.error("Special token <|begin_of_text|> is not defined in the tokenizer.")
raise ValueError("Missing <|begin_of_text|> token in tokenizer.")
tokens.append(begin_of_text_id)
for message in dialog:
tokens.extend(self.encode_message(message))
# Add the start of an assistant message for the model to complete.
assistant_message: Message = {"role": "assistant", "content": ""}
tokens.extend(self.encode_header(assistant_message))
return tokens
import logging
Configure logging
logging.basicConfig(level=logging.INFO)
Initialize the tokenizer with a pre-trained model or a local path
tokenizer = Tokenizer("gpt2") # Replace with your model path or name
Initialize ChatFormat with the tokenizer
chat_format = ChatFormat(tokenizer=tokenizer)
Define a sample dialog
dialog = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"},
{"role": "assistant", "content": "I'm doing well, thank you! How can I assist you today?"},
]
Sure, I can help you implement a generalized robustness tokenization pipeline using the Hugging Face Transformers library while adhering strictly to PEP-8 standards, incorporating type hints, optimizing for performance, and ensuring comprehensive error handling. Below is a complete implementation based on your specifications.
Overview
The implementation consists of the following components:
Tokenizer Class: Handles encoding and decoding of text using a pre-trained Transformers tokenizer. It supports various parameters to customize the tokenization process.
ChatFormat Class: Formats chat dialogs into token sequences suitable for model input, handling roles and content encoding.
Utility Functions: Implements the apply_chat_template function to process conversations, apply templates, and tokenize the input.
Sample Usage: Demonstrates how to use the implemented classes and functions with a sample dialog.
Let's dive into the implementation.
Implementation
python
import logging
import os
from pathlib import Path
from typing import (
Any,
Dict,
List,
Literal,
Optional,
Sequence,
Tuple,
Union,
)
from numpy import ndarray
from torch import Tensor
from transformers import (
AutoTokenizer,
PaddingStrategy,
PreTrainedTokenizerFast,
TruncationStrategy,
)
from transformers.tokenization_utils import BatchEncoding
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Type Definitions
Role = Literal["system", "user", "assistant"]
class Message(Dict[str, str]):
"""
Represents a single message in a dialogue.
"""
role: Role
content: str
Dialog = Sequence[Message]
class Tokenizer:
"""
Tokenizing and encoding/decoding text using the Hugging Face Transformers tokenizer.
"""
def __init__(self, model_name_or_path: str):
"""
Initializes the Tokenizer with a Transformers model.
Args:
model_name_or_path (str): The name or path to the Hugging Face Transformers model.
"""
if not isinstance(model_name_or_path, str):
logger.error("model_name_or_path must be a string.")
raise TypeError("model_name_or_path must be a string.")
if not (
os.path.isdir(model_name_or_path)
or os.path.isfile(model_name_or_path)
):
logger.error(f"Invalid model path or name: {model_name_or_path}")
raise ValueError(f"Invalid model path or name: {model_name_or_path}")
try:
self.tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(
pretrained_model_name_or_path=model_name_or_path, use_fast=True
)
if not isinstance(self.tokenizer, PreTrainedTokenizerFast):
logger.warning(
"Loaded tokenizer is not a PreTrainedTokenizerFast instance. "
"Attempting to convert to PreTrainedTokenizerFast."
)
self.tokenizer = PreTrainedTokenizerFast.from_pretrained(
pretrained_model_name_or_path=model_name_or_path
)
logger.info(f"Loaded tokenizer from {model_name_or_path}")
except Exception as e:
logger.error(f"Failed to load tokenizer from {model_name_or_path}: {e}")
raise RuntimeError(
f"Failed to load tokenizer from {model_name_or_path}: {e}"
) from e
self.bos_token_id: Optional[int] = self.tokenizer.bos_token_id
self.eos_token_id: Optional[int] = self.tokenizer.eos_token_id
self.pad_token_id: Optional[int] = self.tokenizer.pad_token_id
self.stop_tokens = set(filter(None, [self.eos_token_id]))
logger.info(
f"Tokenizer initialized with BOS ID: {self.bos_token_id}, "
f"EOS ID: {self.eos_token_id}, PAD ID: {self.pad_token_id}"
)
def encode(
self,
text: Union[str, List[str], List[List[str]]],
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
stride: int = 0,
is_split_into_words: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, Any]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs: Any,
) -> Union[List[int], BatchEncoding]:
"""
Encodes input text into token IDs using the tokenizer's encode_plus method.
Args:
text (str | List[str] | List[List[str]]): The input text to encode.
add_special_tokens (bool): Whether to add special tokens.
padding (bool | str | PaddingStrategy): Padding strategy.
truncation (bool | str | TruncationStrategy): Truncation strategy.
max_length (int | None): Maximum sequence length.
stride (int): Stride for overflowing tokens.
is_split_into_words (bool): Whether the input is already split into words.
pad_to_multiple_of (int | None): Pad to a multiple of this value.
return_tensors (str | Any | None): Return tensors of this type.
return_token_type_ids (bool | None): Whether to return token type IDs.
return_attention_mask (bool | None): Whether to return attention masks.
return_overflowing_tokens (bool): Whether to return overflowing tokens.
return_special_tokens_mask (bool): Whether to return special tokens mask.
return_offsets_mapping (bool): Whether to return offsets mapping.
return_length (bool): Whether to return the length of each input.
verbose (bool): Whether to log detailed information.
**kwargs (Any): Additional keyword arguments.
Returns:
List[int] | BatchEncoding: Encoded tokens as a list or BatchEncoding object.
"""
if not isinstance(text, (str, list)):
logger.error("Input text must be a string or a list of strings.")
raise TypeError("Input text must be a string or a list of strings.")
try:
encoding: BatchEncoding = self.tokenizer.encode_plus(
text=text,
text_pair=None,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
is_split_into_words=is_split_into_words,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
**kwargs,
)
if verbose:
logger.debug(f"Encoded input: {encoding}")
return encoding["input_ids"]
except Exception as e:
logger.error(f"Encoding failed for text: {text} Error: {e}")
raise RuntimeError(f"Encoding failed: {e}") from e
def decode(
self,
token_ids: Union[int, List[int], ndarray, Tensor, Any],
skip_special_tokens: bool = False,
clean_up_tokenization_spaces: Optional[bool] = None,
**kwargs: Any,
) -> str:
"""
Decodes token IDs back into a string.
Args:
token_ids (int | List[int] | ndarray | Tensor | Any): The token IDs to decode.
skip_special_tokens (bool): Whether to skip special tokens.
clean_up_tokenization_spaces (bool | None): Whether to clean up spaces.
**kwargs (Any): Additional keyword arguments.
Returns:
str: The decoded string.
"""
if isinstance(token_ids, int):
token_ids = [token_ids]
elif isinstance(token_ids, ndarray) or isinstance(token_ids, Tensor):
token_ids = token_ids.tolist()
elif not isinstance(token_ids, list):
logger.error(
"token_ids must be an int, list of ints, ndarray, or Tensor."
)
raise TypeError(
"token_ids must be an int, list of ints, ndarray, or Tensor."
)
if not all(isinstance(token, int) for token in token_ids):
logger.error("All token IDs must be integers.")
raise ValueError("All token IDs must be integers.")
try:
decoded_text: str = self.tokenizer.decode(
token_ids,
skip_special_tokens=skip_special_tokens,
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
**kwargs,
)
logger.debug(f"Decoded text: {decoded_text}")
return decoded_text
except Exception as e:
logger.error(f"Decoding failed for tokens: {token_ids} Error: {e}")
raise RuntimeError(f"Decoding failed: {e}") from e
class ChatFormat:
"""
Formats chat dialogs into token sequences suitable for model input.
"""
def __init__(self, tokenizer: Tokenizer):
"""
Initializes the ChatFormat with a Tokenizer instance.
Args:
tokenizer (Tokenizer): An instance of the Tokenizer class.
"""
if not isinstance(tokenizer, Tokenizer):
logger.error("tokenizer must be an instance of Tokenizer.")
raise TypeError("tokenizer must be an instance of Tokenizer.")
self.tokenizer = tokenizer
def encode_header(self, message: Message) -> List[int]:
"""
Encodes the header of a message (e.g., role).
Args:
message (Message): The message containing role and content.
Returns:
List[int]: Token IDs representing the encoded header.
"""
tokens = []
start_header = "<|start_header|>"
end_header = "<|end_header|>"
start_header_id = self.tokenizer.tokenizer.convert_tokens_to_ids(start_header)
end_header_id = self.tokenizer.tokenizer.convert_tokens_to_ids(end_header)
if start_header_id is None or end_header_id is None:
logger.error(
"Special tokens for headers are not defined in the tokenizer."
)
raise ValueError("Missing special header tokens in tokenizer.")
tokens.append(start_header_id)
role_encoded = self.tokenizer.encode(
message["role"], add_special_tokens=False
)
tokens.extend(role_encoded)
tokens.append(end_header_id)
newline_encoded = self.tokenizer.encode("\n\n", add_special_tokens=False)
tokens.extend(newline_encoded)
logger.debug(f"Encoded header tokens: {tokens}")
return tokens
def encode_message(self, message: Message) -> List[int]:
"""
Encodes a single message into token IDs.
Args:
message (Message): The message to encode.
Returns:
List[int]: Token IDs representing the encoded message.
"""
tokens = self.encode_header(message)
content_encoded = self.tokenizer.encode(
message["content"].strip(), add_special_tokens=False
)
tokens.extend(content_encoded)
eot_token = "<|eot|>"
eot_id = self.tokenizer.tokenizer.convert_tokens_to_ids(eot_token)
if eot_id is None:
logger.error(f"Special token {eot_token} is not defined in the tokenizer.")
raise ValueError("Missing end-of-turn token in tokenizer.")
tokens.append(eot_id)
logger.debug(f"Encoded message tokens: {tokens}")
return tokens
def encode_dialog_prompt(self, dialog: Dialog) -> List[int]:
"""
Encodes an entire dialog into a prompt suitable for model input.
Args:
dialog (Dialog): A sequence of messages forming the dialog.
Returns:
List[int]: Token IDs representing the encoded dialog prompt.
"""
tokens = []
begin_of_text = "<|begin_of_text|>"
begin_of_text_id = self.tokenizer.tokenizer.convert_tokens_to_ids(begin_of_text)
if begin_of_text_id is None:
logger.error("Special token <|begin_of_text|> is not defined in the tokenizer.")
raise ValueError("Missing <|begin_of_text|> token in tokenizer.")
tokens.append(begin_of_text_id)
for message in dialog:
tokens.extend(self.encode_message(message))
# Add the start of an assistant message for the model to complete.
assistant_message: Message = {"role": "assistant", "content": ""}
tokens.extend(self.encode_header(assistant_message))
logger.debug(f"Encoded dialog prompt tokens: {tokens}")
return tokens
def apply_chat_template(
conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]],
tools: Optional[List[Dict[str, Any]]] = None,
documents: Optional[List[Dict[str, str]]] = None,
chat_template: Optional[str] = None,
add_generation_prompt: bool = False,
tokenize: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = False,
max_length: Optional[int] = None,
return_tensors: Optional[Union[str, Any]] = None,
return_dict: bool = False,
return_assistant_tokens_mask: bool = False,
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Union[str, List[int], List[str], List[List[int]], BatchEncoding]:
"""
Applies a chat template to a conversation and optionally tokenizes it.
Args:
conversation (List[Dict[str, str]] | List[List[Dict[str, str]]]): The conversation history.
tools (List[Dict] | None): Optional tools for the assistant.
documents (List[Dict[str, str]] | None): Optional documents to include.
chat_template (str | None): Optional template to format the chat.
add_generation_prompt (bool): Whether to add a generation prompt.
tokenize (bool): Whether to tokenize the output.
padding (bool | str | PaddingStrategy): Padding strategy.
truncation (bool | str | TruncationStrategy): Truncation strategy.
max_length (int | None): Maximum sequence length.
return_tensors (str | Any | None): Type of tensors to return.
return_dict (bool): Whether to return a dictionary.
return_assistant_tokens_mask (bool): Whether to return a mask for assistant tokens.
tokenizer_kwargs (Dict[str, Any] | None): Additional tokenizer arguments.
**kwargs (Any): Additional keyword arguments.
Returns:
str | List[int] | List[str] | List[List[int]] | BatchEncoding: The formatted and optionally tokenized conversation.
"""
formatted_conversation = ""
if chat_template:
formatted_conversation += chat_template.format(conversation=conversation)
else:
for message in conversation:
formatted_conversation += f"{message['role'].capitalize()}: {message['content']}\n"
if tools:
formatted_conversation += "\nTools:\n"
for tool in tools:
formatted_conversation += f"- {tool['name']}: {tool['description']}\n"
if documents:
formatted_conversation += "\nDocuments:\n"
for doc in documents:
formatted_conversation += f"- {doc['title']}: {doc['content']}\n"
if add_generation_prompt:
formatted_conversation += "\nAssistant:"
if tokenize:
tokenizer = kwargs.get("tokenizer")
if not isinstance(tokenizer, Tokenizer):
logger.error("A valid Tokenizer instance must be provided when tokenize is True.")
raise ValueError("A valid Tokenizer instance must be provided when tokenize is True.")
try:
encoding = tokenizer.encode(
formatted_conversation,
add_special_tokens=True,
padding=padding,
truncation=truncation,
max_length=max_length,
**(tokenizer_kwargs if tokenizer_kwargs else {}),
)
if return_dict:
return encoding
if return_assistant_tokens_mask:
# Placeholder for assistant tokens mask implementation
pass
return encoding
except Exception as e:
logger.error(f"Failed to tokenize the conversation: {e}")
raise RuntimeError(f"Failed to tokenize the conversation: {e}") from e
logger.debug(f"Formatted conversation: {formatted_conversation}")
return formatted_conversation
# Example Usage
if __name__ == "__main__":
# Initialize the tokenizer with a pre-trained model or a local path
try:
tokenizer_instance = Tokenizer("gpt2") # Replace with your model path or name
except Exception as e:
logger.error(f"Failed to initialize Tokenizer: {e}")
raise
# Initialize ChatFormat with the tokenizer
chat_format = ChatFormat(tokenizer=tokenizer_instance)
# Define a sample dialog
sample_dialog: Dialog = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"},
{"role": "assistant", "content": "I'm doing well, thank you! How can I assist you today?"},
]
# Encode the dialog prompt
try:
encoded_prompt = chat_format.encode_dialog_prompt(sample_dialog)
print(f"Encoded Prompt: {encoded_prompt}")
except Exception as e:
logger.error(f"Failed to encode dialog prompt: {e}")
raise
# Decode the encoded prompt back to text
try:
decoded_prompt = tokenizer_instance.decode(encoded_prompt)
print(f"Decoded Prompt:\n{decoded_prompt}")
except Exception as e:
logger.error(f"Failed to decode prompt: {e}")
raise
# Apply chat template and tokenize
try:
formatted_and_tokenized = apply_chat_template(
conversation=sample_dialog,
add_generation_prompt=True,
tokenize=True,
padding='max_length',
truncation=True,
max_length=512,
return_tensors='pt',
tokenizer=tokenizer_instance,
chat_template=None, # You can provide a custom template here
)
print(f"Formatted and Tokenized Prompt: {formatted_and_tokenized}")
except Exception as e:
logger.error(f"Failed to apply chat template: {e}")
raise
Explanation
1. Tokenizer Class
Initialization:
Loads a pre-trained tokenizer using AutoTokenizer.from_pretrained.
Ensures that the tokenizer is an instance of PreTrainedTokenizerFast. If not, it attempts to convert it.
Logs the initialization details, including special token IDs.
Encoding (encode method):
Accepts a variety of input types (str, List[str], List[List[str]]) and encoding parameters.
Uses encode_plus from the Transformers library to perform the encoding with the provided parameters.
Provides comprehensive error handling and logging.
Decoding (decode method):
Supports decoding from various input types (int, List[int], ndarray, Tensor, etc.).
Utilizes the tokenizer's decode method with options to skip special tokens and clean up spaces.
Includes error handling to ensure all token IDs are integers.
2. ChatFormat Class
Initialization: Requires an instance of the Tokenizer class.
Encoding Headers and Messages:
encode_header: Encodes the role of the message (e.g., "system", "user", "assistant") using special tokens.
encode_message: Encodes a complete message, including the header and content, and appends an end-of-turn token.
Encoding Dialog Prompts:
encode_dialog_prompt: Iterates through a sequence of messages (dialog) and encodes each one.
Appends a header for the assistant to generate a response.
3. apply_chat_template Function
Purpose: Formats a conversation using an optional template, includes tools and documents if provided, and tokenizes the output based on given parameters.
Parameters:
Accepts conversation history, optional tools, documents, a chat template, and various tokenization parameters.
Ensures that if tokenization is requested, a valid Tokenizer instance is provided.
Functionality:
Constructs the conversation string based on the provided messages and optional components.
Applies tokenization using the Tokenizer class's encode method if requested.
Returns either the formatted string or the tokenized output based on parameters.
4. Sample Usage
Initialization:
Initializes the Tokenizer with the gpt2 model. Replace "gpt2" with your desired model.
Initializes the ChatFormat with the Tokenizer instance.
Encoding and Decoding:
Defines a sample dialog and encodes it into token IDs.
Decodes the token IDs back into a string to verify the encoding process.
Applying Chat Template:
Demonstrates how to use the apply_chat_template function to format and tokenize the conversation.
Best Practices Implemented
PEP-8 Compliance: The code follows PEP-8 standards for readability and structure, including proper naming conventions and spacing.
Type Hints: Utilizes Python's typing module to provide clear type annotations, enhancing code clarity and maintainability.
Performance Optimization:
Leverages the efficient tokenization methods provided by the Fast tokenizers in Transformers.
Minimizes unnecessary computations and handles different input types efficiently.
Comprehensive Error Handling:
Catches and logs exceptions at each critical operation.
Provides meaningful error messages to aid in debugging and ensure robustness.
Maintainability:
Modular design with clear separation of concerns between tokenization and formatting.
Easy to extend and modify for additional functionalities.
Logging:
Uses Python's logging module to provide detailed logs at various levels (INFO, DEBUG, ERROR).
Helps in tracing the execution flow and diagnosing issues.
Notes
Special Tokens: Ensure that your tokenizer includes the special tokens used (<|start_header|>, <|end_header|>, <|eot|>, <|begin_of_text|>). You might need to add them to your tokenizer's vocabulary and adjust the tokenizer's configuration accordingly.
Custom Chat Template: You can provide a custom chat_template string to the apply_chat_template function to format the conversation differently. The current implementation uses a simple format if no template is provided.
Assistant Tokens Mask: The return_assistant_tokens_mask parameter is a placeholder for further implementation based on specific requirements.
Extensibility: The implementation can be extended to handle more complex scenarios, such as multiple conversations, different roles, or integration with other tools and documents.
Dependencies
Ensure you have the required libraries installed:
bash
pip install transformers torch numpy
Conclusion
This implementation provides a robust, flexible, and maintainable tokenization pipeline using the Hugging Face Transformers library. It adheres to best coding practices, ensuring that the code is readable, efficient, and resilient to errors. You can further customize and extend this pipeline based on your specific application needs.