Home > Articles > Programming

GPU Programming and Streaming Multiprocessors

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book
The streaming multiprocessors (SMs) are the part of the GPU that runs CUDA kernels. This chapter focuses on the instruction set capabilities of the SM.

The streaming multiprocessors (SMs) are the part of the GPU that runs our CUDA kernels. Each SM contains the following.

  • Thousands of registers that can be partitioned among threads of execution
  • Several caches:
    • Shared memory for fast data interchange between threads
    • Constant cache for fast broadcast of reads from constant memory
    • Texture cache to aggregate bandwidth from texture memory
    • L1 cache to reduce latency to local or global memory
  • Warp schedulers that can quickly switch contexts between threads and issue instructions to warps that are ready to execute
  • Execution cores for integer and floating-point operations:
    • – Integer and single-precision floating point operations
    • – Double-precision floating point
    • – Special Function Units (SFUs) for single-precision floating-point transcendental functions

The reason there are many registers and the reason the hardware can context switch between threads so efficiently are to maximize the throughput of the hardware. The GPU is designed to have enough state to cover both execution latency and the memory latency of hundreds of clock cycles that it may take for data from device memory to arrive after a read instruction is executed.

The SMs are general-purpose processors, but they are designed very differently than the execution cores in CPUs: They target much lower clock rates; they support instruction-level parallelism, but not branch prediction or speculative execution; and they have less cache, if they have any cache at all. For suitable workloads, the sheer computing horsepower in a GPU more than makes up for these disadvantages.

The design of the SM has been evolving rapidly since the introduction of the first CUDA-capable hardware in 2006, with three major revisions, codenamed Tesla, Fermi, and Kepler. Developers can query the compute capability by calling cudaGetDeviceProperties() and examining cudaDeviceProp.major and cudaDeviceProp.minor, or by calling the driver API function cuDeviceComputeCapability(). Compute capability 1.x, 2.x, and 3.x correspond to Tesla-class, Fermi-class, and Kepler-class hardware, respectively. Table 8.1 summarizes the capabilities added in each generation of the SM hardware.

Table 8.1 SM Capabilities

COMPUTELEVEL

INTRODUCED . . .

SM 1.1

Global memory atomics; mapped pinned memory; debuggable (e.g., breakpoint instruction)

SM 1.2

Relaxed coalescing constraints; warp voting (any() and all() intrinsics); atomic operations on shared memory

SM 1.3

Double precision support

SM 2.0

64-bit addressing; L1 and L2 cache; concurrent kernel execution; configurable 16K or 48K shared memory; bit manipulation instructions ( __clz(), __popc(), __ffs(), __brev() intrinsics); directed rounding for single-precision floating-point values; fused multiply-add; 64-bit clock counter; surface load/store; 64-bit global atomic add, exchange, and compareand-swap; global atomic add for single-precision floating-point values; warp voting (ballot()intrinsic); assertions and formatted output (printf).

SM 2.1

Function calls and indirect calls in kernels

SM 3.0

Increase maximum grid size; warp shuffle; permute; 32K/32K shared memory configuration; configurable shared memory (32- or 64-bit mode) Bindless textures (“texture objects”); faster global atomics

SM 3.5

64-bit atomic min, max, AND, OR, and XOR; 64-bit funnel shift; read global memory via texture; dynamic parallelism

In Chapter 2, Figures 2.29 through 2.32 show block diagrams of different SMs. CUDA cores can execute integer and single-precision floating-point instructions; one double-precision unit implements double-precision support, if available; and Special Function Units implement reciprocal, recriprocal square root, sine/cosine, and logarithm/exponential functions. Warp schedulers dispatch instructions to these execution units as the resources needed to execute the instruction become available.

This chapter focuses on the instruction set capabilities of the SM. As such, it sometimes refers to the “SASS” instructions, the native instructions into which ptxas or the CUDA driver translate intermediate PTX code. Developers are not able to author SASS code directly; instead, NVIDIA has made these instructions visible to developers through the cuobjdump utility so they can direct optimizations of their source code by examining the compiled microcode.

8.1. Memory

8.1.1. Registers

