Two new habits: index mapping and 2-D launch geometry
Vector add launched a 1-D grid. Matrix add launches a 2-D grid because the data is 2-D. The launch shape mirrors the data shape, and the indexing inside the kernel maps thread coordinates to data coordinates.
The mapping has two parts:
- Thread coords → data coords:
row = blockIdx.y * blockDim.y + threadIdx.y,col = blockIdx.x * blockDim.x + threadIdx.x. - Data coords → flat memory offset:
idx = row * ld + colfor row-major; reverse for column-major.
Block size choice: 16×16 = 256 threads is a robust default. It's a multiple of the warp size (32), gives the scheduler ~8 warps for latency hiding, and balances occupancy vs. register pressure. 32×32 = 1024 also works but can hit register limits in heavier kernels.