forked from rapidsai/cuvs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmeans.cuh
More file actions
1184 lines (1132 loc) · 54 KB
/
kmeans.cuh
File metadata and controls
1184 lines (1132 loc) · 54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2020-2024, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "detail/kmeans.cuh"
#include "detail/kmeans_auto_find_k.cuh"
#include "kmeans_mg.hpp"
#include <cuvs/cluster/kmeans.hpp>
#include <raft/core/kvp.hpp>
#include <raft/core/mdarray.hpp>
#include <raft/core/operators.hpp>
#include <raft/core/resource/comms.hpp>
#include <raft/core/resource/cuda_stream.hpp>
#include <optional>
namespace cuvs::cluster::kmeans {
/**
* Functor used for sampling centroids
*/
template <typename DataT, typename IndexT>
using SamplingOp = cuvs::cluster::kmeans::detail::SamplingOp<DataT, IndexT>;
/**
* Functor used to extract the index from a KeyValue pair
* storing both index and a distance.
*/
template <typename IndexT, typename DataT>
using KeyValueIndexOp = cuvs::cluster::kmeans::detail::KeyValueIndexOp<IndexT, DataT>;
/**
* @brief Find clusters with k-means algorithm.
* Initial centroids are chosen with k-means++ algorithm. Empty
* clusters are reinitialized by choosing new centroids with
* k-means++ algorithm.
*
* @code{.cpp}
* #include <raft/core/resources.hpp>
* #include <cuvs/cluster/kmeans.cuh>
* #include <cuvs/cluster/kmeans_types.hpp>
* using namespace cuvs::cluster;
* ...
* raft::resources handle;
* cuvs::cluster::kmeans::params params;
* int n_features = 15, inertia, n_iter;
* auto centroids = raft::make_device_matrix<float, int>(handle, params.n_clusters, n_features);
*
* kmeans::fit(handle,
* params,
* X,
* std::nullopt,
* centroids,
* raft::make_scalar_view(&inertia),
* raft::make_scalar_view(&n_iter));
* @endcode
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X Training instances to cluster. The data must
* be in row-major format.
* [dim = n_samples x n_features]
* @param[in] sample_weight Optional weights for each observation in X.
* [len = n_samples]
* @param[inout] centroids [in] When init is InitMethod::Array, use
* centroids as the initial cluster centers.
* [out] The generated centroids from the
* kmeans algorithm are stored at the address
* pointed by 'centroids'.
* [dim = n_clusters x n_features]
* @param[out] inertia Sum of squared distances of samples to their
* closest cluster center.
* @param[out] n_iter Number of iterations run.
*/
template <typename DataT, typename IndexT>
void fit(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
std::optional<raft::device_vector_view<const DataT, IndexT>> sample_weight,
raft::device_matrix_view<DataT, IndexT> centroids,
raft::host_scalar_view<DataT> inertia,
raft::host_scalar_view<IndexT> n_iter)
{
// use the mnmg kmeans fit if we have comms initialize, single gpu otherwise
if (raft::resource::comms_initialized(handle)) {
cuvs::cluster::kmeans::mg::fit(handle, params, X, sample_weight, centroids, inertia, n_iter);
} else {
cuvs::cluster::kmeans::detail::kmeans_fit<DataT, IndexT>(
handle, params, X, sample_weight, centroids, inertia, n_iter);
}
}
/**
* @brief Predict the closest cluster each sample in X belongs to.
*
* @code{.cpp}
* #include <raft/core/resources.hpp>
* #include <cuvs/cluster/kmeans.cuh>
* #include <cuvs/cluster/kmeans_types.hpp>
* using namespace cuvs::cluster;
* ...
* raft::resources handle;
* cuvs::cluster::kmeans::params params;
* int n_features = 15, inertia, n_iter;
* auto centroids = raft::make_device_matrix<float, int>(handle, params.n_clusters, n_features);
*
* kmeans::fit(handle,
* params,
* X,
* std::nullopt,
* centroids.view(),
* raft::make_scalar_view(&inertia),
* raft::make_scalar_view(&n_iter));
* ...
* auto labels = raft::make_device_vector<int, int>(handle, X.extent(0));
*
* kmeans::predict(handle,
* params,
* X,
* std::nullopt,
* centroids.view(),
* false,
* labels.view(),
* raft::make_scalar_view(&ineratia));
* @endcode
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X New data to predict.
* [dim = n_samples x n_features]
* @param[in] sample_weight Optional weights for each observation in X.
* [len = n_samples]
* @param[in] centroids Cluster centroids. The data must be in
* row-major format.
* [dim = n_clusters x n_features]
* @param[in] normalize_weight True if the weights should be normalized
* @param[out] labels Index of the cluster each sample in X
* belongs to.
* [len = n_samples]
* @param[out] inertia Sum of squared distances of samples to
* their closest cluster center.
*/
template <typename DataT, typename IndexT>
void predict(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
std::optional<raft::device_vector_view<const DataT, IndexT>> sample_weight,
raft::device_matrix_view<const DataT, IndexT> centroids,
raft::device_vector_view<IndexT, IndexT> labels,
bool normalize_weight,
raft::host_scalar_view<DataT> inertia)
{
cuvs::cluster::kmeans::detail::kmeans_predict<DataT, IndexT>(
handle, params, X, sample_weight, centroids, labels, normalize_weight, inertia);
}
/**
* @brief Compute k-means clustering and predicts cluster index for each sample
* in the input.
*
* @code{.cpp}
* #include <raft/core/resources.hpp>
* #include <cuvs/cluster/kmeans.cuh>
* #include <cuvs/cluster/kmeans_types.hpp>
* using namespace cuvs::cluster;
* ...
* raft::resources handle;
* cuvs::cluster::kmeans::params params;
* int n_features = 15, inertia, n_iter;
* auto centroids = raft::make_device_matrix<float, int>(handle, params.n_clusters, n_features);
* auto labels = raft::make_device_vector<int, int>(handle, X.extent(0));
*
* kmeans::fit_predict(handle,
* params,
* X,
* std::nullopt,
* centroids.view(),
* labels.view(),
* raft::make_scalar_view(&inertia),
* raft::make_scalar_view(&n_iter));
* @endcode
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X Training instances to cluster. The data must be
* in row-major format.
* [dim = n_samples x n_features]
* @param[in] sample_weight Optional weights for each observation in X.
* [len = n_samples]
* @param[inout] centroids Optional
* [in] When init is InitMethod::Array, use
* centroids as the initial cluster centers
* [out] The generated centroids from the
* kmeans algorithm are stored at the address
* pointed by 'centroids'.
* [dim = n_clusters x n_features]
* @param[out] labels Index of the cluster each sample in X belongs
* to.
* [len = n_samples]
* @param[out] inertia Sum of squared distances of samples to their
* closest cluster center.
* @param[out] n_iter Number of iterations run.
*/
template <typename DataT, typename IndexT>
void fit_predict(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
std::optional<raft::device_vector_view<const DataT, IndexT>> sample_weight,
std::optional<raft::device_matrix_view<DataT, IndexT>> centroids,
raft::device_vector_view<IndexT, IndexT> labels,
raft::host_scalar_view<DataT> inertia,
raft::host_scalar_view<IndexT> n_iter)
{
cuvs::cluster::kmeans::detail::kmeans_fit_predict<DataT, IndexT>(
handle, params, X, sample_weight, centroids, labels, inertia, n_iter);
}
/**
* @brief Transform X to a cluster-distance space.
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X Training instances to cluster. The data must
* be in row-major format
* [dim = n_samples x n_features]
* @param[in] centroids Cluster centroids. The data must be in row-major format.
* [dim = n_clusters x n_features]
* @param[out] X_new X transformed in the new space.
* [dim = n_samples x n_features]
*/
template <typename DataT, typename IndexT>
void transform(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_matrix_view<const DataT, IndexT> centroids,
raft::device_matrix_view<DataT, IndexT> X_new)
{
cuvs::cluster::kmeans::detail::kmeans_transform<DataT, IndexT>(
handle, params, X, centroids, X_new);
}
template <typename DataT, typename IndexT>
void transform(raft::resources const& handle,
const kmeans::params& params,
const DataT* X,
const DataT* centroids,
IndexT n_samples,
IndexT n_features,
DataT* X_new)
{
cuvs::cluster::kmeans::detail::kmeans_transform<DataT, IndexT>(
handle, params, X, centroids, n_samples, n_features, X_new);
}
/**
* Automatically find the optimal value of k using a binary search.
* This method maximizes the Calinski-Harabasz Index while minimizing the per-cluster inertia.
*
* @code{.cpp}
* #include <raft/core/handle.hpp>
* #include <cuvs/cluster/kmeans.cuh>
* #include <cuvs/cluster/kmeans_types.hpp>
*
* #include <raft/random/make_blobs.cuh>
*
* using namespace cuvs::cluster;
*
* raft::handle_t handle;
* int n_samples = 100, n_features = 15, n_clusters = 10;
* auto X = raft::make_device_matrix<float, int>(handle, n_samples, n_features);
* auto labels = raft::make_device_vector<float, int>(handle, n_samples);
*
* raft::random::make_blobs(handle, X, labels, n_clusters);
*
* auto best_k = raft::make_host_scalar<int>(0);
* auto n_iter = raft::make_host_scalar<int>(0);
* auto inertia = raft::make_host_scalar<int>(0);
*
* kmeans::find_k(handle, X, best_k.view(), inertia.view(), n_iter.view(), n_clusters+1);
*
* @endcode
*
* @tparam idx_t indexing type (should be integral)
* @tparam value_t value type (should be floating point)
* @param handle raft handle
* @param X input observations (shape n_samples, n_dims)
* @param best_k best k found from binary search
* @param inertia inertia of best k found
* @param n_iter number of iterations used to find best k
* @param kmax maximum k to try in search
* @param kmin minimum k to try in search (should be >= 1)
* @param maxiter maximum number of iterations to run
* @param tol tolerance for early stopping convergence
*/
template <typename idx_t, typename value_t>
void find_k(raft::resources const& handle,
raft::device_matrix_view<const value_t, idx_t> X,
raft::host_scalar_view<idx_t> best_k,
raft::host_scalar_view<value_t> inertia,
raft::host_scalar_view<idx_t> n_iter,
idx_t kmax,
idx_t kmin = 1,
idx_t maxiter = 100,
value_t tol = 1e-3)
{
cuvs::cluster::kmeans::detail::find_k(
handle, X, best_k, inertia, n_iter, kmax, kmin, maxiter, tol);
}
/**
* @brief Select centroids according to a sampling operation
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] X The data in row-major format
* [dim = n_samples x n_features]
* @param[in] minClusterDistance Distance for every sample to it's nearest centroid
* [dim = n_samples]
* @param[in] isSampleCentroid Flag the sample chosen as initial centroid
* [dim = n_samples]
* @param[in] select_op The sampling operation used to select the centroids
* @param[out] inRankCp The sampled centroids
* [dim = n_selected_centroids x n_features]
* @param[in] workspace Temporary workspace buffer which can get resized
*
*/
template <typename DataT, typename IndexT>
void sample_centroids(raft::resources const& handle,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_vector_view<DataT, IndexT> minClusterDistance,
raft::device_vector_view<std::uint8_t, IndexT> isSampleCentroid,
SamplingOp<DataT, IndexT>& select_op,
rmm::device_uvector<DataT>& inRankCp,
rmm::device_uvector<char>& workspace)
{
cuvs::cluster::kmeans::detail::sampleCentroids<DataT, IndexT>(
handle, X, minClusterDistance, isSampleCentroid, select_op, inRankCp, workspace);
}
/**
* @brief Compute cluster cost
*
* @tparam DataT the type of data used for weights, distances.
* @tparam ReductionOpT the type of data used for the reduction operation.
*
* @param[in] handle The raft handle
* @param[in] minClusterDistance Distance for every sample to it's nearest centroid
* [dim = n_samples]
* @param[in] workspace Temporary workspace buffer which can get resized
* @param[out] clusterCost Resulting cluster cost
* @param[in] reduction_op The reduction operation used for the cost
*
*/
template <typename DataT, typename IndexT, typename ReductionOpT>
void cluster_cost(raft::resources const& handle,
raft::device_vector_view<DataT, IndexT> minClusterDistance,
rmm::device_uvector<char>& workspace,
raft::device_scalar_view<DataT> clusterCost,
ReductionOpT reduction_op)
{
cuvs::cluster::kmeans::detail::computeClusterCost(
handle, minClusterDistance, workspace, clusterCost, raft::identity_op{}, reduction_op);
}
/**
* @brief Update centroids given current centroids and number of points assigned to each centroid.
* This function also produces a vector of RAFT key/value pairs containing the cluster assignment
* for each point and its distance.
*
* @tparam DataT
* @tparam IndexT
* @param[in] handle: Raft handle to use for managing library resources
* @param[in] X: input matrix (size n_samples, n_features)
* @param[in] sample_weights: number of samples currently assigned to each centroid (size n_samples)
* @param[in] centroids: matrix of current centroids (size n_clusters, n_features)
* @param[in] labels: Iterator of labels (can also be a raw pointer)
* @param[out] weight_per_cluster: sum of sample weights per cluster (size n_clusters)
* @param[out] new_centroids: output matrix of updated centroids (size n_clusters, n_features)
*/
template <typename DataT, typename IndexT, typename LabelsIterator>
void update_centroids(raft::resources const& handle,
raft::device_matrix_view<const DataT, IndexT, raft::row_major> X,
raft::device_vector_view<const DataT, IndexT> sample_weights,
raft::device_matrix_view<const DataT, IndexT, raft::row_major> centroids,
LabelsIterator labels,
raft::device_vector_view<DataT, IndexT> weight_per_cluster,
raft::device_matrix_view<DataT, IndexT, raft::row_major> new_centroids)
{
// TODO: Passing these into the algorithm doesn't really present much of a benefit
// because they are being resized anyways.
// ref https://github.com/rapidsai/raft/issues/930
rmm::device_uvector<char> workspace(0, raft::resource::get_cuda_stream(handle));
cuvs::cluster::kmeans::detail::update_centroids<DataT, IndexT>(
handle, X, sample_weights, centroids, labels, weight_per_cluster, new_centroids, workspace);
}
/**
* @brief Compute distance for every sample to it's nearest centroid
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] X The data in row-major format
* [dim = n_samples x n_features]
* @param[in] centroids Centroids data
* [dim = n_cluster x n_features]
* @param[out] minClusterDistance Distance for every sample to it's nearest centroid
* [dim = n_samples]
* @param[in] L2NormX L2 norm of X : ||x||^2
* [dim = n_samples]
* @param[out] L2NormBuf_OR_DistBuf Resizable buffer to store L2 norm of centroids or distance
* matrix
* @param[in] metric Distance metric to use
* @param[in] batch_samples batch size for input data samples
* @param[in] batch_centroids batch size for input centroids
* @param[in] workspace Temporary workspace buffer which can get resized
*
*/
template <typename DataT, typename IndexT>
void min_cluster_distance(raft::resources const& handle,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_matrix_view<DataT, IndexT> centroids,
raft::device_vector_view<DataT, IndexT> minClusterDistance,
raft::device_vector_view<DataT, IndexT> L2NormX,
rmm::device_uvector<DataT>& L2NormBuf_OR_DistBuf,
cuvs::distance::DistanceType metric,
int batch_samples,
int batch_centroids,
rmm::device_uvector<char>& workspace)
{
cuvs::cluster::kmeans::detail::minClusterDistanceCompute<DataT, IndexT>(handle,
X,
centroids,
minClusterDistance,
L2NormX,
L2NormBuf_OR_DistBuf,
metric,
batch_samples,
batch_centroids,
workspace);
}
template <typename DataT, typename IndexT>
void cluster_cost(raft::resources const& handle,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_matrix_view<const DataT, IndexT> centroids,
raft::host_scalar_view<DataT> cost)
{
auto stream = raft::resource::get_cuda_stream(handle);
auto n_clusters = centroids.extent(0);
auto n_samples = X.extent(0);
auto n_features = X.extent(1);
rmm::device_uvector<char> workspace(n_samples * sizeof(IndexT), stream);
rmm::device_uvector<DataT> x_norms(n_samples, stream);
rmm::device_uvector<DataT> centroid_norms(n_clusters, stream);
raft::linalg::rowNorm(
x_norms.data(), X.data_handle(), n_features, n_samples, raft::linalg::L2Norm, true, stream);
raft::linalg::rowNorm(centroid_norms.data(),
centroids.data_handle(),
n_features,
n_clusters,
raft::linalg::L2Norm,
true,
stream);
rmm::device_uvector<DataT> min_cluster_distance(n_samples, stream);
rmm::device_uvector<DataT> l2_norm_or_distance_buffer(0, stream);
auto metric = cuvs::distance::DistanceType::L2Expanded;
cuvs::cluster::kmeans::min_cluster_distance<DataT, IndexT>(
handle,
X,
raft::make_device_matrix_view<DataT, IndexT>(
const_cast<DataT*>(centroids.data_handle()), n_clusters, n_features),
raft::make_device_vector_view<DataT, IndexT>(min_cluster_distance.data(), n_samples),
raft::make_device_vector_view<DataT, IndexT>(x_norms.data(), n_samples),
l2_norm_or_distance_buffer,
metric,
n_samples,
n_clusters,
workspace);
rmm::device_scalar<DataT> device_cost(0, stream);
cuvs::cluster::kmeans::cluster_cost(
handle,
raft::make_device_vector_view<DataT, IndexT>(min_cluster_distance.data(), n_samples),
workspace,
raft::make_device_scalar_view<DataT>(device_cost.data()),
raft::add_op{});
raft::update_host(cost.data_handle(), device_cost.data(), 1, stream);
}
/**
* @brief Calculates a <key, value> pair for every sample in input 'X' where key is an
* index of one of the 'centroids' (index of the nearest centroid) and 'value'
* is the distance between the sample and the 'centroid[key]'
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] X The data in row-major format
* [dim = n_samples x n_features]
* @param[in] centroids Centroids data
* [dim = n_cluster x n_features]
* @param[out] minClusterAndDistance Distance vector that contains for every sample, the nearest
* centroid and it's distance
* [dim = n_samples]
* @param[in] L2NormX L2 norm of X : ||x||^2
* [dim = n_samples]
* @param[out] L2NormBuf_OR_DistBuf Resizable buffer to store L2 norm of centroids or distance
* matrix
* @param[in] metric distance metric
* @param[in] batch_samples batch size of data samples
* @param[in] batch_centroids batch size of centroids
* @param[in] workspace Temporary workspace buffer which can get resized
*
*/
template <typename DataT, typename IndexT>
void min_cluster_and_distance(
raft::resources const& handle,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_matrix_view<const DataT, IndexT> centroids,
raft::device_vector_view<raft::KeyValuePair<IndexT, DataT>, IndexT> minClusterAndDistance,
raft::device_vector_view<DataT, IndexT> L2NormX,
rmm::device_uvector<DataT>& L2NormBuf_OR_DistBuf,
cuvs::distance::DistanceType metric,
int batch_samples,
int batch_centroids,
rmm::device_uvector<char>& workspace)
{
cuvs::cluster::kmeans::detail::minClusterAndDistanceCompute<DataT, IndexT>(handle,
X,
centroids,
minClusterAndDistance,
L2NormX,
L2NormBuf_OR_DistBuf,
metric,
batch_samples,
batch_centroids,
workspace);
}
/**
* @brief Shuffle and randomly select 'n_samples_to_gather' from input 'in' and stores
* in 'out' does not modify the input
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] in The data to shuffle and gather
* [dim = n_samples x n_features]
* @param[out] out The sampled data
* [dim = n_samples_to_gather x n_features]
* @param[in] n_samples_to_gather Number of sample to gather
* @param[in] seed Seed for the shuffle
*
*/
template <typename DataT, typename IndexT>
void shuffle_and_gather(raft::resources const& handle,
raft::device_matrix_view<const DataT, IndexT> in,
raft::device_matrix_view<DataT, IndexT> out,
uint32_t n_samples_to_gather,
uint64_t seed)
{
cuvs::cluster::kmeans::detail::shuffleAndGather<DataT, IndexT>(
handle, in, out, n_samples_to_gather, seed);
}
/**
* @brief Count the number of samples in each cluster
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] params The parameters for KMeans
* @param[in] X The data in row-major format
* [dim = n_samples x n_features]
* @param[in] L2NormX L2 norm of X : ||x||^2
* [dim = n_samples]
* @param[in] centroids Centroids data
* [dim = n_cluster x n_features]
* @param[in] workspace Temporary workspace buffer which can get resized
* @param[out] sampleCountInCluster The count for each centroid
* [dim = n_cluster]
*
*/
template <typename DataT, typename IndexT>
void count_samples_in_cluster(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_vector_view<DataT, IndexT> L2NormX,
raft::device_matrix_view<DataT, IndexT> centroids,
rmm::device_uvector<char>& workspace,
raft::device_vector_view<DataT, IndexT> sampleCountInCluster)
{
cuvs::cluster::kmeans::detail::countSamplesInCluster<DataT, IndexT>(
handle, params, X, L2NormX, centroids, workspace, sampleCountInCluster);
}
/**
* @brief Selects 'n_clusters' samples from the input X using kmeans++ algorithm.
*
* @see "k-means++: the advantages of careful seeding". 2007, Arthur, D. and Vassilvitskii, S.
* ACM-SIAM symposium on Discrete algorithms.
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] params The parameters for KMeans
* @param[in] X The data in row-major format
* [dim = n_samples x n_features]
* @param[out] centroids Centroids data
* [dim = n_cluster x n_features]
* @param[in] workspace Temporary workspace buffer which can get resized
*/
template <typename DataT, typename IndexT>
void init_plus_plus(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_matrix_view<DataT, IndexT> centroids,
rmm::device_uvector<char>& workspace)
{
cuvs::cluster::kmeans::detail::kmeansPlusPlus<DataT, IndexT>(
handle, params, X, centroids, workspace);
}
/*
* @brief Main function used to fit KMeans (after cluster initialization)
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X Training instances to cluster. The data must
* be in row-major format.
* [dim = n_samples x n_features]
* @param[in] sample_weight Weights for each observation in X.
* [len = n_samples]
* @param[inout] centroids [in] Initial cluster centers.
* [out] The generated centroids from the
* kmeans algorithm are stored at the address
* pointed by 'centroids'.
* [dim = n_clusters x n_features]
* @param[out] inertia Sum of squared distances of samples to their
* closest cluster center.
* @param[out] n_iter Number of iterations run.
* @param[in] workspace Temporary workspace buffer which can get resized
*/
template <typename DataT, typename IndexT>
void fit_main(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_vector_view<const DataT, IndexT> sample_weights,
raft::device_matrix_view<DataT, IndexT> centroids,
raft::host_scalar_view<DataT> inertia,
raft::host_scalar_view<IndexT> n_iter,
rmm::device_uvector<char>& workspace)
{
cuvs::cluster::kmeans::detail::kmeans_fit_main<DataT, IndexT>(
handle, params, X, sample_weights, centroids, inertia, n_iter, workspace);
}
}; // end namespace cuvs::cluster::kmeans
namespace cuvs::cluster {
/**
* Note: All of the functions below in cuvs::cluster are deprecated and will
* be removed in a future release. Please use cuvs::cluster::kmeans instead.
*/
/**
* @brief Find clusters with k-means algorithm.
* Initial centroids are chosen with k-means++ algorithm. Empty
* clusters are reinitialized by choosing new centroids with
* k-means++ algorithm.
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X Training instances to cluster. The data must
* be in row-major format.
* [dim = n_samples x n_features]
* @param[in] sample_weight Optional weights for each observation in X.
* [len = n_samples]
* @param[inout] centroids [in] When init is InitMethod::Array, use
* centroids as the initial cluster centers.
* [out] The generated centroids from the
* kmeans algorithm are stored at the address
* pointed by 'centroids'.
* [dim = n_clusters x n_features]
* @param[out] inertia Sum of squared distances of samples to their
* closest cluster center.
* @param[out] n_iter Number of iterations run.
*/
template <typename DataT, typename IndexT = int>
void kmeans_fit(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
std::optional<raft::device_vector_view<const DataT, IndexT>> sample_weight,
raft::device_matrix_view<DataT, IndexT> centroids,
raft::host_scalar_view<DataT> inertia,
raft::host_scalar_view<IndexT> n_iter)
{
kmeans::fit<DataT, IndexT>(handle, params, X, sample_weight, centroids, inertia, n_iter);
}
template <typename DataT, typename IndexT = int>
void kmeans_fit(raft::resources const& handle,
const kmeans::params& params,
const DataT* X,
const DataT* sample_weight,
DataT* centroids,
IndexT n_samples,
IndexT n_features,
DataT& inertia,
IndexT& n_iter)
{
kmeans::fit<DataT, IndexT>(
handle, params, X, sample_weight, centroids, n_samples, n_features, inertia, n_iter);
}
/**
* @brief Predict the closest cluster each sample in X belongs to.
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X New data to predict.
* [dim = n_samples x n_features]
* @param[in] sample_weight Optional weights for each observation in X.
* [len = n_samples]
* @param[in] centroids Cluster centroids. The data must be in
* row-major format.
* [dim = n_clusters x n_features]
* @param[in] normalize_weight True if the weights should be normalized
* @param[out] labels Index of the cluster each sample in X
* belongs to.
* [len = n_samples]
* @param[out] inertia Sum of squared distances of samples to
* their closest cluster center.
*/
template <typename DataT, typename IndexT = int>
void kmeans_predict(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
std::optional<raft::device_vector_view<const DataT, IndexT>> sample_weight,
raft::device_matrix_view<const DataT, IndexT> centroids,
raft::device_vector_view<IndexT, IndexT> labels,
bool normalize_weight,
raft::host_scalar_view<DataT> inertia)
{
kmeans::predict<DataT, IndexT>(
handle, params, X, sample_weight, centroids, labels, normalize_weight, inertia);
}
template <typename DataT, typename IndexT = int>
void kmeans_predict(raft::resources const& handle,
const kmeans::params& params,
const DataT* X,
const DataT* sample_weight,
const DataT* centroids,
IndexT n_samples,
IndexT n_features,
IndexT* labels,
bool normalize_weight,
DataT& inertia)
{
kmeans::predict<DataT, IndexT>(handle,
params,
X,
sample_weight,
centroids,
n_samples,
n_features,
labels,
normalize_weight,
inertia);
}
/**
* @brief Compute k-means clustering and predicts cluster index for each sample
* in the input.
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X Training instances to cluster. The data must be
* in row-major format.
* [dim = n_samples x n_features]
* @param[in] sample_weight Optional weights for each observation in X.
* [len = n_samples]
* @param[inout] centroids Optional
* [in] When init is InitMethod::Array, use
* centroids as the initial cluster centers
* [out] The generated centroids from the
* kmeans algorithm are stored at the address
* pointed by 'centroids'.
* [dim = n_clusters x n_features]
* @param[out] labels Index of the cluster each sample in X belongs
* to.
* [len = n_samples]
* @param[out] inertia Sum of squared distances of samples to their
* closest cluster center.
* @param[out] n_iter Number of iterations run.
*/
template <typename DataT, typename IndexT = int>
void kmeans_fit_predict(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
std::optional<raft::device_vector_view<const DataT, IndexT>> sample_weight,
std::optional<raft::device_matrix_view<DataT, IndexT>> centroids,
raft::device_vector_view<IndexT, IndexT> labels,
raft::host_scalar_view<DataT> inertia,
raft::host_scalar_view<IndexT> n_iter)
{
kmeans::fit_predict<DataT, IndexT>(
handle, params, X, sample_weight, centroids, labels, inertia, n_iter);
}
template <typename DataT, typename IndexT = int>
void kmeans_fit_predict(raft::resources const& handle,
const kmeans::params& params,
const DataT* X,
const DataT* sample_weight,
DataT* centroids,
IndexT n_samples,
IndexT n_features,
IndexT* labels,
DataT& inertia,
IndexT& n_iter)
{
kmeans::fit_predict<DataT, IndexT>(
handle, params, X, sample_weight, centroids, n_samples, n_features, labels, inertia, n_iter);
}
/**
* @brief Transform X to a cluster-distance space.
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
* @param[in] handle The raft handle.
* @param[in] params Parameters for KMeans model.
* @param[in] X Training instances to cluster. The data must
* be in row-major format
* [dim = n_samples x n_features]
* @param[in] centroids Cluster centroids. The data must be in row-major format.
* [dim = n_clusters x n_features]
* @param[out] X_new X transformed in the new space.
* [dim = n_samples x n_features]
*/
template <typename DataT, typename IndexT = int>
void kmeans_transform(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_matrix_view<const DataT, IndexT> centroids,
raft::device_matrix_view<DataT, IndexT> X_new)
{
kmeans::transform<DataT, IndexT>(handle, params, X, centroids, X_new);
}
template <typename DataT, typename IndexT = int>
void kmeans_transform(raft::resources const& handle,
const kmeans::params& params,
const DataT* X,
const DataT* centroids,
IndexT n_samples,
IndexT n_features,
DataT* X_new)
{
kmeans::transform<DataT, IndexT>(handle, params, X, centroids, n_samples, n_features, X_new);
}
template <typename DataT, typename IndexT>
using SamplingOp = kmeans::SamplingOp<DataT, IndexT>;
template <typename IndexT, typename DataT>
using KeyValueIndexOp = kmeans::KeyValueIndexOp<IndexT, DataT>;
/**
* @brief Select centroids according to a sampling operation
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] X The data in row-major format
* [dim = n_samples x n_features]
* @param[in] minClusterDistance Distance for every sample to it's nearest centroid
* [dim = n_samples]
* @param[in] isSampleCentroid Flag the sample chosen as initial centroid
* [dim = n_samples]
* @param[in] select_op The sampling operation used to select the centroids
* @param[out] inRankCp The sampled centroids
* [dim = n_selected_centroids x n_features]
* @param[in] workspace Temporary workspace buffer which can get resized
*
*/
template <typename DataT, typename IndexT>
void sampleCentroids(raft::resources const& handle,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_vector_view<DataT, IndexT> minClusterDistance,
raft::device_vector_view<std::uint8_t, IndexT> isSampleCentroid,
SamplingOp<DataT, IndexT>& select_op,
rmm::device_uvector<DataT>& inRankCp,
rmm::device_uvector<char>& workspace)
{
kmeans::sample_centroids<DataT, IndexT>(
handle, X, minClusterDistance, isSampleCentroid, select_op, inRankCp, workspace);
}
/**
* @brief Compute cluster cost
*
* @tparam DataT the type of data used for weights, distances.
* @tparam ReductionOpT the type of data used for the reduction operation.
*
* @param[in] handle The raft handle
* @param[in] minClusterDistance Distance for every sample to it's nearest centroid
* [dim = n_samples]
* @param[in] workspace Temporary workspace buffer which can get resized
* @param[out] clusterCost Resulting cluster cost
* @param[in] reduction_op The reduction operation used for the cost
*
*/
template <typename DataT, typename IndexT, typename ReductionOpT>
void computeClusterCost(raft::resources const& handle,
raft::device_vector_view<DataT, IndexT> minClusterDistance,
rmm::device_uvector<char>& workspace,
raft::device_scalar_view<DataT> clusterCost,
ReductionOpT reduction_op)
{
kmeans::cluster_cost(handle, minClusterDistance, workspace, clusterCost, reduction_op);
}
/**
* @brief Compute distance for every sample to it's nearest centroid
*
* @tparam DataT the type of data used for weights, distances.
* @tparam IndexT the type of data used for indexing.
*
* @param[in] handle The raft handle
* @param[in] params The parameters for KMeans
* @param[in] X The data in row-major format
* [dim = n_samples x n_features]
* @param[in] centroids Centroids data
* [dim = n_cluster x n_features]
* @param[out] minClusterDistance Distance for every sample to it's nearest centroid
* [dim = n_samples]
* @param[in] L2NormX L2 norm of X : ||x||^2
* [dim = n_samples]
* @param[out] L2NormBuf_OR_DistBuf Resizable buffer to store L2 norm of centroids or distance
* matrix
* @param[in] workspace Temporary workspace buffer which can get resized
*
*/
template <typename DataT, typename IndexT>
void minClusterDistanceCompute(raft::resources const& handle,
const kmeans::params& params,
raft::device_matrix_view<const DataT, IndexT> X,
raft::device_matrix_view<DataT, IndexT> centroids,
raft::device_vector_view<DataT, IndexT> minClusterDistance,
raft::device_vector_view<DataT, IndexT> L2NormX,
rmm::device_uvector<DataT>& L2NormBuf_OR_DistBuf,