Skip to content

Chapter 10 Reduction

Programming Massively Parallel Processors 5e — English original

Chapter 10 Reduction

CHAPTER

Reduction And mitigating control divergence CONTENTS 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Reduction trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 A simple reduction kernel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 Reducing control divergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 Reducing memory access divergence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 Reducing global memory accesses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 Reducing synchronization overhead with warp-level primitives. . . . . . . . . . . . . . . . . . . . . 237 Further reducing synchronization overhead with two-stage warp-wide reduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 10.9 Reduction for arbitrary length inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 10.10 Thread coarsening to reduce overhead . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 10.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 10.12 Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 A reduction operation derives a single value from a list of values. The single value could be the sum, the maximum, the minimum, etc. of all the values in the list. The value can also be of various types: integer, single-precision floating point, doubleprecision floating point, half-precision floating point, characters, etc. All these types of reductions share the same computation structure. Like histogram, reduction is an important computation pattern as it generates a summary from a large amount of data. Parallel reduction is an important parallel pattern that requires parallel threads to coordinate with each other to produce correct results. Such coordination must be done carefully to avoid performance bottlenecks commonly found in parallel computing systems. Parallel reduction is therefore a good vehicle for illustrating these performance bottlenecks and introducing techniques for mitigating them.

A reduction operation derives a single value from a list of values. The single value could be the sum, the maximum, the minimum, etc. of all the values in the list. The value can also be of various types: integer, single-precision floating point, double-precision floating point, half-precision floating point, characters, etc. All these types of reductions share the same computation structure. Like histogram, reduction is an important computation pattern as it generates a summary from a large amount of data. Parallel reduction is an important parallel pattern that requires parallel threads to coordinate with each other to produce correct results. Such coordination must be done carefully to avoid performance bottlenecks commonly found in parallel computing systems. Parallel reduction is therefore a good vehicle for illustrating these performance bottlenecks and introducing techniques for mitigating them.

10.1 Background

A reduction transforms a set of items into a single item based on a binary operator. For example, a sum reduction can be defined for a set of floating-point numbers based on the addition operator that produces the sum of all the floating-point numbers in Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00020-2 Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.

Figure 10.1

FIGURE 10.1. A simple sum reduction sequential code.

Figure 10.2

FIGURE 10.2. The general form of a reduction sequential code.

the set. For the set {7.0, 2.1, 5.3, 9.0, 11.2}, the sum reduction would produce 7.0 + 2.1 + 5.3 + 9.0 + 11.2 = 34.6. Reduction can be performed by sequentially going through every element of the array. Fig. 10.1 shows a sequential sum reduction code in C. The code initializes the result variable sum to the addition’s identity value 0.0.1 It then uses a for-loop to iterate through the input array that holds the list of values. During the i th iteration, the code performs an addition operation on the current value of sum and the i th element of the input array. In our example, after iteration 0, the sum variable contains the 0.0 + 7.0 = 7.0. After iteration 1, the sum variable contains 7.0 + 2.1 = 9.1. Thus, after each iteration, another value of the input array would be added (accumulated) to the sum variable. After iteration 5, the sum variable contains 34.6 which is the reduction result. Reduction can be defined for many other operators. A product reduction can be defined for a floating-point multiplication operator whose identity value is 1.0. A product reduction of a set of floating-point numbers is the product of all these numbers. A minimum (min) reduction can be defined for a minimum comparison operator that returns the smaller value of the two inputs. A maximum (max) reduction can be defined for a maximum (max) comparison operator that returns the larger value of the two inputs. For real numbers, the identity value for the minimum (minimum) operator is +∞ (−∞). A min (max) reduction of a set of floating-point numbers produces the smallest (largest) number in the list. Fig. 10.2 shows a general form of sequential reduction for an operator, which is defined as a function that takes two inputs and returns a value. When an element is visited during an iteration of the for-loop, the action to take depends on the type of 1 When an identity value for a binary operator is an input to the operator, the output is always the value of the other input. For example, a floating-point addition operator has an identity value of 0.0 because an addition of any floating-point value v and value 0.0 always results in value v itself. Note that using an identity value in the code example is a matter of convenience. If the operator does not have an identity value, we can simply initialize the sum as element 0 and start the loop iterations from i=1.

10.2 Reduction trees

Figure 10.3

FIGURE 10.3. Examples of parallel reduction trees for max and sum reductions.

reduction being performed. For example, for a max reduction, the Operator function performs a comparison between the two inputs and returns the larger value of the two. For a min reduction, the values of the two inputs are compared by the Operator function and the smaller value is returned. The sequential algorithm ends when all the elements are visited by the for-loop. For a set of N elements, the for-loop iterates N iterations and produces the reduction result at the exit of the loop. Reduction is such a common operation that some programming languages have reduction functions built into their standard libraries. For example, the C++ standard library has std::accumulate and std::reduce that perform different variants of the reduction operation. Similarly, CUDA libraries such as Thrust [1,2] and CUB [3] provide built-in implementations of parallel reduction that are highly optimized for GPUs. Still, this chapter covers how to parallelize and optimize reduction on GPUs from scratch because reduction is an excellent example for demonstrating many parallelization and optimization techniques.

Parallel reduction algorithms have been studied extensively in the literature. The basic concept of parallel reduction is illustrated in Fig. 10.3, where time progresses downwards in the vertical direction and the activities that threads perform in parallel in each time step are shown in the horizontal direction. Let us focus on the max reduction tree in Fig. 10.3(a). During the first round (time step), four max operations are performed in parallel on the four pairs of the original elements. These four operations produce partial reduction results – the four larger values from the four pairs of original elements. During the second time step, two max operations are performed in parallel on the two pairs of partial reduction results and produce two partial results that are even closer to the final reduction result. Thesetwo partial results are the largest value of the first four elements and the largest value of the second four elements in the original input. During the third and final time step, one max operation is performed to generate the final result, the largest value 7, from the original input. Note that the order of performing the operations is changed from a sequential reduction algorithm to a parallel reduction algorithm. For example, for the input at the top of Fig. 10.3(a), a sequential max reduction like the one in Fig. 10.2 would start first by comparing the identity value (−∞) in acc with the input value 3 and update acc with the winner which is 3. It will then compare the value of acc (3) with the input value 1 and update acc with the winner which is 3. This will be followed by comparing the value of acc (3) with the input value 7 and updating acc with the winner which is 7. However, in the parallel reduction of Fig. 10.3(a), the input value 7 is first compared with the input value 0 before it is compared against the maximum of 3 and 1. Being able to change the order of performing the operations in this way is essential for parallelizing the reduction operation. To be able to reorder the operations, parallel reduction assumes that the order of applying the operator to the input values does not matter. In a max reduction, no matter what the order is for applying the operator to the input values, the outcome will be the same. This property is guaranteed mathematically if the operator is associative. An operator Θ is associative if (aΘb)Θc = aΘ(bΘc). In other words, if an operator is associative, one can insert parentheses at arbitrary positions of an expression involving the operator and the results are all the same. With this equivalence relation, one can convert any order of operator application to any other order while preserving the equivalence of results. For example, integer addition is associative, i.e., (1 + 2) + 3 = 1 + (2 + 3).2 On the other hand, integer subtraction is not associative, i.e., (1 − 2) − 3 ̸= 1 − (2 − 3). One can convert the subtraction operator into addition of the negative form of the second operand to induce associativity. For example, (1 − 2) − 3 can be converted into (1 + (−2)) + (−3) = 1 + ((−2) + (−3)). As for real numbers, real number addition is associative in the mathematical sense, but strictly speaking, floating-point additions are not associative due to potentially different rounding results for different ways of introducing parentheses. Some applications accept floating-point operation results to be the same if they are within a tolerable difference from each other. Such tolerance allows developers and compiler optimizations to treat floating-point addition as an associative operator for practical purposes. Interested readers are referred to Appendix A for a detailed treatment of this topic. The conversion from the sequential reduction in Fig. 10.2 to the reduction tree in Fig. 10.3(a) requires that the operator be associative. We can think of a reduction as 2 Although integer addition is associative in the mathematical sense, it is not exactly associative in C++ because the order of operations may impact whether or not an overflow or underflow occurs, which has undefined behavior. However, if the programmer is certain that overflow or underflow will not occur, they can treat integer addition as associative for practical purposes.

