Skip to content

Chapter 14 Sorting

Programming Massively Parallel Processors 5e — English original

Chapter 14 Sorting

CHAPTER

Sorting

With special contributions from Michael Garland CONTENTS 14.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 14.2 Parallel odd-even sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 14.3 Parallel merge sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 14.4 Radix sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334 14.5 Parallel radix sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 14.6 Optimizing for memory coalescing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339 14.7 Choice of radix value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 14.8 Thread coarsening to improve coalescing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 14.9 Other parallel sort methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 14.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 14.11 Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Sorting algorithms place the data elements of a list into a certain order. Sorting is foundational to modern data and information services since the computational complexity of retrieving information from data sets can be significantly reduced if the data set is in proper order. For example, sorting is often used to canonicalize the data for fast comparison and reconciliation between data lists. Also, the efficiency of many data processing algorithms can be improved if the data is in a certain order. Due to their importance, efficient sorting algorithms have been the subject of many computer science research efforts. Even with these efficient algorithms, sorting large data lists is still time consuming and can benefit from parallel execution. Parallelizing efficient sorting algorithms is challenging and sometimes requires elaborate designs. This chapter presents the designs of three parallel sorting algorithms – odd-even sort, merge sort, and radix sort. Odd-even sort is covered briefly due to its simplicity and merge sort is covered briefly because it largely depends on the merge pattern already presented in Chapter 13. Most of the chapter is dedicated to radix sort and its optimizations, which rely on a more general form of the stable filter pattern which will be discussed further in Chapter 12. Other popular parallel sorting algorithms such as transposition sort and sampling sort are also discussed. Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00024-X Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.

Sorting algorithms place the data elements of a list into a certain order. Sorting is foundational to modern data and information services since the computational complexity of retrieving information from data sets can be significantly reduced if the data set is in proper order. For example, sorting is often used to canonicalize the data for fast comparison and reconciliation between data lists. Also, the efficiency of many data processing algorithms can be improved if the data is in a certain order. Due to their importance, efficient sorting algorithms have been the subject of many computer science research efforts. Even with these efficient algorithms, sorting large data lists is still time consuming and can benefit from parallel execution. Parallelizing efficient sorting algorithms is challenging and sometimes requires elaborate designs. This chapter presents the designs of three parallel sorting algorithms – odd-even sort, merge sort, and radix sort. Odd-even sort is covered briefly due to its simplicity and merge sort is covered briefly because it largely depends on the merge pattern already presented in Chapter 13. Most of the chapter is dedicated to radix sort and its optimizations, which rely on a more general form of the stable filter pattern which will be discussed further in Chapter 12. Other popular parallel sorting algorithms such as transposition sort and sampling sort are also discussed.

14.1 Background

Sorting is one of the earliest applications for computers. A sorting algorithm arranges the elements of a list into a certain order. The order to be enforced by a sorting algorithm depends on the nature of these elements. Examples of popular orders are numerical order for numbers and lexicographical order for text strings. More formally, any sorting algorithm must satisfy the following two conditions: • The output is in either nondecreasing or nonincreasing order. For nondecreasing order, each element is no smaller than the previous element according to the desired order. For nonincreasing order, each element is no larger than the previous element according to the desired order. • The output is a permutation of the input. That is, the algorithm must retain all of the original input elements while reordering them into the output. In its simplest form, the elements of a list can be sorted according to the values of each element. For example, the list [5, 2, 7, 1, 3, 2, 8] can be sorted into a nondecreasing order output [1, 2, 2, 3, 5, 7, 8]. A more complex and common use case is that each element consists of a key field and a value field and the list should be sorted based on the key field. For example, assume that each element is a tuple (age, income in thousands of dollars). The list [(30,150), (32,80), (22,45), (29,80)] can be sorted using the income as the key field into a nonincreasing order [(30,150), (32,80), (29,80), (22,45)]. If the elements of a list are simply values, these values serve as keys for sorting purposes. Sorting algorithms can be classified into stable and unstable algorithms. A stable sort algorithm preserves the original order of appearance when two elements have equal key value. For example, when sorting the list [(30,150), (32,80), (22,45), (29,80)] into a nonincreasing order using income as the key field, a stable sorting algorithm must guarantee that (32, 80) appears before (29,80) because the former appear before the latter in the original input. On the other hand, an unstable sorting algorithm does not offer such a guarantee. Stable algorithms are required if one wishes to use multiple keys to sort a list in a cascaded manner. For example, if each element has a primary key and a secondary key. With stable sorting algorithms, one can first sort the list according to the secondary key and then sort one more time with the primary key. The second sort will preserve the order produced by the first sort. Sorting algorithms can also be classified into comparison-based and noncomparison-based algorithms. Comparison-based sorting algorithms cannot achieve better than O(N · logN ) complexity when sorting a list of N elements because they must perform a minimal number of comparisons among the elements. In contrast, some of the non-comparison-based algorithms can achieve better than O(N · logN ) complexity, but they may not generalize to arbitrary types of keys. Both comparisonbased and non-comparison-based sorting algorithms can be parallelized. In this chapter, we present two parallel comparison-based sorting algorithms (odd-even sort and merge sort) as well as a parallel non-comparison-based sorting algorithm (radix sort).

