Skip to content

Chapter 23 Multi-GPU programming

Programming Massively Parallel Processors 5e — English original

Chapter 23 Multi-GPU programming

CHAPTER

Multi-GPU programming And an introduction to MPI, NCCL, and NVSHMEM With special contributions from Jiri Kraus and Isaac Gelado CONTENTS 23.1 Stencil as a running example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542 23.2 Multi-GPU stencil with MPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545 23.3 Overlapping computation and communication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553 23.4 Multi-GPU stencil with NCCL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563 23.5 Multi-GPU stencil with NVSHMEM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568 23.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 23.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576 So far, we have focused on programming a heterogeneous computing system with one host and one device. However, many applications require the aggregate computing power of multiple hosts and devices. Many clusters and data centers today have one or more hosts and one or more devices attached to each host. In this chapter, we look at three programming models for programming clusters with multiple GPUs: the Message Passing Interface (MPI) [1], the NVIDIA Collective Communications Library (NCCL) [2], and the NVIDIA OpenSHMEM Library (NVSHMEM) [3]. We only present the key concepts from each programming model that a programmer needs to understand in order to scale their heterogeneous applications to multiple GPUs and nodes in a cluster environment. We focus on domain partitioning, point-topoint communication, collective communication, and overlapping computation and communication in the context of scaling a CUDA stencil computation across multiple GPU nodes. The implementations presented are intended to illustrate the core principles behind each programming model and can each be further optimized within their respective programming models. Readers are encouraged to refer to tutorials and application case studies of each of the three programming models for a more extensive coverage of the full capabilities of each model once they master the concepts in this chapter. Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00034-2 Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.

Figure 23.1

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

So far, we have focused on programming a heterogeneous computing system with one host and one device. However, many applications require the aggregate computing power of multiple hosts and devices. Many clusters and data centers today have one or more hosts and one or more devices attached to each host. In this chapter, we look at three programming models for programming clusters with multiple GPUs: the Message Passing Interface (MPI) [1], the NVIDIA Collective Communications Library (NCCL) [2], and the NVIDIA OpenSHMEM Library (NVSHMEM) [3]. We only present the key concepts from each programming model that a programmer needs to understand in order to scale their heterogeneous applications to multiple GPUs and nodes in a cluster environment. We focus on domain partitioning, point-to-point communication, collective communication, and overlapping computation and communication in the context of scaling a CUDA stencil computation across multiple GPU nodes. The implementations presented are intended to illustrate the core principles behind each programming model and can each be further optimized within their respective programming models. Readers are encouraged to refer to tutorials and application case studies of each of the three programming models for a more extensive coverage of the full capabilities of each model once they master the concepts in this chapter.

23.1 Stencil as a running example

Throughout this chapter, we use the stencil computation introduced in Chapter 8 as a running example. In particular, we use the Jacobi Iterative Method where, in each iteration or time step, the value of a point in a structured grid1 is calculated as a weighted sum of its neighbors from the previous time step. The stencil kernel is called for multiple iterations until the grid point values stop changing significantly. To determine if the values have stopped changing, we calculate the L2 norm of the residual values, i.e., the differences between the old value and new value at each grid point. The stencil kernel in Fig. 23.1 embodies two modifications [4] to those from Chapter 8. The first modification is that we compute a 2D stencil, as opposed to a 3D stencil, to simplify the illustrations and the code examples. The second modification is that the stencil kernel also computes the residual and the L2 norm. As shown in Fig. 23.1, each thread identifies the x and y coordinates of the grid point it is responsible for computing (lines 03-04). A boundary check makes sure that only threads computing grid points that are within bounds are active (line 07). Note that the points at x = 0, x = nx − 1, y = 0, and y = ny − 1 are skipped because they are either boundary points or halo points, as we will see later. The thread calculates the new value at its grid point as the average of the old values at the neighboring grid points (lines 08-12). The code so far should be familiar from the kernels in Chapter 8. 1 Throughout this chapter, we use the word grid'' to refer to structured grid of data values in a modeledsystem as introduced in Section 8.1. To avoid confusion, we use the term thread grid’’ to refer to a grid of GPU threads.

Figure 23.2

FIGURE 23.2. 2D grid array for the modeling system partitioned across 4 GPUs.

After computing the new value at its grid point, each thread calculates its grid point’s residue as the difference between the new value and the old value (line 13). To calculate the L2 norm, the squares of the residues need to be summed up across all threads in the grid. A block-wide reduction, such as that discussed in Chapter 10, is performed to sum up the squares of the residues across the entire block (line 16). After that, one thread in the block atomically accumulates the block-level sum to the grid-wide L2 norm (lines 17-19). The kernel in Fig. 23.1 can be further optimized. For example, shared memory tiling and thread coarsening can be used to reduce global memory accesses, as described in Chapter 8. Furthermore, many optimizations can be applied to the reduction operation, as described in Chapter 10, or the block-wide reduction function from the CUB [5] library can be called. However, these optimizations are not the focus of this chapter. This chapter focuses on how the stencil computation can be distributed across multiple GPUs. Fig. 23.2 illustrates the modeled system and how it can be partitioned across multiple GPUs. We assume that the system is modeled as a structured grid, where the spacing between grid points is constant in each direction. This assumption allows us to use a 2D array to represent the system, where each element stores the state of a grid point, as we discussed in Chapter 8. The physical distance between adjacent elements in each dimension can be represented by a grid spacing variable. In the 2D array, we assume that the data is placed in the memory space in the row-major layout, where x is the lowest dimension followed by y. That is, all elements with y = 0 are placed in consecutive memory locations according to their x coordinate, followed by all elements with y = 1, etc. When one uses multiple GPUs, it is common to divide the input data into several partitions, called domain partitions, and assign each partition to a different GPU FIGURE 23.3 Values available to each GPU before and after computation.

in the cluster. With the row major layout, it is natural to partition the system across GPUs along the y-dimension, giving each GPU a contiguous set of rows. This partitioning is illustrated in Fig. 23.2 where the grid points that each GPU is responsible for computing are indicated by different colors and separated by solid lines. Such partitioning ensures that each GPU’s partition is contiguous in memory according to the row-major layout. Recall that to compute the new value at each grid point, the old values at the neighboring points are needed. Hence, for a GPU to compute the new grid point values at its partition’s edge, it needs the old values of the grid points at the edges of the adjacent partitions. These grid points, called halo points, are indicated in Fig. 23.2 by the dotted lines. For example, for GPU 1 to compute the new values of the grid points in its partition, it needs the old values of all these grid points as well as the old values of the bottom row of GPU 0’s partition and the top row of GPU 2’s partition. The span of input rows needed as input by GPU 1 is indicated by ny. The first and last rows in the span are the halo points, used only as input, whereas the middle ny − 2 rows are both inputs and outputs. Fig. 23.3 further illustrates the values available to each GPU before and after computing the grid point values in its partition. Before computing, the GPU needs the values of the halo rows as shown in Fig. 23.3(a). After computing, the values at its halo rows become out of date as shown in Fig. 23.3(b). The new values at the halo rows are computed by the other GPUs that are responsible these rows. Hence, before proceeding to the next iteration, a GPU needs to obtain the updated values of the halo rows from the GPUs computing the adjacent partitions. For example, GPU 1 needs to copy its top halo row from GPU 0 and its bottom halo row from GPU 2. Simultaneously, GPU 1 needs to send its top row to GPU 0 and its bottom row to GPU 2. This sending and receiving of halo rows between adjacent GPUs is referred to as halo exchange. Here, we observe another benefit of applying a 1Ddomain decomposition across the y-dimension when using the row-major layout. The halo rows that need to be copied from one GPU to another are contiguous in memory, which simplifies the copy operation during halo exchange. One drawback of this 1D domain decomposition scheme is that depending on the shape of the domain and the number of GPUs, large volumes of data may need to be communicated between GPUs. For example, if the domain is very wide, each GPU would need to communicate an entire row of the domain which can be expensive. Alternatively, one could use a 2D domain decomposition where each GPU takes a 2D tile of the domain. A 2D domain decomposition reduces the surface to volume ratio, thereby reducing the amount of data that needs to be communicated. However, a 2D domain decomposition would require each GPU to communicate with four other neighboring GPUs instead of just two, and some of the data that needs to be communicated would not be contiguous. To keep the examples in this chapter simple, we focus on the described 1D domain decomposition. In summary, every iteration of the multi-GPU Jacobi iterative method consists of two phases: a computation phase, where the new values at the grid points are computed, and a communication phase, where the new values at the halo rows are exchanged between GPUs computing adjacent partitions. Moreover, since the L2 norm needs to encompass all the grid points in all the partitions, the communication phase additionally includes a reduction operation that reduces the grid-wide L2 norms computed by each GPU. Each of MPI, NCCL, and NVSHMEM provide their own mechanisms for exchanging data between GPUs. We will see how these operations can be done with each programming model throughout this chapter.

