Full text
Universitat Polit`ecnica de Catalunya Escola T`ecnica Superior d’Enginyeria de Telecomunicaci´o de Barcelona Design and Implementation of a PTX Emulation Library by Albert Claret Exojo Advisor: Isaac Gelado Fern´andez Barcelona, July 2009
Dedicado a mis padres y a Susan, por su paciencia, cari˜no y apoyo.
Contents Contents i 1 Introduction 3 1.1 Motivation and Objectives ................... 3 1.2 Emulation Library Overview .................. 7 1.3 Thesis Overview ......................... 8 2 Background 9 2.1 GPU History .......................... 9 2.2 The NVIDIA CUDA Architecture ............... 11 2.2.1 Computing Model .................... 11 2.2.2 Computing Hardware .................. 14 2.3 Emulation ............................ 17 2.3.1 Techniques ........................ 17 2.3.2 Emulators ........................ 18 2.4 Software Profiling ........................ 20 3 Design and Implementation 21 3.1 Overview ............................. 23 3.2 PTX Parser (libptx) ...................... 24 3.3 Intermediate Code Analysis (libasm) ............. 28 3.4 OPBF Generation (libopbf/opbfas) .............. 33 3.5 Emulation Library (libemul) .................. 38 3.6 CUDA Runtime Library (libecuda) .............. 45 4 Experimental Evaluation 49 4.1 Benchmark Descriptions .................... 49 4.2 Testing Conditions ....................... 52 4.3 Functional Results ....................... 54 4.4 Performance Evaluation .................... 55 i
ii CONTENTS 4.5 Emulation Library Profiling .................. 61 5 Conclusions and Future Work 63 Bibliography 65 List of Figures 69 List of Tables 70 List of Code Listings 71
Acknowledgements Ante todo, quiero agradecer a Isaac Gelado su paciencia, ayuda y apoyo durante estos meses. A pesar de mis infinitas dudas y preguntas, no le he escuchado quejarse ni una sola vez. Tambi´en quiero agradecer el apoyo y la paciencia a mi madre, que probablemente se alegrar´a tanto o m´as que yo de que haya acabado la carrera, a mi padre y a Susan. Sin vosotros, no lo hubiera logrado. Y por ´ultimo, agradecer el apoyo de mis amigos, que me han aguantado y, por alg´un extra˜no motivo, siguen aguantando todos los d´ıas. Gr`acies als Budgets, als de R3, als de DAT, als de les altres plantes de l’Edifici Omega, a la gente del C.EE.T., a Las Ni˜nas, a los de La Salle, a los pibes del ITBA, al resto de los amigos que dej´e en la Argentina, a los compa˜neros del C6-103 por ayudarme durante estos meses y a mis viejos amigos del ASB. 1
Chapter 1 Introduction 1.1 Motivation and Objectives Intel co-founder Gordon E. Moore observed in 1965 that transistor density, the number of transistors that could be placed in an integrated circuit per square inch, increased exponentially, doubling roughly every two years. This would be later known as Moore’s Law, correctly predicting the trend that governed computing hardware manufacturing for the late 20th century. For many decades, software developers have enjoyed a steady application performance increase due to continuous hardware improvements as described by Moore’s Law, as well as computer architecture improvements. Currently, however, the memory wall, which refers to the increasing speed difference between the CPU and memory, and the instruction-level parallelism wall (ILP wall), which refers to the inability to find more operations in an application which can be performed simultaneously due to data dependency, have been reached. Application performance no longer benefits from continuous processor frequency increases as it had before. Furthermore, other issues such as wire delays and static and dynamic power density prevent significant processor frequency increases [1]. The High-performance Computing (HPC) community has developed several strategies to work around these limitations [2]: •Multi-core systems, where a processor includes several independent cores in a single integrated circuit. This strategy currently serves as the most viable candidate to uphold Moore’s Law. Despite this, applications that heavily rely on sequential calculations would only see major advances if the processor frequency increased several orders of magnitude. 3
10 CHAPTER 2. BACKGROUND NV30 NV35 NV40 G70 G70-512 G71 Geforce 8800 GTX Tesla C870 Tesla C1060 3 GHz P4 Pentium D 965 Core 2 Duo X6800 Core 2 Quad QX6700 Core i7 965 0 100 200 300 400 500 600 700 800 900 1000 Jan 2003 Jul 2003 Jan 2004 Jul 2004 Jan 2005 Jul 2005 Jan 2006 Jul 2006 Jan 2007 Jul 2007 Jan 2008 Jul 2008 Jan 2009 GFLOPS Figure 2.1: GPU vs CPU Performance Gap (Based on [12, c.1, p.2]) point performance race. CPUs, on the other hand, have slowed down their performance improvement significantly [12]. This can be clearly seen in Figure 2.1. It should be noted that the graph shows the theoretical peak speed that both CPUs and GPUs can achieve, which is not necessarily reachable. This performance gap is probably the reason for the current GPGPU trend and has motivated many application developers to move the computationally intensive parts of their applications to the GPU when tools have been made available. As mentioned in Section 1.1, NVIDIA saw the potential for the GPU to use its huge computing power for uses outside of purely graphics calculations. In February 2007, they launched CUDA, a SDK and API that allows the development of applications that run on the GPU. It has proven to be very popular among the research community, as it can offer large performance benefits [12]. After being bought by AMD, ATI launched a similar SDK for their own cards called Stream SDK, formerly called Close to Metal (CTM). Even though the first general purpose computing efforts on a GPU was on AMD
2.2. THE NVIDIA CUDA ARCHITECTURE 11 ATI cards in October 2006 [13], NVIDIA strongly backed and publicized CUDA, leaving AMD ATI out of the public spotlight. Some people have claimed that the original CTM API was difficult to work with, besides coming much later than CUDA. Soon after releasing the Steam SDK which supposedly fixed the shortcomings of the CTM API, AMD ATI and NVIDIA announced future support for OpenCL [14]. 2.2 The NVIDIA CUDA Architecture There are three main abstractions in the CUDA architecture: thread groups, shared memories and barrier synchronization. These are all available to the programmer as a minimal set of C extensions. These abstractions allow programmers to partition a problem into sub-problems that can be solved independently in parallel. The problem can then be further split into smaller pieces that can be solved cooperatively in parallel. This approach can be applied to algorithms that can be expressed as data-parallel computations with a high ratio of arithmetic to memory operations. 2.2.1 Computing Model The CUDA API allows programmers to define C functions which are known as kernels. The control-intensive parts of the algorithms are implemented in the host code, while the data parallel parts are implement in kernels. The host code is executed by the CPU, while the kernels are executed by the GPU. When called, kernels are executed in parallel N times by N different threads. Each of these threads is given a unique thread ID that is accessible to the programmer by the threadIdx variable. This allows to distinguish themselves from each other and identify the appropriate portion of the data to process, as they all receive the same parameters. The host code and the device code (kernels) can be stored in the same source file. As we can see in Listing 2.1, both the kernel and host code are written in an extended version of ANSI C. The global keyword is used to declare a kernel, and the kernel name <<<X, Y>>> syntax is used to specify the number of threads for each kernel call. This example adds two vectors A and B of size N and stores the result into vector C. Each of the threads that execute the kernel does a single addition, corresponding to its threadIdx value.
12 CHAPTER 2. BACKGROUND Host Device Grid 1 Block (0,0) Block (1,0) Block (0,1) Block (1,1) Grid 2 Kernel 1 Kernel 2 Block (0,1) Thread (0,0,0) Thread (1,0,0) Thread (2,0,0) Thread (3,0,0) Thread (3,1,0) Thread (2,1,0) Thread (1,1,0) Thread (0,1,0) Thread (3,2,0) Thread (2,2,0) Thread (1,2,0) Thread (0,2,0) T (0,0,1) T (1,0,1) T (2,0,1) T (3,0,1) Figure 2.2: CUDA Thread Hierarchy (Based on [12, c.2, p.10]) __global__ void vecAdd(float* A, float* B, float* C) { int i = threadIdx.x; C[i] = A[i] + B[i]; } int main(int argc, char *argv[]) { vecAdd<<<1, N>>>(A, B, C); return 0; } Listing 2.1: Basic Kernel Example (Taken from [15, p. 13]) CUDA organizes threads in a two-level hierarchy: grids and thread blocks. This can be seen in Figure 2.2. When a kernel is launched, it is executed by a grid of threads. This grid can be seen as a 2D array of thread
2.2. THE NVIDIA CUDA ARCHITECTURE 13 blocks. Each of the grids is usually formed by thousands to millions of GPU threads per kernel invocation. All blocks in a grid have the same number of threads, and are organized into a 3D array of threads. Each thread block has a unique 2D coordinate which can be accessed by the blockIdx.x and blockIdx.y variables. The number of blocks per grid can be accessed by the gridDim.x and gridDim.y variables. In the case of Listing 2.1, most of the hierarchy is ignored, and only one dimension of threadIdx is used. Since it is actually a 3-component vector with x, y and z coordinates, it allows threads to be identified using 1D, 2D or 3D indexes, forming 1D, 2D or 3D thread blocks. The first parameter passed to the kernel is the number of blocks per grid. In Listing 2.1, this value was . The block dimensions (number of threads in each dimension of the block) is supplied by the programmer as the second parameter given at the kernel launch. In Listing 2.1, the block dimension was N. Since the NVIDIA Tesla architecture limits the maximum number of threads per block to 512, this is the total number of elements including all dimensions. The developer has flexibility to chose any distribution of these elements on each dimension, as long as the total number does not exceed 512. A kernel launch, is therefore defined as kernel name <<blocks per grid, threads per block>>. It should be noted that once a kernel is launched, its dimensions cannot change during that invocation. From a programmer point of view, this is a disadvantage, since dynamic dimensions would allow kernel algorithms to be refined. From a performance point of view, it is an advantage, since fixed dimensions allow the hardware to not have resizing capabilities, therefore increasing performance. From our emulation point of view, supporting dimension resizing would complicate the implementation, and therefore the lack of it is an advantage. There is ongoing research[16] about dynamically resized kernels. Threads within the same thread block can cooperate among themselves by sharing data. The sharing is done through the shared memory area and synchronization is performed by using the function syncthreads(). This function performs barrier synchronization, a popular method of coordinating parallel execution. When called, all threads in a block will be stopped at the location until everyone else reaches it, ensuring that all of them have completed a phase of the execution before being allowed to continue. It should be noted that threads in different blocks do not perform barrier synchronization with each other, and therefore, different blocks can be executed in any order and in parallel or in series. This allows application scalability, as newer GPU cards support more blocks to be executed in parallel and
14 CHAPTER 2. BACKGROUND Host Grid Block (0,0) Shared Memory Registers Registers Thread (0,0) Thread (1,0) Block (1,0) Thread (0,0) Thread (1,0) Shared Memory Texture Memory Local Memory Local Memory Local Memory Local Memory Global Memory Registers Registers Constant Memory Figure 2.3: CUDA Memory Hierarchy (Based on [12, c.4, p.3]) therefore can benefit from the independence among different blocks. There are several memory spaces which CUDA threads may access, as seen in Figure 2.3. Each thread has a specific local memory and registers, each thread block has a common shared memory and all threads have access to a global memory space. Additionally, the constant and texture memory spaces provide read-only access. Developers can declare variables into the various spaces by using specific keywords, such as device shared or device constant . Physical characteristics of the spaces are discussed in Section 2.2.2. 2.2.2 Computing Hardware The NVIDIA Tesla architecture is based on a scalable array of multithreaded Streaming Multiprocessors (SMs). [15] A multiprocessor contains 8 Scalar Processor (SP) cores. The multiprocessor creates and executes threads concurrently in hardware with a virtually zero scheduling overhead. Fast barrier synchronization with the syncthreads() function along with the zero-overhead scheduling allows for fine-grained parallelism: assigning, for example, one thread per pixel. The multiprocessor employs an architecture called Single-Instruction, Multiple-Thread (SIMT). Each thread is mapped to one SP core, and each SP core executes independently with a dedicated instruction address and
2.2. THE NVIDIA CUDA ARCHITECTURE 15 register state. This technique is similar to Single Instruction, Multiple Data (SIMD), used in many architectures, such as the IBM Cell. The use of the SM and SP terminology can lead to confusion. The behavior of an SM is closer to a core, as it performs fetch, decode and control on an instruction. An SP, however, is similar to an Arithmetic Logic Unit (ALU), as it just performs the instruction execution. The terminology is used by NVIDIA in its CUDA and PTX documentation, so we will adhere to it. The multiprocessor manages threads in groups of parallel threads called warps. The size of this warps is implementation specific, in the GeForce 8800GTX, warps are made up of 32 threads. It should be noted that all threads in a warp start at the same program address, but they are obviously free to differ once branching occurs. Every time a new instruction can be executed, a warp that is ready to execute is selected and run. If threads on a warp diverge, the warp executes serially each path taken, a phenomenon called branch divergence. It only occurs in a single warp, as different warps will execute independently. Warps play a crucial role in preventing long delay operations such as global memory access from slowing down the execution. When an instruction executed by a warp is waiting for the result of a long operation, the warp is placed on hold, and another warp that is ready for execution is loaded in its place. When the first warp is ready, it will be queued for execution. If there are enough warps, there will most likely always be one of them ready for execution, effectively delaying the execution but increasing throughput. This technique is called Simultaneous Multi Threading (SMT) [17], and tries to exploit parallelism across multiple threads, due to the fact that a single threads has a limited amount of ILP. The GeForce 8800GTX, for example, has 16 SMs, allowing up to 128 thread blocks to be executed simultaneously. One important SM limitation is the number of threads that can be scheduled. In the GeForce 8800GTX, the limit is 768 threads per SM (24 warps), which would result in a total of 12288 threads simultaneously executing. Figure 2.4 shows how the CUDA memory hierarchy is implemented in the SIMT architecture. Every processor core has a complete set of 32-bit processors, a shared memory space, shared by all cores in a SM and readonly constant and texture cache memories shared by all cores. In the GeForce 8800 GTX implementation, each SM has 8000 registers. Since each SM can hold up to 768 threads, this amounts to a total of only 10 registers per thread. If each thread uses more than 10 registers, the total
16 CHAPTER 2. BACKGROUND Grid Multiprocessor 1 Shared Memory Registers Processor 1 Texture Cache Local Memory Local Memory Constant Cache Multiprocessor 2 Multiprocessor N ... Registers Local Memory Registers Processor 1 Processor M ... Device Memory Instruction Unit Figure 2.4: GPU Hardware Model (Based on [15, p.14]) number of threads will be reduced. Since this penalty occurs at the block level, the number of threads will be reduced significantly, such as 128 if each block contains 128 threads. This is a clear example of the fact that memory is a limiting factor in CUDA parallelization, and so code must be optimized to utilize the least amount of available resources. The number of threads can reduce the number of warps available, and therefore increase the latency when many long-latency operations such as global memory accesses occur. Besides the register limiting factor, excessive shared memory usage can lead to the same problem. In the GeForce 8800 GTX, there are 16kB of shared memory in each SM, so each block should not use more than 2kB of it, or the number of blocks will be reduced as described before. Memory characteristics of the different spaces available in the CUDA architecture as implemented on a GeForce 880GTX GPU are shown in Table 2.1. The global memory serves as the storage area for the texture and constant areas. Access to global memory is more efficient when multiple threads access contiguous elements. On the other hand, shared memory, whose scope is limited to threads in the same thread block, is used as a local scratchpad. Constant memory is often used for lookup tables, due to its low
2.3. EMULATION 17 Space Size Latency Read-Only Global 768MB total 200-300 cycles RW Shared 16kB/SM wRegister Latency RW Constant 64kB total wRegister Latency RO Texture Up to global >100 cycles RO Local Up to global 200-300 cycles RW Table 2.1: Memory spaces in a GeForce 880GTX GPU (Based on [8, p.3]) latency. Texture memory can be used to perform hardware interpolation and can be configured to wrap around the edges of the texture. These characteristics are used in certain applications such as video encoding. Local memory is usually used for register spilling. 2.3 Emulation 2.3.1 Techniques An emulator duplicates the functionality of one system using a different system, in a way that allows the second system to behave exactly like the first one. [18] The following is a brief list of currently employed emulation techniques. •Binary translation[19,18] is the emulation of a CPU instruction set (source) on a different instruction set (target) by using code translation. In static binary translation, a complete executable file for the source architecture is translated into an executable file of the target architecture. On the other hand, dynamic binary translation processes a short sequence of code, typically a single basic block, translating it and caching the result. •Native execution[20], also called direct execution, is the execution of instructions of an emulated CPU directly on the host CPU. This is obviously only possible when both instruction sets are the same. Privileged instructions such as I/O are usually not directly executed, as they would affect the operating system running the emulation. Instead, they are usually interpreted. •Dynamic recompilation[21,18] is a feature utilized by some emulators where the emulator recompiles part of a program during execution.
18 CHAPTER 2. BACKGROUND This is usually done to produce more efficient code that perhaps was not available to the compiler or perhaps due to a poor optimization. It is also known as just in time compilation, or JIT. •Interpretation[18] is the slowest emulation technique available, usually performed by parsing the emulated assembly code in a high-level language such as C, and then performing the operations described in the code. •Virtualization[20] is a technique used to implement a virtual machine environment, completely emulating the underlying hardware. All software that can run on the simulated hardware should run on the virtualized environment without any modification. A key aspect of virtualization is the emulation of I/O and other privileged operations that can not be executed directly and must be emulated. It requires instruction set (ISA) compatibility between the emulated and emulating hardware. 2.3.2 Emulators The following is a list of several modern emulators which utilize the tecniques described in Section 2.3.1 and which were taken into consideration when designing the PTX emulator developed in this thesis. •QEMU [22] is a generic open source machine emulator and virtualizer. As a processor emulator, it allows running operating systems and applications made for one architecture on another one. Besides CPU emulation, it also provides a set of device models for peripherals such as video, network or sound cards, which allow it to run numerous operating systems without any modification. The host CPUs supported are x86 (both 32-bit and 64-bit) and PowerPC, while the main supported target emulated CPUs are x86, ARM, SPARC, MIPS, m68k and CRIS. It uses dynamic translation to achieve reasonable performance, and an accelerated mode supporting a mixture of binary translation and native execution. Several software-based accelerators were written to speed up execution. The main one was KQEMU, which speeds up x86 on x86 emulation, by running user mode code directly on the host CPU instead of emulating it. Unlike Linux Kernel-Based Virtual Machine (KVM), it does not require hardware CPU virtualization. Linux KVM is a
2.3. EMULATION 19 virtualization infrastructure implemented in the Linux kernel which supports native virtualization using Intel VT or AMD-V hardware virtualization support. •Bochs[23] is a cross-platform open source x86 (32-bit and 64-bit) emulator. It supports emulation of several processors (386, 486, Pentium up to Pentium 4, and several 64-bit processors) and peripherals, allowing the execution of many guest operating systems such as a Linux, DOS or Windows. Since it uses interpretation and is written in cross-platform code, it runs on many non-x86 systems such as Solaris (Sparc), GNU/Linux (PowerPC/Alpha), MacOS (PowerPC), IRIX (MIPS), BeOS (PowerPC), Digital Unix (Alpha) and AIX (PowerPC). Its emulation method results in very slow performance, and so it is mainly used by hobbyists or OS developers. •PearPC [24] is a cross-platform open source PowerPC emulator, allowing the execution of operating systems such as a PPC Linux or Mac OS X to run in other architectures, mainly x86. Besides the CPU, it also emulates a PCI bridge, an IDE controller, a network controller, among others. If the host is running in an x86 processor, it translates PowerPC instructions into x86 instructions and caches the results, incurring in a slowdown of only 15 times than the host. On non-x86 platforms, it fully emulates the CPU, making it run 500 times slower than the host. •VMWare Inc.[25] is the major virtualization software vendor. Its products provide virtualized peripherals and processors, allowing users to set up multiple x86 (32-bit and 64-bit) virtualized operating systems. They do not emulate an instruction set for different hardware not physically present, utilizing native execution on user code and dynamic translation for kernel code, providing a significant performance boost, running at 80% of the achievable speed. •VirtualBox[26] is an x86 virtualization software, originally created by Innotek and currently developed by Sun Microsystems. It is very similar in features and characteristics to VMWare Workstation, but besides a commercial version, an Open Source edition is available. It supports hardware virtualization using the Intel VT-X and AMD AMD-V extensions.
26 CHAPTER 3. DESIGN AND IMPLEMENTATION which is a parser generator, that converts a grammar into C parser code for that grammar. Instruction BRSInstruction RSInstruction CBInstruction SVSInstruction RSTInstruction GETInstruction UNIInstruction SOTInstruction OPInstruction Figure 3.4: Instruction Classes Hierarchy Parsed instructions are stored in a hierarchy of C++ classes, which all derive from the base Instruction class. These classes, as shown in Figure 3.4, are RSInstruction,BRSInstruction,CBInstruction,SVSIn struction,RSTInstruction,GET Instruction,UNI Instruction,SOTIn struction and OPInstruction. Instructions are organized into these different types according to the number of modifiers and operands. The MUL24 opcode performs the multiplication of the 24 most significant bits of a register and an integer, and stores the result in a third register. It can have up to three modifiers: bits to consider, rounding and saturation. Therefore, it is a BRS instruction. An Instruction object contains all the instruction information, such as the operands, modifiers or source and/or destination type. Obviously, a proper flex grammar definition must be in place in order for the bison code to be straight forward. Listing 3.2 shows a bison semantics snippet for the previously mentioned MUL24 opcode. It shows how the opcode is parsed as a sequence of tokens: the MUL24 token, a bit token, a TYPE token, and so on. Then, the Instruction object is created and initialized with the instruction modifiers by the BRSIns function. The addReg and addValue store the instruction parameters. In this case, the destination and source registers and the multiplication constant. | MUL24 bit TYPE reg COMMA reg COMMA value { BRSIns(_mul24, (bit_t)$<i>2, _no_rnd, false, (type_t)$<i>3); addReg(Dst, (type_t)$<i>3, $<reg>4); addReg(Src, (type_t)$<i>3, $<reg>6); addValue(Src, (type_t)$<i>3, $<value>8); } Listing 3.2: MUL24 opcode bison semantics A basic working version of the code in libptx, including the PTX grammar and parser, had already been developed by my advisor Isaac Gelado
3.2. PTX PARSER (LIBPTX) 27 prior to the beginning of this thesis. There have been, however, numerous additions and bug fixes applied to the code during the thesis development, including the following. •Added the original PTX line number to an instruction to ease the debugging process, particularly basic block visual identification, which can now be done by the start and ending source code line. •Added support for zero-sized vectors, which use all the available shared memory space. This technique is used by the sad benchmark. (Section 4.1) •Although PTX defines all fundamental types (signed integer, unsigned integer, floating point, untyped) with different lengths (8, 16, 32 and 64 bits), these lengths were originally simplified to just 32 and 64 bits. This simplification worked for most cases, but it did not for the sad benchmark, as several kernel parameters were 16 bit integer arrays, which were incorrectly treated as 32 bit integer arrays due to the simplification. Because of this, full support for all lengths was added. More details are available in Section 3.4. •Added support for vectors in the LD and ST opcodes, which allow direct access to up to four-element vectors in a single instruction. These instructions are parsed as a single instruction, but they are split into separate instructions for the OPBF generation. Therefore, an instruction such as ld.global.v4.u32 $r9,$r10,$r11,$r12, [$r8+0] is split into four separate instructions: ld.global.u32 $r9,[$r8+0], ld.global.u32 $r10,[$r8+4],ld.global.u32 $r11,[$r8+8] and ld.global.u32 $r12,[$r8+12]. •Added grammar support for the TEX opcode, as described in Section 3.5. •Fixed a register allocation bug, as described in Section 3.3. It was caused by the ST opcode when used with indirections, such as in the example case st.volatile.shared.u32 [$r107+0], $r114. In this case, register 114 was marked as the source register and register 107 was marked as the destination register. This was incorrect, due to the fact that they are both source registers, as register 107’s value is used to determine the actual memory address to access. This bug caused register 107 to be overwritten before reaching this instruction, as it
28 CHAPTER 3. DESIGN AND IMPLEMENTATION was marked as a destination and not as a source, and therefore was reused by the register allocation process. •Fixed minor bugs, such as the incorrect parsing of the MUL24 opcode, the incorrect parsing of negative float values. •Added support for the volatile modifier in the grammar, which was added in the PTX ISA 1.1. Due to the emulation architecture, this modifier is simply ignored, as all memory locations are considered volatile. 3.3 Intermediate Code Analysis (libasm) The parsed instructions that result from the parsing performed by libptx are stored in a vector of Instruction objects. libasm’s primary goal is to perform register allocation on the PTX code. As seen on Listing 3.1, the generated intermediate assembly language code does not perform register allocation: it always uses a new register, without reusing unused ones. Register allocation is the process of assigning a big number of variables onto a reduced number of CPU registers. On a GPU architecture, the number of registers available is abnormally large (8000) compared to a conventional CPU (16 in a 32-bit x86 architecture). As noted in Section 2.2, however, if the number of registers per thread is greater than 10, the total available number of threads will be reduced. Therefore, register allocation is surely performed on the PTX code when assembling the Cubin format. Emulating it correctly, therefore, requires a reasonable register allocation to be performed on the code. A basic requirement of register allocation is building a control flow graph (CFG) of the application code. A CFG represents all paths that can be taken during the execution of an application. Figure 3.6 shows a simple CFG. In a CFG, each node presents a basic block (BBL), which is a group of consecutive instructions without any jumps or any jump destinations. Therefore, a jump destination marks the start of a BBL, and a jump marks the end of a BBL. In order to construct the CFG, all BBLs in the code must be identified. In our case, this is performed in two steps. First, when parsing the PTX code, as described in Section 3.2, a first approximation is to split the code into BBLs according to those lines with labels: these mark the start of at least some of the BBLs. Further along, in libasm, these BBLs are in-
3.3. INTERMEDIATE CODE ANALYSIS (LIBASM) 29 Figure 3.5: tpacf benchmark CFG
30 CHAPTER 3. DESIGN AND IMPLEMENTATION spected for jump instructions, and split accordingly, resulting in a complete identification of all BBLs. An initial version of the register allocation implementation was developed by my advisor Isaac Gelado. Basically, registers were freed when a their values were not found to be used in the remaining BBLs of the program flow. Then, a register map of the allocated registers was propagated to each BBL edge. This version worked on small CFGs, such as the matrix multiplication benchmark (Section 4.1) CFG shown on Figure 3.6, and was relatively efficient, in that it allocated a small number of registers. The BBL node names identify the source code line intervals contained in each block. The graph nodes, BBLs, were visited in a depth-first search order, in the case of Figure 3.6, this order would be 77:90, 91:122, 126:188, 189:189, 194:203, 191:191. Figure 3.6: matMul benchmark CFG Problems arose, however, when more complex benchmarks such as the tpacf benchmark were tested. The complete CFG for this benchmark is shown on Figure 3.5. As we can see, this was a much more complex graph, and after extensive debugging, the register allocation algorithm was found to be failing. Later on, it was discovered that although the PTX code was in static single assignment form (SSA) for small kernels, it was not for larger-sized kernels, leading to complications. Figure 3.7 shows a small subset of the tpacf benchmark CFG, from its upper part. As we can see from the graph, the program execution flow could take two distinct paths, either through the 129:143 BBL (lines 129
3.3. INTERMEDIATE CODE ANALYSIS (LIBASM) 31 Figure 3.7: Subset of the tpacf benchmark CFG to 143 from the PTX code) or thorough the 146:161 BBL. The register allocation algorithm failed to analyze that, even if a register was not used in the path that goes through the 129:143 BBL, it could be used in the path that went through path 146:161. This caused several registers to be freed and overwritten in the 119:127 BBL, even if they were used in the 146:161 BBL. In order to fix this bug, register dependencies had to be propagated to parallel branches. That is, when reaching node 129:143, registers that were previously allocated in 119:127 should not be reused in node 129:143. The same reasoning applied to node 146:161. Then, when reaching a collecting node such as 163:165, registers that could be freed in both branches are actually freed. In order to perform this, the CFG must be visited in a different order, a balanced search in this case, which in this case would be 119:127, 129:143, 146:161 and finally 163:165. This solution was successfully implemented, although it resulted in an excessively high number of registers, due to it being an excessive conservative approach, specially in very highly branching cases such as those shown in Figure 3.5. Problems arose, however, when applying the algorithm to the rpes CFG. Several hacks had to be applied in the algorithm to correctly traverse that CFG. It was clear that the existing register allocation approach was incorrect, with a high number of registers consumed and code changes needed when the complexity of the CFG increased, due to the more challenging balanced graph visiting. Several popular register allocation algorithms were then considered, to completely replace the existing code. There are several long-established algorithms to perform register allocation, the most popular one being graph coloring. This method usually results in an effective allocation without a major cost in compilation speed [35]. The final working register allocation that was implemented was via coloring of chordal graphs [36,37].
32 CHAPTER 3. DESIGN AND IMPLEMENTATION In this implementation, register allocation by graph coloring [35] is performed in the following steps, as shown in Figure 3.8. First, liveness analysis must be performed on the previously obtained CFG. Then, interference analysis is performed on the CFG, building an interference graph. Finally, registers are assigned by greedy coloring. CFG Generation Liveness Analysis Interference Graph Instruction Vector Greedy Colouring Figure 3.8: Register Allocation Workflow Liveness analysis is performed by calculating, for each BBL in the CFG, which registers are live in each BBL of the CFG. A register is considered to be live if its value is used at some point during the remainder of the code, without redefining it. It is dead if its value is redefined before using it, or not used at all. We have implemented liveness analysis by using backward propagation [38]. Let us take, for example, the instruction x = y + z. According to this implementation, yand zare live at this point since they are used in a calculation, while xis dead since its value is overwritten. It is easy to go backwards, starting from the last instruction, and apply these two rules. This approach is only valid on straight-line code, without jumps and conditional branches. In that case, several iterations should be made until no further information is acquired, typically 2 or 3 iterations are needed. Two registers are said to interfere if there are two BBLs where they are simultaneously live. In this case, it is possible that they contain different values at this point. Therefore, two registers that do not interfere can be merged into a single register. The interference graph is built to hold the interference information of all the registers. The nodes of the interference graph are the application registers. An undirected edge is inserted between two nodes if the two virtual registers interfere and should be assigned to different real registers. For a general instruction, an edge is created between the assigned register in that instruction and any future live registers. On a mov instruction, an edge is created between the destination register and all live registers live except for the source register. Register allocation is performed via graph coloring [36,37]. The problem of assigning colors to a graph (coloring) with K colors is NP-complete for K=3. Fortunately, programs in Static Single Assignment (SSA) form have chordal graphs, which makes the problem achievable in linear time. A program is said to be in SSA form if every variable is assigned exactly
3.4. OPBF GENERATION (LIBOPBF/OPBFAS) 33 once. Even if the program is not in strict SSA form and does not have a strict chordal graph, as some of our benchmarks, the algorithms behave reasonably well. In that case, the minimal number of registers (colors) is not used. A node in a graph is simplicial if all neighbors of a node are connected to each other. An ordering of all nodes in a graph is called simplicial elimination ordering if the last node of the list is simplicial. A simplicial elimination ordering can be found in linear time by implementing a maximum cardinality search. Given an ordering, greedy coloring is applied by assigning colors to the vertices in the exact simplicial order that has been found, always using the lowest available color. If the graph is chordal, this algorithm is guaranteed to use the fewest possible colors [38]. The chosen register allocation implementation is simpler than other more efficient implementations, and works for all tested CFGs. It provides reasonable efficiency: the matrixMul kernel occupies 24 registers. The original implemented algorithm used 17 registers, while the modified algorithm used 24 registers. The NVIDIA implementation of the PTX compiler uses only 14 registers, mainly due to dead-code elimination. 3.4 OPBF Generation (libopbf/opbfas) OPBF files are generated from a PTX file by the opbfas tool, which uses the previously described libptx and libasm to produce an OPBF file from a PTX file. Listing 3.3 shows a basic outline of the opbfas code. First, the input PTX file is parsed using libptx, storing a vector of Instruction objects, as described in Section 3.2. Then, register allocation is performed on the code, as described in Section 3.3. Finally, OPBF instructions are generated from PTX instructions and the binary file that contains the instructions is written. open(PTX file); parse(); /* using libptx */ registerAllocation(); /* using libasm */ generateBinaryCode(); /* using libopbf */ writeBinaryCode(); /* using libopbf */ Listing 3.3: opbfas basic pseudo-code
34 CHAPTER 3. DESIGN AND IMPLEMENTATION OPBFOp OPBFRbs OPBFRs OPBFCb OPBFMem OPBFRst OPBFGet OPBFUni OPBFSot OPBFOb Figure 3.9: OPBFOp Classes Hierarchy OPBFOp *OPBFOp::create(const PtxProgram &global, const PtxFunction &function, const Labels &labels, const Instruction &i) { switch(getFormat(i.op())) { case _rbs: if(i.op() == _mul || i.op() == _div) { return new OPBFRbs(global, function, labels, dynamic_cast<const BRSInstruction&>(i)); } else { return new OPBFRs(global, function, labels, dynamic_cast<const RSInstruction&>(i)); } case _cb: return new OPBFCb(global, function, labels, dynamic_cast<const CBInstruction&>(i)); case _svs: return new OPBFMem(global, function, labels, dynamic_cast<const SVSInstruction&>(i)); case _rst: return new OPBFRst(global, function, labels, dynamic_cast<const RSTInstruction&>(i)); case _get: return new OPBFGet(global, function, labels, dynamic_cast<const GETInstruction&>(i)); case _uni: return new OPBFUni(global, function, labels, dynamic_cast<const UNIInstruction&>(i)); case _op: return new OPBFOb(global, function, labels, dynamic_cast<const OPInstruction&>(i)); } return NULL; } Listing 3.4: OPBFOp creation from a PTX Instruction
3.4. OPBF GENERATION (LIBOPBF/OPBFAS) 35 Similarly to the Instruction class hierarchy, OPBFOp is a class hierarchy, with OPBFRs,OPBFRbs,OPBFCb,OPBFMem,OPBFRst,OPBFGet,OPBFUni and OPBFOb as subclasses. This is shown in Figure 3.9. Each of these subclasses represents the same type of instructions that its Instruction class counterpart represents. An OPBFOp object has all the instruction attributes needed to perform an operation: the exact instruction type, a source and destination register vector, an immediate value vector, among others. The OPBF instructions are generated from the PTX instructions in two passes, to be able to resolve all labels. This is due to the fact that, although PTX code uses labels for both jump destinations and to reference user variables (as seen in Listing 3.1, lines 90 and 80 respectively), in order to reduce the number of lookups performed during the emulation process, all labels are resolved to memory addresses at compilation time, since we are generating static code. In the first pass, a new OPBFOp object is generated for each instruction. The OPBFOp::create method, shown in Listing 3.4, is called. Labels for instructions that have not yet been generated will not be able to be resolved, and so any instruction that references unknown labels will be marked as invalid and added to a pending instructions vector. In the second pass, all of the pending instructions are visited, trying to resolve all remaining labels. At this point, all labels should be able to resolve, since all of the OPBFOp objects have been created. Once all the instructions have been created, all of the information is written into a binary file. It should be noted that neither the binary OPBF file nor the format itself is optimized for hardware execution, as is probably the case with the NVIDIA Cubin format. It is solely intended for emulation purposes. There are several parts to the OPBF file: the OPBF Header, which includes the OPBF Kernel Headers, the code, the global descriptors, variable initialization data, the kernel descriptors, and the label table. The general OPBF file header is shown in Listing 3.5, and is the first information found in the file. It contains a vector of kernel structures, as shown in Listing 3.6, which contain basic information for each kernel in the file, such as the kernel name or the entry point. The descriptors (both global and kernel descriptors) contained in the OPBF file are structured as shown in Listing 3.7. These hold information for the size of each descriptor, which correspond to the memory spaces defined in the PTX specification. The state spaces defined by PTX are registers (.reg), special registers (.sreg), constant memory (.const), global memory (.global), local memory (.local), parameters (.param), shared memory (.shared), surface memory
42 CHAPTER 3. DESIGN AND IMPLEMENTATION with generic types. That is, to code a single function instead of having to code different functions for different data types or to perform runtime typedecision code. Listing 3.11 shows a basic example of a template. With a single function, any two operands can be compared. The calling syntax includes the type, so a call to max<float>(4.5, 8.5) would invoke max function with float operands. This is only an example, as an operation as simple as calculating the maximum of two values could be achieved with a much simpler preprocessor macro. template <typename T> T max(T a, T b) { if(a > b) return a; else return b; } Listing 3.11: C++ template example When a C++ program with templates is compiled, on every call to a templatized function, the compiler creates a copy of the function with the templatized parameters. On the previous example, the compiler would generate a copy of the max function with double parameters. Therefore, the use of templates increases the binary size, but does not add any runtime overhead. In our case, an opcode template will have a template parameter for every operand type, and one or several template parameters based on the opcode data types. For example, the mul opcode (Listing 3.10, line 5) has a data type parameter and three operand type parameters. The data parameter can be an 8, 16, 32 or 64 bit signed or unsigned integer, a float, or a double. The first and second operand types are always registers (the destination and source registers, respectively), but the third operand (the second source operand for the multiplication) can either be a register or an immediate. All of these combinations must be supported, since an opcode could potentially use any of them, and that information will only be available when a kernel is loaded. A fragment of the code that decides, at runtime, which mul opcode implementation should be invoked is shown in Listing 3.12. This code is very repetitive and it can be automatically generated from a data type list and small amounts of information available for each opcode. This is
3.5. EMULATION LIBRARY (LIBEMUL) 43 accomplished by a Perl script that is executed on compilation time, which generates a function similar to the one shown in Listing 3.12 for each opcode. It should be noted that these functions take an OPBFOp operand as a parameter, which is used for obtaining the operation type (op.type()), or if the opcode has an immediate value (op.hasImmediate()). Exe Core::ExeMul(const OPBFOp &op) { switch(op.type()) { case _u32: if(op.hasImmediate()) return Mul<uint32_t, reg, reg, imm>; else return Mul<uint32_t, reg, reg, reg>; case _s32: if(op.hasImmediate()) return Mul<int32_t, reg, reg, imm>; else return Mul<int32_t, reg, reg, reg>; case _s16: if(op.hasImmediate()) return Mul<int16_t, reg, reg, imm>; else return Mul<int16_t, reg, reg, reg>; case _u16: if(op.hasImmediate()) return Mul<uint16_t, reg, reg, imm>; else return Mul<uint16_t, reg, reg, reg>; case _s8: if(op.hasImmediate()) return Mul<int8_t, reg, reg, imm>; else return Mul<int8_t, reg, reg, reg>; ... Listing 3.12: Mul Template Invocation These functions are only executed when generating the code cache, since the type parameters are fixed and cannot change at runtime. This has a strong positive impact on performance, since once the code cache is built, a pointer is available to the template version of the opcode execution function for each opcode. Therefore, once a kernel execution launches, no more type
44 CHAPTER 3. DESIGN AND IMPLEMENTATION comparisons are necessary. This approach also significantly reduces the amount of code needed to actually implement an opcode. Listing 3.13 shows the complete code of the function that implements the mul opcode. Thanks to templatization, the code is extremely straight forward. After obtaining pointers to the operands, they are simply multiplied and stored back. Then, the value of the program counter is incremented. This process makes opcode implementation straight forward. Because of this, about 60% of the opcodes defined in the PTX ISA have been implemented. Implementing the rest of them should be trivial. template<typename T, operand_t D, operand_t A, operand_t B> static void Mul(Core *core, const OPBFOp &op) { T *a, *b, *d; getValues<T, D, A, B>(core, op, d, a, b); *d = *a * *b; core->incPC(op.size()); } Listing 3.13: Mul Executor Implementation getValues() is a templatized functions that obtains pointers to the opcode operands. If the mul operand executor function shown above was called with data type Tand operands D,A, and B, the getValues() function with the same parameters would be invoked. It allows a single function call to obtain operands as different as an immediate, a register or a memory location. Listing 3.14 shows the simplest getValues() implementation, with only two operand parameters. It contains calls to templatized functions getSource() and getDestination(), which retrieve pointers to the source and destination operands, respectively. template<typename T, operand_t D, operand_t A> static inline void getValues(Core *c, OPBFOp &op, T *&d, T *&a) { a = CoreExtractor<T, A>::getSource(*c, op, 0); d = CoreExtractor<T, D>::getDestination(*c, op, 0); } Listing 3.14: getValues() Implementation Since the actual retrieval of the source and destination operands is different if an operand is a register, a memory address or an immediate value, complete template specialization is done, providing different versions of the getSource() and getDestination() functions. The register versions simply call the translation methods to obtain the host address of the register.
3.6. CUDA RUNTIME LIBRARY (LIBECUDA) 45 The immediate version simply obtains the immediate location, which is stored in the OPBFOp object. The indirection version first obtains the address of the register that stores the address, obtains the value, and translates it to a host address. The address version simply returns the translation of the address, which is stored as an immediate and retrieved in the same way. 3.6 CUDA Runtime Library (libecuda) The CUDA Runtime Library libecuda serves as a replacement for the libcudart runtime library provided by NVIDIA. It implements several methods of the documented CUDA API, such as cudaMalloc or cudaMemcpy ToArray, which basically perform execution control and memory management. Several undocumented methods such as cudaRegisterFunction or cudaRegisterTexture have also been implemented, as calls to them are inserted into the host code by the nvcc compilation flow. When a CUDA application with the Cubin data included in the host code is started, as explained in the chapter overview, a kernel call is translated into a conventional C function call which acts as a wrapper to several API function calls. Several other API calls are inserted before and after the kernel call. All of these functions are implemented in the NVIDIA CUDA runtime library, and therefore they must all be reimplemented, or the application would not link correctly. An initialization function init is defined in the library, which is loaded before the program execution starts. In this function, a Card object (as described in Section 3.5) is instantiated. The current directory is searched for OPBF kernel files, which are loaded using the Card::addFile() method. The ECUDA PATH environment variable can also be used to define which directories should be searched for OPBF files. The ECUDA THREADS environment variable is also read at this point, setting the number of threads that will be used to run the emulation. The initialization function is needed because there will be numerous function calls prior to the kernel execution that will requiere the Card object to be loaded. There is an equivalent fini function that calls the Card destructor, freeing allocated memory.
46 CHAPTER 3. DESIGN AND IMPLEMENTATION [__cudaRegisterFatBinary] : 0x8059f80 [__cudaRegisterFatBinary] : 0x8059f40 [__cudaRegisterFunction] : 0x804b35c -> _Z9matrixMulPfS_S_ii [cudaGetDeviceCount] : 0xffaff498 (1) [cudaGetDeviceProperties] : Device 0 [cudaSetDevice] : 0 [cudaMalloc] : 393216 bytes, 0x3000 [0xf7908008] [cudaMalloc] : 524288 bytes, 0x64000 [0xf7887008] [cudaMemcpy] : 0x3000 -> 0xf79ea008 (393216 bytes) (HostToDevice) [cudaMemcpy] : 0x64000 -> 0xf7969008 (524288 bytes) (HostToDevice) [cudaMalloc] : 786432 bytes, 0xe5000 [0xf77c6008] [cudaConfigureCall] : grid (32,24,1) block (16,16,1) [cudaSetupArgument] : 4 @ 0 [cudaSetupArgument] : 4 @ 4 [cudaSetupArgument] : 4 @ 8 [cudaSetupArgument] : 4 @ 12 [cudaSetupArgument] : 4 @ 16 [cudaLaunch] : _Z9matrixMulPfS_S_ii [cudaMemcpy] : 0xf7705008 -> 0xe5000 (786432 bytes) (DeviceToHost) Processing time: 17092.416016 (ms) Test PASSED [cudaFree] : 12288 [cudaFree] : 409600 [cudaFree] : 937984 [__cudaUnRegisterFatBinary] : 0x26 [__cudaUnRegisterFatBinary] : 0x26 Listing 3.15: matMul Runtime Library calls Listing 3.15 shows the complete output when running the matrix multiplication benchmark in DEBUG mode, which shows all calls to runtime library functions. The usual flow of a CUDA application is: 1. Calls to device and kernel registration and initialization functions, such as cudaRegisterFatBinary(),cudaGetDeviceCount(),cud aGetDeviceProperties(), and cudaSetDevice(). Most of these calls are not directly made by the CUDA developer. They are inserted by the nvcc compiler. 2. Space allocation on the device, such as the cudaMalloc() call in the above example.
3.6. CUDA RUNTIME LIBRARY (LIBECUDA) 47 3. Data copying, where the data which the kernel must process is copied from the host to the device, such as the cudaMemcpy() call in the above example. 4. Kernel preparation and launching, done by the cudaConfigureCall(), cudaSetupArgument() and cudaLaunch() calls. The kernel is actually launched after the call to the cudaLaunch, which triggers a call to the Card::SetupCall() method, which as explained in Section 3.5, actually launches the kernel in emulated mode. 5. After the kernel execution finalizes, the calculated data must be copied back to the host, as shown by the cudaMemcpy() call in the above example. 6. Allocated data is freed, and destructors are called, as shown by calls to the cudaFree and cudaUnRegisterFatBinary functions. The implemented runtime library functions can be categorized as follows: •Initialization functions cudaRegisterTexture,cudaRegisterFatBinary,cudaUnregisterFatBinary, cudaRegisterFunction,cudaRegisterShared,cudaRegisterVar These functions are undocumented by NVIDIA, and their intended usage can only be deduced by the function name and parameters. The use of some of them is unknown, and they are implement as a blank function, to allow CUDA applications to link correctly. Most of them are simply implemented as storing the passed values in a data structure to allow later retrieval. For example, the cudaRegisterTexture maps a texture name to a pointer to an unknown data structure. This pointer value must be saved, as future references to texture in other API functions are not done by texture name but by this pointer value. •Memory Allocation Functions cudaMalloc,cudaFree,cudaMallocArray,cudaFreeArray These functions are documented in the NVIDIA CUDA API [15]. They are basically wrappers around the functions Card::Malloc() and Card::Free(). •Memory Copy Functions cudaMemcpy2DToArray,cudaMemcpyToArray,cudaMemset,cudaMemcpy, cudaMemcpyToSymbol These functions basically operate by obtaining the device address, by
48 CHAPTER 3. DESIGN AND IMPLEMENTATION calling Card::translate(), and performing regular recalls to memory copy operations. •Texture Functions cudaBindTextureToArray,cudaUnbindTexture,cudaGetChannelDesc These functions allow texture memory access, by associating the texture device address to the global memory address where the data is stored. •Kernel Launch Functions cudaConfigureCall,cudaSetupArgument,cudaLaunch The first two of these functions copy the kernel parameters to a known area, so the device emulation will be able to obtain them and make them available as the param memory space. •Device Properties Functions cudaGetLastError,cudaGetDeviceCount,cudaSetDevice,cudaGetDeviceProperties These functions hide the fact that no GPU card is actually running the kernel by returning, for example, the physical parameters (such as global memory size or total number of registers) about the emulated GPU card.
Chapter 4 Experimental Evaluation Once an initial working version of the emulation library had been developed, in order to evaluate the correctness of the implemented design, several unmodified CUDA benchmarks were run through the emulation process. Several major bugs were found, as mentioned in Chapter 3, some of which crashed the emulator, and some of which simply prevented the output from being the same as in a native GPU. All of them were fixed, making the emulated output equivalent to the GPU output. Performance measurements were then taken, comparing the libecuda emulation times against equivalent CPU-only algorithms, the GPU, and device emulation mode. Finally, profiling measurements were taken to identify major bottlenecks in the current implementation. 4.1 Benchmark Descriptions The chosen benchmarks were matMul,cp,tpacf,rpes, and sad. Table 4.1 shows a list of the benchmarks, with their grid dimensions and total number of threads. The matMul benchmark was chosen as the first benchmark due to its simplicity. The four remaining benchmarks were taken from the Parboil Benchmark Suite [41,8], developed by the IMPACT Research Group at the University of Illinois at Urbana-Champaign. It offers several benchmark that are better suited to measure a GPU platform performance than traditional benchmark suites. They are all different in the memory spaces they use, the PTX instructions that are generated from the source code, and the runtime calls they make. •The Matrix Multiplication (matMul) benchmark implements matrix multiplication. It has been extracted from the NVIDIA CUDA SDK, 49
50 CHAPTER 4. EXPERIMENTAL EVALUATION Benchmark Grid Dim Block Dim Total Threads matMul (32,24,1) (16,16,1) 196608 cp (4,61,1) (16,8) 32768 rpes (65535,1,1) (64,1,1) 4194240 sad (44,36,1) (61,1,1) 96624 (44,36,1) (61,1,1) 96624 (11,9,1) (32,4,1) 12672 (11,9,1) (32,1,1) 3168 tpacf (201,1,1) (256,1,1) 51456 Table 4.1: Benchmark Properties and is one of the most basic CUDA examples available. It uses shared and param memory. The generated PTX uses the add (addition), bra (branching), cvt (data type conversion), ld (load data from memory to a register), mad (multiply and add), mov (set a register value from an immediate value or another register), mul24 (24-bit multiplication), mul (multiplication), setp (compares two values with a relation operation, optionally combining the result with a predicate value, writing the result to a register), st (copy data from a register to memory) and sub (subtract) instructions. In our tests, the two multiplied matrices have a size of 384x256 and 256x512, yielding a 384x512 matrix as a result. The source matrices are generated randomly at the start of the program. •The Coulomb Potencial (cp) benchmark measures the electric potential at each point in a 3D volume in which charges are randomly distributed. In our tests, the atom count is 40000 and the volume size is 512x512, the default values. Besides using the param memory, it introduces the use of the const memory space. The only additional instruction used is rsqrt, which performs the inverse of a square root. The benchmark uses the cudaMemcpyToSymbol() API call, which allows copying data from a host variable to a device variable. Since it references the device variable by its name, it order to properly support the call, we had to implement keeping a label list in the OPBF file, allowing the runtime library access to it, to obtain the device address of the symbol. •The Two-point Angular Correlation Function (TPACF) describes the
4.1. BENCHMARK DESCRIPTIONS 51 angular distribution of a set of points. It is used to calculate the probability of finding two points separated by a given angular distance. It computes the angular correlation function for a data set of astronomical bodies. The benchmark was used with its original data input and all of its default parameters. It uses the param,const and shared memory spaces. Support was added for several instructions which it introduced, such as div (division), neg (arithmetic negation), or (bitwise or), selp (selects between source operands, based on the predicate source operand), set (very similar to the setp instruction), shl (binary shift-left), shr (binary shift-right). The selp instruction is the only PTX instruction that allows immediate values, although this is not clearly stated in the PTX specification. This caused problems in our initial implementation, which assumed that there was only one immediate value per instruction. Also, this benchmark builds a complex CFG, as shown in Section 3.3, which caused register allocation problems, leading to a complete rewrite of the register allocation algorithm. Selp has two immediates. •The Rys Polynomial Equation Solver (rpes) calculates 2-electron repulsion integrals, a molecular dynamics sub-problem, which represent the Colomb interaction between electrons in molecules. The benchmark was used with its default values, 2 atoms and 5 shells. This was the first benchmark that introduced the use of the texture memory space, besides shared and param memory. Support was added for the new instructions and (bitwise and), tex (texture access), ex2 (exponentiate a value in base 2), rcp (take the inverse of a value) and abs (take the absolute value). The ld instruction was used in vectorized form, writing to four registers in a single instructions, and support for this had to be added to the PTX parsing and the OPBF code generation. Support for 1D textures was added to support this benchmark. Finally, it required barrier support to be properly implemented. The matMul benchmark also used barrier calls, but they were unnecessary. •The computation of Sums of Absolute Differences (sad) benchmark is based on the full-pixel motion estimation algorithm found in the reference H.264 video encoder. It basically searches for blocks in one image that approximately match blocks in another image. It computes sums of absolute differences for pairs of blocks, representing how similar they are. The benchmark is composed of three kernels:
58 CHAPTER 4. EXPERIMENTAL EVALUATION 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 Speedup Number of Threads matMul sad cp rpes tpacf Figure 4.1: libecuda Scalability Evaluation 1 10 100 1000 10000 100000 matMul sad cp rpes tpacf Execution Time (log[s]) hercules obelix praline Figure 4.2: deviceemu Execution Times
4.4. PERFORMANCE EVALUATION 59 -9 -7 -5 -3 -1 1 3 5 7 9 matMul sad cp rpes tpacf Speedup hercules obelix praline Figure 4.3: deviceemu vs libecuda Compared Performance 1 10 100 1000 10000 100000 matMul sad cp rpes tpacf Slowdown libecuda (1 thread) libecuda (2 threads) deviceemu CPU Figure 4.4: libecuda Performance Evaluation in hercules
60 CHAPTER 4. EXPERIMENTAL EVALUATION 1 10 100 1000 10000 100000 matMul sad cp rpes tpacf Slowdown libecuda (1 thread) libecuda (2 thread) libecuda (4 thread) deviceemu CPU Figure 4.5: libecuda Performance Evaluation in obelix 1 10 100 1000 10000 100000 matMul sad cp rpes tpacf Slowdown libecuda (1 thread) libecuda (2 thread) libecuda (4 thread) libecuda (8 thread) deviceemu CPU Figure 4.6: libecuda Performance Evaluation in praline
4.5. EMULATION LIBRARY PROFILING 61 4.5 Emulation Library Profiling Since we wanted to produce exact measurements, the valgrind instrumenting profiler was chosen. By using its callgrind tool, we can generate a call graph of the functions contained in the application. The five benchmarks were ran through callgrind to identify possible bottlenecks and identify code sections which would benefit from a more efficient implementation. Since callgrind slows down execution by a factor of at least 400, only the mat- Mul and sad benchmarks were fully run. The remaining benchmarks were stopped after several hours of execution. This should not alter the results significantly, since the kernel code is basically cyclical. Figure 4.7: Profiling Results for matMul The kcachegrind tool was used to analyze the profiling data generated by the callgrind tool. Besides generating a call graph, this application is also capable of showing a flat profile of all called functions, ordering them by cost (execution time). Figure 4.7 shows the initial part of the flat profile for the matMul benchmark. The self column refers to the total cost of the function itself, while the incl column refers to the cost including all called functions.
62 CHAPTER 4. EXPERIMENTAL EVALUATION By using this information, several bottlenecks can be identified and other conclusions can be taken. •The Core::execute() function, which is the main loop of execution for a core, constitutes the most significant bottleneck. The function is very small, with only 8 lines of code, but due to the fact that it is called for every instruction of every core, its impact on the performance is important. •The Core::translate() function is called every time an device address has to be translated to a host address. This occurs an huge number of times: 7 million times in the matMul benchmark, according to collected data. The translation is basically implemented as a series of interval checks on the device address, to identify the memory space. Then, the address is looked up in an std::map, which stores the address pairs. •The OPBFOp::operandsSize() and OPBFOp::size() functions, are called many times because of a call to the OPBFOp::size() function in the statement core->incPC(op.size()). This is called to increment the program counter value after each instruction. Since the size of an instruction is static, it could be calculated on creation and stored, instead of calculating it every time. •Calls to the opcode implementation functions are not a source of significant bottlenecks. In this case, the call to the Core::Ld opcode implementation is the most significant one, occupying a mere 6.6% of the execution time. Due to the general nature of these bottlenecks, they occur in all benchmarks, although not exactly in the same proportion. These are the program functions that would benefit the most of optimizing them.
Chapter 5 Conclusions and Future Work All of the objectives of the present thesis have been met. Particularly, the development of an emulation library that parses PTX intermediate assembly language generated from a CUDA application, generating a new binary object and using it to emulate the functionality of a GPU. The library, called libecuda, successfully emulates the behavior of a GPU for the tested benchmarks, and should work for other CUDA applications without major changes. Developing and debugging an emulator is a challenging task. Managing to get the emulator to run without causing segmentation faults was relatively straight forward, as identifying the causing problem was as easy as launching gdb. The hardest part proved to be identifying problems that caused the emulated programs to return an invalid result without crashing the emulator. In this case, the less time consuming way was to use the device emulation mode, provided by NVIDIA, to our advantage. This mode allows printf() calls in the kernel code, which would make no sense in the normal mode. By printing the thread ID and a variable value and then identifying which register was assigned to the variable, the expected value of a register at a certain point in time could be known. This simplified the debugging process, which would otherwise be near to impossible. This thesis is based on the knowledge previously acquired in the Introduction to Computer Systems (C programming language), Computer Architecture and Operating Systems I (x86 assembly language and system architecture), Computer Architecture and Operating Systems II (operating system programming) compulsory courses and the Advanced Programming for Telecommunications Engineering (Java programming) elective course. During the thesis, acquired knowledge includes C++ programming and advanced techniques, emulation techniques, compiler theory and techniques, 63
64 CHAPTER 5. CONCLUSIONS AND FUTURE WORK parsing techniques, and performance profiling. There is room for several changes to the emulation code that would reduce its currently enormous slowdown. PTX code analysis for dead code removal could be applied, as the code generated by the nvcc tool includes superfluous instructions. A more sophisticated register allocation algorithm could be implemented, which would reduce the register usage, which is currently about 70% larger than the code generated by NVIDIA for its Cubin format. Several of the current bottlenecks listed in Section 4.5 could be addressed, with the proposed solutions. Thread parallelization performance could increase, as it does not reach the peak value in all benchmarks. This could be done by allocating thread blocks to multiprocessors dynamically instead of statically at the start, which would eliminate the current unbalanced execution syndrome. One of the best optimizations that could be applied would be to substitute the current instruction cache with a basic block cache, which would reduce the number of lookups necessary. The hardest optimization, which would require a dramatic rewrite, would be to substitute the currently employed interpretation emulation technique with abinary translation technique.
Bibliography [1] Intel Corporation. A platform 2015 workload model recognition, mining and synthesis moves computers to the era of tera, 2005. [cited at p. 3] [2] Amar Shan. Heterogeneous processing: a strategy for augmenting moore’s law. Linux Journal, January 2nd, 2006. [cited at p. 3, 4] [3] Sanjay Patel and Wen-mei W. Hwu. Accelerator architectures. Micro, IEEE, 28(4):4–12, July-Aug. 2008. [cited at p. 4] [4] Roger D. Chamberlain, Joseph M. Lancaster, and Ron K. Cytron. Visions for application development on hybrid computing systems. Parallel Comput., 34(4-5):201– 216, 2008. http://rssi.ncsa.illinois.edu/proceedings/posters/rssi07_12_ poster.pdf.[cited at p. 4] [5] Erich Strohmaier et al. Hans Meuer. Top 500. http://www.top500.org/static/ lists/2009/06/TOP500_200906_Poster.pdf, June 2009. [cited at p. 4] [6] Ken Koch. Roadrunner platform overview, March 2008. [cited at p. 5] [7] Samuel Williams, John Shalf, Leonid Oliker, Shoaib Kamil, Parry Husbands, and Katherine Yelick. The potential of the cell processor for scientific computing. In CF ’06: Proceedings of the 3rd conference on Computing frontiers, pages 9– 20, New York, NY, USA, 2006. ACM. http://bebop.cs.berkeley.edu/pubs/ williams2006-cell-scicomp.pdf.[cited at p. 5] [8] Shane Ryoo, Christopher I. Rodrigues, Sam S. Stone, Sara S. Baghsorkhi, Sain- Zee Ueng, John A. Stratton, and Wen-mei W. Hwu. Program optimization space pruning for a multithreaded gpu. In CGO ’08: Proceedings of the sixth annual IEEE/ACM international symposium on Code generation and optimization, pages 195–204, New York, NY, USA, 2008. ACM. http://impact.crhc.illinois.edu/ ftp/conference/cgo-08-ryoo.pdf.[cited at p. 6, 17, 49] [9] NVIDIA Corporation. PTX ISA version 1.3, October 2008. [cited at p. 6, 24] [10] Wladimir J. van der Laan. Cubin utilities. http://www.cs.rug.nl/~wladimir/ decuda/, 2007. [cited at p. 6] [11] Jon Peddie Research. Computer graphics chip shipments dive in q4 ’08 according to jon peddie research. http://jonpeddie.com/press-releases/details/ computer_graphics_chip_shipments_dive_in_q4_08_according_to_jon_ peddie_rese/, January 2009. [cited at p. 9] 65
66 BIBLIOGRAPHY [12] Wen mei Hwu and David Kirk. Ece 498 al programming massively parallel processors textbook, 2006-2008. [cited at p. 10, 12, 14] [13] Scott Wasson. Ati dives into steam computing. http://techreport.com/ articles.x/10956/1, October 2006. [cited at p. 11] [14] Vincent Chang. Steaming into the future. http://www.hardwarezone.com/ articles/view.php?cid=3&id=2821, March 2009. [cited at p. 11] [15] NVIDIA Corporation. CUDA programming guide 2.0. July 2008. [cited at p. 12, 14, 16, 47, 54] [16] John H. Kelm, Daniel R. Johnson, Matthew R. Johnson, Neal C. Crago, William Tuohy, Aqeel Mahesri, Steven S. Lumetta, Matthew I. Frank, and Sanjay J. Patel. Rigel: an architecture and scalable programming interface for a 1000-core accelerator. In ISCA, pages 140–151, 2009. https://netfiles.uiuc.edu/jkelm2/www/ papers/kelm-isca2009.pdf.[cited at p. 13] [17] Mauricio J. Serrano, Wayne Yamamoto, Roger C. Wood, and Mario Nemirovsky. A model for performance estimation in a multistreamed superscalar processor. In Proceedings of the 7th international conference on Computer performance evaluation : modelling techniques and tools, pages 213–230, Secaucus, NJ, USA, 1994. Springer- Verlag New York, Inc. [cited at p. 15] [18] Victor Moya. Study of the techniques for emulation programming. Master’s thesis, Facultat d’Inform`atica de Barcelona, Universitat Polit`ecnica de Catalunya, June 2001. http://personals.ac.upc.edu/vmoya/docs/emuprog.pdf.[cited at p. 17, 18] [19] Wikipedia. Binary translation, 2009. http://en.wikipedia.org/w/index.php? title=Binary_translation&oldid=297418679.[cited at p. 17] [20] Wikipedia. Virtual machine, 2009. http://en.wikipedia.org/w/index.php? title=Virtual_machine&oldid=300097377.[cited at p. 17, 18] [21] Wikipedia. Dynamic recompilation, 2009. http://en.wikipedia.org/w/index. php?title=Dynamic_recompilation&oldid=285654967.[cited at p. 17] [22] Fabrice Bellard. Qemu: Open source processor emulator. http://www.qemu.org/. [cited at p. 18] [23] Kevin Lawton. Bochs. http://bochs.sourceforge.net/.[cited at p. 19] [24] Sebastian Biallas. Pearpc. http://pearpc.sourceforge.net.[cited at p. 19] [25] VMWare Inc. Vmware. http://www.vmware.com.[cited at p. 19] [26] Sun Microsystems. Virtualbox. http://www.virtualbox.org.[cited at p. 19] [27] Jack Veenstra. Mint simulator. http://www.wotug.org/parallel/simulation/ architectures/mint/.[cited at p. 20]
BIBLIOGRAPHY 67 [28] Wikipedia. Software performance analysis, 2009. http://en.wikipedia. org/w/index.php?title=Software_performance_analysis&oldid=300765281. [cited at p. 20] [29] Julian Seward et al. Valgrind. http://valgrind.org/.[cited at p. 20] [30] Ali Bakhoda, George L. Yuan, Wilson W. L. Fung, Henry Wong, and Tor M. Aamodt. Analyzing CUDA Workloads Using a Detailed GPU Simulator. In IEEE International Symposium on Performance Analysis of Systems and Software (ISPASS 2009), pages 163–174, April 2009. http://www.ece.ubc.ca/~aamodt/ papers/gpgpusim.ispass09.pdf.[cited at p. 22] [31] David Parello Sylvain Collange, David Defour. Barra, a modular functional gpu simulator for gpgpu. Technical report, Universit´e de Perpignan, 2009. http://hal. archives-ouvertes.fr/hal-00359342.[cited at p. 22] [32] Gregory Diamos. Ocelot: A binary translation framework for ptx. http://code. google.com/p/gpuocelot/, July 2009. [cited at p. 22] [33] NVIDIA Corporation. The CUDA compiler driver NVCC. http://sbel.wisc. edu/Courses/ME964/2008/Documents/nvccCompilerInfo.pdf.[cited at p. 23] [34] Doug Brown John Levine, Tony Mason. Lex &Yacc. O’Reilly, 2nd edition edition, 1992. [cited at p. 25] [35] Steven S. Muchnick. Advanced Compiler Design and Implementation. Morgan Kaufmann Publishers, 1997. [cited at p. 31, 32] [36] Jens Palsberg. Register allocation via coloring of chordal graphs. In CATS ’07: Proceedings of the thirteenth Australasian symposium on Theory of computing, pages 3–3, Darlinghurst, Australia, Australia, 2007. Australian Computer Society, Inc. http://compilers.cs.ucla.edu/fernando/publications/papers/ APLAS05.pdf.[cited at p. 31, 32] [37] Frank Pfenning. 15-411 compiler design lecture notes on register allocation. http:// www.cs.cmu.edu/~fp/courses/15411-f08/lectures/03-regalloc.pdf, September 2008. [cited at p. 31, 32] [38] Frank Pfenning. 15-411 compiler design lecture notes on liveness analysis. http:// www.cs.cmu.edu/~fp/courses/15411-f08/lectures/04-liveness.pdf, September 2008. [cited at p. 32, 33] [39] Wikipedia. Cpu cache, 2009. http://en.wikipedia.org/w/index.php?title= CPU_cache&oldid=301440796.[cited at p. 41] [40] Stephen Prata. C++ Primer Plus. Sams Publishing, 5th edition edition, November 2004. [cited at p. 41] [41] Shane Ryoo, Christopher I. Rodrigues, Sara S. Baghsorkhi, Sam S. Stone, David B. Kirk, and Wen-mei W. Hwu. Optimization principles and application performance evaluation of a multithreaded gpu using cuda. In PPoPP ’08: Proceedings of the 13th ACM SIGPLAN Symposium on Principles and practice of parallel programming, pages 73–82, New York, NY, USA, 2008. ACM. http://impact.crhc.illinois. edu/ftp/conference/ppopp-08-ryoo.pdf.[cited at p. 49]