Skip to content

Chapter 5 Memory architecture and data locality

Programming Massively Parallel Processors 5e — English original

Chapter 5 Memory architecture and data locality

global void foo_kernel(int* a, int* b) { unsigned int i = blockIdx.x*blockDim.x + threadIdx.x; if(threadIdx.x < 40 || threadIdx.x >= 104) { b[i] = a[i] + 1; } if(i%2 == 0) { a[i] = b[i]*2; } for(unsigned int j = 0; j < 5 - (i%3); ++j) { 4.10 Exercises

b[i] += j; } } void foo(int* a_d, int* b_d) { unsigned int N = 1024; foo_kernel «< (N + 128 - 1)/128, 128 »>(a_d, b_d); } a. What is the number of warps per block? b. What is the number of warps in the grid? c. For the statement on line 04: i. How many warps in the grid are active? ii. How many warps in the grid are divergent? iii. What is the SIMD efficiency (in %) of warp 0 of block 0? iv. What is the SIMD efficiency (in %) of warp 1 of block 0? v. What is the SIMD efficiency (in %) of warp 3 of block 0? d. For the statement on line 07: i. How many warps in the grid are active? ii. How many warps in the grid are divergent? iii. What is the SIMD efficiency (in %) of warp 0 of block 0? e. For the loop on line 09: i. How many iterations have no divergence? ii. How many iterations have divergence? 2. For a vector addition, assume that the vector length is 2000, each thread calculates one output element, and the thread block size is 512 threads. How many threads will be in the grid? 3. For the previous question, how many warps do you expect to have divergence due to the boundary check on vector length? 4. Consider a hypothetical block with 8 threads executing a section of code before reaching a barrier. The threads require the following amount of time (in micro seconds) to execute the sections: 2.0, 2.3, 3.0, 2.8, 2.4, 1.9, 2.6, 2.9 and spend the rest of their time waiting for the barrier. What percentage of the threads’ total execution time is spent waiting for the barrier? 5. A CUDA programmer says that if they launch a kernel with only 32 threads in each block, they can leave out the __syncthreads() instruction wherever barrier synchronization is needed. Do you think this is a good idea? Explain. 6. If a CUDA device’s SM (streaming multiprocessor) can take up to 1536 threads and up to 4 thread blocks. Which of the following block configuration would result in the most number of threads in the SM? a. 128 threads per block b. 256 threads per block c. 512 threads per block d. 1024 threads per block 7. Assume a device that allows up to 64 blocks per SM and 2048 threads per SM. Indicate which of the following assignments per SM is possible. In the cases where it is possible, indicate the occupancy level. a. 8 blocks with 128 threads each b. 16 blocks with 64 threads each c. 32 blocks with 32 threads each d. 64 blocks with 32 threads each e. 32 blocks with 64 threads each 8. Consider a GPU with the following hardware limits: 2048 threads/SM, 32 blocks/SM, and 64 K (65,536) registers/SM. For each of the following kernel characteristics, specify if the kernel can achieve full occupancy. If not, specify the limiting factor. a. The kernel uses 128 threads/block and 30 registers/thread. b. The kernel uses 32 threads/block and 29 registers/thread. c. The kernel uses 256 threads/block and 34 registers/thread. 9. A student mentions that they were able to multiply two 1024×1024 matrices using a matrix multiplication kernel with 32×32 thread blocks. The student is using a CUDA device that allows up to 512 threads per block and up to 8 blocks per SM. The student further mentions that each thread in a thread block calculates one element of the result matrix. What would be your reaction and why?

References [1] NVIDIA, CUDA C++ programming guide. Release 12.3, https://docs.nvidia.com/cuda/ cuda-c-programming-guide/, 2023. [2] M. Flynn, Very high-speed computing systems, Proceedings of the IEEE 54 (12) (1966) 1901–1909. [3] NVIDIA, NVIDIA Tesla V100 GPU Architecture. Version WP-08608-001_v1.1, 2017. [4] S. Ryoo, C.I. Rodrigues, S.S. Stone, S.S. Baghsorkhi, S.-Z. Ueng, J.A. Stratton, W.-m.W. Hwu, Program optimization space pruning for a multithreaded GPU, in: Proceedings of the 6th Annual IEEE/ACM International Symposium on Code Generation and Optimization, 2008, pp. 195–204. [5] NVIDIA, Nsight compute: occupancy calculator, https://docs.nvidia.com/nsight-compute/ NsightCompute/index.html#occupancy-calculator, 2023. [6] NVIDIA, Nsight compute, https://docs.nvidia.com/nsight-compute/index.html, 2023.

CHAPTER

Memory architecture and data locality

CONTENTS 5.1 Memory bandwidth as a performance limiter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 5.2 CUDA memory types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 5.3 Tiling for reduced memory traffic. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 5.4 A tiled matrix multiplication kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 5.5 Boundary checks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 5.6 Impact of memory usage on occupancy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 5.7 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 So far, we have learned how to write a CUDA kernel function and how to configure and coordinate its execution by a massive number of threads. We have also looked at the compute architecture of GPU hardware and how threads are scheduled to execute. In this chapter, we will focus on the on-chip memory architecture of the GPU and begin to study how one can organize and position data for efficient access by a massive number of threads. The CUDA kernels that we have learned so far will likely achieve only a tiny fraction of the potential speed of the underlying hardware. This poor performance is because global memory, which is typically implemented with off-chip DRAM, tends to have long access latency (hundreds of clock cycles) and finite access bandwidth. While having many threads available for execution can theoretically tolerate long memory-access latencies, one can easily run into a situation where traffic congestion in the global memory access paths prevents all but very few threads from making progress, thus rendering some of the cores in the Streaming Multiprocessors (SMs) idle. To circumvent such congestion, GPUs provide a number of additional on-chip memory resources for accessing data that can remove the majority of redundant traffic to and from the global memory. In this chapter, we study the use of different memory types to boost the execution performance of CUDA kernels.

So Far, we have learned how to write a CUDA kernel function and how to configure and coordinate its execution by a massive number of threads. We have also looked at the compute architecture of GPU hardware and how threads are scheduled to execute. In this chapter, we will focus on the on-chip memory architecture of the GPU and begin to study how one can organize and position data for efficient access by a massive number of threads. The CUDA kernels that we have learned so far will likely achieve only a tiny fraction of the potential speed of the underlying hardware. This poor performance is because global memory, which is typically implemented with off-chip DRAM, tends to have long access latency (hundreds of clock cycles) and finite access bandwidth. While having many threads available for execution can theoretically tolerate long memory-access latencies, one can easily run into a situation where traffic congestion in the global memory access paths prevents all but very few threads from making progress, thus rendering some of the cores in the Streaming Multiprocessors (SMs) idle. To circumvent such congestion, GPUs provide a number of additional on-chip memory resources for accessing data that can remove the majority of redundant traffic to and from the global memory. In this chapter, we study the use of different memory types to boost the execution performance of CUDA kernels.

5.1 Memory bandwidth as a performance limiter

Since GPUs have a finite amount of hardware resources, they have limits on the amount of work that they can perform in a given time frame. The two most commonly Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00014-7 Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.

