Foundations to Frontier
Tests
C. Programming, Tools and HPC › C5 High-Performance Computing

CUDA Programming Basics

CUDA lets you write the function that each GPU thread runs. This topic covers the programming model: kernels launched over a grid of thread blocks (kernel<<<grid, block>>>), built-in indices (blockIdx, threadIdx, blockDim, gridDim), the global, shared and register memory spaces, __syncthreads barriers within a block, atomics, host-device memory management and copies, streams and asynchronous execution, error checking, and the patterns every CUDA programmer learns: bounds checks, grid-stride loops, shared-memory tiling for matrix multiplication and tree reductions. In the exercises you build a Python emulator of the execution model (with barriers as generator yields), write vector, matrix, tiled matmul, reduction and histogram kernels and count their global loads; then you replay Harris's classic progression of reduction kernels and measure warp instructions, divergence and bank conflicts at each step.

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).

Parallel reduction: mapping threads to additions
for (s = 1; s < B; s *= 2) { if (tid % (2*s) == 0) sh[tid] += sh[tid + s]; __syncthreads(); }
warp 0warp 1warp 2warp 3s=1: 4 warps, 4 divergent, 4 passess=2: 4 warps, 4 divergent, 4 passess=4: 4 warps, 4 divergent, 4 passess=8: 2 warps, 2 divergent, 2 passess=16: 1 warp, 1 divergent, 1 pass
blue: thread performs an addition in that step · dark separators mark warps
warp-steps issued 15
divergent warp-steps 15
shared-memory read passes 15
Interleaved with tid % (2s): active threads are scattered, so almost every warp diverges and all warps stay busy. Mapping the k-th addition to thread k packs the work into few warps, but the reads jump by 2s words and pile into the same banks. Sequential addressing (pairs s apart, s halving) is both packed and conflict-free; it is the standard pattern, followed by warp shuffles for the last 32 values.
Why engineers care

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.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A CUDA kernel is…
  2. 2. How does a thread know which element to work on?
  3. 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.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Blocks needed for n = 1000 with 256 threads per block?
  2. 2. Why the if (i < n) check?
  3. 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.

🐍 Exercise 1: a CUDA execution-model emulator
Write launch(kernel, grid, block, *args) that runs a per-thread kernel for every blockIdx and threadIdx, gives each block a shared-memory dict, treats generator yields as __syncthreads() barriers (detecting barriers reached by only some threads), and provides atomic_add. Write vector add with a bounds check, 2-D matrix add, naive and shared-memory tiled matmul (counting global loads), a tree reduction and an atomic histogram, and check them against NumPy.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Global loads of A and B for an n×n tiled matmul with T×T tiles?
  2. 2. Why a second __syncthreads() after computing with the tiles?
  3. 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; run compute-sanitizer to find out-of-bounds and race conditions.
  • Warp-level primitives: __shfl_down_sync exchanges 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.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Which tool finds out-of-bounds accesses and races in CUDA kernels?
  2. 2. Copies overlap with kernels when…
  3. 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.

🐍 Exercise 2 (research): the reduction progression
Generate the shared-memory operations of each step for four reduction kernels (interleaved with divergence, interleaved with strided indices, sequential addressing, add during load); execute them to check the sum, and count warp-instructions issued, divergent warp-steps, bank-conflict passes, barriers and blocks; relate the counts to Harris's measured times.

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

  1. NVIDIA (2024). CUDA C++ Programming Guide (docs.nvidia.com/cuda).
  2. M. Harris (2007). “Optimizing parallel reduction in CUDA.” NVIDIA Developer Technology presentation.
  3. D. B. Kirk, W. W. Hwu, I. El Hajj (2022). Programming Massively Parallel Processors, 4th ed. Morgan Kaufmann.
  4. J. Nickolls, I. Buck, M. Garland, K. Skadron (2008). “Scalable parallel programming with CUDA.” ACM Queue, 6(2).
  5. S. K. Lam, A. Pitrou, S. Seibert (2015). “Numba: a LLVM-based Python JIT compiler.” LLVM-HPC Workshop (CUDA from Python).