a list of operations. The difference of ordering between Fig. 10.2 and Fig. 10.3(a) is caused by inserting parentheses at different positions of the same list. For Fig. 10.2, the parentheses are: ((((((3 max 1) max 7) max 0) max 4) max 1) max 6) max 3 Whereas the parentheses for Fig. 10.3(a) are: ((3 max 1) max (7 max 0)) max ((4 max 1) max (6 max 3)) We will apply an optimization in Section 10.4 that not only rearranges the order of applying the operator, but also rearranges the order of the operands. To rearrange the order of the operands, this optimization further requires the operator to be commutative. An operator is commutative if aΘb = bΘa. That is, the position of the operands can be rearranged in an expression and the results are the same. Note that the max operator is also commutative, as are many other operators such as min, addition, and multiplication.3 Obviously, not all operators are commutative. For example, addition is commutative, i.e., 1 + 2 = 2 + 1, whereas integer subtraction is not, i.e., 1 − 2 ̸= 2 − 1. The parallel reduction pattern in Fig. 10.3(a) is called a reduction tree because it looks like a tree whose leaves are the original input elements and whose root is the final result. The term reduction tree is not to be confused with tree data structures where the nodes are linked either explicitly with pointers or implicitly with assigned positions. In reduction trees, the edges are conceptual, reflecting information flow from operations performed in one time step to those in the next time step. To compare the speed of sequential and parallel reduction implementations, we introduce the notions of work and span. The work performed by an implementation refers to the number of operations it performs, whereas the span of an algorithm refers to the time it needs to perform those operations assuming it has infinite resources. For example, the vector addition kernel in Chapter 2, which adds two vectors of size N, launches N threads. During execution, each thread performs one operation that involves reading two input vector elements, performing an addition, and writing one output element. Hence, this kernel performs O(N ) work, i.e., a total of N operations are performed across all threads. We refer to the time period for a thread to perform an operation as a step. When multiple threads are involved, a step is defined as a time period in which all or a subset of the threads each execute an operation in parallel. The span of a computation is measured as the number of steps taken by an implementation assuming an unlimited amount of execution resources. The sequential vector addition implementation has a 3 Although max and min with real numbers are commutative in the mathematical sense, they are notexactly commutative for floating point numbers because of the behavior when one operand is a NaN. Interested readers are referred to the IEEE Floating-Point Standard document for the detailed behavior of the comparison operators when one or more of the operands are NaNs. However, if the programmer is certain that their input does not contain NaN values, they can treat max and min as commutative for practical purposes.

span of O(N ) because the N operations are performed one after the other. On the other hand, the parallel vector addition kernel has a span of O(1) because the N operations would all be performed in parallel. There is no distinction between work and span when analyzing sequential algorithms because operations are performed sequentially so the number of steps taken by the algorithm is directly proportional to the amount of work it performs. For example, a sequential vector addition performs O(N ) work and takes O(N ) steps since the addition operations are performed one after the other. Like sequential addition, a sequential reduction operation also performs O(N ) work and takes O(N ) steps. In comparison, let us analyze the work and the span of the parallel reduction tree algorithm. In Fig. 10.3(a), the parallel reduction tree performs seven operations to reduce eight values: four max operations during the first time step, two during the second, and one during the third. In general, for N input values, a reduction tree performs 12 N operations during the first round, 14 N operations in the second round, and so on. Therefore, the total number of operations performed is defined by the geometric series 12 N + 14 N + 18 N + · · · N1 N = N − 1 operations. In other words, the parallel reduction tree algorithm performs O(N ) work, which is the same as the sequential reduction algorithm. We will see in Chapter 11 that parallel algorithms do not always perform the same amount of work as sequential algorithms, giving rise to the notion of work efficiency. As for span, a parallel reduction tree takes log2 N steps to complete the reduction process for N input value. Since each step performs one operation, the parallel reduction tree has a span of O(log N ). For example, it can reduce N = 1024 input values in just log2 N = 10 steps assuming that there are enough execution resources. During the first step, we need 12 N = 512 execution resources. Note that the number of resources needed diminishes quickly as we progress in time steps. During the final step, we only need to have one execution resource. The level of parallelism at each step is the same as the number of execution units required. It is interesting to calculate the average level of parallelism across all steps. The average parallelism is the total number of operations performed divided by the number of steps, which is (N − 1)/ log2 N. For N = 1024, the average parallelism in the 10 steps is 102.3, while the peak parallelism is 512 (during the first step). Such variation in the level of parallelism and resource consumption across steps makes reduction trees a challenging parallel pattern for parallel computing systems. Parallel Reduction in Sports and Competitions Parallel reduction has been used in sports and competitions long before the dawn of computing. Fig. 10.4 shows the schedule of the 2010 World Cup quarter finals, semi finals, and the final game in South Africa. It should be clear that this is just a rearranged reduction tree. The elimination process of the World Cup is a maximum reduction where the maximum operator returns the team that beats'' the other team. The tournament reduction’’ is done in multiple rounds. The teams are divided into pairs. During the first round, all pairs play in parallel.

10.3 A simple reduction kernel

Winners of the first round advance to the second round, whose winners advance to the third round, etc. With 8 teams entering a tournament, four winners will emerge from the first round (quarter finals in Fig. 10.4), two from the second round (semi finals in Fig. 10.4), and one final winner (champion) from the third round (final in Fig. 10.4). Each round is a step of the reduction process. The tournament in Fig. 10.4 has a span of four steps.

Figure 10.4

FIGURE 10.4. The 2010 World Cup Finals as a reduction tree.