referenced limits are the peak computational throughput and the peak memory bandwidth. The peak computational throughput specifies the limit on how many arithmetic operations the hardware can perform per unit of time. For example, the Hopper H100 GPU has a peak computational throughput of 66.9 terra floating-point operations per second (TFLOPS). The hardware typically has different limits for different datatypes such as 32-bit integers, 64-bit integers, double-precision floating point values, etc. We will focus on single-precision floating point operations in this chapter. The peak memory bandwidth specifies the limit on how many bytes of data the hardware can access from a particular memory structure per unit of time. For example, the Hopper H100 GPU has a peak global memory bandwidth of 3.35 terra bytes per second (TB/s). The hardware typically has different limits for different memory structures. We will focus on global memory bandwidth in this chapter. Different kernels find their performance limited by different hardware resources. A kernel is said to be compute-bound if its performance is limited by the computational throughput of the hardware. For such kernels, the compute cores are busy the majority of the time with a steady supply of instructions to execute. Their performance is limited by how fast the cores can execute these instructions. A kernel is said to be memory-bound if its performance is limited by the memory bandwidth of the hardware. For such kernels, the memory channels are busy the majority of the time, and the compute cores are frequently idle waiting for data to arrive from memory. Their performance is limited by how fast the memory can supply the cores with data. To determine if a kernel is compute-bound or memory-bound, we can look at the ratio of floating-point operations it performs to bytes it accesses from global memory (FLOP/B). We will refer to this ratio as the compute-to-global-memory-access ratio. This ratio is sometimes also referred to as arithmetic intensity or computational intensity in the literature. Compute-bound kernels tend to have a high compute-toglobal-memory-access ratio, performing many arithmetic operations relative to the amount of memory that they access. On the other hand, memory-bound kernels tend to have a small ratio, performing few arithmetic operations relative to the amount of memory that they access. The threshold that separates memory-bound kernels from compute-bound kernels depends on the hardware and can be found by taking the ratio of the peak computational throughput to the peak memory bandwidth. For example, the H100 GPU has a threshold of (66.9 TFLOPS)/(3.35 TB/s) = 20.0 FLOP/B. In other words, kernels whose compute-to-global-memory-access ratio is higher than 20.0 FLOP/B are likely to be compute-bound on the H100 GPU, whereas kernels whose ratio is lower are likely to be memory-bound. The peak computational throughput and the peak memory bandwidth are hardware limits, not guarantees. A compute-bound kernel is not guaranteed to perform 66.9 TFLOPS, and a memory-bound is not guaranteed to access 3.35 TB/s. Only the most well-optimized kernels that use hardware resources efficiently are able to perform close to these limits. Accordingly, by comparing the performance of one’s kernel to these hardware limits, one can assess how efficiently one’s kernel is optimized. The roofline model is a convenient way to analyze whether a kernel is compute-bound or memory-bound, and how well it performs relative to the hardware’s peak (see The Roofline Model sidebar).

The Roofline Model The Roofline Model is a visual model for assessing the performance achieved by an application relative to the limits of the hardware it is running on. A basic example of the Roofline model is shown below.

On the x-axis, we have arithmetic or computational intensity measured in FLOP/B. It reflects the amount of work done by an application for every byte of data loaded. On the y-axis, we have computational throughput measured in GFLOPS. The two lines inside of the plot reflect the hardware limits. The horizontal line is determined by the peak computational throughput (GFLOPS) that the hardware can sustain. The line with a positive slope starting from the origin is determined by the peak memory bandwidth that the hardware can sustain. The point of intersection between these two lines represents the computational intensity threshold at which applications transition from being memory-bound to being compute bound. Applications with lower computational intensity are memory-bound and cannot achieve peak computational throughput because they are limited by memory bandwidth. Within this regime, increasing an application’s computational intensity elevates its potential computational throughput, as reflected by the position slope of the hardware limit line. Once an application’s computational intensity increases beyond the threshold, it becomes computebound and is no longer limited by the peak memory bandwidth but by the peak computational throughput. A point in the plot represents an application with its computational intensity on the x-axis and the computational throughput it achieves on the y-axis. Of course, the points will be under the two lines because they cannot achieve higher throughput than the hardware peak. The position of a point relative to the two lines tells us about an applications efficiency. Points close to the two lines indicate that an application is using memory bandwidth or compute units efficiently, whereas applications far below the lines indicate inefficient use of resources. As an example, points A1 and A2 both represent memory-bound applications, while A3 represents a compute-bound application. A1 uses resources efficiently and operates close to the peak memory bandwidth, whereas A2 does not. For A2, there may be room for additional optimizations to improve throughput by improving memory bandwidth utilization. However, for A1 the only way to improve throughput is to increase the computational intensity of the application. As an example of reasoning about a kernel’s resource bound and efficiency, let us consider the vector addition kernel implemented in Fig. 2.10 from Chapter 2. The main computation performed by each thread in this kernel is replicated as follows: C[i] = A[i] + B[i];

We observe that each thread performs one floating point addition operation and accesses 12 B from global memory (4 B to load A[i], 4 B to load B[i], and 4 B to store C[i]). Accordingly, the kernel’s compute-to-global-memory-access ratio is (1 FLOP)/(12 B) = 0.083 FLOP/B which is much less than the H100 GPU’s threshold of 20.0 FLOP/B. With such a low ratio, the vector addition kernel executing on the H100 GPU is deep in the memory-bound regime. Having established that the vector addition kernel is memory-bound, we can now reason about its performance relative to the hardware peak. If the kernel is executed to add two vectors with one billion elements each, the kernel will access 12 GB of data (4 GB to load the first vector, 4 GB to load the second vector, and 4 GB to store the result vector). If the kernel completes execution in 4 ms, then the average rate at which the data was accessed from memory is (12 GB)/(4 ms) = 3 TB/s. If we divide this rate by the hardware’s peak memory bandwidth, we get (3 TB/s)/(3.35 TB/s) = 90%, which means that the kernel utilizes 90% of the hardware’s memory bandwidth resources. This kind of analysis is referred to as the speed-of-light analysis, and we say that the kernel executes at 90% of the speed of light, i.e., the speed as limited by the hardware. The analysis is useful because it indicates that the kernel utilizes hardware resources efficiently, and that there is only 10% room for further performance optimization. In fact, we can estimate that the fastest possible vector addition kernel when adding two vectors with one billion elements each would take (12 GB)/(3.35 TB/s) = 3.6 ms on the H100 GPU. Let us now apply the same analysis to matrix multiplication. Before looking at a specific implementation, let us reason about matrix multiplication at an abstract level. Assume we would like to multiply two N × N matrices and get a result that is N × N. For each of the N × N output elements, we need to perform a dot-product of two vectors of size N which consists of N multiply operations and N add operations. In total, the matrix multiplication operation performs N 2 · (N + N ) = 2N 3 FLOP. As for the memory accessed, the operation needs to load two matrices with N 2 elements each and store one matrix with N 2 elements. Since each matrix element is 4 B, the total amount of data accessed by the computation is 12N 2 B. Therefore, if we assume a perfect implementation that accesses each data element only once, the compute-to-global-memory-access ratio for matrix multiplication would be (2N 3 )/(12N 2 ) = 0.167N FLOP/B. For N = 1024, the ratio would be 167 FLOP/B which is significantly higher than the H100 GPU’s threshold of 25.1 FLOP/B or 20.0 FLOP/B. Clearly, matrix multiplication has the potential to be a highly computebound computation! We now turn our attention to our specific implementation of matrix multiplication in Fig. 3.11 from Chapter 3. The most dominant part of the kernel in terms of execution time is the for-loop that performs the dot-product of a row of M with a column of N, which is replicated as follows: for (int k = 0; k < Width; ++k) { Pvalue += M[row*Width+k] * N[k*Width+col]; } In every iteration of the loop, two global memory accesses are performed for one floating-point multiplication and one floating-point addition. The global memory accesses fetch elements from the M and N arrays. The floating-point multiplication operation multiplies these two elements together, and the floating-point add operation accumulates the product into Pvalue. Thus, the compute-to-global-memory-access ratio is 2 FLOP to 8 B, or 0.25 FLOP/B. The ratio is actually slightly lower because the Pvalue needs to be stored into the global memory after each thread exits the for-loop. This ratio is lower than the ideal ration of 0.167N of a perfect implementation because each input element is accessed multiple times. The ratio is even lower than the H100 GPU’s threshold of 20.0 FLOP/B, which makes our specific implementation of matrix multiplication memory-bound instead of compute bound. Since our matrix multiplication kernel is memory-bound, the global memory bandwidth limits the throughput of single-precision floating-point operations that can be performed by the kernel to (3.35 TB/s)(0.25 FLOP/B) = 0.84 TFLOPS. However, 0.84 TFLOPS is only around 1% of the peak single-precision operation throughput of the H100 GPU which is 66.9 TFLOPS. The H100 also comes with special purpose units called tensor cores that are useful for accelerating matrix multiplication operations. If one considers the H100’s tensor core peak throughput of 989 TFLOPS, 0.84 TFLOPS is only 0.08% of the peak. In practice, the actual compute-to-globalmemory-access ratio is higher than 0.25 FLOP/B because some of the global memory accesses are served from the on-chip caches instead of the DRAM. Hence, the kernel would achieve a higher percentage of the peak compute throughput. Still, we can further improve the performance of our matrix multiplication implementation by deliberately increasing the ratio at the kernel implementation level. To increase the compute-to-global-memory-access ratio of the kernel, we must reduce the number of global memory accesses it performs. As we will see, matrix multiplication presents opportunities for reduction of global memory accesses that can be captured with relatively simple techniques. The execution speed of matrix multiplication functions can vary by orders of magnitude depending on the level of reduction of global memory accesses. Therefore, matrix multiplication provides an excellent initial example for such techniques. This chapter introduces a commonly used technique for reducing the number of global memory accesses and demonstrates the technique on matrix multiplication.

