Skip to content
ImagineWorld

Training Models Faster

node_idnode-book_accelerate-model-training-with-pytorch_chapter-02-training-models-faster
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleTraining Models Faster
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the last chapter, we learned the factors that contribute to increasing the computational burden of the training process. Those factors have a direct influence on the complexity of the training phase and, hence, on the execution time.

Now, it is time to learn how to accelerate this process. In general, we can improve performance by changing something in the software stack or increasing the number of computing resources.

In this chapter, we will start to understand both of these options. Next, we will learn what can be modified in the application and environment layers.

Here is what you will learn as part of this chapter:

  • Understanding the approaches to accelerate the training process
  • Knowing the layers of the software stack used to train a model
  • Learning the difference between vertical and horizontal scaling
  • Understanding what can be changed in the application layer to accelerate the training process.
  • Understanding what can be changed in the environment layer to improve the performance of the training phase

Once we have decided to accelerate the training process of a model, we can take two directions, as illustrated in Figure 2*.1*:

Figure 2.1 – Approaches to accelerating the training phase

Figure 2.1 – Approaches to accelerating the training phase

In the first option (Modify the software stack), we go through each layer of the software stack used to train a model to seek opportunities to improve the training process. In simpler words, we can change the application code, install and use a specialized library, or enable a special capability regarding the operating system or container environment.

This first approach relies on having profound knowledge of performance tuning techniques. In addition, it demands a high sense of investigation to identify bottlenecks and apply the most suitable solution to overcome them. Thus, this approach is about harnessing the most hardware and software resources by extracting the maximum performance of the computing system.

Nevertheless, remark that depending on the environment we are running the training process in, we may not have the required privileges to change the lower layers of the software stack. For example, suppose we are running the training process in a notebook provided by a third-party environment such as Kaggle or Google Colab. In this case, we cannot change operating system parameters or modify the container image because this environment is controlled and restricted. We can still change the application code, but it may not be enough to accelerate the training process.

When changing things in the software stack is impossible or does not provide the expected performance gain, we can go towards the second option (Increase computing resources) to train the model. So, we can increase the number of processors and the amount of main memory, use accelerator devices, or spread the training process across multiple machines. Naturally, we may need to spend money to bring this option to life.

Notice that this approach is easier in the cloud than for on-premises infrastructures. When using the cloud, we can easily contract a machine endowed with accelerator devices or add more machines to our setup. We can get these resources ready to use with a few clicks. On the other hand, we may face some constraints when adding new computing resources to the on-premises infrastructure, such as physical space and energy capacity restrictions. It is not impossible, though; it might only be more challenging to do.

Furthermore, we also have another scenario in which our infrastructure, either on the cloud or on-premises, already has those computing resources. In this case, we just need to start using them to accelerate the training process.

So, if we have money to buy or contract these resources, or if they are already available to us in our environment, the problem is solved, right? Not necessarily. Unfortunately, there is no guarantee that using additional resources in the training process will automatically improve performance. As we will discuss in this book, the performance bottleneck is not always overcome by adding more computing resources without rethinking the whole process, adjusting the code, and so on.

This last assertion gives us a valuable lesson: we must see these two approaches as a cycle, not as two isolated options. This means we must go back and forth on both methods as often as necessary to reach the desired improvement, as shown in Figure 2*.2*:

Figure 2.2 – Continuous improvement cycle

Figure 2.2 – Continuous improvement cycle

Let’s see more details about both approaches in the following sections.

The software stack used to train a model can vary depending on the environment we use to execute this process. For the sake of simplicity, we will consider in this book a software stack seen from the point of view of data scientists, i.e., as users of a computing service or environment.

In general, we can say the software stack looks like the layers shown in Figure 2*.3*:

Figure 2.3 – Software stack used to train a model

Figure 2.3 – Software stack used to train a model

From the top to the bottom, we have the following layers:

  1. Application: The model-building program occupies this layer. This program can be written in any programming language capable of building neural networks, such as R and Julia, but Python is the language primarily used for this purpose.
  2. Environment: The machine learning framework used to build the application, libraries, and tools used to support this framework lie in this layer. Some examples of machine learning frameworks are PyTorch, TensorFlow, Keras, and MxNet. Concerning the set of libraries, we can cite Nvidia Collective Communication Library (NCCL), for efficient communication among GPUs, and jemalloc, for optimized memory allocation.
  3. Execution: This layer is responsible for supporting the execution of the environment and application layers. Therefore, a container solution or bare metal operating system belongs to this layer. Although the components of the upper layers can be executed directly on the operating system, nowadays, it is common to use a container to wrap up the entire application and its environment. Although Docker is the most famous container solution, it is preferable to adopt a more suitable option to run machine learning workloads such as Apptainer and Enroot.

