-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathkgraph-data.h
370 lines (340 loc) · 12.1 KB
/
kgraph-data.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
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
#ifndef WDONG_KGRAPH_DATA
#define WDONG_KGRAPH_DATA
#include <cmath>
#include <cstring>
#include <malloc.h>
#include <vector>
#include <fstream>
#include <stdexcept>
#include <boost/assert.hpp>
#include <xsimd/xsimd.hpp>
namespace kgraph {
typedef xsimd::best_arch xsimd_arch;
static constexpr size_t KGRAPH_MATRIX_ALIGN = xsimd_arch::alignment();
template <typename T>
T simd_l2sqr (T const *t1, unsigned dim) {
}
template <typename T>
T simd_dot (T const *t1, T const *t2, unsigned dim) {
}
}
namespace kgraph {
using std::vector;
/// namespace for various distance metrics.
namespace metric {
/// L2 square distance.
struct l2sqr {
template <typename T>
/// L2 square distance.
static T apply (T const *t1, T const *t2, unsigned size) {
using b_type = xsimd::batch<T, xsimd_arch>;
unsigned constexpr inc = b_type::size;
unsigned vec_size = size - size % inc;
unsigned i = 0;
b_type c = 0;
for (; i < vec_size; i += inc) {
b_type a = b_type::load_aligned(t1 + i);
b_type b = b_type::load_aligned(t2 + i);
a -= b;
c += a * a;
}
T acc = xsimd::reduce_add(c);
for (; i < size; ++i) {
T a = t1[i];
T b = t2[i];
a -= b;
acc += a * a;
}
return acc;
}
/// inner product.
template <typename T>
static T dot (T const *t1, T const *t2, unsigned size) {
using b_type = xsimd::batch<T, xsimd_arch>;
unsigned constexpr inc = b_type::size;
unsigned vec_size = size - size % inc;
unsigned i = 0;
b_type c = 0;
for (; i < vec_size; i += inc) {
b_type a = b_type::load_aligned(t1 + i);
b_type b = b_type::load_aligned(t2 + i);
c += a * b;
}
T acc = xsimd::reduce_add(c);
for (; i < size; ++i) {
T a = t1[i];
T b = t2[i];
acc += a * b;
}
return acc;
}
/// L2 norm.
template <typename T>
static float norm2 (T const *t1, unsigned size) {
using b_type = xsimd::batch<T, xsimd_arch>;
unsigned constexpr inc = b_type::size;
unsigned vec_size = size - size % inc;
unsigned i = 0;
b_type c = 0;
for (; i < vec_size; i += inc) {
b_type a = b_type::load_aligned(t1 + i);
c += a * a;
}
T acc = xsimd::reduce_add(c);
for (; i < size; ++i) {
T a = t1[i];
acc += a * a;
}
return acc;
}
};
struct l2 {
template <typename T>
static T apply (T const *t1, T const *t2, unsigned dim) {
return std::sqrt(l2sqr::apply<T>(t1, t2, dim));
}
};
}
/// Matrix data.
template <typename T, unsigned A = KGRAPH_MATRIX_ALIGN>
class Matrix {
unsigned col;
unsigned row;
size_t stride;
char *data;
protected:
void reset (unsigned r, unsigned c) {
row = r;
col = c;
stride = (sizeof(T) * c + A - 1) / A * A;
/*
data.resize(row * stride);
*/
if (data) free(data);
data = (char *)memalign(A, row * stride); // SSE instruction needs data to be aligned
if (!data) throw runtime_error("memalign");
}
public:
Matrix (): col(0), row(0), stride(0), data(0) {}
Matrix (unsigned r, unsigned c): data(0) {
reset(r, c);
}
~Matrix () {
if (data) free(data);
}
unsigned size () const {
return row;
}
unsigned dim () const {
return col;
}
size_t step () const {
return stride;
}
void resize (unsigned r, unsigned c) {
reset(r, c);
}
T const *operator [] (unsigned i) const {
return reinterpret_cast<T const *>(&data[stride * i]);
}
T *operator [] (unsigned i) {
return reinterpret_cast<T *>(&data[stride * i]);
}
void zero () {
memset(data, 0, row * stride);
}
void normalize2 () {
#pragma omp parallel for
for (unsigned i = 0; i < row; ++i) {
T *p = operator[](i);
double sum = metric::l2sqr::norm2(p, col);
sum = std::sqrt(sum);
for (unsigned j = 0; j < col; ++j) {
p[j] /= sum;
}
}
}
void load (const std::string &path, unsigned dim, unsigned skip = 0, unsigned gap = 0) {
std::ifstream is(path.c_str(), std::ios::binary);
if (!is) throw io_error(path);
is.seekg(0, std::ios::end);
size_t size = is.tellg();
size -= skip;
unsigned line = sizeof(T) * dim + gap;
unsigned N = size / line;
reset(N, dim);
zero();
is.seekg(skip, std::ios::beg);
for (unsigned i = 0; i < N; ++i) {
is.read(&data[stride * i], sizeof(T) * dim);
is.seekg(gap, std::ios::cur);
}
if (!is) throw io_error(path);
}
void load_lshkit (std::string const &path) {
static const unsigned LSHKIT_HEADER = 3;
std::ifstream is(path.c_str(), std::ios::binary);
unsigned header[LSHKIT_HEADER]; /* entry size, row, col */
is.read((char *)header, sizeof header);
if (!is) throw io_error(path);
if (header[0] != sizeof(T)) throw io_error(path);
is.close();
unsigned D = header[2];
unsigned skip = LSHKIT_HEADER * sizeof(unsigned);
unsigned gap = 0;
load(path, D, skip, gap);
}
void save_lshkit (std::string const &path) {
std::ofstream os(path.c_str(), std::ios::binary);
unsigned header[3];
assert(sizeof header == 3*4);
header[0] = sizeof(T);
header[1] = row;
header[2] = col;
os.write((const char *)header, sizeof(header));
for (unsigned i = 0; i < row; ++i) {
os.write(&data[stride * i], sizeof(T) * col);
}
}
};
/// Matrix proxy to interface with 3rd party libraries (FLANN, OpenCV, NumPy).
template <typename DATA_TYPE, unsigned A = KGRAPH_MATRIX_ALIGN>
class MatrixProxy {
unsigned rows;
unsigned cols; // # elements, not bytes, in a row,
size_t stride; // # bytes in a row, >= cols * sizeof(element)
uint8_t const *data;
public:
MatrixProxy (Matrix<DATA_TYPE> const &m)
: rows(m.size()), cols(m.dim()), stride(m.step()), data(reinterpret_cast<uint8_t const *>(m[0])) {
}
~MatrixProxy () {
}
//#ifndef __AVX__
#ifdef FLANN_DATASET_H_
/// Construct from FLANN matrix.
MatrixProxy (flann::Matrix<DATA_TYPE> const &m)
: rows(m.rows), cols(m.cols), stride(m.stride), data(m.data) {
if (stride % A) throw invalid_argument("bad alignment");
}
#endif
#ifdef CV_MAJOR_VERSION
/// Construct from OpenCV matrix.
MatrixProxy (cv::Mat const &m)
: rows(m.rows), cols(m.cols), stride(m.step), data(m.data) {
if (stride % A) throw invalid_argument("bad alignment");
}
#endif
#ifdef XTENSOR_ARRAY_HPP
/// Construct from NumPy matrix.
MatrixProxy (xt::xtensor<DATA_TYPE, 2> const &obj) {
rows = obj.shape(0);
cols = obj.shape(1);
if (rows <= 1) {
stride = (cols * sizeof(DATA_TYPE) + A -1) / A * A;
}
else {
stride = reinterpret_cast<char const *>(&obj(1,0))
- reinterpret_cast<char const *>(&obj(0,0));
}
data = reinterpret_cast<uint8_t const *>(&obj(0,0));
if (stride % A) throw invalid_argument("bad alignment");
if (!(stride >= cols * sizeof(DATA_TYPE))) throw invalid_argument("bad stride");
}
MatrixProxy (xt::pytensor<DATA_TYPE, 2> const &obj) {
rows = obj.shape(0);
cols = obj.shape(1);
if (rows <= 1) {
stride = (cols * sizeof(DATA_TYPE) + A -1) / A * A;
}
else {
stride = reinterpret_cast<char const *>(&obj(1,0))
- reinterpret_cast<char const *>(&obj(0,0));
}
data = reinterpret_cast<uint8_t const *>(&obj(0,0));
if (stride % A) throw invalid_argument("bad alignment");
if (!(stride >= cols * sizeof(DATA_TYPE))) throw invalid_argument("bad stride");
}
#endif
//#endif
unsigned size () const {
return rows;
}
unsigned dim () const {
return cols;
}
DATA_TYPE const *operator [] (unsigned i) const {
return reinterpret_cast<DATA_TYPE const *>(data + stride * i);
}
DATA_TYPE *operator [] (unsigned i) {
return const_cast<DATA_TYPE *>(reinterpret_cast<DATA_TYPE const *>(data + stride * i));
}
};
/// Oracle for Matrix or MatrixProxy.
/** DATA_TYPE can be Matrix or MatrixProxy,
* DIST_TYPE should be one class within the namespace kgraph.metric.
*/
template <typename DATA_TYPE, typename DIST_TYPE>
class MatrixOracle: public kgraph::IndexOracle {
MatrixProxy<DATA_TYPE> proxy;
public:
class SearchOracle: public kgraph::SearchOracle {
MatrixProxy<DATA_TYPE> proxy;
DATA_TYPE const *query;
public:
SearchOracle (MatrixProxy<DATA_TYPE> const &p, DATA_TYPE const *q): proxy(p), query(q) {
}
virtual unsigned size () const {
return proxy.size();
}
virtual float operator () (unsigned i) const {
return DIST_TYPE::apply(proxy[i], query, proxy.dim());
}
};
template <typename MATRIX_TYPE>
MatrixOracle (MATRIX_TYPE const &m): proxy(m) {
}
virtual unsigned size () const {
return proxy.size();
}
virtual float operator () (unsigned i, unsigned j) const {
return DIST_TYPE::apply(proxy[i], proxy[j], proxy.dim());
}
SearchOracle query (DATA_TYPE const *query) const {
return SearchOracle(proxy, query);
}
};
inline float AverageRecall (Matrix<float> const &gs, Matrix<float> const &result, unsigned K = 0) {
if (K == 0) {
K = result.dim();
}
if (!(gs.dim() >= K)) throw invalid_argument("gs.dim() >= K");
if (!(result.dim() >= K)) throw invalid_argument("result.dim() >= K");
if (!(gs.size() >= result.size())) throw invalid_argument("gs.size() > result.size()");
float sum = 0;
for (unsigned i = 0; i < result.size(); ++i) {
float const *gs_row = gs[i];
float const *re_row = result[i];
// compare
unsigned found = 0;
unsigned gs_n = 0;
unsigned re_n = 0;
while ((gs_n < K) && (re_n < K)) {
if (gs_row[gs_n] < re_row[re_n]) {
++gs_n;
}
else if (gs_row[gs_n] == re_row[re_n]) {
++found;
++gs_n;
++re_n;
}
else {
throw runtime_error("distance is unstable");
}
}
sum += float(found) / K;
}
return sum / result.size();
}
}
#endif