Figure 5.1

FIGURE 5.1. An (incomplete) overview of the CUDA device memory model. An important type of CUDA memory not covered in this figure is the texture memory since its use is not covered in this textbook.

5.2 CUDA memory types

A CUDA device contains several types of memory that can help programmers to improve the compute-to-global-memory-access ratio of their kernels. By declaring a CUDA variable into one of the CUDA memory types, a CUDA programmer dictates the visibility and access speed of the variable. Fig. 5.1 shows these CUDA device memories. At the bottom of the picture, we see global memory and constant memory. Both these types of memory can be written (W) and read (R) by the host. The global memory can also be written and read by the device, whereas the constant memory supports short-latency, high bandwidth read-only access by the device. We have already introduced global memory in Chapter 2 and will look at constant memory in detail in Chapter 7. Another type of memory is the local memory, which can also be read and written. CUDA variables declared into the local memory are actually placed in global memory and have similar access latency, but are not shared across threads. Each thread has its own section of global memory that it uses as its own private local memory where it places its local variables and data that cannot be allocated in registers. Such variables and data include statically allocated arrays, spilled registers, and other elements of the thread’s call stack. However, statically allocated arrays that have small and constant size and are accessed only with constant indices can be allocated into registers (see Chapter 6 for details). Registers in Fig. 5.1 are one type of on-chip memory. Variables that reside in registers can be accessed at very high speed in a highly parallel manner. Registers are allocated to individual threads; each thread can only access its own registers (see the ``CPU vs. GPU Register Architecture’’ sidebar). A kernel function typically uses registers to hold frequently accessed variables that are private to each thread.

CPU vs. GPU Register Architecture The different design objectives across the CPUs and GPUs result in different register architectures. As we saw in Chapter 4, when CPUs context switch between different threads, they save the registers of the outgoing thread to memory and restore the registers of the incoming thread from memory. In contrast, GPUs achieve zero-overhead scheduling by keeping the registers of all the threads that are scheduled on the processing block in the processing block’s register file. This way, switching between warps of threads is instantaneous because the registers of the incoming threads are already in the register file. Consequently, GPU register files need to be substantially larger than CPU register files. We also saw in Chapter 4 that GPUs support dynamic resource partitioning where an SM may provision few registers per thread and execute a large number of threads, or it my provision more registers per thread and execute fewer threads. For this reason, GPU register files need to be designed to support such dynamic partitioning of registers. In contrast, the CPU register architecture dedicates a fixed set of registers per thread regardless of the thread’s actual demand for registers. Shared memory in Fig. 5.1 is another type of on-chip memory. Data that resides in shared memory can also be accessed at a high speed relative to global memory, though not as fast as registers. Shared memory is allocated to thread blocks; all threads in a block can access shared-memory variables declared for the block. Shared memory is an efficient means for threads in the same block to cooperate by sharing their input data and intermediate results. To fully appreciate the difference between registers, shared memory, and global memory, we need to go into a little more detail of how these different memory types are realized and used in modern processors. As we discussed in the Warps and SIMD Hardware'' sidebar of Chapter 4, virtually all modern processors find their root in the model proposed by John von Neumann in 1945, which is shown in Fig. 5.2. CUDA devices are no exception. The global memory in a CUDA device maps to the Memory box in Fig. 5.2. The processor box corresponds to the processor chip boundary that we typically see today. The global memory is off the processor chip and is implemented with DRAM technology, which implies long access latencies and relatively low access bandwidth. The registers correspond to the Register File’’ of the von Neumann model. The Register File is on the processor chip, which implies very short access latency and drastically higher access bandwidth when compared to the global memory. In a typical device, the aggregated access bandwidth of all the register files across all the SMs is at least two orders of magnitude higher than that of the global memory. Furthermore, whenever a variable is stored in a register, its accesses no longer consume off-chip global memory bandwidth. This will be reflected as an increased compute-to-global-memory-access ratio. A subtler point is that an access to a register involves fewer instructions than an access to the global memory. Arithmetic instructions in most modern processors have FIGURE 5.2 Memory vs. registers in a modern computer based on the von Neumann model.

“built-in’’ register operands. For example, a floating-point addition instruction might be of the form: fadd r1, r2, r3 where r2 and r3 are the register numbers that specifies the location in the register file where the input operand values can be found. The location for storing the floating-point addition result value is specified by r1. Therefore, when an operand of an arithmetic instruction is in a register, there is no additional instruction required to make the operand value available to the arithmetic and logic unit (ALU), where the arithmetic calculation is done. Meanwhile, if an operand value is in the global memory, the processor needs to perform a memory load operation to make the operand value available to the ALU. For example, if the first operand of a floating-point addition instruction is in the global memory, the instructions involved will likely look like the following example: load r2, r4, offset fadd r1, r2, r3 where the load instruction adds an offset value to the contents of r4 to form an address for the operand value. It then accesses the global memory and places the value into register r2. Once the operand value is in r2, the fadd instruction performs the floatingpoint addition using the values in r2 and r3 and places the result into r1. Since the processor can only fetch and execute a limited number of instructions per clock cycle, the version with an additional load will likely take more time to process than the one without. This is another reason why placing the operands in registers can improve execution speed. Finally, there is yet another subtle reason why placing an operand value in registers is preferable. In modern computers, the energy consumed for accessing a value FIGURE 5.3 Shared memory vs. registers in a CUDA device SM.

from the register file is at least an order of magnitude lower than for accessing a value from the global memory. Accessing a value from registers has a tremendous advantage in energy efficiency over accessing the value from the global memory. We will look at more details of the speed and energy difference in accessing these two hardware structures in modern computers soon. On the other hand, as we will soon learn, the number of registers available to each thread is quite limited in today’s GPUs. As we have seen in Chapter 4, the occupancy achieved for an application can be reduced if the register usage exceeds the limit for full-occupancy scenarios. Therefore, we also need to avoid oversubscribing to this limited resource whenever possible. Fig. 5.3 shows the shared memory and registers in a CUDA device. Although both are on-chip memories, they differ significantly in functionality and cost of access. Shared memory is designed as part of the memory space that resides on the processor chip. When the processor accesses data that reside in the shared memory, it needs to perform a memory load operation, just like accessing data in the global memory. However, because shared memory resides on chip, it can be accessed with much lower latency and much higher throughput than the global memory. Because of the need to perform a load operation, shared memory has longer latency and lower bandwidth than registers. In computer architecture terminology, the shared memory is a form of scratchpad memory. One important difference between the shared memory and registers in CUDA is that variables that reside in the shared memory are accessible by all threads in a block. This contrasts with register data, which is private to a thread. That is, shared memory is designed to support efficient, high bandwidth sharing of data among threads in the same block. As shown in Fig. 5.3, a CUDA device SM typically employs multiple processing units, to allow multiple threads to make simultaneous progress (see ``Threads’’ sidebar in Chapter 2). Threads in a block can be spread across these processing units. Therefore, the hardware implementations of the shared memory in these CUDA devices are typically designed to allow multiple processing units to simultaneously access its contents to support efficient data sharing among threads in FIGURE 5.4 CUDA variable declaration type qualifiers and the properties of each type.

