Skip to content

Chapter 3 Multidimensional grids and data

Programming Massively Parallel Processors 5e — English original

Chapter 3 Multidimensional grids and data

CHAPTER

Multidimensional grids and data

CONTENTS 3.1 Multidimensional grid organization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.2 Mapping threads to MultiDimensional data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 3.3 Image blur – a more complex kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 3.4 Matrix multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 3.5 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 In Chapter 2, we learned to write a simple CUDA C++ program that calls a kernel function to launch a one-dimensional grid of threads that operates on elements of one-dimensional arrays. A kernel specifies the statements that are executed by each individual thread in the grid. In this chapter, we look more generally at how threads are organized and learn how threads and blocks can be used to process multidimensional arrays. Multiple examples are used throughout the chapter, including converting a colored image to a grayscale image, blurring an image, and matrix multiplication. These examples also serve to familiarize the reader with reasoning about data parallelism before we proceed to discuss the GPU architecture, memory organization, and performance optimizations in the upcoming chapters.

In Chapter 2, we learned to write a simple CUDA C++ program that calls a kernel function to launch a one-dimensional grid of threads that operates on elements of one-dimensional arrays. A kernel specifies the statements that are executed by each individual thread in the grid. In this chapter, we look more generally at how threads are organized and learn how threads and blocks can be used to process multidimensional arrays. Multiple examples are used throughout the chapter, including converting a colored image to a grayscale image, blurring an image, and matrix multiplication. These examples also serve to familiarize the reader with reasoning about data parallelism before we proceed to discuss the GPU architecture, memory organization, and performance optimizations in the upcoming chapters.

3.1 Multidimensional grid organization

In CUDA, all threads in a grid execute the same kernel function, and they rely on their coordinates, i.e., thread indices, to distinguish themselves from each other and to identify the appropriate portion of the data to process. As we saw in Chapter 2, these threads are organized into a two-level hierarchy: a grid consists of one or more blocks and each block in turn consists of one or more threads. All threads in the same block share the same block index, which can be accessed via the blockIdx (built-in) variable. Each thread also has a thread index, which can be accessed via the threadIdx (built-in) variable. When a thread executes a kernel function, references to the blockIdx and threadIdx variables return the coordinates of the thread. The execution configuration parameters in a kernel call statement specify the dimensions of the grid and the dimensions of each block. These dimensions are available via the gridDim and blockDim (built-in) variables. Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00012-3 Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.

In general, a grid is a three-dimensional array of blocks, and each block is a threedimensional array of threads. When calling a kernel, the program needs to specify the size of the grid and the blocks in each dimension. These are specified using the execution configuration parameters (within «< … »>) of the kernel call statement. The first execution configuration parameter specifies the dimensions of the grid in number of blocks. The second specifies the dimensions of each block in number of threads. Each such parameter has the type dim3, which is an integer vector type of three elements x, y, and z. These three elements specify the sizes of the three dimensions. The programmer can use fewer than three dimensions by setting the size of the unused dimensions to 1. For example, the following host code can be used to call the vecAddKernel kernel function and generate a 1D grid that consists of 32 blocks, each of which consists of 128 threads. dim3 dimGrid(32, 1, 1); dim3 dimBlock(128, 1, 1); vecAddKernel«<dimGrid, dimBlock»>(…);

In this case, the total number of threads in the grid is 128 ∗ 32 = 4096. Note that dimBlock and dimGrid are host code variables defined by the programmer. These variables can have any legal C++ variable name as long as they have the type dim3. For example, the following statements accomplish the same as the statements above: dim3 dog(32, 1, 1); dim3 cat(128, 1, 1); vecAddKernel«<dog, cat»>(…);

The grid and block dimensions can also be calculated from other variables. For example, the kernel call in Fig. 2.12 can be written as: dim3 dimGrid(ceil(n/256.0), 1, 1); dim3 dimBlock(256, 1, 1); vecAddKernel«<dimGrid, dimBlock»>(…);

This allows the number of blocks to vary with the size of the vectors so that the grid will have enough threads to cover all vector elements. In this example, the programmer chooses to fix the block size at 256. The value of variable n at kernel call time determines the dimension of the grid. If n is equal to 1000, the grid will consist of four blocks. If n is equal to 4000, the grid will have 16 blocks. In each case, there will be enough threads to cover all the vector elements. Once the grid is launched, the grid and block dimensions will remain the same until the entire grid finishes execution. For convenience, CUDA provides a special shortcut for calling a kernel with onedimensional grids and blocks. Instead of using dim3 variables, one can use arithmetic expressions to specify the configuration of 1D grids and blocks. In this case, the CUDA compiler simply takes the arithmetic expression as the x dimension and assumes that the y and z dimensions are 1. This gives us the kernel call statement shown in Fig. 2.12:

vecAddKernel«<ceil(n/256.0), 256»>(…);

