Computational performance analysis of Deep Learning using high resolution images with variable shapes
Abstract
En este estudio analizo el proceso de entrenamiento de una red neural convolucional desde la perspectiva del rendimiento computacional. Mediante el uso de herramientas de instrumentación y métricas de eficiencia, voy a mostrar cómo se comporta este programa en un entorno de alta capacidad computacional usando distintos conjuntos de datos. Además, mostraré varios test de rendimiento relacionados con la escalabilidad de recursos y un estudio sobre cómo algunos parámetros de ejecución alteran los resultados.
Full text
Universitat Politècnica de Catalunya Facultat d’Informàtica de Barcelona Bachelor Degree in Informatics Engineering Computer Engineering Specialization Degree Final Project Computational Performance Analysis of Deep Learning using High Resolution Images with Variable Shapes Author Pedro Megias Montesinos Director Marta Garcia Gasulla Co-director Ferran Parés Pont Tutor Julián David Morillo Pozo GEP Tutor Paola Lorenza Pinto
Contents 1 Project Management 1 1.1 Context and scope of the project . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1.1 Context..................................... 1 1.1.2 Motivation ................................... 3 1.1.3 Scope ...................................... 4 1.1.4 Methodology .................................. 5 1.2 Timeplanning ..................................... 6 1.2.1 Taskdescription ................................ 6 1.2.2 Resources and requirements . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.2.3 Riskmanagement ............................... 8 1.2.4 Ganttdiagram ................................. 9 1.3 Budget and sustainability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.3.1 Budget ..................................... 10 1.3.2 Sustainability report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2 Background 13 2.1 Deep Learning and Convolutional Neural Networks . . . . . . . . . . . . . . . . . 13 2.2 ResNetmodel...................................... 15 2.3 PyTorchFramework .................................. 16 2.4 From Low resolution to High resolution . . . . . . . . . . . . . . . . . . . . . . . 16 2.5 POP methodology and Efficiency metrics . . . . . . . . . . . . . . . . . . . . . . 17 3 Implementation 19 3.1 Methodology ...................................... 19 3.2 Setup .......................................... 19 3.3 Instrumentation..................................... 24 3.4 Programstructure ................................... 25 4 Analysis of size and shape 26 4.1 Timestudy ....................................... 26 4.2 Pixelstudy ....................................... 28 5 Detailed analysis per phase 29 5.1 Batchloading...................................... 29 5.2 Forwardpropagation.................................. 32 5.3 Backwardpropagation................................. 35 5.4 Optimization ...................................... 37
6 Core scaling study 38 7 Hyperparameters study 42 7.1 Batchsize........................................ 42 7.2 Grainsize........................................ 45 7.3 Accuracytests ..................................... 48 8 Conclusions 50 8.1 Projectconclusions................................... 50 8.2 PersonalConclusions.................................. 51 9 References 52
List of Figures 1 Sample Paraver IPC Timeline. Own creation. . . . . . . . . . . . . . . . . . . . . 3 2 Sample Paraver IPC Histogram. Own creation. . . . . . . . . . . . . . . . . . . . 3 3 Project Gantt diagram. Own creation. . . . . . . . . . . . . . . . . . . . . . . . . 9 4 Deep Neural Network scheme from IBM [1]. . . . . . . . . . . . . . . . . . . . . . 13 5 Batch dimension changes through forward phase. From [2]. . . . . . . . . . . . . 14 6 Training step box diagram. Own creation. . . . . . . . . . . . . . . . . . . . . . . 14 7 Convolution filter over image pixels. Own creation. . . . . . . . . . . . . . . . . . 15 8 Resnet-18 layer connexion diagram. From [2] . . . . . . . . . . . . . . . . . . . . 16 9 Datasets image comparison. Own creation. . . . . . . . . . . . . . . . . . . . . . 17 10 POP methodology scheme from [3] . . . . . . . . . . . . . . . . . . . . . . . . . . 18 11 POP metrics relation from [3] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 12 Full step phase dissemination. Own creation. . . . . . . . . . . . . . . . . . . . . 26 13 Informative megapixel execution times. Own creation. . . . . . . . . . . . . . . . 27 14 Batch megapixel execution times. Own creation. . . . . . . . . . . . . . . . . . . 28 15 Full epoch pixel count comparison. Own creation. . . . . . . . . . . . . . . . . . 28 16 Theoretical batch representation with two images with different aspect ratios. Owncreation....................................... 29 17 Batch size value effects. Own creation. . . . . . . . . . . . . . . . . . . . . . . . . 30 18 Batch loading columns matching batch size value. Own creation. . . . . . . . . . 30 19 Batch loading datasets parallelism comparison. Own creation. . . . . . . . . . . . 31 20 Batch loading metrics comparison. Own creation. . . . . . . . . . . . . . . . . . . 31 21 Pixel count comparison in the test step. Own creation. . . . . . . . . . . . . . . . 32 22 IPC and layers views on Forward propagation. Own creation. . . . . . . . . . . . 32 23 Convolution and select operations. Own creation. . . . . . . . . . . . . . . . . . . 33 24 HRVS and MRVS forward phases comparison. Own creation. . . . . . . . . . . . 34 25 LRFS and MRVS maxpool layer IPC comparison. Same semantic scale. Own creation.......................................... 34 26 Forward phase metrics comparison. Own creation. . . . . . . . . . . . . . . . . . 35 27 LRFS backward phase. Own creation. . . . . . . . . . . . . . . . . . . . . . . . . 36 28 MRVS and HRVS backward phases. Same semantic scale. Own creation. . . . . . 36 29 Backward phase metrics comparison. Own creation. . . . . . . . . . . . . . . . . 36 30 LRFS and HRVS optimization phase comparison. Own creation. . . . . . . . . . 37 31 Core scaling metrics with LRFS dataset. Own creation. . . . . . . . . . . . . . . 38 32 4 and 24 cores phases duration comparison. Own creation. . . . . . . . . . . . . . 38 33 4 and 24 cores full step IPC comparison. Own creation. . . . . . . . . . . . . . . 39 34 4 and 24 cores image loading comparison . Own creation. . . . . . . . . . . . . . 39
35 Core scaling metrics with MRVS dataset. Own creation. . . . . . . . . . . . . . . 40 36 16 and 24 cores batch loading with MRVS dataset. Own creation. . . . . . . . . 40 37 Core scaling metrics with HRVS dataset. Own creation. . . . . . . . . . . . . . . 41 38 8 and 24 cores step comparison with HRVS dataset. Own creation. . . . . . . . . 41 39 Batch size scaling with LRFS dataset. Own creation. . . . . . . . . . . . . . . . . 42 40 LRFS cycles comparison with different batch sizes. Own creation. . . . . . . . . . 43 41 Batch size scaling with MRVS dataset. Own creation. . . . . . . . . . . . . . . . 43 42 Batch size scaling with HRVS dataset. Own creation. . . . . . . . . . . . . . . . 44 43 HRVS batch size traces comparison. Up: batch size=1, Down: batch size=2. Owncreation....................................... 44 44 HRVS(up) & LRFS (down) training phase comparison. Own creation. . . . . . . 45 45 HRVS (up) & LRFS (down) training phase IPC comparison. Own creation. . . . 45 46 Grain size value comparison in all datasets. Own creation. . . . . . . . . . . . . . 46 47 GrainSize effects on Batch loading phase with LRFS. Own creation. . . . . . . . 46 48 GrainSize metrics using LRFS dataset. Own creation. . . . . . . . . . . . . . . . 47 49 GrainSize metrics using MRVS dataset. Own creation. . . . . . . . . . . . . . . . 47 50 GrainSize metrics using HRVS dataset. Own creation. . . . . . . . . . . . . . . . 47 51 Accuracy comparison plot. Own creation. . . . . . . . . . . . . . . . . . . . . . . 48 52 Accuracy comparison table. Own creation. . . . . . . . . . . . . . . . . . . . . . . 49 53 Accuracy plot with Learning Rate variances. Own creation. . . . . . . . . . . . . 49 List of Tables 1 Task summary and dependencies. Own creation. . . . . . . . . . . . . . . . . . . 8 2 Node components list. Own creation. . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Material costs summary. Own creation. . . . . . . . . . . . . . . . . . . . . . . . 10 4 Human costs summary. Own creation. . . . . . . . . . . . . . . . . . . . . . . . . 11 5 Project budget summary. Own creation. . . . . . . . . . . . . . . . . . . . . . . . 11 6 Electric consumtion in executions. Own creation. . . . . . . . . . . . . . . . . . . 11 7 List of Python required modules. Own creation. . . . . . . . . . . . . . . . . . . 20 8 Batch Sizes and steps summary. Own creation. . . . . . . . . . . . . . . . . . . . 27
1 Project Management 1.1 Context and scope of the project 1.1.1 Context Introduction Nowadays, Artificial Intelligence (AI), is becoming a huge study field in computer science, particularly through Deep Neural Networks (DNN), and it is being applied in different daily life spheres, such as medical diagnosis [4,5], autonomous driving [6,7] or satellite data analysis [8]. Some of these fields face similar problems, like object recognition and classification, which could be considered a critical task when looking into, for example, autonomous driving. In fact, image classification is a task commonly performed by Convolutional Neural Networks (CNN), by training a model to understand what we are looking for. Usually, training is done with squared and low resolution images to speed up the process, but this practice entails deformation of visual patterns and generalizes information loss. In this project we want to study a specific CNN called ResNet [2], executing in a High Performance Computing (HPC) environment, using the MAMe [9,10] dataset, which contains images of high resolution and variable shape, to analyse the needs and outcomes of using this kind of data. This project is under an Educational Cooperation Agreement between The Facultat d’Informàtica de Barcelona and the Barcelona Supercomputing Center (BSC) and has been developed in collaboration with the Best Practices for Performance and Programmability (BePPP) group. Terms and concepts High Performance Computing High Performance Computing (HPC) refers to the aggregation of compute power to perform massive and complex computations. This term is commonly associated with supercomputers. Supercomputer A supercomputer is a machine assembled with many computers interconnected to allow performing operations that, otherwise, could not be feasible or may take too much time. MareNostrum4 MareNostrum 4 [11], or MN4, is a supercomputer managed by the Barcelona Supercomputing Center and it is divided in two blocks: general purpose block, which represents the bigger portion of computing power; and the emergent technologies block, which aims to test new technologies. The general purpose block contains 3456 nodes, which contain 2 Intel Xeon 8160 CPUs per node. These CPUs are equipped with 24 cores that run at 2.1 GHz. Also, nodes are interconnected with an Omni-Path full-tree at 100 Gbps. Machine Learning Machine learning represents a branch of the artificial intelligence focused in the usage of data and algorithms to emulate the way we learn as humans. This concept is a subset of all the AI applications and gives birth to the concept of Neural Networks. 1
Neural Network Neural Networks are inspired in human brain cells by trying to simulate their behaviour with mathematical approaches. Basically, a neural network is comprised of four main components: inputs, weights, bias and output. These programs are structured with interconnected layers that can adapt themselves based on the information that flows through the network. Large networks with more layers are also called Deep Neural Networks (DNN) due to their complexity. In this project we are using a kind of DNN which relies on using the convolution operation, Convolutional Neural Networks (CNN), which excel at object recognition in image data. MAMe dataset MAMe [9,10] is an image classification dataset that contains thousands of artworks from three different museums, becoming a huge data pool with high resolution images. This dataset has been created to provide a tool for studying the impact of high resolution and variable shape properties in the image classification field, and also to train CNN models in material recognition. PyTorch PyTorch is an open source machine learning framework specialized in tensor modeling networks, created by Facebook’s AI research lab. It is based on the Torch library and many Deep Learning softwares are built on top of it, like Tesla Autopilot or Uber’s Pyro [12]. Hyperparameter This term is used by AI developers just to highlight that a particular parameter of the execution is used to control the learning process. With this naming scheme, we can differentiate between parameters that have a direct impact on the model’s behaviour from an AI perspective. OpenMP Open Multi-Processing [13], or OpenMP, is an application programming interface that allows the user to create shared-memory multiprocessing software. Consists on a set of compiler directives, library routines and environment variables that affect run-time behaviour. Performance Analysis Performance Analysis refers to the process of gathering data from the application executions, study this data and identify possible bottlenecks that may impact its performance. As this project is a collaboration with the Best Practices for Performance and Programmability group (BePPP) and the Performance Optimization and Productivity (POP) center of excellence, we will follow their methodology. BSC tools In order to do a performance analysis of an execution, we need some data extraction, processing and visualization tools [14]. The main BSC tools we are going to use are: •Extrae: This tool is responsible of gathering all the needed data from the execution. Extrae allows us to trace events as OpenMP calls, gather hardware counter values and create custom events at code level. •Basic Analysis: Is an aggregation of scripts which use existing tools to automatically compute the POP methodology metrics. •Paraver: This tool is a desktop application that allows us to load traces generated by Extrae and to visually study them. The most common views of the traces are histograms and timelines. 2
Figure 1shows an example timeline representing the Instructions Per Cycle (IPC) of threads during the execution, by representing time in the X axis and assigning a row to each thread. With this view we can spot where the IPC of any thread is high or low by its code color and allows us to analyse the behaviour of the code in certain regions. Also, when no color is displayed, means that this thread was not created yet or it does not have any computation to do in the application scope. Figure 1: Sample Paraver IPC Timeline. Own creation. When looking at Figure 2we can see a histogram representing the same metric, IPC. The first row shows a gradient color that represents the IPC value from 0 to the maximum value found. Each other row represents a thread and colors in these rows represent the amount of time this thread has been running with this specific IPC value. Figure 2: Sample Paraver IPC Histogram. Own creation. 1.1.2 Motivation A common practice when training DNN models for image-related tasks is to down-sample images before computations, which is the process of reducing their size to a set amount of pixels and changing their aspect ratio to a squared one. This is typically done to reduce the memory requirements and training time of the model, but comes with a huge drawback, deformation of visual patterns. Many applications are not particularly affected by these deformations because they do not rely on details of the input, as for example telling cats from dogs, but in other domains images are naturally of high-resolution and variable shape and down-sampling could entail significant prediction performance reductions. 3
High-resolution data entails large memory requirements, which limits the amount of images that can be processed together, or in the same batch, and batch size limitations have a significant effect on the efficiency of computation. Currently used accelerators, as Graphics Processing Units (GPU), are rather limited in terms of memory capacity, although workarounds to load larger memories than the one offered by the device have already been proposed, such as model parallelism [15,16], activations re-computation [17] and offloading [18], enabling greater memory loads at the cost of computation efficiency. In this high memory load context we want to avoid accelerators and rather use CPU devices as an alternative. The two main reasons in favour of CPUs are the lack of added components and functionalities for their execution and the access to large memory devices, enabling larger, and therefore more efficient, batch sizes. Variable shape is challenging to deal with in the context of batch training. All images in a batch need to have the exact same shape to be computed, and when our data is of variable shape the easiest way to achieve a uniform one without deformation or loss of information is through padding. Padding is a technique used to extend the size of an image by adding fixedvalued pixels, in our case zeros, to fill the gaps between images of different shape found in the same batch. However, padding generates three main problems [19]. First, it introduces noise in form of non-informative pixels, which can affect the learning process. Second, it increases the computational cost of the task, as padding pixels are also computed by the CNN. And third, padding increases the memory requirements of the task, as these values still need to be kept in memory. Additionally, applying random batching in a variable shape context may result in landscape and portrait images being batched together, entailing huge amounts of padding, to the point where more padding than informative pixels may be present in the batch. Although AI practitioners tend to measure model performance taking into account the elapsed execution time and the model prediction accuracy, we want to study how these different inputs affect computational performance in terms of instruction count, frequency and parallel efficiency among others. With this, we may be able to find run-time configurations that achieve a good AI perspective performance while improving program efficiency in the hardware level. 1.1.3 Scope In this section you will find a description of the objectives of the project and the identification of the possible risks. Objectives This project has three main objectives: • Highlight differences between low resolution and high resolution datasets in terms of computational performance and behaviour. • Identify computational challenges and bottlenecks derived from high resolution data processing. 4
Human costs Type Price per hour Total hours Total price Main developer 9€ 550 4.950€ Supervisor 33€ 80 2.640€ Total - - 7.590€ Table 4: Human costs summary. Own creation. Project budget Source Value Human costs 7.590,00€ Material costs 447,01€ Contingencies 1.607,40€ Total 9.644,41€ Table 5: Project budget summary. Own creation. 1.3.2 Sustainability report Environmental dimension •Have you estimated the environmental impact of the project development? We have not quantified the environmental impact of this project but it could be related to the amount of electricity consumed by the project development. About this matter, measuring some executions we have built Table 6which considers a 5 hour execution and the power consumed during the computation approximately. An estimation of its cost has been included, but electricity price can vary at light speed levels these days. Electric consumption in executions Power (W) 350 Execution time (h) 5 Consumtion (kwh) 1,75 Price (€/kwh) 0,6 Execution cost (€) 1,05 Table 6: Electric consumtion in executions. Own creation. •If you did this project again, could you do it with less resources? I could probaly avoid some mistakes made when launching executions, which led to repeating some of them. Apart from that, all used resources were needed in order to produce enough data and avoid execution noise. •Which resources do you think will be used during this project’s lifespan? It depends on how many AI developers use our guidelines. If they use this project as a starting point, their resource usage could be lower during their own development. •Does this project allow to reduce other resources usage? Will your project improve or worsen the global environmental footprint? 11
As said, if an AI developer uses this project as a guideline, their resource usage can be lowered, so their footprint will be smaller also. •Does exist any scenario where the environmental footprint of this project gets bigger? This project’s environmental footprint will only increase if more research is performed. As mentioned in different sections, main memory constraints have lowered the amount of tests we are able to perform. If this constraint is removed, more analysis can be performed and, therefore, increase our footprint. Economic dimension •Have you estimated the project cost? Which decision have you made to reduce this cost? This has been addressed in Budget 1.3.1 section above and the electricity costs can be found in Table 6. To further reduce costs, we have used free software during the whole development. •Is the final cost adjusted to the original budget? The initial budget was calculated taking into account possible execution flaws or errors and no more than this amount has been spent. •Does exist any scenario where the project viability is affected? Given the nature of CNNs and Deep Learning, our project’s analysis only matter when using this specific ResNet model. Any scenario that uses a different model (even if based in our ResNet version) could produce different behaviour outcomes. Social dimension •Has this project development implied meaningful thoughts at a personal, professional or ethical level? The whole AI field is drowned in ethical discussions nowadays. Deep learning models are giving us the opportunity to create programs with basic but powerful features, like seeing and distinguishing different materials (as our ResNet does). This has brought some funny discussions at a personal level, as a lot of people that doesn’t belong to the computer sciences field isn’t aware of the things that neural networks are capable of doing, sometimes even thinking these are all lies. •Who can benefit of this project? Is there any group that can be harmed by your project? How much? Lots of AI practitioneers could have some benefit by taking a look into this project, some hardware awareness can’t be bad. Also, I don’t really think that any harm can be done to any group with this study. 12
2 Background 2.1 Deep Learning and Convolutional Neural Networks Deep Learning (DL) is a subgroup of Machine Learning, which is indeed a subgroup in AI field. DL takes a step further creating complex hierarchical models to simulate the way humans learn with new information. In this specific group, algorithms are inspired in our brain structure and are known as Neural Networks. Figure 4: Deep Neural Network scheme from IBM [1]. Training and using these networks is time consuming and needs huge amounts of data to be able to test and polish the models. Although neural networks exist since the 50s, only a few years ago we have acquired the computational power and storage capacity needed to use this kind of software and design useful applications. Convolutional Neural Networks, or CNNs, are a sub-type of neural networks based on deep learning modeling which excel in image processing tasks such as object recognition. The process of training a CNN begins with the input preparation. To feed the network we have to create a squared structure called batch, which will be filled with images from the dataset during the first phase of the execution. Also, the amount of images that compose a batch can be adjusted at the beggining of the process, modifying the batch size hyperparameter. After creating a batch, forward phase starts. During forward, the batch is processed in different ways while traversing all the layers in the network. While passing through convolutional layers, batch dimensions are altered as a result of being processed by convolution operations. An example of this dimension change is shown in Figure 5. At the end of this phase, the model will output a set of predictions extracted from the images in the batch, which can be used to know the overall precision of the network, or accuracy. 13
Figure 5: Batch dimension changes through forward phase. From [2]. When forward phase finishes, in order to improve the results of the predictions, backward phase begins. This phase will traverse again all the layers, but in reverse order, to propagate the learnt properties through the network and improve precision during following training steps. These properties are condensed in a variable called gradient, and this phase will register the according gradient value to each of the layers. Once all gradients are calculated and registered in the different layers, the optimization phase begins, which consists on applying the gradients to the layers weight. When applied, this will modify the probabilities of being activated during the next forward phase, to effectively apply knowledge to the network and improve predictions. Figure 6: Training step box diagram. Own creation. Completing the computation of the whole dataset is called an epoch, and could require more than one batch due to the amount of images in the dataset. Therefore this training must be split into several training steps, each one of them processing one batch at a time, until finishing all images in the dataset. A box diagram of the training process cicle can be seen in Figure 6. Also, results may not be accurate enough after a full training epoch, requiring to compute more epochs in sequence to allow the model to further improve its precision. CNN models are based on the mentioned convolution operations, or convolutional layers, that transform two functions into a third that, in some sense, represents the magnitude by which the first and a translated and inverted version of the second overlap. In essence, a convolution consists in using a matrix called filter or kernel. A representation can be seen in Figure 7. For each pixel in the image, we have to center the kernel on it and calculate its value using all surrounding pixels. This process is repeated for each pixel in the image and the kernel will move from left to right and top to bottom. 14
Figure 7: Convolution filter over image pixels. Own creation. 2.2 ResNet model ResNet stands for Residual Neural Network [2]. It is a specific kind of neural network developed for image recognition. To solve complex problems, AI developers stack layers to improve accuracy and performance. The intuition behind adding more layers is that these layers can learn progressively more complex features. As an example, in case of image recognition, the first layer could learn to detect edges, the second layer may learn to recognize textures and so on. In this project we are going to use a specific version of this neural network called ResNet-18, built with 18 of the mentioned layers: •Conv1: this layers applies a first convolution operation over the input. The filter matrix applied during this layer is bigger than those used in following convolutional layers. •BN: performs a batch normalization operation over each element of the input, therefore this layer doesn’t change the output’s size. •ReLu: stands for the rectified linear unit function, which is an element-wise operation. This layer has gained popularity in the deep learning domain because it allows to decide efficiently when a neuron will be activated. This function is as simple as only applying a value if it is positive. •Maxpool: the max pool operation is similar to the convolution, but it uses a submatrix to select the highest values instead of composing them. •Convolution layer: although this layers also perform convolution operations, these differ from Conv1 ones. As kernel matrices are smaller, the output volume is not as reduced as with the first layer. •Averagepool: as mentioned for the max pool operation, average pool uses a submatrix to traverse the input, but this layer obtains the average value for each submatrix processed. •Flatten: this layer transforms multidimensional input data into one-dimensional and is a required step to feed the fully connected layer. •Fully connected: this is also a single threaded layer that brings all inputs from one layer to every activation unit of the next layer. This is used to compile the data extracted by previous layers to form final output. 15
Figure 8: Resnet-18 layer connexion diagram. From [2] In order to better understand how these layers are connected, you can have a look at Figure 8. This diagram shows how each layer serves its output as the input for the following one. There’s also a chance that some layers are skipped during the execution, also shown in the diagram, but this is related to the ”residual” part of the network’s concept, which is not meaningful in this project’s scope. Each one of the above described layers are used in the ResNet-18 model during the Forward and Backward propagation phases. 2.3 PyTorch Framework PyTorch is an open source deep learning framework built to be flexible and modular for research, with the stability and support needed for production deployment. This framework provides a Python package for high-level features like tensor computation, with strong GPU acceleration modules. Prior to PyTorch, deep learning packages such as Caffe and Torch tended to be the most popular. Nowadays this position is being disputed between PyTorch and TensorFlow frameworks. As deep learning started to revolutionize nearly all areas of computer science, developers and researchers wanted an efficient, easy to use library to construct, train and evaluate neural networks in the Python programming language. Python, along with R, are the two most popular programming languages for data scientist and machine learning, so it is natural that researchers wanted deep learning algorithms inside their Python ecosystems. Although Python may not be the preferred programming language for application performance, it makes easier to test models even when not totally implemented. PyTorch also offers a C++ interface to be used, with C++ implemented operations, allowing to deploy with better performance. 2.4 From Low resolution to High resolution AI developers tend to train their models using GPUs and, as these devices tend to be built with scarce memory, they have to face some questions: Should we train with small batch sizes to use the original images? Or should we reduce image resolutions to increase batch sizes? In order to throw some light into these questions we will use the MAMe [9] dataset as a source to create 3 different datasets: •LRFS: Low Resolution and Fixed Shape variant. All images have a squared shape with 256² pixels area. Each original image is down-sampled to fit the requirements. •MRVS: Medium Resolution and Variable Shape variant. Images maintain their original aspect ratio or shape, but resolution is reduced. To fill a batch with these images, padding 16
pixels are added. •HRVS: High Resolution and Variable Shape variant. In fact, this is not a variant but the original dataset, composed by extremely high resolution images with non squared aspect ratios. This input also requires the usage of padding pixels to fit in batches. In Figure 9you can see the differences between the batches. Creating a batch with just 1 image using LRFS images is straight forward, no gaps will generate, but looking at MRVS or HRVS you can see the added padding pixels needed to create a squared batch with non squared images. Figure 9: Datasets image comparison. Own creation. As mentioned in [19], this technique also increases batch computation time, as all pixels must be processed. We must take into account that random batching may lead to strange alignments between landscape and portrait images, generating a huge padding section. 2.5 POP methodology and Efficiency metrics For the development of this project, POP [3] methodology will be followed. This is a performance analysis methodology that does not depend on the tools being used. POP methodology can be summarised with Figure 10. The program structure must be studied in order to accomplish some objectives and to achieve a better understanding of how our program behaves, including: • Understand general structure. • Identify initialization/finalization phases. • Detect iterative pattern. • Work distribution granularity. Selecting the Focus of Analysis is not always an easy task, because it depends on the context of the analysis. For the same trace we may select two different FoA to perform two different studies with two different objectives. When the region to be studied is clear, we can proceed to extract the performance metrics, you can find a summary of the metrics and their relation in Figure 11. 17
Figure 10: POP methodology scheme from [3] Figure 11: POP metrics relation from [3] Metrics follow a hierarchical model and are multiplicative. All metrics are shown in percentages, but computation scalability ones are calculated with respect the base case, which is the first execution. Therefore, all first executions will show a 100% values in their IPC, Instructions and Frequency scalability, and the rest of the executions could show higher or lower values in comparison. Computation scalability is calculated with instructions and cycles hardware counters, but parallel efficiency needs some clarifications: •Load Balance: The efficiency loss due to the global distribution of work among processes or threads. •Communication efficiency: The loss due to the communication of data, be it due to synchronizations between processes (or threads) or to the overhead introduced by the communication itself. 18
3 Implementation 3.1 Methodology In order to understand this program’s behaviour, we will perform several analysis, which will show the effects of altering the parameters in different ways. First of all we have to perform a visual analysis of the execution trace to identify each one of the program phases during the training process and also offer a brief explanation of their functions inside the program execution. When all phases are identified, we can proceed to their isolated analysis inside the traces. This is performed by zooming into each phase to analyse pricesely what happens in them. We will also compare behaviour and performance metrics of each phase for the different datasets used in order to highlight noticeable differences. After the detailed analysis of the identified phases we will proceed with some parameter scaling tests. These tests will run several instances of the program altering only one of the execution parameters in order to see their impact on the overall execution performance and results. At the end, the main goal of training a model is to improve the final accuracy of the network, therefore we will study how each dataset affects the overall accuracy and also we will apply what we learn about execution parameters to see if there’s any improve in this matter. 3.2 Setup In this section you can find a description of all necessary steps to configure our HPC system to run the application. Container creation It is a common practice to use containers in order to execute AI software, this way it becomes easier to solve runtime dependencies and using different execution configurations. Also, containerization allows us to better reproduce the executions, giving a fast way to migrate the experiment to another cluster if necessary. In our case, we are using the Singularity [24] software. This container can be build by using the Docker [25] database with the Python basic tools to start creating our custom environment. We also have a list of required Python modules and features, needed to execute our ResNet model in the PyTorch framework. This requirements can be found in Table 7. We can build the container with the basic functionalities using two simple commands, found in Listing 1. It is also required to install our BSC data extraction tool, Extrae, from the local MN4 filesystem. 1 s i n g u l a r i t y build −−sandbox torch_base docker :// python : l a t e s t 2 pip i n s t a l l −r requirements . txt Listing 1: Building Singularity container With the Singularity container already built, it is time to compile our main module: Torch. 19
Requirement Version used Cycler 0.10.0 Future 0.18.2 Kiwisolver 1.3.1 Matplotlib 3.3.3 Numpy 1.17.4 Pandas 0.25.3 Pillow 6.2.1 Pyparsing 2.4.7 Python-dateutil 2.8.1 Pytz 2019.3 Six 1.13.0 Torch 1.6.0 Torchvision 0.7.0 Table 7: List of Python required modules. Own creation. PyTorch Compilation Even though we could be using the precompiled version of Torch, downloaded during the setup, we want to achieve the best possible performance from the start, and to achieve that we must compile the module inside our HPC system. This way, our PyTorch framework instance will be able to use all our CPUs capabilities, such as AVX-512 instructions, and also will link against some libraries used in our system. This is done not only to achieve the best initial performance, but to ensure that the system uses its own modified versions of some libraries, which can be optimized for this specific machine. First of all, we have to download the source code for the specific version we want to compile. These code lines can be found in Listing 2. This download will be performed in my local laptop and then copied into the system through scp in order to avoid connecting our HPC to the internet if it is not strictly necessary. 1 g i t c lo ne −−r e c u r s i v e https :// github . com/ pytorch / pytorch 2 cd pytorch 3 g i t checkout 1. 6 4 g i t submodule sync 5 g i t submodule update −−i n i t −−r e c u r s i v e Listing 2: PyTorch v1.6 source download The compilation process starts by setting up the compilation script with the appropriate flags. This script can be found in Listing 3, with all the necessary code lines to compile PyTorch framework. We must pay attention to the library links, because we have to use a modified version of some of them, prepared to be used with Python. In fact, we have to execute the last 2 code lines in order to solve all Extrae’s dependencies when interacting with Python. 20
The goal is to use the maximum possible Batch Size value for each dataset given the amount of main memory we have that also allows us to compute the full dataset. With the addition of padding pixels into MRVS and HRVS datasets, the total amount of pixels may differ between steps and this scenario can generate a non computable step if the batch exceeds our available memory. The maximum batch size values for each dataset and their total amount of steps to perform are summarised in Table 8. These values have been found through trial and error executions until finding the maximum value that can fit into memory. Dataset Batch Size Epoch Steps LRFS 1024 20 MRVS 32 632 HRVS 2 10.111 Table 8: Batch Sizes and steps summary. Own creation. In Figure 13 we can see the elapsed time per step to compute informative megapixels (those which are part of an image) per step. LRFS dataset has an extremely low variation in execution time from one step from another because no padding pixels are added in the batches, therefore each batch will contain exactly the same pixels except for the last one, where only the remaining images are present. When looking into MRVS dataset we can see huge differences between steps. These variations come from the differences in the batched images, as each batch will contain distinct amounts of padding and informative pixels. Figure 13: Informative megapixel execution times. Own creation. HRVS dataset results show less variation if compared with MRVS. As these images are processed with their original resolution, the relative amount of padding pixels compared with the informative ones is lesser than in MRVS. If less padding is added proportionally, more computation is used in the informative pixels. Figure 14 represents different steps in the X axis and the elapsed time per megapixel in the Y axis. We can see that MR is the one that needs less time to compute a megapixel, as we discussed before MR is the data set that contains more padding pixels per batch. Our hypothesis is that padding pixels are cheaper to compute than real pixels. 27
Figure 14: Batch megapixel execution times. Own creation. Analyzing the HR execution time in Figure 14 we see that steps 10, 15 and 19 take longer to compute than other steps. These particular steps contain images with similar aspect ratios, which seem to have an impact on performance. 4.2 Pixel study When trying to use images with their original resolution and shape, we find that almost all high resolution images tend to have a non squared geometry. We have explained that, in order to create a squared batch of images needed to feed the CNN, padding pixels are added into the batch through a technique called random batching. This method also has an effect on the amount of instructions executed, as these pixels must be processed because they belong to the batch. After the execution of a full epoch, which consists on processing one time all the images in the dataset, we have built Figure 15, where you can find the total amount of informative and padding pixels computed during the full epoch on each dataset. Figure 15: Full epoch pixel count comparison. Own creation. If we compare LRFS and MRVS, we can spot a 5,5x increase in the informative pixels count, directly related to the MRVS images shape. As those images maintain their original aspect ratio, this increase is expected even when resolution is still lower than the original. Along with the informative pixels increase, we can also notice that the amount of padding pixels is higher than the informative ones. In fact, during the whole MRVS dataset execution, we we process too many padding pixels, as the informative ones only represent around 22% of the whole input. 28
Figure 16: Theoretical batch representation with two images with different aspect ratios. Own creation. In Figure 16 we have built a representation of a possible batch with two images, each with different shape, showing with dotted lines the gaps where padding pixels must be added to obtain a square. In this scenario, we are computing way more padding pixels by filling the batch without considering the arrangement of the informative pixels, generating holes. Better arrangements could reduce the amount of padding pixels at the cost of executing a certain arrangement algorithm, and its costs must be paid at each batch loading phase if no further modifications are implemented. Referring again to Figure 15, if we compare MRVS with HRVS we can observe not only the effect of variable shapes, but also the impact of the total resolution of each image. With HRVS we are computing approximately 28x more informative pixels than MRVS, but only around 4x more padding pixels, increasing the relation up to 65% of useful information processing during the full epoch. For AI practitioners, the execution time of the model training is key in order to fasten the model’s adaptation capabilities. Adding new data to the training sets allows to re-train the model to get better predictions but, if training requires a huge amount of time, this process must be delayed or scheduled in order to train only when the prediction gain should be noticeable, if any. 5 Detailed analysis per phase 5.1 Batch loading The first test to be made is based in varying the batch size value to see its impact on the execution. We executed the LRFS dataset with half the batch size used in the first tests in order to see if this value has an impact in the overall execution time. This comparison is found in Figure 17 with two execution traces. The top trace belongs to an execution with a batch size of 24 and the bottom one with a batch size of 12. Both traces show the useful IPC for each thread involved in the computation. 29
Figure 17: Batch size value effects. Own creation. Comparing just the batch loading region, we can say that halving the batch size also reduces its execution time, but it is reduce 1/3 of the original one, not half as expected if the execution time was propotional to the batch size. In the traces we observe some parallel regions that are opened and closed that identify where the different threads are working (the vertical columns with green colour in the trace). We can see that the number of parallel regions coincides with the batch size used in each execution, but also there is a good portion of time where only one thread is active. If we zoom into the red rectangles from Figure 17 we can create Figure 18 showing a trace view of the IPC at the top and another view of the OpenMP calls at the bottom. These traces reveal how the first thread opens parallel regions for each one of the images, indicating that each individual image is, in fact, split to be processed in parallel, creating and closing a parallel region for each one. Figure 18: Batch loading columns matching batch size value. Own creation. If we zoom into one of the parallel regions we can observe how each thread is performing on the task by using the IPC view of our trace. In Figure 19 we show a comparison of the batch loading phase on each dataset, focusing in one of the image loading bursts. When looking at MRVS and HRVS datasets, we can spot a difference with LRFS: all threads can achieve a high IPC value in the first part. In fact, LRFS can only use 6 of the available threads during the loading process. An explanation to this can be found taking into account that each parallel region is used to load just one image: 30
Figure 19: Batch loading datasets parallelism comparison. Own creation. • Each one of the LRFS images has 256² pixels, and each pixel needs 3 bytes to express the RGB color, therefore the work chunk for this process results in a block of 192 KBytes. • By checking PyTorch’s parallelism policy, we found that the default grain size for each spawned thread cannot be lower than 32 KBytes. Grain size is further studied in following sections. • Being that 192kB 32KBxT hread = 6 threads, we can prove that LRFS is only using 6 of its threads because images are too small. With that in mind we can state that LRFS images will not take profit of a high core count during executions, but MRVS and HRVS will. It is also clear that increasing batch size value will not affect in any way to this phase’s parallelism when using low resolution images. Figure 20: Batch loading metrics comparison. Own creation. In Figure 20 we see a comparison of the different metrics we can obtain using the POP modelfactors script from the Basic Analysis tools, regarding the batch loading phase of each dataset. This table reveals how MRVS and HRVS can achieve better load balance than LRFS during this phase, expected once seen Figure 19 parallel behaviour. 31
Variable shaped datasets require less instructions to complete this phase and also achieve higher frequencies than LRFS executions. This instruction count reduction may be related with the amount of pixels to be loaded in the batch. Although IPC is higher when using LRFS dataset, computation scalability is greatly improved when using variable shaped images. Figure 21 shows the total pixel count when computing the particular step used to create Figure 20. We can see that pixel count follows LRFS > HRVS > MRVS, and coincides with the instruction scalability order. This pattern is repeated when measuring the batch loading phase of other steps. Figure 21: Pixel count comparison in the test step. Own creation. The IPC reduction could be highlighting the effects of adding the padding pixels during the batch creation, because it represents an extra step during this process that LRFS dataset does not perform, but MRVS and HRVS do. Another explanation for this IPC reduction is related to the individual images size. As MRVS and HRVS images have increased sizes when compared with LRFS ones, we could expect extended waiting times until a particular image is loaded in memory, therefore reducing the average IPC of this particular region when using bigger images. 5.2 Forward propagation This phase receives the batched images and applies a series of mathematical operations over the image pixels. These operations are performed inside the so-called interconnected layers. In Figure 22 you can find two views of the same trace from an LRFS execution, showing the layers traversed during the forward propagation phase in the first row and the IPC achieved by each thread in the second. Each executed layer is related to a color in the first row and all layers are always executed in the same order: conv1, bn1, ReLu, maxpool, all convolutional layers, averagepool and the fully connected one. Figure 22: IPC and layers views on Forward propagation. Own creation. We can spot how in the first layer (conv1) all threads are active, but this changes during batch normalization, leaving the last 2 threads unused. This pattern is repeated in other layers. 32
During the first convolution layers we can see that not all threads are being used at some points, showed in the pink rectangle. When reaching the last convolution layer, more threads can be profited and also require less time to finish. As each convolution reduces the output volume, requiring less execution time near the last convolution layers is expected. In fact, if the volume is being reduced while trespassing convolution layers, why more threads can be used when reaching the end? In Figure 23 we see a zoomed in view of two convolution layers. The first row represents the operations that PyTorch framework has launched, the second one shows the layers selected just to clarify at what time the layer changes, and the third is the IPC view of all working threads. Thanks to PyTorch operations tracing (manually done with custom Extrae events), we can see how convolution operations are taking profit of all our threads on both layers. Thread imbalance occurs when select operations are executed, just after convolutions. Both convolution and select operations tend to require less execution time at each layer. Convolution time depends on the input size and the filter submatrix used and, as all filters have the same dimensions, this time reduction can only come from the input size reduction from previous layers. Figure 23: Convolution and select operations. Own creation. The select operation accesses the output tensors of the convolution to slice them through a specific dimension, offering a view of the input tensor without this dimension. If tensors contain less values due to batch volume reduction after the convolution, then select operations will also execute faster. As dimension count in those tensors does not change, we can say that parallelism in this operations is not related to the amount of dimensions, but it could be related with the amount of elements on each dimension. In order to better understand the effects of our datasets in this phase, we have Figure 24 showing a whole forward propagation phase using MRVS and HRVS datasets. The first two rows belong to the MRVS execution, and the last two to the HRVS one. When comparing layers of MRVS with LRFS from Figure 22, we see a similar pattern, with an extension of the conv1 layer duration in the MRVS dataset. We can also spot a huge difference between the three executions regarding the maxpool layer, where only LRFS is able to use all available cores. When counting the number of active threads in maxpool layer, we see that LRFS uses all available cores; MRVS is able to use 16 cores and HRVS uses only 2 of them. Further testing shows that maxpool layer parallelism depends on the batch size value, so parallelism is at image 33
Figure 24: HRVS and MRVS forward phases comparison. Own creation. level. This means that each thread can process one image while another thread processes another image. To clarify, our LRFS execution is using all 24 cores with a batch size of 1024 images, but the last threads are finishing earlier because, even when all images have the same size and shape, 1024 is not multiple of 24, therefore these last threads will end their jobs earlier due to lack of more images. In Figure 25 you can see the IPC of the maxpool layer of LRFS (second view) and MRVS (first view), showing the points where a thread finishes processing an image to start with the next one, in pink rectangles. This behaviour reveals that this layer is easier to balance when using more images (increasing batch size). Figure 25: LRFS and MRVS maxpool layer IPC comparison. Same semantic scale. Own creation. As MRVS is executed with a batch size value of 32, we can ensure each of the 16 working threads will be processing two images. In this case more threads could be profited, resulting in a lot of threads processing one image and some of them processing two. This scenario would not throw any execution time gain compared with the 16 thread execution, as all images must be processed before finishing the layer anyways. In LRFS execution view is easier to spot the points where an image has been finished and the new one starts, just by looking when the IPC has a variation inside the pink rectangle. In 34
this execution we see the maximum thread usage possible during the maxpool layer. We can confirm that even when each thread processes more than one image, the least possible execution time is given by the thread with more workload, forcing others to wait. Convolution operations behave similarly with all datasets, even when changing core count and batch size values, offering no differences in trace views. Figure 26: Forward phase metrics comparison. Own creation. In Figure 26 you can find a summarised table with our beloved metrics, regarding the forward phase of each dataset. As seen with the batch loading phase, HRVS dataset tends to have lower IPC than LRFS and MRVS, but also has better frequency values. Load balance decreases when using HRVS dataset, as seen in Figure 24, this decrease comes from the execution of maxpool layer, which represents a good chunk of the forward phase computation time and, in our case, can only use 2 threads of the 24 available. 5.3 Backward propagation Backward is the function which actually calculates the gradients by passing its argument through the backward graph all the way up to every leaf node traceable from the calling root tensor. This backward graph is generated dynamically during the forward pass, therefore backward only calculates the gradients using the already made graph and stores them in leaf nodes. In essence, this phase consists on following the path made by the forward phase in order to prepare to update the weights, or neuron activation probabilities, based on a loss function. This function will calculate the difference between the expected output and the obtained one, generating the gradient value for each neuron of the network and storing it to update weights later. Figure 27 shows the whole execution of the backward propagation phase, using LRFS dataset with a batch size of 1024 images. The first row shows the operations performed by PyTorch and the second the IPC obtained for each active thread. We can see a familiar pattern in thread usage that behaves as forward phase from Figure 22, but inverted. This was expected given that backward phase executes the same layers as the forward phase but in reverse order, but some points must be highlighted here. At first glance we can see that this phase executes convolution operations, but those are different from the ones executed in forward phase. One of them uses the output of the previous layer to generate the loss gradient and the other uses this loss value to propagate it to superior layers following the chain rule adapted to convolution operations. Both convolutions are needed to generate the output from the previous layer, which will be 35
Figure 27: LRFS backward phase. Own creation. tackled again with both convolutions. As seen during forward propagation phase, convolutions can be executed using all available threads, but select operations cannot. Figure 28: MRVS and HRVS backward phases. Same semantic scale. Own creation. In Figure 28 you can see the whole execution of the backward propagation phase when executing MRVS (first row) and HRVS (second row) datasets. As explained, backward operations are derived from the forward pass design. With this in mind, we can ensure that the regions marked with the red squares belong to the maxpool layers from forward pass, as they show the same parallel behaviour. Although these regions use the same amount of cores, the impact on the overall backward phase execution time is lesser than the impact on forward phase. Figure 29: Backward phase metrics comparison. Own creation. 36
Figure 40: LRFS cycles comparison with different batch sizes. Own creation. In Figures 41 and 42 we can see the metrics for the MRVS and HRVS executions. Figure 41: Batch size scaling with MRVS dataset. Own creation. When using MRVS dataset we can see a sustained increase in parallel efficiency and load balance along the batch size scalation, but this improvements are overshadowed by the IPC drop. The sweet spot for this specific dataset seems to be using a batch size of 8 images. Above this value we see increases in the amount of executed instructions, making even worse the IPC. Load balance and parallel efficiency increases can be caused by the step number reduction, because the impact of the single threaded zones produced at each training step will be lesser. We also know that work distribution occurs at images level, and as these images will be bigger than any LRFS image, parallelism will be better from the start, as seen with batch size 1 global efficiency. Due to memory constraints, HRVS executions can only scale up to two images per batch. In this case we find the same tendency regarding load balance and parallel efficiency, as well as the IPC and instructions drop. Our metrics reveal an improvement of 20% in global efficiency and a speedup of 1,4x with a slight decrease in computation scalability. HRVS is the only dataset that shows good efficiency values when using the maximum batch size possible. Even when MRVS was able to achieve a good parallel performance too, the IPC scalability was lower. Parallel efficiency with HRVS dataset improves drastically due to the well known now maxpool layer. All executed steps during these executions use 1 and 2 threads respectively during this layer, as seen during previous analysis of the forward phase. Figure 43 shows a comparison at the same semantic scale of a full training step between 43
Figure 42: Batch size scaling with HRVS dataset. Own creation. HRVS executions with batch sizes 1 and 2 respectively. This traces reveal the importance of increasing the batch size due to its relation with parallelism. Although the effects during backward propagation phase are not so noticeable (marked with the yellow rectangle), this cannot be overlooked when executing the forward phase (marked with the red rectangle). Increasing the batch size value not only increases the parallel efficiency of this layer, it also reduces the total amount of steps to execute. Figure 43: HRVS batch size traces comparison. Up: batch size=1, Down: batch size=2. Own creation. Although we have noticed huge benefits when increasing batch size when using HRVS dataset, this is not the case for the others. LRFS executions show a huge increase in global efficiency due to instruction scalability gains, but load balance achieved a peak value of 40% efficiency when using a batch of 256 images. Figures 44 and 45 show a comparison of a full training step when using HRVS and LRFS executions in this order. In this case we will compare those executions that showed better results in the measured metrics, using a batch size of 256 for LRFS and 2 for HRVS. When watching Figure 44, the batch loading phase (black zone) of the LRFS run uses around 40% of its step time, while HRVS step spends more than 90% of its time in forward and backward propagations (white and red zones), which consist on convolutional layers. 44
Figure 44: HRVS(up) & LRFS (down) training phase comparison. Own creation. Referring to Figure 45 where the IPC of each dataset step is represented in the same semantic scale, we spot clear differences in their behaviours. On each view we have highlighted with yellow, red and pink rectangles the zones where batch loading, forward and backward phases are being executed. It is clear that maxpool layer is working against HRVS in this comparison, as LRFS is able to use more parallelism there due to its batch size value, but the load imbalance during the batch loading phase of LRFS execution shown in previous sections has a stronger effect over parallel efficiency that overcomes the convolutional layers gains. Figure 45: HRVS (up) & LRFS (down) training phase IPC comparison. Own creation. So far we have seen different flaws in both HRVS and LRFS executions that impact their efficiency, all related to parallelism behaviour in the different execution phases. Core and batch size scalability tests have shown us that we can optimally train the model with LRFS data using a machine with less memory and processing capacities. On the other hand, when using HRVS data we have seen that we can take advantage of more cores, but we do not have enough main memory to continue scaling the batch size. Despite this, we see that HRVS runs benefit greatly from increasing the number of images processed at each step in terms of taking advantage of the hardware. Even if HRVS processing can take profit of the machine, execution time will prevent AI developers from using it if no other advantages can be obtained. Therefore, our next step is to analyze how our model predictions are affected by the input dataset change. 7.2 Grain size When training a deep learning model like the one we are using in this project, parallel execution is of huge importance. During the first tests we found out that PyTorch’s parallelism policy relies on a global variable called ”GRAIN SIZE”, located in the ATen module of the Torch library, which in fact is a constant expression. This avoids the possibility of changing the value dynamically, so each test value requires a recompilation of this specific package. This value determines the minimum amount of work needed to spawn a new thread if the execution is not using all of them yet. 45
PyTorch’s developers have set the value of the work distribution variable to 32 KBytes, arguing that this value has been heuristically chosen to offer the lowest execution times in a general scenario, so we tested different values to verify if they where correct about this matter. Figure 46: Grain size value comparison in all datasets. Own creation. Figure 46 shows the average execution time per training step on the Y axis and the executed dataset in the X one. We tested values near the default and also two extreme values, being 10 Bytes and 100 MBytes, and found out that developers where right. In all executions, the 32 KBytes value is able to finish with slightly lower execution times than other values, regardless the used dataset. Figure 47: GrainSize effects on Batch loading phase with LRFS. Own creation. In Figure 47 we can see the effects of varying the grainsize value by looking at the IPC traces. As explained during batch loading section, LRFS dataset can only take profit of 6 threads when using a 32 KBytes value. Now we can see on the first row an execution with a grainsize value of 16 KBytes that, as expected, is using 12 threads this time. The second row represent the execution with the default value and the third one shows the execution using a value of 64 KBytes, only using 3 threads. 46
In order to evaluate how the grainsize value is affecting our executions, we have created Figures 48,49 and 50 showing the POP metrics applied to our set of testing executions with each dataset. Figure 48: GrainSize metrics using LRFS dataset. Own creation. Figure 49: GrainSize metrics using MRVS dataset. Own creation. Figure 50: GrainSize metrics using HRVS dataset. Own creation. We can appreciate certain variations in the load balance metric on all datasets, reaching the top values when using grainsize values between 32 and 128 KBytes. None of the datasets shows a reasonable improvement in any metric nor in execution time, except for the slight IPC increase showed in the 100 MB columns. This can be explained by knowing that using a higher grainsize value will spawn less threads, allowing the used ones to complete tasks with less data sharing conflicts. With these tests we can ensure that, for our purposes, PyTorch developers have hit the bulls-eye with their default grainsize value. Nevertheless, we are using a specific kind of DNN 47
(CNN) and we can not ensure that this default value would throw the best performance with any network. 7.3 Accuracy tests The goal of training a model with meaningful data is to enhance its capacity to detect certain features from data that wasn’t used to train it. When watching the training process from another perspective, each training step has to face data never processed before, therefore, we can measure the accuracy increases at each training step and calculate an accuracy average for the training process at the end of an epoch. Predictions are computed during the forward phase and are used to calibrate gradients that will affect neuron activations in the next step. When training a specific model, an AI developer may test a model by executing the first epoch and check the accuracy values as a guide to evaluate further development decisions. We know that training models with HRVS data consumes a huge amount of time and energy when compared with LRFS training but, if some meaningful gains are achieved in the accuracy perspective, using this data may be worth the effort in some specific study fields. Until this point we have seen how batch size variations imply different effects on the execution’s behaviour and hardware utilization, but now we want to check if the effects spread to accuracy values by measuring accuracy in the first training epoch with different batch size values. Figure 51: Accuracy comparison plot. Own creation. In Figure 51 we represent the accuracy of the first epoch in percentage through the Y axis, and batch size values over the X axis. From the start, with batch size 1, we clearly see that LRFS dataset achieves better accuracy. All three datasets seem to follow the same curved tendence with batch size variations between 2 and 32. Unfortunately, main memory restrictions make HRVS batch size variations insuficient to confirm this tendence. We can also check Figure 52 where accuracy values are represented in percentage. When using batch size 1, LRFS and MRVS accuracy results only differ 1% but, when more than one image is used, results distance starts to grow at each batch size increase. This effect can be explained with the huge amount of padding pixels contained in MRVS batches shown in Figure 15, as those are computed in the same way that informative ones and could be altering gradients during the backpropagation phases. When checking batch size 2 executions we find that MRVS 48
Figure 52: Accuracy comparison table. Own creation. and HRVS hit almost the same value. Given this data we can state that batch size value is meaningful when training the first epoch. LRFS dataset gets around 42% accuracy when using batch sizes between 16 and 128. If we refer to Figure 39 we can mix our results and find that this specific dataset will achieve its best hardware and accuracy performances when using from 32 to 128 images per batch. Another hyperparameter comes into play when talking about accuracy: learning rate. Now we know that batch size variances alter accuracy results, but an AI developer will be modifying learning rate values in order to find the best value, so we should too. Figure 53: Accuracy plot with Learning Rate variances. Own creation. Figure 53 represents the accuracy values with different LRFS executions but slightly altering learning rate values from 0.0001 to 0.00035. Contrary to our first thoughts, we haven’t surpassed the maximum accuracy found before. Instead, we can see how accuracy values are shifted to the right, getting better values with higher batch sizes. In fact, using a batch size of 256 is a better option from hardware and accuracy perspectives if we set the learning rate to 0.00035. With these tests we have seen not only how the amount of images per training step may affect its accuracy performance, but also spottted a possible relation between the learning rate and the batch size hyperparameters. The main goal of these tests was to find some advantage when using high resolution images but, given our current results, we can say that using HRVS datasets won’t produce better accuracy results. Although this statement might be true in our case, this cannot be ported to other scenarios. If we are using a different dataset or a slightly different CNN (for example with extra or less layers) this study should be repeated. 49
8 Conclusions 8.1 Project conclusions Motivated by the need of processing high resolution images in certain study fields, we have highlighted some relevant performance differences and needs. By tracing and analysing each phase of a CNN model’s training process we have seen how paralelism is used in different ways. In fact, our tests with batch sizes unveiled how the image loading phase opens parallel regions for each image, creating possible overheads when using high batch size values. We have also seen how forward and backward phases have different impacts on resources usage by comparing their metrics, inspite of traversing the same layers during their execution. Traces have shown how backward phase uses a different approach with convolution operations in order to update gradients and, during all the tests, the optimization phase shows the same behaviour independently of the dataset used and the amount of images processed per step. As we know that optimization algorithms traverse all layers to update weights, we can confirm that this phase will only depend on the neural network configuration and size, not on the data used. Scalability tests regarding the amount of CPU cores have shown how the best value depends tightly on the phase we focus on. When creating a batch, image size defines how many threads can be used, therefore using bigger images results in better load balance during this phase. The usage of padding pixels, needed to create a batch of variable shaped images, has a significant impact in computational performance. While creating a batch with non squared images, we are building a bigger structure containing information that doesn’t belong to the meaningful data. This implies not only higher memory requirements and execution times, but also affects the overall prediction accuracy of the model, at least during the first epoch. Given the effect of padding pixels, it is worth trying to apply different batching techniques that, even if they require more processing during batch creation, may allow to perform better in the overall training. Even though low resolution images have shown better accuracy results, we have confirmed that this kind of data isn’t able to profit all our hardware capabilities in the same way that high resolution images do, when using this specific framework in CPU devices. Although this may push us to keep using low resolution images, we have to keep in mind that most of the existing images have really high pixel counts, forcing AI practitioneers to process their datasets to reduce resolution. This process could imply information loss when the resolution difference is extremely high, creating non meaningful data. 50
8.2 Personal Conclusions This project has introduced me to research on the high performance computing field and I have developed my performance analysis skills. Now I am more fluent when adding code changes related to instrumentation with external tools. Before this project, deep learning models acted like a blackbox to me. Being able to understand how the information flows under the hood has increased my interest in this particular field. Knowing that this study is tightly related to a specific model designed for a specific task, I would like to explore other model designs to see if our conclusions are applicable in any way. Although this project is focused on performance in HPC clusters, I’m interested in exploring how to adapt this kind of programs to be used in embedded systems. Also, developing the analysis has improved my working methodology related to data handling, as all traces generated by the executions were huge in size due to the time needed by the training process, creating some troubles when working on trace visualization. 51
9 References [1] ”IBM”, “Ibm learn platform,” https://www.ibm.com/cloud/learn/neural-networks, [Online]. [2] K. He, X. Zhang, S. Ren, and J. Sun, “Deep residual learning for image recognition,” in Proceedings of the IEEE conference on computer vision and pattern recognition, 2016, pp. 770–778. [3] ”POP-COE”, “Performance optimization and productivity coe in hpc,” https://pop-coe. eu/, [Online]. [4] K. J. Geras, S. Wolfson, Y. Shen et al., “High-resolution breast cancer screening with multi-view deep convolutional neural networks,” CoRR, vol. abs/1703.07047, 2017. [Online]. Available: https://arxiv.org/abs/1703.07047 [5] W. Lotter, G. Sorensen, and D. Cox, “A multi-scale CNN and curriculum learning strategy for mammogram classification,” in Deep Learning in Medical Image Analysis and Multimodal Learning for Clinical Decision Support, 17 Sept. 2017, Québec City, QC, Canada. Springer, 2017, pp. 169–177. [Online]. Available: https://doi.org/10.1007/978-3-319-67558-9_20 [6] M. Treml, J. Arjona-Medina, T. Unterthiner et al., “Speeding up semantic segmentation for autonomous driving,” in MLITS, NIPS Workshop, vol. 2, 2016, p. 7. [7] X. Chen, H. Ma, J. Wan, B. Li, and T. Xia, “Multi-view 3d object detection network for autonomous driving,” in Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 21-26 July 2017, Honolulu, HI, USA. IEEE, 2017, pp. 1907–1915. [Online]. Available: https://doi.org/10.1109/cvpr.2017.691 [8] M. Reichstein, G. Camps-Valls, B. Stevens et al., “Deep learning and process understanding for data-driven earth system science,” Nature, vol. 566, no. 7743, pp. 195–204, 2019. [Online]. Available: https://doi.org/10.1038/s41586-019-0912-1 [9] F. Parés, A. Arias-Duart, D. Garcia-Gasulla, G. Campo-Francés, N. Viladrich, E. Ayguadé, and J. Labarta, “The mame dataset: on the relevance of high resolution and variable shape image properties,” Applied Intelligence, pp. 1–22, 2022. [10] F. Parés, A. Arias-Duart, D. Garcia-Gasulla et al., “A Closer Look at Art Mediums: The MAMe Image Classification Dataset,” CoRR, vol. abs/2007.13693, 2020. [Online]. Available: https://arxiv.org/abs/2007.13693 [11] M. . technical information”, “Barcelona supercomputing center,” https://www.bsc.es/ marenostrum/marenostrum/technical-information, accessed: 2022-02-20. [Online]. [12] U. A. labs Pyro”, “Uber technologies inc.” https://eng.uber.com/pyro, accessed: 2022-02- 20. [Online]. [13] O. A. webpage”, “Openmp architecture review board,” https://tools.bsc.es/downloads, accessed: 2022-02-11. [Online]. [14] P. A. tools”, “Barcelona supercomputing center,” https://tools.bsc.es/downloads, accessed: 2022-01-14. [Online]. [15] D. Bahdanau, K. Cho, and Y. Bengio, “Neural machine translation by jointly learning to align and translate,” CoRR, vol. abs/1409.0473, 2014. [Online]. Available: https://arxiv.org/abs/1409.0473 52