Skip to content

Chapter 8 Stencil computation

Programming Massively Parallel Processors 5e — English original

Chapter 8 Stencil computation

CHAPTER

Stencil computation And thread coarsening CONTENTS 8.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 8.2 Parallel stencil – a basic kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 8.3 Memory bandwidth considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 8.4 Shared-memory tiling for stencil sweep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 8.5 Thread coarsening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 8.6 Register tiling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 8.7 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 8.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Stencils are foundational to numerical methods for solving partial differential equations in application domains like fluid dynamics, heat conductance, combustion, weather forecast, climate simulation, and electromagnetics. The data processed by stencil-based algorithms are discretized quantities of physical significance, such as mass, velocity, force, acceleration, temperature, electrical field, and energy whose relations with each other are governed by differential equations. A common use of stencils is to approximate the derivative values of a function based on the function values within a range of input variable values. Stencils bear strong resemblance to convolution in that they both calculate the new value of an element of a multidimensional array based on the current value of the element at the same position and those in the neighborhood in another multidimensional array. Therefore, stencils also need to deal with halo cells and ghost cells. Unlike convolution, a stencil computation is used to iteratively solve the values of continuous and differentiable functions within the domain of interest. The data elements and the weight coefficients used for the elements in the stencil neighborhood are governed by the differential equations being solved. Some stencil patterns are amenable to optimizations that are not applicable to convolution. In the solvers where initial conditions are iteratively propagated through the domain, the calculations of output values may have dependences and need to be performed according to some ordering constraints. Furthermore, because of the numerical accuracy requirements in solving differential equations, the data processed by stencils tend to be high-precision floating data that consume more on-chip memory for tiling techniques. Due to these differences, stencils tend to motivate different optimizations than convolution. Programming Massively Parallel Processors. https://doi.org/10.1016/B978-0-44-343900-1.00018-4 Copyright © 2027 Elsevier Inc. All rights are reserved, including those for text and data mining, AI training, and similar technologies.

Figure 8.1

FIGURE 8.1. (a) Sine as a continuous and differentiable function for 0 ≤ x ≤ π, (b) Design of a regular grid with constant spacing ( π6 ) between grid point for discretization, (c) Resulting discrete representation of the sine function for 0 ≤ x ≤ π.

Stencils are foundational to numerical methods for solving partial differential equations in application domains like fluid dynamics, heat conductance, combustion, weather forecast, climate simulation, and electromagnetics. The data processed by stencil-based algorithms are discretized quantities of physical significance, such as mass, velocity, force, acceleration, temperature, electrical field, and energy whose relations with each other are governed by differential equations. A common use of stencils is to approximate the derivative values of a function based on the function values within a range of input variable values. Stencils bear strong resemblance to convolution in that they both calculate the new value of an element of a multidimensional array based on the current value of the element at the same position and those in the neighborhood in another multidimensional array. Therefore, stencils also need to deal with halo cells and ghost cells. Unlike convolution, a stencil computation is used to iteratively solve the values of continuous and differentiable functions within the domain of interest. The data elements and the weight coefficients used for the elements in the stencil neighborhood are governed by the differential equations being solved. Some stencil patterns are amenable to optimizations that are not applicable to convolution. In the solvers where initial conditions are iteratively propagated through the domain, the calculations of output values may have dependences and need to be performed according to some ordering constraints. Furthermore, because of the numerical accuracy requirements in solving differential equations, the data processed by stencils tend to be high-precision floating data that consume more on-chip memory for tiling techniques. Due to these differences, stencils tend to motivate different optimizations than convolution.

8.1 Background

