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
// 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.
//
// Modified in 2026 for scann-core (a derived work of ScaNN, not an official
// Google product). Includes changes contributed by Arm (Gerda Zsejke More,
// Li Zhang) in google-research PR #3374 and follow-ups; see NOTICE.



#ifndef SCANN_HASHES_INTERNAL_ASYMMETRIC_HASHING_IMPL_H_
#define SCANN_HASHES_INTERNAL_ASYMMETRIC_HASHING_IMPL_H_

#include <cmath>
#include <cstdint>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>

#include "absl/base/optimization.h"
#include "absl/base/prefetch.h"
#include "scann/base/restrict_allowlist.h"
#include "scann/data_format/datapoint.h"
#include "scann/data_format/dataset.h"
#include "scann/hashes/asymmetric_hashing2/training_options_base.h"
#include "scann/hashes/internal/asymmetric_hashing_postprocess.h"
#include "scann/oss_wrappers/scann_aligned_malloc.h"
#include "scann/oss_wrappers/scann_status.h"
#include "scann/projection/chunking_projection.h"
#include "scann/utils/common.h"
#include "scann/utils/datapoint_utils.h"
#include "scann/utils/noise_shaping_utils.h"
#include "scann/utils/top_n_amortized_constant.h"
#include "scann/utils/types.h"

namespace research_scann {
namespace asymmetric_hashing_internal {

template <typename FloatT>
StatusOr<double> ComputeNormBiasCorrection(
    const DenseDataset<FloatT>& db, DatapointPtr<double> center,
    ConstSpan<DatapointIndex> cluster_members) {
  if (cluster_members.empty()) return 1.0;
  SCANN_RETURN_IF_ERROR(VerifyAllFinite(center.values_span()));
  double mean_norm = 0.0;
  for (DatapointIndex idx : cluster_members) {
    SCANN_RETURN_IF_ERROR(VerifyAllFinite(db[idx].values_span()));
    mean_norm += std::sqrt(SquaredL2Norm(db[idx]));
  }
  SCANN_RET_CHECK(std::isfinite(mean_norm)) << mean_norm;
  mean_norm /= cluster_members.size();
  SCANN_RET_CHECK(std::isfinite(mean_norm))
      << mean_norm << " " << cluster_members.size();
  const double center_norm = std::sqrt(SquaredL2Norm(center));
  SCANN_RET_CHECK(std::isfinite(center_norm)) << center_norm;
  return (center_norm == 0.0) ? 1.0 : (mean_norm / center_norm);
}

template <typename T>
inline vector<DenseDataset<FloatingTypeFor<T>>> ConvertCentersIfNecessary(
    std::vector<DenseDataset<double>> double_centers) {
  std::vector<DenseDataset<float>> result(double_centers.size());
  for (size_t i = 0; i < double_centers.size(); ++i) {
    double_centers[i].ConvertType(&result[i]);
  }

  return result;
}

template <>
inline std::vector<DenseDataset<double>> ConvertCentersIfNecessary<double>(
    std::vector<DenseDataset<double>> double_centers) {
  return double_centers;
}

namespace fallback {

struct SubspaceResidualStats {
  double residual_norm = 0.0;

  double parallel_residual_component = 0.0;
};

double ComputeParallelResidualComponent(
    ConstSpan<uint8_t> quantized,
    ConstSpan<std::vector<SubspaceResidualStats>> residual_stats);

struct CoordinateDescentResult {
  uint8_t new_center_idx = 0;
  double cost_delta = 0.0;
  double new_parallel_residual_component = 0.0;
};


Status ValidateNoiseShapingParams(double threshold, double eta);

}  // namespace fallback

template <typename T>
Status IndexDatapointNoiseShapedFallback(
    const DatapointPtr<T>& maybe_residual_dptr,
    const DatapointPtr<T>& original_dptr,
    const ChunkingProjection<T>& projection,
    ConstSpan<DenseDataset<FloatingTypeFor<T>>> centers, double threshold,
    double eta, MutableSpan<uint8_t> result);


template <typename T>
struct AhImpl {
  using FloatT = FloatingTypeFor<T>;
  using TrainingOptionsT = asymmetric_hashing2::TrainingOptionsTyped<T>;