Readers who are familiar with C++ would realize that this ``short-hand’’ convention for 1D configurations takes advantage of how C++ constructors and default parameters work. The default values of the parameters to the dim3 constructor are 1. When a single value is passed where a dim3 is expected, that value will be passed to the first parameter of the constructor while the second and third parameters take the default value of 1. The result is a 1D grid or block where the size of the x-dimension is the value passed and the sizes of the y- and z-dimensions are 1. Within the kernel function, the x field of the variables gridDim and blockDim are pre-initialized according to the values of the execution configuration parameters. For example, if n is equal to 4000, references to gridDim.x and blockDim.x in the vecAddKernel kernel result in 16 and 256 respectively. Note that unlike the dim3 variables in the host code, the names of these variables within the kernel functions are part of the CUDA C++ specification and cannot be changed. That is, the gridDim and blockDim variables are built-in variables and always reflect the dimensions of the grid and the blocks, respectively. In CUDA C++, the allowed values of gridDim.x range from 1 to 231 − 1, and the allowed values of gridDim.y and gridDim.z range from 1 to 216 − 1 (65,535). All threads in a block share the same blockIdx.x, blockIdx.y, and blockIdx.z values. Among blocks, the blockIdx.x value ranges from 0 to gridDim.x−1, the blockIdx.y value ranges from 0 to gridDim.y−1, and the blockIdx.z value ranges from 0 to gridDim.z−1. We now turn our attention to the configuration of blocks. Each block is organized into a three-dimensional array of threads. Two-dimensional blocks can be created by setting blockDim.z to 1. One-dimensional blocks can be created by setting both blockDim.y and blockDim.z to 1, as was in the vecAddKernel example. As mentioned before, all blocks in a grid have the same dimensions and sizes. The number of threads in each dimension of a block is specified by the second execution configuration parameter at the kernel call. Within the kernel, this configuration parameter can be accessed as the x, y, and z fields of blockDim. The total size of a block in current CUDA systems is limited to 1024 threads. These threads can be distributed across the three dimensions in any way as long as the total number of threads does not exceed 1024. For example, blockDim values of (512, 1, 1), (8, 16, 4), and (32, 16, 2) are all allowed. On the other hand, a blockDim value of (32, 32, 2) is not allowed since the total number of threads exceeds 1024. A grid and its blocks do not need to have the same dimensionality. A grid can have higher dimensionality than its blocks and vice versa. For example, Fig. 3.1 shows a small toy grid example with a gridDim of (2, 2, 1) and a blockDim of (4, 2, 2). Such a grid can be created with the following host code: dim3 dimGrid(2, 2, 1); dim3 dimBlock(4, 2, 2); KernelFunction«<dimGrid, dimBlock»>(…);

Figure 3.1

FIGURE 3.1. A multidimensional example of a CUDA grid organization.

The grid in Fig. 3.1 consists of four blocks organized into a 2×2 array. Each block is labeled with (blockIdx.y,blockIdx.x). For example, Block (1,0) has blockIdx.y= 1 and blockIdx.x= 0. Note that the ordering of the block and thread labels is such that highest dimension comes first. This notation uses a reverse ordering of that used in the code for setting configuration parameters where the lowest dimension comes first. This reversed ordering for labeling blocks works better when we illustrate the mapping of thread coordinates into data indexes in accessing multidimensional data. Each threadIdx also consists of three fields: the x coordinate threadId.x, the y coordinate threadIdx.y, and the z coordinate threadIdx.z. Fig. 3.1 illustrates the organization of threads within a block. In this example, each block is organized into a 4×2×2 array of threads. Since all blocks within a grid have the same dimensions, we only show one of them. Fig. 3.1 expands Block (1,1) to show its 16 threads. For example, Thread (1,0,2) has threadIdx.z= 1, threadIdx.y= 0, and threadIdx.x= 2. Note that in this example, we have 4 blocks of 16 threads each, with a grand total of 64 threads in the grid. We use these small numbers to keep the illustration simple. Typical CUDA grids contain thousands to millions of threads.

3.2 Mapping threads to MultiDimensional data

The choice of 1D, 2D, or 3D thread organizations is usually based on the nature of the data. For example, pictures are 2D arrays of pixels. Using a 2D grid that consists of 2D blocks is often convenient for processing the pixels in a picture. Fig. 3.2 shows FIGURE 3.2 Using a 2D thread grid to process a 62×76 picture P in.

such an arrangement for processing a 62×761 picture P in (62 pixels in the vertical or y direction and 76 pixels in the horizontal or x direction). Assume that we decided to use a 16 × 16 block, with 16 threads in the x direction and 16 threads in the y direction. We need 4 blocks in the y direction and 5 blocks in the x direction, which results in 4 × 5 = 20 blocks as shown in Fig. 3.2. The heavy lines mark the block boundaries. The shaded area depicts the threads that cover pixels. Each thread is assigned to process a pixel whose y and x coordinates are derived from its blockIdx, blockDim, and threadIdx variable values: Vertical (row) coordinate = blockIdx.y*blockDim.y + threadIdx.y Horizontal (column) coordinate = blockIdx.x*blockDim.x + threadIdx.x For example, the P in element to be processed by Thread (0,0) of Block (1,0) can be identified as follows: 1 Throughout this book, we refer to the dimensions of multidimensional data in descending order: the zdimension followed by the y dimension followed by the x dimension. For example, for a picture with n pixels in the vertical or y dimension and m pixels in the horizontal or x dimension, we refer to it as a n × m picture. This follows the C++ multidimensional array indexing convention. For example, we can refer to P[y][x] as Py,x in text and figures for conciseness. Unfortunately, this ordering is opposite to the order in which data dimensions are ordered in the gridDim and blockDim dimensions. The discrepancy can be especially confusing when we define the dimensions of a thread grid based on a multidimensional array that is to be processed by its threads.