14.2 Parallel odd-even sort

Due to the importance of sorting, the computer science research community has produced a great spectrum of sorting algorithms based on a rich variety of data structures and algorithmic strategies. As a result, introductory computer science classes often use sorting algorithms to illustrate a variety of core algorithm concepts, such as big O notation, divide and conquer algorithms, data structures such as heaps and binary trees, randomized algorithms, best, worst, and average case analysis, time–space tradeoffs, and upper and lower bounds. In this chapter, we continue this tradition and use three sorting algorithms to illustrate several important parallelization and performance optimization techniques [1].

One of the simplest comparison-based sequential sorting algorithms is bubble sort. The high-level strategy of bubble sort is to compare adjacent pairs of list elements and swap them if they are out of order. This process is repeated until the entire list is sorted. In bubble sort, each iteration goes through the list of elements sequentially from beginning to end, sorting adjacent pairs. However, the order in which the pairs are sorted is not necessary for the strategy to work, as long as all the pairs are covered in each iteration. A parallel sorting algorithm could follow a similar iterative strategy, but have each iteration sort adjacent pairs in parallel rather than in sequential order. The challenge with sorting pairs in parallel is that the pairs being sorted must be independent in order to avoid race conditions. For example, if one thread is assigned to sort the list elements at indices 0 and 1, we cannot assign another thread to sort the list elements at indices 1 and 2. If we do so and both threads decide to swap their pairs simultaneously, they would encounter a race condition when accessing the element at index 1. To maximize the number of independent pairs that are sorted simultaneously, we can sort all the pairs whose first elements have odd indices (odd pairs) in parallel, then sort all the pairs whose first element have even indices (even pairs) in parallel. This technique is the basis for odd-even transposition sort, or odd-even sort for short. Odd-even sort is a comparison-based parallel sorting algorithm that iteratively alternates between odd and even pairs of adjacent list elements. In each iteration, the odd (or even) pairs of adjacent list elements are compared and swapped if they are out of order. Fig. 14.1 shows an example of how odd-even sort can be applied to a list of eight elements. In the first iteration, four threads are launched, one for each even pair. The first two threads find their pairs already in order, while the next two threads find their pairs out of order and swap the elements. In the second iteration, one thread is launched for each odd pair. Again, some threads find their pairs already in order, while others find their pairs out of order and thus swap the elements. In the third iteration, we go back to sorting the even pairs. We keep alternating between odd and even pairs until no elements are swapped, which indicates that the list is sorted. Fig. 14.2 shows a kernel for implementing odd-even sort. The kernel is called once for each iteration with half as many threads as there are elements in the list. The isOddStep parameter (line 02) indicates whether the kernel is sorting odd pairs or FIGURE 14.1 Parallel odd-even sort.

Figure 14.2

FIGURE 14.2. Parallel odd-even sort kernel.

even pairs. The kernel starts by identifying the index of the first element in the pair that the thread is responsible for (lines 03-04). For even pairs (isOddStep = 0), the index is just the thread’s global index multiplied by two such that thread t would sort the pair with indices (2 · t, 2 · t + 1). For odd pairs (isOddStep = 1), we further add 1 such that thread t would sort the pair with indices (2 · t + 1, 2 · t + 2). After the boundary check (line 05), each thread compares the two list elements it is responsible for (line 06) and swaps them if they are out of order (lines 07-09). Finally, if a thread is successful at swapping a pair, it sets a global flag hasChanged to indicate that the list order has changed and that another iteration needs to be performed (line 10).

14.3 Parallel merge sort

Note that when multiple threads write the value 1 to hasChanged, the situation is technically a race condition: multiple threads access the same memory location without ordering and at least one of the accesses is a write. In practice, such race conditions are benign because all threads write the same value so the final outcome is the same regardless of how many threads perform the write. This property of an operation having the same effect regardless of how many times it is applied is referred to as idempotence. However, in principle, in the C++ memory model, race conditions can cause undefined behavior even if the operation is idempotent. So although this code may work in practice, it violates the C++ memory model and is not guaranteed to work. Accordingly, conservative programmers should use an atomic operation to write 1 to hasChanged. While odd-even sort is simple to implement, it has a high time and work complexity. The number of iterations needed is O(N ), where N is the size of the input list, because in the worst case, the largest element is at the beginning of the list and needs N iterations to reach the end. If there are sufficient execution resources to execute each iteration completely in parallel, then the time complexity would be O(N ). In each of the O(N ) iterations, we perform N/2 or O(N ) comparisons. Hence, the work complexity of odd-even sort is O(N 2 ).