  static StatusOr<std::vector<DenseDataset<double>>> TrainAsymmetricHashing(
      const TypedDataset<T>& dataset, const TrainingOptionsT& opts,
      shared_ptr<ThreadPool> pool);

  static Status IndexDatapoint(const DatapointPtr<T>& input,
                               const ChunkingProjection<T>& projection,
                               const DistanceMeasure& quantization_distance,
                               ConstSpan<DenseDataset<FloatT>> centers,
                               Datapoint<uint8_t>* result);

  static Status IndexDatapoint(const DatapointPtr<T>& input,
                               const ChunkingProjection<T>& projection,
                               const DistanceMeasure& quantization_distance,
                               ConstSpan<DenseDataset<FloatT>> centers,
                               MutableSpan<uint8_t> result);

  static Status IndexDatapointNoiseShaped(
      const DatapointPtr<T>& maybe_residual_dptr,
      const DatapointPtr<T>& original_dptr,
      const ChunkingProjection<T>& projection,
      ConstSpan<DenseDataset<FloatingTypeFor<T>>> centers, double threshold,
      double eta, MutableSpan<uint8_t> result);

  static StatusOr<std::vector<float>> CreateRawFloatLookupTable(
      const DatapointPtr<T>& query, const ChunkingProjection<T>& projection,
      const DistanceMeasure& lookup_distance,
      ConstSpan<DenseDataset<FloatT>> centers,
      ConstSpan<FloatT> block_transposed_centers,
      int32_t num_clusters_per_block);
};

SCANN_INSTANTIATE_TYPED_CLASS(extern, AhImpl);

// scann-core: the raw float lookup table of a dot-product LUT16 model (16
// centers per block, blocks of 1 to 4 dimensions), computed for all blocks
// in one pass over a column-major copy of the centers. The generic path
// (CreateRawFloatLookupTable) makes one DenseDistanceOneToMany call per
// block, a 16 x 2 problem each, which with the dispatch and the per-row
// reductions cost about 1 us of a GloVe-100 query (50 blocks). The values
// are bit-identical to the generic path's: each center's distance is
// evaluated with the same floating-point operations in the same order as
// DenseAccumulatingDistanceMeasureOneToManyInternal does for its build's
// Highway lane count (see the .cc). Create() checks that on a set of test
// inputs against the generic path and returns nullptr, so the generic path
// stays in use, for anything it doesn't cover or reproduce exactly.
class Lut16DotProductLookupBuilder {
 public:
  static std::unique_ptr<const Lut16DotProductLookupBuilder> Create(
      ConstSpan<DenseDataset<float>> centers);

  // Whether `projected` has this model's block structure.
  bool Accepts(const ChunkedDatapoint<float>& projected) const;

  // result.size() == 16 * number of blocks.
  void Compute(const ChunkedDatapoint<float>& projected,
               MutableSpan<float> result) const;

  // The same for blocks that are consecutive slices of `query` (a plain
  // chunking projection; query has total_dims() values).
  void ComputeContiguous(const float* query, MutableSpan<float> result) const;

  size_t total_dims() const { return total_dims_; }

 private:
  Lut16DotProductLookupBuilder() = default;

  void ComputeBlock(size_t block, const float* query,
                    float* __restrict__ result) const;

