Count the work each thread does in a grid-stride loop
Why it matters Grid-stride loops are the standard pattern for kernels that must work for any tensor size with a launch tuned to the number of SMs.
A grid-stride loop lets a fixed-size launch handle any n: each thread starts at its global index and jumps by the total number of threads until it passes n.
Write grid_stride_counts(n, grid, block). There are T = grid * block threads. Thread t processes indices t, t + T, t + 2T, ... while they are below n. Return (counts, owner) where counts is an int array of length T with how many indices each thread processed, and owner is an int array of length n with the thread that processed each index.
def grid_stride_counts(n, grid, block)Example
n 10, grid 2, block 2 gives counts [3, 3, 2, 2] and owner [0, 1, 2, 3, 0, 1, 2, 3, 0, 1].
Understand the idea
Think of T workers standing in a row along a long shelf of n boxes. Each worker handles the box in front of them, then everybody steps T boxes to the right together and repeats. Because the workers stay side by side, each step touches one neat stretch of the shelf, which is what memory likes. Worked example: n = 10 and T = 4. Worker 0 handles boxes 0, 4, 8; worker 1 handles 1, 5, 9; workers 2 and 3 handle two boxes each. Rule: thread t handles i = t + k T for k = 0, 1, ... while i < n. With this loop the launch size can be chosen to fill the GPU once, for example a few blocks per SM, and the same kernel works for tiny and huge tensors.