PIXELBANKv9.1.0
Menu

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:

Input:
n = 4096
Output:
True
Reasoning:
  • The input n = 4096 is used to create a 1D array x of length nn and initialize it with some values.
  • The block_sum_kernel function is launched, which performs a shared-memory tree reduction on the array x in 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_result is compared to the reference value calculated using x.sum() and the result of this comparison, np.allclose(gpu_result, reference), is returned as a boolean value, which in this case is True.

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]
๐Ÿ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
CUDA Shared-Memory Block Reduction - Hard | PixelBank