P inblockI dx.y∗blockDim.y+threadI dx.y,blockI dx.x∗blockDim.x+threadI dx.x = P in1∗16+0,0∗16+0 = P in16,0 Note that in Fig. 3.2, we have 2 extra threads in the y direction and 4 extra threads in the x direction. That is, we generate a grid of 64×80 threads in total to process 62×76 pixels. This situation is similar to when a 1000-element vector is processed using four 256-thread blocks by the 1D kernel vecAddKernel in Fig. 2.10. Recall that an if-statement in Fig. 2.10 is needed to prevent the extra 24 threads from taking effect. Similarly, we should expect that the picture processing kernel function will have if-statements to test whether the thread’s vertical and horizontal indices fall within the valid range of pixels. We assume that the host code uses an integer variable n to track the number of pixels in the y direction and another integer variable m to track the number of pixels in the x direction. We further assume that the input picture data has been copied to the device global memory and can be accessed through a pointer variable Pin_d. The output picture has been allocated in the device memory and can be accessed through a pointer variable Pout_d. The following host code can be used to call a 2D kernel colorToGrayscaleConversion to process the picture: dim3 dimGrid(ceil(m/16.0), ceil(n/16.0), 1); dim3 dimBlock(16, 16, 1); colorToGrayscaleConversion«<dimGrid,dimBlock»>(Pin_d, Pout_d, m, n);

In this example, we assume for simplicity that the dimensions of the blocks are fixed at 16 × 16. The dimensions of the grid, on the other hand, depend on the dimensions of the picture. To process a 1500×2000 (3-million-pixel) picture, we would generate 11,750 blocks, 94 in the y direction and 125 in the x direction. Within the kernel function, references to gridDim.x, gridDim.y, blockDim.x, and blockDim.y result in 125, 94, 16, and 16, respectively. Before we show the kernel code, we need to first understand how C and C++ statements access elements of dynamically allocated multidimensional arrays. Ideally, we would like to access Pin_d as a two-dimensional array where an element at the row j and column i can be accessed as Pin_d[j][i]. However, the C++ standard that CUDA C++ is based on requires the number of columns in Pin to be known at compile time for Pin to be accessed as a 2D array. Unfortunately, this information is not known at compile time for dynamically allocated arrays. In fact, part of the reason why one uses dynamically allocated arrays is to allow the sizes and dimensions of these arrays to vary according to the data size at run time. Thus, the information on the number of columns in a dynamically allocated two-dimensional array is not known at compile time by design. As a result, programmers need to explicitly linearize, or flatten'', a dynamically allocated two-dimensional array into an equivalent one-dimensional array in the current CUDA C++. In reality, all multidimensional arrays in C and C++ are linearized. This is due to the use of a flat’’ memory space in modern computers (see ``Memory Space’’ sidebar). In the case of statically allocated arrays, the compilers allow the programmers to use higher dimensional indexing syntax such as Pin_d[j][i] to access their elements.

Under the hood, the compiler linearizes them into an equivalent one-dimensional array and translates the multidimensional indexing syntax into a one-dimensional offset. In the case of dynamically allocated arrays, such translation is left to the programmer due to lack of dimensional information at compile time that is needed to perform the translation. Memory Space A memory space is a simplified view of how a processor accesses its memory in modern computers. A memory space is usually associated with each running application. The data to be processed by an application and the instructions executed for the application are stored in locations in its memory space. Each location typically can accommodate a byte and has an address. Variables that require multiple bytes – 4 bytes for float and 8 bytes for double – are stored in consecutive byte locations. When accessing a data value from the memory space, the processor gives the starting address (address of the starting byte location) and the number of bytes needed. Most modern computers have at least 4G byte-sized locations, where each G is 1,073,741,824 (230 ). All locations are labeled with an address that ranges from 0 to the largest number used. Since there is only one address for every location, we say that the memory space has a “flat’’ organization. As a result, all multidimensional arrays are ultimately ``flattened’’, into equivalent one-dimensional arrays. While a C++ programmer can use multidimensional array syntax to access an element of a multidimensional array, the compiler translates these accesses into a base pointer that points to the beginning element of the array, along with a one-dimensional offset calculated from these multidimensional indices. There are at least two ways one can linearize a two-dimensional array. One way is to place all elements of the same row into consecutive locations. The rows are then placed one after another into the memory space. This arrangement, called the rowmajor layout, is illustrated in Fig. 3.3. To improve readability, we use Mj,i to denote an element of M at the j th row and the i th column. Mj,i is equivalent to the C++ expression M[j][i], but is slightly more readable. Fig. 3.3 shows an example where a 4 × 4 matrix M is linearized into a 16-element one-dimensional array, with the four elements of row 0 first, followed by the four elements of row 1, etc. Therefore, the one-dimensional equivalent index for an element of M at row j and column i is j ∗ 4 + i. The j ∗ 4 term skips over all elements of the rows before row j . The i term then selects the right element within the section for row j . For example, the one-dimensional index for M2,1 is 2 ∗ 4 + 1 = 9. This is illustrated in Fig. 3.3, where M9 is the one-dimensional equivalent to M2,1 . This is the way C and C++ compilers linearize two-dimensional arrays. Another way to linearize a two-dimensional array is to place all elements of the same column into consecutive locations. The columns are then placed one after another into the memory space. This arrangement, called the column-major layout, FIGURE 3.3 Row-major layout for a 2D C++ array. The result is an equivalent 1D array accessed by an index expression j ∗ W idth + i for an element that is in the j th row and i th column of an array of W idth elements in each row.