The first step in using computers to numerically evaluate and solve functions, models, variables, and equations is to convert them into a discrete representation. For example, Fig. 8.1(a) shows the sine function y = sin(x) for 0 ≤ x ≤ π. Fig. 8.1(b) shows the design of a 1D regular (structured) grid whose seven grid points correspond to x values that are of constant spacing ( π6 ) apart. In general, structured grids cover an n-dimensional Euclidean space with identical parallelotopes (e.g., segments in 1D, rectangles in 2D, bricks in 3D). As we will see, with structured grids, derivatives of variables can be conveniently expressed as finite differences. Therefore, structured grids are mainly used in finite-difference methods. Unstructured grids are more complex and are used in finite-element and finite-volume methods. For simplicity, we only use regular grids and thus finite-difference methods in this chapter. Fig. 8.1(c) shows the resulting discrete representation where the sine function is represented with its values at the seven grid points. In this case, the representation is stored in a 1D array F . Note that the x values are implicitly assumed to be i · π6 where i is the index of the array element. For example, the x value that corresponds to element F [2] is 0.87, which is the sine value of 2 · π6 . In a discrete representation, one needs to use an interpolation technique such as linear or splines to derive the approximate value of the function for x values that do not correspond to any of the grid points. The fidelity of the representation, or how accurate the function values from these approximate interpolation techniques are, depends on the spacing between grid points: the smaller the spacing, the more accurate the approximations. By decreasing the spacing, one can improve the accuracy of the representation at the cost of more storage and, as we will see, more compute when we solve a partial differential equation. The fidelity of a discrete representation also depends on the precision of the numbers used. Since we are approximating continuous functions, floating-point numbers are typically used for the grid point values. Mainstream CPUs and GPUs supportdouble-precision (64-bit), single-precision (32-bit), half-precision (16-bit), and other representations (see Appendix A). Among these, double-precision numbers offer the best precision and the most fidelity in discrete representations. However, modern CPUs and GPUs typically have much higher arithmetic computation throughput for single-precision and half-precision arithmetic. Also, since double precision numbers consist of more bits, reading and writing double precision numbers consumes more memory bandwidth. Storing these double precision numbers also requires more memory capacity. This can pose a significant challenge for tiling techniques that require a significant number of grid point values to be stored in on-chip memory and registers in order to achieve high arithmetic intensity, as we learned in Chapter 7. Let us discuss stencils with a little more formalism. In mathematics, a stencil is a geometric pattern of weights applied at each point of a structured grid. The pattern specifies how the values of the grid point of interest can be derived from the values at neighboring points using a numerical approximation routine. For example, a stencil may specify how the derivative value of a function at a point of interest is approximated using finite differences between the values of the function at the point and its neighbors. Since partial differential equations express the relations between functions, variables, and their derivatives, stencils offer a convenient basis for specifying how finite difference methods numerically compute the solutions to partial differential equations. For example, assume that we have a function f (x) discretized into a 1D grid array F and we would like to calculate the discretized derivative of f (x), f ′ (x). We can use the classic finite difference approximation for the first derivative: f ′ (x) = f (x + h) − f (x − h) + O(h2 ) 2h That is, the derivative of a function at point x can be approximated with the difference of the function values at the two neighboring points divided by the difference of the x values of these neighboring points. The value h is the spacing between neighboring points in the grid. The error is expressed by the term O(h2 ), meaning that the error is proportional to the square of h. Obviously, the smaller the h value, the better the approximation. In our example in Fig. 8.1, the h value is π6 or 0.52. The value is not small enough to make the approximation error negligible but should result in a reasonably close approximation. Since the grid spacing is h, the current estimated f (x − h), f (x), f (x + h) values are in F [i − 1], F [i], and F [i + 1] where x = i · h. So, we can calculate the derivative values of f (x) at each grid point into an output array FD: F D[i] = F [i + 1] − F [i − 1] 2·h for all the grid points. This expression can be rewritten as: F D[i] = −1 · F [i − 1] + · F [i + 1] 2·h 2·h FIGURE 8.2 1D stencil examples (a) 3-point (order 1) stencil, (b) 5-point (order 2) stencil, (c) 7-point (order 3) stencil.

Figure 8.3

FIGURE 8.3. (a) 2D 5-point stencil (order 1), (b) 2D 9-point stencil (order 2), (c) 3D 7-point stencil (order 1), (d) 3D 13-point stencil (order 2).

