It looks like you're working on a text preprocessing pipeline for preparing data to feed into a transformer model using the Hugging Face library. You've identified some drawbacks in your current implementation:
- Handling files with inconsistent line content and empty lines.
- Ensuring all tensors are the same size with appropriate padding strategies.
- Returning
input_ids, attention_mask, and labels.
- Modernizing data collection and loading strategies for novelty and efficiency.
Let's address each point and provide suggestions to improve your code.
1. Handling Files with Inconsistent Line Content and Empty Lines
Your current read_txt_files function reads the content of each .txt file and cleans it up by stripping whitespace and handling empty lines. However, if a file contains just one line of content and multiple empty lines, this might not be handled optimally.
Suggestion:
- Instead of stripping out all empty lines, consider preserving the structure of the text or handling consecutive empty lines properly.
- Use more robust text normalization and preprocessing techniques to handle edge cases.
Updated read_txt_files Function:
def read_txt_files(directory: str) -> List[str]:
"""
Reads all .txt files from the given directory and returns a list of their contents.
"""
contents = []
try:
for filename in os.listdir(directory):
if filename.endswith('.txt'):
file_path = os.path.join(directory, filename)
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Optionally, replace multiple newlines with a single newline
content = '\n'.join([line for line in content.splitlines() if line.strip() != ''])
contents.append(content)
except Exception as e:
print(f"An error occurred while reading files: {e}")
return contents
2. Ensuring All Tensors Are the Same Size with Padding
Your goal is to have all input tensors of the same size, even when data is missing. Appropriate padding strategies are essential for this.
Suggestion:
- Utilize the tokenizer's built-in padding functionality.
- Specify
padding='max_length' and truncation=True in the tokenizer.encode or tokenizer.batch_encode_plus methods.
Updated Tokenization Function:
Instead of manually handling padding and attention masks, let the tokenizer handle it.
def tokenize_texts(
texts: List[str],
tokenizer: PreTrainedTokenizer,
max_length: int
) -> Dict[str, List[List[int]]]:
"""
Tokenizes a list of texts, handling padding and truncation automatically.
"""
# Tokenize texts using batch_encode_plus or __call__
encoding = tokenizer(
texts,
max_length=max_length,
padding='max_length',
truncation=True,
return_tensors='pt', # Return PyTorch tensors
return_attention_mask=True
)
return encoding
3. Returning input_ids, attention_mask, and labels
To prepare data for training a language model, you need to return input_ids, attention_mask, and labels. Labels are usually the target tokens you're trying to predict. In causal language modeling, the labels are the same as input_ids, but shifted.
Suggestion:
- Include the
labels in your returned dictionary.
- For causal language modeling, you can use the same
input_ids as labels.
Updated Tokenization with Labels:
def tokenize_texts_with_labels(
texts: List[str],
tokenizer: PreTrainedTokenizer,
max_length: int
) -> Dict[str, torch.Tensor]:
"""
Tokenizes a list of texts and returns input_ids, attention_mask, and labels.
"""
encoding = tokenizer(
texts,
max_length=max_length,
padding='max_length',
truncation=True,
return_tensors='pt', # Return PyTorch tensors
return_attention_mask=True
)
# For language modeling, labels are usually the same as input_ids
encoding['labels'] = encoding['input_ids'].clone()
return encoding
4. Modernizing Data Collection and Loading Strategies
Your current data loading strategy can be improved by using modern libraries and practices, such as:
- Using the
datasets library from Hugging Face for data handling.
- Leveraging PyTorch's
Dataset and DataLoader classes for efficient data loading and batching.
- Implementing streaming datasets if the dataset is large.
Suggestion:
- Convert your data into a
Dataset object.
- Use
DataLoader for batch processing.
Implementing a Custom Dataset:
from torch.utils.data import Dataset, DataLoader
class TextDataset(Dataset):
def __init__(self, texts, tokenizer, max_length):
self.examples = tokenize_texts_with_labels(texts, tokenizer, max_length)
def __len__(self):
return len(self.examples['input_ids'])
def __getitem__(self, idx):
item = {key: val[idx] for key, val in self.examples.items()}
return item
# In your main function
def main():
# ... (previous code)
texts = read_txt_files(directory)
# Initialize the dataset
dataset = TextDataset(texts, tokenizer, max_length)
# Create a DataLoader
dataloader = DataLoader(dataset, batch_size=16, shuffle=True)
# Example iteration
for batch in dataloader:
input_ids = batch['input_ids']
attention_mask = batch['attention_mask']
labels = batch['labels']
# Now you can feed these into your model
# outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
pass
Alternatively, using the Hugging Face datasets library:
from datasets import Dataset
import pandas as pd
def main():
# ... (previous code)
texts = read_txt_files(directory)
df = pd.DataFrame({'text': texts})
dataset = Dataset.from_pandas(df)
def tokenize_function(examples):
encoding = tokenizer(
examples['text'],
max_length=max_length,
padding='max_length',
truncation=True,
)
encoding['labels'] = encoding['input_ids'].copy()
return encoding
tokenized_dataset = dataset.map(tokenize_function, batched=True)
tokenized_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
# Create a DataLoader
dataloader = DataLoader(tokenized_dataset, batch_size=16, shuffle=True)
# Example iteration
for batch in dataloader:
input_ids = batch['input_ids']
attention_mask = batch['attention_mask']
labels = batch['labels']
# Use these tensors in your model
pass
Benefits of Using datasets Library:
- Efficient data handling, even with large datasets.
- Built-in support for multiprocessing and optimized data operations.
- Easy integration with Hugging Face tokenizers and models.
Additional Improvements and Best Practices
-
Tokenizer Special Tokens: Instead of manually adding special tokens and handling them, ensure that your tokenizer and model use the same special tokens configurations.
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased', use_fast=True)
BERT typically does not have a BOS or EOS token, but if you're adapting it for language modeling, consider using a model that is designed for that purpose, like GPT-2.
-
Model Selection: If you're performing language modeling, models like GPT-2 or other causal language models are more suitable than BERT, which is designed for masked language modeling.
-
Padding Side: Ensure that the padding side is consistent with the model's expectations (usually right padding).
tokenizer.padding_side = 'right'
-
Handling Empty Texts: When processing texts, you might want to filter out or handle empty strings to avoid processing errors.
-
Logging and Error Handling: Implement logging instead of print statements for better debug capabilities.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Replace print statements with logger
logger.info(f"Number of tokenized inputs: {len(tokenized_dataset)}")
Putting It All Together
Here's a revised version of your code with the improvements:
import os
from typing import List, Dict
from transformers import PreTrainedTokenizer, AutoTokenizer
from datasets import Dataset
import pandas as pd
from torch.utils.data import DataLoader
def read_txt_files(directory: str) -> List[str]:
contents = []
try:
for filename in os.listdir(directory):
if filename.endswith('.txt'):
file_path = os.path.join(directory, filename)
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Replace multiple newlines with a single newline
content = '\n'.join([line for line in content.splitlines() if line.strip() != ''])
contents.append(content)
except Exception as e:
print(f"An error occurred while reading files: {e}")
return contents
def main():
directory = '/scratch/hemanth/Hemanth/localdataset' # Replace with your directory path
max_length = 512 # Define your desired max sequence length
# Initialize the tokenizer
tokenizer = AutoTokenizer.from_pretrained('gpt2', use_fast=True)
# GPT-2 does not have a padding token by default
if tokenizer.pad_token is None:
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
tokenizer.pad_token = '[PAD]'
# Read the texts from files
texts = read_txt_files(directory)
# Create a Dataset
df = pd.DataFrame({'text': texts})
dataset = Dataset.from_pandas(df)
def tokenize_function(examples):
encoding = tokenizer(
examples['text'],
max_length=max_length,
padding='max_length',
truncation=True,
)
# For language modeling, labels are input_ids shifted by one
encoding['labels'] = encoding['input_ids'].copy()
return encoding
tokenized_dataset = dataset.map(tokenize_function, batched=True)
tokenized_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
# Create a DataLoader
dataloader = DataLoader(tokenized_dataset, batch_size=4, shuffle=True)
# Now you can use the dataloader in your training loop
for batch in dataloader:
input_ids = batch['input_ids']
attention_mask = batch['attention_mask']
labels = batch['labels']
# Feed these into your model
# outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
pass
print('Data loading and tokenization complete.')
if __name__ == '__main__':
main()
Notes:
- Switched to using GPT-2, which is better suited for language modeling tasks where you predict the next word.
- Added a padding token to the GPT-2 tokenizer since it doesn't have one by default.
- Used the
datasets library for modern and efficient data handling.
- The
tokenize_function handles tokenization and creates labels.
- The
DataLoader batches the data for efficient training.
Conclusion
By applying these improvements:
- Your code now handles empty lines and inconsistent content more robustly.
- Padding is managed efficiently, ensuring all tensors are of the same size.
- The data loaders return
input_ids, attention_mask, and labels.
- The data collection and loading strategy is modernized, making use of the
datasets library and PyTorch's data utilities.
These changes should enhance the performance of your data preprocessing pipeline and make it more adaptable to different datasets and models.
If you have any questions or need further assistance with specific parts of the code, feel free to ask!