Building an Efficient Data Pipeline
local graph
Chapter 05: Building an Efficient Data Pipeline
Section titled “Chapter 05: Building an Efficient Data Pipeline”Keeping GPU busy — data pipeline steps, accelerating data loading, optimizing GPU data transfer, increasing workers.
Machine learning is grounded on data. Simply put, the training process feeds the neural network with a bunch of data, such as images, videos, sound, and text. Thus, apart from the training algorithm itself, data loading is an essential part of the entire model-building process.
It turns out that deep learning models deal with huge amounts of data, such as thousands of images and terabytes of text sequences. As a consequence, tasks related to data loading, preparation, and augmentation can severely delay the training process as a whole. So, to overcome a potential bottleneck in the model-building process, we must guarantee an uninterrupted flow of dataset samples to the training process.
In this chapter, we’ll explain how to build an efficient data pipeline to keep the training process running smoothly. The main idea is to prevent the training process from being stalled by data-related tasks.
Here is what you will learn as part of this chapter:
- Understanding why it is mandatory to have an efficient data pipeline
- Learning how to increase the number of workers in the data pipeline
- Understanding how to accelerate data transfer through memory pining
Why do we need an efficient data pipeline?
Section titled “Why do we need an efficient data pipeline?”We’ll start this chapter by making you aware of the relevance of having an efficient data pipeline. In the next few subsections, you will understand what a data pipeline is and how it can impact the performance of the training process.
What is a data pipeline?
Section titled “What is a data pipeline?”As you learned in Chapter 1, Deconstructing the Training Process, the training process is composed of four phases: forward, loss calculation, optimization, and backward. The training algorithm iterates on dataset samples until there’s a complete epoch. Nevertheless, there is an additional phase we excluded from that explanation: data loading.
The forward phase invokes data loading to get dataset samples to execute the training process. More specifically, the forward phase calls the data loading process on each iteration to get the data required to execute the current training step, as shown in Figure 5*.1*:

Figure 5.1 – Data loading process
In short, the data loading executes three main tasks:
- Loading: This step involves reading data from a disk and loading it in memory. We can load data into main memory (DRAM) or directly into GPU memory (GRAM).
- Preparation: Usually, we need to prepare data before using it in the training process, such as by performing normalization and resizing.
- Augmentation: When the dataset is small, we must augment it by creating new samples derived from the original ones. Otherwise, the neural network won’t be able to catch the intrinsic knowledge presented in the data. Augmentation tasks include rotation, mirroring, and flipping images.
In general, data loading executes those tasks on demand. So, when invoked by the forward phase, it starts to execute all tasks to deliver a dataset sample to the training process. Then, we can see this whole process as a data pipeline, in which the data is processed before being used to train the neural network.
A data pipeline (pictorially described in Figure 5*.2*) is similar to an industrial production line. The original dataset sample is processed sequentially and transformed until it is ready to feed the training process:

Figure 5.2 – Data pipeline
In many cases, model quality is dependent on transformations that are made to the dataset. This is particularly true for small datasets – for which augmentation is almost mandatory – and datasets comprised of poor-quality images.
In other situations, we do not need to make any modifications to the sample to reach a highly accurate model, perhaps only changing the data format or something like that. In such cases, the data pipeline is limited to loading dataset samples from memory or disk and delivering them to the forward phase.
Regardless of tasks related to transforming, preparing, and converting data, we need to build a data pipeline to feed the forward phase. In PyTorch, we can use components provided by the torch.utils.data API to create a data pipeline, as we will see in the next section.
How to build a data pipeline
Section titled “How to build a data pipeline”The torch.utils.data API provides two components to build a data pipeline: Dataset and DataLoader (as shown in Figure 5*.3*). The former is used to indicate the source of the dataset (local files, downloads from the internet, and so on) and to define the set of transformations to be applied to the dataset, whereas the latter is used as an interface to obtain samples from the dataset:

Figure 5.3 – The DataLoader and Dataset components
In practical terms, the training process talks directly to DataLoader to consume dataset samples. Thus, the forward phase asks DataLoader for a dataset sample on each training step.
The following piece of code shows an example of the basic usage of DataLoader:
transform = transforms.Compose(transforms.Resize(255))dataset = datasets.CIFAR10(root=data_dir, train=True, download=True, transform=transform)dataloader = torch.utils.data.DataLoader(dataset, batch_size=128)This piece of code creates a DataLoader instance, namely dataloader, to provide samples with batch sizes equal to 128.
Note
Note that Dataset was not used directly in this case since CIFAR-10 encapsulates dataset creation.
There are other strategies to build a data pipeline in PyTorch, but Dataset and DataLoader commonly attend to most cases.
Next, we’ll learn how an inefficient data pipeline can slow down the entire training process.
Data pipeline bottleneck
Section titled “Data pipeline bottleneck”Depending on the complexity of tasks incorporated into the data pipeline, as well as the size of the dataset sample, data loading can take a reasonable time to finish. As a consequence, we can throttle the entire building process.
In general, data loading is executed on the CPU, whereas training takes place on the GPU. As the CPU is much slower than the GPU, the GPU can stay idle, waiting for the next sample to proceed with the training process. The higher the complexity of tasks executed on data feeding, the worse the impact on the training phase.
As shown in Figure 5*.4*, data loading uses the CPU to process dataset samples. When samples become ready, the training phase uses them to train the network. This procedure is continuously executed until all the training steps are completed:

Figure 5.4 – Bottleneck caused by the inefficient data pipeline
Although this procedure seems fine at first sight, we are wasting GPU computing power because it stays idle between training steps. The desired behavior is more like what’s shown in Figure 5*.5*:

Figure 5.5 – Efficient data pipeline
Unlike the previous scenario, the interleaving time between training steps is hardly reduced since samples are loaded earlier, ready to feed the training process that’s executed on the GPU. As a consequence, we experience an overall speedup in the model-building process.
In the next section, we’ll learn how to accelerate the data-loading process by making a couple of simple changes to the code.
Bookmark
Accelerating data loading
Section titled “Accelerating data loading”Accelerating data loading is crucial to get an efficient data pipeline. In general, the following two changes are enough to get the work done:
- Optimizing a data transfer between the CPU and GPU
- Increasing the number of workers in the data pipeline
Putting it that way, these changes may sound tougher to implement than they are. Making these changes is quite simple – we just need to add a couple of parameters when creating the DataLoader instance for the data pipeline. We will cover this in the following subsections.
Optimizing a data transfer to the GPU
Section titled “Optimizing a data transfer to the GPU”To transfer data from main memory to the GPU, and vice versa, the device driver must ask the operating system to pin or lock a portion of memory. After receiving access to that pinned memory, the device driver starts to copy data from the original memory location to the GPU, but using the pinned memory as a staging area:

Figure 5.6 – Data transfer between main memory and GPU
The usage of pinned memory in the middle of this process is obligatory because the device driver cannot copy data directly from pageable memory to the GPU. There are architectural issues involved in that procedure, which explains this behavior. Anyway, we can assert that this double-copy procedure can negatively affect the performance of the data pipeline.
Note
You can find more information about pinned memory transfer here: https://developer.nvidia.com/blog/how-optimize-data-transfers-cuda-cc/.
To overcome this problem, we can tell the device driver to allocate a portion of pinned memory right away instead of requesting a pageable memory area, as usual. By doing so, we can eliminate the unnecessary copy between pageable and pinned memory, thus greatly reducing the overhead involved in GPU data transfer, as shown in Figure 5*.7*:

Figure 5.7 – Data transfer using pinned memory
To enable this option on the data pipeline, we need to turn on the pin_memory flag while creating DataLoader:
dataloader = torch.utils.data.DataLoader(dataset, batch_size=128, pin_memory=True)Nothing else is necessary. But if it is so simple to implement and highly beneficial, why does PyTorch not enable this feature by default? There are two reasons for this:
- Request for pinned memory can fail: As stated on the Nvidia developer blog, “It is possible for pinned memory allocation to fail, so you should always check for errors.” Thus, there is no guarantee of success in allocating pinned memory.
- Increase in memory usage: Modern operating systems commonly adopt a paging mechanism to manage memory resources. By using this strategy, the operating system can move unused memory pages to disk to free space on main memory. However, pinned memory allocation makes the operating system unable to move pages of that area, disrupting the memory management process and increasing the effective amount of memory usage.
Besides optimizing GPU data transfer, we can configure workers to accelerate data pipeline tasks, as discussed in the next section.
Configuring data pipeline workers
Section titled “Configuring data pipeline workers”The default operation mode of DataLoader uses a single process to execute the data pipeline. In other words, a data pipeline has only one process working on loading, preparation, and data augmentation, as shown in Figure 5*.8*. Consequently, DataLoader stays idle waiting for samples, wasting valuable computing resources. Such harmful behavior becomes worse in a heavy data pipeline:

Figure 5.8 – Single worker data pipeline
Fortunately, we can increase the number of processes operating on the data pipeline – that is, we can increase the number of data pipeline workers. When set to more than one worker, PyTorch will create additional processes to work simultaneously in more than one dataset sample:

Figure 5.9 – Multi-worker data pipeline
As illustrated in Figure 5*.9*, DataLoader receives Sample 2 as soon as it asks for a new sample. This happens because Worker 2 has started to work asynchronously and simultaneously on that sample, even without receiving a request to do it.
To increase the number of workers, we just need to set the num_workers parameter on DataLoader creation:
torch.utils.data.DataLoader(train_dataset, batch_size=128, num_workers=2)We’ll look at a practical performance improvement case in the next section.
Reaping the rewards
Section titled “Reaping the rewards”Note
The complete code shown in this section is available at https://github.com/PacktPublishing/Accelerate-Model-Training-with-PyTorch-2.X/blob/main/code/chapter05/complex_pipeline.ipynb.
To see a relevant performance improvement provided by those changes, we need to apply them to a complex data pipeline – that is, a worthy data pipeline! Otherwise, there is no room for performance gain. Therefore, we will adopt a data pipeline composed of seven tasks as our baseline, as shown here:
transform = transforms.Compose( [transforms.Resize(255), transforms.CenterCrop(size=224), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomRotation(20), transforms.GaussianBlur(kernel_size=3), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ])For each sample, the data loading process applies five transformations, namely resizing, cropping, flipping, rotation, and Gaussian blur. After applying these transformations, data loading converts the resultant image into a tensor data type. Finally, the data is normalized according to a set of parameters.
To assess performance improvement, we used this pipeline to train the ResNet121 model over the CIFAR-10 dataset. The training process, which is comprised of 10 epochs, took 1,892 seconds to complete, even running on an environment endowed with an NVIDIA A100 GPU:
Epoch [1/10], Loss: 1.1507, time: 187 secondsEpoch [2/10], Loss: 0.7243, time: 199 seconds Epoch [3/10], Loss: 0.4129, time: 186 seconds Epoch [4/10], Loss: 0.3267, time: 186 seconds Epoch [5/10], Loss: 0.2949, time: 188 seconds Epoch [6/10], Loss: 0.1711, time: 186 seconds Epoch [7/10], Loss: 0.1423, time: 197 seconds Epoch [8/10], Loss: 0.1835, time: 186 seconds Epoch [9/10], Loss: 0.1127, time: 186 seconds Epoch [10/10], Loss: 0.0946, time: 186 seconds Training time: 1892 seconds Accuracy of the network on the 10000 test images: 92.5 %
Note that this data pipeline is significantly heavier than the ones we’ve adopted so far in this book, which is exactly what we want!
To use pinned memory and enable multi-worker capability, we must set those two parameters on the original code:
torch.utils.data.DataLoader(train_dataset, batch_size=128, pin_memory=True, num_workers=8)After applying these changes to our code, we’ll get the following result:
Epoch [1/10], Loss: 1.3163, time: 86 secondsEpoch [2/10], Loss: 0.5258, time: 84 seconds Epoch [3/10], Loss: 0.3629, time: 84 seconds Epoch [4/10], Loss: 0.3328, time: 84 seconds Epoch [5/10], Loss: 0.2507, time: 84 seconds Epoch [6/10], Loss: 0.2655, time: 84 seconds Epoch [7/10], Loss: 0.2022, time: 84 seconds Epoch [8/10], Loss: 0.1434, time: 84 seconds Epoch [9/10], Loss: 0.1462, time: 84 seconds Epoch [10/10], Loss: 0.1897, time: 84 seconds Training time: 846 seconds Accuracy of the network on the 10000 test images: 92.34 %
We have reduced the training time from 1,892 to 846 seconds, representing an impressive performance improvement of 123%!
The next section provides a couple of questions to help you retain what you have learned in this chapter.
Bookmark
Quiz time!
Section titled “Quiz time!”Let’s review what we have learned in this chapter by answering a few questions. Initially, try to answer these questions without consulting the material.
Note
The answers to all these questions are available at https://github.com/PacktPublishing/Accelerate-Model-Training-with-PyTorch-2.X/blob/main/quiz/chapter05-answers.md.
Before starting this quiz, remember that this is not a test! This section aims to complement your learning process by revising and consolidating the content covered in this chapter.
Choose the correct options for the following questions:
- What three main tasks are executed during the data loading process?
- Loading, scaling, and resizing. 2. Scaling, resizing, and loading. 3. Resizing, loading, and filtering. 4. Loading, preparation, and augmentation.
- Data loading feeds which phase of the training process?
- Forward. 2. Backward. 3. Optimization. 4. Loss calculation.
- Which components provided by the
torch.utils.dataAPI can be used to implement a data pipeline?DatapipeandDataLoader. 2.DatasetandDataLoading. 3.DatasetandDataLoader. 4.DatapipeandDataLoading.
- Besides increasing the number of workers in the data pipeline, what can we do to improve the performance of the data loading process?
- Reduce the size of the dataset. 2. Do not use a GPU. 3. Avoid the usage of high-dimensional images. 4. Optimize data transfer between the CPU and GPU.
- How can we accelerate the data transfer between the CPU and GPU?
- Use smaller datasets. 2. Use the fastest GPUs. 3. Allocate and use pinned memory instead of pageable memory. 4. Increase the amount of main memory.
- What should we do to enable the usage of pinned memory on
DataLoader?- Nothing. It is already enabled by default.
2. Set the
pin_memoryparameter toTrue. 3. Set theexperimental_copyparameter toTrue. 4. Update PyTorch to version 2.0.
- Nothing. It is already enabled by default.
2. Set the
- Why can using more than one worker on the pipeline accelerate data loading on PyTorch?
- PyTorch reduces the amount of allocated memory. 2. PyTorch enables the usage of special hardware capabilities. 3. PyTorch uses the fastest links to communicate with GPUs. 4. PyTorch processes simultaneously more than one dataset sample.
- Which of the following is true when making a request to allocate pinned memory?
- It is always satisfied. 2. It can fail. 3. It always fails. 4. It cannot be done through PyTorch.
Now, let’s summarize what we’ve covered in this chapter.