At the bottom of the software stack, there is a box representing all the hardware resources needed to execute the upper software layers.

To obtain a practical understanding of this software stack representation, let’s see a couple of examples, as illustrated in Figure 2*.4*:

Figure 2.4 – Examples of software stacks

Figure 2.4 – Examples of software stacks

All scenarios described in Figure 2*.4* use an application written in Python. As stated before, the application can be a program coded in C++ or a script written in R. It does not matter. The important note to keep in mind is that the application layer represents the location of our code. In examples A, B, and D, we have scenarios using PyTorch as the machine learning framework. Cases A and B have the support of additional libraries, namely OpenMP and Intel One API. This means PyTorch is relying on these libraries to empower tasks and operations.

Finally, the execution layer of scenarios B and C uses a container solution to execute the upper layers, whereas the upper layers of examples A and D run directly on the operating system. Furthermore, notice that the hardware resources in scenarios B and C are endowed with GPU accelerators, whereas the others have only a CPU.

Important note

Remark that we are abstracting the type of infrastructure used to run the software stack since it is irrelevant to our discussion at this moment. Therefore, you can consider the software stack hosted in a cloud or on-premises infrastructure.

Except for the case where we are using an environment provided by our own resources, we probably will not have the administrative rights to modify or add configurations in the execution layer. In most cases, we use the computing environments provisioned by our companies. Thus, we do not possess the privilege to alter anything in the container or operating system layers. Usually, we address these modifications to the IT infrastructure team.

For this reason, we will focus on the application and environment layers, where we have the power to change and perform additional configurations.

The second part of this book focuses on teaching you how to change the software stack in such a way that we can accelerate the training process with the available resources.

Important note

There are exciting configurations we can make in the execution layer to improve performance. However, they are out of the scope of this book. As data scientists are the primary audience of this material, we focus on the layers that these professionals have the necessary access to modify and customize by themselves.

Modifying the software stack to accelerate the training process has a limit. We get stuck on performance improvement, no matter how deep and advanced the techniques we use are. When we reach that limit, the one way to speed up the training phase is by using additional computing resources, as explained in the next section.

There are two approaches to increasing computing resources in an existing environment: vertical and horizontal scaling. In vertical scaling, we augment the computing resources of a single machine, whereas, in horizontal scaling, we add more machines to the pool of equipment used to train the model.

In practical terms, vertical scaling allows for equipping the machine with an accelerator device to increase main memory, add more processor cores, and so on, as exemplified in Figure 2*.5*. After doing this scaling, we obtain an empowered machine with higher resources:

Figure 2.5 – Example of vertical scaling

Figure 2.5 – Example of vertical scaling

Horizontal scaling is related to the increase in the number of machines used by our application. If we originally used one machine to execute the training process, we can apply horizontal scaling and use two machines to work together to train the model, as shown in the example of Figure 2*.6*:

Figure 2.6 – Example of horizontal scaling

Figure 2.6 – Example of horizontal scaling

Regardless of the type of scaling, we need to know how to harness these additional resources to improve performance. Depending on the kind of resources added to our setup, we need to adjust the code in many different parts. In other situations, the machine learning framework can automatically deal with the increase in resources without requiring any additional modification.

As we learned in this section, the first step to accelerate the training process relies on modifying the application layer. Follow me to the next section to know how to do it.

day-mode Bookmark

The application layer is the starting point of the performance improvement journey. As we have complete control of the application code, we can change it without depending on anyone else. Thus, there is no better way to start the performance optimization process than working independently.

What can we change in the application layer?

Section titled “What can we change in the application layer?”

You may wonder how we can modify the code to improve performance. Well, we can reduce model complexity, increase the batch size to optimize memory usage, compile the model to fuse operations and disable profiling functions to eliminate extra overhead in the training process.

Regardless of the changes applied to the application layer, we cannot sacrifice model accuracy in favor of performance improvement since this does not make sense. As the primary goal of a neural network is to solve problems, it would be meaningless to accelerate the building process of a useless model. Then, we must pay attention to model quality when modifying the code to reduce the training phase time.

