forked from facebookresearch/faiss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DirectMap.h
120 lines (81 loc) · 2.6 KB
/
DirectMap.h
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
/**
* 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++ -*-
#ifndef FAISS_DIRECT_MAP_H
#define FAISS_DIRECT_MAP_H
#include <faiss/InvertedLists.h>
#include <unordered_map>
namespace faiss {
// When offsets list id + offset are encoded in an uint64
// we call this LO = list-offset
inline uint64_t lo_build (uint64_t list_id, uint64_t offset) {
return list_id << 32 | offset;
}
inline uint64_t lo_listno (uint64_t lo) {
return lo >> 32;
}
inline uint64_t lo_offset (uint64_t lo) {
return lo & 0xffffffff;
}
/**
* Direct map: a way to map back from ids to inverted lists
*/
struct DirectMap {
typedef Index::idx_t idx_t;
enum Type {
NoMap = 0, // default
Array = 1, // sequential ids (only for add, no add_with_ids)
Hashtable = 2 // arbitrary ids
};
Type type;
/// map for direct access to the elements. Map ids to LO-encoded entries.
std::vector <idx_t> array;
std::unordered_map <idx_t, idx_t> hashtable;
DirectMap();
/// set type and initialize
void set_type (Type new_type, const InvertedLists *invlists, size_t ntotal);
/// get an entry
idx_t get (idx_t id) const;
/// for quick checks
bool no () const {return type == NoMap; }
/**
* update the direct_map
*/
/// throw if Array and ids is not NULL
void check_can_add (const idx_t *ids);
/// non thread-safe version
void add_single_id (idx_t id, idx_t list_no, size_t offset);
/// remove all entries
void clear();
/**
* operations on inverted lists that require translation with a DirectMap
*/
/// remove ids from the InvertedLists, possibly using the direct map
size_t remove_ids(const IDSelector& sel, InvertedLists *invlists);
/// update entries, using the direct map
void update_codes (InvertedLists *invlists,
int n, const idx_t *ids,
const idx_t *list_nos,
const uint8_t *codes);
};
/// Thread-safe way of updating the direct_map
struct DirectMapAdd {
typedef Index::idx_t idx_t;
using Type = DirectMap::Type;
DirectMap &direct_map;
DirectMap::Type type;
size_t ntotal;
size_t n;
const idx_t *xids;
std::vector<idx_t> all_ofs;
DirectMapAdd (DirectMap &direct_map, size_t n, const idx_t *xids);
/// add vector i (with id xids[i]) at list_no and offset
void add (size_t i, idx_t list_no, size_t offset);
~DirectMapAdd ();
};
}
#endif