v9.1.1
Menu

CUDA Grid-Stride Loop

mediumPROCUDA Execution ModelCUDA Basics with Numba

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

Input
n = 4096 (launched with 8 blocks x 128 threads)
Output
True
Reasoning
  • Input: n = 4096 is the length of a random float32 array xx, and the launch has 8 blocks of 128 threads, so only 8×128=10248 \times 128 = 1024 threads exist for 40964096 elements.
  • Thread tt of block bb has global index g=128b+tg = 128b + t, from 00 to 10231023. The stride is the total thread count, S=1024S = 1024.
  • Thread gg handles the indices g,g+S,g+2S,…g, g + S, g + 2S, \dots while they stay below nn. For example thread 55 copies elements 5,1029,2053,30775, 1029, 2053, 3077; the next candidate, 41014101, is past the end, so it stops.
  • Every index ii belongs to exactly one thread, g=i mod 1024g = i \bmod 1024, so all 40964096 elements are written once, 44 per thread.
  • Output: True, because outi=xi\text{out}_i = x_i for every ii. Copying does no arithmetic, so values match exactly.
  • Notice the uneven cases in the tests: for n=100000=97⋅1024+672n = 100000 = 97 \cdot 1024 + 672, threads 00 to 671671 copy 9898 elements and the rest copy 9797; for n=1000n = 1000, threads 10001000 to 10231023 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

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.