That is, the calculation of the estimated function derivative value at grid point i involves the current estimated function values at grid points [i − 1, i, i + 1] with −1 coefficients [ 2·h , 0, 2·h ], which defines a 1D 3-point stencil, as shown in Fig. 8.2(a). If we are approximating higher derivative values at grid points, we would need to use higher-order finite differences. For example, if the differential equation includes up to the second derivative of f (x), we will use a stencil involving grid points [i − 2, i − 1, i, i + 1, i + 2], which is a 1D 5-point stencil, as shown in Fig. 8.2(b). In general, if the equation involves up to the nth derivative, the stencil will involve n grid points on each side of the center grid point. Fig. 8.2(c) shows a 1D 7-point stencil. The number of grid points on each side of the center point is called the order of the stencil, as it reflects the order of the derivative being approximated. According to this definition, the stencils in Fig. 8.3(a), (b), and (c) are of order 1, 2, and 3, respectively. It should be obvious that solving a partial differential equation of two variables would require the function values to be discretized into a 2D grid, and we need to use a 2D stencil to calculate the approximate partial derivatives. If the partial differential equation involves exclusively the partial derivatives by only one of the variables, e.g., ∂f (x,y) ∂f (x,y) ∂f (x,y) ∂x , ∂y , but not ∂x∂y , we can use 2D stencils whose selected grid points FIGURE 8.4 A 2D grid example and a 5-point (order 1) stencil used to calculate the approximate derivative values at different grid points.

8.2 Parallel stencil – a basic kernel

are all along the x axis and y axis. For example, for a partial differential equation involving only first derivatives by x and first derivatives by y, we can use a 2D stencil that involves two grid points on each side of the center point along the x axis and the y-axis, which results in the 2D 5-point stencil in Fig. 8.3(a). If the equation involves up to second order derivatives only by x or by y, we will use a 2D 9-point stencil, as shown in Fig. 8.3(b). Fig. 8.4 uses a 5-point stencil example to illustrate the concepts of numerical grids, and application of stencils on the grid points. Functions are discretized into their grid point values which are stored in multi-dimensional arrays. In Fig. 8.4, a function of two variables is discretized as a 2D grid which is stored as a 2D array. The stencil used in Fig. 8.4 is 2D and is used to calculate an approximate derivative value (output) at each grid point from function values at the neighboring grid points and the grid point itself. In this chapter, we focus on the computation pattern where a stencil is applied to the all the relevant input grid points to generate the output values at all grid points, which will be referred to as a stencil sweep.

We first present a basic kernel for stencil sweep. For simplicity, we assume that there is no dependence between output grid points when generating the output grid point values within a stencil sweep. We further assume that the grid point values on the boundaries store boundary conditions and do not change from input to output, as FIGURE 8.5 Simplifying boundary condition: The boundary cells contain boundary conditions that are not updated from one iteration to the next. Thus, only the inner output grid points need to be calculated during each stencil sweep.

Figure 8.6

FIGURE 8.6. A basic stencil sweep kernel.

illustrated in Fig. 8.5. That is, the shaded inside area in the output grid is calculated whereas the unshaded boundary cells are not. This is a reasonable assumption since stencils are mainly used to solve differential equations with boundary conditions. Fig. 8.6 shows a basic kernel that performs a stencil sweep. This kernel assumes that each thread block is responsible for calculating a tile of output grid values and each thread is assigned to one of the output grid points. A 2D tiling example of the output grid where each thread block is responsible for a 4 × 4 output tile is shown in Fig. 8.5. However, since most real-world applications solve 3D differential equations, the kernel in Fig. 8.6 assumes a 3D grid and a 3D 7-point stencil like the one in Fig. 8.3(c). The assignment of threads to grid points is done with the familiar linear expressions involving the x, y, and z fields of blockIdx, blockDim, and threadIdx (lines 02-04). Once each thread has been assigned to a 3D grid point, the input values at that grid point and all neighboring grid points are multiplied by different coefficients (c0 to c6 on lines 06-12) and added. The values of these coefficients may be hard-coded in the code, or they may be placed in constant memory depending on the desired level of flexibility. These values depend on the specific differential equation that is being solved, as we explained in Section 8.1.

8.3 Memory bandwidth considerations