It should be easy to see that even with 1024 teams, it takes only 10 rounds to determine the final winner. The trick is to have enough resources to hold the 512 games in parallel during the first round, 256 games in the second round, 128 games in the third round, and so on. With enough resources, even with sixty thousand teams, we can determine the final winner in just 16 rounds. It is interesting to note that while reduction trees can greatly speedup the reduction process, they also consume quite a bit of resources. In the World Cup example, a game requires a large soccer stadium, officials, and staff as well as hotels and restaurants to accommodate the massive number of fans in the audience. The four quarter finals in Fig. 10.4 were played in three cities (Nelson Mandela Bay/Port Elizabeth, Cape Town, and Johannesburg) that all together provided enough resources to host the four games. Note that the two games in Johannesburg were played on two different days. Thus, sharing resources between two games made the reduction process take more time. We will see similar tradeoffs in computation reduction trees. Fig. 10.3(b) shows a sum reduction tree example for 8 input values. Everything we presented so far about work and span for max reduction trees is also applicable to sum reduction trees. It takes log2 8 = 3 time steps to complete the reduction using a maximum of four adders and their associated resources for reading and writing data. We will use this example to illustrate the design of sum reduction kernels.

We are now ready to develop a simple kernel to perform the parallel sum reduction tree shown in Fig. 10.3(b). Since the reduction tree requires collaboration across all FIGURE 10.5 A simple sum reduction kernel.

threads which is not possible across an entire grid, we start by implementing a kernel that performs a sum reduction tree within a single block. That is, for an input array of N elements, we call this simple kernel and launch a grid with one block of 12 N threads. Since a block can have up to 1024 threads, we can process up to 2048 input elements. We will eliminate this limitation in Section 10.10. During the first step, all 12 N threads participate and each thread adds two elements to produce 12 N partial sums. During the next step, half of the threads drop off and only 14 N threads continue to participate to produce 14 N partial sums. This process continues until the last step where only one thread remains and produces the total sum. Fig. 10.5 shows the code of the simple sum kernel function, and Fig. 10.6 illustrates the execution of the reduction tree implemented by this code. Note that in Fig. 10.6, the time progresses from top to bottom. We assume that the input array is in the global memory and a pointer to the array is passed as an argument when the kernel function is called. Each thread is assigned to a data location that is 2*threadIdx.x (line 02). That is, the threads are assigned to the even locations in the input array: thread 0 to input[0], thread 1 to input[2], thread 2 to input[4], etc., as shown in the top row of Fig. 10.6. Each thread will be the owner'' of the location it is assigned to and will be the only thread that writes into that location. The design of the kernel follows the owner computes’’ approach where every data location is owned by a unique thread and can be updated by only that owner thread. The top row of Fig. 10.6 shows the assignment of threads to the locations of the input array whereas each of the subsequent rows shows the writes to the input array locations at each step, i.e., iteration of the for-loop in Fig. 10.5 (line 03). The locations that the kernel overwrites in each iteration of the for-loop are marked as filled positions of the input array in Fig. 10.6. For example, at the end of the first iteration, locations with even indices are overwritten with the partial sums of pairs of the original elements (0-1, 2-3, 4-5, etc.) in the input array. At the end of the second iteration, the locations whose indices are multiples of 4 are overwritten with the partial sum of four adjacent original elements (0-3, 4-7, etc.) in the input array. In Fig. 10.5, a stride variable is used for the threads to reach for the appropriate partial sums for accumulation into their owner locations. The stride variable is initialized to 1 (line 03). The value of the stride variable is doubled in each iteration so the FIGURE 10.6 The assignment of threads (``owners’’) to the input array locations and progress of execution over time for the SimpleSumReductionKernel in Fig. 10.5. The time progresses from top to bottom and each level corresponds to one iteration of the for-loop.

stride variable value will be 1, 2, 4, 8, etc. until it becomes greater than blockIdx.x, the total number of threads in the block. As shown in Fig. 10.6, each active thread in an iteration uses the stride variable to add into its owned location the input array element that is of distance stride away. For example, in iteration 0, Thread 0 uses stride value 1 to add input[1] into its owned position input[0]. This updates input[0] to the partial sum of the first pair of original values of input[0] and input[1]. In iteration 1, Thread 0 uses stride value 2 to add input[2] to input[0]. At this time, input[2] contains the sum of the original values of input[2] and input[3] and input[0] contains the sum of the original values of input[0] and input[1]. So, after iteration 1, input[0] contains the sum of the original values of the first four elements of the input array. After the last iteration, input[0] contains the sum of all original elements of the input array and thus the result of the sum reduction. This value is written by Thread 0 as the final output (line 10). We now turn to the if-statement in Fig. 10.5 (line 04). The condition of the ifstatement is set up to select the active threads in each iteration. As shown in Fig. 10.6, during iteration n, the threads whose thread index (threadIdx.x) values are multiples of 2n are to perform addition. The condition is threadIdx.x % stride == 0, which tests if the thread index value is a multiple of the value of the stride variable. Recall that the value of stride is 1, 2, 4, 8, · · · through the iterations, or 2n for iteration n. Thus, the condition indeed tests if the thread index values are multiples of 2n.

Recall that all threads execute the same kernel code. Those threads whose thread index value satisfies the if-condition are the active threads that perform the addition statement (line 05). Those whose thread index values fail to satisfy the condition are the inactive threads that skip the addition statement. As the iterations progress, fewer and fewer threads remain active. At the last iteration, only Thread 0 remains active and produces the sum reduction result. The __syncthreads() statement (line 07 of Fig. 10.5) in the for-loop ensures that all partial sums calculated by the iteration have been written into their destination locations in the input array before any one of threads is allowed to begin the next iteration. In this way, all threads that enter an iteration will be able to correctly use the partial sums produced in the previous iteration. For example, after the first iteration, the even elements will be replaced by the pairwise partial sums. The __syncthreads() statement ensures that all these partial sums from the first iteration are indeed written to the even locations of the input array and ready to be used by the active threads in the second iteration. It is also noteworthy that data written into the global memory by a thread should not be read by other threads without executing a memory fence operation. In this case, since the threads writing and reading the same location across iterations are from the same thread block, the __syncthreads() function at the end of each iteration also serves as a memory fence operation for threads within the same block. Thus, data written before a call to __syncthreads() will be correctly read by threads in the same block after the execution of __syncthreads(). The rules that dictate the expected behavior of data exchange between threads through memory accesses are called the memory consistency model. Interested readers are referred to the CUDA programming guide for more details on the CUDA memory consistency model.

10.4 Reducing control divergence

