v9.1.1
Menu

CUDA Shared-Memory 1D Stencil

hardPROShared Memory & TilingCUDA Basics with Numba

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

Input
n = 512
Output
True
Reasoning
  • The input n = 512 is used to allocate an array of length 512 and initialize it with some values.
  • The stencil_kernel function is launched with a single block, where each thread computes a 3-point stencil along the 1D array: for interior points out[i] = x[i-1] + x[i] + x[i+1], with the two endpoints set to 0, 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) returns True, 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]

Learn this in

More from CUDA Basics with Numba

PRO

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

Sign in to run your code against the test cases.