23.2 Multi-GPU stencil with MPI

There are two main categories of parallel programming models: shared memory models and distributed memory models. In shared memory models, different threads or processes have access to the same memory space, which simplifies data sharing. For example, CUDA kernels follow a shared memory model because different CUDA threads can access the same global memory variable using the same pointer. In distributed memory models, different threads or processes have access to distinct memory spaces. In this case, the sharing of data must be done explicitly, such as by passing messages. The dominating programming interface for computing clusters today is Message Passing Interface (MPI) [1], which is a set of API functions for communication between processes running in a computing cluster. MPI assumes a distributed memory model where processes exchange information by sending messages to each other. When an application uses API communication functions, it does not need to deal with the details of the interconnect network. The MPI implementation allows the processes to address each other using logical numbers, much the same way as using phone numbers in a telephone system: telephone users can dial each other using FIGURE 23.4 Programmer’s view of MPI processes.

Figure 23.5

FIGURE 23.5. Basic MPI API functions for establishing and closing a communication system.

phone numbers without knowing exactly where the called person is and how the call is routed. In a typical MPI application, data and work are partitioned among processes. As shown in Fig. 23.4, each node can contain one or more processes, shown as clouds within nodes. As these processes progress, they may need data from each other, such as when we need to perform halo exchange in the Jacobi iterative method. This need is satisfied by sending and receiving messages. In some cases, the processes also need to synchronize with each other and generate collective results, such as when reducing the L2 norm. This is done with collective communication API functions. Like CUDA, MPI programs are based on the SPMD parallel programming model. All MPI processes execute the same program. The MPI system provides a set of API functions to establish communication systems that allow the processes to communicate with each other. Fig. 23.5 shows five essential MPI functions that set up and tear down the communication system for an MPI application. Fig. 23.6 shows how an MPI application typically uses these functions. To launch an MPI application in a cluster, a user needs to supply the executable file of the program to the mpirun command or the mpiexec command, which creates the processes that run executable file.2 Each process starts by initializing the MPI runtime 2 While the MPI standard suggests mpiexec as the standard name for launching MPI processes, imple mentations such as Open MPI offer both as synonymous commands.

Figure 23.6

FIGURE 23.6. A simple MPI main program.

with a MPI_Init() call (line 03). This call initializes the communication system for all the processes running the application. Next, the MPI_Comm_rank() function is called (line 05), which returns a unique number to each calling process called the MPI rank of the process. The numbers received by the processes vary from 0 to the number of processes minus 1. The MPI rank for a process uniquely identifies the process in a communication, which is equivalent to the phone number in a telephone system. It is analogous to the expression blockIdx.x*blockDim.x + threadIdx.x for a CUDA thread. Recall that a CUDA thread can have up to three dimensions. Similarly, MPI ranks can be organized into multiple dimensions using MPI Cartesian communicators. The MPI_Comm_rank() function takes two parameters. The first one is an MPI builtin type MPI_Comm that specifies the scope of the request, i.e., the collection of processes that form the group identified by a MPI_Comm variable. Each variable of the MPI_Comm type is commonly referred to as a communicator. MPI_Comm and other MPI built-in types are defined in the “mpi.h” header file (line 01) that should be included in all program files that use MPI. An MPI application can create one or more communicators each of which specifies a group of MPI processes to be included when calling a communication function. MPI_Comm_rank() assigns a unique id to each process within the group specified by the communicator parameter when it is called. In Fig. 23.6, the parameter value passed is MPI_COMM_WORLD, which is used as a default and means that the communicator includes all MPI processes running the application.3 The second parameter to the MPI_Comm_rank() function is a pointer to an integer variable into which the function will deposit the returned rank value. In Fig. 23.6, a variable rank is declared for this purpose. After the MPI_Comm_rank() returns, the rank variable will contain the unique id for the calling process within the group of processes specified by the given communicator. In the MPI literature, the terms MPI process and MPI rank are used interchangeably.

3 Interested readers should refer to the MPI reference manual [1] for details on creating and using multiplecommunicators in an application, in particular the definition and use of intracommunicators and intercommunicators.

Next, the MPI_Comm_size() function is called (line 07), which returns the total number of MPI processes running in the communicator. The total number of MPI processes specified by a communicator is referred to as the number of ranks for the communicator. The MPI_Comm_size() function takes two parameters. The first parameter is of MPI_Comm type that gives the scope of the request. In Fig. 23.6, the parameter value passed in is MPI_COMM_WORLD, which means the scope of the MPI_Comm_size() is all the processes of the application. The second parameter is a pointer to an integer variable into which the MPI_Comm_size() function will deposit the return value. In Fig. 23.6, a variable numRanks is declared for this purpose. Since the scope of the call is all MPI processes, after the function returns, the variable numRanks contains the number of MPI processes running the application. This value is configured by the user when the application is executed using the mpirun command or the mpiexec command. Querying the value from the MPI runtime using MPI_Comm_size() avoids making implicit assumptions about how the application was launched when determining how many partitions need to be created. Next, the application program goes on to perform the main computation (line 08). We will discuss this part of the code in the rest of this section. After the application completes the main computation, it notifies the MPI runtime with a call to MPI_Finalize(), which frees all MPI communication resources allocated to the application (line 09). The application can then exit with a return value of 0, which indicates that no error has occurred (line 10). We now turn our attention to the main computation performed by each process in the MPI application. With each process knowing its rank and the number of ranks in the application, each process can identify what partition of the modeled system it is responsible for. The process then allocates GPU memory for its partition using the familiar cudaMalloc function, initializes that memory using the familiar cudaMemset function, and launches a simple kernel to initialize its partition’s boundary elements based on the boundary conditions of the system being modeled. We omit this initialization code and focus our attention on the main computation host code that iteratively performs the stencil computation, halo exchange, and L2 norm reduction. The code assumes a process P executes the host code in Fig. 23.7 on a host CPU, it allocates the output and input arrays in the global memory of the GPU connected to the host CPU. Each of these arrays contains ny × nx elements, as illustrated in Fig. 23.3. Note that the first row (elements 0 through nx-1) of the array consists of the halo elements from the top neighbor. Similarly, the last row (elements (ny-1)*nx through ny*nx-1) consists of the halo elements from the bottom neighbor. The main loop of the MPI-based multi-GPU host code is shown in Fig. 23.7. The loop iterates until the L2 norm drops below the minimum tolerance threshold or until the maximum number of allowed iterations is exceeded (line 01). In each iteration, the L2 norm is first initialized to 0 with a call to cudaMemset (line 04). Next, a function is called (line 07) that launches the Jacobi kernel implemented in Fig. 23.1. The Jacobi kernel performs one iteration of the stencil computation, reading the old grid point values in the input array and writing the new grid point values to the output array, while also updating the L2 norm. These arrays are swapped in each iteration in FIGURE 23.7 Host code for MPI-based multi-GPU implementation of the Jacobi iterative method.

a double-buffering fashion (line 27). We wait for the Jacobi kernel to finish execution (line 08) to ensure that the new grid point values are computed before we begin the halo exchange. The next step is to perform the halo exchange. The halo exchange requires the MPI processes to communicate with their neighbors to send their new boundary grid point values to each other. Such communication can be done with MPI point-to-point communication, which involves exchanging message between two communicating processes. MPI provides many different types of point-to-point communication routines. In our code example, we use the MPI_Sendrecv() routine. To understand what MPI_Sendrecv() does, let us first look at the more basic point-to-point communication routines that MPI provides. The most basic point-to-point communication routines in MPI are MPI_Send() and MPI_Recv(), where a source process calls the MPI_Send() function to send data to a destination process, and the destination process calls the MPI_Recv() function to receive that data from the source process. This is analogous to a caller dialing a call and a receiver answering a call in a telephone system. Because both sides of the communication must participate for the communication to take place, such point-to-point communication is referred to as two-sided communication. Fig. 23.8 shows the signature of the MPI_Send() function. The first parameter is a pointer to the starting location of the memory area where the data to be sent can be found. The second parameter is an integer that gives that number of data elements to be sent. The third parameter is of an MPI built-in type MPI_Datatype. It FIGURE 23.8 Signature of the MPI_Send() function.

Figure 23.9

FIGURE 23.9. Signature of the MPI_Recv() function.