The kernel code in Fig. 10.5 implements the parallel reduction tree in Fig. 10.6 and produces the expected sum reduction result. Unfortunately, its management of active and inactive threads in each iteration results in a high degree of control divergence. For example, as shown in Fig. 10.6, only those threads whose threadIdx.x values are even will execute the addition statement during the second iteration. As we explained in Chapter 4, control divergence can significantly reduce the execution resource utilization efficiency, or the percentage of resources used in generating useful results. In this example, all 32 threads in a warp consume execution resources but only half of them are active, wasting half of the execution resources. The waste of execution resources due to divergence increases over time. During the third iteration, only one fourth of the threads in a warp are active, wasting three quarters of the execution resources. During iteration 6, only one out of the 32 threads in a warp are active, wasting frac3132frac{31}{32} of the execution resources. If the size of the input array is greater than 32, then entire warps will become inactive after the sixth iteration. For example, for input size of 256, 128 threads or 4 warps would be launched. All four warps would have the same divergence pattern as we explained in the previous paragraph for iterations 1 through 6. During the 7th iteration, Warp 1 and Warp 3 would become completely inactive and thus exhibit no control divergence. On the other hand, Warp 0 and Warp 2 would have only one active thread, exhibiting control divergence and wasting frac3132frac{31}{32} of the execution resource. During the 8th iteration, only Warp 0 would be active, exhibiting control divergence and wasting frac3132frac{31}{32} of the execution resource. In general, the execution resource utilization efficiency for an input array of size N can be calculated as the ratio of the total number of active threads to the total number of execution resources consumed. The total number of execution resources consumed is proportional to the total number of active warps across all iterations since every active warp, no matter how few of its threads are active, consumes full execution resources. This number can be calculated as follows: (N/64 ∗ 6 + N/64 ∗ 12 + N/64 ∗ 14 + · · · + 1) ∗ 32 Here, N/64 is the total number of warps launched since N/2 threads will be launched and every 32 threads form a warp. The N/64 term is multiplied by 6 because all launched warps are active for 6 iterations. After the sixth iteration, the number of warps is reduced by half in each successive iteration. The expression in the parenthesis gives the total number of active warps across all the iterations. The second term reflects that each active warp consumes full execution resources for all 32 threads regardless of the number of active threads in these warps. For input array size of 256, the consumed execution resource is (4*6 + 2 + 1)*32 = 864. The number of execution results committed by the active threads is the total number of active threads across all iterations: N/64 ∗ (32 + 16 + 8 + 4 + 2 + 1) + N/64 ∗ 12 ∗ 1 + N/64 ∗ 14 ∗ 1 + · · · + 1 The terms in the parenthesis give the active threads in the first six iterations for all N/64 warps. Starting at the 7th iteration, the number of active warps is reduced by half in each iteration and there is only one active thread in each active warp. For input array size of 256, the total number of committed results is 4 ∗ (32 + 16 + 8 + 4 + 2 + 1) + 2 + 1 = 255. This result should be intuitive because the total number of operations needed to reduce 256 values is 255 operations. Putting the previous two results together, we find that the execution resource utilization efficiency for an input array size of 256 is 255/864 = 0.30. This ratio states that the parallel execution resources did not achieve their full potential in speeding up this computation. On average, only about 30% of the resources consumed contributed to the sum reduction result. That is, we are only using 30% of the hardware’s potential to speed up the computation. Based on the analysis, we see that there is wide-spread control divergence across warps and over time. As the reader might have wondered, there is a better way to assign threads to the input array locations to reduce control divergence and improve resource utilization efficiency. The problem with the assignment illustrated in Fig. 10.6 is that the partial sum locations become increasingly distant from each other FIGURE 10.7 A better assignment of threads to input array locations for reduced control divergence.

and thus the active threads that own these locations are also increasingly distant from each other as time progresses. This increasing distance between active threads contributes to the increasing level of inactivity and resource underutilization. There is, indeed, a better assignment strategy that significantly reduces control divergence. The idea is that we should arrange the threads and their owned positions so that they can remain close to each other as time progresses. That is, we would like to have the stride value to decrease, rather than increase, over time. The revised assignment strategy is shown in Fig. 10.7 for an input array of 16 elements. Here, we assign the threads to the first half of the locations. During the first iteration, each thread reaches halfway across the input array and adds an input element to its owned location. In our example, Thread 0 adds input[8] to its owned position input[0], Thread 1 adds input[9] to position input[1], etc. During each subsequent iteration, half of the active threads drop off and all remaining active threads add an input element whose position is the number of active threads away from its owner position. In our example, during iteration 3, there are two remaining active threads: Thread 0 adds input[2] into its owned position input[0] and Thread 1 adds input[3] into its owned position input[1]. Note that if we compare the operation and operand orders of Fig. 10.7 to Fig. 10.6, there is effectively a reordering of the list of input values, rather than simply inserting parentheses in different ways. That is, the list of input values has been effectively reordered as follows:

Figure 10.8

FIGURE 10.8. A kernel with less control divergence and improved execution resource utilization efficiency.

{input[0], input[8], input[1], input[9], …, input[7], input[15]} For the result to always remain the same after such reordering, the operation must be commutative in addition to being associative. Fig. 10.8 shows a kernel with the work assignment illustrated in Fig. 10.7. There are several small but critical differences between this kernel and the one shown in Fig. 10.5. First, the owner position variable i is set to threadIdx.x rather than 2*threadIdx.x (line 02). Thus, the owner positions of all adjacent threads are now adjacent to each other as illustrated in Fig. 10.7. Second, the stride value is initialized as blockDim.x and is reduced by half until it reaches 1 (line 03). Third, in each iteration, only the threads whose indices are smaller than the stride value remain active (line 04). This way, all active threads are of consecutive thread indices, as shown in Fig. 10.7. With these changes, instead of adding neighbor elements in the first round, it adds elements that are half a section away from each other and the section size is always twice the number of remaining active threads. All pairs added during the first round are blockDim.x away from each other. After the first iteration, all the pair-wise sums are stored in the first half of the input array, as shown in Fig. 10.7. Finally, the loop divides the stride by 2 before entering the next iteration. Thus, for the second iteration, the stride variable value is half of the blockDim.x value. That is, the remaining active threads add elements that are quarter a section away from each other during the second iteration. The kernel in Fig. 10.8 still has an if-statement (line 04) in the loop. The number of threads that execute an addition operation (line 06) in each iteration is the same as in Fig. 10.5. So, why should there be a difference in control divergence between the two kernels? The answer lies in the positions of threads that perform the addition operation relative to those that do not. Let us consider the example of an input array of 256 elements. During the first iteration, all threads are active so there is no control divergence. During the second iteration, Threads 0 through 63 execute the add statement (active) while threads 64 through 127 do not (inactive). The pair-wise sums are stored in elements 0 through 63 during the second iteration. Since the warps consist of 32 threads with consecutive threadIdx.x values, all threads in warps 0 throughwarp 1 execute the add statement whereas all threads in warp 2 through warp 3 become inactive. Since all threads in each warp take the same path of execution, there is no control divergence! However, the kernel in Fig. 10.8 does not completely eliminate the divergence caused by the if-statement. The reader should verify that for the 256-element example, starting with the 4th iteration, the number of threads that execute the addition operation will fall below 32. That is, the final five iterations will have only 16, 8, 4, 2, and 1 thread(s) performing the addition. This means that the kernel execution will still have divergence in these iterations. However, the number of iterations of the loop that has divergence is reduced from ten to five. We can calculate the total number of execution resources consumed as: (N/64 ∗ 1 + N/64 ∗ 12 + · · · + 1 + 5 ∗ 1) ∗ 32 The part in parentheses reflects the fact that in each subsequent iteration, half of the warps become entirely inactive and no longer consume execution resources. This series continues until there is only one full warp of active threads. The last term (5*1) reflects the fact that for the final five iterations, there is only one active warp and all its 32 threads consume execution resources even though only a fraction of the threads are active. Thus, the sum in the parentheses gives the total number of warp executions through all iterations, which when multiplied by 32 gives the total amount of execution resources consumed. For our 256-element example, the execution resources consumed are (4 + 2 + 1 + 5 ∗ 1) ∗ 32 = 384, which is almost half of 736, the resources consumed by the kernel in Fig. 10.5. Since the number of active threads in each iteration did not change from Fig. 10.6 to Fig. 10.7, the efficiency of the new kernel in Fig. 10.8 is 255/384 = 66%, which is almost double the efficiency of the kernel in Fig. 10.5. Note also that since the warps are scheduled to take turns to execute in an SM of limited execution resources, the total execution time will also improve with the reduced resource consumption. The difference between the kernels in Fig. 10.5 and Fig. 10.8 is small but can have a significant performance impact. It requires someone with clear understanding of the execution of threads on the SIMD hardware of the device to be able to confidently make such adjustments.