a block. We will be learning several important types of parallel algorithms that can greatly benefit from such efficient data sharing among threads. Starting with the Hopper architecture, threads in the same thread block cluster can access the shared memory of any block in the cluster. This feature is referred to as distributed shared memory. Distributed shared memory expands the scope of threads that can collaborate without accessing global memory, and gives them access to a larger collective pool of fast memory. It should be clear by now that registers, local memory, shared memory, and global memory all have different functionalities, latencies, and bandwidth. It is therefore important to understand how to declare a variable so that it will reside in the intended type of memory. Fig. 5.4 presents the CUDA syntax for declaring program variables into the various memory types. Each such declaration also gives its declared CUDA variable a scope and lifetime. Scope identifies the set of threads that can access the variable: a single thread only, all threads of a block, or all threads of all grids. If a variable’s scope is a single thread, a private version of the variable will be created for every thread; each thread can only access its private version of the variable. For example, if a kernel declares a variable whose scope is a thread and it is launched with one million threads, one million versions of the variable will be created so that each thread initializes and uses its own version of the variable. Lifetime tells the portion of the program’s execution duration when the variable is available for use: either within a grid’s execution or throughout the entire application. If a variable’s lifetime is within a grid’s execution, it must be declared within the kernel function body and will be available for use only by the kernel’s code. If the kernel is invoked several times, the value of the variable is not maintained across these invocations. Each invocation must initialize the variable in order to use it. On the other hand, if a variable’s lifetime is throughout the entire application, it must be declared outside of any function body. The contents of these variables are maintained throughout the execution of the application and are available to all kernels. We refer to variables that are not arrays as scalar variables. As shown in Fig. 5.4, all automatic scalar variables declared in kernel and device functions are placed into registers. The scopes of these automatic variables are within individual threads. When a kernel function declares an automatic variable, a private copy of that variable is generated for every thread that executes the kernel function. When a thread terminates, all its automatic variables also cease to exist. For example, in Fig. 3.8 in Chapter 3, the variables blurRow, blurCol, curRow, curCol, pixels, and pixVal are all automatic variables and fall into this category. Note that accessing these variables is extremely fast and parallel, but one must be careful not to exceed the limited capacity of the register storage in the hardware implementations. Using a large number of registers can negatively impact the occupancy of each SM, as we have seen in Chapter 4. Automatic array variables are not stored in registers by default. They are stored into the thread’s local memory and may incur long access delays and potential access congestion. The compiler may decide to store an automatic array variable in registers instead of local memory if all accesses are done with constant index values. We revisit this point in Chapter 6. The scope of automatic array variables, like automatic scalar variables, is limited to individual threads. That is, a private version of each automatic array is created for and used by every thread. Once a thread terminates its execution, the contents of its automatic array variables also cease to exist. If a variable declaration is preceded by the shared keyword (each __'' consists of two ’’ characters), it declares a shared memory variable in CUDA. One can also add an optional device in front of shared in the declaration to achieve the same effect. Such a declaration is typically made within a kernel function or a device function. The scope of a shared memory variable is within a thread block, that is, all threads in a block see the same version of a shared memory variable. A private version of the variable is created for and used by each block during kernel execution. The lifetime of a shared memory variable is within the duration of the kernel execution. When a kernel terminates its grid’s execution, the contents of its shared memory variables cease to exist. As we discussed earlier, shared memory variables are an efficient means for threads within a block to collaborate with each other. Accessing shared memory variables is extremely fast and highly parallel. CUDA programmers often use shared memory variables to hold the portion of global memory data that are frequently used and reused in an execution phase of the kernel. One may need to adjust the algorithms used to create execution phases that heavily focus on small portions of the global memory data, as we will demonstrate with matrix multiplication in Section 5.4. If a variable declaration is preceded by the constant keyword (each __'' consists of two ’’ characters), it declares a constant variable in CUDA. One can also add an optional device in front of constant to achieve the same effect. Declaration of constant variables must be outside any function body. The scope of a constant variable is all grids, meaning that all threads in all grids see the same version of a constant variable. The lifetime of a constant variable is the entire application execution. Constant variables are often used to provide input values to kernel functions. The values of the constant variables cannot be changed by the kernel function code. Constant variables are stored in the global memory but are cached for efficient access. With appropriate access patterns, accessing constant memory is extremely fast and parallel. Currently, the total size of constant variables in an application is limited at 65,536 bytes. One may need to break up the input data volume to fit within this limit. We will demonstrate the usage of constant memory in Chapter 7. A variable whose declaration is preceded only by the keyword device (each “__’’ consists of two ``_’’ characters) is a global variable and will be placed in the FIGURE 5.5 A small example of matrix multiplication. For brevity, We show M[y*Width+x], N[y*Width+x], and P[y*Width+x] as My,x , Ny,x , and Py,x , respectively.

global memory. Access to a global variable is slow. Global variables are visible to all threads of all kernels and their contents persist throughout the entire execution. Global variables are often used to pass information from one kernel invocation to another kernel invocation without providing the information as a kernel parameter. In general, global variables are considered bad style and should be used sparingly because they can cause bugs and negatively impact the code’s modularity.

5.3 Tiling for reduced memory traffic

We have an intrinsic tradeoff in the use of device memories in CUDA: the global memory is large but slow whereas the shared memory is small but fast. A common strategy is to partition the data into subsets called tiles so that each tile fits into the shared memory. The term tile draws on the analogy that a large wall (i.e., the global memory data) can be covered by small tiles (i.e., subsets that each can fit into the shared memory). An important criterion is that the kernel computation on these tiles can be done independently of each other. Note that not all data structures can be partitioned into tiles given an arbitrary kernel function. The concept of tiling can be illustrated with the matrix multiplication example from Chapter 3. Fig. 3.13 showed a small example of matrix multiplication. It corresponds to the kernel function in Fig. 3.11. We replicate the example in Fig. 5.5 for convenient reference by the reader. For brevity, we abbreviate P[y*Width+x], M[y*Width+x], and N[y*Width+x] as Py,x , My,x , and Ny,x , respectively. This example assumes that we use four 2 × 2 blocks to compute the P matrix. The heavy FIGURE 5.6 Global memory accesses performed by threads in block0,0 .

boxes in the P matrix define the output tile of P elements processed by each block. Fig. 5.5 highlights the computation done by the four threads of block0,0. These four threads compute P0,0 , P0,1 , P1,0 , and P1,1 . The accesses to the M and N elements by thread0,0 and thread0,1 of block0,0 are highlighted with black arrows. For example, thread0,0 reads M0,0 and N0,0 , followed by M0,1 and N1,0 followed by M0,2 and N2,0 , followed by M0,3 and N3,0 . Fig. 5.6 shows the global memory accesses done by all threads in block0,0. The threads are listed in the vertical direction, with time of access increasing from left to right in the horizontal direction. Note that each thread accesses four elements of M and four elements of N during its execution. Among the four threads highlighted, there is a significant overlap in the M and N elements they access. For example, thread0,0 and thread0,1 both access M0,0 as well as the rest of row 0 of M. Similarly, thread0,1 and thread1,1 both access N0,1 as well as the rest of column 1 of N. The kernel in Fig. 3.13 is written so that both thread0,0 and thread0,1 access row 0 elements of M from the global memory. If we can somehow manage to have thread0,0 and thread0,1 to collaborate so that these M elements are only loaded from global memory once, we can reduce the total number of accesses to the global memory by half. In fact, we can see that every M and N element is accessed exactly twice during the execution of block0,0 . Therefore, if we can have all four threads to collaborate in their accesses to global memory, we can reduce the overall traffic to the global memory by half. The reader should verify that the potential reduction in global memory traffic in the matrix multiplication example is proportional to the size of the output tile that the block is assigned to. With TILE_WIDTH×TILE_WIDTH tiles, the potential reduction of global memory traffic would be TILE_WIDTH. That is, if we use 32 × 32 output tiles, one can potentially reduce the global memory traffic to 1/32 of the original level through collaboration between threads. We now present a tiled matrix-multiplication algorithm. The basic idea is to have the threads collaboratively load subsets of the M and N elements into the shared memory before they individually use these elements in their dot product calculation. Keep in mind that the size of the shared memory is quite small, and one must be careful not to exceed the capacity of the shared memory when loading these M and N elements into the shared memory. This can be accomplished by dividing the M FIGURE 5.7 Tiling M and N to utilize shared memory.

