/* Copyright (c) 2025 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define HIP_ENABLE_WARP_SYNC_BUILTINS #define HIP_ENABLE_EXTRA_WARP_SYNC_TYPES #include "warp_common.hh" #include #include #include #include #include #include #include #include #include #include #include /** * @addtogroup __reduce_op_sync __reduce_op_sync * @{ * @ingroup WarpSyncPerformance * __reduce_op_sync(MaskT mask, T val) * Reduces the val as per the lanes described in mask and calculates the * aggregated result */ static constexpr int kBlockDim = 1024; template struct AtomicAddOp { __device__ T operator()(T* lhs, const T& rhs) { return atomicAdd(lhs, rhs); } }; template struct AtomicMinOp { __device__ T operator()(T* lhs, const T& rhs) { return atomicMin(lhs, rhs); } }; template struct AtomicMaxOp { __device__ T operator()(T* lhs, const T& rhs) { return atomicMax(lhs, rhs); } }; template struct AtomicAndOp { __device__ T operator()(T* lhs, const T& rhs) { return atomicAnd(lhs, rhs); } }; template struct AtomicOrOp { __device__ T operator()(T* lhs, const T& rhs) { return atomicOr(lhs, rhs); } }; template struct AtomicXorOp { __device__ T operator()(T* lhs, const T& rhs) { return atomicXor(lhs, rhs); } }; // uses atomics to reduce the whole warp; depending on the mask our reduce should be faster // @output to store the result, one per warp // @numItems must be a multiple of warpSize template class Op> __global__ void reduceAllAtomics(T* __restrict__ output, const T* __restrict__ input, unsigned long long mask) { int idx = threadIdx.x + blockIdx.x * kBlockDim; extern __shared__ uint8_t shared_mem[]; T* result = reinterpret_cast(shared_mem); // one per warp Op op; int numWarp = threadIdx.x / warpSize; // initialize result[numWarp] to the "identity" element for Op if constexpr (std::is_same, AtomicMinOp>::value) result[numWarp] = std::numeric_limits::max(); else if constexpr (std::is_same, AtomicMaxOp>::value) result[numWarp] = std::numeric_limits::lowest(); else if constexpr (std::is_same, AtomicAndOp>::value) result[numWarp] = 1; else result[numWarp] = 0; __syncthreads(); if (mask & (1ul << __ockl_lane_u32())) op(&result[numWarp], input[idx]); __syncthreads(); if (__ockl_lane_u32() == 0) output[idx / warpSize] = result[numWarp]; } template class Op> __global__ void reduceOpSync(T* __restrict__ output, const T* __restrict__ input, unsigned long long mask) { int idx = threadIdx.x + blockIdx.x * kBlockDim; T result; if (mask & (1ul << __ockl_lane_u32())) { if constexpr (std::is_same, std::plus>::value) result = __reduce_add_sync(mask, input[idx]); else if constexpr (std::is_same, MinOp>::value) result = __reduce_min_sync(mask, input[idx]); else if constexpr (std::is_same, MaxOp>::value) result = __reduce_max_sync(mask, input[idx]); else if constexpr (std::is_same, std::logical_and>::value) result = __reduce_and_sync(mask, input[idx]); else if constexpr (std::is_same, std::logical_or>::value) result = __reduce_or_sync(mask, input[idx]); else if constexpr (std::is_same, XorOp>::value) result = __reduce_xor_sync(mask, input[idx]); else static_assert(std::is_void::value, "Unsupported operator"); if (__ockl_activelane_u32() == 0) output[idx / warpSize] = result; } } template class Op> class AtomicBenchmark : public Benchmark> { public: void operator()(T* output, const T* input, int numItems, unsigned long long mask) { dim3 blockDim = { kBlockDim }; dim3 gridDim = { static_cast(std::ceil(numItems / static_cast(blockDim.x))) }; hipDeviceProp_t props; HIP_CHECK(hipGetDeviceProperties(&props, 0)); int warpSize = props.warpSize; int numWarpsPerBlock = kBlockDim / warpSize; size_t sharedSize = numWarpsPerBlock * sizeof(T); TIMED_SECTION(kTimerTypeEvent) { if constexpr (std::is_same, std::plus>::value) reduceAllAtomics<<>>(output, input, mask); else if constexpr (std::is_same, MinOp>::value) reduceAllAtomics<<>>(output, input, mask); else if constexpr (std::is_same, MaxOp>::value) reduceAllAtomics<<>>(output, input, mask); else if constexpr (std::is_same, std::logical_and>::value) reduceAllAtomics<<>>(output, input, mask); else if constexpr (std::is_same, std::logical_or>::value) reduceAllAtomics<<>>(output, input, mask); else if constexpr (std::is_same, XorOp>::value) reduceAllAtomics<<>>(output, input, mask); else static_assert(std::is_void::value, "Unsupported operator"); HIP_CHECK(hipDeviceSynchronize()); } } }; template class Op> class ReduceSyncBenchmark : public Benchmark> { public: void operator()(T* output, T* input, int numItems, unsigned long long mask) { dim3 blockDim = { kBlockDim }; dim3 gridDim = { static_cast(std::ceil(numItems / static_cast(blockDim.x))) }; TIMED_SECTION(kTimerTypeEvent) { reduceOpSync<<>>(output, input, mask); HIP_CHECK(hipDeviceSynchronize()); } } }; template class Op> void checkResults(T* d_atomicsResult, T* d_reduceResult, size_t numBytes, unsigned long long mask) { using namespace Catch::Matchers; LinearAllocGuard outputAtomic(LinearAllocs::malloc, numBytes); LinearAllocGuard outputReduce(LinearAllocs::malloc, numBytes); bool memcmpResult = std::memcmp(outputAtomic.ptr(), outputReduce.ptr(), numBytes); assert(numBytes % sizeof(T) == 0 && "numBytes needs to be a multiple of sizeof(T)"); HIP_CHECK(hipMemcpy(outputAtomic.ptr(), d_atomicsResult, numBytes, hipMemcpyDeviceToHost)); HIP_CHECK(hipMemcpy(outputReduce.ptr(), d_reduceResult, numBytes, hipMemcpyDeviceToHost)); if (memcmpResult) { for (int i = 0; i < numBytes / sizeof(T); i++) { auto& atomicResult = outputAtomic.ptr()[i]; auto& reduceResult = outputReduce.ptr()[i]; if constexpr (std::is_integral::value || std::is_same, MinOp>::value || std::is_same, MaxOp>::value) // for integral types or min/max the result should match exactly REQUIRE(atomicResult == reduceResult); else // floating point types or operations which are lossy in terms of precision REQUIRE_THAT(reduceResult, WithinRel(atomicResult)); } } } template class Op> struct IsLogicalOp { static constexpr bool value = false; }; template struct IsLogicalOp { static constexpr bool value = true; }; template struct IsLogicalOp { static constexpr bool value = true; }; template struct IsLogicalOp { static constexpr bool value = true; }; // Neither long long or fp16 have atomic operations. In those cases // we only benchmark reduce sync operations, we cannot compare with native atomics template struct HasAtomicOps { static constexpr bool value = true; }; template <> struct HasAtomicOps { static constexpr bool value = false; }; template <> struct HasAtomicOps { static constexpr bool value = false; }; template class Op> struct ReduceBenchmark { void Run() { static constexpr int numMasks = 6; using distribution = typename DistributionType::type; ReduceSyncBenchmark benchmarkReduce; uint64_t inputSize = cmd_options.reduce_input_size * 1_MB; int numItems = inputSize / sizeof(T); int wavefrontSize = getWarpSize(); int outputNumBytes = inputSize / wavefrontSize; LinearAllocGuard input(LinearAllocs::malloc, inputSize); LinearAllocGuard d_input(LinearAllocs::hipMalloc, inputSize); LinearAllocGuard d_outputsAtomic[numMasks]; LinearAllocGuard d_outputsReduce[numMasks]; LinearAllocGuard* d_outputAtomic = &d_outputsAtomic[0]; LinearAllocGuard* d_outputReduce = &d_outputsReduce[0]; std::mt19937_64 gen(123); distribution dist; int halfWaveSize = wavefrontSize / 2; unsigned long long halfBitsOn = (1ul << (wavefrontSize / 2)) - 1; unsigned long long fullMask = -1ul, halfHighBitsOn = halfBitsOn << halfWaveSize, high16BitsOn = halfBitsOn << (wavefrontSize - 16), high8BitsOn = halfBitsOn << (wavefrontSize - 8), high4BitsOn = halfBitsOn << (wavefrontSize - 4), allButOne = -1 & ~1; const char* typeStr = typeToString(); const char* opStr = opToString(); std::map masks; std::pair masksPairs[] = { { "full mask", fullMask }, { "high order 32 bits on", halfHighBitsOn }, { "high order 16 bits on", high16BitsOn }, { "high order 8 bits on", high8BitsOn }, { "high order 4 bits on", high4BitsOn }, { "all but one", allButOne } }; int pos = 0, numMask = 0; for (auto& mask : masksPairs) { // don't use 'halfHighBitsOn' on warp size 32; it's the same as high16BitsOn if (wavefrontSize != 32 || mask.second != halfHighBitsOn) { masks.emplace(std::to_string(numMask) + " - " + mask.first, wavefrontSize == 64? mask.second : mask.second & 0xFFFFFFFF); numMask++; } } // avoid generating values different than 1 or 0 for logical operators; // otherwise the atomic version of the kernels would produce different results as // atomicAnd/Or() are bitwise operations, not logical if constexpr (IsLogicalOp::value) dist = distribution(0, 1); for (int i = 0; i < numItems; i++) { input.ptr()[i] = dist(gen); } for (auto& buffer : d_outputsAtomic) { buffer = LinearAllocGuard(LinearAllocs::hipMalloc, outputNumBytes); } for (auto& buffer : d_outputsReduce) { buffer = LinearAllocGuard(LinearAllocs::hipMalloc, outputNumBytes); } HIP_CHECK(hipMemcpy(d_input.ptr(), input.ptr(), inputSize, hipMemcpyHostToDevice)); if constexpr (HasAtomicOps::value) { AtomicBenchmark benchmarkAtomics; printf("\n--- atomics %s %s---\n", opStr, typeStr); for (auto& mask : masks) { printf("%s %llx\n", mask.first.c_str(), mask.second); benchmarkAtomics.Run((d_outputAtomic++)->ptr(), d_input.ptr(), numItems, mask.second); } } printf("\n--- reduce %s %s--- \n", opStr, typeStr); for (const auto& mask : masks) { printf("%s %llx\n", mask.first.c_str(), mask.second); benchmarkReduce.Run((d_outputReduce++)->ptr(), d_input.ptr(), numItems, mask.second); } printf("\n"); if constexpr (HasAtomicOps::value) { printf("Checking results...\n"); for (const auto& mask : masks) { checkResults(d_outputsAtomic[pos].ptr(), d_outputsReduce[pos].ptr(), outputNumBytes, mask.second); pos++; } } } }; TEMPLATE_TEST_CASE("Performance_Reduce_Sync_Add", "", int, unsigned int, unsigned long long, long long, float, half, double) { ReduceBenchmark benchmark; benchmark.Run(); } TEMPLATE_TEST_CASE("Performance_Reduce_Sync_Min", "", int, unsigned int, unsigned long long, long long, float, half, double) { ReduceBenchmark benchmark; benchmark.Run(); } TEMPLATE_TEST_CASE("Performance_Reduce_Sync_Max", "", int, unsigned int, unsigned long long, long long, float, half, double) { ReduceBenchmark benchmark; benchmark.Run(); } TEMPLATE_TEST_CASE("Performance_Reduce_Sync_And", "", int, unsigned int, unsigned long long, long long) { ReduceBenchmark benchmark; benchmark.Run(); } TEMPLATE_TEST_CASE("Performance_Reduce_Sync_Or", "", int, unsigned int, unsigned long long, long long) { ReduceBenchmark benchmark; benchmark.Run(); } TEMPLATE_TEST_CASE("Performance_Reduce_Sync_Xor", "", int, unsigned int, unsigned long long, long long) { ReduceBenchmark benchmark; benchmark.Run(); }