10.5 Reducing memory access divergence

The simple kernel in Fig. 10.5 has another performance issue: memory access divergence. As we explained in Chapter 5, it is important to achieve memory coalescing within each warp. That is, adjacent threads in a warp should access adjacent locations when they access global memory. Unfortunately, as illustrated in Fig. 10.6, adjacent threads do not access adjacent locations. In each iteration, each thread performs two global memory reads and one global memory write. The first read is from its owned location, the second read is from the location that is of stride distance away from itsowned location, and the write is to its owned location. Since the locations owned by adjacent threads are not adjacent locations, the accesses made by adjacent threads will not be fully coalesced. During each iteration, the memory locations collectively accessed by a warp are of one stride distance away from each other. For example, as shown in Fig. 10.6, when all threads in a warp perform their first read during the first iteration, the locations are two elements away from each other. As a result, twice the number of global memory transactions as that for a coalesced access are triggered, and half the data returned will not be used by the threads. The same behavior also occurs for the second read and the write. During the second iteration, every other thread drops out, and the locations collectively accessed by the warp are four elements away from each other. Four times the number of global memory transactions as that for a coalesced access are performed and only one fourth of the data returned will be used by the threads. This pattern continues and the inefficiency of the accesses increases as the stride increases. This will continue until there is only one active thread for each warp that remains to be active. Only in the case when there is one active thread in the warp, the warp will perform one global memory request. Thus, the total number of global memory requests is: (N/64 ∗ 5 ∗ 2 + N/64 ∗ 1 + N/64 ∗ 12 + N/64 ∗ 14 + · · · + 1) ∗ 3 The first term (N/64 ∗ 5 ∗ 2) corresponds to the first five iterations where all N/64 warps have two or more active threads whose divergent memory accesses trigger two global memory requests, and therefore, each warp triggers two global memory requests. The remaining terms account for the final iterations where each warp has only one active thread and triggers only one global memory request, and half of the warps drop out in each subsequent iteration. The multiplication by 3 accounts for the two reads and one write by each active thread during each iteration. In the 256-element example, the total number of global memory requests performed by the kernel is (4 ∗ 5 ∗ 2 + 4 + 2 + 1) ∗ 3 = 141. For the kernel in Fig. 10.8, the adjacent threads in each warp always access adjacent locations in the global memory so the accesses are always coalesced. As a result, each warp only triggers a minimal number of global memory transactions on any read or write and fully utilizes the returned data. As the iterations progress, entire warps drop out so no global memory access would be performed by any thread in these inactive warps. The active warps still perform coalesced accesses, triggering the minimal number of global memory transactions and fully utilizing the returned data. Half of the warps drop out in each iteration until there is only one warp for the final five iterations. The only period of resource under-utilization occurs when the amount of data requested drops below the size of a single global memory transaction. Since DRAM bandwidth is a limited resource, the execution time of the kernel in Fig. 10.7 is likely to be significantly better than that for the simple kernel in Fig. 10.5. In conclusion, the kernel in Fig. 10.7 offers more efficiency in using both execution resources and DRAM bandwidth compared to the kernel in Fig. 10.5. The advantage comes from both reduced control divergence and improved memory coalescing.

Figure 10.9

FIGURE 10.9. Using shared memory to reduce accesses to the global memory.

10.6 Reducing global memory accesses

The non-divergent kernel in Fig. 10.8 can be further improved by using shared memory. Note that in each iteration, threads write their partial sum result values out to the global memory and these values are reread by the same threads and other threads in the next iteration. Although some of the reads and writes may be served by the last-level cache, there are still significant latency and bandwidth limitations when accessing the last-level cache. Since the shared memory has much lower latency and higher bandwidth than the last-level cache and the global memory, we can further improve the execution speed by keeping the partial sum results in the shared memory. This idea is illustrated in Fig. 10.9. The strategy for using the shared memory is implemented in the kernel shown in Fig. 10.10. The idea is to use each thread to load and add two of the original elements before writing the partial sum into the shared memory (line 04). Since the first iteration is already done when accessing the global memory locations outside the loop, the for-loop starts with blockDim.x/2 (line 04) instead of blockDim.x. The __syncthreads() is moved to the beginning of the loop to ensure that we synchronize between the shared memory accesses and the first iteration of the loop. The threads proceed with the remaining iterations by reading and writing the shared memory (line 08). Finally, at the end of the kernel, Thread 0 writes the sum into output, maintaining the same behavior as the previous kernels (lines 11-13). Using the kernel in Fig. 10.10, the number of global memory accesses are reduced to the initial loading of the original contents of the input array and the final write to FIGURE 10.10 A kernel that uses shared memory to reduce global memory accesses.

10.7 Reducing synchronization overhead with warp-level primitives

input[0]. Thus for an N-element reduction, the number of global memory accesses is just N + 1. Note also that both global memory reads in Fig. 10.10 (line 04) are coalesced. So with coalescing, there will only be (N/32) + 1 global memory requests. For the 256-element example, the total number of global memory requests triggered will be reduced from 36 for the kernel in Fig. 10.8 to 8 + 1 = 9 for the shared memory kernel in Fig. 10.9, a 4× improvement. Another added benefit of using shared memory, besides reducing the number of global memory accesses, is that the input array is not modified. This property is useful if the original values of the array are needed for some other computation in another part of the program.

In the kernel in Fig. 10.10, when the stride reaches 32 and onwards, only one warp in the thread block is active while executing the reduction tree. CUDA provides multiple warp-level primitives that allow threads in the same warp to share data and synchronize with each other in ways that threads across different warps cannot. Accordingly, we can further optimize the reduction kernel when the number of active threads reaches 32 and onwards by using warp-level primitives to reduce the overhead of accessing shared memory and calling __syncthreads(). In this section, we introduce some of the warp-level primitives available in CUDA and show how they can be used to further optimize the reduction kernel. The simplest warp-level primitive is __syncwarp() which behaves like __syncthreads(), but at the warp level. __syncwarp() ensures that all threads in the warp reach the point in the code where it is called before any of them proceed with their execution. In particular, if the threads in the warp have diverged, __syncwarp() ensures that they reconverge. Another category of warp-level primitives, which are relevant for optimizing the reduction kernel in this section, is warp shuffle functions. Warp shuffle functions FIGURE 10.11 The __shfl_down_sync warp-level primitive.