Each SM contains thousands of 32-bit registers that are allocated to threads as specified when the kernel is launched. Registers are both the fastest and most plentiful memory in the SM. As an example, the Kepler-class (SM 3.0) SMX contains 65,536 registers or 256K, while the texture cache is only 48K.

CUDA registers can contain integer or floating-point data; for hardware capable of performing double-precision arithmetic (SM 1.3 and higher), the operands are contained in even-valued register pairs. On SM 2.0 and higher hardware, register pairs also can hold 64-bit addresses.

CUDA hardware also supports wider memory transactions: The built-in int2/float2 and int4/float4 data types, residing in aligned register pairs or quads, respectively, may be read or written using single 64- or 128-bit-wide loads or stores. Once in registers, the individual data elements can be referenced as .x/.y (for int2/float2) or .x/.y/.z/.w (for int4/float4).

Developers can cause nvcc to report the number of registers used by a kernel by specifying the command-line option --ptxas-options -–verbose. The number of registers used by a kernel affects the number of threads that can fit in an SM and often must be tuned carefully for optimal performance. The maximum number of registers used for a compilation may be specified with --ptxas-options --maxregcount N.

Register Aliasing

Because registers can hold floating-point or integer data, some intrinsics serve only to coerce the compiler into changing its view of a variable. The __int_as_float() and __float_as_int() intrinsics cause a variable to “change personalities” between 32-bit integer and single-precision floating point.

float __int_as_float( int i );
int __float_as_int( float f );

The __double2loint(), __double2hiint(), and __hiloint2double() intrinsics similarly cause registers to change personality (usually in-place). __double_as_longlong() and __longlong_as_double() coerce register pairs in-place; __double2loint() and __double2hiint() return the least and the most significant 32 bits of the input operand, respectively; and __hiloint2double() constructs a double out of the high and low halves.

int double2loint( double d );
int double2hiint( double d );
int hiloint2double( int hi, int lo );
double long_as_double(long long int i );
long long int __double_as_longlong( double d );

8.1.2. Local Memory

Local memory is used to spill registers and also to hold local variables that are indexed and whose indices cannot be computed at compile time. Local memory is backed by the same pool of device memory as global memory, so it exhibits the same latency characteristics and benefits as the L1 and L2 cache hierarchy on Fermi and later hardware. Local memory is addressed in such a way that the memory transactions are automatically coalesced. The hardware includes special instructions to load and store local memory: The SASS variants are LLD/LST for Tesla and LDL/STL for Fermi and Kepler.

8.1.3. Global Memory

The SMs can read or write global memory using GLD/GST instructions (on Tesla) and LD/ST instructions (on Fermi and Kepler). Developers can use standard C operators to compute and dereference addresses, including pointer arithmetic and the dereferencing operators *, [], and ->. Operating on 64- or 128-bit built-in data types (int2/float2/int4/float4) automatically causes the compiler to issue 64- or 128-bit load and store instructions. Maximum memory performance is achieved through coalescing of memory transactions, described in Section 5.2.9.

Tesla-class hardware (SM 1.x) uses special address registers to hold pointers; later hardware implements a load/store architecture that uses the same register file for pointers; integer and floating-point values; and the same address space for constant memory, shared memory, and global memory.1

Fermi-class hardware includes several features not available on older hardware.

  • 64-bit addressing is supported via “wide” load/store instructions in which addresses are held in even-numbered register pairs. 64-bit addressing is not supported on 32-bit host platforms; on 64-bit host platforms, 64-bit addressing is enabled automatically. As a result, code generated for the same kernels compiled for 32- and 64-bit host platforms may have different register counts and performance.
  • The L1 cache may be configured to be 16K or 48K in size.2 (Kepler added the ability to split the cache as 32K L1/32K shared.) Load instructions can include cacheability hints (to tell the hardware to pull the read into L1 or to bypass the L1 and keep the data only in L2). These may be accessed via inline PTX or through the command line option –X ptxas –dlcm=ca (cache in L1 and L2, the default setting) or –X ptxas –dlcm=cg (cache only in L2).