specifies the type of each data element being sent as far as the MPI library implementation is concerned. The values that can be held by a variable or argument of the MPI_Datatype are defined in “mpi.h” and include MPI_DOUBLE (double-precision floating point), MPI_FLOAT (single-precision floating point), MPI_INT (integer), and MPI_CHAR (character). The exact sizes of these types depend on the size of the corresponding C types in the host processor. See the MPI reference manual for more sophisticated use of MPI types [1]. The fourth parameter for MPI_Send() is an integer that gives the MPI rank of the destination process. The fifth parameter gives a tag that can be used to classify the messages sent by the same process. The sixth parameter is a communicator that specifies the group of processes in which the destination MPI rank is defined. Fig. 23.9 shows the signature of the MPI_Recv() function. The first parameter is a pointer to the area in memory where the received data should be deposited. The second parameter is an integer that gives the maximum number of elements that the MPI_Recv() function is allowed to receive. The third parameter is an MPI_Datatype that specifies the type of each element to be received. The fourth parameter is an integer that gives the rank of the source of the message. The fifth parameter is an integer that specifies the tag value expected by the destination process. If the destination process does not want to be limited to a particular tag value, it can use MPI_ANY_TAG, which means that the receiver is willing to accept messages of any tag value from the source. For halo exchange, when a process sends its boundary data to its neighbor, it also needs to receive halo data from its other neighbor simultaneously. For example, in FIGURE 23.10 Signature of the MPI_Sendrecv() function.

Fig. 23.3, when process 1 (i.e., the process controlling GPU 1) sends its top boundary grid point values to process 0 (i.e., the process controlling GPU 0), process 2 (i.e., the process controlling GPU 2) will also be sending its top boundary grid point values to process 1. All processes need to send their boundary data to their top neighbors and receive halo data from their bottom neighbors simultaneously. For such situations, MPI provides the MPI_Sendrecv() function that sends data to a destination and receives data from a source simultaneously. The signature of the MPI_Sendrecv() function is shown in Fig. 23.10. It is a combination of MPI_Send() and MPI_Recv() functions so we will not further elaborate on the meaning of the parameters. The same objective can also be accomplished using MPI non-blocking communication. In particular, we could initiate a non-blocking send using the MPI_Isend function and a non-blocking receive using the MPI_Irecv function, and then wait for the two operations to finish using the MPI_Wait function. These non-blocking communication functions enable expressing more complex communication patterns that requires concurrent sending and receiving to and from different neighbors. However, the MPI_Sendrecv() function provides a convenient way of expressing the particular concurrent communication pattern that we are interested in using just a single API call. Interested readers can refer to the MPI documentation for more details on how to use non-blocking communication functions [1] We now turn our attention back to the code in Fig. 23.7, particularly the code that performs the halo exchange (lines 11-18). First, each process identifies the neighbor process at its top (line 11) and the one at its bottom (line 12). Rather than simply computing rank - 1 and rank + 1, the code uses a wrap-around strategy where the topmost rank treats the bottommost rank as its top neighbor, and vice versa. This wrap-around strategy is often referred to as the periodic boundary condition technique for modeling a large system by simulating only a small portion of it without introducing a disproportional amount of edge effects. Such boundary conditions require special handling of the top and the bottom ranks since they would not have a top neighbor and bottom neighbor, respectively, to communicate with.

Next, we have two calls to MPI_Sendrecv that perform the halo exchange. The first call (lines 13-15) sends the top boundary row, which starts at output + nx, to the top neighbor, and receives the bottom halo row, which starts at output + (ny - 1)*nx, from the bottom neighbor. The second call (lines 16-18) sends the bottom boundary row, which starts at output + (ny - 2)*nx, to the bottom neighbor, and receives the top halo row, which starts at output, from the top neighbor. In all cases, the number of elements communicated is nx, the size of the row, and the datatype of MPI_FLOAT, which corresponds to the float datatype in C and C++. It is important to note that the output and input pointers passed to the MPI_Sendrecv function are pointers to the GPU device memory. Passing GPU device memory pointers to MPI functions is possible with CUDA-aware MPI. If the MPI implementation used is not CUDA-aware, the programmer would have needed to copy the data from device memory to host memory and invoke the MPI communication function on the host memory array. In contrast, CUDA-aware MPI implementations are aware of the CUDA programming model and are designed to allow communication functions to be invoked on CUDA global memory arrays directly. Allowing send and receive functions to work directly on the device arrays eliminates the need for cudaMemcpy calls in the source code and thus minimizes the bloat to the host code size as well as the added communication latency. Most MPI implementations (e.g., MPICH [6], OpenMPI [7], MVAPICH2 [8]) are designed to be CUDA-aware and are built with this feature enabled. After the halo exchange, the host code needs to calculate the L2 norm to identify if the system has significantly changed and we need to continue iterating. Each GPU has already computed the square of the L2 norm of its own partition’s residual. However, we still need to sum up these L2 norm squares across all the partitions. In other words, we need to perform a reduction operation across all the MPI ranks, where each rank contributes its own partition’s L2 norm square. Such a reduction across ranks can be done with MPI collective communication. In contrast with MPI point-to-point communication, such as MPI_Sendrecv, which involves communicating between two ranks, MPI collective communication involves communicating between all ranks in the communicator. The commonly used types of MPI collective communication are barrier, broadcast, reduce, gather, and scatter. We will not elaborate on all types of MPI collective communication functions but encourage the reader to read the MPI programming guide [1] for the details of these functions. In general, collective communication functions are highly optimized by the MPI runtime developers and system vendors. Using the collective communication functions usually leads to better performance as well as readability and productivity than trying to achieve the same functionality with sequences of send and receive calls. The MPI collective communication function that we are interested in for computing the L2 norm is MPI_Allreduce. The MPI_Allreduce function takes a buffer of values from each rank, reduces the buffers into a single buffer, and gives a copy of that buffer to each rank. Fig. 23.11 shows the signature of the MPI_Allreduce function. The first parameter, sendbuf, specifies the input buffer that each rank contributes to the reduction operation. The second parameter, recvbuf, specifies where the final FIGURE 23.11 Signature of the MPI_Allreduce() function.

23.3 Overlapping computation and communication

buffer containing the result of the reduction should be placed. That is, every element in the receive buffer contains the reduced value of the elements at the same index in the send buffers of all the ranks. The third parameter, count, specifies the number of elements in the send buffer, which is equal to the number of elements in the receive buffer as well. The fourth parameter, datatype, specifies the type of the elements being reduced, such as integer, floating point, etc. The fifth parameter, op, specifies the reduction operation being performed. MPI provides many built-in reduction operations such as sum, product, minimum, maximum, logic operations, etc. The sixth and final parameter, comm, specifies the communicator whose ranks are participating in the reduction operation. We now turn our attention back to the code in Fig. 23.7, particularly the code that reduces the L2 norm (lines 20-25). First, the partition’s square of the L2 norm is copied from the device to the host (line 21). Next, the MPI_Allreduce collective is used to reduce the L2 norm squares across all ranks (line 24). The number of elements in the buffers (third parameter) in this case is 1 since each rank contributes one value, which is its partition’s L2 norm square. The reduction operation (fifth parameter) is MPI_SUM, which indicates that we would like to calculate the sum of the L2 norms across all the ranks. After MPI_Allreduce returns, every rank now has the sum of all the L2 norm squares. The square root of this value is calculated yielding the ultimate L2 norm across the entire system (line 25), which is used to check whether or not the loop should continue iterating (line 01). The reader may wonder why the square of the L2 norm was copied from the device to the host before invoking MPI_Allreduce. We could have invoked MPI_Allreduce directly on the GPU buffer since it is CUDA-aware. The reason is that the result of MPI_Allreduce is needed on the host to check for convergence, so it needs to be copied to the host anyway. In this case, it is more efficient to copy it to the host before invoking MPI_Allreduce.

In our multi-GPU stencil implementation in Section 23.2, each process computes the new values of its entire partition, exchanges the halo data with the top and bottom FIGURE 23.12 A two-stage strategy for overlapping computation with communication.

neighbors, and repeats. While this strategy is very simple, it is not very efficient. The reason is that this strategy forces the system to be in one of two modes, where each mode only utilizes part of the system. In the first mode, all processes are performing computation using the GPUs. During this time, the communication network is not used. In the second mode, all processes are exchanging halo data with their top and bottom neighbors using the communication network. During this time, the GPU compute hardware is not well utilized. Ideally, we would like to achieve better performance by utilizing both the communication network and GPU compute hardware all the time. This improved utilization can be achieved by dividing the computation tasks of each process into two stages, as illustrated in Fig. 23.12. During the first stage (Stage 1), each process calculates its boundary rows that are needed as halo cells by its neighbors in the next iteration. Fig. 23.12 shows the boundary rows computed in this stage as colored rows. For example, GPU 1 calculates its top and bottom boundary rows, which are the halo rows of GPU 0 and GPU 2, respectively. The rationale is that these boundary rows are needed by the neighbors for the next iteration. By calculating these boundary rows first, the data can be communicated to the neighbors in the second stage while the rest of their internal grid points are calculated. During the second stage (Stage 2), each process performs two activities in parallel. The first is to communicate its new boundary values to its neighbor processes. The second activity is to calculate the rest of the data in the partition. If the communication activity takes a shorter amount of time than the calculation activity, we can hide the communication delay and fully utilize the computing hardware most of the time. This is usually achieved by having enough rows in the internal part of each partition to allow each process to perform enough computation to hide the communication. Fig. 23.13 compares the timeline of execution without and with overlapping computation and communication. In Fig. 23.13(a), when computation and communication FIGURE 23.13 Comparing timelines without and with overlapping computation and communication.