  // Per block: its dimensionality and the offset of its centers in
  // columns_, which holds dims x 16 floats per block (dimension-major).
  std::vector<uint32_t> dims_;
  std::vector<uint32_t> offsets_;
  std::vector<float> columns_;
  ConstSpan<DenseDataset<float>> centers_;
  size_t lanes_ = 0;
  size_t total_dims_ = 0;
};

template <typename T>
StatusOr<std::vector<DenseDataset<double>>> TrainAsymmetricHashing(
    const TypedDataset<T>& dataset,
    const asymmetric_hashing2::TrainingOptionsTyped<T>& opts,
    shared_ptr<ThreadPool> pool) {
  return AhImpl<T>::TrainAsymmetricHashing(dataset, opts, std::move(pool));
}

template <typename T>
Status IndexDatapoint(const DatapointPtr<T>& input,
                      const ChunkingProjection<T>& projection,
                      const DistanceMeasure& quantization_distance,
                      ConstSpan<DenseDataset<FloatingTypeFor<T>>> centers,
                      Datapoint<uint8_t>* result) {
  return AhImpl<T>::IndexDatapoint(input, projection, quantization_distance,
                                   centers, result);
}

template <typename T>
Status IndexDatapoint(const DatapointPtr<T>& input,
                      const ChunkingProjection<T>& projection,
                      const DistanceMeasure& quantization_distance,
                      ConstSpan<DenseDataset<FloatingTypeFor<T>>> centers,
                      MutableSpan<uint8_t> result) {
  return AhImpl<T>::IndexDatapoint(input, projection, quantization_distance,
                                   centers, result);
}

template <typename T>
StatusOr<std::vector<float>> CreateRawFloatLookupTable(
    const DatapointPtr<T>& query, const ChunkingProjection<T>& projection,
    const DistanceMeasure& lookup_distance,
    ConstSpan<DenseDataset<FloatingTypeFor<T>>> centers,
    ConstSpan<FloatingTypeFor<T>> block_transposed_centers,
    int32_t num_clusters_per_block) {
  return AhImpl<T>::CreateRawFloatLookupTable(
      query, projection, lookup_distance, centers, block_transposed_centers,
      num_clusters_per_block);
}

template <typename Uint>
inline constexpr Uint FixedPointBias() {
  return static_cast<Uint>(1) << ((sizeof(Uint) * 8) - 1);
}

template <typename T>
std::vector<T> ConvertLookupToFixedPoint(
    ConstSpan<float> raw_lookup,
    const AsymmetricHasherConfig::FixedPointLUTConversionOptions&
        conversion_options,
    float* multiplier);

extern template vector<uint8_t> ConvertLookupToFixedPoint<uint8_t>(
    ConstSpan<float> raw_lookup,
    const AsymmetricHasherConfig::FixedPointLUTConversionOptions&,
    float* multiplier);
extern template vector<uint16_t> ConvertLookupToFixedPoint<uint16_t>(
    ConstSpan<float> raw_lookup,
    const AsymmetricHasherConfig::FixedPointLUTConversionOptions&,
    float* multiplier);

template <typename T>
vector<T> ConvertLookupToFixedPoint(ConstSpan<float> raw_lookup,
                                    float* multiplier) {
  return ConvertLookupToFixedPoint<T>(
      raw_lookup, AsymmetricHasherConfig::FixedPointLUTConversionOptions(),
      multiplier);
}

bool CanUseInt16Accumulator(ConstSpan<uint8_t> lookup_table, size_t num_blocks);

template <typename LookupElement>
inline std::enable_if_t<IsIntegerType<LookupElement>(), int32_t>
ComputePossiblyFixedPointMaxDistance(float float_max_distance,
                                     float multiplier) {
  if (float_max_distance == numeric_limits<float>::infinity()) {
    return numeric_limits<int32_t>::max();
  } else if (float_max_distance * multiplier >=
             static_cast<float>(numeric_limits<int32_t>::max())) {
    return numeric_limits<int32_t>::max();
  } else {
    return static_cast<int32_t>(std::floor(float_max_distance * multiplier));
  }
}

template <typename LookupElement>
inline std::enable_if_t<IsFloatingType<LookupElement>(), float>
ComputePossiblyFixedPointMaxDistance(float float_max_distance,
                                     float multiplier) {
  return float_max_distance;
}

std::vector<uint8_t> CreatePackedDataset(
    const DenseDataset<uint8_t>& hashed_database);

template <typename LookupElement>
struct DistanceType {
  using type = float;
};

template <>
struct DistanceType<uint8_t> {
  using type = int32_t;
};

template <>
struct DistanceType<uint16_t> {
  using type = int32_t;
};

template <typename TopN, typename Distance, typename DistancePostprocess>
class AddPostprocessedValueToTopN {
 public:
  AddPostprocessedValueToTopN(TopN* top_n, Distance max_distance,
                              DistancePostprocess postprocess)
      : top_n_(top_n), max_distance_(max_distance), postprocess_(postprocess) {}