The high time and work complexity of odd-even sort motivates the need to have more efficient comparison-based parallel sorting algorithms with lower complexity. One such comparison-based sorting algorithm that is amenable to parallelization is merge sort. Merge sort works by dividing the input list into segments, sorting each segment (using merge sort or another sorting algorithm), then performing an ordered merge of the sorted segments. Fig. 14.3 shows one way for parallelizing merge sort. Initially, the input list is divided into many segments that are each sorted independently using some sorting algorithm. After that, every pair of segments is merged into a single segment. This process is repeated until all the keys become part of the same segment. At each stage, the computation can be parallelized by performing different merge operations in parallel as well as extracting parallelism from within each merge operations. We have already seen how to parallelize a merge operation in Chapter 13. As the stages of the parallel merge sort in Fig. 14.3 progress, there is a trade-off between the parallelism that can be extracted across and within merge operations. In the earlier stages, there are more independent merge operations that can be performed in parallel. In the later stages, there are fewer independent merge operations, however, each merge operation merges more keys exposing more parallelism within the merge operation. For example, the first merge stage consists of four independent merge operations. Hence, our grid of eight thread blocks may assign two thread blocks to process each merge operation in parallel. In the next stage, there are only two merge operations, however, each operation merges twice the number of keys.

Figure 14.3

FIGURE 14.3. One way for parallelizing merge sort.

Hence, our grid of eight thread blocks may assign four thread blocks to process each merge operation in parallel. We leave the implementation of this parallel merge sort algorithm as an exercise for the reader. The number of iterations needed by the parallel merge sort in Fig. 14.3 is O(logN ), since the number of segments that need to be merged is halved on every iteration. If there are sufficient execution resources to execute the merge operations of each iteration completely in parallel, then each iteration would have a time complexity of O(logN ) and a work complexity of O(N · logN ), as seen in Chapter 13. Hence, the overall time and work complexity of the parallel merge sort algorithm presented are O(log 2 N ) and O(N · log 2 N ), respectively. Note that this O(N · log 2 N ) work complexity is slightly higher than sequential merge sort’s O(N · logN ) complexity. The higher complexity is due to the fact that parallel merge operation has higher work complexity than sequential merge because of the execution of the co-rank function, as seen in Chapter 13. Cole’s algorithm [2] for parallel merge sort overcomes this limitation and achieves time and work complexity of O(logN ) and O(N · logN ), respectively.

14.4 Radix sort

To achieve better sorting complexity than O(N · logN ), one has to use a noncomparison-based sorting algorithm. One non-comparison-based sorting algorithm FIGURE 14.4 A radix sort example.

that is highly amenable to parallelization is radix sort. Radix sort works by distributing the keys being sorted into buckets based on a radix value (or base in a positional numeral system). If the keys consist of multiple digits, the distribution of the keys is repeated for each digit until all digits are covered. Each iteration is stable, preserving the order of the keys within each bucket from the previous iteration. When processing keys represented as binary numbers, choosing a radix value that is a power of two is convenient because it makes iterating over the digits and extracting them easy. Each iteration essentially handles a fixed-size slice of the bits from the key. We will start by using a radix of 2 (i.e., a 1-bit radix), and then extend to larger radix values later on in the chapter. Fig. 14.4 shows an example of how a list of 4-bit integers can be sorted with radix sort using a 1-bit radix. Since the keys are four bits long and each iteration processes one bit, four iterations are required in total. In the first iteration, the least significant bit is considered. All the keys in the iteration’s input list whose least significant bit is zero are placed on the left side of the iteration’s output list forming a bucket for the zero bits. Similarly, all the keys in the iteration’s input list whose least significant bit is one are placed on the right side of the iteration’s output list forming a bucket for the one bits. Note that within each bucket in the output list, the order of the keys is preserved from that in the input list. In other words, keys that are placed into the same bucket (i.e., have the same least significant bit) must appear in the same order in theoutput list as they did in the input list. We will see why this stability requirement is important when we discuss the next iteration. In the second iteration in Fig. 14.4, the output list from the first iteration becomes the new input list, and the second least significant bit of each key is considered. Like the first iteration, the keys are separated into two buckets: a bucket for the keys whose second least significant bit is zero and another bucket for the keys whose second least significant bit is one. Since the order from the previous iterations is preserved, we observe that the keys in the second iteration’s output list are now sorted by the lower two bits. In other words, all the keys whose lower two bits are 00 come first, followed by those whose lower two bits are 01, followed by those whose lower two bits are 10, followed by those whose lower two bits are 11. In the third iteration in Fig. 14.4, the same process is repeated while considering the third bit in the keys. Again, since the order from previous iterations is preserved, the keys in the output list of the third iteration are sorted by the lower three bits. Finally, in the fourth and last iteration, the same process is repeated while considering the fourth or most significant bit. At the end of this iteration, the keys in the final output list are sorted by all four bits. The operation performed by a radix sort iteration should remind the reader of the stable filter pattern discussed in Chapter 12. In the stable filter pattern, the input keys that meet some condition are brought to the beginning of the output list while preserving their order. A radix sort iteration performs a more general operation where the input keys that meet a condition (having their bit of interest equal to 0) are brought to the beginning of the output list, and those that do not meet the condition are brought to the end of the list, while preserving the order of keys in each sub-list. This more general pattern is sometimes referred to as the stable partition pattern because it divides the input list into multiple partitions. As we will see in the rest of this chapter, the techniques for parallelizing and optimizing a radix sort iteration strongly resemble those for parallelizing and optimizing the stable filter operation.

