CUDA Shared-Memory Block Reduction
Problem Statement
Sum each block's chunk of a 1D array into a per-block partial sum using a shared-memory tree reduction. The kernel outputs one value per block; the host adds the partials. Verify the total equals x.sum().
Background
Each thread loads one element into shared memory. Then halve the active range each step (stride = TPB//2, TPB//4, ...), adding s[t] += s[t + stride], with a cuda.syncthreads() between steps so every add sees the previous round. Thread 0 writes s[0] to out[blockIdx.x].
Your Task
Implement block_sum_kernel and run(n=4096) returning whether the summed partials match x.sum().
How it is tested
Your solution must define a top-level function run(...) that allocates the inputs, copies them to the GPU, launches your @cuda.jit kernel, and returns a Python bool from np.allclose(gpu_result, reference). The grader prints run(...); the expected output is True.
Example
n = 4096
True
- The input
n = 4096is used to create a 1D arrayxof length and initialize it with some values. - The
block_sum_kernelfunction is launched, which performs a shared-memory tree reduction on the arrayxin parallel across multiple blocks, with each block producing a partial sum. - The partial sums from each block are then summed on the host to produce the final
gpu_result. - The
gpu_resultis compared to thereferencevalue calculated usingx.sum()and the result of this comparison,np.allclose(gpu_result, reference), is returned as a boolean value, which in this case isTrue.
Constraints
- Load into shared memory (use 0.0 for out-of-range threads)
- Tree reduction: halve stride each step with cuda.syncthreads() between
- Thread 0 writes s[0] to out[cuda.blockIdx.x]