Skip to content
ImagineWorld

Compiling the Model

node_idnode-book_accelerate-model-training-with-pytorch_chapter-03-compiling-the-model
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleCompiling the Model
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

PyTorch 2.0 Compile API — eager vs graph modes, compiling workflow, accelerating model building.

Paraphrasing one of the famous presenters: “It’s time!” After completing our initial steps toward performance improvement, it is time to learn a new capability of PyTorch 2.0 to accelerate the training and inference of deep learning models.

We are talking about the Compile API, which was presented in PyTorch 2.0 as one of the most exciting capabilities of this new version. In this chapter, we will learn how to use this API to build a faster model to optimize the execution of its training phase.

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

  • The benefits of graph mode over eager mode
  • How to use the API to compile a model
  • The components, workflow, and backends used by the API

day-mode Bookmark

You can find the complete code for the examples mentioned in this chapter in this book’s GitHub repository at https://github.com/PacktPublishing/Accelerate-Model-Training-with-PyTorch-2.X/blob/main.

You can access your favorite environment to execute this notebook, such as Google Collab or Kaggle.

day-mode Bookmark

As a programmer, you will immediately assign the term “compiling” to the process of building a program or application from the source code. Although the complete building process comprises additional phases, such as generating assembly code and linking it to libraries and other objects, it is reasonable to think that way. However, at first glance, it may be a bit confusing to think about the compiling process in the context of this book since we are talking about Python. After all, Python is not a compiled language; it is an interpreted language, and thus, no compiling is involved.

Note

It is important to clarify that Python uses compiled functions for performance purposes, though it is primarily an interpreted language.

That said, what is the meaning of compiling a model? Before answering this question, we must understand the two execution modes of machine learning frameworks. Follow me to the next section.

Essentially, machine learning frameworks have two distinct execution modes. In eager mode, each operation is executed as it appears in the code, which is exactly what we expect to see in an interpreted language. The interpreter – Python, in this case – executes the operation as soon as it comes to light. So, there is no evaluation of what comes next when the operation is executed:

Figure 3.1 – Eager execution mode

Figure 3.1 – Eager execution mode

As shown in Figure 3*.1*, the interpreter executes the three operations one after another in instants of t1, t2, and t3. The term “eager” stands for doing things instantly without taking a breath to evaluate the whole scenario before making the next step.

Besides eager mode, there is another approach named graph mode, which is similar to the traditional compiling process. Graph mode evaluates the complete set of operations to seek optimization opportunities. To perform this process, the program must evaluate the task as a whole, as shown in Figure 3*.2*:

Figure 3.2 – Graph execution mode

Figure 3.2 – Graph execution mode

Figure 3*.2* shows the program uses t1 and t2 to execute the compiling process instead of eagerly running operations, as done before. The set of operations is executed only at t3 when the compiled code is executed.

The term “graph” refers to the directed graph created by this execution mode to represent operations and operands of a task. As this graph represents the processing flow of the task, the execution mode evaluates this representation to find ways to fuse, condense, and optimize operations.

For example, consider the case illustrated in Figure 3*.3*, which represents a task comprised of three operations. Op1 and Op2 receive operands I1 and I2, respectively. The results of these computations are used as input to Op3. Here, Op3 takes these two operands and, together with operand I3, outputs a result of O1:

Figure 3.3 – Example of operations represented in a directed graph

Figure 3.3 – Example of operations represented in a directed graph

After evaluating this graph, the program could decide to fuse all three operations in a single compiled code. As shown in Figure 3*.4*, this piece of code receives all three operands and outputs a value of O1:

Figure 3.4 – Example of compiled operations

Figure 3.4 – Example of compiled operations

Besides fusing and reducing operations, the compiled model – the resultant of graph mode – can be created specifically for some hardware architecture to harness all resources and capabilities provided by that device. This is one of the reasons graph mode can perform better than eager mode.

As with everything in life, each mode has advantages and drawbacks. In short, eager mode is simpler to understand and hack, besides not having any delay in starting to run operations. On the other hand, graph mode is much faster to execute, though it is more complex to comprehend and requires extra initial time to create the compiled piece of code.

Now that you’ve been introduced to eager and graph modes, we can go back to the question that was posed at the beginning of this section: what is the meaning of compiling a model?

Compiling a model means changing the execution mode of forward and backward phases from eager to graph mode. In doing this, the machine learning framework evaluates all operations and operands involved in these phases in advance to compile them into a single piece of code. Therefore, notice that when we use the term “compiling a model,” we are referring to compiling the processing flow that’s executed in the forward and backward phases.

But why would we want to do that? We compile a model to accelerate its training time since the compiled code tends to run faster than the code that’s executed in eager mode. As we will see in the next few sections, performance improvement depends on diverse factors, such as the computational capability of the GPU used to train the model.

Remark, however, that performance improvement is not guaranteed for all hardware platforms and models. On many occasions, the performance of graph mode can be the same as eager mode or even worse because of the extra time needed to compile the model. Even so, we should always consider compiling the model to verify the resultant performance improvement, especially when using novel GPU devices.

At this point, you may be wondering what execution mode is supported by PyTorch. The default execution mode of PyTorch is eager mode since it is “easier to use and more suitable for machine learning researchers,” as stated on PyTorch’s website. Nevertheless, PyTorch also supports graph mode! After version 2.0, PyTorch natively supports graph execution mode through the Compile API.

Before this new version, we needed to use third-party tools and libraries to enable graph mode on PyTorch. However, with the launch of the Compile API, we can now easily compile a model. Let’s learn how to use this API to accelerate the training phase of our models.

day-mode Bookmark

We will start learning the basic usage of the Compile API by applying it to our well-known CNN model and Fashion-MNIST dataset. After that, we will accelerate a heavier model that’s used to classify images from the CIFAR-10 dataset.

Instead of describing the API’s components and explaining a bunch of optional parameters, let’s dive into a simple example to show the basic usage of this capability. The following piece of code uses the Compile API to compile the CNN model presented in previous chapters:

model = CNN()graph_model = torch.compile(model)

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/chapter03/cnn-graph_mode.ipynb.

To compile a model, we need to call a function named compile, passing the model as a parameter. Nothing else is necessary for the basic usage of this API. compile returns an object that will be compiled the first time it is called. The rest of the code remains exactly as before.

We can set the following environment variable to see whether the compiling process occurs:

import osos.environ['TORCH_COMPILE_DEBUG'] = "1"

If so, we will see a lot of messages, as shown here:

[INFO] Step 1: torchdynamo start tracing forward[DEBUG] TRACE LOAD_Fself [] [DEBUG] TRACE LOAD_ATTR layer1 [NNModuleVariable()] [DEBUG] TRACE LOAD_Fx [NNModuleVariable()] [DEBUG] TRACE CALL_FUNCTION 1 [NNModuleVariable(), TensorVariable()]

Another way to certify that we compiled the model successfully is by profiling the forward phase by using the PyTorch Profiler API:

from torch.profiler import profile, ProfilerActivityactivities = [ProfilerActivity.CPU]
prof = profile(activities=activities)
input_sample, _ = next(iter(train_loader))
prof.start()
model(input_sample)
prof.stop()
print(prof.key_averages().table(sort_by="self_cpu_time_total",
row_limit=10))

If the model was compiled successfully, the profiling would show a task labeled as CompiledFunction, as shown in the first line of the following output:

CompiledFunction: 55.50%aten::mkldnn_convolution: 30.36% aten::addmm: 8.25% aten::convolution: 1.06% aten::as_strided: 0.63% aten::empty_strided: 0.59% aten::empty: 0.43% aten::expand: 0.27% aten::resolve_conj: 0.20% detach: 0.20% aten::detach: 0.16%

The preceding output shows that CompiledFunction and aten::mkldnn_convolution took almost 86% of the time required to execute the forward phase. If we profile the model when it’s executed in eager mode, we can easily identify which operations were fused and transformed into CompiledFunction:

aten::mkldnn_convolution: 38.87%aten::max_pool2d_with_indices: 27.31% aten::addmm: 17.89% aten::clamp_min: 6.63% aten::convolution: 1.88% aten::relu: 0.87% aten::conv2d: 0.83% aten::reshape: 0.57% aten::empty: 0.52% aten::max_pool2d: 0.52% aten::linear: 0.44% aten::t: 0.44% aten::transpose: 0.31% aten::expand: 0.26% aten::as_strided: 0.13% aten::resolve_conj: 0.00%

By evaluating the profiling output of eager and graph modes, we can see that the compiling process fused nine operations into the CompiledFunction operation, as illustrated in Figure 3*.5*. As shown in this example, there are situations where the compiling process cannot compile all operations involved in the forward phase. This happens due to many reasons, such as data dependence:

Figure 3.5 – A set of operations incorporated in a compiled function

Figure 3.5 – A set of operations incorporated in a compiled function

You may be wondering about performance improvement. After all, this is what we came for! Do you remember what we discussed at the beginning of this chapter about not achieving performance improvement in all situations? Well, this is one of those cases.

Figure 3*.6* shows the execution time of each training epoch of the CNN model running in both eager and graph modes. As we can see, the execution time of all epochs is higher in graph mode than in eager mode. Furthermore, the first epoch of graph mode is significantly slower than the others because the compiling process is executed at that moment:

Figure 3.6 – Execution time of each training epoch of the CNN model in eager and graph modes

Figure 3.6 – Execution time of each training epoch of the CNN model in eager and graph modes

The overall time of model training executed on eager and graph modes was equal to 118 and 140 seconds, respectively. Thus, the compiled model was 18% slower than the default execution mode.

Frustrating, right? Yes, it is. However, remember that our CNN is just a toy model, thus there is not much space to truly improve performance. In addition, these experiments were executed in a non-GPU environment, though the compiling process tends to yield better results on GPU devices.

That said, let’s go to the next section to see a significant performance improvement through the Compile API.

Give me a real fight – training a heavier model!

Section titled “Give me a real fight – training a heavier model!”

To see all the power of this capability in action, we will apply it to a more complex case. Our guinea pig for this is the DenseNet121 model, which will be trained to classify images from the CIFAR-10 dataset. We can easily load and use both the model and the dataset from the torchvision module.

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/chapter03/densenet121_cifar10.ipynb

CIFAR-10 is a classic image classification dataset comprising 60,000 32x32 colored images. These images belong to 10 distinct categories, which explains the suffix “10” in the dataset’s name.

Although each dataset image is 32x32 in size, it is a good practice to resize them to achieve better results on model training. Thus, we resized each image to 224x224 but kept the original three channels to represent the RGB color codification.

We conducted this experiment with the DenseNet121 model by using the following hyperparameters:

  • Batch size: 64
  • Epochs: 50
  • Learning rate: 0.0001
  • Weight decay: 0.005
  • Criterion: Cross entropy
  • Optimizer: Adam

Unlike previous experiments with the CNN model, this test was executed on an environment with the novel Nvidia A100 GPU. This GPU has a compute capability equal to 8.0, satisfying the requirement informed by PyTorch to achieve better results with the Compile API.

Note

Compute capability is a score assigned by NVIDIA to its GPUs. The higher the compute capability, the higher the computing power that GPU provides. PyTorch’s official documentation states that the Compile API yields better results on GPUs with compute capability equal to or higher than 8.0.

The following piece of code shows how to load and enable the DenseNet121 model for training:

from torchvision import modelsdevice = "cuda"
weights = models.DenseNet121_Weights.DEFAULT
net = models.densenet121(weights=weights)
net.to(device)
net.train()

The usage of the Compile API, in this case, is almost the same as before, except for one slight change in the compile line:

model = torch.compile(net, mode="reduce-overhead")

As you can see, we are invoking a different compiling mode than the one used in the previous example. We did not use the “mode” parameter on the CNNxFashion-MNIST case, so the compile function employed the default compiling mode. The compiling mode changes the entire workflow’s behavior, allowing us to adjust the generated code so that it fits a particular scenario or requirement.

Figure 3*.7* shows the three possible compiling modes:

Figure 3.7 – Compiling modes

Figure 3.7 – Compiling modes

Here’s a breakdown:

  • default: A balance between compiling time and model performance. As its name suggests, this is the default compiling mode of the function. This option is likely to provide good results in many cases.
  • reduce-overhead: This is suitable for small batches – which is our present case. This mode reduces the overhead of loading the batch sample to memory and further executes the forward and backward phases on the computing device.
  • max-autotune: The most optimized code possible. The compiler takes all the time it needs to yield the best-optimized code to run on the target machine or device. Consequently, the time required to compile the model is longer than other modes, which can make this option unfeasible in many practical cases. Even so, this mode is still interesting for experimental purposes since we can evaluate and understand which characteristics make this model better than others generated with default and reduce-overhead modes.

After running the training phase of the eager and compiled models, we got the results listed in Table 3.1:

Eager ModelCompiled Model
Overall training time (s)2,2641,443
First epoch execution time (s)47146
Median epoch execution time (s)4526
Accuracy (%)74.2674.38

Table 3.1 – Results of training the eager and compiled models

The results show that we trained the compiled model 57% faster than its eager version. As expected, the first epoch took much more time to execute on the compiled version than eager mode because the compiling process is performed at that instant. On the other hand, the execution time of the remaining epochs falls from 45 to 26 in the median, representing an execution around 1.73 times faster. Notice that we got this performance improvement without sacrificing the model’s quality since both models achieved the same accuracy.

The Compile API accelerated the training phase of the DenseNet121xCIFAR-10 case by almost 60%. But why couldn’t this capability do the same for the CNNxFashion-MNIST example? Essentially, the answer lies in two issues: computational burden and computing resources. Let’s go over each:

  • Computational burden: The DenseNet121 model has 7,978,856 parameters. Compared to the 1,630,090 weights of our CNN model, the former is nearly four times greater than the latter. In addition, the dimension of one resized sample of the CIFAR-10 dataset is equal to 244x244x3, which is significantly higher than the dimension of one Fashion-MNIST sample. As discussed in Chapter 1, Deconstructing the Training Process model complexity talks directly with the computational burden of the training phase. With a high computational burden, we have a more robust opportunity to accelerate the training phase. Otherwise, it is like removing a speck of dust from a shining surface; there is nothing to do.
  • Computing resources: We executed our previous experiment in a CPU environment. However, as stated in PyTorch’s official documentation, the Compile API tends to provide better results when executed in GPU devices endowed with compute capability higher than 8.0. This is precisely what we did in the DenseNet121xCIFAR-10 case – that is, the training process was executed in a GPU Nvidia A100.

In short, the DenseNet121xCIFAR-10 case, when trained with A100, is a perfect match between computational burden and computing resources. Such a good fit is the key to improving performance through the Compile API.

Now that you’re convinced it is a good idea to incorporate this resource in your performance acceleration toolkit, let’s understand how the Compile API works behind the scenes.

day-mode Bookmark

How does the Compile API work under the hood?

Section titled “How does the Compile API work under the hood?”

The Compile API is exactly what its name suggests: it is an entry point to access a set of functionalities PyTorch provides to move from eager to graph execution mode. Besides intermediary components and processes, we also have the compiler, which is an entity that’s responsible for getting the final work done. There are half a dozen compilers available, each one specialized in generating optimized code for a given architecture or device.

The following sections describe the steps that are involved in the compiling process and the components that make all this possible.

At this point, we can imagine that the compiling process is much more complex than calling a single line in our code. To transform an eager model into a compiled model, the Compile API executes three steps, namely graph acquisition, graph lowering, and graph compilation, as depicted in Figure 3*.8*:

Figure 3.8 – Compiling workflow

Figure 3.8 – Compiling workflow

Let’s discuss each step:

  1. Graph acquisition: The first step of the compiling workflow, graph acquisition is responsible for capturing model definition and transforming it into a representative graph of primitive operations that are executed on forward and backward phases.
  2. Graph lowering: With the graph representation at hand, it is time to simplify and optimize the process by fusing, combining, and reducing operations. The simpler the graph is, the lower the time to execute it.
  3. Graph compilation: The last step consists of generating code for a given target device, such as the CPUs and GPUs of different vendors and architectures, or even for another kind of device, such as a tensor processing unit (TPU).

PyTorch relies on two main components to execute these steps. TorchDynamo executes graph acquisition, whereas the backend compiler does graph lowering and compilation, as shown in Figure 3*.9*:

Figure 3.9 – Components of a compiling workflow

Figure 3.9 – Components of a compiling workflow

TorchDynamo performs graph acquisition by using a new functionality implemented in CPython. This capability is called the Frame Evaluation API and is defined on the PEP 523. In short, TorchDynamo captures Python bytecode right before its execution to create a graph representation of operations that are executed by that function or model.

Note

PEP stands for Python Enhancement Proposal. This document informs the Python community about new features, relevant changes, and general guidance for writing Python code.

After that, TorchDynamo calls the compiler backend, which is the component that’s responsible for effectively transforming the graph into a piece of code that can run on the hardware platform. The compiler backend executes the graph lowering and graph compilation steps of the compiling workflow. We’ll cover this component in more detail in the next subsection.

There is a half-dozen backend compilers available to use with the Compile API. The default backend compiler of PyTorch is TorchInductor, which generates optimized code for the CPU and GPU through the OpenMP framework and Triton compiler, respectively.

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/chapter03/backends.ipynb

To specify the compiler backend, we must set the parameter backend in the torch.compile function. If that parameter is suppressed, the Compile API will use TorchInductor. The following line selects cudagraphs as the compiler backend:

model = torch.compile(net, backend="cudagraphs")

We can easily discover the supported backends of a given environment by running the following command:

torch._dynamo.list_backends()# available backends [‘aot_ts_nvfuser’, ‘cudagraphs’, ‘inductor’, ‘ipex’, ‘nvprims_nvfuser’, ‘onnxrt’, ‘tvm’]

This list shows seven available backends in the environment that’s used in our experiments. Remark that backends returned by list_backends(), though supported by the current PyTorch installation, are not necessarily ready to be used. This happens because some backends could require additional modules, packages, and libraries to execute.

Of the seven backends available in our environment, only three of them were promptly able to run. Table 3.2 shows the results that were achieved when we tested the DenseNet121xCIFAR-10 case and compiled it with aot_ts_nvfuser, cudagraphs, and inductor:

aot_ts_nvfusercudagraphsinductor
Overall training time (s)2,4742,2901,407
First epoch execution time (s)14286140
Median epoch execution time (s)464425
Accuracy (%)74.6877.5779.90

Table 3.2 – Results of the different backend compilers

The results show that TorchInductor overcame other backends since it executed the training phase 63% faster. Although TorchInductor presented the best result for this case and scenario, it is always interesting to test all the backends that are available in the environment. Furthermore, some backends, such as onnxrt and tvm, specialize in generating models that are suitable for inference.

The next section provides a couple of 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. 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/chapter03-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:

  1. Which are the two execution modes of PyTorch?
    1. Horizontal and vertical modes. 2. Eager and graph modes. 3. Eager and distributed modes. 4. Eager and auto modes.
  2. In which execution mode does PyTorch execute operations as soon as they appear in the code?
    1. Graph mode. 2. Eager mode. 3. Distributed mode. 4. Auto mode.
  3. In which execution mode does PyTorch evaluate the complete set of operations seeking optimization opportunities?
    1. Graph mode. 2. Eager mode. 3. Distributed mode. 4. Auto mode.
  4. Compiling a model with PyTorch means changing from eager to graph mode when executing in which of the following phases of the training process?
    1. Forward and optimization. 2. Forward and loss calculation. 3. Forward and backward. 4. Forward and training.
  5. Concerning the time to execute the first training epoch in both eager and graph modes, what can we assert?
    1. The time to execute the first training epoch is always the same in both eager and graph modes. 2. The time to execute the first training epoch in graph mode is always smaller than executing in the eager mode. 3. The time to execute the first training epoch in graph mode is likely to be higher than executing in the eager mode. 4. The time to execute the first training epoch in eager mode is likely to be higher than executing in the eager mode.
  6. Which phases comprise the compiling workflow that’s executed by the Compile API?
    1. Graph forward, graph backward, and graph compilation. 2. Graph acquisition, graph backward, and graph compilation. 3. Graph acquisition, graph lowering, and graph optimization. 4. Graph acquisition, graph lowering, and graph compilation.
  7. TorchDynamo is a component of the Compile API that executes which phase?
    1. Graph backward. 2. Graph acquisition. 3. Graph lowering. 4. Graph optimization.
  8. TorchInductor is the default compiler backend of PyTorch’s Compile API. Which are the other compiler backends?
    1. OpenMP and NCCL. 2. OpenMP and Triton. 3. Cudagraphs and IPEX. 4. TorchDynamo and Cudagraphs.

Now, let’s summarize the key takeaways from this chapter.