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
Add SuperKMeans' pruned assignment
After the first iteration, each row starts from its current centroid:
the fused first filter over the first 256 dims (FP16; float rows are
filtered on half copies), then a pruning kernel ported from SuperKMeans
that finishes the tail dims for the survivors with ADSampling re-filters
and keeps the closest. Rows and centroids go in fixed-size batches; d'
stays at 256 and there is no rotation, so the bound is a heuristic.
Builds or devices without the filter's cubin assign in full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
sherylll and claude committed Nov 2, 2026
commit 19b3fb42ba3a349fb5fe7a3093c83ecd69da6e5e
6 changes: 4 additions & 2 deletions cpp/include/cuvs/cluster/kmeans.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,10 @@ struct balanced_params : base_params {
*
* SuperKMeans is Lloyd's k-means with a pruned assignment step: the first iteration assigns every
* row with the fused 1-NN over all dimensions; later iterations compute partial distances over the
* first 256 dimensions, discard centroids that cannot beat a row's current one
* (ADSampling bound), and finish the remaining dimensions only for the survivors.
* first 256 dimensions, discard centroids that are unlikely to beat a row's current one (the
* ADSampling bound, without its random rotation), and finish the remaining dimensions only for the
* survivors. Pruning applies with more than 256 clusters and at least 256 dimensions, which must
* then be a multiple of 256; otherwise every iteration assigns with the full 1-NN.
*
* The number of clusters is taken from the `centroids` argument. The start centroids are rows
* sampled at random, as with kmeans::params::InitMethod::Random; all `n_iters` iterations run
Expand Down
217 changes: 187 additions & 30 deletions cpp/src/cluster/detail/superkmeans.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@

#include "../../neighbors/detail/ann_utils.cuh"
#include "../kmeans_balanced.cuh"
#include "superkmeans/cutile/fused_filter_tile.hpp"
#include "superkmeans/prune.cuh"

#include <cuvs/cluster/kmeans.hpp>
#include <raft/core/device_mdarray.hpp>
#include <raft/core/error.hpp>
#include <raft/core/resource/cuda_stream.hpp>
#include <raft/core/resource/thrust_policy.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 <thrust/reduce.h>

