Skip to content

Chapter 22 Algorithm selection, problem decomposition, and problem formulation

Programming Massively Parallel Processors 5e — English original

Chapter 22 Algorithm selection, problem decomposition, and problem formulation

CHAPTER

Algorithm selection, problem decomposition, and problem formulation CONTENTS 22.1 Algorithm selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530 22.2 Problem decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532 22.3 Application level considerations – Amdahl’s law . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 22.4 Problem formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 22.5 Batching: latency vs. throughput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539 22.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 We have so far concentrated on practical knowledge in parallel programming, which consists of CUDA programming features, the GPU architecture, performance optimization techniques, parallel patterns, and application case studies. In this chapter, we switch our discussions to concepts that are more abstract. We first generalize parallel programming into a thinking process of designing/selecting parallel algorithms and decomposing a domain problem into well-defined and coordinated parallel work units that can each be efficiently performed by the selected algorithms. With good algorithm selection and problem decomposition, the programmer can achieve an appropriate compromise between parallelism, work efficiency, and resource consumption. A strong combination of domain knowledge and parallel thinking skills is often needed for creating successful computational solutions to challenging domain problems. With strong parallel thinking skills, a parallel programmer does not need to be confined to the role of solving domain problems handed down by domain scientists. Rather, the programmer can collaborate with domain scientists to analyze and transform the structure of a domain problem: which parts are inherently serial, which parts are amenable to high-performance parallel execution, and the domain-specific tradeoffs involved in moving parts from the former category to the latter. This chapter gives the reader more insight into parallel programming and parallel thinking in general. Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00033-0 Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.

We have so far concentrated on practical knowledge in parallel programming, which consists of CUDA programming features, the GPU architecture, performance optimization techniques, parallel patterns, and application case studies. In this chapter, we switch our discussions to concepts that are more abstract. We first generalize parallel programming into a thinking process of designing/selecting parallel algorithms and decomposing a domain problem into well-defined and coordinated parallel work units that can each be efficiently performed by the selected algorithms. With good algorithm selection and problem decomposition, the programmer can achieve an appropriate compromise between parallelism, work efficiency, and resource consumption.

A strong combination of domain knowledge and parallel thinking skills is often needed for creating successful computational solutions to challenging domain problems. With strong parallel thinking skills, a parallel programmer does not need to be confined to the role of solving domain problems handed down by domain scientists. Rather, the programmer can collaborate with domain scientists to analyze and transform the structure of a domain problem: which parts are inherently serial, which parts are amenable to high-performance parallel execution, and the domain-specific tradeoffs involved in moving parts from the former category to the latter. This chapter gives the reader more insight into parallel programming and parallel thinking in general.

22.1 Algorithm selection