is used by FORTRAN compilers. Note that the column-major layout of a twodimensional array is equivalent to the row-major layout of its transposed form. We will not spend more time on this layout except mentioning that readers whose primary previous programming experience was with FORTRAN should be aware that CUDA C++ uses the row-major layout rather than the column major layout. Also, many C libraries that are designed to be used by FORTRAN programs use columnmajor layout to match the FORTRAN compiler layout. As a result, the manual pages for these libraries usually tell the users to transpose the input arrays if they call these libraries from C or C++ programs. We are now ready to study the source code of the colorToGrayscaleConversion kernel, shown in Fig. 3.4. The kernel code uses the following equation to convert each color pixel to its grayscale counterpart: L = 0.299*r + 0.587*g + 0.114*b There are a total of blockDim.x*gridDim.x threads in the horizontal direction. Similar to the vecAddKernel example, the following expression generates every integer value from 0 to blockDim.x*gridDim.x−1 (line 06): col = blockIdx.x*blockDim.x + threadIdx.x We know that gridDim.x*blockDim.x is greater than or equal to the width of the image (m value passed in from the host code). In other words, we have at least as many threads as the number of pixels in the horizontal direction. Similarly, we also know that there are at least as many threads as the number of pixels in the vertical direction.

Figure 3.4

FIGURE 3.4. Source code of colorToGrayscaleConversion with 2D thread mapping to data.

Therefore, as long as we test and make sure only the threads with both row and col values within range participate in the computation, i.e., (col<width) && (row<height), we should be able to cover every pixel in the picture (line 07). Since there are width pixels in each row, we can generate the one-dimensional index for the pixel at row row and column col as row*width+col (line 10). This onedimensional index grayOffset is the pixel index for Pout since each pixel in the output grayscale image is one byte (unsigned char). Using our 62 × 76 image example, the linearized one-dimensional index of the Pout pixel calculated by Thread (0,0) of Block (1,0) with the formula: P outblockI dx.y∗blockDim.y+threadI dx.y,blockI dx.x∗blockDim.x+threadI dx.x = P out1∗16+0,0∗16+0 = P out16,0 =Pout[16*76+0] = Pout[1216] As for Pin, we need to multiply the gray pixel index by 3 (line 13)2 since each colored pixel is stored as three elements (r, g, b), each of which is one byte. The resulting rgbOffset gives the starting location of the color pixel in the Pin array. We read the r, g, and b value from the three consecutive byte locations of the Pin array (lines 14-16), perform the calculation of the grayscale pixel value, and write that value into the Pout array using grayOffset (line 19). Using our 62 × 76 image example, the linearized one-dimensional index of the first component of the Pin pixel that is processed by Thread (0,0) of Block (1,0) can be calculated with the formula:

2 We assume that CHANNELS is a constant of value 3 and its definition is outside the kernel function.

Figure 3.5

FIGURE 3.5. Covering a 76 × 62 picture with 16 × 16 blocks.

