11 #include "IVFUtils.cuh"
12 #include "../utils/DeviceUtils.h"
13 #include "../utils/Limits.cuh"
14 #include "../utils/Select.cuh"
15 #include "../utils/StaticUtils.h"
16 #include "../utils/Tensor.cuh"
23 namespace faiss {
namespace gpu {
25 template <
int ThreadsPerBlock,
int NumWarpQ,
int NumThreadQ,
bool Dir>
27 pass1SelectLists(Tensor<int, 2, true> prefixSumOffsets,
28 Tensor<float, 1, true> distance,
31 Tensor<float, 3, true> heapDistances,
32 Tensor<int, 3, true> heapIndices) {
33 constexpr
int kNumWarps = ThreadsPerBlock / kWarpSize;
35 __shared__
float smemK[kNumWarps * NumWarpQ];
36 __shared__
int smemV[kNumWarps * NumWarpQ];
38 constexpr
auto kInit = Dir ? kFloatMin : kFloatMax;
39 BlockSelect<float, int, Dir, Comparator<float>,
40 NumWarpQ, NumThreadQ, ThreadsPerBlock>
41 heap(kInit, -1, smemK, smemV, k);
43 auto queryId = blockIdx.y;
44 auto sliceId = blockIdx.x;
45 auto numSlices = gridDim.x;
47 int sliceSize = (nprobe / numSlices);
48 int sliceStart = sliceSize * sliceId;
49 int sliceEnd = sliceId == (numSlices - 1) ? nprobe :
50 sliceStart + sliceSize;
51 auto offsets = prefixSumOffsets[queryId].data();
54 int start = *(&offsets[sliceStart] - 1);
55 int end = offsets[sliceEnd - 1];
57 int num = end - start;
58 int limit = utils::roundDown(num, kWarpSize);
61 auto distanceStart = distance[start].data();
65 for (; i < limit; i += blockDim.x) {
66 heap.add(distanceStart[i], start + i);
71 heap.addThreadQ(distanceStart[i], start + i);
79 for (
int i = threadIdx.x; i < k; i += blockDim.x) {
80 heapDistances[queryId][sliceId][i] = smemK[i];
81 heapIndices[queryId][sliceId][i] = smemV[i];
86 runPass1SelectLists(Tensor<int, 2, true>& prefixSumOffsets,
87 Tensor<float, 1, true>& distance,
91 Tensor<float, 3, true>& heapDistances,
92 Tensor<int, 3, true>& heapIndices,
93 cudaStream_t stream) {
94 constexpr
auto kThreadsPerBlock = 128;
96 auto grid = dim3(heapDistances.getSize(1), prefixSumOffsets.getSize(0));
97 auto block = dim3(kThreadsPerBlock);
99 #define RUN_PASS(NUM_WARP_Q, NUM_THREAD_Q, DIR) \
101 pass1SelectLists<kThreadsPerBlock, NUM_WARP_Q, NUM_THREAD_Q, DIR> \
102 <<<grid, block, 0, stream>>>(prefixSumOffsets, \
112 #define RUN_PASS_DIR(DIR) \
115 RUN_PASS(1, 1, DIR); \
116 } else if (k <= 32) { \
117 RUN_PASS(32, 2, DIR); \
118 } else if (k <= 64) { \
119 RUN_PASS(64, 3, DIR); \
120 } else if (k <= 128) { \
121 RUN_PASS(128, 3, DIR); \
122 } else if (k <= 256) { \
123 RUN_PASS(256, 4, DIR); \
124 } else if (k <= 512) { \
125 RUN_PASS(512, 8, DIR); \
126 } else if (k <= 1024) { \
127 RUN_PASS(1024, 8, DIR); \
138 FAISS_ASSERT_FMT(
false,
"unimplemented k value (%d)", k);