From 666a6176673a4945a33c7b98ea73b3866d5290d2 Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Thu, 15 Oct 2026 16:08:10 +0000 Subject: [PATCH 01/15] Optimize sum_rows_by_key kernel - load key once per row (one warp takes one row) - Use read-only cache __ldg - Avoid expensive % operator --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index dbe3f59b69..dea6592c05 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -12,7 +12,10 @@ #include #include +#include +#include #include +#include #define MAX_BLOCKS 65535u namespace raft { @@ -276,6 +279,10 @@ void sum_rows_by_key_large_nkeys_colmajor(const DataIteratorT d_A, d_sums); } +/** + * Large-nkeys reduction with one warp per row: the key and weight are loaded once per row and the + * warp's lanes add consecutive columns of the row into d_sums[key]. + */ template (blockIdx.x)); - IdxT j = gid % ncols; - IdxT i = gid / ncols; - if (i >= nrows) return; - IdxT l = static_cast(d_keys[i]); - SumsT val = d_A[j + lda * i]; - if (d_weights != nullptr) val *= d_weights[i]; - raft::myAtomicAdd(&d_sums[j + ncols * l], val); + // Plain pointers are read through the read-only cache; other iterators (e.g. a transform + // iterator converting the input type) are dereferenced as is. + constexpr bool kIsPlainPointer = + std::is_same_v || std::is_same_v; + const IdxT warp_id = (static_cast(blockIdx.x) * blockDim.x + threadIdx.x) / WarpSize; + const IdxT n_warps = static_cast(gridDim.x) * blockDim.x / WarpSize; + for (IdxT i = warp_id; i < nrows; i += n_warps) { + const auto key = static_cast(d_keys[i]); + const SumsT w = d_weights != nullptr ? static_cast(d_weights[i]) : SumsT(1); + for (IdxT j = laneId(); j < ncols; j += WarpSize) { + SumsT a; + if constexpr (kIsPlainPointer) { + a = __ldg(d_A + lda * i + j); + } else { + a = static_cast(d_A[lda * i + j]); + } + raft::myAtomicAdd(d_sums + ncols * key + j, a * w); + } + } } template (ceildiv(nrows * ncols, (IdxT)block_dim)); + constexpr uint32_t block_dim = 128; + constexpr uint32_t warps_per_block = block_dim / WarpSize; + // Keep gridDim.x within the launch limit; the kernel's grid-stride loop covers extra rows. + const auto grid_dim = static_cast( + std::min(ceildiv(nrows, warps_per_block), IdxT{1} << 30)); raft::launch_kernel(st, grid_dim, block_dim, From 7658a18baed56b38a114ab982a38893340cfc0f6 Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Thu, 15 Oct 2026 16:49:19 +0000 Subject: [PATCH 02/15] Keep the old kernel for K <=32. It is more optimized for that range. --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 65 +++++++++++++++---- 1 file changed, 54 insertions(+), 11 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index dea6592c05..14696157b5 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -279,6 +279,33 @@ void sum_rows_by_key_large_nkeys_colmajor(const DataIteratorT d_A, d_sums); } +/** + * Large-nkeys reduction with one thread per element, used for rows narrower than a warp + * (ncols < WarpSize), where a warp per row would leave lanes idle. + */ +template +RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element(const DataIteratorT d_A, + IdxT lda, + const WeightT* d_weights, + KeysIteratorT d_keys, + IdxT nrows, + IdxT ncols, + SumsT* d_sums) +{ + IdxT gid = threadIdx.x + (blockDim.x * static_cast(blockIdx.x)); + IdxT j = gid % ncols; + IdxT i = gid / ncols; + if (i >= nrows) return; + IdxT l = static_cast(d_keys[i]); + SumsT val = d_A[j + lda * i]; + if (d_weights != nullptr) val *= d_weights[i]; + raft::myAtomicAdd(&d_sums[j + ncols * l], val); +} + /** * Large-nkeys reduction with one warp per row: the key and weight are loaded once per row and the * warp's lanes add consecutive columns of the row into d_sums[key]. @@ -288,13 +315,13 @@ template -RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor(const DataIteratorT d_A, - IdxT lda, - const WeightT* d_weights, - KeysIteratorT d_keys, - IdxT nrows, - IdxT ncols, - SumsT* d_sums) +RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_warp(const DataIteratorT d_A, + IdxT lda, + const WeightT* d_weights, + KeysIteratorT d_keys, + IdxT nrows, + IdxT ncols, + SumsT* d_sums) { // Plain pointers are read through the read-only cache; other iterators (e.g. a transform // iterator converting the input type) are dereferenced as is. @@ -331,15 +358,31 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, SumsT* d_sums, cudaStream_t st) { - constexpr uint32_t block_dim = 128; + constexpr uint32_t block_dim = 128; + if (ncols < WarpSize) { + // Rows narrower than a warp: one thread per element keeps every lane busy. + const auto grid_dim = static_cast(ceildiv(nrows * ncols, IdxT{block_dim})); + raft::launch_kernel(st, + grid_dim, + block_dim, + sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element, + d_A, + lda, + d_weights, + d_keys, + nrows, + ncols, + d_sums); + return; + } constexpr uint32_t warps_per_block = block_dim / WarpSize; // Keep gridDim.x within the launch limit; the kernel's grid-stride loop covers extra rows. - const auto grid_dim = static_cast( - std::min(ceildiv(nrows, warps_per_block), IdxT{1} << 30)); + const auto grid_dim = + static_cast(std::min(ceildiv(nrows, warps_per_block), IdxT{1} << 30)); raft::launch_kernel(st, grid_dim, block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor, + sum_rows_by_key_large_nkeys_kernel_rowmajor_per_warp, d_A, lda, d_weights, From 82fa848423885348f02570f740ed49924fa0ba37 Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Fri, 16 Oct 2026 11:06:45 +0000 Subject: [PATCH 03/15] Extra kernel - Sort rows by key before summing --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 197 +++++++++++++++--- 1 file changed, 173 insertions(+), 24 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 14696157b5..90172ada0e 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -9,7 +9,11 @@ #include #include +#include +#include + #include +#include #include #include @@ -280,8 +284,8 @@ void sum_rows_by_key_large_nkeys_colmajor(const DataIteratorT d_A, } /** - * Large-nkeys reduction with one thread per element, used for rows narrower than a warp - * (ncols < WarpSize), where a warp per row would leave lanes idle. + * Large-nkeys reduction with one thread per element, used for where a warp per row would leave + * lanes idle. */ template (blockIdx.x) * blockDim.x + threadIdx.x) / WarpSize; const IdxT n_warps = static_cast(gridDim.x) * blockDim.x / WarpSize; for (IdxT i = warp_id; i < nrows; i += n_warps) { + const IdxT row = d_row_ids != nullptr ? static_cast(d_row_ids[i]) : i; const auto key = static_cast(d_keys[i]); - const SumsT w = d_weights != nullptr ? static_cast(d_weights[i]) : SumsT(1); + const SumsT w = d_weights != nullptr ? static_cast(d_weights[row]) : SumsT(1); for (IdxT j = laneId(); j < ncols; j += WarpSize) { SumsT a; if constexpr (kIsPlainPointer) { - a = __ldg(d_A + lda * i + j); + a = __ldg(d_A + lda * row + j); } else { - a = static_cast(d_A[lda * i + j]); + a = static_cast(d_A[lda * row + j]); } raft::myAtomicAdd(d_sums + ncols * key + j, a * w); } } } +template +void sum_rows_by_key_large_nkeys_rowmajor_per_warp(const DataIteratorT d_A, + IdxT lda, + const KeysIteratorT d_keys, + const uint32_t* d_row_ids, + const WeightT* d_weights, + IdxT nrows, + IdxT ncols, + SumsT* d_sums, + cudaStream_t st) +{ + constexpr uint32_t block_dim = 128; + constexpr uint32_t warps_per_block = block_dim / WarpSize; + const auto grid_dim = + static_cast(std::min(ceildiv(nrows, warps_per_block), IdxT{1} << 30)); + raft::launch_kernel(st, + grid_dim, + block_dim, + sum_rows_by_key_large_nkeys_kernel_rowmajor_per_warp, + d_A, + lda, + d_weights, + d_keys, + d_row_ids, + nrows, + ncols, + d_sums); +} + +template +RAFT_KERNEL sum_rows_by_key_sort_input_kernel(KeysIteratorT d_keys, + IdxT nrows, + uint32_t* keys, + uint32_t* row_ids) +{ + const IdxT i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < nrows) { + keys[i] = static_cast(d_keys[i]); + row_ids[i] = static_cast(i); + } +} + +/** + * Large-nkeys reduction over the rows in key order: the row ids are radix-sorted by key, so the + * sums rows being updated at any moment stay in L2 even when all sums do not fit there. + * Requires nrows and nkeys to fit in uint32_t; uses 16 bytes per row of temporary memory. + */ +template +void sum_rows_by_key_large_nkeys_rowmajor_sorted(const DataIteratorT d_A, + IdxT lda, + const KeysIteratorT d_keys, + const WeightT* d_weights, + IdxT nrows, + IdxT ncols, + IdxT nkeys, + SumsT* d_sums, + cudaStream_t st) +{ + rmm::device_uvector keys(nrows, st), row_ids(nrows, st); + rmm::device_uvector sorted_keys(nrows, st), sorted_row_ids(nrows, st); + constexpr uint32_t block_dim = 256; + raft::launch_kernel(st, + static_cast(ceildiv(nrows, IdxT{block_dim})), + block_dim, + sum_rows_by_key_sort_input_kernel, + d_keys, + nrows, + keys.data(), + row_ids.data()); + // Only the bits that can be set in a key in [0, nkeys) take part in the sort. + int end_bit = 1; + while (end_bit < 32 && (IdxT{1} << end_bit) < nkeys) { + ++end_bit; + } + size_t tmp_bytes = 0; + RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs(nullptr, + tmp_bytes, + keys.data(), + sorted_keys.data(), + row_ids.data(), + sorted_row_ids.data(), + static_cast(nrows), + 0, + end_bit, + st)); + rmm::device_buffer tmp(tmp_bytes, st); + RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs(tmp.data(), + tmp_bytes, + keys.data(), + sorted_keys.data(), + row_ids.data(), + sorted_row_ids.data(), + static_cast(nrows), + 0, + end_bit, + st)); + sum_rows_by_key_large_nkeys_rowmajor_per_warp(d_A, + lda, + static_cast(sorted_keys.data()), + sorted_row_ids.data(), + d_weights, + nrows, + ncols, + d_sums, + st); +} + +/** + * Whether to visit the rows in key order. Sorting pays off when the sums do not fit in L2, so the + * atomics of unsorted rows would go to DRAM, when the input is large enough to amortize the sort + * and its temporary allocations (16 bytes per row), and when rows are long enough (>= 2 KB) that + * the per-row sort cost and the contention of consecutive rows on the same key stay small. The + * size thresholds scale with the L2 size; all were measured on A100, H100 and B100. + */ +template +bool sum_rows_by_key_use_sorted(IdxT nrows, IdxT ncols, IdxT nkeys, int l2_bytes, int cc_major) +{ + // The sort indexes rows with int and stores keys and row ids as uint32_t. + if (static_cast(nrows) > static_cast(std::numeric_limits::max()) || + static_cast(nkeys) > std::numeric_limits::max()) { + return false; + } + const double row_bytes = static_cast(ncols) * sizeof(SumsT); + const double input_bytes = row_bytes * nrows; + const double sums_bytes = row_bytes * nkeys; + // On Ampere, unsorted atomics still mostly hit L2 until the sums exceed the whole L2. + const double sums_limit = cc_major >= 9 ? 0.5 * l2_bytes : 1.0 * l2_bytes; + return row_bytes >= 2048 && input_bytes >= 40.0 * l2_bytes && sums_bytes > sums_limit; +} + template 4 ? 64 : cc_major >= 9 ? 32 : 48; + if (ncols < min_cols_per_warp) { + // per-element kernel for narrow rows (small ncols), avoiding idle lanes + constexpr uint32_t block_dim = 128; const auto grid_dim = static_cast(ceildiv(nrows * ncols, IdxT{block_dim})); raft::launch_kernel(st, grid_dim, @@ -375,21 +528,16 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, d_sums); return; } - constexpr uint32_t warps_per_block = block_dim / WarpSize; - // Keep gridDim.x within the launch limit; the kernel's grid-stride loop covers extra rows. - const auto grid_dim = - static_cast(std::min(ceildiv(nrows, warps_per_block), IdxT{1} << 30)); - raft::launch_kernel(st, - grid_dim, - block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor_per_warp, - d_A, - lda, - d_weights, - d_keys, - nrows, - ncols, - d_sums); + + if (sum_rows_by_key_use_sorted(nrows, ncols, nkeys, l2_bytes, cc_major)) { + // sorted kernel for highest ncols and nrows by remediating the L2 bottleneck + sum_rows_by_key_large_nkeys_rowmajor_sorted( + d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, st); + } else { + // per-warp kernel for wider rows until L2 bottleneck hits + sum_rows_by_key_large_nkeys_rowmajor_per_warp( + d_A, lda, d_keys, static_cast(nullptr), d_weights, nrows, ncols, d_sums, st); + } } /** @@ -444,7 +592,8 @@ void reduce_rows_by_key(const DataIteratorT d_A, sum_rows_by_key_small_nkeys( d_A, lda, d_keys_char, d_weights, nrows, ncols, nkeys, d_sums, stream); } else { - sum_rows_by_key_large_nkeys_rowmajor(d_A, lda, d_keys, d_weights, nrows, ncols, d_sums, stream); + sum_rows_by_key_large_nkeys_rowmajor( + d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, stream); } } From d6e787751f659a83dedb521d00e5e176132dab06 Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Mon, 19 Oct 2026 09:04:22 +0000 Subject: [PATCH 04/15] Add vectorized load kernel - improve latency-bound at K < 64, given 16-byte alignments --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 90172ada0e..0e11568f9c 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -310,6 +311,44 @@ RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element(const DataIt raft::myAtomicAdd(&d_sums[j + ncols * l], val); } +/** + * One thread does one vectorized float4 load, one key and weight load and one float4 atomic + * (sm_90+) write. + * Vectorized load requirements: + * - ncols % 4 == 0, lda % 4 == 0 and 16-byte aligned d_A and d_sums. + */ +template +RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4(const float* d_A, + IdxT lda, + const WeightT* d_weights, + KeysIteratorT d_keys, + IdxT nvecs, + IdxT ncols, + float* d_sums) +{ + const IdxT q = threadIdx.x + blockDim.x * static_cast(blockIdx.x); + if (q >= nvecs) return; + const IdxT vecs_per_row = ncols / 4; + const IdxT i = q / vecs_per_row; + const IdxT j = (q - i * vecs_per_row) * 4; + float4 a = __ldg(reinterpret_cast(d_A + lda * i + j)); + const float w = d_weights != nullptr ? static_cast(d_weights[i]) : 1.0f; + a.x *= w; + a.y *= w; + a.z *= w; + a.w *= w; + float* dst = d_sums + ncols * static_cast(d_keys[i]) + j; +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 + // vectorized atomic add only available since Hopper + atomicAdd(reinterpret_cast(dst), a); +#else + raft::myAtomicAdd(dst, a.x); + raft::myAtomicAdd(dst + 1, a.y); + raft::myAtomicAdd(dst + 2, a.z); + raft::myAtomicAdd(dst + 3, a.w); +#endif +} + /** * Large-nkeys reduction with one warp per row: the key and weight are loaded once per row and the * warp's lanes add consecutive columns of the row into d_sums[key]. @@ -514,6 +553,25 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, if (ncols < min_cols_per_warp) { // per-element kernel for narrow rows (small ncols), avoiding idle lanes constexpr uint32_t block_dim = 128; + if constexpr (std::is_same_v && (std::is_same_v || + std::is_same_v)) { + if (ncols % 4 == 0 && lda % 4 == 0 && raft::is_aligned(d_A, 16) && + raft::is_aligned(d_sums, 16)) { + const IdxT nvecs = nrows * ncols / 4; + raft::launch_kernel(st, + static_cast(ceildiv(nvecs, IdxT{block_dim})), + block_dim, + sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4, + static_cast(d_A), + lda, + d_weights, + d_keys, + nvecs, + ncols, + d_sums); + return; + } + } const auto grid_dim = static_cast(ceildiv(nrows * ncols, IdxT{block_dim})); raft::launch_kernel(st, grid_dim, From f1f3b6766939c59f55b298bcfb0a37fe9b532a53 Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Mon, 19 Oct 2026 09:59:44 +0000 Subject: [PATCH 05/15] Single kernel selection point. Tune params. --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 162 +++++++++++------- 1 file changed, 102 insertions(+), 60 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 0e11568f9c..0357e6d917 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -285,8 +285,7 @@ void sum_rows_by_key_large_nkeys_colmajor(const DataIteratorT d_A, } /** - * Large-nkeys reduction with one thread per element, used for where a warp per row would leave - * lanes idle. + * One thread does one element, one key and one weight load. Then, one atomic write. */ template RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4(const float* d_A, @@ -350,9 +347,7 @@ RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4(const float* } /** - * Large-nkeys reduction with one warp per row: the key and weight are loaded once per row and the - * warp's lanes add consecutive columns of the row into d_sums[key]. - * If d_row_ids is not null, the i-th visited row is d_row_ids[i] and its key is d_keys[i]. + * One warp processes one row. Key and weight are loaded once per row. */ template RAFT_KERNEL sum_rows_by_key_sort_input_kernel(KeysIteratorT d_keys, IdxT nrows, @@ -437,8 +435,7 @@ RAFT_KERNEL sum_rows_by_key_sort_input_kernel(KeysIteratorT d_keys, } /** - * Large-nkeys reduction over the rows in key order: the row ids are radix-sorted by key, so the - * sums rows being updated at any moment stay in L2 even when all sums do not fit there. + * Radix-sort the row ids by key and then call per-warp kernel. * Requires nrows and nkeys to fit in uint32_t; uses 16 bytes per row of temporary memory. */ template = 2 KB) that - * the per-row sort cost and the contention of consecutive rows on the same key stay small. The - * size thresholds scale with the L2 size; all were measured on A100, H100 and B100. - */ template bool sum_rows_by_key_use_sorted(IdxT nrows, IdxT ncols, IdxT nkeys, int l2_bytes, int cc_major) { @@ -523,9 +513,66 @@ bool sum_rows_by_key_use_sorted(IdxT nrows, IdxT ncols, IdxT nkeys, int l2_bytes const double row_bytes = static_cast(ncols) * sizeof(SumsT); const double input_bytes = row_bytes * nrows; const double sums_bytes = row_bytes * nkeys; - // On Ampere, unsorted atomics still mostly hit L2 until the sums exceed the whole L2. - const double sums_limit = cc_major >= 9 ? 0.5 * l2_bytes : 1.0 * l2_bytes; - return row_bytes >= 2048 && input_bytes >= 40.0 * l2_bytes && sums_bytes > sums_limit; + // On Ampere, unsorted atomics still mostly hit L2 until the sums exceed the whole L2. On RTX + // Blackwell (cc 12, GDDR7) sorting already wins for small inputs and sums of a quarter of L2. + const double sums_limit = cc_major == 12 ? 0.25 * l2_bytes + : cc_major >= 9 ? 0.5 * l2_bytes + : 1.0 * l2_bytes; + const double input_limit = cc_major == 12 ? 6.0 * l2_bytes : 40.0 * l2_bytes; + return row_bytes >= 2048 && input_bytes >= input_limit && sums_bytes > sums_limit; +} + +enum class sum_rows_by_key_kernel { per_element, per_float4, per_warp, sorted }; + +struct sum_rows_by_key_plan { + sum_rows_by_key_kernel kernel; + uint32_t block_dim; +}; + +/** + * Kernel selection decision point: (Heuristically tuned on A100, H100, B100 and RTX PRO 6000) + * - per_float4: float rows of whole 16-byte vectors narrower than max_cols_float4 and 16-byte + * alignment holds; + * - per_element: other narrow rows (ncols < min_cols_per_warp), where a warp per row idles lanes + * or 16-byte alignment doesn't hold. + * - sorted: long rows whose sums do not fit in L2 (sum_rows_by_key_use_sorted); + * - per_warp: everything else. + */ +template +sum_rows_by_key_plan sum_rows_by_key_select_kernel( + const DataIteratorT d_A, IdxT lda, IdxT nrows, IdxT ncols, IdxT nkeys, const SumsT* d_sums) +{ + int dev_id, cc_major, l2_bytes; + RAFT_CUDA_TRY(cudaGetDevice(&dev_id)); + RAFT_CUDA_TRY(cudaDeviceGetAttribute(&cc_major, cudaDevAttrComputeCapabilityMajor, dev_id)); + RAFT_CUDA_TRY(cudaDeviceGetAttribute(&l2_bytes, cudaDevAttrL2CacheSize, dev_id)); + + // Fewest columns for which the per-warp kernel beats the per-element one + const IdxT min_cols_per_warp = sizeof(SumsT) > 4 ? 64 + : cc_major == 10 ? 42 + : (cc_major >= 9 && cc_major != 12) ? 32 + : 48; + + const IdxT max_cols_float4 = cc_major == 10 ? 256 + : cc_major == 12 ? 64 + : cc_major >= 9 ? min_cols_per_warp + : 0; + + if constexpr (std::is_same_v && (std::is_same_v || + std::is_same_v)) { + if (ncols < max_cols_float4 && ncols % 4 == 0 && lda % 4 == 0 && raft::is_aligned(d_A, 16) && + raft::is_aligned(d_sums, 16)) { + return {sum_rows_by_key_kernel::per_float4, 128}; + } + } + if (ncols < min_cols_per_warp) { + // Larger blocks help on cc 10 and 12, where short-lived 128-thread blocks are launch-bound. + return {sum_rows_by_key_kernel::per_element, (cc_major == 10 || cc_major == 12) ? 256u : 128u}; + } + if (sum_rows_by_key_use_sorted(nrows, ncols, nkeys, l2_bytes, cc_major)) { + return {sum_rows_by_key_kernel::sorted, 0}; + } + return {sum_rows_by_key_kernel::per_warp, 0}; } template 4 ? 64 : cc_major >= 9 ? 32 : 48; - if (ncols < min_cols_per_warp) { - // per-element kernel for narrow rows (small ncols), avoiding idle lanes - constexpr uint32_t block_dim = 128; - if constexpr (std::is_same_v && (std::is_same_v || - std::is_same_v)) { - if (ncols % 4 == 0 && lda % 4 == 0 && raft::is_aligned(d_A, 16) && - raft::is_aligned(d_sums, 16)) { + const auto plan = sum_rows_by_key_select_kernel(d_A, lda, nrows, ncols, nkeys, d_sums); + switch (plan.kernel) { + case sum_rows_by_key_kernel::per_float4: + if constexpr (std::is_same_v && (std::is_same_v || + std::is_same_v)) { const IdxT nvecs = nrows * ncols / 4; raft::launch_kernel(st, - static_cast(ceildiv(nvecs, IdxT{block_dim})), - block_dim, + static_cast(ceildiv(nvecs, IdxT{plan.block_dim})), + plan.block_dim, sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4, static_cast(d_A), lda, @@ -569,32 +607,36 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, nvecs, ncols, d_sums); - return; } - } - const auto grid_dim = static_cast(ceildiv(nrows * ncols, IdxT{block_dim})); - raft::launch_kernel(st, - grid_dim, - block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element, - d_A, - lda, - d_weights, - d_keys, - nrows, - ncols, - d_sums); - return; - } - - if (sum_rows_by_key_use_sorted(nrows, ncols, nkeys, l2_bytes, cc_major)) { - // sorted kernel for highest ncols and nrows by remediating the L2 bottleneck - sum_rows_by_key_large_nkeys_rowmajor_sorted( - d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, st); - } else { - // per-warp kernel for wider rows until L2 bottleneck hits - sum_rows_by_key_large_nkeys_rowmajor_per_warp( - d_A, lda, d_keys, static_cast(nullptr), d_weights, nrows, ncols, d_sums, st); + break; + case sum_rows_by_key_kernel::per_element: + raft::launch_kernel(st, + static_cast(ceildiv(nrows * ncols, IdxT{plan.block_dim})), + plan.block_dim, + sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element, + d_A, + lda, + d_weights, + d_keys, + nrows, + ncols, + d_sums); + break; + case sum_rows_by_key_kernel::sorted: + sum_rows_by_key_large_nkeys_rowmajor_sorted( + d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, st); + break; + case sum_rows_by_key_kernel::per_warp: + sum_rows_by_key_large_nkeys_rowmajor_per_warp(d_A, + lda, + d_keys, + static_cast(nullptr), + d_weights, + nrows, + ncols, + d_sums, + st); + break; } } From 31e3608b115d85e2b27535e6578613beb14aa0fe Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Mon, 19 Oct 2026 12:02:51 +0000 Subject: [PATCH 06/15] Fix code rabbit --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 53 ++++++++++--------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 0357e6d917..74a4811a5b 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -367,9 +367,10 @@ RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_warp(const DataItera // iterator converting the input type) are dereferenced as is. constexpr bool kIsPlainPointer = std::is_same_v || std::is_same_v; - const IdxT warp_id = (static_cast(blockIdx.x) * blockDim.x + threadIdx.x) / WarpSize; - const IdxT n_warps = static_cast(gridDim.x) * blockDim.x / WarpSize; - for (IdxT i = warp_id; i < nrows; i += n_warps) { + const int64_t warp_id = (static_cast(blockIdx.x) * blockDim.x + threadIdx.x) / WarpSize; + const int64_t n_warps = static_cast(gridDim.x) * blockDim.x / WarpSize; + for (int64_t r = warp_id; r < static_cast(nrows); r += n_warps) { + const auto i = static_cast(r); const IdxT row = d_row_ids != nullptr ? static_cast(d_row_ids[i]) : i; const auto key = static_cast(d_keys[i]); const SumsT w = d_weights != nullptr ? static_cast(d_weights[row]) : SumsT(1); @@ -596,31 +597,33 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, if constexpr (std::is_same_v && (std::is_same_v || std::is_same_v)) { const IdxT nvecs = nrows * ncols / 4; - raft::launch_kernel(st, - static_cast(ceildiv(nvecs, IdxT{plan.block_dim})), - plan.block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4, - static_cast(d_A), - lda, - d_weights, - d_keys, - nvecs, - ncols, - d_sums); + raft::launch_kernel( + st, + static_cast(ceildiv(nvecs, static_cast(plan.block_dim))), + plan.block_dim, + sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4, + static_cast(d_A), + lda, + d_weights, + d_keys, + nvecs, + ncols, + d_sums); } break; case sum_rows_by_key_kernel::per_element: - raft::launch_kernel(st, - static_cast(ceildiv(nrows * ncols, IdxT{plan.block_dim})), - plan.block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element, - d_A, - lda, - d_weights, - d_keys, - nrows, - ncols, - d_sums); + raft::launch_kernel( + st, + static_cast(ceildiv(nrows * ncols, static_cast(plan.block_dim))), + plan.block_dim, + sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element, + d_A, + lda, + d_weights, + d_keys, + nrows, + ncols, + d_sums); break; case sum_rows_by_key_kernel::sorted: sum_rows_by_key_large_nkeys_rowmajor_sorted( From cf531295ece10ff748fcd2f38af819ef8a21f825 Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Tue, 27 Oct 2026 11:52:19 +0000 Subject: [PATCH 07/15] Static assert weight and sum types --- cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 74a4811a5b..9d3816a380 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -86,6 +86,11 @@ struct quadSum { // The labels are not adjacent // +/** Floating point including the extended types, which std::is_floating_point does not cover. */ +template +inline constexpr bool is_floating_point_v = + std::is_floating_point_v || std::is_same_v || std::is_same_v; + // // Reduce by keys - for keys <= 4 // @@ -683,6 +688,11 @@ void reduce_rows_by_key(const DataIteratorT d_A, bool reset_sums) { typedef typename std::iterator_traits::value_type KeyType; + static_assert( + !is_floating_point_v || + (is_floating_point_v && sizeof(WeightT) <= sizeof(SumsT)), + "Floating weight type is broader than the sum type. Instead of silently casting down the " + "weight precision, we throw an error here."); // Following kernel needs memset if (reset_sums) { cudaMemsetAsync(d_sums, 0, ncols * nkeys * sizeof(SumsT), stream); } From cc4af470b4bd28eb2687b707488869349fb1404b Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Tue, 27 Oct 2026 12:52:00 +0000 Subject: [PATCH 08/15] Reuse / extend libraries. --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 24 +++++++------------ cpp/include/raft/util/cuda_utils.cuh | 16 +++++++++++++ 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 9d3816a380..1a8e277fc9 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -333,22 +334,15 @@ RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4(const float* const IdxT vecs_per_row = ncols / 4; const IdxT i = q / vecs_per_row; const IdxT j = (q - i * vecs_per_row) * 4; - float4 a = __ldg(reinterpret_cast(d_A + lda * i + j)); - const float w = d_weights != nullptr ? static_cast(d_weights[i]) : 1.0f; - a.x *= w; - a.y *= w; - a.z *= w; - a.w *= w; + TxN_t a; + a.load(d_A, lda * i + j); + const float w = d_weights != nullptr ? static_cast(d_weights[i]) : 1.0f; +#pragma unroll + for (int c = 0; c < a.Ratio; ++c) { + a.val.data[c] *= w; + } float* dst = d_sums + ncols * static_cast(d_keys[i]) + j; -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 - // vectorized atomic add only available since Hopper - atomicAdd(reinterpret_cast(dst), a); -#else - raft::myAtomicAdd(dst, a.x); - raft::myAtomicAdd(dst + 1, a.y); - raft::myAtomicAdd(dst + 2, a.z); - raft::myAtomicAdd(dst + 3, a.w); -#endif + raft::myAtomicAdd(reinterpret_cast(dst), *a.vectorized_data()); } /** diff --git a/cpp/include/raft/util/cuda_utils.cuh b/cpp/include/raft/util/cuda_utils.cuh index da56be7bf5..1f0b2fad42 100644 --- a/cpp/include/raft/util/cuda_utils.cuh +++ b/cpp/include/raft/util/cuda_utils.cuh @@ -43,6 +43,22 @@ DI void myAtomicAdd(int64_t* address, int64_t val) } while (assumed != old); } +// Specialization for float4 +template <> +DI void myAtomicAdd(float4* address, float4 val) +{ +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 900 + // Vectorized atomic write is only available from Hopper. + atomicAdd(address, val); +#else + float* elements = reinterpret_cast(address); + myAtomicAdd(elements, val.x); + myAtomicAdd(elements + 1, val.y); + myAtomicAdd(elements + 2, val.z); + myAtomicAdd(elements + 3, val.w); +#endif +} + #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 600) // Ref: // http://on-demand.gputechconf.com/gtc/2013/presentations/S3101-Atomic-Memory-Operations.pdf From 30da49cf2fdebd2e6071b906e4220ac286c52f9b Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Tue, 27 Oct 2026 13:55:00 +0000 Subject: [PATCH 09/15] Dry-run compliance. No dry-run tests --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 44 +++++++++++------- .../raft/linalg/reduce_rows_by_key.cuh | 46 ++++++++++--------- cpp/tests/linalg/reduce_rows_by_key.cu | 17 +++++++ 3 files changed, 68 insertions(+), 39 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 1a8e277fc9..7da03514e2 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -451,19 +451,11 @@ void sum_rows_by_key_large_nkeys_rowmajor_sorted(const DataIteratorT d_A, IdxT ncols, IdxT nkeys, SumsT* d_sums, - cudaStream_t st) + cudaStream_t st, + bool dry_run) { rmm::device_uvector keys(nrows, st), row_ids(nrows, st); rmm::device_uvector sorted_keys(nrows, st), sorted_row_ids(nrows, st); - constexpr uint32_t block_dim = 256; - raft::launch_kernel(st, - static_cast(ceildiv(nrows, IdxT{block_dim})), - block_dim, - sum_rows_by_key_sort_input_kernel, - d_keys, - nrows, - keys.data(), - row_ids.data()); // Only the bits that can be set in a key in [0, nkeys) take part in the sort. int end_bit = 1; while (end_bit < 32 && (IdxT{1} << end_bit) < nkeys) { @@ -481,6 +473,17 @@ void sum_rows_by_key_large_nkeys_rowmajor_sorted(const DataIteratorT d_A, end_bit, st)); rmm::device_buffer tmp(tmp_bytes, st); + if (dry_run) { return; } + + constexpr uint32_t block_dim = 256; + raft::launch_kernel(st, + static_cast(ceildiv(nrows, IdxT{block_dim})), + block_dim, + sum_rows_by_key_sort_input_kernel, + d_keys, + nrows, + keys.data(), + row_ids.data()); RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs(tmp.data(), tmp_bytes, keys.data(), @@ -588,9 +591,11 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, IdxT ncols, IdxT nkeys, SumsT* d_sums, - cudaStream_t st) + cudaStream_t st, + bool dry_run) { const auto plan = sum_rows_by_key_select_kernel(d_A, lda, nrows, ncols, nkeys, d_sums); + if (dry_run && plan.kernel != sum_rows_by_key_kernel::sorted) { return; } switch (plan.kernel) { case sum_rows_by_key_kernel::per_float4: if constexpr (std::is_same_v && (std::is_same_v || @@ -626,7 +631,7 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, break; case sum_rows_by_key_kernel::sorted: sum_rows_by_key_large_nkeys_rowmajor_sorted( - d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, st); + d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, st, dry_run); break; case sum_rows_by_key_kernel::per_warp: sum_rows_by_key_large_nkeys_rowmajor_per_warp(d_A, @@ -679,7 +684,8 @@ void reduce_rows_by_key(const DataIteratorT d_A, IdxT nkeys, SumsT* d_sums, cudaStream_t stream, - bool reset_sums) + bool reset_sums, + bool dry_run = false) { typedef typename std::iterator_traits::value_type KeyType; static_assert( @@ -689,9 +695,10 @@ void reduce_rows_by_key(const DataIteratorT d_A, "weight precision, we throw an error here."); // Following kernel needs memset - if (reset_sums) { cudaMemsetAsync(d_sums, 0, ncols * nkeys * sizeof(SumsT), stream); } + if (reset_sums && !dry_run) { cudaMemsetAsync(d_sums, 0, ncols * nkeys * sizeof(SumsT), stream); } if (d_keys_char != nullptr && nkeys <= SUM_ROWS_BY_KEY_SMALL_K_MAX_K) { + if (dry_run) { return; } // sum_rows_by_key_small_k is BW bounded. d_keys is loaded ncols time - avoiding wasting BW // with doubles we have ~20% speed up - with floats we can hope something around 2x // Converting d_keys to char @@ -700,7 +707,7 @@ void reduce_rows_by_key(const DataIteratorT d_A, d_A, lda, d_keys_char, d_weights, nrows, ncols, nkeys, d_sums, stream); } else { sum_rows_by_key_large_nkeys_rowmajor( - d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, stream); + d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, stream, dry_run); } } @@ -721,6 +728,7 @@ void reduce_rows_by_key(const DataIteratorT d_A, * @param[in] nkeys Number of unique keys in d_keys * @param[out] d_sums Row sums by key (ncols x d_keys) * @param[in] stream CUDA stream + * @param[in] reset_sums Whether to reset the output sums to zero before reducing */ template void reduce_rows_by_key(const DataIteratorT d_A, @@ -732,7 +740,8 @@ void reduce_rows_by_key(const DataIteratorT d_A, IdxT nkeys, SumsT* d_sums, cudaStream_t stream, - bool reset_sums) + bool reset_sums, + bool dry_run = false) { typedef typename std::iterator_traits::value_type DataType; reduce_rows_by_key(d_A, @@ -745,7 +754,8 @@ void reduce_rows_by_key(const DataIteratorT d_A, nkeys, d_sums, stream, - reset_sums); + reset_sums, + dry_run); } }; // end namespace detail diff --git a/cpp/include/raft/linalg/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/reduce_rows_by_key.cuh index 32005b14d1..e771e8d035 100644 --- a/cpp/include/raft/linalg/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/reduce_rows_by_key.cuh @@ -149,36 +149,38 @@ void reduce_rows_by_key( std::optional> d_weights = std::nullopt, bool reset_sums = true) { - if (resource::get_dry_run_flag(handle)) { return; } RAFT_EXPECTS(d_A.extent(0) == d_A.extent(0) && d_sums.extent(1) == n_unique_keys, "Output is not of size ncols * n_unique_keys"); RAFT_EXPECTS(d_keys.extent(0) == d_A.extent(1), "Keys is not of size nrows"); + const bool dry_run = resource::get_dry_run_flag(handle); if (d_weights) { RAFT_EXPECTS(d_weights.value().extent(0) == d_A.extent(1), "Weights is not of size nrows"); - reduce_rows_by_key(d_A.data_handle(), - d_A.extent(0), - d_keys.data_handle(), - d_weights.value().data_handle(), - d_keys_char.data_handle(), - d_A.extent(1), - d_A.extent(0), - n_unique_keys, - d_sums.data_handle(), - resource::get_cuda_stream(handle).get(), - reset_sums); + detail::reduce_rows_by_key(d_A.data_handle(), + d_A.extent(0), + d_keys.data_handle(), + d_weights.value().data_handle(), + d_keys_char.data_handle(), + d_A.extent(1), + d_A.extent(0), + n_unique_keys, + d_sums.data_handle(), + resource::get_cuda_stream(handle).get(), + reset_sums, + dry_run); } else { - reduce_rows_by_key(d_A.data_handle(), - d_A.extent(0), - d_keys.data_handle(), - d_keys_char.data_handle(), - d_A.extent(1), - d_A.extent(0), - n_unique_keys, - d_sums.data_handle(), - resource::get_cuda_stream(handle).get(), - reset_sums); + detail::reduce_rows_by_key(d_A.data_handle(), + d_A.extent(0), + d_keys.data_handle(), + d_keys_char.data_handle(), + d_A.extent(1), + d_A.extent(0), + n_unique_keys, + d_sums.data_handle(), + resource::get_cuda_stream(handle).get(), + reset_sums, + dry_run); } } diff --git a/cpp/tests/linalg/reduce_rows_by_key.cu b/cpp/tests/linalg/reduce_rows_by_key.cu index 43af82279e..39e5f2c325 100644 --- a/cpp/tests/linalg/reduce_rows_by_key.cu +++ b/cpp/tests/linalg/reduce_rows_by_key.cu @@ -262,5 +262,22 @@ INSTANTIATE_TEST_CASE_P(ReduceRowTests, ReduceRowTestManyClusters, ::testing::ValuesIn(inputsf_many_cluster)); +// ReduceRowTestVectorized +// 100000 Obs, 16 cols, 2048 clusters: Should trigger the vectorized kernel on GPU newer than 9.0. +const std::vector> inputsf_vectorized = { + {0.00001f, 100000, 16, 2048, 1234ULL, false}, + {0.00001f, 100000, 16, 2048, 1234ULL, true, 32.0}, + {0.00001f, 100000, 16, 2048, 1234ULL, true, 16.0}}; +typedef ReduceRowTest ReduceRowTestVectorized; +TEST_P(ReduceRowTestVectorized, Result) +{ + ASSERT_TRUE(raft::devArrMatch(out_ref.data(), + out.data(), + params.cols * params.nkeys, + raft::CompareApprox(params.tolerance))); +} +INSTANTIATE_TEST_CASE_P(ReduceRowTests, + ReduceRowTestVectorized, + ::testing::ValuesIn(inputsf_vectorized)); } // end namespace linalg } // end namespace raft From 68538fef8338f8ae8542a1ee71c7597094cefd5d Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Tue, 27 Oct 2026 14:15:40 +0000 Subject: [PATCH 10/15] Clang-format --- cpp/include/raft/util/cuda_utils.cuh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/include/raft/util/cuda_utils.cuh b/cpp/include/raft/util/cuda_utils.cuh index 1f0b2fad42..0a95fd9dff 100644 --- a/cpp/include/raft/util/cuda_utils.cuh +++ b/cpp/include/raft/util/cuda_utils.cuh @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: Copyright (c) 2018-2026, NVIDIA CORPORATION. + * SPDX-FileCopyrightText: Copyright (c) 2018-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ From 1113f2b44c43f02bd141cb04b81741d89c59bee0 Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Thu, 29 Oct 2026 12:19:36 +0000 Subject: [PATCH 11/15] Dry-run unit test for allocating path (sorted variant) --- cpp/tests/linalg/reduce_rows_by_key.cu | 46 ++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/cpp/tests/linalg/reduce_rows_by_key.cu b/cpp/tests/linalg/reduce_rows_by_key.cu index 39e5f2c325..663fda320f 100644 --- a/cpp/tests/linalg/reduce_rows_by_key.cu +++ b/cpp/tests/linalg/reduce_rows_by_key.cu @@ -279,5 +279,51 @@ TEST_P(ReduceRowTestVectorized, Result) INSTANTIATE_TEST_CASE_P(ReduceRowTests, ReduceRowTestVectorized, ::testing::ValuesIn(inputsf_vectorized)); + +TEST(ReduceRowsByKeyDryRun, SortedPathAllocations) +{ + raft::resources handle; + auto stream = resource::get_cuda_stream(handle).get(); + constexpr int nrows = 100000; + constexpr int ncols = 64; + constexpr int nkeys = 256; + constexpr int end_bit = 8; // should fit nkeys + rmm::device_uvector in(nrows * ncols, stream); + rmm::device_uvector sums(nkeys * ncols, stream); + rmm::device_uvector keys(nrows, stream); + raft::random::RngState r(1234ULL); + uniformInt(handle, r, keys.data(), nrows, 0u, uint32_t{nkeys}); + RAFT_CUDA_TRY(cudaMemsetAsync(in.data(), 0, in.size() * sizeof(float), stream)); + + size_t sort_bytes = 0; + RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs( static_cast(nullptr), + sort_bytes, + static_cast(nullptr), + static_cast(nullptr), + static_cast(nullptr), + static_cast(nullptr), + nrows, + 0, + end_bit, + stream)); + const size_t expected = 4 * nrows * sizeof(uint32_t) + sort_bytes; + + auto action = [&](raft::resources const& res) { + detail::sum_rows_by_key_large_nkeys_rowmajor_sorted(in.data(), + ncols, + keys.data(), + static_cast(nullptr), + nrows, + ncols, + nkeys, + sums.data(), + resource::get_cuda_stream(res).get(), + resource::get_dry_run_flag(res)); + }; + const auto dry = raft::util::dry_run_execute(handle, action); + EXPECT_EQ(dry.device_global, expected); + execute_with_dry_run_check(handle, action, alloc_behavior::ARGUMENT_DRIVEN, expected); +} + } // end namespace linalg } // end namespace raft From d8586198d8720b5c3ac7527dccfd23fc2121cf2f Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Fri, 30 Oct 2026 12:18:09 +0000 Subject: [PATCH 12/15] Batching --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 87 +++++++++---------- cpp/tests/linalg/reduce_rows_by_key.cu | 17 ++-- 2 files changed, 46 insertions(+), 58 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 7da03514e2..2313672628 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -436,7 +436,7 @@ RAFT_KERNEL sum_rows_by_key_sort_input_kernel(KeysIteratorT d_keys, /** * Radix-sort the row ids by key and then call per-warp kernel. - * Requires nrows and nkeys to fit in uint32_t; uses 16 bytes per row of temporary memory. + * Batching defines upper limit for peak memory allocation. */ template keys(nrows, st), row_ids(nrows, st); - rmm::device_uvector sorted_keys(nrows, st), sorted_row_ids(nrows, st); + // Limit batch size to 4M rows + const IdxT batch_rows = std::min(nrows, 4000000); + rmm::device_uvector keys(batch_rows, st), keys_alt(batch_rows, st); + rmm::device_uvector row_ids(batch_rows, st), row_ids_alt(batch_rows, st); + // Double buffering avoids additional scratch space when radix sorts undergoes > 1 pass. + // 1 pass corresponds to 8-bit (selected by the CUB library) + cub::DoubleBuffer keys_db(keys.data(), keys_alt.data()); + cub::DoubleBuffer row_ids_db(row_ids.data(), row_ids_alt.data()); // Only the bits that can be set in a key in [0, nkeys) take part in the sort. int end_bit = 1; while (end_bit < 32 && (IdxT{1} << end_bit) < nkeys) { ++end_bit; } size_t tmp_bytes = 0; - RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs(nullptr, - tmp_bytes, - keys.data(), - sorted_keys.data(), - row_ids.data(), - sorted_row_ids.data(), - static_cast(nrows), - 0, - end_bit, - st)); + RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs( + nullptr, tmp_bytes, keys_db, row_ids_db, static_cast(batch_rows), 0, end_bit, st)); rmm::device_buffer tmp(tmp_bytes, st); if (dry_run) { return; } - constexpr uint32_t block_dim = 256; - raft::launch_kernel(st, - static_cast(ceildiv(nrows, IdxT{block_dim})), - block_dim, - sum_rows_by_key_sort_input_kernel, - d_keys, - nrows, - keys.data(), - row_ids.data()); - RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs(tmp.data(), - tmp_bytes, - keys.data(), - sorted_keys.data(), - row_ids.data(), - sorted_row_ids.data(), - static_cast(nrows), - 0, - end_bit, - st)); - sum_rows_by_key_large_nkeys_rowmajor_per_warp(d_A, - lda, - static_cast(sorted_keys.data()), - sorted_row_ids.data(), - d_weights, - nrows, - ncols, - d_sums, - st); + for (IdxT batch_start = 0; batch_start < nrows; batch_start += batch_rows) { + // Rows [batch_start, batch_start + n_batch_rows); row ids are local to the batch. + const IdxT n_batch_rows = std::min(batch_rows, nrows - batch_start); + keys_db = cub::DoubleBuffer(keys.data(), keys_alt.data()); + row_ids_db = cub::DoubleBuffer(row_ids.data(), row_ids_alt.data()); + constexpr uint32_t block_dim = 256; + const auto grid_dim = static_cast(ceildiv(n_batch_rows, IdxT{block_dim})); + raft::launch_kernel(st, + grid_dim, + block_dim, + sum_rows_by_key_sort_input_kernel, + d_keys + batch_start, + n_batch_rows, + keys_db.Current(), + row_ids_db.Current()); + RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs( + tmp.data(), tmp_bytes, keys_db, row_ids_db, static_cast(n_batch_rows), 0, end_bit, st)); + sum_rows_by_key_large_nkeys_rowmajor_per_warp( + d_A + batch_start * lda, + lda, + static_cast(keys_db.Current()), + row_ids_db.Current(), + d_weights != nullptr ? d_weights + batch_start : nullptr, + n_batch_rows, + ncols, + d_sums, + st); + } } template bool sum_rows_by_key_use_sorted(IdxT nrows, IdxT ncols, IdxT nkeys, int l2_bytes, int cc_major) { - // The sort indexes rows with int and stores keys and row ids as uint32_t. - if (static_cast(nrows) > static_cast(std::numeric_limits::max()) || - static_cast(nkeys) > std::numeric_limits::max()) { - return false; - } + if (static_cast(nkeys) > std::numeric_limits::max()) { return false; } + const double row_bytes = static_cast(ncols) * sizeof(SumsT); const double input_bytes = row_bytes * nrows; const double sums_bytes = row_bytes * nkeys; diff --git a/cpp/tests/linalg/reduce_rows_by_key.cu b/cpp/tests/linalg/reduce_rows_by_key.cu index 663fda320f..b12ba85f21 100644 --- a/cpp/tests/linalg/reduce_rows_by_key.cu +++ b/cpp/tests/linalg/reduce_rows_by_key.cu @@ -286,8 +286,8 @@ TEST(ReduceRowsByKeyDryRun, SortedPathAllocations) auto stream = resource::get_cuda_stream(handle).get(); constexpr int nrows = 100000; constexpr int ncols = 64; - constexpr int nkeys = 256; - constexpr int end_bit = 8; // should fit nkeys + constexpr int nkeys = 1024; + constexpr int end_bit = 10; // > 8 bits so that >1 radix passes rmm::device_uvector in(nrows * ncols, stream); rmm::device_uvector sums(nkeys * ncols, stream); rmm::device_uvector keys(nrows, stream); @@ -296,16 +296,9 @@ TEST(ReduceRowsByKeyDryRun, SortedPathAllocations) RAFT_CUDA_TRY(cudaMemsetAsync(in.data(), 0, in.size() * sizeof(float), stream)); size_t sort_bytes = 0; - RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs( static_cast(nullptr), - sort_bytes, - static_cast(nullptr), - static_cast(nullptr), - static_cast(nullptr), - static_cast(nullptr), - nrows, - 0, - end_bit, - stream)); + cub::DoubleBuffer sort_keys, sort_values; + RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs( + nullptr, sort_bytes, sort_keys, sort_values, nrows, 0, end_bit, stream)); const size_t expected = 4 * nrows * sizeof(uint32_t) + sort_bytes; auto action = [&](raft::resources const& res) { From e226e005975264b3d788624afaeaa050c09bc5fa Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Wed, 4 Nov 2026 08:56:53 +0000 Subject: [PATCH 13/15] New kernels: few keys and warp reduce. Simplify kernel selection. Kernel generic for (non)vectorized options. --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 818 ++++++++++-------- .../raft/linalg/reduce_rows_by_key.cuh | 7 +- cpp/tests/linalg/reduce_rows_by_key.cu | 48 +- 3 files changed, 492 insertions(+), 381 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index 2313672628..d2dbebefd6 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -58,29 +58,6 @@ void convert_array(IteratorT1 dst, IteratorT2 src, int n, cudaStream_t st) raft::launch_kernel(st, grid, block, convert_array_kernel, dst, src, n); } -template -struct quad { - T x, y, z, w; -}; - -// -// Functor for reduce by key, small k -// -template -struct quadSum { - __host__ __device__ __forceinline__ quad operator()(const quad& a, const quad& b) const - { - // wasting a double4.. - quad c; - c.x = a.x + b.x; - c.y = a.y + b.y; - c.z = a.z + b.z; - c.w = a.w + b.w; - - return c; - } -}; - // // Reduce by keys // We need to sum each dimension by labels @@ -92,110 +69,6 @@ template inline constexpr bool is_floating_point_v = std::is_floating_point_v || std::is_same_v || std::is_same_v; -// -// Reduce by keys - for keys <= 4 -// - -#define SUM_ROWS_SMALL_K_DIMX 256 -#define SUM_ROWS_BY_KEY_SMALL_K_MAX_K 4 -template -__launch_bounds__(SUM_ROWS_SMALL_K_DIMX, 4) - - RAFT_KERNEL sum_rows_by_key_small_nkeys_kernel(const DataIteratorT d_A, - IdxT lda, - const char* d_keys, - const WeightT* d_weights, - IdxT nrows, - IdxT ncols, - IdxT nkeys, - SumsT* d_sums) -{ - typedef typename std::iterator_traits::value_type DataType; - typedef cub::BlockReduce, SUM_ROWS_SMALL_K_DIMX> BlockReduce; - __shared__ typename BlockReduce::TempStorage temp_storage; - - for (IdxT idim = static_cast(blockIdx.y); idim < ncols; idim += gridDim.y) { - if (idim != static_cast(blockIdx.y)) __syncthreads(); // we're reusing temp_storage - - // threadIdx.x stores partial sum for current dim and key=threadIdx.x in this reg - quad thread_sums; - thread_sums.x = 0.0; - thread_sums.y = 0.0; - thread_sums.z = 0.0; - thread_sums.w = 0.0; - - // May use vectorized load - not necessary for doubles - for (IdxT block_offset_irow = blockIdx.x * blockDim.x; - block_offset_irow < nrows; // we will syncthreads() inside the loop, no CTA divergence - block_offset_irow += blockDim.x * gridDim.x) { - IdxT irow = block_offset_irow + threadIdx.x; - DataType val = (irow < nrows) ? d_A[irow * lda + idim] : DataType(0); - if (d_weights && irow < nrows) { val = val * d_weights[irow]; } - // we are not reusing the keys - after profiling - // d_keys is mainly loaded from L2, and this kernel is DRAM BW bounded - // (experimentation gave a 10% speed up - not worth the many code lines added) - IdxT row_key = (irow < nrows) ? d_keys[irow] : std::numeric_limits::max(); - - thread_sums.x += (row_key == 0) ? static_cast(val) : SumsT(0); - thread_sums.y += (row_key == 1) ? static_cast(val) : SumsT(0); - thread_sums.z += (row_key == 2) ? static_cast(val) : SumsT(0); - thread_sums.w += (row_key == 3) ? static_cast(val) : SumsT(0); - } - - // End of column - // Saving local sums back to global mem - - // Strided access - - // Reducing by key - thread_sums = BlockReduce(temp_storage).Reduce(thread_sums, quadSum()); - - if (threadIdx.x < 32) { - // We only need 4 - thread_sums = cub::ShuffleIndex<32>(thread_sums, 0, 0xffffffff); - if (static_cast(threadIdx.x) < nkeys) { - if (threadIdx.x == 0) raft::myAtomicAdd(&d_sums[threadIdx.x * ncols + idim], thread_sums.x); - if (threadIdx.x == 1) raft::myAtomicAdd(&d_sums[threadIdx.x * ncols + idim], thread_sums.y); - if (threadIdx.x == 2) raft::myAtomicAdd(&d_sums[threadIdx.x * ncols + idim], thread_sums.z); - if (threadIdx.x == 3) raft::myAtomicAdd(&d_sums[threadIdx.x * ncols + idim], thread_sums.w); - } - } - } -} - -template -void sum_rows_by_key_small_nkeys(const DataIteratorT d_A, - IdxT lda, - const char* d_keys, - const WeightT* d_weights, - IdxT nrows, - IdxT ncols, - IdxT nkeys, - SumsT* d_sums, - cudaStream_t st) -{ - dim3 grid, block; - block.x = SUM_ROWS_SMALL_K_DIMX; - block.y = 1; // Necessary - - grid.x = raft::ceildiv(nrows, (IdxT)block.x); - grid.x = std::min(grid.x, 32u); - grid.y = ncols; - grid.y = std::min(grid.y, MAX_BLOCKS); - raft::launch_kernel(st, - grid, - block, - sum_rows_by_key_small_nkeys_kernel, - d_A, - lda, - d_keys, - d_weights, - nrows, - ncols, - nkeys, - d_sums); -} - // // Reduce by keys - large number of keys // Computing a "weighted histogram" with local histograms in smem @@ -269,7 +142,7 @@ void sum_rows_by_key_large_nkeys_colmajor(const DataIteratorT d_A, cudaStream_t st) { dim3 grid, block; - block.x = SUM_ROWS_SMALL_K_DIMX; + block.x = 256; block.y = 1; // Necessary grid.x = raft::ceildiv(nrows, (IdxT)block.x); @@ -290,99 +163,204 @@ void sum_rows_by_key_large_nkeys_colmajor(const DataIteratorT d_A, d_sums); } +/** (Vectorized) load */ +template +DI void sum_rows_by_key_load(const DataIteratorT d_A, IdxT idx, bool valid, SumsT (&v)[VecLen]) +{ + if constexpr (VecLen > 1) { + TxN_t x; + x.fill(SumsT(0)); + if (valid) { x.load(static_cast(d_A), idx); } +#pragma unroll + for (int c = 0; c < VecLen; ++c) { + v[c] = x.val.data[c]; + } + } else { + v[0] = valid ? static_cast(d_A[idx]) : SumsT(0); + } +} + +/** (Vectorized) atomic add */ +template +DI void sum_rows_by_key_atomic_add(SumsT* dst, const SumsT (&v)[VecLen]) +{ + if constexpr (std::is_same_v && VecLen == 4) { + raft::myAtomicAdd(reinterpret_cast(dst), make_float4(v[0], v[1], v[2], v[3])); + } else { +#pragma unroll + for (int c = 0; c < VecLen; ++c) { + raft::myAtomicAdd(dst + c, v[c]); + } + } +} + /** - * One thread does one element, one key and one weight load. Then, one atomic write. + * One thread owns one element of a row, multiplies it by the row's weight and adds it to the sums + * of the row's key. When vectorized, one threads owns a vector of contiguous elements. */ -template -RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element(const DataIteratorT d_A, - IdxT lda, - const WeightT* d_weights, - KeysIteratorT d_keys, - IdxT nrows, - IdxT ncols, - SumsT* d_sums) +RAFT_KERNEL sum_rows_by_key_kernel_rowmajor_elementwise(const DataIteratorT d_A, + IdxT lda, + const WeightT* d_weights, + KeysIteratorT d_keys, + IdxT nrows, + IdxT ncols, + SumsT* d_sums) { - IdxT gid = threadIdx.x + (blockDim.x * static_cast(blockIdx.x)); - IdxT j = gid % ncols; - IdxT i = gid / ncols; + const IdxT q = threadIdx.x + blockDim.x * static_cast(blockIdx.x); + const IdxT vecs_per_row = ncols / VecLen; + const IdxT i = q / vecs_per_row; if (i >= nrows) return; - IdxT l = static_cast(d_keys[i]); - SumsT val = d_A[j + lda * i]; - if (d_weights != nullptr) val *= d_weights[i]; - raft::myAtomicAdd(&d_sums[j + ncols * l], val); + const IdxT j = (q - i * vecs_per_row) * VecLen; + const SumsT w = d_weights != nullptr ? static_cast(d_weights[i]) : SumsT(1); + SumsT a[VecLen]; + sum_rows_by_key_load(d_A, lda * i + j, true, a); +#pragma unroll + for (int c = 0; c < VecLen; ++c) { + a[c] *= w; + } + sum_rows_by_key_atomic_add(d_sums + ncols * static_cast(d_keys[i]) + j, a); } -/** - * One thread does one vectorized float4 load, one key and weight load and one float4 atomic - * (sm_90+) write. - */ -template -RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4(const float* d_A, - IdxT lda, - const WeightT* d_weights, - KeysIteratorT d_keys, - IdxT nvecs, - IdxT ncols, - float* d_sums) +template +void sum_rows_by_key_rowmajor_elementwise(const DataIteratorT d_A, + IdxT lda, + const KeysIteratorT d_keys, + const WeightT* d_weights, + IdxT nrows, + IdxT ncols, + SumsT* d_sums, + uint32_t block_dim, + cudaStream_t st) { - const IdxT q = threadIdx.x + blockDim.x * static_cast(blockIdx.x); - if (q >= nvecs) return; - const IdxT vecs_per_row = ncols / 4; - const IdxT i = q / vecs_per_row; - const IdxT j = (q - i * vecs_per_row) * 4; - TxN_t a; - a.load(d_A, lda * i + j); - const float w = d_weights != nullptr ? static_cast(d_weights[i]) : 1.0f; -#pragma unroll - for (int c = 0; c < a.Ratio; ++c) { - a.val.data[c] *= w; - } - float* dst = d_sums + ncols * static_cast(d_keys[i]) + j; - raft::myAtomicAdd(reinterpret_cast(dst), *a.vectorized_data()); + const IdxT n_items = nrows * (ncols / VecLen); + const auto grid_dim = static_cast(ceildiv(n_items, static_cast(block_dim))); + raft::launch_kernel(st, + grid_dim, + block_dim, + sum_rows_by_key_kernel_rowmajor_elementwise, + d_A, + lda, + d_weights, + d_keys, + nrows, + ncols, + d_sums); } +constexpr int kFewKeysMaxThreads = 512; // Max threads per block +constexpr size_t kFewKeysSmemBytes = 48 * 1024; // 48 KiB - Each GPU from Ampere+ should have it. + /** - * One warp processes one row. Key and weight are loaded once per row. + * Kernel specialized for few keys (high atomic contention) and narrow rows. + * + * - One copy has nkeys * ncols sums (same as the global sums). Each blocks holds multiple copies in + * its shared memory. + * - A block owns a range of whole rows. + * - Each thread owns one column in one copy. It sums the rows in its column of its copy, using the + * row's key. Therefore, each thread owns different addresses in shared memory, so no atomics are + * needed. + * - At the end, the copies are summed into the global sums. */ -template -RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_rowmajor_per_warp(const DataIteratorT d_A, - IdxT lda, - const WeightT* d_weights, - KeysIteratorT d_keys, - const uint32_t* d_row_ids, - IdxT nrows, - IdxT ncols, - SumsT* d_sums) +RAFT_KERNEL __launch_bounds__(kFewKeysMaxThreads) + sum_rows_by_key_kernel_rowmajor_small_keys_narrow_rows(const DataIteratorT d_A, + IdxT lda, + const WeightT* d_weights, + KeysIteratorT d_keys, + IdxT nrows, + IdxT ncols, + IdxT nkeys, + IdxT rows_per_block, + SumsT* d_sums) { - // Plain pointers are read through the read-only cache; other iterators (e.g. a transform - // iterator converting the input type) are dereferenced as is. - constexpr bool kIsPlainPointer = - std::is_same_v || std::is_same_v; - const int64_t warp_id = (static_cast(blockIdx.x) * blockDim.x + threadIdx.x) / WarpSize; - const int64_t n_warps = static_cast(gridDim.x) * blockDim.x / WarpSize; - for (int64_t r = warp_id; r < static_cast(nrows); r += n_warps) { - const auto i = static_cast(r); - const IdxT row = d_row_ids != nullptr ? static_cast(d_row_ids[i]) : i; - const auto key = static_cast(d_keys[i]); - const SumsT w = d_weights != nullptr ? static_cast(d_weights[row]) : SumsT(1); - for (IdxT j = laneId(); j < ncols; j += WarpSize) { - SumsT a; - if constexpr (kIsPlainPointer) { - a = __ldg(d_A + lda * row + j); - } else { - a = static_cast(d_A[lda * row + j]); - } - raft::myAtomicAdd(d_sums + ncols * key + j, a * w); + // Shared memory which holds multiple copies. Chosen layout: smem[n_copies][nkeys][ncols] + /// Layout choice: + /// - Each threads owns one column in one copy. So having ncols in the last dimension + /// makes neighboring threads access neighboring shared memory addresses - no bank conflicts. + /// - nkeys X ncols matches the global sum layout. Writing the sums to global memory is + /// coalesced. + extern __shared__ __align__(16) unsigned char few_keys_smem[]; + SumsT* private_sums = reinterpret_cast(few_keys_smem); + const int n = static_cast(ncols); + const int n_copies = blockDim.x / n; + /// c: column index owned by this thread + const int c = threadIdx.x % n; + /// p: copy index owned by this thread + const int p = threadIdx.x / n; + /// [r0, r1): range of rows owned by this block. + const IdxT r0 = blockIdx.x * rows_per_block; + const IdxT r1 = std::min(r0 + rows_per_block, nrows); + + // Zero-initialize private sums + for (IdxT i = threadIdx.x; i < n_copies * nkeys * ncols; i += blockDim.x) { + private_sums[i] = SumsT(0); + } + __syncthreads(); + + // Load rows and add them to the sums of their keys. + /// private_sums[copies][keys][cols] -> mine[keys][:] + SumsT* mine = private_sums + static_cast(p) * nkeys * ncols + c; + for (IdxT r = r0 + p; r < r1; r += static_cast(kRowsAhead) * n_copies) { + SumsT a[kRowsAhead]; + SumsT w[kRowsAhead]; + IdxT key[kRowsAhead]; + /// Load all kRowsAhead rows beforehand to have enough bytes in flight +#pragma unroll + for (int u = 0; u < kRowsAhead; ++u) { + const IdxT row = r + static_cast(u) * n_copies; + const bool valid = row < r1; + a[u] = valid ? static_cast(d_A[lda * row + c]) : SumsT(0); + w[u] = !valid ? SumsT(0) + : d_weights != nullptr ? static_cast(d_weights[row]) + : SumsT(1); + key[u] = valid ? static_cast(d_keys[row]) : IdxT(0); + } + /// Add each row to the sum of its key +#pragma unroll + for (int u = 0; u < kRowsAhead; ++u) { + mine[key[u] * ncols] += a[u] * w[u]; // mine[key][0] - each key is ncols apart } } + __syncthreads(); + + // Sum the copies into the global sums + for (IdxT i = threadIdx.x; i < nkeys * ncols; i += blockDim.x) { + SumsT t = SumsT(0); + for (int q = 0; q < n_copies; ++q) { + t += private_sums[static_cast(q) * nkeys * ncols + i]; + } + raft::myAtomicAdd(d_sums + i, t); + } +} + +/** Whether one private copy of the sums fits the few-keys kernel's shared memory. */ +template +bool sum_rows_by_key_few_keys_fits(IdxT nkeys, IdxT ncols) +{ + const size_t one_copy_bytes = + sizeof(SumsT) * static_cast(nkeys) * static_cast(ncols); + return one_copy_bytes <= kFewKeysSmemBytes; } template -void sum_rows_by_key_large_nkeys_rowmajor_per_warp(const DataIteratorT d_A, - IdxT lda, - const KeysIteratorT d_keys, - const uint32_t* d_row_ids, - const WeightT* d_weights, - IdxT nrows, - IdxT ncols, - SumsT* d_sums, - cudaStream_t st) +void sum_rows_by_key_rowmajor_few_keys(const DataIteratorT d_A, + IdxT lda, + const KeysIteratorT d_keys, + const WeightT* d_weights, + IdxT nrows, + IdxT ncols, + IdxT nkeys, + SumsT* d_sums, + cudaStream_t st) { - constexpr uint32_t block_dim = 128; - constexpr uint32_t warps_per_block = block_dim / WarpSize; - const auto grid_dim = - static_cast(std::min(ceildiv(nrows, warps_per_block), IdxT{1} << 30)); - raft::launch_kernel(st, + RAFT_EXPECTS( + ncols > 0 && ncols <= kFewKeysMaxThreads && sum_rows_by_key_few_keys_fits(nkeys, ncols), + "The sums do not fit in shared memory"); + constexpr int kRowsAhead = 8; + const size_t copy_bytes = std::max(1, sizeof(SumsT) * nkeys * ncols); + const int n_copies = static_cast(std::max( + 1, std::min(kFewKeysMaxThreads / ncols, kFewKeysSmemBytes / copy_bytes))); + const auto block_dim = static_cast(n_copies * ncols); + const int blocks_per_sm = block_dim >= 256 ? 2 : 4; + const IdxT rows_per_block = + ceildiv(nrows, IdxT{blocks_per_sm} * raft::getMultiProcessorCount()); + const auto grid_dim = static_cast(ceildiv(nrows, rows_per_block)); + raft::launch_kernel({st, copy_bytes * n_copies}, grid_dim, block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor_per_warp, + sum_rows_by_key_kernel_rowmajor_small_keys_narrow_rows, d_A, lda, d_weights, d_keys, - d_row_ids, nrows, ncols, + nkeys, + rows_per_block, d_sums); } -/** - * Prepare inputs for radix-sort - */ +/** Prepare keys and row ids for radix-sort. */ template RAFT_KERNEL sum_rows_by_key_sort_input_kernel(KeysIteratorT d_keys, IdxT nrows, @@ -435,7 +425,150 @@ RAFT_KERNEL sum_rows_by_key_sort_input_kernel(KeysIteratorT d_keys, } /** - * Radix-sort the row ids by key and then call per-warp kernel. + * Sum sorted-by-key rows in registers and flush to output when the key changes or the chunk ends. + * + * Work split: + * tile 0 tile 1 ... + * chunk 0 | warp 0 | warp 1 | ... + * chunk 1 | warp n_tiles | ... + * + * To have enough bytes in flight, each warp loads kRowsAhead rows before adding any of them to the + * sums. On each row, each lane owns kVecs vectors of VecLen contiguous columns. + */ +template +RAFT_KERNEL sum_rows_by_key_kernel_rowmajor_sorted(const DataIteratorT d_A, + IdxT lda, + const WeightT* d_weights, + const uint32_t* d_keys, + const uint32_t* d_row_ids, + IdxT nrows, + IdxT ncols, + IdxT chunk, + IdxT n_tiles, + SumsT* d_sums) +{ + // Each warp owns: rows [r0, r1) and columns [col0, col0 + kTileCols) + constexpr IdxT kTileCols = kVecs * VecLen * WarpSize; + const int64_t warp_id = (static_cast(blockIdx.x) * blockDim.x + threadIdx.x) / WarpSize; + const IdxT r0 = static_cast(warp_id / n_tiles) * chunk; + if (r0 >= nrows) return; // spare warps of the last block + const IdxT r1 = std::min(r0 + chunk, nrows); + const IdxT col0 = static_cast(warp_id % n_tiles) * kTileCols + laneId() * VecLen; + + // Each lane tracks in registers the sums of each vector and the current key of the processed row. + SumsT acc[kVecs][VecLen] = {}; + uint32_t cur = d_keys[r0]; + + // Flush to output + auto flush = [&]() { +#pragma unroll + for (int v = 0; v < kVecs; ++v) { + const IdxT col = col0 + v * VecLen * WarpSize; + if (col < ncols) { + sum_rows_by_key_atomic_add(d_sums + ncols * static_cast(cur) + col, acc[v]); + } +#pragma unroll + for (int c = 0; c < VecLen; ++c) { + acc[v][c] = SumsT(0); // restart at zero for the next run + } + } + }; + + for (IdxT r = r0; r < r1; r += kRowsAhead) { + // Phase 1: issue all loads of the next kRowsAhead sorted rows (keys, weights, data) before + // using any of them, so they are in flight together. + SumsT a[kRowsAhead][kVecs][VecLen]; + uint32_t key[kRowsAhead]; + SumsT w[kRowsAhead]; +#pragma unroll + for (int u = 0; u < kRowsAhead; ++u) { + const IdxT i = r + u; + // Invalid rows: Apply zero weight and unchanged key + const bool valid = i < r1; + const IdxT row = valid ? static_cast(d_row_ids[i]) : IdxT(0); + key[u] = valid ? d_keys[i] : cur; + w[u] = !valid ? SumsT(0) + : d_weights != nullptr ? static_cast(d_weights[row]) + : SumsT(1); +#pragma unroll + for (int v = 0; v < kVecs; ++v) { + const IdxT col = col0 + v * VecLen * WarpSize; + sum_rows_by_key_load(d_A, lda * row + col, valid && col < ncols, a[u][v]); + } + } + // Phase 2: do FMA and flush on key changes +#pragma unroll + for (int u = 0; u < kRowsAhead; ++u) { + if (key[u] != cur) { + flush(); + cur = key[u]; + } +#pragma unroll + for (int v = 0; v < kVecs; ++v) { +#pragma unroll + for (int c = 0; c < VecLen; ++c) { + acc[v][c] += a[u][v][c] * w[u]; + } + } + } + } + flush(); // necessary +} + +template +void sum_rows_by_key_rowmajor_sorted_launch(const DataIteratorT d_A, + IdxT lda, + const WeightT* d_weights, + const uint32_t* d_keys, + const uint32_t* d_row_ids, + IdxT nrows, + IdxT ncols, + SumsT* d_sums, + cudaStream_t st) +{ + constexpr int kVecs = kLaneBytes / (VecLen * sizeof(SumsT)); + constexpr int kRowsAhead = kLaneBytes == 16 ? 4 : 8; + constexpr IdxT kWarpsPerSM = 64; + // n_tiles: how many tiles of kVecs*VecLen columns fit in a row. Each warp owns one tile. + const IdxT n_tiles = ceildiv(ncols, IdxT{kVecs * VecLen * WarpSize}); + // n_chunks: how many chunks of rows to split the work into. Each warp owns one chunk. + const IdxT n_chunks = + std::max(1, IdxT{kWarpsPerSM} * raft::getMultiProcessorCount() / n_tiles); + // chunk: how many rows each warp owns. The last chunk may be smaller. + const IdxT chunk = ceildiv(nrows, n_chunks); + // n_warps: how many warps to cover everything. + const IdxT n_warps = ceildiv(nrows, chunk) * n_tiles; + constexpr uint32_t block_dim = 128; + const auto grid_dim = static_cast(ceildiv(n_warps, IdxT{block_dim / WarpSize})); + raft::launch_kernel(st, + grid_dim, + block_dim, + sum_rows_by_key_kernel_rowmajor_sorted, + d_A, + lda, + d_weights, + d_keys, + d_row_ids, + nrows, + ncols, + chunk, + n_tiles, + d_sums); +} + +/** + * Radix-sort the row ids by key and then sum runs of equal keys in registers. * Batching defines upper limit for peak memory allocation. */ template -void sum_rows_by_key_large_nkeys_rowmajor_sorted(const DataIteratorT d_A, - IdxT lda, - const KeysIteratorT d_keys, - const WeightT* d_weights, - IdxT nrows, - IdxT ncols, - IdxT nkeys, - SumsT* d_sums, - cudaStream_t st, - bool dry_run) +void sum_rows_by_key_rowmajor_sorted(const DataIteratorT d_A, + IdxT lda, + const KeysIteratorT d_keys, + const WeightT* d_weights, + IdxT nrows, + IdxT ncols, + IdxT nkeys, + SumsT* d_sums, + cudaStream_t st, + bool dry_run) { // Limit batch size to 4M rows const IdxT batch_rows = std::min(nrows, 4000000); @@ -473,6 +606,20 @@ void sum_rows_by_key_large_nkeys_rowmajor_sorted(const DataIteratorT d_A, rmm::device_buffer tmp(tmp_bytes, st); if (dry_run) { return; } + // Pick 16-byte vector when the input is a plain pointer and rows and sums are aligned. + constexpr int kVecLen = 16 / sizeof(SumsT); + constexpr bool kIsPlainPointer = + std::is_same_v || std::is_same_v; + bool vectorized = false; + if constexpr (kIsPlainPointer) { + vectorized = ncols % kVecLen == 0 && lda % kVecLen == 0 && raft::is_aligned(d_A, 16) && + raft::is_aligned(d_sums, 16); + } + + // A warp covers kLaneBytes * 32 bytes of a row: 32 bytes per lane (a 1 KiB tile), or 16 bytes + // per lane when the row is narrower than that, so fewer lanes idle. + const bool narrow_rows = ncols * sizeof(SumsT) < 32 * WarpSize; + for (IdxT batch_start = 0; batch_start < nrows; batch_start += batch_rows) { // Rows [batch_start, batch_start + n_batch_rows); row ids are local to the batch. const IdxT n_batch_rows = std::min(batch_rows, nrows - batch_start); @@ -490,87 +637,82 @@ void sum_rows_by_key_large_nkeys_rowmajor_sorted(const DataIteratorT d_A, row_ids_db.Current()); RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs( tmp.data(), tmp_bytes, keys_db, row_ids_db, static_cast(n_batch_rows), 0, end_bit, st)); - sum_rows_by_key_large_nkeys_rowmajor_per_warp( - d_A + batch_start * lda, - lda, - static_cast(keys_db.Current()), - row_ids_db.Current(), - d_weights != nullptr ? d_weights + batch_start : nullptr, - n_batch_rows, - ncols, - d_sums, - st); + const auto batch_A = d_A + batch_start * lda; + const WeightT* batch_w = d_weights != nullptr ? d_weights + batch_start : nullptr; + const uint32_t* s_keys = keys_db.Current(); + const uint32_t* s_rowids = row_ids_db.Current(); + auto launch = [&](auto vec_len) { + constexpr int VecLen = decltype(vec_len)::value; + if (narrow_rows) { + sum_rows_by_key_rowmajor_sorted_launch( + batch_A, lda, batch_w, s_keys, s_rowids, n_batch_rows, ncols, d_sums, st); + } else { + sum_rows_by_key_rowmajor_sorted_launch( + batch_A, lda, batch_w, s_keys, s_rowids, n_batch_rows, ncols, d_sums, st); + } + }; + if constexpr (kIsPlainPointer) { + if (vectorized) { + launch(std::integral_constant{}); + continue; + } + } + launch(std::integral_constant{}); } } -template -bool sum_rows_by_key_use_sorted(IdxT nrows, IdxT ncols, IdxT nkeys, int l2_bytes, int cc_major) -{ - if (static_cast(nkeys) > std::numeric_limits::max()) { return false; } - - const double row_bytes = static_cast(ncols) * sizeof(SumsT); - const double input_bytes = row_bytes * nrows; - const double sums_bytes = row_bytes * nkeys; - // On Ampere, unsorted atomics still mostly hit L2 until the sums exceed the whole L2. On RTX - // Blackwell (cc 12, GDDR7) sorting already wins for small inputs and sums of a quarter of L2. - const double sums_limit = cc_major == 12 ? 0.25 * l2_bytes - : cc_major >= 9 ? 0.5 * l2_bytes - : 1.0 * l2_bytes; - const double input_limit = cc_major == 12 ? 6.0 * l2_bytes : 40.0 * l2_bytes; - return row_bytes >= 2048 && input_bytes >= input_limit && sums_bytes > sums_limit; -} - -enum class sum_rows_by_key_kernel { per_element, per_float4, per_warp, sorted }; +enum class sum_rows_by_key_kernel { elementwise, few_keys, sorted }; struct sum_rows_by_key_plan { sum_rows_by_key_kernel kernel; + int vec_len; uint32_t block_dim; }; /** - * Kernel selection decision point: (Heuristically tuned on A100, H100, B100 and RTX PRO 6000) - * - per_float4: float rows of whole 16-byte vectors narrower than max_cols_float4 and 16-byte - * alignment holds; - * - per_element: other narrow rows (ncols < min_cols_per_warp), where a warp per row idles lanes - * or 16-byte alignment doesn't hold. - * - sorted: long rows whose sums do not fit in L2 (sum_rows_by_key_use_sorted); - * - per_warp: everything else. + * Kernel selection based on the problem size */ template sum_rows_by_key_plan sum_rows_by_key_select_kernel( const DataIteratorT d_A, IdxT lda, IdxT nrows, IdxT ncols, IdxT nkeys, const SumsT* d_sums) { - int dev_id, cc_major, l2_bytes; + constexpr double kSortedMinRowsPerKey = 5000; + constexpr double kSortedMinRowBytes = 512; + constexpr double kSortedMinInputBytes = 128.0 * 1024 * 1024; + // Few keys and narrow rows: per-block sums in shared memory. + constexpr IdxT kFewKeysMaxCols = 32; + constexpr IdxT kFewKeysMaxKeys = 100; + + int dev_id, cc_major; RAFT_CUDA_TRY(cudaGetDevice(&dev_id)); RAFT_CUDA_TRY(cudaDeviceGetAttribute(&cc_major, cudaDevAttrComputeCapabilityMajor, dev_id)); - RAFT_CUDA_TRY(cudaDeviceGetAttribute(&l2_bytes, cudaDevAttrL2CacheSize, dev_id)); - - // Fewest columns for which the per-warp kernel beats the per-element one - const IdxT min_cols_per_warp = sizeof(SumsT) > 4 ? 64 - : cc_major == 10 ? 42 - : (cc_major >= 9 && cc_major != 12) ? 32 - : 48; - - const IdxT max_cols_float4 = cc_major == 10 ? 256 - : cc_major == 12 ? 64 - : cc_major >= 9 ? min_cols_per_warp - : 0; + // Select vectorized loads and vectorized atomic writes + bool whole_vectors = false; + /// plain float pointer if constexpr (std::is_same_v && (std::is_same_v || std::is_same_v)) { - if (ncols < max_cols_float4 && ncols % 4 == 0 && lda % 4 == 0 && raft::is_aligned(d_A, 16) && - raft::is_aligned(d_sums, 16)) { - return {sum_rows_by_key_kernel::per_float4, 128}; - } + /// 16-byte alignments + whole_vectors = + ncols % 4 == 0 && lda % 4 == 0 && raft::is_aligned(d_A, 16) && raft::is_aligned(d_sums, 16); } - if (ncols < min_cols_per_warp) { - // Larger blocks help on cc 10 and 12, where short-lived 128-thread blocks are launch-bound. - return {sum_rows_by_key_kernel::per_element, (cc_major == 10 || cc_major == 12) ? 256u : 128u}; + /// Hopper+ (sm_9x) supports float4 atomics + const int vec_len = whole_vectors && cc_major >= 9 ? 4 : 1; + + // Select kernel + if (ncols > 0 && ncols <= kFewKeysMaxCols && nkeys <= kFewKeysMaxKeys && + sum_rows_by_key_few_keys_fits(nkeys, ncols)) { + return {sum_rows_by_key_kernel::few_keys, 1, 0}; } - if (sum_rows_by_key_use_sorted(nrows, ncols, nkeys, l2_bytes, cc_major)) { - return {sum_rows_by_key_kernel::sorted, 0}; + const double row_bytes = static_cast(ncols) * sizeof(SumsT); + const bool contended = static_cast(nrows) >= kSortedMinRowsPerKey * nkeys; + const bool wide_large = + row_bytes >= kSortedMinRowBytes && row_bytes * nrows >= kSortedMinInputBytes; + if (static_cast(nkeys) <= std::numeric_limits::max() && + (contended || wide_large)) { + return {sum_rows_by_key_kernel::sorted, vec_len, 0}; } - return {sum_rows_by_key_kernel::per_warp, 0}; + return {sum_rows_by_key_kernel::elementwise, vec_len, 256u}; } template -void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, - IdxT lda, - const KeysIteratorT d_keys, - const WeightT* d_weights, - IdxT nrows, - IdxT ncols, - IdxT nkeys, - SumsT* d_sums, - cudaStream_t st, - bool dry_run) +void sum_rows_by_keyrowmajor(const DataIteratorT d_A, + IdxT lda, + const KeysIteratorT d_keys, + const WeightT* d_weights, + IdxT nrows, + IdxT ncols, + IdxT nkeys, + SumsT* d_sums, + cudaStream_t st, + bool dry_run) { const auto plan = sum_rows_by_key_select_kernel(d_A, lda, nrows, ncols, nkeys, d_sums); if (dry_run && plan.kernel != sum_rows_by_key_kernel::sorted) { return; } + + constexpr bool kCanVectorize = + std::is_same_v && + (std::is_same_v || std::is_same_v); + switch (plan.kernel) { - case sum_rows_by_key_kernel::per_float4: - if constexpr (std::is_same_v && (std::is_same_v || - std::is_same_v)) { - const IdxT nvecs = nrows * ncols / 4; - raft::launch_kernel( - st, - static_cast(ceildiv(nvecs, static_cast(plan.block_dim))), - plan.block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor_per_float4, - static_cast(d_A), - lda, - d_weights, - d_keys, - nvecs, - ncols, - d_sums); - } - break; - case sum_rows_by_key_kernel::per_element: - raft::launch_kernel( - st, - static_cast(ceildiv(nrows * ncols, static_cast(plan.block_dim))), - plan.block_dim, - sum_rows_by_key_large_nkeys_kernel_rowmajor_per_element, - d_A, - lda, - d_weights, - d_keys, - nrows, - ncols, - d_sums); - break; case sum_rows_by_key_kernel::sorted: - sum_rows_by_key_large_nkeys_rowmajor_sorted( + sum_rows_by_key_rowmajor_sorted( d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, st, dry_run); break; - case sum_rows_by_key_kernel::per_warp: - sum_rows_by_key_large_nkeys_rowmajor_per_warp(d_A, - lda, - d_keys, - static_cast(nullptr), - d_weights, - nrows, - ncols, - d_sums, - st); + case sum_rows_by_key_kernel::few_keys: + sum_rows_by_key_rowmajor_few_keys( + d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, st); + break; + case sum_rows_by_key_kernel::elementwise: + if constexpr (kCanVectorize) { + if (plan.vec_len == 4) { + sum_rows_by_key_rowmajor_elementwise<4>( + d_A, lda, d_keys, d_weights, nrows, ncols, d_sums, plan.block_dim, st); + break; + } + } + sum_rows_by_key_rowmajor_elementwise<1>( + d_A, lda, d_keys, d_weights, nrows, ncols, d_sums, plan.block_dim, st); break; } } @@ -656,7 +775,7 @@ void sum_rows_by_key_large_nkeys_rowmajor(const DataIteratorT d_A, * @param[in] lda Real row size for input data, d_A * @param[in] d_keys Keys for each row (1 x nrows) * @param[in] d_weights Weights for each observation in d_A (1 x nrows) - * @param[out] d_keys_char Scratch memory for conversion of keys to char + * @param[out] d_keys_char UNUSED, kept for compatibility * @param[in] nrows Number of rows in d_A and d_keys * @param[in] ncols Number of data columns in d_A * @param[in] nkeys Number of unique keys in d_keys @@ -692,18 +811,9 @@ void reduce_rows_by_key(const DataIteratorT d_A, // Following kernel needs memset if (reset_sums && !dry_run) { cudaMemsetAsync(d_sums, 0, ncols * nkeys * sizeof(SumsT), stream); } - if (d_keys_char != nullptr && nkeys <= SUM_ROWS_BY_KEY_SMALL_K_MAX_K) { - if (dry_run) { return; } - // sum_rows_by_key_small_k is BW bounded. d_keys is loaded ncols time - avoiding wasting BW - // with doubles we have ~20% speed up - with floats we can hope something around 2x - // Converting d_keys to char - convert_array(d_keys_char, d_keys, nrows, stream); - sum_rows_by_key_small_nkeys( - d_A, lda, d_keys_char, d_weights, nrows, ncols, nkeys, d_sums, stream); - } else { - sum_rows_by_key_large_nkeys_rowmajor( - d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, stream, dry_run); - } + (void)d_keys_char; + sum_rows_by_keyrowmajor( + d_A, lda, d_keys, d_weights, nrows, ncols, nkeys, d_sums, stream, dry_run); } /** @@ -717,7 +827,7 @@ void reduce_rows_by_key(const DataIteratorT d_A, * @param[in] d_A Input data array (lda x nrows) * @param[in] lda Real row size for input data, d_A * @param[in] d_keys Keys for each row (1 x nrows) - * @param d_keys_char Scratch memory for conversion of keys to char + * @param d_keys_char UNUSED, kept for compatibility * @param[in] nrows Number of rows in d_A and d_keys * @param[in] ncols Number of data columns in d_A * @param[in] nkeys Number of unique keys in d_keys diff --git a/cpp/include/raft/linalg/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/reduce_rows_by_key.cuh index e771e8d035..9023d087dd 100644 --- a/cpp/include/raft/linalg/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/reduce_rows_by_key.cuh @@ -42,7 +42,7 @@ void convert_array(IteratorT1 dst, IteratorT2 src, int n, cudaStream_t st) * @param[in] lda Real row size for input data, d_A * @param[in] d_keys Keys for each row (1 x nrows) * @param[in] d_weights Weights for each observation in d_A (1 x nrows) - * @param[out] d_keys_char Scratch memory for conversion of keys to char + * @param[out] d_keys_char Unused, kept for compatibility (formerly scratch for keys as char) * @param[in] nrows Number of rows in d_A and d_keys * @param[in] ncols Number of data columns in d_A * @param[in] nkeys Number of unique keys in d_keys @@ -82,7 +82,7 @@ void reduce_rows_by_key(const DataIteratorT d_A, * @param[in] d_A Input data array (lda x nrows) * @param[in] lda Real row size for input data, d_A * @param[in] d_keys Keys for each row (1 x nrows) - * @param d_keys_char Scratch memory for conversion of keys to char + * @param d_keys_char Unused, kept for compatibility (formerly scratch for keys as char) * @param[in] nrows Number of rows in d_A and d_keys * @param[in] ncols Number of data columns in d_A * @param[in] nkeys Number of unique keys in d_keys @@ -133,7 +133,8 @@ void reduce_rows_by_key(const DataIteratorT d_A, * @param[in] d_keys Keys for each row raft::device_vector_view (1 x nrows) * @param[out] d_sums Row sums by key raft::device_matrix_view (ncols x d_keys) * @param[in] n_unique_keys Number of unique keys in d_keys - * @param[out] d_keys_char Scratch memory for conversion of keys to char, raft::device_vector_view + * @param[out] d_keys_char Unused, kept for compatibility (formerly scratch for keys as char), + * raft::device_vector_view * @param[in] d_weights Weights for each observation in d_A raft::device_vector_view optional (1 * x nrows) * @param[in] reset_sums Whether to reset the output sums to zero before reducing diff --git a/cpp/tests/linalg/reduce_rows_by_key.cu b/cpp/tests/linalg/reduce_rows_by_key.cu index b12ba85f21..193bc1db1f 100644 --- a/cpp/tests/linalg/reduce_rows_by_key.cu +++ b/cpp/tests/linalg/reduce_rows_by_key.cu @@ -159,7 +159,7 @@ class ReduceRowTest : public ::testing::TestWithParam> { rmm::device_uvector scratch_buf; }; -// ReduceRowTestF +// ReduceRowTestFloat // 128 Obs, 32 cols, 6 clusters const std::vector> inputsf2 = {{0.000001f, 128, 32, 6, 1234ULL, false}, {0.000001f, 128, 32, 6, 1234ULL, true, 1.0}, @@ -174,7 +174,7 @@ TEST_P(ReduceRowTestF, Result) } INSTANTIATE_TEST_CASE_P(ReduceRowTests, ReduceRowTestF, ::testing::ValuesIn(inputsf2)); -// ReduceRowTestD +// ReduceRowTestDouble // 128 Obs, 32 cols, 6 clusters, double precision const std::vector> inputsd2 = { {0.00000001, 128, 32, 6, 1234ULL, false}, @@ -190,14 +190,14 @@ TEST_P(ReduceRowTestD, Result) } INSTANTIATE_TEST_CASE_P(ReduceRowTests, ReduceRowTestD, ::testing::ValuesIn(inputsd2)); -// ReduceRowTestSmallnKey +// ReduceRowTestFewKeys // 128 Obs, 32 cols, 3 clusters const std::vector> inputsf_small_nkey = { {0.000001f, 128, 32, 3, 1234ULL, false}, {0.000001f, 128, 32, 3, 1234ULL, true, 5.0}, {0.000001f, 128, 32, 3, 1234ULL, true, 8.0}}; -typedef ReduceRowTest ReduceRowTestSmallnKey; -TEST_P(ReduceRowTestSmallnKey, Result) +typedef ReduceRowTest ReduceRowTestFewKeys; +TEST_P(ReduceRowTestFewKeys, Result) { ASSERT_TRUE(raft::devArrMatch(out_ref.data(), out.data(), @@ -205,7 +205,7 @@ TEST_P(ReduceRowTestSmallnKey, Result) raft::CompareApprox(params.tolerance))); } INSTANTIATE_TEST_CASE_P(ReduceRowTests, - ReduceRowTestSmallnKey, + ReduceRowTestFewKeys, ::testing::ValuesIn(inputsf_small_nkey)); // ReduceRowTestBigSpace @@ -262,14 +262,14 @@ INSTANTIATE_TEST_CASE_P(ReduceRowTests, ReduceRowTestManyClusters, ::testing::ValuesIn(inputsf_many_cluster)); -// ReduceRowTestVectorized -// 100000 Obs, 16 cols, 2048 clusters: Should trigger the vectorized kernel on GPU newer than 9.0. +// ReduceRowTestLargeClustersAndCols +// 100000 Obs, 5000 cols, 3072 clusters: Should trigger the vectorized kernel on GPU newer than 9.0. const std::vector> inputsf_vectorized = { - {0.00001f, 100000, 16, 2048, 1234ULL, false}, - {0.00001f, 100000, 16, 2048, 1234ULL, true, 32.0}, - {0.00001f, 100000, 16, 2048, 1234ULL, true, 16.0}}; -typedef ReduceRowTest ReduceRowTestVectorized; -TEST_P(ReduceRowTestVectorized, Result) + {0.00001f, 100000, 5000, 3072, 1234ULL, false}, + {0.00001f, 100000, 5000, 3072, 1234ULL, true, 32.0}, + {0.00001f, 100000, 5000, 3072, 1234ULL, true, 16.0}}; +typedef ReduceRowTest ReduceRowTestLargeClustersAndCols; +TEST_P(ReduceRowTestLargeClustersAndCols, Result) { ASSERT_TRUE(raft::devArrMatch(out_ref.data(), out.data(), @@ -277,7 +277,7 @@ TEST_P(ReduceRowTestVectorized, Result) raft::CompareApprox(params.tolerance))); } INSTANTIATE_TEST_CASE_P(ReduceRowTests, - ReduceRowTestVectorized, + ReduceRowTestLargeClustersAndCols, ::testing::ValuesIn(inputsf_vectorized)); TEST(ReduceRowsByKeyDryRun, SortedPathAllocations) @@ -302,16 +302,16 @@ TEST(ReduceRowsByKeyDryRun, SortedPathAllocations) const size_t expected = 4 * nrows * sizeof(uint32_t) + sort_bytes; auto action = [&](raft::resources const& res) { - detail::sum_rows_by_key_large_nkeys_rowmajor_sorted(in.data(), - ncols, - keys.data(), - static_cast(nullptr), - nrows, - ncols, - nkeys, - sums.data(), - resource::get_cuda_stream(res).get(), - resource::get_dry_run_flag(res)); + detail::sum_rows_by_key_rowmajor_sorted(in.data(), + ncols, + keys.data(), + static_cast(nullptr), + nrows, + ncols, + nkeys, + sums.data(), + resource::get_cuda_stream(res).get(), + resource::get_dry_run_flag(res)); }; const auto dry = raft::util::dry_run_execute(handle, action); EXPECT_EQ(dry.device_global, expected); From 9860e6427178f192ce9d3fe04e216c1cbc9a51cd Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Wed, 4 Nov 2026 09:35:19 +0000 Subject: [PATCH 14/15] Tune: Few-keys kernel available up to 128 features (incl. DEEP dataset) --- cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh | 10 ++++++---- cpp/tests/linalg/reduce_rows_by_key.cu | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index d2dbebefd6..b19d40471e 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -388,7 +388,7 @@ void sum_rows_by_key_rowmajor_few_keys(const DataIteratorT d_A, const auto block_dim = static_cast(n_copies * ncols); const int blocks_per_sm = block_dim >= 256 ? 2 : 4; const IdxT rows_per_block = - ceildiv(nrows, IdxT{blocks_per_sm} * raft::getMultiProcessorCount()); + ceildiv(nrows, static_cast(blocks_per_sm) * raft::getMultiProcessorCount()); const auto grid_dim = static_cast(ceildiv(nrows, rows_per_block)); raft::launch_kernel({st, copy_bytes * n_copies}, grid_dim, @@ -680,8 +680,9 @@ sum_rows_by_key_plan sum_rows_by_key_select_kernel( constexpr double kSortedMinRowBytes = 512; constexpr double kSortedMinInputBytes = 128.0 * 1024 * 1024; // Few keys and narrow rows: per-block sums in shared memory. - constexpr IdxT kFewKeysMaxCols = 32; - constexpr IdxT kFewKeysMaxKeys = 100; + constexpr IdxT kFewKeysMaxCols = 128; + constexpr IdxT kFewKeysMaxKeys = 100; + constexpr size_t kFewKeysMaxCopyBytes = kFewKeysSmemBytes / 2; // at least 2 copies int dev_id, cc_major; RAFT_CUDA_TRY(cudaGetDevice(&dev_id)); @@ -701,7 +702,8 @@ sum_rows_by_key_plan sum_rows_by_key_select_kernel( // Select kernel if (ncols > 0 && ncols <= kFewKeysMaxCols && nkeys <= kFewKeysMaxKeys && - sum_rows_by_key_few_keys_fits(nkeys, ncols)) { + sizeof(SumsT) * static_cast(nkeys) * static_cast(ncols) <= + kFewKeysMaxCopyBytes) { return {sum_rows_by_key_kernel::few_keys, 1, 0}; } const double row_bytes = static_cast(ncols) * sizeof(SumsT); diff --git a/cpp/tests/linalg/reduce_rows_by_key.cu b/cpp/tests/linalg/reduce_rows_by_key.cu index 193bc1db1f..005326685e 100644 --- a/cpp/tests/linalg/reduce_rows_by_key.cu +++ b/cpp/tests/linalg/reduce_rows_by_key.cu @@ -191,11 +191,12 @@ TEST_P(ReduceRowTestD, Result) INSTANTIATE_TEST_CASE_P(ReduceRowTests, ReduceRowTestD, ::testing::ValuesIn(inputsd2)); // ReduceRowTestFewKeys -// 128 Obs, 32 cols, 3 clusters +// 128 Obs, 32-128 cols, 3-10 clusters const std::vector> inputsf_small_nkey = { {0.000001f, 128, 32, 3, 1234ULL, false}, {0.000001f, 128, 32, 3, 1234ULL, true, 5.0}, - {0.000001f, 128, 32, 3, 1234ULL, true, 8.0}}; + {0.000001f, 128, 32, 3, 1234ULL, true, 8.0}, + {0.00001f, 10000, 128, 10, 1234ULL, true, 4.0}}; // widest few-keys rows typedef ReduceRowTest ReduceRowTestFewKeys; TEST_P(ReduceRowTestFewKeys, Result) { From fcf2349ecc6deb060abfc792083e0868f100624b Mon Sep 17 00:00:00 2001 From: Huy Nguyen Date: Thu, 5 Nov 2026 08:28:04 +0000 Subject: [PATCH 15/15] Remove used colmajor code --- .../raft/linalg/detail/reduce_rows_by_key.cuh | 94 ------------------- 1 file changed, 94 deletions(-) diff --git a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh index b19d40471e..40bf19dd4d 100644 --- a/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh +++ b/cpp/include/raft/linalg/detail/reduce_rows_by_key.cuh @@ -69,100 +69,6 @@ template inline constexpr bool is_floating_point_v = std::is_floating_point_v || std::is_same_v || std::is_same_v; -// -// Reduce by keys - large number of keys -// Computing a "weighted histogram" with local histograms in smem -// Keeping it simple - not optimized -// - -#define SUM_ROWS_BY_KEY_LARGE_K_MAX_K 1024 - -template -RAFT_KERNEL sum_rows_by_key_large_nkeys_kernel_colmajor(const DataIteratorT d_A, - IdxT lda, - KeysIteratorT d_keys, - const WeightT* d_weights, - IdxT nrows, - IdxT ncols, - int key_offset, - IdxT nkeys, - SumsT* d_sums) -{ - typedef typename std::iterator_traits::value_type KeyType; - typedef typename std::iterator_traits::value_type DataType; - __shared__ SumsT local_sums[SUM_ROWS_BY_KEY_LARGE_K_MAX_K]; - - for (IdxT local_key = threadIdx.x; local_key < nkeys; local_key += blockDim.x) - local_sums[local_key] = 0.0; - - for (IdxT idim = blockIdx.y; idim < ncols; idim += gridDim.y) { - __syncthreads(); // local_sums - - // At this point local_sums if full of zeros - - for (IdxT irow = blockIdx.x * blockDim.x + threadIdx.x; irow < nrows; - irow += blockDim.x * gridDim.x) { - // Branch div in this loop - not an issue with current code - DataType val = d_A[idim * lda + irow]; - if (d_weights) val = val * d_weights[irow]; - - IdxT local_key = d_keys[irow] - key_offset; - - // We could load next val here - raft::myAtomicAdd(&local_sums[local_key], static_cast(val)); - } - - __syncthreads(); // local_sums - - for (IdxT local_key = threadIdx.x; local_key < nkeys; local_key += blockDim.x) { - SumsT local_sum = local_sums[local_key]; - - if (local_sum != 0.0) { - KeyType global_key = key_offset + local_key; - raft::myAtomicAdd(&d_sums[global_key * ncols + idim], local_sum); - local_sums[local_key] = 0.0; - } - } - } -} - -template -void sum_rows_by_key_large_nkeys_colmajor(const DataIteratorT d_A, - IdxT lda, - KeysIteratorT d_keys, - IdxT nrows, - IdxT ncols, - int key_offset, - IdxT nkeys, - SumsT* d_sums, - cudaStream_t st) -{ - dim3 grid, block; - block.x = 256; - block.y = 1; // Necessary - - grid.x = raft::ceildiv(nrows, (IdxT)block.x); - grid.x = std::min(grid.x, 32u); - grid.y = ncols; - grid.y = std::min(grid.y, MAX_BLOCKS); - raft::launch_kernel(st, - grid, - block, - sum_rows_by_key_large_nkeys_kernel_colmajor, - d_A, - lda, - d_keys, - nrows, - ncols, - key_offset, - nkeys, - d_sums); -} - /** (Vectorized) load */ template DI void sum_rows_by_key_load(const DataIteratorT d_A, IdxT idx, bool valid, SumsT (&v)[VecLen])