v9.1.1
Menu

CUDA Vector Addition Kernel

easyFREECUDA Execution ModelCUDA Basics with Numba

Problem Statement

Write a CUDA kernel that adds two 1D float arrays element-wise: c = a + b.

Background

Every CUDA thread computes its own global index. With Numba you get it from cuda.grid(1) (equivalent to blockIdx.x * blockDim.x + threadIdx.x). One thread handles one element, so the launch needs ceil(n / threads) blocks.

Your Task

Implement add_kernel and a run(n=1024) that launches it over a 1D grid and returns whether the result matches a + b.

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 = 1024
Output
True
Reasoning
  • The input n = 1024 is the length of both vectors aa and bb (1024 random 32-bit floats each). The target is ci=ai+bic_i = a_i + b_i for every ii from 00 to 10231023.
  • With 128 threads per block, the grid needs ⌈1024/128⌉=8\lceil 1024 / 128 \rceil = 8 blocks, giving exactly 8×128=10248 \times 128 = 1024 threads, one per element.
  • Each thread's global index is block index ×\times block size ++ thread index. Thread 5 of block 3 gets i=3⋅128+5=389i = 3 \cdot 128 + 5 = 389, so it alone computes c389=a389+b389c_{389} = a_{389} + b_{389}.
  • Notice the test with n=1000n = 1000: it still needs ⌈1000/128⌉=8\lceil 1000/128 \rceil = 8 blocks, so 1024 threads run and indices 10001000 to 10231023 fall past the end of the arrays. Those 24 threads must write nothing.
  • The output True means all nn GPU sums agree with the same sums computed on the CPU, within an absolute tolerance of 10−510^{-5}. A skipped or misplaced element would mismatch and the check would fail.

Constraints

  • Use @cuda.jit and i = cuda.grid(1)
  • Guard with if i < a.size before writing
  • blocks = (n + threads - 1) // threads

Learn this in

More from CUDA Basics with Numba

solution.py

Test results

Sign in to run your code against the test cases.