Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.One instruction sheet, a million workers
Writing a GPU program means writing the instructions for one worker, then hiring a million of them at once. Each worker gets a badge with its number and uses it to decide which piece of data is its own: worker 7 adds element 7, worker 8 adds element 8. Workers are organized in teams (blocks) that share a small whiteboard (shared memory) and can wait for each other at a checkpoint (a barrier).
for (s = 1; s < B; s *= 2) { if (tid % (2*s) == 0) sh[tid] += sh[tid + s]; __syncthreads(); }Custom CUDA kernels accelerate the parts of scientific and robotics codes that libraries don’t cover: particle propagators, ray casting for lidar simulation, custom losses, sparse sensor-fusion updates. Even if you never write one, CUDA’s model explains every GPU library you call and every error message about grids, blocks and out-of-bounds accesses.
- 1. A CUDA kernel is…
- 2. How does a thread know which element to work on?
- 3. In the demo, which mapping keeps whole warps busy without bank conflicts?
Level 1: Beginner
★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.A first kernel
__global__ void vec_add(const float* a, const float* b, float* c, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x; // global thread index
if (i < n) c[i] = a[i] + b[i]; // bounds check: the last block may be partly empty
}
int main() {
float *a, *b, *c; size_t bytes = n * sizeof(float);
cudaMalloc(&a, bytes); cudaMalloc(&b, bytes); cudaMalloc(&c, bytes);
cudaMemcpy(a, h_a, bytes, cudaMemcpyHostToDevice); // ... same for b
int threads = 256, blocks = (n + threads - 1) / threads;
vec_add<<<blocks, threads>>>(a, b, c, n); // asynchronous launch
cudaError_t err = cudaGetLastError(); // check launch errors
cudaMemcpy(h_c, c, bytes, cudaMemcpyDeviceToHost); // waits for the kernel
cudaFree(a); cudaFree(b); cudaFree(c);
}__global__ marks a kernel (called from the host, runs on the device); __device__ functions are called from kernels. Blocks and grids can be 1-, 2- or 3-dimensional (dim3). Block sizes are usually multiples of 32 (warps), typically 128–512.
- 1. Blocks needed for n = 1000 with 256 threads per block?
- 2. Why the if (i < n) check?
- 3. cudaMemcpy device-to-host after a launch…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.Shared memory and barriers
Threads of a block can stage data in __shared__ arrays (on-chip, ~100× lower latency than global memory) and wait for each other with __syncthreads(). Every thread of the block must reach the same barrier: a __syncthreads() inside a branch that some threads skip is undefined behaviour (typically a hang).
Tiled matrix multiplication: each block computes a T×T tile of C; in a loop over k it loads a T×T tile of A and of B into shared memory (each thread loads one element), synchronizes, accumulates T products from shared memory, and synchronizes again before overwriting the tiles. Global loads drop from 2n³ to 2n³/T.
Reductions: each block sums its slice in shared memory in log₂(B) steps, then writes a partial sum; a second launch (or atomics) combines blocks. Atomics (atomicAdd) serialize conflicting updates safely, for histograms and counters.
- 1. Global loads of A and B for an n×n tiled matmul with T×T tiles?
- 2. Why a second __syncthreads() after computing with the tiles?
- 3. __syncthreads() inside if (threadIdx.x < 16) in a 32-thread block…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Patterns and practice
- Grid-stride loops:
for (i = blockIdx.x*blockDim.x + threadIdx.x; i < n; i += blockDim.x*gridDim.x)handles any n with a fixed grid and improves reuse of launched threads. - Streams: kernels and copies in different streams can overlap (copy the next batch while computing this one), using pinned host memory and
cudaMemcpyAsync. - Unified memory (
cudaMallocManaged) simplifies code at a performance cost from page migration. - Errors: check every API call and
cudaGetLastError()after launches; runcompute-sanitizerto find out-of-bounds and race conditions. - Warp-level primitives:
__shfl_down_syncexchanges registers within a warp without shared memory, the fastest way to finish a reduction; cooperative groups generalize synchronization. - From Python: CuPy’s RawKernel, Numba’s
@cuda.jit, PyTorch C++/CUDA extensions, or Triton (C5.7) avoid writing host boilerplate.
Reduction, step by step
Harris’s well-known sequence of reduction kernels shows the main optimization ideas in one problem: avoid divergent branches (map work to consecutive threads), avoid bank conflicts (sequential addressing), keep threads busy (add during the load), then unroll and use warp-level operations.
- 1. Which tool finds out-of-bounds accesses and races in CUDA kernels?
- 2. Copies overlap with kernels when…
- 3. __shfl_down_sync lets threads…
Level 4: Expert
★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.Kernels, measured
Exercise 1. The emulator runs 4 blocks of 256 threads for n = 1000 (the last block partly idle), a 2-D grid of 16×16 blocks for a 20×30 matrix, a tree reduction and an atomic histogram, all matching NumPy. For a 16×16 matmul, the naive kernel makes 8192 global loads of A and B; 4×4 shared-memory tiles make 2048 (a factor T = 4). A barrier reached by only half the threads is reported as a deadlock.
Exercise 2: the reduction progression. Replaying each kernel’s shared-memory steps for 256-thread blocks over 65 536 values (all four compute the correct sum):
| Kernel | warp-instructions per block | divergent warp-steps | shared-memory passes | blocks | Harris’s measured time (G80, 4M ints) |
|---|---|---|---|---|---|
| 1. interleaved, tid % (2s) | 47 | 47 | 94 | 256 | 8.05 ms |
| 2. interleaved, strided index | 12 | 5 | 94 | 256 | 3.46 ms |
| 3. sequential addressing | 12 | 5 | 24 | 256 | 1.72 ms |
| 4. first add during load | 12 | 5 | 24 | 128 | 0.97 ms |
Each step removes one counted waste: kernel 2 packs the work into few non-divergent warps, but its strided indices create bank conflicts that keep shared-memory passes at 94; kernel 3 removes the conflicts (one pass per access); kernel 4 halves the number of blocks. Every kernel needs 9 barriers per block. The measured times are from Harris’s slides, as an external reference for the counts.
CUDA in AI, robotics and aerospace
- Custom operators in PyTorch (C++/CUDA extensions) for new layers, losses and sparse operations.
- Robotics: GPU-accelerated collision checking, signed-distance fields and particle filters (Isaac libraries).
- Simulation: Monte Carlo trajectory propagation with one thread per sample; ray tracing for radiation and sensor models.
- Image processing: onboard image compression and feature extraction on Jetson-class hardware.
References
- NVIDIA (2024). CUDA C++ Programming Guide (docs.nvidia.com/cuda).
- M. Harris (2007). “Optimizing parallel reduction in CUDA.” NVIDIA Developer Technology presentation.
- D. B. Kirk, W. W. Hwu, I. El Hajj (2022). Programming Massively Parallel Processors, 4th ed. Morgan Kaufmann.
- J. Nickolls, I. Buck, M. Garland, K. Skadron (2008). “Scalable parallel programming with CUDA.” ACM Queue, 6(2).
- S. K. Lam, A. Pitrou, S. Seibert (2015). “Numba: a LLVM-based Python JIT compiler.” LLVM-HPC Workshop (CUDA from Python).