scann-core 0.2.1

Rust bindings for scann-core: ScaNN's approximate nearest-neighbour vector search core as a standalone library (derived from Google's ScaNN; not an official Google product)
Documentation
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
// Copyright 2026 The Google Research Authors.
//
// 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.



#include "scann/data_format/dataset.h"

#include <algorithm>
#include <cmath>
#include <cstdint>
#include <memory>
#include <utility>

#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/strings/str_cat.h"
#include "scann/data_format/datapoint.h"
#include "scann/data_format/docid_collection.h"
#include "scann/data_format/docid_collection_interface.h"
#include "scann/data_format/features.pb.h"
#include "scann/data_format/gfv_properties.h"
#include "scann/data_format/sparse_low_level.h"
#include "scann/distance_measures/distance_measure_base.h"
#include "scann/distance_measures/one_to_one/l2_distance.h"
#include "scann/oss_wrappers/scann_status.h"
#include "scann/proto/hashed.pb.h"
#include "scann/utils/common.h"
#include "scann/utils/datapoint_utils.h"
#include "scann/utils/types.h"
#include "scann/utils/util_functions.h"

namespace research_scann {

shared_ptr<DocidCollectionInterface> Dataset::ReleaseDocids() {
  auto result = std::move(docids_);
  docids_ = std::make_unique<VariableLengthDocidCollection>(
      VariableLengthDocidCollection::CreateWithEmptyDocids(result->size()));
  return result;
}

Status Dataset::NormalizeByTag(Normalization tag) {
  if (tag == normalization()) return OkStatus();
  switch (tag) {
    case NONE:
      return OkStatus();
    case UNITL2NORM:
      return NormalizeUnitL2();
    default:
      return UnimplementedError(
          "Normalization type specified by tag not implemented yet.");
  }
}

template <typename T>
Status TypedDataset<T>::Append(const DatapointPtr<T>& dptr) {
  return Append(dptr, absl::StrCat(this->size()));
}

template <typename T>
Status TypedDataset<T>::Append(const GenericFeatureVector& gfv) {
  return Append(gfv, absl::StrCat(this->size()));
}

template <typename T>
void TypedDataset<T>::AppendOrDie(const DatapointPtr<T>& dptr) {
  AppendOrDie(dptr, absl::StrCat(this->size()));
}

template <typename T>
void TypedDataset<T>::AppendOrDie(const GenericFeatureVector& gfv) {
  AppendOrDie(gfv, absl::StrCat(this->size()));
}

template <typename T>
void TypedDataset<T>::AppendOrDie(const DatapointPtr<T>& dptr,
                                  string_view docid) {
  CHECK_OK(this->Append(dptr, docid));
}

template <typename T>
void TypedDataset<T>::AppendOrDie(const GenericFeatureVector& gfv,
                                  string_view docid) {
  CHECK_OK(this->Append(gfv, docid));
}

template <typename T, typename ViewT>
Status MeanByDimensionImpl(const ViewT* view, Datapoint<double>* result) {
  const size_t size = view->size();
  if (size <= 0) {
    return FailedPreconditionError(
        "Cannot compute the mean of an empty dataset.");
  }

  DCHECK(result);
  result->ZeroFill(view->dimensionality());
  std::vector<double>& values = *result->mutable_values();

  if (view->IsSparse()) {
    for (size_t i = 0; i < size; ++i) {
      auto dptr = (*view)[i];
      if (view->is_binary()) {
        for (DimensionIndex j = 0; j < dptr.nonzero_entries(); ++j) {
          ++values[dptr.indices()[j]];
        }
      } else {
        for (DimensionIndex j = 0; j < dptr.nonzero_entries(); ++j) {
          values[dptr.indices()[j]] += dptr.values()[j];
        }
      }
    }
  } else {
    for (size_t i = 0; i < size; ++i) {
      auto dptr = (*view)[i];
      if (view->is_binary()) {
        for (DimensionIndex j = 0; j < dptr.dimensionality(); ++j) {
          values[j] += dptr.GetElementPacked(j);
        }
      } else {
        PointwiseAdd(values.data(), dptr.values(), dptr.nonzero_entries());
      }
    }
  }

  const double multiplier = 1.0 / static_cast<double>(size);
  for (double& elem : values) {
    elem *= multiplier;
  }

  return OkStatus();
}

template <typename T>
Status TypedDataset<T>::MeanByDimension(Datapoint<double>* result) const {
  return MeanByDimensionImpl<T>(this, result);
}

template <typename T>
Status DenseDatasetView<T>::MeanByDimension(Datapoint<double>* result) const {
  return MeanByDimensionImpl<T>(this, result);
}

template <typename T, typename ViewT>
Status MeanByDimensionSubsetImpl(const ViewT* view,
                                 ConstSpan<DatapointIndex> subset,
                                 Datapoint<double>* result) {
  if (subset.empty()) {
    return InvalidArgumentError("Cannot compute the mean of an empty subset.");
  }

  DCHECK(result);
  result->ZeroFill(view->dimensionality());
  std::vector<double>& values = *result->mutable_values();

  if (view->IsSparse()) {
    for (DatapointIndex i : subset) {
      auto dptr = (*view)[i];
      if (view->is_binary()) {
        for (DimensionIndex j = 0; j < dptr.nonzero_entries(); ++j) {
          ++values[dptr.indices()[j]];
        }
      } else {
        for (DimensionIndex j = 0; j < dptr.nonzero_entries(); ++j) {
          values[dptr.indices()[j]] += dptr.values()[j];
        }
      }
    }
  } else {
    for (DatapointIndex i : subset) {
      auto dptr = (*view)[i];
      if (view->is_binary()) {
        for (DimensionIndex j = 0; j < dptr.dimensionality(); ++j) {
          values[j] += dptr.GetElementPacked(j);
        }
      } else {
        PointwiseAdd(values.data(), dptr.values(), dptr.nonzero_entries());
      }
    }
  }

  const double multiplier = 1.0 / static_cast<double>(subset.size());
  for (double& elem : values) {
    elem *= multiplier;
  }

  return OkStatus();
}

template <typename T>
Status TypedDataset<T>::MeanByDimension(ConstSpan<DatapointIndex> subset,
                                        Datapoint<double>* result) const {
  return MeanByDimensionSubsetImpl<T>(this, subset, result);
}

template <typename T>
Status DenseDatasetView<T>::MeanByDimension(ConstSpan<DatapointIndex> subset,
                                            Datapoint<double>* result) const {
  return MeanByDimensionSubsetImpl<T>(this, subset, result);
}

template <typename T>
void TypedDataset<T>::MeanVarianceByDimension(
    Datapoint<double>* means, Datapoint<double>* variances) const {
  CHECK(!this->is_binary()) << "Not implemented for binary datasets.";
  vector<DatapointIndex> subset;
  subset.reserve(this->dimensionality());
  for (DatapointIndex i = 0; i < this->size(); ++i) {
    subset.push_back(i);
  }

  return MeanVarianceByDimension(subset, means, variances);
}

template <typename T>
void DenseDatasetView<T>::MeanVarianceByDimension(
    Datapoint<double>* means, Datapoint<double>* variances) const {
  CHECK(!this->is_binary()) << "Not implemented for binary datasets.";
  vector<DatapointIndex> subset;
  subset.reserve(this->dimensionality());
  for (DatapointIndex i = 0; i < this->size(); ++i) {
    subset.push_back(i);
  }

  return MeanVarianceByDimension(subset, means, variances);
}

template <typename T, typename ViewT>
void MeanVarianceByDimensionImpl(const ViewT* view,
                                 ConstSpan<DatapointIndex> subset,
                                 Datapoint<double>* means,
                                 Datapoint<double>* variances) {
  DCHECK(variances);
  CHECK(!view->is_binary()) << "Not implemented for binary datasets.";
  CHECK_GT(subset.size(), 0)
      << "Cannot compute MeanVarianceByDimension on empty subset.";
  const DimensionIndex dimensionality = view->dimensionality();
  using AT = AccumulatorTypeFor<T>;
  vector<AT> sums(dimensionality);
  vector<AT> squares(dimensionality);

  for (DatapointIndex index : subset) {
    auto point = (*view)[index];
    if (view->IsDense()) {
      for (DimensionIndex i = 0; i < dimensionality; ++i) {
        const T num = point.values()[i];
        sums[i] += num;
        squares[i] += static_cast<AT>(num) * static_cast<AT>(num);
      }
    } else {
      for (size_t i = 0; i < point.nonzero_entries(); ++i) {
        const T num = point.values()[i];
        const DatapointIndex index = point.indices()[i];
        sums[index] += num;
        squares[index] += static_cast<AT>(num) * static_cast<AT>(num);
      }
    }
  }

  const double one_over_n = 1.0 / subset.size();
  variances->clear();
  variances->mutable_values()->resize(dimensionality);
  if (means) {
    means->clear();
    means->mutable_values()->resize(dimensionality);
  }
  for (size_t i = 0; i < dimensionality; ++i) {
    const double mean = sums[i] * one_over_n;
    (*variances->mutable_values())[i] = squares[i] * one_over_n - mean * mean;
    if (means) {
      (*means->mutable_values())[i] = mean;
    }
  }
}

template <typename T>
void TypedDataset<T>::MeanVarianceByDimension(
    ConstSpan<DatapointIndex> subset, Datapoint<double>* means,
    Datapoint<double>* variances) const {
  MeanVarianceByDimensionImpl<T>(this, subset, means, variances);
}

template <typename T>
void DenseDatasetView<T>::MeanVarianceByDimension(
    ConstSpan<DatapointIndex> subset, Datapoint<double>* means,
    Datapoint<double>* variances) const {
  MeanVarianceByDimensionImpl<T>(this, subset, means, variances);
}

template <typename T>
Status TypedDataset<T>::NormalizeUnitL2() {
  if (this->is_binary() || IsIntegerType<T>()) {
    return FailedPreconditionError(
        "Unit L2 normalization is not supported for binary "
        "and integral datasets.");
  }

  const size_t size = this->size();
  for (size_t i = 0; i < size; ++i) {
    auto dptr = (*this)[i];
    const double norm = SquaredL2Norm(dptr);
    if (norm == 0) continue;
    const double multiplier = 1.0 / sqrt(norm);
    T* val_ptr = const_cast<T*>(dptr.values());
    for (size_t j = 0; j < dptr.nonzero_entries(); ++j) {
      val_ptr[j] *= multiplier;
    }
  }

  this->set_normalization(UNITL2NORM);
  return OkStatus();
}

template <typename T>
Status TypedDataset<T>::NormalizeZeroMeanUnitVariance() {
  if (this->is_binary() || IsIntegerType<T>()) {
    return FailedPreconditionError(
        "Zero mean/unit variance normalization is not "
        "supported for binary and integral datasets.");
  }

  const size_t size = this->size();
  for (size_t i = 0; i < size; ++i) {
    auto dptr = (*this)[i];
    double mean, variance;
    MeanVar(dptr, &mean, &variance);

    T* val_ptr = const_cast<T*>(dptr.values());
    if (variance == 0) {
      std::fill(val_ptr, val_ptr + dptr.nonzero_entries(), 0.0);
      return OkStatus();
    }

    const double inv_std = 1.0 / std::sqrt(variance);
    for (size_t j = 0; j < dptr.nonzero_entries(); ++j) {
      val_ptr[j] -= mean;
      val_ptr[j] *= inv_std;
    }
  }

  this->set_normalization(STDGAUSSNORM);
  return OkStatus();
}

namespace {

template <typename T>
inline void ToDoubleAlwaysCopy(const DatapointPtr<T>& dptr,
                               Datapoint<double>* dp) {
  ToDouble(dptr, dp);
}

template <>
inline void ToDoubleAlwaysCopy(const DatapointPtr<double>& dptr,
                               Datapoint<double>* dp) {
  CopyToDatapoint(dptr, dp);
}

template <typename T>
inline void ToFloatAlwaysCopy(const DatapointPtr<T>& dptr,
                              Datapoint<float>* dp) {
  ToFloat(dptr, dp);
}

template <>
inline void ToFloatAlwaysCopy(const DatapointPtr<float>& dptr,
                              Datapoint<float>* dp) {
  CopyToDatapoint(dptr, dp);
}
}  // namespace

template <typename T, typename ViewT>
void GetDatapointDoubleImpl(const ViewT* view, size_t index,
                            Datapoint<double>* result) {
  DCHECK(result);
  result->clear();
  auto unconverted = (*view)[index];
  ToDoubleAlwaysCopy(unconverted, result);
  result->set_normalization(view->normalization());
}

template <typename T, typename ViewT>
void GetDatapointFloatImpl(const ViewT* view, size_t index,
                           Datapoint<float>* result) {
  DCHECK(result);
  result->clear();
  auto unconverted = (*view)[index];
  ToFloatAlwaysCopy(unconverted, result);
  result->set_normalization(view->normalization());
}

template <typename T>
void TypedDataset<T>::GetDatapoint(size_t index,
                                   Datapoint<double>* result) const {
  GetDatapointDoubleImpl<T>(this, index, result);
}

template <typename T>
void TypedDataset<T>::GetDatapoint(size_t index,
                                   Datapoint<float>* result) const {
  GetDatapointFloatImpl<T>(this, index, result);
}

template <typename T>
void DenseDatasetView<T>::GetDatapoint(size_t index,
                                       Datapoint<double>* result) const {
  GetDatapointDoubleImpl<T>(this, index, result);
}

template <typename T>
void DenseDatasetView<T>::GetDatapoint(size_t index,
                                       Datapoint<float>* result) const {
  GetDatapointFloatImpl<T>(this, index, result);
}

template <typename T>
void DenseDataset<T>::set_dimensionality(DimensionIndex dimensionality) {
  if (this->empty()) {
    this->set_dimensionality_no_checks(dimensionality);
    SetStride();
  } else {
    DCHECK_EQ(this->dimensionality(), dimensionality)
        << "Cannot reset the dimensionality of a non-empty Dataset.";
  }
}

template <typename T>
DimensionIndex DenseDataset<T>::NumActiveDimensions() const {
  return this->dimensionality();
}

template <typename T>
void DenseDataset<T>::ShrinkToFit() {
  this->docids()->ShrinkToFit();
  data_.shrink_to_fit();
}

template <typename T>
void DenseDataset<T>::set_is_binary(bool val) {
  this->Dataset::set_is_binary(val);
  SetStride();
}

template <typename T>
void DenseDataset<T>::SetStride() {
  if (this->packing_strategy() == HashedItem::BINARY) {
    stride_ = this->dimensionality() / 8 + (this->dimensionality() % 8 > 0);
  } else if (this->packing_strategy() == HashedItem::NIBBLE) {
    stride_ = this->dimensionality() / 2 + (this->dimensionality() % 2 > 0);
  } else {
    stride_ = this->dimensionality();
  }
}

template <typename T>
void DenseDataset<T>::GetDenseDatapoint(size_t index,
                                        Datapoint<double>* result) const {
  this->GetDatapoint(index, result);
}

template <typename T>
void DenseDataset<T>::GetDenseDatapoint(size_t index,
                                        Datapoint<float>* result) const {
  this->GetDatapoint(index, result);
}

template <typename T>
double DenseDataset<T>::GetDistance(const DistanceMeasure& dist,
                                    size_t vec1_index,
                                    size_t vec2_index) const {
  return dist.GetDistanceDense((*this)[vec1_index], (*this)[vec2_index]);
}

template <typename T>
Status DenseDataset<T>::Append(const DatapointPtr<T>& dptr, string_view docid) {
  if (!dptr.IsDense()) {
    if (dptr.IsSparseOrigin()) {
      return FailedPreconditionError(
          "Cannot append an empty datapoint (ie, the \"sparse origin\") to a "
          "dense dataset. This error sometimes results from datasets that have "
          "an empty GenericFeatureVector proto.");
    } else {
      return FailedPreconditionError(
          "Cannot append a sparse datapoint to a dense dataset.");
    }
  }

  const DimensionIndex dptr_dim = dptr.dimensionality();
  const bool dptr_is_binary = dptr.dimensionality() > dptr.nonzero_entries();
  if (dptr_is_binary && !std::is_same<T, uint8_t>::value) {
    return InvalidArgumentError(
        "Binary DenseDatasets may only be built with uint8 as a template "
        "parameter.");
  }

  if (this->size() == 0) {
    if (this->dimensionality() == 0) this->set_dimensionality(dptr_dim);
    if (this->packing_strategy() == HashedItem::NONE) {
      set_is_binary(dptr_is_binary);
    }
  }

  if (this->dimensionality() != dptr_dim) {
    return FailedPreconditionError(
        StrFormat("Dimensionality mismatch:  Appending a %u dimensional "
                  "datapoint to a %u dimensional dataset.",
                  static_cast<uint64_t>(dptr_dim),
                  static_cast<uint64_t>(this->dimensionality())));
  } else if (stride_ != dptr.nonzero_entries()) {
    return FailedPreconditionError(
        StrFormat("Cannot append a vector to a dataset with different "
                  "stride: Appending a %u dimensional datapoint to a %u "
                  "dimensional dataset.",
                  static_cast<uint64_t>(dptr.nonzero_entries()),
                  static_cast<uint64_t>(stride_)));
  }

  Datapoint<T> storage;
  DatapointPtr<T> to_insert = dptr;
  if (this->normalization() != NONE) {
    CopyToDatapoint(dptr, &storage);
    SCANN_RETURN_IF_ERROR(NormalizeByTag(this->normalization(), &storage));
    to_insert = storage.ToPtr();
  }
  SCANN_RETURN_IF_ERROR(this->AppendDocid(docid));
  data_.insert(data_.end(), to_insert.values_span().begin(),
               to_insert.values_span().end());
  return OkStatus();
}

template <typename T>
Status DenseDataset<T>::Append(const GenericFeatureVector& gfv,
                               string_view docid) {
  Datapoint<T> dp;
  SCANN_RETURN_IF_ERROR(dp.FromGfv(gfv));
  SCANN_RETURN_IF_ERROR(this->Append(dp.ToPtr(), docid))
      << "Docid:  " << docid << " Debug string:  " << gfv.DebugString();
  return OkStatus();
}

template <typename T>
DenseDataset<T>::DenseDataset(vector<T> datapoint_vec,
                              unique_ptr<DocidCollectionInterface> docids)
    : TypedDataset<T>(std::move(docids)), data_(std::move(datapoint_vec)) {
  if (!data_.empty()) {
    stride_ = data_.size() / this->docids()->size();

    this->set_dimensionality_no_checks(stride_);
  }
  DCHECK_EQ(this->docids()->size() * stride_, data_.size());
}

template <typename T>
DenseDataset<T>::DenseDataset(vector<T>&& datapoint_vec, size_t num_dp)
    : DenseDataset<T>(
          std::move(datapoint_vec),
          std::make_unique<VariableLengthDocidCollection>(
              VariableLengthDocidCollection::CreateWithEmptyDocids(num_dp))) {}

template <typename T>
void DenseDataset<T>::Reserve(size_t n) {
  if (mutator_) {
    mutator_->Reserve(n);
    return;
  }
  ReserveImpl(n);
}

template <typename T>
void DenseDataset<T>::ReserveImpl(size_t n) {
  data_.reserve(n * stride_);
}

template <typename T>
void DenseDataset<T>::Resize(size_t n) {
  CHECK_EQ(this->docids()->capacity(), 0)
      << "Resize only works for datasets with empty docids.";
  if (this->size() != n) {
    data_.resize(n * stride_);
    this->set_docids_no_checks(make_unique<VariableLengthDocidCollection>(
        VariableLengthDocidCollection::CreateWithEmptyDocids(n)));
  }
}

template <typename T>
void DenseDataset<T>::clear() {
  *this = DenseDataset<T>();
}

template <typename T>
shared_ptr<DocidCollectionInterface> DenseDataset<T>::ReleaseDocids() {
  auto result = Dataset::ReleaseDocids();
  if (mutator_) {
    mutator_ = nullptr;
    CHECK_OK(GetMutator().status());
  }
  return result;
}

template <typename T>
size_t DenseDataset<T>::MemoryUsageExcludingDocids() const {
  return sizeof(*this) + sizeof(T) * data_.capacity() - sizeof(*this->docids());
}

template <typename T>
StatusOr<typename TypedDataset<T>::Mutator*> DenseDataset<T>::GetMutator()
    const {
  if (!mutator_) {
    SCANN_ASSIGN_OR_RETURN(mutator_, DenseDataset<T>::Mutator::Create(
                                         const_cast<DenseDataset<T>*>(this)));
  }
  return {mutator_.get()};
}

template <typename T>
void SparseDataset<T>::set_dimensionality(DimensionIndex dimensionality) {
  if (this->empty()) {
    this->set_dimensionality_no_checks(dimensionality);
  } else {
    DCHECK_EQ(this->dimensionality(), dimensionality)
        << "Cannot reset the dimensionality of a non-empty Dataset.";
  }
}

template <typename T>
template <typename OutT>
void SparseDataset<T>::GetDenseDatapointImpl(size_t index,
                                             Datapoint<OutT>* result) const {
  DCHECK(result);
  result->clear();
  auto unconverted = (*this)[index];
  result->ZeroFill(unconverted.dimensionality());
  if (this->is_binary()) {
    for (size_t i = 0; i < unconverted.nonzero_entries(); ++i) {
      result->mutable_values()->at(unconverted.indices()[i]) = 1.0;
    }
  } else {
    for (size_t i = 0; i < unconverted.nonzero_entries(); ++i) {
      result->mutable_values()->at(unconverted.indices()[i]) =
          unconverted.values()[i];
    }
  }
  result->set_normalization(this->normalization());
}

template <typename T>
void SparseDataset<T>::GetDenseDatapoint(size_t index,
                                         Datapoint<double>* result) const {
  GetDenseDatapointImpl(index, result);
}

template <typename T>
void SparseDataset<T>::GetDenseDatapoint(size_t index,
                                         Datapoint<float>* result) const {
  GetDenseDatapointImpl(index, result);
}

template <typename T>
DimensionIndex SparseDataset<T>::NumActiveDimensions() const {
  absl::flat_hash_set<DimensionIndex> is_active;
  for (size_t i = 0; i < this->size(); ++i) {
    const DatapointPtr<T> dptr = (*this)[i];
    for (DimensionIndex j = 0; j < dptr.nonzero_entries(); ++j) {
      is_active.insert(dptr.indices()[j]);
    }
  }

  return is_active.size();
}

template <typename T>
double SparseDataset<T>::GetDistance(const DistanceMeasure& dist,
                                     size_t vec1_index,
                                     size_t vec2_index) const {
  return dist.GetDistanceSparse((*this)[vec1_index], (*this)[vec2_index]);
}

template <typename T>
Status SparseDataset<T>::Append(const GenericFeatureVector& gfv,
                                string_view docid) {
  const auto old_dimensionality = this->dimensionality();
  const size_t old_offsets_size = repr_.start_offsets().size();
  auto result = AppendImpl(gfv, docid);
  if (!result.ok()) {
    if (repr_.start_offsets().size() > old_offsets_size) repr_.PopBack();
    this->set_dimensionality_no_checks(old_dimensionality);
    result = AnnotateStatus(
        result, absl::StrCat("  Docid:  ", docid,
                             "  Debug string:  ", gfv.DebugString()));
  }

  DCHECK(!this->is_binary() || repr_.values().empty());
  return result;
}

template <typename T>
Status SparseDataset<T>::AppendImpl(const GenericFeatureVector& gfv,
                                    string_view docid) {
  SCANN_ASSIGN_OR_RETURN(bool is_sparse, IsGfvSparse(gfv));
  if (!is_sparse) {
    return FailedPreconditionError(
        "Cannot append a dense GFV to a sparse dataset.");
  }

  SCANN_ASSIGN_OR_RETURN(DimensionIndex gfv_dim, GetGfvDimensionality(gfv));
  if (this->dimensionality() == 0) {
    this->set_dimensionality(gfv_dim);
  } else if (this->dimensionality() != gfv_dim) {
    return FailedPreconditionError(
        StrFormat("Dimensionality mismatch:  Appending a %u dimensional "
                  "datapoint to a %u dimensional dataset.",
                  static_cast<uint64_t>(gfv_dim),
                  static_cast<uint64_t>(this->dimensionality())));
  }

  const bool gfv_is_binary = gfv.feature_type() == GenericFeatureVector::BINARY;
  if (gfv_is_binary && !std::is_same<T, uint8_t>::value) {
    return InvalidArgumentError(
        "Binary SparseDatasets may only be built with uint8 as a template "
        "parameter.");
  }

  if (this->empty()) {
    this->set_is_binary(gfv_is_binary);
  }

  if (this->is_binary() != gfv_is_binary) {
    return FailedPreconditionError(
        "Cannot append a binary datapoint to a non-binary dataset or "
        "vice-versa.");
  }

  Datapoint<T> dp;
  SCANN_RETURN_IF_ERROR(dp.FromGfv(gfv));
  SCANN_RETURN_IF_ERROR(NormalizeByTag(this->normalization(), &dp));
  SCANN_RETURN_IF_ERROR(this->AppendDocid(docid));
  repr_.Append(dp.indices(), dp.values());
  return OkStatus();
}

template <typename T>
Status SparseDataset<T>::Append(const DatapointPtr<T>& dptr,
                                string_view docid) {
  const auto old_dimensionality = this->dimensionality();
  const size_t old_offsets_size = repr_.start_offsets().size();
  auto result = AppendImpl(dptr, docid);
  if (!result.ok()) {
    if (repr_.start_offsets().size() > old_offsets_size) repr_.PopBack();
    this->set_dimensionality_no_checks(old_dimensionality);
  }

  DCHECK(!this->is_binary() || repr_.values().empty());
  return result;
}

template <typename T>
Status SparseDataset<T>::AppendImpl(const DatapointPtr<T>& dptr,
                                    string_view docid) {
  if (!dptr.IsSparse()) {
    return FailedPreconditionError(
        "Cannot append a dense DatapointPtr to a sparse dataset.");
  }

  const DimensionIndex dptr_dim = dptr.dimensionality();
  if (dptr_dim == 0) {
    return InvalidArgumentError("Invalid datapoint:  Zero dimensionality.");
  }

  if (this->dimensionality() == 0) {
    this->set_dimensionality(dptr_dim);
  } else if (this->dimensionality() != dptr_dim) {
    return FailedPreconditionError(
        StrFormat("Dimensionality mismatch:  Appending a %u dimensional "
                  "datapoint to a %u dimensional dataset.",
                  static_cast<uint64_t>(dptr_dim),
                  static_cast<uint64_t>(this->dimensionality())));
  }

  const bool dptr_may_be_binary = dptr.values() == nullptr;
  const bool dptr_is_definitely_binary =
      dptr_may_be_binary && dptr.nonzero_entries() > 0;
  if (dptr_is_definitely_binary && !std::is_same<T, uint8_t>::value) {
    return InvalidArgumentError(
        "Binary SparseDatasets may only be built with uint8 as a template "
        "parameter.");
  }

  if (repr_.indices().empty()) {
    this->set_is_binary(dptr_is_definitely_binary);
  }

  if (this->is_binary() && !dptr_may_be_binary) {
    return FailedPreconditionError(
        "Cannot append a non-binary datapoint to a binary dataset.");
  } else if (!this->is_binary() && dptr_is_definitely_binary) {
    return FailedPreconditionError(
        "Cannot append a binary datapoint to a non-binary dataset.");
  }

  Datapoint<T> dp;
  CopyToDatapoint(dptr, &dp);
  SCANN_RETURN_IF_ERROR(NormalizeByTag(this->normalization(), &dp));
  SCANN_RETURN_IF_ERROR(this->AppendDocid(docid));
  repr_.Append(dp.indices(), dp.values());
  return OkStatus();
}

template <typename T>
void SparseDataset<T>::ConvertType(SparseDataset<double>* target) {
  CHECK(!this->is_binary()) << "Not implemented for binary datasets.";
  DCHECK(target);
  target->clear();
  vector<double> vals;
  LOG(INFO) << "SZ = " << repr_.start_offsets().size();
  vals.insert(vals.begin(), repr_.values().begin(), repr_.values().end());
  target->repr_ = SparseDatasetLowLevel<DimensionIndex, double>(
      {repr_.indices().begin(), repr_.indices().end()}, std::move(vals),
      {repr_.start_offsets().begin(), repr_.start_offsets().end()});
  target->set_dimensionality(this->dimensionality());
  target->set_docids_no_checks(this->docids()->Copy());
}

template <typename T>
void SparseDataset<T>::Reserve(size_t n_points) {
  repr_.Reserve(n_points);
}

template <typename T>
void SparseDataset<T>::Reserve(size_t n_points, size_t n_entries) {
  if (this->is_binary()) {
    repr_.ReserveForBinaryData(n_points, n_entries);
  } else {
    repr_.Reserve(n_points, n_entries);
  }
}

template <typename T>
void SparseDataset<T>::clear() {
  *this = SparseDataset<T>();
}
template <typename T>
size_t SparseDataset<T>::MemoryUsageExcludingDocids() const {
  return sizeof(*this) + repr_.MemoryUsage() - sizeof(repr_) -
         sizeof(*this->docids());
}

template <typename T>
void SparseDataset<T>::ShrinkToFit() {
  repr_.ShrinkToFit();
  this->docids()->ShrinkToFit();
}

SCANN_INSTANTIATE_TYPED_CLASS(, TypedDatasetView);
SCANN_INSTANTIATE_TYPED_CLASS(, DenseDatasetView);
SCANN_INSTANTIATE_TYPED_CLASS(, TypedDataset);
SCANN_INSTANTIATE_TYPED_CLASS(, SparseDataset);
SCANN_INSTANTIATE_TYPED_CLASS(, DenseDataset);

}  // namespace research_scann