14.5 Parallel radix sort

Each iteration in radix sort depends on the entire result of the previous iteration. Hence, the iterations are performed sequentially with respect to each other. The opportunity for parallelizing radix sort arises within each iteration. For the rest of this chapter, we will focus on the parallelization and optimization of a single radix sort iteration, with the understanding that the iterations will be executed one after the other. In other words, we will focus on the implementation of a kernel that performs a single radix sort iteration and assume that the host code calls this kernel once for each iteration. We will cover multiple optimizations for this radix sort kernel. Interested readers are also encouraged to refer to OneSweep [3], which is a state-of-the-art implementation of radix sort for GPUs. One straightforward approach to parallelize a radix sort iteration on GPUs is to make each thread responsible for one key in the input list. The thread must identify the position of the key in the output list and then store the key to that position.

Figure 14.5

FIGURE 14.5. Parallelizing a radix sort iteration by assigning one input key to each thread.

Fig. 14.5 illustrates this parallelization approach applied to the first iteration from Fig. 14.4. Threads in Fig. 14.5 are illustrated as curvy arrows, and thread blocks are illustrated as boxes around the arrows. Each thread is responsible for the key below it in the input list. In this example, the 16 keys are processed by a grid with four thread blocks having four threads each. In practice, each thread block may have up to 1024 threads and the input is much larger resulting in many more thread blocks. However, we use a small number of threads per block to simplify the illustration. With every thread assigned to a key in the input list, the challenge remains for each thread to identify the destination index of its key in the output list. Identifying the destination index of the key depends on whether the key maps to the zero bucket or the one bucket. For keys mapping to the zero bucket, the destination index can be found as follows: destination of a zero = # zeros before = # keys before - # ones before = key index - # ones before The destination index of a key that maps to the zero bucket (i.e., destination of a zero) is equivalent to the number of keys before the key that also map to the zero bucket (i.e., # zeros before). Since all keys either map to the zero bucket or the one bucket, the number of keys before the key mapping to the zero bucket is equivalent to the total number of keys before the key (i.e., # keys before) minus the number of keys before the key mapping to the one bucket (i.e., # ones before). The total number of keys before the key is just the index of the key in the input list (i.e., key index) which is trivially available. Hence, the only non-trivial part of finding the destination index of a key that maps to the zero bucket is counting the number of keys before it that map to the one bucket. This operation can be done using an exclusive scan as we will see shortly. For keys mapping to the zero bucket, the destination index can be found as follows: destination of a one = # zeros in total + # ones before = (# keys in total - # ones in total) + # ones before = input size - # ones in total + # ones before FIGURE 14.6 Finding the destination of each input key.