  template <typename RawDistance>
  SCANN_INLINE void Postprocess(RawDistance distance, DatapointIndex dp_index) {
    Distance postprocessed = postprocess_.Postprocess(distance, dp_index);
    if (ABSL_PREDICT_FALSE(postprocessed <= max_distance_)) {
      PostprocessImpl(postprocessed, dp_index);
    }
  }

 private:
  void PostprocessImpl(Distance postprocessed, DatapointIndex dp_index) {
    top_n_->push(std::make_pair(dp_index, postprocessed));
    if (top_n_->full()) {
      max_distance_ = top_n_->approx_bottom().second;
    }
  }

  TopN* top_n_;

  Distance max_distance_;

  DistancePostprocess postprocess_;
};

template <size_t kUnrollFactorParam, typename Functor>
class UnrestrictedIndexIterator {
 public:
  static constexpr size_t kUnrollFactor = kUnrollFactorParam;

  explicit UnrestrictedIndexIterator(DatapointIndex n, Functor functor)
      : n_(n), functor_(functor) {}

  void Advance() { i_ += kUnrollFactor; }

  bool FullUnrollLeft() const { return i_ + kUnrollFactor <= n_; }

  size_t num_left() const { return n_ - i_; }

  DatapointIndex GetOffsetIndex(DatapointIndex offset) const {
    return i_ + offset;
  }

  template <typename T>
  void Postprocess(T score, DatapointIndex offset) {
    functor_.Postprocess(score, GetOffsetIndex(offset));
  }

 private:
  size_t i_ = 0;

  const size_t n_;

  Functor functor_;
};

template <size_t kUnrollFactorParam, typename Functor>
class PopulateDistancesIterator {
 public:
  static constexpr size_t kUnrollFactor = kUnrollFactorParam;

  PopulateDistancesIterator(MutableSpan<pair<DatapointIndex, float>> results,
                            Functor functor)
      : results_(results), functor_(functor) {}

  void Advance() { i_ += kUnrollFactor; }

  bool FullUnrollLeft() const { return i_ + kUnrollFactor <= results_.size(); }

  size_t num_left() const { return results_.size() - i_; }

  DatapointIndex GetOffsetIndex(DatapointIndex offset) const {
    return results_[i_ + offset].first;
  }

  template <typename T>
  void Postprocess(T score, DatapointIndex offset) {
    results_[i_ + offset].second =
        functor_.Postprocess(score, GetOffsetIndex(offset));
  }

 private:
  MutableSpan<pair<DatapointIndex, float>> results_;

  size_t i_ = 0;