Following the same approach introduced in Chapter 5 and used in Chapter 7, let us analyze the arithmetic intensity of the 3D 7-point stencil sweep and reason about its demand for memory bandwidth. Let us assume that the size of the grid is n × n × n. Since we only perform a stencil computation for the internal points in the grid, the total number of grid point values we compute is (n − 2)3 . To compute each of these values, we must perform 13 floating-point operations (seven multiplications and six additions). Overall, the total number of arithmetic operations performed is 13 · (n − 2)3 FLOP. The data that needs to be accessed to perform these computations are the values of the input grid to be loaded and the values of the output grid to be stored. For the input grid, all the points in the grid except the points in the edges and corners of the 3D space are accessed, which total n3 − 12 · n + 16 values. For the output grid, all the internal grid points are accessed, which total (n − 2)3 values. Each value is a singleprecision floating point number (4 B). Therefore, the total number of bytes accessed is 4 · (n3 − 12 · n + 16 + (n − 2)3 ). Overall, the arithmetic intensity of an ideal 3D 7-point stencil computation, where 13·(n−2)3 each input grid point is loaded only once, is 4·(n3 −12·n+16+(n−2) 3 ) . For a very largevalue of n, this ratio approaches 13 8 = 1.625 FLOP/B. Clearly, this ratio is very small, which makes the 3D 7-point stencil computation memory-bound on modern GPUs. Let us now calculate the arithmetic intensity for the basic stencil sweep kernel in Fig. 8.6. Each thread in the kernel computes one output element, performing 13 floating-point operations (seven multiplications and six additions), loading seven 4 B input values, and storing one 4 B output value. Therefore, the arithmetic intensity for this kernel is (7+1)·4 = 0.41 FLOP/B. This value is significantly lower than the ideal intensity of 1.625 FLOP/B. In practice, if we measure the arithmetic intensity of the kernel, it may be somewhat higher because the elements may be found in the L1 or L2 cache. Still, we can more reliably improve the arithmetic intensity of the kernel by applying optimizations to improve its memory bandwidth utilization. In Section 8.4, we apply shared memory tiling like we did in Chapter 7 to elevate the arithmetic intensity of the stencil kernel.

8.4 Shared-memory tiling for stencil sweep

As we have seen in Chapter 5, the arithmetic intensity of a computation can be significantly elevated with shared memory tiling. As the reader probably suspected, the FIGURE 8.7 Input and output tiles for a 2D 5-point stencil.

design of shared memory tiling for stencils is almost identical to that for convolutions. However, there are a few subtle but important differences. Fig. 8.7 shows the input and output tiles for a 2D 5-point stencil applied to a small grid example. A quick comparison with Fig. 7.11 shows a small difference between convolution and stencil sweep: the input tiles of the 5-point stencil do not include the corner grid points. This property will become important when we explore register tiling later in this chapter. For the purpose of shared memory tiling, we can expect that the input data reuse for a 2D 5-point stencil to be significantly lower than a 3×3 convolution. As we discussed in Chapter 7, the upper bound of the ideal arithmetic intensity of a 2D 3×3 convolution is 14 · 32 = 2.25 FLOP/B. However, for a 2D 5point stencil, the ideal arithmetic intensity is only 1.125 FLOP/B. This is because each output grid point value only uses 5 input grid values, compared to the 9 input pixel values in a 3×3 convolution. The difference is even more pronounced when the number of dimensions and the order of the stencil increases. For example, if we increase the order of the 2D stencil from 1 (1 grid point on each side, 5-point stencil) to 2 (2 grid points on each side, 9point stencil), the upper bound on the ratio is 2.125 FLOP/B, compared 6.25 FLOP/B for its counterpart 2D 5×5 convolution. This discrepancy is further pronounced when the order of the 2D stencil is increased to 3 (3 grid points on each side, 13-point stencil). The upper bound on the ratio is 3.125 FLOP/B, compared to 12.25 FLOP/B for its counterpart 2D 7 × 7 convolution. When we move into 3D, the discrepancy between the arithmetic intensity of stencil sweep and convolution is even more pronounced. For example, a 3D 3rd order stencil (3 points on each side, 19-point stencil) has an upper bound of 4.625 FLOP/B, compared to 85.75 FLOP/B for its counterpart 3D 7 × 7 × 7 convolution. That is, the benefit of loading of an input grid point value into the shared memory for stencil sweep can be significantly lower than that for convolution, especially for 3D which is the prominent use case for stencils. As we will see later, this small but significant difference motivates the use of thread coarsening and register tiling in the 3rd dimension.

