Cheat sheet
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#
| Name | Type | Value |
|---|---|---|
threadIdx | uint3 | Thread position in block |
blockIdx | uint3 | Block position in grid |
blockDim | dim3 | Threads per block |
gridDim | dim3 | Blocks per grid |
warpSize | int | 32 on all current GPUs |
Launch limits#
| Limit | Value |
|---|---|
| Threads per block | 1,024 |
| Warp size | 32 |
gridDim.x | 2³¹ − 1 |
gridDim.y, gridDim.z | 65,535 |
| Shared memory per block | 48 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);| Specifier | Scope | Lifetime | Where |
|---|---|---|---|
| register | thread | kernel | SM |
__shared__ | block | kernel | SM |
| local (automatic spill) | thread | kernel | DRAM |
__constant__ | grid | app | DRAM + cache |
__device__ global | grid | app | DRAM |
__managed__ global | grid + host | app | migrates |
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);| Call | Waits 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)| Message | Usual cause |
|---|---|
invalid configuration argument | Block > 1,024 threads, bad grid, too much shared memory |
no kernel image is available | Wrong -arch, driver/GPU mismatch |
an illegal memory access was encountered | Out-of-bounds index, bad pointer, use after free |
out of memory | Allocation larger than free VRAM |
operation not permitted | Peer access, profiling permission, or sandbox restriction |
unspecified launch failure | Often 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
ncubefore and after every change.
Glossary#
| Term | Meaning |
|---|---|
| Kernel | A function launched on the GPU |
| Grid | All blocks in one launch |
| Block | A group of threads scheduled on one SM |
| Warp | 32 threads issued together |
| Lane | A thread's index within its warp |
| SM | Streaming multiprocessor; executes blocks |
| Occupancy | Resident warps ÷ maximum warps per SM |
| Coalescing | Combining lane accesses into few memory transactions |
| Bank conflict | Two lanes hitting different words in the same shared-memory bank |
| Divergence | Lanes taking different branches; paths serialise |
| Unified memory | One allocation valid on CPU and GPU |
| Pinned memory | Page-locked host memory usable for async DMA |
| Stream | An ordered queue of asynchronous work |
| Event | A timestamp/dependency marker in a stream |
| Cluster | Co-resident blocks that can share distributed shared memory |
| Tile | A compile-time-shaped block-level array in CUDA 13 |
Where next#
- CUDA Programming Guide — the source material, now readable.
- CUDA C++ Standard Library (CCCL) —
cuda::std, cooperative groups,cuda::atomic. - CUTLASS — production matrix multiplication and tensor cores.
- Nsight Compute and Nsight Systems — profile before you tune.
- NCCL — multi-GPU collectives.
- Triton — a Python DSL for GPU kernels, if C++ is not the right tool.
- CUDA Tile documentation — the model from Chapter 14.
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.