L2 Intermediate · Module 4: CUDA programming fundamentals

4.2Thread, block and grid indexing

Every thread needs to know which piece of data is its own. CUDA arranges threads into blocks and blocks into a grid, in up to three dimensions, and one line of arithmetic turns those coordinates into an array index.

GPU required (Colab or a rented GPU)✦ Interactive~20 min

By the end you will be able to

  • ✓Compute a thread's global index in 1D and 2D launches
  • ✓Size a grid with round-up division and guard the tail
  • ✓Write a grid-stride loop that handles any problem size
  • ✓Map threads to a row-major matrix so that warps read adjacent memory

A launch creates a grid of blocks, each a group of threads (4.1). Inside the kernel, four built-in variables describe where a thread sits:

VariableMeaningType
threadIdxthis thread’s position inside its blockuint3 (x, y, z)
blockIdxthis block’s position inside the griduint3
blockDimthreads per block in each dimensiondim3
gridDimblocks per grid in each dimensiondim3

The 1D formula

i=blockIdx.x×blockDim.x+threadIdx.xi = \texttt{blockIdx.x} \times \texttt{blockDim.x} + \texttt{threadIdx.x}

Block 0 covers indices 0…blockDim−10 \dots \texttt{blockDim}-1, block 1 the next stretch, and so on. To cover nn elements you need ⌈n/blockDim⌉\lceil n / \texttt{blockDim} \rceil blocks, which is usually written (n + threads - 1) / threads. The last block is usually only partly needed, so every kernel guards with if (i < n).

blockDim.x

grid: 3 blocks × 8 threads = 24 threads (click one)

block 0

block 1

block 2

array x[0 … 21]

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
i = blockIdx.x × blockDim.x + threadIdx.x = 1 × 8 + 3 = 11

This thread handles x[11].

fig. 4.2How thread coordinates become array indices. In 1D, click a thread or an element and change the block size and array length. In 2D, click any cell of the matrix to see its block, thread, row, column and linear index.

Grid-stride loops

Instead of launching one thread per element, you can launch a fixed grid (a few blocks per SM) and let each thread walk through the array:

labs/m04/4.2/indexing.cu
__global__ void scale(float* x, float s, int n) {
int stride = gridDim.x * blockDim.x; // total threads in the grid
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += stride)
x[i] *= s;
}

The same launch works for any nn, and each thread amortizes its setup over several elements. In the lab, 20,480 threads correctly cover 10 million elements.

Two dimensions

For matrices and images, 2D blocks are more natural. With a row-major matrix (element (r,c)(r, c) at r * cols + c):

int col = blockIdx.x * blockDim.x + threadIdx.x; // x -> columns
int row = blockIdx.y * blockDim.y + threadIdx.y; // y -> rows
if (row < rows && col < cols) c[row * cols + col] = a[row * cols + col] + b[row * cols + col];

Choosing a block size

  • Make it a multiple of 32 (the warp size), or the last warp in each block runs partly empty.
  • 128–256 threads is a good default. It gives the scheduler several warps per block without hitting resource limits (2.5).
  • The hard limits: 1,024 threads per block; grid up to 231−12^{31}-1 blocks in x and 65,535 in y and z.

In LLM kernels, the grid usually mirrors the data: one block per token row for RMSNorm, a grid of (heads × batch) blocks for decode attention, a 2D grid of output tiles for a matmul.

Lab: indexing in practice 🔴

Terminal window
cd labs/m04/4.2 && nvcc -O2 -arch=native indexing.cu -o indexing && ./indexing
output (excerpt)
1) i = blockIdx.x * blockDim.x + threadIdx.x (3 blocks x 4 threads)
i= 0 <- block 0, thread 0
...
i= 4 <- block 1, thread 0
...
i=11 <- block 2, thread 3
2) grid-stride: 20480 threads covered 10000000 elements: PASS
3) 2D: grid (157, 375) of blocks (32, 8) = 15072000 threads for 15000000 elements: PASS

Sources

Check your understanding

0 / 4 answered
  1. 1.blockDim.x = 128. What is the global index of thread 5 in block 3?

  2. 2.How many 256-thread blocks do you need for n = 1,000 elements?

  3. 3.What is the advantage of a grid-stride loop?

  4. 4.For a row-major matrix, which dimension should threadIdx.x map to?