Figure 8.8

FIGURE 8.8. A 3D 7-point stencil sweep kernel with shared-memory tiling.

Since all the strategies for loading input tiles for convolution directly apply to stencil sweep, we present in Fig. 8.8 a kernel like the convolution kernel in Fig. 7.12 where blocks are of the same size as the input tiles and some of the threads are turned off when calculating output grid point values. The kernel is adapted from the basic stencil sweep kernel in Fig. 8.6 so we will only focus on the changes made during the adaptation. Like the tiled convolution kernel, the tiled stencil sweep kernel first calculates the x, y, and z coordinates of the grid point value that each thread is responsible for loading and possibly computing with. The value 1 is subtracted in each expression because the kernel assumes a 3D 7-point stencil with one grid point on each side (lines 02-04). In general, the value subtracted should be the order of the stencil. The kernel allocates an in_s array in shared memory to hold the input tile for each block (line 05). Every thread loads one input element. Like the tiled convolution kernel, each thread loads the beginning element of the cubic input patch that contains the stencil grid point pattern. Because of the subtraction in lines 02-04, it is possible that some of the threads may attempt to load ghost cells of the grid. The conditions i >= 0, j >= 0, and k >= 0 (line 06) guard against these out-of-bound accesses. Because the blocks are larger than the output tiles, it is also possible that some of the threads at the end of the x, y, and z dimensions of a block attempt to access the ghost cells outside the upper bound of each dimension of the grid array. The conditions i < N, j < N, and k < N (line 6) guard against these out-of-bound accesses. All threads in the thread block collaboratively load the input tile into the shared memory (line 07) and use the barrier synchronization to wait until all input tile grid points are in the shared memory (line 09). Each block calculates its output tile on lines 10-21. The conditions on line 10 reflect the simplifying assumption that the boundary points of both the input grid and the output hold initial condition values and do not need to be calculated from iteration to iteration by the kernel. Therefore, threads whose output grid points fall on these boundary positions are turned off. Note that the boundary grid points form a layer at the surface of the grid. The conditions in lines 11-12 turn off the extra threads that were launched just to load the input tile grid points. The conditions allow those threads whose i, j, and k index values fall within the output tile to calculate the output grid points selected by these indices. Finally, each active thread calculates its output grid point value using the input grid points specified by the 7-point stencil while accessing the input values from shared memory instead of global memory. We can evaluate the effectiveness of shared memory tiling by calculating the arithmetic intensity achieved by this kernel. Recall that the original stencil sweep kernel achieved a ratio of 0.41 FLOP/B when caching is not considered. With the shared memory tiling kernel, let us assume that each input tile is a cube with t grid points in each dimension and each output tile has t − 2 grid points in each dimension. Therefore, each block has (t − 2)3 active threads calculating output grid point values and each active thread performs 13 floating-point multiplication or addition operations, which is a total of 13 · (t − 2)3 floating-point arithmetic operations. Moreover, each block loads an input tile by performing t 3 loads and stores an output tile by performing (t − 2)3 stores that are 4 bytes each. Therefore, the arithmetic intensity of the tiled kernel can be calculated as: 13 · (t − 2)3 · = 8 1· 4 · t + 4 · (t − 2)

t3 + 12 (t−2)3

FLOP/B

