NVIDIA CUDA ProgrammingGuide 2.3
NVIDIA CUDA ProgrammingGuide 2.3
Programming Guide
Version 2.3
7/1/2009
ii CUDA Programming Guide Version 2.3
Table of Contents
Figure 1-1. Floating-Point Operations per Second and Memory Bandwidth for the CPU
and GPU 2
Figure 1-2. The GPU Devotes More Transistors to Data Processing ............................ 3
Figure 1-3. CUDA is Designed to Support Various Languages or Application
Programming Interfaces ...................................................................................... 4
Figure 2-1. Grid of Thread Blocks ........................................................................... 10
Figure 2-2. Memory Hierarchy ............................................................................... 11
Figure 2-3. Heterogeneous Programming ............................................................... 13
Figure 3-1. Matrix Multipliation without Shared Memory .......................................... 22
Figure 3-2. Matrix Multipliation with Shared Memory ............................................... 26
Figure 3-3. Library Context Management ................................................................ 48
Figure 3-4. The Driver API is Forward Compatible ................................................... 68
Figure 4-1. Automatic Scalability ............................................................................ 72
Figure 4-2. Hardware Model .................................................................................. 75
Figure 5-1. Examples of Coalesced Global Memory Access Patterns .......................... 84
Figure 5-2. Examples of Global Memory Access Patterns That Are Non-Coalesced for
Devices of Compute Capability 1.0 or 1.1 ........................................................... 85
Figure 5-3. Examples of Global Memory Access Patterns That Are Non-Coalesced for
Devices of Compute Capability 1.0 or 1.1 ........................................................... 86
Figure 5-4. Examples of Global Memory Access by Devices with Compute Capability
1.2 and Higher .................................................................................................. 87
Figure 5-5. Examples of Shared Memory Access Patterns without Bank Conflicts ..... 93
Figure 5-6. Example of a Shared Memory Access Pattern without Bank Conflicts ...... 94
Figure 5-7. Examples of Shared Memory Access Patterns with Bank Conflicts ........... 95
Figure 5-8. Example of Shared Memory Read Access Patterns with Broadcast........... 96
GT200
G80 G92
Ultra
G80
G71
G70
NV40 3.2 GHz
NV35 3.0 GHz Harpertown
NV30 Core2 Duo
GT200 = GeForce GTX 280 G71 = GeForce 7900 GTX NV35 = GeForce FX 5950 Ultra
G92 = GeForce 9800 GTX G70 = GeForce 7800 GTX NV30 = GeForce FX 5800
G80
Ultra
G80
G71
NV40
Harpertown
Woodcrest
NV30
Prescott EE
Northwood
The reason behind the discrepancy in floating-point capability between the CPU and
the GPU is that the GPU is specialized for compute-intensive, highly parallel
computation – exactly what graphics rendering is about – and therefore designed
such that more transistors are devoted to data processing rather than data caching
and flow control, as schematically illustrated by Figure 1-2.
ALU ALU
Cache
DRAM DRAM
CPU GPU
More specifically, the GPU is especially well-suited to address problems that can be
expressed as data-parallel computations – the same program is executed on many
data elements in parallel – with high arithmetic intensity – the ratio of arithmetic
operations to memory operations. Because the same program is executed for each
data element, there is a lower requirement for sophisticated flow control; and
because it is executed on many data elements and has high arithmetic intensity, the
memory access latency can be hidden with calculations instead of big data caches.
Data-parallel processing maps data elements to parallel processing threads. Many
applications that process large data sets can use a data-parallel programming model
to speed up the computations. In 3D rendering, large sets of pixels and vertices are
mapped to parallel threads. Similarly, image and media processing applications such
as post-processing of rendered images, video encoding and decoding, image scaling,
stereo vision, and pattern recognition can map image blocks and pixels to parallel
processing threads. In fact, many algorithms outside the field of image rendering
and processing are accelerated by data-parallel processing, from general signal
processing or physics simulation to computational finance or computational biology.
from the high-performance enthusiast GeForce GTX 280 GPU and professional
Quadro and Tesla computing products to a variety of inexpensive, mainstream
GeForce GPUs (see Appendix A for a list of all CUDA-enabled GPUs).
This chapter introduces the main concepts that make up the CUDA programming
model by outlining how they are exposed in C. An extensive description of C for
CUDA is given in Section 3.2.
2.1 Kernels
C for CUDA extends C by allowing the programmer to define C functions, called
kernels, that, when called, are executed N times in parallel by N different CUDA
threads, as opposed to only once like regular C functions.
A kernel is defined using the __global__ declaration specifier and the number of
CUDA threads for each call is specified using a new <<<…>>> syntax:
// Kernel definition
__global__ void VecAdd(float* A, float* B, float* C)
{
}
int main()
{
// Kernel invocation
VecAdd<<<1, N>>>(A, B, C);
}
Each of the threads that execute a kernel is given a unique thread ID that is
accessible within the kernel through the built-in threadIdx variable. As an
illustration, the following sample code adds two vectors A and B of size N and
stores the result into vector C:
// Kernel definition
__global__ void VecAdd(float* A, float* B, float* C)
{
int i = threadIdx.x;
C[i] = A[i] + B[i];
}
int main()
{
// Kernel invocation
VecAdd<<<1, N>>>(A, B, C);
}
Each of the threads that execute VecAdd() performs one pair-wise addition.
int main()
{
// Kernel invocation
dim3 dimBlock(N, N);
MatAdd<<<1, dimBlock>>>(A, B, C);
}
The index of a thread and its thread ID relate to each other in a straightforward
way: For a one-dimensional block, they are the same; for a two-dimensional block
of size (Dx, Dy), the thread ID of a thread of index (x, y) is (x + y Dx); for a three-
dimensional block of size (Dx, Dy, Dz), the thread ID of a thread of index (x, y, z) is
(x + y Dx + z Dx Dy).
Threads within a block can cooperate among themselves by sharing data through
some shared memory and synchronizing their execution to coordinate memory
accesses. More precisely, one can specify synchronization points in the kernel by
calling the __syncthreads() intrinsic function; __syncthreads() acts as a
barrier at which all threads in the block must wait before any is allowed to proceed.
Section 3.2.2 gives an example of using shared memory.
For efficient cooperation, the shared memory is expected to be a low-latency
memory near each processor core, much like an L1 cache, __syncthreads() is
expected to be lightweight, and all threads of a block are expected to reside on the
same processor core. The number of threads per block is therefore restricted by the
limited memory resources of a processor core. On current GPUs, a thread block
may contain up to 512 threads.
However, a kernel can be executed by multiple equally-shaped thread blocks, so that
the total number of threads is equal to the number of threads per block times the
number of blocks. These multiple blocks are organized into a one-dimensional or
two-dimensional grid of thread blocks as illustrated by Figure 2-1. The dimension of
the grid is specified by the first parameter of the <<<…>>> syntax. Each block
within the grid can be identified by a one-dimensional or two-dimensional index
accessible within the kernel through the built-in blockIdx variable. The dimension
of the thread block is accessible within the kernel through the built-in blockDim
variable. The previous sample code becomes:
// Kernel definition
__global__ void MatAdd(float A[N][N], float B[N][N],
float C[N][N])
{
int i = blockIdx.x * blockDim.x + threadIdx.x;
int j = blockIdx.y * blockDim.y + threadIdx.y;
if (i < N && j < N)
C[i][j] = A[i][j] + B[i][j];
}
int main()
{
// Kernel invocation
dim3 dimBlock(16, 16);
dim3 dimGrid((N + dimBlock.x – 1) / dimBlock.x,
(N + dimBlock.y – 1) / dimBlock.y);
MatAdd<<<dimGrid, dimBlock>>>(A, B, C);
}
The thread block size of 16x16 = 256 threads was chosen somewhat arbitrarily, and
a grid is created with enough blocks to have one thread per matrix element as
before.
Thread blocks are required to execute independently: It must be possible to execute
them in any order, in parallel or in series. This independence requirement allows
thread blocks to be scheduled in any order across any number of cores, enabling
programmers to write code that scales with the number of cores.
The number of thread blocks in a grid is typically dictated by the size of the data
being processed rather than by the number of processors in the system, which it can
greatly exceed.
Grid
Block (1, 1)
Thread
Per-thread local
memory
Thread Block
Per-block shared
memory
Grid 0
Grid 1
Global memory
Block (0, 0) Block (1, 0)
CUDA’s programming model also assumes that both the host and the device
maintain their own DRAM, referred to as host memory and device memory, respectively.
Therefore, a program manages the global, constant, and texture memory spaces
visible to kernels through calls to the CUDA runtime (described in Chapter 3). This
includes device memory allocation and deallocation, as well as data transfer between
host and device memory.
C Program
Sequential
Execution
Device
Parallel kernel
Grid 1
Kernel1<<<>>>()
Serial code executes on the host while parallel code executes on the device.
Two interfaces are currently supported to write CUDA programs: C for CUDA and
the CUDA driver API. They are mutually exclusive: A program must use either one
or the other.
C for CUDA exposes the CUDA programming model as a minimal set of
extensions to the C language. Any source file that contains some of these extensions
must be compiled with nvcc as outlined in Section 3.1. These extensions allow
programmers to define a kernel as a C function and use some new syntax to specify
the grid and block dimension each time the function is called.
The CUDA driver API is a lower-level C API that provides functions to load
kernels as modules of CUDA binary or assembly code, to inspect their parameters,
and to launch them. Binary or assembly code are usually obtained by compiling
kernels written in C.
C for CUDA comes with a runtime API and both the runtime API and the driver
API provide functions to allocate and deallocate device memory, transfer data
between host memory and device memory, manage systems with multiple devices,
etc.
The runtime API is built on top of the CUDA driver API. Initialization, context,
and module management are all implicit and resulting code is more concise. C for
CUDA also supports device emulation, which facilitates debugging (see
Section 3.2.9).
In contrast, the CUDA driver API requires more code, is harder to program and
debug, but offers a better level of control and is language-independent since it
handles binary or assembly code.
Section 3.2 continues the description of C for CUDA started in Chapter 2. It also
introduces concepts that are common to both C for CUDA and the driver API:
linear memory, CUDA arrays, shared memory, texture memory, page-locked host
memory, device enumeration, asynchronous execution, interoperability with
graphics APIs. Section 3.3 assumes knowledge of these concepts and describes how
they are exposed by the driver API.
3.1.1 __noinline__
By default, a __device__ function is always inlined. The __noinline__
function qualifier however can be used as a hint for the compiler not to inline the
function if possible. The function body must still be in the same file where it is
called.
The compiler will not honor the __noinline__ qualifier for functions with
pointer parameters and for functions with large parameter lists.
// Host code
int main()
{
// Allocate vectors in device memory
size_t size = N * sizeof(float);
float* d_A;
cudaMalloc((void**)&d_A, size);
float* d_B;
cudaMalloc((void**)&d_B, size);
float* d_C;
cudaMalloc((void**)&d_C, size);
// Invoke kernel
int threadsPerBlock = 256;
int blocksPerGrid =
(N + threadsPerBlock – 1) / threadsPerBlock;
VecAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C);
// Device code
__global__ void myKernel(float* devPtr, int pitch)
{
for (int r = 0; r < height; ++r) {
float* row = (float*)((char*)devPtr + r * pitch);
for (int c = 0; c < width; ++c) {
float element = row[c];
}
}
}
The following code sample allocates a width×height×depth 3D array of
floating-point values and shows how to loop over the array elements in device code:
// Host code
cudaPitchedPtr devPitchedPtr;
cudaExtent extent = make_cudaExtent(64, 64, 64);
cudaMalloc3D(&devPitchedPtr, extent);
myKernel<<<100, 512>>>(devPitchedPtr, extent);
// Device code
__global__ void myKernel(cudaPitchedPtr devPitchedPtr,
cudaExtent extent)
{
char* devPtr = devPitchedPtr.ptr;
size_t pitch = devPitchedPtr.pitch;
size_t slicePitch = pitch * extent.height;
for (int z = 0; z < extent.depth; ++z) {
char* slice = devPtr + z * slicePitch;
for (int y = 0; y < extent.height; ++y) {
float* row = (float*)(slice + y * pitch);
for (int x = 0; x < extent.width; ++x) {
float element = row[x];
}
}
}
}
The reference manual lists all the various functions used to copy memory between
linear memory allocated with cudaMalloc(), linear memory allocated with
cudaMallocPitch() or cudaMalloc3D(), CUDA arrays, and memory
allocated for variables declared in global or constant memory space.
The following code sample copies the 2D array to the CUDA array allocated in the
previous code samples:
cudaMalloc((void**)&d_B.elements, size);
cudaMemcpy(d_B.elements, B.elements, size,
cudaMemcpyHostToDevice);
// Invoke kernel
dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
dim3 dimGrid(B.width / dimBlock.x, A.height / dimBlock.y);
MatMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C);
B.width-1
0 col
B.height
0
A C
A.height
row
A.width B.width
A.height-1
By blocking the computation this way, we take advantage of fast shared memory
and save a lot of global memory bandwidth since A is only read (B.width / block_size)
times from global memory and B is read (A.height / block_size) times.
The Matrix type from the previous code sample is augmented with a stride field, so
that sub-matrices can be efficiently represented with the same type. __device__
functions (see Section B.1.1) are used to get and set elements and build any sub-
matrix from a matrix.
// Matrices are stored in row-major order:
// M(row, col) = *(M.elements + row * M.stride + col)
typedef struct {
int width;
int height;
int stride;
float* elements;
} Matrix;
// Invoke kernel
dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
dim3 dimGrid(B.width / dimBlock.x, A.height / dimBlock.y);
MatMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C);
blockCol
BLOCK_SIZE
B
B.height
BLOCK_SIZE
BLOCK_SIZE-1
A C
0 col
BLOCK_SIZE
Csub
blockRow
A.height
row
BLOCK_SIZE-1
A.width B.width
float u = x / (float)width;
float v = y / (float)height;
// Transform coordinates
u -= 0.5f;
v -= 0.5f;
float tu = u * cosf(theta) – v * sinf(theta) + 0.5f;
float tv = v * cosf(theta) + u * sinf(theta) + 0.5f;
// Host code
int main()
{
// Allocate CUDA array in device memory
cudaChannelFormatDesc channelDesc =
cudaCreateChannelDesc(32, 0, 0, 0,
cudaChannelFormatKindFloat);
cudaArray* cuArray;
cudaMallocArray(&cuArray, &channelDesc, width, height);
// Invoke kernel
dim3 dimBlock(16, 16);
dim3 dimGrid((width + dimBlock.x – 1) / dimBlock.x,
(height + dimBlock.y – 1) / dimBlock.y);
transformKernel<<<dimGrid, dimBlock>>>(output, width, height,
angle);
3.2.6.1 Stream
Applications manage concurrency through streams. A stream is a sequence of
commands that execute in order. Different streams, on the other hand, may execute
their commands out of order with respect to one another or concurrently.
A stream is defined by creating a stream object and specifying it as the stream
parameter to a sequence of kernel launches and host ↔ device memory copies. The
following code sample creates two streams and allocates an array hostPtr of
float in page-locked memory.
cudaStream_t stream[2];
for (int i = 0; i < 2; ++i)
cudaStreamCreate(&stream[i]);
float* hostPtr;
cudaMallocHost((void**)&hostPtr, 2 * size);
Each of these streams is defined by the following code sample as a sequence of one
memory copy from host to device, one kernel launch, and one memory copy from
device to host:
for (int i = 0; i < 2; ++i)
cudaMemcpyAsync(inputDevPtr + i * size, hostPtr + i * size,
size, cudaMemcpyHostToDevice, stream[i]);
for (int i = 0; i < 2; ++i)
myKernel<<<100, 512, 0, stream[i]>>>
(outputDevPtr + i * size, inputDevPtr + i * size, size);
for (int i = 0; i < 2; ++i)
cudaMemcpyAsync(hostPtr + i * size, outputDevPtr + i * size,
size, cudaMemcpyDeviceToHost, stream[i]);
cudaThreadSynchronize();
Each stream copies its portion of input array hostPtr to array inputDevPtr in
device memory, processes inputDevPtr on the device by calling myKernel(), and
copies the result outputDevPtr back to the same portion of hostPtr. Processing
hostPtr using two streams allows for the memory copies of one stream to overlap
with the kernel execution of the other stream. hostPtr must point to page-locked
host memory for any overlap to occur. cudaThreadSynchronize() is called in the
end to make sure all streams are finished before proceeding further.
cudaStreamSynchronize() can be used to synchronize the host with a specific
stream, allowing other streams to continue executing on the device. Streams are
released by calling cudaStreamDestroy().
for (int i = 0; i < 2; ++i)
cudaStreamDestroy(&stream[i]);
Any kernel launch, memory set, or memory copy function without a stream
parameter or with a zero stream parameter begins only after all preceding
commands are done, including commands that are part of streams, and no
subsequent command may begin until it is done.
cudaStreamQuery() provides applications with a way to know if all preceding
commands in a stream have completed. cudaStreamSynchronize() provides a
way to explicitly force the runtime to wait until all preceding commands in a stream
have completed.
Similarly, with cudaThreadSynchronize() forces the runtime to wait until all
preceding device tasks in all streams have completed. To avoid unnecessary
slowdowns, these functions are best used for timing purposes or to isolate a launch
3.2.6.2 Event
The runtime also provides a way to closely monitor the device’s progress, as well as
perform accurate timing, by letting the application asynchronously record events at
any point in the program and query when these events are actually recorded. An
event is recorded when all tasks – or optionally, all commands in a given stream –
preceding the event have completed. Events in stream zero are recorded after all
preceding tasks/commands from all streams are completed by the device.
The following code sample creates two events:
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
These events can be used to time the code sample of the previous section the
following way:
cudaEventRecord(start, 0);
for (int i = 0; i < 2; ++i)
cudaMemcpyAsync(inputDev + i * size, inputHost + i * size,
size, cudaMemcpyHostToDevice, stream[i]);
for (int i = 0; i < 2; ++i)
myKernel<<<100, 512, 0, stream[i]>>>
(outputDev + i * size, inputDev + i * size, size);
for (int i = 0; i < 2; ++i)
cudaMemcpyAsync(outputHost + i * size, outputDev + i * size,
size, cudaMemcpyDeviceToHost, stream[i]);
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
float elapsedTime;
cudaEventElapsedTime(&elapsedTime, start, stop);
They are destroyed this way:
cudaEventDestroy(start);
cudaEventDestroy(stop);
void display()
{
// Map buffer object for writing from CUDA
float4* positions;
cudaGLMapBufferObject((void**)&positions, positionsVBO);
// Execute kernel
dim3 dimBlock(16, 16, 1);
dim3 dimGrid(width / dimBlock.x, height / dimBlock.y, 1);
createVertices<<<dimGrid, dimBlock>>>(positions, time,
width, height);
// Swap buffers
glutSwapBuffers();
glutPostRedisplay();
}
void deleteVBO()
{
cudaGLUnregisterBufferObject(positionsVBO);
glDeleteBuffers(1, &positionsVBO);
}
// Calculate uv coordinates
float u = x / (float)width;
float v = y / (float)height;
u = u * 2.0f - 1.0f;
v = v * 2.0f - 1.0f;
// Write positions
positions[y * width + x] = make_float4(u, w, v, 1.0f);
}
On Windows and for Quadro GPUs, cudaWGLGetDevice() can be used to
retrieve the CUDA device associated to the handle returned by
WGL_NV_gpu_affinity(). Quadro GPUs offer higher performance OpenGL
interoperability than GeForce and Tesla GPUs in a multi-GPU configuration where
OpenGL rendering is performed on the Quadro GPU and CUDA computations are
performed on other GPUs in the system.
ID3D10Buffer* buffer;
cudaD3D10RegisterResource(buffer, cudaD3D10RegisterFlagsNone);
ID3D10Texture2D* tex2D;
cudaD3D10RegisterResource(tex2D, cudaD3D10RegisterFlagsNone);
cudaD3D9RegisterResource() (resp. cudaD3D10RegisterResource()) is
potentially high-overhead and typically called only once per resource. Unregistering
is done with cudaD3D9UnregisterVertexBuffer() (resp.
cudaD3D10UnregisterVertexBuffer()).
Once a resource is registered to CUDA, it can be mapped and unmapped as many
times as necessary using cudaD3D9MapResources() (resp.
cudaD3D10MapResources()) and cudaD3D9UnmapResources() (resp.
cudaD3D10UnmapResources()).
A mapped resource can be read from or written to by kernels using the device
memory address returned by cudaD3D9ResourceGetMappedPointer() (resp.
cudaD3D10ResourceGetMappedPointer()) and the size and pitch
information returned by cudaD3D9ResourceGetMappedSize() (resp.
cudaD3D10ResourceGetMappedSize()),
cudaD3D9ResourceGetMappedPitch() (resp.
cudaD3D10ResourceGetMappedPitch()), and
cudaD3D9ResourceGetMappedPitchSlice() (resp.
cudaD3D10ResourceGetMappedPitchSlice()).
When applicable, a CUDA array can also be obtained from a mapped resource using
cudaD3D9ResourceGetMappedArray() (resp.
cudaD3D10ResourceGetMappedArray()).
int main()
{
// Initialize Direct3D
D3D = Direct3DCreate9(D3D_SDK_VERSION);
// Create device
...
D3D->CreateDevice(adapter, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
¶ms, &device);
void Render()
{
// Map vertex buffer for writing from CUDA
float4* positions;
cudaD3D9MapResources(1, (IDirect3DResource9**)&positionsVB);
cudaD3D9ResourceGetMappedPointer((void**)&positions,
positionsVB, 0, 0);
// Execute kernel
dim3 dimBlock(16, 16, 1);
dim3 dimGrid(width / dimBlock.x, height / dimBlock.y, 1);
createVertices<<<dimGrid, dimBlock>>>(positions, time,
width, height);
void releaseVB()
{
cudaD3D9UnregisterResource(positionsVB);
positionsVB->Release();
}
// Calculate uv coordinates
float u = x / (float)width;
float v = y / (float)height;
u = u * 2.0f - 1.0f;
v = v * 2.0f - 1.0f;
// Write positions
positions[y * width + x] =
make_float4(u, w, v, __int_as_float(0xff00ff00));
}
ID3D10Device* device;
struct CUSTOMVERTEX {
FLOAT x, y, z;
DWORD color;
};
ID3D10Buffer* positionsVB;
int main()
{
// Get a CUDA-enabled adapter
IDXGIFactory* factory;
CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
IDXGIAdapter* adapter = 0;
for (unsigned int i = 0; !adapter; ++i) {
if (FAILED(factory->EnumAdapters(i, &adapter))
break;
int dev;
cudaD3D10GetDevice(&dev, adapter);
if (cudaSuccess == cudaGetLastError())
break;
adapter->Release();
}
factory->Release();
void Render()
{
// Map vertex buffer for writing from CUDA
float4* positions;
cudaD3D10MapResources(1, (ID3D10Resource**)&positionsVB);
cudaD3D10ResourceGetMappedPointer((void**)&positions,
positionsVB, 0);
// Execute kernel
dim3 dimBlock(16, 16, 1);
dim3 dimGrid(width / dimBlock.x, height / dimBlock.y, 1);
createVertices<<<dimGrid, dimBlock>>>(positions, time,
width, height);
void releaseVB()
{
cudaD3D10UnregisterResource(positionsVB);
positionsVB->Release();
}
// Calculate uv coordinates
float u = x / (float)width;
float v = y / (float)height;
u = u * 2.0f - 1.0f;
v = v * 2.0f - 1.0f;
// Write positions
positions[y * width + x] =
make_float4(u, w, v, __int_as_float(0xff00ff00));
}
In the following code sample, each thread accesses one pixel of a 2D surface of size
(width, height) and pixel format float4:
// host code
void* devPtr;
cudaD3D9ResourceGetMappedPointer(&devPtr, surface, 0, 0);
size_t pitch;
cudaD3D9ResourceGetMappedPitch(&pitch, 0, surface, 0, 0);
dim3 Db = dim3(16, 16);
dim3 Dg = dim3((width+Db.x–1)/Db.x, (height+Db.y–1)/Db.y);
myKernel<<<Dg, Db>>>((unsigned char*)devPtr,
width, height, pitch);
// device code
__global__ void myKernel(unsigned char* surface,
// host code
void* devPtr;
cudaD3D10ResourceGetMappedPointer(&devPtr, surface, 0);
size_t pitch;
cudaD3D10ResourceGetMappedPitch(&pitch, 0, surface, 0);
dim3 Db = dim3(16, 16);
dim3 Dg = dim3((width+Db.x–1)/Db.x, (height+Db.y–1)/Db.y);
myKernel<<<Dg, Db>>>((unsigned char*)devPtr,
width, height, pitch);
// device code
__global__ void myKernel(unsigned char* surface,
int width, int height, size_t pitch)
{
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
if (x >= width || y >= height) return;
float* pixel = (float*)(surface + y * pitch) + 4 * x;
}
device emulation mode. This is expected since in general, all you need to get
different results for the same floating-point computation are slightly different
compiler options, let alone different compilers, different instruction sets, or
different architectures.
In particular, some host platforms store intermediate results of single-precision
floating-point calculations in extended precision registers, potentially resulting in
significant differences in accuracy when running in device emulation mode.
When this occurs, programmers can try any of the following methods, none of
which is guaranteed to work:
¾ Declare some floating-point variables as volatile to force single-precision
storage;
¾ Use the –ffloat-store compiler option of gcc,
¾ Use the /Op or /fp compiler options of the Visual C++ compiler,
¾ Use _FPU_GETCW() and _FPU_SETCW() on Linux or _controlfp()
on Windows to force single-precision floating-point computation for a
portion of the code by surrounding it with
unsigned int originalCW;
_FPU_GETCW(originalCW);
unsigned int cw = (originalCW & ~0x300) | 0x000;
_FPU_SETCW(cw);
or
unsigned int originalCW = _controlfp(0, 0);
_controlfp(_PC_24, _MCW_PC);
at the beginning, to store the current value of the control word and change
it to force the mantissa to be stored in 24 bits using, and with
_FPU_SETCW(originalCW);
or
_controlfp(originalCW, 0xfffff);
at the end, to restore the original control word.
Also, for single-precision floating-point numbers, unlike compute devices (see
Appendix A), host platforms usually support denormalized numbers. This can
lead to dramatically different results between device emulation and device
execution modes since some computation might produce a finite result in one
case and an infinite result in the other.
The warp size is equal to 1 in device emulation mode (see Section 4.1 for the
definition of a warp). Therefore, the warp vote functions (described in
Section B.11) produce different results than in device execution mode.
The objects available in the driver API are summarized in Table 3-1.
The driver API is implemented in the nvcuda dynamic library and all its entry
points are prefixed with cu.
The driver API must be initialized with cuInit() before any function from the
driver API is called. A CUDA context must then be created that is attached to a
specific device and made current to the calling host thread as detailed in
Section 3.3.1.
Within a CUDA context, kernels are explicitly loaded as PTX or binary objects by
the host code as described in Section 3.3.2. Kernels written in C must therefore be
compiled separately into PTX or binary objects. Kernels are launched using API
entry points as described in Section 3.3.3.
Any application that wants to run on future device architectures must load PTX, not
binary code. This is because binary code is architecture-specific and therefore
incompatible with future architectures, whereas PTX code is compiled to binary
code at load time by the driver.
Here is the host code of the sample from Section 2.1 written using the driver API:
int main()
{
// Initialize
if (cuInit(0) != CUDA_SUCCESS)
exit (0);
// Create context
CUcontext cuContext;
cuCtxCreate(&cuContext, 0, cuDevice);
// Invoke kernel
#define ALIGN_UP(offset, alignment) \
(offset) = ((offset) + (alignment) – 1) & ~((alignment) – 1)
int offset = 0;
void* ptr;
ptr = (void*)(size_t)A;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(vecAdd, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ptr = (void*)(size_t)B;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(vecAdd, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ptr = (void*)(size_t)C;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(vecAdd, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
cuParamSetSize(vecAdd, offset);
int threadsPerBlock = 256;
int blocksPerGrid =
(N + threadsPerBlock – 1) / threadsPerBlock;
cuFuncSetBlockShape(vecAdd, threadsPerBlock, 1, 1);
cuLaunchGrid(vecAdd, blocksPerGrid, 1);
}
3.3.1 Context
A CUDA context is analogous to a CPU process. All resources and actions
performed within the driver API are encapsulated inside a CUDA context, and the
system automatically cleans up these resources when the context is destroyed.
Besides objects such as modules and texture references, each context has its own
distinct 32-bit address space. As a result, CUdeviceptr values from different
contexts reference different memory locations.
A host thread may have only one device context current at a time. When a context is
created with cuCtxCreate(), it is made current to the calling host thread. CUDA
functions that operate in a context (most functions that do not involve device
enumeration or context management) will return
CUDA_ERROR_INVALID_CONTEXT if a valid context is not current to the thread.
Each host thread has a stack of current contexts. cuCtxCreate() pushes the new
context onto the top of the stack. cuCtxPopCurrent() may be called to detach
the context from the host thread. The context is then "floating" and may be pushed
as the current context for any host thread. cuCtxPopCurrent() also restores the
previous current context, if any.
Initialize
cuCtxCreate() context cuCtxPopCurrent()
Library Call
Use
cuCtxPushCurrent() context cuCtxPopCurrent()
3.3.2 Module
Modules are dynamically loadable packages of device code and data, akin to DLLs in
Windows, that are output by nvcc (see Section 3.1). The names for all symbols,
including functions, global variables, and texture references, are maintained at
module scope so that modules written by independent third parties may interoperate
in the same CUDA context.
This code sample loads a module and retrieves a handle to some kernel:
CUmodule cuModule;
cuModuleLoad(&cuModule, “myModule.ptx”);
CUfunction myKernel;
cuModuleGetFunction(&myKernel, cuModule, “myKernel”);
This code sample compiles and loads a new module from PTX code and parses
compilation errors:
#define ERROR_BUFFER_SIZE 100
CUmodule cuModule;
CUptxas_option options[3];
void* values[3];
int i;
ALIGN_UP(offset, __alignof(i));
cuParamSeti(cuFunction, offset, i);
offset += sizeof(i);
float4 f4;
ALIGN_UP(offset, 16); // float4’s alignment is 16
cuParamSetv(cuFunction, offset, &f4, sizeof(f4));
offset += sizeof(f4);
char c;
ALIGN_UP(offset, __alignof(c));
cuParamSeti(cuFunction, offset, c);
offset += sizeof(c);
float f;
ALIGN_UP(offset, __alignof(f));
cuParamSeti(cuFunction, offset, f);
offset += sizeof(f);
CUdeviceptr dptr;
// void* should be used to determine CUdeviceptr’s alignment
void* ptr = (void*)(size_t)dptr;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(cuFunction, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
float2 f2;
ALIGN_UP(offset, 8); // float2’s alignment is 8
cuParamSetv(cuFunction, offset, &f2, sizeof(f2));
offset += sizeof(f2);
cuParamSetSize(cuFunction, offset);
// Initialize
if (cuInit(0) != CUDA_SUCCESS)
exit (0);
// Create context
CUcontext cuContext;
cuCtxCreate(&cuContext, 0, cuDevice);
// Invoke kernel
#define ALIGN_UP(offset, alignment) \
(offset) = ((offset) + (alignment) – 1) & ~((alignment) – 1)
int offset = 0;
void* ptr;
ptr = (void*)(size_t)d_A;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(vecAdd, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ptr = (void*)(size_t)d_B;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(vecAdd, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ptr = (void*)(size_t)d_C;
ALIGN_UP(offset, __alignof(ptr));
// Device code
__global__ void myKernel(float* devPtr)
{
for (int r = 0; r < height; ++r) {
float* row = (float*)((char*)devPtr + r * pitch);
for (int c = 0; c < width; ++c) {
float element = row[c];
}
}
}
The following code sample allocates a width×height CUDA array of one 32-bit
floating-point component:
CUDA_ARRAY_DESCRIPTOR desc;
desc.Format = CU_AD_FORMAT_FLOAT;
desc.NumChannels = 1;
desc.Width = width;
desc.Height = height;
CUarray cuArray;
cuArrayCreate(&cuArray, &desc);
The reference manual lists all the various functions used to copy memory between
linear memory allocated with cuMemAlloc(), linear memory allocated with
cuMemAllocPitch(), and CUDA arrays.
The following code sample copies the 2D array to the CUDA array allocated in the
previous code samples:
CUDA_MEMCPY2D copyParam;
memset(©Param, 0, sizeof(copyParam));
copyParam.dstMemoryType = CU_MEMORYTYPE_ARRAY;
copyParam.dstArray = cuArray;
copyParam.srcMemoryType = CU_MEMORYTYPE_DEVICE;
copyParam.srcDevice = devPtr;
copyParam.srcPitch = pitch;
copyParam.WidthInBytes = width * sizeof(float);
copyParam.Height = height;
cuMemcpy2D(©Param);
The following code sample copies some host memory array to constant memory:
__constant__ float constData[256];
float data[256];
CUdeviceptr devPtr;
unsigned int bytes;
cuModuleGetGlobal(&devPtr, &bytes, cuModule, “constData”);
cuMemcpyHtoD(devPtr, data, bytes);
int deviceCount;
cuDeviceGetCount(&deviceCount);
int device;
for (int device = 0; device < deviceCount; ++device) {
CUdevice cuDevice;
cuDeviceGet(&cuDevice, device);
int major, minor;
cuDeviceComputeCapability(&major, &minor, cuDevice);
}
copyParam.srcMemoryType = CU_MEMORYTYPE_HOST;
copyParam.srcHost = h_data;
copyParam.srcPitch = width * sizeof(float);
copyParam.WidthInBytes = copyParam.srcPitch;
copyParam.Height = height;
cuMemcpy2D(©Param);
3.3.9.1 Stream
The driver API provides functions similar to the runtime API to manage streams.
The following code sample is the driver version of the code sample from
Section 3.2.6.1.
CUstream stream[2];
for (int i = 0; i < 2; ++i)
cuStreamCreate(&stream[i], 0);
float* hostPtr;
cuMemAllocHost((void**)&hostPtr, 2 * size);
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(cuFunction, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ALIGN_UP(offset, __alignof(size));
cuParamSeti(cuFunction, offset, size);
offset += sizeof(int);
cuParamSetSize(cuFunction, offset);
cuFuncSetBlockShape(cuFunction, 512, 1, 1);
cuLaunchGridAsync(cuFunction, 100, 1, stream[i]);
}
for (int i = 0; i < 2; ++i)
cuMemcpyDtoHAsync(hostPtr + i * size, outputDevPtr + i * size,
size, stream[i]);
cuCtxSynchronize();
cuEventRecord(start, 0);
for (int i = 0; i < 2; ++i)
cuMemcpyHtoDAsync(inputDevPtr + i * size, hostPtr + i * size,
size, stream[i]);
for (int i = 0; i < 2; ++i) {
#define ALIGN_UP(offset, alignment) \
(offset) = ((offset) + (alignment) – 1) & ~((alignment) – 1)
int offset = 0;
void* ptr;
ptr = (void*)(size_t)outputDevPtr;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(cuFunction, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ptr = (void*)(size_t)inputDevPtr;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(cuFunction, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ALIGN_UP(offset, __alignof(size));
cuParamSeti(cuFunction, offset, size);
offset += sizeof(size);
cuParamSetSize(cuFunction, offset);
cuFuncSetBlockShape(cuFunction, 512, 1, 1);
cuLaunchGridAsync(cuFunction, 100, 1, stream[i]);
}
for (int i = 0; i < 2; ++i)
cuMemcpyDtoHAsync(hostPtr + i * size, outputDevPtr + i * size,
size, stream[i]);
cuEventRecord(stop, 0);
cuEventSynchronize(stop);
float elapsedTime;
cuEventElapsedTime(&elapsedTime, start, stop);
They are destroyed this way:
cuEventDestroy(start);
cuEventDestroy(stop);
// Create context
CUcontext cuContext;
cuGLCtxCreate(&cuContext, 0, cuDevice);
cuModuleGetFunction(&createVertices,
cuModule, "createVertices");
void display()
{
// Map OpenGL buffer object for writing from CUDA
CUdeviceptr positions;
unsigned int size;
cuGLMapBufferObject(&positions, &size, positionsVBO);
// Execute kernel
#define ALIGN_UP(offset, alignment) \
(offset) = ((offset) + (alignment) – 1) & ~((alignment) – 1)
int offset = 0;
void* ptr = (void*)(size_t)positions;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(createVertices, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ALIGN_UP(offset, __alignof(time));
cuParamSetf(createVertices, offset, time);
offset += sizeof(time);
ALIGN_UP(offset, __alignof(width));
cuParamSeti(createVertices, offset, width);
offset += sizeof(width);
ALIGN_UP(offset, __alignof(height));
cuParamSeti(createVertices, offset, height);
offset += sizeof(height);
cuParamSetSize(createVertices, offset);
int threadsPerBlock = 16;
cuFuncSetBlockShape(createVertices,
threadsPerBlock, threadsPerBlock, 1);
cuLaunchGrid(createVertices,
width / threadsPerBlock, height / threadsPerBlock);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_POINTS, 0, width * height);
glDisableClientState(GL_VERTEX_ARRAY);
// Swap buffers
glutSwapBuffers();
glutPostRedisplay();
}
void deleteVBO()
{
cuGLUnregisterBufferObject(positionsVBO);
glDeleteBuffers(1, &positionsVBO);
}
On Windows and for Quadro GPUs, cuWGLGetDevice() can be used to retrieve
the CUDA device associated to the handle returned by
WGL_NV_gpu_affinity().
ID3D10Buffer* buffer;
cuD3D10RegisterResource(buffer, CU_D3D10_REGISTER_FLAGS_NONE);
ID3D10Texture2D* tex2D;
cuD3D10RegisterResource(tex2D, CU_D3D10_REGISTER_FLAGS_NONE);
cuD3D9RegisterResource() (resp. cuD3D10RegisterResource()) is
potentially high-overhead and typically called only once per resource. Unregistering
is done with cuD3D9UnregisterVertexBuffer() (resp.
cuD3D10UnregisterVertexBuffer()).
Once a resource is registered to CUDA, it can be mapped and unmapped as many
times as necessary using cuD3D9MapResources() (resp.
cuD3D10MapResources()) and cuD3D9UnmapResources() (resp.
cuD3D10UnmapResources()).
A mapped resource can be read from or written to by kernels using the device
memory address returned by cuD3D9ResourceGetMappedPointer() (resp.
cuD3D10ResourceGetMappedPointer()) and the size and pitch information
returned by cuD3D9ResourceGetMappedSize() (resp.
cuD3D10ResourceGetMappedSize()),
cuD3D9ResourceGetMappedPitch() (resp.
cuD3D10ResourceGetMappedPitch()), and
cuD3D9ResourceGetMappedPitchSlice() (resp.
cuD3D10ResourceGetMappedPitchSlice()).
When applicable, a CUDA array can also be obtained from a mapped resource using
cuD3D9ResourceGetMappedArray() (resp.
cuD3D10ResourceGetMappedArray()).
Accessing a resource through Direct3D while it is mapped produces undefined
results.
The following code sample is the driver version of the host code of the sample from
Section 3.2.8.
IDirect3D9* D3D;
IDirect3DDevice9* device;
struct CUSTOMVERTEX {
FLOAT x, y, z;
DWORD color;
};
IDirect3DVertexBuffer9* positionsVB;
int main()
{
// Initialize Direct3D
D3D = Direct3DCreate9(D3D_SDK_VERSION);
// Create device
...
D3D->CreateDevice(adapter, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
¶ms, &device);
// Create context
CUdevice cuDevice;
CUcontext cuContext;
cuD3D9CtxCreate(&cuContext, &cuDevice, 0, &device);
void Render()
{
// Map vertex buffer for writing from CUDA
float4* positions;
cuD3D9MapResources(1, (IDirect3DResource9**)&positionsVB);
cuD3D9ResourceGetMappedPointer((void**)&positions,
positionsVB, 0, 0);
// Execute kernel
#define ALIGN_UP(offset, alignment) \
(offset) = ((offset) + (alignment) – 1) & ~((alignment) – 1)
int offset = 0;
void* ptr = (void*)(size_t)positions;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(createVertices, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ALIGN_UP(offset, __alignof(time));
cuParamSetf(createVertices, offset, time);
offset += sizeof(time);
ALIGN_UP(offset, __alignof(width));
cuParamSeti(createVertices, offset, width);
offset += sizeof(width);
ALIGN_UP(offset, __alignof(height));
cuParamSeti(createVertices, offset, height);
offset += sizeof(height);
cuParamSetSize(createVertices, offset);
int threadsPerBlock = 16;
cuFuncSetBlockShape(createVertices,
threadsPerBlock, threadsPerBlock, 1);
cuLaunchGrid(createVertices,
width / threadsPerBlock, height / threadsPerBlock);
...
}
void releaseVB()
{
cuD3D9UnregisterResource(positionsVB);
positionsVB->Release();
}
ID3D10Device* device;
struct CUSTOMVERTEX {
FLOAT x, y, z;
DWORD color;
};
ID3D10Buffer* positionsVB;
int main()
{
// Get a CUDA-enabled adapter
IDXGIFactory* factory;
CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
IDXGIAdapter* adapter = 0;
for (unsigned int i = 0; !adapter; ++i) {
if (FAILED(factory->EnumAdapters(i, &adapter))
break;
int dev;
cuD3D10GetDevice(&dev, adapter);
if (cudaSuccess == cudaGetLastError())
break;
adapter->Release();
}
factory->Release();
// Create context
CUdevice cuDevice;
CUcontext cuContext;
cuD3D10CtxCreate(&cuContext, &cuDevice, 0, &device);
cuModuleGetFunction(&createVertices,
cuModule, "createVertices");
void Render()
{
// Map vertex buffer for writing from CUDA
float4* positions;
cuD3D10MapResources(1, (ID3D10Resource**)&positionsVB);
cuD3D10ResourceGetMappedPointer((void**)&positions,
positionsVB, 0);
// Execute kernel
#define ALIGN_UP(offset, alignment) \
(offset) = ((offset) + (alignment) – 1) & ~((alignment) – 1)
int offset = 0;
void* ptr = (void*)(size_t)positions;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(createVertices, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ALIGN_UP(offset, __alignof(time));
cuParamSetf(createVertices, offset, time);
offset += sizeof(time);
ALIGN_UP(offset, __alignof(width));
cuParamSeti(createVertices, offset, width);
offset += sizeof(width);
ALIGN_UP(offset, __alignof(height));
cuParamSeti(createVertices, offset, height);
offset += sizeof(height);
cuParamSetSize(createVertices, offset);
int threadsPerBlock = 16;
cuFuncSetBlockShape(createVertices,
threadsPerBlock, threadsPerBlock, 1);
cuLaunchGrid(createVertices,
width / threadsPerBlock, height / threadsPerBlock);
void releaseVB()
{
cuD3D10UnregisterResource(positionsVB);
positionsVB->Release();
}
In the following code sample, each thread accesses one pixel of a 2D surface of size
(width, height) and pixel format float4:
// host code
CUdeviceptr devPtr;
cuD3D9ResourceGetMappedPointer(&devPtr, surface, 0, 0);
size_t pitch;
cuD3D9ResourceGetMappedPitch(&pitch, 0, surface, 0, 0);
cuModuleGetFunction(&cuFunction, cuModule, “myKernel”);
#define ALIGN_UP(offset, alignment) \
(offset) = ((offset) + (alignment) – 1) & ~((alignment) – 1)
int offset = 0;
void* ptr = (void*)(size_t)devPtr;
ALIGN_UP(offset, __alignof(ptr));
cuParamSetv(cuFunction, offset, &ptr, sizeof(ptr));
offset += sizeof(ptr);
ALIGN_UP(offset, __alignof(width));
cuParamSeti(cuFunction, offset, width);
offset += sizeof(width);
ALIGN_UP(offset, __alignof(height));
cuParamSeti(cuFunction, offset, height);
offset += sizeof(height);
ALIGN_UP(offset, __alignof(pitch));
cuParamSeti(cuFunction, offset, pitch);
offset += sizeof(pitch);
cuParamSetSize(cuFunction, offset);
cuFuncSetBlockShape(cuFunction, 16, 16, 1);
cuLaunchGrid(cuFunction,
(width+Db.x–1)/Db.x, (height+Db.y–1)/Db.y);
// device code
__global__ void myKernel(unsigned char* surface,
int width, int height, size_t pitch)
{
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
if (x >= width || y >= height) return;
float* pixel = (float*)(surface + y * pitch) + 4 * x;
}
// host code
CUdeviceptr devPtr;
cuD3D10ResourceGetMappedPointer(&devPtr, surface, 0);
size_t pitch;
cuD3D10ResourceGetMappedPitch(&pitch, 0, surface, 0);
// device code
__global__ void myKernel(unsigned char* surface,
int width, int height, size_t pitch)
{
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
if (x >= width || y >= height) return;
float* pixel = (float*)(surface + y * pitch) + 4 * x;
}
of the CUDA driver API that describes the features supported by the driver API
and runtime.
The version of the driver API is defined in the driver header file as
CUDA_VERSION. It allows developers to check whether their application requires a
newer driver than the one currently installed. This is important, because the driver
API is backward compatible, meaning that applications, plug-ins, and libraries
(including the C runtime) compiled against a particular version of the driver API will
continue to work on subsequent driver releases as illustrated in Figure 3-4. The
driver API is not forward compatible, which means that applications, plug-ins, and
libraries (including the C runtime) compiled against a particular version of the driver
API will not work on previous versions of the driver.
Default compute mode: Multiple host threads can use the device (by calling
cudaSetDevice() on this device, when using the runtime API, or by making
current a context associated to the device, when using the driver API) at the
same time.
Exclusive compute mode: Only one host thread can use the device at any given
time.
Prohibited compute mode: No host thread can use the device.
This means, in particular, that a host thread using the runtime API without explicitly
calling cudaSetDevice() might be associated with a device other than device 0 if
device 0 turns out to be in prohibited compute mode or in exclusive compute mode
and used by another host thread. cudaSetValidDevices() can be used to set a
device from a prioritized list of devices.
Applications may query the compute mode of a device by calling
cudaGetDeviceProperties() and checking the computeMode property or
checking the CU_DEVICE_COMPUTE_MODE attribute using
cuDeviceGetAttribute().
Kernel Grid
SM 0 SM 1 SM 0 SM 1 SM 2 SM 3
Block 4 Block 5
Block 6 Block 7
A device with more multiprocessors will automatically execute a kernel grid in less time than a device
with fewer multiprocessors.
A multiprocessor consists of eight Scalar Processor (SP) cores, two special function
units for transcendentals, a multithreaded instruction unit, and on-chip shared
memory. The multiprocessor creates, manages, and executes concurrent threads in
hardware with zero scheduling overhead. It implements the __syncthreads()
barrier synchronization intrinsic with a single instruction. Fast barrier
synchronization together with lightweight thread creation and zero-overhead thread
scheduling efficiently support very fine-grained parallelism, allowing, for example, a
low granularity decomposition of problems by assigning one thread to each data
element (such as a pixel in an image, a voxel in a volume, a cell in a grid-based
computation).
To manage hundreds of threads running several different programs, the
multiprocessor employs a new architecture we call SIMT (single-instruction,
multiple-thread). The multiprocessor maps each thread to one scalar processor core,
and each scalar thread executes independently with its own instruction address and
register state. The multiprocessor SIMT unit creates, manages, schedules, and
executes threads in groups of 32 parallel threads called warps. (This term originates
from weaving, the first parallel thread technology. A half-warp is either the first or
second half of a warp.) Individual threads composing a SIMT warp start together at
the same program address but are otherwise free to branch and execute
independently.
When a multiprocessor is given one or more thread blocks to execute, it splits them
into warps that get scheduled by the SIMT unit. The way a block is split into warps
is always the same; each warp contains threads of consecutive, increasing thread IDs
with the first warp containing thread 0. Section 2.2 describes how thread IDs relate
to thread indices in the block.
Every instruction issue time, the SIMT unit selects a warp that is ready to execute
and issues the next instruction to the active threads of the warp. A warp executes
one common instruction at a time, so full efficiency is realized when all 32 threads
of a warp agree on their execution path. If threads of a warp diverge via a data-
dependent conditional branch, the warp serially executes each branch path taken,
disabling threads that are not on that path, and when all paths complete, the threads
converge back to the same execution path. Branch divergence occurs only within a
warp; different warps execute independently regardless of whether they are
executing common or disjointed code paths.
SIMT architecture is akin to SIMD (Single Instruction, Multiple Data) vector
organizations in that a single instruction controls multiple processing elements. A
key difference is that SIMD vector organizations expose the SIMD width to the
software, whereas SIMT instructions specify the execution and branching behavior
of a single thread. In contrast with SIMD vector machines, SIMT enables
programmers to write thread-level parallel code for independent, scalar threads, as
well as data-parallel code for coordinated threads. For the purposes of correctness,
the programmer can essentially ignore the SIMT behavior; however, substantial
performance improvements can be realized by taking care that the code seldom
requires threads in a warp to diverge. In practice, this is analogous to the role of
cache lines in traditional code: Cache line size can be safely ignored when designing
for correctness but must be considered in the code structure when designing for
peak performance. Vector architectures, on the other hand, require the software to
coalesce loads into vectors and manage divergence manually.
As illustrated by Figure 4-2, each multiprocessor has on-chip memory of the four
following types:
One set of local 32-bit registers per processor,
A parallel data cache or shared memory that is shared by all scalar processor cores
and is where the shared memory space resides,
A read-only constant cache that is shared by all scalar processor cores and speeds
up reads from the constant memory space, which is a read-only region of device
memory,
A read-only texture cache that is shared by all scalar processor cores and speeds up
reads from the texture memory space, which is a read-only region of device
memory; each multiprocessor accesses the texture cache via a texture unit that
implements the various addressing modes and data filtering mentioned in
Section 3.2.4.
The local and global memory spaces are read-write regions of device memory and
are not cached.
The number of blocks a multiprocessor can process at once – referred to as the
number of active blocks per multiprocessor – depends on how many registers per
thread and how much shared memory per block are required for a given kernel since
the multiprocessor’s registers and shared memory are split among all the threads of
the active blocks. If there are not enough registers or shared memory available per
multiprocessor to process at least one block, the kernel will fail to launch. The
maximum number of active blocks per multiprocessor, as well as the maximum
number of active warps and maximum number of active threads are given in
Appendix A.
If a non-atomic instruction executed by a warp writes to the same location in global
or shared memory for more than one of the threads of the warp, the number of
serialized writes that occur to that location and the order in which they occur is
undefined, but one of the writes is guaranteed to succeed. If an atomic instruction
(see Section B.10) executed by a warp reads, modifies, and writes to the same
location in global memory for more than one of the threads of the warp, each read,
modify, write to that location occurs and they are all serialized, but the order in
which they occur is undefined.
Device
Multiprocessor N
Multiprocessor 2
Multiprocessor 1
Shared Memory
Constant
Cache
Texture
Cache
Device Memory
Second, when a Direct3D application runs in SLI Alternate Frame Rendering mode,
the Direct3D device(s) created by that application can be used for CUDA-Direct3D
interoperability (i.e. passed as a parameter to
cudaD3D[9|10]SetDirect3DDevice() when using the runtime API), but only
one CUDA device can be created at a time from one of these Direct3D devices.
This CUDA device only executes the CUDA work on one of the GPUs in the SLI
configuration. As a consequence, real interoperability only happens with the copy of
a Direct3D resource in that GPU (Note: in AFR mode Direct3D resources that
must be in GPU memory are duplicated in the GPU memory of each GPU in the
SLI configuration). In some cases this is not the desired behavior and an application
may need to forfeit CUDA-Direct3D interoperability and manually copy the output
of its CUDA work to Direct3D resources using the existing CUDA and Direct3D
API.
Due to the lengthy computations and use of local memory in the slow path, the
trigonometric functions throughput is lower by one order of magnitude when the
slow path reduction is used as opposed to the fast path reduction.
Integer Arithmetic
Throughput of integer add is 8 operations per clock cycle.
Throughput of 32-bit integer multiplication is 2 operations per clock cycle, but
__mul24 and __umul24 (see Section C.2) provide signed and unsigned 24-bit
integer multiplication with a troughput of 8 operations per clock cycle. On future
architectures however, __[u]mul24 will be slower than 32-bit integer
multiplication, so we recommend to provide two kernels, one using __[u]mul24
and the other using generic 32-bit integer multiplication, to be called appropriately
by the application.
Integer division and modulo operation are particularly costly and should be avoided
if possible or replaced with bitwise operations whenever possible: If n is a power of
2, (i/n) is equivalent to (i>>log2(n)) and (i%n) is equivalent to (i&(n-1));
the compiler will perform these conversions if n is literal.
Comparison
Throughput of compare, min, max is 8 operations per clock cycle.
Bitwise Operations
Throughput of any bitwise operation is 8 operations per clock cycle.
Type Conversion
Throughput of type conversion operations is 8 operations per clock cycle.
Sometimes, the compiler must insert conversion instructions, introducing additional
execution cycles. This is the case for:
Functions operating on char or short whose operands generally need to be
converted to int,
Double-precision floating-point constants (defined without any type suffix) used
as input to single-precision floating-point computations.
This last case can be avoided by using single-precision floating-point constants,
defined with an f suffix such as 3.141592653589793f, 1.0f, 0.5f.
warpSize is the warp size. In this case, no warp diverges since the controlling
condition is perfectly aligned with the warps.
Sometimes, the compiler may unroll loops or it may optimize out if or switch
statements by using branch predication instead, as detailed below. In these cases, no
warp can ever diverge. The programmer can also control loop unrolling using the
#pragma unroll directive (see Section 3.1.2).
When using branch predication none of the instructions whose execution depends
on the controlling condition gets skipped. Instead, each of them is associated with a
per-thread condition code or predicate that is set to true or false based on the
controlling condition and although each of these instructions gets scheduled for
execution, only the instructions with a true predicate are actually executed.
Instructions with a false predicate do not write results, and also do not evaluate
addresses or read operands.
The compiler replaces a branch instruction with predicated instructions only if the
number of instructions controlled by the branch condition is less or equal to a
certain threshold: If the compiler determines that the condition is likely to produce
many divergent warps, this threshold is 7, otherwise it is 4.
pattern is to stage data coming from device memory into shared memory; in other
words, to have each thread of a block:
Load data from device memory to shared memory,
Synchronize with all the other threads of the block so that each thread can safely
read shared memory locations that were written by different threads,
Process the data in shared memory,
Synchronize again if necessary to make sure that shared memory has been
updated with the results,
Write the results back to device memory.
Figure 5-4 shows some examples of global memory accesses for devices of compute
capability 1.2 and higher.
32B segment
Address Address Address
Thread Thread
1 132 1 132 108
Address Address Address
Thread Thread
2 136 2 136 112
Address Address Address
Thread Thread
3 140 3 140 116
Address Address Address
Thread Thread
4 144 4 144 120
Address Address Address
Thread Thread
5 148 5 148 124
Address Address Address
Thread Thread Thread
6 152 6 152 0 128
64B segment
128B segment
Thread Thread Thread
9 164 9 164 3 140
Address Address Address
Thread Thread Thread
10 168 10 168 4 144
Address Address Address
Thread Thread Thread
11 172 11 172 5 148
Address Address Address
Thread Thread Thread
12 176 12 176 6 152
64B segment
Thread Address Address Address
Thread Thread
13 180 13 180 7 156
Left: random float memory access within a 64B segment, resulting in one memory transaction.
Center: misaligned float memory access, resulting in one transaction.
Right: misaligned float memory access, resulting in two transactions.
However, if two addresses of a memory request fall in the same memory bank, there
is a bank conflict and the access has to be serialized. The hardware splits a memory
request with bank conflicts into as many separate conflict-free requests as necessary,
decreasing the effective bandwidth by a factor equal to the number of separate
memory requests. If the number of separate memory requests is n, the initial
memory request is said to cause n-way bank conflicts.
To get maximum performance, it is therefore important to understand how memory
addresses map to memory banks in order to schedule the memory requests so as to
minimize bank conflicts.
In the case of the shared memory space, the banks are organized such that
successive 32-bit words are assigned to successive banks and each bank has a
bandwidth of 32 bits per two clock cycles.
For devices of compute capability 1.x, the warp size is 32 and the number of banks
is 16 (see Section 5.1); a shared memory request for a warp is split into one request
for the first half of the warp and one request for the second half of the warp. As a
consequence, there can be no bank conflict between a thread belonging to the first
half of a warp and a thread belonging to the second half of the same warp.
A common case is for each thread to access a 32-bit word from an array indexed by
the thread ID tid and with some stride s:
__shared__ float shared[32];
float data = shared[BaseIndex + s * tid];
In this case, the threads tid and tid+n access the same bank whenever s*n is a
multiple of the number of banks m or equivalently, whenever n is a multiple of m/d
where d is the greatest common divisor of m and s. As a consequence, there will be
no bank conflict only if half the warp size is less than or equal to m/d. For devices
of compute capability 1.x, this translates to no bank conflict only if d is equal to 1,
or in other words, only if s is odd since m is a power of two.
Figure 5-5 and Figure 5-6 show some examples of conflict-free memory accesses
while Figure 5-7 shows some examples of memory accesses that cause bank
conflicts.
Other cases worth mentioning are when each thread accesses an element that is
smaller or larger than 32 bits in size. For example, there are bank conflicts if an array
of char is accessed the following way:
__shared__ char shared[32];
char data = shared[BaseIndex + tid];
because shared[0], shared[1], shared[2], and shared[3], for example,
belong to the same bank. There are no bank conflicts however, if the same array is
accessed the following way:
char data = shared[BaseIndex + 4 * tid];
There are also 2-way bank conflicts for arrays of double:
__shared__ double shared[32];
double data = shared[BaseIndex + tid];
since the memory request is compiled into two separate 32-bit requests. One way to
avoid bank conflicts in this case is two split the double operands like in the
following sample code:
__shared__ int shared_lo[32];
double dataIn;
shared_lo[BaseIndex + tid] = __double2loint(dataIn);
shared_hi[BaseIndex + tid] = __double2hiint(dataIn);
double dataOut =
__hiloint2double(shared_hi[BaseIndex + tid],
shared_lo[BaseIndex + tid]);
It might not always improve performance though and will perform worse on future
architectures.
A structure assignment is compiled into as many memory requests as necessary for
each member in the structure, so the following code, for example:
__shared__ struct type shared[32];
struct type data = shared[BaseIndex + tid];
results in:
Three separate memory reads without bank conflicts if type is defined as
struct type {
float x, y, z;
};
since each member is accessed with a stride of three 32-bit words;
Two separate memory reads with bank conflicts if type is defined as
struct type {
float x, y;
};
since each member is accessed with a stride of two 32-bit words;
Two separate memory reads with bank conflicts if type is defined as
struct type {
float f;
char c;
};
since each member is accessed with a stride of five bytes.
Finally, shared memory also features a broadcast mechanism whereby a 32-bit word
can be read and broadcast to several threads simultaneously when servicing one
memory read request. This reduces the number of bank conflicts when several
threads of a half-warp read from an address within the same 32-bit word. More
precisely, a memory read request made of several addresses is serviced in several
steps over time – one step every two clock cycles – by servicing one conflict-free
subset of these addresses per step until all addresses have been serviced; at each
step, the subset is built from the remaining addresses that have yet to be serviced
using the following procedure:
Select one of the words pointed to by the remaining addresses as the broadcast
word,
Include in the subset:
All addresses that are within the broadcast word,
One address for each bank pointed to by the remaining addresses.
Which word is selected as the broadcast word and which address is picked up for
each bank at each cycle are unspecified.
A common conflict-free case is when all threads of a half-warp read from an address
within the same 32-bit word.
Figure 5-8 shows some examples of memory read accesses that involve the
broadcast mechanism.
Thread 0 Bank 0
Thread 1 Bank 1
Thread 2 Bank 2
Thread 3 Bank 3
Thread 4 Bank 4
Thread 5 Bank 5
Thread 6 Bank 6
Thread 7 Bank 7
Thread 8 Bank 8
Thread 9 Bank 9
Thread 10 Bank 10
Thread 11 Bank 11
Thread 12 Bank 12
Thread 13 Bank 13
Thread 14 Bank 14
Thread 15 Bank 15
Left: Linear addressing with a stride of two 32-bit words causes 2-way bank conflicts.
Right: Linear addressing with a stride of eight 32-bit words causes 8-way bank conflicts.
Left: This access pattern is conflict-free since all threads read from an address within the same 32-bit
word.
Right: This access pattern causes either no bank conflicts if the word from bank 5 is chosen as the
broadcast word during the first step or 2-way bank conflicts, otherwise.
5.1.2.6 Registers
Generally, accessing a register is zero extra clock cycles per instruction, but delays
may occur due to register read-after-write dependencies and register memory bank
conflicts.
The delays introduced by read-after-write dependencies can be ignored as soon as
there are at least 192 active threads per multiprocessor to hide them.
The compiler and thread scheduler schedule the instructions as optimally as possible
to avoid register memory bank conflicts. They achieve best results when the number
of threads per block is a multiple of 64. Other than following this rule, an
application has no direct control over these bank conflicts. In particular, there is no
need to pack data into float4 or int4 types.
to allow for more than one active block (see Section 4.1). More thread blocks stream
in pipeline fashion through the device and amortize overhead even more. The
number of blocks per grid should be at least 100 if one wants it to scale to future
devices; 1000 blocks will scale across several generations.
With a high enough number of blocks, the number of threads per block should be
chosen as a multiple of the warp size to avoid wasting computing resources with
under-populated warps, or better, a multiple of 64 for the reason invoked in
Section 5.1.2.6. Allocating more threads per block is better for efficient time slicing,
but the more threads per block, the fewer registers are available per thread, which
might prevent the kernel invocation from succeeding.
Usually, 64 threads per block is minimal and makes sense only if there are multiple
active blocks per multiprocessor; 192 or 256 threads per block is better and usually
allows for enough registers to compile.
The ratio of the number of active warps per multiprocessor to the maximum
number of active warps (given in Appendix A) is called the multiprocessor occupancy.
In order to maximize occupancy, the compiler attempts to minimize register usage
while keeping the number of instructions and local memory usage to a minimum.
This can be controlled using the - maxrregcount compiler option. The CUDA
Software Development Kit provides a spreadsheet to assist programmers in
choosing thread block size based on shared memory and register requirements.
Number of Compute
Multiprocessors Capability
(1 Multiprocessor
= 8 Processors)
GeForce GTX 295 2x30 1.3
GeForce GTX 285, GTX 280 30 1.3
GeForce GTX 260 24 1.3
GeForce 9800 GX2 2x16 1.1
GeForce GTS 250, GTS 150, 9800 GTX, 16 1.1
9800 GTX+, 8800 GTS 512
GeForce 8800 Ultra, 8800 GTX 16 1.0
GeForce 9800 GT, 8800 GT, GTX 280M, 14 1.1
9800M GTX
GeForce GT 130, 9600 GSO, 8800 GS, 12 1.1
8800M GTX, GTX 260M, 9800M GT
GeForce 8800 GTS 12 1.0
GeForce 9600 GT, 8800M GTS, 9800M GTS 8 1.1
GeForce 9700M GT 6 1.1
GeForce GT 120, 9500 GT, 8600 GTS, 8600 GT, 4 1.1
9700M GT, 9650M GS, 9600M GT, 9600M GS,
9500M GS, 8700M GT, 8600M GT, 8600M GS
GeForce G100, 8500 GT, 8400 GS, 8400M GT, 2 1.1
The number of multiprocessors, the clock frequency and the total amount of device
memory can be queried using the runtime (see reference manual).
The cache working set for texture memory varies between 6 and 8 KB per
multiprocessor;
The maximum number of active blocks per multiprocessor is 8;
The maximum number of active warps per multiprocessor is 24;
The maximum number of active threads per multiprocessor is 768;
For a one-dimensional texture reference bound to a CUDA array, the maximum
width is 213;
For a one-dimensional texture reference bound to linear memory, the maximum
width is 227;
For a two-dimensional texture reference bound to linear memory or a CUDA
array, the maximum width is 216 and the maximum height is 215;
For a three-dimensional texture reference bound to a CUDA array, the
maximum width is 211, the maximum height is 211, and the maximum depth is
211;
The limit on kernel size is 2 million PTX instructions;
Absolute value and negation are not compliant with IEEE-754 with respect to
NaNs; these are passed through unchanged;
For single-precision floating-point numbers only:
Denormalized numbers are not supported; floating-point arithmetic and
comparison instructions convert denormalized operands to zero prior to the
floating-point operation;
Underflowed results are flushed to zero;
The result of an operation involving one or more input NaNs is the quiet
NaN of bit pattern 0x7fffffff; note that;
Some instructions are not IEEE-compliant:
Addition and multiplication are often combined into a single multiply-add
instruction (FMAD), which truncates the intermediate result of the
multiplication;
Division is implemented via the reciprocal in a non-standard-compliant
way;
Square root is implemented via the reciprocal square root in a non-
standard-compliant way;
For addition and multiplication, only round-to-nearest-even and
round-towards-zero are supported via static rounding modes; directed
rounding towards +/- infinity is not supported;
But, IEEE-compliant software (and therefore slower) implementations are
provided through the following intrinsics from Section C.2.1:
__fmaf_r{n,z,u,d}(float, float, float): single-precision
fused multiply-add with IEEE rounding modes,
__frcp_r[n,z,u,d](float): single-precision reciprocal with IEEE
rounding modes,
__fdiv_r[n,z,u,d](float, float): single-precision division with
IEEE rounding modes,
__fsqrt_r[n,z,u,d](float): single-precision square root with
IEEE rounding modes,
__fadd_r[u,d](float, float): single-precision addition with
IEEE directed rounding,
__fmul_r[u,d](float, float): single-precision multiplication with
IEEE directed rounding;
For double-precision floating-point numbers only:
Round-to-nearest-even is the only supported IEEE rounding mode for
reciprocal, division, and square root.
In accordance to the IEEE-754R standard, if one of the input parameters to
fminf(), fmin(), fmaxf(), or fmax() is NaN, but not the other, the result is
the non-NaN parameter.
The conversion of a floating-point value to an integer value in the case where the
floating-point value falls outside the range of the integer format is left undefined by
IEEE-754. For compute devices, the behavior is to clamp to the end of the
supported range. This is unlike the x86 architecture behaves.
B.1.1 __device__
The __device__ qualifier declares a function that is:
Executed on the device
Callable from the device only.
B.1.2 __global__
The __global__ qualifier declares a function as being a kernel. Such a function is:
Executed on the device,
Callable from the host only.
B.1.3 __host__
The __host__ qualifier declares a function that is:
Executed on the host,
Callable from the host only.
It is equivalent to declare a function with only the __host__ qualifier or to declare
it without any of the __host__, __device__, or __global__ qualifier; in either
case the function is compiled for the host only.
However, the __host__ qualifier can also be used in combination with the
__device__ qualifier, in which case the function is compiled for both the host and
the device.
B.1.4 Restrictions
__device__ and __global__ functions do not support recursion.
__device__ and __global__ functions cannot declare static variables inside
their body.
__device__ and __global__ functions cannot have a variable number of
arguments.
__device__ functions cannot have their address taken; function pointers to
__global__ functions, on the other hand, are supported.
The __global__ and __host__ qualifiers cannot be used together.
__global__ functions must have void return type.
Any call to a __global__ function must specify its execution configuration as
described in Section B.12.
A call to a __global__ function is asynchronous, meaning it returns before the
device has completed its execution.
__global__ function parameters are currently passed via shared memory to the
device and limited to 256 bytes.
B.2.1 __device__
The __device__ qualifier declares a variable that resides on the device.
At most one of the other type qualifiers defined in the next three sections may be
used together with __device__ to further specify which memory space the
variable belongs to. If none of them is present, the variable:
Resides in global memory space,
Has the lifetime of an application,
Is accessible from all the threads within the grid and from the host through the
runtime library.
B.2.2 __constant__
The __constant__ qualifier, optionally used together with __device__,
declares a variable that:
Resides in constant memory space,
Has the lifetime of an application,
Is accessible from all the threads within the grid and from the host through the
runtime library.
B.2.3 __shared__
The __shared__ qualifier, optionally used together with __device__, declares a
variable that:
Resides in the shared memory space of a thread block,
Has the lifetime of the block,
Is only accessible from all the threads within the block.
When declaring a variable in shared memory as an external array such as
extern __shared__ float shared[];
the size of the array is determined at launch time (see Section B.12). All variables
declared in this fashion, start at the same address in memory, so that the layout of
the variables in the array must be explicitly managed through offsets. For example, if
one wants the equivalent of
short array0[128];
float array1[64];
int array2[256];
in dynamically allocated shared memory, one could declare and initialize the arrays
the following way:
extern __shared__ char array[];
__device__ void func() // __device__ or __global__ function
{
short* array0 = (short*)array;
float* array1 = (float*)&array0[128];
int* array2 = (int*)&array1[64];
}
B.2.4 Volatile
Only after the execution of a __threadfence_block(), __threadfence(),
or __syncthreads() (Sections B.5 and B.6) are prior writes to global or shared
memory guaranteed to be visible by other threads. As long as this requirement is
met, the compiler is free to optimize reads and writes to global or shared memory.
For example, in the code sample below, the first reference to myArray[tid]
compiles into a global or shared memory read instruction, but the second reference
does not as the compiler simply reuses the result of the first read.
// myArray is an array of non-zero integers
// located in global or shared memory
__global__ void myKernel(int* result) {
int tid = threadIdx.x;
int ref1 = myArray[tid] * 1;
myArray[tid + 1] = 2;
int ref2 = myArray[tid] * 1;
result[tid] = ref1 * ref2;
}
Therefore, ref2 cannot possibly be equal to 2 in thread tid as a result of thread
tid-1 overwriting myArray[tid] by 2.
This behavior can be changed using the volatile keyword: If a variable located in
global or shared memory is declared as volatile, the compiler assumes that its value
can be changed at any time by another thread and therefore any reference to this
variable compiles to an actual memory read instruction.
Note that even if myArray is declared as volatile in the code sample above, there is
no guarantee, in general, that ref2 will be equal to 2 in thread tid since thread
tid might read myArray[tid] into ref2 before thread tid-1 overwrites its
value by 2. Synchronization is required as mentioned in Section 5.4.
B.2.5 Restrictions
These qualifiers are not allowed on struct and union members, on formal
parameters and on local variables within a function that executes on the host.
__shared__ and __constant__ variables have implied static storage.
__device__, __shared__ and __constant__ variables cannot be defined as
external using the extern keyword. The only exception is for dynamically allocated
__shared__ variables as described in Section B.2.3.
__device__ and __constant__ variables are only allowed at file scope.
__constant__ variables cannot be assigned to from the device, only from the
host through host runtime functions (Sections 3.2.1 and 3.3.4).
__shared__ variables cannot have an initialization as part of their declaration.
An automatic variable declared in device code without any of these qualifiers
generally resides in a register. However in some cases the compiler might choose to
place it in local memory, which can have adverse performance consequences as
detailed in Section 5.1.2.2.
Pointers in code that is executed on the device are supported as long as the compiler
is able to resolve whether they point to either the shared memory space or the
global memory space, otherwise they are restricted to only point to memory
allocated or declared in the global memory space.
Dereferencing a pointer either to global or shared memory in code that is executed
on the host or to host memory in code that is executed on the device results in an
undefined behavior, most often in a segmentation fault and application termination.
The address obtained by taking the address of a __device__, __shared__ or
__constant__ variable can only be used in device code. The address of a
__device__ or __constant__ variable obtained through
cudaGetSymbolAddress() as described in Section 3.3.4 can only be used in
host code.
B.3.2 dim3
This type is an integer vector type based on uint3 that is used to specify
dimensions. When defining a variable of type dim3, any component left unspecified
is initialized to 1.
B.4.1 gridDim
This variable is of type dim3 (see Section B.3.2) and contains the dimensions of the
grid.
B.4.2 blockIdx
This variable is of type uint3 (see Section B.3.1) and contains the block index
within the grid.
B.4.3 blockDim
This variable is of type dim3 (see Section B.3.2) and contains the dimensions of the
block.
B.4.4 threadIdx
This variable is of type uint3 (see Section B.3.1) and contains the thread index
within the block.
B.4.5 warpSize
This variable is of type int and contains the warp size in threads (see Section 4.1
for the definition of a warp).
B.4.6 Restrictions
It is not allowed to take the address of any of the built-in variables.
It is not allowed to assign values to any of the built-in variables.
waits until all global and shared memory accesses made by the calling thread prior to
__threadfence() are visible to all threads in the device for global memory
accesses and all threads in the thread block for shared memory accesses.
void __threadfence_block();
waits until all global and shared memory accesses made by the calling thread prior to
__threadfence_block() are visible to all threads in the thread block.
In general, when a thread issues a series of writes to memory in a particular order,
other threads may see the effects of these memory writes in a different order.
__threadfence() and __threadfence_block() can be used to enforce
some ordering.
One use case is when threads consume some data produced by other threads as
illustrated by the following code sample of a kernel that computes the sum of an
array of N numbers in one call. Each block first sums a subset of the array and
stores the result in global memory. When all blocks are done, the last block done
reads each of these partial sums from global memory and sums them to obtain the
final result. In order to determine which block is finished last, each block atomically
increments a counter to signal that it is done with computing and storing its partial
sum (see Section B.10 about atomic functions). The last block is the one that
receives the counter value equal to gridDim.x-1. If no fence is placed between
storing the partial sum and incrementing the counter, the counter might increment
before the partial sum is stored and therefore, might reach gridDim.x-1 and let
the last block start reading partial sums before they have been actually updated in
memory.
__device__ unsigned int count = 0;
__shared__ bool isLastBlockDone;
__global__ void sum(const float* array, unsigned int N,
float* result)
{
// Each block sums a subset of the input array
float partialSum = calculatePartialSum(array, N);
if (threadIdx.x == 0) {
if (isLastBlockDone) {
if (threadIdx.x == 0) {
changed properties such as reduced accuracy and different special case handling can
be tolerated.
B.8.1 tex1Dfetch()
template<class Type>
Type tex1Dfetch(
texture<Type, 1, cudaReadModeElementType> texRef,
int x);
float tex1Dfetch(
texture<unsigned char, 1, cudaReadModeNormalizedFloat> texRef,
int x);
float tex1Dfetch(
texture<signed char, 1, cudaReadModeNormalizedFloat> texRef,
int x);
float tex1Dfetch(
texture<unsigned short, 1, cudaReadModeNormalizedFloat> texRef,
int x);
float tex1Dfetch(
texture<signed short, 1, cudaReadModeNormalizedFloat> texRef,
int x);
fetch the region of linear memory bound to texture reference texRef using integer
texture coordinate x. No texture filtering and addressing modes are supported. For
integer types, these functions may optionally promote the integer to single-precision
floating point.
Besides the functions shown above, 2-, and 4-tuples are supported; for example:
float4 tex1Dfetch(
texture<uchar4, 1, cudaReadModeNormalizedFloat> texRef,
int x);
fetches the region of linear memory bound to texture reference texRef using
texture coordinate x.
B.8.2 tex1D()
template<class Type, enum cudaTextureReadMode readMode>
Type tex1D(texture<Type, 1, readMode> texRef,
float x);
fetches the CUDA array bound to texture reference texRef using floating-point
texture coordinates x.
B.8.3 tex2D()
template<class Type, enum cudaTextureReadMode readMode>
Type tex2D(texture<Type, 2, readMode> texRef,
float x, float y);
fetches the CUDA array or the region of linear memory bound to texture reference
texRef using texture coordinates x and y.
B.8.4 tex3D()
template<class Type, enum cudaTextureReadMode readMode>
Type tex3D(texture<Type, 3, readMode> texRef,
float x, float y, float z);
fetches the CUDA array bound to texture reference texRef using texture
coordinates x, y, and z.
B.10.1.2 atomicSub()
int atomicSub(int* address, int val);
unsigned int atomicSub(unsigned int* address,
unsigned int val);
reads the 32-bit word old located at the address address in global or shared
memory, computes (old - val), and stores the result back to memory at the
same address. These three operations are performed in one atomic transaction. The
function returns old.
B.10.1.3 atomicExch()
int atomicExch(int* address, int val);
unsigned int atomicExch(unsigned int* address,
unsigned int val);
unsigned long long int atomicExch(unsigned long long int* address,
unsigned long long int val);
float atomicExch(float* address, float val);
reads the 32-bit or 64-bit word old located at the address address in global or
shared memory and stores val back to memory at the same address. These two
operations are performed in one atomic transaction. The function returns old.
64-bit words are only supported for global memory.
B.10.1.4 atomicMin()
int atomicMin(int* address, int val);
unsigned int atomicMin(unsigned int* address,
unsigned int val);
reads the 32-bit word old located at the address address in global or shared
memory, computes the minimum of old and val, and stores the result back to
memory at the same address. These three operations are performed in one atomic
transaction. The function returns old.
B.10.1.5 atomicMax()
int atomicMax(int* address, int val);
unsigned int atomicMax(unsigned int* address,
unsigned int val);
reads the 32-bit word old located at the address address in global or shared
memory, computes the maximum of old and val, and stores the result back to
memory at the same address. These three operations are performed in one atomic
transaction. The function returns old.
B.10.1.6 atomicInc()
unsigned int atomicInc(unsigned int* address,
unsigned int val);
reads the 32-bit word old located at the address address in global or shared
memory, computes ((old >= val) ? 0 : (old+1)), and stores the result
back to memory at the same address. These three operations are performed in one
atomic transaction. The function returns old.
B.10.1.7 atomicDec()
unsigned int atomicDec(unsigned int* address,
unsigned int val);
reads the 32-bit word old located at the address address in global or shared
memory, computes (((old == 0) | (old > val)) ? val : (old-1)),
and stores the result back to memory at the same address. These three operations
are performed in one atomic transaction. The function returns old.
B.10.1.8 atomicCAS()
int atomicCAS(int* address, int compare, int val);
unsigned int atomicCAS(unsigned int* address,
unsigned int compare,
unsigned int val);
unsigned long long int atomicCAS(unsigned long long int* address,
unsigned long long int compare,
unsigned long long int val);
reads the 32-bit or 64-bit word old located at the address address in global or
shared memory, computes (old == compare ? val : old), and stores the
result back to memory at the same address. These three operations are performed in
one atomic transaction. The function returns old (Compare And Swap).
B.10.2.2 atomicOr()
int atomicOr(int* address, int val);
unsigned int atomicOr(unsigned int* address,
unsigned int val);
reads the 32-bit word old located at the address address in global or shared
memory, computes (old | val), and stores the result back to memory at the
same address. These three operations are performed in one atomic transaction. The
function returns old.
B.10.2.3 atomicXor()
int atomicXor(int* address, int val);
unsigned int atomicXor(unsigned int* address,
unsigned int val);
reads the 32-bit word old located at the address address in global or shared
memory, computes (old ^ val), and stores the result back to memory at the
same address. These three operations are performed in one atomic transaction. The
function returns old.
Functions from Section C.1 can be used in both host and device code whereas
functions from Section C.2 can only be used in device code.
Note that floating-point functions are overloaded, so that in general, there are three
prototypes for a given function <func-name>:
(1) double <func-name>(double), e.g. double log(double)
(2) float <func-name>(float), e.g. float log(float)
(3) float <func-name>f(float), e.g. float logf(float)
This means, in particular, that passing a float argument always results in a float
result (variants (2) and (3) above).
__fmul_[rn,rz,ru,rd](x,y) IEEE-compliant.
__fmaf_[rn,rz,ru,rd](x,y,z) IEEE-compliant.
__frcp_[rn,rz,ru,rd](x) IEEE-compliant.
__fsqrt_[rn,rz,ru,rd](x) IEEE-compliant.
__fdiv_[rn,rz,ru,rd](x,y) IEEE-compliant.
__fdividef(x,y) For y in [2-126, 2126], the maximum ulp error is
2.
__expf(x) The maximum ulp error is
2 + floor(abs(1.16 * x)).
__exp10f(x) The maximum ulp error is
2 + floor(abs(2.95 * x)).
__logf(x) For x in [0.5, 2], the maximum absolute error
is 2-21.41, otherwise, the maximum ulp error is
3.
__log2f(x) For x in [0.5, 2], the maximum absolute error
is 2-22, otherwise, the maximum ulp error is 2.
__log10f(x) For x in [0.5, 2], the maximum absolute error
is 2-24, otherwise, the maximum ulp error is 3.
__sinf(x) For x in [-π, π], the maximum absolute error
is 2-21.41, and larger otherwise.
__cosf(x) For x in [-π, π], the maximum absolute error
is 2-21.19, and larger otherwise.
__sincosf(x,sptr,cptr) Same as sinf(x) and cosf(x).
__tanf(x) Derived from its implementation as
__sinf(x) * (1 / __cosf(x)).
__powf(x, y) Derived from its implementation as
exp2f(y * __log2f(x)).
__int_as_float(x) N/A
__float_as_int(x) N/A
__saturate(x) N/A
__float2int_[rn,rz,ru,rd](x) N/A
__float2uint_[rn,rz,ru,rd](x) N/A
__int2float_[rn,rz,ru,rd](x) N/A
__uint2float_[rn,rz,ru,rd](x) N/A
__float2ll_[rn,rz,ru,rd](x) N/A
__float2ull_[rn,rz,ru,rd](x) N/A
__popcll(x) returns the number of bits that are set to 1 in the binary
representation of 64-bit integer parameter x.
__brev(x) reverses the bits of 32-bit unsigned integer parameter x, i.e. bit N of
the result corresponds to bit 31-N of x.
__brevll(x) reverses the bits of 64-bit unsigned long long parameter x, i.e. bit N
of the result corresponds to bit 63-N of x.
CUDA supports the following C++ language constructs for device code:
Polymorphism
Default Parameters
Operator Overloading
Namespaces
Function Templates
These C++ constructs are implemented as specified in “The C++ Programming
Langue” reference. It is valid to use any of these constructs in .cu CUDA files for
host, device, and kernel (__global__) functions. Any restrictions detailed in previous
parts of this programming guide, like the lack of support for recursion, still apply.
The following subsections provide examples of the various constructs.
D.1 Polymorphism
Generally, polymorphism is the ability to define that functions or operators behave
differently in different contexts. This is also referred to as function (and operator,
see below) overloading.
In practical terms, this means that it is permissible to define two different functions
within the same scope (namespace) as long as they have a distinguishable function
signature. That means that the two functions either consume a different number of
parameters or parameters of different types. When either of the multiple functions
gets invoked the compiler resolves to the function’s implementation that matches
the function signature.
Because of implicit typecasting, a compiler may encounter multiple potential
matches for a function invocation and in that case the matching rules as described in
the C++ Language Standard apply. In practice this means that the compiler will pick
the closest match in case of multiple potential matches.
Example: The following is valid CUDA code:
__device__ void f(float x)
{
// do something with x
}
With support for polymorphism as described in the previous subsection and the
function signature matching rules in place it becomes possible to provide support
for default values for function parameters.
Example:
__device__ void f(float x = 0.0f)
{
// do something with x
}
Kernel or other device functions can now invoke this version of f in one of two
ways:
f();
// or
Default parameters can only be given for the last n parameters of a function.
D.4 Namespaces
Namespaces in C++ allow for the creation of a hierarchy of scopes of visibility. All
the symbols inside a namespace can be used within this namespaces without
additional syntax.
The use of namespaces can be used to solve the problem of name-clashes (two
different symbols using identical names), which commonly occurs when using
multiple function libraries from different sources.
Example: The following code defines two functions “f()” in two separate
namespaces (“nvidia” and “other”):
namespace nvidia {
__device__ void f(float x)
{ /* do something with x */ ;}
}
namespace other {
__device__ void f(float x)
{ /* do something with x */ ;}
}
The functions can now be used anywhere via fully qualified names:
nvidia::f(0.5f);
All the symbols in a namespace can be imported into another namespace (scope)
like this:
using namespace nvidia;
f(0.5f);
Example:
template <T>
__device__ bool f(T x)
{ return /* some clever code that turns x into a bool here */ }
This function will convert x of any data-type to a bool as long as the code in the
function’s body can be compiled for the actually type (T) of the variable x.
f() can be invoked in two ways:
int x = 1;
bool result = f(x);
This first type of invocation relies on the compiler’s ability to implicitly deduce the
correct function type for T. In this case the compiler would deduce T to be int and
instantiate f<int>(x).
The second type of invoking the template function is via explicit instantiation like
this:
bool result = f<double>(0.5);
template <>
__device__ bool
f<int>(T x)
{ return true; }
In this case the implementation for T representing the int type are specialized to
return true, all other types will be caught by the more general template and return
false.
The complete set of matching rules (for implicitly deducing template parameters)
and matching polymorphous functions apply as specified in the C++ standard.
This appendix gives the formula used to compute the value returned by the texture
functions of Section B.8 depending on the various attributes of the texture reference
(see Section 3.2.4).
The texture bound to the texture reference is represented as an array T of N texels
for a one-dimensional texture, N × M texels for a two-dimensional texture, or
N × M × L texels for a three-dimensional texture. It is fetched using texture
coordinates x , y , and z .
A texture coordinate must fall within T ’s valid addressing range before it can be
used to address T . The addressing mode specifies how an out-of-range texture
coordinate x is remapped to the valid range. If x is non-normalized, only the
clamp addressing mode is supported and x is replaced by 0 if x < 0 and N − 1 if
N ≤ x . If x is normalized:
In clamp addressing mode, x is replaced by 0 if x < 0 and 1 − 1 N if 1 ≤ x ,
In wrap addressing mode, x is replaced by frac (x) , where
frac ( x ) = x − floor ( x ) and floor (x ) is the largest integer not greater than x .
In the remaining of the appendix, x , y , and z are the non-normalized texture
coordinates remapped to T ’s valid addressing range. x , y , and z are derived
from the normalized texture coordinates x̂ , ŷ , and ẑ as such: x = Nxˆ , y = Myˆ , and
z = Lzˆ .
tex(x)
T[3]
T[0]
T[2]
T[1]
x
0 1 2 3 4 Non-Normalized
tex(x)
T[3]
T[0]
T[2]
T[1]
x
0 1 2 3 4 Non-Normalized
TL(x)
T[3]
T[0]
T[2]
T[1]
x
0 4/3 8/3 4
0 1/3 2/3 1
NVIDIA Corporation
2701 San Tomas Expressway
Santa Clara, CA 95050
www.nvidia.com