Sub topic 7
Parallel loading: workers, prefetching, and persistent workers
This chapter assumes you know basic PyTorch (Dataset, DataLoader, tensors), can read a NumPy image array shaped height by width by channels, and have already measured your pipeline's stages as covered earlier in the tutorial. If the profile shows that reading, decoding and resizing take longer than the model step, this chapter is where you fix that.
Why one process is not enough
Decoding a JPEG and resizing it is CPU work. With num_workers=0, the DataLoader runs that work in the same process that drives the training loop. The GPU sits idle while the next batch is built, and the CPU sits idle while the GPU computes.
Python adds a second limit. The Global Interpreter Lock (GIL) lets only one thread run Python bytecode at a time. Pillow releases the GIL during decoding and resizing, so threads can help a little, but the Python code around those calls (indexing, array conversion, your own transforms) still serialises. PyTorch's DataLoader therefore uses separate processes instead of threads.
Each worker process holds its own copy of the dataset object and builds whole batches. The main process receives finished batches through shared memory and feeds them to the model.
How the DataLoader assigns work
The main process asks the sampler for indices and groups them into batches of batch_size. It then sends one batch of indices to one worker. That worker calls dataset[i] for each index, runs the collate function, and places the resulting batch in shared memory. The main process hands batches to your loop in the original order, even if a later batch finishes first.
Two consequences follow:
- Parallelism is across batches. With a batch size of 64 and four workers, four batches are being built at once.
- One slow image delays its whole batch, and therefore delays every batch behind it in the ordering.
The main parameters
The configuration below uses the dataset from the earlier chapter, which decodes with draft and returns uint8 tensors.
from torch.utils.data import DataLoader
loader = DataLoader(
ImageDataset(paths),
batch_size=64,
shuffle=True,
num_workers=4,
pin_memory=True,
persistent_workers=True,
prefetch_factor=2,
)| Parameter | What it does | Typical guidance |
|---|---|---|
| `num_workers` | Number of worker processes. `0` means load in the main process. | Start near the number of physical CPU cores available to this job, then measure. |
| `prefetch_factor` | Batches each worker prepares ahead of demand. Default is 2. | Raise only if the GPU waits on data despite enough workers. Only valid when `num_workers > 0`. |
| `persistent_workers` | Keep workers alive between epochs. | Use `True` when epochs are short or worker startup is slow. Requires `num_workers > 0`. |
| `pin_memory` | Allocate batches in page-locked memory for faster GPU copies. | Use `True` when training on a CUDA GPU. Covered fully in a later chapter. |
| `timeout` | Seconds to wait for a batch before raising an error. | Set a limit when debugging hangs. `0` means no limit. |
Prefetching
With prefetch_factor=2 and four workers, up to eight batches can be waiting in the queue. Prefetching hides variation in per-batch time: while the GPU works on batch N, the workers are already building N+1 through N+8.
More prefetch does not make a slow pipeline faster. If the workers cannot produce batches as fast as the GPU consumes them, the queue is always empty and the extra capacity is never used. Larger queues only cost memory, because each queued batch occupies shared memory. A 64-image batch of 224 by 224 uint8 images is about 9.6 MB, which is small. The same batch as float32 is about 38.5 MB, so eight queued batches would hold roughly 300 MB.
Persistent workers
By default, workers are shut down at the end of each pass over the loader and started again at the next one. Starting a worker means creating a process, and on platforms that use the spawn start method (Windows, and macOS by default) it also means re-importing your modules and rebuilding the dataset object in each process. With short epochs this startup can be a visible pause at every epoch boundary.
persistent_workers=True keeps the processes alive. The first epoch pays the startup cost once, and later epochs begin immediately, with workers already prefetching.
Choosing num_workers
The right number depends on the CPU, the storage and the per-image cost. A practical procedure:
- Time the loader alone, with no model, over a fixed number of batches.
- Try
num_workersvalues such as 0, 2, 4, 8 and 16. - Stop increasing when throughput stops rising.
This script performs steps 1 and 2. It skips the first few batches so that worker startup does not distort the numbers.
import time
from torch.utils.data import DataLoader
def loader_throughput(dataset, num_workers, batch_size=64, n_batches=50, warmup=5):
loader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
persistent_workers=num_workers > 0,
)
it = iter(loader)
for _ in range(warmup):
next(it)
t0 = time.perf_counter()
count = 0
for _ in range(n_batches):
batch = next(it)
count += batch.shape[0]
dt = time.perf_counter() - t0
return count / dt
if __name__ == "__main__":
ds = ImageDataset(paths) # paths: your list of image files
for nw in (0, 2, 4, 8):
print(nw, "workers:", round(loader_throughput(ds, nw)), "images/s")The if __name__ == "__main__": guard matters. Under spawn, each worker imports your script, and without the guard it would start creating loaders of its own.
Expect gains to flatten for three common reasons:
- CPU limit. Workers beyond the number of available cores compete for the same cores. Respect container or scheduler limits:
os.cpu_count()reports the machine, not your allocation. On Linux,len(os.sched_getaffinity(0))reports the cores this process may use. - Storage limit. If files sit on a network disk, throughput is capped by the disk or network, and more workers add no speed.
- Hidden threading. Libraries such as NumPy, OpenCV and PyTorch can use several threads per process. Eight workers each running eight threads oversubscribe the CPU. PyTorch sets intra-op threads to 1 inside workers, but OpenCV and BLAS libraries may need
cv2.setNumThreads(0)orOMP_NUM_THREADS=1.
Common errors and failure modes
Memory growth in workers
Linux creates workers with fork, which shares the parent's memory copy-on-write. Python reference counting writes to objects whenever they are read, so memory pages holding a large Python list of file paths are gradually copied into each worker. A list of millions of strings can therefore use several times the expected memory with many workers.
The fix is to store large metadata in a NumPy array or Arrow table, which keeps data in a few big buffers instead of millions of small objects. For paths, one approach is a single byte array plus an offsets array.
Random augmentation repeating across workers
PyTorch seeds each worker's torch random generator differently, so torch.rand augmentations differ per worker. NumPy and Python's random module are not always seeded distinctly, depending on version and start method. If you use them in __getitem__, seed them in worker_init_fn:
import random
import numpy as np
import torch
def seed_worker(worker_id):
seed = torch.initial_seed() % 2**32
np.random.seed(seed)
random.seed(seed)
# DataLoader(..., worker_init_fn=seed_worker)Hangs and crashes
- A worker killed by the operating system for running out of memory produces an error such as "DataLoader worker exited unexpectedly". Reduce
num_workers,prefetch_factororbatch_size. - In containers, a small
/dev/shm(shared memory) makes batch transfer fail with a bus error. Increase the shared memory size for the container. - To debug an exception inside
__getitem__, setnum_workers=0first. The traceback is then direct and breakpoints work. - Opening a CUDA context or a database connection in the dataset's
__init__and then forking can break. Open such resources lazily inside__getitem__or inworker_init_fn.
Tiny datasets and short epochs
With a small dataset and a large num_workers, some workers receive no batches. Startup cost can then exceed the work. Use fewer workers, or use persistent_workers=True so you pay startup once.
Reading the result
Run the throughput script and compare it with your model's training speed in images per second. If loader throughput is above the model's rate, the loader is not the bottleneck and extra workers waste CPU and memory. If it is below, the GPU waits for data and the pipeline is the limit: reduce per-image cost with the earlier techniques (draft decoding, uint8 data) or add workers until a CPU, storage or memory limit stops you.
Exercise
A training job on an 8-core machine uses num_workers=16 and prefetch_factor=4. Throughput is no higher than with num_workers=8, and memory use is much higher. Give two likely reasons and one change you would test first.
Show answer
With only 8 cores, the extra 8 workers compete for the same CPUs, so decoding cannot go faster, and each extra worker adds memory for its own dataset copy and queued batches. The larger prefetch queue also holds up to 16 x 4 = 64 batches in shared memory, which does not help when the workers cannot produce batches faster than they are consumed. Test first with num_workers at about the core count (for example 8 or 6, leaving a core for the main process) and prefetch_factor=2, measuring loader-only throughput.
Exercise
Your epochs are 20 seconds long and you see a pause of several seconds at the start of every epoch, but loader throughput within an epoch is fine. What setting addresses this, and what is the catch?
Show answer
Set persistent_workers=True (with num_workers > 0), so workers start once and stay alive between epochs. The catch is that workers keep their copy of the dataset, so any change you make to the dataset object between epochs is not seen by them. If you need to change it, build a new loader.