An algorithm is a step-by-step procedure where each step is precisely stated and can be carried out by a computer. An algorithm must exhibit three essential properties: definiteness, effective computability, and finiteness. Definiteness refers to the notion that each step is precisely stated; there is no room for ambiguity as to what is to be done. Effective computability refers to the fact that each step can be carried out by a computer. Finiteness means that the algorithm must be guaranteed to terminate. Given a problem, one can typically come up with multiple algorithms to solve the problem. Some require fewer steps of computation than others (i.e., have lower algorithmic complexity), some expose a higher degree of parallel execution than others, some are more generally applicable than others, and some have better accuracy or numerical stability than others. Unfortunately, there is often not a single algorithm that is better than others in all these aspects. A parallel programmer often needs to select an algorithm that achieves the best compromise for a given hardware system. We have seen examples of assessing the trade-offs between different algorithms for a computation in several chapters throughout this book. For the prefix sum computation in Chapter 11, we compared two different algorithms for performing parallel prefix sum, namely the Kogge-Stone algorithm and the Brent-Kung algorithm. Our analysis showed that the Brent-Kung algorithm has lower algorithmic complexity. It requires fewer operations to perform the same computation, which makes it more work efficient. However, we also showed that the Kogge-Stone algorithm exposes more parallelism than the Brent-Kung algorithm, allowing it to complete in fewer iterations. This trade-off between algorithmic complexity and the amount of parallelism exposed by an algorithm is a classic trade-off that is encountered by parallel programmers. The best algorithm usually depends on the characteristics of the parallel hardware being targeted, as well as the extent to which the higher complexity of an algorithm can be mitigated with hybrid approaches that combine two parallel algorithms or combine a parallel algorithm with a lower-complexity sequential algorithm via thread coarsening. For the sorting pattern in Chapter 14, we compared three different algorithms for performing parallel sorting: odd-even sort, merge sort, and radix sort. Odd-even sort has the highest algorithmic complexity, but is the most trivial to parallelize. Radix sort can achieve lower algorithmic complexity than merge sort because it is a noncomparison sorting algorithm. It is also highly amenable to parallelization. However, radix sort is not generally applicable because it can only be used with certain types of keys. Merge sort, which is a comparison-based sort, is more generally applicable than radix sort and can be used with any type of key that has a well-define comparison operator. The trade-off between generality and parallel execution efficiency is yet another trade-off that parallel programmers encounter when selecting a parallel algorithm. For the electrostatic potential map computation in Chapter 21, we compared two different algorithms for performing the computation, namely Direct Coulomb Summation (DCS) and cutoff summation. These two approaches both expose ampleparallelism. However, they present the classic trade-off between algorithmic complexity and accuracy. In Chapter 21, we showed that the cutoff summation algorithm can significantly improve the execution efficiency of grid computation by sacrificing a small amount of accuracy. The challenge addressed by this technique is that the amount of computation performed by fully accurate methods like DCS increases with the square of the volume. For large volume systems, such increase makes the computation excessively long even for massively parallel devices. The cut-off summation method is based on the observation that many grid calculation problems are based on physical laws where numerical contributions from particles or samples that are far away from a grid point are tiny and can be collectively treated with an implicit method at much lower algorithmic complexity. Although this trade-off between algorithmic complexity and accuracy is not unique to parallel programming and is also encountered with sequential implementations, it often presents additional challenges to parallel programmers. We discuss an example of these additional challenges for the cutoff summation algorithm in the rest of this section. In sequential computing, a simple cutoff algorithm handles one atom at a time. For each atom, the algorithm iterates through the grid points that fall within a radius of the atom’s coordinate. This is a straightforward procedure since the grid points are in an array that can be easily indexed as a function of their coordinates. However, this simple procedure does not carry easily to parallel execution. The reason is that the atom-centric decomposition does not work well due to it scatter memory access behavior. Therefore, we need to use a cutoff binning algorithm based on the grid-centric decomposition: each thread calculates the energy value at one grid point. The key idea of the algorithm is to first sort the input atoms into bins according to their coordinates. Each bin corresponds to a box in the grid space and it contains all atoms whose coordinates fall into the box. We define a ``neighborhood’’ of bins for a grid point to be the collection of bins that contain all the atoms that can contribute to the energy value of a grid point according to the cut-off distance threshold. We describe an efficient way of managing neighborhood bins for all grid points in Chapter 21. In this algorithm, all blocks iterate through their own neighborhood bins while all threads in a block scan through the atoms in their combined neighborhood bins together but make individual decisions on whether each atom falls within its cut-off radius. One subtle issue with binning is that bins may end up with different numbers of atoms. Some bins may have many atoms and some bins may have no atom at all. Declaring the size (capacity) of the bins to accommodate the largest possible number of atoms can be prohibitively expensive. A well-known solution is to set the bin size at a reasonable level, typically much smaller than the largest possible number of atoms in a bin. The binning process maintains an overflow list. When sorting atoms into bins, if an atom’s home bin is full, the atom is added to the overflow list instead. After the device completes executing a cut-off summation kernel for calculating an electrostatic potential map, atoms in the overflow list need to be processed to complete the missing contributions.

Figure 22.1

FIGURE 22.1. Problem decomposition strategies: (a) output-centric and (b) input-centric.

22.2 Problem decomposition

