Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Writing CUDA programs

Practical, exam-ready notes on writing CUDA programs: how to write kernels, map threads/blocks/grids to data, launch kernels, and basic memory/copy patterns with runnable example programs.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

CUDA lets programmers run parts of a C/C++ program on an NVIDIA GPU to get large speedups for data-parallel tasks. An engineer uses CUDA to move compute‑heavy loops from the CPU (host) to the GPU (device), write kernels that run many threads in parallel, and manage memory and launches so programs are correct and fast.

Key ideas

Start with simple, clear definitions (I bold each term when it is first used):

  • CUDA — a programming model and API from NVIDIA to run C/C++ functions on NVIDIA GPUs; it splits program execution between a host (CPU) and one or more devices (GPUs).
  • Host — the CPU side of the program that allocates memory, launches kernels and controls the device.
  • Device — the GPU where kernels execute; it has its own memory spaces and execution units.
  • Kernel — a function written in CUDA C/C++ that runs on the device; marked with the qualifier global when callable from the host.
  • Thread — the smallest unit of execution on a GPU; many threads run the kernel in parallel.
  • Block — a group of threads that can cooperate via shared memory and synchronization; indexed by blockIdx.
  • Grid — the full set of blocks launched for a kernel; can be 1D, 2D or 3D.
  • Warp — a hardware group of threads that execute the same instruction at the same time (SIMT). All threads in a warp follow the same instruction path; divergent branches inside a warp serialize those branches. On NVIDIA GPUs a warp contains 32 threads.
  • Global memory — device memory accessible by all threads and by the host via cudaMemcpy; high latency, high capacity.
  • Shared memory — on-chip memory shared by threads within the same block; low latency but small capacity.

Exact, exam-style facts and assumptions (state these in answers):

  • A kernel is declared with __global__ void kernelName(args) and launched from the host with the triple-angle bracket syntax: kernelName<<<gridDim, blockDim, sharedBytes, stream>>>(args).
  • Each thread has built-in indices: threadIdx (index within block), blockIdx (block index), blockDim (size of block), and gridDim (size of grid). These can be 1D, 2D or 3D structures.

Derivation commonly asked: formula for computing a unique 1D global thread index from 1D block and thread indices.

  1. Let block index be b = blockIdx.x (0-based), block size be B = blockDim.x, and thread index within block be t = threadIdx.x (0-based).
  2. Threads in block b start at global index b·B.
  3. The thread's global index is g = b·B + t.
  4. Therefore, global thread index: g = blockIdx.x * blockDim.x + threadIdx.x.

If you use 2D blocks and grids, map them to linear indices for array indexing. For a 2D thread arrangement with blockDim=(Bx,By) and threadIdx=(tx,ty):

  • local index within block: local = ty * Bx + tx.
  • block offset in grid: blockOffset = blockIdx.y * (gridDim.x * Bx * By) + blockIdx.x * (Bx * By) (drawn as rows of blocks). Then the 1D global index is global = blockOffset + local.

Diagram to draw in an exam when asked for mapping (describe exactly what to draw):

  • Draw a rectangle labelled "Grid" containing smaller rectangles labelled "Block 0", "Block 1", etc., arranged left-to-right for 1D or as a matrix for 2D. Inside a single block draw small squares labelled "t0, t1, t2, ..." representing threads. Label axes: x along blocks, inside a block x along threads. Next to the figure write the formula g = blockIdx.x * blockDim.x + threadIdx.x.

Memory rule-of-thumb students should write: move data to device global memory using cudaMalloc + cudaMemcpy before kernel, use shared memory to reuse data inside a block, and copy results back with cudaMemcpy after kernel. Always call cudaDeviceSynchronize() or check for errors after kernel launch when correct ordering is required.

Formulas

(For programming topics we list syntax lines to remember; each line is followed by explanation.)

__global__ void kernelName(args) — declare a kernel function callable from the host; runs on device.

  • kernelName: function name. args: arguments passed by value or as device pointers.

kernelName<<<gridDim, blockDim>>>(args) — launch kernel with grid and block dimensions.

  • gridDim and blockDim are integers or dim3 (1D/2D/3D). Example: kernel<<<(N+255)/256, 256>>>(...).

cudaMalloc(&ptr, size) — allocate device global memory; ptr is void**, size in bytes.

cudaFree(ptr) — free device memory.

cudaMemcpy(dst, src, size, cudaMemcpyHostToDevice) — copy memory host→device. Use cudaMemcpyDeviceToHost for device→host.

__shared__ type name[size] — allocate shared memory array in a kernel for use by threads in the same block. Use __syncthreads(); as a barrier to synchronize threads within a block when sharing data.

int g = blockIdx.x * blockDim.x + threadIdx.x; — compute 1D global thread index.

cudaDeviceSynchronize() — block host until device finishes work; check its return value to catch asynchronous kernel errors. Use cudaGetLastError() (or cudaPeekAtLastError()) immediately after a kernel launch to detect launch configuration errors.

cudaGetLastError() and cudaGetErrorString(err) — check kernel launch errors.

