Triton Clamp Kernel
Problem Statement
Implement a clamp kernel: out = min(max(x, lo), hi) with runtime scalars lo and hi.
Background
Compose tl.maximum and tl.minimum. Clamping bounds activations or gradients.
Your Task
Implement clamp_kernel and run(n=1024, lo=-0.5, hi=0.5) comparing to torch.clamp.
How it is tested
Your solution must define a top-level function run(...) that allocates inputs on the GPU, launches your Triton kernel, and returns a boolean from torch.allclose(triton_out, torch_reference, ...). The grader prints run(...); the expected output is True.
Example
n = 1024, lo = -0.5, hi = 0.5
True
- The input values are , , and , which represent the number of elements to clamp and the lower and upper bounds, respectively.
- The
clamp_kernelfunction is applied to an array of elements, effectively computing for each element . - The result from the
clamp_kernelfunction is then compared to the result fromtorch.clampusingtorch.allclose, which checks if the two arrays are element-wise equal within a tolerance. - The comparison yields
Trueif the results are close enough, indicating that the customclamp_kernelimplementation matches the PyTorch reference implementation.
Constraints
- out = tl.minimum(tl.maximum(x, lo), hi)
- lo, hi are runtime scalars