After selecting an appropriate algorithm, for a problem to be solved with parallel computing, the problem must be formulated in such a way that it can be decomposed into sub-problems that can be safely solved at the same time. Under such formulation and decomposition, the programmer writes code and organizes data to solve these sub-problems concurrently. Finding parallelism in large computational problems is often conceptually simple, but can be challenging in practice. The key is to identify the units of work to be performed, or the subproblem to be solved, by each thread or collection so that the inherent parallelism in the problem is well utilized. The two most common strategies for decomposing a problem for parallel execution are output-centric and input-centric decompositions. These decomposition strategies are illustrated in Fig. 22.1. As the names imply, with output-centric decomposition, solving each sub-problem produces the result for one or more output elements. An implementation based on output-centric decomposition assigns a thread or a collection of threads to solve one or more sub-problems and produce one or more output elements. The solution of each sub-problem may require all input elements (e.g., grid-centric DCS in Chapter 21) or a subset of the input elements (e.g., matrix multiplication in Chapter 5 and grid-centric cut-off-summation with binning in Chapter 21). In contrast, with input-centric decomposition, solving each sub-problem derives the contribution of one or more input elements to the final output. An implementation based on input-centric decomposition assigns a thread or a collection of threads to process one or more input elements and apply their contributions to the output elements. The solution of each sub-problem may update one output element (e.g., histogram in Chapter 9), a subset of output elements (e.g., hypothetically, atom-centric cut-off summation in Chapter 21) or all output elements (e.g., atom-centric DCS in Chapter 21).

