Optimising CUDA applications
Practical, exam-focused notes on techniques to speed up CUDA programs: memory coalescing, tiling (shared memory), occupancy, avoiding warp divergence, roofline reasoning, and relevant CUDA syntax with two runnable example kernels (naive and tiled matrix multiply).
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 programs run on GPUs where peak throughput is very high but only reachable when you organise work and memory correctly. Engineers use these optimisation techniques to make GPU kernels run faster, use less energy, and cost less per unit work — for example in computer vision, scientific simulation, and machine learning.
Key ideas
Start from first principles: the GPU gives many arithmetic units but accesses to global memory (device DRAM) are slow compared to arithmetic. Therefore performance depends on balancing computation and memory traffic.
GPU kernel — a function marked with global that runs on the device and is launched from the host. A kernel executes many threads in parallel. Use grid-stride loops to let each thread process multiple elements when data size exceeds grid size or to increase memory-level parallelism.
Thread, block, grid — a thread is one execution context; threads are grouped into blocks; blocks form a grid for a kernel launch. Blocks map to Streaming Multiprocessors (SMs) for scheduling; a block executes entirely on one SM and does not migrate.
Warp — a group of threads (usually 32) that execute the same instruction in lock-step on an SM. On exam diagrams draw a rectangle labelled "SM" with several small boxes grouped in 32s; label one group "warp".
Warp divergence — when threads in a warp follow different control paths (if/else), they serialize, slowing the warp. Definition: warp divergence occurs when threads in a warp have different branch outcomes for a branch instruction.
Global memory vs shared memory vs registers — global memory is off-chip DRAM, high latency, high bandwidth; shared memory is on-chip SRAM per block, low latency when used correctly; registers are fastest per-thread storage. Constant memory is a small cached read-only space optimized for broadcast; texture/read-only data cache can help with spatial locality. Draw a memory hierarchy: CPU RAM (if explaining in context), GPU DRAM (global), per-SM shared memory and L1, per-thread registers.
Memory coalescing — arranging memory accesses so consecutive threads access consecutive addresses in global memory. Exact rule (GPU generations vary): a load by a warp is coalesced when thread i accesses address base + i·sizeof(type) within a properly aligned 32/64/128-byte segment (depending on access size and architecture); poor coalescing can severely cut effective bandwidth.
Bank conflicts — shared memory is divided into banks; simultaneous accesses by threads to the same bank can serialize. Definition: a bank conflict occurs when two or more threads in a warp access different addresses that map to the same shared-memory bank (broadcast of the same address is conflict-free on recent NVIDIA GPUs; typical configurations have 32 banks with 4-byte granularity).
Occupancy — fraction of the maximum possible active warps or threads that are active on an SM. Exact definition: occupancy = active warps per SM / maximum warps per SM. Occupancy depends on threads per block, registers per thread, and shared memory per block. High occupancy is not a guarantee of performance; aim for enough occupancy to hide latency while preserving ILP and avoiding spills.
Register pressure — when a thread needs many registers, the compiler limits the number of active threads per SM, lowering occupancy. The trade-off: more registers reduce spilling but may reduce occupancy.
Tiling (blocking) — restructure computation so threads load a small tile of data into shared memory once and reuse it many times. For matrix multiply, tile A and B into shared memory and compute partial results.
Roofline model — a simple performance model. Let P_peak be peak compute (FLOPS/s) and B_mem be peak memory bandwidth (bytes/s). For a kernel with operational intensity I (FLOPs per byte), attainable performance P is P = min(P_peak, B_mem · I). On an exam draw axes: x = operational intensity (log scale), y = performance; draw a horizontal line at P_peak and diagonal line slope = B_mem; their intersection is the ridge point.
Latency hiding — GPUs hide global memory latency by switching between warps; you need enough active warps per SM to hide latency. If you have too few active warps (low occupancy), the SM stalls waiting for memory.
Loop unrolling and ILP (Instruction-Level Parallelism) — manually unrolling small loops can expose more independent instructions to the compiler and increase ILP, often improving throughput when compute-bound. Warp-level intrinsics (e.g., __shfl_sync) can exchange data within a warp without shared memory, accelerating reductions/scans and avoiding bank conflicts.
Assumptions behind these definitions: warp size = 32 for NVIDIA GPUs commonly used in coursework (verify for new architectures); memory bank count is architecture-dependent; P_peak and B_mem are device properties you must check for your GPU.
Diagrams to draw in exam answers:
- Memory hierarchy: show global memory at top (label latency ~hundreds of cycles), SM box with shared memory and registers and ALUs inside. Label flows of data.
- Roofline: x-axis operational intensity, y-axis performance. Draw and label P_peak and B_mem·I lines and the ridge point.
- Tiled matrix multiply: show two input matrices A and B, a tile box loaded into shared memory per block, and threads inside block computing sub-block of C.
Formulas
P = min(P_peak, B_mem · I) — P: attainable performance (FLOPS/s), P_peak: device peak FLOPS (FLOPS/s), B_mem: memory bandwidth (bytes/s), I: operational intensity (FLOPS/byte). Applies for steady-state kernels. Ridge point: I_ridge = P_peak / B_mem (separates memory-bound from compute-bound regions).
CUDA syntax and functions to remember (each on its own line):
__global__ void kernel(...) — marks a device kernel launched from host.
kernel<<<gridDim, blockDim>>>(...) — kernel launch syntax; gridDim and blockDim can be dim3.
__device__ — function runs on device, callable from device code.
__host__ — function runs on host.
__shared__ — declares per-block shared memory variable.
__syncthreads() — barrier synchronisation for threads in a block.
cudaDeviceSynchronize() — host-side blocking wait for all preceding device work; useful for timing and error checking.
cudaMalloc(void** ptr, size_t bytes) — allocate device memory.
cudaMemcpy(dst, src, size, cudaMemcpyHostToDevice) — copy memory; common kinds: cudaMemcpyHostToDevice, cudaMemcpyDeviceToHost, cudaMemcpyDeviceToDevice, cudaMemcpyHostToHost. To overlap transfers with kernels, use cudaMemcpyAsync with a cudaStream_t and pinned (page-locked) host memory.
cudaFree(ptr) — free device memory.
warpSize — built-in constant for warp width (usually 32).
occupancy = active_warps_per_SM / max_warps_per_SM — occupancy formula; active warps limited by registers/shared memory and threads per block.
Worked examples
Example 1 — Naive GPU matrix multiply (4x4 fixed matrices). This program compiles with nvcc and computes C = A·B on GPU using one thread per C element.
Code (save as mm_naive.cu):
#include <cstdio> #include <cuda_runtime.h>
#define N 4
global void mm_naive(const float* A, const float* B, float* C, int n) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; if (row < n && col < n) { float sum = 0.0f; for (int k = 0; k < n; ++k) sum += A[rown + k] * B[kn + col]; C[row*n + col] = sum; } }
int main() { float hA[NN] = {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16}; float hB[NN] = {16,15,14,13, 12,11,10,9, 8,7,6,5, 4,3,2,1}; float hC[N*N];
float *dA, *dB, *dC;
cudaMalloc(&dA, N*N*sizeof(float));
cudaMalloc(&dB, N*N*sizeof(float));
cudaMalloc(&dC, N*N*sizeof(float));
cudaMemcpy(dA, hA, N*N*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(dB, hB, N*N*sizeof(float), cudaMemcpyHostToDevice);
dim3 bs(2,2); // small block for example
dim3 gs((N+bs.x-1)/bs.x, (N+bs.y-1)/bs.y);
mm_naive<<<gs, bs>>>(dA, dB, dC, N);
cudaMemcpy(hC, dC, N*N*sizeof(float), cudaMemcpyDeviceToHost);
printf("C (naive) =\n");
for (int i=0;i<N;i++){
for (int j=0;j<N;j++) printf("%.1f ", hC[i*N+j]);
printf("\n");
}
cudaFree(dA); cudaFree(dB); cudaFree(dC);
return 0;
}
Sample output (exact): C (naive) = 80.0 70.0 60.0 50.0 240.0 214.0 188.0 162.0 400.0 358.0 316.0 274.0 560.0 502.0 444.0 386.0
Example 2 — Tiled (shared memory) matrix multiply, same inputs. Saves global memory reads by reusing tiles in shared memory.
Code (save as mm_tiled.cu):
#include <cstdio> #include <cuda_runtime.h>
#define N 4 #define TILE 2
global void mm_tiled(const float* A, const float* B, float* C, int n) { shared float sA[TILE][TILE]; shared float sB[TILE][TILE];
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
float sum = 0.0f;
for (int t = 0; t < (n + TILE - 1)/TILE; ++t) {
int aRow = row;
int aCol = t * TILE + threadIdx.x;
int bRow = t * TILE + threadIdx.y;
int bCol = col;
sA[threadIdx.y][threadIdx.x] = (aRow < n && aCol < n) ? A[aRow*n + aCol] : 0.0f;
sB[threadIdx.y][threadIdx.x] = (bRow < n && bCol < n) ? B[bRow*n + bCol] : 0.0f;
__syncthreads();
for (int k = 0; k < TILE; ++k) sum += sA[threadIdx.y][k] * sB[k][threadIdx.x];
__syncthreads();
}
if (row < n && col < n) C[row*n + col] = sum;
}
int main() { float hA[NN] = {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16}; float hB[NN] = {16,15,14,13, 12,11,10,9, 8,7,6,5, 4,3,2,1}; float hC[N*N];
float *dA, *dB, *dC;
cudaMalloc(&dA, N*N*sizeof(float));
cudaMalloc(&dB, N*N*sizeof(float));
cudaMalloc(&dC, N*N*sizeof(float));
cudaMemcpy(dA, hA, N*N*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(dB, hB, N*N*sizeof(float), cudaMemcpyHostToDevice);
dim3 bs(TILE, TILE);
dim3 gs((N+bs.x-1)/bs.x, (N+bs.y-1)/bs.y);
mm_tiled<<<gs, bs>>>(dA, dB, dC, N);
cudaMemcpy(hC, dC, N*N*sizeof(float), cudaMemcpyDeviceToHost);
printf("C (tiled) =\n");
for (int i=0;i<N;i++){
for (int j=0;j<N;j++) printf("%.1f ", hC[i*N+j]);
printf("\n");
}
cudaFree(dA); cudaFree(dB); cudaFree(dC);
return 0;
}
Sample output (exact): C (tiled) = 80.0 70.0 60.0 50.0 240.0 214.0 188.0 162.0 400.0 358.0 316.0 274.0 560.0 502.0 444.0 386.0
Notes on the examples: both programs produce identical C; the tiled version reduces global memory reads for larger N and therefore usually runs faster on real hardware. These example codes are minimal and meant for clarity.
Common mistakes
- Assuming warpSize is always 32 (it is usually 32 on NVIDIA but verify for your GPU).
- Not coalescing global memory accesses: using strided accesses where each thread reads separated addresses hurts bandwidth.
- Causing shared-memory bank conflicts by indexing shared arrays poorly (e.g., using [threadIdx.x][k] may conflict depending on bank mapping).
- Excessive register use leading to register spilling (to local memory, which is in global memory) and huge slowdowns.
- Not checking CUDA errors (e.g., missing cudaGetLastError() after kernel launch) so failures go unnoticed.
For your exam
Question types you will see:
- Definitions: explain warp divergence, occupancy, tiling, coalescing.
- Short notes: explain roofline model, how shared memory speeds up matrix multiply.
- Derivations: show why P = min(P_peak, B_mem·I) and draw roofline, compute ridge point I_ridge = P_peak / B_mem.
- Numericals: given P_peak and B_mem and kernel FLOPs and bytes transferred, compute expected performance using roofline.
- Programs/diagrams: draw tiled matrix multiply, write kernel pseudo-code, or explain bank conflict patterns.
What a full-marks answer includes:
- Precise definitions with assumptions (e.g., warp size assumed), diagrams when asked, step-by-step derivations for formulas, and discussion of trade-offs (e.g., more shared memory reduces global traffic but may reduce occupancy).
Quick check
- What is memory coalescing?
- Give the roofline performance formula.
- Why can increasing per-thread register usage reduce overall throughput?
Answers: 1) Arranging global memory accesses so consecutive threads access consecutive addresses, producing wide aligned transactions; 2) P = min(P_peak, B_mem · I) where I = FLOPs/byte; 3) More registers per thread can reduce active warps per SM (lower occupancy), reducing the GPU's ability to hide latency and thus lowering throughput.
Note on certainty: I assume warp size = 32 and common GPU shared-memory bank layouts; exact hardware limits (max threads/SM, registers/SM, shared memory per SM, roofline device numbers) vary with GPU model — verify on your GPU via cudaGetDeviceProperties and vendor documentation.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?