Atomic operations (or just “atomics”) update a memory location in a way that works correctly even when multiple GPU threads are operating on the same memory location. The hardware enforces mutual exclusion on the memory location for the duration of the operation. Since the order of operations is not guaranteed, the operators supported generally are associative.3

Atomics first became available for global memory for SM 1.1 and greater and for shared memory for SM 1.2 and greater. Until the Kepler generation of hardware, however, global memory atomics were too slow to be useful.

The global atomic intrinsics, summarized in Table 8.2, become automatically available when the appropriate architecture is specified to nvcc via --gpu-architecture. All of these intrinsics can operate on 32-bit integers. 64-bit support for atomicAdd(), atomicExch(), and atomicCAS() was added in SM 1.2. atomicAdd() of 32-bit floating-point values (float) was added in SM 2.0. 64-bit support for atomicMin(), atomicMax(), atomicAnd(), atomicOr(), and atomicXor() was added in SM 3.5.

Table 8.2 Atomic Operations

MNEMONIC

DESCRIPTION

atomicAdd

Addition

atomicSub

Subtraction

atomicExch

Exchange

atomicMin

Minimum

atomicMax

Maximum

atomicInc

Increment (add 1)

atomicDec

Decrement (subtract 1)

atomicCAS

Compare and swap

atomicAnd

AND

atomicOr

OR

atomicXor

XOR

At the hardware level, atomics come in two forms: atomic operations that return the value that was at the specified memory location before the operator was performed, and reduction operations that the developer can “fire and forget” at the memory location, ignoring the return value. Since the hardware can perform the operation more efficiently if there is no need to return the old value, the compiler detects whether the return value is used and, if it is not, emits different instructions. In SM 2.0, for example, the instructions are called ATOM and RED, respectively.

8.1.4. Constant Memory

Constant memory resides in device memory, but it is backed by a different, read-only cache that is optimized to broadcast the results of read requests to threads that all reference the same memory location. Each SM contains a small, latency-optimized cache for purposes of servicing these read requests. Making the memory (and the cache) read-only simplifies cache management, since the hardware has no need to implement write-back policies to deal with memory that has been updated.

SM 2.x and subsequent hardware includes a special optimization for memory that is not denoted as constant but that the compiler has identified as (1) read-only and (2) whose address is not dependent on the block or thread ID. The “load uniform” (LDU) instruction reads memory using the constant cache hierarchy and broadcasts the data to the threads.

8.1.5. Shared Memory

Shared memory is very fast, on-chip memory in the SM that threads can use for data interchange within a thread block. Since it is a per-SM resource, shared memory usage can affect occupancy, the number of warps that the SM can keep resident. SMs load and store shared memory with special instructions: G2R/R2G on SM 1.x, and LDS/STS on SM 2.x and later.

Shared memory is arranged as interleaved banks and generally is optimized for 32-bit access. If more than one thread in a warp references the same bank, a bank conflict occurs, and the hardware must handle memory requests consecutively until all requests have been serviced. Typically, to avoid bank conflicts, applications access shared memory with an interleaved pattern based on the thread ID, such as the following.

extern __shared__ float shared[];
float data = shared[BaseIndex + threadIdx.x];

Having all threads in a warp read from the same 32-bit shared memory location also is fast. The hardware includes a broadcast mechanism to optimize for this case. Writes to the same bank are serialized by the hardware, reducing performance. Writes to the same address cause race conditions and should be avoided.

For 2D access patterns (such as tiles of pixels in an image processing kernel), it’s good practice to pad the shared memory allocation so the kernel can reference adjacent rows without causing bank conflicts. SM 2.x and subsequent hardware has 32 banks,4 so for 2D tiles where threads in the same warp may access the data by row, it is a good strategy to pad the tile size to a multiple of 33 32-bit words.

On SM 1.x hardware, shared memory is about 16K in size;5 on later hardware, there is a total of 64K of L1 cache that may be configured as 16K or 48K of shared memory, of which the remainder is used as L1 cache.6