#include <algorithm>
#include <optional>
#include <type_traits>
Expand All @@ -28,8 +28,7 @@ namespace cuvs::cluster::kmeans::detail::superkmeans {

// Pruning works on whole dimension tiles and only pays off with enough centroids to discard; below
// that every iteration assigns with the full 1-NN.
constexpr int64_t kDimTileSize = 256;
constexpr int64_t kMinPrunedK = 256;
constexpr int64_t kMinPrunedK = 256;

inline bool prunes(int64_t n_clusters, int64_t dim)
{
Expand All @@ -43,24 +42,22 @@ auto inertia(const raft::resources& handle,
raft::device_matrix_view<const float, int64_t> centroids,
raft::device_vector_view<const uint32_t, int64_t> labels) -> float
{
const int64_t dim = X.extent(1);
auto dist = raft::make_device_vector<float, int64_t>(handle, X.extent(0));
const T* x = X.data_handle();
const float* c = centroids.data_handle();
const uint32_t* l = labels.data_handle();
raft::linalg::map_offset(handle, dist.view(), [=] __device__(int64_t row) {
const float* center = c + static_cast<int64_t>(l[row]) * dim;
float sum = 0;
for (int64_t j = 0; j < dim; j++) {
const float diff = static_cast<float>(x[row * dim + j]) - center[j];
sum += diff * diff;
}
return sum;
});
return thrust::reduce(raft::resource::get_thrust_policy(handle),
dist.data_handle(),
dist.data_handle() + dist.size(),
0.0f);
auto dist = raft::make_device_vector<float, int64_t>(handle, X.extent(0));
distance_to_assigned(handle,
X.data_handle(),
X.extent(0),
centroids.data_handle(),
X.extent(1),
labels.data_handle(),
dist.data_handle());
cudaStream_t stream = raft::resource::get_cuda_stream(handle).get();
auto sum = raft::make_device_scalar<float>(handle, 0.0f);
raft::linalg::mapThenSumReduce(
sum.data_handle(), dist.size(), raft::identity_op{}, stream, dist.data_handle());
float out = 0;
raft::copy(&out, sum.data_handle(), 1, stream);
raft::resource::sync_stream(handle);
return out;
}

template <typename T>
Expand Down Expand Up @@ -96,6 +93,157 @@ void predict(const raft::resources& handle,
cuvs::spatial::knn::detail::utils::mapping<float>{});
}

/** The fused first filter's tile on this device, or nullopt when the build or device has none. */
inline auto filter_tile() -> std::optional<fused_filter_tile>
{
#if CUVS_CUTILE_ENABLED
return fused_filter_tile_config();
#else
return std::nullopt;
#endif
}

/** The first `cols` dims of n rows (row stride `stride`) as half, packed (row stride `cols`). */
template <typename S>
void copy_first_columns(
const raft::resources& handle, const S* in, int64_t n, int64_t stride, int64_t cols, half* out)
{
raft::linalg::map_offset(
handle, raft::make_device_vector_view(out, n * cols), [=] __device__(int64_t i) {
return static_cast<half>(in[i / cols * stride + i % cols]);
});
}

/**
* 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.
*/
template <typename T>
class pruned_assignment {
public:
pruned_assignment(const raft::resources& handle,
raft::device_matrix_view<const T, int64_t> X,
int64_t n_clusters,
fused_filter_tile tile)
: handle_(handle),
X_(X),
n_rows_(X.extent(0)),
dim_(X.extent(1)),
n_clusters_(n_clusters),
filter_dim_(std::is_same_v<T, half> ? dim_ : kDimTileSize),
tile_(tile),
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_)),
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_)),
packed_(raft::make_device_vector<int64_t, int64_t>(
handle, std::min(n_rows_, kRowBatchSize) * n_col_tiles_ * tile.tile_n)),
seg_count_(raft::make_device_vector<int32_t, int64_t>(
handle, std::min(n_rows_, kRowBatchSize) * n_col_tiles_))
{
const auto ratios = adsampling_ratios(dim_);
ratio_ = ratios[kDimTileSize];
raft::copy(
ratios_.data_handle(), ratios.data(), ratios.size(), raft::resource::get_cuda_stream(handle));
squared_norms(handle, X.data_handle(), n_rows_, dim_, kDimTileSize, row_norms_.data_handle());
if constexpr (!std::is_same_v<T, half>) {
copy_columns(X.data_handle(), n_rows_, filter_rows_.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`. */
void assign(raft::device_matrix_view<const float, int64_t> centroids,
raft::device_vector_view<uint32_t, int64_t> labels)
{
#if CUVS_CUTILE_ENABLED
// 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());
const T* kernel_centroids = nullptr;
const half* filter_rows = nullptr;
if constexpr (std::is_same_v<T, half>) {
kernel_centroids = filter_centroids_.data_handle();
filter_rows = X_.data_handle();
} else {
kernel_centroids = centroids.data_handle();
filter_rows = filter_rows_.data_handle();
}
squared_norms(
handle_, kernel_centroids, n_clusters_, dim_, kDimTileSize, centroid_norms_.data_handle());

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;
// 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) {
const int64_t n_centroids = std::min<int64_t>(kCentroidBatchSize, n_clusters_ - j);
launch_fused_filter(handle_,
filter_rows + i * filter_dim_,
static_cast<int>(n_rows),
filter_centroids_.data_handle() + j * filter_dim_,
static_cast<int>(n_centroids),
static_cast<int>(filter_dim_),
row_norms_.data_handle() + i,
centroid_norms_.data_handle() + j,
row_dist,
ratio_,
static_cast<int>(kDimTileSize),
packed_.data_handle(),
seg_count_.data_handle());
prune(handle_,
rows,
n_rows,
kernel_centroids + j * dim_,
static_cast<uint32_t>(j),
dim_,
kDimTileSize,
ratios_.data_handle(),
first_filter_lists{
packed_.data_handle(),
seg_count_.data_handle(),
static_cast<uint32_t>(raft::ceildiv<int64_t>(n_centroids, tile_.tile_n)),
static_cast<uint32_t>(tile_.tile_n)},
row_labels,
row_dist);
}
}
#else
RAFT_FAIL("SuperKMeans pruning needs a build with cuTile");
#endif
}

private:
/** The first filter_dim_ dims of n rows as half, packed into `out`. */
template <typename S>
void copy_columns(const S* in, int64_t n, raft::device_matrix_view<half, int64_t> out)
{
copy_first_columns(handle_, in, n, dim_, filter_dim_, out.data_handle());
}

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_col_tiles_;
float ratio_;
raft::device_vector<float, int64_t> ratios_, row_norms_, centroid_norms_, dist_;
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_;
};

/**
* Lloyd's iterations from rows sampled at random, a fixed number of them. Each iteration assigns
* every row (the full 1-NN when pruning does not apply) and sets each centroid to the mean of its
Expand All @@ -118,16 +266,18 @@ void fit(const raft::resources& handle,
RAFT_EXPECTS(!labels.has_value() || labels->extent(0) == n_rows,
"Number of rows in dataset and labels are different");
RAFT_EXPECTS(params.n_iters > 0, "SuperKMeans needs at least one iteration");
if (prunes(n_clusters, dim)) {
RAFT_FAIL("SuperKMeans with pruning (dim >= %ld and n_clusters > %ld) is not implemented yet",
kDimTileSize,
kMinPrunedK);
}
RAFT_EXPECTS(!prunes(n_clusters, dim) || dim % kDimTileSize == 0,
"SuperKMeans with pruning (n_clusters > %ld) needs dim to be a multiple of %u",
kMinPrunedK,
kDimTileSize);
// Without the filter's kernels on this build or device, every iteration assigns in full
const auto tile = prunes(n_clusters, dim) ? filter_tile() : std::nullopt;
const bool pruned = tile.has_value();

auto stream = raft::resource::get_cuda_stream(handle);
auto mapping_op = cuvs::spatial::knn::detail::utils::mapping<float>{};

// The start centroids: rows sampled at random, the same draw as kmeans::fit's Random init.
// The start centroids: rows sampled at random
raft::random::RngState random_state(params.rng_state.seed);
if constexpr (std::is_same_v<T, float>) {
raft::matrix::sample_rows(handle, random_state, X, centroids);
Expand All @@ -144,8 +294,15 @@ void fit(const raft::resources& handle,
predict(handle, params, X, raft::make_const_mdspan(centroids), assigned.view());
};

std::optional<pruned_assignment<T>> pruned_assign;
if (pruned) { pruned_assign.emplace(handle, X, n_clusters, *tile); }

for (uint32_t iter = 0; iter < params.n_iters; iter++) {
assign();
if (pruned_assign.has_value() && iter > 0) {
pruned_assign->assign(raft::make_const_mdspan(centroids), assigned.view());
} else {
assign();
}
cuvs::cluster::kmeans_balanced::helpers::calc_centers_and_sizes(
handle,
X,
Expand Down
Loading