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;
126 for (
size_t i = 0; i < index->codes.size(); ++i) {
127 auto& codes = index->codes[i];
128 auto& ids = index->
ids[i];
130 FAISS_ASSERT(ids.size() * subQuantizers_ == codes.size());
133 FAISS_THROW_IF_NOT_FMT(ids.size() <=
134 (size_t) std::numeric_limits<int>::max(),
135 "GPU inverted list can only support "
136 "%zu entries; %zu found",
137 (size_t) std::numeric_limits<int>::max(),
140 index_->addCodeVectorsFromCpu(i, codes.data(), ids.data(), ids.size());
149 FAISS_THROW_IF_NOT_MSG(ivfpqConfig_.
indicesOptions != INDICES_IVF,
150 "Cannot copy to CPU as GPU index doesn't retain "
151 "indices (INDICES_IVF)");
169 index->codes.clear();
170 index->codes.resize(
nlist_);
175 for (
int i = 0; i <
nlist_; ++i) {
182 index->
pq.
centroids.resize(devPQCentroids.numElements());
184 fromDevice<float, 3>(devPQCentroids,
196 reserveMemoryVecs_ = numVecs;
221 return subQuantizers_;
231 return utils::pow2(bitsPerCode_);
252 FAISS_ASSERT(this->
ntotal == 0);
257 GpuIndexIVFPQ::trainResidualQuantizer_(
Index::idx_t n,
const float* x) {
260 n = std::min(n, (
Index::idx_t) (1 << bitsPerCode_) * 64);
263 printf(
"computing residuals\n");
266 std::vector<Index::idx_t>
assign(n);
269 std::vector<float> residuals(n *
d);
271 for (
idx_t i = 0; i < n; i++) {
276 printf(
"training %d x %d product quantizer on %ld vectors in %dD\n",
283 pq.train(n, residuals.data());
293 if (reserveMemoryVecs_) {
307 FAISS_ASSERT(index_);
311 FAISS_ASSERT(!index_);
313 trainQuantizer_(n, x);
314 trainResidualQuantizer_(n, x);
324 FAISS_ASSERT(index_);
327 auto stream =
resources_->getDefaultStreamCurrentDevice();
332 const_cast<float*
>(x),
334 {(int) n, index_->
getDim()});
356 FAISS_ASSERT(index_);
364 const_cast<float*
>(x),
365 resources_->getDefaultStream(device_),
366 {(int) n, index_->
getDim()});
371 resources_->getDefaultStream(device_),
377 resources_->getDefaultStream(device_),
387 fromDevice<float, 2>(
388 devDistances, distances, resources_->getDefaultStream(device_));
389 fromDevice<faiss::Index::idx_t, 2>(
390 devLabels, labels, resources_->getDefaultStream(device_));
395 FAISS_ASSERT(index_);
399 std::vector<unsigned char>
401 FAISS_ASSERT(index_);
409 FAISS_ASSERT(index_);
416 GpuIndexIVFPQ::verifySettings_()
const {
420 FAISS_THROW_IF_NOT_MSG(
nlist_ > 0,
"nlist must be >0");
423 FAISS_THROW_IF_NOT_FMT(bitsPerCode_ <= 8,
424 "Bits per code must be <= 8 (passed %d)", bitsPerCode_);
427 FAISS_THROW_IF_NOT_FMT(this->
d % subQuantizers_ == 0,
428 "Number of sub-quantizers (%d) must be an "
429 "even divisor of the number of dimensions (%d)",
430 subQuantizers_, this->
d);
434 "Number of bytes per encoded vector / sub-quantizers (%d) "
440 int lookupTableSize =
sizeof(float);
441 #ifdef FAISS_USE_FLOAT16
443 lookupTableSize =
sizeof(half);
449 size_t requiredSmemSize =
450 lookupTableSize * subQuantizers_ * utils::pow2(bitsPerCode_);
451 size_t smemPerBlock = getMaxSharedMemPerBlock(device_);
453 FAISS_THROW_IF_NOT_FMT(requiredSmemSize
454 <= getMaxSharedMemPerBlock(device_),
455 "Device %d has %zu bytes of shared memory, while "
456 "%d bits per code and %d sub-quantizers requires %zu "
457 "bytes. Consider useFloat16LookupTables and/or "
459 device_, smemPerBlock, bitsPerCode_, subQuantizers_,
466 this->d / subQuantizers_),
467 "Number of dimensions per sub-quantizer (%d) "
468 "is unsupported with precomputed codes",
469 this->d / subQuantizers_);
472 FAISS_THROW_IF_NOT_MSG(this->
metric_type == faiss::METRIC_L2,
473 "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
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
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)
size_t code_size
code size per vector in bytes
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.
MetricType
Some algorithms support both an inner product vetsion 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)