That is, the larger the value of t, the higher the arithmetic intensity. Intuitively, the larger the output tile, the more the input grid point values are reused. The upper bound on the arithmetic intensity as t increases asymptotically is 13 8 = 1.625 FLOP/B, which is the ideal arithmetic intensity derived in Section 8.3. Unfortunately, the 1024 limit on the block size on current hardware makes it difficult to have large t values for the kernel in Fig. 8.8. The practical limit on t is 8 because an 8 × 8 × 8 thread block has a total of 512 threads. Furthermore, the amount of shared memory used for the input tile is proportional to t 3 . Thus, a larger t dramatically increases the consumption of the shared memory. These hardware constraints force us to use small tile sizes for the tiled stencil kernel. There are two major disadvantages to the small limit on the t value imposed by the hardware. The first disadvantage is that it limits the arithmetic intensity. For t = 8, the arithmetic intensity for a 7-point stencil is only 0.96 FLOP/B, which is much less than the ideal arithmetic intensity of 1.625 FLOP/B. The arithmetic intensity decreases as the t value decreases because of the halo overhead. As we discussed in Chapter 7, halo elements are less reused than the non-halo elements. As t decreases, the portion of halo elements in the input tile increases so the arithmetic intensity decreases. For example, for a convolution filter with radius 1, a 32 × 32 2D input tile has 1024 input elements. The corresponding output tile has 30 × 30 = 900 elements, which means that 1024 − 900 = 124 of the input elements are halo elements. The portion of halo elements in the input tile is about 12%. In contrast, for a 3D stencil of order 1, an 8 × 8 × 8 3D input tile has 512 elements. The corresponding output tile has 6 × 6 × 6 = 216 elements, which means that 512 − 216 = 296 of the input elements are halo elements. The portion of halo elements in the input tile is about 58%! The second disadvantage of a small tile size is that it has an adverse impact on memory coalescing. For an 8 × 8 × 8 tile, every warp which consists of 32 threads is responsible for loading 4 different rows of the tile that each have 8 input values. Hence, on the same load instruction, the threads of the warp access at least 4 distant locations in global memory. These accesses cannot be coalesced and underutilize the DRAM bandwidth. This second disadvantage can be overcome by using non-square tiles such that the x-dimension of the thread block is 32 and threads in the same warp access a contiguous chunk of 32 elements. For example, the block dimension could be set to 32, 8, and 4 in the x, y, and z dimensions. Such a block dimension would result in better performance than the cubic blocks with 8 threads in each dimension because it would improve the coalescing of memory accesses. Nevertheless, even with such a rearrangement of the block dimensions, the size of the output tile remains small overall and the arithmetic intensity remains low. This need for a larger tile size to improve arithmetic intensity motivates the approach that we cover in Section 8.5.

8.5 Thread coarsening

As we mentioned in the previous section, the fact that stencils are typically applied to 3D grids and the sparse nature of the stencil patterns can make stencil sweep a less profitable target of shared memory tiling than convolution. This section presents the use of thread coarsening to overcome the block size limitation by coarsening the work done by each thread from calculating one grid point value to a column of grid point values, as illustrated in Fig. 8.9. Recall from Chapter 6 that with thread coarsening, the programmer partially serializes parallel units of work into each thread and reduces the overhead of parallelization. In this case, the overhead of fine-grain parallelization is having to load the halo elements (which have low data reuse) into more thread blocks. In Fig. 8.9, we assume that each input tile consists of t 3 = 63 = 216 grid points. Note that to make the inside of the input tile visible, we have peeled away the front, left, and top layers of the tile. We also assume that each output tile consists of (t − 2)3 = 43 = 64 grid points. The x, y, and z directions in the illustration are shown with the coordinate system for the input and the output. Each x-y plane of the input tile consists of 62 = 36 grid points and each x-y plane of the output tile consists of 42 = 16 grid points. The thread block assigned to process this tile consists of the same number of threads as one x-y plane of the input tile (i.e., 6×6). In the illustration, we only show the internal threads of the thread block that are active in computing output tile values (i.e., 4 × 4).

Figure 8.9

FIGURE 8.9. Thread coarsening in the z direction for a 3D 7-point stencil sweep.

Figure 8.10

FIGURE 8.10. Kernel with thread coarsening in the z direction for a 3D 7-point stencil sweep.

