When you pass an IterableDataset to DataLoader, the behavior changes significantly compared to using a Dataset (e.g., TensorDataset, ImageFolder, etc.). Let's explore the key differences.
🔑 Key Differences with IterableDataset
- No Indexing:
IterableDataset doesn't support indexing (__getitem__). Instead, it implements __iter__, which returns an iterator over the data.
- No Sampler: Since there's no indexing, samplers (like
RandomSampler, SequentialSampler) aren't used. The iteration order is determined by the IterableDataset itself.
- Workers Iterate Independently: When
num_workers > 0, each worker gets its own iterator over the IterableDataset. They don't share a common index or sampler.
How Workers Interact with IterableDataset
- Each worker creates a separate iterator:
iter(dataset)
- Workers fetch data independently:
next(iterator)
- Batches are formed (if
batch_size is set) and put into the output queue
Implications
- No Automatic Sharding: Unlike
Dataset, where PyTorch automatically shards the data across workers, IterableDataset requires you to implement sharding logic yourself (if needed).
- Data Duplication: If not handled properly, the same data might be processed multiple times across workers.
📝 Example: Basic IterableDataset
class MyIterableDataset(torch.utils.data.IterableDataset):
def __init__(self, start, end):
super().__init__()
self.start = start
self.end = end
def __iter__(self):
return iter(range(self.start, self.end))
# Usage
dataset = MyIterableDataset(0, 10)
dataloader = DataLoader(dataset, num_workers=2, batch_size=2)
for batch in dataloader:
print(batch)
In this example, both workers will iterate over the entire range (0, 10), potentially leading to duplicated batches.
🔩 Sharding IterableDataset Across Workers
To avoid duplication, you need to shard the data manually. PyTorch provides a utility function: torch.utils.data.get_worker_info().
Example: Sharding IterableDataset
import torch
from torch.utils.data import IterableDataset, DataLoader, get_worker_info
class ShardedIterableDataset(IterableDataset):
def __init__(self, start, end):
super().__init__()
self.start = start
self.end = end
def __iter__(self):
worker_info = get_worker_info()
if worker_info is None: # single-process mode
return iter(range(self.start, self.end))
else:
per_worker = (self.end - self.start) // worker_info.num_workers
worker_id = worker_info.id
start = self.start + worker_id * per_worker
end = min(start + per_worker, self.end)
return iter(range(start, end))
# Usage
dataset = ShardedIterableDataset(0, 10)
dataloader = DataLoader(dataset, num_workers=2, batch_size=2)
for batch in dataloader:
print(batch)
In this sharded version, each worker gets a disjoint subset of the data, avoiding duplication.
📚 Best Practices for IterableDataset
- Implement Sharding: Use
get_worker_info() to shard data across workers.
- Handle Edge Cases: Consider cases like uneven data distribution or single-process mode (
num_workers=0).
- Be Mindful of
batch_size: If batch_size is set, ensure that the last batch is handled correctly (e.g., using drop_last=True or handling partial batches).
🚀 Example with Real Data (e.g., Reading Files)
When working with files or other iterable sources, you can shard the data by dividing the file list or using a similar strategy.
class FileIterableDataset(IterableDataset):
def __init__(self, file_list):
self.file_list = file_list
def __iter__(self):
worker_info = get_worker_info()
if worker_info is None:
files_to_process = self.file_list
else:
per_worker = len(self.file_list) // worker_info.num_workers
worker_id = worker_info.id
start = worker_id * per_worker
end = min(start + per_worker, len(self.file_list))
files_to_process = self.file_list[start:end]
for file in files_to_process:
# Process file
yield file
# Usage
file_list = [...] # List of files
dataset = FileIterableDataset(file_list)
dataloader = DataLoader(dataset, num_workers=4, batch_size=1)
for file in dataloader:
print(file)
By following these guidelines and examples, you can effectively use IterableDataset with DataLoader and num_workers > 0 to parallelize your data loading and preprocessing.