forked from facebookresearch/faiss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OnDiskInvertedLists.cpp
674 lines (535 loc) · 17.3 KB
/
OnDiskInvertedLists.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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// -*- c++ -*-
#include <faiss/OnDiskInvertedLists.h>
#include <pthread.h>
#include <unordered_set>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <faiss/impl/FaissAssert.h>
#include <faiss/utils/utils.h>
namespace faiss {
/**********************************************
* LockLevels
**********************************************/
struct LockLevels {
/* There n times lock1(n), one lock2 and one lock3
* Invariants:
* a single thread can hold one lock1(n) for some n
* a single thread can hold lock2, if it holds lock1(n) for some n
* a single thread can hold lock3, if it holds lock1(n) for some n
* AND lock2 AND no other thread holds lock1(m) for m != n
*/
pthread_mutex_t mutex1;
pthread_cond_t level1_cv;
pthread_cond_t level2_cv;
pthread_cond_t level3_cv;
std::unordered_set<int> level1_holders; // which level1 locks are held
int n_level2; // nb threads that wait on level2
bool level3_in_use; // a threads waits on level3
bool level2_in_use;
LockLevels() {
pthread_mutex_init(&mutex1, nullptr);
pthread_cond_init(&level1_cv, nullptr);
pthread_cond_init(&level2_cv, nullptr);
pthread_cond_init(&level3_cv, nullptr);
n_level2 = 0;
level2_in_use = false;
level3_in_use = false;
}
~LockLevels() {
pthread_cond_destroy(&level1_cv);
pthread_cond_destroy(&level2_cv);
pthread_cond_destroy(&level3_cv);
pthread_mutex_destroy(&mutex1);
}
void lock_1(int no) {
pthread_mutex_lock(&mutex1);
while (level3_in_use || level1_holders.count(no) > 0) {
pthread_cond_wait(&level1_cv, &mutex1);
}
level1_holders.insert(no);
pthread_mutex_unlock(&mutex1);
}
void unlock_1(int no) {
pthread_mutex_lock(&mutex1);
assert(level1_holders.count(no) == 1);
level1_holders.erase(no);
if (level3_in_use) { // a writer is waiting
pthread_cond_signal(&level3_cv);
} else {
pthread_cond_broadcast(&level1_cv);
}
pthread_mutex_unlock(&mutex1);
}
void lock_2() {
pthread_mutex_lock(&mutex1);
n_level2 ++;
if (level3_in_use) { // tell waiting level3 that we are blocked
pthread_cond_signal(&level3_cv);
}
while (level2_in_use) {
pthread_cond_wait(&level2_cv, &mutex1);
}
level2_in_use = true;
pthread_mutex_unlock(&mutex1);
}
void unlock_2() {
pthread_mutex_lock(&mutex1);
level2_in_use = false;
n_level2 --;
pthread_cond_signal(&level2_cv);
pthread_mutex_unlock(&mutex1);
}
void lock_3() {
pthread_mutex_lock(&mutex1);
level3_in_use = true;
// wait until there are no level1 holders anymore except the
// ones that are waiting on level2 (we are holding lock2)
while (level1_holders.size() > n_level2) {
pthread_cond_wait(&level3_cv, &mutex1);
}
// don't release the lock!
}
void unlock_3() {
level3_in_use = false;
// wake up all level1_holders
pthread_cond_broadcast(&level1_cv);
pthread_mutex_unlock(&mutex1);
}
void print () {
pthread_mutex_lock(&mutex1);
printf("State: level3_in_use=%d n_level2=%d level1_holders: [", level3_in_use, n_level2);
for (int k : level1_holders) {
printf("%d ", k);
}
printf("]\n");
pthread_mutex_unlock(&mutex1);
}
};
/**********************************************
* OngoingPrefetch
**********************************************/
struct OnDiskInvertedLists::OngoingPrefetch {
struct Thread {
pthread_t pth;
OngoingPrefetch *pf;
bool one_list () {
idx_t list_no = pf->get_next_list();
if(list_no == -1) return false;
const OnDiskInvertedLists *od = pf->od;
od->locks->lock_1 (list_no);
size_t n = od->list_size (list_no);
const Index::idx_t *idx = od->get_ids (list_no);
const uint8_t *codes = od->get_codes (list_no);
int cs = 0;
for (size_t i = 0; i < n;i++) {
cs += idx[i];
}
const idx_t *codes8 = (const idx_t*)codes;
idx_t n8 = n * od->code_size / 8;
for (size_t i = 0; i < n8;i++) {
cs += codes8[i];
}
od->locks->unlock_1(list_no);
global_cs += cs & 1;
return true;
}
};
std::vector<Thread> threads;
pthread_mutex_t list_ids_mutex;
std::vector<idx_t> list_ids;
int cur_list;
// mutex for the list of tasks
pthread_mutex_t mutex;
// pretext to avoid code below to be optimized out
static int global_cs;
const OnDiskInvertedLists *od;
explicit OngoingPrefetch (const OnDiskInvertedLists *od): od (od)
{
pthread_mutex_init (&mutex, nullptr);
pthread_mutex_init (&list_ids_mutex, nullptr);
cur_list = 0;
}
static void* prefetch_list (void * arg) {
Thread *th = static_cast<Thread*>(arg);
while (th->one_list()) ;
return nullptr;
}
idx_t get_next_list () {
idx_t list_no = -1;
pthread_mutex_lock (&list_ids_mutex);
if (cur_list >= 0 && cur_list < list_ids.size()) {
list_no = list_ids[cur_list++];
}
pthread_mutex_unlock (&list_ids_mutex);
return list_no;
}
void prefetch_lists (const idx_t *list_nos, int n) {
pthread_mutex_lock (&mutex);
pthread_mutex_lock (&list_ids_mutex);
list_ids.clear ();
pthread_mutex_unlock (&list_ids_mutex);
for (auto &th: threads) {
pthread_join (th.pth, nullptr);
}
threads.resize (0);
cur_list = 0;
int nt = std::min (n, od->prefetch_nthread);
if (nt > 0) {
// prepare tasks
for (int i = 0; i < n; i++) {
idx_t list_no = list_nos[i];
if (list_no >= 0 && od->list_size(list_no) > 0) {
list_ids.push_back (list_no);
}
}
// prepare threads
threads.resize (nt);
for (Thread &th: threads) {
th.pf = this;
pthread_create (&th.pth, nullptr, prefetch_list, &th);
}
}
pthread_mutex_unlock (&mutex);
}
~OngoingPrefetch () {
pthread_mutex_lock (&mutex);
for (auto &th: threads) {
pthread_join (th.pth, nullptr);
}
pthread_mutex_unlock (&mutex);
pthread_mutex_destroy (&mutex);
pthread_mutex_destroy (&list_ids_mutex);
}
};
int OnDiskInvertedLists::OngoingPrefetch::global_cs = 0;
void OnDiskInvertedLists::prefetch_lists (const idx_t *list_nos, int n) const
{
pf->prefetch_lists (list_nos, n);
}
/**********************************************
* OnDiskInvertedLists: mmapping
**********************************************/
void OnDiskInvertedLists::do_mmap ()
{
const char *rw_flags = read_only ? "r" : "r+";
int prot = read_only ? PROT_READ : PROT_WRITE | PROT_READ;
FILE *f = fopen (filename.c_str(), rw_flags);
FAISS_THROW_IF_NOT_FMT (f, "could not open %s in mode %s: %s",
filename.c_str(), rw_flags, strerror(errno));
uint8_t * ptro = (uint8_t*)mmap (nullptr, totsize,
prot, MAP_SHARED, fileno (f), 0);
FAISS_THROW_IF_NOT_FMT (ptro != MAP_FAILED,
"could not mmap %s: %s",
filename.c_str(),
strerror(errno));
ptr = ptro;
fclose (f);
}
void OnDiskInvertedLists::update_totsize (size_t new_size)
{
// unmap file
if (ptr != nullptr) {
int err = munmap (ptr, totsize);
FAISS_THROW_IF_NOT_FMT (err == 0, "munmap error: %s",
strerror(errno));
}
if (totsize == 0) {
// must create file before truncating it
FILE *f = fopen (filename.c_str(), "w");
FAISS_THROW_IF_NOT_FMT (f, "could not open %s in mode W: %s",
filename.c_str(), strerror(errno));
fclose (f);
}
if (new_size > totsize) {
if (!slots.empty() &&
slots.back().offset + slots.back().capacity == totsize) {
slots.back().capacity += new_size - totsize;
} else {
slots.push_back (Slot(totsize, new_size - totsize));
}
} else {
assert(!"not implemented");
}
totsize = new_size;
// create file
printf ("resizing %s to %ld bytes\n", filename.c_str(), totsize);
int err = truncate (filename.c_str(), totsize);
FAISS_THROW_IF_NOT_FMT (err == 0, "truncate %s to %ld: %s",
filename.c_str(), totsize,
strerror(errno));
do_mmap ();
}
/**********************************************
* OnDiskInvertedLists
**********************************************/
#define INVALID_OFFSET (size_t)(-1)
OnDiskInvertedLists::List::List ():
size (0), capacity (0), offset (INVALID_OFFSET)
{}
OnDiskInvertedLists::Slot::Slot (size_t offset, size_t capacity):
offset (offset), capacity (capacity)
{}
OnDiskInvertedLists::Slot::Slot ():
offset (0), capacity (0)
{}
OnDiskInvertedLists::OnDiskInvertedLists (
size_t nlist, size_t code_size,
const char *filename):
InvertedLists (nlist, code_size),
filename (filename),
totsize (0),
ptr (nullptr),
read_only (false),
locks (new LockLevels ()),
pf (new OngoingPrefetch (this)),
prefetch_nthread (32)
{
lists.resize (nlist);
// slots starts empty
}
OnDiskInvertedLists::OnDiskInvertedLists ():
OnDiskInvertedLists (0, 0, "")
{
}
OnDiskInvertedLists::~OnDiskInvertedLists ()
{
delete pf;
// unmap all lists
if (ptr != nullptr) {
int err = munmap (ptr, totsize);
if (err != 0) {
fprintf(stderr, "mumap error: %s",
strerror(errno));
}
}
delete locks;
}
size_t OnDiskInvertedLists::list_size(size_t list_no) const
{
return lists[list_no].size;
}
const uint8_t * OnDiskInvertedLists::get_codes (size_t list_no) const
{
if (lists[list_no].offset == INVALID_OFFSET) {
return nullptr;
}
return ptr + lists[list_no].offset;
}
const Index::idx_t * OnDiskInvertedLists::get_ids (size_t list_no) const
{
if (lists[list_no].offset == INVALID_OFFSET) {
return nullptr;
}
return (const idx_t*)(ptr + lists[list_no].offset +
code_size * lists[list_no].capacity);
}
void OnDiskInvertedLists::update_entries (
size_t list_no, size_t offset, size_t n_entry,
const idx_t *ids_in, const uint8_t *codes_in)
{
FAISS_THROW_IF_NOT (!read_only);
if (n_entry == 0) return;
const List & l = lists[list_no];
assert (n_entry + offset <= l.size);
idx_t *ids = const_cast<idx_t*>(get_ids (list_no));
memcpy (ids + offset, ids_in, sizeof(ids_in[0]) * n_entry);
uint8_t *codes = const_cast<uint8_t*>(get_codes (list_no));
memcpy (codes + offset * code_size, codes_in, code_size * n_entry);
}
size_t OnDiskInvertedLists::add_entries (
size_t list_no, size_t n_entry,
const idx_t* ids, const uint8_t *code)
{
FAISS_THROW_IF_NOT (!read_only);
locks->lock_1 (list_no);
size_t o = list_size (list_no);
resize_locked (list_no, n_entry + o);
update_entries (list_no, o, n_entry, ids, code);
locks->unlock_1 (list_no);
return o;
}
void OnDiskInvertedLists::resize (size_t list_no, size_t new_size)
{
FAISS_THROW_IF_NOT (!read_only);
locks->lock_1 (list_no);
resize_locked (list_no, new_size);
locks->unlock_1 (list_no);
}
void OnDiskInvertedLists::resize_locked (size_t list_no, size_t new_size)
{
List & l = lists[list_no];
if (new_size <= l.capacity &&
new_size > l.capacity / 2) {
l.size = new_size;
return;
}
// otherwise we release the current slot, and find a new one
locks->lock_2 ();
free_slot (l.offset, l.capacity);
List new_l;
if (new_size == 0) {
new_l = List();
} else {
new_l.size = new_size;
new_l.capacity = 1;
while (new_l.capacity < new_size) {
new_l.capacity *= 2;
}
new_l.offset = allocate_slot (
new_l.capacity * (sizeof(idx_t) + code_size));
}
// copy common data
if (l.offset != new_l.offset) {
size_t n = std::min (new_size, l.size);
if (n > 0) {
memcpy (ptr + new_l.offset, get_codes(list_no), n * code_size);
memcpy (ptr + new_l.offset + new_l.capacity * code_size,
get_ids (list_no), n * sizeof(idx_t));
}
}
lists[list_no] = new_l;
locks->unlock_2 ();
}
size_t OnDiskInvertedLists::allocate_slot (size_t capacity) {
// should hold lock2
auto it = slots.begin();
while (it != slots.end() && it->capacity < capacity) {
it++;
}
if (it == slots.end()) {
// not enough capacity
size_t new_size = totsize == 0 ? 32 : totsize * 2;
while (new_size - totsize < capacity)
new_size *= 2;
locks->lock_3 ();
update_totsize(new_size);
locks->unlock_3 ();
it = slots.begin();
while (it != slots.end() && it->capacity < capacity) {
it++;
}
assert (it != slots.end());
}
size_t o = it->offset;
if (it->capacity == capacity) {
slots.erase (it);
} else {
// take from beginning of slot
it->capacity -= capacity;
it->offset += capacity;
}
return o;
}
void OnDiskInvertedLists::free_slot (size_t offset, size_t capacity) {
// should hold lock2
if (capacity == 0) return;
auto it = slots.begin();
while (it != slots.end() && it->offset <= offset) {
it++;
}
size_t inf = 1UL << 60;
size_t end_prev = inf;
if (it != slots.begin()) {
auto prev = it;
prev--;
end_prev = prev->offset + prev->capacity;
}
size_t begin_next = 1L << 60;
if (it != slots.end()) {
begin_next = it->offset;
}
assert (end_prev == inf || offset >= end_prev);
assert (offset + capacity <= begin_next);
if (offset == end_prev) {
auto prev = it;
prev--;
if (offset + capacity == begin_next) {
prev->capacity += capacity + it->capacity;
slots.erase (it);
} else {
prev->capacity += capacity;
}
} else {
if (offset + capacity == begin_next) {
it->offset -= capacity;
it->capacity += capacity;
} else {
slots.insert (it, Slot (offset, capacity));
}
}
// TODO shrink global storage if needed
}
/*****************************************
* Compact form
*****************************************/
size_t OnDiskInvertedLists::merge_from (const InvertedLists **ils, int n_il,
bool verbose)
{
FAISS_THROW_IF_NOT_MSG (totsize == 0, "works only on an empty InvertedLists");
std::vector<size_t> sizes (nlist);
for (int i = 0; i < n_il; i++) {
const InvertedLists *il = ils[i];
FAISS_THROW_IF_NOT (il->nlist == nlist && il->code_size == code_size);
for (size_t j = 0; j < nlist; j++) {
sizes [j] += il->list_size(j);
}
}
size_t cums = 0;
size_t ntotal = 0;
for (size_t j = 0; j < nlist; j++) {
ntotal += sizes[j];
lists[j].size = 0;
lists[j].capacity = sizes[j];
lists[j].offset = cums;
cums += lists[j].capacity * (sizeof(idx_t) + code_size);
}
update_totsize (cums);
size_t nmerged = 0;
double t0 = getmillisecs(), last_t = t0;
#pragma omp parallel for
for (size_t j = 0; j < nlist; j++) {
List & l = lists[j];
for (int i = 0; i < n_il; i++) {
const InvertedLists *il = ils[i];
size_t n_entry = il->list_size(j);
l.size += n_entry;
update_entries (j, l.size - n_entry, n_entry,
ScopedIds(il, j).get(),
ScopedCodes(il, j).get());
}
assert (l.size == l.capacity);
if (verbose) {
#pragma omp critical
{
nmerged++;
double t1 = getmillisecs();
if (t1 - last_t > 500) {
printf("merged %ld lists in %.3f s\r",
nmerged, (t1 - t0) / 1000.0);
fflush(stdout);
last_t = t1;
}
}
}
}
if(verbose) {
printf("\n");
}
return ntotal;
}
void OnDiskInvertedLists::crop_invlists(size_t l0, size_t l1)
{
FAISS_THROW_IF_NOT(0 <= l0 && l0 <= l1 && l1 <= nlist);
std::vector<List> new_lists (l1 - l0);
memcpy (new_lists.data(), &lists[l0], (l1 - l0) * sizeof(List));
lists.swap(new_lists);
nlist = l1 - l0;
}
} // namespace faiss