Fig. 8.10 shows a kernel with thread coarsening in the z direction for a 3D 7-point stencil sweep. The idea is for the thread block to iterate in the z direction (into thefigure), calculating the values of grid points in one x-y plane of the output tile during each iteration. The kernel first assigns each thread to a grid point in an x-y plane of the output (lines 03-04). Note that i is the z index of the output tile grid point calculated by each thread. During each iteration, all threads in a block process an x-y plane of an output tile and thus they all calculate output grid points whose z indices are identical. Initially, each block needs to load into the shared memory the three input tile planes that contain all the points needed to calculate the values of the output tile plane that is the closest to the reader (marked with threads) in Fig. 8.9. This is done by having all the threads in the block to load the first layer into the shared memory array inPrev_s (lines 08-10) and the second layer into the shared memory array inCurr_s (lines 11-13). For the first layer, inPrev_s is loaded from the front layer of the input tile that has been peeled off for visibility into the internal layers. During the first iteration, all threads in a block collaborate to load the third layer needed for the current output tile layer into the shared memory array inNext_s (lines 15-17). All threads then wait on a barrier (line 18) until everyone has completed loading the input tile layers. The conditions in lines 19-21 serve the same purpose as their counterparts in the shared memory kernel in Fig. 8.8. Each thread then calculates its output grid point value in the current output tile plane using the four x-y neighbors stored in inCurr_s, the z neighbor in inPrev_s, and the z neighbor in inNext_s. All threads in the block then wait at the barrier to ensure that every thread completes its calculation before they move on to the next output tile plane. Once off the barrier, all threads collaborate to move the contents of inCurr_s to inPrev_s and the contents of inNext_s to inCurr_s. This is because the roles played by the input tile planes change when the threads move by one output plane in the z direction. So, by the end of each iteration, the block has two of the three input tile planes needed for calculating the output tile plane of the next iteration. All threads then move into the next iteration and load the third plane of the input tile needed for the output plane of the iteration. The updated mappings of inPrev_s, inCurr_s, and inNext_s in preparation for the calculation of the second output tile plane are illustrated in Fig. 8.11. The advantage of the thread coarsening kernel is that it increases the tile size without increasing the number of threads, and it does not require all planes of the input tile to be present in the shared memory simultaneously. The thread block size is now only t 2 instead of t 3 , where t is the dimension of the input tile, so we can use a much larger t value. For example, we can use t = 32 that would result in a block size of t 2 = 1024 threads. With this t value, the arithmetic intensity of the kernel is 1.52 FLOP/B, which is a significant improvement over the 0.96 FLOP/B intensity of the original shared memory tiling kernel with 8 × 8 × 8 input tiles, and closer to the 1.625 FLOP/B ideal intensity. Moreover, at any point in time, only three layers of the input tile need to be in the shared memory. The shared memory capacity requirement is now 3 · t 2 elements instead of t 3 elements. For t = 32, the shared memory consumption is now at a reasonable level of 3 · 322 · 4 = 12 KB per block.

Figure 8.11

FIGURE 8.11. The mapping of the shared memory arrays to the input tile after the first iteration.

8.6 Register tiling

The special characteristics of some stencil patterns can give rise to new optimization opportunities. Here we present an optimization that can be especially effective for stencil patterns that involve only neighbors along the x, y, and z directions of the center point. All stencils in Fig. 8.3 match this description. The 3D 7-point stencil sweep kernel in Fig. 8.10 reflects this property. Each inPrev_s and inNext_s element is only used by one thread in the calculation of the output tile grid point with the same x-y indices. Only the inCurr_s elements are accessed by multiple threads and truly need to be in the shared memory. The z neighbors in inPrev_s and inNext_s can instead stay in the registers of the single user thread. Keeping data in registers to reduce shared or global memory accesses is called register tiling, as discussed in Chapter 5 and Chapter 6. Fig. 8.12 shows a stencil sweep kernel with register tiling applied to the previous and next planes of the input tile. The kernel is built on the thread coarsening kernel in Fig. 8.10 with some simple but important modifications. We focus our discussion on these modifications. First, we create three register variables inPrev, inCurr, and inNext (lines 05, 07, 08). Register variables inPrev and inNext replace the shared memory arrays inPrev_s and inNext_s, respectively. In comparison, we keep inCurr_s to allow the x-y neighbor grid point values to be shared among threads. Therefore, the amount of shared memory used by this kernel is reduced to one third of that by the kernel in Fig. 8.12. The initial loading of the previous and current input tile planes (lines 09-15) and the loading of the next plane of the input tile before each new iteration (lines 17-19) are all performed with register variables as destinations. Thus, the three planes of the “active part’’ of the input tile are held in registers across the threads of the same block. In addition, the kernel always maintains a copy the current plane of the input tile in FIGURE 8.12 Kernel with thread coarsening and register tiling in the z direction for a 3D 7-point stencil sweep.

