Draw back : lets assume in some file one line context and 5 line spaces are there (may or may not)
2) all tensor should same size (if data is not there some padding tragies)
3) returns input_ids, attention_mask, labels
data collection and loading stragies are very old , not novelity missing
import os
from typing import List, Dict
from transformers import PreTrainedTokenizer, AutoTokenizer
def read_txt_files(directory: str) -> List[str]:
"""
Reads all .txt files from the given directory and returns a list of their contents.
code
Args:
directory (str): The path to the directory containing .txt files.
Returns:
List[str]: A list of strings, each string is the content of a .txt file.
"""
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()
# Clean up the content by stripping whitespace and handling empty lines
content = '\n'.join(line.strip() 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 split_text(
text: str,
tokenizer: PreTrainedTokenizer,
max_length: int
) -> List[str]:
"""
Splits a text into chunks that fit within the max_length when tokenized.
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Args:
text (str): The text to split.
tokenizer (PreTrainedTokenizer): The tokenizer to use.
max_length (int): The maximum length of the tokenized output.
Returns:
List[str]: A list of text chunks.
"""
words = text.strip().split()
chunks = []
current_chunk = []
current_length = 0
for word in words:
# Encode the word to get its token length
tokenized_word = tokenizer.encode(word, add_special_tokens=False)
word_length = len(tokenized_word)
# Check if adding the word exceeds the max_length
if current_length + word_length > max_length:
if current_chunk:
chunks.append(' '.join(current_chunk))
current_chunk = [word]
current_length = word_length
else:
current_chunk.append(word)
current_length += word_length
if current_chunk:
chunks.append(' '.join(current_chunk))
return chunks
def tokenize_texts(
texts: List[str],
tokenizer: PreTrainedTokenizer,
max_length: int
) -> Dict[str, List[List[int]]]:
"""
Tokenizes a list of texts using the given tokenizer, ensuring zero data loss by splitting long texts.
Adds BOS and EOS tokens manually.
code
Args:
texts (List[str]): The texts to tokenize.
tokenizer (PreTrainedTokenizer): The tokenizer to use.
max_length (int): The maximum length of the tokenized output.
Returns:
Dict[str, List[List[int]]]: A dictionary containing 'input_ids' and 'attention_mask'.
"""
all_input_ids = []
all_attention_masks = []
for text in texts:
# Skip empty texts
if not text:
continue
chunks = split_text(text, tokenizer, max_length - 2) # Reserve space for BOS and EOS tokens
for chunk in chunks:
# Tokenize the chunk without adding any special tokens
tokens = tokenizer.encode(
chunk,
add_special_tokens=False,
max_length=max_length - 2,
truncation=True
)
# Manually add BOS and EOS tokens
tokens = [tokenizer.bos_token_id] + tokens + [tokenizer.eos_token_id]
# Create attention mask
attention_mask = [1] * len(tokens)
# Pad if necessary
if len(tokens) < max_length:
padding_length = max_length - len(tokens)
tokens += [tokenizer.pad_token_id] * padding_length
attention_mask += [0] * padding_length
else:
tokens = tokens[:max_length]
attention_mask = attention_mask[:max_length]
all_input_ids.append(tokens)
all_attention_masks.append(attention_mask)
return {'input_ids': all_input_ids, 'attention_mask': all_attention_masks}
def main():
directory = '/scratch/hemanth/Hemanth/localdataset' # Replace with your directory path
max_length = 512 # Define your desired max sequence length
code
# Initialize the tokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
# Add special tokens if they are not already present
if not tokenizer.special_tokens_map.get('bos_token'):
tokenizer.add_special_tokens({'bos_token': '[BOS]'})
if not tokenizer.special_tokens_map.get('eos_token'):
tokenizer.add_special_tokens({'eos_token': '[EOS]'})
if not tokenizer.special_tokens_map.get('pad_token'):
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
# Adjust the tokenizer to recognize the new special tokens
tokenizer.bos_token = '[BOS]'
tokenizer.eos_token = '[EOS]'
tokenizer.pad_token = '[PAD]'
# Update tokenizer's vocabulary to include the new tokens
tokenizer.save_pretrained('./tokenizer_with_special_tokens')
tokenizer = AutoTokenizer.from_pretrained('./tokenizer_with_special_tokens')
# Read the texts from files
texts = read_txt_files(directory)
# Tokenize the texts
tokenized_data = tokenize_texts(texts, tokenizer, max_length)
print(len(tokenized_data['input_ids']))
# You can now use tokenized_data['input_ids'] and tokenized_data['attention_mask'] for your model
print('Tokenization complete.')
# For example, to see the first tokenized input:
print(tokenized_data['input_ids'][0])
print(tokenized_data['attention_mask'][0])
if name == 'main':
main()
Your current data preprocessing pipeline for handling text data with transformers is functional, but as you've pointed out, it has several drawbacks that could impact performance and scalability. Let's address each of the drawbacks you've listed and suggest improvements to modernize and optimize your approach.
1. Handling Variable Line Contexts and Line Spaces
Drawback:
Assuming files may have one line of context followed by 5 lines of spaces (which may or may not be present) can lead to inconsistent data processing. The current method of stripping empty lines might not adequately capture the intended context or structure of the data.
Improvements:
Structured Parsing: Instead of merely stripping empty lines, implement a more structured parsing approach that recognizes patterns in the data. For example, if your data is organized in blocks separated by empty lines, you can split the text into sections accordingly.
Regular Expressions: Use regular expressions to identify and separate different sections or meaningful chunks of text based on specific patterns.
Metadata Inclusion: If applicable, include metadata (like labels or context indicators) within the files to provide more information during preprocessing.
Revised read_txt_files Function Example:
python
import re
def read_txt_files(directory: str) -> List[str]:
"""
Reads all .txt files from the given directory and returns a list of their contents.
Handles structured data with specific patterns.
Args:
directory (str): The path to the directory containing .txt files.
Returns:
List[str]: A list of strings, each string is the content of a .txt file.
"""
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()
# Example: Split by two or more newlines to separate blocks
blocks = re.split(r'\n{2,}', content)
# Clean each block
cleaned_blocks = ['\n'.join(line.strip() for line in block.splitlines() if line.strip()) for block in blocks]
contents.extend(cleaned_blocks)
except Exception as e:
print(f"An error occurred while reading files: {e}")
return contents
2. Ensuring Consistent Tensor Sizes and Managing Padding
Drawback:
Padding sequences to the same length can introduce inefficiency and potentially degrade model performance if large amounts of padding are added, especially for shorter sequences.
Improvements:
Dynamic Padding: Instead of padding all sequences to a fixed maximum length, pad them dynamically within each batch to the longest sequence in that batch. This reduces the amount of padding and computation.
Efficient Collation: Utilize a custom collate function in your data loader that handles dynamic padding.
Memory Optimization: Consider using data generators or streaming large datasets to manage memory usage effectively.
Implementing Dynamic Padding with Hugging Face's Datasets and DataLoader:
python
from datasets import Dataset
from transformers import DataCollatorWithPadding
from torch.utils.data import DataLoader
# Convert your tokenized data into a Hugging Face Dataset
dataset = Dataset.from_dict(tokenized_data)
# Initialize the data collator for dynamic padding
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
# Create a DataLoader with dynamic padding
dataloader = DataLoader(dataset, batch_size=32, shuffle=True, collate_fn=data_collator)
# Example of iterating through the DataLoader
for batch in dataloader:
input_ids = batch['input_ids']
attention_mask = batch['attention_mask']
# Pass to model or further processing
This approach ensures that each batch is padded only to the length of the longest sequence in that batch, reducing unnecessary padding and computation.
3. Returning input_ids, attention_mask, and labels
Drawback:
Your current implementation returns only input_ids and attention_mask. For supervised learning tasks, including labels is essential.
Improvements:
Label Integration: Modify your data processing pipeline to include labels. This could involve reading labels from the file names, a separate label file, or embedded within the text files.
Alignment of Inputs and Labels: Ensure that each input sequence has a corresponding label. This alignment is crucial for training models effectively.
Revised Tokenization Function with Labels:
Assuming that labels are embedded in the first line of each text file or can be extracted accordingly:
python
def read_txt_files_with_labels(directory: str) -> List[Dict[str, str]]:
"""
Reads all .txt files from the given directory and returns a list of dictionaries with content and label.
Args:
directory (str): The path to the directory containing .txt files.
Returns:
List[Dict[str, str]]: A list of dictionaries with 'text' and 'label'.
"""
data = []
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:
lines = file.readlines()
if not lines:
continue
label = lines[0].strip() # Assuming the first line is the label
content = '\n'.join(line.strip() for line in lines[1:] if line.strip())
data.append({'text': content, 'label': label})
except Exception as e:
print(f"An error occurred while reading files: {e}")
return data
def tokenize_texts_with_labels(
data: List[Dict[str, str]],
tokenizer: PreTrainedTokenizer,
max_length: int
) -> Dataset:
"""
Tokenizes texts and aligns them with labels.
Args:
data (List[Dict[str, str]]): List containing 'text' and 'label'.
tokenizer (PreTrainedTokenizer): The tokenizer to use.
max_length (int): Maximum sequence length.
Returns:
Dataset: Hugging Face Dataset with tokenized inputs and labels.
"""
texts = [item['text'] for item in data]
labels = [item['label'] for item in data]
tokenized = tokenize_texts(texts, tokenizer, max_length)
tokenized['labels'] = labels # Assign labels
return Dataset.from_dict(tokenized)
4. Modernizing Data Collection and Loading Strategies
Drawback:
Using outdated data collection and loading strategies can lead to inefficiencies, scalability issues, and lack of flexibility in handling diverse data types or large datasets.
Improvements:
Leverage Hugging Face Datasets: Utilize the Hugging Face Datasets library, which offers efficient data handling, built-in support for streaming, and integration with various preprocessing and tokenization steps.
Parallel Processing: Implement parallel data loading and preprocessing to speed up the pipeline, especially when dealing with large datasets.
Caching Mechanisms: Use caching to avoid redundant computations during preprocessing and tokenization.
Example Using Hugging Face Datasets:
python
from datasets import load_dataset
def load_dataset_from_directory(directory: str) -> Dataset:
"""
Loads a dataset from a directory with text files.
Args:
directory (str): Path to the directory containing .txt files.
Returns:
Dataset: Hugging Face Dataset object.
"""
dataset = load_dataset('text', data_files={'train': os.path.join(directory, '*.txt')})
return dataset['train']
def preprocess_dataset(dataset: Dataset, tokenizer: PreTrainedTokenizer, max_length: int) -> Dataset:
"""
Preprocesses the dataset by tokenizing and aligning labels.
Args:
dataset (Dataset): The dataset to preprocess.
tokenizer (PreTrainedTokenizer): The tokenizer to use.
max_length (int): Maximum sequence length.
Returns:
Dataset: Tokenized and preprocessed dataset.
"""
# Example: Assuming labels are the first line in each text block
def tokenize_function(examples):
lines = [line.strip() for line in examples['text'].split('\n') if line.strip()]
label, text = lines[0], ' '.join(lines[1:])
tokenized = tokenizer(
text,
truncation=True,
max_length=max_length,
padding='max_length',
return_attention_mask=True,
return_tensors='pt'
)
tokenized['labels'] = label # Modify as per your labeling scheme
return tokenized
tokenized_dataset = dataset.map(tokenize_function, batched=False, remove_columns=['text'])
return tokenized_dataset
Additional Recommendations
Use Specialized Tokenizers:
Depending on your task, consider using tokenizers tailored for specific languages or domains.
Implement byte-level or subword tokenization to better handle out-of-vocabulary words.
Incorporate Data Augmentation:
Enhance your dataset with data augmentation techniques such as synonym replacement, random insertion, or back-translation to improve model robustness.
Handle Class Imbalance:
If you're dealing with classification tasks, ensure that your dataset is balanced. Use techniques like oversampling, undersampling, or synthetic data generation (e.g., SMOTE) to address class imbalance.
Optimize Storage and Loading:
Store preprocessed data in efficient formats like Apache Arrow or HDF5 for faster loading.
Utilize data streaming for extremely large datasets to minimize memory footprint.
Integrate with Modern Frameworks:
Combine Hugging Face Datasets with frameworks like PyTorch Lightning or TensorFlow for streamlined training pipelines.
Final Revised Pipeline Example
Combining the improvements, here's how a modernized data preprocessing pipeline might look:
python
Key Enhancements in the Revised Pipeline:
Structured File Reading: The read_txt_files_with_labels function assumes that the first line of each text file contains the label and the subsequent lines contain the text. Adjust this based on your actual data format.
Dynamic Padding with DataLoader: By using DataCollatorWithPadding, the DataLoader dynamically pads each batch to the longest sequence in that batch, reducing unnecessary computation.
Inclusion of Labels: Labels are integrated into the tokenized data, allowing for supervised learning tasks.
Use of Hugging Face Datasets: Although the example combines manual reading and tokenization, integrating fully with Hugging Face Datasets can further optimize the pipeline, especially for larger datasets.
Error Handling and Logging: Enhanced error handling ensures that issues during file reading are logged, aiding in debugging.
Final Thoughts
Modernizing your data preprocessing pipeline involves adopting more flexible and efficient tools and methodologies. By leveraging libraries like Hugging Face Datasets, implementing dynamic padding, and ensuring that labels are correctly integrated, you can create a robust and scalable pipeline suitable for various machine learning tasks. Additionally, always consider the specific requirements of your task and data to tailor the preprocessing steps accordingly.
If you have any specific questions or need further assistance with any part of the pipeline, feel free to ask!
Not yet included in a published release.
import os
import re
from typing import List, Dict
from transformers import PreTrainedTokenizer, AutoTokenizer, DataCollatorWithPadding
from datasets import Dataset, load_dataset
from torch.utils.data import DataLoader
def read_txt_files_with_labels(directory: str) -> List[Dict[str, str]]:
data = []
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:
lines = file.readlines()
if not lines:
continue
label = lines[0].strip() # Adjust based on how labels are stored
content = '\n'.join(line.strip() for line in lines[1:] if line.strip())
data.append({'text': content, 'label': label})
except Exception as e:
print(f"An error occurred while reading files: {e}")
return data
def split_text(
text: str,
tokenizer: PreTrainedTokenizer,
max_length: int
) -> List[str]:
words = text.strip().split()
chunks = []
current_chunk = []
current_length = 0
for word in words:
tokenized_word = tokenizer.encode(word, add_special_tokens=False)
word_length = len(tokenized_word)
if current_length + word_length > max_length:
if current_chunk:
chunks.append(' '.join(current_chunk))
current_chunk = [word]
current_length = word_length
else:
current_chunk.append(word)
current_length += word_length
if current_chunk:
chunks.append(' '.join(current_chunk))
return chunks
def tokenize_texts(
texts: List[str],
tokenizer: PreTrainedTokenizer,
max_length: int
) -> Dict[str, List[List[int]]]:
all_input_ids = []
all_attention_masks = []
for text in texts:
if not text:
continue
chunks = split_text(text, tokenizer, max_length - 2)
for chunk in chunks:
tokens = tokenizer.encode(
chunk,
add_special_tokens=False,
max_length=max_length - 2,
truncation=True
)
tokens = [tokenizer.bos_token_id] + tokens + [tokenizer.eos_token_id]
attention_mask = [1] * len(tokens)
if len(tokens) < max_length:
padding_length = max_length - len(tokens)
tokens += [tokenizer.pad_token_id] * padding_length
attention_mask += [0] * padding_length
else:
tokens = tokens[:max_length]
attention_mask = attention_mask[:max_length]
all_input_ids.append(tokens)
all_attention_masks.append(attention_mask)
return {'input_ids': all_input_ids, 'attention_mask': all_attention_masks}
def main():
directory = '/scratch/hemanth/Hemanth/localdataset' # Replace with your directory path
max_length = 512 # Define your desired max sequence length
batch_size = 32 # Define your batch size
# Initialize the tokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
# Add special tokens if they are not already present
special_tokens_dict = {'bos_token': '[BOS]', 'eos_token': '[EOS]', 'pad_token': '[PAD]'}
num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
# Update tokenizer's internal properties
tokenizer.bos_token = '[BOS]'
tokenizer.eos_token = '[EOS]'
tokenizer.pad_token = '[PAD]'
# Save and reload tokenizer to ensure changes
tokenizer.save_pretrained('./tokenizer_with_special_tokens')
tokenizer = AutoTokenizer.from_pretrained('./tokenizer_with_special_tokens')
# Read the texts with labels from files
data = read_txt_files_with_labels(directory)
# Separate texts and labels
texts = [item['text'] for item in data]
labels = [item['label'] for item in data]
# Tokenize the texts
tokenized_data = tokenize_texts(texts, tokenizer, max_length)
tokenized_data['labels'] = labels
# Create a Hugging Face Dataset
dataset = Dataset.from_dict(tokenized_data)
# Initialize the data collator for dynamic padding
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
# Create a DataLoader with dynamic padding
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=data_collator)
print(f"Total samples: {len(dataset)}")
print('Tokenization complete.')
# Example: Iterating through the DataLoader
for batch in dataloader:
input_ids = batch['input_ids']
attention_mask = batch['attention_mask']
labels = batch['labels']
# Pass to model or further processing
print(input_ids)
print(attention_mask)
print(labels)
break # Remove this break in actual use
if __name__ == '__main__':
main()