are not overlapped, the entire computation is performed by the compute hardware while the communication network is idle. Subsequently, the top and bottom halos are exchanged over the communication network while the compute hardware is idle. The L2 norm reduction is also performed. In contrast, in Fig. 23.13(b), the top and bottom grid points are computed distinctly from the internal grid points, and the top and bottom halo exchanges are initiated as soon as the corresponding grid points are computed. For GPUs with a sufficient amount of compute resources, grid points in the three categories can be computed concurrently. However, priority should be given to the boundary grid points in order to initiate the halo exchange as soon as possible. Importantly, the internal grid points continue to be computed while the halo exchanges are performed. This overlap between computing the grid points and performing the halo exchanges ensures that both the compute hardware and communication network are utilized simultaneously, resulting in the overall execution to finish sooner. Inevitably, reducing the L2 norm cannot be overlapped because it depends on all the grid points being computed. Accomplishing this kind of overlap between communication and computation requires splitting the Jacobi kernel call into separate kernel calls for computing the boundary elements and the internal elements. For example, we can split the kernel call into three different calls: one for the top boundary row, one for the bottom boundary row, and one for the internal elements. In this way, the halo exchanges can be initiated as soon as the kernels processing the boundary rows are done. To execute these three kernels concurrently and synchronize the communication activities with each of them independently, we need to use an important feature of the CUDA programming model which is CUDA streams. In CUDA, a stream is an ordered sequence of CUDA operations. These operations could include kernel calls and memory copies, among other things. All operations in the same stream are done sequentially according to the order in which they are placed into that stream. On the other hand, operations in different streams may be executed concurrently without any ordering constraint. Hence, to get the three aforementioned Jacobi kernels to execute concurrently, we should insert them into three different streams, which starts with the creation of stream objects in the following code: cudaStream_t topStream, bottomStream, internalStream; cudaStreamCreate(&internalStream); cudaStreamCreate(&topStream); cudaStreamCreate(&bottomStream);

The first line declares three stream objects of type cudaStream_t. The stream objects are named topStream, bottomStream, and internalStream, referring to the streams that will contain the calls to the kernels that process the top boundary row, the bottom boundary row, and the internal rows, respectively. The next three lines create these streams by calling cudaStreamCreate and passing to it a pointer to the stream object. Each call to cudaStreamCreate() creates a new stream and initializes the state of that stream. To insert a kernel call into a particular stream, the stream object can be passed as a configuration parameter for the kernel call. Recall from Chapter 2 that a kernel call takes two required configuration parameters in triangle brackets, the first being the grid dimension and the second being the block dimension. Also recall from Chapter 5 that the kernel call takes an optional third configuration parameter which is the size of the dynamically allocated shared memory. If not specified, the value is 0 by default. Similarly, the kernel call also takes an optional fourth configuration parameter which is the stream into which the kernel call is to be inserted. If not specified, the kernel call is inserted into a default stream. The following code shows how a kernel call can be inserted into a specific stream: kernelName«<dimGrid, dimBlock, 0, myStream»>(…)

This code inserts a call to kernel kernelName with a grid dimension specified in dimGrid, a block dimension specified in dimBlock, and zero dynamically allocated shared memory, and inserts itself into the stream specified in myStream. Note that returning from the call does not mean that the kernel has been executed. It simply means that the kernel has been inserted into the designated stream. The execution of the host code will continue with the following code as soon as the kernel has been inserted into the stream. The fact that a kernel call in the host code inserts the kernel into a stream, rather than actually executing the kernel, makes the CUDA kernel calls asynchronous. Furthermore, the continued execution of the host code after the kernel call does not mean that the corresponding thread grid has completed executing the kernel. It does not even mean that the thread grid has started executing the kernel. It simply means that the kernel has been inserted into the designated stream and a grid will eventually be launched to execute the kernel after all preceding operations in the stream have completed their execution.

Figure 23.14

FIGURE 23.14. Host code for MPI-based multi-GPU implementation of the Jacobi iterative method that overlaps computation and communication.

Having seen how to create streams and insert kernel calls into them, we now proceed to split our Jacobi kernel into three calls to be inserted into three different streams. Fig. 23.14 shows the host code for the MPI-based multi-GPU implementation of the Jacobi iterative method that overlaps computation and communication. Compared to the code in Fig. 23.7 which calls the launch_jacobi_kernel a single time launching a single kernel per iteration, the code in Fig. 23.14 makes three different calls to compute the top boundary row (line 10), the bottom boundary row (line 12-13), and the internal grid points (line 15-16). To compute the top boundary row (line 10), the function needs the first three rows (top halo row, top boundary row, and top internal row) as an input so we pass the output and input pointers as they are, and pass 3 as the fourth parameter indicating that there are three input rows of interest. Importantly, we also pass topStream as anadditional parameter, into which the launch_jacobi_kernel function inserts the kernel call. As for the bottom boundary row (line 12-13), the function needs the last three rows (bottom halo row, bottom boundary row, and bottom internal row) as an input so we pass the output + (ny - 3)*nx and input + (ny - 3)*nx pointers which point to the beginning of the last three rows, and pass 3 as the fourth parameter indicating that there are three input rows of interest. We also pass bottomStream as the stream into which the kernel call is inserted. Finally, to calculate the internal grid points (line 15-16), the function needs all the rows except the top halo and bottom halo rows so we pass output + nx and input + nx pointers which skip the first halo row, and pass ny - 2 as the fourth parameter omitting the two halo rows. We also pass internalStream as the stream into which the kernel call is inserted. One important consideration to keep in mind when executing the three kernels concurrently in three different streams is that these kernels may execute in any order. The likely scenario is that the kernels computing the boundary grid point values will execute first because they were called first, but this ordering is not guaranteed. It is possible for the kernel computing the internal grid point values to execute first and occupy all the GPU resources, preventing the kernels computing the boundary grid point values and the subsequent halo exchange from executing, and thereby not achieving the desired overlap between computation and communication. To avoid such a situation, we need to give higher priority for the kernel computing the boundary grid point values than we give to the kernel computing the internal grid point values. In other words, we need to give higher priority to the topStream and bottomStream than we do to the internalStream. By default, streams created with cudaStreamCreate have the same priority. To assign different priorities to different streams, we need to use different CUDA API functions. The following code shows how streams can be created with different priorities: int low, high; cudaDeviceGetStreamPriorityRange(&low, &high); cudaStreamCreateWithPriority(&internalStream, cudaStreamDefault, low); cudaStreamCreateWithPriority(&topStream, cudaStreamDefault, high); cudaStreamCreateWithPriority(&bottomStream, cudaStreamDefault, high);

On the second line, the function cudaDeviceGetStreamPriorityRange returns the range (high value and low value) of stream priority values supported by the CUDA runtime. The third and fourth/fifth lines then use cudaStreamCreateWithPriority to create the internalStream and topStream/bottomStream with the lowest and highest priority, respectively. In our example, we are only interested in distinguishing between two kinds of streams, so two priority values are sufficient. In other cases, when may be interested in more than two priority levels and use intermediate values as well. The absolute values of the priority values are not important. Only their relative values matter.

