High Performance Scientific Computing

a high performance scientific cloud computing environment for materials simulations high-performance cloud computing a view of scientific applications
ImogenCameron Profile Pic
Published Date:14-07-2017
Your Website URL(Optional)
Introduction to High Performance Scientific Computing Evolving Copy - open for comments Victor Eijkhout with Edmond Chow, Robert van de Geijn 2nd edition 2014Chapter 1 Single-processor Computing In order to write efficient scientific codes, it is important to understand computer architecture. The differ- ence in speed between two codes that compute the same result can range from a few percent to orders of magnitude, depending only on factors relating to how well the algorithms are coded for the processor architecture. Clearly, it is not enough to have an algorithm and ‘put it on the computer’: some knowledge of computer architecture is advisable, sometimes crucial. Some problems can be solved on a single CPU, others need a parallel computer that comprises more than one processor. We will go into detail on parallel computers in the next chapter, but even for parallel pro- cessing, it is necessary to understand the invidual CPUs. In this chapter, we will focus on what goes on inside a CPU and its memory system. We start with a brief general discussion of how instructions are handled, then we will look into the arithmetic processing in the processor core; last but not least, we will devote much attention to the movement of data between mem- ory and the processor, and inside the processor. This latter point is, maybe unexpectedly, very important, since memory access is typically much slower than executing the processor’s instructions, making it the 1 determining factor in a program’s performance; the days when ‘flop counting’ was the key to predicting a code’s performance are long gone. This discrepancy is in fact a growing trend, so the issue of dealing with memory traffic has been becoming more important over time, rather than going away. This chapter will give you a basic understanding of the issues involved in CPU design, how it affects per- formance, and how you can code for optimal performance. For much more detail, see an online book about PC architecture 95, and the standard work about computer architecture, Hennesey and Patterson 84. 1.1 The Von Neumann architecture While computers, and most relevantly for this chapter, their processors, can differ in any number of details, they also have many aspects in common. On a very high level of abstraction, many architectures can be described as von Neumann architectures. This describes a design with an undivided memory that stores both program and data (‘stored program’), and a processing unit that executes the instructions, operating 2 on the data in ‘fetch, execute, store’ cycle’ . 1. Floating Point Operation. 2. This model with a prescribed sequence of instructions is also referred to as control flow. This is in contrast to data flow, which we will see in section 6.13. 121.1. The Von Neumann architecture This setup distinguishes modern processors for the very earliest, and some special purpose contemporary, designs where the program was hard-wired. It also allows programs to modify themselves or generate other programs, since instructions and data are in the same storage. This allows us to have editors and 3 compilers: the computer treats program code as data to operate on . In this book we will not explicitly discuss compilers, the programs that translate high level languages to machine instructions. However, on occasion we will discuss how a program at high level can be written to ensure efficiency at the low level. In scientific computing, however, we typically do not pay much attention to program code, focusing almost exclusively on data and how it is moved about during program execution. For most practical purposes it is as if program and data are stored separately. The little that is essential about instruction handling can be described as follows. The machine instructions that a processor executes, as opposed to the higher level languages users write in, typically specify the name of an operation, as well as of the locations of the operands and the result. These locations are not expressed as memory locations, but as registers: a small number of named memory 4 locations that are part of the CPU . As an example, here is a simple C routine void store(double a, double b, double c) c = a + b; 5 and its X86 assembler output, obtained by gcc -O2 -S -o - store.c: .text .p2align 4,,15 .globl store .type store, function store: movsd (%rdi), %xmm0 Load a to %xmm0 addsd (%rsi), %xmm0 Load b and add to %xmm0 movsd %xmm0, (%rdx) Store to c ret The instructions here are:  A load from memory to register;  Another load, combined with an addition;  Writing back the result to memory. Each instruction is processed as follows:  Instruction fetch: the next instruction according to the program counter is loaded into the proces- sor. We will ignore the questions of how and from where this happens. 3. At one time, the stored program concept was include as an essential component the ability for a running program to modify its own source. However, it was quickly recognized that this leads to unmaintainable code, and is rarely done in practice 41. 4. Direct-to-memory architectures are rare, though they have existed. The Cyber 205 supercomputer in the 1980s could have 3 data streams, two from memory to the processor, and one back from the processor to memory, going on at the same time. Such an architecture is only feasible if memory can keep up with the processor speed, which is no longer the case these days. 5. This is 64-bit output; add the option-m64 on 32-bit systems. Victor Eijkhout 131. Single-processor Computing  Instruction decode: the processor inspects the instruction to determine the operation and the operands.  Memory fetch: if necessary, data is brought from memory into a register.  Execution: the operation is executed, reading data from registers and writing it back to a register.  Write-back: for store operations, the register contents is written back to memory. The case of array data is a little more complicated: the element loaded (or stored) is then determined as the base address of the array plus an offset. In a way, then, the modern CPU looks to the programmer like a von Neumann machine. There are various 6 ways in which this is not so. For one, while memory looks randomly addressable , in practice there is a concept of locality: once a data item has been loaded, nearby items are more efficient to load, and reloading the initial item is also faster. Another complication to this story of simple loading of data is that contemporary CPUs operate on several instructions simultaneously, which are said to be ‘in flight’, meaning that they are in various stages of completion. Of course, together with these simultaneous instructions, their inputs and outputs are also being moved between memory and processor in an overlapping manner. This is the basic idea of the superscalar CPU architecture, and is also referred to as Instruction Level Parallelism (ILP). Thus, while each instruction can take several clock cycles to complete, a processor can complete one instruction per cycle in favourable circumstances; in some cases more than one instruction can be finished per cycle. The main statistic that is quoted about CPUs is their Gigahertz rating, implying that the speed of the pro- cessor is the main determining factor of a computer’s performance. While speed obviously correlates with performance, the story is more complicated. Some algorithms are cpu-bound, and the speed of the proces- sor is indeed the most important factor; other algorithms are memory-bound, and aspects such as bus speed and cache size, to be discussed later, become important. In scientific computing, this second category is in fact quite prominent, so in this chapter we will devote plenty of attention to the process that moves data from memory to the processor, and we will devote rela- tively little attention to the actual processor. 1.2 Modern processors Modern processors are quite complicated, and in this section we will give a short tour of what their con- stituent parts. Figure 1.1 is a picture of the die of an Intel Sandy Bridge processor. This chip is about two inches in diameter and contains close to a billion transistors. 1.2.1 The processing cores In the Von Neuman model there is a single entity that executes instructions. This has not been the case in increasing measure since the early 2000s. The Sandy Bridge pictured above has four cores, each of which is an independent unit executing a stream of instructions. In this chapter we will mostly discuss aspects of a single core; section 1.4 will discuss the integration aspects of the multiple cores. 6. There is in fact a theoretical model for computation called the ‘Random Access Machine’; we will briefly see its parallel generalization in section 2.2.2. 14 Introduction to High Performance Scientific Computing1.2. Modern processors Figure 1.1: The Intel Sandybridge processor die Instruction handling The Von Neuman model is also unrealistic in that it assumes that all instructions are executed strictly in sequence. Increasingly, over the last twenty years, processor have used out-of-order instruction handling, where instructions can be processed in a different order than the user program specifies. Of course the processor is only allowed to re-order instructions if that leaves the result of the execution intact In the block diagram (figure 1.2) you see various units that are concerned with instrunction handling: This cleverness actually costs considerable energy, as well as sheer amount of transistors. For this reason, processors such as the Intel Xeon Phi use in-order instruction handling. Floating point units In scientific computing we are mostly interested in what a processor does with floating point data. Comput- ing with integers or booleans is typically of less interest. For this reason, cores have considerable sophisti- cation for dealing with numerical data. For instance, while past processors had just a single Floating Point Unit (FPU), these days they will have multiple, capable of executing simultaneously. Victor Eijkhout 151. Single-processor Computing Figure 1.2: Block diagram of the Intel Sandy Bridge core For instance, often there are separate addition and multiplication units; if the compiler can find addition and multiplication operations that are independent, it can schedule them so as to be executed simultaneously, thereby doubling the performance of the processor. In some cases, a processor will have multiple addition or multiplication units. Another way to increase performance is to have a Fused Multiply-Add (FMA) unit, which can execute the instructionx ax +b in the same amount of time as a separate addition or multiplication. Together with pipelining (see below), this means that a processor has an asymptotic speed of several floating point operations per clock cycle. Incidentally, there are few algorithms in which division operations are a limiting factor. Correspondingly, the division operation is not nearly as much optimized in a modern CPU as the additions and multiplications are. Division operations can take 10 or 20 clock cycles, while a CPU can have multiple addition and/or multiplication units that (asymptotically) can produce a result per cycle. 16 Introduction to High Performance Scientific Computing1.2. Modern processors Processor year add/mult/fma units daxpy cycles (countwidth) (arith vs load/store) MIPS R10000 1996 1 1 + 1 1 + 0 8/24 Alpha EV5 1996 1 1 + 1 1 + 0 8/12 IBM Power5 2004 0 + 0 + 2 1 4/12 AMD Bulldozer 2011 2 2 + 2 2 + 0 2/4 Intel Sandy Bridge 2012 1 4 + 1 4 + 0 2/4 Intel Haswell 2014 0 + 0 + 2 4 1/2 Table 1.1: Floating point capabilities of several processor architectures, and DAXPY cycle number for 8 operands Pipelining The floating point add and multiply units of a processor are pipelined, which has the effect that a stream of independent operations can be performed at an asymptotic speed of one result per clock cycle. The idea behind a pipeline is as follows. Assume that an operation consists of multiple simpler opera- tions, and that for each suboperation there is separate hardware in the processor. For instance, an addition instruction can have the following components:  Decoding the instruction, including finding the locations of the operands.  Copying the operands into registers (‘data fetch’). 1 2 1 1  Aligning the exponents; the addition:35 10 +:6 10 becomes:35 10 +:06 10 .  Executing the addition of the mantissas, in this case giving:41. 1  Normalizing the result, in this example to:41 10 . (Normalization in this example does not do 0 0 3 3 anything. Check for yourself that in:3 10 + :8 10 and:35 10 + (:34) 10 there is a non-trivial adjustment.)  Storing the result. These parts are often called the ‘stages’ or ‘segments’ of the pipeline. If every component is designed to finish in 1 clock cycle, the whole instruction takes 6 cycles. However, if each has its own hardware, we can execute two operations in less than 12 cycles:  Execute the decode stage for the first operation;  Do the data fetch for the first operation, and at the same time the decode for the second.  Execute the third stage for the first operation and the second stage of the second operation simul- taneously.  Et cetera. You see that the first operation still takes 6 clock cycles, but the second one is finished a mere 1 cycle later. Let us make a formal analysis of the speedup you can get from a pipeline. On a traditional FPU, producing n results takest(n) = n` where` is the number of stages, and the clock cycle time. The rate at which 1 results are produced is the reciprocal oft(n)=n:r  (`) . serial On the other hand, for a pipelined FPU the time ist(n) = s +` +n 1 wheres is a setup cost: the first operation still has to go through the same stages as before, but after that one more result will be produced Victor Eijkhout 171. Single-processor Computing each cycle. We can also write this formula as t(n) = n +n : 1=2 Figure 1.3: Schematic depiction of a pipelined operation Exercise 1.1. Let us compare the speed of a classical FPU, and a pipelined one. Show that the result rate is now dependent onn: give a formula forr(n), and forr = lim r(n). 1 n1 What is the asymptotic improvement inr over the non-pipelined case? Next you can wonder how long it takes to get close to the asymptotic behaviour. Show that forn =n you getr(n) =r =2. This is often used as the definition ofn . 1=2 1 1=2 Since a vector processor works on a number of instructions simultaneously, these instructions have to be independent. The operation8 : a b +c has independent additions; the operation8 : a i i i i i i+1 ab +c feeds the result of one iteration (a ) to the input of the next (a =:::), so the operations are not i i i i i+1 independent. A pipelined processor can speed up operations by a factor of 4; 5; 6 with respect to earlier CPUs. Such numbers were typical in the 1980s when the first successful vector computers came on the market. These days, CPUs can have 20-stage pipelines. Does that mean they are incredibly fast? This question is a bit complicated. Chip designers continue to increase the clock rate, and the pipeline segments can no longer finish their work in one cycle, so they are further split up. Sometimes there are even segments in which nothing happens: that time is needed to make sure data can travel to a different part of the chip in time. The amount of improvement you can get from a pipelined CPU is limited, so in a quest for ever higher performance several variations on the pipeline design have been tried. For instance, the Cyber 205 had 18 Introduction to High Performance Scientific Computing1.2. Modern processors separate addition and multiplication pipelines, and it was possible to feed one pipe into the next without data going back to memory first. Operations like8 : a b +cd were called ‘linked triads’ (because i i i i of the number of paths to memory, one input operand had to be scalar). Exercise 1.2. Analyse the speedup andn of linked triads. 1=2 Another way to increase performance is to have multiple identical pipes. This design was perfected by the NEC SX series. With, for instance, 4 pipes, the operation8 : a b +c would be split module 4, so that i i i i the first pipe operated on indicesi = 4j, the second oni = 4j + 1, et cetera. Exercise 1.3. Analyze the speedup andn of a processor with multiple pipelines that operate 1=2 in parallel. That is, suppose that there arep independent pipelines, executing the same instruction, that can each handle a stream of operands. (You may wonder why we are mentioning some fairly old computers here: true pipeline supercomputers hardly exist anymore. In the US, the Cray X1 was the last of that line, and in Japan only NEC still makes them. However, the functional units of a CPU these days are pipelined, so the notion is still important.) Exercise 1.4. The operation for (i) xi+1 = ai xi + bi; can not be handled by a pipeline because there is a dependency between input of one iteration of the operation and the output of the previous. However, you can transform the loop into one that is mathematically equivalent, and potentially more efficient to compute. Derive an expression that computes xi+2 from xi without involving xi+1. This is known as recursive doubling. Assume you have plenty of temporary storage. You can now perform the calculation by  Doing some preliminary calculations;  computingxi,xi+2,xi+4,..., and from these,  compute the missing termsxi+1,xi+3,.... Analyze the efficiency of this scheme by giving formulas forT (n) andT (n). Can you 0 s think of an argument why the preliminary calculations may be of lesser importance in some circumstances? Peak performance Thanks to pipelining, for modern CPUs there is a simple relation between the clock speed and the peak performance. Since each FPU can produce one result per cycle asymptotically, the peak performance is the clock speed times the number of independent FPUs. The measure of floating point performance is ‘floating point operations per second’, abbreviated flops. Considering the speed of computers these days, you will 9 mostly hear floating point performance being expressed in ‘gigaflops’: multiples of 10 flops. 1.2.2 8-bit, 16-bit, 32-bit, 64-bit Processors are often characterized in terms of how big a chunk of data they can process as a unit. This can relate to Victor Eijkhout 191. Single-processor Computing  The width of the path between processor and memory: can a 64-bit floating point number be loaded in one cycle, or does it arrive in pieces at the processor.  The way memory is addressed: if addresses are limited to 16 bits, only 64,000 bytes can be identi- fied. Early PCs had a complicated scheme with segments to get around this limitation: an address was specified with a segment number and an offset inside the segment.  The number of bits in a register, in particular the size of the integer registers which manipulate data address; see the previous point. (Floating point register are often larger, for instance 80 bits in the x86 architecture.) This also corresponds to the size of a chunk of data that a processor can operate on simultaneously.  The size of a floating point number. If the arithmetic unit of a CPU is designed to multiply 8-byte numbers efficiently (‘double precision’; see section 3.2.2) then numbers half that size (‘single precision’) can sometimes be processed at higher efficiency, and for larger numbers (‘quadruple precision’) some complicated scheme is needed. For instance, a quad precision number could be emulated by two double precision numbers with a fixed difference between the exponents. These measurements are not necessarily identical. For instance, the original Pentium processor had 64-bit data busses, but a 32-bit processor. On the other hand, the Motorola 68000 processor (of the original Apple Macintosh) had a 32-bit CPU, but 16-bit data busses. The first Intel microprocessor, the 4004, was a 4-bit processor in the sense that it processed 4 bit chunks. These days, 64 bit processors are becoming the norm. 1.2.3 Caches: on-chip memory The bulk of computer memory is in chips that are separate from the processor. However, there is usually a small amount (typically a few megabytes) of on-chip memory, called the cache. This will be explained in detail in section 1.3.4. 1.2.4 Graphics, controllers, special purpose hardware One difference between ‘consumer’ and ‘server’ type processors is that the consumer chips devote consid- erable real-estate on the processor chip to graphics. Processors for cell phones and tablets can even have dedicated circuitry for security or mp3 playback. Other parts of the processor are dedicated to communi- cating with memory or the I/O subsystem. We will not discuss those aspects in this book. 1.2.5 Superscalar processing and instruction-level parallelism In the von Neumann model processors operate through control flow: instructions follow each other linearly or with branches without regard for what data they involve. As processors became more powerful and capable of executing more than one instruction at a time, it became necessary to switch to the data flow model. Such superscalar processors analyze several instructions to find data dependencies, and execute instructions in parallel that do not depend on each other. This concept is also known as Instruction Level Parallelism (ILP), and it is facilitated by various mecha- nisms: 20 Introduction to High Performance Scientific Computing1.3. Memory Hierarchies  multiple-issue: instructions that are independent can be started at the same time;  pipelining: already mentioned, arithmetic units can deal with multiple operations in various stages of completion;  branch prediction and speculative execution: a compiler can ‘guess’ whether a conditional instruc- tion will evaluate to true, and execute those instructions accordingly;  out-of-order execution: instructions can be rearranged if they are not dependent on each other, and if the resulting execution will be more efficient;  prefetching: data can be speculatively requested before any instruction needing it is actually en- countered (this is discussed further in section 1.3.5). Above, you saw pipelining in the context of floating point operations. Nowadays, the whole CPU is pipelined. Not only floating point operations, but any sort of instruction will be put in the instruction pipeline as soon as possible. Note that this pipeline is no longer limited to identical instructions: the notion of pipeline is now generalized to any stream of partially executed instructions that are simultaneously “in flight”. As clock frequency has gone up, the processor pipeline has grown in length to make the segments executable in less time. You have already seen that longer pipelines have a largern , so more independent instructions 1=2 are needed to make the pipeline run at full efficiency. As the limits to instruction-level parallelism are reached, making pipelines longer (sometimes called ‘deeper’) no longer pays off. This is generally seen as the reason that chip designers have moved to multicore architectures as a way of more efficiently using the transistors on a chip; section 1.4. There is a second problem with these longer pipelines: if the code comes to a branch point (a conditional or the test in a loop), it is not clear what the next instruction to execute is. At that point the pipeline can stall. CPUs have taken to speculative execution for instance, by always assuming that the test will turn out true. If the code then takes the other branch (this is called a branch misprediction), the pipeline has to be flushed and restarted. The resulting delay in the execution stream is called the branch penalty. 1.3 Memory Hierarchies We will now refine the picture of the Von Neuman architecture, in which data is loaded immediately from memory to the processors, where it is operated on. This picture is unrealistic because of the so-called memory wall 166: the memory is too slow to load data into the process at the rate the processor can absorb it. Specifically, a single load can take 1000 cycles, while a processor can perform several operations per cycle. (After this long wait for a load, the next load can come faster, but still too slow for the processor. This matter of wait time versus throughput will be addressed below in section 1.3.2.) In reality, there will be various memory levels in between the FPU and the main memory: the registers and the caches, together called the memory hierarchy. These try to alleviate the memory wall problem by mak- ing recently used data available quicker than it would be from main memory. Of course, this presupposes that the algorithm and its implementation allow for data to be used multiple times. Such questions of data reuse will be discussed in more detail in section 1.5.1. Victor Eijkhout 211. Single-processor Computing Both registers and caches are faster than main memory to various degrees; unfortunately, the faster the memory on a certain level, the smaller it will be. These differences in size and access speed lead to inter- esting programming problems, which we will discuss later in this chapter, and particularly section 1.6. We will now discuss the various components of the memory hierarchy and the theoretical concepts needed to analyze their behaviour. 1.3.1 Busses The wires that move data around in a computer, from memory to cpu or to a disc controller or screen, are called busses. The most important one for us is the Front-Side Bus (FSB) which connects the processor to memory. In one popular architecture, this is called the ‘north bridge’, as opposed to the ‘south bridge’ which connects to external devices, with the exception of the graphics controller. Figure 1.4: Bus structure of a processor The bus is typically slower than the processor, operating with clock frequencies slightly in excess of 1GHz, which is a fraction of the CPU clock frequency. This is one reason that caches are needed; the fact that a processors can consume many data items per clock tick contributes to this. Apart from the frequency, the bandwidth of a bus is also determined by the number of bits that can be moved per clock cycle. This is typically 64 or 128 in current architectures. We will now discuss this in some more detail. 1.3.2 Latency and Bandwidth Above, we mentioned in very general terms that accessing data in registers is almost instantaneous, whereas loading data from memory into the registers, a necessary step before any operation, incurs a substantial delay. We will now make this story slightly more precise. There are two important concepts to describe the movement of data: latency and bandwidth. The assump- tion here is that requesting an item of data incurs an initial delay; if this item was the first in a stream of data, usually a consecutive range of memory addresses, the remainder of the stream will arrive with no further delay at a regular amount per time period. 22 Introduction to High Performance Scientific Computing1.3. Memory Hierarchies Latency is the delay between the processor issuing a request for a memory item, and the item actually arriving. We can distinguish between various latencies, such as the transfer from memory to cache, cache to register, or summarize them all into the latency between memory and processor. Latency is measured in (nano) seconds, or clock periods. If a processor executes instructions in the order they are found in the assembly code, then execu- tion will often stall while data is being fetched from memory; this is also called memory stall. For this reason, a low latency is very important. In practice, many processors have ‘out-of-order exe- cution’ of instructions, allowing them to perform other operations while waiting for the requested data. Programmers can take this into account, and code in a way that achieves latency hiding; see also section 1.5.1. Graphics Processing Units (GPUs) (see section 2.9.3) can switch very quickly between threads in order to achieve latency hiding. Bandwidth is the rate at which data arrives at its destination, after the initial latency is overcome. Band- width is measured in bytes (kilobyes, megabytes, gigabyes) per second or per clock cycle. The bandwidth between two memory levels is usually the product of the cycle speed of the channel (the bus speed) and the bus width: the number of bits that can be sent simultaneously in every cycle of the bus clock. The concepts of latency and bandwidth are often combined in a formula for the time that a message takes from start to finish: T (n) = + n where is the latency and is the inverse of the bandwidth: the time per byte. Typically, the further away from the processor one gets, the longer the latency is, and the lower the band- width. These two factors make it important to program in such a way that, if at all possible, the processor uses data from cache or register, rather than from main memory. To illustrate that this is a serious matter, consider a vector addition for (i) ai = bi+ci Each iteration performs one floating point operation, which modern CPUs can do in one clock cycle by 7 using pipelines. However, each iteration needs two numbers loaded and one written, for a total of 24 bytes of memory traffic. Typical memory bandwidth figures (see for instance figure 1.5) are nowhere near 24 (or 32) bytes per cycle. This means that, without caches, algorithm performance can be bounded by memory performance. Of course, caches will not speed up every operations, and in fact will have no effect on the above example. Strategies for programming that lead to significant cache use are discussed in section 1.6. The concepts of latency and bandwidth will also appear in parallel computers, when we talk about sending data from one processor to the next. 1.3.3 Registers Every processor has a small amount of memory that is internal to the processor: the registers, or together the register file. The registers are what the processor actually operates on: an operation such as 7. Actually,ai is loaded before it can be written, so there are 4 memory access, with a total of 32 bytes, per iteration. Victor Eijkhout 231. Single-processor Computing a := b + c is actually implemented as  load the value ofb from memory into a register,  load the value ofc from memory into another register,  compute the sum and write that into yet another register, and  write the sum value back to the memory location ofa. Looking at assembly code (for instance the output of a compiler), you see the explicit load, compute, and store instructions. Compute instructions such as add or multiply only operate on registers. For instance, in assembly language you will see instructions such as addl %eax, %edx which adds the content of one register to another. As you see in this sample instruction, registers are not numbered, as opposed to memory addresses, but have distinct names that are referred to in the assembly instruction. Typically, a processor has 16 or 32 floating point registers; the Intel Itanium was exceptional with 128 floating point registers. Registers have a high bandwidth and low latency because they are part of the processor. You can consider data movement to and from registers as essentially instantaneous. In this chapter you will see stressed that moving data from memory is relatively expensive. Therefore, it would be a simple optimization to leave data in register when possible. For instance, if the above computa- tion is followed by a statement a := b + c d := a + e the computed value of a could be left in register. This optimization is typically performed as a compiler optimization: the compiler will simply not generate the instructions for storing and reloading a. We say thata stays resident in register. Keeping values in register is often done to avoid recomputing a quantity. For instance, in t1 = sin(alpha) x + cos(alpha) y; t2 = -cos(alsph) x + sin(alpha) y; the sine and cosine quantity will probably be kept in register. You can help the compiler by explicitly introducing temporary quantities: s = sin(alpha); c = cos(alpha); t1 = s x + c y; t2 = -c x + s y 24 Introduction to High Performance Scientific Computing1.3. Memory Hierarchies Of course, there is a limit to how many quantities can be kept in register; trying to keep too many quantities in register is called register spill and lowers the performance of a code. Keeping a variable in register is especially important if that variable appears in an inner loop. In the com- putation for i=1,length ai = bi c the quantityc will probably be kept in register by the compiler, but in for k=1,nvectors for i=1,length ai,k = bi,k ck it is a good idea to introduce explicitly a temporary variable to holdck. In C, you can give a hint to the compiler to keep a veriable in register by declaring it as a register variable: register double t; 1.3.4 Caches In between the registers, which contain the immediate input and output data for instructions, and the main memory where lots of data can reside for a long time, are various levels of cache memory, that have lower latency and higher bandwidth than main memory and where data are kept for an intermediate amount of time. Caches typically consist of Static Random-Access Memory (SRAM), which is faster than then Dynamic Random-Access Memory (DRAM) used for the main memory, but is also more expensive. Data from memory travels through the caches to wind up in registers. The advantage to having cache memory is that if a data item is reused shortly after it was first needed, it will still be in cache, and therefore it can be accessed much faster than if it would have to be brought in from memory. A motivating example As an example, let’s suppose a variable x is used twice, and its uses are too far apart that it would stay resident in register: ... = ... x ..... // instruction using x ......... // several instructions not involving x ... = ... x ..... // instruction using x The assembly code would then be  loadx from memory into register; operate on it;  do the intervening instructions;  loadx from memory into register; operate on it; Victor Eijkhout 251. Single-processor Computing With a cache, the assembly code stays the same, but the actual behaviour of the memory system now becomes:  loadx from memory into cache, and from cache into register; operate on it;  do the intervening instructions;  requestx from memory, but since it is still in the cache, load it from the cache into register; operate on it. Since loading from cache is faster than loading from main memoory, the computation will now be faster. Caches are fairly small, so values can not be kept there indefinitely. We will see the implications of this in the following discussion. There is an important difference between cache memory and registers: while data is moved into register by explicit assembly instructions, the move from main memory to cache is entirely done by hardware. Thus cache use and reuse is outside of direct programmer control. Later, especially in sections 1.5.2 and 1.6, you will see how it is possible to influence cache use indirectly. Cache levels, speed and size The caches are called ‘level 1’ and ‘level 2’ (or, for short, L1 and L2) cache; some processors can have an L3 cache. The L1 and L2 caches are part of the die, the processor chip, although for the L2 cache that is a relatively recent development; the L3 cache is off-chip. The L1 cache is small, typically around 16Kbyte. Level 2 (and, when present, level 3) cache is more plentiful, up to several megabytes, but it is also slower. Unlike main memory, which is expandable, caches are fixed in size. If a version of a processor chip exists with a larger cache, it is usually considerably more expensive. Data needed in some operation gets copied into the various caches on its way to the processor. If, some instructions later, a data item is needed again, it is first searched for in the L1 cache; if it is not found there, it is searched for in the L2 cache; if it is not found there, it is loaded from main memory. Finding data in cache is called a cache hit, and not finding it a cache miss. Figure 1.5 illustrates the basic facts of the cache hierarchy, in this case for the Intel Sandy Bridge chip: the closer caches are to the FPUs, the faster, but also the smaller they are. Some points about this figure.  Loading data from registers is so fast that it does not constitute a limitation on algorithm execution speed. On the other hand, there are few registers. Each core has 16 general purpose registers, and 16 SIMD registers.  The L1 cache is small, but sustains a bandwidth of 32 bytes, that is 4 double precision number, per cycle. This is enough to load two operands each for two operations, but note that the core can actually perform 4 operations per cycle. Thus, to achieve peak speed, certain operands need to stay in register: typically, L1 bandwidth is enough for about half of peak performance.  The bandwidth of the L2 and L3 cache is nominally the same as of L1. However, this bandwidth is partly wasted on coherence issues.  Main memory access has a latency of more than 100 cycles, and a bandwidth of 4.5 bytes per cy- cle, which is about 1=7th of the L1 bandwidth. However, this bandwidth is shared by the multiple cores of a processor chip, so effectively the bandwidth is a fraction of this number. Most clusters 26 Introduction to High Performance Scientific Computing1.3. Memory Hierarchies Figure 1.5: Memory hierarchy of an Intel Sandy Bridge, characterized by speed and size. will also have more than one socket (processor chip) per node, typically 2 or 4, so some band- width is spent on maintaining cache coherence (see section 1.4), again reducing the bandwidth available for each chip. On level 1, there are separate caches for instructions and data; the L2 and L3 cache contain both data and instructions. You see that the larger caches are increasingly unable to supply data to the processors fast enough. For this reason it is necessary to code in such a way that data is kept as much as possible in the highest cache level possible. We will discuss this issue in detail in the rest of this chapter. Exercise 1.5. The L1 cache is smaller than the L2 cache, and if there is an L3, the L2 is smaller than the L3. Give a practical and a theoretical reason why this is so. Types of cache misses There are three types of cache misses. As you saw in the example above, the first time you reference data you will always incur a cache miss. This is known as a compulsory cache miss since these are unavoidable. Does that mean that you will always be waiting for a data item, the first time you need it? Not necessarily: section 1.3.5 explains how the hardware tries to help you by predicting what data is needed next. The next type of cache misses is due to the size of your working set: a capacity cache miss is caused by data having been overwritten because the cache can simply not contain all your problem data. (Section discusses how the processor decides what data to overwrite.) If you want to avoid this type of misses, you need to partition your problem in chunks that are small enough that data can stay in cache for an appreciable time. Of course, this presumes that data items are operated on multiple times, so that there is actually a point in keeping it in cache; this is discussed in section 1.5.1. Finally, there are conflict misses caused by one data item being mapped to the same cache location as another, while both are still needed for the computation, and there would have been better candidates to Victor Eijkhout 271. Single-processor Computing evict. This is discussed in section In a multicore context there is a further type of cache miss: the invalidation miss. This happens if an item in cache has become invalid because another core changed the value of the corresponding memory address. The core will then have to reload this address. Reuse is the name of the game The presence of one or more caches is not immediately a guarantee for high performance: this largely depends on the memory access pattern of the code, and how well this exploits the caches. The first time that an item is referenced, it is copied from memory into cache, and through to the processor registers. The latency and bandwidth for this are not mitigated in any way by the presence of a cache. When the same item is referenced a second time, it may be found in cache, at a considerably reduced cost in terms of latency and bandwidth: caches have shorter latency and higher bandwidth than main memory. We conclude that, first, an algorithm has to have an opportunity for data reuse. If every data item is used only once (as in addition of two vectors), there can be no reuse, and the presence of caches is largely irrelevant. A code will only benefit from the increased bandwidth and reduced latency of a cache if items in cache are referenced more than once; see section 1.5.1 for a detailed discussion.. An example would be the matrix-vector multiplicationy = Ax where each element ofx is used inn operations, wheren is the matrix dimension. Secondly, an algorithm may theoretically have an opportunity for reuse, but it needs to be coded in such a way that the reuse is actually exposed. We will address these points in section 1.5.2. This second point especially is not trivial. Some problems are small enough that they fit completely in cache, at least in the L3 cache. This is something to watch out for when benchmarking, since it gives a too rosy picture of processor performance. Replacement policies Data in cache and registers is placed there by the system, outside of programmer control. Likewise, the system decides when to overwrite data in the cache or in registers if it is not referenced in a while, and as other data needs to be placed there. Below, we will go into detail on how caches do this, but as a general principle, a Least Recently Used (LRU) cache replacement policy is used: if a cache is full and new data needs to be placed into it, the data that was least recently used is flushed, meaning that it is overwritten with the new item, and therefore no longer accessible. LRU is by far the most common replacement policy; other possibilities are FIFO (first in first out) or random replacement. Exercise 1.6. Sketch a simple scenario, and give some (pseudo) code, to argue that LRU is preferable over FIFO as a replacement strategy. Cache lines Data movement between memory and cache, or between caches, is not done in single bytes, or even words. Instead, the smallest unit of data moved is called a cache line, sometimes called a cache block. A typical cache line is 64 or 128 bytes long, which in the context of scientific computing implies 8 or 16 double 28 Introduction to High Performance Scientific Computing1.3. Memory Hierarchies precision floating point numbers. The cache line size for data moved into L2 cache can be larger than for data moved into L1 cache. It is important to acknowledge the existence of cache lines in coding, since any memory access costs the transfer of several words (see section 1.6.4 for some examples). An efficient program then tries to use the other items on the cache line, since access to them is effectively free. This phenomenon is visible in code that accesses arrays by stride: elements are read or written at regular intervals. Stride 1 corresponds to sequential access of an array: for (i=0; iN; i++) ... = ... xi ... Let us use as illustration a case with 4 words per cache- line. Requesting the first elements loads the whole cacheline that contains it into cache. A request for the Figure 1.6: Accessing 4 elements at stride 1 2nd, 3rd, and 4th element can then be satisfied from cache, meaning with high bandwidth and low latency. A larger stride for (i=0; iN; i+=stride) ... = ... xi ... Figure 1.7: Accessing 4 elements at stride 3 implies that in every cache line only certain elements are used. We illustrate that with stride 3: requesting the first elements loads a cacheline, and this cacheline also contains the second element. However, the third element is on the next cacheline, so loading this incurs the latency and bandwidth of main memory. The same holds for the fourth element. Loading four elements now needed loading three cache lines instead of one, meaning that two-thirds of the available bandwidth has been wasted. (This second case would also incur three times the latency of the first, if it weren’t for a hardware mechanism that notices the regular access patterns, and pre-emtively loads further cachelines; see section 1.3.5.) Some applications naturally lead to strides greater than 1, for instance, accessing only the real parts of an array of complex numbers (for some remarks on the practical realization of complex numbers see sec- tion 3.5.5). Also, methods that use recursive doubling often have a code structure that exhibits non-unit strides for (i=0; iN/2; i++) xi = y2 i; In this discussion of cachelines, we have implicitly assumed the beginning of a cacheline is also the begin- ning of a word, be that an integer or a floating point number. This need not be true: an 8-byte floating point number can be placed straddling the boundary between two cachelines. You can image that this is not good for performance. To force allocated space to be aligned with a cacheline boundary aligment, you can do the following: Victor Eijkhout 291. Single-processor Computing Figure 1.8: Direct mapping of 32-bit addresses into a 64K cache double a; a = malloc( / some number of bytes / +8 ); if ( (int)a % 8 = 0 ) / it is not 8-byte aligned / a += 1; / advance address by 8 bytes, then / / either: / a = ( (a3) 3 ); / or: / a = 8 ( ( (int)a )/8 ); This code allocates a block of memory, and, if necessary, shifts it right to have a starting address that is a multiple of 8. This sort of alignment can sometimes be forced by compiler options. Cache mapping Caches get faster, but also smaller, the closer to the FPUs they get, yet even the largest cache is considerably smaller than the main memory size. We already noted that this has implications for the cache replacement strategy. Another issue we need to address in this context is that of cache mapping, which is the question of ‘if an item is placed in cache, where does it get placed’. This problem is generally addressed by mapping the (main memory) address of the item to an address in cache, leading to the question ‘what if two items get mapped to the same address’. Direct mapped caches The simplest cache mapping strategy is direct mapping. Suppose that memory addresses are 32 bits long, 8 so that they can address 4G bytes ; suppose further that the cache has 8K words, that is, 64K bytes, needing 16 bits to address. Direct mapping then takes from each memory address the last (‘least significant’) 16 bits, and uses these as the address of the data item in cache; see figure 1.8. Direct mapping is very efficient because of its address calculations can be performed very quickly, leading to low latency, but it has a problem in practical applications. If two items are addressed that are separated by 8. We implicitly use the convention that K,M,G suffixes refer to powers of 2 rather than 10: 1K=1024, 1M=1,048,576, 1G=4,294,967,296. 30 Introduction to High Performance Scientific Computing