P inblockI dx.y∗blockDim.y+threadI dx.y,blockI dx.x∗blockDim.x+threadI dx.x = P in1∗16+0,0∗16+0 = P in16,0 = Pin[16*76*3+0] = Pin[3648] The data being accessed are the three bytes starting at byte offset 3648. Fig. 3.5 illustrates the execution of colorToGrayscaleConversion when processing our 62 × 76 example. Assuming 16 × 16 blocks, calling the colorToGrayscaleConversion kernel generates 64 × 80 threads. The grid will have 4 × 5 = 20 blocks, 4 in the vertical direction and 5 in the horizontal direction. The execution behavior of blocks will fall into one of four different cases, shown as four shaded areas in Fig. 3.5. The first area, marked as 1 in Fig. 3.5, consists of the threads that belong to the 12 blocks covering the majority of pixels in the picture. Both col and row values of these threads are within range; all these threads pass the if-statement test and process pixels in the dark shaded area of the picture. That is all 16 × 16 = 256 threads in each block will process pixels. The second area, marked as 2 in Fig. 3.5, contains the threads that belong to the three blocks in the medium shaded area covering the upper right pixels of the picture. Although the row values of these threads are always within range, the col values of some of them exceed the m value of 76. This is because the number of threads in the horizontal direction is always a multiple of the blockDim.x value chosen by the programmer (16 in this case). The smallest multiple of 16 needed to cover 76 pixels is 80. As a result, 12 threads in each row will find their col values within range and will process pixels. On the other hand, the remaining 4 threads in each row will find their col values out of range, and thus fail the if-statement condition. These threadswill not process any pixels. Overall, 12 × 16 = 192 of the 16 × 16 = 256 threads in each of these blocks will process pixels. The third area, marked as 3 in Fig. 3.5, accounts for the four lower left blocks covering the medium shaded area of the picture. Although the col values of these threads are always within range, the row values of some of them exceed the n value of 62. This is because the number of threads in the vertical direction is always a multiple of the blockDim.y value chosen by the programmer (16 in this case). The smallest multiple of 16 to cover 62 is 64. As a result, 14 threads in each column will find their row values within range and will process pixels. On the other hand, the remaining 2 threads in each column will not pass the if-statement and will not process any pixels. Overall, 16 × 14 = 224 of the 256 threads will process pixels. The fourth area, marked as 4 in Fig. 3.5, contains the threads that cover the lower right, lightly shaded area of the picture. Like Area 2, 4 threads in each of the top 14 rows will find their col values out of range. Like Area 3, the entire bottom two rows of this block will find their row values out of range. Overall, only 14 × 12 = 168 of the 16 × 16 = 256 threads will process pixels. We can easily extend our discussion of 2D arrays to 3D arrays by including another dimension when we linearize arrays. This is done by placing each ``plane’’ of the array one after another into the address space. Assume that the programmer uses variables m and n to track the number of columns and rows in a 3D array, respectively. The programmer also needs to determine the values of blockDim.z and gridDim.z when calling a kernel. In the kernel, the array index will involve another global index: int plane = blockIdx.z*blockDim.z + threadIdx.z;

3.3 Image blur – a more complex kernel

The linearized access to a three-dimensional array P will be in the form of P[plane*m*n + row*m + col]. A kernel processing the 3D P array needs to check whether all the three global indices, plane, row, and col fall within the valid range of the array. The use of 3D arrays in CUDA kernels will be further studies for the stencil pattern in Chapter 8.

So far, we have studied two kernels, vecAddKernel and colorToGrayscaleConversion, where each thread performs only a small number of arithmetic operations on one array element. These kernels serve their purposes well: to illustrate the basic CUDA program structure and data parallel execution concepts. At this point, the reader should ask the obvious question: do all threads in CUDA programs perform only such simple and trivial operations independently of each other? The answer is no. In real CUDA programs, threads often perform complex operations on their data and need to cooperate with each other. For the next few chapters, we are going to work on increasingly more complex examples that exhibit these characteristics. We will start with an image blurring function.

Figure 3.6

FIGURE 3.6. An original image (left) and a blurred version (right).

Image blurring smoothens out abrupt variation of pixel values in an image. Fig. 3.6 illustrates the effect of image blurring. Simply stated, we make the image blurry. To human eyes, a blurred image tends to obscure the fine details and present the ``big picture’’ impression, or the major thematic objects in the picture. In computer image processing algorithms, a common use case of image blurring is to reduce the impact of noise and granular rendering effects in an image by correcting problematic pixel values with the clean surrounding pixel values. In computer vision, image blurring can be used to allow edge detection and object recognition algorithms to focus on thematic objects rather than being bogged down by a massive quantity of fine-grained objects. In displays, image blurring is sometimes used to highlight a particular part of the image by blurring the rest of the image. Mathematically, an image blurring function calculates the value of an output image pixel as a weighted sum of a patch of pixels encompassing the original pixel in the input image. As we will learn in Chapter 7, the computation of such weighted sums belongs to the convolution pattern. We will use a simplified approach in this chapter by taking a simple average value of an N × N patch of pixels surrounding, and including, the target pixel. To keep the algorithm simple, we will not place a weight on the value of any pixel based on its distance from the target pixel. In practice, placing such weights is quite common in convolution blurring approaches such as Gaussian Blur. Fig. 3.7 shows an example of image blurring using a 3×3 patch. When calculating an output pixel value at the (row, col) position, we see that the patch is centered at the input pixel located at the (row, col) position. The 3 × 3 patch spans three rows (row-1, row, row+1) and three columns (col-1, col, col+1). For example, the coordinates of the nine pixels for calculating the output pixel at (25, 50) are (24, 49), (24, 50), (24, 51), (25, 49), (25, 50), (25, 51), (26, 49), (26, 50), and (26, 51). Fig. 3.8 shows an image blur kernel. Similar to the strategy used in the kernel colorToGrayscaleConversion, we use each thread to calculate an output pixel. That is, the thread-to-output-data mapping remains the same. At the beginning of the kernel, we see the familiar calculation of the col and row indices (lines 03-04). We also see the familiar if-statement that verifies that both col and row are within the valid range FIGURE 3.7 Each output pixel is the average of a patch of surrounding pixels and itself in the input image.

Figure 3.8

FIGURE 3.8. An image blur kernel.