  Functor functor_;
};

extern template class UnrestrictedIndexIterator<6, IdentityPostprocessFunctor>;
extern template class UnrestrictedIndexIterator<6, AddBiasFunctor>;
extern template class UnrestrictedIndexIterator<6, LimitedInnerFunctor>;
extern template class PopulateDistancesIterator<6, IdentityPostprocessFunctor>;
extern template class PopulateDistancesIterator<6, AddBiasFunctor>;
extern template class PopulateDistancesIterator<6, LimitedInnerFunctor>;

template <typename T>
uint32_t ComputeTotalBias(size_t num_blocks) {
  return 0;
}

template <>
inline uint32_t ComputeTotalBias<uint16_t>(size_t num_blocks) {
  return num_blocks * FixedPointBias<uint16_t>();
}

template <>
inline uint32_t ComputeTotalBias<uint8_t>(size_t num_blocks) {
  return num_blocks * FixedPointBias<uint8_t>();
}

template <typename T>
struct make_unsigned_if_int_struct {
  using type = make_unsigned_t<T>;
};

template <>
struct make_unsigned_if_int_struct<float> {
  using type = float;
};

template <typename T>
using make_unsigned_if_int_t = typename make_unsigned_if_int_struct<T>::type;

template <typename DatasetView, typename LookupElement,
          size_t kCompileTimeNumCenters, typename IndexIterator, bool kPrefetch>
SCANN_OUTLINE void
GetNeighborsViaAsymmetricDistanceWithCompileTimeNumCentersImpl(
    ConstSpan<LookupElement> lookup, size_t runtime_num_centers,
    const DatasetView* __restrict__ hashed_database, IndexIterator it) {
  using Dist = typename DistanceType<LookupElement>::type;
  using UnsignedDist = make_unsigned_if_int_t<Dist>;
  static_assert(IndexIterator::kUnrollFactor == 6,
                "Mismatch between unroll factor of IndexIterator and "
                "unroll factor used in "
                "GetNeighborsViaAsymmetricDistanceWithCompileTimeNumCenters.");

  const size_t num_blocks = hashed_database->dimensionality();

  const size_t num_centers = (kCompileTimeNumCenters == 0)
                                 ? runtime_num_centers
                                 : kCompileTimeNumCenters;

  const UnsignedDist total_bias = ComputeTotalBias<LookupElement>(num_blocks);
  auto remove_bias = [total_bias](UnsignedDist d) -> Dist {
    return d - total_bias;
  };

  DCHECK_GT(num_blocks, 0);

  constexpr size_t kCacheLineSize = 64;
  const size_t num_cache_lines_per_dp =
      kPrefetch ? DivRoundUp(num_blocks, kCacheLineSize) : 0;

  for (; it.FullUnrollLeft(); it.Advance()) {
    if constexpr (kPrefetch) {
      const size_t num_prefetch =
          std::min(it.kUnrollFactor, it.num_left() - it.kUnrollFactor);
      for (size_t prefetch_idx : Seq(num_prefetch)) {
        const size_t offset =
            it.GetOffsetIndex(prefetch_idx + it.kUnrollFactor);
        const uint8_t* hashed_database_point = hashed_database->GetPtr(offset);
        for (size_t cache_line_idx : Seq(num_cache_lines_per_dp)) {
          absl::PrefetchToLocalCache(hashed_database_point +
                                     cache_line_idx * kCacheLineSize);
        }
      }
    }
    const uint8_t* hashed_database_point0 =
        hashed_database->GetPtr(it.GetOffsetIndex(0));
    const uint8_t* hashed_database_point1 =
        hashed_database->GetPtr(it.GetOffsetIndex(1));
    const uint8_t* hashed_database_point2 =
        hashed_database->GetPtr(it.GetOffsetIndex(2));
    const uint8_t* hashed_database_point3 =
        hashed_database->GetPtr(it.GetOffsetIndex(3));
    const uint8_t* hashed_database_point4 =
        hashed_database->GetPtr(it.GetOffsetIndex(4));
    const uint8_t* hashed_database_point5 =
        hashed_database->GetPtr(it.GetOffsetIndex(5));
    const LookupElement* cur_lookup_row =
        lookup.data() + num_centers * (num_blocks - 1);
    ssize_t j = num_blocks - 1;
    DCHECK_LT(hashed_database_point0[j], num_centers);
    UnsignedDist sum0 = cur_lookup_row[hashed_database_point0[j]];
    DCHECK_LT(hashed_database_point1[j], num_centers);
    UnsignedDist sum1 = cur_lookup_row[hashed_database_point1[j]];
    DCHECK_LT(hashed_database_point2[j], num_centers);
    UnsignedDist sum2 = cur_lookup_row[hashed_database_point2[j]];
    DCHECK_LT(hashed_database_point3[j], num_centers);
    UnsignedDist sum3 = cur_lookup_row[hashed_database_point3[j]];
    DCHECK_LT(hashed_database_point4[j], num_centers);
    UnsignedDist sum4 = cur_lookup_row[hashed_database_point4[j]];
    DCHECK_LT(hashed_database_point5[j], num_centers);
    UnsignedDist sum5 = cur_lookup_row[hashed_database_point5[j]];
    cur_lookup_row -= num_centers;
    --j;

    for (; j >= 0; --j) {
      DCHECK_LT(hashed_database_point0[j], num_centers);
      sum0 += cur_lookup_row[hashed_database_point0[j]];
      DCHECK_LT(hashed_database_point1[j], num_centers);
      sum1 += cur_lookup_row[hashed_database_point1[j]];
      DCHECK_LT(hashed_database_point2[j], num_centers);
      sum2 += cur_lookup_row[hashed_database_point2[j]];
      DCHECK_LT(hashed_database_point3[j], num_centers);
      sum3 += cur_lookup_row[hashed_database_point3[j]];
      DCHECK_LT(hashed_database_point4[j], num_centers);
      sum4 += cur_lookup_row[hashed_database_point4[j]];
      DCHECK_LT(hashed_database_point5[j], num_centers);
      sum5 += cur_lookup_row[hashed_database_point5[j]];
      cur_lookup_row -= num_centers;
    }

    it.Postprocess(remove_bias(sum0), 0);
    it.Postprocess(remove_bias(sum1), 1);
    it.Postprocess(remove_bias(sum2), 2);
    it.Postprocess(remove_bias(sum3), 3);
    it.Postprocess(remove_bias(sum4), 4);
    it.Postprocess(remove_bias(sum5), 5);
  }

  for (DatapointIndex offset = 0; offset < it.num_left(); ++offset) {
    const LookupElement* cur_lookup_row = lookup.data();
    const uint8_t* hashed_database_point =
        hashed_database->GetPtr(it.GetOffsetIndex(offset));
    DCHECK_LT(hashed_database_point[0], num_centers);
    UnsignedDist sum = cur_lookup_row[hashed_database_point[0]];
    cur_lookup_row += num_centers;
    for (size_t j = 1; j < num_blocks; ++j) {
      DCHECK_LT(hashed_database_point[j], num_centers);
      sum += cur_lookup_row[hashed_database_point[j]];
      cur_lookup_row += num_centers;
    }

    it.Postprocess(remove_bias(sum), offset);
  }
}

template <typename DatasetView, typename LookupElement, typename IndexIterator,
          bool kPrefetch = false>
SCANN_INLINE void GetNeighborsViaAsymmetricDistanceWithCompileTimeNumCenters(
    ConstSpan<LookupElement> lookup, size_t runtime_num_centers,
    const DatasetView* __restrict__ hashed_database, IndexIterator it) {
  if constexpr (std::is_same_v<LookupElement, uint8_t>) {
    if (ABSL_PREDICT_TRUE(runtime_num_centers == 256)) {
      return GetNeighborsViaAsymmetricDistanceWithCompileTimeNumCentersImpl<
          DatasetView, LookupElement, 256, IndexIterator, kPrefetch>(
          lookup, runtime_num_centers, hashed_database, it);
    }
  }
  return GetNeighborsViaAsymmetricDistanceWithCompileTimeNumCentersImpl<
      DatasetView, LookupElement, 0, IndexIterator, kPrefetch>(
      lookup, runtime_num_centers, hashed_database, it);
}

#define SCANN_SINGLE_ARG(...) __VA_ARGS__

#define SCANN_INSTANTIATE_AH_FUNCTION_IMPL0(                                   \
    extern_or_nothing, LookupElement, kCompileTimeNumCenters, IndexIterator)   \
  extern_or_nothing template void                                              \
  GetNeighborsViaAsymmetricDistanceWithCompileTimeNumCentersImpl<              \
      DefaultDenseDatasetView<uint8_t>, LookupElement, kCompileTimeNumCenters, \
      IndexIterator, false>(                                                   \
      ConstSpan<LookupElement> lookup, size_t runtime_num_centers,             \
      const DefaultDenseDatasetView<uint8_t>* __restrict__ hashed_database,    \
      IndexIterator it);

#define SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_TOPN_RESTRICTS( \
    extern_or_nothing, LookupElement, kCompileTimeNumCenters, Postprocess)

