forked from facebookresearch/faiss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MetaIndexes.cpp
733 lines (588 loc) · 17.7 KB
/
MetaIndexes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD+Patents license found in the
* LICENSE file in the root directory of this source tree.
*/
// -*- c++ -*-
#include "MetaIndexes.h"
#include <pthread.h>
#include <cstdio>
#include "FaissAssert.h"
#include "Heap.h"
#include "AuxIndexStructures.h"
namespace faiss {
/*****************************************************
* IndexIDMap implementation
*******************************************************/
IndexIDMap::IndexIDMap (Index *index):
index (index),
own_fields (false)
{
FAISS_THROW_IF_NOT_MSG (index->ntotal == 0, "index must be empty on input");
is_trained = index->is_trained;
metric_type = index->metric_type;
verbose = index->verbose;
d = index->d;
}
void IndexIDMap::add (idx_t, const float *)
{
FAISS_THROW_MSG ("add does not make sense with IndexIDMap, "
"use add_with_ids");
}
void IndexIDMap::train (idx_t n, const float *x)
{
index->train (n, x);
is_trained = index->is_trained;
}
void IndexIDMap::reset ()
{
index->reset ();
id_map.clear();
ntotal = 0;
}
void IndexIDMap::add_with_ids (idx_t n, const float * x, const long *xids)
{
index->add (n, x);
for (idx_t i = 0; i < n; i++)
id_map.push_back (xids[i]);
ntotal = index->ntotal;
}
void IndexIDMap::search (idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
index->search (n, x, k, distances, labels);
idx_t *li = labels;
#pragma omp parallel for
for (idx_t i = 0; i < n * k; i++) {
li[i] = li[i] < 0 ? li[i] : id_map[li[i]];
}
}
void IndexIDMap::range_search (idx_t n, const float *x, float radius,
RangeSearchResult *result) const
{
index->range_search(n, x, radius, result);
#pragma omp parallel for
for (idx_t i = 0; i < result->lims[result->nq]; i++) {
result->labels[i] = result->labels[i] < 0 ?
result->labels[i] : id_map[result->labels[i]];
}
}
namespace {
struct IDTranslatedSelector: IDSelector {
const std::vector <long> & id_map;
const IDSelector & sel;
IDTranslatedSelector (const std::vector <long> & id_map,
const IDSelector & sel):
id_map (id_map), sel (sel)
{}
bool is_member(idx_t id) const override {
return sel.is_member(id_map[id]);
}
};
}
long IndexIDMap::remove_ids (const IDSelector & sel)
{
// remove in sub-index first
IDTranslatedSelector sel2 (id_map, sel);
long nremove = index->remove_ids (sel2);
long j = 0;
for (idx_t i = 0; i < ntotal; i++) {
if (sel.is_member (id_map[i])) {
// remove
} else {
id_map[j] = id_map[i];
j++;
}
}
FAISS_ASSERT (j == index->ntotal);
ntotal = j;
id_map.resize(ntotal);
return nremove;
}
IndexIDMap::~IndexIDMap ()
{
if (own_fields) delete index;
}
/*****************************************************
* IndexIDMap2 implementation
*******************************************************/
IndexIDMap2::IndexIDMap2 (Index *index): IndexIDMap (index)
{}
void IndexIDMap2::add_with_ids(idx_t n, const float* x, const long* xids)
{
size_t prev_ntotal = ntotal;
IndexIDMap::add_with_ids (n, x, xids);
for (size_t i = prev_ntotal; i < ntotal; i++) {
rev_map [id_map [i]] = i;
}
}
void IndexIDMap2::construct_rev_map ()
{
rev_map.clear ();
for (size_t i = 0; i < ntotal; i++) {
rev_map [id_map [i]] = i;
}
}
long IndexIDMap2::remove_ids(const IDSelector& sel)
{
// This is quite inefficient
long nremove = IndexIDMap::remove_ids (sel);
construct_rev_map ();
return nremove;
}
void IndexIDMap2::reconstruct (idx_t key, float * recons) const
{
try {
index->reconstruct (rev_map.at (key), recons);
} catch (const std::out_of_range& e) {
FAISS_THROW_FMT ("key %ld not found", key);
}
}
/*****************************************************
* IndexShards implementation
*******************************************************/
// subroutines
namespace {
typedef Index::idx_t idx_t;
template<class Job>
struct Thread {
Job job;
pthread_t thread;
Thread () {}
explicit Thread (const Job & job): job(job) {}
void start () {
pthread_create (&thread, nullptr, run, this);
}
void wait () {
pthread_join (thread, nullptr);
}
static void * run (void *arg) {
static_cast<Thread*> (arg)->job.run();
return nullptr;
}
};
/// callback + thread management to train 1 shard
struct TrainJob {
IndexShards *index; // the relevant index
int no; // shard number
idx_t n; // train points
const float *x;
void run ()
{
if (index->verbose)
printf ("begin train shard %d on %ld points\n", no, n);
index->shard_indexes [no]->train(n, x);
if (index->verbose)
printf ("end train shard %d\n", no);
}
};
struct AddJob {
IndexShards *index; // the relevant index
int no; // shard number
idx_t n;
const float *x;
const idx_t *ids;
void run ()
{
if (index->verbose)
printf ("begin add shard %d on %ld points\n", no, n);
if (ids)
index->shard_indexes[no]->add_with_ids (n, x, ids);
else
index->shard_indexes[no]->add (n, x);
if (index->verbose)
printf ("end add shard %d on %ld points\n", no, n);
}
};
/// callback + thread management to query in 1 shard
struct QueryJob {
const IndexShards *index; // the relevant index
int no; // shard number
// query params
idx_t n;
const float *x;
idx_t k;
float *distances;
idx_t *labels;
void run ()
{
if (index->verbose)
printf ("begin query shard %d on %ld points\n", no, n);
index->shard_indexes [no]->search (n, x, k,
distances, labels);
if (index->verbose)
printf ("end query shard %d\n", no);
}
};
// add translation to all valid labels
void translate_labels (long n, idx_t *labels, long translation)
{
if (translation == 0) return;
for (long i = 0; i < n; i++) {
if(labels[i] < 0) return;
labels[i] += translation;
}
}
/** merge result tables from several shards.
* @param all_distances size nshard * n * k
* @param all_labels idem
* @param translartions label translations to apply, size nshard
*/
template <class C>
void merge_tables (long n, long k, long nshard,
float *distances, idx_t *labels,
const float *all_distances,
idx_t *all_labels,
const long *translations)
{
if(k == 0) {
return;
}
long stride = n * k;
#pragma omp parallel
{
std::vector<int> buf (2 * nshard);
int * pointer = buf.data();
int * shard_ids = pointer + nshard;
std::vector<float> buf2 (nshard);
float * heap_vals = buf2.data();
#pragma omp for
for (long i = 0; i < n; i++) {
// the heap maps values to the shard where they are
// produced.
const float *D_in = all_distances + i * k;
const idx_t *I_in = all_labels + i * k;
int heap_size = 0;
for (long s = 0; s < nshard; s++) {
pointer[s] = 0;
if (I_in[stride * s] >= 0)
heap_push<C> (++heap_size, heap_vals, shard_ids,
D_in[stride * s], s);
}
float *D = distances + i * k;
idx_t *I = labels + i * k;
for (int j = 0; j < k; j++) {
if (heap_size == 0) {
I[j] = -1;
D[j] = C::neutral();
} else {
// pop best element
int s = shard_ids[0];
int & p = pointer[s];
D[j] = heap_vals[0];
I[j] = I_in[stride * s + p] + translations[s];
heap_pop<C> (heap_size--, heap_vals, shard_ids);
p++;
if (p < k && I_in[stride * s + p] >= 0)
heap_push<C> (++heap_size, heap_vals, shard_ids,
D_in[stride * s + p], s);
}
}
}
}
}
};
IndexShards::IndexShards (idx_t d, bool threaded, bool successive_ids):
Index (d), own_fields (false),
threaded (threaded), successive_ids (successive_ids)
{
}
void IndexShards::add_shard (Index *idx)
{
shard_indexes.push_back (idx);
sync_with_shard_indexes ();
}
void IndexShards::sync_with_shard_indexes ()
{
if (shard_indexes.empty()) return;
Index * index0 = shard_indexes[0];
d = index0->d;
metric_type = index0->metric_type;
is_trained = index0->is_trained;
ntotal = index0->ntotal;
for (int i = 1; i < shard_indexes.size(); i++) {
Index * index = shard_indexes[i];
FAISS_THROW_IF_NOT (metric_type == index->metric_type);
FAISS_THROW_IF_NOT (d == index->d);
ntotal += index->ntotal;
}
}
void IndexShards::train (idx_t n, const float *x)
{
// pre-alloc because we don't want reallocs
std::vector<Thread<TrainJob > > tss (shard_indexes.size());
int nt = 0;
for (int i = 0; i < shard_indexes.size(); i++) {
if(!shard_indexes[i]->is_trained) {
TrainJob ts = {this, i, n, x};
if (threaded) {
tss[nt] = Thread<TrainJob> (ts);
tss[nt++].start();
} else {
ts.run();
}
}
}
for (int i = 0; i < nt; i++) {
tss[i].wait();
}
sync_with_shard_indexes ();
}
void IndexShards::add (idx_t n, const float *x)
{
add_with_ids (n, x, nullptr);
}
void IndexShards::add_with_ids (idx_t n, const float * x, const long *xids)
{
FAISS_THROW_IF_NOT_MSG(!(successive_ids && xids),
"It makes no sense to pass in ids and "
"request them to be shifted");
if (successive_ids) {
FAISS_THROW_IF_NOT_MSG(!xids,
"It makes no sense to pass in ids and "
"request them to be shifted");
FAISS_THROW_IF_NOT_MSG(ntotal == 0,
"when adding to IndexShards with sucessive_ids, "
"only add() in a single pass is supported");
}
long nshard = shard_indexes.size();
const long *ids = xids;
ScopeDeleter<long> del;
if (!ids && !successive_ids) {
long *aids = new long[n];
for (long i = 0; i < n; i++)
aids[i] = ntotal + i;
ids = aids;
del.set (ids);
}
std::vector<Thread<AddJob > > asa (shard_indexes.size());
int nt = 0;
for (int i = 0; i < nshard; i++) {
long i0 = i * n / nshard;
long i1 = (i + 1) * n / nshard;
AddJob as = {this, i,
i1 - i0, x + i0 * d,
ids ? ids + i0 : nullptr};
if (threaded) {
asa[nt] = Thread<AddJob>(as);
asa[nt++].start();
} else {
as.run();
}
}
for (int i = 0; i < nt; i++) {
asa[i].wait();
}
ntotal += n;
}
void IndexShards::reset ()
{
for (int i = 0; i < shard_indexes.size(); i++) {
shard_indexes[i]->reset ();
}
sync_with_shard_indexes ();
}
void IndexShards::search (
idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
long nshard = shard_indexes.size();
float *all_distances = new float [nshard * k * n];
idx_t *all_labels = new idx_t [nshard * k * n];
ScopeDeleter<float> del (all_distances);
ScopeDeleter<idx_t> del2 (all_labels);
#if 1
// pre-alloc because we don't want reallocs
std::vector<Thread<QueryJob> > qss (nshard);
for (int i = 0; i < nshard; i++) {
QueryJob qs = {
this, i, n, x, k,
all_distances + i * k * n,
all_labels + i * k * n
};
if (threaded) {
qss[i] = Thread<QueryJob> (qs);
qss[i].start();
} else {
qs.run();
}
}
if (threaded) {
for (int i = 0; i < qss.size(); i++) {
qss[i].wait();
}
}
#else
// pre-alloc because we don't want reallocs
std::vector<QueryJob> qss (nshard);
for (int i = 0; i < nshard; i++) {
QueryJob qs = {
this, i, n, x, k,
all_distances + i * k * n,
all_labels + i * k * n
};
if (threaded) {
qss[i] = qs;
} else {
qs.run();
}
}
if (threaded) {
#pragma omp parallel for
for (int i = 0; i < qss.size(); i++) {
qss[i].run();
}
}
#endif
std::vector<long> translations (nshard, 0);
if (successive_ids) {
translations[0] = 0;
for (int s = 0; s + 1 < nshard; s++)
translations [s + 1] = translations [s] +
shard_indexes [s]->ntotal;
}
if (metric_type == METRIC_L2) {
merge_tables< CMin<float, int> > (
n, k, nshard, distances, labels,
all_distances, all_labels, translations.data ());
} else {
merge_tables< CMax<float, int> > (
n, k, nshard, distances, labels,
all_distances, all_labels, translations.data ());
}
}
IndexShards::~IndexShards ()
{
if (own_fields) {
for (int s = 0; s < shard_indexes.size(); s++)
delete shard_indexes [s];
}
}
/*****************************************************
* IndexSplitVectors implementation
*******************************************************/
IndexSplitVectors::IndexSplitVectors (idx_t d, bool threaded):
Index (d), own_fields (false),
threaded (threaded), sum_d (0)
{
}
void IndexSplitVectors::add_sub_index (Index *index)
{
sub_indexes.push_back (index);
sync_with_sub_indexes ();
}
void IndexSplitVectors::sync_with_sub_indexes ()
{
if (sub_indexes.empty()) return;
Index * index0 = sub_indexes[0];
sum_d = index0->d;
metric_type = index0->metric_type;
is_trained = index0->is_trained;
ntotal = index0->ntotal;
for (int i = 1; i < sub_indexes.size(); i++) {
Index * index = sub_indexes[i];
FAISS_THROW_IF_NOT (metric_type == index->metric_type);
FAISS_THROW_IF_NOT (ntotal == index->ntotal);
sum_d += index->d;
}
}
void IndexSplitVectors::add(idx_t /*n*/, const float* /*x*/) {
FAISS_THROW_MSG("not implemented");
}
namespace {
/// callback + thread management to query in 1 shard
struct SplitQueryJob {
const IndexSplitVectors *index; // the relevant index
int no; // shard number
// query params
idx_t n;
const float *x;
idx_t k;
float *distances;
idx_t *labels;
void run ()
{
if (index->verbose)
printf ("begin query shard %d on %ld points\n", no, n);
const Index * sub_index = index->sub_indexes[no];
long sub_d = sub_index->d, d = index->d;
idx_t ofs = 0;
for (int i = 0; i < no; i++) ofs += index->sub_indexes[i]->d;
float *sub_x = new float [sub_d * n];
ScopeDeleter<float> del (sub_x);
for (idx_t i = 0; i < n; i++)
memcpy (sub_x + i * sub_d, x + ofs + i * d, sub_d * sizeof (sub_x));
sub_index->search (n, sub_x, k, distances, labels);
if (index->verbose)
printf ("end query shard %d\n", no);
}
};
}
void IndexSplitVectors::search (
idx_t n, const float *x, idx_t k,
float *distances, idx_t *labels) const
{
FAISS_THROW_IF_NOT_MSG (k == 1,
"search implemented only for k=1");
FAISS_THROW_IF_NOT_MSG (sum_d == d,
"not enough indexes compared to # dimensions");
long nshard = sub_indexes.size();
float *all_distances = new float [nshard * k * n];
idx_t *all_labels = new idx_t [nshard * k * n];
ScopeDeleter<float> del (all_distances);
ScopeDeleter<idx_t> del2 (all_labels);
// pre-alloc because we don't want reallocs
std::vector<Thread<SplitQueryJob> > qss (nshard);
for (int i = 0; i < nshard; i++) {
SplitQueryJob qs = {
this, i, n, x, k,
i == 0 ? distances : all_distances + i * k * n,
i == 0 ? labels : all_labels + i * k * n
};
if (threaded) {
qss[i] = Thread<SplitQueryJob> (qs);
qss[i].start();
} else {
qs.run();
}
}
if (threaded) {
for (int i = 0; i < qss.size(); i++) {
qss[i].wait();
}
}
long factor = 1;
for (int i = 0; i < nshard; i++) {
if (i > 0) { // results of 0 are already in the table
const float *distances_i = all_distances + i * k * n;
const idx_t *labels_i = all_labels + i * k * n;
for (long j = 0; j < n; j++) {
if (labels[j] >= 0 && labels_i[j] >= 0) {
labels[j] += labels_i[j] * factor;
distances[j] += distances_i[j];
} else {
labels[j] = -1;
distances[j] = 0.0 / 0.0;
}
}
}
factor *= sub_indexes[i]->ntotal;
}
}
void IndexSplitVectors::train(idx_t /*n*/, const float* /*x*/) {
FAISS_THROW_MSG("not implemented");
}
void IndexSplitVectors::reset ()
{
FAISS_THROW_MSG ("not implemented");
}
IndexSplitVectors::~IndexSplitVectors ()
{
if (own_fields) {
for (int s = 0; s < sub_indexes.size(); s++)
delete sub_indexes [s];
}
}
} // namespace faiss