according to the height h and width w of the image (line 05). Only the threads whose col and row indices are both within valid ranges are allowed to participate in the execution. As shown in Fig. 3.7, the col and row values also give the central pixel location of the patch of input pixels used for calculating the output pixel for the thread. The nested for-loops in Fig. 3.8 (lines 10-11) iterate through all the pixels in the patch. We assume that the program has a defined constant BLUR_SIZE. The value of BLUR_SIZE is set such that BLUR_SIZE gives the number of pixels on each side of the patch, also called its radius. In this case, 2∗BLUR_SIZE+1 gives the total number of pixels across one dimension of the patch. For example, for a 3 × 3 patch, BLUR_SIZE is set to 1, whereas for a 7 × 7 patch, BLUR_SIZE is set to 3. The outer loop iterates through the rows of the patch. For each row, the inner loop iterates through the columns of the patch. In our 3 × 3 patch example, the BLUR_SIZE is 1. For the thread that calculates output pixel (25, 50), during the first iteration of the outer loop, the curRow variable is row−BLUR_SIZE = (25 − 1) = 24. Thus, during the first iteration of the outer loop, the inner loop iterates through the patch pixels in row 24. The inner loop iterates from column col−BLUR_SIZE = 50 − 1 = 49 to col+BLUR_SIZE = 51 using the curCol variable. Therefore, the pixels processed in the first iteration of the outer loop are (24, 49), (24, 50), and (24, 51). The reader should verify that in the second iteration of the outer loop, the inner loop iterates through pixels (25, 49), (25, 50), and (25, 51). Finally, the in the third iteration of the outer loop, the inner loop iterates through pixels (26, 49), (26, 50), and (26, 51). Line 16 uses the linearized index of curRow and curCol to access the value of the input pixel visited in the current iteration. It accumulates the pixel value into a running sum variable pixVal. Line 17 records the fact that one more pixel value has been added into the running sum by incrementing the pixels variable. After all the pixels in the patch are processed, line 22 calculates the average value of the pixels in the patch by dividing the pixVal value by the pixels value. It uses the linearized index of row and col to write the result into its output pixel. Line 15 contains a conditional statement that guards the execution of lines 16 and 17. For example, when computing output pixels near the edge of the image, the patch may extend beyond the valid range of the input image. This situation is illustrated in Fig. 3.9 assuming 3 × 3 patches. In Case 1, the pixel at the upper left corner is being blurred. Five out of the nine pixels in the intended patch do not exist in the input image. In this case, the row and col values of the output pixel are 0 and 0, respectively. During the execution of the nested loop, the curRow and curCol values for the nine iterations are (−1,-1), (−1,0), (−1,1), (0,-1), (0,0), (0,1), (1,-1), (1,0), (1,1). Note that for the five pixels that are outside the image, at least one of the index values is less than 0. The curRow>=0 and curCol>=0 conditions of the if-statement catch these values and skips the execution of lines 16 and 17. As a result, only the values of the four valid pixels are accumulated into the running sum variable. The pixels value is also correctly incremented only four times so that the average can be calculated properly at line 22.

3.4 Matrix multiplication

Figure 3.9

FIGURE 3.9. Handling boundary conditions for pixels near the edges of the image.

The readers should work through the other cases in Fig. 3.9 and analyze the execution behavior of the nested loop in blurKernel. Note that most of the threads find all the pixels in their assigned 3 × 3 patch within the input image. They accumulate all the nine pixels. However, for the pixels on the four corners, the responsible threads accumulate only 4 pixels. For other pixels on the four edges, the responsible threads accumulate 6 pixels. These variations are what necessitates keeping track of the actual number of pixels accumulated with variable pixels.

Matrix-matrix multiplication, or matrix multiplication in short, is an important component of the Basic Linear Algebra Subprograms (BLAS) standard (see ``Linear Algebra Functions’’ sidebar). It is the basis of many linear algebra solvers such as LU decomposition. It is also an important computation for deep learning, as we will see in Chapter 19 on convolutional neural networks and Chapter 20 on large language models. Linear Algebra Functions Linear algebra operations are widely used in science and engineering applications. In the Basic Linear Algebra Subprograms (BLAS), a de facto standard for publishing libraries that perform basic algebra operations, there are three levels of linear algebra functions. As the level increases, the number of operations performed by the function increases. Level-1 functions perform vector operations of the form y = αx + y, where x and y are vectors and α is a scalar. Our vector addition example in Chapter 2 is a special case of a level-1 BLASfunction with α = 1. Level-2 functions perform matrix-vector operations of the form y = αAx + βy, where A is a matrix, x and y are vectors, and α and β are scalars. We will be studying a form of level-2 functions Chapter 17 on sparse linear algebra. Level-3 functions perform matrix-matrix operations of the form C = αAB + βC, where A, B, and C are matrices, and α and β are scalars. Our matrix-matrix multiplication example is a special case of a level-3 function where α = 1 and β = 0. These BLAS functions are important because they are used as basic building blocks of higher-level algebraic functions such as linear system solvers and eigenvalue analysis. As we will discuss later, the performance of different implementations of BLAS functions can vary by orders of magnitude in both sequential and parallel computers. Matrix multiplication between an i × j (i rows by j columns) matrix M and a j × k matrix N produces an i × k matrix P . When performing a matrix multiplication, each element of the output matrix P is an inner product of a row of M and a column of N. We will continue to use the convention where Prow,col is the element at row th position in the vertical direction and col th position in the horizontal direction. As shown in Fig. 3.10, Prow,col (the small square in P ) is the inner product of the vector formed by the row th row of M (shown as a horizontal strip in M) and the vector formed by the col th column of N (shown as a vertical strip in N). The inner product, sometimes called the dot product, of two vectors is the sum of products of the individual vector elements. That is: ∑︁ Prow,col = Mrow,k ∗ Nk,col for k = 0, 1, …, W idth − 1 For example, in Fig. 3.10, assuming row = 1 and col = 5: P1,5 = M1,0 ∗ N0,5 + M1,1 ∗ N1,5 + M1,2 ∗ N2,5 + … + M1,W idth−1 ∗ NW idth−1,5 To implement matrix multiplication using CUDA, we can map the threads in the grid to the elements of the output matrix P with the same approach that we used for the colorToGrayscaleConversion kernel. That is, each thread is responsible for calculating one P element. The row and column indices for the P element to be calculated by each thread are the same as before: row = blockIdx.y*blockDim.y + threadIdx.y and col = blockIdx.x*blockDim.x + threadIdx.x.

