Chapter 11 Scan
Chapter 11 Scan
CHAPTER
Scan And work efficiency in parallel algorithms With special contributions from Li-Wen Chang, Juan Gómez-Luna, and John Owens CONTENTS 11.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 11.2 Parallel scan with the Kogge-Stone algorithm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 11.3 Double-buffering to reduce synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 11.4 Warp-level primitives to reduce synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 11.5 Work efficiency considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265 11.6 Coarsening to improve work-eiciency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 11.7 Register tiling to avoid shared memory access latency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 11.8 Memory bandwidth considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 11.9 Consolidating block segments for a global scan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 11.10 Parallel scan with the Brent-Kung algorithm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 11.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 11.12 Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286 Parallel scan is frequently used to parallelize seemingly sequential operations, such as resource allocation, work assignment, and polynomial evaluation. In general, if a computation is naturally described as a mathematical recursion where each item in a series is defined in terms of the previous item, it is likely parallelizable as a parallel scan operation. Parallel scan plays a key role in massively parallel computing for a simple reason: any sequential section of an application can drastically limit the overall performance of the application. Many such sequential sections can be converted into parallel computation with parallel scan. For this reason, parallel scan is often used as a primitive operation in parallel algorithms that perform filtering, radix sort, quick sort, string comparison, polynomial evaluation, solving recurrences, and tree operations. The filtering example is presented in Chapter 12 and the radix sort example is presented in Chapter 14. Multiple algorithms exist for parallel scan with different tradeoffs between work complexity and span. Some parallel algorithms can have higher work complexity than a sequential algorithm. As we shall discuss in this chapter, an increase in work complexity can make a parallel scan run slower than a sequential scan when hardware resources are constrained, necessitating optimizations that mitigate the higher work Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00021-4 Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.
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.
Parallel scan is frequently used to parallelize seemingly sequential operations, such as resource allocation, work assignment, and polynomial evaluation. In general, if a computation is naturally described as a mathematical recursion where each item in a series is defined in terms of the previous item, it is likely parallelizable as a parallel scan operation. Parallel scan plays a key role in massively parallel computing for a simple reason: any sequential section of an application can drastically limit the overall performance of the application. Many such sequential sections can be converted into parallel computation with parallel scan. For this reason, parallel scan is often used as a primitive operation in parallel algorithms that perform filtering, radix sort, quick sort, string comparison, polynomial evaluation, solving recurrences, and tree operations. The filtering example is presented in Chapter 12 and the radix sort example is presented in Chapter 14.
Multiple algorithms exist for parallel scan with different tradeoffs between work complexity and span. Some parallel algorithms can have higher work complexity than a sequential algorithm. As we shall discuss in this chapter, an increase in work complexity can make a parallel scan run slower than a sequential scan when hardware resources are constrained, necessitating optimizations that mitigate the higher work 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.
11.1 Background
Mathematically, an inclusive scan operation takes a binary operator ⊕, and an input array of N elements [x0 , x1 , · · · , xN −1 ], and returns the output array: [x0 , (x0 ⊕ x1 ), · · · , (x0 ⊕ x1 ⊕ · · · ⊕ xN −1 )]. For example, if ⊕ is addition, an inclusive scan operation on the input array [3, 1, 7, 0, 4, 1, 6, 3], would return [3, 3 + 1, 3 + 1 + 7, 3 + 1 + 7 + 0, · · · , 3 + 1 + 7 + 0 + 4 + 1 + 6 + 3] = [3, 4, 11, 11, 15, 16, 22, 25]. The name inclusive scan comes from the fact that each output element includes the effect of the corresponding input element. Note that when the scan operator is addition, the computation is sometimes also referred to as prefix sum. We can illustrate the applications for inclusive scan operations using an example of cutting sausage for a group of people. Assume that we have a 40-inch sausage to be served to 8 people. Each person has ordered a different amount in terms of inches: 3, 1, 7, 0, 4, 1, 6, 3. That is, Person 0 wants 3 inches of sausage, Person 1 wants 1 inch, and so on. We can cut the sausage either sequentially or in parallel. The sequential way is very straightforward. We first cut a 3-inch section for Person 0. The sausage is now 37 inches long. We then cut a 1-inch section for Person 1. The sausage becomes 36 inches long. We can continue to cut more sections until we serve the 3-inch section to Person 7. At that point, we have served a total of 25 inches of sausage, with 15 inches remaining. With an inclusive scan operation, we can calculate the locations of all the cutting points based on the amount ordered by each person. That is, given an addition operation and an order input array [3, 1, 7, 0, 4, 1, 6, 3], the inclusive scan operation returns [3, 4, 11, 11, 15, 16, 22, 25]. The numbers in the return array are the cutting locations. With this information, one can simultaneously make all the eight cuts that will generate the sections that each person ordered. The first cut point is at the 3-inch location so the first section will be 3 inches, as ordered by Person 0. The second cut point is at the 4-inch location, therefore the second section will be 1-inch long, as ordered by Person 1. The final cut point will be at the 25-inch location, which will produce a 3-inch-long section since the previous cut point is at 22-inch point. This gives Person 7 what she ordered. Note that since all the cut points are known from the scan operation, all cuts can be done in parallel or in any arbitrary sequence. In summary, an intuitive way of thinking about inclusive scan is that the operation takes a request from a group of people and identifies all the cut points that allow the orders to be served all at once. The order could be for sausage, bread, campgroundspace, or a contiguous chunk of memory in a computer. As long as we can quickly calculate all the cut points, all orders can be served in parallel. An exclusive scan operation is similar to an inclusive scan operation with a slightly different arrangement of the output array: [ID⊕ , x0 , (x0 ⊕ x1 ), · · · , (x0 ⊕ x1 ⊕ · · · ⊕ xN −2 )]. That is, each output element excludes the effect of the corresponding input element. The first output element is ID⊕ , the identity value for operator ⊕, while the last output element only reflects the contribution of up to xN −2. An identity value for a binary operator is defined as a value that when used as an input operand, it causes the operation to generate an output value that is the same as the other input operand’s value. In the case of the addition operator, the identity value is 0 as any number added with zero will result in itself. The applications of an exclusive scan operation are pretty much the same as those for inclusive scan. The inclusive scan provides slightly different information. In the sausage example, exclusive scan would return [0, 3, 4, 11, 11, 15, 16, 22], which are the beginning points of the cut sections. For example, the section for Person 0 starts at the 0-inch point, and the section for Person 7 starts at the 22-inch point. The beginning point information is important in applications such as memory allocation, where the allocated memory is returned to the requester via a pointer to its beginning point. Note that it is easy to convert between the inclusive scan output and the exclusive scan output. One simply needs to shift all the elements and fill in an element. When converting from inclusive scan to exclusive scan, one can simply shift all the elements to the right and fill in the identity value for the 0th element. When converting from exclusive scan to inclusive scan, one can shift all elements to the left and fill in the last element with the previous last element ⊕ the last input element. It is just a matter of convenience that we can directly generate an inclusive or exclusive scan depending on whether we care about the cut points or the beginning points for the sections. Therefore, we will only present parallel algorithms and implementations for inclusive scan throughout this chapter. Before we present parallel scan algorithms and their implementations, we would like to first show a sequential inclusive scan algorithm and its implementation. We will assume that the operator involved is addition. The code in Fig. 11.1 assumes that the input elements are in the input array and the output elements are to be written into the output array. The code initializes the output element output[0] with the value of input element input[0] (line 02). After that, in each iteration of the loop (lines 03-05), the loop body adds one more input element to the previous output element (which stores the accumulation of all the previous input elements) to generate one more output element. It should be clear that the work done by the sequential implementation of inclusive scan in Fig. 11.1 is linearly proportional to the number of input elements. That is, the computational complexity of the sequential scan algorithm is O(N ).
FIGURE 11.1. A simple sequential implementation of inclusive scan based on addition.
Similar to reduction, scan is a common operation that is available in many libraries. For example, the C++ standard library includes the functions std::inclusive_scan and std::exclusive_scan, and CUDA libraries such as Thrust [1,2] and CUB [3] also provide implementations of parallel scan that are highly optimized for GPUs. While programmers will use these libraries in practice, parallel scan is a great vehicle for demonstrating many parallelization and optimization techniques.
11.2 Parallel scan with the Kogge-Stone algorithm
To parallelize inclusive scan, one might be tempted to assign a thread to each output element that performs a sequential reduction to compute that element. After all, this approach allows the calculation of all output elements to be performed in parallel. However, this approach will unlikely improve the execution time over the sequential scan code in Fig. 11.1. The reason is that the calculation of yN −1 by the last thread would take N steps, and since the completion time of a parallel program is limited by the thread that takes the longest time, the span of such a parallelization would be O(N ). This span is no different from that of a sequential scan which also has a complexity of O(N ). In fact, with limited computing resources, the execution time of this naïve parallel scan algorithm can be much longer than the sequential algorithm. To understand why this approach may have longer execution time, let us analyze the amount of work it performs. The work complexity, or the total number of operations performed, is much higher for the approach described. Since the number of computations for output element i would be i, the total number of computations performed by all threads would be: ∑︁N −1 N ·(N −1) i=0 i = That is, the proposed approach has a work complexity of O(N 2 ), which is higher than the complexity of the sequential scan which is O(N ) while offering no speedup. The higher work complexity means that much more execution resources need to be provisioned, which is obviously a bad idea. A better approach to parallel scan is to adapt the parallel reduction tree described in Chapter 10 to calculate each output element with a reduction tree on the relevant input elements. From what we learned in Chapter 10, the reader should realize that FIGURE 11.2 A parallel inclusive scan algorithm based on Kogge-Stone adder design. The heavy lines highlight the reduction tree for generating output element y15 .
using reduction trees requires that the scan operator to be associative, and even commutative depending on the optimizations used. There are multiple ways to design the reduction tree for each output element. Since the reduction tree for element i involves i add operations, this approach would still increase the work complexity to O(N 2 ) unless we find a way to share the partial sums across the reduction trees of different output elements. We present such a sharing approach that is based on the KoggeStone algorithm which was originally invented for designing fast adder circuits in the 1970s [4]. This algorithm is still being used in the design of high-speed computer arithmetic hardware today. The algorithm, illustrated in Fig. 11.2, is an in-place scan algorithm that operates on an array that originally contains input elements. It iteratively evolves the contents of the array into output elements. Before the algorithm begins, we assume that position i of the array contains input element xi . After k iterations, position i will contain the sum of up to 2k input elements at and before the location. For example, after one iteration, position i will contain xi−1 + xi and at the end of iteration 2, position i will contain xi−3 + xi−2 + xi−1 + xi , and so on. Fig. 11.2 shows the operations of the algorithm with a 16-element input example. Each vertical line represents an element of the array, with the 0th element in the FIGURE 11.3 A Kogge-Stone kernel for inclusive (per-block) scan.
leftmost position. The vertical direction shows the progress of iterations, starting from the top of the figure. For inclusive scan, by definition, y0 is x0 so position 0 already contains its final answer. In the first iteration, each position other than position 0 receives the sum of its current content and that of its left neighbor. This is illustrated by the first row of addition operators in Fig. 11.2. As a result, position i contains xi−1 + xi . This is reflected in the labeling boxes under the first row of addition operators in Fig. ∑︁ 11.2. For example, after the first iteration, position 3 contains x2 + x3 , shown as x2 ..x3 . Note that after the first iteration, position 1 contains x0 + x1 , which is the final answer for this position. So, there should be no further changes to position 1 in subsequent iterations. In the second iteration, each position other than positions 0 and 1 receives the sum of its current content and that of the position that is two elements to its left. This is illustrated in the labeled boxes below the second row of addition operators. example, after the As a result, position i now contains xi−3 + xi−2 + xi−1 + xi . For∑︁ second iteration, position 3 contains x0 + x1 + x2 + x3 , shown as x0 ..x3 . Note that after the second iteration, positions 2 and 3 have reached their final answers and will not need to be changed in subsequent iterations. The reader is encouraged to work through the rest of the iterations. Fig. 11.3 shows a kernel that implements the algorithm illustrated in Fig. 11.2. Since the parallel scan operation requires synchronization across participating threads, we will for now implement a kernel where each thread block performs a local parallel scan on a segment of the input. Later, in Section 11.9, we will discuss how to consolidate these scanned segments to produce a globally scanned output array for the entire input array. The size of the block’s segment is defined as a compile-time constant SEG_SIZE. We assume that the kernel function is called using SEG_SIZE as the block size so there will be the same number of threads as segment elements. We assign each thread to evolve the contents of one of the elements in the segment. The implementation shown in Fig. 11.3 assumes that input values were originally in a global memory array input, whose address is passed into the kernel as an argument (line 01). First, the threads in the block collaboratively load the segment of the input array that the block is responsible for into a shared memory array buffer_s (line 02). To do so, each thread calculates its global data index i = blockIdx.x*blockDim.x + threadIdx.x to find the position of the element it is responsible for evolving (line 03). Each thread then loads the input element at that position into the shared memory array (lines 04-08). At the end of the kernel, each thread writes its final result from the shared memory array to the output array output (lines 18-20). We now focus on the for-loop (lines 09-17) that executes the concurrent reduction trees for generating buffer_s elements. Similar to the implementation of the first version of the reduction tree in Chapter 10, the loop index is the stride which doubles every iteration. In every iteration, each thread adds the element that it is responsible for evolving to the element that is stride positions away to its left (line 13) and writes the result back at the thread’s position (line 16). When the stride value becomes greater than a thread’s threadIdx.x value, it means that the thread’s assigned buffer_s position has already accumulated all the required input values, and the thread no longer needs to be active (lines 12 and 15). Two barrier synchronizations are needed in the loop to ensure that there are no race conditions. The first barrier synchronization (line 10) ensures that all threads have finished writing the values they calculated to buffer_s in the previous iteration before other threads read them in the current iteration. The second barrier synchronization (line 14) ensures that all threads have finished reading their input values from buffer_s before other threads overwrite them. The control divergence introduced by the conditions on lines 12 and 15 is quite modest. When the stride values are smaller than the size of a warp, only threads in the first warp drop out causing only the first warp to exhibit control divergence. For large thread blocks with many warps, the impact of this divergence is hardly felt. Once the stride reaches and exceeds the size of a warp, entire warps drop out from the first half of the thread block resulting in no control divergence. The first barrier synchronization on line 10 is the same use of __syncthreads() as in the reduction kernel implemented in Chapter 10. However, the second barrier synchronization is not needed in the reduction kernel and is only needed in the scan kernel. Let us further examine why we would have a race condition if we did not have the second barrier. In each loop iteration, each active thread adds the buffer_s value at its own position (buffer_s[threadIdx.x]) and that at a position of another thread (buffer_s[threadIdx.x-stride]). If a thread i writes to its output position before the thread i + stride reads the old value at that position, the new value would corrupt the addition performed by thread i + stride. For example, in Fig. 11.2, let us examine the activities of thread 4 and thread 6 during iteration 2, which is represented as the addition operations in the second row from the top. Thread 6 needs to add the old value of buffer_s[4] (x3 + x4 ) to the old value of buffer_s[6] (x5 + x6 ) to generate the new value of buffer_s[6] (x3 + x4 + x5 + x6 ). However, if thread 4 stores its addition result for the iteration (x1 + x2 + x3 + x4 ) into buffer_s[4] too early, thread 6 could end up using the new value as its input and store (x1 + x2 + x3 + x4 + x5 + x6 ) into buffer_s[6]. Since x1 + x2 will be added again to buffer_s[6] by thread 6 in the third iteration, the final answer in buffer_s[6] will become (2x1 + 2x2 + x3 + x4 + x5 + x6 ), which is obviously incorrect. On the other hand, if thread 6 happens to read the old value in buffer_s[4] before thread 4 overwrites it during iteration 2, the results would be correct. That is, the execution result of the code may or may not be correct depending on the timing of thread execution and the execution results can vary from run to run. Such lack of reproducibility can make debugging a nightmare. The race condition is overcome in Fig. 11.3 with the temporary variable temp used in line 13 and the __syncthreads() barrier in line 14. In line 13, all active threads first perform addition and write into their private temp variables. Therefore, none of the old values in buffer_s locations will be overwritten. The barrier __syncthread() in line 14 ensures that all active threads have completed their read of the old buffer_s values before any of them can move forward and perform a write. Thus, it is safe for the statement in line 16 to overwrite the buffer_s locations. The reader may wonder why the reduction tree kernels in Chapter 10 did not need to use a second __syncthreads(). The answer is that the elements written to by the active threads in an iteration are not read by any of the other active threads during the same iteration. This should be apparent by inspecting Figs. 10.6 and 10.7. For example, in Fig. 10.7, each active threads takes its inputs from its own position (input[threadIdx.x]) and a position that is of stride distance to the right (input[threadIdx.x+stride]). None of the stride-distance positions are updated by any active threads during any given iteration. Therefore, all active threads will always be able to read the old value of their respective input[threadIdx.x] safely. The reader should verify that the same property holds in Fig. 10.6. In contrast, in the parallel scan kernel, the reason why a buffer_s position being written to may be read by another active thread is because of the interaction between the concurrent reduction trees being executed. In particular, the Kogge-Stone approach reuses the partial sums across reduction trees to reduce the computational complexity. We will further study this point in Section 11.5.
11.3 Double-buffering to reduce synchronization
One of the main bottlenecks in the parallel scan kernel that we implemented in Fig. 11.3 is the overhead of barrier synchronization. Every loop iteration must perform two calls to __syncthreads() to order concurrent memory accesses to avoid race conditions. However, we observe that these two barriers do not enforce the same kind of memory access ordering. The first barrier (line 10) ensures that all threads finish writing their computed values before other threads read them. In other words, it enforces a true dependence. On the other hand, the second barrier (line 14) ensures that FIGURE 11.4 Double buffering applied to Kogge-Stone parallel scan.
all threads finish reading the values they need before other threads overwrite them. In other words, it enforces a false dependence. Recall from Chapter 6 that we can eliminate barrier synchronizations that enforce false dependences via double-buffering. In general, we can avoid overwriting values that are being read in the same iteration by using different memory buffers to store the loop iteration’s input values and its output values. One way to do so is to allocate a different output buffer for each iteration, which is also the input buffer to the next iteration. However, this approach would require a large amount of shared memory resources. Alternatively, we observe that once the output values of an iteration have been computed, the input values to that iteration are no longer needed. Hence, the input buffer of an iteration can be recycled and used as the output buffer of the next iteration. Overall, it is sufficient to allocate two buffers in total that keep trading places as the input and output buffers. Fig. 11.4 illustrates how double-buffering can be applied to parallel scan. We use two shared memory buffers called buffer1 and buffer2. Initially, we load the input elements from the global memory to buffer1. Next, in iteration 0, we read the values from buffer1, perform the addition, and write the sums to buffer2. Note that if we would be read by thread 2 from did not use two different buffers, then the value x1 ∑︁ the same location where thread 1 writes its result∑︁ x1 ..x2 , so a barrier would be needed to make sure that thread 1 does not write x1 ..x2 before thread 2 reads x1 . However, since we are using∑︁two different buffers, the synchronization is not needed because thread 1 is writing x1 ..x2 to buffer2, whereas thread 1 is reading x1 from buffer1. After iteration 0 is over, buffer2 has the most up-to-date results and the values in buffer1 are no longer needed. Hence, in iteration 1, we use buffer2 as our input buffer and write our results to buffer1. Following the same reasoning, in the third iteration, we read from buffer1 and write to buffer2. We alternate the input and output buffers until the iterations complete. An important observation in Fig. 11.4 is that since we are using different buffers for input and output, the values that are complete and are no longer evolving (e.g., FIGURE 11.5 A Kogge-Stone kernel for inclusive (per-block) scan with double-buffering applied.
x0 in iteration 0) are no longer retained automatically. They need be explicitly copied from the input buffer to the output buffer. Hence, the threads responsible for evolving these values (e.g., thread 0 in iteration 0), which became inactive in the original kernel, are now responsible for copying the values they are evolving from the input buffer to the output buffer. For example, in iteration 0, thread 0 is responsible for copying x0 from position 0 in buffer1 to position 0 in buffer2. Fig. 11.5 shows the kernel code for parallel scan with the double-buffering optimization applied. Like the kernel in Fig. 11.3, each thread first identifies the position in the input array that it is responsible for evolving (line 02). Next, two shared memory buffers, buffer1_s and buffer2_s, are created instead of just one (lines 03-04). Moreover, two pointers, inBuffer_s and outBuffer_s, are created to assist with swapping the two buffers each iteration (lines 05-06). They are initialized to point to buffer1_s and buffer2_s, respectively, which are to be the input and output buffers, respectively, in the first iteration. After that, each thread loads the input value it is responsible for evolving from the global memory to the input buffer in shared memory (line 07). Next, we begin the main loop for executing the Kogge-Stone algorithm (lines 08-19). The loop header (line 08) is the same as the kernel in Fig. 11.3, and the condition for the threads responsible for performing an addition (line 10) is also the same. However, an important difference is that the threads involved in the addition do not read and write the same buffer, but instead, they load their input values from inBuffer_s and write their computed sum to outBuffer_s (lines 11-12). Meanwhile, the threads not involved in the addition simply copy their value from the input buffer to the output buffer (line 14). At the end of the loop body, the input buffer and the output buffer are swapped (lines 16-18).
11.4 Warp-level primitives to reduce synchronization
Notice that the loop in Fig. 11.5 only contains one call to __syncthreads() (line 09). This call enforces the true dependence whereby threads wait for their input values to be written by other threads in the previous iteration before they read them. The second __syncthreads() is no longer needed because all reads are happening from inBuffer_s and all writes are happening to outBuffer_s, so there is no write-after-read (false) dependence.
While the overhead of barrier synchronization is reduced by double-buffering, it remains substantial. In the kernel in Fig. 11.5, every loop iteration calls __syncthreads() in conjunction with just a single floating point addition. Moreover, every loop iteration also performs three accesses to shared memory. It is clear that the performance of the loop is dominated by barrier synchronizations and shared memory accesses. Recall from Chapter 10 that one way to reduce the overhead of barrier synchronizations and shared memory accesses is to leverage warp-level primitives, which allow threads within the warp to synchronize and share data much more efficiently than threads across an entire block. Hence, to reduce the overhead of barrier synchronizations and shared memory accesses for parallel scan, we can decompose our computation across multiple warps to take advantage of warp-level primitives. In particular, we can allow each warp to perform its own local scan on the segment belonging to the threads in the warp, then combine the results to yield a scanned segment for the entire block. One way to decompose a scan operation into multiple smaller scan operations is using the scan-scan-add decomposition. The scan-scan-add decomposition divides the scan operation into three stages: a scan operation on smaller segments, a scan operation on the sums of the segments, and an add operation that updates each segment with the sum of previous segments. Fig. 11.6 shows a small example of the scan-scanadd decomposition. In this example, the input has 16 elements and is decomposed into four segments with four elements each. In the first stage, each segment is scanned independently. After this stage, each element contains the scan result within its segment. For example, the second segment has inputs 0, 4, 1, 2. The first scan stage produces the scan result for this segment, which is 0, 4, 5, 7. Note that these results do not contain the contributions from any of the elements in the previous segment. To produce the final result for this segment, the sum of all elements in the previous segment, 2 + 1 + 3 + 1 = 7, should be added to every result element of the segment. As another example, the inputs of the third segment are 0, 3, 1, 2. After the first scan stage, the scanned segment values are 0, 3, 4, 6. In order to produce the final results for this segment, the sum of all elements in the two previous segments, 2 + 1 + 3 + 1 + 0 + 4 + 1 + 2 = 14, should be added to every result. After the first scan stage, the last element of each scanned segment gives the sum of all input elements of that segment. These values are 7, 7, 6, and 11 for the four FIGURE 11.6 An example of the scan-scan-add decomposition.
segments in Fig. 11.6. This brings us to the second stage of the scan-scan-add decomposition, which gathers the last result from each segment into an array of sums and performs a scan operation on those sums. The result of that second scan operation is an array of scanned sums: 7, 14, 20, 31. Note that each of these values is the accumulated sum from the first element in the original input to the end of the corresponding segment. That is, the first value 7 is the accumulated sum from the first input element to the end of the first segment. The second value 14 is the accumulated sum from the first input element to the end of the second segment. Therefore, the values in the array of scanned sums give the scan results at strategic locations of the original scan problem. That is, scanned sums at indices 0, 1, 2, and 3 give the final scan results for the original input at positions 3, 7, 11, and 15, respectively. These results can be used to bring the partial results in each segment to their final values. This brings us to the last step of the scan-scan-add decomposition in Fig. 11.6. The scanned sums are added to the values of their subsequent segments. For example the first scanned sum 7 is added to all the elements in the second segment, which completes them. The final results of the second segment are 7, 11, 12, 14. As another example, the second scanned sum 14 is added to the elements of the third segment, which completes them. These final results are 14, 17, 18, and 20. Similarly, the third scanned sum 20 is added to the elements of the fourth segment, which completes them. The fourth scanned sum 31 is the sum of all elements of the original input, which is also the final result in the last element. Having seen how to decompose a scan operation into multiple smaller scan operations, we now apply this decomposition in the context of decomposing a block-level scan operation across multiple warps. Fig. 11.7 shows how a block-level scan can be decomposed into warp-level scans using the scan-scan-add decomposition. On the top of the figure, we start with the block’s input segment that has already been loaded from global memory. Next, every warp performs a warp-level scan on the warp’s FIGURE 11.7 Decomposing a block-level scan into warp-level scans using the scan-scan-add decomposition.
contiguous subsegment of the block’s segment. Once we have scanned the warp subsegments, we still need to add the sum of all the elements belonging to the preceding warps to complete the block’s scanned segment. To do so, we observe that the last thread of each warp has the sum of all the elements belonging to the warp. Therefore, we can have this thread write that sum to a shared memory array of warp sums, i.e., the sums of the elements in each warp. Next, we have a single warp perform a warplevel scan on these warp sums. The result is an array that has, for each warp, the sum of the elements belonging to it and all preceding warps. These values are the values we would like to add to the warp subsegments. Accordingly, we have each warp load the value that represents the sum of all previous warps’ values and add that value to all its own scanned elements, which yields the scanned block segment. We are now ready to show how this approach can be implemented in code. We start by showing how a warp-level scan can be executed by a warp. Fig. 11.8 shows a device function that performs a parallel warp-level scan using the Kogge-Stone approach. The device function takes a parameter val that contains the value the thread in the warp is responsible for evolving (line 01). Similar to the codes in Figs. 11.3 and 11.5, the loop starts at stride one, and doubles it until it reaches the size of the segment being scanned, which in this case is the size of the warp (line 02). In each iteration, the thread obtains the value owned by the thread that is stride to its left. In this case, the value is obtained using a shule-up instruction (line 03), so no shared memory accesses or barrier synchronizations are needed. Once each thread has obtained the value it needs, it adds it to its own value (line 05). Similar to the codes in Figs. 11.3 and 11.5, only the threads whose indices are at least the stride value participate in the addition (line 04). However, we cannot use threadIdx.x as the index in the condition because we are doing a warp-level scan, so we need the thread’s index FIGURE 11.8 A device function that performs a warp-level scan using warp-level primitives.
FIGURE 11.9. A device function that performs a block-level scan using the scan-scan-add decomposition and the warp-level scan.
within the warp, i.e., its lane index. To obtain the thread’s index in the warp, we call a device function laneIdx() which is defined in Chapter 10. After the loop is finished, the device function returns val which contains each thread’s evolved value after the wap-level scan is complete. Having written a warp-level scan operation, our next step is to write the blocklevel scan operation that uses it. Fig. 11.9 shows a device function that performs a block-level scan using the scan-scan-add decomposition and the warp-level scan. The device function takes a parameter val that contains the value the thread in the block is responsible for evolving (line 01). The first step is for each warp to perform its own warp-level scan (line 03). Next, the last thread in each warp (line 06) writes its warp’s sum to a shared memory array (line 07). Here, the array is indexed with the warp’s index within the block, which is obtained by calling the device function warpIdx() which is defined in Chapter 10. A barrier synchronization ensures that all FIGURE 11.10 A block-level kernel that uses the block-level scan function which uses the warp-level scan.
11.5 Work efficiency considerations
warps have written their sums to the shared memory (line 09). After that, the first warp (line 11) has each thread load one of the warp sums (line 12) and performs a warp-level scan on the warp sums (line 13). The scanned warp sums are then written to shared memory (line 15) and a barrier synchronization ensures that all the other warps wait for this first warp to finish (line 18). Finally, all the threads except those in the first warp (line 20) read the sum of all the preceding warps’ elements from shared memory and add it to their own value (line 21). The value is finally returned (line 23). An important distinction between the code in Fig. 11.9 and the code in Fig. 11.5 is the number of barrier synchronizations and shared memory accesses performed. The code in Fig. 11.5 performs barrier synchronizations and shared memory accesses in every loop iteration. On the other hand, the code in Fig. 11.5 only performs barrier synchronizations and shared memory accesses on two occasions: once between the first warp-level scan stage and the second warp-level scan stage, and once between the second warp-level scan stage and the final addition stage. Having written the block-level scan function, the block-level scan kernel is quite simple as shown in Fig. 11.10. Every thread identifies the element it is responsible for evolving (line 02), loads it from global memory (line 03), calls the block scan function (line 04), then writes the final value back to global memory.
One important consideration when analyzing parallel algorithms is work efficiency. The work efficiency of an algorithm refers to the extent to which the work performed by the algorithm is close to the minimum amount of work needed for the computation.1 For example, the minimum number of additions required by the scan operation is N − 1 additions, or O(N ), which is the number of additions that the sequential algorithm performs. However, as we saw in the beginning of Section 11.2, the naïve parallel algorithm performs N ·(N2 −1) additions, or O(N 2 ), which is substantially larger than the sequential algorithm. For this reason, the naïve parallel algorithm is not work efficient. 1 The minimum amount of work for the computation is empirically defined by the minimum amount ofwork performed among all known algorithms.
Let us analyze the work efficiency of the Kogge-Stone parallel scan algorithm illustrated in Fig. 11.2. Let N be the number of elements in the segment being scanned. We observe that the algorithm iterates for log2 N steps. In each step, out of a total of N threads, the number of inactive threads is equal to the stride, which means that the number of active threads is N − stride. Each active thread performs one addition operation. Therefore, we can calculate the amount of work done for the algorithm as ∑︁ stride (N − stride), for stride = 1, 2, 4, · · · N/2 (log2 N terms) The first part of each term is independent of stride, its summation adds up to N · log2 N. The second part is a familiar geometric series and sums up to N − 1. Hence, the total amount of work done by the computation is: N · log2 N − (N − 1) When executed on a real CUDA GPU device, the amount of resources consumed by the Kogge-Stone parallel algorithm is even more than the theoretical N · log2 N − (N − 1). This reason is that while many of the N threads stop participating in later iterations, some of them still consume execution resources until the entire warp that they are part of completes execution. Hence, the amount of execution resources consumed by the Kogge-Stone parallel algorithm is closer to N · log2 N. Either way, the work complexity of the Kogge-Stone approach is O(N · log2 N ). The good news is that the work complexity of the Kogge-Stone approach is better than the O(N 2 ) complexity of the naïve approach that performs sequential reductions for all the output elements. The bad news is that the Kogge-Stone algorithm is still not as work efficient as the sequential algorithm which performs O(N ) operations. Even for modest sized sections, the parallel algorithm does much more work than the sequential algorithm. For example, in the case of 512 elements, the algorithm does between eight and nine times more work than the sequential code. Although the Kogge-Stone algorithm performs more computations than the sequential algorithm, it does so in fewer steps because of parallel execution. The loop of the sequential code executes N iterations, which means that the sequential algorithm has a time complexity of O(N ). As for the kernel code, the loop(s) execute up to log2 N iterations, which means that the parallel implementation has a span of O(log N ). With unlimited execution resources, the reduction in the number of steps of the kernel code over the sequential code would be approximately N/ log2 N. For N = 512, the reduction in the number of steps would be about 512/9 = 56.9×. We will use the concept of steps as an approximate indicator for comparing between scan algorithms. The sequential scan should take approximately N steps to process N input elements. For example, the sequential scan should take approximately 1024 steps to process 1024 input elements. With P execution units in the CUDA device, we can expect the Kogge-Stone kernel to execute for (N · log2 N )/P steps. If P was equal to N, i.e., if we had enough execution units to process all input element in parallel, then we need log2 N steps as we saw earlier. However, P could be smaller than N. For example, if we use 1024 threads and 32 execution units to process 1024 input elements, the kernel will likely take (1024 ∗ 10)/32 = 320 steps.
11.6 Coarsening to improve work-eiciency
In this case, we expect to achieve a 1024/320 = 3.2× reduction in the number of steps. The additional work done by the Kogge-Stone kernel over the sequential code is problematic in two ways. First, the use of hardware for executing the parallel kernel is much less efficient. If the hardware does not have enough resources (i.e., if P is small), the parallel algorithm could end up needing more steps than the sequential algorithm and the parallel algorithm will be slower. Second, even if the kernel is faster, the extra work done consumes additional energy. This makes the kernel less appropriate for power-constrained environments such as mobile applications.
We have seen in Section 11.5 that the main overhead of parallelizing scan is the reduction in work efficiency. We also saw that with enough execution resources, this overhead is worth paying because of the reduction in the span of the execution. However, with constrained execution resources where the hardware begins to serialize the execution of threads, the overhead is incurred unnecessarily. Instead, we can serialize some of the work ourselves with thread coarsening, thereby reducing the parallelization overhead of the kernel and improving its work efficiency. To apply thread coarsening to scan, we need to assign each thread to perform a work efficient sequential scan of multiple input elements before the threads collaborate to perform the parallel scan. We can do so by using the scan-scan-add decomposition to decompose the scan operation into independent thread-level scans. Fig. 11.11 illustrates how thread coarsening can be applied to parallel scan using the scan-scan-add decomposition. On the top of the figure, we start with the block’s input FIGURE 11.11 Applying thread coarsening to parallel scan using the scan-scan-add decomposition.
FIGURE 11.12. A parallel scan kernel with thread coarsening applied using the scan-scan-add decomposition.
segment that has already been loaded from global memory to shared memory. The number of elements in this block segment is greater than the number of threads in the block by some factor which is the coarsening factor. We partition the block’s segment into multiple contiguous subsegments, one for each thread. Next, every thread performs a sequential scan of its subsegment, which is work efficient. Once we have scanned the thread subsegments, each thread uses its last value, which represents the sum of all the elements owned by the thread, and participates in a block-level scan. After the block-level scan, each thread obtains the value that represents the sum of all previous threads’ values and adds that value to all its own scanned values, which yields the scanned block segment. Fig. 11.12 shows the code for a parallel scan kernel with thread coarsening applied using the scan-scan-add decomposition. We define a constant COARSE_FACTOR that determines the coarsening factor, i.e., the number of elements assigned to each thread. We also define the block dimension as a constant BLOCK_DIM for convenience. The size of the segment owned by a single block is therefore COARSE_FACTOR*BLOCK_DIM.
The code in Fig. 11.12 starts by identifying the location of the segment the block is responsible for by multiplying the block index with the segment size (line 02). Next, a shared memory buffer for storing the segment is declared (line 04) and the segment is loaded from global memory to shared memory (lines 05-09). Importantly, although each thread needs to load COARSE_FACTOR input elements from global memory to shared memory, we do not have each thread load the contiguous subsegment it owns because doing so would lead to uncoalesced accesses. For example, if our coarsening factor was four, then during the first iteration of block 0, thread 0 would access input element 0, thread 1 would access input element 4, thread 2 would access input element 8, etc, which are not contiguous. Instead, we transfer data from global memory to shared memory in a coalesced manner by dividing the block’s segment into COARSE_FACTOR contiguous chunks that are each BLOCK_DIM in size and loading them one chunk at a time (lines 05-08). For example, if our coarsening factor was four, then during the first iteration of block 0, thread 0 loads element 0, thread 1 loads element 1, thread 2 loads element 2, etc. Finally, a barrier synchronization (line 09) ensures that the whole segment is loaded before threads proceed to access their subsegments. Once the block segment is in shared memory, each thread identifies the location of its subsegment by multiplying its index with the size of the subsegment (line 11). Next, each thread performs a sequential scan operation (lines 12-14) similar to that in Fig. 11.1. Next, each thread loads its final scanned value, which represents the sum of all elements owned by the thread (line 16), and passes it to the blockSum device function from Fig. 11.9, which performs a block-level scan of the thread sums (line 17). Next, the threads place their scanned thread sums in shared memory (lines 1920) and perform a barrier synchronization to ensure that the other threads can read them (line 21). With the scanned thread sums now available, all threads except the first one (line 23) load the scanned thread sum of the previous thread (line 24) which represents the sum of all the elements owned by the preceding threads. Each thread then iterates through its subsegment and adds the sum to all the values it owns (line 25-27). The scanned block segment is now complete in shared memory. The final step is to store the scanned block segment from shared memory to global memory. Similar to the concerns when loading the input block segment, we cannot have each thread store the subsegment it owns because the stores would not be coalesced. Instead, the threads execute a barrier synchronization to ensure that all threads finish computing their subsegments (line 29). Finally, we divide the output segment into COARSE_FACTOR contiguous chunks that are each BLOCK_DIM in size and store them one chunk at a time (lines 31-34). Let us now analyze the work efficiency of parallel scan after thread coarsening is applied. Assume that we are scanning N input elements using P workers (i.e., threads). With coarsening, each of the P threads performs a sequential scan of N/P elements, which is a total of P · (N/P − 1) = N − P operations. Next, the P thread sums are scanned in parallel which requires P · log2 P operations. Finally, each of the P threads except the first adds the scanned thread sums to its N/P scanned values, which requires (P − 1) · N/P = N − N/P operations. Overall, the number ofoperations performed with thread coarsening is 2N + P · log2 P − P − N/P . Hence, when P is large and close to N, the number of operations is O(N · log2 N ) which is similar to the parallel implementation without coarsening. However, when P is much smaller than N, the number of operations is closer to N and is O(N ) like the sequential implementation. This analysis shows that thread coarsening substantially improves the parallel scan work efficiency when the number of execution resources is significantly smaller than the number of input elements. The improvement in work efficiency also impacts the number of steps performed. With coarsening, each thread performs a sequential scan of N/P elements which takes N/P − 1 steps. Next, the P thread sums are scanned in parallel which takes log2 P steps. Finally, the threads add the scanned thread sums to their scanned values which takes N/P steps. Overall, the approach with thread coarsening requires 2N/P + log2 P − 1 steps. Recall that without thread coarsening, the number of steps 2N . Hence, when P is large and close to N, both approaches is approximately N ·log P take O(log2 N ) steps. However, when P is much smaller than N, the approach with2N out thread coarsening takes approximately N ·log steps, while the approach with P 2N thread coarsening takes approximately P steps, which is a substantial improvement. Thread coarsening has other benefits to parallel scan besides improving work efficiency. The parallel block-level scan needs to perform barrier synchronization and incurs modest control divergence, whereas the sequential thread-level scan does not. When we move more operations from the parallel block-level scan to the sequential thread-level scan, we reduce the impact of the barrier synchronization and control divergence overhead on overall performance. This benefit is similar to the benefit we see from applying thread coarsening to the reduction kernel in Chapter 10. Yet another benefit of thread coarsening will become more apparent in Section 11.9. Recall that so far we have been implementing a scan kernel where each thread block scans its own segment, and we have deferred the discussion on how to consolidate the results of different blocks to Section 11.9. When we apply thread coarsening to scan and assign each thread to multiple input elements, one way we can do that is by keeping the size of the block segment the same and reducing the number of threads in the block by the coarsening factor. Another approach is to keep the number of threads in the block the same and increase the size of the block segment by the coarsening factor. The latter approach would in turn reduce the number of thread blocks by the coarsening factor. Reducing the number of thread blocks participating in the global scan operation is favorable when we need to consolidate the segments of the different thread blocks. We will revisit this point in Section 11.9.
11.7 Register tiling to avoid shared memory access latency
In the kernel in Fig. 11.12, the subsegments owned by each thread were placed in shared memory. Hence, whenever a thread needs to access its subsegment’s elements, it must access shared memory. Since the elements of a thread’s subsegment are private to the thread and are not needed by other threads, it is wasteful for the thread FIGURE 11.13 A parallel scan kernel with register tiling applied to thread subsegments.
to repeatedly load and store the elements of its subsegment from and to the shared memory. Instead, we can apply register tiling where the thread places the elements of its subsegments in registers and repeatedly accesses them from there. Fig. 11.13 shows a parallel scan kernel with register tiling applied to the thread subsegments. Most of the kernel resembles the kernel that applies thread coarsening in Fig. 11.12. The key differences are as follows. We declare a local array buffer_r that is used to store the thread’s subsegment (line 12). As we scan the thread’s subsegment, the first time we load it from shared memory, we keep it in the local array (lines 13 and 16). Subsequent accesses to the thread’s subsegment are made using the local array (lines 16, 19, and 29). Finally, as we add the preceding threads’ sum, we return the thread’s subsegment to shared memory (line 29). Note that all the loops that iterate over buffer_r are annotated with #pragma unroll (lines 14 and 27) to ensure that the compiler unrolls the loops. Recall from Chapter 6 that loop unrolling ensures that the local array is accessed with a constant index and can therefore be promoted to a register. In practice, the compiler most likely unrolls the loops in the kernel without needing this annotation. However, the annotation is a useful reminder to the reader that the loop is intended to be unrolled. It is noteworthy that the kernel still loads the thread subsegments to shared memory (line 06) before loading them to the register tile (lines 13 and 16), and stores the thread subsegments to shared memory (line 29) before storing them to global memory (line 34). The reason shared memory is still retained as an intermediary is that if a thread were to transfer data between global memory and its register tile directly, the accesses would not be coalesced. Hence, this kernel uses shared memory not for the purpose of tiling since the data in shared memory is not reused. The kernel uses shared memory just to enable coalesced accesses to global memory. This optimization is similar to the corner turning optimization discussed in Chapter 6. There are still additional optimizations from the checklist in Chapter 6 that we can apply to the scan kernel in Fig. 11.13. First, since each thread is responsible for loading multiple elements from global memory to shared memory (lines 05-08 in Fig. 11.13) and storing multiple elements from shared memory to global memory (lines 33-36 in Fig. 11.13), the threads can use vector loads and stores instead of scalar ones. Second, when threads access their thread segments in shared memory (lines 13 and 29 in Fig. 11.13), the strided access pattern can cause bank conflicts. These bank conflicts can be eliminated by adding padding to the shared memory array, as described in Chapter 6. We leave these optimizations as an exercise to the reader.
11.8 Memory bandwidth considerations
A scan operation on an array of N floating point elements loads N floating point values (or 4 · N bytes) from memory, performs N − 1 floating point additions, and stores N floating point values (or 4 · N bytes) to memory. Hence, the arithmetic intensity of the scan operation is OP/B. Recall from Chapter 5 that the NVIDIA H100 GPU has a peak floating point throughput of 66.9 TFLOPS and a peak global memory bandwidth of 3.35 TB/s, thereby requiring a computation to perform at least FLOP/B to be compute-bound. Clearly, the arithmetic intensity of the scan operation is well below this threshold, making scan a highly memory-bound computation. For memory-bound computations, the peak memory bandwidth sets the limit for the peak performance achievable by a computation. On an NVIDIA H100 GPU with a peak global memory bandwidth of 3.35 TB/s, since scan needs to access at least 8 B of global memory for every element it scans, the peak performance of a scan operation is elements/s. In other words, the fastest possible scan kernel cannot scan more than 419 billion elements per second on an NVIDIA H100 GPU. Achieving this elements/s target would require the kernel to use the memory bandwidth perfectly, accessing each global memory location only once and hiding the latency of all the other compute, synchronization, and shared memory access operations behind the global memory accesses. In practice, such perfect utilization of the memory bandwidth is hard to achieve. Even a kernel that simply copies data from one array to another without performing any computations or synchronization cannot achieve an absolute 100% utilization of the global memory bandwidth. Typically, a memory-bound kernel that achieves > 80% utilization of global memory bandwidth without having redundant global memory accesses is considered to be well-optimized. The scan kernel that we have implemented so far in Fig. 11.13 does not perform any redundant global memory accesses, and is thoroughly optimized to limit the overhead of computation, synchronization, and shared memory accesses. Accordingly, this kernel can hide most of the work it performs behind the global memory accesses and achieve > 80% utilization of the global memory bandwidth. However, recall that this kernel only performs local scans, where each thread block scans a block segment that it owns. Consolidating the block segments into a global scanned segment requires more global memory accesses and synchronization overhead, which poses a challenge for retaining the kernel’s global memory access efficiency. We look deeply at this issue in Section 11.9.
11.9 Consolidating block segments for a global scan
The kernels presented so far perform block-wide scans on segments of the input. For some applications, a block-wide scan may be all we need. However, for other applications, the number of elements to be processed by a scan operation can be in the millions or even billions. For such applications, we need to perform a grid-wide scan using multiple thread blocks, and we need a way to consolidate the different block segments. One way to decompose a grid-wide scan across multiple thread blocks is to use the scan-scan-add decomposition, as illustrated in Fig. 11.14. On the top of the figure, we start with the global input to be scanned. We partition the input into multiple contiguous segments that can each be processed by a single thread block. Next, every thread block scans its segment using one of the kernels we have seen so far, such as the most optimized kernel in Fig. 11.13. Once we have scanned the block segments, each block contributes its last value, which represents the sum of all the elements owned by the block, to a global inter-block scan. After the inter-block scan, each thread obtains the value that represents the sum of all previous blocks’ values and adds that value to all its own scanned values, which yields the final globally scanned output. The main challenge with this strategy is how to perform the inter-block scan, which requires synchronization across the thread blocks after they finish their local scans. A simple approach to perform the inter-block scan is to use separate kernel calls for each of the three stages. In other words, we call a first kernel to perform the local scan of the block segments, a second kernel to scan the block sums using a single thread block, and a third kernel to add the scanned block sums.
FIGURE 11.14. Decomposing a global scan into block-level scans using the scan-scan-add decomposition.
The main drawback of this three-kernel approach is that the intermediate scanned values need to be written to and read from global memory between kernel calls. In particular, when scanning N elements, the first kernel which performs the local scans loads N elements from global memory and stores N elements to global memory. The second kernel which scans the block sums loads elements from global memory and stores elements to global memory, where S is the number of elements per block segment. The third kernel which adds the scanned block sums loads N elements from global memory and stores N elements to global memory. Overall, the three-kernel approach accesses a total of elements, or bytes. For a very large where is negligible, the three-kernel approach accesses bytes to scan N elements, or 16 B per element. On an NVIDIA H100 GPU with a peak global memory bandwidth of 3.35 TB/s, the peak performance of this approach is elements/s. This peak performance is half the peak performance of an ideal scan implementation which was found in Section 11.8 to be elements/s. Intuitively, this approach can only achieve half the performance of the ideal implementation because it performs twice the number of global memory accesses due to the need to store all N intermediate values at the end of the first kernel and load them back at the beginning of the third kernel. To avoid performing such a large number of global memory accesses, let us explore alternative strategies for decomposing a global scan across multiple thread blocks. One alternative decomposition is the reduce-scan-scan decomposition which has three stages: a reduce stage followed by two scan stages. Fig. 11.15 illustrates the reduce-scan-scan decomposition applied to decomposing a grid-wide scan across multiple thread blocks. On the top of the figure, we start with the global input to be FIGURE 11.15 Reduce-scan-scan decomposition of a global scan into block-level scans.
scanned and partition it to multiple contiguous segments each processed by a different thread block. Every thread block starts by performing a reduction operation on its segment using a reduction kernel similar to those implemented in Chapter 10. Next, each block contributes the sum it computed to a global inter-block scan. After the inter-block scan, each thread block adds the sum of all previous blocks’ values to the first element in its block segment, then performs a scan of the block segment yielding the final globally scanned array. Similar to the scan-scan-add decomposition, the reduce-scan-scan decomposition also requires an inter-block scan step. Again, a simple approach for performing the inter-block scan is to use a three-kernel approach: the first kernel to reduce the block segments, the second kernel to scan the block sums using a single thread block, and the third kernel to perform the local scans. However, when applying the three-kernel approach to the reduce-scan-scan decomposition, the number of global memory accesses is not as high. In particular, when scanning N elements, the first kernel which performs the reduction loads N elements from global memory and stores elements to global memory, where S is the number of elements per block segment. The second kernel which scans the block sums loads elements from global memory and stores elements to global memory. The third kernel which performs the local scans loads N elements from global memory and stores N elements to global memory. Overall, the three-kernel approach with the reduce-scan-scan decomposition accesses a total of elements, or bytes. For a very large where is negligible, the three-kernel approach with the reduce-scan-scan decomposition accesses bytes to scan N elements, or 12 B per element. On an NVIDIA H100 GPU with a peak global memory bandwidth
of 3.35 TB/s, the peak performance of this approach is elements/s. This peak performance is two-thirds the elements/s peak performance of the ideal scan implementation, which is better than the three-kernel approach with the scan-scan-add. Intuitively, the three-kernel approach with the reduce-scan-scan decomposition avoids having to store N elements at the end of the first kernel, but still needs to load N elements at the beginning of the third kernel. An important consideration when using the reduce-scan-scan decomposition is operator commutativity. So far, all our parallelization and optimization strategies for scan have only assumed that the scan operator is associative. However, some optimizations for the reduction pattern in Chapter 10 also assumed that the operator is commutative. Therefore, when implementing the reduce-scan-scan decomposition, we must be careful about which implementation of reduction to use depending on whether or not the scan operator is commutative. After seeing that the reduce-scan-scan decomposition outperforms the scan-scanadd decomposition in this context, the reader may wonder if the reduce-scan-scan decomposition would also perform better when decomposing the block-wide scan across warps in Section 11.4 and across threads in Section 11.6. To answer this question, let us compare the two decomposition strategies more closely. Both strategies have two scan operations. They key difference is that one has an add operation while the other has a reduce operation. The advantage of the reduce operation over the add operation is that it writes to fewer outputs. On the other hand, the advantage of the add operation over the reduce operation is that it does not need to perform multiple steps with intermediate synchronization to execute a reduction tree. When decomposing the global computation across blocks, our primary concern is to limit accesses to the array elements in global memory. Hence, the reduce operation which performs fewer accesses is more favorable. On the other hand, when decomposing the block-wide scan across warps or threads, the elements are already in the registers. Accessing the elements more frequently from the registers in the add operation is much cheaper than the synchronization overhead incurred by the reduce operation. Accordingly, the scan-scan-add decomposition is better when decomposing the block-wide scan across warps and threads. Although the three-kernel approach with the reduce-scan-scan decomposition accesses fewer bytes in global memory than with the scan-scan-add decomposition, it still falls short from the ideal scan implementation because of the need to load the input from global memory twice. To come closer to ideal performance, we must load the entire input array only once and store the entire output array only once, which cannot be achieved with a multi-kernel implementation. For this reason, we need to use an alternative method for the inter-block scan that does not involve terminating a kernel and calling a new one [5–7]. Fig. 11.16 shows three alternative methods for implementing an inter-block scan without terminating the kernel and calling a new one. The first method, illustrated in Fig. 11.16(a), requires all thread blocks to share their sums with one thread block, such as block 0, which scans the block sums and redistributes the scanned sums. This method would require all the thread blocks in the grid to perform grid-wide barrier FIGURE 11.16 Alternative methods of inter-block scan within a single kernel.
synchronizations before and after block 0 performs the scan operation. Such a gridwide barrier synchronization can be done using cooperative groups, as we will see in Chapter 18. However, it requires that all thread blocks in the grid run simultaneously, which limits the number of thread blocks that can be configured. Since each thread block has a limit on the size of the block segment it can scan due to the limited shared memory and register capacity in an SM, the limit on the number of thread blocks limits the total size of the array that can be scanned with this method. More importantly, grid-wide barrier synchronizations are very expensive operations, and this method requires performing it twice. The second method, shown in Fig. 11.16(b), involves passing sums from one thread block to the next and scanning them along the way. In other words, each thread block waits for the previous thread block’s scanned sum, adds the previous thread block’s scanned sum to its own sum to find its own scanned sum, then passes its own scanned sum to the next thread block. This method is referred to as the single lookback method because each thread block looks back to a single preceding thread block. The advantage of the single lookback method over the method in Fig. 11.16(a) is that it does not require a grid-wide barrier synchronization. Instead, each thread block only needs to wait for the preceding thread blocks to complete the previous operation. We refer to this kind of synchronization as unidirectional synchronization. Unlike barrier synchronization, unidirectional synchronization does not require all participating thread blocks to be active simultaneously. It only requires earlier thread blocks in the grid to be scheduled before later thread blocks. This requirement can be achieved by assigning a block index to a thread block only after it starts executing, instead of relying on its default blockIdx.x value. We will see how this dynamic assignment can be done later in this section.
FIGURE 11.17. Code for inter-block scan with single lookback.
Fig. 11.17 shows the code for performing an inter-block scan using the single lookback method. The device function takes four parameters (lines 01-02): the value val that the thread block contributes to the scan, the block index bid that is dynamically assigned, an array partialSums where the thread blocks should place their scanned sums, and another array flags that the thread blocks use to indicate when their scanned sums are ready. The last thread in the block (line 04), which has the block’s sum, acts on behalf of the whole block as the leader thread. The leader thread first checks if the block is the first block or not (line 05). If it is the first block, the scanned sum of the previous block is trivially zero because there is no previous block (line 13). Otherwise, the leader thread must wait until the previous block’s scanned sum is ready. To signal that its scanned sum is ready, the previous block sets its entry in the flags array to one. Hence, the leader thread waits for the previous block by repeatedly checking if the previous block’s flag is still set to zero. Checking the flag should be done atomically because the flag is set by a thread in another block. The atomic operations should be performed with device scope to ensure the visibility of the updated flag value across multiple blocks in the device. For this reason, the thread creates a device-scope (cuda::thread_scope_device) atomic reference to the flag of the previous block (lines 07-08) and repeatedly adds zero to it and checks its old value (line 09). Since adding zero does not change the flag’s value, the flag is expected to remain zero until the previous block sets it. At that point, the leader thread breaks out of the loop and loads the previous block’s scanned sum from the partialSums array (line 11). An important distinction between this use of atomic operations and the previous use in Chapter 9 is that the second argument to the fetch_add function iscuda::memory_order_acquire, not cuda::memory_order_relaxed. The reason we do not use cuda::memory_order_relaxed is that in this case, we care about the order between this atomic operation and other memory accesses in the code. The purpose of the flag is to indicate that the scanned sum is ready, so the subsequent load of the scanned sum should not be reordered to occur before the atomic operation on the flag. Using cuda::memory_order_acquire indicates that the atomic operation has acquire semantics, meaning that subsequent memory instructions should not be reordered to occur before the atomic operation. Once the leader thread has obtained the previous block’s partial sum, it adds the obtained sum value to its own block’s value val and stores the resulting scanned partial sum for its own block in the partialSums array (line 16). After that, the thread needs to set its own block’s flag to indicate to the next block that its own block’s scanned sum is ready. This update must also be done atomically and with device scope since the flag is being accessed simultaneously by the leader thread of the next block. For this reason, the thread creates an atomic reference to its block’s flag with device scope (lines 18-19) and atomically adds one to it using fetch_add (line 20). When incrementing the flag to one, we use yet another option for the second argument to the fetch_add function which is cuda::memory_order_release, not cuda::memory_order_relaxed or cuda::memory_order_acquire. For this atomic operation too, the order between the atomic operation and other memory accesses in the code is important. The purpose of the flag is to indicate that the scanned sum is ready, so the preceding store of the scanned sum should not be reordered to occur after the atomic operation on the flag. Using cuda::memory_order_release indicates that the atomic operation has release semantics, meaning that preceding memory instructions should not be reordered to occur after the atomic operation. The final part of the inter-block scan function in Fig. 11.17 is to perform a barrier synchronization across all threads in the block (line 22). The barrier ensures that none of the threads in the block proceed before the leader thread has written the previous block’s scanned sum to shared memory where the other threads can see it. Finally, all threads return the previous block’s scanned sum to the caller. While the single lookback method enables performing the scan operation in a single kernel, its performance can be actually quite poor. The disadvantage of the single lookback method is that it creates a long chain of dependence between thread blocks, which becomes a long-latency critical path in the execution of the kernel. For an array of size N and a block segment of size S, the kernel executes NS thread blocks. In this case, the method Fig. 11.16(a) would require two grid-wide barrier synchronizations, whereas the method in Fig. 11.16(b) would require NS unidirectional synchronizations. Hence, even if unidirectional synchronizations are more lightweight, they are much larger in number making the single lookback method inefficient when we have a large number of thread blocks. The critical path in the single lookback method can be reduced by allowing the thread block to look back to multiple preceding thread blocks, which is known as multiple lookback. For example, if a thread block b finds that its preceding thread block b − 1 has its sum ready but not its scanned sum, it can look back to threadblock b − 2. If thread block b − 2 has its scanned sum ready, then thread block b does not need to wait for thread block b − 1 to add thread block b − 2’s scanned sum. Thread block b can itself add thread block b − 1’s sum to thread block b − 2’s scanned sum and proceed. In doing so, we would have performed more redundant work since both thread blocks b and b − 1 will add the scanned sum of thread block b − 2 to the sum of thread block b − 1. However, this redundant work would reduce the latency of waiting that thread block b has to do. The multiple lookback method could look back for a fixed number of blocks or a variable number of blocks. That is, a thread block could keep checking a fixed number of preceding blocks until one of them has its scanned sum ready and the rest have their sums ready. Alternatively, a thread block can keep looking back further and further until it finds a scanned sum that is ready, then add the sums of all the later thread blocks. The more a thread block looks back, the more redundant work it performs but the longer the chain of dependence that it bypasses. The multiple lookback method where a thread blocks keeps looking back until it finds a scanned sum ready is referred to as decoupled lookback. We leave the implementation of a revised interBlockScan device function based on decoupled lookback as an exercise. Fig. 11.16(c) shows decoupled lookback in its most extreme case where each thread block goes back and reduces all the preceding thread blocks’ sums. It is visually clear that this method can finish in much fewer steps and synchronizations than the other two methods at the expense of more computations performed. This method should remind the reader of the naïve parallel scan presented in Section 11.2 where each thread performs its own reduction operation. Although the naïve parallel scan has the worst work efficiency, it has the lowest synchronization overhead. This property makes it favorable in the inter-block scan scenario where the cost of synchronization is much higher than the cost of compute, and the number of block sums to be reduced is much smaller than the total number of input elements. Having seen the alternative methods for performing an inter-block scan without terminating the kernel, we can now look at the implementation of a single-kernel scan that includes an inter-block scan to consolidate block segments. Fig. 11.18 shows the code for such a kernel. The kernel follows the scan-scan-add decomposition. Since we perform the scan in a single kernel, there is no need to write the output of the first scan to global memory and read it back for the add operation. Therefore, the benefit of the reduce-scan-scan decomposition over the scan-scan-add decomposition is no longer applicable. The kernel in Fig. 11.18 starts by assigning an index to the thread block dynamically (lines 04-10). Recall that the inter-block scan requires unidirectional synchronization, which requires earlier thread blocks to be scheduled before later thread blocks. This can be achieved by assigning the indices of the thread blocks dynamically in increasing order after the thread blocks are scheduled. To ensure that, once a thread block starts executing, one thread in the block (line 05) atomically increments a thread block counter (line 06-08) to obtain an index, which the other threads in the block wait for (line 10) and read from shared memory (line 11). The thread block counter is allocated in memory, initialized to zero, and passed as a parameter to the kernel (line 01).
FIGURE 11.18. A scan kernel that includes an inter-block scan to consolidate block segments.
The next part of the kernel in Fig. 11.18 (lines 12-40) is mostly the same as the code in Fig. 11.13. A block segment is loaded to shared memory, each thread scans a thread subsegment, the block scans the thread sums, and the threads add the scanned thread sums to their segment yielding the scanned block segment. This point marks the completion of the first scan operation in the scan-scan-add decomposition. For the second scan operation, the device function from Fig. 11.17 that performs an inter-block scan operation is called (lines 42-43). After the second scan operation, the add operation remains (lines 45-48). Each thread iterates over its thread segment (line 46) and adds the previous block’s scanned sum to all its elements (line 47). The final part of the kernel writes the block’s segment to global memory (lines 51-54) in the same way as is done in the code in Fig. 11.13.
11.10 Parallel scan with the Brent-Kung algorithm
Throughout this chapter, we used the Kogge-Stone algorithm as the basis for our parallel implementation of the scan operation. We then observed that the Kogge-Stone algorithm exhibits poor work efficiency. In this section, we cover an alternative algorithm for parallelizing scan that exhibits better work efficiency at the expense of more computation steps. We cover this alternative algorithm for the completeness of the reader’s knowledge, while noting that the Kogge-Stone algorithm’s work efficiency limitation was overcome with thread coarsening making work efficiency no longer a major concern. By inspecting the progression of the Kogge-Stone algorithm in Fig. 11.2, we can see that there are potential opportunities for further sharing of some intermediate results. However, to allow more sharing across multiple threads, we need to strategically calculate the intermediate results and distribute them to different threads, which may require additional computation steps. As we know, the fastest parallel way to produce sum values for a set of values using a binary operator is a reduction tree. With sufficient execution units, a reduction tree can generate the sum for N values in log2 N time units. Furthermore, the tree can also generate several sub-sums that can be used in the calculation of some of the scan output values. This observation was used as a basis for the Kogge-Stone adder design, and also forms the basis of the Brent-Kung adder design [8]. The Brent-Kung adder design can also be followed to implement a parallel scan algorithm with better work efficiency. Fig. 11.19 illustrates the steps for a parallel inclusive scan algorithm based on the Brent-Kung adder design. In the top half of Fig. 11.19, we produce the sum of all 16 elements in 4 steps. We use the minimal number of operations needed to generate the sum. During the first step, only the positions whose indices are of the form 2 · n − 1 are updated. During the second step, only the positions whose indices are of the form of 4 · n − 1 are updated. During the third step, only the positions whose indices are of the form 8 · n − 1 are updated. Finally, during the fourth step, only the last position 15 whose index is of the form 16 · n − 1 is updated. The total number of operations performed is 8 + 4 + 2 + 1 = 15. In general, for a scan segment of N elements, we would do N2 + N4 + · · · + 2 + 1 = N − 1 operations for this reduction phase. The second part of the algorithm is to use a reverse tree to distribute the partial sums to the positions that can use them to complete the result of those positions. The distribution of partial sums is illustrated in the bottom half of Fig. 11.19. To understand the design of the reverse tree, we should first analyze the needs for additional values to complete the scan output at each position of the array. It should be apparent FIGURE 11.19 A parallel inclusive scan algorithm based on Brent-Kung adder design.
from an inspection of Fig. 11.19 that the additions in the reduction tree always accumulate input elements in a continuous range. Therefore, we know that the values that have been accumulated into each position of the array can always be expressed as a range of input elements xi ..xj where xi is the starting position and xj is the ending position (inclusive). Fig. 11.20 shows the state of each position (column), both the values already accumulated into the position as well as the need for additional input element values at each level (row) of the reverse tree. The state of each position initially and after each level of additions in the reverse tree is expressed as the input elements, in the form of xi ..xj , that have already been accounted for in the position. For example, x8 ..x1 1 in row Initial and column 11 indicates that the values of x8 , x9 , x1 0, and x1 1 have been accumulated into position 11 before the reverse tree begins (right after the reduction phase shown in the bottom portion of Fig. 11.19). At the end of the reduction tree phase, we have quite a few positions that are complete with the final scan values. In our example, positions 0, 1, 3, 7, and 15 are all complete with their final answers. The need for additional input element values is indicated with the shade of each cell in Fig. 11.20. Black means that the position needs to accumulate partial sums from three other positions, dark gray means two, light gray means one, and white means zero. For example, initially, position 14 is marked black because it has only the value of x1 4 at the end of the reduction tree phase and needs to accumulate the partial sums from positions 7 (x0 ..x7 ), 11 (x8 ..x1 1) and 13 (x1 2..x1 3) to complete FIGURE 11.20 Progression of values in input after each level of additions in the reverse tree.
its final scan value (x0 ..x1 4). The reader should verify that because of the structure of the reduction tree, the array positions for an input of size N elements will never need to accumulate from more than log2 N − 1 partial sums from other positions. Furthermore, these partial sum positions will always be 1, 2, 4, · · · (powers of 2) away from each other. In our example, position 14 needs log2 (16) − 1 = 3 partial sums from positions that are 1 (between 14 and 13), 2 (between 13 and 11), and 4 (between 11 and 7). To organize the second half of the addition operations, we first show all the operations that need partial sums from 4 positions away, then 2 positions away, and then 1 position way. During the first level of the reverse tree, we add the value at position 7 to that at position 11, which brings position 11 to the final answer. In Fig. 11.20, position 11 is the only one that advances to its final answer. During the second level, we complete positions 5, 9, and 13 that can be completed with the partial sums that are 2 positions away at 3, 7, and 11, respectively. Finally, during the third level, we complete the positions 2, 4, 6, 8, 10, 12, and 14 by accumulating the partial sums that are of 1 position away (immediate left neighbor of each position). We now turn our attention to the analysis of the number of operations in the reverse tree stage. The number of operations is 16 8 − 1 + 4 − 1 + 2 − 1. In general, for N input elements, the total number of operations would be (2−1)+(4−1)+· · ·+ ( N4 − 1) + ( N2 − 1) which is N − 1 − log2 N. Therefore, the total number of operations in the parallel scan, including both the reduction tree phase (N − 1 operations) and the reverse tree phase (N − 1 − log2 N operations), is 2 ∗ N − 2 − log2 N. Hence, the total number of operations is O(N ), as opposed to O(N · log2 N ) for the Kogge-Stone algorithm. The tradeoffs between the Brent-Kung algorithm and the Kogge-Stone algorithm are quite clear. The Brent-Kung algorithm has better work efficiency, performing fewer operations in total, at the expense of executing more steps. However, recall from Section 11.6 that after applying thread coarsening, most of the work in the parallel scan kernel is done by the work efficient thread-level sequential scans. The work inefficient parallel scan is only performed at the warp level and comprises a small part of the kernel’s execution time. In fact, when comparing the Kogge-Stone algorithm and the Brent-Kung algorithm at the warp-level, we find that the Kogge-Stone algorithm has better performance in practice. The work avoided by the Brent-Kung algorithm at the warp level is replaced by inactive warp lanes that still consume execution resources because of the nature of SIMD execution. It is better to utilize those inactive warp lanes to perform more work but finish in fewer steps, as the Kogge-Stone algorithm does. Still, the Brent-Kung algorithm is an interesting case study for reasoning about the interactions between theoretical work efficiency and practical implementation considerations. We leave the implementation of the Brent-Kung algorithm for parallel scan as an exercise for the reader.
11.11 Summary
In this chapter, we studied parallel scan, also known as prefix-sum, as an important parallel computation pattern. Scan is used to enable parallel allocation of resources to parties whose needs are not uniform. It converts seemingly sequential computation based on mathematical recurrence into parallel computation, which helps to reduce sequential bottlenecks in many applications. We show that a simple sequential scan algorithm performs only N − 1, or O(N ), additions for an input of N elements. We first introduced a parallel Kogge-Stone scan algorithm that is fast, conceptually simple, but not work-eicient. The algorithm performs O(N · log2 N ) operations which is more than its sequential counterpart. As the data set size increases, the number of execution units needed for a parallel algorithm to break even with the simple sequential algorithm also increases. Therefore, Kogge-Stone scan algorithms are typically used to process modest-sized scan blocks in processors with abundant execution resources. We saw how to reduce the synchronization overhead of the scan kernel by using double-buffering and warp-level primitives. We also applied thread coarsening to improve its work efficiency. Thread coarsening was applied by having each thread in the block perform a work-eicient sequential scan on its own subsegment of input elements before the threads collaborate to perform the less work efficient block-wide parallel scan to produce the entire block’s segment. We presented two different decompositions of scan to consolidate scanned segments across multiple thread blocks: scan-scan-add and reduce-scan-scan. We saw that a three-kernel implementation of the reduce-scan-scan decomposition incurs fewer redundant global memory accesses than that of the scan-scan-add decomposition. We also saw that global memory accesses can be further reduced with a single-kernel scan that performs an inter-block scan using unidirectional synchronization between thread blocks. The unidirectional synchronization requires special care to prevent deadlocks by using dynamic block index assignment. Decoupled lookback was also presented to overcome the latency of the critical path created by unidirectional synchronization. We then presented the Brent-Kung algorithm for parallel scan as an alternative to the Kogge-Stone algorithm. Using a reduction tree phase and a reverse tree phase, the algorithm performs only O(N ) additions. However, although the Brent-Kung algorithm has better work efficiency than the Kogge-Stone algorithm, it requires moresteps to complete. Moreover, its work efficiency advantage is obviated by the application of thread coarsening to improve work efficiency, and the SIMD nature of warp execution whereby the work avoided is replaced by inactive threads that still consume resources. In general, implementing and optimizing parallel scan algorithms on GPUs is complex and programmers are encouraged to use a parallel scan library for GPUs such as Thrust [1,2] or CUB [3] than to implement their own scan kernels from scratch. Nevertheless, parallel scan is an important parallel pattern, and it offers an interesting and relevant case study of the trade-offs that go into optimizing parallel patterns.
11.12 Exercises
\1. Consider the following array: [4 6 7 1 2 8 5 2]. Perform a parallel inclusive prefix scan on the array using the Kogge-Stone algorithm. Report the intermediate states of the array after each step. 2. Analyze the Kogge-Stone parallel scan kernel in Fig. 11.3. Show that control divergence only occurs in the first warp of each block for stride values up to half of the warp size. That is, for warp size 32, control divergence will occur to iterations for stride values 1, 2, 4, 8, and 16. 3. For the Kogge-Stone scan kernel in Fig. 11.3, assuming that we have 2048 elements, how many add operations are performed in total? 4. Modify the kernel in Fig. 11.13 to use vector loads and stores and to eliminated shared memory bank conflicts. 5. Modify the interBlockScan device function in Fig. 11.17 to use decoupled lookback instead of single-lookback. 6. Consider the following array: [4 6 7 1 2 8 5 2]. Perform a parallel inclusive prefix scan on the array using the Brent-Kung algorithm. Report the intermediate states of the array after each step. 7. Implement a CUDA kernel that executes the Brent-Kung algorithm to scan an array at the block level.
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. [4] P.M. Kogge, H.S. Stone, A parallel algorithm for the efficient solution of a general class of recurrence equations, IEEE Transactions on Computers 100 (8) (1973) 786–793.
References
CHAPTER
Filter And warp voting
References
[5] Y. Dotsenko, N.K. Govindaraju, P.-P. Sloan, C. Boyd, J. Manferdelli, Fast scan algorithms on graphics processors, in: Proceedings of the 22nd Annual International Conference on Supercomputing, 2008, pp. 205–213. [6] S. Yan, G. Long, Y. Zhang, Streamscan: fast scan algorithms for gpus without global barrier synchronization, in: Proceedings of the 18th ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming, 2013, pp. 229–238. [7] D. Merrill, M. Garland, Single-pass parallel prefix scan with decoupled look-back, Tech. Rep. NVR-2016-002, NVIDIA, 2016. [8] Brent Kung, A regular layout for parallel adders, IEEE Transactions on Computers 100 (3) (1982) 260–264.