Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
8b35602
Add SuperKMeans k-means API with an unpruned fallback
sherylll Oct 26, 2026
e83a28f
Add SuperKMeans' fused first-filter cuTile kernel
sherylll Oct 26, 2026
19b3fb4
Add SuperKMeans' pruned assignment
sherylll Oct 26, 2026
443bb05
Order SuperKMeans' pruning by survivor count (LPT)
sherylll Oct 26, 2026
669fcc1
Run SuperKMeans' row batches on the handle's stream pool
sherylll Oct 26, 2026
844f2f0
Move SuperKMeans' pruned assignment into a pruned 1-NN distance
sherylll Oct 26, 2026
4bf9ccc
Prune survivor lists in place, out of shared memory
sherylll Oct 28, 2026
18779b1
Write one contiguous first-filter survivor list per row
sherylll Oct 28, 2026
e58ee5c
Prune only with dims past the first filter's; simplify the kernel
sherylll Oct 28, 2026
1edbba5
Return early from pruning rows with no survivors
sherylll Oct 28, 2026
75ea3ab
Overlap row batches on the main stream and one pool stream
sherylll Oct 28, 2026
fca97b1
Fix style: SuperKMeans API reference, formatting, copyright
sherylll Oct 28, 2026
2d869df
Compute the filter's norms from its FP16 values, with the FP16 copy
sherylll Oct 30, 2026
6a2ae57
Compute the pruning ratios from eps0 in the kernel, not from a device…
sherylll Nov 2, 2026
a57a157
Assign in full for half rows the filter can't read in place; document…
sherylll Nov 2, 2026
e7cb068
Load the pruning kernel's tiles in 16-byte loads; drop its launch bounds
sherylll Nov 2, 2026
0ee37a6
Add license
sherylll Nov 3, 2026
e02f9db
Replace custom warp reduce with cub::WarpReduceBatched
sherylll Nov 3, 2026
31b9674
Merge branch 'main' into superkmeans
sherylll Nov 4, 2026
6b3a662
Hardcode eps0
sherylll Nov 5, 2026
f2355d4
Halve pruned 1-NN centroid batch to 1024
sherylll Nov 6, 2026
9565eb9
Merge branch 'main' into superkmeans
sherylll Nov 6, 2026
4760f3b
Merge branch 'main' into superkmeans
sherylll Nov 8, 2026
79bdbba
Prepare SuperKMeans filter rows per batch
sherylll Nov 9, 2026
b3e9476
Require supported layouts for high-dimensional SuperKMeans pruning
sherylll Nov 9, 2026
a71429f
Size SuperKMeans row batches from workspace budget
sherylll Nov 9, 2026
3b2571b
Tune tile sizes for different arch (coarsely)
sherylll Nov 9, 2026
4c2585a
Fix style
sherylll Nov 9, 2026
26372e2
Add sm103 for completeness; update tile sizes based on measurements on
sherylll Nov 10, 2026
0bbf70c
Merge upstream/main into superkmeans
sherylll Nov 11, 2026
78d844a
Remove duplicate kmeans_type definition
sherylll Nov 11, 2026
5a45435
Small refactor
sherylll Nov 11, 2026
976b372
More refactoring: in F32 mode, use F32 data to calculate norm, even t…
sherylll Nov 11, 2026
f92bdc4
Use raft launch_kernel
sherylll Nov 12, 2026
6f9fb0a
Peel single-survivor tail from pruned nearest-neighbor search
sherylll Nov 13, 2026
91ee26a
Order pruning rows from each fused-filter tile
sherylll Nov 13, 2026
7054a3f
Small cleanup
sherylll Nov 16, 2026
3e2964b
Merge branch 'release/26.12' into superkmeans
sherylll Nov 16, 2026
e3a2550
Mark SuperKMeans API experimental
sherylll Nov 18, 2026
0a70f8c
Use RAFT warp primitives in pruned assignment
sherylll Nov 18, 2026
572253e
Support partial dimension tiles in pruned assignment
sherylll Nov 18, 2026
d2713a5
Remove redundant initial survivor check in prune
sherylll Nov 18, 2026
7fa7a8b
Merge branch 'release/26.12' into superkmeans
sherylll Nov 18, 2026
8cb98b7
Simplify prune survivor arguments and use RAFT warp helpers
sherylll Nov 18, 2026
29970b1
Use workspace memory and dry-run sizing in SuperKMeans
sherylll Nov 19, 2026
82ac907
Add NVTX ranges for pruned 1-NN filter and pruning
sherylll Nov 19, 2026
20e5fbb
Use dry-run execution and round up SuperKMeans batches
sherylll Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Order SuperKMeans' pruning by survivor count (LPT)
Within a row batch the pruning kernel takes the rows with the most
first-filter survivors in the previous iteration first, as SuperKMeans
does: the kernel counts each row's survivors and an approximate
segmented radix sort of the counts orders the next call's rows. The
smoke test now has several row batches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
sherylll and claude committed Nov 2, 2026
commit 443bb05b03c2123d747d1e1e55e9eb67de555e2c
103 changes: 94 additions & 9 deletions cpp/src/cluster/detail/superkmeans.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@
#include <raft/core/device_mdarray.hpp>
#include <raft/core/error.hpp>
#include <raft/core/resource/cuda_stream.hpp>
#include <raft/core/resource/device_memory_resource.hpp>
#include <raft/core/resources.hpp>
#include <raft/linalg/map.cuh>
#include <raft/linalg/map_then_reduce.cuh>
#include <raft/matrix/sample_rows.cuh>
#include <raft/random/rng_state.hpp>
#include <raft/util/cudart_utils.hpp>

