10 #include "IVFUtils.cuh"
11 #include "../utils/DeviceUtils.h"
12 #include "../utils/Limits.cuh"
13 #include "../utils/Select.cuh"
14 #include "../utils/StaticUtils.h"
15 #include "../utils/Tensor.cuh"
22 namespace faiss {
namespace gpu {
24 template <
int ThreadsPerBlock,
int NumWarpQ,
int NumThreadQ,
bool Dir>
26 pass1SelectLists(Tensor<int, 2, true> prefixSumOffsets,
27 Tensor<float, 1, true> distance,
30 Tensor<float, 3, true> heapDistances,
31 Tensor<int, 3, true> heapIndices) {
32 constexpr
int kNumWarps = ThreadsPerBlock / kWarpSize;
34 __shared__
float smemK[kNumWarps * NumWarpQ];
35 __shared__
int smemV[kNumWarps * NumWarpQ];
37 constexpr
auto kInit = Dir ? kFloatMin : kFloatMax;
38 BlockSelect<float, int, Dir, Comparator<float>,
39 NumWarpQ, NumThreadQ, ThreadsPerBlock>
40 heap(kInit, -1, smemK, smemV, k);
42 auto queryId = blockIdx.y;
43 auto sliceId = blockIdx.x;
44 auto numSlices = gridDim.x;
46 int sliceSize = (nprobe / numSlices);
47 int sliceStart = sliceSize * sliceId;
48 int sliceEnd = sliceId == (numSlices - 1) ? nprobe :
49 sliceStart + sliceSize;
50 auto offsets = prefixSumOffsets[queryId].data();
53 int start = *(&offsets[sliceStart] - 1);
54 int end = offsets[sliceEnd - 1];
56 int num = end - start;
57 int limit = utils::roundDown(num, kWarpSize);
60 auto distanceStart = distance[start].data();
64 for (; i < limit; i += blockDim.x) {
65 heap.add(distanceStart[i], start + i);
70 heap.addThreadQ(distanceStart[i], start + i);
78 for (
int i = threadIdx.x; i < k; i += blockDim.x) {
79 heapDistances[queryId][sliceId][i] = smemK[i];
80 heapIndices[queryId][sliceId][i] = smemV[i];
85 runPass1SelectLists(Tensor<int, 2, true>& prefixSumOffsets,
86 Tensor<float, 1, true>& distance,
90 Tensor<float, 3, true>& heapDistances,
91 Tensor<int, 3, true>& heapIndices,
92 cudaStream_t stream) {
93 constexpr
auto kThreadsPerBlock = 128;
95 auto grid = dim3(heapDistances.getSize(1), prefixSumOffsets.getSize(0));
96 auto block = dim3(kThreadsPerBlock);
98 #define RUN_PASS(NUM_WARP_Q, NUM_THREAD_Q, DIR) \
100 pass1SelectLists<kThreadsPerBlock, NUM_WARP_Q, NUM_THREAD_Q, DIR> \
101 <<<grid, block, 0, stream>>>(prefixSumOffsets, \
111 #define RUN_PASS_DIR(DIR) \
114 RUN_PASS(1, 1, DIR); \
115 } else if (k <= 32) { \
116 RUN_PASS(32, 2, DIR); \
117 } else if (k <= 64) { \
118 RUN_PASS(64, 3, DIR); \
119 } else if (k <= 128) { \
120 RUN_PASS(128, 3, DIR); \
121 } else if (k <= 256) { \
122 RUN_PASS(256, 4, DIR); \
123 } else if (k <= 512) { \
124 RUN_PASS(512, 8, DIR); \
125 } else if (k <= 1024) { \
126 RUN_PASS(1024, 8, DIR); \
137 FAISS_ASSERT_FMT(
false,
"unimplemented k value (%d)", k);