Having inserted the three Jacobi kernel calls into three different streams so they may execute concurrently, we now turn our attention to how we can wait for specific kernels to finish before initiating subsequent tasks such as halo exchange. CUDA provides a function cudaStreamSynchronize that waits for all preceding (existing) tasks in a specific stream to finish executing. We can use this function to wait for the kernels that compute the top and bottom boundary rows to finish executing before initiating the top and bottom halo exchanges, as shown in Fig. 23.14. Compared to the code in Fig. 23.7, Fig. 23.14 adds a call that waits for the kernel calculating the top boundary row in topStream to finish (line 27) before calling MPI_Sendrecv to perform the halo exchange of that top boundary row. Similarly, Fig. 23.14 adds a call that waits for the kernel calculating the bottom boundary row in bottomStream to finish (line 32) before calling MPI_Sendrecv to perform the halo exchange of that bottom boundary row. In the meantime, since the kernel solving the internal rows is in internalStream which we have not synchronized on, that kernel may proceed to execute concurrently as the MPI_Sendrecv halo exchanges are being performed. In this way, we have enabled overlapping computation of the internal rows with communication of the halo rows. Although splitting the kernel call into three different calls enables synchronizing on the three calls independently for the purpose of halo exchange, it introduces a challenge when it comes to computing the L2 norm. All three kernels update the same L2 norm, which means that all three kernels must wait for the L2 norm to be initialized to 0, and all three kernels must complete before the L2 norm can be copied to the host and reduced across ranks. However, the kernel calls are placed in three different streams, but the calls to initialize and copy the L2 norm can only go in a single stream. To overcome this challenge, we need to be able to have operations in one stream wait for operations in another stream to complete. Such interaction between streams can be accomplished with CUDA events. In CUDA, an event is a marker that marks a certain point in a stream. CUDA allows programmers to synchronize on specific events, i.e., wait for the execution in a stream to reach the point marked by the event. Such synchronization can be done by the host thread, or a synchronization operation on an event can be placed in another stream. The latter capability is the one we are interested in for the purpose of initializing and copying the L2 norm. To initialize the L2 norm to zero in the GPU’s global memory, the code in Fig. 23.7 uses cudaMemset which is a blocking function call that does not return until the initialization operation is complete. In contrast, the code in Fig. 23.14 uses a variant of cudaMemset, cudaMemsetAsync (line 04), that is non-blocking. Like kernel calls, the cudaMemsetAsync function inserts the initialization operation into the stream specified by an additional parameter. In our case, we place cudaMemsetAsync in internalStream which ensures that subsequent operations in internalStream (i.e., the kernel call that solves the internal rows) do not execute before cudaMemsetAsync completes. However, we also need to make sure that the other two kernels that calculate the top and bottom boundary rows do not execute before cudaMemsetAsync completes. This can be done by inserting an event in internalStream after cudaMemsetAsync, and inserting waiting (i.e., synchronization) operations that wait for that event in topStream and in bottomStream before the kernels. The following code shows how an event can be created for the aforementioned synchronization purpose: cudaEvent_t resetL2; cudaEventCreateWithFlags(&resetL2, cudaEventDisableTiming);

The first line declares an event object of type cudaEvent_t. The second line creates the event by calling cudaEventCreateWithFlags with a pointer to the event object as its first parameter. The second parameter, cudaEventDisableTiming, is a compile-time constant indicating that we do not wish to use this event for timing purposes, which allows synchronization activities based on the event to be implemented more efficiently. With the event created, we can place it in the internalStream after the call to cudaMemsetAsync using the function cudaEventRecord as shown in Fig. 23.14 (line 05). In this case, the event resetL2 now marks the completion of the cudaMemsetAsync operation. To insert waiting operations for that event in another stream, namely topStream and bottomStream, we can use the function cudaStreamWaitEvent as shown in Fig. 23.14 (lines 06-07). The first parameter specifies the stream into which the waiting operation should be inserted, namely topStream (line 6) and bottomStream (line 7). The second parameter specifies the event that the operation is waiting for, namely resetL2 for both. The third parameter indicates if any special options should be used for the waiting operation. The 0 value for the third parameter indicates that the default option should be used. We now turn our attention to copying back the L2 norm after all three kernels have completed execution. In Fig. 23.7, this copy was done using cudaMemcpy. In contrast, the code in Fig. 23.14 uses a variant of cudaMemcpy, cudaMemcpyAsync (line 21), that is non-blocking and takes an additional parameter for the stream it is to be placed in. In our case, we place cudaMemcpyAsync in internalStream which ensures that it waits for preceding operations in internalStream (i.e., the kernel call that calculates the internal rows). However, we also want it to wait for the other two kernels that solve the top and bottom boundary rows. This can be done by inserting events in topStream and bottomStream after the kernel calls, and inserting waiting operations for them in internalStream before cudaMemcpyAsync. Indeed, the code in Fig. 23.14 uses cudaEventRecord to insert such events in topStream (line 11) and bottomStream (line 14), and inserts waiting operations for these events in internalStream (lines 19-20) before the memory copy operation. One further optimization applied to our host code in Fig. 23.14, based on the fact that cudaMemcpyAsync is non-blocking, is that we can use cudaMemcpyAsync to insert the memory copy of the l2norm from the global memory to the host memory before the calls to MPI_Sendrecv as shown in Fig. 23.14. Doing so overlaps the FIGURE 23.15 An example timeline for overlapping computation and MPI communication using CUDA streams and events.

memory copy from the GPU to the host CPU with the network communication performing the halo exchange if the kernel computing the internal grid points finishes before the halo exchange does. However, we must ensure that the memory copy completes before the call to MPI_Allreduce is performed. This can be done with a call to cudaStreamSynchronize which waits for the internalStream where cudaMemcpyAsync is executing (line 37). Fig. 23.15 illustrates how the host code in Fig. 23.14 accomplishes the goal of overlapping the computation of the internal grid points and the exchange of halos within each iteration of the Jacobi solver (line 04 through line 41). The four timelines show the activities of the host CPU, topStream, bottomStream, and internalStream. For the host CPU, each slot is either an insertion into one of the streams (marked with the line number of the host code in Fig. 23.14) or the nature of the activities performed by the host CPU. For each operation in one of the streams, a slot in the host timeline marks the time of insertion whereas a slot in the stream shows the time of execution by the GPU. A solid line associates the insertion with the execution. For example, the host timeline slot for line 10 of the host code inserts the Jacobi kernel (for calculating the top grid points) into topStream. Note that the kernel call has to wait for the resetL2 event so its execution is delayed. If the reset operation for l2Norm takes less (more) time, the Jacobi kernel would be executed earlier (later). A dotted arrow represents how an event allows a waiting operation to complete its execution. For example, a dotted arrow goes from the event resetL2 to the wait operation on resetL2 in topStream. Soon after the cudaMemset operation is complete, the resetL2 event is reached, allowing the wait operation on resetL2 to complete. The completion of the wait operation, in turn, allows the Jacobi kernel call for the top grid points in the same stream to proceed. A thick dotted line shows how reaching a point in a stream allows the corresponding cudaStreamSynchronize function called on the host to return, thereby allowing the host to proceed to subsequent activities. For example, the thick dotted line immediately after the bottom event of bottomStream indicates the point in time when cudaStreamsynchronize on bottomStream can return. Since cudaStreamSynchronize function starts execution after this point, it will immediately return and unblock the halo exchange for the bottom grid points. An important observation from Fig. 23.15 is that host synchronization can cause significant latency between the completion of a compute operation, e.g., the Jacobi kernel in the Top Stream, and dependent data transfer operations, e.g., MPI Exchange Top by the host. This extra latency is commonly referred to as synchronization overhead and can significantly impact the achieved overlap between operations, e.g., the Jacobi kernel in the Internal Stream and the MPI Exchange operations in the Host. For example, because the MPI Exchange call is blocking, the host’s stream synchronization for the Bottom Stream and MPI Exchange Bottom cannot start until the MPI Exchange Top is complete. It should be clear that this blocking causes additional latencies between the completion of the Jacobi kernel in the Bottom stream and the MPI Exchange for the bottom cells, thus reducing the amount of overlap between the MPI Exchange operations and the Jacobi kernel in the Internal stream in Fig. 23.15. Reducing such synchronization overhead is an important design goal of NCCL and NVSHMEM, which will be presented in Sections 23.4 and 23.5, respectively. One important detail to note is that since the host memory pointed to by l2norm_h is involved in asynchronous memory operations such as cudaMemcpyAsync, it cannot be allocated using the standard host memory allocation methods such as malloc(). Instead, it must be allocated in pinned memory, sometimes also referred to as page locked memory. Pinned memory allocation can be performed using the cudaMallocHost function as follows: float* l2norm_h; cudaMallocHost(&l2norm_h, sizeof(float));

To fully understand the concept of pinned memory and why it is needed for asynchronous copies, we first need to know a little more background on the memory management in operating systems. In a modern computer system, the operating system manages the memory address spaces of many applications simultaneously. Each application has access to a large and logically consecutive address space called a virtual address space. In reality, the system only has a limited amount of physical memory that needs to be shared among all running applications. This sharing is done by partitioning the virtual address spaces of applications into virtual pages and mapping these pages to physical pages in the physical memory. Mapping virtual pages to physical pages achieves multiple goals. One goal is to ensure that processes cannot access each other’s pages inphysical memory without explicit sharing arrangements. They can only access the physical pages that are mapped into their own virtual address space. Another goal is to accommodate situations when there is higher demand for memory than the amount of physical memory available. In such cases, only the most actively used virtual pages are mapped to physical pages while the others are placed on disk. As part of this process, the operating system may need to page out'' some of the pages from the physical memory to mass storage such as disks to make room for other pages. Therefore, an application may have its data paged out of physical memory at any time during its execution. The implementation of cudaMemcpy() uses a type of hardware called a Direct Memory Access (DMA) device. When a cudaMemcpy() function is called to copy between the host and device memories, its implementation uses a DMA to complete the task. On the host memory side, the DMA hardware operates on physical addresses. That is, the operating system needs to give a translated physical address to the DMA. However, there is a chance that the data may be paged out before the DMA operation is complete. The physical memory locations for the data may be re-assigned to other data corresponding to a different virtual memory location. In this case, the DMA operation can be potentially corrupted since its data can be overwritten by the paging activity. A common solution to this data corruption problem is for the CUDA runtime to perform the copy operation in two steps. For a host-to-device copy, the CUDA runtime first copies the source host memory data into a pinned’’ memory buffer, which means that the memory locations are marked so that the paging mechanism will not page out the data. It then uses the DMA device to copy the data from the pinned memory buffer to the device memory. For a device-to-host copy, the CUDA runtime first uses a DMA device to copy the data from the device memory into a pinned memory buffer. It then copies the data from the pinned memory buffer to the destination host memory location. By using an extra pinned memory buffer, the DMA copy will be safe from any paging activities. There are two problems with this approach. The first problem is that the extra copy adds delay to the cudaMemcpy() operation. The second problem is that the extra complexity involved leads to a synchronous implementation of the cudaMemcpy() function. That is, the host cannot continue to execute until the cudaMemcpy() function completes its operation and returns because the host needs to be involved in the memory copy operation. In order to support asynchronous copies such as cudaMemcpyAsync(), we need to eliminate the step where the host copies the data from a regular memory buffer to a pinned memory buffer. For this reason, the cudaMemcpyAsync() function requires that the host memory buffer passed to it be already allocated as a pinned memory buffer.