#define SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_TOPN(                          \
    extern_or_nothing, LookupElement, kCompileTimeNumCenters, Postprocess) \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL0(                                     \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters,            \
      SCANN_SINGLE_ARG(UnrestrictedIndexIterator<6, Postprocess>));        \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_TOPN_RESTRICTS(                      \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters,            \
      SCANN_SINGLE_ARG(Postprocess));

#define SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_POPULATE(                          \
    extern_or_nothing, LookupElement, kCompileTimeNumCenters, Postprocess)     \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL0(                                         \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters,                \
      SCANN_SINGLE_ARG(PopulateDistancesIterator<6, Postprocess>));            \
  extern_or_nothing template void                                              \
  GetNeighborsViaAsymmetricDistanceWithCompileTimeNumCentersImpl<              \
      DefaultDenseDatasetView<uint8_t>, LookupElement, kCompileTimeNumCenters, \
      PopulateDistancesIterator<6, Postprocess>, true>(                        \
      ConstSpan<LookupElement> lookup, size_t runtime_num_centers,             \
      const DefaultDenseDatasetView<uint8_t>* __restrict__ hashed_database,    \
      PopulateDistancesIterator<6, Postprocess> it);

#define SCANN_INSTANTIATE_AH_FUNCTION_IMPL2_CROWDING( \
    extern_or_nothing, LookupElement, kCompileTimeNumCenters, Postprocess)

