CUDA Clamp Kernel
Problem Statement
Clamp every element into a range: out = min(max(x, lo), hi) with runtime scalars lo and hi.
Background
Two conditionals in sequence bound the value from below and above. Clamping is used to bound activations, gradients, or pixel values.
Your Task
Implement clamp_kernel and run(n=1024, lo=-0.5, hi=0.5) comparing to np.clip(x, lo, hi).
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
n = 1024, lo = -0.5, hi = 0.5
True
- The input values
n = 1024,lo = -0.5, andhi = 0.5are used to generate an arrayxof lengthnand clamp its elements into the range . - The
clamp_kernelfunction is applied toxusing CUDA, which applies the transformation to each element. - A reference solution is computed using
np.clip(x, -0.5, 0.5), which also clampsxinto the range . - The final output is
Truebecause the result from the CUDA kernel matches the reference solution, as verified bynp.allclose(gpu_result, reference).
Constraints
- Bound below by lo then above by hi
- lo and hi are runtime scalars
- Bounds-check the global index