For some problems, input-centric and output-centric decomposition may lead to the same sub-problems. For example, in odd-even sort in Chapter 14, each thread is responsible for reading a pair of input elements to produce the result values for the corresponding pair of output elements. In this case, since the input elements and output elements have simple direct relations, it does not matter whether we view the decomposition as input-centric or output-centric. While both decomposition strategies lead to the same execution results, they can exhibit very different performance in a given hardware system. The output-centric decomposition usually exhibits the gather memory access behavior, where each thread gathers or collects the effect of input values into an output value. Fig. 22.1(a) illustrates the gather access behavior. Gather-based access patterns are usually more desirable in CUDA devices because the threads can accumulate their results in their private registers. Also, multiple threads can share input values, and can effectively use the GPU caches or shared memory to conserve global memory bandwidth. The input-centric decomposition, on the other hand, usually exhibits the scatter memory access behavior, where each thread scatters or distributes the effect of an input value into the output values. The scatter behavior is illustrated in Fig. 22.1(b). Scatter-based access patterns are usually undesirable in CUDA devices because multiple threads can update the same output value at the same time. The output values must be stored in a memory that can be written by all the threads involved. Atomic operations must be used to prevent race conditions and loss of values during simultaneous writes to an output value by multiple threads. These atomic operations are significantly slower than the register accesses used in the output-centric decomposition. However, aside from gather versus scatter access patterns, other considerations may go into deciding whether an output-centric or input-centric decomposition (or another decomposition) is more suitable for a particular application. These considerations include: the amount of parallelism exposed by the decomposition, the ease of identifying which input data contributes to which output data, the load balance induced by the decomposition, and others depending on the application. The comparison between input-centric and output-centric decompositions was most evident in Chapter 21 where the two strategies were both implemented and explicitly compared. In particular, the atom-centric decomposition was an input-centric one, and the grid-centric decomposition was an output-centric one. However, aside from Chapter 21, problem decomposition has been an implicit design decision that was made throughout many computations discussed in this book. We revisit these computations to highlight the problem decomposition chosen in each case and why it is advantageous over alternative decompositions. The image processing (Chapter 3), matrix multiplication (Chapter 3, Chapter 5, and Chapter 15), convolution (Chapter 7), and stencil (Chapter 8) computations were all parallelized using an output-centric decomposition. That is, the threads in these computations are assigned to output elements (image pixels, matrix entries, or grid points) and iterate over the input elements that contribute to them. Alternatively, an input-centric decomposition would assign threads to the input elements and haveeach thread iterate over the output elements that its input element contributes to and make an update using atomic operations. The clear advantage of the output-centric decomposition over the input-centric decomposition in these cases is avoiding atomic operations by using a gather access pattern instead of a scatter access pattern. On the other hand, none of the other considerations make the input-centric decomposition favorable. There are enough output elements to expose a high degree of parallelism; it is straightforward to identify which input elements are needed by each output element; and all output elements require the same amount of work to be computed so there is no load imbalance. The histogram computation (Chapter 9) was parallelized using an input-centric decomposition. That is, each thread is assigned to an input element (or chunk of elements) and updates the output bins based on the input value(s). Since multiple threads may update the same output bin, atomic operations are needed (scatter access pattern). Alternatively, an output-centric decomposition for the histogram computation would assign threads to output bins and have each thread search for the inputs that map to the bin and update the bin accordingly. This decomposition would eliminate the atomic operations because each bin would be updated by a single thread (gather access pattern). However, the output-centric decomposition would create many problems. First, the number of output bins is typically much smaller than the number of input values so parallelism is substantially reduced. Second, a thread cannot know which input values map to its output bin without inspecting those input values, so each thread will need to iterate over every input value which is not work efficient. Third, even if threads had some way of quickly identifying which input values map to their output bins, each bin will have a different number of input values mapping to it, which would create load imbalance across threads. All these considerations make the input-centric decomposition more favorable for the histogram computation. The reduction (Chapter 10) and scan (Chapter 12) patterns both involve multiple iterations. If one considers problem decomposition on an iteration-by-iteration basis, both reduction and scan are parallelized using an output-centric decomposition. Each thread is responsible for updating one element of the iteration’s output array by gathering and adding two elements from the iteration’s input array. An input-centric decomposition of a reduction or scan iteration would assign each thread to an element of the iteration’s input array, and that thread would scatter that element’s value to the elements that need it in the iteration’s output array. Since multiple input elements contribute to the same output element, such a decomposition would require atomic operations to avoid race conditions which would significantly impede performance. The unstable and stable filter patterns (Chapter 12) were both parallelized using an input-centric decomposition. Each thread is assigned to an input element and is responsible for identifying if that input element should be retained, and if yes, where it should be placed in the output array. An efficient output-centric decomposition of the unstable or stable filter patterns would be quite difficult. It would entail assigning a thread to an element of the output array and having that thread identify which input element should be placed there. However, doing so would require the thread to inspect a large number of other elements which would be inefficient and cause redundant work across threads. The input-centric decomposition is naturally a better fit. It is noteworthy that while the overall decomposition of the stable filter computation is input-centric, the computation includes a scan operation which itself is outputcentric. It is not unusual for complex computations to include multiple operations that are parallelized with different decomposition strategies. The merge operation (Chapter 13) was parallelized using an output-centric decomposition. That is, each thread is assigned to a chunk of elements in the output array and performs a binary search to find the corresponding input element(s) to be copied into these output elements. While many other computations favor the outputcentric decomposition to avoid atomic operations, this consideration is not relevant for the merge operation. Every output element in the merge operation receives contribution from only one input element, so an input-centric merge operation would not need to use atomic operations. The main reason for merge to prefer an output-centric merge over an input-centric merge is to achieve load balance when thread coarsening is applied. In an input-centric merge, we would partition one of the input arrays across the threads and have each thread find the corresponding elements in the other input array and merge them into the output array. However, different threads could end up merging very different numbers of input elements, resulting in control divergence and load imbalance across threads. For this reason, the output-centric decomposition for parallel merge is preferred. Sorting (Chapter 14) uses different problem decompositions depending on the algorithm used. For odd-even sort, the input-centric and output-centric decompositions are equivalent. In every iteration of odd-even sort, each thread is assigned to a pair of elements and decides whether or not to swap it. In other words, each thread is assigned to one input pair and processes it to produce one output pair. There is no scattering or gathering involved. For merge sort, each level consists primarily of a merge operation, which uses an output-centric decomposition as we have seen. For radix sort, each iteration uses an input-centric decomposition where each thread is assigned to an input element and identifies its new position in the output array. Recall that the partition operation used in radix sort is a generalization of the stable filter pattern, which also uses an input-centric decomposition as we have seen. The wavefront pattern (Chapter 16) is parallelized using an output-centric decomposition. To compute each (output) element of the dynamic programming matrix, the thread assigned to that element gathers the values of multiple previously computed (input) elements. Alternatively, an input-centric decomposition of the wavefront pattern would entail having each thread scatter the value of a previously computed (input) element to all the succeeding (output) elements that depend on that value. Since multiple elements of the dynamic programming matrix can contribute to the same succeeding element, such a decomposition would require atomic operations making it less favorable. For sparse matrix computations (Chapter 17), the SpMV/CSR, SpMV/ELL, and SpMV/JDS kernels all use output-centric decomposition where each thread is assigned to an output vector element and iterates over the corresponding input row of non-zeros to gather their contribution. On the other hand, the SpMV/COO kernel uses input-centric decomposition where each thread is assigned to a non-zero element in the input matrix and atomically updates the corresponding element in theoutput vector, resulting in a scatter access pattern. Compared to the output-centric kernels, the input-centric SpMV/COO kernel has the disadvantage of performing atomic operations, but it has other advantages such as extracting more parallelism and better load balance. An output-centric decomposition for SpMV/COO would require threads to search through all input elements to find the ones that contribute to their output vector element, which would drastically increase the computation complexity. The SpMV/CSC kernel also uses input-centric decomposition, where each thread is assigned to an element of the input vector and iterates through a column of the input matrix, scattering its contribution to the relevant output vector elements using atomic operations. The CSC format does not provide convenient access for an output-centric decomposition to iterate through all non-zero elements of a row. Finding all input elements that contribute to an output element would require each thread to scan through all columns to check for any input element from the row that contributes to its assigned output element. Ultimately, the best decomposition for this computation depends on the input dataset. Moreover, the hybrid ELL-COO format showcases an example of where a hybrid output-centric and input-centric decomposition may be beneficial. For graph traversal (Chapter 18), the vertex-centric push implementation and the edge-centric implementation use input-centric decomposition. That is, threads are assigned to vertices or edges, and update the levels of neighboring vertices. In contrast, the vertex-centric pull implementation uses output-centric decomposition where each thread only updates the level of the vertex that it is assigned to. The trade-off between the scatter and gather access patterns is not a concern when selecting between different decompositions because the updates to the level values are idempotent and do not use atomic operations. However, the amount of parallelism extracted and the load balance achieved play an important role in deciding which decomposition is more favorable, and the best decomposition ultimately depends on the input dataset. The reader is encouraged to review Chapter 18 for a more detailed handling of this topic. The electrostatic potential map calculation problem (Chapter 21) favors the output-centric decomposition because of the benefit over the gather pattern of the scatter pattern in avoiding atomic operations. The chapter already handles the distinction between the two decomposition strategies in depth. The computation involves the calculation of the contribution of many input atoms to the potential energy at a large number of output grid points. A realistic molecular system model typically involves at least hundreds of thousands of atoms and millions of energy grid points. The electrostatic charge information of each atom is used many times in calculating its contributions to the energy grid points. We show that the decomposition of the electrostatic potential map calculation problem can be atom-centric (i.e., input-centric) or grid-centric (i.e., output-centric). In an atom-centric decomposition, each thread is responsible for calculating the effect of one atom on all grid points. In contrast, a grid-centric decomposition uses each thread to calculate the effect of all atoms on a grid point. The grid-centric (i.e., output-centric) decomposition proved to be better because it uses the more favorable gather access pattern. The amount of parallelism exposed by both decompositions is sufficient. For the cutoff summation algorithm, the difficulty of mapping input data to output data in the grid-centric decomposition is overcome with the use of binning.

