v9.1.1
Menu

CUDA Bounds-Checked Increment

easyPROCUDA Execution ModelCUDA Basics with Numba

Problem Statement

Add one to every element of a 1D array, out = x + 1, with a length that is not a multiple of the block size.

Background

When n isn't a multiple of blockDim.x, the last block has threads whose global index runs past the end of the array. The if i < n guard is what stops those threads from writing out of bounds.

Your Task

Implement inc_kernel and run(n=1000) (deliberately non-power-of-two) returning whether the result 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 = 1000
Output
True
Reasoning
  • The input n = 1000 is the array length. The array xx holds 10001000 random float32 values, and the expected result is outi=xi+1\text{out}_i = x_i + 1 for every ii from 00 to 999999.
  • With 256256 threads per block, covering 10001000 elements needs ⌈1000/256⌉=4\lceil 1000 / 256 \rceil = 4 blocks, which is 4×256=10244 \times 256 = 1024 threads in total.
  • Thread tt of block bb owns global index i=256 b+ti = 256\,b + t. Blocks 00 to 22 cover indices 00 to 767767; block 33 covers 768768 to 10231023, and only 768768 to 999999 (232 threads) land inside the array.
  • The remaining 1024−1000=241024 - 1000 = 24 threads have i≥ni \ge n and must write nothing; otherwise they would touch memory past the end of the output.
  • When every valid element equals xi+1x_i + 1 within a tolerance of 10−510^{-5}, the result is True.
  • Notice how the size of the idle tail changes with nn: for n=1n = 1 it is 255255 threads, for n=4095n = 4095 it is just 11.

Constraints

  • out[i] = x[i] + 1.0
  • The if i < x.size guard must protect the tail block
  • n is not a multiple of the block size

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.