Great question! When using torch.utils.data.DataLoader with IterableDataset and num_workers > 0, the behavior is very different from Dataset, due to how data is streamed rather than indexable.
Let’s break it down:
🔄 IterableDataset vs. Dataset
Dataset: Random access via indices — supports __getitem__ and __len__. Workers can split work by assigning disjoint index ranges.
IterableDataset: Data is streamed (e.g., from a file, network, generator). No random access, no fixed length. Workers must iterate independently — but this leads to duplication or coordination issues if not handled carefully.
🧵 How Workers Work with IterableDataset and num_workers > 0
When num_workers > 0 with IterableDataset, PyTorch uses a "multi-process iterator" — each worker runs its own instance of the IterableDataset and yields data independently.
⚠️ Key Differences:
| Feature | Dataset | IterableDataset |
|---|
| Worker assignment | Split by index ranges | Each worker runs its own iterator |
| Data duplication | No (each index assigned once) | Yes, unless coordinated |
| Shuffling | Global shuffle possible | Harder to coordinate across workers |
| Reproducibility | Easier with worker_init_fn | Challenging with parallel streams |
📌 What Actually Happens:
Each worker:
- Instantiates its own copy of the
IterableDataset
- Iterates independently (e.g., reading from a file, yielding items one by one)
- Sends its own stream of data to the main process
❗ This means: you will get duplicated or interleaved data unless you coordinate the workers (e.g., via DistributedSampler logic or custom coordination).
Example: If your IterableDataset yields 1000 items and you have 2 workers, each worker will iterate the entire stream independently → total ~2000 items per epoch (unless you stop them early).
🧩 How to Avoid Duplication?
✅ Option 1: Use torchdata or torch.utils.data.IterableWrapper with num_workers=0
If you want parallelism, avoid IterableDataset unless you handle coordination manually.
✅ Option 2: Use DistributedSampler (even for single machine)
You can simulate sharding:
from torch.utils.data import IterableDataset, DataLoader, DistributedSampler
import torch.distributed as dist
class MyIterableDataset(IterableDataset):
def __init__(self):
# e.g., open a file or start a stream
self.rank = int(os.environ.get("RANK", 0))
self.world_size = int(os.environ.get("WORLD_SIZE", 1))
def __iter__(self):
# Each worker yields only its portion
for i, item in enumerate(stream):
if i % self.world_size == self.rank:
yield item
# Launch with torchrun or manually init group
dist.init_process_group(backend="gloo")
dataset = MyIterableDataset()
loader = DataLoader(dataset, num_workers=0) # Or num_workers > 0, but careful!
🚫 Note: num_workers > 0 with IterableDataset is not well-coordinated in PyTorch as of v2.0 — it’s best to set num_workers=0 and handle parallelism in the IterableDataset itself.
✅ Option 3: Use torchdata's ShardingFilter
From torchdata (PyTorch Labs):
from torchdata.datapipes.iter import ShardingFilter
class MyIterableDataset(IterableDataset):
def __init__(self, dp):
self.dp = dp.sharding_filter() # auto-shards across workers
def __iter__(self):
for x in self.dp:
yield x
This requires using DataPipes, but enables proper sharding.
🧪 Practical Recommendation
If you're using IterableDataset:
| Goal | Recommendation |
|---|
| Simple streaming, no duplication | Use num_workers=0 |
| Want parallel data loading | Implement sharding logic inside __iter__ (manually or via ShardingFilter) |
| Want to shuffle | Use ShuffleList or buffer in __iter__ (careful with memory) |
| Want reproducibility | Set worker_init_fn, but note that IterableDataset may not reseed properly across workers |
🧠 Example: Manual Sharding in IterableDataset
import os
class MyIterableDataset(IterableDataset):
def __init__(self, source):
self.source = source
self.rank = int(os.getenv("RANK", 0))
self.world_size = int(os.getenv("WORLD_SIZE", 1))
def __iter__(self):
# e.g., read lines from a huge file
with open(self.source) as f:
for i, line in enumerate(f):
if i % self.world_size == self.rank:
yield process(line)
Then launch with:
RANK=0 WORLD_SIZE=2 python -m torch.distributed.launch --nproc_per_node=2 train.py
📦 Prefetching with IterableDataset
prefetch_factor still works: each worker will prefetch prefetch_factor batches.
- But since workers are streaming independently, prefetching helps smooth out I/O jitter.
- Tensors are still stored in RAM (CPU), then moved to GPU in main process.
🚫 Known Limitations (as of PyTorch 2.1)
IterableDataset + num_workers > 0 does not split data across workers automatically.
- Workers do not coordinate — so you get duplicated data unless you implement sharding manually.
- No built-in support for
DistributedSampler-style sharding unless you do it yourself.
- Shuffling is hard — you can buffer locally in each worker, but global shuffle is not possible without full data.
✅ Summary: IterableDataset + num_workers
| Aspect | Behavior |
|---|
| Workers | Each runs its own iterator |
| Data duplication | Yes, unless sharded manually |
| Prefetch | Works per-worker |
| Data transfer | Same as Dataset — CPU → main → GPU |
| Best practice | Use num_workers=0 or implement sharding in __iter__ |
| Reproducibility | Tricky — manual seeding required |
If you're working with streaming data (e.g., large files, real-time sensors), consider:
- Using
torchdata (pip install torchdata)
- Implementing
__iter__ with sharding
- Avoiding
num_workers > 0 unless you're confident about duplication
Would you like a full working example with file-based streaming and sharding?