22.3 Application level considerations – Amdahl’s law

Figure 22.2

FIGURE 22.2. Major tasks of a molecular dynamics application.

A real application often consists of multiple modules that work together. Fig. 22.2 shows an overview of the major modules of a molecular dynamics application. For each atom in the system, the application needs to calculate the various forms of forces – e.g., vibrational, rotational, and non-bonded – that are exerted on the atom. Each form of forces is calculated with a different method. At the high level, a programmer needs to decide how the work is organized. Note that the amount of work can vary dramatically between these modules. The non-bonded force calculation typically involves interactions among many atoms and incurs much more calculations than the vibrational and rotational forces. Therefore, these modules tend to be realized as separate passes over the force data structure. The programmer needs to decide if each pass is worth implementing for a CUDA device. For example, the programmer may decide that the vibrational and rotational force calculations do not involve sufficient amount of work to warrant execution on a GPU device. Such a decision would lead to a CUDA program that launches a kernel that calculates non-bonding force fields for all the grid points while continuing to calculate the vibrational and rotational forces for the grid points on the host. The module that updates atom positions and velocities may also run on the host. It first combines the vibrational and rotational forces from the host and the non-bonding forces from the device. It then uses the combined forces to calculate the new atomic positions and velocities. The portion of work done by the GPU device ultimately decides the applicationlevel speedup achieved by parallelization. For example, assume that the non-bonding force calculation accounts for 95% of the original sequential execution time and it is accelerated by 100× using a GPU. Further assume that the rest of the application remains on the host and receives no speedup. The application-level speed up is 1/(5% + 95%/100) = 1/(5% + 0.95%) = 1/(5.95%) = 17×. In the case where the execution of the host and the CUDA device can be overlapped, the execution time of the parallel section is completely hidden in the host execution time. The application-level speedup would be 1/(5%) = 20×. This is a demonstration of Amdahl’s Law that we saw in Chapter 1: the application speedup due to parallel computing is limited by the sequential portion of the application. In this case, even though the sequential portion of the application is quite small (5%), it limits the application-level speedup to 20× despite the non-bonding force calculation having a speedup of 100× and being completely hidden in the shadow of the host execution of the sequential portion. This example illustrates a major challenge in accelerating large applications: the accumulated execution time of small activities that are not worth parallel execution on a CUDA device can become a limiting factor in the speedup seen by the end users. Amdahl’s Law often motivates task-level parallelization. Although some of these smaller activities do not warrant fine-grained massive parallel execution, it may be desirable to execute some of these activities in parallel with each other when the data set is large enough. This could be achieved by using a multi-core host to execute such tasks in parallel. Alternatively, we could try to simultaneously execute multiple small kernels, each corresponding to one task. Although each kernel may not be able to make good use of the GPU and achieve significant speedup over CPU execution, executing them simultaneously on a GPU may overlap their execution with each other and achieve good speedup overall. CUDA devices support task parallelism with streams, which are discussed in Chapter 23.