All keys mapping to the zero bucket must come before the keys mapping to the one bucket in the output array. For this reason, the destination index of a key that maps to the one bucket (i.e., destination of a one) is equivalent to the total number of keys mapping to the zero bucket (i.e., # zeros in total) plus the number of keys before the key that map to the one bucket (i.e., # ones before). Since all keys either map to the zero bucket or the one bucket, the total number of keys mapping to the zero bucket is equivalent to the total number of keys in the input list (i.e., # keys in total) minus the total number of keys mapping to the one bucket (i.e., # ones in total). The total number of keys in the input list is just the input size which is trivially available. Hence, the non-trivial part of finding the destination index of a key that maps to the one bucket is counting the number of keys before it that map to the one bucket, which is the same information needed for the zero bucket case. Again, this operation can be done using an exclusive scan as we will see shortly. The total number of keys mapping to the one bucket can be found as a byproduct of the exclusive scan. Fig. 14.6 shows the operations that each thread performs to find its key’s destination index in the example in Fig. 14.5. The corresponding kernel code to perform these operations is shown in Fig. 14.7. First, each thread identifies the index of the key it is responsible for (line 03), performs a boundary check (line 05), and loads the key from the input list (line 06). Next, each thread extracts from the key the bit for the current iteration to identify whether it is a zero or a one (line 07). Here, the iteration number iter tells us the position of the bit that we are interested in. By shifting the key to the right by this amount, we move the bit to the rightmost position. By applying a bitwise-and operation (&) between the shifted key and a 1, we zero out all the bits in the shifted key except the rightmost bit. Hence, the value of bit will be the value of the bit we are interested in. In the example in Fig. 14.6, since the example is for iteration 0, the least significant bit is extracted as shown in the row labeled bits.

14.6 Optimizing for memory coalescing

Figure 14.7

FIGURE 14.7. Radix sort iteration kernel code.

Once each thread extracts the bit it is interested in from the key, it stores the bit to memory (line 08) and the threads collaborate to perform a grid-wide exclusive scan on the bits (line 10). We have already discussed how to perform a grid-wide parallel scan operation in Chapter 11. The array resulting from the exclusive scan operation contains, at each position, the sum of the bits before of that position. Since these bits are either zero or one, the sum of the bits before the position is equivalent to the number of the ones before the position (i.e., the number of keys that map to the one bucket). In the example in Fig. 14.6, the result of the exclusive scan is shown in the row labeled # ones before. Each thread accesses this array to obtain the number of ones before its position (line 12) and the total number of ones in the input list (line 13). Each thread can then identify the destination of its key using the expressions we derived previously (lines 14-15). Having identified its destination index, the thread can proceed to store the key it is responsible for at the corresponding location in the output list (line 16). In the example in Fig. 14.6, the destination indices are shown in the row labeled destination. The reader can refer to Fig. 14.5 to verify that the values obtained are indeed to right destination indices of each element.

The approach we just described is effective at parallelizing a radix sort iteration. However, one major source of inefficiency in this approach is that the writes to the output list exhibit an access pattern that cannot be adequately coalesced. Consider how each thread in Fig. 14.5 writes its key to the output list. In the first thread block, the first thread writes to the zero bucket, the second thread writes to the one bucket, the third thread writes to the zero bucket, and the fourth thread writes to the one bucket. Hence, threads with consecutive index values are not necessarily writing toconsecutive memory locations, resulting in poor coalescing and requiring multiple memory requests to be issued per warp. For a 1-bit radix where there are only two buckets, threads in the same warp will only write to one of two buckets. Consequently, the number of distinct cache lines written to by a warp is most likely two cache lines, or a little more depending on the alignment of the accesses. However, as we will see in Section 14.7, larger radix values result in a larger number of buckets, and consequently, more distinct cache lines to be potentially written to by the same warp. Hence, uncoalesced memory accesses can be a serious impediment to the performance of a radix sort iteration kernel. Recall from Chapter 6 that there are various approaches to enable better memory coalescing in kernels: (1) rearranging the threads, (2) rearranging the data that the threads access, or (3) performing the uncoalesceable accesses on shared memory, and transferring data between shared memory and global memory in a coalesced way. To optimize for coalescing in this chapter, we will use the third approach. Instead of having all threads write their keys to global memory buckets in an uncoalesced manner, we will have each thread block maintain its own local buckets in the shared memory. That is, we will no longer perform a global sort as shown in Fig. 14.7. Rather, the threads in each block will first perform a block-level local sort to separate the keys mapping to the zero bucket and the keys mapping to the one bucket in shared memory. After that, the buckets will be written from shared memory to global memory in a coalesced manner. Fig. 14.8 shows an example of how memory coalescing can be enhanced for the example in Fig. 14.5. In this example, each thread block first performs a local radix sort on the keys that it owns and stores the output list into the shared memory. The local sort can be done in the same way as the global sort was done previously, and only requires each thread block to perform a local exclusive scan instead of requiring a global one. After the local sort, each thread block writes its local buckets to the global buckets in a more coalesced way. For example, in Fig. 14.8, consider how the first thread block writes out its buckets to global memory. The first two threads both write to adjacent locations in global memory when writing the zero bucket, while the last two threads also write to adjacent locations in global memory when writing the one bucket. Hence, the majority of writes to global memory will be coalesced. The main challenge in this optimization is for each thread block to identify the beginning position of each of its local buckets in the corresponding global bucket. The beginning position of a thread block’s local buckets depends on the sizes of the local buckets in the other thread blocks. In particular, the position of a thread block’s local zero bucket is after all the local zero buckets of the preceding thread blocks. On the other hand, the position of a thread block’s local one bucket is after all the local zero buckets of all the thread blocks and all the local one buckets of the preceding thread blocks. These positions can be obtained by performing an exclusive scan on the thread blocks’ local bucket sizes. Fig. 14.9 shows an example of how an exclusive scan can be used to find the position of each thread block’s local buckets. After completing the local radix sort, each thread block identifies the number of keys in each of its local buckets. Next, FIGURE 14.8 Optimizing for memory coalescing by sorting locally in shared memory before sorting into to the global memory.

Figure 14.9

FIGURE 14.9. Finding the destination of each thread block’s local buckets.

each thread block stores these values in a table as shown in Fig. 14.9. The table is stored in row-major order, meaning that it places the sizes of the local zero buckets for all thread blocks consecutively followed by the sizes of the local one buckets. After the table is constructed, an exclusive scan is executed on the linearized table. The resulting table consists of the beginning positions of each thread block’s local buckets, which are the values we are looking for. Once a thread block identifies the beginning position of its local buckets in global memory, the threads in the block can proceed to store their keys from the local buckets to the global buckets. To do so, each thread needs to keep track of the number of keys in bucket zero vs. bucket one. During the write phase, threads in each block will be writing a key in either of the buckets depending on its thread index values. For example, for block 2 in Fig. 14.9, thread 0 writes the single key in the zero bucket and threads 1-3 write the three keys in the one bucket. In comparison, for block 3 in Fig. 14.9, threads 0-2 write the three keys in the zero bucket and thread 3 writes the one key in the one bucket. Hence, each thread needs to test if it is responsible for writing a key in the local zero bucket or the one bucket. Each block tracks the number of keys in each of its two local buckets so that the threads can determine where their threadIdx values fall into and participate in the writing of the zero bucket keys or one bucket keys. We leave the implementation of this optimization as an exercise for the reader.

14.7 Choice of radix value

So far, we have seen how radix sort can be parallelized using a 1-bit radix as an example. For the 4-bit keys in the example, four iterations (one for each bit) are needed for the keys to be fully sorted. In general, for N-bit keys, N iterations are needed to fully sort the keys. To reduce the number of iterations needed, a larger radix value can be used. Fig. 14.10 shows an example of how radix sort can be performed using a 2-bit radix. Each iteration uses two bits to distribute the keys to buckets. Hence, the 4-bit keys can be fully sorted using only two iterations. In the first iteration, the lower two bits are considered. The keys are distributed across four buckets corresponding to the keys where the lower two bits are 00, 01, 10, and 11. In the second iteration, the upper two bits are considered. The keys are then distributed across four buckets based on the upper two bits. Similar to the 1-bit example, the order of the keys within each bucket is preserved from the previous iteration. Preserving the order of the keys within each bucket ensures that after the second iteration, the keys are fully sorted by all four bits. Similar to the 1-bit example, each iteration can be parallelized by assigning a thread to each key in the input list to find the key’s destination index and store it in the output list. To optimize for memory coalescing, each thread block can sort its keys locally in the shared memory, then write the local buckets to global memory in a coalesced manner. An example of how to parallelize a radix sort iteration and optimize it for memory coalescing using the shared memory is shown in Fig. 14.11. The key distinction between the 1-bit example and the 2-bit example is how to separate the keys into four buckets instead of two. For the local sort inside of each thread block, a 2-bit radix sort is performed by applying two consecutive 1-bit radix sort iterations. Each of these 1-bit iterations requires its own exclusive scan operation, however, these operations are local to the thread block so there is no coordination across thread blocks in between the two 1-bit iterations. In general, for an r-bit radix, r local 1-bit iterations are needed to sort the keys into 2r local buckets. After the local sort is complete, each thread block must find the position of each of its local buckets in the global output list. Fig. 14.12 shows an example of how the FIGURE 14.10 Radix sort example with 2-bit radix.

Figure 14.11

FIGURE 14.11. Parallelizing a radix sort iteration and optimizing it for memory coalescing using the shared memory for a 2-bit radix.

destination of each local bucket can be found for the 2-bit radix example. The procedure is similar to the 1-bit example in Fig. 14.9. Each thread block stores the number of keys in each local bucket to a table that is then scanned to obtain the global position of each of the local buckets. The main distinction from the 1-bit radix example is that each thread block has four local buckets instead of two, so the exclusive scan operation is performed on a table with four rows instead of two. In general, for an r-bit radix, the exclusive scan operation is performed on a table with 2r rows. We have seen that the advantage of using a larger radix is that it reduces the number of iterations needed to fully sort the keys. Fewer iterations means fewer grid launches, global memory accesses, and global exclusive scan operations. However, using a larger radix also has disadvantages. The first disadvantage is that each thread block has more local buckets where each bucket has fewer keys. As a result, each thread block has more distinct global memory bucket sections that it needs to write to and less data that it needs to write to each section. For this reason, the opportunities for memory coalescing decrease as the radix gets larger. The second disadvantage is FIGURE 14.12 Finding the destination of each block’s local buckets for 2-bit radix.

that the table on which the global exclusive scan is applied gets larger with a larger radix. For this reason, the overhead of the global exclusive scan increases as the radix increases. Therefore, the radix cannot be made arbitrarily large. The choice of radix value must strike a balance between the number of iterations on one hand, and the memory coalescing behavior as well as the overhead of the global exclusive scan on the other hand. We leave the implementation of radix sort with a multi-bit radix as an exercise for the reader.

14.8 Thread coarsening to improve coalescing

The overhead of parallelizing radix sort across many thread blocks is poor coalescing of writes to global memory. Each thread block has its own local buckets that it writes to global memory. Having more thread blocks means having fewer keys per thread block, which means that the local buckets are going to be smaller, exposing fewer opportunities for coalescing when they are written to global memory. If these thread blocks were to be executed in parallel, the price of poor coalescing might be worth paying. However, if these thread blocks were to be serialized by the hardware, the price is paid unnecessarily. To address this issue, thread coarsening can be applied whereby each thread is assigned to multiple keys in the input list instead of just one. Fig. 14.13 illustrates FIGURE 14.13 Radix sort for 2-bit radix with thread coarsening to improve memory coalescing.

14.9 Other parallel sort methods

how thread coarsening can be applied to a radix sort iteration for the 2-bit radix example. In this case, each thread block is responsible for more keys than the example in Fig. 14.11. Consequently, the local buckets of each thread block are larger exposing more opportunities for coalescing. When comparing Fig. 14.11 and Fig. 14.13, it is clear that in Fig. 14.13, it is more likely the case that consecutive threads write to consecutive memory locations. Another overhead of parallelizing radix sort across many thread blocks is the overhead of performing the global exclusive scan to identify the destination of each thread block’s local buckets. Recall from Fig. 14.12 that the size of the table on which the exclusive scan is performed is proportional to the number of buckets as well as the number of blocks. By applying thread coarsening, the number of blocks is reduced, thereby reducing the size of the table and the overhead of the exclusive scan operation. We leave the application of thread coarsening to radix sort as an exercise for the reader.

The algorithms outlined in this chapter are only some of the many possible ways to sort data in parallel. In this section, we briefly outline some of the other methods that may be of interest to readers. The odd-even transposition sort covered in Section 14.2 uses a fixed pattern of comparisons and it swaps elements when they are out of order. It is easily parallelized because each step compares pairs of keys that do not overlap. There is an entire category of sorting methods that use fixed patterns of comparison to sort sequences, often in parallel. These methods are usually referred to as sorting networks and the most well-known parallel sorting networks are Batcher’s bitonic sort and odd-even mergesort [4]. Batcher’s algorithms operate on sequences of fixed length and are more efficient than odd-even transposition sort, requiring only O(N · log 2 N ) comparisons for a sequence of N elements. Even though the cost of these algorithms is asymptotically worse than the O(N · logN ) cost of methods like merge sort, in practice, they are often the most efficient methods on small sequences because of their simplicity. Most comparison-based parallel sorts that do not use the fixed set of comparisons typical of sorting networks can be divided into two broad categories. The first partitions the unsorted input into tiles, sorts each tile, and then performs most of its work in combining these tiles to form the output. The merge sort described in this chapter is an example of such an algorithm; most of the work is performed in the merge tree that combines sorted tiles. The second category focuses most of its work on partitioning the unsorted sequence, such that combining partitions is relatively trivial. Sample sort algorithms [5] are the typical example of this category. Sample sort begins by selecting p-1 keys from the input (e.g., at random), sorts them, and then uses them to partition the input into p buckets such that all keys in bucket k are greater than all keys in any bucket j < k and less than all in any bucket j > k. This step is analogous to a p-way generalization of the 2-way partitioning performed by quicksort. Having partitioned the data in this way, each bucket can be sorted independently, and the sorted output is formed by merely concatenating the buckets in order. Sample sort algorithms are often the most efficient choice for extremely large sequences where data must be distributed across multiple physical memories, including across the memories of multiple GPUs in a single node. In practice, over-sampling the keys is common, since modest over-sampling will result in balanced partitions with high probability [6]. Just as merge sort and sample sort typify bottom-up and top-down strategies to comparison-based sorting, radix sorting algorithms can be designed to follow a bottom-up or top-down strategy. The radix sort described in this chapter is more completely described as a least-significant bit (LSB), or more generally least-significant digit (LSD), radix sort. The successive steps of the algorithm start with the leastsignificant digit of the key and work towards the most-significant digit. A mostsignificant digit (MSD) radix sort adopts the opposite strategy. It begins by using the most-significant digit to partition the input into buckets corresponding to the possible values of that digit. This same partitioning is then applied independently in each bucket using the next-most-significant digit. Upon reaching the least-significant digit, the entire sequence will have been sorted. Like sample sort, MSD radix sort is often a better choice for very large sequences. Whereas the LSD radix sort requires global shuffling of data in each step, each step of MSD radix sort operates on progressively more localized regions of the data.

14.10 Summary

In this chapter, we have seen how to sort keys (and their associated values) on GPUs in parallel. We started with two comparison-based parallel sorting algorithms: parallel odd-even sort and parallel merge sort. Parallel odd-even sort iteratively swaps Referencespairs of adjacent elements in the list until the list is sorted, alternating between odd pairs and even pairs to avoid race conditions. Parallel merge sort performs independent merge operations of different input segments in parallel, as well as parallelizing within each merge operation by leveraging the parallel merge operation discussed in Chapter 13. We then focused on a non-comparison-based sorting algorithm, radix sort, which has the advantage of having work complexity that is lower than O(N · logN ). Radix sort works by iteratively distributing keys across buckets. The distribution process is repeated for each digit in the key, while preserving the order from the previous digit’s iteration, to ensure that the keys are sorted according to all the digits at the end. Each iteration is parallelized by assigning a thread to each key in the input list and having that thread find the destination of the key in the output list, which involves collaborating with other threads to perform an exclusive scan operation. One of the key challenges with optimizing radix sort is achieving coalesced memory accesses when writing the keys to the output list. An important optimization to enhance coalescing is to have each thread block perform a local sort to local buckets in shared memory, then write each local bucket to global memory in a coalesced manner. Another optimization is to increase the size of the radix to reduce the number of iterations needed, and thus the number of grids launched. However, the radix size should not be increased too much because it would result in poorer coalescing of memory accesses and more overhead from the global exclusive scan operation. Finally, applying thread coarsening is effective at improving memory coalescing as well as reducing the overhead of the global exclusive scan. Implementing and optimizing parallel sorting algorithms on GPUs is complex and programmers are encouraged to use parallel sorting libraries for GPUs such as Thrust [7,8] or CUB [9] rather than to implement their own sorting kernels from scratch. Nevertheless, parallel sorting remains an interesting case study of the tradeoffs that go into optimizing parallel patterns.

14.11 Exercises

\1. Extend the kernel in Fig. 14.7 by using shared memory to improve memory coalescing. 2. Extend the kernel in Fig. 14.7 to work for a multi-bit radix. 3. Extend the kernel in Fig. 14.7 by applying thread coarsening to improve memory coalescing. 4. Implement parallel merge sort using the parallel merge implementation from Chapter 13.

References [1] N. Satish, M. Harris, M. Garland, Designing efficient sorting algorithms for manycore gpus, in: 2009 IEEE International Symposium on Parallel & Distributed Processing, IEEE, 2009, pp. 1–10.

CHAPTER

Advanced optimizations for matrix multiplication

References

[2] R. Cole, Parallel merge sort, SIAM Journal on Computing 17 (4) (1988) 770–785. [3] A. Adinets, D. Merrill, Onesweep: a faster least significant digit radix sort for gpus, arXiv preprint, arXiv:2206.01784, 2022. [4] K.E. Batcher, Sorting networks and their applications, in: Proceedings of the April 30–May 2, 1968, Spring Joint Computer Conference, 1968, pp. 307–314. [5] W.D. Frazer, A.C. McKellar, Samplesort: a sampling approach to minimal storage tree sorting, Journal of the ACM 17 (3) (1970) 496–507. [6] G.E. Blelloch, C.E. Leiserson, B.M. Maggs, C.G. Plaxton, S.J. Smith, M. Zagha, A comparison of sorting algorithms for the connection machine cm-2, in: Proceedings of the Third Annual ACM Symposium on Parallel Algorithms and Architectures, 1991, pp. 3–16. [7] N. Bell, J. Hoberock, Thrust: a productivity-oriented library for cuda, in: GPU Computing Gems Jade Edition, Elsevier, 2012, pp. 359–371. [8] NVIDIA, Thrust: the C++ parallel algorithms library, https://nvidia.github.io/cccl/thrust/ index.html, 2025. [9] NVIDIA, CUB, https://nvidia.github.io/cccl/cub/index.html, 2025.