GPU by Example
16 / 16

Cheat sheet

7 min readChapter 16 of 16

Reference page. Skim it before an interview, paste it next to your keyboard, or use it to remember which of the four index variables is which.

Kernel syntax#

CUDA C++
__global__ void kernel(float* out, const float* in, int n) {  // GPU entry point
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) out[i] = in[i];
}

__device__ float helper(float x) { return x * x; }   // callable only on GPU
__host__   float hostFn(float x)  { return x + 1; }   // normal CPU function
__host__ __device__ float both(float x) { return x; } // compiled for both

kernel<<<blocks, threads>>>(out, in, n);                      // launch
kernel<<<dim3(gx, gy), dim3(bx, by), sharedBytes, stream>>>(...);
  • Kernels return void, run asynchronously, and are called with <<<>>>.
  • __global__ can be called from host; __device__ only from device; __host__ only from host.
  • __shared__ inside a kernel allocates per block; __constant__ at file scope is read-only to kernels.

Index formulas#

CUDA C++
int i  = blockIdx.x * blockDim.x + threadIdx.x;                       // 1D
int x  = blockIdx.x * blockDim.x + threadIdx.x;
int y  = blockIdx.y * blockDim.y + threadIdx.y;
int i2 = y * width + x;                                               // 2D row-major

int tid = threadIdx.x
        + threadIdx.y * blockDim.x
        + threadIdx.z * blockDim.x * blockDim.y;                      // linear in block
int warp = tid / 32;
int lane = tid % 32;

Built-in variables#

NameTypeValue
threadIdxuint3Thread position in block
blockIdxuint3Block position in grid
blockDimdim3Threads per block
gridDimdim3Blocks per grid
warpSizeint32 on all current GPUs

Launch limits#

LimitValue
Threads per block1,024
Warp size32
gridDim.x2³¹ − 1
gridDim.y, gridDim.z65,535
Shared memory per block48 KB default, up to ~227 KB opt-in (varies)

Memory#

CUDA C++
cudaMalloc(&d, bytes);
cudaMemset(d, 0, bytes);
cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice);
cudaMemcpy(h, d, bytes, cudaMemcpyDeviceToHost);
cudaMemcpy(d2, d1, bytes, cudaMemcpyDeviceToDevice);
cudaMemcpy(d, h, bytes, cudaMemcpyDefault);       // infer from pointers
cudaFree(d);

cudaMallocManaged(&m, bytes);                     // unified memory
cudaMemPrefetchAsync(m, bytes, device, stream);
cudaMemAdvise(m, bytes, cudaMemAdviseSetReadMostly, device);

cudaMallocHost((void**)&p, bytes);                        // pinned host memory
cudaHostAlloc((void**)&p, bytes, cudaHostAllocMapped);
cudaHostRegister(p, bytes, 0);
cudaFreeHost(p);
SpecifierScopeLifetimeWhere
registerthreadkernelSM
__shared__blockkernelSM
local (automatic spill)threadkernelDRAM
__constant__gridappDRAM + cache
__device__ globalgridappDRAM
__managed__ globalgrid + hostappmigrates

Synchronisation#

CUDA C++
__syncthreads();            // block barrier + shared/global fence
__syncwarp(mask);           // warp barrier (0xffffffff for all lanes)
__threadfence_block();      // order this thread's accesses within block
__threadfence();            // order within grid
__threadfence_system();     // order across host/peers

__shfl_down_sync(0xffffffff, v, offset);
__ballot_sync(0xffffffff, predicate);
atomicAdd(&x, 1);
atomicCAS(&x, compare, value);
CallWaits for
cudaDeviceSynchronize()All device work
cudaStreamSynchronize(s)One stream
cudaStreamQuery(s)Non-blocking check
cudaEventSynchronize(e)One event
cudaStreamWaitEvent(s, e)Makes a stream wait, host stays free

Streams and events#

CUDA C++
cudaStream_t stream;
cudaStreamCreate(&stream);
cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking);
kernel<<<grid, block, 0, stream>>>(...);
cudaMemcpyAsync(d, h, bytes, cudaMemcpyHostToDevice, stream);
cudaStreamSynchronize(stream);
cudaStreamDestroy(stream);

cudaEvent_t start, stop;
cudaEventCreate(&start); cudaEventCreate(&stop);
cudaEventRecord(start, stream);
// work
cudaEventRecord(stop, stream);
cudaEventSynchronize(stop);
float ms; cudaEventElapsedTime(&ms, start, stop);
cudaEventDestroy(start); cudaEventDestroy(stop);

