Skip to main content

Loading data in parallel

Author

Marie-Hélène Burle

DataLoaders can handle multiple workers to load and transform data in parallel.

In this section, we start launching batch jobs to do this efficiently.

Worker processes

Decoding and transforming images is CPU work. With the default num_workers=0, it all happens in the main Python process, one image at a time. While the main process decodes the next batch, the accelerator has nothing to do.

With num_workers=n, the DataLoader spawns n worker processes. Each worker prepares whole batches (decodes, transforms, collates) and pushes them into a queue, from which the main process pulls as it consumes them:

flowchart TB
    classDef default color:#0081c2, stroke:#0081c2;
    D[(Files on disk)] --> w1 & w2 & w3
    subgraph W["`** Worker processes**`"]
        w1[Decode + transform] --> b1[Batch]
        w2[Decode + transform] --> b2[Batch]
        w3[Decode + transform] --> b3[Batch]
    end
    b1 & b2 & b3 --> Q[Prefetch queue]
    Q --> P[Pinned memory] -->|async copy| G([Training step on the accelerator])

The queue smooths out the hiccups: workers run ahead of the consumer (by how much is set by the prefetch_factor option seen below), so loading overlaps with compute.

How many workers to use?

Obviously, workers beyond your CPU count are wasted. But you shouldn’t necessarily use as much hardware as is available: every worker is a separate process with a copy of the dataset object and its prefetch buffers. This means that more workers use more RAM.

4 is a reasonable default, but ideally, you want to run tests to find the optimum value. Once the gains flatten, decoding is no longer the bottleneck.

I ran some measurements on my laptop (8 CPU cores, 16 threads) with the following script. The timed_pass function runs one warmup pass (spawning workers and paying the one-time startup cost), then times a second pass in a steady state:

n_workers.py
import time  # to time experiments
from pathlib import Path

import torch
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import EuroSAT
from torchvision.transforms import v2 as T

to_tensor = T.Compose([T.ToImage(), T.ToDtype(torch.float32, scale=True)])
root = Path("/project/def-sponsor00/data")
eurosat = EuroSAT(root=root, transform=to_tensor)
idx = torch.load(root / "split.pt", weights_only=True)
train = Subset(eurosat, idx["train"])


def timed_pass(num_workers):
    """Time one full pass over the training data at steady state."""
    loader = DataLoader(train, batch_size=64, num_workers=num_workers)
    for _ in loader:
        pass  # warmup
    t0 = time.perf_counter()
    n = 0
    for _, labels in loader:
        n += labels.numel()
    dt = time.perf_counter() - t0
    del loader  # shuts the workers down
    assert n == len(train)
    return dt


if __name__ == "__main__":
    for w in (0, 2, 4, 8, 16):
        print(f"num_workers={w}: {timed_pass(w):5.1f} s")

In a Python script, code that creates DataLoaders with workers must sit under the main guard:

if __name__ == "__main__":

Without it, worker startup re-imports your script: module-level code runs again and the run crashes with a RuntimeError. Jupyter notebook cells are immune: an interactive __main__ cannot be re-imported.

On my laptop, one pass over the 21,600 training images took about 6 s in the main process, and less than 1 s with 16 workers.

num_workers=0:   6.1 s
num_workers=2:   3.6 s
num_workers=4:   1.9 s
num_workers=8:   1.2 s
num_workers=16:  0.8 s

The benefit of additional workers is decreasing but hasn’t quite flattened out yet, so on my system, I could use all my threads.

Let’s test it on the cluster. The current training cluster contains 2 CPU nodes, each with 8 CPUs and 30 GB of RAM. First, save the script above as a Python file (e.g. with nano n_workers.py). If you launch it as is, you will get:

UserWarning: This DataLoader will create 16 worker processes in total. Our suggested max
number of worker in current system is 8, which is smaller than what this DataLoader is
going to create. Please be aware that excessive worker creation might get DataLoader
running slow or even freeze, lower the worker number to avoid potential slowness/freeze
if necessary.

This makes sense, since you would be trying to launch 16 workers on 8 CPUs. So edit the script first to remove the 16-worker run, then run it with:

srun --mem-per-cpu=3600 --cpus-per-task=8 python n_workers.py
  • Because we only have 2 compute nodes, only 2 people can run this at a time, so this might take some time. Not everybody has to run it though.

  • Normally, batch jobs are launched with sbatch, but srun is convenient here because the jobs are extremely short and we can see immediately when the job has finished running, without having to run sq repeatedly to check on them.

This is what I got:

num_workers=0:   9.5 s
num_workers=2:   5.5 s
num_workers=4:   2.7 s
num_workers=8:   1.8 s

So you can see that we don’t reach a plateau here either, and we would probably benefit from more CPUs (but we don’t have them).

Worker lifetime

Workers are spawned when iteration starts and die when the iterator is exhausted, so a fresh set is spawned at every epoch. persistent_workers=True keeps them alive across epochs. Does it matter in our situation? Let’s test it:

n_persistent_workers.py
import time  # to time experiments
from pathlib import Path

import torch
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import EuroSAT
from torchvision.transforms import v2 as T

to_tensor = T.Compose([T.ToImage(), T.ToDtype(torch.float32, scale=True)])
root = Path("/project/def-sponsor00/data")
eurosat = EuroSAT(root=root, transform=to_tensor)
idx = torch.load(root / "split.pt", weights_only=True)
train = Subset(eurosat, idx["train"])