23.4 Multi-GPU stencil with NCCL

The multi-GPU implementation of the Jacobi iterative method described in Section 23.3 is effective at overlapping computation and communication by using concurrent asynchronous kernel calls, memory copies, and CUDA streams. However, the implementation still has some synchronization points that introduce inefficiency. If we look back to the code in Fig. 23.14, we observe that the host thread calls cudaStreamSynchronize (lines 27 and 31) before the calls to MPI_Sendrecv to ensure that the kernels computing the top and bottom boundary rows are complete before initiating the network communication for the halo exchange. During this time, the cudaStreamSynchronize function blocks the host thread from executing any of the subsequent statements in the host code. This need to involve the host thread in the synchronization means that the host cannot be used to perform other useful work. This inefficiency can be overcome if we free the host thread from the burden of synchronizing between CUDA operations such as kernel calls and communication operations. In other words, if the communication operations themselves could be placed inside the streams, then the stream mechanism can simply be used to initiate the communication operations as soon as the operations that they depend on are complete, and without involving the host thread. This desire to perform the communication operations within the context of the CUDA streams is one motivation behind the NVIDIA Collective Communications Library (NCCL) [2]. NCCL is a library that provides various inter-GPU communication primitives. It supports both point-to-point communication, such as send and receive primitives, and collective communication, such as reduce, broadcast, scatter, and gather primitives. While the communication primitives in NCCL resemble those in MPI, an important difference is that NCCL communication primitives run on the GPU, not the host CPU, and can be placed inside of CUDA streams. Hence, using NCCL frees the host thread from having to serve as a synchronizing intermediary between kernel calls and communication primitives. Another benefit of NCCL communication primitives is that they are highly optimized for multi-GPU communication, both within and across nodes, in a topology-aware manner. NCCL thus frees developers from the burden of optimizing their communication routines for specific systems and interconnects. NCCL supports multiple interconnect technologies such as PCIe, NVLINK, InfiniBand Verbs, and sockets. NCCL is not a complete replacement for MPI, but rather, a library that can be used in conjunction with MPI to enhance multi-GPU communication. To use NCCL in conjunction with MPI, we must set up and tear down the NCCL communication system similar to how we set up and tear down the MPI communication system. To set up and tear down the NCCL communication system, there are three important NCCL API functions that we need to be aware of: ncclGetUniqueId, ncclCommInitRank, and ncclCommDestroy. The signatures and descriptions of these three functions are shown in Fig. 23.16. Fig. 23.17 shows how the API functions in Fig. 23.16 are typically used for setting up and tearing down the NCCL communication system in conjunction with doing so for an MPI communication system. The code for setting up and tearing down the MPI communication system is the same as that in Fig. 23.6. Compared to Fig. 23.6, Fig. 23.17 additionally includes a header file to access the NCCL API functions (line 02) and uses the API functions to set up (lines 09-14) and tear down (line 16) the NCCL communication system.

Figure 23.16

FIGURE 23.16. Basic NCCL API functions for establishing and closing a communication system.

Figure 23.17

FIGURE 23.17. A simple MPI + NCCL main program.

Similarly to MPI, NCCL communication operations are based on the concept of communicators that specify all the entities involved in each operation. Thus, one must create a NCCL communicator before a group of n CUDA devices can communicate with each other using NCCL. When creating a NCCL communicator, a unique rank between 0 and n − 1 has to be assigned to each CUDA device which is part of the communicator. If there is a 1-to-1 mapping between MPI processes/threads and CUDA devices in an application, one can simply use their MPI ranks for the NCCL ranks, which is the case in the example host code in Fig. 23.17. Given assigned ranks, the next step is to create a unique object which will be used by all processes and threads to synchronize and understand that they are part of the same communicator. This should be done by only one of the ranks calling the ncclGetUniqueId function. In Fig. 23.17, rank 0 calls ncclGetUniqueId to create a unique ID (line 10). The MPI_Bcast function is then used to send this unique object from rank 0 to all other MPI ranks (line 11). Note that all receiving ranks must FIGURE 23.18 NCCL API functions for sending and receiving data.

also execute the MPI_Bcast function to receive the broadcasted object. The reader is referred to the MPI user guide for details of the MPI_Bcast function. Briefly, the parameters specify the address of the data to be broadcasted, its size, its type, the rank that is doing the broadcast (rank 0 in this case), and the scope of the broadcast which is all the MPI ranks in the application. A call to MPI_Barrier forces all the ranks to wait for each other to receive the ID object before creating the communicator (line 12). Next, all ranks call ncclCommInitRank to intialize the NCCL communicator object in each rank and the communication system (line 14). They all pass the same ncclID to ncclCommInitRank which registers the participating ranks as part of the same communicator that is replicated into each rank. Finally, at the end of the main function, the call to ncclCommDestroy tears down the NCCL communication system (line 16). We only need to use one communicator in our examples, however, interested readers should refer to the NCCL user guide for details on using multiple NCCL communicators and multiple NCCL communication systems in an application. Having seen how to set up and tear down a NCCL communication system, we now turn our attention to how we can use NCCL primitives, i.e., API functions, instead of MPI_Sendrecv for performing the halo exchange. For this purpose, the communication primitives we are particularly interested in are ncclSend and ncclRecv. The signatures and descriptions of these two functions are shown in Fig. 23.18. Note that the functions resemble the MPI_Send and MPI_Recv functions, with one major difference. The difference is that they are asynchronous functions that accept a CUDA stream object for the stream in which they should be executed. Recall from Section 23.2 that we could not use MPI_Send and MPI_Recv for halo exchange because each rank needs to simultaneously send data to one rank and receive data from another rank. For this reason, we resorted to MPI_Sendrecv which fuses the FIGURE 23.19 NCCL API functions for grouping communication primitives together.

two operations in one. However, NCCL does not provide a similar function that consists of a fused send and receive operation. Instead, NCCL provides a feature for fusing communication primitives which is group calls. In NCCL, a set of communication primitives can be fused together by sandwiching them in between calls to two API functions: ncclGroupStart and ncclGroupEnd. The descriptions of these two functions are shown in Fig. 23.19. Accordingly, a fused send and receive operation can be achieved by placing calls to ncclSend and ncclRecv in between calls to ncclGroupStart and ncclGroupEnd. NCCL primitives will run concurrently on each CUDA device, ensuring that each device will be able to send its boundary grid points to one of its neighbors while simultaneously receiving its halo grid points for the other neighbor. We are now ready to show how the halo exchange that overlaps computation and communication can be achieved with NCCL. Fig. 23.20 shows the host code for such a NCCL-based implementation. Compared to the MPI-based host code in Fig. 23.14, the main change in Fig. 23.20 is in the halo exchange (lines 25-36). Here, each call to MPI_Sendrecv is replaced with a call to ncclSend and a call to ncclRecv sandwiched between calls to ncclGroupStart and ncclGroupEnd. Importantly, instead of synchronizing on topStream and bottomStream before the calls using cudaStreamSynchronize(), we pass the streams to ncclSend and ncclRecv as their last parameter. The CUDA runtime ensures that these communication primitives are initiated after the preceding kernels in the streams finish computing the corresponding halo rows. An important distinction between the call to MPI_Sendrecv and the group call to ncclSend and ncclRecv is that MPI_Sendrecv is blocking. In other words, MPI_Sendrecv does not return until the communication is complete. On the other hand, the group call to ncclSend and ncclRecv is non-blocking. Even after the call to ncclGroupEnd, the only guarantee is that ncclSend and ncclRecv have been inserted into the specified stream. For this reason, we need to take further action to ensure that we do not begin the next iteration before the halo exchange communication is actually complete. This can be done by recording the events exchangeTop and exchangeBottom in the topStream and the bottomStream after their respective calls to ncclSend and ncclRecv (line 31 and 36), and synchronizing on these events in the internalStream before proceeding to the next iteration (line 43-44). Fig. 23.21 illustrates the timelines achieved by the host code in Fig. 23.20 while overlapping computation and communication using NCCL. Compared to the timelines in Fig. 23.15, the key difference is that the halo exchange has moved from being MPI calls in the host timeline to NCCL group calls in the topStream and bottomStream timelines. Moreover, the synchronization on these two streams has moved from being a stream synchronization in the host timeline to event synchronizations in the FIGURE 23.20 Host code for NCCL-based multi-GPU implementation of the Jacobi iterative method that overlaps computation and communication.

