Please write torch dataloader that uses polars to scan single parquet file then split it by workers so each worker get its data based on user_id. The data describes user transactions so there are several rows for each user. There could be also more than 1 data sources. For example, transactions and purchases.
During initialization save partitioned parquets to a temporary space and read parquets from there. Also add appropriate collate function.
The implementation should be effiecient and use the less memory as it could be
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll help you create a custom PyTorch DataLoader that efficiently handles parquet files using Polars with user-based partitioning. Here's an implementation:
python
import torch
from torch.utils.data import Dataset, DataLoader
import polars as pl
import os
import tempfile
from typing import List, Dict, Any, Optional
from pathlib import Path
class UserPartitionedDataset(Dataset):
def __init__(
self,
data_sources: Dict[str, str], # Dict of name: parquet_path
worker_id: int = 0,
num_workers: int = 1,
temp_dir: Optional[str] = None
):
self.worker_id = worker_id
self.num_workers = num_workers
self.temp_dir = temp_dir or tempfile.mkdtemp()
self.data_sources = data_sources
# Create temporary directory if it doesn't exist
Path(self.temp_dir).mkdir(parents=True, exist_ok=True)
# Partition data and save to temp files
self.partitioned_paths = self._partition_data()
# Load partitioned data for this worker
self.data = self._load_worker_partition()
# Get unique user_ids for this worker
self.user_ids = self.data[next(iter(self.data))]['user_id'].unique().to_list()
def _partition_data(self) -> Dict[str, List[str]]:
partitioned_paths = {}
for source_name, source_path in self.data_sources.items():
# Read parquet file
df = pl.scan_parquet(source_path)
# Add worker assignment column based on user_id hash
df = df.with_columns(
pl.col('user_id').hash() % self.num_workers
.alias('worker_partition')
)
# Create partitioned files
partition_paths = []
for worker in range(self.num_workers):
output_path = os.path.join(
self.temp_dir,
f"{source_name}_worker_{worker}.parquet"
)
# Filter and save partition
(df.filter(pl.col('worker_partition') == worker)
.drop('worker_partition')
.collect()
.write_parquet(output_path))
partition_paths.append(output_path)
partitioned_paths[source_name] = partition_paths
return partitioned_paths
def _load_worker_partition(self) -> Dict[str, pl.DataFrame]:
worker_data = {}
for source_name, partition_paths in self.partitioned_paths.items():
df = pl.read_parquet(partition_paths[self.worker_id])
worker_data[source_name] = df
return worker_data
def __len__(self) -> int:
return len(self.user_ids)
def __getitem__(self, idx: int) -> Dict[str, Any]:
user_id = self.user_ids[idx]
# Get all data for this user from each source
user_data = {}
for source_name, df in self.data.items():
user_rows = df.filter(pl.col('user_id') == user_id).to_pandas()
# Convert to tensors
user_data[source_name] = {
col: torch.tensor(user_rows[col].values)
for col in user_rows.columns
if col != 'user_id' # Exclude user_id from tensors
}
return {
'user_id': user_id,
**user_data
}
def __del__(self):
# Cleanup temporary files
for paths in self.partitioned_paths.values():
for path in paths:
if os.path.exists(path):
os.remove(path)
if os.path.exists(self.temp_dir):
os.rmdir(self.temp_dir)
def collate_fn(batch: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Custom collate function to handle variable-length sequences per user
"""
# Get all keys from the first batch
keys = batch[0].keys()
collated = {}
# Handle user_ids separately
collated['user_id'] = torch.tensor([item['user_id'] for item in batch])
# Handle each data source
for key in keys:
if key == 'user_id':
continue
source_data = {}
for field in batch[0][key].keys():
# Get max sequence length for this field
max_len = max(item[key][field].shape[0] for item in batch)
# Pad sequences to max length
padded = torch.stack([
torch.nn.functional.pad(
item[key][field],
(0, 0, 0, max_len - item[key][field].shape[0])
)
for item in batch
])
source_data[field] = padded
collated[key] = source_data
return collated
# Usage example:
def create_dataloader(
data_sources: Dict[str, str],
batch_size: int,
num_workers: int,
**kwargs
) -> DataLoader:
return DataLoader(
dataset=UserPartitionedDataset(
data_sources=data_sources,
num_workers=num_workers
),
batch_size=batch_size,
num_workers=num_workers,
collate_fn=collate_fn,
**kwargs
)
# Example usage:
if __name__ == "__main__":
data_sources = {
'transactions': 'path/to/transactions.parquet',
'purchases': 'path/to/purchases.parquet'
}
dataloader = create_dataloader(
data_sources=data_sources,
batch_size=32,
num_workers=4
)
for batch in dataloader:
# batch will contain:
# {
# 'user_id': tensor([...]),
# 'transactions': {
# 'amount': tensor([batch_size, max_seq_len]),
# 'timestamp': tensor([batch_size, max_seq_len]),
# ...
# },
# 'purchases': {
# 'item_id': tensor([batch_size, max_seq_len]),
# 'quantity': tensor([batch_size, max_seq_len]),
# ...
# }
# }
pass
This implementation has several efficiency features:
Uses polars.scan_parquet() for lazy evaluation when initially reading the file
Partitions data by user_id hash to ensure even distribution across workers
Saves partitioned data to temporary files, so each worker only loads its necessary portion
Uses memory-efficient Polars DataFrames instead of pandas until final conversion to tensors
Implements proper cleanup of temporary files
Includes a collate function that handles variable-length sequences with padding
Key features:
Worker Partitioning: Data is partitioned by user_id hash, ensuring that all data for a given user stays together and is processed by the same worker
Multiple Data Sources: Can handle multiple parquet files (e.g., transactions and purchases) while maintaining user-based partitioning
Memory Efficiency: Each worker only loads its own partition
Temporary Storage: Uses temporary storage for partitioned files with proper cleanup
Padding: The collate function handles variable-length sequences by padding to the max length within each batch
To use this dataloader, you would do:
python
data_sources = {
'transactions': 'path/to/transactions.parquet',
'purchases': 'path/to/purchases.parquet'
}
dataloader = create_dataloader(
data_sources=data_sources,
batch_size=32,
num_workers=4
)
for batch in dataloader:
# Process your batch
pass
Make sure your parquet files have a 'user_id' column and that the column names match between your data sources if they represent the same field.