allow threads in the same warp to exchange data with each other (or shuffle data) directly from their registers without having to access shared memory or call __syncthreads(). Of particular relevance to the reduction kernel is the __shfl_down_sync primitive which allows a thread to shuffle data from another thread whose index is higher by a given stride. The specific parameters to __shfl_down_sync are shown and explained in Fig. 10.11. The __shfl_down_sync primitive can be used to implement a warp-wide reduction without the need to access shared memory or call __syncthreads(). Fig. 10.12 illustrates how such a warp-wide reduction can be integrated into the block-wide reduction to reduce the barrier synchronization overhead and access to shared memory. For simplicity, the illustration shows a block consisting of four warps with four threads each. In practice, a block with 1024 threads would consist of 32 warps with 32 threads each. In Fig. 10.12, the first few iterations are executed like the previous implementation in Fig. 10.9. Each thread loads two elements from shared memory, adds them, and stores the result in shared memory. A block-wide barrier synchronization using __syncthreads() separates each iteration. After each iteration completes, half the threads drop out of the computation. However, unlike the previous implementation in Fig. 10.9, once the threads remaining comprise a single warp, there is no longer a need to use __syncthreads() and shared memory. Instead, the threads in the warp load the values from shared memory to their registers, and execute the remaining reduction tree iterations by shuffling values across their registers. We now turn our attention to the code for implementing the approach in Fig. 10.12. To assist with warp-level programming, we define two preliminary device functions for identifying the index of a warp in a block and the index of a thread in a warp. To identify the index of a warp in a block we define the following device function: device unsigned int warpIdx() { return threadIdx.x/WARP_SIZE; } FIGURE 10.12 Using warp-wide reduction in the final stage to reduce synchronization overhead and accesses to shared memory.

This function divides the thread index by the warp size of 32 such that every group of 32 consecutive threads have the same warp index. For example, threads 0 to 31 all have a warp index of 0, threads 32 to 63 all have a warp index of 1, etc. To identify the index of a thread in a warp, also known as the lane index, we define the following device function: device unsigned int laneIdx() { return threadIdx.x%WARP_SIZE; } This function takes the modulo of the thread index with respect to the warp size of 32 such that 32 consecutive threads in the same warp have lane indices ranging from 0 to 31. For example, thread 32 in the block has a lane index of 32%32 = 0 because it is the first thread in warp 1, thread 33 in the block has a lane index of 33%32 = 1 because it is the second thread in warp 1, etc. With these helper device functions defined, we now turn our attention to implementing a warp-wide reduction. Fig. 10.13 shows a device function warp_reduce for performing a warp-wide reduction operation by shuffling values across registers. The function is intended to be called by all threads in the warp, with each thread providing a value val as a parameter that it would like to contribute to the reduction. Each thread starts by initializing its partial sum variable partialSum to val (line 02). A reduction loop is then executed starting from stride 16 down to stride one (line 03). The first stride is 16 because a warp has 32 threads, hence 32 values to reduce, so in the first iteration, the first 16 threads will accumulate values coming from the next 16 threads.

Figure 10.13

FIGURE 10.13. A device function that uses warp-level primitives to perform a warp-wide reduction.

Figure 10.14

FIGURE 10.14. A reduction kernel that uses warp-wide reduction in the final stage to reduce synchronization overhead and accesses to shared memory.

In each iteration of the reduction loop, we use __shfl_down_sync to exchange data and synchronize within the warp in a lightweight manner (line 04). The first argument, 0xffffffff, is a 32-bit mask where all the bits are set, indicating that all threads in the warp participate in this reduction operation. The second argument indicates that each sending thread will pass the value in its register containing partialSum to the receiving thread. The third argument indicates that the receiving thread’s index is stride below the sending thread’s index. The value returned by __shfl_down_sync is the value received by the receiving thread from the sending thread. In other words, for thread i in the warp, __shfl_down_sync will return the value of partialSum for thread i+stride. This value is then added to the receiving thread’s partial sum. After the loop finishes executing, the final result is found in the partialSum variable of the first thread in the warp. Hence, this value is returned to the caller (line 06) with the understanding that only the first thread’s return value represents the true result. Having implemented a warp-wide reduction using warp-level primitives, we can now use this device function to optimize the reduction kernel. Fig. 10.14 shows the updated reduction kernel that uses warp-wide reduction. The first part of the code (lines 01-10) is similar to that in Fig. 10.10, with the exception that the loop on line 10.8 Further reducing synchronization overhead 05 ends when the stride reaches the warp size, which is 32. Starting from stride 32 down to stride one, only the first warp in the thread block participates in executing the reduction tree. For this reason, only the threads whose warp index evaluates to 0 continue to execute (line 12). Each thread in the remaining warp begins by loading the element corresponding to its own index from shared memory to a register called partialSum (line 13). Next, the threads of the warp jointly call the warp_reduce function from Fig. 10.13 (line 14), which returns the final sum to the first thread in the warp, i.e., thread 0 of the block. This thread then writes the result to the output in global memory (lines 17-19). In this way, we have eliminated the shared memory accesses and barrier synchronization from the iterations with stride 16 onwards. The __shfl_down_sync function, as well as other warp-level primitives, takes an additional optional parameter that specifies the width of the group of threads involved in executing the primitive. By default, this width is 32, which means that all 32 threads in the warp are treated as a single group. However, it is possible to specify a smaller width that breaks the warp into smaller collaborating groups. For example, if a width of eight is specified, then the warp is treated as four groups of eight threads, and each eight threads of a group execute the primitive in collaboration with each other and independent of the other threads in the warp. Other types of warp shuffle functions are also available in CUDA, and are useful in other contexts where exchanging data between different threads in the same warp is needed. These other functions include __shfl_sync, __shfl_up_sync, and __shfl_xor_sync. We refer the reader to the CUDA C++ Programming Guide for details about how the other warp shuffle functions operate. In addition to warp shuffle functions, other types of warp-level primitives include warp voting functions that check which threads in a warp meet some condition, warp match functions which check which threads in a warp have the same value for some parameter, and warp reduce functions which perform warp-wide reductions for integer values. Chapter 12 presents an example of how warp voting functions can be used.

10.8 Further reducing synchronization overhead with two-stage warp-wide reduction

The kernel in Fig. 10.14 eliminates the overhead of shared memory accesses and barrier synchronization in the last few iterations of the reduction tree. However, the initial iterations still incur this overhead. One way to eliminate this overhead is to use warp-wide reductions in the initial stages as well. In this case, we can have each warp in the thread block perform a warp-wide reduction on a segment of the input and place its partial sum in shared memory, then have a single warp perform a warp-wide reduction to reduce the partial sums. Fig. 10.15 illustrates how two stages of warp-wide reduction can be used to further reduce the barrier synchronization overhead and access to shared memory. Initially, each warp loads the elements its threads are responsible for reducing and performs a FIGURE 10.15 Using two-stage warp-wide reduction to further reduce synchronization overhead and accesses to shared memory.