With this one-to-one mapping, the row and col thread indices are also the row and column indices for their output elements. Fig. 3.11 shows the source code of the kernel based on this thread-to-data mapping. The reader should immediately see the familiar pattern of calculating row and col (lines 03-04), and the if-statement testing if row and col are both within range (line 05). These statements are almost identical FIGURE 3.10 Matrix multiplication using multiple blocks by tiling P .

Figure 3.11

FIGURE 3.11. A matrix multiplication kernel using one thread to compute one P element.

to their counterparts in the colorToGrayscaleConversion kernel. The only significant difference is that we are making a simplifying assumption that matrixMulKernel needs to handle only square matrices so we replace both width and height with just Width. This thread-to-data mapping effectively divides P into tiles, one of which is shown as a large, light-colored square in Fig. 3.10. Each block is responsible for calculating one of these tiles. We now turn our attention to the work done by each thread. Recall that Prow,col is calculated as the inner product of the row th row of M and the col th column of N. In Fig. 3.11, we use a for-loop to perform this inner product operation. Before we FIGURE 3.12 A small execution example of matrixMulKernel.

enter the loop, we initialize a local variable Pvalue to 0 (line 06). Each iteration of the loop accesses an element from the rowth row of M and one from the colth column of N, multiplies the two elements together, and accumulates the product into Pvalue (line 08). Let us first focus on accessing the M element within the for-loop. M is linearized into an equivalent 1D array using row major order. That is, the rows of M are placed one after another in the memory space, starting with the 0th row. Therefore, the beginning element of row 1 is M[1*Width] because we need to account for all elements of row 0. In general, the beginning element of the rowth row is M[row*Width]. Since all the elements of a row are placed in consecutive locations, the kth element of the rowth row is at M[row*Width+k]. This linearized array offset is what we use in Fig. 3.11 (line 08). We now turn our attention to accessing N. As shown in Fig. 3.11, the beginning element of the colth column is the colth element of row 0, which is N[col]. Accessing the next element in the colth column requires skipping over an entire row. This is because the next element of the same column is the same element in the next row. Therefore, the kth element of the colth column is N[k*Width+col] (line 08). After the execution exits the for-loop, all threads have their P element values in the Pvalue variables. Each thread then uses the one-dimensional equivalent index expression row*Width+col to write its P element (line 10). Again, this index pattern is like that used in the colorToGrayscaleConversion kernel. We now use a small example to illustrate the execution of the matrix multiplication kernel. Fig. 3.12 shows a 4 × 4 matrix P with BLOCK_WIDTH = 2. Although such small matrix and block sizes are not realistic, they allow us to fit the entire example in one picture. The P matrix is divided into four tiles and each block calculates one tile. We do so by creating blocks that are 2 × 2 arrays of threads, with each thread calculating one P element. In the example, Thread (0,0) of Block (0,0) calculates P0,0 whereas Thread (0,0) of Block (1,0) calculates P2,0 .

Figure 3.13

FIGURE 3.13. Matrix multiplication actions of one thread block.

