CUDA Shared-Memory Block Reverse
Problem Statement
Reverse a 1D array (length ≤ block size) using shared memory: out[i] = x[n - 1 - i]. Stage the whole array in shared memory, synchronize, then read it back reversed.
Background
cuda.shared.array(SIZE, dtype) allocates fast on-chip memory shared by all threads in a block. The pattern is: every thread copies one element into shared memory, cuda.syncthreads() so all writes are visible, then each thread reads the mirrored position.
Your Task
Implement reverse_kernel (single block of TPB threads) and run(n=256) comparing to x[::-1]. 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 = 256
True
- The input array
xof lengthn = 256is allocated and copied to the GPU. - The
reverse_kernelfunction is launched with a single block ofTPBthreads, where each thread copies one element ofxinto shared memory, and thencuda.syncthreads()is called to ensure all writes are visible. - After synchronization, each thread reads the mirrored position from shared memory, effectively reversing the array, and stores it in the output array
out. - The
runfunction compares the reversed arrayoutfrom the GPU with the reference arrayx[::-1]usingnp.allclose, and returnsTrueif they are equal within a tolerance, which is the case for the given input.
Constraints
- s = cuda.shared.array(TPB, dtype=float32); TPB is a module-level constant
- Load s[t] = x[t], then cuda.syncthreads(), then out[t] = s[n - 1 - t]
- Single block; guard threads with if t < n