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()
Hello,
I've reviewed your code and the concerns you've raised. Below, I've addressed each point and provided suggestions on how to improve your code to handle the issues you've identified.
1. Handling Short Files with Empty Lines
Issue:
"Let's assume in some file one line content and 5 line spaces are there (may or may not)."
Your current read_txt_files function reads text files and strips out empty lines:
python
content = '\n'.join(line.strip() for line in content.splitlines() if line.strip())
This removes all empty lines, which might not be desirable if empty lines carry meaningful information (e.g., paragraph separation).
Suggestion:
Preserve Empty Lines: If empty lines are important, modify the code to retain them. For instance, you can replace multiple consecutive empty lines with a single empty line to reduce unnecessary space while keeping paragraph breaks.
Handle Short Files: Ensure that your code can handle files with minimal content without errors. Include checks for empty or very short files.
Revised Code Snippet:
python
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()
# Optionally, normalize multiple empty lines to a single one
# and strip spaces from each line without removing empty lines
lines = [line.rstrip() for line in content.split('\n')]
normalized_content = '\n'.join(lines)
contents.append(normalized_content)
except Exception as e:
print(f"An error occurred while reading files: {e}")
return contents
2. Ensuring All Tensors Have the Same Size (Padding Strategies)
Issue:
"All tensors should be the same size (if data is not there, some padding strategies)."
Your code manually pads sequences to max_length, which can be inefficient, especially with variable-length sequences.
Suggestion:
Use Built-in Padding: Let the tokenizer handle padding by setting padding='max_length' or padding=True. This ensures consistency and leverages optimized tokenization methods.
Dynamic Padding: For efficiency, especially with variable-length sequences, consider dynamic padding to the length of the longest sequence in each batch.
Data Collators: Use data collators like DataCollatorWithPadding from Hugging Face, which dynamically pad sequences to the maximum length in the batch.
3. Returning input_ids, attention_mask, and labels
Issue:
"Returns input_ids, attention_mask, labels."
Your current code returns input_ids and attention_mask but does not include labels, which are essential for supervised learning tasks.
Suggestion:
Include Labels: Depending on your task (e.g., language modeling, classification), generate labels appropriately.
For language modeling tasks, labels can be the same as input_ids shifted by one position (for causal language modeling) or identical to input_ids (for masked language modeling).
Update Tokenization Function: Modify the tokenization function to generate and include labels in the output.
Revised Code Snippet for Language Modeling:
python
def tokenize_texts(
texts: List[str],
tokenizer: PreTrainedTokenizer,
max_length: int
) -> Dict[str, List[List[int]]]:
tokenized_inputs = tokenizer(
texts,
max_length=max_length,
padding='max_length',
truncation=True,
return_tensors='pt' # Return PyTorch tensors
)
# For language modeling, labels are same as input_ids
tokenized_inputs['labels'] = tokenized_inputs['input_ids'].clone()
return tokenized_inputs
4. Outdated Data Collection and Loading Strategies
Issue:
"Data collection and loading strategies are very old, novelty missing."
Your current approach reads all data into memory and processes it, which isn't efficient or scalable for large datasets.
Suggestion:
Use datasets Library: Leverage the Hugging Face datasets library for efficient data handling. It supports memory-mapped datasets that don't load the entire dataset into RAM.
Data Pipelines: Implement data pipelines using datasets that can handle streaming data, large datasets, and offer built-in methods for tokenization and batching.
Data Collators and Loaders: Use DataCollator classes and DataLoader objects to handle batching and padding dynamically during training.
Revised Code Using datasets:
python
from datasets import load_dataset
from transformers import DataCollatorForLanguageModeling
def main():
directory = '/scratch/hemanth/Hemanth/localdataset' # Replace with your directory path
max_length = 512
# Initialize the tokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
# Create a Dataset object
def gen():
for text in read_txt_files(directory):
yield {'text': text}
raw_datasets = Dataset.from_generator(gen)
# Tokenize the dataset
def tokenize_function(examples):
return tokenizer(
examples['text'],
padding='max_length',
truncation=True,
max_length=max_length,
return_special_tokens_mask=True,
)
tokenized_datasets = raw_datasets.map(
tokenize_function,
batched=True,
remove_columns=["text"],
)
# Data collator for language modeling
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer, mlm=False
)
# Create a DataLoader
train_dataloader = DataLoader(
tokenized_datasets,
batch_size=8,
shuffle=True,
collate_fn=data_collator,
)
# Now, train_dataloader can be used in the training loop
for batch in train_dataloader:
# Training loop logic here
pass
if __name__ == '__main__':
main()
Additional Improvements and Modern Practices
1. Leveraging Special Tokens Properly
Your code manually adds BOS and EOS tokens. Modern tokenizers handle special tokens automatically when add_special_tokens=True.
Suggestion:
Ensure that the tokenizer and model configurations are aligned regarding special tokens.
Use add_special_tokens=True in the tokenizer to automatically include necessary tokens.
2. Efficient Tokenization
Use batch processing when tokenizing to speed up processing.
Utilize the return_tensors parameter to get outputs directly as PyTorch tensors.
3. Model Integration
Load and integrate a model compatible with your tokenizer, such as AutoModelForCausalLM if you're performing language modeling.
4. Memory Management
For large datasets, consider streaming data or processing it in chunks to avoid memory overflow.
5. Using DataCollator with Padding
Use DataCollatorWithPadding for tasks where dynamic padding is beneficial.
Here’s a revised version of your code incorporating all the suggestions:
python
import os
from datasets import Dataset
from transformers import (
AutoTokenizer,
DataCollatorForLanguageModeling,
AutoModelForCausalLM
)
from torch.utils.data import DataLoader
def read_txt_files(directory: str):
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 normalize empty lines
lines = [line.rstrip() for line in content.split('\n')]
normalized_content = '\n'.join(lines)
yield {'text': normalized_content}
except Exception as e:
print(f"An error occurred while reading files: {e}")
def main():
directory = '/scratch/hemanth/Hemanth/localdataset' # Replace with your directory path
max_length = 512
batch_size = 8
# Initialize the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
model = AutoModelForCausalLM.from_pretrained('bert-base-uncased')
# Create a Dataset object
raw_datasets = Dataset.from_generator(
lambda: read_txt_files(directory),
features={'text': 'string'}
)
# Tokenize the dataset
def tokenize_function(examples):
return tokenizer(
examples['text'],
padding='max_length',
truncation=True,
max_length=max_length,
return_special_tokens_mask=True,
)
tokenized_datasets = raw_datasets.map(
tokenize_function,
batched=True,
remove_columns=["text"],
)
# Labels are input_ids shifted (for causal LM)
tokenized_datasets = tokenized_datasets.map(
lambda examples: {'labels': examples['input_ids']},
batched=True,
)
tokenized_datasets.set_format(
type='torch', columns=['input_ids', 'attention_mask', 'labels']
)
# Use DataCollatorForLanguageModeling
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer, mlm=False,
)
# Create DataLoader
train_dataloader = DataLoader(
tokenized_datasets,
batch_size=batch_size,
shuffle=True,
collate_fn=data_collator,
)
# Training loop (simplified)
for batch in train_dataloader:
outputs = model(
input_ids=batch['input_ids'],
attention_mask=batch['attention_mask'],
labels=batch['labels'],
)
loss = outputs.loss
# Backpropagation and optimization steps go here
print(f"Loss: {loss.item()}")
break # Remove break to train over all batches
if __name__ == '__main__':
main()
Summary
Handling Empty Lines and Short Files: Adjusted read_txt_files to preserve empty lines if necessary and ensure short files are handled correctly.
Padding Strategies: Leveraged tokenizer's built-in padding and used DataCollator classes for efficient batching and padding.
Including Labels: Modified the code to return labels alongside input_ids and attention_mask, essential for supervised learning tasks.
Modern Data Loading: Used the Hugging Face datasets library to create efficient, scalable data pipelines.
Additional Improvements: Adopted best practices for tokenization, model integration, and training loop setup.
By implementing these changes, your data processing and model training code will be more efficient, scalable, and aligned with modern standards in natural language processing.
Let me know if you have any questions or need further assistance!