Sub topic 7
Parallel loading: workers, prefetching, and persistent workers
Assume you know basic Python, NumPy image arrays, and PyTorch Dataset and DataLoader. This chapter focuses on training pipelines where the CPU must decode and resize images while the accelerator trains the model.
Why one loader can leave the accelerator idle
With num_workers=0, the training process usually performs these steps in sequence:
- Read and decode a batch.
- Resize and transform the images.
- Copy the batch to the accelerator.
- Run the model.
- Repeat.
If decoding takes longer than the model computation, the accelerator waits between batches. Worker processes overlap data preparation with model execution. While the main process trains on batch 3, workers can prepare batches 4 and 5.
Configure workers and prefetching
num_workers is the number of child processes used to call Dataset.__getitem__. Each worker reads different samples. prefetch_factor controls how many batches each worker prepares ahead of the batch currently requested by the main process.
from pathlib import Path
import io
import sys
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader
class ImageDataset(Dataset):
def __init__(self, paths, size=(224, 224)):
self.paths = [str(path) for path in paths]
self.size = size
def __len__(self):
return len(self.paths)
def __getitem__(self, index):
with open(self.paths[index], "rb") as file:
data = file.read()
with Image.open(io.BytesIO(data)) as image:
image = image.convert("RGB")
image = image.resize(self.size, Image.Resampling.BILINEAR)
array = torch.from_numpy(
__import__("numpy").array(image, dtype="uint8")
)
return array.permute(2, 0, 1)
def main(paths):
loader = DataLoader(
ImageDataset(paths),
batch_size=64,
shuffle=True,
num_workers=4,
prefetch_factor=2,
persistent_workers=True,
pin_memory=True,
)
for batch in loader:
batch = batch.to("cuda", non_blocking=True)
print(batch.shape)
if __name__ == "__main__":
if not torch.cuda.is_available():
raise RuntimeError("This example expects a CUDA device.")
main(sys.argv[1:])The if __name__ == "__main__" guard matters on systems that start workers by importing the script. Without it, each worker can create another DataLoader, causing recursive process creation.
Tune the settings
| Setting | Effect | Common cost |
|---|---|---|
| `num_workers` | Parallel decoding and transforms | CPU cores and memory |
| `prefetch_factor` | Batches queued per worker | More RAM and possible stale work |
| `persistent_workers` | Keeps workers between epochs | Workers retain dataset state |
| `pin_memory` | Allocates page-locked host memory | Extra host-memory overhead |
Start with one worker per available CPU group, not automatically one worker per core. Too many workers can oversubscribe the CPU, compete for disk bandwidth, or make JPEG decoding slower. Measure images per second and accelerator utilisation while changing one setting at a time.
persistent_workers=True avoids process startup at every epoch. It helps when epochs are short or worker initialization is expensive. It does not help if the loader is created only once and never reused.
Common failure modes
- A slow storage device remains the bottleneck even with more workers.
- Random augmentations behave differently because each worker has its own random state.
- Dataset objects that contain open file handles or unpicklable objects fail when workers start.
- Persistent workers can retain stale dataset state. Recreate the loader when the dataset configuration must change.
Exercise
A loader uses four workers and prefetch_factor=2. How many batches can workers request ahead of the current batch?
Show answer
Up to eight batches, because each worker can prefetch two batches.