warp-wide reduction. At the end of the first stage of warp-wide reductions, the first thread in each warp has the total sum of all elements assigned to that warp. These threads write the sums to shared memory and a block-wide barrier synchronization is performed using __syncthreads().4 After that, the first warp picks up these sums and reduces them into a total sum using another warp-wide reduction. Fig. 10.16 shows a reduction kernel that performs such a block-wide reduction using two stages of warp-wide reductions. First, each thread loads the two input elements assigned to it, adds them, and places the result in a register (line 04). Next, the threads in the same warp jointly call the warp_reduce function to perform a warp-wide reduction (line 05). All warps in the thread block are active throughout this process, each performing an independent reduction. Next, the first thread in each warp, i.e., the thread with lane index 0 which has the warp’s partial sum, places the partial sum in shared memory at a location associated with that warp (lines 07-10). A barrier synchronization is then performed to ensure that all warps have written their partial sums (line 11).

4 Keep in mind that we still assume that only one thread block is used to reduce up to 2048 elements. This is why all warps can exchange data through shared memory. This assumption will be removed in the next section.

10.8 Further reducing synchronization overhead FIGURE 10.16 A reduction kernel that uses two-stage warp-wide reduction to further reduce synchronization overhead and accesses to shared memory.

Once all warps have written their partial sums, the code proceeds similar to the kernel in Fig. 10.14. Only the threads in the first warp continue execution (line 13).5 Each thread in the warp loads one of the partial sums from shared memory (line 14), then the threads perform a warp-wide reduction (line 15). Finally, the first thread in the warp writes out the final sum to global memory (lines 16-18). The main advantage of the implementation in Fig. 10.16 that uses two stages of warp-wide reductions is that it eliminates the overhead of shared memory accesses and barrier synchronization from the first stage as well. The only time we need to access shared memory and perform barrier synchronization is when transitioning between the two stages. However, this implementation also has a disadvantage compared to the one in Fig. 10.14. Recall that in the first stage of the implementation in Fig. 10.14, half the warps become inactive after each iteration and there is no control divergence. However, in Fig. 10.16 that uses two stages, all the warps are active throughout the entire first stage. However, within each warp, not all threads perform useful work in every shuffle operation, which means that this implementation suffers from more control divergence. Hence, this implementation trades off more control divergence to reduce shared memory accesses and barrier synchronization. In practice, this trade-off is worthwhile because once the data is loaded from global memory, the performance of the rest of the reduction kernel is primarily limited by latency. Eliminating the shared memory accesses and barrier synchronizations helps reduce the long-latency instructions in the kernel. On the other hand, eliminating divergent warps, while effective, does not substantially benefit a latency bound 5 Since there are up to 1024 threads in a block and 32 threads in a warp, there will be only up to 32 warps in the block and thus we up to 32 partial sums from the first stage. Therefore, we will need only one warp to complete the second stage.

Figure 10.17

FIGURE 10.17. Multi-block reduction using atomic operations.

kernel because the execution cycles saved by eliminating divergence will likely be replaced by stall cycles.

10.9 Reduction for arbitrary length inputs

All the kernels that we have studied so far assume that they will be launched with one thread block. The main reason for this assumption is that __syncthreads() is used as a barrier synchronization among all the active threads. Recall that __syncthreads() can be used only among threads in the same block. This limits the level of parallelism to 1024 threads on current hardware. For large input arrays that contain millions or even billions of elements, we can benefit from launching more threads to further accelerate the reduction process. Since we do not have a good way to perform barrier synchronization among threads in different blocks, we will need to allow threads in different blocks to execute independently. Fig. 10.17 illustrates the concept of multi-block reduction using atomic operations. The idea is to partition the input array into segments so that each segment is of appropriate size for a block. All blocks then independently execute a reduction tree and accumulate their results to the final output using an atomic add operation. Fig. 10.18 shows the kernel implementation for the multi-block reduction, which has only a few changes compared to the kernel in Fig. 10.16. The partitioning is done by assigning a different value to the segment variable according to the thread’s block index (line 03). The size of each segment is 2*blockDim.x. That is, each block processes 2*blockDim.x elements. Thus, when we multiply the size of each segment by blockIdx.x of a block, we have the starting location of the segment to be processed by the block. For example, if we have 1024 threads in a block, the segment size would be 2*1024 = 2048. The starting locations of segments would be 0 for block 0, 2048 (2048 * 1) for block 1, 4096 (2048 * 2) for block 2, etc.

Figure 10.18

FIGURE 10.18. A multi-block sum reduction kernel using atomic operations.

Once we know the starting location for each block, all threads in a block can simply work on the assigned segment as if it is the entire input data. Within a block, we assign the owned location to each thread by adding the threadIdx.x to the segment starting location for the block that the thread belongs to (line 04). The local variable i holds the owned location of the thread in the global input array, in place of t in the previous kernels. Line 05 is adapted to use i instead of t when accessing the global input array. The rest of the code that performs the main reduction computation remains as is. One can adapt any of the single-block reduction kernel code into this part of the kernel. The final difference is that instead of having Thread 0 (leader thread) of each thread block writing the partial sum to the global output value, it accumulates the partial sum to the output using an atomic addition operation (line 18-20). The atomic operation ensures that the leader threads of all thread blocks accumulate their partial sums to the global value without any race conditions. A subtle but important aspect of using the atomic operation to accumulate partial sums into the final sum is that the thread blocks can make their contributions in any arbitrary order with respect to each other. This is because atomic operations only enforce mutual exclusion but not ordering. Therefore, the operator for the reduction must be both commutative and associative in order to benefit from the use of atomic operations to generalize to inputs of arbitrary length. As an alternative to using atomic operations to produce a global reduction from the reduction results of segments, one can have the leader threads of thread blocks to write into a partial sum array using their block index. A new kernel can then be launched with one thread block to produce the final output value. Another alternative is to copy the partial sum array to the host memory and use the CPU to complete the reduction. In systems where atomic operations are not available or are too expensive, using a single-block grid or the host to complete the reduction would make sense. These approaches also give the programmer more control over the order in which the partial sums are accumulated.

10.10 Thread coarsening to reduce overhead