and N matrices into smaller input tiles. The size of these tiles is chosen so that they can fit into the shared memory. In the simplest form, the input tile dimensions and output tile dimensions are equal to those of the block dimensions, as illustrated in Fig. 5.7. In Fig. 5.7, we divide M and N into 2 × 2 input tiles, as delineated by the thick lines. The dot product calculations performed by each thread are now divided into phases. In each phase, all threads in a block collaborate to load a tile of M and a tile of N into the shared memory. This can be done by having every thread in a block to load one M element and one N element into the shared memory, as illustrated in Fig. 5.8. Each row of Fig. 5.8 shows the execution activities of a thread. Note that time progresses from left to right. We only need to show the activities of threads in block0,0 ; the other blocks all have the same behavior. The shared memory array for the M elements is called Mds. The shared memory array for the N elements is called N ds. At the beginning of Phase 1, the four threads of block0,0 collaboratively load a tile of M into shared memory: thread0,0 loads M0,0 into Mds0,0 , thread0,1 loads M0,1 into Mds0,1 , thread1,0 loads M1,0 into Mds1,0 , and thread1,1 loads M1,1 into Mds1,1 . These loads are shown in the second column of Fig. 5.8. A tile of N is also loaded in a similar manner, shown in the third column of Fig. 5.8. After the two tiles of M and N are loaded into the shared memory, these elements are used in the calculation of the dot product. Note that each value in the shared memory is used twice. For example, the M1,1 value, loaded by thread1,1 into Mds1,1 , is used twice, once by thread1,0 and once by thread1,1 . By loading each global memory value into shared memory so that it can be used multiple times, we reduce the number of accesses to the global memory. In this case, we reduce the number of FIGURE 5.8 Execution phases of a tiled matrix multiplication.

accesses to the global memory by a factor of two. The reader should verify that the reduction is by a factor of N if the tiles are N × N elements. Note that the calculation of each dot product is now performed in two phases, shown as Phase 1 and Phase 2 in Fig. 5.8. In each phase, each thread accumulates products of two pairs of the input matrix elements into the Pvalue variable. Note that Pvalue is an automatic variable, so a private version is generated for each thread. The subscripts clarify that these are different instances of the Pvalue variable created for each thread. The first phase calculation is shown in the fourth column of Fig. 5.8, and the second phase in the seventh column. In general, if an input matrix is of dimension Width and the tile size is TILE_WIDTH, the dot product would be performed in Width/TILE_WIDTH phases. The creation of these phases is key to the reduction of accesses to the global memory. With each phase focusing on a small subset of the input matrix values, the threads can collaboratively load the subset into the shared memory and use the values in the shared memory to satisfy their overlapping input needs in the phase. Note also that Mds and N ds are re-used across phases. In each phase, the same Mds and N ds are reused to hold the subset of M and N elements used in the phase. This allows a much smaller shared memory to serve most of the accesses to global memory. This is because each phase focuses on a small subset of the input matrix elements. Such focused access behavior is called locality. When an algorithm exhibits locality, there is an opportunity to use small, high-speed memories to serve most of the accesses and remove these accesses from the global memory. Locality is as important for achieving high-performance in multi-core CPUs as in many-thread GPUs. We will return to the concept of locality in Chapter 6.

Figure 5.9

FIGURE 5.9. A tiled Matrix Multiplication Kernel using shared memory.

5.4 A tiled matrix multiplication kernel

We are now ready to present a tiled matrix multiplication kernel that uses shared memory to reduce traffic to the global memory. The kernel shown in Fig. 5.9 implements the phases illustrated in Fig. 5.8. In Fig. 5.9, line 04 and line 05 declare Mds and Nds as shared memory arrays. Recall that the scope of shared memory variables is a block. Thus, one version of the Mds and Nds arrays will be created for each block and all threads of a block have access to the same Mds and Nds version. This is important since all threads in a block must have access to the M and N elements loaded into Mds and Nds by their peers so that they can use these values to satisfy their input needs. Lines 07 and 08 save the threadIdx and blockIdx values into automatic variables with shorter names to make the code more concise. Recall that automatic scalar variables are placed into registers. Their scope is in each individual thread. That is, one private version of tx, ty, bx, and by is created for each thread and will reside in registers that are accessible by the thread. They are initialized with the threadIdx and blockIdx values and used many times during the lifetime of thread. Once the thread ends, the values of these variables cease to exist. Lines 11 and 12 determine the row index and column index of the P element that the thread is to produce. The code assumes that each thread is responsible for calculating one P element. As shown in line 12, the horizontal (x) position, or the FIGURE 5.10 Calculation of the matrix indices in tiled multiplication.

column index of the P element to be produced by a thread, can be calculated as bx*TILE_WIDTH+tx. This is because each block covers TILE_WIDTH elements of P in the horizontal dimension. A thread in block bx would have before it bx blocks of threads, or bx*TILE_WIDTH threads; they cover bx*TILE_WIDTH elements of P. Another tx threads within the same block would cover another tx elements. Thus, the thread with indices bx and tx should be responsible for calculating the P element whose x index is bx*TILE_WIDTH+tx. For the example in Fig. 5.7, the horizontal (x) index of the P element to be calculated by thread0,1 of block1,0 is 0*2+1 = 1. This horizontal index is saved in the variable Col for the thread and is also illustrated in Fig. 5.10. Similarly, the vertical (y) position, or the row index, of the P element to be processed by a thread is calculated as by*TILE_WIDTH+ty. Going back to the example in Fig. 5.7, the y index of the P element to be calculated by thread0,1 of block1,0 is 1*2+0 = 2. This vertical index is saved in the variable Row for the thread. As shown in Fig. 5.10, each thread calculates the P element at the Colth column and the Rowth row. Thus, the P element to be calculated by thread0,1 of block1,0 is P2,1 . Line 16 of Fig. 5.9 marks the beginning of the loop that iterates through all the phases of calculating the P element. Each iteration of the loop corresponds to one phase of the calculation shown in Fig. 5.8. The ph variable indicates the number of phases that have already been done for the dot product. Recall that each phase uses one tile of M and one tile of N elements. Therefore, at the beginning of each phase, ph*TILE_WIDTH pairs of M and N elements have been processed by previous phases.

