CUDA Grid-Stride Loop
Problem Statement
Copy a 1D array using a grid-stride loop so the kernel is correct even when there are fewer total threads than elements: out = x.
Background
A grid-stride loop lets each thread process multiple elements, stepping by the total number of threads (gridDim.x * blockDim.x). This decouples the launch configuration from the data size — the same kernel works for any n.
Your Task
Implement copy_stride_kernel and run(n=4096) (launched with deliberately few blocks) that returns whether the copy is exact.
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 (launched with 8 blocks x 128 threads)
True
- Input:
n = 4096is the length of a random float32 array , and the launch has 8 blocks of 128 threads, so only threads exist for elements. - Thread of block has global index , from to . The stride is the total thread count, .
- Thread handles the indices while they stay below . For example thread copies elements ; the next candidate, , is past the end, so it stops.
- Every index belongs to exactly one thread, , so all elements are written once, per thread.
- Output:
True, because for every . Copying does no arithmetic, so values match exactly. - Notice the uneven cases in the tests: for , threads to copy elements and the rest copy ; for , threads to copy nothing.
Constraints
- start = cuda.grid(1); stride = cuda.gridDim.x * cuda.blockDim.x
- Loop i from start to n stepping by stride
- Must work when total threads < n