The reduction kernels that we have worked with so far all try to maximize parallelism by using as many threads as possible. That is, for a reduction of N elements, N/2 threads are launched. With a thread block size of 1024 threads, the resulting number of thread blocks is N/2048. However, in processors with limited execution resources, the hardware may have only enough resources to execute a portion of the thread blocks in parallel. In this case, the hardware will serialize the surplus thread blocks, executing a new thread block whenever an old one has completed. To parallelize reduction, we have actually paid a heavy price to distribute the work across multiple threads and thread blocks. As we have seen in earlier sections, hardware underutilization increases with each successive stage of the reduction tree because of more threads become idle. The phase where the hardware is underutilized occurs for every thread block we launch. It is an inevitable price to pay if the thread blocks were to actually run in parallel. However, if the hardware were to serialize these thread blocks, we are better off serializing them ourselves in a more efficient manner. As we discussed in Chapter 6, thread granularity coarsening, or thread coarsening for brevity, is a category of optimizations that serializes some of the work into fewer threads to reduce parallelization overhead. We start by showing an implementation of parallel reduction with thread coarsening applied by assigning more elements to each thread block. We then further elaborate on how this implementation reduces hardware underutilization. Fig. 10.19 illustrates how thread coarsening can be applied to the example in Fig. 10.9. In Fig. 10.9, each thread block received 16 elements which is two elements per thread. Each thread independently adds the two elements it is responsible for while loading them from global memory, then the threads collaborate to execute a reduction tree. In Fig. 10.19, we coarsen the thread block by a factor of two. Hence, each thread block receives twice the number of elements, i.e., 32 elements which is 4 elements per thread. In this case, each thread independently adds four elements while loading them from global memory before the threads collaborate to execute a reduction tree. The three steps to add the four elements are illustrated by the first three rows of arrows in Fig. 10.19. Note that all threads are active and performing useful work during these three steps. Moreover, since the threads add the four elements that they are responsible for independently, they do not need to synchronize. The remaining steps performing the reduction tree are the same as before. Fig. 10.20 shows the kernel code for implementing reduction with thread coarsening for the multi-block kernel. Compared to Fig. 10.18, the kernel has two main FIGURE 10.19 Thread coarsening in reduction.

Figure 10.20

FIGURE 10.20. Sum reduction kernel with thread coarsening.

differences. The first difference is that, when the beginning of the block’s segment is identified, we multiply by COARSE_FACTOR to reflect the fact that the size of the block’s segment is COARSE_FACTOR times larger (line 03). The second difference is that, when adding the elements that the thread is responsible for, rather than just adding two elements (line 05 in Fig. 10.18), we use a coarsening loop to iterate over the elements and add them based on COARSE_FACTOR (lines 06-08 in Fig. 10.20). Note that all threads are active throughout this coarsening loop, the partial sum is accumulated to the local variable partialSum, and no calls to __syncthreads() are made in the loop because the threads act independently. Fig. 10.21 compares the execution of two original thread blocks without coarsening serialized by the hardware, shown in Fig. 10.21(a), with one coarsened thread block performing the work of two thread blocks, shown in Fig. 10.21(b). In Fig. 10.21(a), the first thread block performs one step where each thread adds the two elements that it is responsible for. All threads are active during this step, so the hardware is fully utilized. The remaining three steps execute the reduction tree where FIGURE 10.21 Comparing parallel reduction with and without thread coarsening.

half the threads drop out each step, underutilizing the hardware. Moreover, each step requires a barrier synchronization as well as accesses to shared memory. When the first thread block is done, the hardware then schedules the second thread block which follows the same steps but on a different segment of the data. Overall, the two blocks collectively take a total of eight steps, out of which two steps fully utilize the hardware whereas six steps underutilize the hardware and require barrier synchronization and shared memory access. In contrast, in Fig. 10.21(b), the same amount of data is processed by only a single thread block that is coarsened by a factor of two. This thread block initially takes three steps where each thread adds the four elements it is responsible for. All threads are active during all three steps so the hardware is fully utilized, and there are no barrier synchronizations or accesses to shared memory performed. The remaining three steps execute the reduction tree where half the threads drop out each step, underutilizing the hardware, and where barrier synchronization and accesses to shared memory are needed. Overall, only six steps are needed (instead of eight), out of which three steps (instead of two) fully utilize the hardware whereas three steps (instead of six) underutilize the hardware and require barrier synchronization and shared memory access. Therefore, thread coarsening effectively reduces the overhead from hardware underutilization, synchronization, and access to shared memory. Theoretically, we can increase the coarsening factor well beyond two. However, one must keep in mind that as we coarsen threads, less work will be done in parallel. Therefore, increasing the coarsening factor will reduce the amount of data parallelism being exploited by the hardware. If we increase the coarsening factor too much such that we launch fewer thread blocks than the hardware is capable of executing, we will no longer be able to take full advantage of the available parallel hardware execution resources. The best coarsening factor ensures that there are enough thread blocks to fully utilize the hardware, which usually depends on the total size of the input as well as the characteristics of the specific device.

10.11 Summary

The parallel reduction pattern is important as it plays a key role in many data processing applications. Although the sequential code is simple, it should be clear to the reader that several techniques are needed to achieve high performance parallel execution. These techniques include thread index assignment for reduced divergence, using shared memory for reduced global memory accesses, using warp-level primitives for reduced barrier synchronizations and shared memory access, multi-block reduction with atomic operations, and thread coarsening. Reduction is also an important foundation for the prefix-sum pattern that is an important algorithm component for parallelizing many applications and will be the topic for the next chapter. We reiterate that in practice, programmers do not need to implement parallel reduction from scratch because CUDA libraries such as Thrust [1,2] and CUB [3] provide built-in implementations that are highly optimized for GPUs. However, parallel reduction serves as an excellent vehicle for introducing parallelization and optimization techniques that are applicable in many application contexts.

10.12 Exercises

\1. For the simple reduction kernel in Fig. 10.5, if the number of elements is 1024 and the warp size is 32, how many warps in the block will have divergence during the 5th iteration? 2. For the improved reduction kernel in Fig. 10.8, if the number of elements is 1024 and the warp size is 32, how many warps will have divergence during the 5th iteration? 3. Modify the kernel in Fig. 10.8 to use the access pattern illustrated below.

\4. Modify the kernel in Fig. 10.20 to perform a max reduction instead of a sum reduction. 5. Modify the kernel in Fig. 10.20 to work for an arbitrary length input that is not necessarily a multiple of COARSE_FACTOR*2*blockDim.x. Add an extra parameter N to the kernel which represents the length of the input. 6. Assume parallel reduction is to be applied on the following input array: {6, 2, 7, 4, 5, 8, 3, 1} Show how the contents of the array change after each iteration if: a. The unoptimized kernel in Fig. 10.5 is used. b. The kernel optimized for coalescing and divergence in Fig. 10.8 is used.

References [1] N. Bell, J. Hoberock, Thrust: a productivity-oriented library for CUDA, in: GPU Computing Gems Jade Edition, Elsevier, 2012, pp. 359–371. [2] NVIDIA, Thrust: the C++ parallel algorithms library, https://nvidia.github.io/cccl/thrust/ index.html, 2025. [3] NVIDIA, CUB, https://nvidia.github.io/cccl/cub/index.html, 2025.

CHAPTER

Scan And work efficiency in parallel algorithms With special contributions from Li-Wen Chang, Juan Gómez-Luna, and John Owens

complexity. We also use parallel scan as an example to introduce new techniques such as double-buffering and unidirectional synchronization, as well as showcase other optimizations that we have already seen such as using warp-level primitives, thread coarsening, and register tiling.

References

[1] N. Bell, J. Hoberock, Thrust: a productivity-oriented library for CUDA, in: GPU Computing Gems Jade Edition, Elsevier, 2012, pp. 359–371.

[2] NVIDIA, Thrust: the C++ parallel algorithms library, https://nvidia.github.io/cccl/thrust/

[3] NVIDIA, CUB, https://nvidia.github.io/cccl/cub/index.html, 2025.