Repository navigation
Balanced kmeans gpu fine partition #3016
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
rapids-bot
merged 5 commits into
NVIDIA:main
from
sherylll:balanced-kmeans-gpu-fine-partition
Nov 6, 2026
+75
−38
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
68979e3
Partition rows by mesocluster on the GPU in balanced k-means
sherylll d7afac1
Compute the radix sort bit count with std::bit_width
sherylll 9a2b15f
Merge branch 'main' into balanced-kmeans-gpu-fine-partition
sherylll 1cd0480
Drop managed memory from IVF-PQ per-cluster codebook training
sherylll 0694e76
Drop thrust sequence
sherylll File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
Partition rows by mesocluster on the GPU in balanced k-means
build_fine_clusters scanned all mesocluster labels on the host once per mesocluster, through managed memory, leaving the GPU idle in the fine stage. Group row ids by label with one device radix sort instead and slice each mesocluster's range by the size prefix sum. This also drops the hard-coded managed_memory_resource in favor of the handle's workspace resources. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Loading branch information
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,12 +35,13 @@ | |
| #include <raft/util/integer_utils.hpp> | ||
|
|
||
| #include <rmm/device_scalar.hpp> | ||
| #include <rmm/mr/managed_memory_resource.hpp> | ||
| #include <rmm/resource_ref.hpp> | ||
|
|
||
| #include <cub/device/device_radix_sort.cuh> | ||
| #include <thrust/gather.h> | ||
| #include <thrust/iterator/counting_iterator.h> | ||
| #include <thrust/iterator/transform_iterator.h> | ||
| #include <thrust/sequence.h> | ||
| #include <thrust/transform.h> | ||
|
|
||
| #include "../../neighbors/detail/ann_utils.cuh" | ||
|
|
@@ -1341,18 +1342,22 @@ inline auto arrange_fine_clusters(IdxT n_clusters, | |
| * Given the (coarse) mesoclusters and the distribution of fine clusters within them, | ||
| * build the fine clusters. | ||
| * | ||
| * Processing one mesocluster at a time: | ||
| * The row ids are first grouped by mesocluster on the device (a stable sort by label), so that | ||
| * each mesocluster's rows are a contiguous range in row order. Then, one mesocluster at a time: | ||
| * 1. Copy mesocluster data into a separate buffer | ||
| * 2. Predict fine cluster | ||
| * 3. Refince the fine cluster centers | ||
| * 3. Refine the fine cluster centers | ||
| * | ||
| * As a result, the fine clusters are what is returned by `build_hierarchical`; | ||
| * this function returns the total number of fine clusters, which can be checked to be | ||
| * the same as the requested number of clusters. | ||
| * | ||
| * Note: this function uses at most `fine_clusters_nums_max` points per mesocluster for training; | ||
| * Note: this function uses at most `mesocluster_size_max` points per mesocluster for training; | ||
| * if one of the clusters is larger than that (as given by `mesocluster_sizes`), the extra data | ||
| * is ignored. | ||
| * | ||
| * `labels` is a device pointer [n_rows]; `mesocluster_sizes`, `fine_clusters_nums` and | ||
| * `fine_clusters_csum` are host pointers [n_mesoclusters] (the sizes must count `labels`). | ||
| */ | ||
| template <typename T, | ||
| typename MathT, | ||
|
|
@@ -1365,7 +1370,7 @@ auto build_fine_clusters(const raft::resources& handle, | |
| IdxT dim, | ||
| const T* dataset_mptr, | ||
| const MathT* dataset_norm_mptr, | ||
| const LabelT* labels_mptr, | ||
| const LabelT* labels, | ||
| IdxT n_rows, | ||
| const IdxT* fine_clusters_nums, | ||
| const IdxT* fine_clusters_csum, | ||
|
|
@@ -1375,18 +1380,52 @@ auto build_fine_clusters(const raft::resources& handle, | |
| IdxT fine_clusters_nums_max, | ||
| MathT* cluster_centers, | ||
| MappingOpT mapping_op, | ||
| rmm::device_async_resource_ref managed_memory, | ||
| rmm::device_async_resource_ref device_memory) -> IdxT | ||
| { | ||
| auto stream = raft::resource::get_cuda_stream(handle); | ||
| IdxT transformed_dim = centers_dim<T>(dim, params.is_packed_binary); | ||
| rmm::device_uvector<IdxT> mc_trainset_ids_buf(mesocluster_size_max, stream, managed_memory); | ||
| // for small cluster counts the maximum mesocluster size is proportional to the number of rows, so | ||
| // we use large workspace | ||
| auto large_ws = raft::resource::get_large_workspace_resource_ref(handle); | ||
|
|
||
| // Row ids grouped by mesocluster, in row order within each, so that each mesocluster's training | ||
| // rows are a contiguous range (the first `mesocluster_size_max` of them, as before) | ||
| rmm::device_uvector<IdxT> grouped_ids(n_rows, stream, large_ws); | ||
| { | ||
| rmm::device_uvector<IdxT> row_ids(n_rows, stream, large_ws); | ||
| rmm::device_uvector<LabelT> sorted_labels(n_rows, stream, large_ws); | ||
| thrust::sequence(raft::resource::get_thrust_policy(handle), row_ids.begin(), row_ids.end()); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Plese use raft::linalg::map_offset(raft::identity_op) for this. |
||
| int end_bit = 1; | ||
| while (end_bit < static_cast<int>(sizeof(LabelT) * 8) && | ||
| (uint64_t{1} << end_bit) < static_cast<uint64_t>(n_mesoclusters)) { | ||
| end_bit++; | ||
| } | ||
| size_t sort_bytes = 0; | ||
| RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs(nullptr, | ||
| sort_bytes, | ||
| labels, | ||
| sorted_labels.data(), | ||
| row_ids.data(), | ||
| grouped_ids.data(), | ||
| n_rows, | ||
| 0, | ||
| end_bit, | ||
| stream.get())); | ||
| rmm::device_uvector<char> sort_ws(sort_bytes, stream, device_memory); | ||
| RAFT_CUDA_TRY(cub::DeviceRadixSort::SortPairs(sort_ws.data(), | ||
| sort_bytes, | ||
| labels, | ||
| sorted_labels.data(), | ||
| row_ids.data(), | ||
| grouped_ids.data(), | ||
| n_rows, | ||
| 0, | ||
| end_bit, | ||
| stream.get())); | ||
| } | ||
|
|
||
| rmm::device_uvector<T> mc_trainset_buf(mesocluster_size_max * dim, stream, large_ws); | ||
| rmm::device_uvector<MathT> mc_trainset_norm_buf(mesocluster_size_max, stream, device_memory); | ||
| auto mc_trainset_ids = mc_trainset_ids_buf.data(); | ||
| auto mc_trainset = mc_trainset_buf.data(); | ||
| auto mc_trainset_norm = mc_trainset_norm_buf.data(); | ||
|
|
||
|
|
@@ -1401,16 +1440,12 @@ auto build_fine_clusters(const raft::resources& handle, | |
|
|
||
| // Training clusters in each meso-cluster | ||
| IdxT n_clusters_done = 0; | ||
| IdxT mc_offset = 0; | ||
| for (IdxT i = 0; i < n_mesoclusters; i++) { | ||
| IdxT k = 0; | ||
| for (IdxT j = 0; j < n_rows && k < mesocluster_size_max; j++) { | ||
| if (labels_mptr[j] == LabelT(i)) { mc_trainset_ids[k++] = j; } | ||
| } | ||
| if (k != static_cast<IdxT>(mesocluster_sizes[i])) | ||
| RAFT_LOG_DEBUG("Incorrect mesocluster size at %d. %zu vs %zu", | ||
| static_cast<int>(i), | ||
| static_cast<size_t>(k), | ||
| static_cast<size_t>(mesocluster_sizes[i])); | ||
| const auto mc_size = static_cast<IdxT>(mesocluster_sizes[i]); | ||
| const IdxT k = std::min(mc_size, mesocluster_size_max); | ||
| const IdxT* mc_trainset_ids = grouped_ids.data() + mc_offset; | ||
| mc_offset += mc_size; | ||
| if (k == 0) { | ||
| RAFT_LOG_DEBUG("Empty cluster %d", i); | ||
| RAFT_EXPECTS(fine_clusters_nums[i] == 0, | ||
|
|
@@ -1458,7 +1493,6 @@ auto build_fine_clusters(const raft::resources& handle, | |
| fine_clusters_nums[i] * transformed_dim), | ||
| raft::make_device_vector_view<const MathT>(mc_trainset_ccenters.data(), | ||
| fine_clusters_nums[i] * transformed_dim)); | ||
| raft::resource::sync_stream(handle, stream); | ||
| n_clusters_done += fine_clusters_nums[i]; | ||
| } | ||
| return n_clusters_done; | ||
|
|
@@ -1505,8 +1539,6 @@ void build_hierarchical(const raft::resources& handle, | |
| IdxT n_mesoclusters = std::min(n_clusters, static_cast<IdxT>(std::sqrt(n_clusters) + 0.5)); | ||
| RAFT_LOG_DEBUG("build_hierarchical: n_mesoclusters: %u", n_mesoclusters); | ||
|
|
||
| // TODO: Remove the explicit managed memory- we shouldn't be creating this on the user's behalf. | ||
| rmm::mr::managed_memory_resource managed_memory; | ||
| rmm::device_async_resource_ref device_memory = raft::resource::get_workspace_resource_ref(handle); | ||
| auto [max_minibatch_size, mem_per_row] = calc_minibatch_size<MathT>( | ||
| handle, n_clusters, n_rows, transformed_dim, params.metric, !std::is_same_v<T, MathT>); | ||
|
|
@@ -1558,8 +1590,9 @@ void build_hierarchical(const raft::resources& handle, | |
| CounterT; | ||
|
|
||
| // build coarse clusters (mesoclusters) | ||
| rmm::device_uvector<LabelT> mesocluster_labels_buf(n_rows, stream, managed_memory); | ||
| rmm::device_uvector<CounterT> mesocluster_sizes_buf(n_mesoclusters, stream, managed_memory); | ||
| rmm::device_uvector<LabelT> mesocluster_labels_buf( | ||
| n_rows, stream, raft::resource::get_large_workspace_resource_ref(handle)); | ||
| rmm::device_uvector<CounterT> mesocluster_sizes_buf(n_mesoclusters, stream, device_memory); | ||
| { | ||
| rmm::device_uvector<MathT> mesocluster_centers_buf( | ||
| n_mesoclusters * transformed_dim, stream, device_memory); | ||
|
|
@@ -1577,10 +1610,12 @@ void build_hierarchical(const raft::resources& handle, | |
| dataset_norm); | ||
| } | ||
|
|
||
| auto mesocluster_sizes = mesocluster_sizes_buf.data(); | ||
| auto mesocluster_labels = mesocluster_labels_buf.data(); | ||
|
|
||
| std::vector<CounterT> mesocluster_sizes_host(n_mesoclusters); | ||
| raft::update_host( | ||
| mesocluster_sizes_host.data(), mesocluster_sizes_buf.data(), n_mesoclusters, stream); | ||
| raft::resource::sync_stream(handle, stream); | ||
| auto mesocluster_sizes = mesocluster_sizes_host.data(); | ||
| auto mesocluster_labels = mesocluster_labels_buf.data(); | ||
|
|
||
| // build fine clusters | ||
| auto [mesocluster_size_max, fine_clusters_nums_max, fine_clusters_nums, fine_clusters_csum] = | ||
|
|
@@ -1616,7 +1651,6 @@ void build_hierarchical(const raft::resources& handle, | |
| fine_clusters_nums_max, | ||
| cluster_centers, | ||
| mapping_op, | ||
| managed_memory, | ||
| device_memory); | ||
| RAFT_EXPECTS(n_clusters_done == n_clusters, "Didn't process all clusters."); | ||
|
|
||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Skip the radix sort when there is one mesocluster.
When
n_clustersis one or two,build_hierarchicalsetsn_mesoclustersto one. Every row then has the same mesocluster label. This path still allocatesrow_ids,sorted_labels, and CUB sort workspace, although sorting cannot change the row order. On a large input, those avoidable device allocations can makefitfail with out-of-memory. Initializegrouped_idsas a sequence in this case, and run the sort only whenn_mesoclusters > 1. (raw.githubusercontent.com)As per coding guidelines, “Resource exhaustion (GPU memory)” requires review attention.
Source: Coding guidelines