Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
78 changes: 29 additions & 49 deletions cpp/src/cluster/detail/kmeans.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -1262,64 +1262,45 @@ void kmeans_predict(raft::resources const& handle,
// Allocate memory
// Device-accessible allocation of expandable storage used as temporary buffers
rmm::device_uvector<char> workspace(0, stream);
auto weight = raft::make_device_vector<DataT, IndexT>(handle, n_samples);
if (sample_weight.has_value())
raft::copy(handle, weight.view(), sample_weight.value());
else
raft::matrix::fill(handle, weight.view(), DataT(1));

if (normalize_weight && sample_weight.has_value()) {
const DataT* weight_ptr = sample_weight.has_value() ? sample_weight->data_handle() : nullptr;
auto normalized_weight =
raft::make_device_vector<DataT, IndexT>(handle, normalize_weight && weight_ptr ? n_samples : 0);
if (normalize_weight && weight_ptr != nullptr) {
auto d_wt_sum = raft::make_device_scalar<DataT>(handle, DataT{0});
weightSum(handle, raft::make_const_mdspan(weight.view()), d_wt_sum.view(), true);
weightSum(handle, sample_weight.value(), d_wt_sum.view(), true);
const DataT* d_wt_sum_ptr = d_wt_sum.data_handle();
raft::linalg::map(
handle,
weight.view(),
normalized_weight.view(),
[n_samples, d_wt_sum_ptr] __device__(DataT w) {
return w * static_cast<DataT>(n_samples) / *d_wt_sum_ptr;
},
raft::make_const_mdspan(weight.view()));
sample_weight.value());
weight_ptr = normalized_weight.data_handle();
}

rmm::device_uvector<char> assignment_output(0, stream);
rmm::device_uvector<DataT> L2NormBuf_OR_DistBuf(0, stream);

auto L2NormX = raft::make_device_vector<DataT, IndexT>(handle, n_samples);
auto Tf32NormX = raft::make_device_vector<DataT, IndexT>(
handle, kmeans_may_require_tf32_norms_v<DataT> ? n_samples : IndexT{0});
std::optional<raft::device_vector_view<const DataT, IndexT>> tf32_normx_view = std::nullopt;
const bool needs_norms = metric == cuvs::distance::DistanceType::L2Expanded ||
metric == cuvs::distance::DistanceType::L2SqrtExpanded ||
metric == cuvs::distance::DistanceType::CosineExpanded;
if (needs_norms) {
bool use_tf32_norms = false;
if constexpr (kmeans_may_require_tf32_norms_v<DataT>) {
const auto plan = probe_kmeans_top_1_nn(handle,
X.data_handle(),
centroids.data_handle(),
n_samples,
static_cast<IndexT>(centroids.extent(0)),
n_features,
metric,
pams.batch_samples,
pams.batch_centroids,
cuvs::distance::detail::Top1nnBackend::Auto);
use_tf32_norms =
plan.available && plan.norm_policy == cuvs::distance::detail::Top1nnNormPolicy::Tf32;
if (use_tf32_norms) {
compute_fp32_tf32_norms(handle,
X,
L2NormX.view(),
Tf32NormX.view(),
metric == cuvs::distance::DistanceType::CosineExpanded);
tf32_normx_view = raft::make_const_mdspan(Tf32NormX.view());
} else {
raft::linalg::norm<raft::linalg::L2Norm, raft::Apply::ALONG_ROWS>(
handle, X, L2NormX.view());
}
} else {
raft::linalg::norm<raft::linalg::L2Norm, raft::Apply::ALONG_ROWS>(handle, X, L2NormX.view());
}
bool use_tf32_norms = false;
if constexpr (kmeans_may_require_tf32_norms_v<DataT>) {
const auto plan = probe_kmeans_top_1_nn(handle,
X.data_handle(),
centroids.data_handle(),
n_samples,
static_cast<IndexT>(centroids.extent(0)),
n_features,
metric,
pams.batch_samples,
pams.batch_centroids,
cuvs::distance::detail::Top1nnBackend::Auto);
use_tf32_norms =
plan.available && plan.norm_policy == cuvs::distance::detail::Top1nnNormPolicy::Tf32;
}
auto L2NormX =
raft::make_device_vector<DataT, IndexT>(handle, use_tf32_norms ? IndexT{0} : n_samples);
if (!use_tf32_norms) {
raft::linalg::norm<raft::linalg::L2Norm, raft::Apply::ALONG_ROWS>(handle, X, L2NormX.view());
}

auto l2normx_view =
Expand All @@ -1334,16 +1315,15 @@ void kmeans_predict(raft::resources const& handle,
pams.metric,
pams.batch_samples,
pams.batch_centroids,
workspace,
tf32_normx_view);
workspace);

cuvs::cluster::kmeans::detail::copyClusterLabels(handle, result, labels.data_handle());

rmm::device_scalar<DataT> clusterCostD(stream);
cuvs::cluster::kmeans::detail::weightAndComputeClusterCost(
handle,
result,
raft::make_const_mdspan(weight.view()),
raft::make_device_vector_view<const DataT, IndexT>(weight_ptr, n_samples),
pams.metric,
workspace,
raft::make_device_scalar_view(clusterCostD.data()));
Expand Down
60 changes: 48 additions & 12 deletions cpp/src/cluster/detail/kmeans_balanced.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ auto make_bitwise_expanded_iterator(const uint8_t* packed_data)
return thrust::make_transform_iterator(counting_iter, decoder);
}

