Launch an elementwise kernel with the right grid size and bounds check
Why it matters Every CUDA or Triton kernel starts with this grid and bounds arithmetic, and the missing tail block is one of the most common GPU bugs.
A GPU kernel runs in blocks of block_size threads. To cover n elements you launch ceil(n / block_size) blocks, and threads whose global index is past the end must do nothing.
Write launch_axpy(x, y, alpha, block_size). Simulate the launch: grid = ceil(n / block_size) blocks; thread t of block b has global index i = b * block_size + t and, only if i < n, writes out[i] = alpha * x[i] + y[i]. Return (out as a float array, grid, idle) where idle is the number of launched threads that skipped work. For n = 0, grid is 0.
def launch_axpy(x, y, alpha, block_size)Example
x [1, 2, 3, 4, 5], y [10, 10, 10, 10, 10], alpha 2, block_size 4 gives ([12, 14, 16, 18, 20], 2, 3).
Understand the idea
Launching a kernel is like sending buses of fixed size to pick up a crowd. If 5 people wait and each bus holds 4, you need 2 buses, and the second bus runs with 3 empty seats. On a GPU, each bus is a block and each seat is a thread. Worked example: n = 5, block_size 4. grid = ceil(5 / 4) = 2, so 8 threads launch. Threads with global index 0 to 4 compute alpha x[i] + y[i]; indices 5, 6, 7 are idle. Rule: grid = (n + bs - 1) // bs, i = blockIdx x bs + threadIdx, and only i < n does work. Choosing block sizes that divide common tensor sizes keeps the idle tail small, but the bounds check must always be there.