The row and col indices in matrixMulKernel identify the P element to be calculated by a thread. The row index also identifies the row of M and the col index identifies the column of N as input values for the thread. Fig. 3.13 illustrates the multiplication actions in each thread block. For the small matrix multiplication example, threads in Block (0,0) produce four dot products. The row and col indices of Thread (1,0) in Block (0,0) are 0 ∗ 0 + 1 = 1 and 0 ∗ 0 + 0 = 0, respectively. The thread thus maps to P1,0 and calculates the dot product of row 1 of M and column 0 of N. Let us walk through the execution of the for-loop of Fig. 3.11 for Thread (0,0) in Block (0,0). During iteration 0 (k = 0), row ∗ W idth + k = 0 ∗ 4 + 0 = 0 and k ∗ W idth + col = 0 ∗ 4 + 0 = 0. Therefore, the input elements accessed are M[0] and N [0], which are the 1D equivalent of M0,0 and N0,0 . Note that these are indeed the 0th elements of row 0 of M and column 0 of N. During iteration 1 (k = 1), row ∗ W idth + k = 0 ∗ 4 + 1 = 1 and k ∗ W idth + col = 1 ∗ 4 + 0 = 4. Therefore, we are accessing M[1] and N [4], which are the 1D equivalent of M0,1 and N1,0 . These are the 1st elements of row 0 of M and column 0 of N. During iteration 2 (k = 2), row ∗ W idth + k = 0 ∗ 4 + 2 = 2 and k ∗ W idth + col2 ∗ 4 + 0 = 8, which results in M[2] and N [8]. Therefore, the elements accessed are the 1D equivalent of M0,2 and N2,0 . Finally, during iteration 3 (k = 3), row ∗ W idth + k = 0 ∗ 4 + 3 = 3 and k ∗ W idth + col = 3 ∗ 4 + 0 = 12, which results in M[3] and N [12], the 1D equivalent of M0,3 and N3,0 . We now have verified that the for-loop performs the inner product between the 0th row of M and the 0th column of N for Thread (0,0) in Block (0,0). After the loop, the thread writes P[row*Width+col], which is P [0]. This is the 1D equivalent of P0,0 so Thread (0,0) in Block (0,0) successfully calculated the inner product between the 0th row of M and the 0th column of N and deposited the result in P0,0 . We will leave it as an exercise for the reader to hand-execute and verify the for-loop for other threads in Block (0,0) or in other blocks.

Since the size of a grid is limited by the maximum number of blocks per grid and threads per block, the size of the largest output matrix P that can be handled by matrixMulKernel is also be limited by these constraints. In the situation where output matrices larger than this limit are to be computed, one can divide the output matrix into sub-matrices whose sizes can be covered by a grid and use the host code to launch a different grid for each sub-matrix. Alternatively, we can change the kernel code so that each thread calculates multiple elements of P . We will further optimize our implementation of matrix multiplication in Chapter 5 and dive deeply into advanced optimizations for this important computation in Chapter 15.

3.5 Summary

CUDA grids and blocks are multidimensional with up to three dimensions. The multidimensionality of grids and blocks is useful for organizing threads to be mapped to multidimensional data. The kernel execution configuration parameters define the dimensions of a grid and its blocks. Unique coordinates in blockIdx and threadIdx allow threads of a grid to identify themselves and their domains of data. It is the programmer’s responsibility to use these variables in kernel functions so that the threads can properly identify the portion of the data to process. When accessing multidimensional data, programmers will often have to linearize multidimensional indices into a one-dimensional offset. The reason is that dynamically allocated multidimensional arrays in C++ are typically stored as one-dimensional arrays in row-major order. We use examples of increasing complexity to familiarize the reader with the mechanics of processing multidimensional arrays with multidimensional grids. These skills are foundational for understanding the parallel patterns to be presented in the book and their associated optimization techniques. 1. In this chapter, we implemented a matrix multiplication kernel that has each thread produce one output matrix element. In this question, you will implement different matrix-matrix multiplication kernels and compare them. a. Write a kernel that has each thread produce one output matrix row. Fill in the execution configuration parameters for the design. b. Write a kernel that has each thread to produce one output matrix column. Fill in the execution configuration parameters for the design. c. Analyze the pros and cons of each kernel design above. 2. A matrix-vector multiplication takes an input matrix B and a vector c and produces one output vector a. Each element of the output∑︁vector a is the dot product of one row of the input matrix B and c, i.e., ai = j Bi,j × cj . For simplicity, we will only handle square matrices whose elements are single precision floating-point number. Write a matrix-vector multiplication kernel and the host stub function that can be called with four parameters: pointer to the output vector a, pointer to the input matrix B, pointer to the input vector c, and the number of elements in each dimension N. Use one thread to calculate an output vector element.

\3. Consider the following CUDA kernel and the corresponding host function that calls it:

global void foo_kernel(float* a, float* b, unsigned int M, unsigned int N) { unsigned int row = blockIdx.y*blockDim.y + threadIdx.y;

unsigned int col = blockIdx.x*blockDim.x + threadIdx.x;

if(row < M && col < N) {

b[row*N + col] = a[row*N + col]/2.1f + 4.8f;

}

}

void foo(float* a_d, float* b_d) {

unsigned int M = 150;

unsigned int N = 300;

dim3 bd(16, 32);

dim3 gd((N - 1)/16 + 1, (M - 1)/32 + 1);

foo_kernel «< gd, bd »>(a_d, b_d, M, N); } a. What is the number of threads per block? b. What is the number of threads in the grid? c. What is the number of blocks in the grid? d. What is the number of threads that execute the code on line 05? 4. Consider a two-dimensional matrix with a width of 400 and a height of 500. The matrix is stored as a one-dimensional array. Specify the array index of the matrix element at row 20 and column 10: a. If the matrix is stored in row major order. b. If the matrix is stored in column major order. 5. Consider a three-dimensional tensor with a width of 400, a height of 500, and a depth of 300. The tensor is stored as a one-dimensional array in row major order. Specify the array index of the tensor element at x = 10, y = 20, and z = 5?

CHAPTER

Compute architecture and scheduling

Figure 4.1

FIGURE 4.1. Architecture of a CUDA-capable GPU.

练习