CPU Bottleneck in `IterableDataset.state_dict()` when shuffling multiple shards
Describe the bug
There is a significant CPU bottleneck in IterableDataset dataloading when buffer_size and max_buffer_input_shards are greater than 1 (i.e. highly parallelized streaming with a shuffle buffer).
Currently, _BaseExamplesIterable.state_dict() falls back to performing a full recursive copy.deepcopy(self._state_dict).
In nested iterator chains (like BufferShuffledExamplesIterable wrapping CyclingMultiSourcesExamplesIterable wrapping multiple ArrowExamplesIterable shards), the state_dict() is queried and updated on every yielded row.
Because copy.deepcopy relies on Python's pickle mechanics for object introspection and memoization, it incurs massive CPU overhead. Furthermore, pickle often crashes or fails gracefully when it encounters unpicklable objects like generator states.
When max_buffer_input_shards is scaled up, the dictionary size grows, and the deepcopy completely blocks the CPU, throttling the dataloader significantly.
Steps to Reproduce
import datasets
from torch.utils.data import DataLoader
from datasets.distributed import split_dataset_by_node
ds = datasets.load_dataset(
"parquet",
data_files="gs://your-bucket/benchmark_data/shard_*.parquet",
split="train",
streaming=True
)
# Scaling max_buffer_input_shards triggers the bottleneck
ds = ds.shuffle(seed=0, buffer_size=10000, max_buffer_input_shards=10)
ds = split_dataset_by_node(ds, rank=0, world_size=8)
ds = ds.with_format("torch")
loader = DataLoader(
ds,
batch_size=8,
num_workers=4,
prefetch_factor=2,
persistent_workers=True,
)
for epoch in range(3):
ds.set_epoch(epoch)
for batch in loader:
pass
- Before fix: ~103.5 seconds per epoch.
- After fix: ~65.8 seconds per epoch.
Proposed Solution
We have drafted a fix in PR #8387 that replaces the expensive deepcopy() logic with a fast, dynamic _fast_copy() helper directly inside _BaseExamplesIterable.state_dict(). Because dataset state_dicts strictly consist of acyclic standard collections (dict, list) and primitive state objects, _fast_copy() manually recursively walks dict and list structures and natively clones the values, bypassing pickle and deepcopy entirely.
Environment info
datasetsversion:mainbranch- Python version: 3.13