In each phase, lines 19 and 20 in Fig. 5.9 load the appropriate M and N elements into the shared memory. Since we already know the row of M and column of N to be processed by the thread, we now turn our focus to the column index of M and row index of N. As shown in Fig. 5.10, each block has TILE_WIDTH2 threads that will collaborate to load TILE_WIDTH2 elements of M and TILE_WIDTH2 elements of N into the shared memory. Thus, all we need to do is to assign each thread to load one M element and one N element. This is conveniently done using the blockIdx and threadIdx. Note that the beginning column index of the section of M elements to be loaded is ph*TILE_WIDTH. Therefore, an easy approach is to have every thread load an element that is tx positions away from that beginning point. Similarly, the beginning row index of the section of N elements to be loaded is also ph*TILE_WIDTH. Therefore, every thread loads an element that is ty positions away from that beginning point. This is precisely what we have in lines 19 and 20. In line 19, each thread loads M[Row*Width + ph*TILE_WIDTH + tx], where the linearized index is formed with the row index Row and column index ph*TILE_WIDTH + tx. Since the value of Row is a linear function of ty, each of the TILE_WIDTH2 threads will load a unique M element into the shared memory because each thread has a unique combination of tx and ty. Together, these threads will load a dark square subset of M in Fig. 5.10. In a similar way, on Line 20, each thread loads the appropriate N element to shared memory using the linearized index (ph*TILE_WIDTH + ty)*Width + Col. The reader should use the small example in Fig. 5.7 and Fig. 5.8 to verify that the address calculation works correctly for individual threads. The barrier __syncthreads() in line 21 ensures that all threads have finished loading the tiles of M and N into Mds and Nds before any of them can move forward. Recall from Chapter 4 that the call to __syncthreads() can be used to make all threads in a block wait for each other to reach the barrier before any of them can proceed. This is important because the M and N elements to be used by a thread can be loaded by other threads. One needs to ensure that all elements are properly loaded into the shared memory before any of the threads start to use the elements. The loop in line 23 then performs one phase of the dot product based on the tile elements. The progression of the loop for threadty,tx is shown in Fig. 5.10, with the access direction of the M and N elements along the arrow marked with k, the loop variable in line 23. Note that these elements will be accessed from Mds and Nds, the shared memory arrays holding these M and N elements. The barrier __syncthreads() in line 26 ensures that all threads have finished using the M and N elements in the shared memory before any of them move on to the next iteration and load the elements from the next tiles. This way, none of the threads would load the elements too early and corrupt the input values of other threads. The two __syncthreads() calls on lines 21 and 26 demonstrate two different types of data dependences that parallel programmers often have to reason about when coordinating between threads. The first is called a read-after-write dependence because threads must wait for data to be written to the proper place by other threads before they try to read it. The second is called a write-after-read dependence because a thread must wait for the data to be read by all threads that need it before overwriting it. Other names for read-after-write and write-after-read dependences are true andfalse dependences, respectively. A read-after-write dependence is a true dependence because the reading thread truly needs the data supplied by the writing thread, so it has no choice but to wait for it. A write-after-read dependence is a false dependence because the writing thread does not need any data from the reading thread. The dependence is caused by the fact that they are reusing the same memory location and would not exist if they used different locations. We will revisit these types of dependences in Chapter 6. The loop nest from line 16 to line 28 illustrates a technique called strip-mining, which takes a long-running loop and breaks it into phases. Each phase consists of an inner loop that executes a few consecutive iterations of the original loop. The original loop becomes an outer loop whose role is to iteratively invoke the inner loop so that all the iterations of the original loop are executed in their original order. By adding barrier synchronizations before and after the inner loop, we force all threads the same block to all focus their work on a section of their input data during each phase. Stripmining is an important means to creating the phases needed by tiling in data parallel programs.1 After all phases of the dot product are complete, the execution exits the outer loop. In Line 29, all threads write to their P element using the linearized index calculated from Row and Col. The benefit of the tiled algorithm is substantial. For matrix multiplication, the global memory accesses are reduced by a factor of TILE_WIDTH. With 32 × 32 tiles, one can reduce the global memory accesses by a factor of 32. This increases the compute-to-global-memory-access ratio from 0.25 FLOP/B to 8 FLOP/B. This improvement brings the ratio closer to the H100 GPU’s threshold of 20 FLOP/B, but keeps the kernel in the memory-bound range. With this improvement, the memory bandwidth of a CUDA device can support a higher computation rate. For example, in the H100 GPU which has a global memory bandwidth of 3.35 TB/s, this improvement allows the device to achieve (3.35 TB/s)*(8 FLOP/B) = 26.8 TFLOPS, which is substantially higher than the 0.84 TFLOPS achieved by the kernel that did not use tiling. In practice, the ratio and compute throughput may be even higher because of the help of the on-chip caches. Although tiling improves throughput substantially, 26.8 TFLOPS is still only 40% of the device’s peak throughput of 66.9 TFLOPS. To push the ratio above 20 FLOP/B into the compute-bound range and improve compute throughput, one can further optimize the code to reduce the number of global memory accesses. We will see some of these optimizations in Chapter 15. Due to the importance of matrix multiplication in many domains, there are highly optimized libraries such as cuBLAS [1] and CUTLASS [2] that already incorporate many of these advanced optimizations. Programmers can use these libraries to immediately achieve close to peak performance on their linear algebra applications. 1 The reader should note that strip-mining has long been used in programming CPUs. Strip-mining fol lowed by loop interchange is often used to enable tiling for improved locality in sequential programs. Strip-mining is also the main vehicle for vectorizing compilers to generate vector or SIMD instructions for CPU programs.

Note that tiling as an optimization does not only refer to placing frequently accessed subset of data in shared memory. It is a general optimization that refers to placing frequently accessed subset of data in a memory that is faster than where the data previously resides. In our tiled matrix multiplication example, we tiled the M and N matrices in shared memory because the same data elements are repeatedly accessed by different threads in the same block. However, we also applied tiling to the P matrix. Since the same element of P is repeatedly accessed by the same thread, we placed it in a register (Pvalue) and repeatedly accessed it from the register. We refer to this kind of tiling as register tiling. In this particular example, the application of register tiling seems trivial. We will see less trivial examples of register tiling in Chapter 8, Chapter 11, and Chapter 15. The effectiveness of tiling at improving the throughput of matrix multiplication in particular, and applications in general, is not unique to GPUs. There is a long history of applying tiling (or blocking) techniques to improve performance on CPUs by ensuring that the data reused by a CPU thread within a particular time window will be found in the cache. One key difference is that tiling techniques on CPUs rely on the CPU cache to keep reused data on-chip implicitly, whereas tiling techniques on GPUs use shared memory and registers explicitly to keep the data on-chip. The reason is that a CPU core typically runs one or two threads at a time, so a thread can rely on the cache keeping recently used data around. In contrast, a GPU SM runs many threads simultaneously to be able to hide latency. These threads may compete for cache slots which makes the GPU cache less reliable, necessitating the use of shared memory for important data that is to be reused. While the performance improvement of the tiled matrix multiplication kernel is impressive, it does make a few simplifying assumptions. First, the width of the matrices is assumed to be a multiple of the width of thread blocks. This prevents the kernel from correctly processing matrices with arbitrary width. The second assumption is that the matrices are square matrices. This is not always true in practice. In the next section, we will present a kernel with boundary checks that remove these assumptions.

5.5 Boundary checks

We now extend the tiled matrix multiplication kernel to handle matrices with arbitrary width. The extensions will have to allow the kernel to correctly handle matrices whose width is not a multiple of the tile width. Let’s change the small example in Fig. 5.7 to use M, N, and P matrices that have dimensions of 3 × 3. The revised example is shown in Fig. 5.11. Note that the width of the matrices is 3, which is not a multiple of the tile width (2). Fig. 5.11 shows the memory access pattern during the second phase of block0,0 . We see that thread0,1 and thread1,1 attempt to load M elements that do not exist. Similarly, we see that thread1,0 and thread1,1 attempt to access N elements that do not exist.

Figure 5.11

FIGURE 5.11. Loading input matrix elements that are close to the edge – phase 1 of block0,0 .

Accessing non-existing elements is problematic in two ways. In the case of accessing a non-existing element that are past the end of a row (M accesses by thread0,1 and thread1,1 in Fig. 5.11), these accesses will be done to incorrect elements. In our example, the threads will attempt to access M0,3 and M1,3 , which do not exist. So, what will happen to these memory loads? To answer this question, we need to go back to the linearized layout of 2D matrices. The element after M0,2 in the linearized layout is M1,0 . Although thread0,1 is attempting to access M0,3 , it will end up getting M1,0 . The use of this value in the subsequent inner product calculation will obviously corrupt the output value. A similar problem arises when accessing an element past the end of a column (N accesses by thread1,0 and thread1,1 in Fig. 5.11). These accesses are to memory locations outside the allocated area for the array. In some systems, they will return random values from other data structures. Other systems will reject these accesses and cause the program to abort. Either way, the outcome of such accesses is undesirable. From our discussion so far, it may seem that the problematic accesses only arise in the last phase of execution of the threads. This would suggest that we can deal with it by taking special actions during the last phase of the tiled kernel execution. Unfortunately, this is not true. Problematic accesses can arise in all phases. Fig. 5.12 shows the memory access pattern of block1,1 during phase 0. We see that thread1,0 and thread1,1 attempt to access non-existing M elements M3,0 and M3,1 whereas thread0,1 and thread1,1 attempt to access N0,3 and N1,3 , which do not exist. Note that these problematic accesses cannot be prevented by simply excluding the threads that do not calculate valid P elements. For example, thread1,0 in block1,1 does not calculate any valid P element. However, it needs to load M2,1 during phase 0 for other threads in block1,1 to use. Furthermore, note that some threads that calculate valid P elements will attempt to access M or N elements that do not exist.

Figure 5.12

FIGURE 5.12. Loading input elements during phase 0 of block1,1 .

