Home > Articles > Programming

GPU Programming and Streaming Multiprocessors

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.
This chapter is from the book

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020