In Figure 2*.7*, we can see the sort of changes we can make in the application layer to speed up the training phase:

Figure 2.7 – Changes in the application layer to accelerate the training process

Figure 2.7 – Changes in the application layer to accelerate the training process

Let’s look at each of the changes:

  • Change model definition: Modify the neural network architecture to reduce the number of layers, weights, and operations executed on each layer
  • Adjust hyperparameters: Change hyperparameters such as batch size, the number of epochs, and the optimizer
  • Use a framework capability: Take advantage of a framework capability such as kernel fusion, automatic mixed precision, and model compiling
  • Disable unnecessary functions: Get rid of undue burdens such as computing the gradient on the validation phase

Important note

Some framework capabilities rely on making changes in the environment layer, such as installing an additional tool or library or even upgrading the framework version.

Naturally, these categories do not cover all possibilities for performance improvement in the application layer; their purpose is to give you a clear mental model of what we can effectively do to the code to accelerate the training phase.

Let’s see a practical example of performance improvement by changing only the application code. Our guinea pig is the CNN model introduced in the previous chapter, which was used to classify the images of the Fashion-MNIST dataset.

Important note

Details about the computing environment used in this experiment are irrelevant at this time. What truly matters is the speedup achieved with these modifications, considering the same environment and conditions.

This model has two convolutional layers and two fully connected layers, resulting in 1,630,090 weights. With the number of epochs equal to 10 and the batch size equal to 64, the training phase took 148 seconds to complete. The trained model achieved 83.99% accuracy when tested against 10,000 images from the test dataset, as you can see here:

Epoch [1/10], Loss: 0.9136Epoch [2/10], Loss: 0.6925 Epoch [3/10], Loss: 0.7313 Epoch [4/10], Loss: 0.6681 Epoch [5/10], Loss: 0.3191 Epoch [6/10], Loss: 0.5790 Epoch [7/10], Loss: 0.4824 Epoch [8/10], Loss: 0.6229 Epoch [9/10], Loss: 0.7279 Epoch [10/10], Loss: 0.3292 Training time: 148 seconds Accuracy of the network on the 10000 test images: 83.99 %

Important 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/chapter02/baseline.ipynb.

By making only one simple modification to the code, we can reduce the training time of this model by 15% while keeping the same accuracy achieved with the baseline code. The improved code took 125 seconds to complete, and the trained model reached an accuracy equal to 83.76%:

Epoch [1/10], Loss: 1.0960Epoch [2/10], Loss: 0.6656 Epoch [3/10], Loss: 0.6444 Epoch [4/10], Loss: 0.6463 Epoch [5/10], Loss: 0.4772 Epoch [6/10], Loss: 0.5548 Epoch [7/10], Loss: 0.4800 Epoch [8/10], Loss: 0.4190 Epoch [9/10], Loss: 0.4885 Epoch [10/10], Loss: 0.4708 Training time: 125 seconds Accuracy of the network on the 10000 test images: 83.76 %

Important 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/chapter02/application_layer-bias.ipynb.

We improved performance by disabling the bias parameter on the two convolutional and two fully connected layers. The following piece of code shows the use of the bias parameter to disable the bias weight on the function’s Conv2d and Linear layers:

def __init__(self, num_classes=10): super(CNN, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d
(1, 32, kernel_size=3, stride=1,padding=1, bias=False),
nn.ReLU(),
nn.MaxPool2d(kernel_size = 2, stride = 2))
self.layer2 = nn.Sequential(
nn.Conv2d
(32, 64, kernel_size=3,stride=1,padding=1, bias=False),
nn.ReLU(),
nn.MaxPool2d(kernel_size = 2, stride = 2))
self.fc1 = nn.Linear(64*7*7, 512, bias=False)
self.fc2 = nn.Linear(512, num_classes, bias=False)

This modification reduced the number of weights from 1,630,090 to 1,629,472, representing a decrease of only 0.04% in the total number of neural network weights. As we can see, this change in the number of weights did not affect the model’s accuracy since it achieved practically the same efficiency as before. Therefore, we trained the model 15% faster with almost no additional effort.

If we double the batch size from 64 to 128, we achieve an even better performance gain than disabling the bias:

Epoch [1/10], Loss: 1.1859Epoch [2/10], Loss: 0.7575 Epoch [3/10], Loss: 0.6956 Epoch [4/10], Loss: 0.6296 Epoch [5/10], Loss: 0.6997 Epoch [6/10], Loss: 0.5369 Epoch [7/10], Loss: 0.5247 Epoch [8/10], Loss: 0.5866 Epoch [9/10], Loss: 0.4931 Epoch [10/10], Loss: 0.4058 Training time: 96 seconds Accuracy of the network on the 10000 test images: 82.14 %

Important 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/chapter02/application_layer-batchsize.ipynb.

We trained the model 54% faster by doubling the batch size. As we learned in Chapter 1, Deconstructing the Training Process, the batch size dictates the number of steps in the training phase. Because we increased the batch size from 64 to 128, we obtained a fewer number of steps per epoch, i.e., the number of steps passed from 938 to 469. As a consequence, the learning algorithm executes half of the phases needed to complete an epoch.

However, such modification came with a price: the accuracy was reduced from 83.99% to 82.14%. This happens because the learning algorithm executes the optimization phase per each training step. Since the number of steps reduced and the number of epochs remained the same, the learning algorithm executed a fewer number of optimization phases, which consequently decreases its opportunity to reduce the training cost.

Just out of curiosity, let’s see what happens when changing the batch size to 256:

Epoch [1/10], Loss: 1.5919Epoch [2/10], Loss: 0.9232 Epoch [3/10], Loss: 0.8151 Epoch [4/10], Loss: 0.6488 Epoch [5/10], Loss: 0.7208 Epoch [6/10], Loss: 0.5085 Epoch [7/10], Loss: 0.5984 Epoch [8/10], Loss: 0.5603 Epoch [9/10], Loss: 0.6575 Epoch [10/10], Loss: 0.4694 Training time: 76 seconds Accuracy of the network on the 10000 test images: 80.01 %

The training time was reduced even more, though not as significantly as when we changed from 64 to 128. On the other hand, the model efficiency fell to 80%. We can also observe an increase in the loss per epoch when compared to the previous test.

In short, we have to find the balance between training speedup and model efficiency when adjusting the batch size. The ideal batch size value depends on the model architecture, dataset characteristics, and the hardware resource used to train the model. Thus, the best way to define it is by doing some experiments before starting the training process for real.

These simple examples showed is possible to accelerate the training process by making direct modifications to the code. In the next section, we will see what kind of changes we can make in the environment layer to speed up model training.

day-mode Bookmark

The environment layer comprises the machine learning framework and all the software needed to support its execution, such as libraries, compilers, and auxiliary tools.

What can we change in the environment layer?

Section titled “What can we change in the environment layer?”

As we discussed before, we may not have the necessary permission to change anything in the environment layer. This restriction depends on the type of environment we use to train the model. In third-party environments, such as notebook’s online services, we do not have the flexibility to make advanced configurations, such as downloading, compiling, and installing a specialized library. We can upgrade a package or install a new library, but nothing beyond that.

To overcome this restriction, we commonly use containers. Containers allow us to configure anything we need to run our application without requiring the support or permission of everyone else. Obviously, we are talking about the environment layer and not about the execution layer. As we discussed previously, making changes to the execution layer requires administrative privileges, which would be out of our hands in most environments we usually use.

Important 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/chapter02/environment_layer.ipynb.

In the case of the environment layer, we can modify these sorts of things:

  • Install and use a specialized library: The machine learning framework comes with everything we need to train a model. However, we can speed up the training process by using libraries specialized in tasks such as memory allocation, math operations, and collective communication.
  • Control libraries’ behavior through environment variables: The default behavior of libraries cannot be the best one for a given scenario or specific setup. In that case, we can change it directly through environment variables from the application code.
  • Upgrade framework and libraries to new versions: This may sound silly, but upgrading the machine learning framework and libraries to new versions can raise the performance of the training process much more than we think.

We are going to learn many of these things throughout this book. For now, let’s jump to the next section to see performance improvement in practice.

As we did in the last section, we will use the baseline code here to assess the performance gain from modifying the environment layer. Remember that the training process of our baseline code took 148 seconds to run. The environment layer used for that execution is composed of PyTorch 2.0 (2.0.0+cpu) as the machine learning framework.

After making two modifications to the environment layer, we got a performance improvement near 40%, with the model’s accuracy being practically the same as before, as you can see:

Epoch [1/10], Loss: 0.6036Epoch [2/10], Loss: 0.3941 Epoch [3/10], Loss: 0.4808 Epoch [4/10], Loss: 0.5834 Epoch [5/10], Loss: 0.6347 Epoch [6/10], Loss: 0.3218 Epoch [7/10], Loss: 0.4646 Epoch [8/10], Loss: 0.4960 Epoch [9/10], Loss: 0.3683 Epoch [10/10], Loss: 0.6173 Training time: 106 seconds Accuracy of the network on the 10000 test images: 83.25 %

We made only one change to accelerate the training process of the baseline model by almost 40%: the installation and configuration of Intel OpenMP version 2023.1.0. We have configured the behavior of this library by setting three environment variables:

import osos.environ['OMP_NUM_THREADS'] = "16"

os.environ[‘KMP_AFFINITY’] = “granularity=fine,compact,1,0” os.environ[‘KMP_BLOCKTIME’] = “0”

In short, these parameters control the way Intel Open launches and orchestrates the threads, besides determining the number of threads created by the library. We should configure these parameters, taking into account the characteristics of the training burden and hardware resources. Notice that setting up these parameters in the code is part of modifying the environment layer and not the application layer. Even though we are changing the code, those modifications are related to environment control rather than model definition.

Important note

Do not worry about how to install and enable the Intel OpenMP library and what each of the environment variables used in this test means. We will cover this topic in detail in Chapter 4, Using Specialized Libraries.

Although the PyTorch package installed from PIP comes with the GNU OpenMP library by default, the Intel version tends to provide better results in machines endowed with Intel CPUs. As the hardware machine used in this test possesses an Intel CPU, it is recommended to use the Intel version of OpenMP instead of the implementation provided by the GNU project.

We can see that changing a few things in the environment layer can result in a relevant performance gain without consuming much time or effort to implement.

The next section provides some questions to help you retain what you have learned in this chapter.

day-mode Bookmark

Let’s review what we have learned in this chapter by answering a few questions. At first, try to answer these questions without consulting the material.

Important note

The answers to all these questions are available at https://github.com/PacktPublishing/Accelerate-Model-Training-with-PyTorch-2.X/blob/main/quiz/chapter02-answers.md.

Before starting the quiz, remember that it is not a test at all! This section aims to complement your learning process by revising and consolidating the content covered in this chapter.

Choose the correct answers for the following questions:

  1. After running the training process using two GPUs in a single machine, we decided to add two extra GPUs to accelerate the training process. In this case, we tried to improve the performance of the training process by applying which of the following?
    1. Horizontal scaling. 2. Vertical scaling. 3. Transversal scaling. 4. Distributed scaling.
  2. The training process of a simple model is taking a long time to finish. After adjusting the batch size and cutting of one of the convolutional layers, we could train the model faster while achieving the same accuracy. In this case, we improve the performance of the training process by changing which of the following layers of the software stack?
    1. Application layer. 2. Hardware layer. 3. Environment layer. 4. Execution layer.
  3. Which of the following changes is applied to the environment layer?
    1. Modify the hyperparameters. 2. Adopt another network architecture. 3. Update the framework’s version. 4. Set a parameter in the operating system.
  4. Which one of the following components lies in the execution layer?
    1. OpenMP. 2. PyTorch. 3. Apptainer. 4. NCCL.
  5. As users of a given environment, we usually do not modify anything at the execution layer. What is the reason for that?
    1. We usually do not have administrative rights to change anything at the execution layer. 2. There is no change at the execution layer that could accelerate the training process. 3. The execution and application layers are almost the same thing. So, there is no difference between changing one or another layer. 4. As we usually execute the training process on containers, there is no change on the execution layer that could improve the training process.
  6. We have accelerated the training process of a given model by using two additional machines and applying a given capability provided by the machine learning framework. In this case, which of the following actions have we taken to improve the training process?
    1. We have performed horizontal and vertical scaling. 2. We have performed horizontal scaling and increased the number of resources. 3. We have performed horizontal scaling and applied changes to the environment layer. 4. We have performed horizontal scaling and applied changes to the execution layer.
  7. Controlling the behavior of a library through environment variables is a change that is applied in which of the following layers?
    1. Application layer. 2. Environment layer. 3. Execution layer. 4. Hardware layer.
  8. Increasing the batch size can improve the performance of the training process. However, it can also present which of the following side effects?
    1. Reduce the number of samples. 2. Reduce the number of operations. 3. Reduce the number of training steps. 4. Reduce model accuracy.

Let’s summarize what we’ve covered in this chapter.