For example, as we have seen in Fig. 5.11, thread0,1 of block0,0 calculates a valid P element P0,1 . However, it attempts to access a non-existing M0,3 during phase 1. These two facts indicate that we will need to use different boundary condition tests for loading M tiles, loading N tiles, and calculating/storing P elements. A rule of thumb to follow is that every memory access needs to have a corresponding check that ensures that the indices used in the access are within the bounds of the array being accessed. Let’s start with the boundary test condition for loading input tiles. When a thread is to load an input tile element, it should test whether the input element it is attempting to load is a valid element. This is easily done by examining the y and x indices. For example, at Line 19 in Fig. 5.9, the linearized index is a derived from a y index of Row and an x index of ph*TILE_WIDTH + tx. The boundary condition test would be that both of indices are smaller than Width: Row < Width && (ph*TILE_WIDTH+tx) < Width. If the condition is true, the thread should go ahead and load the M element. The reader should verify that the condition test for loading the N element is (ph*TILE_WIDTH+ty) < Width && Col < Width. If the condition is false, the thread should not load the element. The question is what should be placed into the shared memory location. The answer is zero (0.0f), a value that will not cause any harm if it is used in the inner product calculation. If any thread uses this zero value in the calculation of its inner product, there will not be any change in the inner product value. Finally, a thread should only store its final inner product value if it is responsible for calculating a valid P element. The test for this condition is (Row < Width) && (Col < Width). The kernel code with the additional boundary condition checks is shown in Fig. 5.13. With the boundary condition checks, the tiled matrix multiplication kernel is just one more step away from being a general matrix multiplication kernel. In general, FIGURE 5.13 Tiled matrix multiplication kernel with boundary condition checks.

5.6 Impact of memory usage on occupancy

matrix multiplication is defined for rectangular matrices: a j × k matrix M multiplied with a k × l matrix N results in a j × l matrix P. Our kernel can only handle square matrices so far. Fortunately, it is quite easy to further extend our kernel into a general matrix multiplication kernel. We need to make a few simple changes. First, the Width argument is replaced by three unsigned integer arguments: j, k, and l. Where Width is used to refer to the height of M or height of P, replace it with j. Where Width is used to refer to the width of M or height of N, replace it with k. Where Width is used to refer to the width of N or width of P, replace it with l. The revision of the kernel with these changes is left as an exercise.

Recall that in Chapter 4, we discussed the importance of maximizing the occupancy of threads on SMs to be able to tolerate long latency operations. The memory usage of a kernel plays an important role in occupancy tuning. While CUDA registers and shared memory can be extremely effective at reducing the number of accesses to global memory, one must be mindful of the SM’s capacity of these memories. Each CUDA device offers limited memory resources, which limit the number threads that can simultaneously reside in the SM for a given application. In general, the more resources each thread requires, the fewer the number of threads that can reside in each SM. Hence, programmers must manage the delicate balance between the benefit of using on-chip memory resources to increase arithmetic intensity, and the benefit of achieving high occupancy to improve latency tolerance.

We have already seen in Chapter 4 how register usage can be a limiting factor for occupancy. Shared memory usage can also limit the number of threads assigned to each SM. For example, the H100 GPU can be configured to have up to 228 KB of shared memory per SM, and supports a maximum of 2048 threads per SM. Thus, for all 2048 thread slots to be used, a thread block should not use more than an average of (228 KB)/(2048 threads) = 114 B/thread. In the tiled matrix multiplication example, every block has extttTILE_WIDTH2 exttt{TILE\_WIDTH}^2 threads, and uses extttTILE_WIDTH2×4 exttt{TILE\_WIDTH}^2\times 4 B of shared memory for MdsM_{ds} and extttTILE_WIDTH2×4 exttt{TILE\_WIDTH}^2\times 4 B of shared memory for NdsN_{ds}. Thus, the thread block uses an average of (TILE_WIDTH2×4 B+TILE_WIDTH2×4 B)/(TILE_WIDTH2 threads)=8(\texttt{TILE\_WIDTH}^2\times 4\ \text{B}+\texttt{TILE\_WIDTH}^2\times 4\ \text{B})/(\texttt{TILE\_WIDTH}^2\ \text{threads})=8 B/thread of shared memory. Therefore, the tiled matrix multiplication kernel’s occupancy is not limited by the shared memory. However, consider if a kernel has thread blocks that use 38 KB of shared memory, and each have 256 threads. In this case, the kernel uses an average of (38 KB)/(256 threads) = 152 B/thread of shared memory. With such shared memory usage, the kernel cannot achieve full occupancy. Each SM can only host a maximum of (228 KB)/(152 B/thread) = 1536 threads. Therefore, the maximum achievable occupancy of this kernel will be (1536 assigned threads)/(2048 maximum threads) = 75%. For kernels that need to use a very large amount of shared memory, CUDA provides the possibility of reconfiguring the SM to use more resources for the shared memory at the expense of other on-chip memory resources, particularly the cache. This configurability enables the coverage of both predictable and less predictable access patterns to benefit from on-chip memory, allowing programmers to apportion the on-chip memory resources according to the best fit for their application. Note that the size of shared memory in each SM can also vary from device to device. Each generation or model of devices can have a different amount of shared memory in each SM. It is often desirable for a kernel to be able to use different amounts of shared memory according to the amount available in the hardware or the amount needed by the program. That is, we may want a host code to dynamically determine the size of the shared memory and adjust the amount of shared memory used by a kernel. This can be done by calling the cudaGetDeviceProperties function. Assume that variable &devProp is passed to the function. In this case, the field devProp.sharedMemPerBlock gives the amount of shared memory available in each SM. The programmer can then determine the amount of shared memory that should be used by each block. The kernels in Fig. 5.9 and Fig. 5.13 do not support any dynamic adjustment of shared memory usage by the host code. The declarations used in Fig. 5.9 hardwire the size of its shared memory usage to a compile-time constant: shared float Mds[TILE_WIDTH][TILE_WIDTH]; shared float Nds[TILE_WIDTH][TILE_WIDTH];

That is, the size of MdsM_{ds} and NdsN_{ds} is set to be TILE_WIDTH2\texttt{TILE\_WIDTH}^2 elements, whatever the value of TILE_WIDTH is set to be at compile time. Since the code contains: #define TILE_WIDTH 32 FIGURE 5.14 Tiled matrix multiplication kernel with dynamically sized shared memory usage.

Both Mds and Nds will have 322 = 1024 elements. If we want to change the size of Mds and Nds, we need to change the value of TILE_WIDTH and recompile the code. The kernel cannot easily adjust its shared memory usage at runtime without recompilation. We can enable dynamic adjustment of the shared memory size with a different style of declaration in CUDA by adding the extern keyword in front of the shared memory declaration and omitting the size of the array in the declaration. Based on this style, the declarations for Mds and Nds need to be merged into one dynamically allocated array as follows: extern shared Mds_Nds[];

Since there is only one merged array, we will also need to manually define where the Mds section of the array starts and where the Nds section starts. Note that the merged array is one-dimensional. We will need to access it using a linearized index based on the vertical and horizontal indices. At run time, when we call the kernel, we can dynamically configure the amount of shared memory to be used for each block as a third configuration parameter to the kernel call. For example, the revised kernel could be launched with the following statements: size_t size = …; matrixMulKernel «< dimGrid, dimBlock, size »> (Md, Nd, Pd, Width, size/2, size/2);

where size_t is a built-in type for declaring a variable to hold the size information for dynamically allocated data structures. The size is expressed in number of bytes. In our matrix multiplication example, for a 32 × 32 tile, we have size to be 2 × 32 × 32 × 4 = 8, 192 bytes to accommodate both Mds and Nds. We have omitted the details of the calculation for setting the value of size at run time and leave it as an exercise for the reader. In Fig. 5.14, we show how one can modify the kernel code in Figs. 5.9 and 5.11 to use dynamically sized shared memory for the Mds and Nds arrays. It may also be useful to pass the sizes of each section of the array as arguments into the kernel function. In this example, we added two arguments: the first one is the size of the Mds section and the second is the size of the Nds section, both in terms of bytes. Note that the in the host code above, we pass size/2 as the values of these arguments, which is 1024 bytes. With the assignments in lines 06 and 07, the rest of the kernel code can use Mds and Nds as the base of the array and use a linearized index to access the Mds and Nds elements. For example, instead of using Mds[ty][tx], one would use Mds[ty*TILE_WIDTH+tx].

