text stringlengths 1 7.76k | source stringlengths 17 81 |
|---|---|
646 Chapter 7 Multicores, Multiprocessors, and Clusters throughput losses, especially from shorter stalls. This limitation arises from the pipeline start-up costs of coarse-grained multithreading. Because a processor with coarse-grained multithreading issues instructions from a single thread, when a stall occurs, the pipeline must be emptied or frozen. The new thread that begins executing after the stall must fill the pipeline before instructions will be able to complete. Due to this start-up overhead, coarse-grained multithreading is much more useful for reducing the penalty of high-cost stalls, where pipeline refill is negligible compared to the stall time. Simultaneous multithreading (SMT) is a variation on hardware multithread ing that uses the resources of a multiple-issue, dynamically scheduled processor to exploit thread-level parallelism at the same time it exploits instruction-level parallelism. The key insight that motivates SMT is that multiple-issue processors often have more functional unit parallelism available than a single thread can effec tively use. Furthermore, with register renaming and dynamic scheduling, multiple instructions from independent threads can be issued without regard to the depen dences among them; the resolution of the dependences can be handled by the dynamic scheduling capability. Since you are relying on the existing dynamic mechanisms, SMT does not switch resources every cycle. Instead, SMT is always executing instructions from multiple threads, leaving it up to the hardware to associate instruction slots and renamed registers with their proper threads. Figure 7.5 conceptually illustrates the differences in a processor’s ability to exploit superscalar resources for the following processor configurations. The top portion shows how four threads would execute independently on a superscalar with no multithreading support. The bottom portion shows how the four threads could be combined to execute on the processor more efficiently using three multi threading options: ■ ■A superscalar with coarse-grained multithreading ■ ■A superscalar with fine-grained multithreading ■ ■A superscalar with simultaneous multithreading In the superscalar without hardware multithreading support, the use of issue slots is limited by a lack of instruction-level parallelism. In addition, a major stall, such as an instruction cache miss, can leave the entire processor idle. In the coarse-grained multithreaded superscalar, the long stalls are partially hidden by switching to another thread that uses the resources of the processor. Although this reduces the number of completely idle clock cycles, the pipeline start-up overhead still leads to idle cycles, and limitations to ILP means all issue slots will not be used. In the fine-grained case, the interleaving of threads mostly eliminates fully empty slots. Because only a single thread issues instructions in a given clock cycle, however, limitations in instruction-level parallelism still lead to idle slots within some clock cycles. simultaneous multithreading (SMT) A version of multi threading that lowers the cost of multithreading by utilizing the resources needed for multiple issue, dynamically schedule microarchitecture. | clipped_hennesy_Page_644_Chunk6001 |
In the SMT case, thread-level parallelism and instruction-level parallelism are both exploited, with multiple threads using the issue slots in a single clock cycle. Ideally, the issue slot usage is limited by imbalances in the resource needs and resource availability over multiple threads. In practice, other factors can restrict how many slots are used. Although Figure 7.5 greatly simplifies the real operation of these processors, it does illustrate the potential performance advantages of multithreading in general and SMT in particular. For example, the recent Intel Nehalem multicore supports SMT with two threads to improve core utilization. Let us conclude with three observations. First, from Chapter 1, we know that the power wall is forcing a design toward simpler and more power-efficient processors on a chip. It may well be that the under-utilized resources of out-of-order processors may be reduced, and so simpler forms of multithreading will be used. For example, the Sun UltraSPARC T2 (Niagara 2) microprocessor in Section 7.11 is an example of a return to simpler microarchitectures and hence the use of fine-grained multithreading. Issue slots Thread C Thread D Thread A Thread B Time Time SMT Coarse MT Fine MT Issue slots FIGURE 7.5 How four threads use the issue slots of a superscalar processor in different approaches. The four threads at the top show how each would execute running alone on a standard superscalar processor without multithreading support. The three examples at the bottom show how they would execute running together in three multithreading options. The horizontal dimension represents the instruction issue capability in each clock cycle. The vertical dimension represents a sequence of clock cycles. An empty (white) box indicates that the corresponding issue slot is unused in that clock cycle. The shades of gray and color correspond to four different threads in the multithreading processors. The additional pipeline start-up effects for coarse multithreading, which are not illustrated in this figure, would lead to further loss in throughput for coarse multithreading. 7.5 Hardware Multithreading 647 | clipped_hennesy_Page_645_Chunk6002 |
648 Chapter 7 Multicores, Multiprocessors, and Clusters Second, a key performance challenge is tolerating latency due to cache misses. Fine-grained computers like the UltraSPARC T2 switch to another thread on a miss, which is probably more effective in hiding memory latency than trying to fill unused issue slots as in SMT. A third observation is that the goal of hardware multithreading is to use hardware more efficiently by sharing components between different tasks. Multicore designs share resources as well. For example, two processors might share a floating-point unit or an L3 cache. Such sharing reduces some of the benefits of multithreading compared with providing more non-multithreaded cores. 1. True or false: Both multithreading and multicore rely on parallelism to get more efficiency from a chip. 2. True or false: Simultaneous multithreading uses threads to improve resource utilization of a dynamically scheduled, out-of-order processor. 7.6 SISD, MIMD, SIMD, SPMD, and Vector Another categorization of parallel hardware proposed in the 1960s is still used today. It was based on the number of instruction streams and the number of data streams. Figure 7.6 shows the categories. Thus, a conventional uniprocessor has a single instruction stream and single data stream, and a conventional multiproces sor has multiple instruction streams and multiple data streams. These two cate gories are abbreviated SISD and MIMD, respectively. Data Streams Single Multiple Instruction Streams Single SISD: Intel Pentium 4 SIMD: SSE instructions of x86 Multiple MISD: No examples today MIMD: Intel Xeon e5345 (Clovertown) FIGURE 7.6 Hardware categorization and examples based on number of instruction streams and data streams: SISD, SIMD, MISD, and MIMD. While it is possible to write separate programs that run on different processors on a MIMD computer and yet work together for a grander, coordinated goal, pro grammers normally write a single program that runs on all processors of an MIMD computer, relying on conditional statements when different processors should execute different sections of code. This style is called Single Program Multiple Data (SPMD), but it is just the normal way to program a MIMD computer. Check Yourself SISD or Single Instruction stream, Single Data stream. A uniprocessor. MIMD or Multiple Instruction streams, Multiple Data streams. A multiprocessor. SPMD Single Program, Multiple Data streams. The conventional MIMD programming model, where a single program runs across all processors. | clipped_hennesy_Page_646_Chunk6003 |
While it is hard to provide examples of useful computers that would be classified as multiple instruction streams and single data stream (MISD), the inverse makes much more sense. SIMD computers operate on vectors of data. For example, a single SIMD instruction might add 64 numbers by sending 64 data streams to 64 ALUs to form 64 sums within a single clock cycle. The virtues of SIMD are that all the parallel execution units are synchronized and they all respond to a single instruction that emanates from a single program counter (PC). From a programmer’s perspective, this is close to the already famil iar SISD. Although every unit will be executing the same instruction, each execu tion unit has its own address registers, and so each unit can have different data addresses. Thus, in terms of Figure 7.1, a sequential application might be compiled to run on serial hardware organized as a SISD or in parallel hardware that was organized as an SIMD. The original motivation behind SIMD was to amortize the cost of the control unit over dozens of execution units. Another advantage is the reduced size of pro gram memory—SIMD needs only one copy of the code that is being simultaneously executed, while message-passing MIMDs may need a copy in every processor, and shared memory MIMD will need multiple instruction caches. SIMD works best when dealing with arrays in for loops. Hence, for parallel ism to work in SIMD, there must be a great deal of identically structured data, which is called data-level parallelism. SIMD is at its weakest in case or switch state ments, where each execution unit must perform a different operation on its data, depending on what data it has. Execution units with the wrong data are disabled so that units with proper data may continue. Such situations essentially run at 1/nth performance, where n is the number of cases. The so-called array processors that inspired the SIMD category faded into his tory (see Section 7.14 on the CD), but two current interpretations of SIMD remain active today. SIMD in x86: Multimedia Extensions The most widely used variation of SIMD is found in almost every microproces sor today, and is the basis of the hundreds of MMX and SSE instructions of the x86 microprocessor (see Chapter 2). They were added to improve performance of multimedia programs. These instructions allow the hardware to have many ALUs operate simultaneously or, equivalently, to partition a single, wide ALU into many parallel smaller ALUs that operate simultaneously. For example, you could con sider a single hardware component to be one 64-bit ALU or two 32-bit ALUs or four 16-bit ALUs or eight 8-bit ALUs. Loads and stores are simply as wide as the widest ALU, so the programmer can think of the same data transfer instruction as transferring either a single 64-bit data element or two 32-bit data elements or four 16-bit data elements or eight 8-bit data elements. SIMD or Single Instruction stream, Multiple Data streams. A multiprocessor. The same instruction is applied to many data streams, as in a vector pro cessor or array processor. data-level parallelism Parallelism achieved by operating on independent data. 7.6 SISD, MIMD, SIMD, SPMD, and Vector 649 | clipped_hennesy_Page_647_Chunk6004 |
650 Chapter 7 Multicores, Multiprocessors, and Clusters This very low cost parallelism for narrow integer data was the original inspiration of the MMX instructions of the x86. As Moore’s law continued, more hardware was added to these multimedia extensions, and now SSE2 supports the simultaneous execution of a pair of 64-bit floating-point numbers. The width of the operation and the registers is encoded in the opcode of these multimedia instructions. As the data width of the registers and operations grew, the number of opcodes for multimedia instructions exploded, and now there are hundreds of SSE instructions to perform the useful combinations (see Chapter 2). Vector An older and more elegant interpretation of SIMD is called a vector architecture, which has been closely identified with Cray Computers. It is again a great match to problems with lots of data-level parallelism. Rather than having 64 ALUs perform 64 additions simultaneously, like the old array processors, the vector architectures pipelined the ALU to get good performance at lower cost. The basic philosophy of vector architecture is to collect data elements from memory, put them in order into a large set of registers, operate on them sequentially in registers, and then write the results back to memory. A key feature of vector architectures is a set of vector registers. Thus, a vector architecture might have 32 vector registers, each with 64 64-bit elements. Comparing Vector to Conventional Code Suppose we extend the MIPS instruction set architecture with vector instruc tions and vector registers. Vector operations use the same names as MIPS operations, but with the letter “V” appended. For example, addv.d adds two double-precision vectors. The vector instructions take as their input either a pair of vector registers (addv.d) or a vector register and a scalar register (addvs.d). In the latter case, the value in the scalar register is used as the input for all operations—the operation addvs.d will add the contents of a scalar register to each element in a vector register. The names lv and sv denote vector load and vector store, and they load or store an entire vector of double-precision data. One operand is the vector register to be loaded or stored; the other operand, which is a MIPS general-purpose register, is the starting address of the vector in memory. Given this short description, show the conventional MIPS code versus the vector MIPS code for Y = a × X + Y where X and Y are vectors of 64 double precision floating-point numbers, initially resident in memory, and a is a scalar double precision variable. (This example is the so-called DAXPY loop that forms the inner loop of the Linpack benchmark; DAXPY stands for double precision a × X plus Y.). Assume that the starting addresses of X and Y are in $s0 and $s1, respectively. EXAMPLE | clipped_hennesy_Page_648_Chunk6005 |
Here is the conventional MIPS code for DAXPY: l.d $f0,a($sp) ;load scalar a addiu r4,$s0,#512 ;upper bound of what to load loop: l.d $f2,0($s0) ;load x(i) mul.d $f2,$f2,$f0 ;a × x(i) l.d $f4,0($s1) ;load y(i) add.d $f4,$f4,$f2 ;a × x(i) + y(i) s.d $f4,0($s1) ;store into y(i) addiu $s0,$s0,#8 ;increment index to x addiu $s1,$s1,#8 ;increment index to y subu $t0,r4,$s0 ;compute bound bne $t0,$zero,loop ;check if done Here is the vector MIPS code for DAXPY: l.d $f0,a($sp) ;load scalar a lv $v1,0($s0) ;load vector x mulvs.d $v2,$v1,$f0 ;vector-scalar multiply lv $v3,0($s1) ;load vector y addv.d $v4,$v2,$v3 ;add y to product sv $v4,0($s1) ;store the result There are some interesting comparisons between the two code segments in this example. The most dramatic is that the vector processor greatly reduces the dynamic instruction bandwidth, executing only six instructions versus almost 600 for MIPS. This reduction occurs both because the vector operations work on 64 elements and because the overhead instructions that constitute nearly half the loop on MIPS are not present in the vector code. As you might expect, this reduction in instructions fetched and executed saves power. Another important difference is the frequency of pipeline hazards (Chapter 4). In the straightforward MIPS code, every add.d must wait for a mul.d, and every s.d must wait for the add.d. On the vector processor, each vector instruction will only stall for the first element in each vector, and then subsequent elements will flow smoothly down the pipeline. Thus, pipeline stalls are required only once per vector operation, rather than once per vector element. In this example, the pipeline stall frequency on MIPS will be about 64 times higher than it is on VMIPS. The pipeline stalls can be reduced on MIPS by using loop-unrolling (see Chapter 4). However, the large difference in instruction bandwidth cannot be reduced. ANSWER 7.6 SISD, MIMD, SIMD, SPMD, and Vector 651 | clipped_hennesy_Page_649_Chunk6006 |
652 Chapter 7 Multicores, Multiprocessors, and Clusters Elaboration: The loop in the example above exactly matched the vector length. When loops are shorter, vector architectures use a register that reduces the length of vector operations. When loops are larger, we add bookkeeping code to iterate full-length vector operations and to handle the leftovers. This latter process is called strip mining. Vector versus Scalar Vector instructions have several important properties compared to conventional instruction set architectures, which are called scalar architectures in this context: ■ ■A single vector instruction specifies a great deal of work—it is equivalent to executing an entire loop. The instruction fetch and decode bandwidth needed is dramatically reduced. ■ ■By using a vector instruction, the compiler or programmer indicates that the computation of each result in the vector is independent of the computation of other results in the same vector, so hardware does not have to check for data hazards within a vector instruction. ■ ■Vector architectures and compilers have a reputation of making it much eas ier than MIMD multiprocessors to write efficient applications when they contain data-level parallelism. ■ ■Hardware need only check for data hazards between two vector instructions once per vector operand, not once for every element within the vectors. Reduced checking can save power as well. ■ ■Vector instructions that access memory have a known access pattern. If the vector’s elements are all adjacent, then fetching the vector from a set of heavily interleaved memory banks works very well. Thus, the cost of the latency to main memory is seen only once for the entire vector, rather than once for each word of the vector. ■ ■Because an entire loop is replaced by a vector instruction whose behavior is predetermined, control hazards that would normally arise from the loop branch are nonexistent. ■ ■The savings in instruction bandwidth and hazard checking plus the efficient use of memory bandwidth give vector architectures advantages in power and energy versus scalar architectures. For these reasons, vector operations can be made faster than a sequence of sca lar operations on the same number of data items, and designers are motivated to include vector units if the application domain can use them frequently. | clipped_hennesy_Page_650_Chunk6007 |
Vector versus Multimedia Extensions Like multimedia extensions found in the x86 SSE instructions, a vector instruction specifies multiple operations. However, multimedia extensions typically specify a few operations while vector specifies dozens of operations. Unlike multimedia extensions, the number of elements in a vector operation is not in the opcode but in a separate register. This means different versions of the vector architecture can be implemented with a different number of elements just by changing the contents of that register and hence retain binary compatibility. In contrast, a new large set of opcodes is added each time the “vector” length changes in the multimedia exten sion architecture of the x86. Also unlike multimedia extensions, the data transfers need not be contiguous. Vectors support both strided accesses, where the hardware loads every nth data element in memory, and indexed accesses, where hardware finds the addresses of the items to be loaded in a vector register. Like multimedia extensions, vector easily captures the flexibility in data widths, so it is easy to make an operation work on 32 64-bit data elements or 64 32-bit data elements or 128 16-bit data elements or 256 8-bit data elements. Generally, vector architectures are a very efficient way to execute data parallel processing programs; they are better matches to compiler technology than multi media extensions; and they are easier to evolve over time than the multimedia extensions to the x86 architecture. True or false: As exemplified in the x86, multimedia extensions can be thought of as a vector architecture with short vectors that supports only sequential vector data transfers. Elaboration: Given the advantages of vector, why aren’t they more popular outside high- performance computing? There were concerns about the larger state for vector registers increasing context switch time and the difficulty of handling page faults in vector loads and stores, and SIMD instructions achieved some of the benefits of vector instructions. However, recent announcements from Intel suggest that vectors will play a bigger role. Intel’s Advanced Vector Instructions (AVI), to arrive in 2010, will expand the width of the SSE registers from 128 bits to 256 bits immediately and allow eventual expansion to 1024 bits. This latter width is equivalent to 16 double-precision floating-point numbers. Whether there will be vector load and store instructions are unclear. In addition, Intel’s entry into the discrete GPU market for 2010—code named “Larrabee”—is reputed to have vector instructions. Elaboration: Another advantage of vector and multimedia extensions is that it is relatively easy to extend a scalar instruction set architecture with these instructions to improve performance of data parallel operations. Check Yourself 7.6 SISD, MIMD, SIMD, SPMD, and Vector 653 | clipped_hennesy_Page_651_Chunk6008 |
654 Chapter 7 Multicores, Multiprocessors, and Clusters 7.7 Introduction to Graphics Processing Units A major justification for adding SIMD instructions to existing architectures was that many microprocessors were connected to graphics displays in PCs and work stations, so an increasing fraction of processing time was used for graphics. Hence, as Moore’s law increased the number of transistors available to microprocessors, it made sense to improve graphics processing. Just as Moore’s law allowed the CPU to improve graphics processing, it also enabled video graphics controller chips to add functions to accelerate 2D and 3D graphics. Moreover, at the very high end were expensive graphics cards typically from Silicon Graphics, that could be added to workstations, to enable the creation of photographic quality images. These high-end graphics cards were popular for creating computer-generated images that later found their way into television advertisements and then into movies. Thus, video graphics controllers had a target to shoot for as processing resources increased, much as supercomputers provided a rich resource of ideas for microprocessors to borrow in the quest for greater performance. A major driving force for improving graphics processing was the computer game industry, both on PCs and in dedicated game consoles such as the Sony PlayStation. The rapidly growing game market encouraged many companies to make increasing investments in developing faster graphics hardware, and this positive feedback led graphics processing to improve at a faster rate than general-purpose processing in mainstream microprocessors. Given that the graphics and game community had different goals than the microprocessor development community, it evolved its own style of processing and terminology. As the graphics processors increased in power, they earned the name Graphics Processing Units or GPUs to distinguish themselves from CPUs. Here are some of the key characteristics as to how GPUs vary from CPUs: ■ ■GPUs are accelerators that supplement a CPU, so they do not need be able to perform all the tasks of a CPU. This role allows them to dedicate all their resources to graphics. It’s fine for GPUs to perform some tasks poorly or not at all, given that in a system with both a CPU and a GPU, the CPU can do them if needed. Thus, the CPU-GPU combination is one example of hetero geneous multiprocessing, where not all the processors are identical. (Another example is the IBM Cell architecture in Section 7.11, which was also designed to accelerate 2D and 3D graphics.) ■ ■The programming interfaces to GPUs are high-level application pro gramming interfaces (APIs), such as OpenGL and Microsoft’s DirectX, coupled with high-level graphics shading languages, such as NVIDIA’s C for Graphics (Cg) and Microsoft’s High Level Shader Language (HLSL). | clipped_hennesy_Page_652_Chunk6009 |
The language compilers target industry-standard intermediate languages instead of machine instructions. GPU driver software generates optimized GPU-specific machine instructions. While these APIs and languages evolve rapidly to embrace new GPU resources enabled by Moore’s law, the freedom from backward binary instruction compatibility enables GPU designers to explore new architectures without the fear that they will be saddled with implementing failed experiments forever. This environment leads to more rapid innovation in GPUs than in CPUs. ■ ■Graphics processing involves drawing vertices of 3D geometry primitives such as lines and triangles and shading or rendering pixel fragments of geo metric primitives. Video games, for example, draw 20 to 30 times as many pixels as vertices. ■ ■Each vertex can be drawn independently, and each pixel fragment can be rendered independently. To render millions of pixels per frame rapidly, the GPU evolved to execute many threads from vertex and pixel shader programs in parallel. ■ ■The graphics data types are vertices, consisting of (x, y, z, w) coordinates, and pixels, consisting of (red, green, blue, alpha) color components. (See Appendix A to learn more about vertices and pixels.) GPUs represent each vertex component as a 32-bit floating-point number. Each of the four pixel components was originally an 8-bit unsigned integer, but recent GPUs now represent each component as single-precision floating-point number between 0.0 and 1.0. ■ ■The working set can be hundreds of megabytes, and it does not show the same temporal locality as data does in mainstream applications. Moreover, there is a great deal of data-level parallelism in these tasks. These differences led to different styles of architecture: ■ ■Perhaps the biggest difference is that GPUs do not rely on multilevel caches to overcome the long latency to memory, as do CPUs. Instead, GPUs rely on having enough threads to hide the latency to memory. That is, between the time of a memory request and the time that data arrives, the GPU executes hundreds or thousands of threads that are independent of that request. ■ ■GPUs rely on extensive parallelism to obtain high performance, implement ing many parallel processors and many concurrent threads. ■ ■The GPU main memory is thus oriented toward bandwidth rather than latency. There are even separate DRAM chips for GPUs that are wider and have higher bandwidth than DRAM chips for CPUs. In addition, GPU memories have traditionally had smaller main memories than conventional microprocessors. In 2008, GPUs typically have 1 GB or less, while CPUs have 7.7 Introduction to Graphics Processing Units 655 | clipped_hennesy_Page_653_Chunk6010 |
656 Chapter 7 Multicores, Multiprocessors, and Clusters 2 to 32 GB. Finally, keep in mind that for general-purpose computation, you must include the time to transfer the data between CPU memory and GPU memory, since the GPU is a coprocessor. ■ ■Given the reliance on many threads to deliver good memory bandwidth, GPUs can accommodate many parallel processors as well as many threads. Hence, each GPU processor is highly multithreaded. ■ ■In the past, GPUs relied on heterogeneous special purpose processors to deliver the performance needed for graphics applications. Recent GPUs are heading toward identical general-purpose processors to give more flexibil ity in programming, making them more like the multicore designs found in mainstream computing. ■ ■Given the four-element nature of the graphics data types, GPUs historically have SIMD instructions, like CPUs. However, recent GPUs are focusing more on scalar instructions to improve programmability and efficiency. ■ ■Unlike CPUs, there has been no support for double precision floating-point arithmetic, since there has been no need for it in the graphics applications. In 2008, the first GPUs to support double precision in hardware were announced. Nevertheless, single precision operations will still be eight to ten times faster than double precision, even on these new GPUs, while the differ ence in performance for CPUs is limited to benefits in transferring fewer bytes in the memory system due to using narrow data. Although GPUs were designed for a narrower set of applications, some pro grammers wondered if they could specify their applications in a form that would let them tap the high potential performance of GPUs. To distinguish this style of using GPUs, some called it General Purpose GPUs or GPGPUs. After tiring of try ing to specify their problems using the graphics APIs and graphics shading lan guages, they developed C-inspired programming languages to allow them to write programs directly for the GPUs. An example is Brook, a streaming language for GPUs. The next step in programmability of both the hardware and the program ming language is NVIDIA’s CUDA (Compute Unified Device Architecture), which enables the programmer to write C programs to execute on GPUs, albeit with some restrictions. The use of GPUs for parallel computing is growing with their increasing programmability. An Introduction to the NVIDIA GPU Architecture Appendix A goes into much more depth on GPUs and presents in detail the most recent NVIDIA GPU architecture, called Tesla. Since GPUs evolved in their own environment, they not only have different architectures, as suggested above, but they also have a different set of terms. Once you learn the GPU terms, you will | clipped_hennesy_Page_654_Chunk6011 |
see the similarities to approaches presented in prior sections, such as fine-grained multithreading and vectors. To help you with that transition to the new vocabulary, we present a quick introduction to the terms and ideas in the Tesla GPU architecture and the CUDA programming environment. A discrete GPU chip sits on a separate card that plugs into a standard PC over the PCI-Express interconnect. So-called motherboard GPUs are integrated into the motherboard chip set, such as a north bridge or a south bridge (Chapter 6). GPUs are generally offered as a family of chips at different price performance points, with all being software compatible. Tesla-based GPUs chips are offered with between 1 and 16 nodes, which NVIDIA calls multiprocessors. In early 2008, the largest version is called the GeForce 8800 GTX, which has 16 multiprocessors and a clock rate of 1.35 GHz. Each multiprocessor contains eight multithreaded single-precision floating- point units and integer processing units, which NVIDIA calls streaming processors. Since the architecture includes a single-precision floating-point multiply-add instruction, the peak single precision multiply-add performance of the 8800 GTX chip is: 16 MPs × 8 SPs _____ MP × 2 FLOPs/instr ____________ SP × 1 instr ______ clock × 1.35 × 109 clocks ______________ second = 16 × 8 × 2 × 1.35 GFLOPs _____________________ second = 345.6 GFLOPs ____________ second Each of the 16 multiprocessors of the GeForce 8800 GTX has a software-managed local store with a capacity of 16 KB plus 8192 32-bit registers. The memory system of the 8800 GTX consists of six partitions of 900 MHz Graphics DDR3 DRAM, each 8 bytes wide and with 128 MB of capacity. The total memory size is thus 768 MB. The peak GDDR3 memory bandwidth is 6 × 8 Bytes _______ transfer × 2 transfers _________ clock × 0.9 × 109 clocks _____________ second = 6 × 8 × 2 × 0.9GB _______________ second = 86.4 GB _______ second To hide memory latency, each streaming processor has hardware-supported threads. Each group of 32 threads is called a warp. A warp is the unit of schedul ing, and the active threads in a warp—up to 32—execute in parallel in SIMD fash ion. The multithreaded architecture copes with conditions, however, by allowing threads to take different branch paths. When threads of a warp take diverging paths, the warp sequentially executes both code paths with some inactive threads, which makes the active threads run more slowly. The hardware joins the threads back into a fully active warp as soon as the conditional paths are completed. To get the best performance, all 32 threads of a warp need to execute together in parallel. In simi lar style, the hardware also looks at the address streams coming from the different threads to try to merge the individual requests into fewer but larger memory block transfers to increase memory performance. 7.7 Introduction to Graphics Processing Units 657 | clipped_hennesy_Page_655_Chunk6012 |
658 Chapter 7 Multicores, Multiprocessors, and Clusters Figure 7.7 combines all these features together and compares a Tesla multiprocessor to a Sun UltraSPARC T2 core, which is described in Sections 7.5 and 7.11. Both are hardware multithreaded by scheduling threads over time, shown on the vertical axis. Each Tesla multiprocessor consists of eight streaming processors, which execute eight parallel threads per clock showing horizontally. As mentioned above, the best performance comes when all 32 threads of a warp execute together in a SIMD-like fashion, which the Tesla architecture calls single-instruction multiple-thread (SIMT). SIMT dynamically discovers which threads of a warp can execute the same instruction together, and which independent threads are idle that cycle. The T2 core contains just a single multithreaded processor. Each cycle it executes one instruction for one thread. The Tesla multiprocessor uses fine-grained hardware multithreading to sched ule 24 warps over time, which are shown vertically in blocks of four clock cycles. Similarly, the UltraSPARC T2 schedules eight hardware-supported threads over time, one thread per cycle, shown vertically. Thus, just as the T2 hardware switches between threads to keep the T2 core busy, the Tesla hardware switches between warps to keep the Tesla multiprocessor busy. The major difference is that the T2 core has one processor that can switch threads every clock cycle, while the minimum unit of switching warps in the Tesla microprocessor is two clock cycles across eight streaming cores. Since Tesla is aimed at programs with a great deal of data-level parallelism, the designers believed there is little performance difference between FIGURE 7.7 Comparing single core of a Sun UltraSPARC T2 (Niagara 2) to a single Tesla multi- processor. The T2 core is a single processor and uses hardware multithreading with eight threads (although there are some restrictions scheduling threads to pipelines). The Tesla multiprocessor contains eight streaming proces sors and uses hardware-supported multithreading with 24 warps of 32 threads (eight processors times four clock cycles). The T2 can switch every clock cycle, while the Tesla can switch only every two or four clock cycles. One way to compare the two is that the T2 can only multithread the processor over time, while Tesla can multithread over time and over space; that is, across the eight streaming processors as well as segments of four clock cycles. Processors UltraSPARC T2 ... Hardware Supported Threads Thread0 Thread1 Thread2 Thread3 Thread4 Thread5 Thread6 Thread7 Tesla Multiprocessor Warp0 Warp1 Warp23 | clipped_hennesy_Page_656_Chunk6013 |
switching every two or four clock cycles versus every clock cycle, and the hardware was much simpler by restricting the frequency of switching. The CUDA programming environment has its own terminology as well. A CUDA program is a unified C/C++ program for a heterogeneous CPU and GPU system. It executes on the CPU and dispatches parallel work to the GPU. This work consists of a data transfer from main memory and a thread dispatch. A thread is a piece of the program for the GPU. Programmers specify the number of threads in a thread block, and the number of thread blocks they wish to start executing on the GPU. The reason the programmers care about thread blocks is that all the threads in the thread block are scheduled to run on the same multiprocessor so they all share the same local memory. Thus, they can communicate via loads and stores instead of messages. The CUDA compiler allocates registers to each thread, under the constraint that the registers per thread times threads per thread block does not exceed the 8192 registers per multiprocessor. A thread block can be up to 512 threads. Each group of 32 threads in a thread block is packed into warps. Large thread blocks have better efficiency than small ones, and they can be as small as a single thread. As mentioned above, thread blocks and warps with fewer than 32 threads operate less efficiently than full ones. A hardware scheduler tries to schedule multiple thread blocks per multiproces sor when possible. If it does, the scheduler also partitions the 16 KB local store dynamically between the different thread blocks. Putting GPUs into Perspective GPUs like the NVIDIA Tesla architecture do not fit neatly into prior classifications of computers, such Figure 7.6 on page 648. Clearly, the GeForce 8800 GTX, with 16 Tesla multiprocessors, is an MIMD. The question is how to classify each of the Tesla multiprocessors and the eight streaming processors that make up a Tesla multiprocessor. Recall that we earlier said that SIMD was at its best with for loops and was at its weakest in case and switch statements. Tesla aims at the high performance for data- level parallelism while making it easy for programmers to deal with independent thread-level parallel cases. Tesla allows the programmer to think the multiprocessor is a multithreaded MIMD of eight streaming processors, but the hardware tries to gang together the eight streaming processors to act in SIMT fashion when multi ple threads of the same warp can execute together. When the threads do operate independently and follow an independent execution path, they execute more slowly than in SIMT fashion, for all 32 threads of a warp share a single instruction fetch unit. If all 32 threads of a warp were executing independent instructions, each thread would operate at 1/16th the peak performance of a full warp of 32 threads executing on eight streaming processors over four clocks. Thus, each independent thread has its own effective PC, so programmers can think of the Tesla multiprocessor as MIMD, but programmers need to take care to write control flow statements that allow the SIMT hardware to execute CUDA programs in SIMD fashion to deliver the desired performance. 7.7 Introduction to Graphics Processing Units 659 | clipped_hennesy_Page_657_Chunk6014 |
660 Chapter 7 Multicores, Multiprocessors, and Clusters In contrast to vector architectures, which rely on a vectorizing compiler to recognize data-level parallelism at compile time and generate vector instructions, hardware implementations of Tesla architecture discovers data-level parallelism among threads at runtime. Thus, Tesla GPUs do not need vectorizing compilers, and they make it easier for the programmer to handle the portions of the program that do not have data-level parallelism. To put this unique approach into perspective, Figure 7.8 places GPUs in a classification that looks at instruction-level parallelism versus data-level parallelism and whether it is discovered at compile time or runtime. This categorization is one indication that the Tesla GPU is breaking new ground in computer architecture. Static: Discovered at Compile Time Dynamic: Discovered at Runtime InstructionLevel Parallelism VLIW Superscalar DataLevel Parallelism SIMD or Vector Tesla Multiprocessor FIGURE 7.8 Hardware categorization of processor architectures and examples based on static versus dynamic and ILP versus DLP. True or false: GPUs rely on graphics DRAM chips to reduce memory latency and thereby increase performance on graphics applications. 7.8 Introduction to Multiprocessor Network Topologies Multicore chips require networks on chips to connect cores together. This section reviews the pros and cons of different multiprocessor networks. Network costs include the number of switches, the number of links on a switch to connect to the network, the width (number of bits) per link, and length of the links when the network is mapped into chip. For example, some cores may be adjacent and others may be on the other side of the chip. Network performance is multifaceted as well. It includes the latency on an unloaded network to send and receive a message, the throughput in terms of the maximum number of messages that can be transmitted in a given time period, delays caused by contention for a portion of the network, and variable performance depending on the pattern of communication. Another obligation of the network may be fault tolerance, since systems may be required to operate in the presence of broken components. Finally, in this era of power-limited chips, the power efficiency of different organizations may trump other concerns. Networks are normally drawn as graphs, with each arc of the graph representing a link of the communication network. The processor-memory node is shown as a Check Yourself | clipped_hennesy_Page_658_Chunk6015 |
black square, and the switch is shown as a colored circle. In this section, all links are bidirectional; that is, information can flow in either direction. All networks consist of switches whose links go to processor-memory nodes and to other switches. The first improvement over a bus is a network that connects a sequence of nodes together: This topology is called a ring. Since some nodes are not directly connected, some messages will have to hop along intermediate nodes until they arrive at the final destination. Unlike a bus, a ring is capable of many simultaneous transfers. Because there are numerous topologies to choose from, performance metrics are needed to dis tinguish these designs. Two are popular. The first is total network bandwidth, which is the bandwidth of each link multiplied by the number of links. This repre sents the very best case. For the ring network above, with P processors, the total network bandwidth would be P times the bandwidth of one link; the total network bandwidth of a bus is just the bandwidth of that bus, or two times the bandwidth of that link. To balance this best case, we include another metric that is closer to the worst case: the bisection bandwidth. This is calculated by dividing the machine into two parts, each with half the nodes. Then you sum the bandwidth of the links that cross that imaginary dividing line. The bisection bandwidth of a ring is two times the link bandwidth, and it is one times the link bandwidth for the bus. If a single link is as fast as the bus, the ring is only twice as fast as a bus in the worst case, but it is P times faster in the best case. Since some network topologies are not symmetric, the question arises of where to draw the imaginary line when bisecting the machine. This is a worst-case met ric, so the answer is to choose the division that yields the most pessimistic network performance. Stated alternatively, calculate all possible bisection bandwidths and pick the smallest. We take this pessimistic view because parallel programs are often limited by the weakest link in the communication chain. At the other extreme from a ring is a fully connected network, where every processor has a bidirectional link to every other processor. For fully connected networks, the total network bandwidth is P × (P - 1)/2, and the bisection band width is (P/2)2. The tremendous improvement in performance of fully connected networks is offset by the tremendous increase in cost. This inspires engineers to invent new topologies that are between the cost of rings and the performance of fully con nected networks. The evaluation of success depends in large part on the nature of the communication in the workload of parallel programs run on the machine. The number of different topologies that have been discussed in publications would be difficult to count, but only a handful have been used in commercial parallel processors. Figure 7.9 illustrates two of the popular topologies. Real machines bisection bandwidth The bandwidth between two equal parts of a multiprocessor. This measure is for a worst case split of the multiprocessor. fully connected network A network that connects processor-memory nodes by supplying a dedicated communication link between every node. 7.8 Introduction to Multiprocessor Network Topologies 661 network bandwidth Informally, the peak transfer rate of a network; can refer to the speed of a single link or the collective transfer rate of all links in the network. | clipped_hennesy_Page_659_Chunk6016 |
662 Chapter 7 Multicores, Multiprocessors, and Clusters frequently add extra links to these simple topologies to improve performance and reliability. An alternative to placing a processor at every node in a network is to leave only the switch at some of these nodes. The switches are smaller than processor- memory-switch nodes, and thus may be packed more densely, thereby lessening distance and increasing performance. Such networks are frequently called multistage networks to reflect the multiple steps that a message may travel. Types of multistage networks are as numerous as single-stage networks; Figure 7.10 illustrates two of the popular multistage organizations. A fully connected or crossbar network allows any node to communicate with any other node in one pass through the network. An Omega network uses less hardware than the crossbar network (2n log2 n versus n2 switches), but contention can occur between messages, depending on the pattern of communication. For example, the Omega network in Figure 7.10 cannot send a message from P0 to P6 at the same time that it sends a message from P1 to P7. Implementing Network Topologies This simple analysis of all the networks in this section ignores important practical considerations in the construction of a network. The distance of each link affects the cost of communicating at a high clock rate—generally, the longer the distance, the more expensive it is to run at a high clock rate. Shorter distances also make multistage network A network that supplies a small switch at each node. fully connected network A network that connects processor-memory nodes by supplying a dedicated communication link between every node. crossbar network A network that allows any node to communicate with any other node in one pass through the network. FIGURE 7.9 Network topologies that have appeared in commercial parallel processors. The colored circles represent switches and the black squares represent processor-memory nodes. Even though a switch has many links, generally only one goes to the processor. The Boolean n-cube topology is an n-dimensional interconnect with 2n nodes, requiring n links per switch (plus one for the processor) and thus n nearest-neighbor nodes. Frequently, these basic topologies have been supplemented with extra arcs to improve performance and reliability. a. 2-D grid or mesh of 16 nodes b. n-cube tree of 8 nodes (8 = 23 so n = 3) | clipped_hennesy_Page_660_Chunk6017 |
it easier to assign more wires to the link, as the power to drive many wires from a chip is less if the wires are short. Shorter wires are also cheaper than longer wires. Another practical limitation is that the three-dimensional drawings must be mapped onto chips that are essentially two-dimensional media. The final concern is power. Power concerns may force multicore chips to rely on simple grid topologies, for example. The bottom line is that topologies that appear elegant when sketched on the blackboard may be impractical when constructed in silicon. FIGURE 7.10 Popular multistage network topologies for eight nodes. The switches in these drawings are simpler than in earlier drawings because the links are unidirectional; data comes in at the bottom and exits out the right link. The switch box in c can pass A to C and B to D or B to C and A to D. The crossbar uses n2 switches, where n is the number of processors, while the Omega network uses 2n log2n of the large switch boxes, each of which is logically composed of four of the smaller switches. In this case, the crossbar uses 64 switches versus 12 switch boxes, or 48 switches, in the Omega network. The crossbar, however, can support any combination of messages between processors, while the Omega network cannot. a. Crossbar b. Omega network c. Omega network switch box C D A B P0 P1 P2 P3 P4 P5 P6 P7 P0 P1 P2 P3 P4 P5 P6 P7 7.8 Introduction to Multiprocessor Network Topologies 663 | clipped_hennesy_Page_661_Chunk6018 |
664 Chapter 7 Multicores, Multiprocessors, and Clusters 7.9 Multiprocessor Benchmarks As we saw in Chapter 1, benchmarking systems is always a sensitive topic, because it is a highly visible way to try to determine which system is better. The results affect not only the sales of commercial systems, but also the reputation of the designers of those systems. Hence, the participants want to win the competition, but they also want to be sure that if someone else wins, they deserve to win because they have a genuinely better system. This desire leads to rules to ensure that the benchmark results are not simply engineering tricks for that benchmark, but are instead advances that improve performance of real applications. To avoid possible tricks, a typical rule is that you can’t change the benchmark. The source code and data sets are fixed, and there is a single proper answer. Any deviation from those rules makes the results invalid. Many multiprocessor benchmarks follow these traditions. A common exception is to be able to increase the size of the problem so that you can run the benchmark on systems with a widely different number of processors. That is, many bench marks allow weak scaling rather than require strong scaling, even though you must take care when comparing results for programs running different problem sizes. Figure 7.11 is a summary of several parallel benchmarks, also described below: ■ ■Linpack is a collection of linear algebra routines, and the routines for per forming Gaussian elimination constitute what is known as the Linpack benchmark. The DAXPY routine in the example on page 650 represents a small fraction of the source code of the Linpack benchmark, but it accounts for most of the execution time for the benchmark. It allows weak scaling, letting the user pick any size problem. Moreover, it allows the user to rewrite Linpack in any form and in any language, as long as it computes the proper result. Twice a year, the 500 computers with the fastest Linpack performance are published at www.top500.org. The first on this list is considered by the press to be the world’s fastest computer. ■ ■SPECrate is a throughput metric based on the SPEC CPU benchmarks, such as SPEC CPU 2006 (see Chapter 1). Rather than report performance of the individual programs, SPECrate runs many copies of the program simulta neously. Thus, it measures job-level parallelism, as there is no communica tion between the jobs. You can run as many copies of the programs as you want, so this is again a form of weak scaling. ■ ■SPLASH and SPLASH 2 (Stanford Parallel Applications for Shared Memory) were efforts by researchers at Stanford University in the 1990s to put together | clipped_hennesy_Page_662_Chunk6019 |
Benchmark Scaling? Reprogram? Description Linpack Weak Yes Dense matrix linear algebra [Dongarra, 1979] SPECrate Weak No Independent job parallelism [Henning, 2007] Stanford Parallel Applications for Shared Memory SPLASH 2 [Woo et al., 1995] Strong (although offers two problem sizes) No Complex 1D FFT Blocked LU Decomposition Blocked Sparse Cholesky Factorization Integer Radix Sort BarnesHut Adaptive Fast Multipole Ocean Simulation Hierarchical Radiosity Ray Tracer Volume Renderer Water Simulation with Spatial Data Structure Water Simulation without Spatial Data Structure NAS Parallel Benchmarks [Bailey et al., 1991] Weak Yes (C or Fortran only) EP: embarrassingly parallel MG: simplified multigrid CG: unstructured grid for a conjugate gradient method FT: 3D partial differential equation solution using FFTs IS: large integer sort PARSEC Benchmark Suite [Bienia et al., 2008] Weak No Blackscholes—Option pricing with BlackScholes PDE Bodytrack—Body tracking of a person Canneal—Simulated cacheaware annealing to optimize routing Dedup—Nextgeneration compression with data deduplication Facesim—Simulates the motions of a human face Ferret—Content similarity search server Fluidanimate—Fluid dynamics for animation with SPH method Freqmine—Frequent itemset mining Streamcluster—Online clustering of an input stream Swaptions—Pricing of a portfolio of swaptions Vips—Image processing x264—H.264 video encoding Berkeley Design Patterns [Asanovic et al., 2006] Strong or Weak Yes FiniteState Machine Combinational Logic Graph Traversal Structured Grid Dense Matrix Sparse Matrix Spectral Methods (FFT) Dynamic Programming NBody MapReduce Backtrack/Branch and Bound Graphical Model Inference Unstructured Grid 7.9 Multiprocessor Benchmarks 665 FIGURE 7.11 Examples of parallel benchmarks. | clipped_hennesy_Page_663_Chunk6020 |
666 Chapter 7 Multicores, Multiprocessors, and Clusters a parallel benchmark suite similar in goals to the SPEC CPU benchmark suite. It includes both kernels and applications, including many from the high-performance computing community. This benchmark requires strong scaling, although it comes with two data sets. ■ ■The NAS (NASA Advanced Supercomputing) parallel benchmarks were another attempt from the 1990s to benchmark multiprocessors. Taken from computational fluid dynamics, they consist of five kernels. They allow weak scaling by defining a few data sets. Like Linpack, these benchmarks can be rewritten, but the rules require that the programming language can only be C or Fortran. ■ ■The recent PARSEC (Princeton Application Repository for Shared Memory Computers) benchmark suite consists of multithreaded programs that use Pthreads (POSIX threads) and OpenMP (Open MultiProcessing). They focus on emerging markets and consist of nine applications and three ker nels. Eight rely on data parallelism, three rely on pipelined parallelism, and one on unstructured parallelism. The downside of such traditional restrictions to benchmarks is that innovation is chiefly limited to the architecture and compiler. Better data structures, algo rithms, programming languages, and so on often can not be used, since that would give a misleading result. The system could win because of, say, the algorithm, and not because of the hardware or the compiler. While these guidelines are understandable when the foundations of computing are relatively stable—as they were in the 1990s and the first half of this decade— they are undesirable at the beginning of a revolution. For this revolution to succeed, we need to encourage innovation at all levels. One recent approach has been advocated by researchers at the University of California at Berkeley. They have identified 13 design patterns that they claim will be part of applications of the future. These design patterns are implemented by frameworks or kernels. Examples are sparse matrices, structured grid, finite-state machines, map reduce, and graph traversal. By keeping the definitions at a high level, they hope to encourage innovations at any level of the system. Thus, the system with the fastest sparse matrix solver is welcome to use any data structure, algorithm, and programming language, in addition to novel architectures and compilers. We’ll see examples of such benchmarks in Section 7.11. True or false: The main drawback with conventional approaches to bench marks for parallel computers is that the rules that ensure fairness also suppress innovation. Pthreads A UNIX API for creating and manipulating threads. It comes with a library. OpenMP An API for shared memory multiprocessing in C, C++, or Fortran that runs on UNIX and Microsoft platforms. It includes compiler directives, a library, and runtime directives. Check Yourself | clipped_hennesy_Page_664_Chunk6021 |
7.10 Roofline: A Simple Performance Model This section is based on a paper by Williams and Patterson [2008]. In the recent past, conventional wisdom in computer architecture led to similar microproces sor designs. Nearly every desktop and server computer used caches, pipelining, superscalar instruction issue, branch prediction, and out-of-order execution. The instruction sets varied, but the microprocessors were all from the same school of design. The switch to multicore likely means that microprocessors will become more diverse, since there is no conventional wisdom as to which architecture will make it easiest to write correct parallel processing programs that run efficiently and scale as the number of cores increases over time. Moreover, as the number of cores per chip does increase, a single manufacturer will likely offer different numbers of cores per chip at different price points at the same time. Given the increasing diversity, it would be especially helpful if we had a simple model that offered insights into the performance of different designs. It need not be perfect, just insightful. The 3Cs model from Chapter 5 is an analogy. It is not a perfect model, since it ignores potentially important factors like block size, block allocation policy, and block replacement policy. Moreover, it has quirks. For example, a miss can be ascribed due to capacity in one design and to a conflict miss in another cache of the same size. Yet 3Cs model has been popular for 20 years, because it offers insight into the behavior of programs, helping both architects and programmers improve their creations based on insights from that model. To find such a model, let’s start with the 13 Berkeley design patterns in Figure 7.9. The idea of the design patterns is that the performance of a given application is really the weighted sum of several kernels that implement those design patterns. We’ll evaluate individual kernels here, but keep in mind that real applications are combinations of many kernels. While there are versions with different data types, floating point is popular in several implementations. Hence, peak floating-point performance is a limit on the speed of such kernels on a given computer. For multicore chips, peak floating- point performance is the collective peak performance of all the cores on the chip. If there were multiple microprocessors in the system, you would multiply the peak per chip by the total number of chips. The demands on the memory system can be estimated by dividing this peak floating-point performance by the average number of floating-point operations per byte accessed: Floating-Point Operations/Sec Floating-Point Operations/Byte = Bytes/Sec 7.10 Roofline: A Simple Performance Model 667 | clipped_hennesy_Page_665_Chunk6022 |
668 Chapter 7 Multicores, Multiprocessors, and Clusters The ratio of floating-point operations per byte of memory accessed is called the arithmetic intensity. It can be calculated by taking the total number of floating- point operations for a program divided by the total number of data bytes transferred to main memory during program execution. Figure 7.12 shows the arithmetic intensity of several of the Berkeley design patterns from Figure 7.11. arithmetic intensity The ratio of floating-point operations in a program to the number of data bytes accessed by a program from main memory. FIGURE 7.12 Arithmetic intensity, specified as the number of float-point operations to run the program divided by the number of bytes accessed in main memory [Williams, Patterson, 2008]. Some kernels have an arithmetic intensity that scales with problem size, such as Dense Matrix, but there are many kernels with arithmetic intensities independent of problem size. For kernels in this former case, weak scaling can lead to different results, since it puts much less demand on the memory system. A r i t h m e t i c I n t e n s i t y O(N) O(log(N)) O(1) Sparse Matrix (SpMV) Structured Grids (Stencils, PDEs) Structured Grids (Lattice Methods) Spectral Methods (FFTs) Dense Matrix (BLAS3) N-body (Particle Methods) The Roofline Model The proposed simple model ties floating-point performance, arithmetic intensity, and memory performance together in a two-dimensional graph [Williams, Patterson, 2008]. Peak floating-point performance can be found using the hardware specifications mentioned above. The working set of the kernels we consider here do not fit in on-chip caches, so peak memory performance may be defined by the memory system behind the caches. One way to find the peak memory performance is the Stream benchmark. (See the Elaboration on page 473 in Chapter 5). Figure 7.13 shows the model, which is done once for a computer, not for each kernel. The vertical Y-axis is achievable floating-point performance from 0.5 to 64.0 GFLOPs/second. The horizontal X-axis is arithmetic intensity, varying from 1/8 FLOPs/DRAM byte accessed to 16 FLOPs/DRAM byte accessed. Note that the graph is a log-log scale. For a given kernel, we can find a point on the X-axis based on its arithmetic intensity. If we drew a vertical line through that point, the performance of the ker nel on that computer must lie somewhere along that line. We can plot a horizontal line showing peak floating-point performance of the computer. Obviously, the | clipped_hennesy_Page_666_Chunk6023 |
actual floating-point performance can be no higher than the horizontal line, since that is a hardware limit. How could we plot the peak memory performance? Since X-axis is FLOPs/ byte and the Y-axis is FLOPs/second, bytes/second is just a diagonal line at a 45-degree angle in this figure. Hence, we can plot a third line that gives the maximum floating-point performance that the memory system of that computer can support for a given arithmetic intensity. We can express the limits as a formula to plot the line in the graph in Figure 7.13: Attainable GFLOPs/sec = Min (Peak Memory BW × Arithmetic Intensity, Peak Floating-Point Performance) The horizontal and diagonal lines give this simple model its name and indicates its value. The “roofline” sets an upper bound on performance of a kernel depend ing on its arithmetic intensity. If we think of arithmetic intensity as a pole that hits the roof, either it hits the flat part of the roof, which means performance is computationally limited, or it hits the slanted part of the roof, which means perfor mance is ultimately limited by memory bandwidth. In Figure 7.13, kernel 2 is an example of the former and kernel 1 is an example of the latter. Given a roofline of a computer, you can apply it repeatedly, since it doesn’t vary by kernel. FIGURE 7.13 Roofline Model [Williams, Patterson, 2008]. This example has a peak floating-point performance of 16 GFLOPS/sec and a peak memory bandwidth of 16 GB/sec from the Stream benchmark. (Since stream is actually four measurements, this line is the average of the four.) The dotted vertical line in color on the left represents Kernel 1, which has an arithmetic intensity of 0.5 FLOPs/byte. It is limited by memory bandwidth to no more than 8 GFLOPS/sec on this Opteron X2. The dotted vertical line to the right represents Kernel 2, which has an arithmetic intensity of 4 FLOPs/byte. It is limited only computationally to 16 GFLOPS/s. (This data is based on the AMD Opteron X2 (Revision F) using dual cores running at 2 GHz in a dual socket system.) Arithmetic Intensity: FLOPs/Byte Ratio Attainable GFLOPs/second 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 1/8 1/4 1/2 1 2 4 8 16 peak floating-point performance peak memory BW (stream) Kernel 1 (Memory Bandwidth limited) Kernel 2 (Computation limited) 7.10 Roofline: A Simple Performance Model 669 | clipped_hennesy_Page_667_Chunk6024 |
670 Chapter 7 Multicores, Multiprocessors, and Clusters Note that the “ridge point,” where the diagonal and horizontal roofs meet, offers an interesting insight into the computer. If it is far to the right, then only kernels with very high arithmetic intensity can achieve the maximum performance of that computer. If it is far to the left, then almost any kernel can potentially hit the maximum performance. We’ll see examples of both shortly. Comparing Two Generations of Opterons The AMD Opteron X4 (Barcelona) with four cores is the successor to the Opteron X2 with two cores. To simplify board design, they use the same socket. Hence, they have the same DRAM channels and thus the same peak memory bandwidth. In addition to doubling the number of cores, the Opteron X4 also has twice the peak floating-point performance per core: Opteron X4 cores can issue two floating-point SSE2 instructions per clock cycle, while Opteron X2 cores issue at most one. As the two systems we’re comparing have similar clock rates—2.2 GHz for Opteron X2 versus 2.3 GHz for Opteron X4—the Opteron X4 has more than four times the peak floating-point performance of the Opteron X2 with the same DRAM bandwidth. The Opteron X4 also has a 2MB L3 cache, which is not found in the Opteron X2. Figure 7.14 compares the roofline models for both systems. As we would expect, the ridge point moves from 1 in the Opteron X2 to 5 in the Opteron X4. Hence, to see a performance gain in the next generation, kernels need an arithmetic intensity higher than 1 or their working sets must fit in the caches of the Opteron X4. FIGURE 7.14 Roofline models of two generations of Opterons. The Opteron X2 roofline, which is the same as Figure 7.11, is in black, and the Opteron X4 roofline is in color. The bigger ridge point of Opteron X4 means that kernels that where computationally bound on the Opteron X2 could be memory- performance bound on the Opteron X4. Actual FLOPbyte ratio Attainable GFLOP/s 128.0 64.0 32.0 16.0 8.0 4.0 2.0 1.0 0.5 1/8 1/4 1/2 16 8 4 2 1 Opteron X4 (Barcelona) Opteron X2 | clipped_hennesy_Page_668_Chunk6025 |
The roofline model gives an upper bound to performance. Suppose your program is far below that bound. What optimizations should you perform, and in what order? To reduce computational bottlenecks, the following two optimizations can help almost any kernel: 1. Floating-point operation mix. Peak floating-point performance for a com puter typically requires an equal number of nearly simultaneous additions and multiplications. That balance is necessary either because the computer supports a fused multiply-add instruction (see the Elaboration on page 268 in Chapter 3) or because the floating-point unit has an equal number of floating-point adders and floating-point multipliers. The best performance also requires that a significant fraction of the instruction mix is floating- point operations and not integer instructions. 2. Improve instruction-level parallelism and apply SIMD. For superscalar archi tectures, the highest performance comes when fetching, executing, and committing three to four instructions per clock cycle (see Chapter 4). The goal here is to improve the code from the compiler to increase ILP. One way is by unrolling loops. For the x86 architectures, a single SIMD instruction can operate on pairs of double precision operands, so they should be used whenever possible. To reduce memory bottlenecks, the following two optimizations can help: 1. Software prefetching. Usually the highest performance requires keeping many memory operations in flight, which is easier to do by performing software prefetch instructions rather than waiting until the data is required by the computation. 2. Memory affinity. Most microprocessors today include a memory controller on the same chip with the microprocessor. If the system has multiple chips, this means that some addresses go to the DRAM that is local to one chip, and the rest require accesses over the chip interconnect to access the DRAM that is local to another chip. The latter case lowers performance. This optimiza tion tries to allocate data and the threads tasked to operate on that data to the same memory-processor pair, so that the processors rarely have to access the memory of the other chips. The roofline model can help decide which of these optimizations to perform and the order in which to perform them. We can think of each of these optimizations as a “ceiling” below the appropriate roofline, meaning that you cannot break through a ceiling without performing the associated optimization. 7.10 Roofline: A Simple Performance Model 671 | clipped_hennesy_Page_669_Chunk6026 |
672 Chapter 7 Multicores, Multiprocessors, and Clusters FIGURE 7.15 Roofline model with ceilings. The top graph shows the computational “ceilings” of 8 GFLOPs/sec if the floating-point operation mix is imbalanced and 2 GFLOPs/sec if the optimizations to increase ILP and SIMD are also missing. The bottom graph shows the memory bandwidth ceilings of 11 GB/sec without software prefetching and 4.8 GB/sec if memory affinity optimizations are also missing. 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 1/8 1/4 1/2 1 2 4 8 16 peak floating-point performance 1. Fl. Pt. imbalance 2. Without ILP or SIMD AMD Opteron peak memory BW (stream) Arithmetic Intensity: FLOPs/Byte Ratio Attainable GFLOPs/second 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 1/8 1/4 1/2 1 2 4 8 16 AMD Opteron peak memory BW (stream) Arithmetic Intensity: FLOPs/Byte Ratio Attainable GFLOPs/second 3. w/out SW prefetching 4. w/out Memory Affinity peak floating-point performance | clipped_hennesy_Page_670_Chunk6027 |
The computational roofline can be found from the manuals, and the memory roofline can be found from running the stream benchmark. The computational ceilings, such as floating-point balance, also come from the manuals for that com puter. The memory ceiling requires running experiments on each computer to determine the gap between them. The good news is that this process only need be done once per computer, for once someone characterizes a computer’s ceilings, everyone can use the results to prioritize their optimizations for that computer. Figure 7.15 adds ceilings to the roofline model in Figure 7.13, showing the computational ceilings in the top graph and the memory bandwidth ceilings on the bottom graph. Although the higher ceilings are not labeled with both opti mizations, that is implied in this figure; to break through the highest ceiling, you need to have already broken through all the ones below. The thickness of the gap between the ceiling and the next higher limit is the reward for trying that optimization. Thus, Figure 7.15 suggests that optimization 2, which improves ILP, has a large benefit for improving computation on that computer, and optimization 4, which improves memory affinity, has a large benefit for improving memory bandwidth on that computer. Figure 7.16 combines the ceilings of Figure 7.15 into a single graph. The arith metic intensity of a kernel determines the optimization region, which in turn sug gests which optimizations to try. Note that the computational optimizations and the memory bandwidth optimizations overlap for much of the arithmetic inten sity. Three regions are shaded differently in Figure 7.16 to indicate the different optimization strategies. For example, Kernel 2 falls in the blue trapezoid on the right, which suggests working only on the computational optimizations. Kernel 1 falls in the blue-gray parallelogram in the middle, which suggests trying both types of optimizations. Moreover, it suggests starting with optimizations 2 and 4. Note that the Kernel 1 vertical lines fall below the floating-point imbalance optimization, so optimization 1 may be unnecessary. If a kernel fell in the gray triangle on the lower left, it would suggest trying just memory optimizations. Thus far, we have been assuming that the arithmetic intensity is fixed, but that is not really the case. First, there are kernels where the arithmetic intensity increases with problem size, such as for Dense Matrix and N-body problems (see Figure 7.12). Indeed, this can be a reason that programmers have more success with weak scaling than with strong scaling. Second, caches affect the number of accesses that go to memory, so optimizations that improve cache performance also improve arithmetic intensity. One example is improving temporal locality by unrolling loops and then grouping together statements with similar addresses. Many computers have special cache instructions that allocate data in a cache but do not first fill the data from memory at that address, since it will soon be overwritten. Both these optimizations reduce memory traffic, thereby moving the arithmetic intensity pole to the right by a factor of, say, 1.5. This shift right could put the kernel in a different optimization region. 7.10 Roofline: A Simple Performance Model 673 | clipped_hennesy_Page_671_Chunk6028 |
674 Chapter 7 Multicores, Multiprocessors, and Clusters The next section uses the roofline model to demonstrate the difference for four recent multicore microprocessors for two real application kernels. While the examples above show how to help programmers improve performance, the model can also be used by architects to decide where they optimize hardware to improve performance of the kernels that they think will be important. Elaboration: The ceilings are ordered so that lower ceilings are easier to optimize. Clearly, a programmer can optimize in any order, but following this sequence reduces the chances of wasting effort on an optimization that has no benefit due to other constraints. Like the 3Cs model, as long as the roofline model delivers on insights, a model can have quirks. For example, it assumes the program is load balanced between all processors. FIGURE 7.16 Roofline model with ceilings, overlapping areas shaded, and the two ker nels from Figure 7.13. Kernels whose arithmetic intensity land in the blue trapezoid on the right should focus on computation optimizations, and kernels whose arithmetic intensity land in the gray triangle in the lower left should focus on memory bandwidth optimizations. Those that land in the blue-gray parallelogram in the middle need to worry about both. As Kernel 1 falls in the parallelogram in the middle, try optimizing ILP and SIMD, memory affinity, and software prefetching. Kernel 2 falls in the trapezoid on the right, so try optimizing ILP and SIMD and the balance of floating-point operations. 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 1 2 4 8 16 peak memory BW (stream) Arithmetic Intensity: FLOPs/Byte Ratio Attainable GFLOPs/second Kernel 1 Kernel 2 2. Without ILP or SIMD 4. w/out Memory Affinity 1. Fl. Pt. imbalance 3. w/out SW prefetching peak floating-point performance 1/8 1/4 1/2 | clipped_hennesy_Page_672_Chunk6029 |
Elaboration: An alternative to the Stream benchmark is to use the raw DRAM bandwidth as the roofline. While the DRAMs definitely set a hard bound, actual memory performance is often so far from that boundary that it’s not that useful as an upper bound. That is, no program can go close to that bound. The downside to using Stream is that very careful programming may exceed the Stream results, so the memory roofline may not be as hard a limit as the computational roofline. We stick with Stream because few programmers will be able to deliver more memory bandwidth than Stream discovers. Elaboration: The two axes used above were floating-point operations per second and arithmetic intensity of accesses to main memory. The roofline model could be used for other kernels and computers where the performance was a function of different performance metrics. For example, if the working set fits in the L2 cache of the computer, the bandwidth plotted on the diagonal roofline could be L2 cache bandwidth instead of main memory bandwidth, and the arithmetic intensity on the X-axis would be based on FLOPs per L2 cache byte accessed. The diagonal L2 performance line would move up, and the ridge point would likely move to the left. As a second example, if the kernel was sort, records sorted per second could replace floating-point operations per instruction on the Y-axis and arithmetic intensity would become records per DRAM byte accessed. The roofline model could even work for an I/O intensive kernel. The Y-axis would be I/O operations per second, the X-axis would be the average number of instructions per I/O operation, and the roofline would show peak I/O bandwidth. Elaboration: Although the roofline model shown is for multicore processors, it clearly would work for a uniprocessor as well. 7.11 Real Stuff: Benchmarking Four Multicores Using the Roofline Model Given the uncertainty about the best way to proceed in this parallel revolution, it’s not surprising that we see as many different designs as there are multicore chips. In this section, we’ll examine four multicore systems for two kernels of the design patterns in Figure 7.11: sparse matrix and structured grid. (The information in this section is from [Williams, Oliker, et al., 2007], [Williams, Carter, et al., 2008], [Williams and Patterson, 2008].) 7.11 Real Stuff: Benchmarking Four Multicores Using the Roofline Model 675 | clipped_hennesy_Page_673_Chunk6030 |
676 Chapter 7 Multicores, Multiprocessors, and Clusters Four Multicore Systems Figure 7.17 shows the basic organization of the four systems, and Figure 7.18 lists the key characteristics of the examples of this section. These are all dual socket systems. Figure 7.19 shows the roofline performance model for each system. 667 MHz FBDIMMs Chipset (4x64 b controllers) 10.66 GB/s(write) 21.33 GB/s(read) 10.66 GB/s Core FSB Core Core Core 10.66 GB/s Core FSB Core Core Core 4 MB Shared L2 4 MB Shared L2 4 MB Shared L2 4 MB Shared L2 667 MHz FBDIMMs 4MB Shared L2 (16 way) (address interleaving via 8x64 B banks) 179 GB/s (fill) 90 GB/s (writethru) 21.33 GB/s (read) 10.66 GB/s (write) 8x6.4 GB/s (1 per hub per direction) 4 Coherency Hubs (2 banks each) 2x128 b memory controllers (4 banks each) 21.33 GB/s (read) 10.66 GB/s (write) Crossbar Switch (16 Byte reads 8 Byte writes) MT sparc MT sparc MT sparc MT sparc MT sparc MT sparc MT sparc MT sparc 8K L1 8K L1 8K L1 8K L1 8K L1 8K L1 8K L1 8K L1 667 MHz FBDIMMs 4MB Shared L2 (16 way) (address interleaving via 8x64 B banks) 4 Coherency Hubs (2 banks each) 2x128 b memory controllers (4 banks each) MT sparc MT sparc MT sparc MT sparc MT sparc MT sparc 8K L1 8K L1 8K L1 8K L1 8K L1 8K L1 179 GB/s (fill) 90 GB/s (writethru) MT sparc MT sparc 8K L1 8K L1 Crossbar Switch (16 Byte reads 8 Byte writes) (c) Sun UltraSPARC T2 5140 (Niagara 2) (a) Intel Xeon e5345 (Clovertown) FIGURE 7.17 Four recent multiprocessors, each using two sockets for the processors. Starting from the upper left hand corner, the computers are: (a) Intel Xeon e5345 (Clovertown), (b) AMD Opteron X4 2356 (Barcelona), (c) Sun UltraSPARC T2 5140 (Niagara 2), and (d) IBM Cell QS20. Note that the Intel Xeon e5345 (Clovertown) has a separate north bridge chip not found in the other microprocessors. (d) IBM Cell QS20 667 MHz DDR2 DIMMs 10.66 GB/s 2x64 b memory controllers HyperTransport Opteron Opteron Opteron 667 MHz DDR2 DIMMs 10.66 GB/s 2x64 b memory controllers 512 KB victim 2 MB Shared quasi-victim (32 way) SRI/crossbar 2 MB Shared quasi-victim (32 way) SRI/crossbar HyperTransport 4 GB/s (each direction) 512 KB victim 512 KB victim 512 KB victim 512 KB victim 512 KB victim 512 KB victim 512 KB victim Opteron Opteron Opteron Opteron Opteron <32 GB 800 MHz DDR2 DIMMs 25.6 GB/s EIB (Ring Network) SPE 256 K MFC SPE 256 K MFC SPE 256 K MFC SPE 256 K MFC MFC MFC MFC MFC 256 K 256 K 256 K 256 K SPE SPE SPE SPE 4x64b controllers BIF VMT PPE 512 KB L2 <32 GB 800 MHz DDR2 DIMMs 25.6 GB/s EIB (Ring Network) BIF VMT PPE 512 KB L2 SPE 256 K MFC SPE 256 K MFC SPE 256 K MFC SPE 256 K MFC <20 GB/s (each direction) MFC MFC MFC MFC 256 K 256 K 256 K 256 K SPE SPE SPE SPE 4x64b controllers (b) AMD Opteron X4 2356 (Barcelona) | clipped_hennesy_Page_674_Chunk6031 |
The Intel Xeon e5345 (code-named “Clovertown”) contains four cores per socket by packaging two dual core chips into a single socket. These two chips share a front side bus that is attached to a separate north bridge chip set (see Chapter 6). This north bridge chip set supports two front side buses and hence two sockets. It includes the memory controller for the 667 MHz Fully Buffered DRAM DIMMs (FBDIMMs). This dual-socket system uses a processor clock rate of 2.33 GHz and has the highest peak performance of the four examples: 75 GFLOPS. However, the roofline model in Figure 7.19 shows that this can be achieved only with arithmetic intensities of 8 and above. The reason is that the dual front side buses interfere with each other, yielding relatively low memory bandwidth to programs. The AMD Opteron X4 2356 (Barcelona) contains four cores per chip, and each socket has a single chip. Each chip has a memory controller on board and its own path to 667 MHz DDR2 DRAM. These two sockets communicate over separate, dedicated Hypertransport links, which makes it possible to build a “glueless” multichip system. This dual-socket system uses a processor clock rate of 2.30 GHz and has a peak performance of about 74 GFLOPS. Figure 7.19 shows that the ridge point in the roofline model is to the left of the Xeon e5345 (Clovertown), at an arithmetic intensity of about 5 FLOPS per byte. The Sun UltraSPARC T2 5140 (code named “Niagara 2”) is quite different from the two x86 microarchitectures. It uses eight relatively simple cores per chip with a much lower clock rate. It also provides fine-grained multithreading with eight threads per core. A single chip has four memory controllers that could drive four sets of 667 MHz FBDIMMs. To join two UltraSPARC T2 chips together, two of the four memory channels are connected, leaving two memory channels per chip. This dual-socket system has a peak performance of about 22 GFLOPS, and the ridge point is an amazingly low arithmetic intensity of just 1/3 FLOPS per byte. FIGURE 7.18 Characteristics of the four recent multicores. Although the Xeon e5345 and Opteron X4 have the same speed DRAMs, the Stream benchmark shows a higher practical memory bandwidth due to the inefficiencies of the front side bus on the Xeon e5345. MPU Type ISA Number Threads Number Cores Number Sockets Clock GHz Peak GFLOP/s DRAM: Peak GB/s, Clock Rate, Type Intel Xeon e5345 (Clovertown) x86/64 8 8 2 2.33 75 FSB: 2 x 10.6 667 MHz FBDIMM AMD Opteron X4 2356 (Barcelona) x86/64 8 8 2 2.30 74 2 x 10.6 667 MHz DDR2 Sun UltraSPARC T2 5140 (Niagara 2) Sparc 128 16 2 1.17 22 2 x 21.3 (read) 2 x 10.6 (write) 667 MHz FBDIMM IBM Cell QS20 Cell 16 16 2 3.20 29 2 x 25.6 XDR 7.11 Real Stuff: Benchmarking Four Multicores Using the Roofline Model 677 | clipped_hennesy_Page_675_Chunk6032 |
678 Chapter 7 Multicores, Multiprocessors, and Clusters FIGURE 7.19 Roofline model for multicore multiprocessors in Figure 7.15. The ceilings are the same as in Figure 7.13. Starting from the upper left hand corner, the computers are: (a) Intel Xeon e5345 (Clovertown), (b) AMD Opteron X4 2356 (Barcelona), (c) Sun UltraSPARC T2 5140 (Niagara 2), and (d) IBM Cell QS20. Note the ridge points for the four microprocessors intersect the X-axis at the arithmetic intensities of 6, 4, 1/3, and 3/4, respectively. The dashed vertical lines are for the two kernels of this section and the stars mark the performance achieved for these kernels after all the optimizations. SpMV is the pair of dashed vertical lines on the left. It has two lines because its arithmetic intensity improved from 0.166 to 0.255 based on register blocking optimizations. LBHMD is the dashed vertical lines on the right. It has a pair of lines in (a) and (b) because a cache optimization skips filling the cache block on a miss when the processor would write new data into the entire block. That optimization increases the arithmetic intensity from 0.70 to 1.07. It’s a single line in (c) at 0.70 because UltraSPARC T2 does not offer the cache optimization. It is a single line at 1.07 in (d) because Cell has local store loaded by DMA, so the program doesn’t fetch unnecessary data as do caches. Attainable GFLOP/s Actual FLOPbyte ratio 1/8 1/4 1/2 1 2 4 8 16 Peak DP mul/add imbalance w/out SIMD w/out ILP 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 1.0 a. Intel Xeon e5345 (Clovertown) Attainable GFLOP/s Actual FLOPbyte ratio b. AMD Opteron X4 2356 (Barcelona) 1/8 1/4 1/2 1 2 4 8 16 Peak DP mul/add imbalance w/out SIMD w/out ILP 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 1.0 Actual FLOPbyte ratio Attainable GFLOP/s Attainable GFLOP/s d. IBM Cell QS20 Peak DP w/out FMA w/out SIMD w/out ILP 1/8 1/4 1/2 1 2 4 8 16 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 1.0 Actual FLOPbyte ratio c. Sun UltraSPARC T2 5140 (Niagara 2) 25% issued = FP Peak DP 1/8 1/4 1/2 1 2 4 8 16 0.5 1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 1.0 | clipped_hennesy_Page_676_Chunk6033 |
The IBM Cell QS20 is again different from the two x86 microarchitectures and from UltraSPARC T2. It is a heterogeneous design, with a relatively simple PowerPC core and with eight SPEs (Synergistic Processing Elements) that have their own unique SIMD-style instruction set. Each SPE also has its own local memory instead of a cache. An SPE must transfer data from main memory into the local memory to operate on it and then back to main memory when it is completed. It uses DMA, which has some similarity to software prefetching. The two sockets are connected via links dedicated to multichip communications. The clock rate of this system is highest of the four multicores at 3.2 GHz, and it uses XDR DRAM chips, which are typically found in game consoles. They have high bandwidth but low capacity. Given that the Cell’s main application was graphics, it has much higher single precision performance than double precision performance. The peak double precision performance of the SPEs in the dual socket system is 29 GFLOPS, and the ridge point of arithmetic intensity is 0.75 FLOPs per byte. While the two x86 architectures have many fewer cores per chip than the IBM and Sun offerings in early 2008, that is just where they are today. As the number of cores is expected to double every technology generation, it will be interesting to see whether the x86 architectures will close the “core gap” or if IBM and Sun can sustain a larger number of cores, given that their primary focus is on servers versus the desktop. Note that these machines take very different approaches to the memory system. The Xeon e5345 uses a conventional private L1 cache and then pairs of processors each share an L2 cache. These are connected through an off-chip memory controller to a common memory over two buses. In contrast, Opteron X4 has a separate memory controller and memory per chip, and each core has private L1 and L2 caches. UltraSPARC T2 has the memory controller on-chip and four separate DRAM channels per chip, and the cores all share the L2 cache, which has four banks to improve bandwidth. Its fine-grained multithreading on top of its multicore design allows it to keep many memory accesses in flight. The most radical is the Cell. It has local private memories per SPE and uses DMA to transfer data between the DRAM attached to each chip and local memory. It sustains many memory accesses in flight by having many cores and then many DMA transfers per core. Let’s see how these four contrasting multicores perform on two kernels. Sparse Matrix The first example kernel of the Sparse Matrix computational design pattern is Sparse Matrix-Vector multiply (SpMV). SpMV is popular in scientific computing, economic modeling, and information retrieval. Alas, conventional implementa tions often run at less than 10% of peak performance of uniprocessors. One reason is the irregular access to memory, which you might expect from a kernel working with sparse matrices. The computation is 7.11 Real Stuff: Benchmarking Four Multicores Using the Roofline Model 679 | clipped_hennesy_Page_677_Chunk6034 |
680 Chapter 7 Multicores, Multiprocessors, and Clusters y = A × x where A is a sparse matrix and x and y are dense vectors. Fourteen sparse matrices taken from a variety of real applications were used to evaluate SpMV performance, but only the median performance is reported here. The arithmetic intensity varies from 0.166 before a register blocking optimization to 0.250 FLOPS per byte afterward. The code was first parallelized to utilize all the cores. Given that the low arithmetic intensity of SpMV was below the ridge point of all four multicores in Figure 7.19, most of the optimizations involved the memory system: ■ ■Prefetching. To get the most out of the memory systems, both software and hardware prefetching were used. ■ ■Memory Affinity. This optimization reduces accesses to the DRAM memory connected to the other socket in the three systems that have local DRAM memory. ■ ■Compressing Data Structures. Since memory bandwidth likely limits per formance, this optimization uses smaller data structures to increase performance—for example, using a 16-bit index instead of a 32-bit index, and using more space efficient representations of the nonzeros in the rows of a sparse matrix. Figure 7.20 shows the performance on SpMV for the four systems versus the number of cores. (The same results are found in Figure 7.19, but it’s hard to compare performance when on a log scale.) Note that despite having the highest peak performance in Figure 7.18 and the highest single core performance, the Intel Xeon e5345 has the lowest delivered performance of the four multicores. Opteron X4 doubles its performance. The Xeon e5345 bottleneck is the dual front side buses. Despite the lowest clock rate, the larger number of simple cores of the Sun UltraSPARC T2 outperforms the two x86 processors. The IBM Cell has the highest performance of the four. Note that all but the Xeon e5345 scale well with the number of cores, although the Opteron X4 scales more slowly with four or more cores. Structured Grid The second kernel is an example of the structured grid design pattern. Lattice- Boltzmann Magneto-Hydrodynamics (LBMHD) is popular for computational fluid dynamics; it is a structured grid code with a series of time steps. | clipped_hennesy_Page_678_Chunk6035 |
Each point involves reading and writing about 75 double precision floating- point numbers and about 1300 floating-point operations. Like SpMV, LBMHD tends to get a small fraction of peak performance on uniprocessors because of the complexity of the data structures and the irregularity of memory access patterns. The FLOPS to byte ratio is a much higher 0.70 versus less than 0.25 in SpMV. By not filling the cache block from memory on a write miss when the program is going to overwrite the whole block, the intensity rises to 1.07. All multicores but UltraSPARC T2 (Niagara 2) offer this cache optimization. Figure 7.19 shows that the arithmetic intensity of LBMHD is high enough that both computational and memory bandwidth optimizations make sense on all multicores but UltraSPARC T2, whose roofline ridge point is below that of LBMHD. UltraSPARC T2 can reach the roofline using only the computational optimizations. In addition to parallelizing the code so that it could use all the cores, the following optimizations were used for LBMHD: ■ ■Memory Affinity: This optimization is again useful for the same reasons mentioned above. ■ ■TLB Miss Minimization: To reduce TLB misses significantly in LBMHD, use a structure of arrays and combine some loops together rather than the con ventional approach of using an array of structures. FIGURE 7.20 Performance of SpMV on the four multicores. 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Cores GFLOPs/sec Opteron X4 2356 Cell QS20 UltraSPARC T2 Xeon e5346 7.11 Real Stuff: Benchmarking Four Multicores Using the Roofline Model 681 | clipped_hennesy_Page_679_Chunk6036 |
682 Chapter 7 Multicores, Multiprocessors, and Clusters ■ ■Loop Unrolling and Reordering: To expose sufficient parallelism and improve cache utilization, the loops were unrolled and then reordered to group state ments with similar addresses. ■ ■“SIMD-ize”: The compilers of the two x86 systems could not generate good SSE code, so these had to be written by hand in assembly language. Figure 7.21 shows the performance for the four systems versus the number of cores for LBMHD. Like the SpMV, the Intel Xeon e5345 has the worst scalability. This time the more powerful cores of Opteron X4 outperform the simple cores of UltraSPARC T2 despite having half the number of cores. Once again, the IBM Cell is the fastest system. All but Xeon e5345 scale with the number of cores, although T2 and Cell scale more smoothly than the Opteron X4. FIGURE 7.21 Performance of LBMHD on the four multicores. 0.0 2.0 4.0 6.0 8.0 10.0 12.0 14.0 16.0 18.0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Cores GFLOPs/sec Opteron X4 2356 Cell QS20 UltraSPARC T2 Xeon e5345 Productivity In addition to performance, another important issue for the parallel computing revolution is productivity, or the programming difficulty of achieving perfor mance. To illustrate the differences, Figure 7.22 compares naïve performance to fully optimized performance for the four cores on the two kernels. | clipped_hennesy_Page_680_Chunk6037 |
FIGURE 7.22 Base versus fully optimized performance of the four cores on the two kernels. Note the high fraction of fully optimized performance delivered by the Sun UltraSPARC T2 (Niagara 2). There is no base performance column for the IBM Cell because there is no way to port the code to the SPEs without caches. While you could run the code on the Power core, it has an order of magnitude lower performance than the SPES, so we ignore it in this figure. MPU Type Kernel Base GFLOPs/s Optimized GFLOPs/s Naïve % of Optimized Intel Xeon e5345 (Clovertown) SpMV LBMHD 1.0 4.6 1.5 5.6 64% 82% AMD Opteron X4 2356 (Barcelona) SpMV LBMHD 1.4 7.1 3.6 14.1 38% 50% Sun UltraSPARC T2 (Niagara 2) SpMV LBMHD 3.5 9.7 4.1 10.5 86% 93% IBM Cell QS20 SpMV LBMHD 6.4 16.7 0% 0% The easiest was UltraSPARC T2, due to its large memory bandwidth and its easy-to-understand cores. The advice for these two kernels in UltraSPARC T2 is simply to try to get good performing code from the compiler and then use as many threads as possible. The one caution for other kernels is that UltraSPARC T2 can come afoul of the pitfall about making sure set associativity matches the number of hardware threads (see page 545 of Chapter 5). Each chip supports 64 hardware threads, while the L2 cache is four-way set associative. This mismatch can require restructuring loops to reduce conflict misses. The Xeon e5346 was difficult because it was hard to understand the memory behavior of the dual front side buses, it was hard to understand how hardware prefetching worked, and it was difficult to get good SIMD code from the compiler. The C code for it and for the Opteron X4 are liberally sprinkled with intrinsic statements involving SIMD instructions to get good performance. The Opteron X4 benefited from the most types of optimizations, so it needed more effort than the Xeon e5345, although the memory behavior of the Opteron X4 was easier to understand than that of the Xeon e5345. Cell provided two types of challenges. First, the SIMD instructions of the SPE were awkward to compile for, so at times you needed to help the compiler by inserting intrinsic statements with assembly language instructions into the C code. Second, the memory system was more interesting. Since each SPE has local memory in a separate address space, you could not simply port the code and start 7.11 Real Stuff: Benchmarking Four Multicores Using the Roofline Model 683 | clipped_hennesy_Page_681_Chunk6038 |
684 Chapter 7 Multicores, Multiprocessors, and Clusters running on the SPE. Hence, there is no base code column for the IBM Cell in Figure 7.22, and you needed to change the program to issue DMA commands to transfer data back and forth between local store and memory. The good news is that DMA played the role of software prefetch in caches, and DMA is much easier to use and achieve good memory performance. Cell was able to deliver almost 90% of the memory bandwidth “roofline” to these kernels, compared to 50% or less for the other multicores. 7.12 Fallacies and Pitfalls The many assaults on parallel processing have uncovered numerous fallacies and pitfalls. We cover three here. Fallacy: Amdahl’s law doesn’t apply to parallel computers. In 1987, the head of a research organization claimed that Amdahl’s law had been broken by a multiprocessor machine. To try to understand the basis of the media reports, let’s see the quote that gave us Amdahl’s law [1967, p. 483]: A fairly obvious conclusion which can be drawn at this point is that the effort expended on achieving high parallel processing rates is wasted unless it is accompanied by achievements in sequential processing rates of very nearly the same magnitude. This statement must still be true; the neglected portion of the program must limit performance. One interpretation of the law leads to the following lemma: por tions of every program must be sequential, so there must be an economic upper bound to the number of processors—say, 100. By showing linear speed-up with 1000 processors, this lemma is disproved; hence the claim that Amdahl’s law was broken. The approach of the researchers was to use weak scaling: rather than going 1000 times faster on the same data set, they computed 1000 times more work in comparable time. For their algorithm, the sequential portion of the program was constant, independent of the size of the input, and the rest was fully parallel— hence, linear speed-up with 1000 processors. Amdahl’s law obviously applies to parallel processors. What this research does point out is that one of the main uses of faster computers is to run larger problems, but to beware how the algorithm scales as you increase problem size. Fallacy: Peak performance tracks observed performance. For example, Section 7.11 shows that the Intel Xeon e5345, the microprocessor with the highest peak performance, was the slowest of the four multicore micro processors for two kernels. For over a decade prophets have voiced the contention that the organization of a single computer has reached its limits and that truly significant advances can be made only by interconnec tion of a multiplicity of computers in such a manner as to permit cooperative solution. . . . Demonstration is made of the continued validity of the single processor approach . . . Gene Amdahl, “Validity of the single processor approach to achieving large scale computing capabilities,” Spring Joint Computer Conference, 1967 | clipped_hennesy_Page_682_Chunk6039 |
The supercomputer industry used this metric in marketing, and the fallacy is exacerbated with parallel machines. Not only are marketers using the nearly unattainable peak performance of a uniprocessor node, but also they are then multiplying it by the total number of processors, assuming perfect speed-up! Amdahl’s law suggests how difficult it is to reach either peak; multiplying the two together multiplies the sins. The roofline model helps put peak performance in perspective. Pitfall: Not developing the software to take advantage of, or optimize for, a multi processor architecture. There is a long history of software lagging behind on parallel processors, possibly because the software problems are much harder. We give one example to show the subtlety of the issues, but there are many examples we could choose! One frequently encountered problem occurs when software designed for a uniprocessor is adapted to a multiprocessor environment. For example, the SGI operating system originally protected the page table with a single lock, assum ing that page allocation is infrequent. In a uniprocessor, this does not represent a performance problem. In a multiprocessor, it can become a major performance bottleneck for some programs. Consider a program that uses a large number of pages that are initialized at start-up, which UNIX does for statically allocated pages. Suppose the program is parallelized so that multiple processes allocate the pages. Because page allocation requires the use of the page table, which is locked when ever it is in use, even an OS kernel that allows multiple threads in the OS will be serialized if the processes all try to allocate their pages at once (which is exactly what we might expect at initialization time!). This page table serialization eliminates parallelism in initialization and has significant impact on overall parallel performance. This performance bottleneck persists even for job-level parallelism. For example, suppose we split the parallel processing program apart into separate jobs and run them, one job per processor, so that there is no sharing between the jobs. (This is exactly what one user did, since he reasonably believed that the performance problem was due to unintended sharing or interference in his application.) Unfortunately, the lock still serializes all the jobs—so even the independent job performance is poor. This pitfall indicates the kind of subtle but significant performance bugs that can arise when software runs on multiprocessors. Like many other key software components, the OS algorithms and data structures must be rethought in a multi processor context. Placing locks on smaller portions of the page table effectively eliminates the problem. 7.12 Fallacies and Pitfalls 685 | clipped_hennesy_Page_683_Chunk6040 |
686 Chapter 7 Multicores, Multiprocessors, and Clusters 7.13 Concluding Remarks The dream of building computers by simply aggregating processors has been around since the earliest days of computing. Progress in building and using effec tive and efficient parallel processors, however, has been slow. This rate of progress has been limited by difficult software problems as well as by a long process of evolv ing the architecture of multiprocessors to enhance usability and improve efficiency. We have discussed many of the software challenges in this chapter, including the difficulty of writing programs that obtain good speed-up due to Amdahl’s law. The wide variety of different architectural approaches and the limited success and short life of many of the parallel architectures of the past have compounded the software difficulties. We discuss the history of the development of these multiprocessors in Section 7.14 on the CD. As we said in Chapter 1, despite this long and checkered past, the information technology industry has now tied its future to parallel computing. Although it is easy to make the case that this effort will fail like many in the past, there are reasons to be hopeful: ■ ■Clearly, software as a service is growing in importance, and clusters have proven to be a very successful way to deliver such services. By providing redun dancy at a higher-level, including geographically distributed datacenters, such services have delivered 24 × 7 × 365 availability for customers around the world. It’s hard not to imagine that both the number of servers per datacenter and the number of datacenters will continue to grow. Certainly, such datacenters will embrace multicore designs, since they can already use thousands of processors in their applications. ■ ■The use of parallel processing in domains such as scientific and engineering computation is popular. This application domain has an almost limitless thirst for more computation. It also has many applications that have lots of natural concurrency. Once again, clusters dominate this application area. For example, using the 2007 Linpack report, clusters represent more than 80% of the 500 fastest computers. Nonetheless, it has not been easy: programming parallel processors even for these applications remains challenging. Yet this group too will surely embrace multicore chips, since again they have experience with hundreds to thousand of processors. ■ ■All desktop and server microprocessor manufacturers are building multi processors to achieve higher performance, so unlike the past, there is no easy We are dedicating all of our future product development to multicore designs. We believe this is a key inflection point for the industry. ... This is not a race. This is a sea change in computing...” Paul Otellini, Intel President, Intel Developers Forum, 2004. software as a service Rather than selling software that is installed and run on customers own computers, software is run at a remote site and made available over the Internet typically via a Web interface to customers. Customers are charged based on use. | clipped_hennesy_Page_684_Chunk6041 |
path to higher performance for sequential applications. Hence, programmers who need higher performance must parallelize their codes or write new parallel processing programs. ■ ■Multiple processors on the same chip allow a very different speed of commu nication than multiple chip designs, offering both much lower latency and much higher bandwidth. These improvements may make it easier to deliver good performance. ■ ■In the past, microprocessors and multiprocessors were subject to different definitions of success. When scaling uniprocessor performance, micropro cessor architects were happy if single thread performance went up by the square root of the increased silicon area. Thus, they were happy with sublin ear performance in terms of resources. Multiprocessor success used to be defined as linear speed-up as a function of the number of processors, assum ing that the cost of purchase or cost of administration of n processors was n times as much as one processor. Now that parallelism is happening on-chip via multicore, we can use the traditional microprocessor of being successful with sublinear performance improvement. ■ ■The success of just-in-time runtime compilation makes it feasible to think of software adapting itself to take advance of the increasing number of cores per chip, which provides flexibility that is not available when limited to static compilers. ■ ■Unlike in the past, the open source movement has become a critical portion of the software industry. This movement is a meritocracy, where better engi neering solutions can win the mind share of the developers over legacy concerns. It also embraces innovation, inviting change to old software and welcoming new languages and software products. Such an open culture could be extremely helpful in this time of rapid change. This revolution in the hardware/software interface is perhaps the greatest chal lenge facing the field in the last 50 years. It will provide many new research and business opportunities inside and outside the IT field, and the companies that dominate the multicore era may not be the same ones that dominated the unipro cessor era. Perhaps you will be one of the innovators who will seize the opportunities that are sure to appear in the uncertain times ahead. 7.13 Concluding Remarks 687 | clipped_hennesy_Page_685_Chunk6042 |
688 Chapter 7 Multicores, Multiprocessors, and Clusters 7.14 Historical Perspective and Further Reading This section on the CD gives the rich and often disastrous history of multiproces sors over the last 50 years. 7.15 Exercises Contributed by David Kaeli of Northeastern University Exercise 7.1 First, write down a list of your daily activities that you typically do on a weekday. For instance, you might get out of bed, take a shower, get dressed, eat breakfast, dry your hair, brush your teeth, etc. Make sure to break down your list so you have a minimum of 10 activities. 7.1.1 [5] <7.2> Now consider which of these activities is already exploiting some form of parallelism (e.g., brushing multiple teeth at the same time, versus one at a time, carrying one book at a time to school, versus loading them all into your backpack and then carry them “in parallel”). For each of your activities, discuss if they are already working in parallel, but if not, why they are not. 7.1.2 [5] <7.2> Next, consider which of the activities could be carried out con currently (e.g., eating breakfast and listening to the news). For each of your activi ties, describe which other activity could be paired with this activity. 7.1.3 [5] <7.2> For 7.1.2, what could we change about current systems (e.g., showers, clothes, TVs, cars) so that we could perform more tasks in parallel? 7.1.4 [5] <7.2> Estimate how much shorter time it would take to carry out these activities if you tried to carry out as many tasks in parallel as possible. Exercise 7.2 Many computer applications involve searching through a set of data and sorting the data. A number of efficient searching and sorting algorithms have been devised in order to reduce the runtime of these tedious tasks. In this problem we will consider how best to parallelize these tasks. | clipped_hennesy_Page_686_Chunk6043 |
7.2.1 [10] <7.2> Consider the following binary search algorithm (a classic divide and conquer algorithm) that searches for a value X in an sorted N-element array A and returns the index of matched entry: BinarySearch(A[0..N-1], X) { low = 0 high = N - 1 while (low <= high) { mid = (low + high) / 2 if (A[mid] > X) high = mid - 1 else if (A[mid] < X) low = mid + 1 else return mid // found } return -1 // not found } Assume that you have Y cores on a multi-core processor to run BinarySearch. Assuming that Y is much smaller than N, express the speedup factor you might expect to obtain for values of Y and N. Plot these on a graph. 7.2.2 [5] <7.2> Next, assume that Y is equal to N. How would this affect your conclusions in your previous answer? If you were tasked with obtaining the best speedup factor possible (i.e., strong scaling), explain how you might change this code to obtain it. Exercise 7.3 Consider the following piece of C code: for (j=2;j<1000;j++) D[j] = D[j-1]+D[j-2]; The MIPS code corresponding to the above fragment is: DADDIU r2,r2,999 loop: L.D f1, -16(f1) L.D f2, -8(f1) ADD.D f3, f1, f2 S.D f3, 0(r1) DADDIU r1, r1, 8 BNE r1, r2, loop 7.15 Exercises 689 | clipped_hennesy_Page_687_Chunk6044 |
690 Chapter 7 Multicores, Multiprocessors, and Clusters Instructions have the following associated latencies (in cycles): ADD.D L.D S.D DADDIU 4 6 1 2 7.3.1 [10] <7.2> How many cycles does it take for all instructions in a single iteration of the above loop to execute? 7.3.2 [10] <7.2> When an instruction in a later iteration of a loop depends upon a data value produced in an earlier iteration of the same loop, we say that there is a loop carried dependence between iterations of the loop. Identify the loop-carried dependences in the above code. Identify the dependent program variable and assembly-level registers. You can ignore the loop induction variable j. 7.3.3 [10] <7.2> Loop unrolling was described in Chapter 4. Apply loop unroll ing to this loop and then consider running this code on a 2-node distributed mem ory message passing system. Assume that we are going to use message passing as described in Section 7.4, where we introduce a new operation send (x, y) that sends to node x the value y, and an operation receive( ) that waits for the value being sent to it. Assume that send operations take a cycle to issue (i.e., later instructions on the same node can proceed on the next cycle), but take 10 cycles be received on the receiving node. Receive instructions stall execution on the node where they are executed until they receive a message. Produce a schedule for the two nodes assuming an unroll factor of 4 for the loop body (i.e., the loop body will appear 4 times). Compute the number of cycles it will take for the loop to run on the message passing system. 7.3.4 [10] <7.2> The latency of the interconnect network plays a large role in the efficiency of message passing systems. How fast does the interconnect need to be in order to obtain any speedup from using the distributed system described in 7.3.3? Exercise 7.4 Consider the following recursive mergesort algorithm (another classic divide and conquer algorithm). Mergesort was first described by John Von Neumann in 1945. The basic idea is to divide an unsorted list x of m elements into two sublists of about half the size of the original list. Repeat this operation on each sublist, and continue until we have lists of size 1 in length. Then starting with sublists of length 1, “merge” the two sublists into a single sorted list. Mergesort(m) var list left, right, result if length(m) ≤ 1 return m | clipped_hennesy_Page_688_Chunk6045 |
else var middle = length(m) / 2 for each x in m up to middle add x to left for each x in m after middle add x to right left = Mergesort(left) right = Mergesort(right) result = Merge(left, right) return result The merge step is carried out by the following code: Merge(left,right) var list result while length(left) > 0 and length(right) > 0 if first(left) ≤ first(right) append first(left) to result left = rest(left) else append first(right) to result right = rest(right) if length(left) > 0 append rest(left) to result if length(right) > 0 append rest(right) to result return result 7.4.1 [10] <7.2> Assume that you have Y cores on a multi-core processor to run MergeSort. Assuming that Y is much smaller than length(m), express the speedup factor you might expect to obtain for values of Y and length(m). Plot these on a graph. 7.4.2 [10] <7.2> Next, assume that Y is equal to length(m). How would this affect your conclusions your previous answer? If you were tasked with obtaining the best speedup factor possible (i.e., strong scaling), explain how you might change this code to obtain it. Exercise 7.5 You are trying to bake 3 blueberry pound cakes. Cake ingredients are as follows: 1 cup butter, softened 1 cup sugar 7.15 Exercises 691 | clipped_hennesy_Page_689_Chunk6046 |
692 Chapter 7 Multicores, Multiprocessors, and Clusters 4 large eggs 1 teaspoon vanilla extract 1/2 teaspoon salt 1/4 teaspoon nutmeg 1 1/2 cups flour 1 cup blueberries The recipe for a single cake is as follows: Step 1: Preheat oven to 325°F (160°C). Grease and flour your cake pan. Step 2: In large bowl, beat together with a mixer butter and sugar at medium speed until light and fluffy. Add eggs, vanilla, salt and nutmeg. Beat until thoroughly blended. Reduce mixer speed to low and add flour, 1/2 cup at a time, beating just until blended. Step 3: Gently fold in blueberries. Spread evenly in prepared baking pan. Bake for 60 minutes. 7.5.1 [5] <7.2> Your job is to cook 3 cakes as efficiently as possible. Assuming that you only have one oven large enough to hold one cake, one large bowl, one cake pan, and one mixer, come up with a schedule to make three cakes as quickly as possible. Identify the bottlenecks in completing this task. 7.5.2 [5] <7.2> Assume now that you have three bowls, 3 cake pans and 3 mixers. How much faster is the process now that you have additional resources? 7.5.3 [5] <7.2> Assume now that you have two friends that will help you cook, and that you have a large oven that can accommodate all three cakes. How will this change the schedule you arrived at in 7.5.1 above? 7.5.4 [5] <7.2> Compare the cake-making task to computing 3 iterations of a loop on a parallel computer. Identify data-level parallelism and task-level parallelism in the cake-making loop. Exercise 7.6 Matrix multiplication plays an important role in a number of applications. Two matrices can only be multiplied if the number of columns of the first matrix is equal to the number of rows in the second. Let’s assume we have an m × n matrix A and we want to multiply it by an n × p matrix B. We can express their product as an m × p matrix denoted by AB (or A · B). If we assign C = AB, and ci,j denotes the entry in C at position (i, j), then ci,j = r = 1 n ai, rbr,j = ai, 1b1,j + ai,2b2,j + … + ai,nbn,j | clipped_hennesy_Page_690_Chunk6047 |
for each element i and j with 1 ≤ i ≤ m and 1 ≤ j ≤ p. Now we want to see if we can parallelize the computation of C. Assume that matrices are laid out in memory sequentially as follows: a1,1, a2,1, a3,1, a4,1, …, etc.. 7.6.1 [10] <7.3> Assume that we are going to compute C on both a single core shared memory machine and a 4-core shared-memory machine. Compute the speedup we would expect to obtain on the 4-core machine, ignoring any memory issues. 7.6.2 [10] <7.3> Repeat 7.6.1, assuming that updates to C incur a cache miss due to false sharing when consecutive elements are in a row (i.e., index i) are updated. 7.6.3 [10] <7.3> How would you fix the false sharing issue that can occur? Exercise 7.7 Consider the following portions of two different programs running at the same time on four processors in a symmetric multi-core processor (SMP). Assume that before this code is run, both x and y are 0. Core 1: x = 2; Core 2: y = 2; Core 3: w = x + y + 1; Core 4: z = x + y; 7.7.1 [10] <7.3> What are all the possible resulting values of w, x, y, and z? For each possible outcome, explain how we might arrive at those values. You will need to examine all possible interleavings of instructions. 7.7.2 [5] <7.3> How could you make the execution more deterministic so that only one set of values is possible? Exercise 7.8 In a CC-NUMA shared memory system, CPUs and physical memory are divided across compute nodes. Each CPU has local caches. To maintain the coherency of memory, we can add status bits into each cache block, or we can introduce dedi cated memory directories. Using directories, each node provides a dedicated hard ware table for managing the status of every block of memory that is “local” to that node. The size of each directory is a function of the size of the CC-NUMA shared space (an entry is provided for each block of memory local to a node). If we store coherency information in the cache, we add this information to every cache in every system (i.e., the amount of storage space is a function of the number of cache lines available in all caches). 7.15 Exercises 693 | clipped_hennesy_Page_691_Chunk6048 |
694 Chapter 7 Multicores, Multiprocessors, and Clusters In the following proplems, assume that all nodes have the same number of CPUs and the same amount memory (i.e., CPUs and memory are evenly divided between the nodes of the CC-NUMA machine). 7.8.1 [15] <7.3> If we have P CPU in the system, with T nodes in the CC- NUMA system, with each CPU having C memory blocks stored in it, and we maintain a byte of coherency information in each cache line, provide an equation that expresses the amount of memory that will be present in the caches in a single node of the system to maintain coherency. Do not include the actual data storage space consumed in this equation, only account for space used to store coherency information. 7.8.2 [15] <7.3>If each directory entry maintains a byte of information for each CPU, if our CC-NUMA system has S memory blocks, and the system has T nodes, provide an equation that expresses the amount of memory that will be present in each directory. Exercise 7.9 Considering the CC-NUMA system described in the Exercise 7.8, assume that the system has 4 nodes, each with a single-core CPU (each CPU has its own L1 data cache and L2 data cache). The L1 data cache is store-through, though the L2 data cache is write-back. Assume that system has a workload where one CPU writes to an address, and the other CPUs all read that data that is written. Also assume that the address written to is initially only in memory and not in any local cache. Also, after the write, assume that the updated block is only present in the L1 cache of the core performing the write. 7.9.1 [10] <7.3> �For a system that maintains coherency using cache-based block status, describe the inter-node traffic that will be generated as each of the 4 cores writes to a unique address, after which each address written to is read from by each of the remaining 3 cores. 7.9.2 [10] <7.3> �For a directory-based coherency mechanism, describe the inter- node traffic generated when executing the same code pattern. � 7.9.3 [20] <7.3> Repeat 7.9.1 and 7.9.2 assuming that each CPU is now a multi- core CPU, with 4 cores per CPU, each maintaining an L1 data cache, but provided with a shared L2 data cache across the 4 cores. Each core will perform the write, followed by reads by each of the 15 other cores. 7.9.4 [10] <7.3> Consider the system described in 7.9.3, now assuming that each core writes to byte stored in the same cache block. How does this impact bus traffic? Explain. | clipped_hennesy_Page_692_Chunk6049 |
Exercise 7.10 On a CC-NUMA system, the cost of accessing non-local memory can limit our ability to utilize multiprocessing effectively. The following table shows the costs associated with access data in local memory versus non-local memory and the locality of our application expresses as the proportion of access that are local. Local load/store (cycle) Non-local load/store (cycles) % local accesses 25 200 20 Answer the following questions. Assume that memory accesses are evenly distrib uted through the application. Also, assume that only a single memory operation can be active during any cycle. State all assumptions about the ordering of local versus non-local memory operations. 7.10.1 [10] <7.3> If on average we need to access memory once every 75 cycles, what is impact on our application? 7.10.2 [10] <7.3> If on average we need to access memory once every 50 cycles, what is impact on our application? 7.10.3 [10] <7.3> If on average we need to access memory once every 100 cycles, what is impact on our application? Exercise 7.11 The dining philosopher’s problem is a classic problem of synchronization and con currency. The general problem is stated as philosophers sitting at a round table doing one of two things: eating or thinking. When they are eating, they are not thinking, and when they are thinking, they are not eating. There is a bowl of pasta in the center. A fork is placed in between each philosopher. The result is that each philosopher has one fork to her left and one fork to her right. Given the nature of eating pasta, the philosopher needs two forks to eat, and can only use the forks on her immediate left and right. The philosophers do not speak to one another. 7.11.1 [10] <7.4> Describe the scenario where none of philosophers ever eats (i.e., starvation). What is the sequence of events that happen that lead up to this problem? 7.11.2 [10] <7.4> Describe how we can solve this problem by introducing the concept of a priority? But can we guarantee that we will treat all the philosophers fairly? Explain. Now assume we hire a waiter who is in charge of assigning forks to philosophers. Nobody can pick up a fork until the waiter says they can. The waiter has global 7.15 Exercises 695 | clipped_hennesy_Page_693_Chunk6050 |
696 Chapter 7 Multicores, Multiprocessors, and Clusters knowledge of all forks. Further, if we impose the policy that philosophers will always request to pick up their left fork before requesting to pick up their right fork, then we can guarantee to avoid deadlock. 7.11.3 [10] <7.4> �We can implement requests to the waiter as either a queue of requests or as a periodic retry of a request. With a queue, requests are handled in the order they are received. The problem with using the queue is that we may not always be able to service the philosopher whose request is at the head of the queue (due to the unavailability of resources). Describe a scenario with 5 philosophers where a queue is provided, but service is not granted even though there are forks available for another philosopher (whose request is deeper in the queue) to eat. 7.11.4 [10] <7.4> If we implement requests to the waiter by periodically repeat ing our request until the resources become available, will this solve the problem described in 7.11.3? Explain. Exercise 7.12 Consider the following three CPU organizations: CPU SS: A 2-core superscalar microprocessor that provides out-of-order issue capabilities on 2 function units (FUs). Only a single thread can run on each core at a time. CPU MT: A fine-grained multithreaded processor that allows instructions from 2 threads to be run concurrently (i.e., there are two functional units), though only instructions from a single thread can be issued on any cycle. CPU SMT: An SMT processor that allows instructions from 2 threads to be run concurrently (i.e., there are two functional units), and instructions from either or both threads can be issued to run on any cycle. Assume we have two threads X and Y to run on these CPUs that include the following operations: Thread X Thread Y A1 – takes 3 cycles to execute A2 – no dependencies A3 – conflicts for a functional unit with A1 A4 – depends on the result of A3 B1 – take 2 cycles to execute B2 – conflicts for a functional unit with B1 B3 – depends on the result of B2 B4 – no dependencies and takes 2 cycles to execute Assume all instructions take a single cycle to execute unless noted otherwise or they encounter a hazard. 7.12.1 [10] <7.5> Assume that you have 1 SS CPU. How many cycles will it take to execute these two threads? How many issue slots are wasted due to hazards? | clipped_hennesy_Page_694_Chunk6051 |
7.12.2 [10] <7.5> Now assume you have 2 SS CPUs. How many cycles will it take to execute these two threads? How many issue slots are wasted due to hazards? 7.12.3 [10] <7.5> Assume that you have 1 MT CPU. How many cycles will it take to execute these two threads? How many issue slots are wasted due to hazards? Exercise 7.13 Virtualization software is being aggressively deployed to reduce the costs of man aging today’s high performance servers. Companies like VMWare, Microsoft and IBM have all developed a range of virtualization products. The general concept, described in Chapter 5, is that a hypervisor layer can be introduced between the hardware and the operating system to allow multiple operating systems to share the same physical hardware. The hypervisor layer is then responsible for allocating CPU and memory resources, as well as handling services typically handled by the operating system (e.g., I/O). Virtualization provides an abstract view of the underlying hardware to the hosted operating system and application software. This will require us to rethink how multi-core and multiprocessor systems will be designed in the future to support the sharing of CPUs and memories by a number of operating systems concurrently. 7.13.1 [30] <7.5> Select two hypervisors on the market today, and compare and contrast how they virtualize and manage the underlying hardware (CPUs and memory). 7.13.2 [15] <7.5> Discuss what changes may be necessary in future multi-core CPU platforms in order to better match the resource demands placed on these systems. For instance, can multi-threading play an effective role in alleviating the competition for computing resources? Exercise 7.14 We would like to execute the loop below as efficiently as possible. We have two dif ferent machines, a MIMD machine and a SIMD machine. for (i=0; i < 2000; i++) for (j=0; j<3000; j++) X_array[i][j] = Y_array[j][i] + 200; 7.14.1 [10] <7.6> For a 4 CPU MIMD machine, show the sequence of MIPS instructions that you would execute on each CPU. What is the speedup for this MIMD machine? 7.15 Exercises 697 | clipped_hennesy_Page_695_Chunk6052 |
698 Chapter 7 Multicores, Multiprocessors, and Clusters 7.14.2 [20] <7.6> For an 8-wide SIMD machine (i.e., 8 parallel SIMD functional units), write an assembly program in using your own SIMD extensions to MIPS to execute the loop. Compare the number of instructions executed on the SIMD machine to the MIMD machine. Exercise 7.15 A systolic array is an example of an MISD machine. A systolic array is a pipeline network or “wavefront” of data processing elements. Each of these elements does not need a program counter since execution is triggered by the arrival of data. Clocked systolic arrays compute in “lock-step” with each processor undertaking alternate compute and communication phases. 7.15.1 [10] <7.6> Consider proposed implementations of a systolic array (you can find these in on the Internet or in technical publications). Then attempt to program the loop provided in Exercise 7.14 using this MISD model. Discuss any difficulties you encounter. 7.15.2 [10] <7.6> Discuss the similarities and differences between an MISD and SIMD machine. Answer this question in terms of data-level parallelism. Exercise 7.16 Assume we want to execute the DAXP loop show on page 651 in MIPS assembly on the NVIDIA 8800 GTX GPU described in this Chapter. In this problem, we will assume that all math operations are performed on single-precision floating-point numbers (we will rename the loop SAXP). Assume that instructions take the fol lowing number of cycles to execute. Loads Stores Add.S Mult.S 5 2 3 4 7.16.1 [20] <7.7> Describe how you will constructs warps for the SAXP loop to exploit the 8 cores provided in a single multiprocessor. Exercise 7.17 Download the CUDA Toolkit and SDK from http://www.nvidia.com/object/cuda_ get.html. Make sure to use the “emurelease” (Emulation Mode) version of the code (you will not need actual NVIDIA hardware for this assignment). Build the exam ple programs provided in the SDK, and confirm that they run on the emulator. | clipped_hennesy_Page_696_Chunk6053 |
7.17.1 [90] <7.7> Using the “template” SDK sample as a starting point, write a CUDA program to perform the following vector operations: 1) a − b (vector-vector subtraction) 2) a · b (vector dot product) The dot product of two vectors a = [a1, a2, … , an] and b = [b1, b2, … , bn] is defined as: a · b = i = 1 n aibi = a1b1 + a2b2 + … + anbn Submit code for each program that demonstrates each operation and verifies the correctness of the results. 7.17.2 [90] <7.7> If you have GPU hardware available, complete a performance analysis your program, examining the computation time for the GPU and a CPU version of your program for a range of vector sizes. Explain any results you see. Exercise 7.18 AMD has recently announced that they will be integrating a graphics processing unit with their X86 cores in a single package, though with different clocks for each of the cores. This is an example of a heterogeneous multiprocessor system which we expect to see produced commericially in the near future. One of the key design points will be to allow for fast data communication between the CPU and the GPU. Presently communications must be performed between discrete CPU and GPU chips. But this is changing in AMDs Fusion architecture. Presently the plan is to use multiple (at least 16) PCI express channels for facilitate intercommunication. Intel is also jumping into this arena with their Larrabee chip. Intel is considering to use their QuickPath interconnect technology. 7.18.1 [25] <7.7> Compare the bandwidth and latency associated with these two interconnect technologies. Exercise 7.19 Refer to Figure 7.7b that shows an n-cube interconnect topology of order 3 that interconnects 8 nodes. One attractive feature of an n-cube interconnection net work topology is its ability to sustain broken links and still provide connectivity. 7.19.1 [10] <7.8> Develop an equation that computes how many links in the n-cube (where n is the order of the cube) can fail and we can still guarantee an unbroken link will exist to connect any node in the n-cube. 7.15 Exercises 699 | clipped_hennesy_Page_697_Chunk6054 |
700 Chapter 7 Multicores, Multiprocessors, and Clusters 7.19.2 [10] <7.8> Compare the resiliency to failure of n-cube to a fully-connected interconnection network. Plot a comparison of reliability as a function of the added number of links for the two topologies. Exercise 7.20 Benchmarking is field of study that involves identifying representative workloads to run on specific computing platforms in order to be able to objectively compare performance of one system to another. In this exercise we will compare two classes of benchmarks: the Whetstone CPU benchmark and the PARSEC Benchmark suite. Select one program from PARSEC. All programs should be freely available on the Internet. Consider running multiple copies of Whetstone versus running the PARSEC Benchmark on any of systems described in Section 7.11. 7.20.1 [60] <7.9> What is inherently different between these two classes of work load when run on these multi-core systems? 7.20.2 [60] <7.9, 7.10> In terms of the Roofline Model, how dependent will the results you obtain when running these benchmarks be on the amount of sharing and synchronization present in the workload used? Exercise 7.21 When performing computations on sparse matrices, latency in the memory hierar chy becomes much more of a factor. Sparse matrices lack the spatial locality in the data stream typically found in matrix operations. As a result, new matrix represen tations have been proposed. One the earliest sparse matrix representations is the Yale Sparse Matrix Format. It stores an initial sparse m×n matrix, M in row form using three one-dimensional arrays. Let R be the number of nonzero entries in M. We construct an array A of length R that contains all nonzero entries of M (in left-to-right top-to-bottom order). We also construct a second array IA of length m + 1 (i.e., one entry per row, plus one). IA(i) contains the index in A of the first nonzero element of row i. Row i of the original matrix extends from A(IA(i)) to A(IA(i+1)–1). The third array, JA, contains the column index of each element of A, so it also is of length R. 7.21.1 [15] <7.9> Consider the sparse matrix X below and write C code that would store this code in Yale Sparse Matrix Format. Row 1 [1, 2, 0, 0, 0, 0] Row 2 [0, 0, 1, 1, 0, 0] Row 3 [0, 0, 0, 0, 9, 0] Row 4 [2, 0, 0, 0, 0, 2] Row 5 [0, 0, 3, 3, 0, 7] Row 6 [1, 3, 0, 0, 0, 1] | clipped_hennesy_Page_698_Chunk6055 |
7.21.2 [10] <7.9> In terms of storage space, assuming that each element in matrix X is single precision floating point, compute the amount of storage used to store the Matrix above in Yale Sparse Matrix Format. 7.21.3 [15] <7.9> Perform matrix multiplication of Matrix X by Matrix Y shown below. [2, 4, 1, 99, 7, 2] Put this computation in a loop, and time its execution. Make sure to increase the number of times this loop is executed to get good resolution in your timing mea surement. Compare the runtime of using a naïve representation of the matrix, and the Yale Sparse Matrix Format. 7.21.4 [15] <7.9> Can you find a more efficient sparse matrix representation (in terms of space and computational overhead)? Exercise 7.22 In future systems, we expect to see heterogeneous computing platforms con structed out of heterogeneous CPUs. We have begun to see some appear in the embedded processing market in systems that contain both floating point DSPs and a microcontroller CPUs in a multichip module package. Assume that you have three classes of CPU: CPU A—A moderate speed multi-core CPU (with a floating point unit) that can execute multiple instructions per cycle. CPU B—A fast single-core integer CPU (i.e., no floating point unit) that can exe cute a single instruction per cycle. CPU C—A slow vector CPU (with floating point capability) that can execute mul tiple copies of the same instruction per cycle. Assume that our processors run at the following frequencies: CPU A CPU B CPU C 1 GHz 3 GHz 250 MHz CPU A can execute 2 instructions per cycle, CPU B can execute 1 instruction per cycle, and CPU C can execute 8 instructions (though the same instruction) per cycle. Assume all operations can complete execution in a single cycle of latency without any hazards. 7.15 Exercises 701 | clipped_hennesy_Page_699_Chunk6056 |
702 Chapter 7 Multicores, Multiprocessors, and Clusters All three CPUs have the ability to perform integer arithmetic, though CPU B can not perform floating point arithmetic. CPU A and B have an instruction set similar to a MIPS processor. CPU C can only perform floating point add and subtract operations, as well as memory loads and stores. Assume all CPUs have access to shared memory and that synchronization has zero cost. The task at hand is to compare two matrices X and Y that each contain 1024 × 1024 floating point elements. The output should be a count of the number indices where the value in X was larger or equal to the value in Y. 7.22.1 [10] <7.11> Describe how you would partition the problem on the 3 dif ferent CPUs to obtain the best performance. 7.22.2 [10] <7.11> What kind of instruction would you add to the vector CPU C to obtain better performance? Exercise 7.23 Assume a quad-core computer system can process database queries at a steady state rate of requests per second. Also assume that each transaction takes, on average, a fixed amount of time to process. The following table shows pairs of transaction latency and processing rate. Average Transaction Latency Maximum transaction processing rate 1 ms 5000/sec 2 ms 5000/sec 1 ms 10,000/sec 2 ms 10,000/sec For each of the pairs in the table, answer the following questions: 7.23.1 [10] <7.11> On average, how many requests are being processed at any given instant? 7.23.2 [10] <7.11> If move to an 8-core system, ideally, what will happen to the system throughput (i.e., how many queries/second will the computer process)? 7.22.3 [10] <7.11> Discuss why we rarely obtain this kind of speedup by simply increasing the number of cores. | clipped_hennesy_Page_700_Chunk6057 |
§7.1, page 634: False. Job-level parallelism can help sequential applications and sequential applications can be made to run on parallel hardware, although it is more challenging. §7.2, page 638: False. Weak scaling can compensate for a serial portion of the program that would otherwise limit scalability. §7.3, page 640: False. Since the shared address is a physical address, multiple jobs each in their own virtual address spaces can run well on a shared memory multi processor. §7.4, page 645: 1. False. Sending and receiving a message is an implicit synchroni zation, as well as a way to share data. 2. True. §7.5, page 648: 1. True. 2. True. §7.6, page 653: True. §7.7, page 660: False. Graphics DRAM DIMMs are prized for their higher band width. §7.9, page 666: True. We likely need innovation at all levels of the hardware and software stack to win the industry’s bet on parallel computing. Answers to Check Yourself 7.15 Exercises 703 | clipped_hennesy_Page_701_Chunk6058 |
A Imagination is more important than knowledge. Albert Einstein On Science, 1930s Graphics and Computing GPUs John Nickolls Director of Architecture NVIDIA David Kirk Chief Scientist NVIDIA A P P E N D I X | clipped_hennesy_Page_702_Chunk6059 |
A.1 Introduction A-3 A.2 GPU System Architectures A-7 A.3 Programming GPUs A-12 A.4 Multithreaded Multiprocessor Architecture A-25 A.5 Parallel Memory System A-36 A.6 Floating-point Arithmetic A-41 A.7 Real Stuff: The NVIDIA GeForce 8800 A-46 A.8 Real Stuff: Mapping Applications to GPUs A-55 A.9 Fallacies and Pitfalls A-72 A.10 Concluding Remarks A-76 A.11 Historical Perspective and Further Reading A-77 A.1 Introduction This appendix focuses on the GPU—the ubiquitous graphics processing unit in every PC, laptop, desktop computer, and workstation. In its most basic form, the GPU generates 2D and 3D graphics, images, and video that enable window- based operating systems, graphical user interfaces, video games, visual imaging applications, and video. The modern GPU that we describe here is a highly parallel, highly multithreaded multiprocessor optimized for visual computing. To provide real-time visual interaction with computed objects via graphics, images, and video, the GPU has a unified graphics and computing architecture that serves as both a programmable graphics processor and a scalable parallel computing platform. PCs and game consoles combine a GPU with a CPU to form heterogeneous systems. A Brief History of GPU Evolution Fifteen years ago, there was no such thing as a GPU. Graphics on a PC were performed by a video graphics array (VGA) controller. A VGA controller was simply a memory controller and display generator connected to some DRAM. In the 1990s, semiconductor technology advanced sufficiently that more functions could be added to the VGA controller. By 1997, VGA controllers were beginning to incorporate some three-dimensional (3D) acceleration functions, including graphics processing unit (GPU) A processor optimized for 2D and 3D graphics, video, visual computing, and display. visual computing A mix of graphics processing and computing that lets you visually interact with computed objects via graphics, images, and video. heterogeneous system A system combining different processor types. A PC is a heterogeneous CPU–GPU system. | clipped_hennesy_Page_703_Chunk6060 |
hardware for triangle setup and rasterization (dicing triangles into individual pixels) and texture mapping and shading (applying “decals” or patterns to pixels and blending colors). In 2000, the single chip graphics processor incorporated almost every detail of the traditional high-end workstation graphics pipeline and therefore, deserved a new name beyond VGA controller. The term GPU was coined to denote that the graphics device had become a processor. Over time, GPUs became more programmable, as programmable processors replaced fixed function dedicated logic while maintaining the basic 3D graphics pipeline organization. In addition, computations became more precise over time, progressing from indexed arithmetic, to integer and fixed point, to single precision floating-point, and recently to double precision floating-point. GPUs have become massively parallel programmable processors with hundreds of cores and thousands of threads. Recently, processor instructions and memory hardware were added to support general purpose programming languages, and a programming environment was created to allow GPUs to be programmed using familiar languages, including C and C++. This innovation makes a GPU a fully general-purpose, programmable, manycore processor, albeit still with some special benefits and limitations. GPU Graphics Trends GPUs and their associated drivers implement the OpenGL and DirectX models of graphics processing. OpenGL is an open standard for 3D graphics programming available for most computers. DirectX is a series of Microsoft multimedia pro gramming interfaces, including Direct3D for 3D graphics. Since these application programming interfaces (APIs) have well-defined behavior, it is possible to build effective hardware acceleration of the graphics processing functions defined by the APIs. This is one of the reasons (in addition to increasing device density) that new GPUs are being developed every 12 to 18 months that double the performance of the previous generation on existing applications. Frequent doubling of GPU performance enables new applications that were not previously possible. The intersection of graphics processing and parallel computing invites a new paradigm for graphics, known as visual computing. It replaces large sections of the traditional sequential hardware graphics pipeline model with programmable elements for geometry, vertex, and pixel programs. Visual computing in a modern GPU combines graphics processing and parallel computing in novel ways that permit new graphics algorithms to be implemented, and open the door to entirely new parallel processing applications on pervasive high-performance GPUs. Heterogeneous System Although the GPU is arguably the most parallel and most powerful processor in a typical PC, it is certainly not the only processor. The CPU, now multicore and application programming interface (API) A set of function and data structure definitions providing an interface to a library of functions. A-4 Appendix A Graphics and Computing GPUs | clipped_hennesy_Page_704_Chunk6061 |
soon to be manycore, is a complementary, primarily serial processor companion to the massively parallel manycore GPU. Together, these two types of processors comprise a heterogeneous multiprocessor system. The best performance for many applications comes from using both the CPU and the GPU. This appendix will help you understand how and when to best split the work between these two increasingly parallel processors. GPU Evolves into Scalable Parallel Processor GPUs have evolved functionally from hardwired, limited capability VGA controllers to programmable parallel processors. This evolution has proceeded by changing the logical (API-based) graphics pipeline to incorporate programmable elements and also by making the underlying hardware pipeline stages less specialized and more programmable. Eventually, it made sense to merge disparate programmable pipeline elements into one unified array of many programmable processors. In the GeForce 8-series generation of GPUs, the geometry, vertex, and pixel processing all run on the same type of processor. This unification allows for dramatic scalability. More programmable processor cores increase the total system throughput. Unifying the processors also delivers very effective load balancing, since any processing function can use the whole processor array. At the other end of the spectrum, a processor array can now be built with very few processors, since all of the functions can be run on the same processors. Why CUDA and GPU Computing? This uniform and scalable array of processors invites a new model of programming for the GPU. The large amount of floating-point processing power in the GPU processor array is very attractive for solving nongraphics problems. Given the large degree of parallelism and the range of scalability of the processor array for graphics applications, the programming model for more general computing must express the massive parallelism directly, but allow for scalable execution. GPU computing is the term coined for using the GPU for computing via a parallel programming language and API, without using the traditional graphics API and graphics pipeline model. This is in contrast to the earlier General Purpose computation on GPU (GPGPU) approach, which involves programming the GPU using a graphics API and graphics pipeline to perform nongraphics tasks. Compute Unified Device Architecture (CUDA) is a scalable parallel program ming model and software platform for the GPU and other parallel processors that allows the programmer to bypass the graphics API and graphics interfaces of the GPU and simply program in C or C++. The CUDA programming model has an SPMD (single-program multiple data) software style, in which a programmer writes a program for one thread that is instanced and executed by many threads in parallel on the multiple processors of the GPU. In fact, CUDA also provides a facility for programming multiple CPU cores as well, so CUDA is an environment for writing parallel programs for the entire heterogeneous computer system. GPU computing Using a GPU for computing via a parallel programming language and API. GPGPU Using a GPU for general-purpose computation via a traditional graphics API and graphics pipeline. CUDA A scalable parallel programming model and language based on C/C++. It is a parallel programming platform for GPUs and multicore CPUs. A.1 Introduction A-5 | clipped_hennesy_Page_705_Chunk6062 |
GPU Unifies Graphics and Computing With the addition of CUDA and GPU computing to the capabilities of the GPU, it is now possible to use the GPU as both a graphics processor and a computing processor at the same time, and to combine these uses in visual computing applications. The underlying processor architecture of the GPU is exposed in two ways: first, as implementing the programmable graphics APIs, and second, as a massively parallel processor array programmable in C/C++ with CUDA. Although the underlying processors of the GPU are unified, it is not necessary that all of the SPMD thread programs are the same. The GPU can run graphics shader programs for the graphics aspect of the GPU, processing geometry, vertices, and pixels, and also run thread programs in CUDA. The GPU is truly a versatile multiprocessor architecture, supporting a variety of processing tasks. GPUs are excellent at graphics and visual computing as they were specifically designed for these applications. GPUs are also excellent at many general- purpose throughput applications that are “first cousins” of graphics, in that they perform a lot of parallel work, as well as having a lot of regular problem structure. In general, they are a good match to data-parallel problems (see Chapter 7), particularly large problems, but less so for less regular, smaller problems. GPU Visual Computing Applications Visual computing includes the traditional types of graphics applications plus many new applications. The original purview of a GPU was “anything with pixels,” but it now includes many problems without pixels but with regular computation and/or data structure. GPUs are effective at 2D and 3D graphics, since that is the purpose for which they are designed. Failure to deliver this application performance would be fatal. 2D and 3D graphics use the GPU in its “graphics mode,” accessing the pro- cessing power of the GPU through the graphics APIs, OpenGLTM, and DirectXTM. Games are built on the 3D graphics processing capability. Beyond 2D and 3D graphics, image processing and video are important applica- tions for GPUs. These can be implemented using the graphics APIs or as compu- tational programs, using CUDA to program the GPU in computing mode. Using CUDA, image processing is simply another data-parallel array program. To the extent that the data access is regular and there is good locality, the program will be efficient. In practice, image processing is a very good application for GPUs. Video processing, especially encode and decode (compression and decompression according to some standard algorithms) is quite efficient. The greatest opportunity for visual computing applications on GPUs is to “break the graphics pipeline.” Early GPUs implemented only specific graphics APIs, albeit at very high performance. This was wonderful if the API supported the operations that you wanted to do. If not, the GPU could not accelerate your task, because early GPU functionality was immutable. Now, with the advent of GPU computing and CUDA, these GPUs can be programmed to implement a different virtual pipeline by simply writing a CUDA program to describe the computation and data flow A-6 Appendix A Graphics and Computing GPUs | clipped_hennesy_Page_706_Chunk6063 |
that is desired. So, all applications are now possible, which will stimulate new visual computing approaches. A.2 GPU System Architectures In this section, we survey GPU system architectures in common use today. We discuss system configurations, GPU functions and services, standard programming interfaces, and a basic GPU internal architecture. Heterogeneous CPU–GPU System Architecture A heterogeneous computer system architecture using a GPU and a CPU can be described at a high level by two primary characteristics: first, how many functional subsystems and/or chips are used and what are their interconnection technologies and topology; and second, what memory subsystems are available to these functional subsystems. See Chapter 6 for background on the PC I/O systems and chip sets. The Historical PC (circa 1990) Figure A.2.1 is a high-level block diagram of a legacy PC, circa 1990. The north bridge (see Chapter 6) contains high-bandwidth interfaces, connecting the CPU, memory, and PCI bus. The south bridge contains legacy interfaces and devices: ISA bus (audio, LAN), interrupt controller; DMA controller; time/counter. In this system, the display was driven by a simple framebuffer subsystem known A.2 GPU System Architectures A-7 CPU North Bridge South Bridge Front Side Bus PCI Bus Framebuffer Memory VGA Controller Memory UART LAN VGA Display FIGURE A.2.1 Historical PC. VGA controller drives graphics display from framebuffer memory. | clipped_hennesy_Page_707_Chunk6064 |
A-8 Appendix A Graphics and Computing GPUs as a VGA (video graphics array) which was attached to the PCI bus. Graphics subsystems with built-in processing elements (GPUs) did not exist in the PC landscape of 1990. Figure A.2.2 illustrates two configurations in common use today. These are characterized by a separate GPU (discrete GPU) and CPU with respective memory subsystems. In Figure A.2.2a, with an Intel CPU, we see the GPU attached via a 16-lane PCI-Express 2.0 link to provide a peak 16 GB/s transfer rate, (peak of 8 GB/s in each direction). Similarly, in Figure A.2.2b, with an AMD CPU, the GPU PCI-Express (PCIe) A standard system I/O interconnect that uses point-to-point links. Links have a configurable number of lanes and bandwidth. Front Side Bus GPU Memory South Bridge North Bridge Intel CPU DDR2 Memory x16 PCI-Express Link x4 PCI-Express Link derivative 128-bit 667 MT/s display GPU 128-bit 667 MT/s internal bus GPU Memory DDR2 Memory x16 PCI-Express Link Chipset CPU core AMD CPU GPU North Bridge HyperTransport 1.03 display (a) (b) FIGURE A.2.2 Contemporary PCs with Intel and AMD CPUs. See Chapter 6 for an explanation of the components and interconnects in this figure. | clipped_hennesy_Page_708_Chunk6065 |
is attached to the chipset, also via PCI-Express with the same available bandwidth. In both cases, the GPUs and CPUs may access each other’s memory, albeit with less available bandwidth than their access to the more directly attached memories. In the case of the AMD system, the north bridge or memory controller is integrated into the same die as the CPU. A low-cost variation on these systems, a unified memory architecture (UMA) system, uses only CPU system memory, omitting GPU memory from the system. These systems have relatively low performance GPUs, since their achieved performance is limited by the available system memory bandwidth and increased latency of memory access, whereas dedicated GPU memory provides high bandwidth and low latency. A high performance system variation uses multiple attached GPUs, typically two to four working in parallel, with their displays daisy-chained. An example is the NVIDIA SLI (scalable link interconnect) multi-GPU system, designed for high performance gaming and workstations. The next system category integrates the GPU with the north bridge (Intel) or chipset (AMD) with and without dedicated graphics memory. Chapter 5 explains how caches maintain coherence in a shared address space. With CPUs and GPUs, there are multiple address spaces. GPUs can access their own physical local memory and the CPU system’s physical memory using virtual addresses that are translated by an MMU on the GPU. The operating system kernel manages the GPU’s page tables. A system physical page can be accessed using either coherent or noncoherent PCI-Express transactions, determined by an attribute in the GPU’s page table. The CPU can access GPU’s local memory through an address range (also called aperture) in the PCI-Express address space. Game Consoles Console systems such as the Sony PlayStation 3 and the Microsoft Xbox 360 resemble the PC system architectures previously described. Console systems are designed to be shipped with identical performance and functionality over a lifespan that can last five years or more. During this time, a system may be reimplemented many times to exploit more advanced silicon manufacturing processes and thereby to provide constant capability at ever lower costs. Console systems do not need to have their subsystems expanded and upgraded the way PC systems do, so the major internal system buses tend to be customized rather than standardized. GPU Interfaces and Drivers In a PC today, GPUs are attached to a CPU via PCI-Express. Earlier generations used AGP. Graphics applications call OpenGL [Segal and Akeley, 2006] or Direct3D [Microsoft DirectX Specification] API functions that use the GPU as a coprocessor. The APIs send commands, programs, and data to the GPU via a graphics device driver optimized for the particular GPU. unified memory architecture (UMA) A system architecture in which the CPU and GPU share a common system memory. AGP An extended version of the original PCI I/O bus, which provided up to eight times the bandwidth of the original PCI bus to a single card slot. Its primary purpose was to connect graphics subsystems into PC systems. A.2 GPU System Architectures A-9 | clipped_hennesy_Page_709_Chunk6066 |
A-10 Appendix A Graphics and Computing GPUs Graphics Logical Pipeline The graphics logical pipeline is described in Section A.3. Figure A.2.3 illustrates the major processing stages, and highlights the important programmable stages (vertex, geometry, and pixel shader stages). FIGURE A.2.3 Graphics logical pipeline. Programmable graphics shader stages are blue, and fixed-function blocks are white. Input Assembler Vertex Shader Geometry Shader Setup & Rasterizer Pixel Shader Raster Operations/ Output Merger Unified Processor Array Input Assembler Vertex Shader Setup & Rasterizer Raster Operations/ Output Merger Geometry Shader Pixel Shader FIGURE A.2.4 Logical pipeline mapped to physical processors. The programmable shader stages execute on the array of unified processors, and the logical graphics pipeline dataflow recirculates through the processors. Mapping Graphics Pipeline to Unified GPU Processors Figure A.2.4 shows how the logical pipeline comprising separate independent programmable stages is mapped onto a physical distributed array of processors. Basic Unified GPU Architecture Unified GPU architectures are based on a parallel array of many programmable processors. They unify vertex, geometry, and pixel shader processing and parallel computing on the same processors, unlike earlier GPUs which had separate processors dedicated to each processing type. The programmable processor array is tightly integrated with fixed function processors for texture filtering, rasterization, raster operations, anti-aliasing, compression, decompression, display, video decoding, and high-definition video processing. Although the fixed-function processors significantly outperform more general programmable processors in terms of absolute performance constrained by an area, cost, or power budget, we will focus on the programmable processors here. Compared with multicore CPUs, manycore GPUs have a different architectural design point, one focused on executing many parallel threads efficiently on many | clipped_hennesy_Page_710_Chunk6067 |
processor cores. By using many simpler cores and optimizing for data-parallel behavior among groups of threads, more of the per-chip transistor budget is devoted to computation, and less to on-chip caches and overhead. Processor Array A unified GPU processor array contains many processor cores, typically organized into multithreaded multiprocessors. Figure A.2.5 shows a GPU with an array of 112 streaming processor (SP) cores, organized as 14 multithreaded streaming multiprocessors (SM). Each SP core is highly multithreaded, managing 96 concurrent threads and their state in hardware. The processors connect with four 64-bit-wide DRAM partitions via an interconnection network. Each SM has eight SP cores, two special function units (SFUs), instruction and constant caches, a multithreaded instruction unit, and a shared memory. This is the basic Tesla architecture implemented by the NVIDIA GeForce 8800. It has a unified architecture in which the traditional graphics programs for vertex, geometry, and pixel shading run on the unified SMs and their SP cores, and computing programs run on the same processors. A.2 GPU System Architectures A-11 GPU Host CPU System Memory DRAM ROP L2 DRAM ROP L2 DRAM ROP L2 DRAM ROP L2 TPC Texture Unit Tex L1 SM SP SP SP SP SP SP SP SP SM SP SP SP SP SP SP SP SP TPC Texture Unit Tex L1 SM SP SP SP SP SP SP SP SP SM SP SP SP SP SP SP SP SP TPC Texture Unit Tex L1 SM SP SP SP SP SP SP SP SP SM SP SP SP SP SP SP SP SP TPC Texture Unit Tex L1 SM SP SP SP SP SP SP SP SP SM SP SP SP SP SP SP SP SP TPC Texture Unit Tex L1 SM SP SP SP SP SP SP SP SP SM SP SP SP SP SP SP SP SP TPC Texture Unit Tex L1 SM SP SP SP SP SP SP SP SP SM SP SP SP SP SP SP SP SP TPC Texture Unit Tex L1 SM SP SP SP SP SP SP SP SP SM SP SP SP SP SP SP SP SP Vertex Work Distribution Input Assembler Host Interface Bridge Pixel Work Distribution Viewport/Clip/ Setup/Raster/ ZCull Compute Work Distribution SP Shared Memory SP SP SP SP SP SP SM SP I-Cache MT Issue C-Cache SFU SFU Interconnection Network Display Interface Display High-Definition Video Processors Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory Shared Memory FIGURE A.2.5 Basic unified GPU architecture. Example GPU with 112 streaming processor (SP) cores organized in 14 streaming multiprocessors (SMs); the cores are highly multithreaded. It has the basic Tesla architecture of an NVIDIA GeForce 8800. The processors connect with four 64-bit-wide DRAM partitions via an interconnection network. Each SM has eight SP cores, two special function units (SFUs), instruction and constant caches, a multithreaded instruction unit, and a shared memory. | clipped_hennesy_Page_711_Chunk6068 |
A-12 Appendix A Graphics and Computing GPUs The processor array architecture is scalable to smaller and larger GPU configu rations by scaling the number of multiprocessors and the number of memory partitions. Figure A.2.5 shows seven clusters of two SMs sharing a texture unit and a texture L1 cache. The texture unit delivers filtered results to the SM given a set of coordinates into a texture map. Because filter regions of support often overlap for successive texture requests, a small streaming L1 texture cache is effective to reduce the number of requests to the memory system. The processor array connects with raster operation (ROP) processors, L2 texture caches, external DRAM memories, and system memory via a GPU-wide interconnection network. The number of processors and number of memories can scale to design balanced GPU systems for different performance and market segments. A.3 Programming GPUs Programming multiprocessor GPUs is qualitatively different than programming other multiprocessors like multicore CPUs. GPUs provide two to three orders of magnitude more thread and data parallelism than CPUs, scaling to hundreds of processor cores and tens of thousands of concurrent threads in 2008. GPUs continue to increase their parallelism, doubling it about every 12 to 18 months, enabled by Moore’s law [1965] of increasing integrated circuit density and by improving architectural efficiency. To span the wide price and performance range of different market segments, different GPU products implement widely varying numbers of processors and threads. Yet users expect games, graphics, imaging, and computing applications to work on any GPU, regardless of how many parallel threads it executes or how many parallel processor cores it has, and they expect more expensive GPUs (with more threads and cores) to run applications faster. As a result, GPU programming models and application programs are designed to scale transparently to a wide range of parallelism. The driving force behind the large number of parallel threads and cores in a GPU is real-time graphics performance—the need to render complex 3D scenes with high resolution at interactive frame rates, at least 60 frames per second. Correspondingly, the scalable programming models of graphics shading languages such as Cg (C for graphics) and HLSL (high-level shading language) are designed to exploit large degrees of parallelism via many independent parallel threads and to scale to any number of processor cores. The CUDA scalable parallel programming model similarly enables general parallel computing applications to leverage large numbers of parallel threads and scale to any number of parallel processor cores, transparently to the application. In these scalable programming models, the programmer writes code for a single thread, and the GPU runs myriad thread instances in parallel. Programs thus scale transparently over a wide range of hardware parallelism. This simple paradigm arose from graphics APIs and shading languages that describe how to shade one | clipped_hennesy_Page_712_Chunk6069 |
vertex or one pixel. It has remained an effective paradigm as GPUs have rapidly increased their parallelism and performance since the late 1990s. This section briefly describes programming GPUs for real-time graphics applications using graphics APIs and programming languages. It then describes programming GPUs for visual computing and general parallel computing applications using the C language and the CUDA programming model. Programming Real-Time Graphics APIs have played an important role in the rapid, successful development of GPUs and processors. There are two primary standard graphics APIs: OpenGL and Direct3D, one of the Microsoft DirectX multimedia programming interfaces. OpenGL, an open standard, was originally proposed and defined by Silicon Graphics Incorporated. The ongoing development and extension of the OpenGL standard [Segal and Akeley, 2006], [Kessenich, 2006] is managed by Khronos, an industry consortium. Direct3D [Blythe, 2006], a de facto standard, is defined and evolved forward by Microsoft and partners. OpenGL and Direct3D are similarly structured, and continue to evolve rapidly with GPU hardware advances. They define a logical graphics processing pipeline that is mapped onto the GPU hardware and processors, along with programming models and languages for the programmable pipeline stages. Logical Graphics Pipeline Figure A.3.1 illustrates the Direct3D 10 logical graphics pipeline. OpenGL has a similar graphics pipeline structure. The API and logical pipeline provide a streaming dataflow infrastructure and plumbing for the programmable shader stages, shown in blue. The 3D application sends the GPU a sequence of vertices grouped into geometric primitives—points, lines, triangles, and polygons. The input assembler collects vertices and primitives. The vertex shader program executes per-vertex processing, OpenGL An open- standard graphics API. Direct3D A graphics API defined by Microsoft and partners. A.3 Programming GPUs A-13 FIGURE A.3.1 Direct3D 10 graphics pipeline. Each logical pipeline stage maps to GPU hardware or to a GPU processor. Programmable shader stages are blue, fixed-function blocks are white, and memory objects are grey. Each stage processes a vertex, geometric primitive, or pixel in a streaming dataflow fashion. Input Assembler Vertex Shader Geometry Shader Setup & Rasterizer Pixel Shader Raster Operations/ Output Merger Vertex Buffer Texture Texture Texture Render Target Sampler Sampler Sampler Constant Depth Z-Buffer Constant Constant Stream Buffer Stream Out Index Buffer Memory Stencil GPU | clipped_hennesy_Page_713_Chunk6070 |
A-14 Appendix A Graphics and Computing GPUs including transforming the vertex 3D position into a screen position and lighting the vertex to determine its color. The geometry shader program executes per-primitive processing and can add or drop primitives. The setup and rasterizer unit generates pixel fragments (fragments are potential contributions to pixels) that are covered by a geometric primitive. The pixel shader program performs per-fragment processing, including interpolating per-fragment parameters, texturing, and coloring. Pixel shaders make extensive use of sampled and filtered lookups into large 1D, 2D, or 3D arrays called textures, using interpolated floating-point coordinates. Shaders use texture accesses for maps, functions, decals, images, and data. The raster operations processing (or output merger) stage performs Z-buffer depth testing and stencil testing, which may discard a hidden pixel fragment or replace the pixel’s depth with the fragment’s depth, and performs a color blending operation that combines the fragment color with the pixel color and writes the pixel with the blended color. The graphics API and graphics pipeline provide input, output, memory objects, and infrastructure for the shader programs that process each vertex, primitive, and pixel fragment. Graphics Shader Programs Real-time graphics applications use many different shader programs to model how light interacts with different materials and to render complex lighting and shadows. Shading languages are based on a dataflow or streaming programming model that corresponds with the logical graphics pipeline. Vertex shader programs map the position of triangle vertices onto the screen, altering their position, color, or orientation. Typically a vertex shader thread inputs a floating-point (x, y, z, w) vertex position and computes a floating-point (x, y, z) screen position. Geometry shader programs operate on geometric primitives (such as lines and triangles) defined by multiple vertices, changing them or generating additional primitives. Pixel fragment shaders each “shade” one pixel, computing a floating-point red, green, blue, alpha (RGBA) color contribution to the rendered image at its pixel sample (x, y) image position. Shaders (and GPUs) use floating-point arithmetic for all pixel color calculations to eliminate visible artifacts while computing the extreme range of pixel contribution values encountered while rendering scenes with complex lighting, shadows, and high dynamic range. For all three types of graphics shaders, many program instances can be run in parallel, as independent parallel threads, because each works on independent data, produces independent results, and has no side effects. Independent vertices, primitives, and pixels further enable the same graphics program to run on differently sized GPUs that process different numbers of vertices, primitives, and pixels in parallel. Graphics programs thus scale transparently to GPUs with different amounts of parallelism and performance. Users program all three logical graphics threads with a common targeted high- level language. HLSL (high-level shading language) and Cg (C for graphics) are commonly used. They have C-like syntax and a rich set of library functions for matrix operations, trigonometry, interpolation, and texture access and filtering, but are far from general computing languages: they currently lack general memory texture A 1D, 2D, or 3D array that supports sampled and filtered lookups with interpolated coordinates. shader A program that operates on graphics data such as a vertex or a pixel fragment. shading language A graphics rendering language, usually having a dataflow or streaming programming model. | clipped_hennesy_Page_714_Chunk6071 |
access, pointers, file I/O, and recursion. HLSL and Cg assume that programs live within a logical graphics pipeline, and thus I/O is implicit. For example, a pixel fragment shader may expect the geometric normal and multiple texture coordinates to have been interpolated from vertex values by upstream fixed-function stages and can simply assign a value to the COLOR output parameter to pass it downstream to be blended with a pixel at an implied (x, y) position. The GPU hardware creates a new independent thread to execute a vertex, geometry, or pixel shader program for every vertex, every primitive, and every pixel fragment. In video games, the bulk of threads execute pixel shader programs, as there are typically 10 to 20 times or more pixel fragments than vertices, and complex lighting and shadows require even larger ratios of pixel to vertex shader threads. The graphics shader programming model drove the GPU architecture to efficiently execute thousands of independent fine-grained threads on many parallel processor cores. Pixel Shader Example Consider the following Cg pixel shader program that implements the “environment mapping” rendering technique. For each pixel thread, this shader is passed five parameters, including 2D floating-point texture image coordinates needed to sample the surface color, and a 3D floating-point vector giving the reflection of the view direction off the surface. The other three “uniform” parameters do not vary from one pixel instance (thread) to the next. The shader looks up color in two texture images: a 2D texture access for the surface color, and a 3D texture access into a cube map (six images corresponding to the faces of a cube) to obtain the external world color corresponding to the reflection direction. Then the final four-component (red, green, blue, alpha) floating-point color is computed using a weighted average called a “lerp” or linear interpolation function. A.3 Programming GPUs A-15 void reflection( float2 texCoord : TEXCOORD0, float3 reflection_dir : TEXCOORD1, out float4 color : COLOR, uniform float shiny, uniform sampler2D surfaceMap, uniform samplerCUBE envMap) { // Fetch the surface color from a texture float4 surfaceColor = tex2D(surfaceMap, texCoord); // Fetch reflected color by sampling a cube map float4 reflectedColor = texCUBE(environmentMap, reflection_dir); // Output is weighted average of the two colors color = lerp(surfaceColor, reflectedColor, shiny); } | clipped_hennesy_Page_715_Chunk6072 |
A-16 Appendix A Graphics and Computing GPUs Although this shader program is only three lines long, it activates a lot of GPU hardware. For each texture fetch, the GPU texture subsystem makes multiple memory accesses to sample image colors in the vicinity of the sampling coordinates, and then interpolates the final result with floating-point filtering arithmetic. The multithreaded GPU executes thousands of these lightweight Cg pixel shader threads in parallel, deeply interleaving them to hide texture fetch and memory latency. Cg focuses the programmer’s view to a single vertex or primitive or pixel, which the GPU implements as a single thread; the shader program transparently scales to exploit thread parallelism on the available processors. Being application-specific, Cg provides a rich set of useful data types, library functions, and language constructs to express diverse rendering techniques. Figure A.3.2 shows skin rendered by a fragment pixel shader. Real skin appears quite different from flesh-color paint because light bounces around a lot before re-emerging. In this complex shader, three separate skin layers, each with unique subsurface scattering behavior, are modeled to give the skin a visual depth and translucency. Scattering can be modeled by a blurring convolution in a flattened “texture” space, with red being blurred more than green, and blue blurred less. FIGURE A.3.2 GPU-rendered image. To give the skin visual depth and translucency, the pixel shader program models three separate skin layers, each with unique subsurface scattering behavior. It executes 1400 instructions to render the red, green, blue, and alpha color components of each skin pixel fragment. | clipped_hennesy_Page_716_Chunk6073 |
The compiled Cg shader executes 1400 instructions to compute the color of one skin pixel. As GPUs have evolved superior floating-point performance and very high streaming memory bandwidth for real-time graphics, they have attracted highly parallel applications beyond traditional graphics. At first, access to this power was available only by couching an application as a graphics-rendering algorithm, but this GPGPU approach was often awkward and limiting. More recently, the CUDA programming model has provided a far easier way to exploit the scalable high-performance floating-point and memory bandwidth of GPUs with the C programming language. Programming Parallel Computing Applications CUDA, Brook, and CAL are programming interfaces for GPUs that are focused on data parallel computation rather than on graphics. CAL (Compute Abstraction Layer) is a low-level assembler language interface for AMD GPUs. Brook is a streaming language adapted for GPUs by Buck, et. al. [2004]. CUDA, developed by NVIDIA [2007], is an extension to the C and C++ languages for scalable parallel programming of manycore GPUs and multicore CPUs. The CUDA programming model is described below, adapted from an article by Nickolls, Buck, Garland, and Skadron [2008]. With the new model the GPU excels in data parallel and throughput computing, executing high performance computing applications as well as graphics applications. Data Parallel Problem Decomposition To map large computing problems effectively to a highly parallel processing architecture, the programmer or compiler decomposes the problem into many small problems that can be solved in parallel. For example, the programmer par- titions a large result data array into blocks and further partitions each block into elements, such that the result blocks can be computed independently in parallel, and the elements within each block are computed in parallel. Figure A.3.3 shows a decomposition of a result data array into a 3 × 2 grid of blocks, where each block is further decomposed into a 5 × 3 array of elements. The two-level parallel decomposition maps naturally to the GPU architecture: parallel multiprocessors compute result blocks, and parallel threads compute result elements. The programmer writes a program that computes a sequence of result data grids, partitioning each result grid into coarse-grained result blocks that can be computed independently in parallel. The program computes each result block with an array of fine-grained parallel threads, partitioning the work among threads so that each computes one or more result elements. Scalable Parallel Programming with CUDA The CUDA scalable parallel programming model extends the C and C++ languages to exploit large degrees of parallelism for general applications on highly parallel multiprocessors, particularly GPUs. Early experience with CUDA shows A.3 Programming GPUs A-17 | clipped_hennesy_Page_717_Chunk6074 |
A-18 Appendix A Graphics and Computing GPUs that many sophisticated programs can be readily expressed with a few easily understood abstractions. Since NVIDIA released CUDA in 2007, developers have rapidly developed scalable parallel programs for a wide range of applications, including seismic data processing, computational chemistry, linear algebra, sparse matrix solvers, sorting, searching, physics models, and visual computing. These applications scale transparently to hundreds of processor cores and thousands of concurrent threads. NVIDIA GPUs with the Tesla unified graphics and computing architecture (described in sections A.4 and A.7) run CUDA C programs, and are widely available in laptops, PCs, workstations, and servers. The CUDA model is also applicable to other shared memory parallel processing architectures, including multicore CPUs [Stratton, 2008]. CUDA provides three key abstractions—a hierarchy of thread groups, shared memories, and barrier synchronization—that provide a clear parallel structure to con ventional C code for one thread of the hierarchy. Multiple levels of threads, memory, and synchronization provide fine-grained data parallelism and thread parallelism, nested within coarse-grained data parallelism and task parallelism. The abstractions guide the programmer to partition the problem into coarse subproblems that can be solved independently in parallel, and then into finer pieces that can be solved in parallel. The programming model scales transparently to large numbers of proces- sor cores: a compiled CUDA program executes on any number of processors, and only the runtime system needs to know the physical processor count. Step 1: Sequence Blo (0, Blo (0, Step 2: Result Data Grid 1 ck 0) Block (1, 0) Block (1, 1) Block (2, 0) Block (2, 1) Block (1, 1) Elem (0, 0) Elem (1, 0) Elem (2, 0) Elem (3, 0) Elem (4, 0) Elem (0, 1) Elem (1, 1) Elem (2, 1) Elem (3, 1) Elem (4, 1) Elem (0, 2) Elem (1, 2) Elem (2, 2) Elem (3, 2) Elem (4, 2) ck 1) Result Data Grid 2 FIGURE A.3.3 Decomposing result data into a grid of blocks of elements to be computed in parallel. | clipped_hennesy_Page_718_Chunk6075 |
A.3 Programming GPUs A-19 The CUDA Paradigm CUDA is a minimal extension of the C and C++ programming languages. The programmer writes a serial program that calls parallel kernels, which may be simple functions or full programs. A kernel executes in parallel across a set of parallel threads. The programmer organizes these threads into a hierarchy of thread blocks and grids of thread blocks. A thread block is a set of concurrent threads that can cooperate among themselves through barrier synchronization and through shared access to a memory space private to the block. A grid is a set of thread blocks that may each be executed independently and thus may execute in parallel. When invoking a kernel, the programmer specifies the number of threads per block and the number of blocks comprising the grid. Each thread is given a unique thread ID number threadIdx within its thread block, numbered 0, 1, 2, ..., blockDim–1, and each thread block is given a unique block ID number blockIdx within its grid. CUDA supports thread blocks containing up to 512 threads. For convenience, thread blocks and grids may have 1, 2, or 3 dimensions, accessed via .x, .y, and .z index fields. As a very simple example of parallel programming, suppose that we are given two vectors x and y of n floating-point numbers each and that we wish to compute the result of y = ax + y for some scalar value a. This is the so-called SAXPY kernel defined by the BLAS linear algebra library. Figure A.3.4 shows C code for perform- ing this computation on both a serial processor and in parallel using CUDA. The __global__ declaration specifier indicates that the procedure is a kernel entry point. CUDA programs launch parallel kernels with the extended function call syntax: kernel<<<dimGrid, dimBlock>>>(... parameter list ...); where dimGrid and dimBlock are three-element vectors of type dim3 that specify the dimensions of the grid in blocks and the dimensions of the blocks in threads, respectively. Unspecified dimensions default to one. In Figure A.3.4, we launch a grid of n threads that assigns one thread to each element of the vectors and puts 256 threads in each block. Each individual thread computes an element index from its thread and block IDs and then performs the desired calculation on the corresponding vector elements. Comparing the serial and parallel versions of this code, we see that they are strikingly similar. This represents a fairly common pattern. The serial code consists of a loop where each iteration is independent of all the others. Such loops can be mechanically transformed into parallel kernels: each loop iteration becomes an independent thread. By assigning a single thread to each output element, we avoid the need for any synchronization among threads when writing results to memory. The text of a CUDA kernel is simply a C function for one sequential thread. Thus, it is generally straightforward to write and is typically simpler than writing parallel code for vector operations. Parallelism is determined clearly and explicitly by specifying the dimensions of a grid and its thread blocks when launching a kernel. kernel A program or function for one thread, designed to be executed by many threads. thread block A set of concurrent threads that execute the same thread program and may cooperate to compute a result. grid A set of thread blocks that execute the same kernel program. | clipped_hennesy_Page_719_Chunk6076 |
A-20 Appendix A Graphics and Computing GPUs Parallel execution and thread management is automatic. All thread creation, scheduling, and termination is handled for the programmer by the underlying sys- tem. Indeed, a Tesla architecture GPU performs all thread management directly in hardware. The threads of a block execute concurrently and may synchronize at a synchronization barrier by calling the __syncthreads() intrinsic. This guar- antees that no thread in the block can proceed until all threads in the block have reached the barrier. After passing the barrier, these threads are also guaranteed to see all writes to memory performed by threads in the block before the barrier. Thus, threads in a block may communicate with each other by writing and reading per-block shared memory at a synchronization barrier. Since threads in a block may share memory and synchronize via barriers, they will reside together on the same physical processor or multiprocessor. The number of thread blocks can, however, greatly exceed the number of processors. The CUDA thread programming model virtualizes the processors and gives the programmer the flexibility to parallelize at whatever granularity is most convenient. Virtualization synchronization barrier Threads wait at a synchro nization barrier until all threads in the thread block arrive at the barrier. Computing y = ax + y with a serial loop: void saxpy_serial(int n, float alpha, float *x, float *y) { for(int i = 0; i<n; ++i) y[i] = alpha*x[i] + y[i]; } // Invoke serial SAXPY kernel saxpy_serial(n, 2.0, x, y); Computing y = ax + y in parallel using CUDA: __global__ void saxpy_parallel(int n, float alpha, float *x, float *y) { int i = blockIdx.x*blockDim.x + threadIdx.x; if( i<n ) y[i] = alpha*x[i] + y[i]; } // Invoke parallel SAXPY kernel (256 threads per block) int nblocks = (n + 255) / 256; saxpy_parallel<<<nblocks, 256>>>(n, 2.0, x, y); FIGURE A.3.4 Sequential code (top) in C versus parallel code (bottom) in CUDA for SAXPY (see Chapter 7). CUDA parallel threads replace the C serial loop—each thread computes the same result as one loop iteration. The parallel code computes n results with n threads organized in blocks of 256 threads. | clipped_hennesy_Page_720_Chunk6077 |
into threads and thread blocks allows intuitive problem decompositions, as the number of blocks can be dictated by the size of the data being processed rather than by the number of processors in the system. It also allows the same CUDA program to scale to widely varying numbers of processor cores. To manage this processing element virtualization and provide scalability, CUDA requires that thread blocks be able to execute independently. It must be possible to execute blocks in any order, in parallel or in series. Different blocks have no means of direct communication, although they may coordinate their activities using atomic memory operations on the global memory visible to all threads—by atomically incrementing queue pointers, for example. This independence requirement allows thread blocks to be scheduled in any order across any number of cores, making the CUDA model scalable across an arbitrary number of cores as well as across a variety of parallel architectures. It also helps to avoid the possibility of deadlock. An application may execute multiple grids either independently or dependently. Independent grids may execute concurrently, given sufficient hardware resources. Dependent grids execute sequentially, with an implicit interkernel barrier between them, thus guaranteeing that all blocks of the first grid complete before any block of the second, dependent grid begins. Threads may access data from multiple memory spaces during their execution. Each thread has a private local memory. CUDA uses local memory for thread- private variables that do not fit in the thread’s registers, as well as for stack frames and register spilling. Each thread block has a shared memory, visible to all threads of the block, which has the same lifetime as the block. Finally, all threads have access to the same global memory. Programs declare variables in shared and global memory with the __shared__ and __device__ type qualifiers. On a Tesla architecture GPU, these memory spaces correspond to physically separate memories: per-block shared memory is a low-latency on-chip RAM, while global memory resides in the fast DRAM on the graphics board. Shared memory is expected to be a low-latency memory near each processor, much like an L1 cache. It can therefore provide high-performance communication and data sharing among the threads of a thread block. Since it has the same lifetime as its corresponding thread block, kernel code will typically initialize data in shared variables, compute using shared variables, and copy shared memory results to global memory. Thread blocks of sequentially dependent grids communicate via global memory, using it to read input and write results. Figure A.3.5 diagrams the nested levels of threads, thread blocks, and grids of thread blocks. It further shows the corresponding levels of memory sharing: local, shared, and global memories for per-thread, per-thread-block, and per-application data sharing. A program manages the global memory space visible to kernels through calls to the CUDA runtime, such as cudaMalloc() and cudaFree(). Kernels may execute on a physically separate device, as is the case when running kernels on the GPU. Consequently, the application must use cudaMemcpy() to copy data between the allocated space and the host system memory. atomic memory operation A memory read, modify, write operation sequence that completes without any intervening access. local memory Per-thread local memory private to the thread. shared memory Per- block memory shared by all threads of the block. global memory Per- application memory shared by all threads. A.3 Programming GPUs A-21 | clipped_hennesy_Page_721_Chunk6078 |
A-22 Appendix A Graphics and Computing GPUs The CUDA programming model is similar in style to the familiar single-program multiple data (SPMD) model—it expresses parallelism explicitly, and each kernel executes on a fixed number of threads. However, CUDA is more flexible than most realizations of SPMD, because each kernel call dynamically creates a new grid with the right number of thread blocks and threads for that application step. The pro- grammer can use a convenient degree of parallelism for each kernel, rather than having to design all phases of the computation to use the same number of threads. Figure A.3.6 shows an example of an SPMD-like CUDA code sequence. It first instantiates kernelF on a 2D grid of 3 × 2 blocks where each 2D thread block con- sists of 5 × 3 threads. It then instantiates kernelG on a 1D grid of four 1D thread blocks with six threads each. Because kernelG depends on the results of kernelF, they are separated by an interkernel synchronization barrier. The concurrent threads of a thread block express fine-grained data paral lelism and thread parallelism. The independent thread blocks of a grid express single-program multiple data (SPMD) A style of parallel programming model in which all threads execute the same program. SPMD threads typically coordinate with barrier synchronization. Thread per-Thread Local Memory Thread Block per-Block Shared Memory Grid 0 . . . Grid 1 . . . Global Memory Sequence Inter-Grid Synchronization FIGURE A.3.5 Nested granularity levels—thread, thread block, and grid—have corresponding memory sharing levels—local, shared, and global. Per-thread local memory is private to the thread. Per-block shared memory is shared by all threads of the block. Per-application global memory is shared by all threads. | clipped_hennesy_Page_722_Chunk6079 |
coarse-grained data parallelism. Independent grids express coarse-grained task parallelism. A kernel is simply C code for one thread of the hierarchy. Restrictions For efficiency, and to simplify its implementation, the CUDA programming model has some restrictions. Threads and thread blocks may only be created by invoking a parallel kernel, not from within a parallel kernel. Together with the required independence of thread blocks, this makes it possible to execute CUDA programs kernelG 1D Grid is 4 thread blocks, each block is 6 threads Sequence Interkernel Synchronization Barrier Block 2 Thread 5 Thread 0 Thread 1 Thread 2 Thread 3 Thread 4 kernelF<<<(3, 2), (5, 3)>>>(params); kernelF 2D Grid is 3 2 thread blocks; each block is 5 3 threads Block 1, 1 Thread 0, 0 Thread 1, 0 Thread 2, 0 Thread 3, 0 Thread 4, 0 Thread 0, 1 Thread 1, 1 Thread 2, 1 Thread 3, 1 Thread 4, 1 Thread 0, 2 Thread 1, 2 Thread 2, 2 Thread 3, 2 Thread 4, 2 Block 0, 1 Block 2, 1 Block 1, 1 Block 0, 0 Block 2, 0 Block 1, 0 kernelG<<<4, 6>>>(params); Block 0 Block 2 Block 1 Block 3 FIGURE A.3.6 Sequence of kernel F instantiated on a 2D grid of 2D thread blocks, an interkernel synchronization barrier, followed by kernel G on a 1D grid of 1D thread blocks. A.3 Programming GPUs A-23 | clipped_hennesy_Page_723_Chunk6080 |
A-24 Appendix A Graphics and Computing GPUs with a simple scheduler that introduces minimal runtime overhead. In fact, the Tesla GPU architecture implements hardware management and scheduling of threads and thread blocks. Task parallelism can be expressed at the thread block level but is difficult to express within a thread block because thread synchronization barriers operate on all the threads of the block. To enable CUDA programs to run on any number of processors, dependencies among thread blocks within the same kernel grid are not allowed—blocks must execute independently. Since CUDA requires that thread blocks be independent and allows blocks to be executed in any order, combining results generated by multiple blocks must in general be done by launching a second kernel on a new grid of thread blocks (although thread blocks may coordinate their activities using atomic memory operations on the global memory visible to all threads—by atomically incrementing queue pointers, for example). Recursive function calls are not currently allowed in CUDA kernels. Recursion is unattractive in a massively parallel kernel, because providing stack space for the tens of thousands of threads that may be active would require substantial amounts of memory. Serial algorithms that are normally expressed using recursion, such as quicksort, are typically best implemented using nested data parallelism rather than explicit recursion. To support a heterogeneous system architecture combining a CPU and a GPU, each with its own memory system, CUDA programs must copy data and results between host memory and device memory. The overhead of CPU–GPU interaction and data transfers is minimized by using DMA block transfer engines and fast interconnects. Compute-intensive problems large enough to need a GPU performance boost amortize the overhead better than small problems. Implications for Architecture The parallel programming models for graphics and computing have driven GPU architecture to be different than CPU architecture. The key aspects of GPU programs driving GPU processor architecture are: ■ ■Extensive use of fine-grained data parallelism: Shader programs describe how to process a single pixel or vertex, and CUDA programs describe how to compute an individual result. ■ ■Highly threaded programming model: A shader thread program processes a single pixel or vertex, and a CUDA thread program may generate a single result. A GPU must create and execute millions of such thread programs per frame, at 60 frames per second. ■ ■Scalability: A program must automatically increase its performance when provided with additional processors, without recompiling. ■ ■Intensive floating-point (or integer) computation. ■ ■Support of high throughput computations. | clipped_hennesy_Page_724_Chunk6081 |
A.4 Multithreaded Multiprocessor Architecture To address different market segments, GPUs implement scalable numbers of multiprocessors—in fact, GPUs are multiprocessors composed of multiprocessors. Furthermore, each multiprocessor is highly multithreaded to execute many fine- grained vertex and pixel shader threads efficiently. A quality basic GPU has two to four multiprocessors, while a gaming enthusiast’s GPU or computing platform has dozens of them. This section looks at the architecture of one such multithreaded multiprocessor, a simplified version of the NVIDIA Tesla streaming multiprocessor (SM) described in Section A.7. Why use a multiprocessor, rather than several independent processors? The parallelism within each multiprocessor provides localized high performance and supports extensive multithreading for the fine-grained parallel programming models described in Section A.3. The individual threads of a thread block execute together within a multiprocessor to share data. The multithreaded multiprocessor design we describe here has eight scalar processor cores in a tightly coupled archi- tecture, and executes up to 512 threads (the SM described in Section A.7 executes up to 768 threads). For area and power efficiency, the multiprocessor shares large complex units among the eight processor cores, including the instruction cache, the multithreaded instruction unit, and the shared memory RAM. Massive Multithreading GPU processors are highly multithreaded to achieve several goals: ■ ■Cover the latency of memory loads and texture fetches from DRAM ■ ■Support fine-grained parallel graphics shader programming models ■ ■Support fine-grained parallel computing programming models ■ ■Virtualize the physical processors as threads and thread blocks to provide transparent scalability ■ ■Simplify the parallel programming model to writing a serial program for one thread Memory and texture fetch latency can require hundreds of processor clocks, because GPUs typically have small streaming caches rather than large working-set caches like CPUs. A fetch request generally requires a full DRAM access latency plus interconnect and buffering latency. Multithreading helps cover the latency with useful computing—while one thread is waiting for a load or texture fetch to complete, the processor can execute another thread. The fine-grained parallel programming models provide literally thousands of independent threads that can keep many processors busy despite the long memory latency seen by individual threads. A.4 Multithreaded Multiprocessor Architecture A-25 | clipped_hennesy_Page_725_Chunk6082 |
A-26 Appendix A Graphics and Computing GPUs A graphics vertex or pixel shader program is a program for a single thread that processes a vertex or a pixel. Similarly, a CUDA program is a C program for a single thread that computes a result. Graphics and computing programs instantiate many parallel threads to render complex images and compute large result arrays. To dynamically balance shifting vertex and pixel shader thread workloads, each multiprocessor concurrently executes multiple different thread programs and different types of shader programs. To support the independent vertex, primitive, and pixel programming model of graphics shading languages and the single-thread programming model of CUDA C/C++, each GPU thread has its own private registers, private per-thread memory, program counter, and thread execution state, and can execute an independent code path. To efficiently execute hundreds of concurrent lightweight threads, the GPU multiprocessor is hardware multithreaded—it manages and executes hundreds of concurrent threads in hardware without scheduling overhead. Concurrent threads within thread blocks can synchronize at a barrier with a single instruction. Lightweight thread creation, zero-overhead thread scheduling, and fast barrier synchronization efficiently support very fine-grained parallelism. Multiprocessor Architecture A unified graphics and computing multiprocessor executes vertex, geometry, and pixel fragment shader programs, and parallel computing programs. As Figure A.4.1 shows, the example multiprocessor consists of eight scalar processor (SP) cores each with a large multithreaded register file (RF), two special function units (SFU), a multithreaded instruction unit, an instruction cache, a read-only constant cache, and a shared memory. The 16 KB shared memory holds graphics data buffers and shared computing data. CUDA variables declared as __shared__ reside in the shared memory. To map the logical graphics pipeline workload through the multiprocessor multiple times, as shown in Section A.2, vertex, geometry, and pixel threads have independent input and output buffers, and workloads arrive and depart independently of thread execution. Each SP core contains scalar integer and floating-point arithmetic units that execute most instructions. The SP is hardware multithreaded, supporting up to 64 threads. Each pipelined SP core executes one scalar instruction per thread per clock, which ranges from 1.2 GHz to 1.6 GHz in different GPU products. Each SP core has a large register file (RF) of 1024 general-purpose 32-bit registers, partitioned among its assigned threads. Programs declare their register demand, typically 16 to 64 scalar 32-bit registers per thread. The SP can concurrently run many threads that use a few registers or fewer threads that use more registers. The compiler optimizes register allocation to balance the cost of spilling registers versus the cost of fewer threads. Pixel shader programs often use 16 or fewer registers, enabling each SP to run up to 64 pixel shader threads to cover long-latency texture fetches. Compiled CUDA programs often need 32 registers per thread, limiting each SP to 32 threads, which limits such a kernel program to 256 threads per thread block on this example multiprocessor, rather than its maximum of 512 threads. | clipped_hennesy_Page_726_Chunk6083 |
The pipelined SFUs execute thread instructions that compute special functions and interpolate pixel attributes from primitive vertex attributes. These instructions can execute concurrently with instructions on the SPs. The SFU is described later. The multiprocessor executes texture fetch instructions on the texture unit via the texture interface, and uses the memory interface for external memory load, store, and atomic access instructions. These instructions can execute concurrently with instructions on the SPs. Shared memory access uses a low-latency interconnection network between the SP processors and the shared memory banks. Single-Instruction Multiple-Thread (SIMT) To manage and execute hundreds of threads running several different programs efficiently, the multiprocessor employs a single-instruction multiple-thread (SIMT) architecture. It creates, manages, schedules, and executes concurrent threads in groups of parallel threads called warps. The term warp originates from weaving, the first parallel thread technology. The photograph in Figure A.4.2 shows a warp of parallel threads emerging from a loom. This example multiprocessor uses a SIMT warp size of 32 threads, executing four threads in each of the eight Instruction Cache Multithreaded Instruction Unit Multithreaded Multiprocessor Constant Cache SFU SFU SP RF SP RF SP RF SP RF SP RF SP RF SP RF SP RF Shared Memory Texture Interface Memory Interface Multiprocessor Controller Output Interface Interconnection Network Input Interface Work Interface FIGURE A.4.1 Multithreaded multiprocessor with eight scalar processor (SP) cores. The eight SP cores each have a large multithreaded register file (RF) and share an instruction cache, multithreaded instruction issue unit, constant cache, two special function units (SFUs), interconnection network, and a multibank shared memory. single-instruction multiple-thread (SIMT) A processor architecture that applies one instruction to multiple independent threads in parallel. warp The set of parallel threads that execute the same instruction together in a SIMT architecture. A.4 Multithreaded Multiprocessor Architecture A-27 | clipped_hennesy_Page_727_Chunk6084 |
A-28 Appendix A Graphics and Computing GPUs SP cores over four clocks. The Tesla SM multiprocessor described in Section A.7 also uses a warp size of 32 parallel threads, executing four threads per SP core for efficiency on plentiful pixel threads and computing threads. Thread blocks consist of one or more warps. This example SIMT multiprocessor manages a pool of 16 warps, a total of 512 threads. Individual parallel threads composing a warp are the same type and start together at the same program address, but are otherwise free to branch and execute independently. At each instruction issue time, the SIMT multithreaded instruction unit selects a warp that is ready to execute its next instruction, then issues that instruction to the active threads of that warp. A SIMT instruction is broadcast synchronously to the active parallel threads of a warp; individual threads may be inactive due to independent branching or predication. In this multiprocessor, each SP scalar processor core executes an instruction for four individual threads of a warp using four clocks, reflecting the 4:1 ratio of warp threads to cores. SIMT processor architecture is akin to single-instruction multiple data (SIMD) design, which applies one instruction to multiple data lanes, but differs in that SIMT applies one instruction to multiple independent threads in parallel, not just warp 8 instruction 11 warp 1 instruction 42 warp 3 instruction 95 warp 8 instruction 12 time SIMT multithreaded instruction scheduler warp 1 instruction 43 warp 3 instruction 96 Photo: Judy Schoonmaker FIGURE A.4.2 SIMT multithreaded warp scheduling. The scheduler selects a ready warp and issues an instruction synchronously to the parallel threads composing the warp. Because warps are independent, the scheduler may select a different warp each time. | clipped_hennesy_Page_728_Chunk6085 |
to multiple data lanes. An instruction for a SIMD processor controls a vector of multiple data lanes together, whereas an instruction for a SIMT processor controls an individual thread, and the SIMT instruction unit issues an instruction to a warp of independent parallel threads for efficiency. The SIMT processor finds data-level parallelism among threads at runtime, analogous to the way a superscalar processor finds instruction-level parallelism among instructions at runtime. A SIMT processor realizes full efficiency and performance when all threads of a warp take the same execution path. If threads of a warp diverge via a data- dependent conditional branch, execution serializes for each branch path taken, and when all paths complete, the threads converge to the same execution path. For equal length paths, a divergent if-else code block is 50% efficient. The multiprocessor uses a branch synchronization stack to manage independent threads that diverge and converge. Different warps execute independently at full speed regardless of whether they are executing common or disjoint code paths. As a result, SIMT GPUs are dramatically more efficient and flexible on branching code than earlier GPUs, as their warps are much narrower than the SIMD width of prior GPUs. In contrast with SIMD vector architectures, SIMT enables programmers to write thread-level parallel code for individual independent threads, as well as data-parallel code for many coordinated threads. For program correctness, the programmer can essentially ignore the SIMT execution attributes of warps; however, substantial performance improvements can be realized by taking care that the code seldom requires threads in a warp to diverge. In practice, this is analogous to the role of cache lines in traditional codes: cache line size can be safely ignored when designing for correctness but must be considered in the code structure when designing for peak performance. SIMT Warp Execution and Divergence The SIMT approach of scheduling independent warps is more flexible than the scheduling of previous GPU architectures. A warp comprises parallel threads of the same type: vertex, geometry, pixel, or compute. The basic unit of pixel fragment shader processing is the 2-by-2 pixel quad implemented as four pixel shader threads. The multiprocessor controller packs the pixel quads into a warp. It similarly groups vertices and primitives into warps, and packs computing threads into a warp. A thread block comprises one or more warps. The SIMT design shares the instruction fetch and issue unit efficiently across parallel threads of a warp, but requires a full warp of active threads to get full performance efficiency. This unified multiprocessor schedules and executes multiple warp types concurrently, allowing it to concurrently execute vertex and pixel warps. Its warp scheduler operates at less than the processor clock rate, because there are four thread lanes per processor core. During each scheduling cycle, it selects a warp to execute a SIMT warp instruction, as shown in Figure A.4.2. An issued warp-instruction executes as four sets of eight threads over four processor cycles of throughput. The processor pipeline uses several clocks of latency to complete each instruction. If the number of active warps times the clocks per warp exceeds the pipeline latency, the A.4 Multithreaded Multiprocessor Architecture A-29 | clipped_hennesy_Page_729_Chunk6086 |
programmer can ignore the pipeline latency. For this multiprocessor, a round-robin schedule of eight warps has a period of 32 cycles between successive instructions for the same warp. If the program can keep 256 threads active per multiprocessor, instruction latencies up to 32 cycles can be hidden from an individual sequential thread. However, with few active warps, the processor pipeline depth becomes visible and may cause processors to stall. A challenging design problem is implementing zero-overhead warp scheduling for a dynamic mix of different warp programs and program types. The instruction scheduler must select a warp every four clocks to issue one instruction per clock per thread, equivalent to an IPC of 1.0 per processor core. Because warps are independent, the only dependencies are among sequential instructions from the same warp. The scheduler uses a register dependency scoreboard to qualify warps whose active threads are ready to execute an instruction. It prioritizes all such ready warps and selects the highest priority one for issue. Prioritization must consider warp type, instruction type, and the desire to be fair to all active warps. Managing Threads and Thread Blocks The multiprocessor controller and instruction unit manage threads and thread blocks. The controller accepts work requests and input data and arbitrates access to shared resources, including the texture unit, memory access path, and I/O paths. For graphics workloads, it creates and manages three types of graphics threads concurrently: vertex, geometry, and pixel. Each of the graphics work types have independent input and output paths. It accumulates and packs each of these input work types into SIMT warps of parallel threads executing the same thread program. It allocates a free warp, allocates registers for the warp threads, and starts warp execution in the multiprocessor. Every program declares its per-thread register demand; the controller starts a warp only when it can allocate the requested register count for the warp threads. When all the threads of the warp exit, the controller unpacks the results and frees the warp registers and resources. The controller creates cooperative thread arrays (CTAs) which implement CUDA thread blocks as one or more warps of parallel threads. It creates a CTA when it can create all CTA warps and allocate all CTA resources. In addition to threads and registers, a CTA requires allocating shared memory and barriers. The program declares the required capacities, and the controller waits until it can allocate those amounts before launching the CTA. Then it creates CTA warps at the warp scheduling rate, so that a CTA program starts executing immediately at full multiprocessor performance. The controller monitors when all threads of a CTA have exited, and frees the CTA shared resources and its warp resources. Thread Instructions The SP thread processors execute scalar instructions for individual threads, unlike earlier GPU vector instruction architectures, which executed four-component vector instructions for each vertex or pixel shader program. Vertex programs cooperative thread array (CTA) A set of concurrent threads that executes the same thread program and may cooperate to compute a result. A GPU CTA implements a CUDA thread block. A-30 Appendix A Graphics and Computing GPUs | clipped_hennesy_Page_730_Chunk6087 |
generally compute (x, y, z, w) position vectors, while pixel shader programs compute (red, green, blue, alpha) color vectors. However, shader programs are becoming longer and more scalar, and it is increasingly difficult to fully occupy even two components of a legacy GPU four-component vector architecture. In effect, the SIMT architecture parallelizes across 32 independent pixel threads, rather than parallelizing the four vector components within a pixel. CUDA C/C++ programs have predominantly scalar code per thread. Previous GPUs employed vector packing (e.g., combining subvectors of work to gain efficiency) but that complicated the scheduling hardware as well as the compiler. Scalar instructions are simpler and compiler friendly. Texture instructions remain vector based, taking a source coordinate vector and returning a filtered color vector. To support multiple GPUs with different binary microinstruction formats, high‑level graphics and computing language compilers generate intermediate assembler-level instructions (e.g., Direct3D vector instructions or PTX scalar instructions), which are then optimized and translated to binary GPU microin- structions. The NVIDIA PTX (parallel thread execution) instruction set definition [2007] provides a stable target ISA for compilers, and provides compatibility over several generations of GPUs with evolving binary microinstruction-set architec- tures. The optimizer readily expands Direct3D vector instructions to multiple sca- lar binary microinstructions. PTX scalar instructions translate nearly one to one with scalar binary microinstructions, although some PTX instructions expand to multiple binary microinstructions, and multiple PTX instructions may fold into one binary microinstruction. Because the intermediate assembler-level instruc- tions use virtual registers, the optimizer analyzes data dependencies and allocates real registers. The optimizer eliminates dead code, folds instructions together when feasible, and optimizes SIMT branch diverge and converge points. Instruction Set Architecture (ISA) The thread ISA described here is a simplified version of the Tesla architecture PTX ISA, a register-based scalar instruction set comprising floating-point, integer, logical, conversion, special functions, flow control, memory access, and texture operations. Figure A.4.3 lists the basic PTX GPU thread instructions; see the NVIDIA PTX specification [2007] for details. The instruction format is: opcode.type d, a, b, c; where d is the destination operand, a, b, c are source operands, and .type is one of: Type .type Specifier Untyped bits 8, 16, 32, and 64 bits .b8, .b16, .b32, .b64 Unsigned integer 8, 16, 32, and 64 bits .u8, .u16, .u32, .u64 Signed integer 8, 16, 32, and 64 bits .s8, .s16, .s32, .s64 Floating-point 16, 32, and 64 bits .f16, .f32, .f64 A.4 Multithreaded Multiprocessor Architecture A-31 | clipped_hennesy_Page_731_Chunk6088 |
A-32 Appendix A Graphics and Computing GPUs Basic PTX GPU Thread Instructions Group Instruction Example Meaning Comments Arithmetic arithmetic .type = .s32, .u32, .f32, .s64, .u64, .f64 add.type add.f32 d, a, b d = a + b; sub.type sub.f32 d, a, b d = a – b; mul.type mul.f32 d, a, b d = a * b; mad.type mad.f32 d, a, b, c d = a * b + c; multiply-add div.type div.f32 d, a, b d = a / b; multiple microinstructions rem.type rem.u32 d, a, b d = a % b; integer remainder abs.type abs.f32 d, a d = |a|; neg.type neg.f32 d, a d = 0 - a; min.type min.f32 d, a, b d = (a < b)? a:b; floating selects non-NaN max.type max.f32 d, a, b d = (a > b)? a:b; floating selects non-NaN setp.cmp.type setp.lt.f32 p, a, b p = (a < b); compare and set predicate numeric .cmp = eq, ne, lt, le, gt, ge; unordered cmp = equ, neu, ltu, leu, gtu, geu, num, nan mov.type mov.b32 d, a d = a; move selp.type selp.f32 d, a, b, p d = p? a: b; select with predicate cvt.dtype.atype cvt.f32.s32 d, a d = convert(a); convert atype to dtype Special Function special .type = .f32 (some .f64) rcp.type rcp.f32 d, a d = 1/a; reciprocal sqrt.type sqrt.f32 d, a d = sqrt(a); square root rsqrt.type rsqrt.f32 d, a d = 1/sqrt(a); reciprocal square root sin.type sin.f32 d, a d = sin(a); sine cos.type cos.f32 d, a d = cos(a); cosine lg2.type lg2.f32 d, a d = log(a)/log(2) binary logarithm ex2.type ex2.f32 d, a d = 2 ** a; binary exponential Logical logic.type = .pred,.b32, .b64 and.type and.b32 d, a, b d = a & b; or.type or.b32 d, a, b d = a | b; xor.type xor.b32 d, a, b d = a ^ b; not.type not.b32 d, a, b d = ~a; one’s complement cnot.type cnot.b32 d, a, b d = (a==0)? 1:0; C logical not shl.type shl.b32 d, a, b d = a << b; shift left shr.type shr.s32 d, a, b d = a >> b; shift right Memory Access memory .space = .global, .shared, .local, .const; .type = .b8, .u8, .s8, .b16, .b32, .b64 ld.space.type ld.global.b32 d, [a+off] d = *(a+off); load from memory space st.space.type st.shared.b32 [d+off], a *(d+off) = a; store to memory space tex.nd.dtyp.btype tex.2d.v4.f32.f32 d, a, b d = tex2d(a, b); texture lookup atom.spc.op.type atom.global.add.u32 d,[a], b atom.global.cas.b32 d,[a], b, c atomic { d = *a; *a = op(*a, b); } atomic read-modify-write operation atom .op = and, or, xor, add, min, max, exch, cas; .spc = .global; .type = .b32 Control Flow branch @p bra target if (p) goto target; conditional branch call call (ret), func, (params) ret = func(params); call function ret ret return; return from function call bar.sync bar.sync d wait for threads barrier synchronization exit exit exit; terminate thread execution FIGURE A.4.3 Basic PTX GPU thread instructions. | clipped_hennesy_Page_732_Chunk6089 |
Source operands are scalar 32-bit or 64-bit values in registers, an immediate value, or a constant; predicate operands are 1-bit Boolean values. Destinations are registers, except for store to memory. Instructions are predicated by prefixing them with @p or @!p, where p is a predicate register. Memory and texture instructions transfer scalars or vectors of two to four components, up to 128 bits total. PTX instructions specify the behavior of one thread. The PTX arithmetic instructions operate on 32-bit and 64-bit floating-point, signed integer, and unsigned integer types. Recent GPUs support 64-bit double precision floating-point; see Section A.6. On current GPUs, PTX 64-bit integer and logical instructions are translated to two or more binary microinstructions that perform 32-bit operations. The GPU special function instructions are limited to 32-bit floating-point. The thread control flow instructions are conditional branch, function call and return, thread exit, and bar.sync (barrier synchronization). The conditional branch instruction @p bra target uses a predicate register p (or !p) previously set by a compare and set predicate setp instruction to determine whether the thread takes the branch or not. Other instructions can also be predicated on a predicate register being true or false. Memory Access Instructions The tex instruction fetches and filters texture samples from 1D, 2D, and 3D texture arrays in memory via the texture subsystem. Texture fetches generally use interpolated floating-point coordinates to address a texture. Once a graphics pixel shader thread computes its pixel fragment color, the raster operations processor blends it with the pixel color at its assigned (x, y) pixel position and writes the final color to memory. To support computing and C/C++ language needs, the Tesla PTX ISA implements memory load/store instructions. They use integer byte addressing with register plus offset address arithmetic to facilitate conventional compiler code optimizations. Memory load/store instructions are common in processors, but are a significant new capability in the Tesla architecture GPUs, as prior GPUs provided only the texture and pixel accesses required by the graphics APIs. For computing, the load/store instructions access three read/write memory spaces that implement the corresponding CUDA memory spaces in Section A.3: ■ ■Local memory for per-thread private addressable temporary data (imple- mented in external DRAM) ■ ■Shared memory for low-latency access to data shared by cooperating threads in the same CTA/thread block (implemented in on-chip SRAM) ■ ■Global memory for large data sets shared by all threads of a computing application (implemented in external DRAM) The memory load/store instructions ld.global, st.global, ld.shared, st.shared, ld.local, and st.local access the global, shared, and local mem ory spaces. Computing programs use the fast barrier synchronization instruction bar.sync to synchronize threads within a CTA/thread block that communicate with each other via shared and global memory. A.4 Multithreaded Multiprocessor Architecture A-33 | clipped_hennesy_Page_733_Chunk6090 |
A-34 Appendix A Graphics and Computing GPUs To improve memory bandwidth and reduce overhead, the local and global load/ store instructions coalesce individual parallel thread requests from the same SIMT warp together into a single memory block request when the addresses fall in the same block and meet alignment criteria. Coalescing memory requests provides a significant performance boost over separate requests from individual threads. The multiprocessor’s large thread count, together with support for many outstanding load requests, helps cover load-to-use latency for local and global memory imple mented in external DRAM. The latest Tesla architecture GPUs also provide efficient atomic memory opera- tions on memory with the atom.op.u32 instructions, including integer operations add, min, max, and, or, xor, exchange, and cas (compare-and-swap) opera- tions, facilitating parallel reductions and parallel data structure management. Barrier Synchronization for Thread Communication Fast barrier synchronization permits CUDA programs to communicate frequently via shared memory and global memory by simply calling __syncthreads(); as part of each interthread communication step. The synchronization intrinsic func- tion generates a single bar.sync instruction. However, implementing fast barrier synchronization among up to 512 threads per CUDA thread block is a challenge. Grouping threads into SIMT warps of 32 threads reduces the synchronization difficulty by a factor of 32. Threads wait at a barrier in the SIMT thread scheduler so they do not consume any processor cycles while waiting. When a thread executes a bar.sync instruction, it increments the barrier’s thread arrival counter and the scheduler marks the thread as waiting at the barrier. Once all the CTA threads arrive, the barrier counter matches the expected terminal count, and the scheduler releases all the threads waiting at the barrier and resumes executing threads. Streaming Processor (SP) The multithreaded streaming processor (SP) core is the primary thread instruction processor in the multiprocessor. Its register file (RF) provides 1024 scalar 32-bit registers for up to 64 threads. It executes all the fundamental floating-point operations, including add.f32, mul.f32, mad.f32 (floating multiply-add), min.f32, max.f32, and setp.f32 (floating compare and set predicate). The floating-point add and multiply operations are compatible with the IEEE 754 standard for single precision FP numbers, including not-a-number (NaN) and infinity values. The SP core also implements all of the 32-bit and 64-bit integer arithmetic, comparison, conversion, and logical PTX instructions in Figure A.4.3. The floating-point add and mul operations employ IEEE round-to-nearest-even as the default rounding mode. The mad.f32 floating-point multiply-add operation performs a multiplication with truncation, followed by an addition with round- to-nearest-even. The SP flushes input denormal operands to sign-preserved‑zero. Results that underflow the target output exponent range are flushed to sign- preserved-zero after rounding. | clipped_hennesy_Page_734_Chunk6091 |
Special Function Unit (SFU) Certain thread instructions can execute on the SFUs, concurrently with other thread instructions executing on the SPs. The SFU implements the special function instructions of Figure A.4.3, which compute 32-bit floating-point approximations to reciprocal, reciprocal square root, and key transcendental functions. It also implements 32-bit floating-point planar attribute interpolation for pixel shaders, providing accurate interpolation of attributes such as color, depth, and texture coordinates. Each pipelined SFU generates one 32-bit floating-point special function result per cycle; the two SFUs per multiprocessor execute special function instructions at a quarter the simple instruction rate of the eight SPs. The SFUs also execute the mul.f32 multiply instruction concurrently with the eight SPs, increasing the peak computation rate up to 50% for threads with a suitable instruction mixture. For functional evaluation, the Tesla architecture SFU employs quadratic interpolation based on enhanced minimax approximations for approximating the reciprocal, reciprocal square-root, log2x, 2x, and sin/cos functions. The accuracy of the function estimates ranges from 22 to 24 mantissa bits. See Section A.6 for more details on SFU arithmetic. Comparing with Other Multiprocessors Compared with SIMD vector architectures such as x86 SSE, the SIMT multipro- cessor can execute individual threads independently, rather than always executing them together in synchronous groups. SIMT hardware finds data parallelism among independent threads, whereas SIMD hardware requires the software to express data parallelism explicitly in each vector instruction. A SIMT machine executes a warp of 32 threads synchronously when the threads take the same execution path, yet can execute each thread independently when they diverge. The advantage is signi ficant because SIMT programs and instructions simply describe the behavior of a single independent thread, rather than a SIMD data vector of four or more data lanes. Yet the SIMT multiprocessor has SIMD-like efficiency, spreading the area and cost of one instruction unit across the 32 threads of a warp and across the eight streaming processor cores. SIMT provides the performance of SIMD together with the productivity of multithreading, avoiding the need to explicitly code SIMD vec- tors for edge conditions and partial divergence. The SIMT multiprocessor imposes little overhead because it is hardware multithreaded with hardware barrier synchronization. That allows graphics shaders and CUDA threads to express very fine-grained parallelism. Graphics and CUDA programs use threads to express fine-grained data parallelism in a per- thread program, rather than forcing the programmer to express it as SIMD vector instructions. It is simpler and more productive to develop scalar single-thread code than vector code, and the SIMT multiprocessor executes the code with SIMD-like efficiency. A.4 Multithreaded Multiprocessor Architecture A-35 | clipped_hennesy_Page_735_Chunk6092 |
Coupling eight streaming processor cores together closely into a multiprocessor and then implementing a scalable number of such multiprocessors makes a two- level multiprocessor composed of multiprocessors. The CUDA programming model exploits the two-level hierarchy by providing individual threads for fine-grained parallel computations, and by providing grids of thread blocks for coarse-grained parallel operations. The same thread program can provide both fine-grained and coarse-grained operations. In contrast, CPUs with SIMD vector instructions must use two different programming models to provide fine-grained and coarse-grained operations: coarse-grained parallel threads on different cores, and SIMD vector instructions for fine-grained data parallelism. Multithreaded Multiprocessor Conclusion The example GPU multiprocessor based on the Tesla architecture is highly multithreaded, executing a total of up to 512 lightweight threads concurrently to support fine-grained pixel shaders and CUDA threads. It uses a variation on SIMD architecture and multithreading called SIMT (single-instruction multiple-thread) to efficiently broadcast one instruction to a warp of 32 parallel threads, while permitting each thread to branch and execute independently. Each thread executes its instruction stream on one of the eight streaming processor (SP) cores, which are multithreaded up to 64 threads. The PTX ISA is a register-based load/store scalar ISA that describes the execution of a single thread. Because PTX instructions are optimized and translated to binary microinstructions for a specific GPU, the hardware instructions can evolve rapidly without disrupting compilers and software tools that generate PTX instructions. A.5 Parallel Memory System Outside of the GPU itself, the memory subsystem is the most important determiner of the performance of a graphics system. Graphics workloads demand very high transfer rates to and from memory. Pixel write and blend (read-modify-write) operations, depth buffer reads and writes, and texture map reads, as well as command and object vertex and attribute data reads, comprise the majority of memory traffic. Modern GPUs are highly parallel, as shown in Figure A.2.5. For example, the GeForce 8800 can process 32 pixels per clock, at 600 MHz. Each pixel typically requires a color read and write and a depth read and write of a 4-byte pixel. Usually an average of two or three texels of four bytes each are read to generate the pixel’s color. So for a typical case, there is a demand of 28 bytes times 32 pixels = 896 bytes per clock. Clearly the bandwidth demand on the memory system is enormous. A-36 Appendix A Graphics and Computing GPUs | clipped_hennesy_Page_736_Chunk6093 |
To supply these requirements, GPU memory systems have the following characteristics: ■ ■They are wide, meaning there are a large number of pins to convey data between the GPU and its memory devices, and the memory array itself comprises many DRAM chips to provide the full total data bus width. ■ ■They are fast, meaning aggressive signaling techniques are used to maximize the data rate (bits/second) per pin. ■ ■GPUs seek to use every available cycle to transfer data to or from the memory array. To achieve this, GPUs specifically do not aim to minimize latency to the memory system. High throughput (utilization efficiency) and short latency are fundamentally in conflict. ■ ■Compression techniques are used, both lossy, of which the programmer must be aware, and lossless, which is invisible to the application and opportunistic. ■ ■Caches and work coalescing structures are used to reduce the amount of off‑chip traffic needed and to ensure that cycles spent moving data are used as fully as possible. DRAM Considerations GPUs must take into account the unique characteristics of DRAM. DRAM chips are internally arranged as multiple (typically four to eight) banks, where each bank includes a power-of-2 number of rows (typically around 16,384), and each row contains a power-of-2 number of bits (typically 8192). DRAMs impose a variety of timing requirements on their controlling processor. For example, dozens of cycles are required to activate one row, but once activated, the bits within that row are randomly accessible with a new column address every four clocks. Double-data rate (DDR) synchronous DRAMs transfer data on both rising and falling edges of the interface clock (see Chapter 5). So a 1 GHz clocked DDR DRAM transfers data at 2 gigabits per second per data pin. Graphics DDR DRAMs usually have 32 bidirectional data pins, so eight bytes can be read or written from the DRAM per clock. GPUs internally have a large number of generators of memory traffic. Different stages of the logical graphics pipeline each have their own request streams: command and vertex attribute fetch, shader texture fetch and load/ store, and pixel depth and color read-write. At each logical stage, there are often multiple independent units to deliver the parallel throughput. These are each independent memory requestors. When viewed at the memory system, there are an enormous number of uncorrelated requests in flight. This is a natural mismatch to the reference pattern preferred by the DRAMs. A solution is for the GPU’s memory controller to maintain separate heaps of traffic bound for A.5 Parallel Memory System A-37 | clipped_hennesy_Page_737_Chunk6094 |
different DRAM banks, and wait until enough traffic for a particular DRAM row is pending before activating that row and transferring all the traffic at once. Note that accumulating pending requests, while good for DRAM row locality and thus efficient use of the data bus, leads to longer average latency as seen by the requestors whose requests spend time waiting for others. The design must take care that no particular request waits too long, otherwise some processing units can starve waiting for data and ultimately cause neighboring processors to become idle. GPU memory subsystems are arranged as multiple memory partitions, each of which comprises a fully independent memory controller and one or two DRAM devices that are fully and exclusively owned by that partition. To achieve the best load balance and therefore approach the theoretical performance of n partitions, addresses are finely interleaved evenly across all memory partitions. The partition interleaving stride is typically a block of a few hundred bytes. The number of memory partitions is designed to balance the number of processors and other memory requesters. Caches GPU workloads typically have very large working sets—on the order of hundreds of megabytes to generate a single graphics frame. Unlike with CPUs, it is not practical to construct caches on chips large enough to hold anything close to the full working set of a graphics application. Whereas CPUs can assume very high cache hit rates (99.9% or more), GPUs experience hit rates closer to 90% and must therefore cope with many misses in flight. While a CPU can reasonably be designed to halt while waiting for a rare cache miss, a GPU needs to proceed with misses and hits intermingled. We call this a streaming cache architecture. GPU caches must deliver very high-bandwidth to their clients. Consider the case of a texture cache. A typical texture unit may evaluate two bilinear interpolations for each of four pixels per clock cycle, and a GPU may have many such texture units all operating independently. Each bilinear interpolation requires four separate texels, and each texel might be a 64-bit value. Four 16-bit components are typical. Thus, total bandwidth is 2 × 4 × 4 × 64 = 2048 bits per clock. Each separate 64-bit texel is independently addressed, so the cache needs to handle 32 unique addresses per clock. This naturally favors a multibank and/or multiport arrangement of SRAM arrays. MMU Modern GPUs are capable of translating virtual addresses to physical addresses. On the GeForce 8800, all processing units generate memory addresses in a 40-bit virtual address space. For computing, load and store thread instructions use 32-bit byte addresses, which are extended to a 40-bit virtual address by adding a 40-bit offset. A memory management unit performs virtual to physical address A-38 Appendix A Graphics and Computing GPUs | clipped_hennesy_Page_738_Chunk6095 |
translation; hardware reads the page tables from local memory to respond to misses on behalf of a hierarchy of translation lookaside buffers spread out among the processors and rendering engines. In addition to physical page bits, GPU page table entries specify the compression algorithm for each page. Page sizes range from 4 to 128 kilobytes. Memory Spaces As introduced in Section A.3, CUDA exposes different memory spaces to allow the programmer to store data values in the most performance-optimal way. For the following discussion, NVIDIA Tesla architecture GPUs are assumed. Global memory Global memory is stored in external DRAM; it is not local to any one physical streaming multiprocessor (SM) because it is meant for communication among different CTAs (thread blocks) in different grids. In fact, the many CTAs that reference a location in global memory may not be executing in the GPU at the same time; by design, in CUDA a programmer does not know the relative order in which CTAs are executed. Because the address space is evenly distributed among all memory partitions, there must be a read/write path from any streaming multiprocessor to any DRAM partition. Access to global memory by different threads (and different processors) is not guaranteed to have sequential consistency. Thread programs see a relaxed memory ordering model. Within a thread, the order of memory reads and writes to the same address is preserved, but the order of accesses to different addresses may not be preserved. Memory reads and writes requested by different threads are unordered. Within a CTA, the barrier synchronization instruction bar.sync can be used to obtain strict memory ordering among the threads of the CTA. The membar thread instruction provides a memory barrier/fence operation that commits prior memory accesses and makes them visible to other threads before proceeding. Threads can also use the atomic memory operations described in Section A.4 to coordinate work on memory they share. Shared memory Per-CTA shared memory is only visible to the threads that belong to that CTA, and shared memory only occupies storage from the time a CTA is created to the time it terminates. Shared memory can therefore reside on-chip. This approach has many benefits. First, shared memory traffic does not need to compete with limited off-chip bandwidth needed for global memory references. Second, it is practical to build very high-bandwidth memory structures on-chip to support the read/write demands of each streaming multiprocessor. In fact, the shared memory is closely coupled to the streaming multiprocessor. A.5 Parallel Memory System A-39 | clipped_hennesy_Page_739_Chunk6096 |
A-40 Appendix A Graphics and Computing GPUs Each streaming multiprocessor contains eight physical thread processors. During one shared memory clock cycle, each thread processor can process two threads’ worth of instructions, so 16 threads’ worth of shared memory requests must be handled in each clock. Because each thread can generate its own addresses, and the addresses are typically unique, the shared memory is built using 16 independently addressable SRAM banks. For common access patterns, 16 banks are sufficient to maintain throughput, but pathological cases are possible; for example, all 16 threads might happen to access a different address on one SRAM bank. It must be possible to route a request from any thread lane to any bank of SRAM, so a 16-by-16 interconnection network is required. Local Memory Per-thread local memory is private memory visible only to a single thread. Local memory is architecturally larger than the thread’s register file, and a program can compute addresses into local memory. To support large allocations of local memory (recall the total allocation is the per-thread allocation times the number of active threads), local memory is allocated in external DRAM. Although global and per-thread local memory reside off-chip, they are well- suited to being cached on-chip. Constant Memory Constant memory is read-only to a program running on the SM (it can be written via commands to the GPU). It is stored in external DRAM and cached in the SM. Because commonly most or all threads in a SIMT warp read from the same address in constant memory, a single address lookup per clock is sufficient. The constant cache is designed to broadcast scalar values to threads in each warp. Texture Memory Texture memory holds large read-only arrays of data. Textures for computing have the same attributes and capabilities as textures used with 3D graphics. Although textures are commonly two-dimensional images (2D arrays of pixel values), 1D (linear) and 3D (volume) textures are also available. A compute program references a texture using a tex instruction. Operands include an identifier to name the texture, and 1, 2, or 3 coordinates based on the texture dimensionality. The floating-point coordinates include a fractional portion that specifies a sample location often in between texel locations. Noninteger coordinates invoke a bilinear weighted interpolation of the four closest values (for a 2D texture) before the result is returned to the program. Texture fetches are cached in a streaming cache hierarchy designed to optimize throughput of texture fetches from thousands of concurrent threads. Some programs use texture fetches as a way to cache global memory. | clipped_hennesy_Page_740_Chunk6097 |
Surfaces Surface is a generic term for a one-dimensional, two-dimensional, or three- dimensional array of pixel values and an associated format. A variety of formats are defined; for example, a pixel may be defined as four 8-bit RGBA integer components, or four 16-bit floating-point components. A program kernel does not need to know the surface type. A tex instruction recasts its result values as floating-point, depending on the surface format. Load/Store Access Load/store instructions with integer byte addressing enable the writing and com- piling of programs in conventional languages like C and C++. CUDA programs use load/store instructions to access memory. To improve memory bandwidth and reduce overhead, the local and global load/ store instructions coalesce individual parallel thread requests from the same warp together into a single memory block request when the addresses fall in the same block and meet alignment criteria. Coalescing individual small memory requests into large block requests provides a significant performance boost over separate requests. The large thread count, together with support for many outstanding load requests, helps cover load-to-use latency for local and global memory implemented in external DRAM. ROP As shown in Figure A.2.5, NVIDIA Tesla architecture GPUs comprise a scalable streaming processor array (SPA), which performs all of the GPU’s programmable calculations, and a scalable memory system, which comprises external DRAM control and fixed function Raster Operation Processors (ROPs) that perform color and depth framebuffer operations directly on memory. Each ROP unit is paired with a specific memory partition. ROP partitions are fed from the SMs via an interconnection network. Each ROP is responsible for depth and stencil tests and updates, as well as color blending. The ROP and memory controllers cooperate to implement lossless color and depth compression (up to 8:1) to reduce external bandwidth demand. ROP units also perform atomic operations on memory. A.6 Floating-point Arithmetic GPUs today perform most arithmetic operations in the programmable processor cores using IEEE 754–compatible single precision 32-bit floating-point operations (see Chapter 3). The fixed-point arithmetic of early GPUs was succeeded by 16-bit, 24-bit, and 32-bit floating-point, then IEEE 754–compatible 32-bit floating-point. A.6 Floating-point A-41 | clipped_hennesy_Page_741_Chunk6098 |
Some fixed-function logic within a GPU, such as texture-filtering hardware, continues to use proprietary numeric formats. Recent GPUs also provide IEEE 754 compatible double precision 64-bit floating-point instructions. Supported Formats The IEEE 754 standard for floating-point arithmetic [2008] specifies basic and storage formats. GPUs use two of the basic formats for computation, 32-bit and 64-bit binary floating-point, commonly called single precision and double pre- cision. The standard also specifies a 16-bit binary storage floating-point format, half precision. GPUs and the Cg shading language employ the narrow 16-bit half data format for efficient data storage and movement, while maintaining high dynamic range. GPUs perform many texture filtering and pixel blending computa- tions at half precision within the texture filtering unit and the raster operations unit. The OpenEXR high dynamic-range image file format developed by Industrial Light and Magic [2003] uses the identical half format for color component values in computer imaging and motion picture applications. Basic Arithmetic Common single precision floating-point operations in GPU programmable cores include addition, multiplication, multiply-add, minimum, maximum, compare, set predicate, and conversions between integer and floating-point numbers. Floating-point instructions often provide source operand modifiers for negation and absolute value. The floating-point addition and multiplication operations of most GPUs today are compatible with the IEEE 754 standard for single precision FP numbers, includ- ing not-a-number (NaN) and infinity values. The FP addition and multiplica- tion operations use IEEE round-to-nearest-even as the default rounding mode. To increase floating-point instruction throughput, GPUs often use a compound multiply-add instruction (mad). The multiply-add operation performs FP multipli cation with truncation, followed by FP addition with round-to-nearest-even. It provides two floating-point operations in one issuing cycle, without requiring the instruction scheduler to dispatch two separate instructions, but the computation is not fused and truncates the product before the addition. This makes it different from the fused multiply-add instruction discussed in Chapter 3 and later in this section. GPUs typically flush denormalized source operands to sign-preserved zero, and they flush results that underflow the target output exponent range to sign- preserved zero after rounding. Specialized Arithmetic GPUs provide hardware to accelerate special function computation, attribute interpolation, and texture filtering. Special function instructions include cosine, half precision A 16-bit binary floating-point format, with 1 sign bit, 5-bit exponent, 10-bit fraction, and an implied integer bit. multiply-add (MAD) A single floating-point instruction that performs a compound operation: multiplication followed by addition. A-42 Appendix A Graphics and Computing GPUs | clipped_hennesy_Page_742_Chunk6099 |
sine, binary exponential, binary logarithm, reciprocal, and reciprocal square root. Attribute interpolation instructions provide efficient generation of pixel attributes, derived from plane equation evaluation. The special function unit (SFU) introduced in Section A.4 computes special functions and interpolates planar attributes [Oberman and Siu, 2005]. Several methods exist for evaluating special functions in hardware. It has been shown that quadratic interpolation based on Enhanced Minimax Approximations is a very efficient method for approximating functions in hardware, including reciprocal, reciprocal square-root, log2x, 2x, sin, and cos. We can summarize the method of SFU quadratic interpolation. For a binary input operand X with n-bit significand, the significand is divided into two parts: Xu is the upper part containing m bits, and Xl is the lower part containing n-m bits. The upper m bits Xu are used to consult a set of three lookup tables to return three finite-word coefficients C0, C1, and C2. Each function to be approximated requires a unique set of tables. These coefficients are used to approximate a given function f(X) in the range Xu <= X < Xu + 2-m by evaluating the expression: f(X) = C0 + C1 Xl + C2 Xl 2 The accuracy of each of the function estimates ranges from 22 to 24 significand bits. Example function statistics are shown in Figure A.6.1. The IEEE 754 standard specifies exact-rounding requirements for division and square root, however, for many GPU applications, exact compliance is not required. Rather, for those applications, higher computational throughput is more important than last-bit accuracy. For the SFU special functions, the CUDA math library provides both a full accuracy function and a fast function with the SFU instruction accuracy. Another specialized arithmetic operation in a GPU is attribute interpolation. Key attributes are usually specified for vertices of primitives that make up a scene to be rendered. Example attributes are color, depth, and texture coordinates. These attributes must be interpolated in the (x,y) screen space as needed to determine the special function unit (SFU) A hardware unit that computes special functions and interpolates planar attributes. Function Input interval Accuracy (good bits) ULP* error % exactly rounded Monotonic 1/x [1, 2) 24.02 0.98 87 Yes 1/sqrt(x) [1, 4) 23.40 1.52 78 Yes 2x [0, 1) 22.51 1.41 74 Yes log2x [1, 2) 22.57 N/A** N/A Yes sin/cos [0, p/2) 22.47 N/A N/A No * ** FIGURE A.6.1 Special function approximation statistics. For the NVIDIA GeForce 8800 special function unit (SFU). ULP: unit in the last place. N/A: not applicable. A.6 Floating-point A-43 | clipped_hennesy_Page_743_Chunk6100 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.