Hi,
In my case i have a large array. The block size is small compared to the dimensions of the array. Shared memory didn’t work as the kernel crashes when i increase the block size. I have a scalar variable in the kernel. I want to find the thread which has the maximum value of the variable. How can i do this?
Thanks,
This is a reduction, specifically a max reduce. Use a library for that like thrust or cub. Here is a related topic in CUDA C++. But my suggestion is still to use a library routine.
I could use the library routine to find the max. But i dont have the input to the max routine in an array. Rather i have a scalar variable inside the kernel. Will something like this work.
@cuda.jit
def my_kernel(result):
a=random()
cuda.syncthreads()
If a>result[0]:
result[0]=a
No, that won’t work as-is. CUDA doesn’t automatically sort out simultaneous access from multiple threads to the result[0] location for you.
However, subject to the data type you are using for a, you may be able to use cuda.atomic.max(). The supported types for this are 32 and 64 bit signed integers, unsigned integers, and floating-point types. See here. An example is given there, showing your use-case: how to store the maximum across variables from each thread into result[0]. Where they are using values[i] you can use a.
Thank you for your support.
If you use cuda.atomic.max() directly from each thread, it could be a performance limiter. It may or may not matter for your case. If you believe it to be a performance limiter, then an intermediate optimization you could make would be to do a threadblock level max reduction, and at the end of the threadblock activity, when you have a single maximum value for all the data processed by that threadblock, then do an atomic to a global location using that value.
The general idea is covered in unit 5 of this online training series albeit in CUDA C++. However the translation to numba CUDA should be fairly mechanical. Otherwise, with a bit of searching you can find examples of threadblock level reductions in numba CUDA that you can adapt. For example this question/answer shows a numba block-level reduction.
Numba also has reduce operators, however I think these are primarily useful as a replacement for e.g. a thrust or cub device level reduction, not exactly what you wanted.
Ok. At this point i may not be in a position for maximizing performance. I just want to get things done. I will definitely try your solution when i want max performance. Once again thank you for your support.