CUDA 2D Grid Matrix Scale
Problem Statement
Scale a 2D matrix by a runtime scalar using a 2D launch grid: out[i, j] = a[i, j] * scale.
Background
cuda.grid(2) returns a pair (i, j) — the row and column this thread owns. Launch with 2D threadsperblock (e.g. (16, 16)) and a 2D blockspergrid covering both dimensions.
Your Task
Implement scale2d_kernel and run(M=64, N=48, scale=3.0) returning whether the result matches a * scale.
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
M = 64, N = 48, scale = 3.0
True
- The input values are , , and , representing the dimensions of the 2D matrix and the scaling factor.
- A 2D launch grid is created with a suitable number of blocks and threads per block to cover the entire matrix, allowing each thread to calculate .
- The
scale2d_kernelfunction is launched on the GPU, performing the scaling operation on each element of the input matrix using the given factor: . - The resulting scaled matrix is compared to the reference solution using
np.allclose, checking if the GPU result matches the expected result within a tolerance, yielding the outputTrueif the results match.
Constraints
- i, j = cuda.grid(2)
- Guard with if i < a.shape[0] and j < a.shape[1]
- Launch with a 2D block and 2D grid