Worked examples

All examples are complete CUDA C++ programs (compile with nvcc). Sample input is the program itself; output is exact printed output.

Example 1 — Vector addition (1D indexing)

Code (save as vector_add.cu):

#include <cstdio> #include <cuda_runtime.h>

global void vecAdd(const float* a, const float* b, float* c, int n) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx < n) c[idx] = a[idx] + b[idx]; }

int main() { const int n = 8; float h_a[n] = {0,1,2,3,4,5,6,7}; float h_b[n] = {0,10,20,30,40,50,60,70}; float h_c[n] = {0}; float d_a, d_b, d_c; cudaMalloc(&d_a, n * sizeof(float)); cudaMalloc(&d_b, n * sizeof(float)); cudaMalloc(&d_c, n * sizeof(float)); cudaMemcpy(d_a, h_a, nsizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(d_b, h_b, nsizeof(float), cudaMemcpyHostToDevice); int blockSize = 4; int gridSize = (n + blockSize - 1) / blockSize; vecAdd<<<gridSize, blockSize>>>(d_a, d_b, d_c, n); cudaDeviceSynchronize(); cudaMemcpy(h_c, d_c, nsizeof(float), cudaMemcpyDeviceToHost); printf("a: "); for (int i=0;i<n;i++) printf("%g ", h_a[i]); printf("\n"); printf("b: "); for (int i=0;i<n;i++) printf("%g ", h_b[i]); printf("\n"); printf("c: "); for (int i=0;i<n;i++) printf("%g ", h_c[i]); printf("\n"); cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); return 0; }

Exact output when run:

a: 0 1 2 3 4 5 6 7 b: 0 10 20 30 40 50 60 70 c: 0 11 22 33 44 55 66 77

Example 2 — Dot product using atomicAdd (simple parallel accumulation)

Code (save as dot_atomic.cu):

#include <cstdio> #include <cuda_runtime.h>

global void dotProd(const float* a, const float* b, float* result, int n) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx < n) { float prod = a[idx] * b[idx]; atomicAdd(result, prod); } }

int main() { const int n = 8; float h_a[n] = {1,2,3,4,5,6,7,8}; float h_b[n] = {1,1,1,1,1,1,1,1}; float h_res = 0.0f; float *d_a, d_b, d_res; cudaMalloc(&d_a, n * sizeof(float)); cudaMalloc(&d_b, n * sizeof(float)); cudaMalloc(&d_res, sizeof(float)); cudaMemcpy(d_a, h_a, nsizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(d_b, h_b, nsizeof(float), cudaMemcpyHostToDevice); cudaMemset(d_res, 0, sizeof(float)); int blockSize = 4; int gridSize = (n + blockSize - 1) / blockSize; dotProd<<<gridSize, blockSize>>>(d_a, d_b, d_res, n); cudaDeviceSynchronize(); cudaMemcpy(&h_res, d_res, sizeof(float), cudaMemcpyDeviceToHost); printf("Dot product = %g\n", h_res); cudaFree(d_a); cudaFree(d_b); cudaFree(d_res); return 0; }

Exact output when run:

Dot product = 36

(36 = 1+2+3+4+5+6+7+8)

Notes: atomicAdd on float is supported for devices with compute capability >= 2.0. For double precision, atomicAdd requires compute capability >= 6.0. Prefer reductions in shared memory for high performance.

Common mistakes

  • Not calling cudaDeviceSynchronize() before copying results back or before reading kernel errors; kernel launches are asynchronous.
  • Using too large a block: exceeding the device's maximum threads per block (commonly 1024 total threads per block; also respect per-axis limits), not just blockDim.x.
  • Ignoring warp divergence: branching by threadIdx inside a warp can serialize execution and kill performance.
  • Overusing atomic operations for reduction when shared-memory tree-reduction would be better for performance.

For your exam

Types of questions to expect:

  • Definitions: define kernel, thread, block, grid, shared/global memory (give concise definitions and examples).
  • Short notes: explain kernel launch syntax, memory copy functions, and how to compute thread indices.
  • Derivations/diagrams: derive the global index formula and draw grid/block/thread layout with labels.
  • Programs: write a short CUDA kernel to add two vectors and show host code for allocation, copy, launch and result retrieval.
  • Performance questions: explain why shared memory is faster than global memory and describe warp divergence.

What a full-marks answer includes:

  • Correct definitions with bold terms, correct kernel declaration and launch syntax, indexing formula with derivation, clear diagram or description of block/grid, and a working host–device memory sequence (cudaMalloc, cudaMemcpy, kernel<<<>>>, cudaDeviceSynchronize, cudaMemcpy back, cudaFree). Mention boundary checks and answer performance trade-offs where asked.

Quick check

  1. How do you compute a 1D global thread index?
  2. Which memory is shared between threads of the same block?
  3. Is kernel launch synchronous or asynchronous by default from the host?

Answers: g = blockIdx.x * blockDim.x + threadIdx.x; shared memory; asynchronous (use cudaDeviceSynchronize to wait).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?