#define SCANN_INSTANTIATE_AH_FUNCTION_IMPL2(                                   \
    extern_or_nothing, LookupElement, kCompileTimeNumCenters, Postprocess)     \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_TOPN(                                    \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters,                \
      SCANN_SINGLE_ARG(AddPostprocessedValueToTopN<TopNeighbors<float>, float, \
                                                   Postprocess>));             \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_TOPN(                                    \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters,                \
      SCANN_SINGLE_ARG(AddPostprocessedValueToTopN<TopNeighbors<int32_t>,      \
                                                   int32_t, Postprocess>));    \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_TOPN(                                    \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters,                \
      SCANN_SINGLE_ARG(AddPostprocessedValueToTopN<                            \
                       TopNeighbors<float>, float,                             \
                       ConvertToFloatAndPostprocess<Postprocess>>));           \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL2_CROWDING(                                \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters, Postprocess);  \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL1_POPULATE(                                \
      extern_or_nothing, LookupElement, kCompileTimeNumCenters, Postprocess);

#define SCANN_INSTANTIATE_AH_FUNCTION_IMPL3(extern_or_nothing, LookupElement,  \
                                            kCompileTimeNumCenters)            \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL2(extern_or_nothing, LookupElement,        \
                                      kCompileTimeNumCenters,                  \
                                      IdentityPostprocessFunctor);             \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL2(extern_or_nothing, LookupElement,        \
                                      kCompileTimeNumCenters, AddBiasFunctor); \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL2(extern_or_nothing, LookupElement,        \
                                      kCompileTimeNumCenters,                  \
                                      LimitedInnerFunctor);

#define SCANN_INSTANTIATE_AH_FUNCTION(extern_or_nothing)               \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL3(extern_or_nothing, float, 0);    \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL3(extern_or_nothing, uint16_t, 0); \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL3(extern_or_nothing, uint8_t, 0);  \
  SCANN_INSTANTIATE_AH_FUNCTION_IMPL3(extern_or_nothing, uint8_t, 256);

SCANN_INSTANTIATE_AH_FUNCTION(extern);

template <typename TopNsrc, typename TopNdst>
inline void DistanceTranslateWithMultiplier(const TopNsrc& top_n_src,
                                            const float multiplier,
                                            TopNdst* top_n_dst) {
  top_n_dst->resize(top_n_src.size());
  const float inv_mul = 1.0f / multiplier;
  auto dst_ptr = top_n_dst->begin();
  auto src_ptr = top_n_src.begin();
  auto src_size = top_n_src.size();
  for (size_t i = 0; i < src_size; ++i) {
    dst_ptr[i].first = src_ptr[i].first;
    dst_ptr[i].second = src_ptr[i].second * inv_mul;
  }
}

extern template class UnrestrictedIndexIterator<6, IdentityPostprocessFunctor>;
extern template class UnrestrictedIndexIterator<6, AddBiasFunctor>;
extern template class UnrestrictedIndexIterator<6, LimitedInnerFunctor>;
extern template class PopulateDistancesIterator<6, IdentityPostprocessFunctor>;
extern template class PopulateDistancesIterator<6, AddBiasFunctor>;
extern template class PopulateDistancesIterator<6, LimitedInnerFunctor>;

}  // namespace asymmetric_hashing_internal
}  // namespace research_scann

#endif