Faiss
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
GpuIndexIVFPQ.cu
1 /**
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD+Patents license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 // Copyright 2004-present Facebook. All Rights Reserved.
10 
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"
20 
21 #include <limits>
22 
23 namespace faiss { namespace gpu {
24 
26  const faiss::IndexIVFPQ* index,
27  GpuIndexIVFPQConfig config) :
28  GpuIndexIVF(resources,
29  index->d,
30  index->metric_type,
31  index->nlist,
32  config),
33  ivfpqConfig_(config),
34  subQuantizers_(0),
35  bitsPerCode_(0),
36  reserveMemoryVecs_(0),
37  index_(nullptr) {
38 #ifndef FAISS_USE_FLOAT16
39  FAISS_ASSERT(!ivfpqConfig_.useFloat16LookupTables);
40 #endif
41 
42  copyFrom(index);
43 }
44 
46  int dims,
47  int nlist,
48  int subQuantizers,
49  int bitsPerCode,
50  faiss::MetricType metric,
51  GpuIndexIVFPQConfig config) :
52  GpuIndexIVF(resources,
53  dims,
54  metric,
55  nlist,
56  config),
57  ivfpqConfig_(config),
58  subQuantizers_(subQuantizers),
59  bitsPerCode_(bitsPerCode),
60  reserveMemoryVecs_(0),
61  index_(nullptr) {
62 #ifndef FAISS_USE_FLOAT16
63  FAISS_ASSERT(!useFloat16LookupTables_);
64 #endif
65 
66  verifySettings_();
67 
68  // FIXME make IP work fully
69  FAISS_ASSERT(this->metric_type == faiss::METRIC_L2);
70 
71  // We haven't trained ourselves, so don't construct the PQ index yet
72  this->is_trained = false;
73 }
74 
75 GpuIndexIVFPQ::~GpuIndexIVFPQ() {
76  delete index_;
77 }
78 
79 void
81  DeviceScope scope(device_);
82 
83  // FIXME: support this
84  FAISS_THROW_IF_NOT_MSG(index->metric_type == faiss::METRIC_L2,
85  "inner product unsupported");
86  GpuIndexIVF::copyFrom(index);
87 
88  // Clear out our old data
89  delete index_;
90  index_ = nullptr;
91 
92  subQuantizers_ = index->pq.M;
93  bitsPerCode_ = index->pq.nbits;
94 
95  // We only support this
96  FAISS_ASSERT(index->pq.byte_per_idx == 1);
97  FAISS_ASSERT(index->by_residual);
98  FAISS_ASSERT(index->polysemous_ht == 0);
99 
100  verifySettings_();
101 
102  // The other index might not be trained
103  if (!index->is_trained) {
104  return;
105  }
106 
107  // Otherwise, we can populate ourselves from the other index
108  this->is_trained = true;
109 
110  // Copy our lists as well
111  // The product quantizer must have data in it
112  FAISS_ASSERT(index->pq.centroids.size() > 0);
113  index_ = new IVFPQ(resources_,
115  subQuantizers_,
116  bitsPerCode_,
117  (float*) index->pq.centroids.data(),
118  ivfpqConfig_.indicesOptions,
119  ivfpqConfig_.useFloat16LookupTables,
120  memorySpace_);
121  // Doesn't make sense to reserve memory here
122  index_->setPrecomputedCodes(ivfpqConfig_.usePrecomputedTables);
123 
124  // Copy database vectors, if any
125  for (size_t i = 0; i < index->codes.size(); ++i) {
126  auto& codes = index->codes[i];
127  auto& ids = index->ids[i];
128 
129  FAISS_ASSERT(ids.size() * subQuantizers_ == codes.size());
130 
131  // GPU index can only support max int entries per list
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(),
137  ids.size());
138 
139  index_->addCodeVectorsFromCpu(i, codes.data(), ids.data(), ids.size());
140  }
141 }
142 
143 void
145  DeviceScope scope(device_);
146 
147  // We must have the indices in order to copy to ourselves
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)");
151 
152  GpuIndexIVF::copyTo(index);
153 
154  //
155  // IndexIVFPQ information
156  //
157  index->by_residual = true;
158  index->use_precomputed_table = 0;
159  index->code_size = subQuantizers_;
160  index->pq = faiss::ProductQuantizer(this->d, subQuantizers_, bitsPerCode_);
161 
162  index->do_polysemous_training = false;
163  index->polysemous_training = nullptr;
164 
165  index->scan_table_threshold = 0;
166  index->max_codes = 0;
167  index->polysemous_ht = 0;
168  index->codes.clear();
169  index->codes.resize(nlist_);
170  index->precomputed_table.clear();
171 
172  if (index_) {
173  // Copy the inverted lists
174  for (int i = 0; i < nlist_; ++i) {
175  index->ids[i] = getListIndices(i);
176  index->codes[i] = getListCodes(i);
177  }
178 
179  // Copy PQ centroids
180  auto devPQCentroids = index_->getPQCentroids();
181  index->pq.centroids.resize(devPQCentroids.numElements());
182 
183  fromDevice<float, 3>(devPQCentroids,
184  index->pq.centroids.data(),
186 
187  if (ivfpqConfig_.usePrecomputedTables) {
188  index->precompute_table();
189  }
190  }
191 }
192 
193 void
195  reserveMemoryVecs_ = numVecs;
196  if (index_) {
197  DeviceScope scope(device_);
198  index_->reserveMemory(numVecs);
199  }
200 }
201 
202 void
204  ivfpqConfig_.usePrecomputedTables = enable;
205  if (index_) {
206  DeviceScope scope(device_);
207  index_->setPrecomputedCodes(enable);
208  }
209 
210  verifySettings_();
211 }
212 
213 bool
215  return ivfpqConfig_.usePrecomputedTables;
216 }
217 
218 int
220  return subQuantizers_;
221 }
222 
223 int
225  return bitsPerCode_;
226 }
227 
228 int
230  return utils::pow2(bitsPerCode_);
231 }
232 
233 size_t
235  if (index_) {
236  DeviceScope scope(device_);
237  return index_->reclaimMemory();
238  }
239 
240  return 0;
241 }
242 
243 void
245  if (index_) {
246  DeviceScope scope(device_);
247 
248  index_->reset();
249  this->ntotal = 0;
250  } else {
251  FAISS_ASSERT(this->ntotal == 0);
252  }
253 }
254 
255 void
256 GpuIndexIVFPQ::trainResidualQuantizer_(Index::idx_t n, const float* x) {
257  // Code largely copied from faiss::IndexIVFPQ
258  // FIXME: GPUize more of this
259  n = std::min(n, (Index::idx_t) (1 << bitsPerCode_) * 64);
260 
261  if (this->verbose) {
262  printf("computing residuals\n");
263  }
264 
265  std::vector<Index::idx_t> assign(n);
266  quantizer_->assign (n, x, assign.data());
267 
268  std::vector<float> residuals(n * d);
269 
270  for (idx_t i = 0; i < n; i++) {
271  quantizer_->compute_residual(x + i * d, &residuals[i * d], assign[i]);
272  }
273 
274  if (this->verbose) {
275  printf("training %d x %d product quantizer on %ld vectors in %dD\n",
276  subQuantizers_, getCentroidsPerSubQuantizer(), n, this->d);
277  }
278 
279  // Just use the CPU product quantizer to determine sub-centroids
280  faiss::ProductQuantizer pq(this->d, subQuantizers_, bitsPerCode_);
281  pq.verbose = this->verbose;
282  pq.train(n, residuals.data());
283 
284  index_ = new IVFPQ(resources_,
286  subQuantizers_,
287  bitsPerCode_,
288  pq.centroids.data(),
289  ivfpqConfig_.indicesOptions,
290  ivfpqConfig_.useFloat16LookupTables,
291  memorySpace_);
292  if (reserveMemoryVecs_) {
293  index_->reserveMemory(reserveMemoryVecs_);
294  }
295 
296  index_->setPrecomputedCodes(ivfpqConfig_.usePrecomputedTables);
297 }
298 
299 void
300 GpuIndexIVFPQ::train(Index::idx_t n, const float* x) {
301  DeviceScope scope(device_);
302 
303  if (this->is_trained) {
304  FAISS_ASSERT(quantizer_->is_trained);
305  FAISS_ASSERT(quantizer_->ntotal == nlist_);
306  FAISS_ASSERT(index_);
307  return;
308  }
309 
310  FAISS_ASSERT(!index_);
311 
312  trainQuantizer_(n, x);
313  trainResidualQuantizer_(n, x);
314 
315  this->is_trained = true;
316 }
317 
318 void
320  const float* x,
321  const Index::idx_t* xids) {
322  // Device is already set in GpuIndex::addInternal_
323  FAISS_ASSERT(index_);
324  FAISS_ASSERT(n > 0);
325 
326  auto stream = resources_->getDefaultStreamCurrentDevice();
327 
328  auto deviceVecs =
329  toDevice<float, 2>(resources_,
330  device_,
331  const_cast<float*>(x),
332  stream,
333  {(int) n, index_->getDim()});
334 
335  auto deviceIndices =
336  toDevice<Index::idx_t, 1>(resources_,
337  device_,
338  const_cast<Index::idx_t*>(xids),
339  stream,
340  {(int) n});
341 
342  // Not all vectors may be able to be added (some may contain NaNs
343  // etc)
344  ntotal += index_->classifyAndAddVectors(deviceVecs, deviceIndices);
345 }
346 
347 void
349  const float* x,
351  float* distances,
352  faiss::Index::idx_t* labels) const {
353  // Device is already set in GpuIndex::search
354 
355  FAISS_ASSERT(index_);
356  FAISS_ASSERT(n > 0);
357 
358  // Make sure arguments are on the device we desire; use temporary
359  // memory allocations to move it if necessary
360  auto devX =
361  toDevice<float, 2>(resources_,
362  device_,
363  const_cast<float*>(x),
364  resources_->getDefaultStream(device_),
365  {(int) n, index_->getDim()});
366  auto devDistances =
367  toDevice<float, 2>(resources_,
368  device_,
369  distances,
370  resources_->getDefaultStream(device_),
371  {(int) n, (int) k});
372  auto devLabels =
373  toDevice<faiss::Index::idx_t, 2>(resources_,
374  device_,
375  labels,
376  resources_->getDefaultStream(device_),
377  {(int) n, (int) k});
378 
379  index_->query(devX,
380  nprobe_,
381  (int) k,
382  devDistances,
383  devLabels);
384 
385  // Copy back if necessary
386  fromDevice<float, 2>(
387  devDistances, distances, resources_->getDefaultStream(device_));
388  fromDevice<faiss::Index::idx_t, 2>(
389  devLabels, labels, resources_->getDefaultStream(device_));
390 }
391 
392 int
393 GpuIndexIVFPQ::getListLength(int listId) const {
394  FAISS_ASSERT(index_);
395  return index_->getListLength(listId);
396 }
397 
398 std::vector<unsigned char>
399 GpuIndexIVFPQ::getListCodes(int listId) const {
400  FAISS_ASSERT(index_);
401  DeviceScope scope(device_);
402 
403  return index_->getListCodes(listId);
404 }
405 
406 std::vector<long>
407 GpuIndexIVFPQ::getListIndices(int listId) const {
408  FAISS_ASSERT(index_);
409  DeviceScope scope(device_);
410 
411  return index_->getListIndices(listId);
412 }
413 
414 void
415 GpuIndexIVFPQ::verifySettings_() const {
416  // Our implementation has these restrictions:
417 
418  // Must have some number of lists
419  FAISS_THROW_IF_NOT_MSG(nlist_ > 0, "nlist must be >0");
420 
421  // up to a single byte per code
422  FAISS_THROW_IF_NOT_FMT(bitsPerCode_ <= 8,
423  "Bits per code must be <= 8 (passed %d)", bitsPerCode_);
424 
425  // Sub-quantizers must evenly divide dimensions available
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);
430 
431  // The number of bytes per encoded vector must be one we support
432  FAISS_THROW_IF_NOT_FMT(IVFPQ::isSupportedPQCodeLength(subQuantizers_),
433  "Number of bytes per encoded vector / sub-quantizers (%d) "
434  "is not supported",
435  subQuantizers_);
436 
437  // We must have enough shared memory on the current device to store
438  // our lookup distances
439  int lookupTableSize = sizeof(float);
440 #ifdef FAISS_USE_FLOAT16
441  if (ivfpqConfig_.useFloat16LookupTables) {
442  lookupTableSize = sizeof(half);
443  }
444 #endif
445 
446  // 64 bytes per code is only supported with usage of float16, at 2^8
447  // codes per subquantizer
448  size_t requiredSmemSize =
449  lookupTableSize * subQuantizers_ * utils::pow2(bitsPerCode_);
450  size_t smemPerBlock = getMaxSharedMemPerBlock(device_);
451 
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 "
457  "reduce parameters",
458  device_, smemPerBlock, bitsPerCode_, subQuantizers_,
459  requiredSmemSize);
460 
461  // If precomputed codes are disabled, we have an extra limitation in
462  // terms of the number of dimensions per subquantizer
463  FAISS_THROW_IF_NOT_FMT(ivfpqConfig_.usePrecomputedTables ||
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_);
474 
475  // TODO: fully implement METRIC_INNER_PRODUCT
476  FAISS_THROW_IF_NOT_MSG(this->metric_type == faiss::METRIC_L2,
477  "METRIC_INNER_PRODUCT is currently unsupported");
478 }
479 
480 } } // namespace
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
Definition: IndexIVFPQ.cpp:356
size_t nbits
number of bits per quantization index
cudaStream_t getDefaultStreamCurrentDevice()
Calls getDefaultStream with the current device.
PolysemousTraining * polysemous_training
if NULL, use default
Definition: IndexIVFPQ.h:35
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.
Definition: IVFBase.cu:100
int getListLength(int listId) const
Definition: IVFBase.cu:200
FlatIndex * getGpuData()
For internal access.
Definition: GpuIndexFlat.h:120
void assign(idx_t n, const float *x, idx_t *labels, idx_t k=1)
Definition: Index.cpp:23
void reserveMemory(size_t numVecs)
Reserve GPU memory in our inverted lists for this number of vectors.
Definition: IVFBase.cu:45
int getListLength(int listId) const
bool do_polysemous_training
reorder PQ centroids after training?
Definition: IndexIVFPQ.h:34
size_t scan_table_threshold
use table computation or on-the-fly?
Definition: IndexIVFPQ.h:38
std::vector< float > precomputed_table
Definition: IndexIVFPQ.h:45
int polysemous_ht
Hamming thresh for polysemous filtering.
Definition: IndexIVFPQ.h:40
int getBitsPerCode() const
Return the number of bits per PQ code.
virtual cudaStream_t getDefaultStream(int device)=0
std::vector< std::vector< long > > ids
Inverted lists for indexes.
Definition: IndexIVF.h:62
int d
vector dimension
Definition: Index.h:64
void train(Index::idx_t n, const float *x) override
size_t max_codes
max nb of codes to visit to do a query
Definition: IndexIVFPQ.h:39
static bool isSupportedPQCodeLength(int size)
Returns true if we support PQ in this size.
Definition: IVFPQ.cu:72
int nprobe_
Number of inverted list probes per query.
Definition: GpuIndexIVF.h:91
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)
Definition: IVFPQ.cu:120
void query(Tensor< float, 2, true > &queries, int nprobe, int k, Tensor< float, 2, true > &outDistances, Tensor< long, 2, true > &outIndices)
Definition: IVFPQ.cu:516
const int device_
The GPU device we are resident on.
Definition: GpuIndex.h:94
void copyFrom(const faiss::IndexIVFPQ *index)
Tensor< float, 3, true > getPQCentroids()
Definition: IVFPQ.cu:591
GpuResources * resources_
Manages streans, cuBLAS handles and scratch memory for devices.
Definition: GpuIndex.h:91
void copyTo(faiss::IndexIVF *index) const
Copy what we have to the CPU equivalent.
Definition: GpuIndexIVF.cu:148
long idx_t
all indices are this type
Definition: Index.h:62
int nlist_
Number of inverted lists that we manage.
Definition: GpuIndexIVF.h:88
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
Definition: Index.h:65
bool verbose
verbosity level
Definition: Index.h:66
void setPrecomputedCodes(bool enable)
Enable or disable pre-computed codes.
Definition: IVFPQ.cu:102
std::vector< unsigned char > getListCodes(int listId) const
Return the list codes of a particular list back to the CPU.
Definition: IVFPQ.cu:583
void copyTo(faiss::IndexIVFPQ *index) const
const MemorySpace memorySpace_
The memory space of our primary storage on the GPU.
Definition: GpuIndex.h:97
bool by_residual
Encode residual or plain vector?
Definition: IndexIVFPQ.h:30
GpuIndexFlat * quantizer_
Quantizer for inverted lists.
Definition: GpuIndexIVF.h:94
MetricType metric_type
type of metric this index uses for search
Definition: Index.h:72
ProductQuantizer pq
produces the codes
Definition: IndexIVFPQ.h:32
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.
Definition: IVFBase.cu:207
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.
Definition: GpuIndexIVF.cu:80
bool is_trained
set if the Index does not require training, or if training is done already
Definition: Index.h:69
void compute_residual(const float *x, float *residual, idx_t key) const
Definition: Index.cpp:56
bool getPrecomputedCodes() const
Are pre-computed codes enabled?
IndicesOptions indicesOptions
Index storage options for the GPU.
Definition: GpuIndexIVF.h:31
size_t reclaimMemory()
Definition: IVFBase.cu:105
Implementing class for IVFPQ on the GPU.
Definition: IVFPQ.cuh:19
size_t code_size
code size per vector in bytes
Definition: IndexIVF.h:64
MetricType
Some algorithms support both an inner product version and a L2 search version.
Definition: Index.h:43
int use_precomputed_table
if by_residual, build precompute tables
Definition: IndexIVFPQ.h:31
std::vector< unsigned char > getListCodes(int listId) const
std::vector< float > centroids
Centroid table, size M * ksub * dsub.
static bool isSupportedNoPrecomputedSubDimSize(int dims)
Definition: IVFPQ.cu:97