Over the last few generations of hardware, NVIDIA has improved the hardware’s handling of operand sizes other than 32 bits. On SM 1.x hardware, 8- and 16-bit reads from the same bank caused bank conflicts, while SM 2.x and later hardware can broadcast reads of any size out of the same bank. Similarly, 64-bit operands (such as double) in shared memory were so much slower than 32-bit operands on SM 1.x that developers sometimes had to resort to storing the data as separate high and low halves. SM 3.x hardware adds a new feature for kernels that predominantly use 64-bit operands in shared memory: a mode that increases the bank size to 64 bits.

Atomics in Shared Memory

SM 1.2 added the ability to perform atomic operations in shared memory. Unlike global memory, which implements atomics using single instructions (either GATOM or GRED, depending on whether the return value is used), shared memory atomics are implemented with explicit lock/unlock semantics, and the compiler emits code that causes each thread to loop over these lock operations until the thread has performed its atomic operation.

Listing 8.1 gives the source code to atomic32Shared.cu, a program specifically intended to be compiled to highlight the code generation for shared memory atomics. Listing 8.2 shows the resulting microcode generated for SM 2.0. Note how the LDSLK (load shared with lock) instruction returns a predicate that tells whether the lock was acquired, the code to perform the update is predicated, and the code loops until the lock is acquired and the update performed.

The lock is performed per 32-bit word, and the index of the lock is determined by bits 2–9 of the shared memory address. Take care to avoid contention, or the loop in Listing 8.2 may iterate up to 32 times.

Listing 8.1. atomic32Shared.cu.

__global__ void
Return32( int *sum, int *out, const int *pIn )
{
    extern __shared__ int s[];
    s[threadIdx.x] = pIn[threadIdx.x];
    __syncthreads();
    (void) atomicAdd( &s[threadIdx.x], *pIn );
    __syncthreads();
    out[threadIdx.x] = s[threadIdx.x];
}

Listing 8.2. atomic32Shared.cubin (microcode compiled for SM 2.0).

code for sm_20
    Function : _Z8Return32PiS_PKi
/*0000*/     MOV R1, c [0x1] [0x100];
/*0008*/     S2R R0, SR_Tid_X;
/*0010*/     SHL R3, R0, 0x2;
/*0018*/     MOV R0, c [0x0] [0x28];
/*0020*/     IADD R2, R3, c [0x0] [0x28];
/*0028*/     IMAD.U32.U32 RZ, R0, R1, RZ;
/*0030*/     LD R2, [R2];
/*0038*/     STS [R3], R2;
/*0040*/     SSY 0x80;
/*0048*/     BAR.RED.POPC RZ, RZ;
/*0050*/     LD R0, [R0];
/*0058*/     LDSLK P0, R2, [R3];
/*0060*/     @P0 IADD R2, R2, R0;
/*0068*/     @P0 STSUL [R3], R2;
/*0070*/     @!P0 BRA 0x58;
/*0078*/     NOP.S CC.T;
/*0080*/     BAR.RED.POPC RZ, RZ;
/*0088*/     LDS R0, [R3];
/*0090*/     IADD R2, R3, c [0x0] [0x24];
/*0098*/     ST [R2], R0;
/*00a0*/     EXIT;
    ...................................

8.1.6. Barriers and Coherency

The familiar __syncthreads() intrinsic waits until all the threads in the thread block have arrived before proceeding. It is needed to maintain coherency of shared memory within a thread block.7 Other, similar memory barrier instructions can be used to enforce some ordering on broader scopes of memory, as described in Table 8.3.

Table 8.3 Memory Barrier Intrinsics

INTRINSIC

DESCRIPTION

__syncthreads()

Waits until all shared memory accesses made by the calling thread are visible to all threads in the threadblock

threadfence_block()

Waits until all global and shared memory accesses made by the calling thread are visible to all threads in the threadblock

threadfence()

Waits until all global and shared memory accesses made by the calling thread are visible to

  • All threads in the threadblock for shared memory accesses
  • All threads in the device for global memory accesses

threadfence_system() (SM 2.x only)

Waits until all global and shared memory accesses made by the calling thread are visible to

  • All threads in the threadblock for shared memory accesses
  • All threads in the device for global memory accesses
  • Host threads for page-locked host memory accesses
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus