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])
Data loading optimizations
There are many ways to improve training, but you should first identify what is slowing things down.
The bottleneck can be caused by data loading. When that is the case, the best way to improve timing is to load and transform the data in parallel using multiple CPUs (DataLoaders can handle multiple workers). But how many should you use? Other options involve keeping the workers alive, prefetching, or pinning memory.
In this section, we run 2 epochs of our training loop to test a number of loading configurations.
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 or check epoch times against a rough estimate of pure compute.
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:
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.
The optimum depends on the balance between:
- the time the workers need to prepare a batch,
- the time the rest of the training loop needs to consume it.
Once the workers keep up with the loop, additional workers don’t bring anything. So the meaningful test is to time epochs of the real training loop with increasing numbers of workers, and to stop when the epochs stop getting faster. If the accelerator is still idle at that point, the limit is elsewhere (e.g. saturated CPUs or slow storage), not in the number of workers.
Let’s create a directory for the course, then enter it:
mkdir pytorch_course && cd pytorch_courseNow, we can wrap a simpler version of the code we developed earlier in a script (let’s call it bottleneck.py) which trains the model for two epochs and plays with data loading configurations.
To create the file, you can use nano or the text editor of your choice:
nano bottleneck.pyThere is something that we need to change though. 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. A standard way to handle this is to bring the setup and our three functions inside a main() function and run that that function under the guard.
Jupyter notebook cells are immune to this which is why we didn’t have to worry about this until now.
Here is the script:
Ideally, you want to use more CPUs and run the test on, for instance, 2, 4, 8, and 16 workers. Unfortunately, our training cluster’s GPU node only has 3 CPUs, so this is all we can test here.
In addition to the timed epoch, it would be great to get some average GPU utilization.
On my laptop, I installed the nvidia-ml-py package (Python bindings for the NVIDIA Management Library (NVML), which is the library behind nvidia-smi). A background thread calls nvmlDeviceGetUtilizationRates every 0.1 s and appends the value (the one shown in the GPU-Util column of nvidia-smi) to a list. At the end of the timed epoch, the thread is stopped and the mean of the list is printed. The GPU is identified by its UUID rather than by its index because NVML does not number GPUs like CUDA does: it ignores CUDA_VISIBLE_DEVICES, so on a node with several GPUs, NVML’s GPU 0 is not necessarily the GPU of your job. The driver only refreshes this value every 1/6 to 1 s (depending on the GPU), so polling it faster would be pointless, and the average remains a coarse number for epochs that last a few seconds.
I then adapted the script above to use this package:
This gives me an estimate of the mean GPU usage during the test.
Our training cluster however uses an NVIDIA multi-instance GPU (MIG). For security reasons, nvidia-smi can only gather limited information on MIGs and the nvidia-ml-py package does not work with them.
If you use the Alliance clusters, you have several options to monitor GPU usage:
If you use a cluster that has a Metrix portal (currently Rorqual, Narval, and Nibi, with Fir coming up), this is the easiest option.
If you use a cluster without the Metrix portal and you use a full GPU, you can:
- run an equivalent to the script bottleneck_nvml.py to use the Python wrapper package,
- log metrics as part of your job,
- monitor the GPU live from another terminal with either of:
# using nvtop
srun --jobid=<your_running_job_id> --overlap --pty nvtop
# using nvidia-smi
srun --jobid=<your_running_job_id> --overlap --pty watch -n 1 nvidia-smiYou can find the job id by running sq.
Running the script
To launch this script, we can use:
srun --mem=10000 --gpus-per-node=1 --cpus-per-task=3 python bottleneck.py--mem is the memory requested for all the CPUs of the job (3 here), not per CPU. Let’s thus roughly triple the memory we were asking for per CPU on the CPU nodes.
We are using srun here because the jobs are very short and we want to be notified and get the results as soon as they become available. On a production cluster, for a normal job, you would create a batch script:
bottleneck.sh
#!/bin/bash
#SBATCH --account=def-<user>
#SBATCH --gpus-per-node=h100:1 # or whatever GPU type you want
#SBATCH --cpus-per-task=3 # CPU cores
#SBATCH --mem=10000 # memory per node
#SBATCH --time=0-03:00
python bottleneck.pyThen you would launch the job with:
sbatch bottleneck.shYou would then monitor it with sq, seff, etc.
Because we only have 2 GPU nodes, only 2 people can run this at a time (and it takes a while), so maybe not everybody should run it.
Results
This is what I got on the training cluster:
num_workers=0: 24.1 s/epoch
num_workers=2: 15.7 s/epoch
num_workers=3: 8.7 s/epoch
On my laptop (8 CPU cores, 16 threads), using the script bottleneck_nvml.py with for num_workers in (0, 2, 4, 8, 16): I got:
num_workers=0: 11.3 s/epoch, GPU util 29%
num_workers=2: 6.6 s/epoch, GPU util 41%
num_workers=4: 3.6 s/epoch, GPU util 76%
num_workers=8: 3.1 s/epoch, GPU util 89%
num_workers=16: 3.3 s/epoch, GPU util 84%
These numbers show that, on the training cluster, we should keep increasing the number of workers (we just don’t have the hardware). On my laptop however, going from 4 to 8 workers didn’t bring much and going to 16 workers made things worse. With this model and these settings, 8 workers already feed the GPU as fast as it consumes.
On my laptop, with loading in the main process, the GPU did useful work 29% of the time: the rest was waiting for the data pipeline, which decoded the images and applied the transforms one image at a time in the main process. 8 workers hid loading under compute: epochs got 3.6 times faster and GPU utilization reached 89%.
These ratios are specific to our small model: a larger model computes longer per batch, so it needs fewer workers to stay busy.
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.
Edit the bottleneck.py file to have:
bottleneck.py
...
for num_workers in (2, 3): # remove 0
loader = DataLoader(
train,
batch_size=64,
shuffle=True,
generator=torch.Generator().manual_seed(42),
num_workers=num_workers,
# This is the new line:
persistent_workers=True,
)
...We remove the measurement with 0 worker as it is meaningless for this test.
With persistent_workers=False, the workers are shut down at the end of the warmup pass, so the timed pass includes the cost of starting a new set. With persistent_workers=True, the timed pass reuses the workers of the warmup pass. This is what I got on the cluster:
Results
On the training cluster:
num_workers=2: 15.7 s/epoch
num_workers=3: 7.8 s/epoch
On my machine with bottleneck_nvml.py, also removing the now ruled-out measurement with 16 workers:
num_workers=2: 6.4 s/epoch, GPU util 42%
num_workers=4: 3.4 s/epoch, GPU util 80%
num_workers=8: 2.9 s/epoch, GPU util 95%
Both on the training cluster and on my laptop, we got a little improvement: keeping the workers alive saved their start-up time.
In most cases, keeping workers alive 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 (idle workers hold RAM between epochs),
- 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 works with num_workers > 0:
Edit the bottleneck.py file to now have:
bottleneck.py
...
for num_workers in (2, 3):
loader = DataLoader(
train,
batch_size=64,
shuffle=True,
generator=torch.Generator().manual_seed(42),
num_workers=num_workers,
persistent_workers=True,
# This is the new line:
prefetch_factor=4,
)
...Results
This is what I got on the cluster:
num_workers=2: 16.2 s/epoch
num_workers=3: 8.3 s/epoch
And on my laptop:
num_workers=2: 6.2 s/epoch, GPU util 44%
num_workers=4: 3.5 s/epoch, GPU util 79%
num_workers=8: 2.9 s/epoch, GPU util 95%
With our dataset, we get no improvement by prefetching data.
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.
Edit the bottleneck.py file to now have:
bottleneck.py
...
for num_workers in (2, 3):
loader = DataLoader(
train,
batch_size=64,
shuffle=True,
generator=torch.Generator().manual_seed(42),
num_workers=num_workers,
persistent_workers=True,
# This is the new line:
pin_memory=True,
)
...Results
Results on the cluster:
num_workers=2: 15.5 s/epoch
num_workers=3: 7.4 s/epoch
On my laptop:
num_workers=2: 7.8 s/epoch, GPU util 34%
num_workers=4: 3.4 s/epoch, GPU util 79%
num_workers=8: 2.8 s/epoch, GPU util 100%
Pinned memory gives us a speedup and on my laptop, I am now reaching 100% GPU usage with 8 workers! (this is what you want: it means that you optimized the code for the hardware).
This is a useful technique in many situations. The only downside is that pinned memory cannot be swapped, so pin batches, not full datasets.
Summary
When a run is accelerator-starved, tune in this order:
- more workers first and keep them alive if possible,
- then
prefetch_factor, - then
pin_memory.
The complete data pipeline
The data side of the course is now complete: datasets with the right transform per split, loaders with the options measured earlier. Here is what it looks like:
train = Subset(EuroSAT(root=root, transform=train_tf), idx["train"])
val = Subset(EuroSAT(root=root, transform=val_tf), idx["val"])
print(
f"Length of the training set: {len(train)}\nLength of the validation set: {len(val)}"
)Length of the training set: 21600
Length of the validation set: 5400
loader_kwargs = {
"batch_size": 64,
"num_workers": 3,
"persistent_workers": True,
"pin_memory": True,
}
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.
- 3 persistent workers (we would use more if we had the hardware).
- Pinned memory.
- Shuffling for training only.
Batches of float32 tensors in [0, 1] now flow from both splits.
One training batch:
images, labels = next(iter(train_loader))
print(
f"Images batch shape: {images.shape}\nImages batch type: {images.dtype}\nMin, max image values: {images.min():.2f}, {images.max():.2f}"
)
print(f"First few labels: {labels[:8]}")Images batch shape: torch.Size([64, 3, 64, 64])
Images batch type: torch.float32
Min, max image values: -2.12, 2.64
First few labels: tensor([7, 2, 9, 7, 8, 1, 1, 9])
Augmented, normalized, shuffled batches of tensors now flow at steady state.
Let’s create a train.py script with the code we developed earlier modified with the new loader arguments. Additionally, we will save the training history to file so that we can plot it later.
Plotting the learning curves after training makes sense here because training is so fast. When you run training loops for hours, days, or weeks, you don’t want to wait until the end to see how things are going! In those cases, you want to use live monitoring tools such as TensorBoard or MLflow. We will talk about MLflow later in this course.
This is the script we will run to train our model in the next section.