Below is a comprehensive, highly flexible pipeline for handling image and text datasets using PyTorch, torchvision, and Hugging Face's datasets and transformers libraries. The pipeline is designed to be adaptable, allowing users to define custom augmentations, tokenizations, data loading parameters, and seed configurations to ensure reproducibility. The implementation adheres strictly to PEP-8 standards, employs type hints for clarity, and includes robust error handling to ensure resilience against unexpected conditions.
import os
import random
from typing import Any, Callable, Dict, Optional, Tuple, Union
import torch
from torch.utils.data import DataLoader, Dataset, random_split
from torchvision import transforms
from PIL import Image
from datasets import load_dataset, DatasetDict
from transformers import PreTrainedTokenizer
from urllib.request import urlopen
from io import BytesIO
class FlexibleImageTextDataset(Dataset):
"""A flexible dataset for handling image and text data."""
def __init__(
self,
hf_dataset: DatasetDict,
split: str = "train",
image_column: str = "image",
text_column: str = "source",
transform: Optional[Callable] = None,
tokenizer: Optional[PreTrainedTokenizer] = None,
tokenizer_params: Optional[Dict[str, Any]] = None,
seed: Optional[int] = None,
) -> None:
"""
Initializes the FlexibleImageTextDataset.
Args:
hf_dataset (DatasetDict): The Hugging Face dataset.
split (str): The dataset split to use (e.g., 'train', 'validation', 'test').
image_column (str): The column name for images.
text_column (str): The column name for text.
transform (Optional[Callable]): torchvision transforms to apply to images.
tokenizer (Optional[PreTrainedTokenizer]): Tokenizer for text data.
tokenizer_params (Optional[Dict[str, Any]]): Parameters for tokenization.
seed (Optional[int]): Seed for reproducibility.
"""
super().__init__()
if split not in hf_dataset:
raise ValueError(f"Split '{split}' not found in the dataset.")
self.dataset = hf_dataset[split]
self.image_column = image_column
self.text_column = text_column
self.transform = transform
self.tokenizer = tokenizer
self.tokenizer_params = tokenizer_params or {}
self.seed = seed
if self.seed is not None:
random.seed(self.seed)
torch.manual_seed(self.seed)
def _load_image(self, image_data: Union[str, Dict[str, Any]]) -> Image.Image:
"""
Loads an image from a local path or a URL.
Args:
image_data (Union[str, Dict[str, Any]]): Image path or URL.
Returns:
Image.Image: Loaded PIL image.
"""
try:
if isinstance(image_data, dict) and "url" in image_data:
with urlopen(image_data["url"]) as response:
image_bytes = response.read()
image = Image.open(BytesIO(image_bytes)).convert("RGB")
elif isinstance(image_data, str):
if image_data.startswith("http://") or image_data.startswith("https://"):
with urlopen(image_data) as response:
image_bytes = response.read()
image = Image.open(BytesIO(image_bytes)).convert("RGB")
else:
if not os.path.exists(image_data):
raise FileNotFoundError(f"Image file '{image_data}' not found.")
image = Image.open(image_data).convert("RGB")
else:
raise TypeError("Unsupported image data type.")
return image
except Exception as e:
raise IOError(f"Error loading image: {e}") from e
def _tokenize_text(self, text: str) -> Dict[str, Any]:
"""
Tokenizes text using the provided tokenizer.
Args:
text (str): The text to tokenize.
Returns:
Dict[str, Any]: Tokenized text.
"""
if self.tokenizer is None:
raise ValueError("Tokenizer not provided.")
try:
return self.tokenizer(text, **self.tokenizer_params)
except Exception as e:
raise ValueError(f"Error during tokenization: {e}") from e
def __len__(self) -> int:
"""Returns the number of samples in the dataset."""
return len(self.dataset)
def __getitem__(self, idx: int) -> Dict[str, Any]:
"""
Retrieves a sample from the dataset.
Args:
idx (int): Index of the sample.
Returns:
Dict[str, Any]: A dictionary containing image and tokenized text.
"""
try:
sample = self.dataset[idx]
# Load and transform image
image = self._load_image(sample[self.image_column])
if self.transform:
image = self.transform(image)
else:
image = transforms.ToTensor()(image)
# Tokenize text
text = sample[self.text_column]
tokenized_text = self._tokenize_text(text) if self.tokenizer else text
return {
"image": image,
"text": tokenized_text,
"metadata": {k: v for k, v in sample.items() if k not in [self.image_column, self.text_column]},
}
except Exception as e:
raise RuntimeError(f"Error processing index {idx}: {e}") from e
class DataPipeline:
"""A flexible data pipeline for image and text datasets."""
def __init__(
self,
dataset_name: str,
dataset_config: Optional[str] = None,
split_ratio: Tuple[float, float, float] = (0.8, 0.1, 0.1),
image_column: str = "image",
text_column: str = "source",
image_transforms: Optional[Callable] = None,
tokenizer: Optional[PreTrainedTokenizer] = None,
tokenizer_params: Optional[Dict[str, Any]] = None,
batch_size: int = 32,
shuffle: bool = True,
num_workers: int = 4,
seed: Optional[int] = None,
) -> None:
"""
Initializes the DataPipeline.
Args:
dataset_name (str): The name of the Hugging Face dataset.
dataset_config (Optional[str]): The configuration of the dataset.
split_ratio (Tuple[float, float, float]): Ratios for train, validation, and test splits.
image_column (str): The column name for images.
text_column (str): The column name for text.
image_transforms (Optional[Callable]): torchvision transforms to apply to images.
tokenizer (Optional[PreTrainedTokenizer]): Tokenizer for text data.
tokenizer_params (Optional[Dict[str, Any]]): Parameters for tokenization.
batch_size (int): Batch size for DataLoader.
shuffle (bool): Whether to shuffle the data.
num_workers (int): Number of worker processes for data loading.
seed (Optional[int]): Seed for reproducibility.
"""
self.dataset_name = dataset_name
self.dataset_config = dataset_config
self.split_ratio = split_ratio
self.image_column = image_column
self.text_column = text_column
self.image_transforms = image_transforms or transforms.ToTensor()
self.tokenizer = tokenizer
self.tokenizer_params = tokenizer_params or {}
self.batch_size = batch_size
self.shuffle = shuffle
self.num_workers = num_workers
self.seed = seed
self._validate_split_ratio()
self.hf_dataset = self._load_dataset()
self.train_dataset, self.val_dataset, self.test_dataset = self._create_datasets()
def _validate_split_ratio(self) -> None:
"""Validates the split ratio."""
total = sum(self.split_ratio)
if not torch.isclose(torch.tensor(total), torch.tensor(1.0)):
raise ValueError("Split ratios must sum to 1.")
def _load_dataset(self) -> DatasetDict:
"""Loads the dataset using Hugging Face's load_dataset."""
try:
if self.dataset_config:
dataset = load_dataset(self.dataset_name, self.dataset_config)
else:
dataset = load_dataset(self.dataset_name)
if not isinstance(dataset, DatasetDict):
raise ValueError("Loaded dataset is not a DatasetDict.")
return dataset
except Exception as e:
raise RuntimeError(f"Error loading dataset: {e}") from e
def _create_datasets(self) -> Tuple[Dataset, Dataset, Dataset]:
"""Creates train, validation, and test datasets with the specified split ratio."""
try:
full_dataset = self.hf_dataset["train"] # Assuming 'train' split exists
total_length = len(full_dataset)
train_length = int(self.split_ratio[0] * total_length)
val_length = int(self.split_ratio[1] * total_length)
test_length = total_length - train_length - val_length
if self.seed is not None:
generator = torch.Generator().manual_seed(self.seed)
else:
generator = None
train_ds, val_ds, test_ds = random_split(
full_dataset,
[train_length, val_length, test_length],
generator=generator,
)
return (
train_ds,
val_ds,
test_ds,
)
except Exception as e:
raise RuntimeError(f"Error creating dataset splits: {e}") from e
def _prepare_dataloader(self, dataset: Dataset, split: str) -> DataLoader:
"""
Prepares a DataLoader for a given dataset split.
Args:
dataset (Dataset): The dataset split.
split (str): The name of the split.
Returns:
DataLoader: Configured DataLoader.
"""
try:
dataset_kwargs = {
"hf_dataset": self.hf_dataset,
"split": split,
"image_column": self.image_column,
"text_column": self.text_column,
"transform": self.image_transforms,
"tokenizer": self.tokenizer,
"tokenizer_params": self.tokenizer_params,
"seed": self.seed,
}
flexible_dataset = FlexibleImageTextDataset(**dataset_kwargs)
dataloader = DataLoader(
flexible_dataset,
batch_size=self.batch_size,
shuffle=self.shuffle,
num_workers=self.num_workers,
)
return dataloader
except Exception as e:
raise RuntimeError(f"Error preparing DataLoader for split '{split}': {e}") from e
def get_dataloaders(self) -> Tuple[DataLoader, DataLoader, DataLoader]:
"""
Retrieves the train, validation, and test DataLoaders.
Returns:
Tuple[DataLoader, DataLoader, DataLoader]: Train, validation, and test DataLoaders.
"""
try:
train_loader = self._prepare_dataloader(self.train_dataset, "train")
val_loader = self._prepare_dataloader(self.val_dataset, "validation")
test_loader = self._prepare_dataloader(self.test_dataset, "test")
return train_loader, val_loader, test_loader
except Exception as e:
raise RuntimeError(f"Error retrieving DataLoaders: {e}") from e
Explanation
1. FlexibleImageTextDataset Class
This class inherits from torch.utils.data.Dataset and is responsible for handling individual samples within the dataset. It provides the following functionalities:
-
Image Loading: Supports loading images from both local paths and remote URLs. It handles different image formats and ensures that images are converted to RGB.
-
Transformations: Applies user-defined torchvision transformations to images, enabling flexibility in preprocessing steps such as resizing, normalization, augmentation, etc.
-
Text Tokenization: Utilizes Hugging Face's tokenizers to process text data. This supports any tokenizer compatible with transformer models, allowing for a wide range of NLP tasks.
-
Error Handling: Implements comprehensive error handling to catch and report issues during image loading and text tokenization.
2. DataPipeline Class
This class orchestrates the entire data pipeline, handling dataset loading, splitting, and batching. Key features include:
-
Dataset Loading: Dynamically loads datasets using Hugging Face's load_dataset function. It ensures that the loaded dataset is a DatasetDict, which facilitates easy splitting.
-
Dataset Splitting: Splits the dataset into training, validation, and testing subsets based on user-defined ratios (defaulting to 80:10:10). The split is reproducible if a seed is provided.
-
DataLoader Configuration: Creates PyTorch DataLoader instances for each dataset split, allowing users to control batch size, shuffling behavior, and the number of worker processes for data loading.
-
Flexibility: Accommodates various dataset structures by allowing users to specify the columns corresponding to images and text.
-
Error Handling: Ensures that any issues during dataset loading, splitting, or DataLoader preparation are gracefully handled and reported.
3. Usage Example
Below is an example of how to utilize the DataPipeline class to create DataLoaders for training, validation, and testing.
from transformers import BertTokenizer
def main():
# Configuration Parameters
dataset_name = "lmms-lab/llava-critic-113k"
dataset_config = "pairwise"
split_ratio = (0.8, 0.1, 0.1)
image_column = "image"
text_column = "source"
batch_size = 64
shuffle = True
num_workers = 8
seed = 42
# Define Image Transformations
image_transforms = transforms.Compose([
transforms.Resize((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], # Example mean
std=[0.229, 0.224, 0.225]) # Example std
])
# Initialize Tokenizer
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
tokenizer_params = {
"padding": "max_length",
"truncation": True,
"max_length": 128
}
# Initialize Data Pipeline
pipeline = DataPipeline(
dataset_name=dataset_name,
dataset_config=dataset_config,
split_ratio=split_ratio,
image_column=image_column,
text_column=text_column,
image_transforms=image_transforms,
tokenizer=tokenizer,
tokenizer_params=tokenizer_params,
batch_size=batch_size,
shuffle=shuffle,
num_workers=num_workers,
seed=seed
)
# Retrieve DataLoaders
train_loader, val_loader, test_loader = pipeline.get_dataloaders()
# Iterate through the training DataLoader
for batch in train_loader:
images = batch["image"] # Tensor of shape (batch_size, 3, 224, 224)
input_ids = batch["text"]["input_ids"] # Tokenized input IDs
attention_mask = batch["text"]["attention_mask"] # Attention masks
# Your training code here
# For demonstration, we'll just print the batch size
print(f"Batch size: {images.size(0)}")
break # Remove this break to iterate through the entire DataLoader
if __name__ == "__main__":
main()
Explanation of Usage Example
-
Configuration Parameters: Define the dataset name, configuration, split ratios, column names for images and text, batching parameters, and a seed for reproducibility.
-
Image Transformations: Utilize torchvision.transforms to define a sequence of augmentations and preprocessing steps applied to each image. Users can customize this pipeline as needed.
-
Tokenizer Initialization: Initialize a tokenizer from Hugging Face's transformers library. In this example, BertTokenizer is used, but any compatible tokenizer can be substituted.
-
Data Pipeline Initialization: Create an instance of the DataPipeline class with the specified configurations and transformations.
-
Retrieving DataLoaders: Obtain the training, validation, and testing DataLoaders from the pipeline.
-
Iterating Through DataLoader: Demonstrates how to iterate through the DataLoader and access images and tokenized text. Replace the print statement with actual training or evaluation logic.
Conclusion
This flexible data pipeline provides a robust foundation for handling diverse image and text datasets in machine learning workflows. By allowing extensive customization and ensuring adherence to best practices in code structure and error handling, it facilitates scalable and maintainable data processing tailored to various project requirements.