internalStream timeline. Consequently, the host is now free from the communication and synchronization operations, except for the synchronization on the internal stream before the call to MPI_Allreduce.

23.5 Multi-GPU stencil with NVSHMEM

So far, we have seen how to use MPI and NCCL to perform data communication for the purpose of halo exchange. The style of communication used by both MPI and FIGURE 23.21 An example timeline for overlapping computation and NCCL communication using CUDA streams and events.

NCCL is referred to as two-sided communication. The communication is two-sided because for a process to send data to or receive data from another process, the two processes have to both be executing corresponding primitives. In the case of MPI, the call to MPI_Sendrecv in the sending process must have a corresponding call to MPI_Sendrecv in the receiving process. In the case of NCCL, the call to ncclSend in the sending process must have a corresponding call to ncclRecv in the receiving process. The reason that both processes have to be involved is that the sending process specifies where the communicated data is coming from, whereas the receiving process specifies where the communicated data should be placed after being received. During actual execution, the sending and receiving processes need to wait for each other to reach these calls to initiate the communication, which incurs additional latency. An alternative form of communication that is commonly used in parallel computing is one-sided communication. In one-sided communication, a process can send data to or receive data from another process without involving the other process. The process directly accesses the other process’ address space with put operations that store data to the other process’ address space, or get operations that load data from the other process’ address space. The ability to directly access parts of another process’ address space without waiting for the other process to become available reduces the latency of data communication. It also enables the communication to be initiated by threads executing on the device since matching send and receive calls is not scalable to hundreds of thousands of threads executing on the device, but one-sided put and get operations are. A commonly used library for one-sided communication is OpenSHMEM [9]. NVIDIA provides an implementation of OpenSHMEM for clusters of GPUs called the NVIDIA OpenSHMEM Library (NVSHMEM) [3]. NVSHMEM allows put and get operations to be initiated by the host threads or by individual device threads of a FIGURE 23.22 NVSHMEM API functions for allocating, putting, and getting data in the symmetric heaps.

kernel. That is, any thread running on the CPU or GPU in one process can directly load or store data to part of the memory space of another GPU in another process. In NVSHMEM terminology, a process or rank is referred to as a processing element (PE). The reader may wonder how threads in a process initiating a put or get operation can know the address of the accessed data object in the target process’ address space. In two-sided communication, this address is specified by the matching call executed by the target process, whereas in one-sided communication, the initiating process needs to specify it. To enable the initiating process to specify addresses in the target process’ address space, a symmetric heap is used. Each process allocates a portion of its address space to locally accommodate the symmetric heap, and all processes allocate corresponding memory objects within their address spaces at the same offset in their respective local instances of the symmetric heap. Hence, for an initiating process to access an object in a target process’ address space, it can simply provide the address of the corresponding object in its own address space. The runtime can then infer the object’s offset, and consequently, the address of the object in the target process’ address space. Fig. 23.22 shows the NVSHMEM API functions for allocating objects in the symmetric heap (nvshmem_malloc and nvshmem_free) and accessing them from within kernels (nvshmem_float_g and nvshmem_float_p). The following code shows an example of how nvshmem_malloc can be used to perform symmetric memory allocation of the arrays holding the input and output grid point values: input = (float*) nvshmem_malloc(nx*ny*sizeof(float)); output = (float*) nvshmem_malloc(nx*ny*sizeof(float));

The following code shows how nvshmem_free can subsequently be used to free these arrays: nvshmem_free(input); nvshmem_free(output);

All PEs must participate when calling these routines. Note that all PEs only allocate their own partition of the input and output grids. The assumption is that the layout of FIGURE 23.23 Stencil kernel for the Jacobi iterative method that uses NVSHMEM put functions for halo exchange.

the partitions, i.e., the offsets of the top and bottom grid points, is symmetrical, i.e., identical, across all partitions. Fig. 23.23 shows how the kernel in Fig. 23.1 can be modified to use NVSHMEM to exchange halo values within the kernel. The key changes from Fig. 23.1 are the inclusion of the NVSHMEM library header file (line 01), the passing of the top and bottom PE’s IDs as parameters to the kernel (line 03), and the calls to nvshmem_float_p to send the boundary values to the top and bottom PEs (lines 15-20). In particular, each thread checks if it is computing a value in the top boundary row of its PE, i.e., if y == 1 (line 15). If so, the thread uses nvshmem_float_p to send that value to its top PE, passing the value as the second parameter and the ID of the top PE as the third parameter (line 16). Since this value needs to be placed in the bottom halo row of the top PE, the thread passes the address of the symmetric halo element in its own bottom halo row as the first parameter. Similarly, each thread checks if it is computing a value in the bottom boundary row of its PE, i.e., if y == ny - 2 (line 18). If so, the thread uses nvshmem_float_p to send that value to its bottom PE, passing the value as the second parameter and the ID of the bottom PE as the third parameter (line 19). Since this value needs to be placed in the top halo row of the bottom PE, the thread passes the address of the symmetric halo element in its own top halo row as the first parameter.

Figure 23.24

FIGURE 23.24. A simple MPI + NVSHMEM main program.

Having seen how to implement a kernel that uses NVSHMEM, we now turn our attention to the host code that calls this kernel. Similarly to NCCL, NVSHMEM can be used in conjunction with MPI. Fig. 23.24 shows the typical host code for setting up NVSHMEM in conjunction with MPI. The code for setting up and tearing down the MPI communication system is the same as that in Fig. 23.6. Compared to Fig. 23.6, Fig. 23.24 additionally includes header files to access the NVSHMEM API functions (lines 02-03) and uses these API functions to allocate and initialize (lines 10-13) as well as release (line 15) the resources needed by the NVSHMEM library. In particular, an object of type nvshmemx_init_attr_t is created (line 10) to provide configuration details for initializing the NVSHMEM communication system. Interested readers are referred to the NVSHMEM user guide for all the configuration attribute fields supported by the type. In our example, we focus on one of the configuration attribute fields, mpi_comm, that points to an MPI communicator object specifying the scope of the processes involved in the NVSHMEM communication. In our stencil example, the scope is all the ranks of the MPI communication system (lines 11-12). The nvshmemx_init_attr function is then called to initialize the NVSHMEM library resources using the object, which is passed as the second parameter (line 13). The first parameter, NVSHMEMX_INIT_WITH_MPI_COMM, indicates that we are initializing NVSHMEM using an MPI communicator. Finally, after the host code completes the Jacobi method computation, it calls nvshmem_finalize releases the NVSHMEM library resources (line 15). Note that NVSHMEM can also be initialized without an MPI communicator. We refer the reader to the NVSHMEM documentation [3] for instructions on how to initialize NVSHMEM when not used in conjunction with MPI. Fig. 23.25 shows the host code for the main loop that executes the Jacobi iterative method using the NVSHMEM-based kernel. The code for resetting the L2 norm (line 04) and reducing it (lines 12-16) is the same as previous examples. The main difference is in the code for launching the compute kernel and performing the halo exchange (lines 07-09). In contrast with the MPI example in Fig. 23.14 and the NCCL FIGURE 23.25 Host code for NVSHMEM-based multi-GPU implementation of the Jacobi iterative method that overlaps computation and communication.

