CUDA threads, blocks, grids and warps
How CUDA maps computation onto a hierarchy of threads, blocks and grids, and how warps (SIMT groups) affect performance and indexing.
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
GPU programs run thousands of lightweight threads in parallel. Understanding how CUDA groups threads into blocks and grids, and how hardware executes them in warps, is essential for writing correct kernels, computing each thread's data index, avoiding errors, and achieving good performance.
Key ideas
Start with the hardware and programming model building blocks.
Thread — a single CUDA execution context that runs a kernel function. It has per-thread registers and local memory. (Definition used everywhere below.)
Block — a group of threads that can cooperate by fast on-chip shared memory and can synchronise with __syncthreads(). Each block runs entirely on one streaming multiprocessor (SM) for its lifetime; different blocks may be scheduled on different SMs, but a block does not migrate between SMs. Blocks are independent: no ordering or guaranteed communication across blocks inside a single kernel launch except via global memory and subsequent kernel launches.
Grid — the collection of all blocks launched by a single kernel. A kernel launch defines its grid and block dimensions.
Thread index variables — CUDA provides built-in variables to identify threads: threadIdx (thread index within block), blockIdx (block index within grid), blockDim (size of block), gridDim (size of grid). Each of these can be 1D, 2D or 3D (dim3). Their .x/.y/.z components are 0-based: threadIdx.{x,y,z} ∈ [0, blockDim.{x,y,z}-1], blockIdx.{x,y,z} ∈ [0, gridDim.{x,y,z}-1].
Global thread index (1D case) — the formula to map each thread to a unique index in a linear data array is:
global_index = blockIdx.x * blockDim.x + threadIdx.x
Derivation (step-by-step exam style):
- Number threads within each block from 0 to blockDim.x - 1: this gives per-block ids = threadIdx.x.
- Number blocks from 0 to gridDim.x - 1. Each block is responsible for blockDim.x consecutive global thread slots.
- Block k starts at offset k * blockDim.x in linear space. Add per-block thread id: offset + threadIdx.x → blockIdx.x * blockDim.x + threadIdx.x.
2D/3D indexing — extend by treating row-major packing of blocks and threads. For 2D:
global_x = blockIdx.x * blockDim.x + threadIdx.x global_y = blockIdx.y * blockDim.y + threadIdx.y element index in row-major = global_y * width + global_x, where width = blockDim.x * gridDim.x when the grid exactly covers the array; otherwise use the array’s actual width
Draw for exam: draw a grid of blocks (label blockIdx.x, blockIdx.y). Inside one block draw a small grid of threads (label threadIdx.x, threadIdx.y). Mark one thread and show how you compute global_x and global_y and then the linear index.
Warp — a hardware scheduling unit of threads that execute the same instruction in lock-step (also called SIMD or SIMT group). On NVIDIA GPUs the warp size is 32 threads (common across modern architectures). In device code, prefer the built-in constant warpSize over hard-coding 32. Warps are formed from consecutive threads in a block in row-major order of (z, y, x) indices (i.e., threadIdx.x varies fastest, then y, then z), not solely by threadIdx.x. If threads within a warp branch differently, execution serialises and some threads are masked out — called warp divergence.
Scheduling and occupancy basics — a block is split into warps by the hardware; the number of resident warps and blocks per SM depends on resources (registers, shared memory, warp scheduler limits). Maximising occupancy can hide memory latency but is not always the best for performance; balance registers, shared memory and threads per block.
Important constraints and assumptions (often asked in exams):
- Threads in a block can use __syncthreads() to synchronise.
- No cross-block synchronisation or ordering is guaranteed inside one kernel launch.
- Kernel launch syntax: kernel<<<gridDim, blockDim>>>(arguments);
- CUDA provides 1D/2D/3D dim3 objects: dim3 grid(…); dim3 block(…);
- Hardware limits (query via cudaGetDeviceProperties): typical max threads per block is 1024 on modern NVIDIA GPUs; max dimensions for blocks and grids vary by compute capability.
Where to draw diagrams: for a mapping question draw (A) a grid of blocks (e.g. 2×2 blocks), label blockIdx coordinates; (B) within one block draw threads (e.g. 4×4) and label threadIdx; (C) show mapping to global coordinates and the formula used.
Formulas
global_index = blockIdx.x * blockDim.x + threadIdx.x — blockIdx.x: block index along x (no unit), blockDim.x: threads per block along x, threadIdx.x: thread index in block along x. Use when grid and blocks are 1D.
global_x = blockIdx.x * blockDim.x + threadIdx.x — x coordinate in 2D mapping.
global_y = blockIdx.y * blockDim.y + threadIdx.y — y coordinate in 2D mapping.
linear_index = global_y * (blockDim.x * gridDim.x) + global_x — row-major index for a 2D array with width = blockDim.x * gridDim.x.
kernel<<<gridDim, blockDim, sharedMemBytes, stream>>>(args) — kernel launch syntax. gridDim, blockDim can be dim3 or integers.
dim3 grid(GX, GY, GZ); dim3 block(BX, BY, BZ); — how to declare 3D launch dimensions.
int tid = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * threadIdx.z); int lane = tid & (warpSize - 1); — thread’s lane within a warp (works for 1D/2D/3D blocks; uses built-in warpSize).
Notes: blockDim.x * gridDim.x is the global width (number of threads across x). Units: counts of threads (dimensionless).
Worked examples
Example 1 — Vector add (1D mapping). Complete CUDA C++ program that runs on a CUDA-capable machine. This adds two float vectors and prints the result.
// vector_add.cu
#include <cstdio>
#include <cuda_runtime.h>
__global__ void vecAdd(const float* a, const float* b, float* c, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) c[i] = a[i] + b[i];
}
int main() {
const int n = 8;
float h_a[n] = {0,1,2,3,4,5,6,7};
float h_b[n] = {10,10,10,10,10,10,10,10};
float h_c[n];
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, n * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_b, h_b, n * sizeof(float), cudaMemcpyHostToDevice);
int threadsPerBlock = 4;
int blocks = (n + threadsPerBlock - 1) / threadsPerBlock;
vecAdd<<<blocks, threadsPerBlock>>>(d_a, d_b, d_c, n);
cudaMemcpy(h_c, d_c, n * sizeof(float), cudaMemcpyDeviceToHost);
printf("Result:\n");
for (int i = 0; i < n; ++i) printf("c[%d] = %0.1f\n", i, h_c[i]);
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
return 0;
}
Sample output (exact):
Result: c[0] = 10.0 c[1] = 11.0 c[2] = 12.0 c[3] = 13.0 c[4] = 14.0 c[5] = 15.0 c[6] = 16.0 c[7] = 17.0
Example 2 — 2D indexing (fill a small 4×4 matrix with its linear global index). This demonstrates 2D block and grid mapping.
// matrix_index.cu
#include <cstdio>
#include <cuda_runtime.h>
__global__ void fillIndices(int* out, int width, int height) {
int gx = blockIdx.x * blockDim.x + threadIdx.x;
int gy = blockIdx.y * blockDim.y + threadIdx.y;
if (gx < width && gy < height) {
int linear = gy * width + gx;
out[linear] = linear;
}
}
int main() {
const int width = 4, height = 4;
int h_out[width*height];
int* d_out;
cudaMalloc(&d_out, width*height*sizeof(int));
dim3 block(2,2);
dim3 grid((width+block.x-1)/block.x, (height+block.y-1)/block.y);
fillIndices<<<grid, block>>>(d_out, width, height);
cudaMemcpy(h_out, d_out, width*height*sizeof(int), cudaMemcpyDeviceToHost);
printf("Matrix (row-major linear indices):\n");
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) printf("%2d ", h_out[y*width + x]);
printf("\n");
}
cudaFree(d_out);
return 0;
}
Sample output (exact):
Matrix (row-major linear indices):
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Common mistakes
- Assuming threads in different blocks can use __syncthreads() to synchronise — they cannot.
- Ignoring warp divergence: placing branch conditions that differ per thread in the same warp can serialise execution and slow kernels.
- Choosing threadsPerBlock larger than hardware maximum or assuming it must be divisible by warp size — multiples of 32 often give better performance but divisibility is not required for correctness.
- Assuming warp size is 16 or 64 — modern NVIDIA GPUs use 32; this varies by vendor/architecture (verify). Avoid hard-coding unless you query device properties.
For your exam
Typical question types:
- Definitions: define thread, block, grid, warp, shared memory, threadIdx, blockIdx.
- Short notes: describe how to compute a global index for 1D and 2D; explain warps and divergence.
- Derivations: derive the global index formula and show how to map a 2D thread/block layout to a linear array index (draw labelled diagrams).
- Programming: write a CUDA kernel for vector addition or for filling a matrix with a computed value; include kernel launch parameters and bounds checks.
- Diagrams: draw a grid of blocks and threads inside a block and mark an example thread's indices and the computed global index.
What a full-marks answer includes:
- Correct precise definitions (bolded terms in your notes: thread, block, grid, warp).
- The indexing formula with clear derivation and a labelled diagram if asked.
- For programs: correct kernel, correct host calls (cudaMalloc, cudaMemcpy, kernel<<<>>>), bounds checks, and correct output formatting.
- Performance awareness: mention warp divergence and shared memory where relevant.
Quick check
- Write the formula for a 1D global thread index.
- True/False: __syncthreads() synchronises threads across all blocks in a grid.
- What is a warp and why does divergence hurt performance?
Answers: global_index = blockIdx.x * blockDim.x + threadIdx.x ; False ; A warp is a hardware group of threads (commonly 32 on NVIDIA) that execute instructions in lock-step; if threads in a warp take different branches execution serialises and some threads are masked, reducing parallel efficiency.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?