Occupancy and device queries#

CUDA C++
int blocks;
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&blocks, kernel, 256, 0);

cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, 0);
printf("%s, %d SMs, %.1f GB, CC %d.%d\n",
       prop.name, prop.multiProcessorCount,
       prop.totalGlobalMem / 1e9, prop.major, prop.minor);

int sms;
cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, 0);

Compilation#

Shell
$ nvcc -O3 -arch=native app.cu -o app
$ nvcc -O3 -arch=sm_90 app.cu -o app          # explicit architecture
$ nvcc -O3 -lineinfo app.cu -o app           # profiler line info
$ nvcc -G -g app.cu -o app                   # device debug build
$ nvcc -Xptxas -v app.cu                     # registers/smem report
$ compute-sanitizer ./app                    # memory checker
$ ncu --set full ./app                       # Nsight Compute
$ nsys profile --stats=true ./app            # Nsight Systems

-arch=native targets the GPU in the machine. Binaries built for an older architecture may fail on a newer one with no kernel image is available for execution on the device.

Error handling#

CUDA C++
#define CUDA_CHECK(call)                                                     \
    do {                                                                     \
        cudaError_t err_ = (call);                                           \
        if (err_ != cudaSuccess) {                                           \
            fprintf(stderr, "%s:%d: %s -> %s\n", __FILE__, __LINE__,         \
                    #call, cudaGetErrorString(err_));                        \
            exit(EXIT_FAILURE);                                              \
        }                                                                    \
    } while (0)
MessageUsual cause
invalid configuration argumentBlock > 1,024 threads, bad grid, too much shared memory
no kernel image is availableWrong -arch, driver/GPU mismatch
an illegal memory access was encounteredOut-of-bounds index, bad pointer, use after free
out of memoryAllocation larger than free VRAM
operation not permittedPeer access, profiling permission, or sandbox restriction
unspecified launch failureOften a segfault inside the kernel; run compute-sanitizer

cudaGetLastError() catches launch errors and clears them. cudaDeviceSynchronize() catches execution errors.

The whole program#

skeleton_full.cuCUDA C++
#include <cstdio>
#include <cuda_runtime.h>

__global__ void scale(float* data, int n, float factor) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) data[i] *= factor;
}

int main() {
    const int n = 1 << 20;
    const size_t bytes = n * sizeof(float);

    float* h = (float*)malloc(bytes);
    for (int i = 0; i < n; ++i) h[i] = 1.0f;

    float* d;
    cudaMalloc(&d, bytes);
    cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice);

    int threads = 256;
    int blocks  = (n + threads - 1) / threads;
    scale<<<blocks, threads>>>(d, n, 2.0f);
    cudaDeviceSynchronize();

    cudaMemcpy(h, d, bytes, cudaMemcpyDeviceToHost);
    printf("%f\n", h[n - 1]);

    cudaFree(d);
    free(h);
    return 0;
}

Rules of thumb#

  • Blocks are multiples of 32; 128–256 threads is a good default.
  • Bounds-check every index that comes from the launch geometry.
  • Consecutive lanes → consecutive addresses.
  • Synchronise within blocks with __syncthreads; never rely on block order.
  • Copy once, compute many times.
  • Pin host memory for async copies.
  • Prefer many small kernels to one giant one; prefer streams for independent work.
  • Measure with ncu before and after every change.

Glossary#

TermMeaning
KernelA function launched on the GPU
GridAll blocks in one launch
BlockA group of threads scheduled on one SM
Warp32 threads issued together
LaneA thread's index within its warp
SMStreaming multiprocessor; executes blocks
OccupancyResident warps ÷ maximum warps per SM
CoalescingCombining lane accesses into few memory transactions
Bank conflictTwo lanes hitting different words in the same shared-memory bank
DivergenceLanes taking different branches; paths serialise
Unified memoryOne allocation valid on CPU and GPU
Pinned memoryPage-locked host memory usable for async DMA
StreamAn ordered queue of asynchronous work
EventA timestamp/dependency marker in a stream
ClusterCo-resident blocks that can share distributed shared memory
TileA compile-time-shaped block-level array in CUDA 13

Where next#

Write a kernel. Measure it. Make it faster. That is the whole job.

◆

That's the end of the book. Go write a kernel that beats your CPU code.