{{ message }}
Repository navigation
Expand file tree
/
Copy pathutils.h
More file actions
539 lines (466 loc) · 18.7 KB
/
Copy pathutils.h
File metadata and controls
539 lines (466 loc) · 18.7 KB
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
#pragma once
#include <fcntl.h>
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <string>
#include <memory>
#include <random>
#include <set>
#include <sstream>
#include <stdexcept>
#include <type_traits>
#include <vector>
#include <malloc.h>
#include <unistd.h>
#include <sys/stat.h>
#include <omp.h>
#include "utils/arch_compat.h"
#include "utils/log.h"
/*
* Necessary definitions and
* functions used both by both in-memory and on-disk index.
* Avoid including other headers in this project!
*/
constexpr uint64_t SECTOR_LEN = 4096;
#define ROUND_UP(X, Y) ((((uint64_t) (X) / (Y)) + ((uint64_t) (X) % (Y) != 0)) * (Y))
#define DIV_ROUND_UP(X, Y) (((uint64_t) (X) / (Y)) + ((uint64_t) (X) % (Y) != 0))
#ifndef likely
#define likely(x) __builtin_expect(!!(x), 1)
#endif
#ifndef unlikely
#define unlikely(x) __builtin_expect(!!(x), 0)
#endif
/* Used to replace exception. */
inline void crash() {
// #ifndef NDEBUG
__builtin_trap();
// #endif
}
static inline bool file_exists(const std::string &name, bool dirCheck = false) {
int val;
struct stat buffer;
val = stat(name.c_str(), &buffer);
DLOG(INFO) << " Stat(" << name.c_str() << ") returned: " << val;
if (val != 0) {
switch (errno) {
case EINVAL:
DLOG(INFO) << "Invalid argument passed to stat()";
break;
case ENOENT:
DLOG(INFO) << "File " << name.c_str() << " does not exist";
break;
default:
DLOG(INFO) << "Unexpected error in stat():" << errno;
break;
}
return false;
} else {
// the file entry exists. If reqd, check if this is a directory.
return dirCheck ? buffer.st_mode & S_IFDIR : true;
}
}
inline void open_file_to_write(std::ofstream &writer, const std::string &filename) {
writer.exceptions(std::ofstream::failbit | std::ofstream::badbit);
if (!file_exists(filename))
writer.open(filename, std::ios::binary | std::ios::out);
else
writer.open(filename, std::ios::binary | std::ios::in | std::ios::out);
if (writer.fail()) {
LOG(ERROR) << std::string("Failed to open file") + filename + " for write because " << std::strerror(errno);
crash();
}
}
inline uint64_t get_file_size(const std::string &fname) {
std::ifstream reader(fname, std::ios::binary | std::ios::ate);
if (!reader.fail() && reader.is_open()) {
uint64_t end_pos = reader.tellg();
reader.close();
return end_pos;
} else {
LOG(ERROR) << "Could not open file: " << fname;
return 0;
}
}
inline int delete_file(const std::string &fileName) {
if (file_exists(fileName)) {
auto rc = ::remove(fileName.c_str());
if (rc != 0) {
LOG(ERROR) << "Could not delete file: " << fileName
<< " even though it exists. This might indicate a permissions issue. "
"If you see this message, please contact the pipeann team.";
}
return rc;
} else {
return 0;
}
}
namespace pipeann {
enum Metric { L2 = 0, INNER_PRODUCT = 1, COSINE = 2 };
enum FilterType : int { PRE_FILTER = 0, IN_FILTER = 1, POST_FILTER = 2, N_FILTER_TYPES = 3 };
// Predicate that accepts everything, whatever the argument list. Serves as the
// default readiness predicate for synchronous CandidatePool callers (they
// never consult it, so the return value is a don't-care) and, in the search
// entry points, as the no-op membership/verification predicate for unfiltered
// search. Variadic so one type covers both the (id) and (id, node) call shapes.
struct AlwaysTrue {
template<class... Args>
constexpr bool operator()(const Args &...) const noexcept {
return true;
}
};
inline void alloc_aligned(void **ptr, size_t size, size_t align) {
std::ignore = posix_memalign(ptr, align, size);
// *ptr = nullptr;
// assert(IS_ALIGNED(size, align));
// *ptr = ::aligned_alloc(align, size);
// assert(*ptr != nullptr);
}
inline void aligned_free(void *ptr) {
if (ptr == nullptr) {
return;
}
free(ptr);
}
inline void get_bin_metadata(const std::string &bin_file, size_t &nrows, size_t &ncols, size_t offset = 0) {
std::ifstream reader(bin_file.c_str(), std::ios::binary);
int nrows_32, ncols_32;
reader.seekg(offset, reader.beg);
reader.read((char *) &nrows_32, sizeof(int));
reader.read((char *) &ncols_32, sizeof(int));
nrows = nrows_32;
ncols = ncols_32;
}
template<typename T>
inline void load_bin_impl(std::basic_istream<char> &reader, T *&data, size_t &npts, size_t &dim,
size_t file_offset = 0) {
int npts_i32, dim_i32;
reader.seekg(file_offset, reader.beg);
reader.read((char *) &npts_i32, sizeof(int));
reader.read((char *) &dim_i32, sizeof(int));
npts = (unsigned) npts_i32;
dim = (unsigned) dim_i32;
DLOG(INFO) << "Metadata: #pts = " << npts << ", #dims = " << dim << "...";
data = new T[npts * dim];
reader.read((char *) data, npts * dim * sizeof(T));
}
// FileT defaults to the vector element type. An explicit FileT also allows
// typed records to be read directly into a byte vector, without conversion.
template<typename FileT = void, typename T, typename Allocator>
inline void load_bin_impl(std::basic_istream<char> &reader, std::vector<T, Allocator> &data, size_t &npts, size_t &dim,
size_t file_offset = 0) {
using ElementT = std::conditional_t<std::is_void_v<FileT>, T, FileT>;
static_assert(std::is_same_v<T, ElementT> || std::is_same_v<T, uint8_t>);
uint32_t npts_i32 = 0, dim_i32 = 0;
reader.seekg(file_offset, reader.beg);
reader.read((char *) &npts_i32, sizeof(int));
reader.read((char *) &dim_i32, sizeof(int));
if (!reader) throw std::runtime_error("Cannot read bin header");
npts = (unsigned) npts_i32;
dim = (unsigned) dim_i32;
DLOG(INFO) << "Metadata: #pts = " << npts << ", #dims = " << dim << "...";
const size_t bytes = npts * dim * sizeof(ElementT);
data.resize(bytes / sizeof(T));
reader.read(reinterpret_cast<char *>(data.data()), bytes);
if (!reader) throw std::runtime_error("Truncated bin file");
}
template<typename T>
inline void load_bin(const std::string &bin_file, T *&data, size_t &npts, size_t &dim, size_t offset = 0) {
DLOG(INFO) << "Reading bin file " << bin_file.c_str() << " ...";
std::ifstream reader(bin_file, std::ios::binary | std::ios::ate);
reader.seekg(0);
load_bin_impl<T>(reader, data, npts, dim, offset);
}
template<typename FileT = void, typename T, typename Allocator>
inline void load_bin(const std::string &bin_file, std::vector<T, Allocator> &data, size_t &npts, size_t &dim,
size_t offset = 0) {
DLOG(INFO) << "Reading bin file " << bin_file.c_str() << " ...";
std::ifstream reader(bin_file, std::ios::binary | std::ios::ate);
reader.seekg(0);
load_bin_impl<FileT>(reader, data, npts, dim, offset);
}
inline void load_truthset(const std::string &bin_file, uint32_t *&ids, float *&dists, size_t &npts, size_t &dim,
uint32_t **tags = nullptr) {
std::ifstream reader(bin_file, std::ios::binary);
DLOG(INFO) << "Reading truthset file " << bin_file.c_str() << "...";
size_t actual_file_size = get_file_size(bin_file);
int npts_i32, dim_i32;
reader.read((char *) &npts_i32, sizeof(int));
reader.read((char *) &dim_i32, sizeof(int));
npts = (unsigned) npts_i32;
dim = (unsigned) dim_i32;
DLOG(INFO) << "Metadata: #pts = " << npts << ", #dims = " << dim << "...";
int truthset_type = -1; // 1 means truthset has ids and distances, 2 means
// only ids, -1 is error
size_t expected_file_size_with_dists = 2 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
if (actual_file_size == expected_file_size_with_dists)
truthset_type = 1;
size_t expected_file_size_just_ids = npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
size_t with_tags_actual_file_size = 3 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t);
if (actual_file_size == expected_file_size_just_ids)
truthset_type = 2;
if (actual_file_size == with_tags_actual_file_size)
truthset_type = 3;
if (truthset_type == -1) {
std::stringstream stream;
stream << "Error. File size mismatch. File should have bin format, with "
"npts followed by ngt followed by npts*ngt ids and optionally "
"followed by npts*ngt distance values; actual size: "
<< actual_file_size << ", expected: " << expected_file_size_with_dists << " or "
<< expected_file_size_just_ids;
LOG(INFO) << stream.str();
crash();
}
ids = new uint32_t[npts * dim];
reader.read((char *) ids, npts * dim * sizeof(uint32_t));
if ((truthset_type == 1) || (truthset_type == 3)) {
dists = new float[npts * dim];
reader.read((char *) dists, npts * dim * sizeof(float));
}
if (truthset_type == 3 && tags != nullptr) {
*tags = new uint32_t[npts * dim];
reader.read((char *) *tags, npts * dim * sizeof(uint32_t));
}
}
template<typename T>
inline void load_bin(const std::string &bin_file, std::unique_ptr<T[]> &data, size_t &npts, size_t &dim,
size_t offset = 0) {
T *ptr;
load_bin<T>(bin_file, ptr, npts, dim, offset);
data.reset(ptr);
}
template<typename T>
inline uint64_t save_bin(const std::string &filename, T *data, size_t npts, size_t ndims, size_t offset = 0) {
std::ofstream writer;
open_file_to_write(writer, filename);
DLOG(INFO) << "Writing bin: " << filename.c_str();
writer.seekp(offset, writer.beg);
int npts_i32 = (int) npts, ndims_i32 = (int) ndims;
size_t bytes_written = npts * ndims * sizeof(T) + 2 * sizeof(uint32_t);
writer.write((char *) &npts_i32, sizeof(int));
writer.write((char *) &ndims_i32, sizeof(int));
DLOG(INFO) << "bin: #pts = " << npts << ", #dims = " << ndims << ", size = " << bytes_written << "B";
writer.write((char *) data, npts * ndims * sizeof(T));
writer.close();
DLOG(INFO) << "Finished writing bin.";
return bytes_written;
}
template<typename InType, typename OutType>
void convert_types(const InType *srcmat, OutType *destmat, size_t npts, size_t dim) {
#pragma omp parallel for schedule(static, 65536)
for (int64_t i = 0; i < (int64_t) npts; i++) {
for (uint64_t j = 0; j < dim; j++) {
destmat[i * dim + j] = (OutType) srcmat[i * dim + j];
}
}
}
// Include a partial final block (e.g. a 128-byte code plus its 16-byte header).
inline void prefetch_vector(const char *vec, size_t vecsize) {
for (size_t d = 0; d < vecsize; d += 64)
pipeann::cpu_prefetch_t0((const char *) vec + d);
}
inline double calculate_recall(unsigned num_queries, unsigned *gold_std, float *gs_dist, unsigned dim_gs,
unsigned *our_results, unsigned dim_or, unsigned recall_at) {
double total_recall = 0;
std::set<unsigned> gt, res;
for (size_t i = 0; i < num_queries; i++) {
gt.clear();
res.clear();
unsigned *gt_vec = gold_std + dim_gs * i;
unsigned *res_vec = our_results + dim_or * i;
size_t tie_breaker = recall_at;
if (gs_dist != nullptr) {
float *gt_dist_vec = gs_dist + dim_gs * i;
tie_breaker = recall_at - 1;
while (tie_breaker < dim_gs && gt_dist_vec[tie_breaker] == gt_dist_vec[recall_at - 1])
tie_breaker++;
}
gt.insert(gt_vec, gt_vec + tie_breaker);
res.insert(res_vec, res_vec + recall_at);
unsigned cur_recall = 0;
for (auto &v : res) {
if (gt.find(v) != gt.end()) {
cur_recall++;
}
}
total_recall += cur_recall;
}
return total_recall / (num_queries) * (100.0 / recall_at);
}
struct PiPNNConfig {
int cmax = 2048;
int cmin = 256;
float p_samp = 0.01f;
int pmax = 1000;
int first_layer_fanout = 6;
int second_layer_fanout = 10;
int k = 2; // k-NN in leaf build
int climit = 128;
uint32_t seed = 42;
void print() {
LOG(INFO) << "PiPNNConfig: cmax=" << cmax << " cmin=" << cmin << " p_samp=" << p_samp << " pmax=" << pmax
<< " first_layer_fanout=" << first_layer_fanout << " second_layer_fanout=" << second_layer_fanout
<< " k=" << k << " climit=" << climit << " seed=" << seed;
}
};
/* Index parameters: graph build + runtime config. */
struct IndexBuildParameters {
uint32_t R = 0; // maximum out-neighbors (0 means auto-configure).
uint32_t L = 0; // build L (0 means auto-configure).
uint32_t C = 384; // delete pruning capacity.
float alpha = 1.2f; // alpha for Vamana.
uint32_t num_threads = 0; // num_threads used for build (0 uses all available threads).
bool saturate_graph = true; // saturate graph during build (using kNN neighbors).
uint32_t beam_width = 8; // insert beam width. (for SSD)
bool use_pipnn = false;
PiPNNConfig pipnn_config;
// By default, we assume a maximum parallelism of 128.
uint32_t max_nthreads = 128; // max threads for SSD I/O buffer allocation.
uint32_t sampled_nbrs_for_delete = 20; // neighbors sampled during merge.
void set(uint32_t R, uint32_t L, uint32_t C, float alpha = 1.2, uint32_t num_threads = 0,
bool saturate_graph = true, uint32_t beam_width = 8) {
this->R = R;
this->L = L;
this->C = C;
this->alpha = alpha;
this->num_threads = num_threads;
this->beam_width = beam_width;
this->saturate_graph = saturate_graph;
}
void pipnn_set(int cmax, int cmin, float p_samp, int pmax, int first_layer_fanout, int second_layer_fanout, int k,
int climit, uint32_t seed = 42) {
this->pipnn_config = {cmax, cmin, p_samp, pmax, first_layer_fanout, second_layer_fanout, k,
climit, seed};
}
void print() {
LOG(INFO) << "IndexBuildParameters with L: " << (L == 0 ? "auto" : std::to_string(L))
<< " R: " << (R == 0 ? "auto" : std::to_string(R)) << " C: " << C << " alpha: " << alpha
<< " num_threads: " << (num_threads == 0 ? "auto" : std::to_string(num_threads))
<< " beam_width: " << beam_width << " saturate_graph: " << saturate_graph
<< " max_nthreads: " << max_nthreads;
if (use_pipnn) {
pipnn_config.print();
}
}
};
/* Graph neighbor-related definitions. */
struct Neighbor {
unsigned id;
float distance;
bool flag;
bool visited;
bool is_member; // Accurate, to check if early stop.
Neighbor() = default;
Neighbor(unsigned id, float distance) : id{id}, distance{distance}, flag(true), visited(false), is_member(false) {
}
inline bool operator<(const Neighbor &other) const {
return (distance < other.distance) || (distance == other.distance && id < other.id);
}
inline bool operator==(const Neighbor &other) const {
return (id == other.id);
}
inline bool operator>(const Neighbor &other) const {
return (distance > other.distance) || (distance == other.distance && id > other.id);
}
inline bool operator>=(const Neighbor &other) const {
return (distance > other.distance) || (distance == other.distance && id >= other.id);
}
};
// Squared normalization scale used by internal IP/cosine distances and their conversions.
template<typename T>
constexpr float metric_scale() {
if constexpr (std::is_same_v<T, uint8_t>)
return 255.0f * 255.0f;
if constexpr (std::is_same_v<T, int8_t>)
return 127.0f * 127.0f;
return 1.0f;
}
// Convert the distance calculated by Distance<T>, to actual distance.
template<typename T>
inline float get_actual_distance(float distance, Metric m) {
if constexpr (!std::is_same_v<T, float> && !std::is_same_v<T, int8_t> && !std::is_same_v<T, uint8_t>) {
LOG(ERROR) << "Unsupported type: " << typeid(T).name();
return distance;
}
constexpr float A_2 = metric_scale<T>();
if (m == Metric::L2) {
return std::sqrt(distance);
} else if (m == Metric::COSINE) {
// distance = A^2 * (1 - cosine(theta))
return 1 - (distance / A_2);
} else if (m == Metric::INNER_PRODUCT) {
return A_2 - distance;
}
LOG(ERROR) << "Unsupported metric: " << m << " and type: " << typeid(T).name();
return distance;
}
// Inverse of get_actual_distance: convert a user-facing range threshold into
// the partial-order distance used internally by Distance<T>::compare().
template<typename T>
inline float get_partial_order_distance(float range, Metric m) {
if constexpr (!std::is_same_v<T, float> && !std::is_same_v<T, int8_t> && !std::is_same_v<T, uint8_t>) {
LOG(ERROR) << "Unsupported type: " << typeid(T).name();
return range;
}
constexpr float A_2 = metric_scale<T>();
if (m == Metric::L2) {
return range * range;
} else if (m == Metric::COSINE) {
return A_2 * (1.0f - range);
} else if (m == Metric::INNER_PRODUCT) {
return A_2 - range;
}
LOG(ERROR) << "Unsupported metric: " << m << " and type: " << typeid(T).name();
return range;
}
/*
* For float, we normalize to 1.
* For non-float types, we do not normalize to 1 to avoid underflow.
* Instead, we normalize to TYPE_MAX:
* - For uint8_t, we normalize to 255.
* - For int8_t, we normalize to 127.
*/
template<typename T>
inline void normalize_data(T *data_out, const T *data_in, size_t dim) {
float norm_sq = 0.0f;
#pragma omp simd reduction(+ : norm_sq) aligned(data_in : 8)
for (size_t i = 0; i < dim; i++) {
norm_sq += (float) (data_in[i]) * (float) (data_in[i]);
}
if (unlikely(norm_sq < FLT_EPSILON)) {
memset(data_out, 0, dim * sizeof(T));
return;
}
float norm = std::sqrt(norm_sq);
float scale = 1.0f;
if constexpr (std::is_same_v<T, uint8_t>) {
scale = 255.0f / norm;
} else if constexpr (std::is_same_v<T, int8_t>) {
scale = 127.0f / norm;
} else if constexpr (std::is_same_v<T, float>) {
scale = 1.0f / norm;
} else {
LOG(ERROR) << "Unsupported type: " << typeid(T).name();
crash();
}
// Round up for integer types.
#pragma omp simd aligned(data_out, data_in : 8)
for (size_t i = 0; i < dim; i++) {
float val = (float) data_in[i] * scale;
if constexpr (std::is_same_v<T, float>) {
data_out[i] = val;
} else {
data_out[i] = static_cast<T>(std::round(val));
}
}
}
// We reserve kInvalidID to mark an invalid ID or location.
static constexpr uint32_t kInvalidID = std::numeric_limits<uint32_t>::max();
} // namespace pipeann
You can’t perform that action at this time.
