CUDA Atomic Histogram
Problem Statement
Build a histogram of values in [0, 1) into nbins bins using atomic adds. Each thread computes its bin index and does cuda.atomic.add(hist, b, 1).
Background
Many threads land in the same bin, so the increment must be atomic. Compute the bin as int(x[i] * nbins), clamped into [0, nbins-1], then atomically bump that counter.
Your Task
Implement hist_kernel and run(n=4096, nbins=10) returning whether the GPU histogram matches np.bincount.
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 = 4096, nbins = 10
True
- The input values
n = 4096andnbins = 10are used to allocate an array ofnrandom values between 0 and 1, and a histogram array of sizenbins. - Each thread in the
hist_kernelcomputes its bin index as , where is the value in the input array. - The threads then perform an atomic add operation on the corresponding bin in the histogram array using
cuda.atomic.add(hist, b, 1), effectively counting the number of values that fall into each bin. - The resulting histogram is compared to a reference histogram computed using
np.bincount, and the function returnsTrueif the two histograms are close (i.e.,np.allclose(gpu_result, reference)), indicating that the GPU histogram matches the expected result.
Constraints
- b = int(x[i] * nbins), clamped to [0, nbins-1]
- cuda.atomic.add(hist, b, 1) on an int32 histogram
- Inputs are in [0, 1)