-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
annoylib.h
1479 lines (1308 loc) · 44 KB
/
annoylib.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
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013 Spotify AB
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#ifndef ANNOYLIB_H
#define ANNOYLIB_H
#include <stdio.h>
#include <sys/stat.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stddef.h>
#if defined(_MSC_VER) && _MSC_VER == 1500
typedef unsigned char uint8_t;
typedef signed __int32 int32_t;
typedef unsigned __int64 uint64_t;
typedef signed __int64 int64_t;
#else
#include <stdint.h>
#endif
#if defined(_MSC_VER) || defined(__MINGW32__)
// a bit hacky, but override some definitions to support 64 bit
#define off_t int64_t
#define lseek_getsize(fd) _lseeki64(fd, 0, SEEK_END)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "mman.h"
#include <windows.h>
#else
#include <sys/mman.h>
#define lseek_getsize(fd) lseek(fd, 0, SEEK_END)
#endif
#include <cerrno>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <limits>
#ifdef ANNOYLIB_MULTITHREADED_BUILD
#include <thread>
#include <mutex>
#include <shared_mutex>
#endif
#ifdef _MSC_VER
// Needed for Visual Studio to disable runtime checks for mempcy
#pragma runtime_checks("s", off)
#endif
// This allows others to supply their own logger / error printer without
// requiring Annoy to import their headers. See RcppAnnoy for a use case.
#ifndef __ERROR_PRINTER_OVERRIDE__
#define showUpdate(...) { fprintf(stderr, __VA_ARGS__ ); }
#else
#define showUpdate(...) { __ERROR_PRINTER_OVERRIDE__( __VA_ARGS__ ); }
#endif
// Portable alloc definition, cf Writing R Extensions, Section 1.6.4
#ifdef __GNUC__
// Includes GCC, clang and Intel compilers
# undef alloca
# define alloca(x) __builtin_alloca((x))
#elif defined(__sun) || defined(_AIX)
// this is necessary (and sufficient) for Solaris 10 and AIX 6:
# include <alloca.h>
#endif
inline void set_error_from_errno(char **error, const char* msg) {
showUpdate("%s: %s (%d)\n", msg, strerror(errno), errno);
if (error) {
*error = (char *)malloc(256); // TODO: win doesn't support snprintf
sprintf(*error, "%s: %s (%d)", msg, strerror(errno), errno);
}
}
inline void set_error_from_string(char **error, const char* msg) {
showUpdate("%s\n", msg);
if (error) {
*error = (char *)malloc(strlen(msg) + 1);
strcpy(*error, msg);
}
}
// We let the v array in the Node struct take whatever space is needed, so this is a mostly insignificant number.
// Compilers need *some* size defined for the v array, and some memory checking tools will flag for buffer overruns if this is set too low.
#define V_ARRAY_SIZE 65536
#ifndef _MSC_VER
#define popcount __builtin_popcountll
#else // See #293, #358
#define popcount cole_popcount
#endif
#if !defined(NO_MANUAL_VECTORIZATION) && defined(__GNUC__) && (__GNUC__ >6) && defined(__AVX512F__) // See #402
#define USE_AVX512
#elif !defined(NO_MANUAL_VECTORIZATION) && defined(__AVX__) && defined (__SSE__) && defined(__SSE2__) && defined(__SSE3__)
#define USE_AVX
#else
#endif
#if defined(USE_AVX) || defined(USE_AVX512)
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__GNUC__)
#include <x86intrin.h>
#endif
#endif
#if !defined(__MINGW32__)
#define FTRUNCATE_SIZE(x) static_cast<int64_t>(x)
#else
#define FTRUNCATE_SIZE(x) (x)
#endif
using std::vector;
using std::pair;
using std::numeric_limits;
using std::make_pair;
inline bool remap_memory_and_truncate(void** _ptr, int _fd, size_t old_size, size_t new_size) {
#ifdef __linux__
*_ptr = mremap(*_ptr, old_size, new_size, MREMAP_MAYMOVE);
bool ok = ftruncate(_fd, new_size) != -1;
#else
munmap(*_ptr, old_size);
bool ok = ftruncate(_fd, FTRUNCATE_SIZE(new_size)) != -1;
#ifdef MAP_POPULATE
*_ptr = mmap(*_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0);
#else
*_ptr = mmap(*_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0);
#endif
#endif
return ok;
}
namespace {
template<typename S, typename Node>
inline Node* get_node_ptr(const void* _nodes, const size_t _s, const S i) {
return (Node*)((uint8_t *)_nodes + (_s * i));
}
template<typename T>
inline T dot(const T* x, const T* y, int f) {
T s = 0;
for (int z = 0; z < f; z++) {
s += (*x) * (*y);
x++;
y++;
}
return s;
}
template<typename T>
inline T manhattan_distance(const T* x, const T* y, int f) {
T d = 0.0;
for (int i = 0; i < f; i++)
d += fabs(x[i] - y[i]);
return d;
}
template<typename T>
inline T euclidean_distance(const T* x, const T* y, int f) {
// Don't use dot-product: avoid catastrophic cancellation in #314.
T d = 0.0;
for (int i = 0; i < f; ++i) {
const T tmp=*x - *y;
d += tmp * tmp;
++x;
++y;
}
return d;
}
#ifdef USE_AVX
// Horizontal single sum of 256bit vector.
inline float hsum256_ps_avx(__m256 v) {
const __m128 x128 = _mm_add_ps(_mm256_extractf128_ps(v, 1), _mm256_castps256_ps128(v));
const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128));
const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55));
return _mm_cvtss_f32(x32);
}
template<>
inline float dot<float>(const float* x, const float *y, int f) {
float result = 0;
if (f > 7) {
__m256 d = _mm256_setzero_ps();
for (; f > 7; f -= 8) {
d = _mm256_add_ps(d, _mm256_mul_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y)));
x += 8;
y += 8;
}
// Sum all floats in dot register.
result += hsum256_ps_avx(d);
}
// Don't forget the remaining values.
for (; f > 0; f--) {
result += *x * *y;
x++;
y++;
}
return result;
}
template<>
inline float manhattan_distance<float>(const float* x, const float* y, int f) {
float result = 0;
int i = f;
if (f > 7) {
__m256 manhattan = _mm256_setzero_ps();
__m256 minus_zero = _mm256_set1_ps(-0.0f);
for (; i > 7; i -= 8) {
const __m256 x_minus_y = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y));
const __m256 distance = _mm256_andnot_ps(minus_zero, x_minus_y); // Absolute value of x_minus_y (forces sign bit to zero)
manhattan = _mm256_add_ps(manhattan, distance);
x += 8;
y += 8;
}
// Sum all floats in manhattan register.
result = hsum256_ps_avx(manhattan);
}
// Don't forget the remaining values.
for (; i > 0; i--) {
result += fabsf(*x - *y);
x++;
y++;
}
return result;
}
template<>
inline float euclidean_distance<float>(const float* x, const float* y, int f) {
float result=0;
if (f > 7) {
__m256 d = _mm256_setzero_ps();
for (; f > 7; f -= 8) {
const __m256 diff = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y));
d = _mm256_add_ps(d, _mm256_mul_ps(diff, diff)); // no support for fmadd in AVX...
x += 8;
y += 8;
}
// Sum all floats in dot register.
result = hsum256_ps_avx(d);
}
// Don't forget the remaining values.
for (; f > 0; f--) {
float tmp = *x - *y;
result += tmp * tmp;
x++;
y++;
}
return result;
}
#endif
#ifdef USE_AVX512
template<>
inline float dot<float>(const float* x, const float *y, int f) {
float result = 0;
if (f > 15) {
__m512 d = _mm512_setzero_ps();
for (; f > 15; f -= 16) {
//AVX512F includes FMA
d = _mm512_fmadd_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y), d);
x += 16;
y += 16;
}
// Sum all floats in dot register.
result += _mm512_reduce_add_ps(d);
}
// Don't forget the remaining values.
for (; f > 0; f--) {
result += *x * *y;
x++;
y++;
}
return result;
}
template<>
inline float manhattan_distance<float>(const float* x, const float* y, int f) {
float result = 0;
int i = f;
if (f > 15) {
__m512 manhattan = _mm512_setzero_ps();
for (; i > 15; i -= 16) {
const __m512 x_minus_y = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y));
manhattan = _mm512_add_ps(manhattan, _mm512_abs_ps(x_minus_y));
x += 16;
y += 16;
}
// Sum all floats in manhattan register.
result = _mm512_reduce_add_ps(manhattan);
}
// Don't forget the remaining values.
for (; i > 0; i--) {
result += fabsf(*x - *y);
x++;
y++;
}
return result;
}
template<>
inline float euclidean_distance<float>(const float* x, const float* y, int f) {
float result=0;
if (f > 15) {
__m512 d = _mm512_setzero_ps();
for (; f > 15; f -= 16) {
const __m512 diff = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y));
d = _mm512_fmadd_ps(diff, diff, d);
x += 16;
y += 16;
}
// Sum all floats in dot register.
result = _mm512_reduce_add_ps(d);
}
// Don't forget the remaining values.
for (; f > 0; f--) {
float tmp = *x - *y;
result += tmp * tmp;
x++;
y++;
}
return result;
}
#endif
template<typename T>
inline T get_norm(T* v, int f) {
return sqrt(dot(v, v, f));
}
template<typename T, typename Random, typename Distance, typename Node>
inline void two_means(const vector<Node*>& nodes, int f, Random& random, bool cosine, Node* p, Node* q) {
/*
This algorithm is a huge heuristic. Empirically it works really well, but I
can't motivate it well. The basic idea is to keep two centroids and assign
points to either one of them. We weight each centroid by the number of points
assigned to it, so to balance it.
*/
static int iteration_steps = 200;
size_t count = nodes.size();
size_t i = random.index(count);
size_t j = random.index(count-1);
j += (j >= i); // ensure that i != j
Distance::template copy_node<T, Node>(p, nodes[i], f);
Distance::template copy_node<T, Node>(q, nodes[j], f);
if (cosine) { Distance::template normalize<T, Node>(p, f); Distance::template normalize<T, Node>(q, f); }
Distance::init_node(p, f);
Distance::init_node(q, f);
int ic = 1, jc = 1;
for (int l = 0; l < iteration_steps; l++) {
size_t k = random.index(count);
T di = ic * Distance::distance(p, nodes[k], f),
dj = jc * Distance::distance(q, nodes[k], f);
T norm = cosine ? get_norm(nodes[k]->v, f) : 1;
if (!(norm > T(0))) {
continue;
}
if (di < dj) {
for (int z = 0; z < f; z++)
p->v[z] = (p->v[z] * ic + nodes[k]->v[z] / norm) / (ic + 1);
Distance::init_node(p, f);
ic++;
} else if (dj < di) {
for (int z = 0; z < f; z++)
q->v[z] = (q->v[z] * jc + nodes[k]->v[z] / norm) / (jc + 1);
Distance::init_node(q, f);
jc++;
}
}
}
} // namespace
struct Base {
template<typename T, typename S, typename Node>
static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) {
// Override this in specific metric structs below if you need to do any pre-processing
// on the entire set of nodes passed into this index.
}
template<typename Node>
static inline void zero_value(Node* dest) {
// Initialize any fields that require sane defaults within this node.
}
template<typename T, typename Node>
static inline void copy_node(Node* dest, const Node* source, const int f) {
memcpy(dest->v, source->v, f * sizeof(T));
}
template<typename T, typename Node>
static inline void normalize(Node* node, int f) {
T norm = get_norm(node->v, f);
if (norm > 0) {
for (int z = 0; z < f; z++)
node->v[z] /= norm;
}
}
};
struct Angular : Base {
template<typename S, typename T>
struct Node {
/*
* We store a binary tree where each node has two things
* - A vector associated with it
* - Two children
* All nodes occupy the same amount of memory
* All nodes with n_descendants == 1 are leaf nodes.
* A memory optimization is that for nodes with 2 <= n_descendants <= K,
* we skip the vector. Instead we store a list of all descendants. K is
* determined by the number of items that fits in the space of the vector.
* For nodes with n_descendants == 1 the vector is a data point.
* For nodes with n_descendants > K the vector is the normal of the split plane.
* Note that we can't really do sizeof(node<T>) because we cheat and allocate
* more memory to be able to fit the vector outside
*/
S n_descendants;
union {
S children[2]; // Will possibly store more than 2
T norm;
};
T v[V_ARRAY_SIZE];
};
template<typename S, typename T>
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) {
// want to calculate (a/|a| - b/|b|)^2
// = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b|
// = 2 - 2cos
T pp = x->norm ? x->norm : dot(x->v, x->v, f); // For backwards compatibility reasons, we need to fall back and compute the norm here
T qq = y->norm ? y->norm : dot(y->v, y->v, f);
T pq = dot(x->v, y->v, f);
T ppqq = pp * qq;
if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq);
else return 2.0; // cos is 0
}
template<typename S, typename T>
static inline T margin(const Node<S, T>* n, const T* y, int f) {
return dot(n->v, y, f);
}
template<typename S, typename T, typename Random>
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) {
T dot = margin(n, y, f);
if (dot != 0)
return (dot > 0);
else
return (bool)random.flip();
}
template<typename S, typename T, typename Random>
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) {
Node<S, T>* p = (Node<S, T>*)alloca(s);
Node<S, T>* q = (Node<S, T>*)alloca(s);
two_means<T, Random, Angular, Node<S, T> >(nodes, f, random, true, p, q);
for (int z = 0; z < f; z++)
n->v[z] = p->v[z] - q->v[z];
Base::normalize<T, Node<S, T> >(n, f);
}
template<typename T>
static inline T normalized_distance(T distance) {
// Used when requesting distances from Python layer
// Turns out sometimes the squared distance is -0.0
// so we have to make sure it's a positive number.
return sqrt(std::max(distance, T(0)));
}
template<typename T>
static inline T pq_distance(T distance, T margin, int child_nr) {
if (child_nr == 0)
margin = -margin;
return std::min(distance, margin);
}
template<typename T>
static inline T pq_initial_value() {
return numeric_limits<T>::infinity();
}
template<typename S, typename T>
static inline void init_node(Node<S, T>* n, int f) {
n->norm = dot(n->v, n->v, f);
}
static const char* name() {
return "angular";
}
};
struct DotProduct : Angular {
template<typename S, typename T>
struct Node {
/*
* This is an extension of the Angular node with an extra attribute for the scaled norm.
*/
S n_descendants;
S children[2]; // Will possibly store more than 2
T dot_factor;
T v[V_ARRAY_SIZE];
};
static const char* name() {
return "dot";
}
template<typename S, typename T>
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) {
return -dot(x->v, y->v, f);
}
template<typename Node>
static inline void zero_value(Node* dest) {
dest->dot_factor = 0;
}
template<typename S, typename T>
static inline void init_node(Node<S, T>* n, int f) {
}
template<typename T, typename Node>
static inline void copy_node(Node* dest, const Node* source, const int f) {
memcpy(dest->v, source->v, f * sizeof(T));
dest->dot_factor = source->dot_factor;
}
template<typename S, typename T, typename Random>
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) {
Node<S, T>* p = (Node<S, T>*)alloca(s);
Node<S, T>* q = (Node<S, T>*)alloca(s);
DotProduct::zero_value(p);
DotProduct::zero_value(q);
two_means<T, Random, DotProduct, Node<S, T> >(nodes, f, random, true, p, q);
for (int z = 0; z < f; z++)
n->v[z] = p->v[z] - q->v[z];
n->dot_factor = p->dot_factor - q->dot_factor;
DotProduct::normalize<T, Node<S, T> >(n, f);
}
template<typename T, typename Node>
static inline void normalize(Node* node, int f) {
T norm = sqrt(dot(node->v, node->v, f) + pow(node->dot_factor, 2));
if (norm > 0) {
for (int z = 0; z < f; z++)
node->v[z] /= norm;
node->dot_factor /= norm;
}
}
template<typename S, typename T>
static inline T margin(const Node<S, T>* n, const T* y, int f) {
return dot(n->v, y, f) + (n->dot_factor * n->dot_factor);
}
template<typename S, typename T, typename Random>
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) {
T dot = margin(n, y, f);
if (dot != 0)
return (dot > 0);
else
return (bool)random.flip();
}
template<typename T>
static inline T normalized_distance(T distance) {
return -distance;
}
template<typename T, typename S, typename Node>
static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) {
// This uses a method from Microsoft Research for transforming inner product spaces to cosine/angular-compatible spaces.
// (Bachrach et al., 2014, see https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/XboxInnerProduct.pdf)
// Step one: compute the norm of each vector and store that in its extra dimension (f-1)
for (S i = 0; i < node_count; i++) {
Node* node = get_node_ptr<S, Node>(nodes, _s, i);
T d = dot(node->v, node->v, f);
T norm = d < 0 ? 0 : sqrt(d);
node->dot_factor = norm;
}
// Step two: find the maximum norm
T max_norm = 0;
for (S i = 0; i < node_count; i++) {
Node* node = get_node_ptr<S, Node>(nodes, _s, i);
if (node->dot_factor > max_norm) {
max_norm = node->dot_factor;
}
}
// Step three: set each vector's extra dimension to sqrt(max_norm^2 - norm^2)
for (S i = 0; i < node_count; i++) {
Node* node = get_node_ptr<S, Node>(nodes, _s, i);
T node_norm = node->dot_factor;
T squared_norm_diff = pow(max_norm, static_cast<T>(2.0)) - pow(node_norm, static_cast<T>(2.0));
T dot_factor = squared_norm_diff < 0 ? 0 : sqrt(squared_norm_diff);
node->dot_factor = dot_factor;
}
}
};
struct Hamming : Base {
template<typename S, typename T>
struct Node {
S n_descendants;
S children[2];
T v[V_ARRAY_SIZE];
};
static const size_t max_iterations = 20;
template<typename T>
static inline T pq_distance(T distance, T margin, int child_nr) {
return distance - (margin != (unsigned int) child_nr);
}
template<typename T>
static inline T pq_initial_value() {
return numeric_limits<T>::max();
}
template<typename T>
static inline int cole_popcount(T v) {
// Note: Only used with MSVC 9, which lacks intrinsics and fails to
// calculate std::bitset::count for v > 32bit. Uses the generalized
// approach by Eric Cole.
// See https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSet64
v = v - ((v >> 1) & (T)~(T)0/3);
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3);
v = (v + (v >> 4)) & (T)~(T)0/255*15;
return (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * 8;
}
template<typename S, typename T>
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) {
size_t dist = 0;
for (int i = 0; i < f; i++) {
dist += popcount(x->v[i] ^ y->v[i]);
}
return dist;
}
template<typename S, typename T>
static inline bool margin(const Node<S, T>* n, const T* y, int f) {
static const size_t n_bits = sizeof(T) * 8;
T chunk = n->v[0] / n_bits;
return (y[chunk] & (static_cast<T>(1) << (n_bits - 1 - (n->v[0] % n_bits)))) != 0;
}
template<typename S, typename T, typename Random>
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) {
return margin(n, y, f);
}
template<typename S, typename T, typename Random>
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) {
size_t cur_size = 0;
size_t i = 0;
int dim = f * 8 * sizeof(T);
for (; i < max_iterations; i++) {
// choose random position to split at
n->v[0] = random.index(dim);
cur_size = 0;
for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
if (margin(n, (*it)->v, f)) {
cur_size++;
}
}
if (cur_size > 0 && cur_size < nodes.size()) {
break;
}
}
// brute-force search for splitting coordinate
if (i == max_iterations) {
int j = 0;
for (; j < dim; j++) {
n->v[0] = j;
cur_size = 0;
for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
if (margin(n, (*it)->v, f)) {
cur_size++;
}
}
if (cur_size > 0 && cur_size < nodes.size()) {
break;
}
}
}
}
template<typename T>
static inline T normalized_distance(T distance) {
return distance;
}
template<typename S, typename T>
static inline void init_node(Node<S, T>* n, int f) {
}
static const char* name() {
return "hamming";
}
};
struct Minkowski : Base {
template<typename S, typename T>
struct Node {
S n_descendants;
T a; // need an extra constant term to determine the offset of the plane
S children[2];
T v[V_ARRAY_SIZE];
};
template<typename S, typename T>
static inline T margin(const Node<S, T>* n, const T* y, int f) {
return n->a + dot(n->v, y, f);
}
template<typename S, typename T, typename Random>
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) {
T dot = margin(n, y, f);
if (dot != 0)
return (dot > 0);
else
return (bool)random.flip();
}
template<typename T>
static inline T pq_distance(T distance, T margin, int child_nr) {
if (child_nr == 0)
margin = -margin;
return std::min(distance, margin);
}
template<typename T>
static inline T pq_initial_value() {
return numeric_limits<T>::infinity();
}
};
struct Euclidean : Minkowski {
template<typename S, typename T>
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) {
return euclidean_distance(x->v, y->v, f);
}
template<typename S, typename T, typename Random>
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) {
Node<S, T>* p = (Node<S, T>*)alloca(s);
Node<S, T>* q = (Node<S, T>*)alloca(s);
two_means<T, Random, Euclidean, Node<S, T> >(nodes, f, random, false, p, q);
for (int z = 0; z < f; z++)
n->v[z] = p->v[z] - q->v[z];
Base::normalize<T, Node<S, T> >(n, f);
n->a = 0.0;
for (int z = 0; z < f; z++)
n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2;
}
template<typename T>
static inline T normalized_distance(T distance) {
return sqrt(std::max(distance, T(0)));
}
template<typename S, typename T>
static inline void init_node(Node<S, T>* n, int f) {
}
static const char* name() {
return "euclidean";
}
};
struct Manhattan : Minkowski {
template<typename S, typename T>
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) {
return manhattan_distance(x->v, y->v, f);
}
template<typename S, typename T, typename Random>
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) {
Node<S, T>* p = (Node<S, T>*)alloca(s);
Node<S, T>* q = (Node<S, T>*)alloca(s);
two_means<T, Random, Manhattan, Node<S, T> >(nodes, f, random, false, p, q);
for (int z = 0; z < f; z++)
n->v[z] = p->v[z] - q->v[z];
Base::normalize<T, Node<S, T> >(n, f);
n->a = 0.0;
for (int z = 0; z < f; z++)
n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2;
}
template<typename T>
static inline T normalized_distance(T distance) {
return std::max(distance, T(0));
}
template<typename S, typename T>
static inline void init_node(Node<S, T>* n, int f) {
}
static const char* name() {
return "manhattan";
}
};
template<typename S, typename T>
class AnnoyIndexInterface {
public:
// Note that the methods with an **error argument will allocate memory and write the pointer to that string if error is non-NULL
virtual ~AnnoyIndexInterface() {};
virtual bool add_item(S item, const T* w, char** error=NULL) = 0;
virtual bool build(int q, int n_threads=-1, char** error=NULL) = 0;
virtual bool unbuild(char** error=NULL) = 0;
virtual bool save(const char* filename, bool prefault=false, char** error=NULL) = 0;
virtual void unload() = 0;
virtual bool load(const char* filename, bool prefault=false, char** error=NULL) = 0;
virtual T get_distance(S i, S j) const = 0;
virtual void get_nns_by_item(S item, size_t n, int search_k, vector<S>* result, vector<T>* distances) const = 0;
virtual void get_nns_by_vector(const T* w, size_t n, int search_k, vector<S>* result, vector<T>* distances) const = 0;
virtual S get_n_items() const = 0;
virtual S get_n_trees() const = 0;
virtual void verbose(bool v) = 0;
virtual void get_item(S item, T* v) const = 0;
virtual void set_seed(int q) = 0;
virtual bool on_disk_build(const char* filename, char** error=NULL) = 0;
};
template<typename S, typename T, typename Distance, typename Random, class ThreadedBuildPolicy>
class AnnoyIndex : public AnnoyIndexInterface<S, T> {
/*
* We use random projection to build a forest of binary trees of all items.
* Basically just split the hyperspace into two sides by a hyperplane,
* then recursively split each of those subtrees etc.
* We create a tree like this q times. The default q is determined automatically
* in such a way that we at most use 2x as much memory as the vectors take.
*/
public:
typedef Distance D;
typedef typename D::template Node<S, T> Node;
protected:
const int _f;
size_t _s;
S _n_items;
void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate
S _n_nodes;
S _nodes_size;
vector<S> _roots;
S _K;
bool _is_seeded;
int _seed;
bool _loaded;
bool _verbose;
int _fd;
bool _on_disk;
bool _built;
public:
AnnoyIndex(int f) : _f(f) {
_s = offsetof(Node, v) + _f * sizeof(T); // Size of each node
_verbose = false;
_built = false;
_K = (S) (((size_t) (_s - offsetof(Node, children))) / sizeof(S)); // Max number of descendants to fit into node
reinitialize(); // Reset everything
}
~AnnoyIndex() {
unload();
}
int get_f() const {
return _f;
}
bool add_item(S item, const T* w, char** error=NULL) {
return add_item_impl(item, w, error);
}
template<typename W>
bool add_item_impl(S item, const W& w, char** error=NULL) {
if (_loaded) {
set_error_from_string(error, "You can't add an item to a loaded index");
return false;
}
_allocate_size(item + 1);
Node* n = _get(item);
D::zero_value(n);
n->children[0] = 0;
n->children[1] = 0;
n->n_descendants = 1;
for (int z = 0; z < _f; z++)
n->v[z] = w[z];
D::init_node(n, _f);
if (item >= _n_items)
_n_items = item + 1;
return true;
}
bool on_disk_build(const char* file, char** error=NULL) {
_on_disk = true;
_fd = open(file, O_RDWR | O_CREAT | O_TRUNC, (int) 0600);
if (_fd == -1) {
set_error_from_errno(error, "Unable to open");
_fd = 0;
return false;
}
_nodes_size = 1;
if (ftruncate(_fd, FTRUNCATE_SIZE(_s) * FTRUNCATE_SIZE(_nodes_size)) == -1) {
set_error_from_errno(error, "Unable to truncate");
return false;
}
#ifdef MAP_POPULATE
_nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0);
#else
_nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0);
#endif
return true;
}
bool build(int q, int n_threads=-1, char** error=NULL) {
if (_loaded) {
set_error_from_string(error, "You can't build a loaded index");
return false;
}
if (_built) {
set_error_from_string(error, "You can't build a built index");
return false;
}
D::template preprocess<T, S, Node>(_nodes, _s, _n_items, _f);
_n_nodes = _n_items;
ThreadedBuildPolicy::template build<S, T>(this, q, n_threads);
// Also, copy the roots into the last segment of the array
// This way we can load them faster without reading the whole file
_allocate_size(_n_nodes + (S)_roots.size());
for (size_t i = 0; i < _roots.size(); i++)
memcpy(_get(_n_nodes + (S)i), _get(_roots[i]), _s);
_n_nodes += _roots.size();
if (_verbose) showUpdate("has %d nodes\n", _n_nodes);
if (_on_disk) {
if (!remap_memory_and_truncate(&_nodes, _fd,
static_cast<size_t>(_s) * static_cast<size_t>(_nodes_size),
static_cast<size_t>(_s) * static_cast<size_t>(_n_nodes))) {
// TODO: this probably creates an index in a corrupt state... not sure what to do
set_error_from_errno(error, "Unable to truncate");
return false;
}
_nodes_size = _n_nodes;
}
_built = true;
return true;
}
bool unbuild(char** error=NULL) {
if (_loaded) {
set_error_from_string(error, "You can't unbuild a loaded index");
return false;
}
_roots.clear();
_n_nodes = _n_items;
_built = false;
return true;
}
bool save(const char* filename, bool prefault=false, char** error=NULL) {
if (!_built) {
set_error_from_string(error, "You can't save an index that hasn't been built");
return false;
}
if (_on_disk) {
return true;
} else {
// Delete file if it already exists (See issue #335)
unlink(filename);