11 #include "GpuIndexIVFPQ.h"
12 #include "../IndexFlat.h"
13 #include "../IndexIVFPQ.h"
14 #include "../ProductQuantizer.h"
15 #include "GpuIndexFlat.h"
16 #include "GpuResources.h"
17 #include "impl/IVFPQ.cuh"
18 #include "utils/CopyUtils.cuh"
19 #include "utils/DeviceUtils.h"
23 namespace faiss {
namespace gpu {
36 reserveMemoryVecs_(0),
38 #ifndef FAISS_USE_FLOAT16
58 subQuantizers_(subQuantizers),
59 bitsPerCode_(bitsPerCode),
60 reserveMemoryVecs_(0),
62 #ifndef FAISS_USE_FLOAT16
63 FAISS_ASSERT(!useFloat16LookupTables_);
69 FAISS_ASSERT(this->
metric_type == faiss::METRIC_L2);
75 GpuIndexIVFPQ::~GpuIndexIVFPQ() {
84 FAISS_THROW_IF_NOT_MSG(index->
metric_type == faiss::METRIC_L2,
85 "inner product unsupported");
92 subQuantizers_ = index->
pq.
M;
125 for (
size_t i = 0; i < index->codes.size(); ++i) {
126 auto& codes = index->codes[i];
127 auto& ids = index->
ids[i];
129 FAISS_ASSERT(ids.size() * subQuantizers_ == codes.size());
132 FAISS_THROW_IF_NOT_FMT(ids.size() <=
133 (size_t) std::numeric_limits<int>::max(),
134 "GPU inverted list can only support "
135 "%zu entries; %zu found",
136 (size_t) std::numeric_limits<int>::max(),
139 index_->addCodeVectorsFromCpu(i, codes.data(), ids.data(), ids.size());
148 FAISS_THROW_IF_NOT_MSG(ivfpqConfig_.
indicesOptions != INDICES_IVF,
149 "Cannot copy to CPU as GPU index doesn't retain "
150 "indices (INDICES_IVF)");
168 index->codes.clear();
169 index->codes.resize(
nlist_);
174 for (
int i = 0; i <
nlist_; ++i) {
181 index->
pq.
centroids.resize(devPQCentroids.numElements());
183 fromDevice<float, 3>(devPQCentroids,
195 reserveMemoryVecs_ = numVecs;
220 return subQuantizers_;
230 return utils::pow2(bitsPerCode_);
251 FAISS_ASSERT(this->
ntotal == 0);
256 GpuIndexIVFPQ::trainResidualQuantizer_(
Index::idx_t n,
const float* x) {
259 n = std::min(n, (
Index::idx_t) (1 << bitsPerCode_) * 64);
262 printf(
"computing residuals\n");
265 std::vector<Index::idx_t>
assign(n);
268 std::vector<float> residuals(n *
d);
270 for (
idx_t i = 0; i < n; i++) {
275 printf(
"training %d x %d product quantizer on %ld vectors in %dD\n",
282 pq.train(n, residuals.data());
292 if (reserveMemoryVecs_) {
306 FAISS_ASSERT(index_);
310 FAISS_ASSERT(!index_);
312 trainQuantizer_(n, x);
313 trainResidualQuantizer_(n, x);
323 FAISS_ASSERT(index_);
331 const_cast<float*
>(x),
333 {(int) n, index_->
getDim()});
355 FAISS_ASSERT(index_);
363 const_cast<float*
>(x),
364 resources_->getDefaultStream(device_),
365 {(int) n, index_->
getDim()});
370 resources_->getDefaultStream(device_),
376 resources_->getDefaultStream(device_),
386 fromDevice<float, 2>(
387 devDistances, distances, resources_->getDefaultStream(device_));
388 fromDevice<faiss::Index::idx_t, 2>(
389 devLabels, labels, resources_->getDefaultStream(device_));
394 FAISS_ASSERT(index_);
398 std::vector<unsigned char>
400 FAISS_ASSERT(index_);
408 FAISS_ASSERT(index_);
415 GpuIndexIVFPQ::verifySettings_()
const {
419 FAISS_THROW_IF_NOT_MSG(
nlist_ > 0,
"nlist must be >0");
422 FAISS_THROW_IF_NOT_FMT(bitsPerCode_ <= 8,
423 "Bits per code must be <= 8 (passed %d)", bitsPerCode_);
426 FAISS_THROW_IF_NOT_FMT(this->
d % subQuantizers_ == 0,
427 "Number of sub-quantizers (%d) must be an "
428 "even divisor of the number of dimensions (%d)",
429 subQuantizers_, this->
d);
433 "Number of bytes per encoded vector / sub-quantizers (%d) "
439 int lookupTableSize =
sizeof(float);
440 #ifdef FAISS_USE_FLOAT16
442 lookupTableSize =
sizeof(half);
448 size_t requiredSmemSize =
449 lookupTableSize * subQuantizers_ * utils::pow2(bitsPerCode_);
450 size_t smemPerBlock = getMaxSharedMemPerBlock(device_);
452 FAISS_THROW_IF_NOT_FMT(requiredSmemSize
453 <= getMaxSharedMemPerBlock(device_),
454 "Device %d has %zu bytes of shared memory, while "
455 "%d bits per code and %d sub-quantizers requires %zu "
456 "bytes. Consider useFloat16LookupTables and/or "
458 device_, smemPerBlock, bitsPerCode_, subQuantizers_,
465 this->d / subQuantizers_),
466 "Number of dimensions per sub-quantizer (%d) "
467 "is not currently supported without precomputed codes. "
468 "Only 1, 2, 3, 4, 6, 8, 10, 12, 16, 20, 24, 28, 32 dims "
469 "per sub-quantizer are currently supported with no "
470 "precomputed codes. "
471 "Precomputed codes supports any number of dimensions, but "
472 "will involve memory overheads.",
473 this->d / subQuantizers_);
476 FAISS_THROW_IF_NOT_MSG(this->
metric_type == faiss::METRIC_L2,
477 "METRIC_INNER_PRODUCT is currently unsupported");
std::vector< long > getListIndices(int listId) const
void searchImpl_(faiss::Index::idx_t n, const float *x, faiss::Index::idx_t k, float *distances, faiss::Index::idx_t *labels) const override
Called from GpuIndex for search.
void precompute_table()
build precomputed table
size_t nbits
number of bits per quantization index
cudaStream_t getDefaultStreamCurrentDevice()
Calls getDefaultStream with the current device.
bool usePrecomputedTables
PolysemousTraining * polysemous_training
if NULL, use default
size_t byte_per_idx
nb bytes per code component (1 or 2)
GpuIndexIVFPQ(GpuResources *resources, const faiss::IndexIVFPQ *index, GpuIndexIVFPQConfig config=GpuIndexIVFPQConfig())
int getDim() const
Return the number of dimensions we are indexing.
int getListLength(int listId) const
FlatIndex * getGpuData()
For internal access.
void assign(idx_t n, const float *x, idx_t *labels, idx_t k=1)
void reserveMemory(size_t numVecs)
Reserve GPU memory in our inverted lists for this number of vectors.
int getListLength(int listId) const
bool do_polysemous_training
reorder PQ centroids after training?
size_t scan_table_threshold
use table computation or on-the-fly?
std::vector< float > precomputed_table
int polysemous_ht
Hamming thresh for polysemous filtering.
int getBitsPerCode() const
Return the number of bits per PQ code.
bool useFloat16LookupTables
virtual cudaStream_t getDefaultStream(int device)=0
std::vector< std::vector< long > > ids
Inverted lists for indexes.
void train(Index::idx_t n, const float *x) override
size_t max_codes
max nb of codes to visit to do a query
static bool isSupportedPQCodeLength(int size)
Returns true if we support PQ in this size.
int nprobe_
Number of inverted list probes per query.
void reserveMemory(size_t numVecs)
Reserve GPU memory in our inverted lists for this number of vectors.
int classifyAndAddVectors(Tensor< float, 2, true > &vecs, Tensor< long, 1, true > &indices)
void query(Tensor< float, 2, true > &queries, int nprobe, int k, Tensor< float, 2, true > &outDistances, Tensor< long, 2, true > &outIndices)
const int device_
The GPU device we are resident on.
void copyFrom(const faiss::IndexIVFPQ *index)
Tensor< float, 3, true > getPQCentroids()
GpuResources * resources_
Manages streans, cuBLAS handles and scratch memory for devices.
void copyTo(faiss::IndexIVF *index) const
Copy what we have to the CPU equivalent.
long idx_t
all indices are this type
int nlist_
Number of inverted lists that we manage.
void addImpl_(faiss::Index::idx_t n, const float *x, const faiss::Index::idx_t *ids) override
Called from GpuIndex for add/add_with_ids.
idx_t ntotal
total nb of indexed vectors
bool verbose
verbosity level
void setPrecomputedCodes(bool enable)
Enable or disable pre-computed codes.
std::vector< unsigned char > getListCodes(int listId) const
Return the list codes of a particular list back to the CPU.
void copyTo(faiss::IndexIVFPQ *index) const
const MemorySpace memorySpace_
The memory space of our primary storage on the GPU.
bool by_residual
Encode residual or plain vector?
GpuIndexFlat * quantizer_
Quantizer for inverted lists.
MetricType metric_type
type of metric this index uses for search
ProductQuantizer pq
produces the codes
size_t M
number of subquantizers
int getNumSubQuantizers() const
Return the number of sub-quantizers we are using.
std::vector< long > getListIndices(int listId) const
Return the list indices of a particular list back to the CPU.
int getCentroidsPerSubQuantizer() const
Return the number of centroids per PQ code (2^bits per code)
void setPrecomputedCodes(bool enable)
Enable or disable pre-computed codes.
void copyFrom(const faiss::IndexIVF *index)
Copy what we need from the CPU equivalent.
bool is_trained
set if the Index does not require training, or if training is done already
void compute_residual(const float *x, float *residual, idx_t key) const
bool getPrecomputedCodes() const
Are pre-computed codes enabled?
IndicesOptions indicesOptions
Index storage options for the GPU.
Implementing class for IVFPQ on the GPU.
size_t code_size
code size per vector in bytes
MetricType
Some algorithms support both an inner product version and a L2 search version.
int use_precomputed_table
if by_residual, build precompute tables
std::vector< unsigned char > getListCodes(int listId) const
std::vector< float > centroids
Centroid table, size M * ksub * dsub.
static bool isSupportedNoPrecomputedSubDimSize(int dims)