CUDA Shared-Memory 1D Stencil
Problem Statement
Compute a 3-point stencil along a 1D array (length ≤ block size): for interior points out[i] = x[i-1] + x[i] + x[i+1], with the two endpoints set to 0. Use shared memory so each value is read from DRAM only once.
Background
Neighboring threads need overlapping inputs. Stage the array in shared memory and cuda.syncthreads(); then each thread reads its neighbors s[t-1] and s[t+1] straight from shared memory instead of going back to global memory.
Your Task
Implement stencil_kernel (single block) and run(n=512) comparing to a NumPy reference. Assume n ≤ TPB.
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 = 512
True
- The input
n = 512is used to allocate an array of length 512 and initialize it with some values. - The
stencil_kernelfunction is launched with a single block, where each thread computes a 3-point stencil along the 1D array: for interior pointsout[i] = x[i-1] + x[i] + x[i+1], with the two endpoints set to0, using shared memory to minimize global memory access. - The result from the GPU is compared to a NumPy reference implementation using
np.allclose(gpu_result, reference), which checks if the two arrays are element-wise equal within a tolerance. - Since the GPU result matches the reference implementation, the function
run(n=512)returnsTrue, indicating that the GPU result is correct.
Constraints
- Stage x into shared memory, then cuda.syncthreads()
- Endpoints (t == 0 or t == n-1) -> 0.0
- Interior -> s[t-1] + s[t] + s[t+1]