def timed_pass(num_workers):
    """Time one full pass over the training data at steady state."""
    loader = DataLoader(
        train,
        batch_size=64,
        num_workers=num_workers,
        persistent_workers=num_workers > 0,  # keeps workers alive
    )
    for _ in loader:
        pass  # warmup
    t0 = time.perf_counter()
    n = 0
    for _, labels in loader:
        n += labels.numel()
    dt = time.perf_counter() - t0
    del loader  # shuts the workers down
    assert n == len(train)
    return dt


if __name__ == "__main__":
    for w in (0, 2, 4, 8, 16):
        print(f"num_workers={w}: {timed_pass(w):5.1f} s")

This is what I got:

num_workers=0:   6.1 s
num_workers=2:   3.7 s
num_workers=4:   2.0 s
num_workers=8:   1.4 s
num_workers=16:  1.2 s

And on the training cluster:

num_workers=0:   9.7 s
num_workers=2:   6.3 s
num_workers=4:   2.7 s
num_workers=8:   1.9 s

We get very much the same timings. In addition, idle workers hold RAM between epochs, and the dataset must not change while the workers are alive. In our situation, it isn’t worth it.

In many cases, it will make multi-epoch training loops more efficient, so whenever you use num_workers > 0 on static datasets for multiple epochs, you should consider it. On Linux (my system and the cluster), Python 3.14 launches them with forkserver, which is efficient. On Windows and macOS, they are started by the much slower spawn, so avoiding multiple launches by keeping your workers alive is likely to make a big difference there.

Situations in which you should not consider this option include:

  • single-epoch runs (obviously),
  • num_workers=0 (obviously),
  • limited available RAM,
  • dynamic datasets that get updated at each epoch (the DataLoader will not get the updates).

Prefetching

Each worker prepares prefetch_factor batches (2 by default) ahead of the one being consumed, so up to num_workers × prefetch_factor batches sit in the queue. With fast storage and cheap transforms, the default is plenty. Raise it when the storage is slow (e.g. a network filesystem) or the transforms are expensive, so that occasional slow reads get absorbed by the queue rather than stalling the accelerator. It costs buffer RAM and only takes effect with num_workers > 0:

loader = DataLoader(train, batch_size=64, num_workers=8, prefetch_factor=4)

Pinned memory

By default, tensors loaded in the main process live in pageable memory, which the operating system can move or swap out to disk.

Transfers to the accelerator from pinned (page-locked) memory are faster and can run asynchronously (with .to(device, non_blocking=True)) while the previous training step computes.

With pin_memory=True, the DataLoader copies each batch into pinned memory for you.

Here is the time of one host-to-device copy, measured on my laptop GPU for our batch shape (64, 3, 64, 64) in float32 (3 MiB) and for a batch 8 times larger (24 MiB):

batch  64:  pageable 541 µs   pinned 495 µs
batch 512:  pageable 6250 µs  pinned 3933 µs

That is only a few percent at our batch size and about 40% for the larger one: the gain is small, but it has few downsides. The caveat is that pinned memory cannot be swapped, so pin batches, but not full datasets.

Data loading bottleneck

How do you diagnose an accelerator-starved run?

The classic symptom is an accelerator that alternates between busy and idle: watch the GPU-Util column of nvidia-smi while training (see our GPU notes) or check epoch times against a rough estimate of pure compute.

I trained a small CNN that we will see later (about 95,000 parameters) on EuroSAT for two epochs per configuration on my laptop GPU (RTX 2060, 6 GiB):

for num_workers in (0, 2, 4, 8):
    loader = DataLoader(
        train,
        batch_size=64,
        shuffle=True,
        pin_memory=True,
        num_workers=num_workers,
        persistent_workers=num_workers > 0,
    )
    for epoch in range(2):  # warmup, then the timed epoch
        t0 = time.perf_counter()
        for x, y in loader:
            x = x.to(device, non_blocking=True)
            y = y.to(device, non_blocking=True)
            loss = loss_fn(model(x), y)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        if epoch:  # mean_util: average of the nvidia-smi samples
            print(
                f"num_workers={num_workers}: "
                f"{time.perf_counter() - t0:5.1f} s/epoch, GPU util {mean_util:3.0f}%"
            )

I sampled utilization with nvidia-smi in a background thread and got the following results:

num_workers=0:  10.7 s/epoch, GPU util  31%
num_workers=2:   5.2 s/epoch, GPU util  51%
num_workers=4:   3.2 s/epoch, GPU util  85%
num_workers=8:   3.1 s/epoch, GPU util  89%

These numbers show that:

  • With loading in the main process, the GPU did useful work 31% of the time: the rest was waiting for JPEG decoding. A pure loading pass took 8.1 s, longer than a compute-bound epoch.
  • Four workers hid loading under compute: epochs got 3.4× faster and utilization reached 85%.
  • Going from 4 to 8 workers bought almost nothing: with this model, 4 workers already feed the GPU as fast as it consumes.

These ratios are specific to a small model on a laptop GPU. A larger model computes longer per batch, so it needs fewer workers to stay busy. When a run is accelerator-starved, tune in this order: more workers first, then prefetch_factor, then pin_memory.

Our final loaders

Here are the loaders that we will use for the rest of the course:

loader_kwargs = {
    "batch_size": 64,
    "num_workers": 8,
    "pin_memory": torch.accelerator.is_available(),
}
train_loader = DataLoader(train, shuffle=True, **loader_kwargs)
val_loader = DataLoader(val, **loader_kwargs)
  • Batches of 64: a good size for the small models of this course.
  • 8 workers each.
  • Pinned memory when an accelerator is present.
  • Shuffling for training only.

Batches of float32 tensors in [0, 1] now flow from both splits.