Faiss

- Main Page
- Namespaces
- Classes
- Files

- File List

All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
IVFPQ.cu
1
2 /**
3 * Copyright (c) 2015-present, Facebook, Inc.
4 * All rights reserved.
5 *
6 * This source code is licensed under the CC-by-NC license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10 // Copyright 2004-present Facebook. All Rights Reserved.
11
12 #include "IVFPQ.cuh"
13 #include "../GpuResources.h"
14 #include "BroadcastSum.cuh"
15 #include "Distance.cuh"
16 #include "FlatIndex.cuh"
17 #include "InvertedListAppend.cuh"
18 #include "L2Norm.cuh"
19 #include "PQCodeDistances.cuh"
20 #include "PQScanMultiPassNoPrecomputed.cuh"
21 #include "PQScanMultiPassPrecomputed.cuh"
22 #include "RemapIndices.h"
23 #include "VectorResidual.cuh"
24 #include "../utils/DeviceDefs.cuh"
25 #include "../utils/DeviceUtils.h"
26 #include "../utils/HostTensor.cuh"
27 #include "../utils/MatrixMult.cuh"
28 #include "../utils/NoTypeTensor.cuh"
29 #include "../utils/Transpose.cuh"
30 #include <limits>
31 #include <thrust/host_vector.h>
32 #include <unordered_map>
33
34 namespace faiss { namespace gpu {
35
36 IVFPQ::IVFPQ(GpuResources* resources,
37 FlatIndex* quantizer,
38 int numSubQuantizers,
39 int bitsPerSubQuantizer,
40 float* pqCentroidData,
41 IndicesOptions indicesOptions,
42 bool useFloat16LookupTables) :
43 IVFBase(resources,
44 quantizer,
45 numSubQuantizers,
46 indicesOptions),
47 numSubQuantizers_(numSubQuantizers),
48 bitsPerSubQuantizer_(bitsPerSubQuantizer),
49 numSubQuantizerCodes_(utils::pow2(bitsPerSubQuantizer_)),
50 dimPerSubQuantizer_(dim_ / numSubQuantizers),
51 precomputedCodes_(false),
52 useFloat16LookupTables_(useFloat16LookupTables) {
53 FAISS_ASSERT(pqCentroidData);
54
55 FAISS_ASSERT(bitsPerSubQuantizer_ <= 8);
56 FAISS_ASSERT(dim_ % numSubQuantizers_ == 0);
57 FAISS_ASSERT(isSupportedPQCodeLength(bytesPerVector_));
58
59 #ifndef FAISS_USE_FLOAT16
60 FAISS_ASSERT(!useFloat16LookupTables_);
61 #endif
62
63 setPQCentroids_(pqCentroidData);
64 }
65
66 IVFPQ::~IVFPQ() {
67 }
68
69
70 bool
71 IVFPQ::isSupportedPQCodeLength(int size) {
72 switch (size) {
73 case 1:
74 case 2:
75 case 3:
76 case 4:
77 case 8:
78 case 12:
79 case 16:
80 case 20:
81 case 24:
82 case 28:
83 case 32:
84 case 40:
85 case 48:
86 case 56: // only supported with float16
87 case 64: // only supported with float16
88 case 96: // only supported with float16
89 return true;
90 default:
91 return false;
92 }
93 }
94
95 bool
96 IVFPQ::isSupportedNoPrecomputedSubDimSize(int dims) {
97 return faiss::gpu::isSupportedNoPrecomputedSubDimSize(dims);
98 }
99
100 void
101 IVFPQ::setPrecomputedCodes(bool enable) {
102 if (precomputedCodes_ != enable) {
103 precomputedCodes_ = enable;
104
105 if (precomputedCodes_) {
106 precomputeCodes_();
107 } else {
108 // Clear out old precomputed code data
109 precomputedCode_ = std::move(DeviceTensor<float, 3, true>());
110
111 #ifdef FAISS_USE_FLOAT16
112 precomputedCodeHalf_ = std::move(DeviceTensor<half, 3, true>());
113 #endif
114 }
115 }
116 }
117
118 int
119 IVFPQ::classifyAndAddVectors(Tensor<float, 2, true>& vecs,
120 Tensor<long, 1, true>& indices) {
121 FAISS_ASSERT(vecs.getSize(0) == indices.getSize(0));
122 FAISS_ASSERT(vecs.getSize(1) == dim_);
123
124 FAISS_ASSERT(!quantizer_->getUseFloat16());
125 auto& coarseCentroids = quantizer_->getVectorsFloat32Ref();
126 auto& mem = resources_->getMemoryManagerCurrentDevice();
127 auto stream = resources_->getDefaultStreamCurrentDevice();
128
129 // Number of valid vectors that we actually add; we return this
130 int numAdded = 0;
131
132 // We don't actually need this
133 DeviceTensor<float, 2, true> listDistance(mem, {vecs.getSize(0), 1}, stream);
134 // We use this
135 DeviceTensor<int, 2, true> listIds2d(mem, {vecs.getSize(0), 1}, stream);
136 auto listIds = listIds2d.view<1>({vecs.getSize(0)});
137
138 quantizer_->query(vecs, 1, listDistance, listIds2d, false);
139
140 // Copy the lists that we wish to append to back to the CPU
141 // FIXME: really this can be into pinned memory and a true async
142 // copy on a different stream; we can start the copy early, but it's
143 // tiny
144 HostTensor<int, 1, true> listIdsHost(listIds, stream);
145
146 // Calculate the residual for each closest centroid
147 DeviceTensor<float, 2, true> residuals(
148 mem, {vecs.getSize(0), vecs.getSize(1)}, stream);
149
150 runCalcResidual(vecs, coarseCentroids, listIds, residuals, stream);
151
152 // Residuals are in the form
153 // (vec x numSubQuantizer x dimPerSubQuantizer)
154 // transpose to
155 // (numSubQuantizer x vec x dimPerSubQuantizer)
156 auto residualsView = residuals.view<3>(
157 {residuals.getSize(0), numSubQuantizers_, dimPerSubQuantizer_});
158
159 DeviceTensor<float, 3, true> residualsTranspose(
160 mem,
161 {numSubQuantizers_, residuals.getSize(0), dimPerSubQuantizer_},
162 stream);
163
164 runTransposeAny(residualsView, 0, 1, residualsTranspose, stream);
165
166 // Get the product quantizer centroids in the form
167 // (numSubQuantizer x numSubQuantizerCodes x dimPerSubQuantizer)
168 // which is pqCentroidsMiddleCode_
169
170 // We now have a batch operation to find the top-1 distances:
171 // batch size: numSubQuantizer
172 // centroids: (numSubQuantizerCodes x dimPerSubQuantizer)
173 // residuals: (vec x dimPerSubQuantizer)
174 // => (numSubQuantizer x vec x 1)
175
176 DeviceTensor<float, 3, true> closestSubQDistance(
177 mem, {numSubQuantizers_, residuals.getSize(0), 1}, stream);
178 DeviceTensor<int, 3, true> closestSubQIndex(
179 mem, {numSubQuantizers_, residuals.getSize(0), 1}, stream);
180
181 for (int subQ = 0; subQ < numSubQuantizers_; ++subQ) {
182 auto closestSubQDistanceView = closestSubQDistance[subQ].view();
183 auto closestSubQIndexView = closestSubQIndex[subQ].view();
184
185 auto pqCentroidsMiddleCodeView = pqCentroidsMiddleCode_[subQ].view();
186 auto residualsTransposeView = residualsTranspose[subQ].view();
187
188 runL2Distance(resources_,
189 pqCentroidsMiddleCodeView,
190 nullptr, // no precomputed norms
191 residualsTransposeView,
192 1,
193 closestSubQDistanceView,
194 closestSubQIndexView,
195 // We don't care about distances
196 true,
197 // Much larger tile size, since these vectors are a
198 // lot smaller than query vectors
199 1024);
200 }
201
202 // Now, we have the nearest sub-q centroid for each slice of the
203 // residual vector.
204 auto closestSubQIndexView = closestSubQIndex.view<2>(
205 {numSubQuantizers_, residuals.getSize(0)});
206
207 // Transpose this for easy use
208 DeviceTensor<int, 2, true> encodings(
209 mem, {residuals.getSize(0), numSubQuantizers_}, stream);
210
211 runTransposeAny(closestSubQIndexView, 0, 1, encodings, stream);
212
213 // Now we add the encoded vectors to the individual lists
214 // First, make sure that there is space available for adding the new
215 // encoded vectors and indices
216
217 // list id -> # being added
218 std::unordered_map<int, int> assignCounts;
219
220 // vector id -> offset in list
221 // (we already have vector id -> list id in listIds)
222 HostTensor<int, 1, true> listOffsetHost({listIdsHost.getSize(0)});
223
224 for (int i = 0; i < listIdsHost.getSize(0); ++i) {
225 int listId = listIdsHost[i];
226
227 // Add vector could be invalid (contains NaNs etc)
228 if (listId < 0) {
229 listOffsetHost[i] = -1;
230 continue;
231 }
232
233 FAISS_ASSERT(listId < numLists_);
234 ++numAdded;
235
236 int offset = deviceListData_[listId]->size() / bytesPerVector_;
237
238 auto it = assignCounts.find(listId);
239 if (it != assignCounts.end()) {
240 offset += it->second;
241 it->second++;
242 } else {
243 assignCounts[listId] = 1;
244 }
245
246 listOffsetHost[i] = offset;
247 }
248
249 // If we didn't add anything (all invalid vectors), no need to
250 // continue
251 if (numAdded == 0) {
252 return 0;
253 }
254
255 // We need to resize the data structures for the inverted lists on
256 // the GPUs, which means that they might need reallocation, which
257 // means that their base address may change. Figure out the new base
258 // addresses, and update those in a batch on the device
259 {
260 // Resize all of the lists that we are appending to
261 for (auto& counts : assignCounts) {
262 auto& codes = deviceListData_[counts.first];
263 codes->resize(codes->size() + counts.second * bytesPerVector_,
264 stream);
265 int newNumVecs = (int) (codes->size() / bytesPerVector_);
266
267 auto& indices = deviceListIndices_[counts.first];
268 if ((indicesOptions_ == INDICES_32_BIT) ||
269 (indicesOptions_ == INDICES_64_BIT)) {
270 size_t indexSize =
271 (indicesOptions_ == INDICES_32_BIT) ? sizeof(int) : sizeof(long);
272
273 indices->resize(indices->size() + counts.second * indexSize, stream);
274 } else if (indicesOptions_ == INDICES_CPU) {
275 // indices are stored on the CPU side
276 FAISS_ASSERT(counts.first < listOffsetToUserIndex_.size());
277
278 auto& userIndices = listOffsetToUserIndex_[counts.first];
279 userIndices.resize(newNumVecs);
280 } else {
281 // indices are not stored on the GPU or CPU side
282 FAISS_ASSERT(indicesOptions_ == INDICES_IVF);
283 }
284
285 // This is used by the multi-pass query to decide how much scratch
286 // space to allocate for intermediate results
287 maxListLength_ = std::max(maxListLength_, newNumVecs);
288 }
289
290 // Update all pointers and sizes on the device for lists that we
291 // appended to
292 {
293 std::vector<int> listIds(assignCounts.size());
294 int i = 0;
295 for (auto& counts : assignCounts) {
296 listIds[i++] = counts.first;
297 }
298
299 updateDeviceListInfo_(listIds, stream);
300 }
301 }
302
303 // If we're maintaining the indices on the CPU side, update our
304 // map. We already resized our map above.
305 if (indicesOptions_ == INDICES_CPU) {
306 // We need to maintain the indices on the CPU side
307 HostTensor<long, 1, true> hostIndices(indices, stream);
308
309 for (int i = 0; i < hostIndices.getSize(0); ++i) {
310 int listId = listIdsHost[i];
311
312 // Add vector could be invalid (contains NaNs etc)
313 if (listId < 0) {
314 continue;
315 }
316
317 int offset = listOffsetHost[i];
318
319 FAISS_ASSERT(listId < listOffsetToUserIndex_.size());
320 auto& userIndices = listOffsetToUserIndex_[listId];
321
322 FAISS_ASSERT(offset < userIndices.size());
323 userIndices[offset] = hostIndices[i];
324 }
325 }
326
327 // We similarly need to actually append the new encoded vectors
328 {
329 DeviceTensor<int, 1, true> listOffset(mem, listOffsetHost, stream);
330
331 // This kernel will handle appending each encoded vector + index to
332 // the appropriate list
333 runIVFPQInvertedListAppend(listIds,
334 listOffset,
335 encodings,
336 indices,
337 deviceListDataPointers_,
338 deviceListIndexPointers_,
339 indicesOptions_,
340 stream);
341 }
342
343 return numAdded;
344 }
345
346 void
347 IVFPQ::addCodeVectorsFromCpu(int listId,
348 const void* codes,
349 const long* indices,
350 size_t numVecs) {
351 // This list must already exist
352 FAISS_ASSERT(listId < deviceListData_.size());
353 auto stream = resources_->getDefaultStreamCurrentDevice();
354
355 // If there's nothing to add, then there's nothing we have to do
356 if (numVecs == 0) {
357 return;
358 }
359
360 size_t lengthInBytes = numVecs * bytesPerVector_;
361
362 auto& listCodes = deviceListData_[listId];
363 auto prevCodeData = listCodes->data();
364
365 // We only have int32 length representations on the GPU per each
366 // list; the length is in sizeof(char)
367 FAISS_ASSERT(listCodes->size() % bytesPerVector_ == 0);
368 FAISS_ASSERT(listCodes->size() + lengthInBytes <=
369 (size_t) std::numeric_limits<int>::max());
370
371 listCodes->append((unsigned char*) codes,
372 lengthInBytes,
373 stream,
374 true /* exact reserved size */);
375
376 // Handle the indices as well
377 addIndicesFromCpu_(listId, indices, numVecs);
378
379 // This list address may have changed due to vector resizing, but
380 // only bother updating it on the device if it has changed
381 if (prevCodeData != listCodes->data()) {
382 deviceListDataPointers_[listId] = listCodes->data();
383 }
384
385 // And our size has changed too
386 int listLength = listCodes->size() / bytesPerVector_;
387 deviceListLengths_[listId] = listLength;
388
389 // We update this as well, since the multi-pass algorithm uses it
390 maxListLength_ = std::max(maxListLength_, listLength);
391
392 // device_vector add is potentially happening on a different stream
393 // than our default stream
394 if (resources_->getDefaultStreamCurrentDevice() != 0) {
395 streamWait({stream}, {0});
396 }
397 }
398
399 void
400 IVFPQ::setPQCentroids_(float* data) {
401 size_t pqSize =
402 numSubQuantizers_ * numSubQuantizerCodes_ * dimPerSubQuantizer_;
403
404 // Make sure the data is on the host
405 // FIXME: why are we doing this?
406 thrust::host_vector<float> hostMemory;
407 hostMemory.insert(hostMemory.end(), data, data + pqSize);
408
409 HostTensor<float, 3, true> pqHost(
410 hostMemory.data(),
411 {numSubQuantizers_, numSubQuantizerCodes_, dimPerSubQuantizer_});
412 DeviceTensor<float, 3, true> pqDevice(
413 pqHost,
414 resources_->getDefaultStreamCurrentDevice());
415
416 DeviceTensor<float, 3, true> pqDeviceTranspose(
417 {numSubQuantizers_, dimPerSubQuantizer_, numSubQuantizerCodes_});
418 runTransposeAny(pqDevice, 1, 2, pqDeviceTranspose,
419 resources_->getDefaultStreamCurrentDevice());
420
421 pqCentroidsInnermostCode_ = std::move(pqDeviceTranspose);
422
423 // Also maintain the PQ centroids in the form
424 // (sub q)(code id)(sub dim)
425 DeviceTensor<float, 3, true> pqCentroidsMiddleCode(
426 {numSubQuantizers_, numSubQuantizerCodes_, dimPerSubQuantizer_});
427 runTransposeAny(pqCentroidsInnermostCode_, 1, 2, pqCentroidsMiddleCode,
428 resources_->getDefaultStreamCurrentDevice());
429
430 pqCentroidsMiddleCode_ = std::move(pqCentroidsMiddleCode);
431 }
432
433 void
434 IVFPQ::precomputeCodes_() {
435 //
436 // d = || x - y_C ||^2 + || y_R ||^2 + 2 * (y_C|y_R) - 2 * (x|y_R)
437 // --------------- --------------------------- -------
438 // term 1 term 2 term 3
439 //
440
441 // Terms 1 and 3 are available only at query time. We compute term 2
442 // here.
443 FAISS_ASSERT(!quantizer_->getUseFloat16());
444 auto& coarseCentroids = quantizer_->getVectorsFloat32Ref();
445
446 // Compute ||y_R||^2 by treating
447 // (sub q)(code id)(sub dim) as (sub q * code id)(sub dim)
448 auto pqCentroidsMiddleCodeView =
449 pqCentroidsMiddleCode_.view<2>(
450 {numSubQuantizers_ * numSubQuantizerCodes_, dimPerSubQuantizer_});
451 DeviceTensor<float, 1, true> subQuantizerNorms(
452 {numSubQuantizers_ * numSubQuantizerCodes_});
453
454 runL2Norm(pqCentroidsMiddleCodeView, subQuantizerNorms, true,
455 resources_->getDefaultStreamCurrentDevice());
456
457 // Compute 2 * (y_C|y_R) via batch matrix multiplication
458 // batch size (sub q) x {(centroid id)(sub dim) x (code id)(sub dim)'}
459 // => (sub q) x {(centroid id)(code id)}
460 // => (sub q)(centroid id)(code id)
461
462 // View (centroid id)(dim) as
463 // (centroid id)(sub q)(dim)
464 // Transpose (centroid id)(sub q)(sub dim) to
465 // (sub q)(centroid id)(sub dim)
466 auto centroidView = coarseCentroids.view<3>(
467 {coarseCentroids.getSize(0), numSubQuantizers_, dimPerSubQuantizer_});
468 DeviceTensor<float, 3, true> centroidsTransposed(
469 {numSubQuantizers_, coarseCentroids.getSize(0), dimPerSubQuantizer_});
470
471 runTransposeAny(centroidView, 0, 1, centroidsTransposed,
472 resources_->getDefaultStreamCurrentDevice());
473
474 DeviceTensor<float, 3, true> coarsePQProduct(
475 {numSubQuantizers_, coarseCentroids.getSize(0), numSubQuantizerCodes_});
476
477 runIteratedMatrixMult(coarsePQProduct, false,
478 centroidsTransposed, false,
479 pqCentroidsMiddleCode_, true,
480 2.0f, 0.0f,
481 resources_->getBlasHandleCurrentDevice(),
482 resources_->getDefaultStreamCurrentDevice());
483
484 // Transpose (sub q)(centroid id)(code id) to
485 // (centroid id)(sub q)(code id)
486 DeviceTensor<float, 3, true> coarsePQProductTransposed(
487 {coarseCentroids.getSize(0), numSubQuantizers_, numSubQuantizerCodes_});
488 runTransposeAny(coarsePQProduct, 0, 1, coarsePQProductTransposed,
489 resources_->getDefaultStreamCurrentDevice());
490
491 // View (centroid id)(sub q)(code id) as
492 // (centroid id)(sub q * code id)
493 auto coarsePQProductTransposedView = coarsePQProductTransposed.view<2>(
494 {coarseCentroids.getSize(0), numSubQuantizers_ * numSubQuantizerCodes_});
495
496 // Sum || y_R ||^2 + 2 * (y_C|y_R)
497 // i.e., add norms (sub q * code id)
498 // along columns of inner product (centroid id)(sub q * code id)
499 runSumAlongColumns(subQuantizerNorms, coarsePQProductTransposedView,
500 resources_->getDefaultStreamCurrentDevice());
501
502 #ifdef FAISS_USE_FLOAT16
503 if (useFloat16LookupTables_) {
504 precomputedCodeHalf_ = toHalf(resources_,
505 resources_->getDefaultStreamCurrentDevice(),
506 coarsePQProductTransposed);
507 return;
508 }
509 #endif
510
511 // We added into the view, so `coarsePQProductTransposed` is now our
512 // precomputed term 2.
513 precomputedCode_ = std::move(coarsePQProductTransposed);
514 }
515
516 void
517 IVFPQ::query(Tensor<float, 2, true>& queries,
518 int nprobe,
519 int k,
520 Tensor<float, 2, true>& outDistances,
521 Tensor<long, 2, true>& outIndices) {
522 // Validate these at a top level
523 FAISS_ASSERT(nprobe <= 1024);
524 FAISS_ASSERT(k <= 1024);
525
526 auto& mem = resources_->getMemoryManagerCurrentDevice();
527 auto stream = resources_->getDefaultStreamCurrentDevice();
528 nprobe = std::min(nprobe, quantizer_->getSize());
529
530 FAISS_ASSERT(queries.getSize(1) == dim_);
531 FAISS_ASSERT(outDistances.getSize(0) == queries.getSize(0));
532 FAISS_ASSERT(outIndices.getSize(0) == queries.getSize(0));
533
534 // Reserve space for the closest coarse centroids
535 DeviceTensor<float, 2, true>
536 coarseDistances(mem, {queries.getSize(0), nprobe}, stream);
537 DeviceTensor<int, 2, true>
538 coarseIndices(mem, {queries.getSize(0), nprobe}, stream);
539
540 // Find the `nprobe` closest coarse centroids; we can use int
541 // indices both internally and externally
542 quantizer_->query(queries,
543 nprobe,
544 coarseDistances,
545 coarseIndices,
546 true);
547
548 if (precomputedCodes_) {
549 runPQPrecomputedCodes_(queries,
550 coarseDistances,
551 coarseIndices,
552 k,
553 outDistances,
554 outIndices);
555 } else {
556 runPQNoPrecomputedCodes_(queries,
557 coarseDistances,
558 coarseIndices,
559 k,
560 outDistances,
561 outIndices);
562 }
563
564 // If the GPU isn't storing indices (they are on the CPU side), we
565 // need to perform the re-mapping here
566 // FIXME: we might ultimately be calling this function with inputs
567 // from the CPU, these are unnecessary copies
568 if (indicesOptions_ == INDICES_CPU) {
569 HostTensor<long, 2, true> hostOutIndices(outIndices, stream);
570
571 ivfOffsetToUserIndex(hostOutIndices.data(),
572 numLists_,
573 hostOutIndices.getSize(0),
574 hostOutIndices.getSize(1),
575 listOffsetToUserIndex_);
576
577 // Copy back to GPU, since the input to this function is on the
578 // GPU
579 outIndices.copyFrom(hostOutIndices, stream);
580 }
581 }
582
583 std::vector<unsigned char>
584 IVFPQ::getListCodes(int listId) const {
585 FAISS_ASSERT(listId < deviceListData_.size());
586
587 return deviceListData_[listId]->copyToHost<unsigned char>(
588 resources_->getDefaultStreamCurrentDevice());
589 }
590
591 Tensor<float, 3, true>
592 IVFPQ::getPQCentroids() {
593 return pqCentroidsMiddleCode_;
594 }
595
596 void
597 IVFPQ::runPQPrecomputedCodes_(
598 Tensor<float, 2, true>& queries,
599 DeviceTensor<float, 2, true>& coarseDistances,
600 DeviceTensor<int, 2, true>& coarseIndices,
601 int k,
602 Tensor<float, 2, true>& outDistances,
603 Tensor<long, 2, true>& outIndices) {
604 auto& mem = resources_->getMemoryManagerCurrentDevice();
605 auto stream = resources_->getDefaultStreamCurrentDevice();
606
607 // Compute precomputed code term 3, - 2 * (x|y_R)
608 // This is done via batch MM
609 // {sub q} x {(query id)(sub dim) * (code id)(sub dim)'} =>
610 // {sub q} x {(query id)(code id)}
611 DeviceTensor<float, 3, true> term3Transposed(
612 mem,
613 {queries.getSize(0), numSubQuantizers_, numSubQuantizerCodes_},
614 stream);
615
616 // These allocations within are only temporary, so release them when
617 // we're done to maximize free space
618 {
619 auto querySubQuantizerView = queries.view<3>(
620 {queries.getSize(0), numSubQuantizers_, dimPerSubQuantizer_});
621 DeviceTensor<float, 3, true> queriesTransposed(
622 mem,
623 {numSubQuantizers_, queries.getSize(0), dimPerSubQuantizer_},
624 stream);
625 runTransposeAny(querySubQuantizerView, 0, 1, queriesTransposed, stream);
626
627 DeviceTensor<float, 3, true> term3(
628 mem,
629 {numSubQuantizers_, queries.getSize(0), numSubQuantizerCodes_},
630 stream);
631
632 runIteratedMatrixMult(term3, false,
633 queriesTransposed, false,
634 pqCentroidsMiddleCode_, true,
635 -2.0f, 0.0f,
636 resources_->getBlasHandleCurrentDevice(),
637 stream);
638
639 runTransposeAny(term3, 0, 1, term3Transposed, stream);
640 }
641
642 NoTypeTensor<3, true> term2;
643 NoTypeTensor<3, true> term3;
644 #ifdef FAISS_USE_FLOAT16
645 DeviceTensor<half, 3, true> term3Half;
646
647 if (useFloat16LookupTables_) {
648 term3Half = toHalf(resources_, stream, term3Transposed);
649 term2 = NoTypeTensor<3, true>(precomputedCodeHalf_);
650 term3 = NoTypeTensor<3, true>(term3Half);
651 }
652 #endif
653
654 if (!useFloat16LookupTables_) {
655 term2 = NoTypeTensor<3, true>(precomputedCode_);
656 term3 = NoTypeTensor<3, true>(term3Transposed);
657 }
658
659 runPQScanMultiPassPrecomputed(queries,
660 coarseDistances, // term 1
661 term2, // term 2
662 term3, // term 3
663 coarseIndices,
664 useFloat16LookupTables_,
665 bytesPerVector_,
666 numSubQuantizers_,
667 numSubQuantizerCodes_,
668 deviceListDataPointers_,
669 deviceListIndexPointers_,
670 indicesOptions_,
671 deviceListLengths_,
672 maxListLength_,
673 k,
674 outDistances,
675 outIndices,
676 resources_);
677 }
678
679 void
680 IVFPQ::runPQNoPrecomputedCodes_(
681 Tensor<float, 2, true>& queries,
682 DeviceTensor<float, 2, true>& coarseDistances,
683 DeviceTensor<int, 2, true>& coarseIndices,
684 int k,
685 Tensor<float, 2, true>& outDistances,
686 Tensor<long, 2, true>& outIndices) {
687 FAISS_ASSERT(!quantizer_->getUseFloat16());
688 auto& coarseCentroids = quantizer_->getVectorsFloat32Ref();
689
690 runPQScanMultiPassNoPrecomputed(queries,
691 coarseCentroids,
692 pqCentroidsInnermostCode_,
693 coarseIndices,
694 useFloat16LookupTables_,
695 bytesPerVector_,
696 numSubQuantizers_,
697 numSubQuantizerCodes_,
698 deviceListDataPointers_,
699 deviceListIndexPointers_,
700 indicesOptions_,
701 deviceListLengths_,
702 maxListLength_,
703 k,
704 outDistances,
705 outIndices,
706 resources_);
707 }
708
709 } } // namespace
faiss::gpu::IVFBase::numLists_
const int numLists_
Number of inverted lists we maintain.
Definition: IVFBase.cuh:90
faiss::gpu::IVFBase::maxListLength_
int maxListLength_
Maximum list length seen.
Definition: IVFBase.cuh:111
faiss::gpu::IVFPQ::addCodeVectorsFromCpu
void addCodeVectorsFromCpu(int listId, const void *codes, const long *indices, size_t numVecs)
Definition: IVFPQ.cu:347
faiss::gpu::FlatIndex::getSize
int getSize() const
Returns the number of vectors we contain.
Definition: FlatIndex.cu:40
faiss::gpu::IVFBase::listOffsetToUserIndex_
std::vector< std::vector< long > > listOffsetToUserIndex_
Definition: IVFBase.cuh:123
faiss::gpu::FlatIndex
Holder of GPU resources for a particular flat index.
Definition: FlatIndex.cuh:23
faiss::gpu::Tensor::data
__host__ __device__ DataPtrType data()
Returns a raw pointer to the start of our data.
Definition: Tensor.cuh:162
faiss::gpu::IVFBase
Base inverted list functionality for IVFFlat and IVFPQ.
Definition: IVFBase.cuh:27
faiss::gpu::GpuResources
Definition: GpuResources.h:24
faiss::gpu::IVFPQ::IVFPQ
IVFPQ(GpuResources *resources, FlatIndex *quantizer, int numSubQuantizers, int bitsPerSubQuantizer, float *pqCentroidData, IndicesOptions indicesOptions, bool useFloat16LookupTables)
Definition: IVFPQ.cu:36
faiss::gpu::IVFBase::deviceListLengths_
thrust::device_vector< int > deviceListLengths_
Definition: IVFBase.cuh:108
faiss::gpu::IVFPQ::isSupportedPQCodeLength
static bool isSupportedPQCodeLength(int size)
Returns true if we support PQ in this size.
Definition: IVFPQ.cu:71
faiss::gpu::IVFBase::deviceListIndexPointers_
thrust::device_vector< void * > deviceListIndexPointers_
Definition: IVFBase.cuh:104
faiss::gpu::IVFPQ::classifyAndAddVectors
int classifyAndAddVectors(Tensor< float, 2, true > &vecs, Tensor< long, 1, true > &indices)
Definition: IVFPQ.cu:119
faiss::gpu::IVFPQ::query
void query(Tensor< float, 2, true > &queries, int nprobe, int k, Tensor< float, 2, true > &outDistances, Tensor< long, 2, true > &outIndices)
Definition: IVFPQ.cu:517
faiss::gpu::IVFPQ::getPQCentroids
Tensor< float, 3, true > getPQCentroids()
Definition: IVFPQ.cu:592
faiss::gpu::IVFBase::quantizer_
FlatIndex * quantizer_
Quantizer object.
Definition: IVFBase.cuh:84
faiss::gpu::IVFPQ::setPrecomputedCodes
void setPrecomputedCodes(bool enable)
Enable or disable pre-computed codes.
Definition: IVFPQ.cu:101
faiss::gpu::IVFPQ::getListCodes
std::vector< unsigned char > getListCodes(int listId) const
Return the list codes of a particular list back to the CPU.
Definition: IVFPQ.cu:584
faiss::gpu::IVFBase::deviceListDataPointers_
thrust::device_vector< void * > deviceListDataPointers_
Definition: IVFBase.cuh:100
faiss::gpu::IVFBase::resources_
GpuResources * resources_
Collection of GPU resources that we use.
Definition: IVFBase.cuh:81
faiss::gpu::Tensor
Our tensor type.
Definition: Tensor.cuh:31
faiss::gpu::Tensor::view
__host__ __device__ Tensor< T, SubDim, Contig, IndexT, PtrTraits > view(DataPtrType at)
Definition: Tensor-inl.cuh:526
faiss::gpu::IVFBase::bytesPerVector_
const int bytesPerVector_
Number of bytes per vector in the list.
Definition: IVFBase.cuh:93
faiss::gpu::IVFBase::updateDeviceListInfo_
void updateDeviceListInfo_(cudaStream_t stream)
Update all device-side list pointer and size information.
Definition: IVFBase.cu:137
faiss::gpu::Tensor::getSize
__host__ __device__ IndexT getSize(int i) const
Definition: Tensor.cuh:210
faiss::gpu::Tensor::copyFrom
__host__ void copyFrom(Tensor< T, Dim, Contig, IndexT, PtrTraits > &t, cudaStream_t stream)
Copies a tensor into ourselves; sizes must match.
Definition: Tensor-inl.cuh:101
faiss::gpu::FlatIndex::getVectorsFloat32Ref
Tensor< float, 2, true > & getVectorsFloat32Ref()
Returns a reference to our vectors currently in use.
Definition: FlatIndex.cu:61
faiss::gpu::IVFBase::indicesOptions_
const IndicesOptions indicesOptions_
How are user indices stored on the GPU?
Definition: IVFBase.cuh:96
faiss::gpu::HostTensor
Definition: HostTensor.cuh:23
faiss::gpu::IVFBase::deviceListData_
std::vector< std::unique_ptr< DeviceVector< unsigned char > > > deviceListData_
Definition: IVFBase.cuh:117
faiss::gpu::DeviceTensor< float, 3, true >
faiss::gpu::IVFBase::dim_
const int dim_
Expected dimensionality of the vectors.
Definition: IVFBase.cuh:87
faiss::gpu::IVFBase::addIndicesFromCpu_
void addIndicesFromCpu_(int listId, const long *indices, size_t numVecs)
Shared function to copy indices from CPU to GPU.
Definition: IVFBase.cu:244
faiss::gpu::IVFPQ::isSupportedNoPrecomputedSubDimSize
static bool isSupportedNoPrecomputedSubDimSize(int dims)
Definition: IVFPQ.cu:96