EINA Universidad Zaragoza Máster Universitario en Meánia Apliada Trabajo Fin de Máster 2D Shallow Flow Simulation Using GPU Technologies Asier Lacasta Soto Grupo de Hidráulica Computacional -
[email protected] Directora: Pilar García Navarro1 Co-Director: Javier Murillo Castarlenas1 (1) Area de Mecánica de Fluidos Escuela de Ingeniería y Arquitectura Universidad Zaragoza Curso 2011/2012
2
Aknowledgements I would like to express my appreiation to Dra. Pilar Garía Navarro for her valuable and onstrutive suggestions during the planning and development of this researh work. My grateful thanks are also extended to Dr. Javier Murillo for his help with the mo del solving my doubts. I would also like to thank the other memb ers of the group for their advies and p oints of view when neessary. I would like sp eially mention to Hetor Ratia. Finally, I wish to thank nVidia for their partial supp ort providing us with a Hardware part under the Nvidia Aademi Partnership program. This work has b een develop ed under pro jet CENIT-TECOAGUA CEN-20091028. i
ii
Resumen Los mo delos matemátios y méto dos numérios impliados en la simulaión de ujos on sup er- ie libre han sido estudiados durante tiemp o en el Grup o de Hidráulia Computaional de la Universidad de Zaragoza. Estos mo delos son la base de nuevos desarrollos omo el transp orte de sedimento, el mo delado de interaión on puentes o el aoplamiento hidrológio. A p esar de la alidad de estos méto dos, el oste omputaional es muy alto y en gran parte esto se deb e a la tenología numéria que requieren. Con la nalidad de sup erar esta limitaión, este traba jo estudia la implementaión de un ó digo de simulaión hidráulia orientada a ejeuión en GPU, p ermitiendo simular un amplio onjunto de situaiones transitorias en gran esala temp oral, on un tiemp o de simulaión razonable. El oste omputaional de éste tip o de herramientas ha sido reduido, tradiionalmente, utilizando ténias de paralelismo, impliando un alto número de pro esadores para reduir el tiemp o de álulo al máximo. En los últimos años, las freuenias de los pro esadores pareen hab er alanzado su límite (Figura 1 extraida de [9℄) p or lo que las ténias de paralelismo en pro esadores masivos son una nueva op ión. Figure 1: Evoluión de las freuenias de CPU desde 1985 hasta 2011 iii
En este traba jo, se analiza el rendimiento del ó digo implementado en GPU, omparándolo on su equivalente en CPU. Este segudo, viene siendo desarrollado, en su totalidad, en Fortran mientras que el primero, ha sido desarrollado utilizando el lengua je de programaión C, ompartiendo el pro esamiento geométrio on la versión CPU. Las fuionalidades implementadas en la versión GPU, ubre una gran parte de situaiones de interés, tales omo el avane de una inundaión, los ambios de fondo y friión y algunas ondiiones de ontorno de entrada y de salidas. La implementaión del méto do en GPU no es trivial y requiere de un ono imiento en profundidad del funionamiento de esta tenología a ba jo nivel. Los b eneios de la versión GPU serán analizados a través de la aeleraión rep eto a la versión CPU en diferentes tip os de aso. EL rendimiento del ó digo GPU además, será medido teniendo en uenta el uso de mallas no estruturadas, las uales suelen ser neesarias en muhos o digos de CFD. Para su simulaión, se utilizará la GPU Tesla 2075 de nVidia. Además se utilizará el estándar CUDA, que hae la programaión más senilla que otros estándar en programión GPU, p ermietiendo al programador exprimir los b eneios de esta tenología. iv
Abstrat The mathematial mo dels and numerial metho ds implied in the resolution of free surfae ows have b een studied for a long time within the Computational Hydrauli Group at the Universidad Zaragoza. They supp ort new developments suh as sediment transp ort, bridges mo deling or hydrologial oupling. Despite the quality that the numerial solvers prop osed by the group oer, the omputational ost of these metho ds is very high, due to the omplexity of the numerial to ols required. In order to avoid this limitation, the present work studies the implementation of a sienti hydrauli simulation to ol oriented to b e run on GPU, allowing to simulate a wide range of situations over large time sale problems, that otherwise an not b e omputed at an aordable ost. The omputational ost has b een traditionally redued by using parallel tehniques, involving a large numb er of pro essors in order to redue the simulation time as muh as p ossible. Sine CPU frequenies seem to b e reahing their maximum apaity (Figure 2 extrated from [9℄), nowadays Many-Core parallel tehniques app ear to b e an interesting option. Figure 2: CPU Frequeny evolution sine 1985 until 2011 The p erformane of the GPU version is analyzed omparing b oth CPU and GPU versions of the same o de. While the former was fully develop ed in Fortran language, the numerial v
kernel of the new GPU version has b een written in C, sharing the geometrial prepro essing mo dule with the CPU version. The funtionalities implemented in the GPU version over a wide range of situations as they inlude all the harateristis that are desirable in the ontext of shallow ow simulation: o o ding advane, frition and b ed slop e soure-terms as weel as inlet and outlet b oundary onditions. The implementation of these requirements in the ontext of realisti simulations is not straightforward. This is explained when onsidering that, ontrary to other programming languages, the GPU version requires a go o d omprehension of the low level op erations, that do es not allow a diret onventional implementation. The b enets of the GPU version will b e analyzed in depth fo using on sp eed-up gain in omplex ases. The p erformane of the GPU o de is analyzed in depth to ensure not only the eieny but also the p ossibilities of GPU programming when using unstrutured meshes, that are often required in CFD o des. A Tesla 2075 nVidia GPU has b een used in the present study. Moreover, it has b een develop ed using nVidia-CUDA standard, whih makes friendly the programming for general purp ose appliations, allowing the programmer to exploit the many-ore paradigm. vi
Contents 1 Intro dution 1 1.1 Context and assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Struture of the rep ort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 Mathematial Mo del and Numerial Metho d 3 2.1 Approximate Riemann solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2.2 Appliation to the 2D Shallow Water equations . . . . . . . . . . . . . . . . . . . 6 2.3 Numerial resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3 CUDA Tehnology Overview 11 3.1 GPU Tehnology history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 nVidia CUDA tehnology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 CUDA development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.3.1 Example of implementation in a 1D ase . . . . . . . . . . . . . . . . . . . 14 3.4 Results Al l that glitters is not gold . . . . . . . . . . . . . . . . . . . . . . . . . . 16 4 Implementation 19 4.1 Mo del overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.2 Memory oalesing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 4.3 Gathering data avoiding b ottlenek . . . . . . . . . . . . . . . . . . . . . . . . . . 23 4.4 Writing output les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 4.5 Compilation and other issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 5 Results 29 5.1 Preision: A test-ase with analytial solution . . . . . . . . . . . . . . . . . . . . 29 5.2 Performane: A large-sale simulation at Júar River . . . . . . . . . . . . . . . . 33 5.3 Comparing with a distributed memory parallel implementation . . . . . . . . . . 39 6 Conlusions and future work 45 Bibliography 47 vii
2.1. APPROXIMATE RIEMANN SOLUTION - - 6 ?@ @ @ @ @ @ @ @ HHHHHHHH H @ @ @ @ @ x′ lk 0 Un i Un j nk Figure 2.1: Riemann problem in 2D along the normal diretion to a ell side. where following previous work, [28℄ Z+X′ −X′ S(x′,0) dx′= (Tn)n k (2.13) where T is a suitable numerial soure matrix. This enables the following formulation of (2.8) ∂ ∂t ZΩ UdΩi+ NE X k=1 (δE−T)knklk= 0 (2.14) that is approximated by using the following linear problem ∂ ∂t RΩ ˆ UdΩi+PNE k=1 J∗ n,kδˆ Uklk= 0 ˆ U(x′,0)k=(Uiif x′<0 Ujif x′>0 (2.15) Integrating 2.15 over the same ontrol volume as b efore the following expression is obtained for eah k edge Z+X′ −X′ ˆ U(x′,1) dx′=X(Ui+Uj)−J∗(Uj−Ui) (2.16) and sine we want to satisfy (2.12), the onstraint that follows is: (δE−T)knk=˜ J∗(Uj−Ui) (2.17) Due to the non-linear harater of the ux matrix E , the denition of an approximated Jaobian matrix, e Jn,k , allows for a lo al linearization δ(En)k=e Jn,kδUk (2.18) and is exploited here [24℄. This approah provides a set of three real eigenvalues e λm k and eigenve- tors eem k . Then, it is p ossible to dene two matries e P= (ee1,ee2,ee3) and e P−1 with the following prop erty e Jn,k =e Pke Λke P−1 k (2.19) 5
CHAPTER 2. MATHEMATICAL MODEL AND NUMERICAL METHOD The dierene in vetor U aross the grid edge and the soure term are pro jeted onto the matrix eigenvetors basis: δUk=e PkAk(Tn)k=e PkBk (2.20) with Ak=α1α2α3T k and Bk=β1β2β3T k . Expressing all terms more ompatly: δ(E·n)k−(T·n)k= Nλ X m=1 e λ θαeem k (2.21) with θm k=1−β e λαm k (2.22) Finally, it is p ossible to dene the desired matrix in (2.17) e J∗ k= (e Pe Λ∗e P−1)k (2.23) with e Λ∗=e ΛΘ , where e Λk is a diagonal matrix with eigenvalues e λm,∗ k in the main diagonal and Θk is a diagonal matrix with θm k in the main diagonal: e Λk= e λ10 0 0e λ20 0 0 e λ3 k Θk= θ10 0 0θ20 0 0 θ3 k (2.24) 2.2 Appliation to the 2D Shallow Water equations The two-dimensional shallow water equations, whih represent depth averaged mass and momentum onservation, an b e obtained from the Navier-Stokes equations. Negleting diusion of momentum due to visosity and turbulene, wind eets and the Coriolis term, they form a system of equations [2℄ as in (2.1), where U= (h, qx, qy)T (2.25) are the onserved variables with h representing the water depth, qx=hu and qy=hv , with (u, v) the depth averaged omp onents of the velo ity vetor u along the (x, y) o ordinates resp etively. The uxes of these variables are given by: F=qx,q2 x h+1 2gh2,qxqy hT ,G= qy,qxqy h q2 y h+1 2gh2!T (2.26) where g is the aeleration of the gravity. The soure terms of the system are the b ed slop e and the frition terms: S=0,pb,x ρw−τb,x ρw ,pb,y ρw−τb,y ρwT (2.27) 6
2.3. NUMERICAL RESOLUTION where the b ed slop es of the b ottom level z are pb,x ρw =−gh∂z ∂x,pb,y ρw =−gh∂z ∂y (2.28) and the frition losses are written in terms of the Manning's roughness o eient n : τb,x ρw =ghSfx Sfx =n2u√u2+v2 h4/3,τb,y ρw =ghSfy Sfy =n2v√u2+v2 h4/3 (2.29) 2.3 Numerial resolution Following Go dunov's metho d, the solutions of the RP's are evolved for a time equal to the time step and the resulting solution is ell-averaged. The volume integral in the ell at time tn+1 leads to the up dating numerial sheme as: Un+1 iAi=Un iAi− NE X k=1 3 X m=1 (e λ−θαee)m klk∆t (2.30) with e λ±,m k=1 2(e λ±|e λ|)m k . When applied to the shallow water system presented in setion 2.2 the approximate Jaobian e Jn,k for the homogeneous part is onstruted with the following averaged variables [24℄ euk=ui√hi+ujphj √hi+phj ,evk=vi√hi+vjphj √hi+phj ,eck=rghi+hj 2 (2.31) leading to e λ1 k= (e un −ec)k,e λ2 k= (e un)k,e λ3 k= (e un +ec)k (2.32) and ee1 k= 1 eu−ecnx ev−ecny k ,ee2 k= 0 −ecny ecnx k ,ee3 k= 1 eu+ecnx ev+ecny k (2.33) When ell averaging the solution in the 1D dimensional ase the time step ∆t is taken small enough so that there is no interation of waves from neighb ouring Riemann problems, attending to a distane ∆x/2 . In the 2D framework, onsidering unstrutured meshes, the equivalent distane to ∆x , that will b e referred to as χi in eah ell i must onsider the volume of the ell and the length of the shared k edges. χi=Ai maxk=1,NE lk (2.34) Considering that eah k RP is used to deliver information b etween eah pair of neighb ouring ells of dierent size, the asso iated distane min(Ai, Aj)/lk is relevant, so in ase that ˆ h(x′, t)≥0 in all k RP's the time step is limited by ∆t≤CFL ∆t e λ∆t e λ=min(χi, χj) maxm=1,2,3|e λm| (2.35) 7
CHAPTER 2. MATHEMATICAL MODEL AND NUMERICAL METHOD The previous stability ondition is insuient in presene of relatively imp ortant soure terms. The systemati ontrol of numerial stability in those ases has b een a matter of reent researh in the group as it is related with the appliability of the sheme to real situations. A simple generalization of the CFL ondition paying attention to the existene of the soure terms an lead to extremely small values of ∆t various orders of magnitude smaller than the value ditated by the homogeneous ondition, hene rendering the metho d impratial. This an b e avoided by means of a reonstrution of the approximate solution ˆ U(x′, t) that is not detailed here for the sake of oniseness. The strategy prop osed is based on enforing p ositive values of auxiliary quantities h∗ i h∗ i=hn i+α1 k−β e λ1 k≥0 (2.36) and h∗∗∗ j h∗∗∗ j=hn j−α3 k+β e λ3 k≥0 (2.37) so that, when they b eome negative, the numerial soure term is redued instead of reduing the time step size. For more details, see [21, 18℄. Furthermore, following the unied disretization in [6℄ the non-onservative term (Tn)k in (2.13) at a ell edge is written [20 ℄ as: (Tn)k= 0 pb ρw−τb ρwnx pb ρw−τb ρwny k (2.38) where pb ρw and τb ρw attend to the pressure and frition exerted on the b ed resp etively. In this work the following expression for the thrust term pb ρw is prop osed: pb ρwk = max pb ρwa,pb ρwbk if δd δz ≥0 and (e un)δz > 0 pb ρwb k otherwise (2.39) where d= (h+z) and pb ρwa k =−g(ehδz)kpb ρwb k =−ghr−|δz′| 2δz′ (2.40) with r=(i if δz ≥0 j if δz < 0δz′= hi if δz ≥0 and di< zj hj if δz < 0 and dj< zi δz otherwise (2.41) The disretization of the frition term based on [21℄ is applied τb ρwk =g(ehSf)kdnSf,k =n2e un|e u| max(hi, hj)4/3k (2.42) 8
2.3. NUMERICAL RESOLUTION with dn the normal distane b etween neighb or ell enters. 9
10
3 CUDA Tehnology Overview Nowadays, GPU tehnologies start to onquer from ordinary business appliations to sieniti appliations. This general purpose orientation is denomined GPGPU 1 , allowing its develop ers to reah higher p erformane than in oventional arhitetures (Single Instrution Single Data) where the op erations are urrently p erformed sequentially. In the ase of sienti omputation, the GPGPU paradigm p erforms the numerial metho ds. nVidia has b een working in the improvement of the GPGPU paradigm, reating the CUDA to olkit. CUDA to olkit is a parallel arhiteture for graphi pro essing whih implements an intrution-set oriented to the GPU memory aess and op erations in C. Other more general implementations have b een p erformed through op en-soure platforms suh as Op enCL and others like PGI-Cuda as propietary-soure. Op enCL has the main advantage of b eing hardwareindep endent. It implies that the same o de ould b e exeuted on b oth nVidia and ATI GPUs. The main disadvantage is that the learning-urve is harder than for the CUDA to olkit. The other option is PGI-Cuda. It has the main advantage in the supp ort of CUDA primitives for Fortran but the disadvantage is the ost of it. So, as we are interested in simulating at nVidia GPUs, the implementation of the o de has b een develop ed using CUDA-To olkit. 3.1 GPU Tehnology history Sine the advent of Op enGL, GPUs added programmable shading to their apabilities. Eah pixel ould inop orate its pro essing as a program to b e shown on sreen after applying it. nVidia was the rst to pro due a hip apable of programmable shading. In 2002, ATI develop ed the rst Diret3D 9.0 aelerator, whih implemented lo oping and lengthy oating p oint math, b e- oming as exible as CPU and orders of magnitude faster for image-array op erations. Abstrating the graphial purp ose and taking a double-p oint array as if it were a vertexarray, the same op erations were able to b e applied, so with the nVidia CUDA To olkit, a new programming mo del for GPU omputing was stablished. After its app earane, Op enCL b eame broadly supp orted allowing develop ers o ding for AMD/ATI GPUs. 1 General Purp ose Graphi Pro essor Unit 11
CHAPTER 3. CUDA TECHNOLOGY OVERVIEW 3.2 nVidia CUDA tehnology The present work has b een develop ed using an nVidia Tesla GPU. The partiular organization and how it works is explained b elow and has followed [11 ℄. Most of the details are ommon with the previous GPU generations and it is previsible that will b e ommon with future generations to o. There are two main p oints of view when explaining how CUDA works. The rst is based on the hardware arhiteture. The minimum unit is the Streaming Pro essor (SP), where a single thread is exeuted. A group of SP's form the Streaming Multipro essor (SM), tipially with 32 SP's. Finally, a GPU is omp osed by b etween 2 and 16 SM's. The seond p oint of view is based on the way CUDA appliations are develop ed. The minimum unit is alled Thread. Threads are identied by lab els ranging b etween 0 and blokDim . The group of Threads is alled Blo k, and it ontains a (reommended) 32 multiple numb er of Threads. Finally any group of Blo ks is alled Grid. These elements are illustrated on Figure 3.1. Block 0 Block 1 Block 2 Thread Block Grid Figure 3.1: thread, blok, grid sheme omp osition Atual nVidia GPU's p erforms the threads sheduling inside the SM in groups of 32 alled Warps (we also reommend [15℄ for future onsiderations). Eah SM features two Warp shedulers and two instrution dispath units, allowing two Warps to b e issued and exeuted onurrently. Fermi's dual Warp sheduler selets two Warps, and issues one instrution from eah Warp to a group of sixteen ores, sixteen load/store units, or four SFU's. Beause Warps exeute indep endently, Fermi's sheduler do es not need to hek for dep endenies from within the instrution stream. Using this elegant mo del of dual-issue, Fermi ahieves near p eak hardware p erformane. Most instrutions an b e dual issued; two integer instrutions, two oating instrutions, or a mix of integer, oating p oint, load, store, and SFU instrutions an b e issued onurrently. Double preision instrutions do not supp ort dual dispath with any other op eration. Figure 3.2 shows how the SP are distributed inside the SM and how the multipro essors are distributed inside the GPU. Furthermore, Figure 3.3 shows the temp oral evolution inside the SM and how it works for a blo k with 256 elements ( warp = 256/32 = 8 elements). Any Thread an b e lab elled using blokDim , blokId and threadId . In an example with 14 Blo ks and 256 Threads/Blo k (3584 elements), we nd that for element 23 in Blo k 4, the lab els inside the o de are 12
3.3. CUDA DEVELOPMENT Streaming Multiprocessor Instruction Cache Register File WS/DU WS/DU Interconnected Network Shared Memory/L1 Cache Uniform Cache (a) GF100 Streaming Multipro essor (SM) Streaming Multiprocessor Streaming Multiprocessor Streaming Multiprocessor Streaming Multiprocessor Streaming Multiprocessor Streaming Multiprocessor Streaming Multiprocessor Streaming Multiprocessor Streaming MultiprocessorStreaming Multiprocessor Streaming MultiprocessorStreaming Multiprocessor Streaming MultiprocessorStreaming Multiprocessor L2 Cache Host Interface / GigaThread Engine Memory Controller Memory Controller (b) 14-SM based Fermi Arhiteure detail Figure 3.2: Desription of our Fermi 2075 GPU based on GF100/GF110 Arhiteture. Warp Scheduler Warp Scheduler Inst. Disp. Unit Warp 8 Instruction 5 Warp 2 Instruction 1 Warp 6 Instruction 17 Warp 8 Instruction 3 Warp 2 Instruction 2 ... ... Block 4 Warp 5 Instruction 14 Warp 7 Instruction 5 Warp 1 Instruction 2 Warp 5 Instruction 15 Warp 1 Instruction 3 Warp 7 Instruction 6 ... Inst. Disp. Unit Time Warp 6 Instruction 16 Figure 3.3: Exeution pip eline for a Strem Multipro essor (left) whih pro ess blo k number 4 (right) • blokDim=256 • blokId=4 • threadId=23 and then, the typial aess pattern, p oints to i=threadId+blokDim*blokId=23+256*4=1047 3.3 CUDA development The CUDA main funtions are related to the memory interation b etween CPU and GPU, in partiular, udaMempy with the dierent ags to stablish the way of the transfer. It is imp ortant to remark that these interations or data transfers b etween GPU and CPU are extremely slow and should b e minimized. Moreover, the allo ation and memory freeing op erations ould b e p erformed using their equivalenes in CUDA as shown in listing 3.1 13
CHAPTER 3. CUDA TECHNOLOGY OVERVIEW Listing 3.1: CUDA Most imp ortant funtions 1 // GPU Memory alloation 2 udaMallo(...,size); 3 // GPU Memory free 4 udaFree(..); 5 // Copy Host To devie 6 udaMempy(...,udaMempyHostToDevie); 7 // Copy Devie To Host 8 udaMempy(...,udaMempyDevieToHost); 9 // Copy Devie To devie 10 udaMempy(...,udaMempyDevieToDevie); The advantage of using GPU for programming numerial metho ds, omes from the High- Level Single Instrution Multiple Data (SIMD) or as nVidia alls, Single Intrutions Multiple Threads (SIMT) paradigm. Any op eration an b e exeuted in onurrene with many others allowing any CUDA Thread to aess to a partiular p osition while any other is aessing to another one. 3.3.1 Example of implementation in a 1D ase Consider, for example, the 1D transp ort equation: ∂u ∂t +c∂u ∂x = 0 (3.1) with c > 0 , and its initial and b oundary onditions u(x, 0) = f(x) u(0, t) = U0 applying the temp oral disretization with forward Euler and the upwind sheme: ∆ui ∆t=−ui−ui−1 δx (3.2) writing its as un+1 i=un i−un i−un i−1 δx ∆t·c (3.3) and the pro edure ould b e written in Standard C as follows Listing 3.2: Simple 1D transp ort equation in C 1 void upwindStepCPU(double *fn,double *fnmas1,double DELTAX){ 2 int i; 3 for (i=1; i<1/DELTAX; i++) { 4 fnmas1[i℄=fn[i℄+*DELTAT*(fn[i-1℄-fn[i℄)/(DELTAX); 5 } 6 } 14
4.2. MEMORY COALESCING 1 3 97 2 6 8 4 11 4 1 8 5 2 3 67 10 14 17 21 24 20 23 19 22 18 15 12 9 13 16 5 Figure 4.2: Strutured mesh with Cell Numb ering detail (Right) and Wall Numbering detail (Left) example 4.2 Memory oalesing Memory oalesing is the way the memory is ordered allowing half-Warp to aess global memory at the same time (using only 1 yle to p erform the load op eration). This means that, if a Thread (The rst one) in a Warp aesses to a partiular memory address and it aess pattern is suh that aess to the next address ( i, i+1, i+2.... ) the following 31 Threads do not need to read the memory again. Otherwise, two or more aesses are needed to allow eah Thread the aess to data. Memory oalesing is one of the most imp ortant things to take into aount when programming GPU's. Reent works [29℄ have demonstrated the eieny of oalesing tehniques, b eing this implementation b etter in some ases than shared memory strategies. Although there exist works dealing with the prots of using this strategy, the way to pro eed when using unstru- tured meshes is not lear. This topi will b e disussed in the next May 2012 GPU Tehnology Conferene [8℄ and some improvements are detailed in [25℄. In our ase, the p erfet memory oalesing tehnique ould b e implemented, [5 ℄ [7℄, if using strutured meshes. As it app ears in Figure 4.2, ell lab elling implies that the aess pattern for a Blo k of (in this ase 9) ells allows the programmer to make the p erfet math aess into a Warp. In other words, for any group of ells within a Warp, all the variables are aessible in only a oalesed reading. Being the present work oriented to a general implementation of the nite volume sheme on b oth strutured and unstrutured grids, the memory optimization is not as easy as desrib ed ab ove. Aording to the general up dating formula 2.30, this sheme works with the ell edge uxes or inter-ell elements through whih the Rienmann Problem is solved. In the ase of the strutured mesh, this ux takes plae into the left, right, upside and downside ell to a given ell, so all the op erations ould b e p erformed lo oping by ells. In unstrutured grids, this onept is dierent 21
CHAPTER 4. IMPLEMENTATION ... ... ... ... 32 Threads Warp Cell Data Array ... ... ... ... 32 Threads Warp Cell Data Array ... ... ... ... 32 Threads Warp Cell Data Array ... ... ... ... 32 Threads Warp Cell Data Array Time Figure 4.3: Misaligned and Coalesed aess pattern to ompute the ux variation for any group of elements following the sheme of Right, Left, Down, Up for W data (Stored by ell) in a mesh ordered as Figure 4.2. Light oloured orresp ond to the pro essed element 5, wih implies ells 2, 4, 6 and 8. 16 74 8 61 23 9 75 12 11 16 33 9 24 21 17 20 14 10 45 31 87 56 8 22 18 49 2359 27 30 Figure 4.4: Unstrutured mesh with Cell Numb ering detail (Right) and Wall Numb ering detail (Left) example and it is go o d idea to make the ux alulations by walls and then, to assign them to eah ell with the need to keep trae via a onnetivity matrix. For the general unstrutured ase it is imp ortant to deide how to stablish the order of the variables. It an b e p erformed through ells or through walls. Using as example Figure 4.2, the op erations of applying the variation to the ell (8) has no a oalesed pattern. There exists the need of searhing the neighb ouring ells (74,61,16) and alulating the ux through walls (33,9,16). Skething these op erations in an example for wall 33 (i=33, 1=8, 2=74) we have: Listing 4.2: Aess pattern for the main ux variation op eration. 1 alulateWallFluxes(...){ 2 // Loop by wall 3 int i = threadIdx.x+(blokIdx.x*blokDim.x); 4 if(i<nWall){ 22
4.3. GATHERING DATA AVOIDING BOTTLENECK ... ... ... ... ... ... ... ... ... ... ... ... 32 Threads Warp Wall Neighbouring Vector Cell Data Array Figure 4.5: Unoalesed aess pattern to get W data (Stored by ell). Pro essing wall 9 is light oloured when it aesses to ell 8 (i=9, 1=8) 5 1=wall[i℄; 6 2=wall[i+1℄; 7 // [COALESCED℄ Aess to the variables of the wall 8 // Normal Vetor 9 // Length of the side 10 // ... 11 ... 12 // [UNCOALESCED℄ Aess to the variables of 1 and 2 13 // Primitives variables 14 // Area of the ells 15 // ... 16 ... 17 // Store the value of the flux for the wall i 18 } 19 } Although this is the main funtion where the ux is alulated and it involves many unoalesed aesses to the variables, there are some op erations whose aess ould b e p erformed through the ells. 4.3 Gathering data avoiding b ottlenek One of the troubles when trying to make all the op erations inside the GPU is the identiation of global quantities suh as the minimum value of a vetor. As the Many-Core paradigm is not designed to share information b etween elements, redution op erations like min, max, sum... are p erformed at ublas library [23℄. ublas library has high-level funtions that work retrieving results to GPU or to CPU. When interested in using them without taking out the data from the GPU, that must b e sp eied. This ould b e done through ublasSetPointerMode_v2(handle, CUBLAS_POINTER_MODE_DEVICE) , stating that all results have to b e returned to the GPU memory. In our ase, it is essential that the algorithm alulates the minimum ∆t following the CFL ondition when running along all the ell edges. Then, following Figure 4.3 sheme, the minimum among all of them is seleted. Details are shown in Listing 4.3. 23
CHAPTER 4. IMPLEMENTATION 1 2 3 n-2 n-1 n 0.13 0.45 0.05 0.62 0.78 0.11 cublasIdamin() 3 dt[1..n] Δt=dt[3] Figure 4.6: Gathering minimum ∆t for all the domain Listing 4.3: Gathering ∆t op eration 1 __global__ void newDt(double *dt,double *vDt, int *id){ 2 // As ublasIdamin returns it value following 3 // 1-based indexing, we must to substrate 1 4 *dt=vDt[*id-1℄; 5 } 6 .... 7 ublasIdamin(handle,*npared,vDt,1,id); 8 newDt<<<1,1>>>(dt,vDt,d_id); 9 ... While alulation is ontrolled by host, it is neessary to transfer the up dated tn+1 . After δt is alulated, the up dating op eration an b e p erform as 4.4 and then, you an transfer the up dated value of tn+1 to CPU. Listing 4.4: Up dating ∆t 1 __global__ void updateT(double *dt,double *t){ 2 int i; 3 *t=*t+*dt; 4 } In order to alulate the global mass error, there is a sum of mass inside the mesh and the balane b etween the inlet and outlet b oundaries M =ρXhiAi (4.1) and then, it alulates the error as ǫ= M n+1 − M n+ M in − M out M n+1 (4.2) The sums are p erformed using ublasDasum where all elements are added within a vetor and the results stored in a variable, working similar to ublasIdamin . 4.4 Writing output les The feature of the newest CUDA mo dels allowing for simultaneous exeution and opy streams an b e used to hide delays aused by writing data to disk. 24
4.4. WRITING OUTPUT FILES Figure 4.7: Asynhronus dumping data diagram. Traditional udaMempy p erforms a synhronous opy, i.e., the all do es not return until the opy is omplete. However, alls to the new family of asynhronous funtions like udaMem- pyAsyn may return b efore the opy is omplete. Furthermore, the opy may b e assigned to a stream. In this way it is p ossible for the CPU host o de to all udaMempyAsyn and assign it to a opy stream, then launh kernels in an exeution stream. Both streams are pro essed simultaneously by the GPU. It is not p ossible to use udaMempyAsyn diretly to opy simulation results to Host memory in the ase of shallow ow simulation b eause the onurrent simulation would alter the values in the variables b eing opied. It is neessary to make a synhronous opy to a buer in GPU memory rst (Figure 4.7). One the opy of the results to the buer is omplete, a all to udaMempyAsyn is made whih opies the buer to host memory, and the simulation kernels are launhed simultaneously op erating on the usual variables. 25
CHAPTER 4. IMPLEMENTATION This sheme requires that the CPU launhes kernels after the all to the asynhronous opy. It is neessary to intro due a parallel CPU thread that waits for the opy to nish and then writes the results to disk. Thus, the main CPU thread will rst all udaMempyAsyn, then spawn a write thread and ontinue launhing kernels to advane the simulation. The rst task for the writing CPU thread will b e to wait for the opy stream to nish, then pro eed to write the results in host memory to disk. The limitation in this sheme is that the omputation time b etween dumps to disk has to b e greater than the writing time to disk itself. If that is not the ase, gains an still b e ahieved from using this sheme but further barriers are required. One of them is that the main CPU thread has to wait for the writing thread to nish b efore alling udaMempyAsyn. Dep ending on the problem, further gains an b e made e.g. using multibuering. 4.5 Compilation and other issues In the original Fortran version of the o de there are several funtions related to the prepro ess and p ostpro ess as skethed on gure 4.8. To b e more eient, the programming of that part of the o de in C has b een ommitted and the work has fo used on the eient programming of the numerial asp ets. So the prepro ess is p erformed through the Fortran version and the omputing kernel is p erformed using C/CUDA. To work with the two o des at the same time, they have b een ompiled together. The tehnique used is based on making a standard C interfae whih interop erates with CUDA and is alled from Fortran as shown in [1℄. The most ompliated and interesting detail of this op eration is the way of ompiling them. It is shown in Listing 4.5. Listing 4.5: Makele Sript 1 2 NVCC = nv 3 FORT = gfortran 4 5 FORTFLAGS = -w -O3 6 CUFLAGS = -g -w -O3 -m64 -arh sm_21 -Xptxas -dlm=a -I$(EXTRAE_HOME)/inlude 7 LDFLAGS = -L/opt/uda/4.0/lib64 -L$(EXTRAE_HOME)/lib -ludatrae -luda -ludart -lstd++ -lublas -lrt -lm -lpthread 8 OBJ = uda_bloks2mf.o SFS2Dv01_64.o 9 BIN = sfsGPU 10 11 $(BIN): $(OBJ) 12 $(FORT) $(FORTFLAGS) $(OBJ) $(LDFLAGS) -o $ 13 14 lean: 15 $(RM) $(OBJ) 26
4.5. COMPILATION AND OTHER ISSUES 16 17 leanEx: 18 $(RM) $(OBJ) $(BIN) 19 20 uda_atualiza.o: uda_atualiza.u 21 $(NVCC) $(CUFLAGS) $< - -o $ 22 23 uda_bloks2mf.o: uda_bloks2mf.u 24 $(NVCC) $(CUFLAGS) $< - -o $ 25 26 SFS2Dv01_64.o: SFS2Dv01_64.for 27 $(FORT) $(FORTFLAGS) $< - -o $ Bearing in mind that all the strutures are reated as Vetors in Fortran and Fortran indexing are 1-based (C uses 0-Based) an sp eial aess is required (Eq (4.5), (4.5) and (4.5)). Furthermore, Fortran stores the elements following Column-Ma jor Order while C storing is Row-Ma jor Order based. These two asp ets imply that: • The aess to the partiular p osition i of array V[M] is made, in C, as V(i) = V[i−1] (4.3) • The aess to the partiular p osition i, j of array V[MxN] is made in C as V(i, j) = V[(j−1) ·M+i−1] (4.4) • The aess to the partiular p osition i, j, k of array V[MxNxO] is made in C as V(i, j, k) = V[(k−1) ·M·N+ (j−1)M+i−1] (4.5) Load the mesh Load Initial Conditions Load BCs Stablish Sim. Length Stablish Sim. Length Compute Results Dump Data Free Resources t<tsim? Calc. dW Calc. dt Wet/Dry Correction Sync dt Update W No Yes Sync dW t=t+dt ⊗ Figure 4.8: Flux diagram for the appliation. Green-highlighted is the p orted slie of the o de 27
28
5 Results The ases hosen to show the results are fo used on how similar are the GPU numerial results to the ones obtained from the original CPU version (preision) and how eient this implementation an b e (p erformane). To ahieve this, two examples have b eed seleted. First, an aademi ase of unsteady ow with soure terms with analytial solution and seond a real life inundation ow of hydrauli interest. Furthermore, the GPU p erfomane has b een ompared with that of a distributed-parallel version of the CPU o de at [14℄ using a dam-break ow simulation with a large numb er of ells. 5.1 Preision: A test-ase with analytial solution This ase has b een used to minimize the dierenes b etween the results provided by the CPU and the GPU versions. The ase simulates the evolution of a mass of water ontained in a fritionless parab oloid. Test Case 1 orresp onds to zero initial velo ity and a urved initial free surfae shap e (Figure 5.1). As times go es on, the p otential energy transforms into kineti energy. It is a go o d ase b eause it has analytial solution [27℄ and there exists a hallenging wet/dry b oundary all the time. Figure 5.1: Left: Bed level and initial water depth state for test ase 1. As shown in Figure 5.2 and Figure 5.3 there are not visible dierenes b etween b oth simulations. In order to quantify the preision of the GPU implementation with resp et to the CPU, 29
CHAPTER 5. RESULTS Figure 5.2: Test ase 1. Left: GPU Simulated results for h and Right: CPU Simulated results for h at t= 42.03s. Figure 5.3: Test ase 1. Left: GPU Simulated result for |v| and Right: CPU Simulated results for |v| at t= 42.03s. the L1 , L2 and L∞ norm of the error in water depth at dierent times has b een alulated. Test Case 1 shows aeptable dierenes. This agrees with the error in the alulation reahing ma- hine preission ( O(−14) ) in b oth versions of the o de. The most sensitive region is the wet/dry b oundary where b oth the water depth and velo ity are very small. Test Case 2 orresp onds to the same fritionless ontainer but with dierent initial data orresp onding to a at surfae with velo ity. Although the visual omparison is also favorable, the detailed evaluation of the L1 , L2 and L∞ norm of the error in water depth at dierent times shows unaeptable dierenes whih ome from the preision of the double oating p oint data typ e, reahing O(L∞) = −4 . Studying the pro edene of the dierenes we nd the problem at the rst time step (See Figure 5.1). Following the numerial sheme, we found that: h∗∗∗ j=hn j−α1 k+β ˜ λ1 k≥0 (5.1) Attending to the new state for the seond time-step, we found the values for ell 65399 as app ears in Table 5.2 30
5.2. PERFORMANCE: A LARGE-SCALE SIMULATION AT JÚCAR RIVER if go o d preditions an b e obtained using redued domains of the study area or if, otherwise, it is preferable to dene large domains at the ost of less denition for the top ographi data if extremely long omputational times are to b e avoided. This hydrograph is syntheti sine no atual disharge reords exist [3℄. As the numerial domain D2 is lo ated 4 km downstrean of the Tous Dam it is p ossible to ompute a new dis- harge urve by reording the rate of ow disharge at an appropriate setion in D1 . Due to the huge magnitude of the o o ding the dierene b etween the two disharge urves is merely a lag time of a few hours. Both are displayed in Figure 5.14. Considering this, and the fat that no reords of the o o d wave arrival time exist, the same original disharge urve was set as inlet b oundary ondition in domains D1 and D2 when p erforming numerial simulations. At the oulet b oundary, downstream of the domains, the ow was let to exit freely without imp osing any onditions, as no information was provided. The initial depth of water in the river reah prior to the rain events is unknown. Taking into aount that the base ow of Júar River is roughly 50 m3s−1 whih is totally negligible in omparison with the sale of Tous outow hydrograph, the valley was assumed initially dry. Following [3℄ a Manning o eient of 0.030 sm−1/3 was used for the whole river b ed reah. Other zones of inreased Manning o eient are inluded. As the ground in the town area was fully paved with onrete, the o o d did not ero de it. Regarding reorded hydrauli data of the o o ding of the town of Sumaárel, a range for the maximum water elevation marks was olleted at 21 lo ations within or very lose to Sumaárel village. In b oth alulations a total time of 39 h was simulated with a omputational time of 5.5 h in the D1 domain and 22.3 h in the D2 domain. These gauging p oints are shown in Figure 5.11. Some gauges (numb ers 5, 9, 15, 17, 18 and 21) show no o o ding (zero or near zero maximum water depth) and orresp ond to lo ations just barely reahed by the o o ding so that they represent a sort of shore line of the o o d within the town. Table 1 ontains a summary of prob e lo ations, estimated maximum water depths and omputed maximum water depths on the two omputational domains. The values of the water depth at gauges 1 and 2, plaed in the lower part of the village indiate that the numerial solutions provided by b oth grids are a go o d predition of the maximum water level reahed by the o o ding at b oth stations. Both gauges register almost the same water level surfae evolution, as exp eted due to their proximity. Go o d agreement b etween maximum water elevation marks and predited data is also found for gauge lo ations 3 and 4, of similar b ed level elevation, and lo ated within the village. The results in table 1 show also a go o d agreement for gauge 5 that remains dry aording to the eld observations, despite it b eing lose to the river b ed. The elevation at gauge 6, within Sumaárel, is overestimated in approximately 1 m . The water depth at gauge 7 agrees well with the maximum water elevation mark, whilst water depth in gauge 8 is overestimated in approximately 1 m . 37
CHAPTER 5. RESULTS Gauge x(m)y(m) Est. max. h(m) Comp. max. h(m)D1 Comp. max. h(m)D2 1 2410 3290 17.5-19 18.613149 18.684626 2 2400 3335 8.0-9.0 10.181195 9.806911 3 2355 3315 7.0-8.0 7.270638 7.386148 4 2345 3380 7 6.775814 6.895801 5 2335 3175 0.2 0.000 0.00 6 2335 3420 5.0-6.0 7.464109 7.615280 7 2330 3365 6 6.101556 6.143140 8 2315 3450 5 6.561674 6.679546 9 2310 3590 0 0.304004 0.119698 10 2303 3255 4 3.887516 3.979779 11 2285 3425 2 3.039008 3.194761 12 2285 3500 5.0-6.0 4.772985 4.909878 13 2280 3280 2.5-3.0 4.186196 4.330580 14 2266 3550 2 3.549098 3.122085 15 2265 3400 0 1.928118 2.134662 16 2259 3530 3.0-4.0 3.698947 3.802850 17 2250 3440 0 0.661666 0.901334 18 2230 3525 0 1.041024 1.215631 19 2205 3445 2.0-3.0 2.026697 2.257170 20 2195 3440 2 1.857008 2.096829 21 2190 3485 0 0.000 0.00 Table 5.5: Gauges p osition, estimated maximum water depth and simulated water depth The results for gauges 9 and 10 show go o d agreement with eld observations. Gauge lo ation 9 remained dry along the o o ding and the simulation provides a maximum water depth in the sale of the entimeters. The numerial results for gauge 11 indiate an overestimation of the eld water depth estimation of approximately 1 m , whilst very go o d agreement is found for gauge 12. The simulations at the gauge lo ations 13 and 14 overestimate eld observations in approximately 1 m . Gauge lo ation 15 remained dry along the o o ding whereas the numerial simulation did not. On the other hand the results for gauge lo ation 16 are in go o d aordane with the observed eld data. Gauges 17 and 18 remained dry but the simulation estimates a maximum depth of nearly 1 m . The results for gauge lo ations 19 and 20 and 21 are in aordane with eld observations. The evolution of the omputed o o ding an b e seen in plan view in Figure 5.10 for times t= 5, 10, 15, 20, 25, and 30 hours. The omputed ow advanes and passes around the buildings but always moving inside the limit given by that line. Although mesh D1 has larger ells than D2 the numerial preditions from b oth grids are in general in agreement with observed data. It is remarkable that for this extreme event, despite the dierent lo ations of the inlet disharge setions and the dierent size of the ells in D1 and D2 , the water depth results for D1 are only slightly inferior than the ones obtained with D2 . 38
5.3. COMPARING WITH A DISTRIBUTED MEMORY PARALLEL IMPLEMENTATION It is very useful, when an exhaustive study is required, to rene the mesh in the area of interest. In this ase, the main trouble is to stablish the input hydrograph. Although water depth has no many signiative dierenes Figure 5.12 and 5.13, velo ity has not the same b ehaviour (Gauges 5 and 21 have b een ommited b eause of b oth have alulated the dry state). In Figure 5.15 is p ossible to appreiate the dierenes where the simulation p erformed with the oarse mesh makes a higher estimation of the velo ity. As displayed by the results of the water level time evolution at the gauges, the mesh renement in the zone of interest improves the quality of the preditions. The GPU simulation of the omputation on the rened mesh was 22 hours and 20 minutes (more than 28 days of simulation using CPU) and that for the oarse mesh was 5 hours and 30 minutes. The oarse mesh was a go o d aproximation of how the o o d advanes but not always an b e used to study the details in a partiular area. 5.3 Comparing with a distributed memory parallel implementation 28-Core ⋄ 1-Core GPU Cells 106648 CFL 0.9 tn 400.0 h0 5 - 0 Comp. Load (s.) 363.2 9383.83 250.79 Sup 25.84 37.41 Table 5.6: Computational load for a Dam-Break simulation (400 s.) with the mono-ore version, the MPI paralellized version and the new CUDA version. ⋄ Eah ore omes from an Intel i7 CPU 860 2.80 GHz This ase simulates the evolution of two onneted b oxes where one of them ontains 5 m. of water level and the other one is dry. The initial onditions and geometry are shown at 5.16. The reason to inlude this additional test ase is that it was run previously with a CPU version of the metho d paralellized through distrubuted mahines paradigm using Standard MPI. The simulation was run during 400 s. dumping data eah 200 time-steps. Furthermore, it has b een used CFL=0.9 and a manning o eient of m= 0.03 . The results show that the p ower of omputing of the GPU is omparable with the p ower of more than 30 omputers working at the same time using the Distrubuted Computing paradigm. Although CUDA programming is not as easy as MPI programming and it is imp ortant to note that not every implementations supp ort b oth kind of implementations, the p erformane of the rst tehnique is muh b etter. 39
CHAPTER 5. RESULTS Figure 5.12: Simulated and estimated water depth in 1-11 Gauges. 40
5.3. COMPARING WITH A DISTRIBUTED MEMORY PARALLEL IMPLEMENTATION Figure 5.13: Simulated and estimated water depth in 12-21 Gauges. 41
CHAPTER 5. RESULTS 0 2000 4000 6000 8000 10000 12000 14000 16000 0 20000 40000 60000 80000 100000 120000 140000 160000 Discharge (m3/s) t (s) 0 2000 4000 6000 8000 10000 12000 14000 16000 0 20000 40000 60000 80000 100000 120000 140000 160000 Discharge (m3/s) t (s) Figure 5.14: Tous syntheti hydrograph for D1 (Right) and D2 (Left) Figure 5.15: Comparison of Left: Coarse mesh velo ity mo dule and Righ: Rened mesh veloity module at t= 13h Figure 5.16: Initial onditions of water depth and mesh plot 42
5.3. COMPARING WITH A DISTRIBUTED MEMORY PARALLEL IMPLEMENTATION Figure 5.17: 5-0 Dam-Break simulation for (Right-Left, Top-Down) t=5, 10, 15, 20, 25, 30 seonds 43
44
6 Conlusions and future work A rst order nite volume sheme to disretize the Shallow Water equations on unstrutured meshes has b een implemented using GPUs. The asso iated sp eed-up has b een studied when solving dierent problems with nVidia Tesla Series 2070. The diulties generated by the use of unstrutured meshes have b een identied and partially overome so that our results show that it is p ossible to solve many dierent problems 30 times faster than a ommon CPU version on a single pro essor. Furthermore, only mahine preision dierenes are enountered b etween b oth implementations, so it is imp ortant to note that the sp eed of the simulation do es not aet the preision of the numerial metho d. Communiating data b etween CPU and GPU has a very exp ensive ost. An interesting strategy to redue the impat of the ommuniation has b een prop osed. The only neessity of ommuniation is the elapsed simulation time so that the CPU shedules the op erations. Previous work related to reduing the omputational ost by means of parallel CPU programming has b een ompared, showing that a GPU ould b e faster than 30 CPU ores involving less investment and less energy onsumption. The values of 50-100x sp eed-up announed in the related literature have not b een reahed in our implementation. Our interpretation is that it is not p ossible to b e more than 42 times faster than a CPU pro essor when working with double preision data and serious and areful sp eed-up omparisons are required in any ase. Although it is very ompliated to reah the theorial p erformane p eak, b oth implementations ould reah a reasonable p ower, so if b oth implementations are mostly optimized, sp eed ups like the related in this work are aeptable. As further work, it is interesting to explore the Multi-GPU paradigms, simulating with many GPUs and to study other implementations whih p erform the memory aess pattern under unstrutured meshes. 45
46