/** Buffers for predict_core, reused across calls so each minibatch does not reallocate them. */
template <typename MathT>
struct predict_core_workspace {
predict_core_workspace(cuda::stream_ref stream, rmm::device_async_resource_ref mr)
: norms_or_distances(0, stream, mr), workspace(0, stream, mr), output(0, stream, mr)
{
}

rmm::device_uvector<MathT> norms_or_distances;
rmm::device_uvector<char> workspace;
rmm::device_uvector<char> output;
};

/**
* @brief Predict labels for the dataset; floating-point types only.
*
Expand All @@ -116,6 +129,7 @@ auto make_bitwise_expanded_iterator(const uint8_t* packed_data)
* @param[in] n_rows Number samples in the `dataset`
* @param[out] labels Output predictions [n_rows]
* @param[inout] mr (optional) Memory resource to use for temporary allocations
* @param[inout] scratch Buffers reused across calls
*/
template <typename MathT, typename IdxT, typename LabelT>
inline std::enable_if_t<std::is_floating_point_v<MathT>> predict_core(
Expand All @@ -128,34 +142,30 @@ inline std::enable_if_t<std::is_floating_point_v<MathT>> predict_core(
const MathT* dataset_norm,
IdxT n_rows,
LabelT* labels,
rmm::device_async_resource_ref mr)
rmm::device_async_resource_ref mr,
predict_core_workspace<MathT>& scratch)
{
auto stream = raft::resource::get_cuda_stream(handle);
switch (params.metric) {
case cuvs::distance::DistanceType::L2Expanded:
case cuvs::distance::DistanceType::L2SqrtExpanded:
case cuvs::distance::DistanceType::CosineExpanded: {
rmm::device_uvector<MathT> L2NormBuf_OR_DistBuf(0, stream, mr);
rmm::device_uvector<char> workspace(0, stream, mr);

auto X_view = raft::make_device_matrix_view<const MathT, IdxT>(dataset, n_rows, dim);
auto centroids_view =
raft::make_device_matrix_view<const MathT, IdxT>(centers, n_clusters, dim);
auto X_norm_view = raft::make_device_vector_view<const MathT, IdxT>(dataset_norm, n_rows);

rmm::device_uvector<char> assignment_output(0, stream, mr);

const auto result = cuvs::cluster::kmeans::detail::minClusterAndDistanceCompute<MathT, IdxT>(
handle,
X_view,
centroids_view,
assignment_output,
scratch.output,
X_norm_view,
L2NormBuf_OR_DistBuf,
scratch.norms_or_distances,
params.metric,
0, // default top_1_nn row tuning
0, // default top_1_nn candidate tuning
workspace);
scratch.workspace);

cuvs::cluster::kmeans::detail::copyClusterLabels(handle, result, labels);
break;
Expand Down Expand Up @@ -718,6 +728,9 @@ void predict(const raft::resources& handle,
const MathT* dataset_norm_ptr =
need_norm && params.is_packed_binary ? cur_dataset_norm.data() : nullptr;
auto cur_dataset_ptr = cur_dataset.data();

// Buffers reused by every minibatch, instead of allocated per predict_core call.
predict_core_workspace<MathT> core_scratch(stream, mem_res);
for (IdxT offset = 0; offset < n_rows; offset += max_minibatch_size) {
IdxT minibatch_size = std::min<IdxT>(max_minibatch_size, n_rows - offset);

Expand Down Expand Up @@ -755,8 +768,30 @@ void predict(const raft::resources& handle,
mapping_op);
}

// Compute the norm now if it hasn't been pre-computed.
if (need_compute_norm) {
// When this minibatch's 1-NN plan uses TF32 norms (cuTile), the 1-NN computes them itself and
// never reads FP32 norms. Probe per minibatch: cuTile needs aligned rows, and a minibatch below
// 64 rows can leave later minibatches unaligned.
bool tf32_norms_in_1nn = false;
if constexpr (kmeans_may_require_tf32_norms_v<MathT>) {
if (need_compute_norm) {
const auto plan =
probe_kmeans_top_1_nn<MathT, IdxT>(handle,
cur_dataset_ptr,
centers,
minibatch_size,
n_clusters,
transformed_dim,
params.metric,
0,
0,
cuvs::distance::detail::Top1nnBackend::Auto,
false);
tf32_norms_in_1nn =
plan.available && plan.norm_policy == cuvs::distance::detail::Top1nnNormPolicy::Tf32;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
// Compute the norm now if it hasn't been pre-computed and the 1-NN needs it.
if (need_compute_norm && !tf32_norms_in_1nn) {
if (params.metric == cuvs::distance::DistanceType::CosineExpanded)
compute_norm(handle,
cur_dataset_norm.data(),
Expand Down Expand Up @@ -789,7 +824,8 @@ void predict(const raft::resources& handle,
dataset_norm_ptr,
minibatch_size,
labels + offset,
mem_res);
mem_res,
core_scratch);
}
}

Expand Down
4 changes: 2 additions & 2 deletions cpp/src/cluster/detail/kmeans_common.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,13 @@ struct CopyClusterLabelOp {
template <bool SquareDistance, typename DataT, typename IndexT, typename DistanceIterator>
struct WeightedDistanceOp {
DistanceIterator distances;
const DataT* weights;
const DataT* weights; // nullptr: every weight is effectively 1

__device__ DataT operator()(IndexT offset) const
{
auto distance = static_cast<DataT>(distances[offset]);
if constexpr (SquareDistance) { distance *= distance; }
return distance * weights[offset];
return weights == nullptr ? distance : distance * weights[offset];
}
};

Expand Down
110 changes: 49 additions & 61 deletions cpp/src/distance/detail/fused_distance_nn/cutile/fused_1nn_tile.cu
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <cuvs/detail/jit_lto/fused_distance_nn/fused_1nn_fragments.hpp>
#include <raft/core/operators.hpp>
#include <raft/core/resource/cuda_stream.hpp>
#include <raft/core/resource/device_properties.hpp>
#include <raft/linalg/unary_op.cuh>
#include <raft/util/cuda_utils.cuh>

Expand All @@ -26,6 +27,10 @@ namespace detail {

namespace {

/** Rows per cuTile launch when the candidates do not fit in L2. */
constexpr int64_t kFused1nnCutileL2RowBatch =
32768; // must be a multiple of 64 (16-byte alignment)

/**
* Returns true when the problem dimensions exceed the per-arch high-dim crossover thresholds.
*
Expand Down Expand Up @@ -352,75 +357,58 @@ void launch_fused_1nn_tile(raft::resources const& handle,
use_strict_abi &&
should_use_high_dim_tile<DataT>(n, k, capabilities.cc_major, capabilities.cc_minor);

if constexpr (std::is_same_v<IdxT, int>) {
// Row batching for L2-optimization
const auto candidate_bytes =
static_cast<int64_t>(n) * static_cast<int64_t>(k) * static_cast<int64_t>(sizeof(DataT));
const int64_t row_batch =
candidate_bytes > raft::resource::get_device_properties(handle).l2CacheSize
? kFused1nnCutileL2RowBatch
: fused_1nn_cutile_max_batch_m<DataT>;

const auto stream = raft::resource::get_cuda_stream(handle);
for (int64_t offset = 0; offset < static_cast<int64_t>(m);) {
const int64_t batch_m64 = std::min<int64_t>(row_batch, static_cast<int64_t>(m) - offset);
const int batch_m = static_cast<int>(batch_m64);
// int64 indices go through an int32 index workspace and are widened per batch.
int* batch_idx = nullptr;
if (nearest_idx != nullptr) {
if constexpr (std::is_same_v<IdxT, int>) {
batch_idx = nearest_idx + offset;
} else {
batch_idx = static_cast<int*>(index_workspace);
}
}

auto launch = [&](auto abi) {
launch_fused_1nn_tile_impl<DataT, int, decltype(abi)>(
handle,
batch_idx,
nearest_dist + offset,
x + static_cast<size_t>(offset) * static_cast<size_t>(k),
y,
xn == nullptr ? nullptr : xn + offset,
yn,
batch_m,
static_cast<int>(n),
static_cast<int>(k),
metric,
is_sqrt);
};
if (use_high_dim_abi) {
launch_fused_1nn_tile_impl<DataT, int, cutile_abi_high_dim>(
handle, nearest_idx, nearest_dist, x, y, xn, yn, m, n, k, metric, is_sqrt);
launch(cutile_abi_high_dim{});
} else if (use_strict_abi) {
launch_fused_1nn_tile_impl<DataT, int, cutile_abi_strict>(
handle, nearest_idx, nearest_dist, x, y, xn, yn, m, n, k, metric, is_sqrt);
launch(cutile_abi_strict{});
} else {
launch_fused_1nn_tile_impl<DataT, int, cutile_abi_relaxed>(
handle, nearest_idx, nearest_dist, x, y, xn, yn, m, n, k, metric, is_sqrt);
launch(cutile_abi_relaxed{});
}
} else {
const auto stream = raft::resource::get_cuda_stream(handle);
constexpr int64_t max_batch_m = fused_1nn_cutile_max_batch_m<DataT>;
auto* tmp_idx = nearest_idx == nullptr ? nullptr : static_cast<int*>(index_workspace);
for (int64_t offset = 0; offset < m;) {
const int64_t batch_m64 = std::min<int64_t>(max_batch_m, m - offset);
const int batch_m = static_cast<int>(batch_m64);
const auto* batch_x = x + static_cast<size_t>(offset) * static_cast<size_t>(k);
const auto* batch_xn = xn == nullptr ? nullptr : xn + offset;
auto* batch_dist = nearest_dist + offset;

if (use_high_dim_abi) {
launch_fused_1nn_tile_impl<DataT, int, cutile_abi_high_dim>(handle,
tmp_idx,
batch_dist,
batch_x,
y,
batch_xn,
yn,
batch_m,
static_cast<int>(n),
static_cast<int>(k),
metric,
is_sqrt);
} else if (use_strict_abi) {
launch_fused_1nn_tile_impl<DataT, int, cutile_abi_strict>(handle,
tmp_idx,
batch_dist,
batch_x,
y,
batch_xn,
yn,
batch_m,
static_cast<int>(n),
static_cast<int>(k),
metric,
is_sqrt);
} else {
launch_fused_1nn_tile_impl<DataT, int, cutile_abi_relaxed>(handle,
tmp_idx,
batch_dist,
batch_x,
y,
batch_xn,
yn,
batch_m,
static_cast<int>(n),
static_cast<int>(k),
metric,
is_sqrt);
}

if (nearest_idx != nullptr) {
if constexpr (!std::is_same_v<IdxT, int>) {
if (batch_idx != nullptr) {
raft::linalg::unaryOp(
nearest_idx + offset, tmp_idx, batch_m, raft::cast_op<int64_t>{}, stream.get());
nearest_idx + offset, batch_idx, batch_m, raft::cast_op<int64_t>{}, stream.get());
}
offset += batch_m64;
}
offset += batch_m64;
}
}

Expand Down
Loading