22.4 Problem formulation

Problem formulation is arguably the most consequential aspect of parallel application development [1]. The ``best’’ approach to parallelizing an application is not using generic numerical methods to map domain problems to computing steps that can be implemented using the skills you have learned from this book. Such approach often results in high computational complexity and/or limited parallelism. Rather, one often needs to rethink numerical methods to relax some of the constraints on the implementation. The cutoff binning approach in Chapter 21 is a good example. The approach requires domain expertise to trade accuracy for dramatically reduced algorithmic complexity, and requires problem decomposition and optimization skills to use the grid-centric decomposition with the binning techniques designed by computer scientists. In this approach, there is the potential for the biggest performance advantage and fundamental new discoveries and capabilities. For example, one may be able to perform highfidelity simulation of a biochemical system whose size is considered beyond reach with traditional methods. This approach is interdisciplinary and requires both computer science and domain insights, but the payoff is worth the effort.

22.5 Batching: latency vs. throughput

The parallel programming optimization techniques that we have discussed so far are designed to make the parallel program run faster given the same problem. For example, in Chapter 11, techniques such as double buffering, warp-level shuffling register tiling, and look-back help the code run faster, i.e., with shorter latency, when processing the same input. The process of making parallel code run faster for the same input data is often referred to as latency optimization. While it is desirable to make the parallel code run faster on the same input, it is not the only motivation for optimizing a parallel program. In general, there are at least two motivations for optimizing parallel programs. The first and most intuitive motivation is to solve a given problem, i.e. processing a given input data set, in less time, which has been our focus in this book. For example, an investment firm may need to perform a financial portfolio risk analysis on all its portfolios during after-trading hours. Such an analysis may take 10 hours with a current parallel program. However, the portfolio management team may request that the analysis be completed in four hours in order to make more timely decisions. When the parallel program fails to meet the new latency requirement, optimization techniques can further enhance the speed and allow the analysis to finish within the time window. In Chapter 20, the use of flash attention technique reduces the transformer latency for a given input by eliminating redundant accesses to global memory. The second, and somewhat less intuitive, motivation of using parallel computing is to improve the total latency for solving many problems. In our financial portfolio analysis example, the investment firm may decide to run multiple instances of the analysis with different parameters for statistical reasons. However, the current parallel program may not be able to run all the instances within the time window. Optimizing the current parallel program to reduce the total latency for solving multiple instances of the problem involves an additional tradeoff: latency for solving each individual problem vs. latency for solving all problem instances. In Chapter 20, processing a query from a user can be viewed as an instance of the inference problem. When there are many users making queries, there are many instances of inference problems. Batching queries from different users allows these queries to be processed by the transformer layers together to increase the arithmetic intensity of the attention heads. For example, batching allows the QKV projection vector-matrix multiplication operations to be converted into matrix multiplications. Although a matrix multiplication takes more time to execute than a vector-matrix multiplication, it takes much shorter time than the sum of the execution time for all the vector-matrix multiplications in the batch. This is because reusing the original matrix elements in matrix multiplication eliminates redundant global memory accesses across vector-matrix multiplications and greatly improves arithmetic intensity. That is, individual queries experience longer QKV projection latency, but the whole group of queries finish with shorter total latency. Thus, the throughput of QKV prototal number of queries jection is higher with batching ( latency f or matrix multiplication ) than without batching number of queries ( total latency ftotal or all matrix−vector multiplications ). Such tradeoff between latency for individual problem instances vs. the throughput of a batch of problem instances is animportant aspect of optimizing parallel programs. The reader should also recognize that the same tradeoff has been discussed in Chapter 1. The CPU design has shorter latency for processing each individual data element, whereas the GPU design has higher throughput for processing a large number of data elements. There is a very large volume of literature on a wide range of algorithms, problem decompositions, problem formulation, and optimization strategies. It is beyond the scope of this book to have a comprehensive coverage of all the available concepts and techniques. We discuss a substantial set of techniques in each of the algorithm, problem decomposition, problem formulation, and optimization steps that have broad applicability. Although these techniques are demonstrated using CUDA implementations, they help the readers build up the foundation for parallel thinking in general. We believe that humans understand best when we learn from the bottom up. That is, we first learn concepts in the context of a particular programming model, which provides us with solid footing before we generalize our knowledge. An in-depth experience with the CUDA implementations also enables us to gain maturity, which helps us learn parallel programming and thinking concepts that may not even be pertinent to GPUs.

22.6 Summary

In summary, we have discussed the main steps of parallel programming and thinking, namely: problem formulation, algorithm selection, problem decomposition, and optimization. Given a computational problem, the programmer will typically have to select from a variety of algorithms. Some of these algorithms achieve different tradeoffs while maintaining the same numerical accuracy. Others involve sacrificing some level of accuracy to achieve much more scalable running times. For the selected algorithm, different choices of problem decomposition can result in different levels of interference between threads, level of exposed parallelism, load imbalance, and other performance considerations during parallel execution. Batching techniques can also be used to trade increased individual latency for increased throughput for groups of problem instances. Parallel thinking skills allow a parallel programmer to work around roadblocks and reach a good solution.

References [1] J.M. Wing, Computational thinking, Communications of the ACM 49 (3) (2006) 33–35.

CHAPTER

Multi-GPU programming And an introduction to MPI, NCCL, and NVSHMEM With special contributions from Jiri Kraus and Isaac Gelado

Figure 23.1

FIGURE 23.1. Modified stencil kernel for the Jacobi iterative method in 2D.

References

[1] J.M. Wing, Computational thinking, Communications of the ACM 49 (3) (2006) 33–35.