#include <rmm/device_uvector.hpp>

#include <cub/device/device_segmented_radix_sort.cuh>

#include <algorithm>
#include <optional>
#include <type_traits>
Expand Down Expand Up @@ -114,12 +119,29 @@ void copy_first_columns(
});
}

/** Each row's id within its row batch, and the row batches' bounds (n_row_batches + 1). */
inline void row_batch_layout(const raft::resources& handle,
int64_t n_rows,
raft::device_vector_view<uint32_t, int64_t> local_ids,
raft::device_vector_view<int64_t, int64_t> batch_offsets)
{
raft::linalg::map_offset(handle, local_ids, [] __device__(int64_t i) {
return static_cast<uint32_t>(i % kRowBatchSize);
});
raft::linalg::map_offset(handle, batch_offsets, [n_rows] __device__(int64_t b) {
return b * kRowBatchSize < n_rows ? b * kRowBatchSize : n_rows;
});
}

/**
* The pruned assignment: from each row's current centroid, the fused partial GEMM over the first
* kDimTileSize dims with the first filter, then the pruning kernel on the survivors' tail dims.
* Rows go in batches of kRowBatchSize against centroid batches of kCentroidBatchSize. The filter
* runs on FP16: float rows are filtered on half copies of their first dims, and the centroids the
* kernels read are T, a half copy of the float centroids for half rows.
*
* Within a row batch the pruning kernel's blocks take the heaviest rows first (LPT): the rows
* ordered by their first-filter survivors in the previous call.
*/
template <typename T>
class pruned_assignment {
Expand All @@ -135,11 +157,17 @@ class pruned_assignment {
n_clusters_(n_clusters),
filter_dim_(std::is_same_v<T, half> ? dim_ : kDimTileSize),
tile_(tile),
n_row_batches_(raft::ceildiv(n_rows_, kRowBatchSize)),
n_col_tiles_(raft::ceildiv<int64_t>(kCentroidBatchSize, tile.tile_n)),
ratios_(raft::make_device_vector<float, int64_t>(handle, dim_ + 1)),
row_norms_(raft::make_device_vector<float, int64_t>(handle, n_rows_)),
centroid_norms_(raft::make_device_vector<float, int64_t>(handle, n_clusters)),
dist_(raft::make_device_vector<float, int64_t>(handle, n_rows_)),
survivors_(raft::make_device_vector<uint32_t, int64_t>(handle, n_rows_)),
row_order_(raft::make_device_vector<uint32_t, int64_t>(handle, n_rows_)),
local_ids_(raft::make_device_vector<uint32_t, int64_t>(handle, n_rows_)),
sorted_keys_(raft::make_device_vector<uint32_t, int64_t>(handle, n_rows_)),
batch_offsets_(raft::make_device_vector<int64_t, int64_t>(handle, n_row_batches_ + 1)),
filter_rows_(raft::make_device_matrix<half, int64_t>(
Comment thread
huuanhhuyn marked this conversation as resolved.
Resolved
handle, std::is_same_v<T, half> ? 0 : n_rows_, filter_dim_)),
filter_centroids_(raft::make_device_matrix<half, int64_t>(handle, n_clusters, filter_dim_)),
Expand All @@ -156,15 +184,22 @@ class pruned_assignment {
if constexpr (!std::is_same_v<T, half>) {
copy_columns(X.data_handle(), n_rows_, filter_rows_.view());
}
// LPT's sort: each row's id within its batch, and the batches' bounds
row_batch_layout(handle, n_rows_, local_ids_.view(), batch_offsets_.view());
// The host ratios are released when the copy is done
raft::resource::sync_stream(handle);
}

/** Updates `labels`, each row's centroid from the previous assignment, for `centroids`. */
/**
* Updates `labels`, each row's centroid from the previous assignment, for `centroids`.
* `order_next`: another call follows, so order the rows for it.
*/
void assign(raft::device_matrix_view<const float, int64_t> centroids,
raft::device_vector_view<uint32_t, int64_t> labels)
raft::device_vector_view<uint32_t, int64_t> labels,
bool order_next)
{
#if CUVS_CUTILE_ENABLED
auto stream = raft::resource::get_cuda_stream(handle_).get();
// The filter's FP16 copy of the centroids' first dims; for half rows, all dims, which is also
// the copy the other kernels read
copy_columns(centroids.data_handle(), n_clusters_, filter_centroids_.view());
Expand All @@ -179,12 +214,15 @@ class pruned_assignment {
}
squared_norms(
handle_, kernel_centroids, n_clusters_, dim_, kDimTileSize, centroid_norms_.data_handle());
RAFT_CUDA_TRY(
cudaMemsetAsync(survivors_.data_handle(), 0, survivors_.size() * sizeof(uint32_t), stream));

for (int64_t i = 0; i < n_rows_; i += kRowBatchSize) {
const int64_t n_rows = std::min(kRowBatchSize, n_rows_ - i);
const T* rows = X_.data_handle() + i * dim_;
uint32_t* row_labels = labels.data_handle() + i;
float* row_dist = dist_.data_handle() + i;
const int64_t n_rows = std::min(kRowBatchSize, n_rows_ - i);
const T* rows = X_.data_handle() + i * dim_;
uint32_t* row_labels = labels.data_handle() + i;
float* row_dist = dist_.data_handle() + i;
const uint32_t* order = has_row_order_ ? row_order_.data_handle() + i : nullptr;
// Each row's bound: its distance to its current centroid
distance_to_assigned(handle_, rows, n_rows, kernel_centroids, dim_, row_labels, row_dist);
for (int64_t j = 0; j < n_clusters_; j += kCentroidBatchSize) {
Expand All @@ -205,6 +243,7 @@ class pruned_assignment {
prune(handle_,
rows,
n_rows,
order,
kernel_centroids + j * dim_,
static_cast<uint32_t>(j),
dim_,
Expand All @@ -216,9 +255,14 @@ class pruned_assignment {
static_cast<uint32_t>(raft::ceildiv<int64_t>(n_centroids, tile_.tile_n)),
static_cast<uint32_t>(tile_.tile_n)},
row_labels,
row_dist);
row_dist,
survivors_.data_handle() + i);
}
}
if (order_next) {
order_rows_by_survivors(stream);
has_row_order_ = true;
}
#else
RAFT_FAIL("SuperKMeans pruning needs a build with cuTile");
#endif
Expand All @@ -232,13 +276,52 @@ class pruned_assignment {
copy_first_columns(handle_, in, n, dim_, filter_dim_, out.data_handle());
}

/**
* Each row batch's local row ids ordered by survivor count, descending, into row_order_.
* Approximate: one radix pass over the counts' top 8 significant bits (the counts are at most
* n_clusters), rows of a bucket keeping their order.
*/
void order_rows_by_survivors(cudaStream_t stream)
{
int end_bit = 1;
while (end_bit < 32 && (int64_t{1} << end_bit) <= n_clusters_) {
end_bit++;
}
Comment on lines +224 to +231

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this approach, but perhaps we can start with something smaller than n_rows?
Can we argue that there is a certain size, after which increasing it doesn't yield any performance improvement? For example, in IVF-PQ we limit the internal search batch to 4096 queries.

const int begin_bit = std::max(0, end_bit - 8);
auto sort = [&](void* temp, size_t& temp_bytes) {
RAFT_CUDA_TRY(
cub::DeviceSegmentedRadixSort::SortPairsDescending(temp,
temp_bytes,
survivors_.data_handle(),
sorted_keys_.data_handle(),
local_ids_.data_handle(),
row_order_.data_handle(),
n_rows_,
n_row_batches_,
batch_offsets_.data_handle(),
batch_offsets_.data_handle() + 1,
begin_bit,
end_bit,
stream));
};
size_t temp_bytes = 0;
sort(nullptr, temp_bytes);
rmm::device_uvector<char> temp(
temp_bytes, stream, raft::resource::get_workspace_resource_ref(handle_));
sort(temp.data(), temp_bytes);
}

const raft::resources& handle_;
raft::device_matrix_view<const T, int64_t> X_;
int64_t n_rows_, dim_, n_clusters_, filter_dim_;
fused_filter_tile tile_;
int64_t n_row_batches_;
int64_t n_col_tiles_;
float ratio_;
float ratio_ = 1.0f;
bool has_row_order_ = false;
raft::device_vector<float, int64_t> ratios_, row_norms_, centroid_norms_, dist_;
raft::device_vector<uint32_t, int64_t> survivors_, row_order_, local_ids_, sorted_keys_;
raft::device_vector<int64_t, int64_t> batch_offsets_;
raft::device_matrix<half, int64_t> filter_rows_, filter_centroids_;
raft::device_vector<int64_t, int64_t> packed_;
raft::device_vector<int32_t, int64_t> seg_count_;
Expand Down Expand Up @@ -299,7 +382,9 @@ void fit(const raft::resources& handle,

for (uint32_t iter = 0; iter < params.n_iters; iter++) {
if (pruned_assign.has_value() && iter > 0) {
pruned_assign->assign(raft::make_const_mdspan(centroids), assigned.view());
// The last pruned call orders no rows: the final labels come from a full assignment
pruned_assign->assign(
raft::make_const_mdspan(centroids), assigned.view(), iter + 1 < params.n_iters);
} else {
assign();
}
Expand Down
22 changes: 16 additions & 6 deletions cpp/src/cluster/detail/superkmeans/prune.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -253,29 +253,34 @@ __device__ inline uint32_t refilter(uint32_t n,
/**
* A warp per block and row, against one centroid batch: the row's first-filter survivors (partial
* distances over the first partial_dim dims), the tail dims in dim tiles with a re-filter after
* each but the last, then the argmin, kept if closer than the row's current centroid.
* each but the last, then the argmin, kept if closer than the row's current centroid. Block b
* handles row row_order[b] when given (heaviest rows first), and each row's first-filter survivors
* are added to `survivors`.
*/
template <typename T>
RAFT_KERNEL prune_kernel(const T* __restrict__ rows,
const uint32_t* __restrict__ row_order,
const T* __restrict__ centroids,
uint32_t centroid_offset,
uint32_t dim,
uint32_t partial_dim,
const float* __restrict__ ratios,
first_filter_lists lists,
uint32_t* __restrict__ labels,
float* __restrict__ dist)
float* __restrict__ dist,
uint32_t* __restrict__ survivors)
{
__shared__ survivor_id_t ids[kCentroidBatchSize];
__shared__ float distances[kCentroidBatchSize];
const uint32_t lane = threadIdx.x;
const int64_t row = blockIdx.x;
const int64_t row = row_order != nullptr ? row_order[blockIdx.x] : blockIdx.x;
const T* row_values = rows + row * dim;
uint32_t best_index = labels[row];
float best = dist[row];
const float bound = best;

uint32_t n_left = load_survivors(lists, row, ids, distances);
if (lane == 0) { survivors[row] += n_left; }
if (n_left == 0 || (n_left == 1 && centroid_offset + ids[0] == best_index)) { return; }

for (uint32_t d = partial_dim; d < dim && n_left; d += kDimTileSize) {
Expand Down Expand Up @@ -323,34 +328,39 @@ RAFT_KERNEL prune_kernel(const T* __restrict__ rows,
/**
* The pruning kernel for n_rows rows against one centroid batch (its first centroid
* centroid_offset), after the fused first filter wrote `lists`. `labels` and `dist` hold each
* row's current centroid and distance, and get the closer survivor if there is one.
* row's current centroid and distance, and get the closer survivor if there is one; `survivors`
* gets each row's first-filter survivors added. row_order (optional): the rows' order.
*/
template <typename T>
void prune(raft::resources const& handle,
const T* rows,
int64_t n_rows,
const uint32_t* row_order,
const T* centroids,
uint32_t centroid_offset,
int64_t dim,
uint32_t partial_dim,
const float* ratios,
first_filter_lists lists,
uint32_t* labels,
float* dist)
float* dist,
uint32_t* survivors)
{
RAFT_EXPECTS(partial_dim <= dim && (dim - partial_dim) % kDimTileSize == 0,
"SuperKMeans pruning needs dim - partial_dim to be a multiple of %u",
kDimTileSize);
prune_kernel<<<n_rows, kWarpSize, 0, raft::resource::get_cuda_stream(handle).get()>>>(
rows,
row_order,
centroids,
centroid_offset,
static_cast<uint32_t>(dim),
partial_dim,
ratios,
lists,
labels,
dist);
dist,
survivors);
RAFT_CUDA_TRY(cudaPeekAtLastError());
}

Expand Down
5 changes: 3 additions & 2 deletions cpp/tests/cluster/kmeans_superkmeans.cu
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,9 @@ TEST(KmeansSuperKMeans, Fallback)
*/
TEST(KmeansSuperKMeans, Pruned)
{
// Two centroid batches, the second partial, and two tail dim tiles (one re-filter)
constexpr int64_t n_rows = 20000;
// Three row batches, the last partial; two centroid batches, the second partial; and two tail
// dim tiles (one re-filter)
constexpr int64_t n_rows = 300000;
constexpr int64_t dim = 768;
constexpr int64_t n_clusters = 1100;
constexpr uint32_t n_iters = 8;
Expand Down