example in Fig. 23.20 where three different kernels are launched into three different streams, only a single kernel is launched into a single stream called stream to compute the entire partition (line 09). The kernel takes two additional parameters, top and bottom to tell the kernel to which PEs to send the boundary values. The values of top and bottom are computed (lines 07-08) in the same manner as the previous examples. We comment on the implications of launching only one kernel for both the computation and communication in each Jacobi iteration later in this section. After inserting the kernel that performs the computation and the halo exchange into the stream, we need to guarantee that the boundary values have arrived at the target process before proceeding to the next iteration. In the MPI-based implementation in Fig. 23.14, this guarantee comes from the fact that the calls to MPI_Sendrecv are blocking, which means they do not return until the data have arrived. Therefore, by the time all processes have reached the MPI_Allreduce in the timeline in Fig. 23.15, we know for sure that all halo exchange data have been received. In the NCCL-based implementation in Fig. 23.20, this guarantee comes from the fact that we synchronize on the ncclSend and ncclRecv events in the appropriate streams. The cudaStreamWaitEvent() calls before the end of the iteration guarantee that the halo exchange data have arrived for each process before the L2 norm is reset for the next iteration. In the NVSHMEM-based implementation in Fig. 23.25, the boundary values are sent by the same kernel that calculates the grid points. The kernel will complete as soon as all the launched threads complete their work in computing the grid point values and sending the halo data. Synchronizing on the stream only guarantees that the kernel has finished its computation and sending the data; it does not guarantee that the data has been received. To ensure that data have been received, we need to callnvshmemx_barrier_all_on_stream, the NVSHMEM API function that provides suchguarantee, on the same stream as the kernel (line 18). This call makes all PEs wait at the barrier until all the NVSHMEM memory access operations initiated by any preceding kernels in the stream have completed. Therefore, when all the processes proceed to the next iteration, we know for sure that all halo exchange data have been received and it is safe to proceed. Using NVSHMEM to perform put operations of the halo values directly from the kernel has two key advantages. The first advantage is that it automatically overlaps computation and communication. With MPI and NCCL, the kernel needs to be terminated before the communication could be started. For this reason, we have to separate the computation of the boundary values and the internal values into different kernels so that we can wait for only the kernel computing the boundary values before initiating the communication in parallel with the kernel computing the internal values. In NVSHMEM, it is unnecessary to launch separate kernels and orchestrate the concurrency between them. NVSHMEM allows the halo values to be sent from within some of the GPU threads using the put operation as soon as they are computed, and allows other threads to continue to compute the internal grid point values while the communication initiated by the put operation happens in the background. The second advantage of performing put and get operations directly from within the kernel is that it allows multiple operations to be fused into a single kernel. This advantage is less apparent with our Jacobi iterative method example because there is only one operation, i.e., the stencil operation. However, if the computation consisted of multiple computations with different communications happening in between these computations, then MPI and NCCL would require each of these computations to be executed by separate kernels. On the other hand, NVSHMEM would enable fusing these operations in the same kernel and communicating from within the kernel. Such kernel fusion could reduce the overhead of kernel launches for small kernels, as well as enable keeping data in shared memory and registers if this data is used across the different operations being fused. One subject for potential further study is that the fine-grain manner in which we have used the put operations in the kernel in Fig. 23.23 would perform reasonably well for GPUs connected over NVLINK, which supports low latency and high bandwidth communication. However, for slower interconnects and communication over a network, it would be more efficient to perform fewer and more coarse-grain put operations. NVSHMEM provides an alternative function, nvshmemx_float_put_block where threads in the same thread block can collaborate to execute one coarse-grain put operation. We refer the reader to the NVSHMEM documentation for more information on how to use such more advanced techniques [3].

23.6 Summary

We have covered basic patterns of multi-GPU programming for clusters of GPUs using three programming models: MPI, NCCL, and NVSHMEM. We use the stencilpattern to show how multiple processes exchange data throughout the execution. Our first implementation uses MPI alone and has each process compute all grid point values in its partition then send the boundary values to neighboring processes after all the computation is done. We then improve on this MPI implementation by computing the boundary values first, then sending the boundary values to neighboring processing while computing the internal grid point values, thereby overlapping computation and communication. Achieving this overlap required the use of CUDA streams to execute different kernels concurrently. We then looked at how the same overlap between computation and communication can be achieved with using NCCL in conjunction with MPI. The advantage of NCCL is that it allows communication operations to be placed inside of CUDA streams, freeing the host from the burden of synchronizing between GPU kernels and MPI communication primitives. Furthermore, the NCCL library is well-optimized for multi-GPU communication, freeing the programmer from the burden of customizing their communication primitives to the underlying system organization and network topology. After that, we looked at how the same overlap between computation and communication can be achieved with NVSHMEM. Unlike MPI and NCCL which rely on two-sided communication, NVSHMEM relies on one-sided communication, which removes the latency of send operations needed to match with corresponding receive operations. Moreover, NVSHMEM put and get operations can be executed from within GPU kernels, which allows kernels to be fused and achieves the overlap between computation and communication transparently. Our comparison of NCCL and NVSHMEM focused on contrasting the hostinitiated two-sided communication in NCCL with the device-initiated one-sided communication in NVSHMEM. However, it is worth noting that these multi-GPU programming APIs continue to evolve and have more and more features in common. For example, NCCL recently added support for symmetric memory and deviceinitiated communication, and may add support for one-sided communication soon. On the other hand, NVSHMEM supports host-initiated communication as well, not just device-initiated communication. Host-initiated communication works well when the data to be communicated are of coarse granularity and can be determined independently of the computation that overlaps with the communication. On the other hand, device-initiated communication is preferred when the data to be communicated are of fine granularity and are determined as part of the computation that overlaps with the communication. While multi-GPU programming is very different from programming GPU kernels, the major programming concepts that we covered (SPMD, ranks, and barriers) all have counterparts in the CUDA programming model. This confirms our belief that by teaching parallel programming with one model well, students can pick up other programming models quickly and easily. We encourage the reader to build on the foundation from this chapter and study more advanced features of MPI, NCCL, and NVSHMEM, and apply them to other important patterns.

23.7 Exercises

\1. Assume that the 5-point stencil computation in this chapter is applied to a grid whose size is 64 grid points in the x-dimension and 512 grid points in the ydimension. The computation is divided across 16 MPI ranks. a. How many output grid point values are computed by each process? b. How many halo grid points are needed by each process? c. How many boundary grid points are computed by each process in Stage 1 of Fig. 23.12? d. How many internal grid points are computed by each process in Stage 2 of Fig. 23.12? e. How many bytes are sent by each process in Stage 2 of Fig. 23.12? 2. If the MPI call MPI_Send(ptr_a, 1000, MPI_FLOAT, 2000, 4, MPI_COMM_WORLD) resulted in a data transfer of 4,000 bytes, what is the size of each data element being sent? a. 1 byte b. 2 bytes c. 4 bytes d. 8 bytes 3. Which of the following statements is true? a. MPI_Send() is blocking by default. b. MPI_Recv() is blocking by default. c. MPI messages must be at least 128 bytes.

References [1] W. Gropp, E. Lusk, A. Skjellum, Using MPI: Portable Parallel Programming with the Message-Passing Interface, vol. 1, MIT Press, 1999. [2] NVIDIA, Overview of NCCL, https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/ overview.html, 2024. [3] NVIDIA, NVIDIA OpenSHMEM library (NVSHMEM) documentation, https://docs. nvidia.com/nvshmem/api/index.html, 2024. [4] NVIDIA, Multi GPU programming models, https://github.com/NVIDIA/multi-gpuprogramming-models, 2025. [5] NVIDIA, CUB, https://nvidia.github.io/cccl/cub/index.html, 2025. [6] MPICH, MPICH, https://www.mpich.org, 2025. [7] OpenMPI, Open MPI: open source high performance computing, https://www.open-mpi. org, 2025. [8] MVAPICH, MVAPICH: MPI over InfiniBand, omni-path, Ethernet/iWARP, RoCE, and slingshot, https://mvapich.cse.ohio-state.edu, 2025. [9] B. Chapman, T. Curtis, S. Pophale, S. Poole, J. Kuehn, C. Koelbel, L. Smith, Introducing openshmem: shmem for the pgas community, in: Proceedings of the Fourth Conference on Partitioned Global Address Space Programming Model, 2010, pp. 1–3.

CHAPTER

Conclusion and future outlook

References

[1] W. Gropp, E. Lusk, A. Skjellum, Using MPI: Portable Parallel Programming with the Message-Passing Interface, vol. 1, MIT Press, 1999.

[2] NVIDIA, Overview of NCCL, https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/

[3] NVIDIA, NVIDIA OpenSHMEM library (NVSHMEM) documentation, https://docs. nvidia.com/nvshmem/api/index.html, 2024.

[4] NVIDIA, Multi GPU programming models, https://github.com/NVIDIA/multi-gpuprogramming-models, 2025.

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

[6] MPICH, MPICH, https://www.mpich.org, 2025.

[7] OpenMPI, Open MPI: open source high performance computing, https://www.open-mpi.

[8] MVAPICH, MVAPICH: MPI over InfiniBand, omni-path, Ethernet/iWARP, RoCE, and slingshot, https://mvapich.cse.ohio-state.edu, 2025.

[9] B. Chapman, T. Curtis, S. Pophale, S. Poole, J. Kuehn, C. Koelbel, L. Smith, Introducing openshmem: shmem for the pgas community, in: Proceedings of the Fourth Conference on Partitioned Global Address Space Programming Model, 2010, pp. 1–3.