v9.1.1
Menu

CUDA Host-to-Device Roundtrip

easyFREEMemory & Data MovementCUDA Basics with Numba

Problem Statement

Square every element on the GPU: out = x * x. The point is the full memory roundtrip — copy the input host array to the device, compute, then copy the result back.

Background

cuda.to_device(host_array) allocates device memory and copies the data up; device_array.copy_to_host() brings it back. The kernel only ever touches device memory.

Your Task

Implement square_kernel and run(n=1024) returning whether the device result matches x * x.

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 used to create a host array of size 1024, which is then copied to the device using cuda.to_device().
  • The square_kernel function is launched on the GPU, which squares every element in the device array: out=x∗xout = x * x.
  • The result is then copied back to the host using device_array.copy_to_host() and compared to the reference result, which is also obtained by squaring the original host array: reference=x∗xreference = x * x.
  • The comparison is done using np.allclose(), which checks if the two arrays are element-wise equal within a tolerance, resulting in the output True if they match.

Constraints

  • Use cuda.to_device for the input and copy_to_host for the output
  • out[i] = x[i] * x[i]
  • Bounds-check the global index

Learn this in

More from CUDA Basics with Numba

solution.py

Test results

Sign in to run your code against the test cases.