the shared memory (lines 14 and 34). That is, the x-y neighbors of the active input tile plane are always available to all threads that need to access these neighbors. The kernels in Fig. 8.10 and Fig. 8.12 both keep only the ``active part’’ of the input tile in the on-chip memory. The number of planes in the active part depends on the order of the stencil and is 3 for the 3D 7-point stencil. The coarsening and register tiling kernel in Fig. 8.12 has two advantages over the coarsening kernel in Fig. 8.10. First, many reads from and writes to the shared memory are now performed on registers. Since registers have significantly lower latency and higher bandwidth than the shared memory, we expect the code to run faster. Second, each block consumes only one third of the shared memory it did previously. This is, of course, achieved at the cost of three more registers used by each thread, or 3072 more registers per block assuming 32 × 32 blocks. The reader should keep in mind that register use will become even higher for higher order stencils. If the register usage becomes a problem, one can go back to storing some of the planes in shared memory. This scenario represents a common trade-off that often needs to be made between shared memory and register usage. Overall, the data reuse is now spread across registers and the shared memory. The number of global memory accesses has not changed. The overall data reuse if we consider both registers and the shared memory remains the same as the thread coarsening kernel that uses only the shared memory for the input tile. Thus, there is no impact on the consumption of the global memory bandwidth when we add register tiling to thread coarsening.

8.7 Summary

In this chapter, we dived into stencil sweep computation, which seems to be just convolution with special filter patterns. However, because the stencils come from discretization and numerical approximation of derivatives in solving differential equations, they have two characteristics that motivate and enable new optimizations. First stencil sweeps are typically done on 3D grids whereas convolution is typically done on 2D images or a small number of time slices of 2D images. This makes the tiling considerations different between the two and motivate thread coarsening for 3D stencils to enable larger input tiles and higher arithmetic intensity. Second, the stencil patterns can sometimes enable register tiling of input data to further improve data access throughput and alleviate shared memory pressure.

8.8 Exercises

\1. Consider a 3D stencil computation on a grid of size 120 × 120 × 120 including boundary cells. a. What is the number of output grid points computed during each stencil sweep? b. For the basic kernel in Fig. 8.6, what is the number of thread blocks needed assuming a block size of 8 × 8 × 8? c. For the kernel with shared memory tiling in Fig. 8.8, what is the number of thread blocks needed assuming a block size of 8 × 8 × 8? d. For the kernel with shared memory tiling and thread coarsening in Fig. 8.10, what is the number of thread blocks needed assuming a block size of 32×32? 2. Consider an implementation of 7-point (3D) stencil with shared memory tiling and thread coarsening applied. The implementation is similar to those in Fig. 8.10 and Fig. 8.12, except that the tiles are not perfect cubes. Instead, a thread block size of 32 × 32 is used as well as a coarsening factor of 16 (i.e., each thread block processes 16 consecutive output planes in the z-dimension). a. What is the size of the input tile (in number of elements) that the thread block loads throughout its lifetime?

b. What is the size of the output tile (in number of elements) that the thread block processes throughout its lifetime? c. What is the arithmetic intensity (in FLOP/B) of the kernel? d. How much shared memory (in B) is needed by each thread block if register tiling is not used, as in Fig. 8.10? e. How much shared memory (in B) is needed by each thread block if register tiling is used, as in Fig. 8.12?

CHAPTER

Histogram An introduction to atomic operations and privatization

Figure 9.1

FIGURE 9.1. An example of an image histogram.