NVIDIA CUDA Programming Guide 2.0
NVIDIA CUDA Programming Guide 2.0
Compute Unified
Device Architecture
Programming Guide
Version 2.0
6/7/2008
ii CUDA Programming Guide Version 2.0
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 2-1. Grid of Thread Blocks.............................................................................8
Figure 2-2. Memory Hierarchy .................................................................................9
Figure 2-3. Heterogeneous Programming ............................................................... 11
Figure 2-4. Compute Unified Device Architecture Software Stack ............................. 12
Figure 3-1. Hardware Model ..................................................................................16
Figure 4-1. Library Context Management................................................................43
Figure 5-1. Examples of Coalesced Global Memory Access Patterns.......................... 55
Figure 5-2. Examples of Global Memory Access Patterns That Are Non-Coalesced for
Devices of Compute Capability 1.0 or 1.1 ...........................................................56
Figure 5-3. Examples of Global Memory Access Patterns That Are Non-Coalesced for
Devices of Compute Capability 1.0 or 1.1 ...........................................................57
Figure 5-4. Examples of Global Memory Access by Devices with Compute Capability
1.2 and Higher..................................................................................................58
Figure 5-5. Examples of Shared Memory Access Patterns without Bank Conflicts ..... 63
Figure 5-6. Example of a Shared Memory Access Pattern without Bank Conflicts...... 64
Figure 5-7. Examples of Shared Memory Access Patterns with Bank Conflicts ........... 65
Figure 5-8. Example of Shared Memory Read Access Patterns with Broadcast........... 66
Figure 6-1. Matrix Multiplication .............................................................................72
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
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.
The CUDA programming model is very well suited to expose the parallel
capabilities of GPUs. The latest generation of NVIDIA GPUs, based on the Tesla
architecture (see Appendix A for a list of all CUDA-capable GPUs), supports the
CUDA programming model and tremendously accelerates CUDA applications.
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:
__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 are allowed to proceed.
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 NVIDIA Tesla architecture, 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:
__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 scalable code.
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 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 4). 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.
Host
Application
CUDA Libraries
CUDA Runtime
CUDA Driver
Device
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 4.3.4.
The local and global memory spaces are read-write regions of device memory and
are not cached.
How many blocks a multiprocessor can process at once 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 batch of 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. A multiprocessor can execute as many as eight thread blocks
concurrently.
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 4.4.4) 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
A new directive to specify how a kernel is executed on the device from the host
(Section 4.2.3);
Four built-in variables that specify the grid and block dimensions and the block
and thread indices (Section 4.2.4).
Each source file containing these extensions must be compiled with the CUDA
compiler nvcc, as briefly described in Section 4.2.5. A detailed description of nvcc
can be found in a separate document.
Each of these extensions come with some restrictions described in each of the
sections below. nvcc will give an error or a warning on some violations of these
restrictions, but some of them cannot be detected.
4.2.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.
4.2.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.
4.2.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.
4.2.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.
4.2.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.
Only after the execution of a __syncthreads() (Section 4.4.2) are writes to
shared variables guaranteed to be visible by other threads. Unless the variable is
declared as volatile, the compiler is free to optimize the reads and writes to shared
memory as long as the previous statement is met.
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 4.2.3). 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];
}
4.2.2.4 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.
__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 4.5.2.3 and 4.5.3.6).
__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. This is often the case for large structures or arrays that
would consume too much register space, and arrays for which the compiler cannot
determine that they are indexed with constant quantities. Inspection of the ptx
assembly code (obtained by compiling with the –ptx or -keep option) will tell if a
variable has been placed in local memory during the first compilation phases as it
will be declared using the .local mnemonic and accessed using the ld.local
and st.local mnemonics. If it has not, subsequent compilation phases might still
decide otherwise though if they find it consumes too much register space for the
targeted architecture. This can be checked by compiling with the --ptxas-
options=-v option that reports local memory usage (lmem).
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
4.2.4.2 blockIdx
This variable is of type uint3 (see Section 4.3.1.1) and contains the block index
within the grid.
4.2.4.3 blockDim
This variable is of type dim3 (see Section 4.3.1.2) and contains the dimensions of
the block.
4.2.4.4 threadIdx
This variable is of type uint3 (see Section 4.3.1.1) and contains the thread index
within the block.
4.2.4.5 warpSize
This variable is of type int and contains the warp size in threads.
4.2.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.
4.2.5.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.
coordinates fell between the texels. Simple linear interpolation is performed for one-
dimensional textures and bilinear interpolation is performed for two-dimensional
textures.
Appendix D gives more details on texture fetching.
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);
These functions fetch the region of linear memory bound to texture reference
texRef using 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 linear memory bound to texture reference texRef using texture
coordinate x.
4.5.1.2 Memory
Device memory can be allocated either as linear memory or as CUDA arrays.
Linear memory exists on the device in a 32-bit address space, so separately allocated
entities can reference one another via pointers, for example, in a binary tree.
CUDA arrays are opaque memory layouts optimized for texture fetching (see
Section 4.3.4). They are one-dimensional, two-dimensional, or three-dimensional
and composed of elements, each of which has 1, 2 or 4 components that may be
signed or unsigned 8-, 16- or 32-bit integers, 16-bit floats (currently only supported
through the driver API), or 32-bit floats. CUDA arrays are only readable by kernels
through texture fetching and may only be bound to texture references with the same
number of packed components.
Both linear memory and CUDA arrays are readable and writable by the host
through the memory copy functions described in Sections 4.5.2.3 and 4.5.3.6.
The host runtime also provides functions to allocate and free page-locked host
memory – as opposed to regular pageable host memory allocated by malloc().
One advantage of page-locked memory is that the bandwidth between host memory
and device memory is higher if host memory is allocated as page-locked – only for
data transfers performed by the host thread that allocated host memory. Page-
locked memory is a scarce resource however, so allocations in page-locked memory
will start failing long before allocations in pageable memory. In addition, by
reducing the amount of physical memory available to the operating system for
paging, allocating too much page-locked memory reduces overall system
performance.
environment variable to 1. This feature is provided for debugging purposes only and
should never be used as a way to make production software run reliably.
// 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];
}
}
}
CUDA arrays are allocated using cudaMallocArray() and freed using
cudaFreeArray(). cudaMallocArray() requires a format description created
using cudaCreateChannelDesc().
The following code sample allocates a width×height CUDA array of one 32-bit
floating-point component:
cudaChannelFormatDesc channelDesc =
cudaCreateChannelDesc<float>();
cudaArray* cuArray;
cudaMallocArray(&cuArray, &channelDesc, width, height);
cudaGetSymbolAddress() is used to retrieve the address pointing to the
memory allocated for a variable declared in global memory space. The size of the
allocated memory is obtained through cudaGetSymbolSize().
The reference manual lists all the various functions used to copy memory between
linear memory allocated with cudaMalloc(), linear memory allocated with
cudaMallocPitch(), 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:
cudaMemcpy2DToArray(cuArray, 0, 0, devPtr, pitch,
width * sizeof(float), height,
cudaMemcpyDeviceToDevice);
The following code sample copies some host memory array to device memory:
float data[256];
int size = sizeof(data);
float* devPtr;
cudaMalloc((void**)&devPtr, size);
cudaMemcpy(devPtr, data, size, cudaMemcpyHostToDevice);
The following code sample copies some host memory array to constant memory:
__constant__ float constData[256];
float data[256];
cudaMemcpyToSymbol(constData, data, sizeof(data));
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:
float* hostPtr;
cudaMallocHost((void**)&hostPtr, 2 * size);
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().
cudaEventDestroy(start);
cudaEventDestroy(stop);
Before a kernel can use a texture reference to read from texture memory, the texture
reference must be bound to a texture using cudaBindTexture() or
cudaBindTextureToArray().
The following code samples bind a texture reference to linear memory pointed to by
devPtr:
Using the low-level API:
texture<float, 1, cudaReadModeElementType> texRef;
textureReference* texRefPtr;
cudaGetTextureReference(&texRefPtr, “texRef”);
cudaChannelFormatDesc channelDesc =
cudaCreateChannelDesc<float>();
cudaBindTexture(0, texRefPtr, devPtr, &channelDesc, size);
Using the high-level API:
texture<float, 1, cudaReadModeElementType> texRef;
cudaBindTexture(0, texRef, devPtr, size);
The following code samples bind a texture reference to a CUDA array cuArray:
Using the low-level API:
texture<float, 2, cudaReadModeElementType> texRef;
textureReference* texRefPtr;
cudaGetTextureReference(&texRefPtr, “texRef”);
cudaChannelFormatDesc channelDesc;
cudaGetChannelDesc(&channelDesc, cuArray);
cudaBindTextureToArray(texRef, cuArray, &channelDesc);
Using the high-level API:
texture<float, 2, cudaReadModeElementType> texRef;
cudaBindTextureToArray(texRef, cuArray);
The format specified when binding a texture to a texture reference must match the
parameters specified when declaring the texture reference; otherwise, the results of
texture fetches are undefined.
cudaUnbindTexture() is used to unbind a texture reference.
// 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;
}
programmer to use the host’s native debugging support to debug the application as
if it were a host application. The preprocessor macro __DEVICE_EMULATION__ is
defined in this mode. All code for an application, including any libraries used, must
be compiled consistently either for device emulation or for device execution.
Linking code compiled for device emulation with code compiled for device
execution causes the following runtime error to be returned upon initialization:
cudaErrorMixedDeviceExecution.
When running an application in device emulation mode, the programming model is
emulated by the runtime. For each thread in a thread block, the runtime creates a
thread on the host. The programmer needs to make sure that:
The host is able to run up to the maximum number of threads per block, plus
one for the master thread.
Enough memory is available to run all threads, knowing that each thread gets
256 KB of stack.
Many features provided through the device emulation mode make it a very effective
debugging tool:
By using the host’s native debugging support programmers can use all features
that the debugger supports, like setting breakpoints and inspecting data.
Since device code is compiled to run on the host, the code can be augmented
with code that cannot run on the device, like input and output operations to files
or to the screen (printf(), etc.).
Since all data resides on the host, any device- or host-specific data can be read
from either device or host code; similarly, any device or host function can be
called from either device or host code.
In case of incorrect usage of the synchronization intrinsic function, the runtime
detects dead lock situations.
Programmers must keep in mind that device emulation mode is emulating the
device, not simulating it. Therefore, device emulation mode is very useful in finding
algorithmic errors, but certain errors are hard to find:
Race conditions are less likely to manifest themselves in device-emulation mode,
since the number of threads executing simultaneously is much smaller than on
an actual device.
When dereferencing a pointer to global memory on the host or a pointer to host
memory on the device, device execution almost certainly fails in some undefined
way, whereas device emulation can produce correct results.
Most of the time the same floating-point computation will not produce exactly
the same result when performed on the device as when performed on the host in
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:
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);
Texture reference CUtexref Object that describes how to interpret texture memory data
4.5.3.1 Initialization
Initialization with cuInit() is required before any function from the driver API is
called.
API clients who may or may not have created contexts of their own – would use
cuCtxPushCurrent() and cuCtxPopCurrent() as illustrated in Figure 4-1.
Initialize
cuCtxCreate() context cuCtxPopCurrent()
Library Call
Use
cuCtxPushCurrent() context cuCtxPopCurrent()
char data[32];
cuParamSetv(cuFunction, offset, (void*)data, sizeof(data));
offset += sizeof(data);
cuParamSetSize(cuFunction, offset);
cuFuncSetSharedSize(cuFunction, numElements * sizeof(float));
cuLaunchGrid(cuFunction, gridWidth, gridHeight);
// 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];
}
}
}
CUDA arrays are created using cuArrayCreate() and destroyed using
cuArrayDestroy().
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 device memory:
float data[256];
int size = sizeof(data);
CUdeviceptr devPtr;
cuMemAlloc(&devPtr, size);
cuMemcpyHtoD(devPtr, data, size);
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
potentially overlap with the kernel execution of the other stream. hostPtr must
point to page-locked host memory for any overlap to occur:
float* hostPtr;
cuMemAllocHost((void**)&hostPtr, 2 * size);
cuCtxSynchronize() is called in the end to make sure all streams are finished
before proceeding further. Host can be synchronized with a specific stream by
calling cuStreamSynchronize(), allowing other streams to continue executing on
the device.
cuEventDestroy(start);
cuEventDestroy(stop);
returned by cuD3D9ResourceGetMappedSize(),
cuD3D9ResourceGetMappedPitch(), and
cuD3D9ResourceGetMappedPitchSlice(). Accessing a mapped resource
through Direct3D produces undefined results.
This code sample fills a buffer with zeros:
CUdeviceptr devPtr;
cuD3D9ResourceGetMappedPointer(&devPtr, buffer);
size_t size;
cuD3D9ResourceGetMappedSize(&size, buffer);
cuMemset(devPtr, 0, size);
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);
size_t pitch;
cuD3D9ResourceGetMappedPitch(&pitch, surface);
cuModuleGetFunction(&cuFunction, cuModule, “myKernel”);
cuFuncSetBlockShape(cuFunction, 16, 16, 1);
int offset = 0;
cuParamSeti(cuFunction, offset, devPtr);
offset += sizeof(devPtr);
cuParamSeti(cuFunction, 0, width);
offset += sizeof(width);
cuParamSeti(cuFunction, 0, height);
offset += sizeof(height);
cuParamSeti(cuFunction, 0, pitch);
offset += sizeof(pitch);
cuParamSetSize(cuFunction, offset);
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;
}
To obtain best performance in cases where the control flow depends on the thread
ID, the controlling condition should be written so as to minimize the number of
divergent warps. This is possible because the distribution of the warps across the
block is deterministic as mentioned in Section 3.1. A trivial example is when the
controlling condition only depends on (threadIdx / WSIZE) where WSIZE 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 4.2.5.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.
float c;
float d;
float e;
};
which is compiled into two 128-bit load instructions instead of five 32-bit load
instructions.
Any address of a variable residing in global memory or returned by one of the
memory allocation routines from the driver or runtime API is always aligned to at
least 256 bytes.
Second, global memory bandwidth is used most efficiently when the simultaneous
memory accesses by threads in a half-warp (during the execution of a single read or
write instruction) can be coalesced into a single memory transaction. The size of a
memory transaction can be either 32 bytes (for compute capability 1.2 and higher
only), 64 bytes, or 128 bytes.
The rest of this section describes the various requirements for memory accesses to
coalesce based on the compute capability of the device. If a half-warp fulfills these
requirements, coalescing is achieved even if the warp is divergent and some threads
of the half-warp do not actually access memory.
For the purpose of the following discussion, global memory is considered to be
partitioned into segments of size equal to 32, 64, or 128 bytes and aligned to this
size.
Coalescing on Devices with Compute Capability 1.0 and 1.1
The global memory access by all threads of a half-warp is coalesced into one or two
memory transactions if it satisfies the following three conditions:
Threads must access
Either 32-bit words, resulting in one 64-byte memory transaction,
Or 64-bit words, resulting in one 128-byte memory transaction,
Or 128-bit words, resulting in two 128-byte memory transactions;
All 16 words must lie in the same segment of size equal to the memory
transaction size (or twice the memory transaction size when accessing 128-bit
words);
Threads must access the words in sequence: The kth thread in the half-warp must
access the kth word.
If a half-warp does not fulfill all the requirements above, a separate memory
transaction is issued for each thread and throughput is significantly reduced.
Figure 5-1 shows some examples of coalesced memory accesses, while Figure 5-2
and Figure 5-3 show some examples of memory accesses that are non-coalesced for
devices of compute capability 1.0 or 1.1.
Coalesced 64-bit accesses deliver a little lower bandwidth than coalesced 32-bit
accesses and coalesced 128-bit accesses deliver a noticeably lower bandwidth than
coalesced 32-bit accesses. But, while bandwidth for non-coalesced accesses is
around an order of magnitude lower than for coalesced accesses when these
accesses are 32-bit, it is only around four times lower when they are 64-bit and
around two times when they are 128-bit.
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.
the same warp that read texture addresses that are close together will achieve best
performance. Also, it is designed for streaming fetches with a constant latency, i.e. a
cache hit reduces DRAM bandwidth demand, but not fetch latency.
Reading device memory through texture fetching can be an advantageous alternative
to reading device memory from global or constant memory as detailed in
Section 5.4.
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];
__shared__ int shared_hi[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;
};
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.
The number of registers a kernel compiles to (as well as local, shared, and constant
memory usage) is reported by the compiler when compiling with the
--ptxas-options=-v option. Note that each double or long long variable
uses two registers for devices that natively support these types, namely devices of
compute capability 1.2 and higher for long long and devices of compute
capability 1.3 and higher for double. However, devices of compute capability 1.2
and higher have twice as many registers per multiprocessor as devices with lower
compute capability.
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
and programmers need to choose execution configurations with care. The CUDA
Software Development Kit provides a spreadsheet to assist programmers in
choosing thread block size based on shared memory and register requirements.
However, within the same kernel call, the texture cache is not kept coherent with
respect to global memory writes, so that any texture fetch to an address that has
been written to via a global write in the same kernel call returns undefined data. In
other words, a thread can safely read via texture some memory location only if this
memory location has been updated by a previous kernel call or memory copy, but
not if it has been previously updated by the same thread or another thread from the
same kernel call. This is only relevant when fetching from linear memory as a kernel
cannot write to CUDA arrays anyway.
Optimizing memory usage starts with minimizing data transfers with low-
bandwidth. That means minimizing data transfers between the host and the device,
as detailed in Section 5.3, since these have much lower bandwidth than data
transfers between the device and global memory. That also means minimizing data
transfers between the device and global memory by maximizing use of shared
memory on the device, as mentioned in Section 5.1.2. Sometimes, the best
optimization might even be to avoid any data transfer in the first place by simply
recomputing the data instead whenever it is needed.
As detailed in Sections 5.1.2.1, 5.1.2.3, 5.1.2.4, and 5.1.2.5, the effective bandwidth
can vary by an order of magnitude depending on access pattern for each type of
memory. The next step in optimizing memory usage is therefore to organize
memory accesses as optimally as possible based on the optimal memory access
patterns. This optimization is especially important for global memory accesses as
global memory bandwidth is low and its latency is hundreds of clock cycles (see
Section 5.1.1.3). Shared memory accesses, on the other hand, are usually worth
optimizing only in case they have a high degree of bank conflicts.
As for optimizing instruction usage, the use of arithmetic instructions with low
throughput (see Section 5.1.1.1) should be minimized. This includes trading
precision for speed when it does not affect the end result, such as using intrinsic
instead of regular functions (intrinsic functions are listed in Section B.2) or single-
precision instead of double-precision. Particular attention must be paid to control
flow instructions due to the SIMT nature of the device as detailed in Section 5.1.1.2.
6.1 Overview
The task of computing the product C of two matrices A and B of dimensions
(wA, hA) and (wB, wA) respectively, is split among several threads in the following
way:
Each thread block is responsible for computing one square sub-matrix Csub of C;
Each thread within the block is responsible for computing one element of Csub.
The dimension block_size of Csub is chosen equal to 16, so that the number of threads
per block is a multiple of the warp size (Section 5.2) and remains below the
maximum number of threads per block (Appendix A).
As illustrated in Figure 6-1, Csub is equal to the product of two rectangular matrices:
the sub-matrix of A of dimension (wA, block_size) that has the same line indices as
Csub, and the sub-matrix of B of dimension (block_size, wA) that has the same column
indices as Csub. In order to fit into the device’s resources, these two rectangular
matrices are divided into as many square matrices of dimension block_size as
necessary and Csub is computed as the sum of the products of these square matrices.
Each of these products is performed by first loading the two corresponding square
matrices from global memory to shared memory with one thread loading one
element of each matrix, and then by having each thread compute one element of the
product. Each thread accumulates the result of each of these products into a register
and once done writes the result to global memory.
By blocking the computation this way, we take advantage of fast shared memory
and save a lot of global memory bandwidth since A and B are read from global
memory only (wA / block_size) times.
Nonetheless, this example has been written for clarity of exposition to illustrate
various CUDA programming principles, not with the goal of providing a
high-performance kernel for generic matrix multiplication and should not be
construed as such.
BLOCK_SIZE
B
wA
BLOCK_SIZE
C
A
BLOCK_SIZE
Csub
hA
wA wB
Each thread block computes one sub-matrix Csub of C. Each thread within the block
computes one element of Csub.
// Thread index
int tx = threadIdx.x;
int ty = threadIdx.y;
6.3.1 Mul()
Mul() takes as input:
Two pointers to host memory that point to the elements of A and B,
The height and width of A and the width of B,
A pointer to host memory that points where C should be written.
Mul() performs the following operations:
It allocates enough global memory to store A, B, and C using cudaMalloc();
It copies A and B from host memory to global memory using cudaMemcpy();
It calls Muld() to compute C on the device;
It copies C from global memory to host memory using cudaMemcpy();
It frees the global memory allocated for A, B, and C using cudaFree().
6.3.2 Muld()
Muld() has the same input as Mul(), except that pointers point to device memory
instead of host memory.
For each block, Muld()iterates through all the sub-matrices of A and B required to
compute Csub. At each iteration:
It loads one sub-matrix of A and one sub-matrix of B from global memory to
shared memory;
It synchronizes to make sure that both sub-matrices are fully loaded by all the
threads within the block;
It computes the product of the two sub-matrices and adds it to the product
obtained during the previous iteration;
It synchronizes again to make sure that the product of the two sub-matrices is
done before starting the next iteration.
Once all sub-matrices have been handled, Csub is fully computed and Muld() writes
it to global memory.
Muld() is written to maximize memory performance according to Section 5.1.2.1
and 5.1.2.5.
Indeed, assuming that wA and wB are multiples of 16 as suggested in Section 5.1.2.1,
global memory coalescing is ensured because a, b, and c are all multiples of
BLOCK_SIZE, which is equal to 16.
There is also no shared memory bank conflict since for each half-warp, ty and k are
the same for all threads and tx varies from 0 to 15, so each thread accesses a
different bank for the memory accesses As[ty][tx], Bs[ty][tx], and
Bs[k][tx] and the same bank for the memory access As[ty][k].
Number of Compute
Multiprocessors Capability
GeForce GTX 280 30 1.3
GeForce GTX 260 24 1.3
GeForce 9800 GX2 2x16 1.1
GeForce 9800 GTX 16 1.1
GeForce 8800 Ultra, 8800 GTX 16 1.0
GeForce 8800 GT 14 1.1
GeForce 9600 GSO, 8800 GS, 8800M GTX 12 1.1
GeForce 8800 GTS 12 1.0
GeForce 9600 GT, 8800M GTS 8 1.1
GeForce 9500 GT, 8600 GTS, 8600 GT, 4 1.1
8700M GT, 8600M GT, 8600M GS
GeForce 8500 GT, 8400 GS, 8400M GT, 2 1.1
8400M GS
GeForce 8400M G 1 1.1
Tesla S1070 4x30 1.3
Tesla C1060 30 1.3
Tesla S870 4x16 1.0
The clock frequency and total amount of device memory can be queried using the
runtime (Sections 4.5.2.2 and 4.5.3.2).
Functions from Section B.1 can be used by both host and device functions whereas
functions from Section B.2 can only be used in device functions.
Table B-1. Also, for 2126 < y < 2128, if x is infinity, __fdividef(x,y) delivers a
NaN (as a result of multiplying infinity by zero), while the regular division returns
infinity.
__[u]mul24(x,y) computes the product of the 24 least significant bits of the
integer parameters x and y and delivers the 32 least significant bits of the result. The
8 most significant bits of x or y are ignored.
__[u]mulhi(x,y) computes the product of the integer parameters x and y and
delivers the 32 most significant bits of the 64-bit result.
__[u]mul64hi(x,y) computes the product of the 64-bit integer parameters x
and y and delivers the 64 most significant bits of the 128-bit result.
__saturate(x) returns 0 if x is less than 0, 1 if x is more than 1, and x
otherwise.
__[u]sad(x,y,z) (Sum of Absolute Difference) returns the sum of integer
parameter z and the absolute value of the difference between integer parameters x
and y.
__clz(x) returns the number, between 0 and 32 inclusive, of consecutive zero bits
starting at the most significant bit (i.e. bit 31) of integer parameter x.
__clzll(x) returns the number, between 0 and 64 inclusive, of consecutive zero
bits starting at the most significant bit (i.e. bit 63) of 64-bit integer parameter x.
__ffs(x) returns the position of the first (least significant) bit set in integer
parameter x. The least significant bit is position 1. If x is 0, __ffs() returns 0.
Note that this is identical to the Linux function ffs.
__ffsll(x) returns the position of the first (least significant) bit set in 64-bit
integer parameter x. The least significant bit is position 1. If x is 0, __ffsll()
returns 0. Note that this is identical to the Linux function ffsll.
__uint2double_rn(x) N/A
__ll2double_[rn,rz,ru,rd](x) N/A
__ull2double_[rn,rz,ru,rd](x) N/A
__double_as_longlong(x) N/A
__longlong_as_double(x) N/A
__double2hiint(x) N/A
__double2loint(x) N/A
__hiloint2double(x, ys) N/A
Atomic functions can only be used in device functions and are only available for
devices of compute capability 1.1 and above.
Atomic functions operating on shared memory and atomic functions operating on
64-bit words are only available for devices of compute capability 1.2 and above.
C.1.1 atomicAdd()
int atomicAdd(int* address, int val);
unsigned int atomicAdd(unsigned int* address,
unsigned int val);
unsigned long long int atomicAdd(unsigned long long int* address,
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 + 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.
64-bit words are only supported for global memory.
C.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.
C.1.3 atomicExch()
int atomicExch(int* address, int val);
C.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.
C.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.
C.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.
C.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.
C.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).
64-bit words are only supported for global memory.
C.2.1 atomicAnd()
int atomicAnd(int* address, int val);
unsigned int atomicAnd(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.
C.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.
C.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.
This appendix gives the formula used to compute the value returned by the texture
functions of Section 4.4.3 depending on the various attributes of the texture
reference (see Section 4.3.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