5.7 Summary

In summary, the execution speed of a program in modern processors depends on the compute-to-global-memory-access ratio in the kernel code. If the ratio is high, the kernel is compute-bound and its execution speed can be close the peak computational throughput of the hardware. If the ratio is low, the kernel is memory-bound and its execution speed is limited by the rate at which its operands are accessed from memory. CUDA provides access to registers, shared memory, and constant memory. These memories are much smaller than the global memory but can be accessed at much higher speed. Placing data in these memories allows them to be accessed without consuming global memory bandwidth, and thus elevating the compute-to-globalmemory-access ratio for the code. However, using these memories effectively requires re-design of the algorithm. We use matrix multiplication as an example to illustrate tiling, a popular strategy to enhance locality of data access and enable effective use of shared memory. In parallel programming, tiling uses barrier synchronization to force multiple threads to jointly focus on a subset of the input data at each phase of the execution so that the subset data can be placed into these special memory types to enable much higher access speed. It is, however, important for CUDA programmers to be aware of the limited sizes of these special types of memory. Their capacities are implementation dependent. Once their capacities are exceeded, they limit the number of threads that can be simultaneously executing in each SM and can negatively impact the GPU’s computation throughput as well as its ability to tolerate latency. The ability to reason about hardware limitations when developing an application is a key aspect of parallel programming. Although we introduced tiled algorithms in the context of CUDA programming for GPUs, it is an effective strategy for achieving high-performance in virtually all types of parallel computing systems. The reason is that an application must exhibit locality in data access to make effective use of high-speed memories in these systems. For example, in a multi-core CPU system, data locality allows an application to effectively use on-chip data caches to reduce memory access latency and achieve high performance. These on-chip data caches are also of limited size and require the computation to exhibit locality. Therefore, the reader will also find the tiled algorithm useful when developing a parallel application for other types of parallel computing systems using other programming models. Our goal for this chapter is to introduce the concept of locality, tiling, and different CUDA memory types. We introduced a tiled matrix multiplication kernel usingshared memory. We further studied the need for boundary test conditions to allow for arbitrary data dimensions when applying tiling techniques. We also briefly discussed the use of dynamically sized shared memory allocation so that the kernel can adjust the size of shared memory used by each block according to the hardware capability.

5.8 Exercises

\1. Consider matrix addition. Can one use shared memory to reduce the global memory bandwidth consumption? Hint: analyze the elements accessed by each thread and see if there is any commonality between threads. 2. Draw the equivalent of Fig. 5.7 for a 8×8 matrix multiplication with 2×2 tiling and 4×4 tiling. Verify that the reduction in global memory bandwidth is indeed proportional to the dimension size of the tiles. 3. What type of incorrect execution behavior can happen if one forgot to use one or both __syncthreads() in the kernel of Fig. 5.9? 4. Assuming capacity were not an issue for registers or shared memory, give one important reason why it would be valuable to use shared memory instead of registers to hold values fetched from global memory? Explain your answer. 5. For our tiled matrix-matrix multiplication kernel, if we use a 32x32 tile, what is the reduction of memory bandwidth usage for input matrices M and N? 6. Assume that a CUDA kernel is launched with 1000 thread blocks each of which has 512 threads. If a variable is declared as a local variable in the kernel, how many versions of the variable will be created through the lifetime of the execution of the kernel? 7. In the previous question, if a variable is declared as a shared memory variable, how many versions of the variable will be created through the lifetime of the execution of the kernel? 8. Consider performing a matrix multiplication of two input matrices with dimensions N×N. How many times is each element in the input matrices requested from global memory when: a. There is no tiling? b. Tiles of size TxT are used? 9. A kernel performs 36 floating point operations and 7 32-bit global memory accesses per thread. For each of the following device properties, indicate whether this kernel is compute- or memory-bound. a. Peak FLOPS = 200 GFLOPS, Peak Memory Bandwidth = 100 GB/s b. Peak FLOPS = 300 GFLOPS, Peak Memory Bandwidth = 250 GB/s 10. To manipulate tiles, a new CUDA programmer has written the following device kernel which will transpose each tile in a matrix. The tiles are of size BLOCK_WIDTH by BLOCK_WIDTH, and each of the dimensions of matrix A is known to be a multiple of BLOCK_WIDTH. The kernel invocation and code are shown below. BLOCK_WIDTH is known at compile-time and could be set anywhere from 1 to 20.

dim3 blockDim(BLOCK_WIDTH,BLOCK_WIDTH);

dim3 gridDim(A_width/blockDim.x,A_height/blockDim.y);

BlockTranspose«<gridDim, blockDim»>(A, A_width, A_height);

global void

BlockTranspose(float* A_elements, int A_width, int A_height)

{

shared float blockA[BLOCK_WIDTH][BLOCK_WIDTH];

int baseIdx = blockIdx.x * BLOCK_SIZE + threadIdx.x;

baseIdx += (blockIdx.y * BLOCK_SIZE + threadIdx.y) * A_width;

blockA[threadIdx.y][threadIdx.x] = A_elements[baseIdx];

A_elements[baseIdx] = blockA[threadIdx.x][threadIdx.y]; } a. Out of the possible range of values for BLOCK_SIZE, for what values of BLOCK_SIZE will this kernel function execute correctly on the device? b. If the code does not execute correctly for all BLOCK_SIZE values, what is the root cause of this incorrect execution behavior? Suggest a fix to the code to make it work for all BLOCK_SIZE values. 11. Consider the following CUDA kernel and the corresponding host function that calls it:

global void foo_kernel(float* a, float* b) { unsigned int i = blockIdx.x*blockDim.x + threadIdx.x;

float x[4];

shared float y_s;

shared float b_s[128];

for(unsigned int j = 0; j < 4; ++j) {

x[j] = a[j*blockDim.x*gridDim.x + i];

}

if(threadIdx.x == 0) {

y_s = 7.4f;

}

b_s[threadIdx.x] = b[i];

__syncthreads();

b[i] = 2.5f*x[0] + 3.7f*x[1] + 6.3f*x[2] + 8.5f*x[3]

+ y_s*b_s[threadIdx.x] + b_s[(threadIdx.x + 3)%128];

}

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

unsigned int \texttts{N} = 1024;

foo_kernel «< (N + 128 - 1)/128, 128 »>(a_d, b_d); } a. How many versions of the variable i are there? b. How many versions of the array x[] are there?

References

c. d. e. f.

How many versions of the variable y_s are there? How many versions of the array b_s[] are there? What is the amount of shared memory used per block (in B)? What is the floating point to global memory access ratio of the kernel (in OP/B)? 12. Consider a GPU with the following hardware limits: 2048 threads/SM, 32 blocks/SM, 64 K (65536) registers/SM, and 96 KB of shared memory/SM. For each of the following kernel characteristics, specify if the kernel can achieve full occupancy. If not, specify the limiting factor. a. The kernel uses 64 threads/block, 27 registers/thread, and 4 KB of shared memory/SM. b. The kernel uses 256 threads/block, 31 registers/thread, and 8 KB of shared memory/SM.

References [1] NVIDIA, cuBLAS, http://docs.nvidia.com/cuda/cublas, 2025. [2] NVIDIA, CUTLASS, https://docs.nvidia.com/cutlass, 2025.

CHAPTER

Performance considerations

Since different applications impose different demands on architectural resources, different architecture constraints may dominate and become the limiting factors of performance, commonly referred to as bottlenecks. One can often dramatically improve the performance of an application on a particular CUDA device, by trading one resource usage for another. This strategy works well if the resource constraint thus alleviated was the dominating constraint before the strategy was applied and the one thus exacerbated does not have negative effects on parallel execution. Without such understanding, performance tuning would be a guess work; plausible strategies may or may not lead to performance enhancements.

References

[1] NVIDIA, cuBLAS, http://docs.nvidia.com/cuda/cublas, 2025.

[2] NVIDIA, CUTLASS, https://docs.nvidia.com/cutlass, 2025.