scieee AI-readable full text Open interactive document viewer

Optimization of a finite element code implemented in MATLAB. On the use of GPUs for High Performance Computing

Navarro Jiménez, José Manuel

Abstract

[EN] The Department of Mechanical and Materials Engineering has developed a 2D Finite Element code based on geometry independent Cartesian grids (cgFEM) capable of solving shape optimization problems as well as making patient-specific analyses using medical images. A similar code in 3D (FEAVox) is currently under development. Both codes are implemented in MATLAB, a simple and intuitive programming language but with a higher computational cost than compiled languages such as C++ or FORTRAN. The objective of this Thesis is to develop programming procedures to improve the performance of the existing and the currently under development software. Among other optimization techniques this Thesis will focus on the use of Graphics Processing Units (GPU) for high performance computing. The use of these techniques has led to a software that, despite being implemented with MATLAB, improves the computational efficiency of commercial software which is developed using compiled programming languages.

Full text

UNIVERSITAT POLIT` ECNICA DE VAL` ENCIA Department of Mechanical and Materials Engineering Master Thesis Optimization of a finite element code implemented in MATLABr. On the use of GPUs for High Performance Computing. Presented by:D. Jos´e Manuel Navarro Jim´enez Supervised by:Dr. D. Juan Jos´e R´odenas Garc´ıa Valencia, July, 2014 Master Thesis Optimization of a finite element code implemented in MATLABr. On the use of GPUs for High Performance Computing. for the degree of Master of Science in Mechanical and Materials Engineering presented by D. Jos´e Manuel Navarro Jim´enez at the Department of Mechanical and Materials Engineering at Universitat Polit`ecnica de Val`encia Supervised by Dr. D. Juan Jos´e R´odenas Garc´ıa Valencia, July, 2014 Abstract The Department of Mechanical and Materials Engineering has developed a 2D Finite Element code based on geometry independent Cartesian grids (cgFEM) capable of solving shape optimization problems as well as making patientspecific analyses using medical images. A similar code in 3D (FEAVox) is currently under development. Both codes are implemented in MATLABr, a simple and intuitive programming language but with a higher computational cost than compiled languages such as C++ or FORTRAN. The objective of this Thesis is to develop programming procedures to improve the performance of the existing and the currently under development software. Among other optimization techniques this Thesis will focus on the use of Graphics Processing Units (GPU) for high performance computing. The use of these techniques has led to a software that, despite being implemented with MATLABr, improves the computational efficiency of commercial software which is developed using compiled programming languages. I Resumen El Departamento de Ingenier´ıa Mec´anica y de Materiales ha desarrollado un c´odigo de Elementos Finitos 2D basado en mallados Cartesianos independientes de la geometr´ıa (cgFEM) capaz de resolver problemas de optimizaci´on topol´ogica y de realizar an´alisis espec´ıficos de paciente a partir de im´agenes m´edicas. Se est´a desarrollando actualmente un c´odigo similar 3D (FEAVox). Ambos c´odigos est´an implementados en MATLABr, un lenguaje de programaci´on sencillo e intuitivo pero menos eficiente computacionalmente que otros lenguajes compilados como C++ o FORTRAN. El objetivo de este Trabajo Fin de M´aster es desarrollar procedimientos de programaci´on que permitan aumentar el rendimiento computacional del software que ha sido o est´a siendo desarrollado en el Departamento. De entre las t´ecnicas de optimizaci´on disponibles, se har´a hincapi´e en el uso de tarjetas gr´aficas (GPU) como medio de computaci´on de alto rendimiento. La utilizaci´on de estas t´ecnicas ha permitido obtener un software de EF que, pese a estar implementado en MATLABr, mejora el rendimiento computacional de software comercial desarrollado con lenguajes de programaci´on compilados. III Resum El Departament d’Enginyeria Mec`anica i de Materials ha desenvolupat un codi d’Elements Finits 2D basat en mallats Cartesians independents de la geometria (cgFEM) capa¸c de resoldre problemes d’optimitzaci´o topol`ogica i de realitzar an`alisis espec´ıfics de pacient a partir d’imatges m`ediques. Actualment s’est`a treballant en un codi similar 3D (FEAVox). Ambd´os codis estan implementats en MATLABr, un llenguatge de programaci´o senzill i intuitiu per`o menys eficient computacionalment que altres llenguatges compil·lats com C++ o FORTRAN. Aquest Treball Fi de M`aster t´e com a objectiu desenvolupar procediments de programaci´o que permeten millorar el rendiment computacional del software que ha sigut o est`a sent desenvolupat al Departament. De les t`ecniques d’optimitzaci´o disponibles, aquest Treball es centrar`a en l’utilitzaci´o de targetes gr`afiques (GPU) com a mitj`a de computaci´o d’alt rendiment. L’´us d’aquestes t`ecniques ha perm´es obtindre un software d’EF que, a pesar d’estar implementat en MATLABr, millora el rendiment computacional del software comercial elaborat amb llenguatges de programaci´o compil·lats. V 1. Introduction However, the main difficulty to overcome in all these cases is the high computational cost of the numerical analysis. Even with High Performance Computing (HPC) workstations some analyses with a huge amount of degrees of freedom (DOFs) can take hours to be solved. In other cases, like real time simulations, the available time to solve each problem is not enough to reach a sufficiently accurate solution. 1.1 cgFEM As FEM provides the industry with several benefits, a lot of resources have been invested in order to improve all aspects of the FEM, and specially those regarding computational cost. Following this research line, the approach made by the Department of Mechanical and Material Engineering of the Universitat Polit´ecnica de Valencia has been exploring the possibilities and limits of geometry independent Cartesian grids, developing a 2D FEM code called cgFEM [9], [7]. The FE mesh is usually constructed in 2D by the division of the real domain into a group of linear or curved, triangular and/or quadrilateral subdomains that have no overlapping between them. cgFEM instead uses two different meshes (Fig. 1.1). The mesh used for the FEM approximation is called the approximation mesh. The only requirement of this mesh is that it has to cover all the problem’s domain (Fig. 1.1a). The second one is called the integration mesh. All the numerical integrations are performed on this mesh. The integration mesh is created by dividing the elements of the approximation mesh that are intersected by the domain into integration subdomains. A Delaunay triangulation is performed using the internal nodes and some intersection points of the boundary (Fig. 1.1b and 1.1c). Then, cgFEM implicitly takes 2 Jos´e Manuel Navarro Jim´enez 1.1. cgFEM into account the geometry of the problem’s domain through the numerical integration process. (a) Approximation mesh. (b) Integration mesh. (c) Detail of the integration mesh. Figure 1.1: Different meshes used in cgFEM. Internal elements, those fully located in the interior of the domain, are treated as standard FEM elements, whose integrals are evaluated using a Gauss quadra- Optimization of a FEM code. Usage of GPUs in parallel computing. 3 1. Introduction ture for quadrilaterals common for all elements. Boundary elements are integrated using a triangle Gauss quadrature in all of the subdomains created with the Delaunay triangulation, as shown in Figure 1.2. t1 t2 t3 t4 Figure 1.2: Integration subdomain generation. cgFEM uses a set of Cartesian grids hierarchically structured that allows for a great computational cost reduction. Each mesh is composed by regular quadrilaterals. The 0-level mesh includes one single element that covers the whole calculation domain. Next levels are created by splitting the previous level elements into 4 new elements. Therefore, level 1 will have 4 elements, level 2 will have 16 elements, and so forth. Generally, the n-level mesh will have 22nelements. Due to the hierarchical structure of the Cartesian grid, it is trivial to calculate geometrical properties of each element like coordinates, topology or size. Then, it is not mandatory to store all this information, thus allowing for a considerable reduction of RAM memory usage. Figure 1.3 shows an example of the hierarchical mesh structure in cgFEM. The calculation domain is initially superimposed on the Cartesian grid pile (Fig. 1.3a). Then the approximation mesh that cgFEM will use for solving 4 Jos´e Manuel Navarro Jim´enez 1.1. cgFEM (a) Cartesian grid pile. k ij (b) Analysis mesh. ◦nodes with multipoint constrais for C0continuity. Figure 1.3: Difference between the Cartesian grids pile and the analysis mesh. the problem is a combination of elements from each of the Cartesian grid levels so that the final mesh (also known as calculation mesh) includes the whole calculation domain without overlapping elements (Fig. 1.3b). All analyses start with a uniform mesh. There are three different refinement options available in cgFEM. The first option is a geometrical refinement that adapts the mesh depending on the domain’s curvature. There is also a hadaptive refinement based on the numerical solution’s precision in each part of the domain evaluated by means of error estimation techniques. The last option is onlyfor the analysis of a medical image. The refinement is then performed based on statistical values related to the gray-level distribution of the image’s pixels within each element [2]. It is worth to highlight that when different Cartesian grids are combined, there are some nodes belonging to the smaller elements that are located on the side Optimization of a FEM code. Usage of GPUs in parallel computing. 5 1. Introduction of other bigger element (see Fig. 1.3b). These nodes are called hanging nodes. In order to ensure C0continuity along these sides, a relation between hanging nodes’ displacements and displacements of the nodes located on the same side of the adjacent element has to be added to the equation system. These constraining equations are called Multi-Point Constrains (MPC), thus, this hanging nodes are also called MPC nodes. cgFEM has been used by the research group in the Department as the basic FEM code for developing new features like a displacement-based error estimator (SPR-CD, [7]), an error estimator based on quantities of interest [8] or a new efficient nested solver [11]. cgFEM is also able to directly create FEM models using medical images and mix them with geometrical entities that simulate surgical implants [2], [12]. According to [1], a study at Sandia National Laboratories (USA) revealed that the generation of the finite element numerical model, this is, creating a geometry suitable for a FEM analysis and generating a proper calculation mesh, uses 80% of the total time spent on the analysis, whereas only 20% is devoted to the numerical analysis. The Cartesian elements together with the hierarchical structure make cgFEM a highly efficient methodology in terms of computational cost, as generating h-adapted meshes even for complex geometries is a simple task in this case. 1.2 FEAVox A 2D FEM program is of little use for industrial applications, as almost all real problems are 3D problems. Therefore, after several years acquiring experience and knowledge developing the 2D code cgFEM, the Department has decided to take the next step by implementing a new FEM code in 3D named FEAVox. 6 Jos´e Manuel Navarro Jim´enez 1.2. FEAVox The aim is to use all this know-how to implement in 3D all the features existing in cgFEM. It is thought that the computational cost of the analysis made in cgFEM can be reduced by optimizing the code. As the chosen programming language, MATLABr, is not a compiled language, one trivial optimization decision could be translating all the code to a compiled language such as C or C++. However, this change is not likely to happen in the short term due to two main reasons. First, MATLABris an excellent programming language for the fast implementation of new algorithms. There are plenty of very efficient high level tools for numerical analysis that allows the programmer to concentrate in the algorithm itself rather than in the coding formalisms of other programming languages. Second, most of the students that helped in the development of cgFEM have a good background in mechanical engineering, extremely useful for the development of the code, but a very limited experience on C, C++ or FORTRAN. In this Thesis, MATLABrspecial features for code performance improvement are studied and then applied to cgFEM code. Among all optimization techniques available it is worth to outline the usage of Graphics Processing Units (GPU) for parallel computation, as it is a relatively new technique with lots of possibilities in the field of numerical computation. The research made in this Thesis is intended to provide the Department with the technical know-how on GPU computing as well as other optimization procedures for MATLABrprogramming language. As the new 3D code implementation is currently in progress, the conclusions obtained in this Thesis will set the programming basis for an optimal implementation of FEAVox in terms of computational cost. Optimization of a FEM code. Usage of GPUs in parallel computing. 7 Chapter 2 Optimizing code using MATLABr The performance enhancement can be achieved by acting on different levels. All computer applications have two main areas in which one can make modifications, hardware and software. It is trivial that an upgrade on the workstation’s components can produce a performance improvement. A faster CPU provides faster calculations and more RAM memory allows to perform bigger analysis in terms of DOF avoiding the use of the hard disk drive. The first improvement regarding the software is the programming language. MATLABrlanguage needs no compiler, as it works as an interpreted language. This is, each time a code line is executed, MATLABr“translates” the line into machine code and then the instruction is executed. This particular feature of interpreted languages make them slower than other compiled codes like C, C++ or FORTRAN, specially when programs grow bigger and more complex. For this reason, MATLABris often used to create simple programs that solve 9 2. Optimizing code using MATLABr small problems, and when it comes to High Performance Computing (HPC) compiled programming languages like C++ are used. As said in the MathWorksroverview web page [4], “MATLABris a high-level language and interactive environment for numerical computation, visualization, and programming.”. MATLABris able to deal with matrices and arrays and operate with them in a highly effective way (actually the name stands for Matrix Laboratory). This feature makes this language very suitable for numerical computation. Actually, the usage of MATLABris widespread among diverse engineering and science fields such as mechanical engineering, biology, signal and image processing, control systems and so on. Despite having that handicap in comparison with complied languages, users can reach a reasonable performance of MATLABrcode by taking advantage of the special features like high efficiency in handling arrays and parallel computation. In this chapter a series of techniques and optimization procedures are given in order to improve any MATLABr-based program’s performance. It is worth to outline that the first way to improve the efficiency of a computer program should be changing the main “philosophy” on which the code is based. For example, the usage of Cartesian grids in FEM represents an important philosophy change with respect to the classical FEM implementation. This different point of view led to the construction of a highly effective data structure that provides with multiple possibilities to enhance the code’s performance. After the programming language and the main “philosophy” are established it is important to check if the algorithms used to accomplish the function’s objectives are optimal or could be improved. This will be explained in section 2.1. Once the proper algorithm is selected it is time to take advantage of the chosen programming language. In this case, the benefits of “vectorizing” with 10 Jos´e Manuel Navarro Jim´enez 2.1. Algorithm change MATLABrare explained in section 2.2. The last optimizing technique that this Thesis covers is a mix between a hardware and a software improvement, this is, the usage of GPU for parallel computation. Finally, section 2.4 shows a basic example comparing all optimization techniques. 2.1 Algorithm change Usually when working with big complex programs it is not trivial to find an algorithm that fits current function’s purpose. In addition, it is very common that the first algorithm designed is inefficient, so it has to be improved in a second step. And even when the algorithm has been optimized one could still find a different algorithm that could be much more efficient than the first one. An example of algorithm change that leads to a considerable performance improvement is shown in [10]. The first objective of that project was to improve the refinement routine of cgFEM, as it was the most important bottleneck in the program (the refinement process consumed up to 85% of the whole computation time in some large problems). The old refinement procedure is shown in Algorithm 2.1.1. The input variable, SubN, contains the number of all the elements to refine and the number of times that it has to be split. Split2D algorithm only splits one element at a time, so the algorithm has to be run each time for each element times the number of times to be split. Optimization of a FEM code. Usage of GPUs in parallel computing. 11 2. Optimizing code using MATLABr An h-adaptive procedure was performed with both linear and quadratic elements in order to reach fine meshes. Finest meshes reached 3.75 and 3.45 million of degrees of freedom respectively for linear and quadratic cases. The results are shown in Figure 2.5. It is clear that the computational cost has been drastically reduced, specially in the linear case. Figure 2.5: Performance test of the new refinement routine. 2.2 Vectorization As it has been said before, MATLABris able to deal with matrices and arrays and operate with them in a highly effective way. This statement involves not only typical mathematical operations like additions, multiplications or evaluation of trigonometric functions, but also the reading and writing of elements inside an array or a matrix. 18 Jos´e Manuel Navarro Jim´enez 2.2. Vectorization For example, let Abe a random n×mmatrix. The standard procedure to read an entire column of that matrix in C should be a for loop through all the rows of the desired column. However, MATLABrhas the colon operator (:) so you can read an entire column of a given matrix by just typing A[:,Column]. Also if you want to read several columns you can substitute the number in the Column variable for an array with all the columns wanted. This particular way of accessing elements in an array is called Matrix Indexing. Further information about different types of matrix indexing can be found in MATLABrDocumentation Center [4]. By changing the code above to read matrix data we are vectorizing the code. Quoting [4]: “The process of revising loop-based, scalar-oriented code to use MATLABrmatrix and vector operations is called vectorization”. Some of the main benefits of vectorizing are the code becoming easier to understand, as it is shorter, as well as the fact that vectorized code in MATLABrlanguage is frequently faster than a code with loops. Vectorizing is not only an improvement technique but a whole programming philosophy while coding in MATLABrlanguage. This means that it is needed a change of mind for a programmer that starts using this language in order to reach high code performance, but after that learning process vectorizing should be like one more rule to follow while programming, like the language’s syntax rules. The following sections explain different ways of vectorization with general examples in order to have a better understanding of this technique. 2.2.1 Modify some values of an array. Taking a look again at the second step of algorithms 2.1.1 & 2.1.2 the only difference is that there is no for loop in the new algorithm. This is because Optimization of a FEM code. Usage of GPUs in parallel computing. 19 2. Optimizing code using MATLABr the operation of writing the value 1 on multiple positions of the vector Active can be done in one single step by using matrix indexation. Also remember that the old algorithm worked for a unique element and one split at a time, while the new algorithm splits once all elements that require refinement. Thus, the variable Elements is not an scalar but an array, so the same matrix indexation is performed. 2.2.2 Transform scalar operations’ loop into array operations. Here some general examples are presented in order to give a full sight of vectorization possibilities regarding scalar operations. Chapter 3 will show more practical examples, taking into account both Finite Element Method and cgFEM code distinctive features. Parallel dot product of arrays The first and easiest way of vectorizing scalar operations can be found in the dot product of an array. Let a,bbe random vectors with the same number of components. The resulting dot product of these two vectors (vector c) fulfills ci=ai×bi. This can be easily performed by using MATLABr’s array operations, this is, introducing a period (.) before the operators ∗,/or ∧. In this example, the code should be something like c=a.*b. The only requirement to perform these array operation is that both arrays must have the same dimensions. This means that aand b can be N−dimension matrices. The resulting variable will be of the dimension and size of aand b. Scalar operations between arrays with different dimensions This is another common situation when performing numerical computations. For 20 Jos´e Manuel Navarro Jim´enez 2.2. Vectorization example, let {x1,x2...xn}be column vectors with the same number of components, and {λ1, λ2...λn}different scalars. Finally, let {y1,y2...yn}be vectors resulting from the following operation: yi=xiλii= 1,2, ...n (2.1) This operation should be performed with a loop through all vectors, but there is a faster way to achieve the same results, specially if the number of elements grows higher. The first step is to concatenate all vectors and scalars in order to apply vectorization: Y= [y1,y2...yn]X= [x1,x2...xn]λ= [λ1, λ2...λn] (2.2) In this case an array operation would not work since both arrays Xand λhave different number of dimensions, but there is a MATLABrbuilt-in function that can solve this problem, bsxfun. This function performs array operations between different size matrices provided that only one dimension has a different size. The syntax to perform this operation should be Y=bsxfun(@times,X,λ). It can be noticed that when using bsxfun the desired element-wise operation must be introduced as a function handle, that has to be a MATLABrbuilt-in function. A list of the available functions is shown in Table 2.2. To perform more complex, element-wise operations between arrays we can use arrayfun. This function acts like bsxfun but it works with any function handle that contains a set of scalar operations (like a series of sums and multiplications). Optimization of a FEM code. Usage of GPUs in parallel computing. 21 2. Optimizing code using MATLABr @plus @atan2d @minus @hypot @times @eq @rdivide @ne @ldivide @lt @power @le @max @gt @min @ge @rem @and @mod @or @atan2 @xor Table 2.2: MATLABrbuilt-in functions available for bsxfun, [4] Matrix-vector multiplications The last vectorization case concerns multiplications between a common matrix and different vectors. This situation occurs often in FEM as it will be explained in Chapter 3. Take for example the relationship between stress and strain by means of the elasticity theory in the linear elasticity case: σ=D(ϵ−ϵ0) + σ0(2.3) where: ϵ={ϵxϵyϵzγxy γyz γzx}T:strain field. D: material properties matrix. ϵ0,σ0:initial strain and stress. if initial strain and stress are not considered, assuming that the strain is already calculated at all points, the stress calculation at each point pbecomes a simple multiplication: σp=Dpϵp(2.4) 22 Jos´e Manuel Navarro Jim´enez 2.2. Vectorization This operation would be normally worked out with a loop through points performing that multiplication. However, one can code a for loop for the different materials (different mechanical properties, means different Dmatrices). The number of materials is always much lower than the number of points and the for loop will result in a much better performance in terms of computation time. As in the previous example, the first step is to concatenate arrays in order to perform the vectorization. The stress of all points with the common material iis calculated as follows: σi= [σp1 i, ..., σpn i]ϵi= [ϵp1 i, ..., ϵpn i] σi=Diϵii= 1, ..., NMaterials (2.5) where σicontains the stress evaluated at all points that have material iproperties. Resolution of multiple systems of equations The previous procedure can be applied when it comes to solving linear systems of equations that have a common coefficient matrix. This occurs when solving the FE equation system with multiple load cases and some other cases explained in Chapter 3. The vectorized FE equation system considering all load cases has exactly the same shape of the original, this is: KU =F(2.6) Optimization of a FEM code. Usage of GPUs in parallel computing. 23 2. Optimizing code using MATLABr However, in this case Fis not a vector but a matrix that contains each different load case in each column. MATLABr’s solving command (\) has a better performance solving this “vectorized equation system” than if all different equation systems were solved in a for loop where each iteration had a different load case. It is easy to understand why it is more efficient vectorizing equation systems: when the system is vectorized the coefficient matrix has to be factorized only once, while an inverse substitution is performed for each load case. It is widely known that factorizing the coefficient matrix is the hardest step while solving an equation system in terms of computational cost, specially when equation systems have a high amount of variables, so reducing the number of times the matrix has to be factorized becomes in a reduction of computing time. 2.3 Parallel computation through GPU 2.3.1 General-Purpose Graphics Processing Unit At present, Graphics Processing Units (GPUs) are used not only for graphical rendering, but also as a co-processing device for massive computations in different fields such as mechanical computation, medical imaging or financial analysis. This new generation of devices are called General-purpose GPU, or GPGPU. Almost all personal computers are provided with a GPU. These devices were originally created for 3D rendering, specially for video-games. As the gaming industry grew up, graphic rendering became more complex and there was a huge development in GPUs. In order to achieve more complex visual effects, 24 Jos´e Manuel Navarro Jim´enez 2.3. Parallel computation through GPU the first application programming interfaces (APIs) for GPUs, like OpenGL or Direct3D (inside DirectX), were deployed. However, these APIs were still graphics-oriented, and it was very hard for programmers to develop software for general-purpose computations. NVIDIArwas the first company that introduced a specific technology for General-purpose computing with GPUs, it is called CUDA (compute unified device architecture). CUDA was originally designed to work in C language, but currently there are other programming languages that allow GPU computing through NVIDIArCUDA, such as C++ or MATLABr. The main competitor in GPU sector, AMD (former ATI), also developed a lower level API for GPUPU called Stream SDK. This API was not successful at all and finally AMD opted joining the open source project OpenCL. NVIDIArGPUs can also work with OpenCL, but a comparison made in paper [5] shows that CUDA is slightly more effective than OpenCL when using NVIDIArhardware. Despite being a registered technology that only works with the same company’s GPU devices, CUDA has become a standard when using GPUPU applied to scientific computation. A program developed with CUDA is usually divided into two parts. The CPU handles with the data management, memory transfers between different devices and sets the GPU execution settings, whereas the GPU acts as a coprocessing device performing massive parallel computations through special functions called kernels. The main idea behind GPGPU is that instead of having a handful of powerful processing units, like modern CPUs which have between 4-8 cores, GPU devices are provided with a huge amount of small processors (between one and two thousand in nowadays’ devices) that are only able to execute the same instructions all at a time. This special feature makes GPU devices very suit- Optimization of a FEM code. Usage of GPUs in parallel computing. 25 2. Optimizing code using MATLABr able for all kinds of parallel computations, like adding a constant number to all the components of a vector. Figure 2.6 shows the hardware structure of a CUDA GPU device. Each processing unit inside a GPU has some memory slots exclusively associated to it (registers). A processing unit together with its corresponding registers is called a thread. Threads can also be organized in blocks. When any code is executed on a GPU device, a copy of this code is sent to each block, and all threads run all the instructions contained in the code at the same time. This means that if there are any conditional statements in the code (like if or while), threads that do not fulfill the statement will not continue executing the next instructions until all other threads have finished running the instructions given inside the conditional statement. Block Thread Figure 2.6: GPU grid configuration. The configuration of threads and blocks define the computation grid. These grid has to be configured for each kernel run, and the performance of the program can be improved by choosing a near-optimal setting for each kernel [6]. 26 Jos´e Manuel Navarro Jim´enez 2.3. Parallel computation through GPU CPUs have a hierarchical memory structure composed by registers, cache memory, RAM memory and hard drives. Similarly to the CPU memory structure, GPUs have the following hierarchical memory structure: Registers: Each thread can only access its own registers. It is a small but fast memory. Shared memory: All the threads in the same block have a shared memory so that they can interact between them. Constant memory: Read-only, fast memory that all threads of the GPU can access. Texture memory: Special memory related to graphics rendering structure. Global memory: All threads of the GPU can access this slots, but the read-write speed is rather slow compared to the previous memory types. As the read and write speed of each type of memory is different, having an optimal memory management between all types can be critical in terms of computing time. SHARED MEMORY CONSTANT MEMORY GLOBAL MEMORY BLOCK 1 BLOCK 2 GRID REGISTERS THREAD 1 THREAD 2 THREAD 3 REGISTERS REGISTERS REGISTERS THREAD 1 THREAD 2 THREAD 3 REGISTERS REGISTERS SHARED MEMORY Figure 2.7: Hierarchical memory structure of a GPU. Optimization of a FEM code. Usage of GPUs in parallel computing. 27 2. Optimizing code using MATLABr Regarding strain energy, a more detailed explanation about its calculation will be given in Chapter 3, and here we will perform a simple version with algebraic operations similar to those used in these kind of calculations. To sum up, strain energy at elements is calculated as a numerical integration of the strain energy inside the element. Here we will disregard the numerical integration features (weights and jacobian matrix) because including them should be only a matter of repeating the same kind of operations. Instead, we will consider this equation to calculate the strain energy-like value at each element that will be called the accumulative value Ee: Ee= nIP ∑ i σe iϵe i(2.9) where, in these code example: Ee:1×Number of elements. Accumulative value Eat each element. nIP:Number of integration points per element. Constant in this example. σe:Number of elements ×(Number of integration points × 3). Each row has the stress at all integration points of each element. ϵe:Number of elements ×(Number of integration points ×3). Each row has the strain at all integration points of each element. 34 Jos´e Manuel Navarro Jim´enez 2.4. Code optimization example The example is divided into three parts: the first one contains which is supposed to be the original piece of code to improve, then in the second part the code is improved by means of vectorization, and finally in the third part GPU computation is brought in to go a step further in the optimization process. After those three parts there are some results showing the performance comparison between different versions. Optimization of a FEM code. Usage of GPUs in parallel computing. 35 2. Optimizing code using MATLABr 2.4.1 Original Code This is the initial function that performs the established calculations. The code is shown in Listing 2.1. The structure is very similar to a C-code function. Initial variables simulate the available data in the program and are created as random variables. Then both output variables are pre-allocated in memory, and finally calculations are performed in a loop through elements and integration points inside elements. 36 Jos´e Manuel Navarro Jim´enez 2.4. Code optimization example Listing 2.1: Optimization example. Original code. 1% I n i t i a l data DOFperNode = 2; 3Comp = 3; IntegrPts = 4; 5NodesPerElem = 4; NumElements = 1000; % This i s the parameter t o sweep 7D = rand (Comp ,Comp , NumElements ); B = rand (Comp , NodesPerElem * DOFperNode , IntegrPts ); 9u = rand ( NodesPerElem * DOFperNode , NumElements ); epsilon = rand ( NodesPerElem *( DOFperNode +1) , NumElements ); 11 % Output v a r i a b l e s 13 sigma1 = zeros ( NumElements , IntegrPts * Comp ); E_def = zeros(NumElements ,1) ; 15 % C a l c u l a t i o n . Element lo op 17 for iElement = 1: NumElements uElem = u(: , iElement ); 19 DElem = D(: ,: , iElement ); epsilonElem = epsilon (: , iElement ); 21 for iPoint = 1: IntegrPts % S t r e s s 23 stress = DElem *B (: ,: , iPoint )* uElem ; sigma1 ( iElement ,( iPoint -1) * Comp +1: iPoint * Comp ) = stress; 25 % Acc umul ativ e v a l u e E E_def ( iElement ) = E_def ( iElement ) +... 27 sum (stress ’* epsilonElem (( iPoint -1) *Comp +1: iPoint * Comp)); end 29 end Optimization of a FEM code. Usage of GPUs in parallel computing. 37 2. Optimizing code using MATLABr 2.4.2 CPU optimized code This optimized version is focused on vectorizing all possible operations to get rid of as most single operations inside loops as possible. The vectorized code is shown in Listing 2.2. The most clear example is with the accumulative value (line 28). The accumulative value at each point is calculated with a single scalar product, so performing a dot product with stress and strain data matrices we vectorize this operation. The next step is to accumulate the values at each element, therefore we perform an addition of the point’s values matrix through the first dimension, so we get a vector that has the total accumulative value at each element. Stress calculation cannot be fully vectorized because it involves matrix-vector multiplications without a common matrix (Dmatrices were set as random for each element with this purpose), but there is still some work that can be done. The stress is a result of the multiplication of two matrices and one vector. If we use the whole matrix uinstead of the corresponding column for each element we will perform all operations for all elements at a time. Moreover we said that Bmatrices were the same for each local integration point, so we can make a previous loop (lines 17-19) where we compute the product Bu for all points, and then the only operation performed in the element’s loop would be a matrix multiplication. The product matrices Bu are stored as a 3D matrix where, after a permutation (line 20), each page has the matrices corresponding to each element, just like matrix D. 38 Jos´e Manuel Navarro Jim´enez 2.4. Code optimization example Listing 2.2: Optimization example. CPU optimized code. 1% I n i t i a l data . Same as in th e o r i g i n a l code DOFperNode = 2; 3Comp = 3; IntegrPts = 4; 5NodesPerElem = 4; NumElements = 1000; % This i s the parameter t o sweep 7D = rand (Comp ,Comp , NumElements ); B = rand (Comp , NodesPerElem * DOFperNode , IntegrPts ); 9u = rand ( NodesPerElem * DOFperNode , NumElements ); epsilon = rand ( NodesPerElem *( DOFperNode +1) , NumElements ); 11 % Output v a r i a b l e s . E def2 memory pre−a l l o c a t i o n i s not needed anymore . 13 sigma2 = zeros ( NumElements , IntegrPts * Comp ); 15 % Stress , s te p 1 . Loop t hro ugh d i f f e r e n t l o c a l i n t e g r a t i o n points . B_u = zeros (Comp , NumElements , IntegrPts ); 17 for iPoint = 1: IntegrPts B_u (: ,: , iPoint ) = B (: ,: , iPoint )*u; 19 end B_u = permute (B_u ,[1 3 2]) ; 21 % S tr e ss , s t e p 2 . Loop t hr ough e le me nt s . for iElement = 1: NumElements 23 DBu = D (: ,: , iElement )* B_u (: ,: , iElement ); sigma2 ( iElement ,:) = DBu (:) ; 25 end 27 % Acc umul ativ e v a l u e E. V e c t o r iz e d o p e r a t i o n E_def2 = sum (sigma2 ’.* epsilon ,1) ’; Optimization of a FEM code. Usage of GPUs in parallel computing. 39 2. Optimizing code using MATLABr 2.4.3 GPU optimized code The last optimization step includes GPU computation in the code. As it has been said, it is very easy to introduce GPU in MATLABrlanguage, since there are only a few changes to make. First of all, the variables are now initialized directly in the GPU device, by adding gpuArray to the functions rand and zeros. In case the variables already exist in the CPU the transfer would be as easy as typing GPUVariable=gpuArray(CPUVariable). The same thing happens when the calculations are finished, this is, we need to transfer the data back into the CPU using the command gather(). Listing 2.3 shows this last optimized code. Just by performing the same calculations on the GPU we could have some gain. For example, the calculation of the accumulative value (l. 24) is exactly the same line as in listing 2.2, and its computing time is lower. But we can also add some important features in order to gain efficiency, like multiplying matrices in parallel. Using pagefun we multiply all matrices Band u, and then all element multiplication of D×Bu, so we just get rid of both loops that were still in the CPU-optimized code. 40 Jos´e Manuel Navarro Jim´enez 2.4. Code optimization example Listing 2.3: Optimization example. GPU optimized code. % I n i t i a l data . V a r i a b l e s are now c r e a t e d in t h e GPU memory 2DOFperNode = 2; Comp = 3; 4IntegrPts = 4; NodesPerElem = 4; 6NumElements = 1000; % This i s the parameter t o sweep B = gpuArray . rand (Comp , NodesPerElem * DOFperNode , IntegrPts ); 8u = gpuArray . rand ( NodesPerElem * DOFperNode , NumElements ); epsilon = gpuArray . rand ( NodesPerElem *( DOFperNode +1) , NumElements); 10 D = gpuArray . rand (Comp ,Comp , NumElements ); 12 % Output v a r i a b l e s sigma3 = gpuArray . zeros ( IntegrPts * Comp , NumElements ); 14 % Stress , s t ep 1. Loop s u b s t i t u t e d by pagefun . 16 B_u = pagefun ( @mtimes ,B ,u); B_u = permute (B_u ,[1 3 2]) ; 18 % Stress , s t ep 2. Loop s u b s t i t u t e d by pagefun . DBu = pagefun ( @mtimes ,D ,B_u ); 20 sigma3 (:) = DBu; % Transfer s t r e s s data from GPU to CPU memory 22 cpu_sigma = gather ( sigma3 ’) ; 24 % Accumulative v alue E a t each element and data t r a n s f e r to CPU E_def3 = gather ( sum ( sigma3 .* epsilon ,1) ’); Optimization of a FEM code. Usage of GPUs in parallel computing. 41 2. Optimizing code using MATLABr 2.4.4 Performance test The performance comparison test consisted in executing all three different codes with an increasing number of elements. Computing time of each code version is measured using MATLABr’s tic and toc functions. In the GPU case the function wait(gpuDevice) was used in order to avoid stopping the CPU timer while the GPU device is still performing operations. In addition, GPU code was executed and measured three times for each parameter value, and the mean value between those three times is used to calculate the speed-up ratio. CPU and GPU speed-up ratio over the original routine are evaluated as follows: RatioCP U =TimeOriginal TimeCP U RatioGP U =TimeOriginal TimeGP U (2.10) The test can be divided into two parts: the first one involves low number of elements (from 103to 106), and the second part goes from 106to 2 ×107 elements. During the first part of the test the GPU device’s memory is not saturated and all the data can be processed at once. As we reach 5 million elements the GPU’s memory is not big enough to perform all the calculations. Therefore, as said in section 2.3, some memory management work has to be done in order to split all data into smaller pieces, so that each data block can be processed by the device. Figures 2.9 and 2.10 show the results of this test. The first highlighting result is that vectorized code has an almost constant speed-up ratio, between 7.66x and 8x. The independence of the speed-up with the number of elements in the arrays shows that this computing improvement has been achieved because MATLABris capable of dealing with array operations in a more efficient way than performing for loops with scalar operations, as said before. 42 Jos´e Manuel Navarro Jim´enez 2.4. Code optimization example Regarding the GPU, in the first part of the test (Figure 2.9) the speed-up rapidly escalates with the number of elements, and starting from around 3×105 the speed-up ratio varies between 90x and 100x. However in the GPU case there are some considerable oscillations in the speed-up ratio as the number of elements increases. These variations can be produced due to a non-optimal setting of the GPU grid of blocks and threads. As these settings cannot be modified or read when using parallel computing features included in MATLABr there is no way neither to find a near-optimal setting of the grid nor to demonstrate this hypothesis. Nevertheless, this should be the most probable cause of the oscillation because as it is said in [6] “gridification strongly impacts the performance of algorithms”. 0246810 x 105 0 20 40 60 80 100 120 Number of elements Speed−up ratio GPU speed−up CPU speed−up Figure 2.9: Performance test, part 1. From 103to 106elements Optimization of a FEM code. Usage of GPUs in parallel computing. 43 3. Finite Element Method optimization are applied and the error of the solution is estimated in the post-processing block. With the information of estimated error at each element, the refinement routine generates a new calculation mesh in order to solve a new problem, so the block sequence starts again from the intersection of the geometry with the new mesh. FEAVox, the 3D version of cgFEM is also capable of creating h-adapted meshes from CAT scans such as cgFEM does. Figure 3.1 shows a 3D mesh obtained from a dental computed tomography (CT) scan. The whole mesh contains near 3 million elements. Thanks to the new refinement algorithm that has been adapted to the 3D code this procedure took about two minutes. Figure 3.1: Cross section of a 3D mesh obtained from a dental CT scan. 50 Jos´e Manuel Navarro Jim´enez 3.2. FEM problem resolution 3.2 FEM problem resolution Once the calculation mesh is created it is time to formulate and solve the FEM system of equations, which was already presented in equation 2.6: KU =F(3.1) This global system of equations is created from the assembly of element matrices ke, that depend on material property and the geometry of the domain, and element vectors fewhich depend on the boundary conditions. The optimization of this block has been focused on the creation of the element stiffness matrices, although some minor improvements were made in the integration of the boundary conditions to create vectors fe. Although minor changes regarding vectorization have been made in the routine that creates element vectors fe, this section will focus on the improvement of the element stiffness matrices integration. 3.2.1 Stiffness matrix integration. The element stiffness matrices is defined as: ke=∫Ae BTDBdA (3.2) Optimization of a FEM code. Usage of GPUs in parallel computing. 51 3. Finite Element Method optimization The 0-level mesh element in cgFEM is called the reference element. All elements in the Cartesian grid pile of meshes are geometrically similar, they are all square elements, whose only difference is their size. Thus, it is possible to set some relation between the reference element’s characteristics, such as the element stiffness matrix, Jacobian matrix, etc. R´odenas et al. defined in [13] 5 hierarchical properties that relate the element matrices of geometrically similar elements. The parameter relating the elements is the relative elements size, ς. In the cgFEM framework ς= 2−L, being Lthe level of the element. Then, we could easily relate all the following properties with those of the reference element, indicated with the sub-index 0. •Jacobian matrix:J=ςJ0. •Inverse Jacobian:J−1=1 ςJ−1 0. •Jacobian:|J|=ςD|J|0, where Dis the problem dimension (2 for 2D). •Shape function derivatives matrix:B=1 ςB0. •Stiffness matrix:k=ςD−2k0, for Dbeing constant. Therefore, in cgFEM, the element stiffness matrix is equal for elements fully located into the domain that have the same material. Thus, only one stiffness matrix is calculated for all those elements. However, there are multiple materials within the elements of a medical imagebased analysis, so all the element stiffness matrices have to be calculated one 52 Jos´e Manuel Navarro Jim´enez 3.2. FEM problem resolution by one. The numerical integration that takes place to calculate this matrix is the following one: ke= NIP ∑ i=1 BT(ξi, ηi)D(ξi, ηi)B(ξi, ηi)|J(ξi, ηi)|ωi(3.3) where: NIP:Number of integration points. In this case the pixels of the image will be considered integration points as well. (ξi, ηi):Local coordinates of the integration points expressed in the local reference system of the element. D(ξi, ηi):Material properties associated to each integration point. As the one integration point will be associated to each pixel in the image, the material properties of each integration point will correspond to those of the gray level of the corresponding pixel. |J(ξi, ηi)|:The determinant of the jacobian matrix evaluated at (ξi, ηi). ωi:Weights associated to the integration points, depending on the integration quadrature used. A Riemann integration will be used in this case, so all weights will be the same within an element. The bounding box of the initial mesh of a medical image analysis is calculated so that all mesh levels have an integer number of pixels inside, until the mesh Optimization of a FEM code. Usage of GPUs in parallel computing. 53 3. Finite Element Method optimization level that has one pixel per element. This is made by adding “black” pixels (meaning pixels with null material properties) until the size of the image contains N×Npixels, being Na power of two. The size of the pixels is constant for all the image, so it is known that NIP =N×N 22p, being pthe mesh level of the element. If elements of the same level contain the same amount of integration points, located at the same local coordinates, then B(ξi, ηi), |J(ξi, ηi)|and ωiwill be common for all elements of the same level. Therefore, it seems that an efficient way of calculating the stiffness matrices in a medical image analysis would be to use a loop through different mesh levels and a second loop inside through local integration points. These two loops do not imply an increase in the computational cost as the number of elements rises, because the number of iterations is smaller (the more elements in the mesh, the less integration points/pixels within each element). The only way to avoid a third loop through elements is using GPUs, because the operations for the stiffness matrix calculation include two matrix multiplications. The evaluation of the material properties matrices (D(ξi, ηi)) for each integration point is also performed in parallel with GPU. If the workstation does not have a GPU device, a third loop will be run calculating the matrix for each element, and Dmatrices will be gathered through a vectorized procedure. Section 4.3 shows the results of both changes. The improvement in the integration of the stiffness matrices for medical image analyses has allowed to rapidly implement and test different integration methods shown in paper [3]. 54 Jos´e Manuel Navarro Jim´enez 3.2. FEM problem resolution Integration data structure In cgFEM, all the information of the stiffness matrix calculation (stiffness matrix, local coordinates of integration points, Bmatrices of each integration point, material associated to each integration point) is stored in a struct type variable called MatK. Table 3.1 shows how the integration data is stored for each element in cgFEM. Field Type Description Ke Float Element stiffness matrix IntegrType Int Flag that indicates if it is an internal (0) or boundary element (1) OrigLev Int Level of the element where the integration of kehas been performed BPtG Float Stores matrix B = LN evaluated at each integration point PsiEtaG Float Local coordinates of the integration points in the element AreaGauss Float Area associated to each integration point Triangs Float Global coordinates of the triangulation vertices. Only for boundary elements PsiEtaVert Float Local coordinates of the triangulation vertices. Only for boundary elements MaterialTr Float Material associated to each integration point Table 3.1: Information stored for each element. The structure shown in table 3.1 is repeated for each element stiffness matrix that is calculated during the analysis. Therefore, MatK is not only a struct type variable, but a vector of struct variables. The information related to the reference element of each different material existing in the model is stored in the first positions of this structure. Therefore, all internal elements will point to the corresponding reference element information, saving a high amount of repeated data. However, each boundary element has its own data stored in MatK. As the vector grows higher (when the number of boundary elements increases) the time spent accessing and writing values of MatK becomes the most time-consuming task in the stiffness matrix creation. The improvement of the stiffness matrix integration when analyzing medical images stores the calculated data in an auxiliary variable and then transfers Optimization of a FEM code. Usage of GPUs in parallel computing. 55 3. Finite Element Method optimization the data of multiple elements to the MatK variable at the same time using vectorization techniques, thus reducing the number of accesses to the struct variable. A vector of struct type variables is difficult to manipulate. Gathering all the values of a given field and storing new data are complex, time-consuming tasks. In addition, some of the stored data in MatK (mainly the local coordinates, the material ID and the Bmatrices) are necessary to make some calculations that could be easily vectorized if the data were stored in another type of variable. Taking this features into account, the data structure of the integration has been changed for the FEAVox code. MatK variable has been split into two different matrices: KMatrix and IntegrationPoints. The first matrix has the element stiffness matrix for all elements stored as columns. This matrix is only used for the assembly of the global stiffness matrix K, so the storage of the element matrices as columns may also help with the vectorization of the assembly task. The second variable, IntegrationPoints, is a standard matrix that contains in each row all the information of all the integration points, such as the element that the point belongs to, global and local coordinates, associated material, integration sub-domain in case of boundary elements, and results like stress, displacements and energy norms evaluated at each point. This modification completely changes the calculating procedure for any magnitude. Instead of having an iterative loop through elements and calculating the desired magnitude, the operation can be performed in a vectorized way (and furthermore, using GPU computation) for all the integration points in the calculation mesh, regardless of the element that they belong to. 56 Jos´e Manuel Navarro Jim´enez 3.3. FEM solution post-processing 3.2.2 System of equations’ resolution The resolution of the system of equations is usually one of the most expensive procedures in terms of computational cost, specially when it comes to 3D problems. Although MATLABr’s command “\” can be computed with GPU variables, MATLABrstill cannot handle with sparse variables in the GPU, so at the moment there is no chance to solve the system of equations with the GPU device, as the global stiffness matrix Kis a sparse matrix. Preliminary tests in FEAVox show that the resolution of the 3D system of equations will have a high computational cost when the number of degrees of freedom increase, so implementing iterative solving procedures using GPU parallel computation in FEAVox is one of the future research lines. 3.3 FEM solution post-processing As the FEM formulation used in cgFEM and FEAVox is based on displacements, the solution obtained after solving the system of equations is the displacement field of the domain. However, this results are usually less interesting for the industry than the stress field. It is also important to evaluate the error of the current solution, as the FEM solution is always an approximation of the real solution. All these tasks are suitable for vectorization and for the introduction of GPU computation, as there are simple operations performed on large amounts of data. Optimization of a FEM code. Usage of GPUs in parallel computing. 57 3. Finite Element Method optimization 3.3.1 Stress calculation Earlier in section 2.4 an optimization example of a code that calculated stresses and an accumulative value was given. Equation 2.8 , which is repeated here for convenience showed how stresses could be calculated at integration points: σ=DBue It has been said before that in cgFEM there is a relationship between the reference element’s characteristics and the internal element’s ones. Regarding the stress calculations, the relationship between the shape function derivatives matrix is B=1 ςB0, where ςis a value related to the element’s level. Then, the stress value for the integration points of an internal element is: σe=DB 1 ςeue(3.4) The displacements and scaling factor of all internal elements can be multiplied using bsxfun as it was shown in section 2.2.2. Then, Dand Bmatrices are common for all elements, so the stress at all integration points of all internal elements is calculated by vectorizing the matrix-vector multiplication, as it was also shown in section 2.2.2. When it comes to medical image analyses Bmatrices are common but each integration point has a different Dmatrix. In this case, the stress at all integration points can be calculated at once through GPU parallel computing. If the GPU is not available in the workstation, a loop through all integration 58 Jos´e Manuel Navarro Jim´enez 3.3. FEM solution post-processing points has to be performed, just like in the calculation of element stiffness matrices. Stress calculation is already vectorized in FEAVox for internal elements. However, boundary elements have different number of integration points so a for loop is needed for those elements. GPU computation has been applied to compute all boundary elements at once using pagefun. A test problem with up to 150000 boundary integration points showed a speed-up of 18x in this task. 3.3.2 Error estimation After the FE solution of the first analysis mesh has been obtained, new meshes are created following a h-adaptive refinement procedure that aims to minimize the error in energy norm of the solution. The exact error in energy norm of the solution is given by: |||e|||2 Ω:= ∫Ω (σ−σh)TD−1(σ−σh) dΩ (3.5) where σhis the FE stress field and σis the exact stress field, which is usually unknown. In order to estimate the error in energy norm cgFEM uses the Zienkiewicz & Zhu (ZZ) error estimator (3.6), presented in [14], where σ∗is an improved stress field, more accurate than σh. |||e|||2 Ω≈E2 ZZ := ∫Ω (σ∗−σh)TD−1(σ∗−σh) dΩ (3.6) Optimization of a FEM code. Usage of GPUs in parallel computing. 59 4. Overall performance tests The workstation used to measure all computing times in this Thesis had a Intel Xeon E5-2609 CPU with 16GB RAM memory. The GPU device used for parallel computing was a ASUS GeForce GTX780 with 3GB RAM memory. Although the performance improvement results in this Thesis are expressed as speed-up ratios, it is worth to outline that the CPU and GPU device are decisive parameters that affect the absolute computational cost. In fact, some of the examples shown here have been tested in a different workstation with a Intel i7-4770K CPU and the same RAM memory and GPU, reporting computation times twice as fast as the times shown in this chapter in all cases. The benchmark problems that are going to be used to test the performance of the cgFEM code are a hollow cylinder under internal pressure, a flywheel under external torque and a medical image-based analysis. At the end of the Chapter a qualitative comparison is made between cgFEM and a commercial FE code, ANSYSr. 4.1 Hollow cylinder under internal pressure The model of this problem was already used to test the new refinement routine in section 2.1, and is shown again in Figure 4.1 for convenience. Two different tests have been made using this model, one with linear elements and other with quadratic elements. A h-adaptive analysis was executed for both tests, with the aim to reach non-uniform meshes with a high number of degrees of freedom (dofs). The last iterations of both tests had 760 ×103dofs for the linear element case and over 1.2×106dofs in the case of quadratic elements. Tables 4.1 and 4.2 show the number of dofs and the estimated error in energy norm of each mesh in the h-adaptive process. 66 Jos´e Manuel Navarro Jim´enez 4.1. Hollow cylinder under internal pressure Figure 4.1: Hollow cylinder under internal pressure model. DOF Estimated error in energy norm (%) 5542 3.0315 14734 1.0975 106094 0.4017 760206 0.1685 Table 4.1: Hollow cylinder analysis. Linear elements. Time results for the test with linear elements are shown in Figure 4.2. The three coloured areas at the bars correspond to the three different blocks in which the FEM program was divided in Chapter 3. It can be noticed that the vectorization process has provided an important improvement in the preprocessing and post-processing blocks. The enhanced intersection procedure has led to a 60% time reduction. Moreover, the GPU implementations have an 82% total improvement of the post-processing block with respect to the original code. The overall time results report a 64% reduction in computation time with the usage of GPUs. Optimization of a FEM code. Usage of GPUs in parallel computing. 67 4. Overall performance tests DOF Estimated error in energy norm (%) 62572 0.0463 72066 0.0129 132098 0.0038 405240 0.0011 1239678 0.0003 Table 4.2: Hollow cylinder analysis. Quadratic elements. The results of the test for the quadratic element’s case are shown in Figure 4.3. On the one hand the overall performance improvement reaches only a 20%, which is a significantly lower reduction compared to the one achieved in the case with linear elements. But, on the other hand, the computation time of the original code with linear elements is similar to the time elapsed in the quadratic element’s case, despite doubling the number of dofs. Quadratic element meshes need less elements to obtain the same amount of dofs than meshes with linear elements. As many operations in cgFEM are performed element-wise, the computational cost in this case increases not with the number dofs but with the number of elements. This explains why the original code had a worse efficiency when using linear elements than when using quadratic ones, because all element-wise operations were performed in sequential loops. By applying vectorization techniques the dependence of the computational cost with the number of elements has decreased, and now the effectiveness of cgFEM is similar with both types of element. The improvement of the GPU computed tasks in this case is a 38% with respect to the original code. The decrease in this speed-up is due to the same reason of the lower overall performance. GPU implementations are focused on calculations performed for internal elements, while contour elements’ calculations such as energy norm or SPR stress fields are still not vectorized. Meshes with quadratic elements have also a lower ratio between internal and 68 Jos´e Manuel Navarro Jim´enez 4.2. Flywheel under external torque Original Code Improved Code CPU Improved Code GPU Post-processing 492,367 278,36 87,745 FEM resolu!on 88,977 87,881 87,871 Pre-processing 548,494 212,667 212,662 0 200 400 600 800 1000 1200 Elapsed Time 1129.838 578.908 388.278 ≈ ≈ -68% -43% ≈ -61% Figure 4.2: Hollow cylinder h-adaptive analysis. Time results for linear elements. boundary elements, so the improvement achieved with GPU computation is extended to a lower number of elements. 4.2 Flywheel under external torque The next problem used to test cgFEM is the model of a flywheel subject to an external torque. Figure 4.4 shows the model as it is introduced in the program. This model has a higher ratio of contour per surface, so all calculation meshes will have more boundary elements, and the intersection process will have an increased computational cost. Optimization of a FEM code. Usage of GPUs in parallel computing. 69 4. Overall performance tests Original Code Improved Code CPU Improved Code GPU Post-processing 624,279 526,965 390,155 FEM resolu!on 394,246 390,774 390,827 Pre-processing 187,135 185,604 185,366 0 200 400 600 800 1000 1200 1400 Elapsed Time 1205.66 1103.343 966.348 ≈ ≈ ≈ ≈ -26% -16% Figure 4.3: Hollow cylinder h-adaptive analysis. Time results for quadratic elements. Again, both tests with linear and quadratic elements have been run. Tables 4.3 and 4.4 show the data of all the iterations in the analyses. It is worth to highlight that this time the refinement parameters have been changed so that the linear test had almost 3 million dofs in the last iteration. This is at the moment the biggest analysis that cgFEM has been able to solve without running out of RAM memory. DOF Estimated error in energy norm (%) 18488 8.711 127834 1.619 2957774 0.294 Table 4.3: Flywheel analysis. Linear elements. 70 Jos´e Manuel Navarro Jim´enez 4.2. Flywheel under external torque Figure 4.4: Flywheel under external torque model. The time results shown in Figure 4.5 confirm that the old intersection routine becomes the main bottleneck in the program when the calculation mesh has a large amount of elements. The intersection procedure in this test consumes about 92% of the total analysis time with the original code. This bottleneck is drastically reduced with the proposed vectorized solution, reducing 85% of the whole computation time. GPU improvements are hidden because of the huge computational cost of the intersections in the original code. This was the main reason to include the new refinement algorithm in the original code, because the results of the refinement improvement would cover all other optimizations. Nevertheless, the new GPU calculations decrease 55% of the elapsed time of Optimization of a FEM code. Usage of GPUs in parallel computing. 71 4. Overall performance tests DOF Estimated error in energy norm (%) 15800 10.795 21414 2.610 39536 0.587 97238 0.148 296918 0.039 986956 0.012 Table 4.4: Flywheel analysis. Quadratic elements. the post-processing block with respect to the original code, reaching an overall 86% speed-up of the program. Original Code Improved Code CPU Improved Code GPU Post-processing 1538,101 1099,441 699,577 FEM resolu!on 331,499 334,252 343,767 Pre-processing 24555,292 2254,343 2281,204 0 5000 10000 15000 20000 25000 30000 Elapsed Time 26424.892 3688.036 3324.548 ≈ ≈ -36% -29% ≈ -91% Figure 4.5: Flywheel h-adaptive analysis. Time results for linear elements. The results of the test with quadratic elements lead to the same conclusions obtained in the cylinder test with quadratic elements. In this example the improvement is even lower (overall 10%). This is because, as it has been said, this model has a higher proportion of boundary elements in the calculation 72 Jos´e Manuel Navarro Jim´enez 4.3. Femur analysis based on a medical image meshes, and the vectorization of the calculations for internal elements has less impact on the total computation time. One of the future tasks is to extend some optimizations to the boundary element calculations (such as error in energy norm or stress). However, this improvements also imply some changes in the data structure, like the one exposed in section 3.2.1. Original Code Improved Code CPU Improved Code GPU Post-processing 694,937 676,224 576,039 FEM resolu!on 508,083 500,823 499,268 Pre-processing 114,663 107,188 107,168 0 200 400 600 800 1000 1200 1400 Elapsed Time 1317.683 1284.235 1182.475 ≈ ≈ -15% -3% ≈ -7% Figure 4.6: Flywheel h-adaptive analysis. Time results for quadratic elements. 4.3 Femur analysis based on a medical image The final test in this Chapter consists of a medical image-based analysis. This example will check the speed-up of the specific improvements made for this special feature of cgFEM, particularly those made on the FEM resolution block. Optimization of a FEM code. Usage of GPUs in parallel computing. 73 4. Overall performance tests Figure 4.7a shows the medical image on which the problem is based. The boundary conditions are applied through curves defined by the user. In this case there is a straight line where the Dirichlet constrain is imposed and a pressure is applied on the arc on the top. (a) (b) Figure 4.7: Medical image of a femur and calculation mesh for the analysis. There is no contour in this model to intersect with the Cartesian grid pile, and the analysis consists of one only iteration because the h-adaptive refinement based on the quality of the solution has not yet been implemented for medical image analyses. Therefore the pre-processing block is negligible in terms of computational cost, and only the resolution and the post-processing block are considered. The element stiffness matrices procedure is shown here apart 74 Jos´e Manuel Navarro Jim´enez 4.3. Femur analysis based on a medical image from the rest of the resolution block, as major changes were performed in this routine. The results of the test are shown in Figure 4.8. Original Code Improved Code CPU Improved Code GPU Post-processing 107,105 106,857 37,832 S!ffness matrix crea!on 75,672 14,941 2,684 FEM resolu!on 14,204 13,959 14,607 0 50 100 150 200 250 Elapsed Time 196.981 135.757 55.123 -82% ≈ ≈ -65% ≈ -80% Figure 4.8: Time results for a medical image-based analysis. Some of the benefits of the Cartesian grids regarding the computational efficiency disappear when it comes to an analysis based on a medical image. This is because all elements have different material properties. Therefore, the element characteristics cannot be linked to the reference element’s characteristics, as it happened with the internal elements in standard cgFEM. In this case all elements have to be treated as if they were “boundary elements”, meaning that all characteristics have to be calculated element-wise. This explains why the original code test consumed almost 200 seconds to solve a 86 ×103thou- sand dofs problem, which is a small amount of dofs considering the size of the previous tests. The vectorization of the element stiffness matrices report a 80% reduction on the time consumed by this task. This result demonstrates that struct type Optimization of a FEM code. Usage of GPUs in parallel computing. 75 Bibliography [7] E Nadal. Cartesian grid FEM (cgFEM): High performance h-adaptive FE analysis with efficient error control. Application to structural shape optimization. PhD thesis, Universidad Polit´ecnica de Valencia, 2014. [8] E Nadal and O A Gonz. Error estimation and error bounding in quantities of interest based on equilibrated recovered displacement fields. (Eccomas), 2012. [9] E Nadal, J J R´odenas, J Albelda, M Tur, J E Taranc´on, and F J Fuenmayor. Efficient Finite Element Methodology Based on Cartesian Grids: Application to Structural Shape Optimization. Abstract and Applied Analysis, 2013:1–19, 2013. [10] J M Navarro-Jim´enez. Obtenci´on de modelos de elementos finitos con mallados cartesianos independientes de la geometr´ıa a partir de im´agenes m´edicas y su uso en la simulaci´on de interacci´on entre pr´otesis y tejidos vivos. Proyecto Final de Carrera. ETSII-UPV., 2013. [11] J J R´odenas, C Corral, J Albelda, J Mas, and C Adam. Solver directo de divisi´on recursiva en subdominios basado en un programa de refinamiento h adaptable de estructura jer´arquica. M´etodos Num´ericos e Computacionais em Engenharia. CMNE CILAMCE, 2007. [12] J J R´odenas, L Giovannelli, E Nadal, J M Navarro, and M Tur. Creation of patient specific finite element models of bone-prosthesis—simulation of the effect of future implants. VipImage 2013, IV Eccomas thematic conference on computational vision and medical image processing, 2013. [13] J J R´odenas, J E Taranc´on, J Albelda, A Roda, and F J Fuenmayor. Hierarchical properties in elements obtained by subdivision: A hierarquical h-adaptivity program. In Pedro D´ıez and Nils-Erik Wiberg, editors, Adaptive Modeling and Simulation 2005, 2005. 82 Jos´e Manuel Navarro Jim´enez Bibliography [14] O C Zienkiewicz and J Z Zhu. A simple error estimator and adaptive procedure for practical engineering analysis. International Journal for Numerical Methods in Engineering, 24(2):337–357, 1987. [15] O C Zienkiewicz and J Z Zhu. The superconvergent patch recovery and a posteriori error estimates. Part 1: The recovery technique. International Journal for Numerical Methods in Engineering, 33(7):1331–1364, 1992. Optimization of a FEM code. Usage of GPUs in parallel computing. 83