| 1 |
// Copyright (c) 2013 Spotify AB |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 4 |
// use this file except in compliance with the License. You may obtain a copy of |
| 5 |
// the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 |
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 |
// License for the specific language governing permissions and limitations under |
| 13 |
// the License. |
| 14 |
|
| 15 |
|
| 16 |
#ifndef ANNOYLIB_H |
| 17 |
#define ANNOYLIB_H |
| 18 |
|
| 19 |
#include <stdio.h> |
| 20 |
#include <sys/stat.h> |
| 21 |
#ifndef _MSC_VER |
| 22 |
#include <unistd.h> |
| 23 |
#endif |
| 24 |
#include <stdio.h> |
| 25 |
#include <stdlib.h> |
| 26 |
#include <sys/types.h> |
| 27 |
#include <fcntl.h> |
| 28 |
#include <stddef.h> |
| 29 |
|
| 30 |
#if defined(_MSC_VER) && _MSC_VER == 1500 |
| 31 |
typedef unsigned char uint8_t; |
| 32 |
typedef signed __int32 int32_t; |
| 33 |
typedef unsigned __int64 uint64_t; |
| 34 |
typedef signed __int64 int64_t; |
| 35 |
#else |
| 36 |
#include <stdint.h> |
| 37 |
#endif |
| 38 |
|
| 39 |
#if defined(_MSC_VER) || defined(__MINGW32__) |
| 40 |
// a bit hacky, but override some definitions to support 64 bit |
| 41 |
#define off_t int64_t |
| 42 |
#define lseek_getsize(fd) _lseeki64(fd, 0, SEEK_END) |
| 43 |
#ifndef NOMINMAX |
| 44 |
#define NOMINMAX |
| 45 |
#endif |
| 46 |
#include "mman.h" |
| 47 |
#include <windows.h> |
| 48 |
#else |
| 49 |
#include <sys/mman.h> |
| 50 |
#define lseek_getsize(fd) lseek(fd, 0, SEEK_END) |
| 51 |
#endif |
| 52 |
|
| 53 |
#include <cerrno> |
| 54 |
#include <string.h> |
| 55 |
#include <math.h> |
| 56 |
#include <vector> |
| 57 |
#include <algorithm> |
| 58 |
#include <queue> |
| 59 |
#include <limits> |
| 60 |
|
| 61 |
#ifdef ANNOYLIB_MULTITHREADED_BUILD |
| 62 |
#include <thread> |
| 63 |
#include <mutex> |
| 64 |
#include <shared_mutex> |
| 65 |
#endif |
| 66 |
|
| 67 |
#ifdef _MSC_VER |
| 68 |
// Needed for Visual Studio to disable runtime checks for mempcy |
| 69 |
#pragma runtime_checks("s", off) |
| 70 |
#endif |
| 71 |
|
| 72 |
// This allows others to supply their own logger / error printer without |
| 73 |
// requiring Annoy to import their headers. See RcppAnnoy for a use case. |
| 74 |
#ifndef __ERROR_PRINTER_OVERRIDE__ |
| 75 |
#define showUpdate(...) { fprintf(stderr, __VA_ARGS__ ); } |
| 76 |
#else |
| 77 |
#define showUpdate(...) { __ERROR_PRINTER_OVERRIDE__( __VA_ARGS__ ); } |
| 78 |
#endif |
| 79 |
|
| 80 |
// Portable alloc definition, cf Writing R Extensions, Section 1.6.4 |
| 81 |
#ifdef __GNUC__ |
| 82 |
// Includes GCC, clang and Intel compilers |
| 83 |
# undef alloca |
| 84 |
# define alloca(x) __builtin_alloca((x)) |
| 85 |
#elif defined(__sun) || defined(_AIX) |
| 86 |
// this is necessary (and sufficient) for Solaris 10 and AIX 6: |
| 87 |
# include <alloca.h> |
| 88 |
#endif |
| 89 |
|
| 90 |
inline void set_error_from_errno(char **error, const char* msg) { |
| 91 |
showUpdate("%s: %s (%d)\n", msg, strerror(errno), errno); |
| 92 |
if (error) { |
| 93 |
*error = (char *)malloc(256); // TODO: win doesn't support snprintf |
| 94 |
sprintf(*error, "%s: %s (%d)", msg, strerror(errno), errno); |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
inline void set_error_from_string(char **error, const char* msg) { |
| 99 |
showUpdate("%s\n", msg); |
| 100 |
if (error) { |
| 101 |
*error = (char *)malloc(strlen(msg) + 1); |
| 102 |
strcpy(*error, msg); |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
// We let the v array in the Node struct take whatever space is needed, so this is a mostly insignificant number. |
| 107 |
// 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. |
| 108 |
#define V_ARRAY_SIZE 65536 |
| 109 |
|
| 110 |
#ifndef _MSC_VER |
| 111 |
#define popcount __builtin_popcountll |
| 112 |
#else // See #293, #358 |
| 113 |
#define popcount cole_popcount |
| 114 |
#endif |
| 115 |
|
| 116 |
#if !defined(NO_MANUAL_VECTORIZATION) && defined(__GNUC__) && (__GNUC__ >6) && defined(__AVX512F__) // See #402 |
| 117 |
#define USE_AVX512 |
| 118 |
#elif !defined(NO_MANUAL_VECTORIZATION) && defined(__AVX__) && defined (__SSE__) && defined(__SSE2__) && defined(__SSE3__) |
| 119 |
#define USE_AVX |
| 120 |
#else |
| 121 |
#endif |
| 122 |
|
| 123 |
#if defined(USE_AVX) || defined(USE_AVX512) |
| 124 |
#if defined(_MSC_VER) |
| 125 |
#include <intrin.h> |
| 126 |
#elif defined(__GNUC__) |
| 127 |
#include <x86intrin.h> |
| 128 |
#endif |
| 129 |
#endif |
| 130 |
|
| 131 |
#if !defined(__MINGW32__) |
| 132 |
#define FTRUNCATE_SIZE(x) static_cast<int64_t>(x) |
| 133 |
#else |
| 134 |
#define FTRUNCATE_SIZE(x) (x) |
| 135 |
#endif |
| 136 |
|
| 137 |
using std::vector; |
| 138 |
using std::pair; |
| 139 |
using std::numeric_limits; |
| 140 |
using std::make_pair; |
| 141 |
|
| 142 |
inline bool remap_memory_and_truncate(void** _ptr, int _fd, size_t old_size, size_t new_size) { |
| 143 |
#ifdef __linux__ |
| 144 |
*_ptr = mremap(*_ptr, old_size, new_size, MREMAP_MAYMOVE); |
| 145 |
bool ok = ftruncate(_fd, new_size) != -1; |
| 146 |
#else |
| 147 |
munmap(*_ptr, old_size); |
| 148 |
bool ok = ftruncate(_fd, FTRUNCATE_SIZE(new_size)) != -1; |
| 149 |
#ifdef MAP_POPULATE |
| 150 |
*_ptr = mmap(*_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0); |
| 151 |
#else |
| 152 |
*_ptr = mmap(*_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0); |
| 153 |
#endif |
| 154 |
#endif |
| 155 |
return ok; |
| 156 |
} |
| 157 |
|
| 158 |
namespace { |
| 159 |
|
| 160 |
template<typename S, typename Node> |
| 161 |
inline Node* get_node_ptr(const void* _nodes, const size_t _s, const S i) { |
| 162 |
return (Node*)((uint8_t *)_nodes + (_s * i)); |
| 163 |
} |
| 164 |
|
| 165 |
template<typename T> |
| 166 |
inline T dot(const T* x, const T* y, int f) { |
| 167 |
T s = 0; |
| 168 |
for (int z = 0; z < f; z++) { |
| 169 |
s += (*x) * (*y); |
| 170 |
x++; |
| 171 |
y++; |
| 172 |
} |
| 173 |
return s; |
| 174 |
} |
| 175 |
|
| 176 |
template<typename T> |
| 177 |
inline T manhattan_distance(const T* x, const T* y, int f) { |
| 178 |
T d = 0.0; |
| 179 |
for (int i = 0; i < f; i++) |
| 180 |
d += fabs(x[i] - y[i]); |
| 181 |
return d; |
| 182 |
} |
| 183 |
|
| 184 |
template<typename T> |
| 185 |
inline T euclidean_distance(const T* x, const T* y, int f) { |
| 186 |
// Don't use dot-product: avoid catastrophic cancellation in #314. |
| 187 |
T d = 0.0; |
| 188 |
for (int i = 0; i < f; ++i) { |
| 189 |
const T tmp=*x - *y; |
| 190 |
d += tmp * tmp; |
| 191 |
++x; |
| 192 |
++y; |
| 193 |
} |
| 194 |
return d; |
| 195 |
} |
| 196 |
|
| 197 |
#ifdef USE_AVX |
| 198 |
// Horizontal single sum of 256bit vector. |
| 199 |
inline float hsum256_ps_avx(__m256 v) { |
| 200 |
const __m128 x128 = _mm_add_ps(_mm256_extractf128_ps(v, 1), _mm256_castps256_ps128(v)); |
| 201 |
const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128)); |
| 202 |
const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55)); |
| 203 |
return _mm_cvtss_f32(x32); |
| 204 |
} |
| 205 |
|
| 206 |
template<> |
| 207 |
inline float dot<float>(const float* x, const float *y, int f) { |
| 208 |
float result = 0; |
| 209 |
if (f > 7) { |
| 210 |
__m256 d = _mm256_setzero_ps(); |
| 211 |
for (; f > 7; f -= 8) { |
| 212 |
d = _mm256_add_ps(d, _mm256_mul_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y))); |
| 213 |
x += 8; |
| 214 |
y += 8; |
| 215 |
} |
| 216 |
// Sum all floats in dot register. |
| 217 |
result += hsum256_ps_avx(d); |
| 218 |
} |
| 219 |
// Don't forget the remaining values. |
| 220 |
for (; f > 0; f--) { |
| 221 |
result += *x * *y; |
| 222 |
x++; |
| 223 |
y++; |
| 224 |
} |
| 225 |
return result; |
| 226 |
} |
| 227 |
|
| 228 |
template<> |
| 229 |
inline float manhattan_distance<float>(const float* x, const float* y, int f) { |
| 230 |
float result = 0; |
| 231 |
int i = f; |
| 232 |
if (f > 7) { |
| 233 |
__m256 manhattan = _mm256_setzero_ps(); |
| 234 |
__m256 minus_zero = _mm256_set1_ps(-0.0f); |
| 235 |
for (; i > 7; i -= 8) { |
| 236 |
const __m256 x_minus_y = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y)); |
| 237 |
const __m256 distance = _mm256_andnot_ps(minus_zero, x_minus_y); // Absolute value of x_minus_y (forces sign bit to zero) |
| 238 |
manhattan = _mm256_add_ps(manhattan, distance); |
| 239 |
x += 8; |
| 240 |
y += 8; |
| 241 |
} |
| 242 |
// Sum all floats in manhattan register. |
| 243 |
result = hsum256_ps_avx(manhattan); |
| 244 |
} |
| 245 |
// Don't forget the remaining values. |
| 246 |
for (; i > 0; i--) { |
| 247 |
result += fabsf(*x - *y); |
| 248 |
x++; |
| 249 |
y++; |
| 250 |
} |
| 251 |
return result; |
| 252 |
} |
| 253 |
|
| 254 |
template<> |
| 255 |
inline float euclidean_distance<float>(const float* x, const float* y, int f) { |
| 256 |
float result=0; |
| 257 |
if (f > 7) { |
| 258 |
__m256 d = _mm256_setzero_ps(); |
| 259 |
for (; f > 7; f -= 8) { |
| 260 |
const __m256 diff = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y)); |
| 261 |
d = _mm256_add_ps(d, _mm256_mul_ps(diff, diff)); // no support for fmadd in AVX... |
| 262 |
x += 8; |
| 263 |
y += 8; |
| 264 |
} |
| 265 |
// Sum all floats in dot register. |
| 266 |
result = hsum256_ps_avx(d); |
| 267 |
} |
| 268 |
// Don't forget the remaining values. |
| 269 |
for (; f > 0; f--) { |
| 270 |
float tmp = *x - *y; |
| 271 |
result += tmp * tmp; |
| 272 |
x++; |
| 273 |
y++; |
| 274 |
} |
| 275 |
return result; |
| 276 |
} |
| 277 |
|
| 278 |
#endif |
| 279 |
|
| 280 |
#ifdef USE_AVX512 |
| 281 |
template<> |
| 282 |
inline float dot<float>(const float* x, const float *y, int f) { |
| 283 |
float result = 0; |
| 284 |
if (f > 15) { |
| 285 |
__m512 d = _mm512_setzero_ps(); |
| 286 |
for (; f > 15; f -= 16) { |
| 287 |
//AVX512F includes FMA |
| 288 |
d = _mm512_fmadd_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y), d); |
| 289 |
x += 16; |
| 290 |
y += 16; |
| 291 |
} |
| 292 |
// Sum all floats in dot register. |
| 293 |
result += _mm512_reduce_add_ps(d); |
| 294 |
} |
| 295 |
// Don't forget the remaining values. |
| 296 |
for (; f > 0; f--) { |
| 297 |
result += *x * *y; |
| 298 |
x++; |
| 299 |
y++; |
| 300 |
} |
| 301 |
return result; |
| 302 |
} |
| 303 |
|
| 304 |
template<> |
| 305 |
inline float manhattan_distance<float>(const float* x, const float* y, int f) { |
| 306 |
float result = 0; |
| 307 |
int i = f; |
| 308 |
if (f > 15) { |
| 309 |
__m512 manhattan = _mm512_setzero_ps(); |
| 310 |
for (; i > 15; i -= 16) { |
| 311 |
const __m512 x_minus_y = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y)); |
| 312 |
manhattan = _mm512_add_ps(manhattan, _mm512_abs_ps(x_minus_y)); |
| 313 |
x += 16; |
| 314 |
y += 16; |
| 315 |
} |
| 316 |
// Sum all floats in manhattan register. |
| 317 |
result = _mm512_reduce_add_ps(manhattan); |
| 318 |
} |
| 319 |
// Don't forget the remaining values. |
| 320 |
for (; i > 0; i--) { |
| 321 |
result += fabsf(*x - *y); |
| 322 |
x++; |
| 323 |
y++; |
| 324 |
} |
| 325 |
return result; |
| 326 |
} |
| 327 |
|
| 328 |
template<> |
| 329 |
inline float euclidean_distance<float>(const float* x, const float* y, int f) { |
| 330 |
float result=0; |
| 331 |
if (f > 15) { |
| 332 |
__m512 d = _mm512_setzero_ps(); |
| 333 |
for (; f > 15; f -= 16) { |
| 334 |
const __m512 diff = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y)); |
| 335 |
d = _mm512_fmadd_ps(diff, diff, d); |
| 336 |
x += 16; |
| 337 |
y += 16; |
| 338 |
} |
| 339 |
// Sum all floats in dot register. |
| 340 |
result = _mm512_reduce_add_ps(d); |
| 341 |
} |
| 342 |
// Don't forget the remaining values. |
| 343 |
for (; f > 0; f--) { |
| 344 |
float tmp = *x - *y; |
| 345 |
result += tmp * tmp; |
| 346 |
x++; |
| 347 |
y++; |
| 348 |
} |
| 349 |
return result; |
| 350 |
} |
| 351 |
|
| 352 |
#endif |
| 353 |
|
| 354 |
|
| 355 |
template<typename T> |
| 356 |
inline T get_norm(T* v, int f) { |
| 357 |
return sqrt(dot(v, v, f)); |
| 358 |
} |
| 359 |
|
| 360 |
template<typename T, typename Random, typename Distance, typename Node> |
| 361 |
inline void two_means(const vector<Node*>& nodes, int f, Random& random, bool cosine, Node* p, Node* q) { |
| 362 |
/* |
| 363 |
This algorithm is a huge heuristic. Empirically it works really well, but I |
| 364 |
can't motivate it well. The basic idea is to keep two centroids and assign |
| 365 |
points to either one of them. We weight each centroid by the number of points |
| 366 |
assigned to it, so to balance it. |
| 367 |
*/ |
| 368 |
static int iteration_steps = 200; |
| 369 |
size_t count = nodes.size(); |
| 370 |
|
| 371 |
size_t i = random.index(count); |
| 372 |
size_t j = random.index(count-1); |
| 373 |
j += (j >= i); // ensure that i != j |
| 374 |
|
| 375 |
Distance::template copy_node<T, Node>(p, nodes[i], f); |
| 376 |
Distance::template copy_node<T, Node>(q, nodes[j], f); |
| 377 |
|
| 378 |
if (cosine) { Distance::template normalize<T, Node>(p, f); Distance::template normalize<T, Node>(q, f); } |
| 379 |
Distance::init_node(p, f); |
| 380 |
Distance::init_node(q, f); |
| 381 |
|
| 382 |
int ic = 1, jc = 1; |
| 383 |
for (int l = 0; l < iteration_steps; l++) { |
| 384 |
size_t k = random.index(count); |
| 385 |
T di = ic * Distance::distance(p, nodes[k], f), |
| 386 |
dj = jc * Distance::distance(q, nodes[k], f); |
| 387 |
T norm = cosine ? get_norm(nodes[k]->v, f) : 1; |
| 388 |
if (!(norm > T(0))) { |
| 389 |
continue; |
| 390 |
} |
| 391 |
if (di < dj) { |
| 392 |
for (int z = 0; z < f; z++) |
| 393 |
p->v[z] = (p->v[z] * ic + nodes[k]->v[z] / norm) / (ic + 1); |
| 394 |
Distance::init_node(p, f); |
| 395 |
ic++; |
| 396 |
} else if (dj < di) { |
| 397 |
for (int z = 0; z < f; z++) |
| 398 |
q->v[z] = (q->v[z] * jc + nodes[k]->v[z] / norm) / (jc + 1); |
| 399 |
Distance::init_node(q, f); |
| 400 |
jc++; |
| 401 |
} |
| 402 |
} |
| 403 |
} |
| 404 |
} // namespace |
| 405 |
|
| 406 |
struct Base { |
| 407 |
template<typename T, typename S, typename Node> |
| 408 |
static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) { |
| 409 |
// Override this in specific metric structs below if you need to do any pre-processing |
| 410 |
// on the entire set of nodes passed into this index. |
| 411 |
} |
| 412 |
|
| 413 |
template<typename Node> |
| 414 |
static inline void zero_value(Node* dest) { |
| 415 |
// Initialize any fields that require sane defaults within this node. |
| 416 |
} |
| 417 |
|
| 418 |
template<typename T, typename Node> |
| 419 |
static inline void copy_node(Node* dest, const Node* source, const int f) { |
| 420 |
memcpy(dest->v, source->v, f * sizeof(T)); |
| 421 |
} |
| 422 |
|
| 423 |
template<typename T, typename Node> |
| 424 |
static inline void normalize(Node* node, int f) { |
| 425 |
T norm = get_norm(node->v, f); |
| 426 |
if (norm > 0) { |
| 427 |
for (int z = 0; z < f; z++) |
| 428 |
node->v[z] /= norm; |
| 429 |
} |
| 430 |
} |
| 431 |
}; |
| 432 |
|
| 433 |
struct Angular : Base { |
| 434 |
template<typename S, typename T> |
| 435 |
struct Node { |
| 436 |
/* |
| 437 |
* We store a binary tree where each node has two things |
| 438 |
* - A vector associated with it |
| 439 |
* - Two children |
| 440 |
* All nodes occupy the same amount of memory |
| 441 |
* All nodes with n_descendants == 1 are leaf nodes. |
| 442 |
* A memory optimization is that for nodes with 2 <= n_descendants <= K, |
| 443 |
* we skip the vector. Instead we store a list of all descendants. K is |
| 444 |
* determined by the number of items that fits in the space of the vector. |
| 445 |
* For nodes with n_descendants == 1 the vector is a data point. |
| 446 |
* For nodes with n_descendants > K the vector is the normal of the split plane. |
| 447 |
* Note that we can't really do sizeof(node<T>) because we cheat and allocate |
| 448 |
* more memory to be able to fit the vector outside |
| 449 |
*/ |
| 450 |
S n_descendants; |
| 451 |
union { |
| 452 |
S children[2]; // Will possibly store more than 2 |
| 453 |
T norm; |
| 454 |
}; |
| 455 |
T v[V_ARRAY_SIZE]; |
| 456 |
}; |
| 457 |
template<typename S, typename T> |
| 458 |
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { |
| 459 |
// want to calculate (a/|a| - b/|b|)^2 |
| 460 |
// = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b| |
| 461 |
// = 2 - 2cos |
| 462 |
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 |
| 463 |
T qq = y->norm ? y->norm : dot(y->v, y->v, f); |
| 464 |
T pq = dot(x->v, y->v, f); |
| 465 |
T ppqq = pp * qq; |
| 466 |
if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq); |
| 467 |
else return 2.0; // cos is 0 |
| 468 |
} |
| 469 |
template<typename S, typename T> |
| 470 |
static inline T margin(const Node<S, T>* n, const T* y, int f) { |
| 471 |
return dot(n->v, y, f); |
| 472 |
} |
| 473 |
template<typename S, typename T, typename Random> |
| 474 |
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { |
| 475 |
T dot = margin(n, y, f); |
| 476 |
if (dot != 0) |
| 477 |
return (dot > 0); |
| 478 |
else |
| 479 |
return (bool)random.flip(); |
| 480 |
} |
| 481 |
template<typename S, typename T, typename Random> |
| 482 |
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { |
| 483 |
Node<S, T>* p = (Node<S, T>*)alloca(s); |
| 484 |
Node<S, T>* q = (Node<S, T>*)alloca(s); |
| 485 |
two_means<T, Random, Angular, Node<S, T> >(nodes, f, random, true, p, q); |
| 486 |
for (int z = 0; z < f; z++) |
| 487 |
n->v[z] = p->v[z] - q->v[z]; |
| 488 |
Base::normalize<T, Node<S, T> >(n, f); |
| 489 |
} |
| 490 |
template<typename T> |
| 491 |
static inline T normalized_distance(T distance) { |
| 492 |
// Used when requesting distances from Python layer |
| 493 |
// Turns out sometimes the squared distance is -0.0 |
| 494 |
// so we have to make sure it's a positive number. |
| 495 |
return sqrt(std::max(distance, T(0))); |
| 496 |
} |
| 497 |
template<typename T> |
| 498 |
static inline T pq_distance(T distance, T margin, int child_nr) { |
| 499 |
if (child_nr == 0) |
| 500 |
margin = -margin; |
| 501 |
return std::min(distance, margin); |
| 502 |
} |
| 503 |
template<typename T> |
| 504 |
static inline T pq_initial_value() { |
| 505 |
return numeric_limits<T>::infinity(); |
| 506 |
} |
| 507 |
template<typename S, typename T> |
| 508 |
static inline void init_node(Node<S, T>* n, int f) { |
| 509 |
n->norm = dot(n->v, n->v, f); |
| 510 |
} |
| 511 |
static const char* name() { |
| 512 |
return "angular"; |
| 513 |
} |
| 514 |
}; |
| 515 |
|
| 516 |
|
| 517 |
struct DotProduct : Angular { |
| 518 |
template<typename S, typename T> |
| 519 |
struct Node { |
| 520 |
/* |
| 521 |
* This is an extension of the Angular node with an extra attribute for the scaled norm. |
| 522 |
*/ |
| 523 |
S n_descendants; |
| 524 |
S children[2]; // Will possibly store more than 2 |
| 525 |
T dot_factor; |
| 526 |
T v[V_ARRAY_SIZE]; |
| 527 |
}; |
| 528 |
|
| 529 |
static const char* name() { |
| 530 |
return "dot"; |
| 531 |
} |
| 532 |
template<typename S, typename T> |
| 533 |
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { |
| 534 |
return -dot(x->v, y->v, f); |
| 535 |
} |
| 536 |
|
| 537 |
template<typename Node> |
| 538 |
static inline void zero_value(Node* dest) { |
| 539 |
dest->dot_factor = 0; |
| 540 |
} |
| 541 |
|
| 542 |
template<typename S, typename T> |
| 543 |
static inline void init_node(Node<S, T>* n, int f) { |
| 544 |
} |
| 545 |
|
| 546 |
template<typename T, typename Node> |
| 547 |
static inline void copy_node(Node* dest, const Node* source, const int f) { |
| 548 |
memcpy(dest->v, source->v, f * sizeof(T)); |
| 549 |
dest->dot_factor = source->dot_factor; |
| 550 |
} |
| 551 |
|
| 552 |
template<typename S, typename T, typename Random> |
| 553 |
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { |
| 554 |
Node<S, T>* p = (Node<S, T>*)alloca(s); |
| 555 |
Node<S, T>* q = (Node<S, T>*)alloca(s); |
| 556 |
DotProduct::zero_value(p); |
| 557 |
DotProduct::zero_value(q); |
| 558 |
two_means<T, Random, DotProduct, Node<S, T> >(nodes, f, random, true, p, q); |
| 559 |
for (int z = 0; z < f; z++) |
| 560 |
n->v[z] = p->v[z] - q->v[z]; |
| 561 |
n->dot_factor = p->dot_factor - q->dot_factor; |
| 562 |
DotProduct::normalize<T, Node<S, T> >(n, f); |
| 563 |
} |
| 564 |
|
| 565 |
template<typename T, typename Node> |
| 566 |
static inline void normalize(Node* node, int f) { |
| 567 |
T norm = sqrt(dot(node->v, node->v, f) + pow(node->dot_factor, 2)); |
| 568 |
if (norm > 0) { |
| 569 |
for (int z = 0; z < f; z++) |
| 570 |
node->v[z] /= norm; |
| 571 |
node->dot_factor /= norm; |
| 572 |
} |
| 573 |
} |
| 574 |
|
| 575 |
template<typename S, typename T> |
| 576 |
static inline T margin(const Node<S, T>* n, const T* y, int f) { |
| 577 |
return dot(n->v, y, f) + (n->dot_factor * n->dot_factor); |
| 578 |
} |
| 579 |
|
| 580 |
template<typename S, typename T, typename Random> |
| 581 |
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { |
| 582 |
T dot = margin(n, y, f); |
| 583 |
if (dot != 0) |
| 584 |
return (dot > 0); |
| 585 |
else |
| 586 |
return (bool)random.flip(); |
| 587 |
} |
| 588 |
|
| 589 |
template<typename T> |
| 590 |
static inline T normalized_distance(T distance) { |
| 591 |
return -distance; |
| 592 |
} |
| 593 |
|
| 594 |
template<typename T, typename S, typename Node> |
| 595 |
static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) { |
| 596 |
// This uses a method from Microsoft Research for transforming inner product spaces to cosine/angular-compatible spaces. |
| 597 |
// (Bachrach et al., 2014, see https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/XboxInnerProduct.pdf) |
| 598 |
|
| 599 |
// Step one: compute the norm of each vector and store that in its extra dimension (f-1) |
| 600 |
for (S i = 0; i < node_count; i++) { |
| 601 |
Node* node = get_node_ptr<S, Node>(nodes, _s, i); |
| 602 |
T d = dot(node->v, node->v, f); |
| 603 |
T norm = d < 0 ? 0 : sqrt(d); |
| 604 |
node->dot_factor = norm; |
| 605 |
} |
| 606 |
|
| 607 |
// Step two: find the maximum norm |
| 608 |
T max_norm = 0; |
| 609 |
for (S i = 0; i < node_count; i++) { |
| 610 |
Node* node = get_node_ptr<S, Node>(nodes, _s, i); |
| 611 |
if (node->dot_factor > max_norm) { |
| 612 |
max_norm = node->dot_factor; |
| 613 |
} |
| 614 |
} |
| 615 |
|
| 616 |
// Step three: set each vector's extra dimension to sqrt(max_norm^2 - norm^2) |
| 617 |
for (S i = 0; i < node_count; i++) { |
| 618 |
Node* node = get_node_ptr<S, Node>(nodes, _s, i); |
| 619 |
T node_norm = node->dot_factor; |
| 620 |
T squared_norm_diff = pow(max_norm, static_cast<T>(2.0)) - pow(node_norm, static_cast<T>(2.0)); |
| 621 |
T dot_factor = squared_norm_diff < 0 ? 0 : sqrt(squared_norm_diff); |
| 622 |
|
| 623 |
node->dot_factor = dot_factor; |
| 624 |
} |
| 625 |
} |
| 626 |
}; |
| 627 |
|
| 628 |
struct Hamming : Base { |
| 629 |
template<typename S, typename T> |
| 630 |
struct Node { |
| 631 |
S n_descendants; |
| 632 |
S children[2]; |
| 633 |
T v[V_ARRAY_SIZE]; |
| 634 |
}; |
| 635 |
|
| 636 |
static const size_t max_iterations = 20; |
| 637 |
|
| 638 |
template<typename T> |
| 639 |
static inline T pq_distance(T distance, T margin, int child_nr) { |
| 640 |
return distance - (margin != (unsigned int) child_nr); |
| 641 |
} |
| 642 |
|
| 643 |
template<typename T> |
| 644 |
static inline T pq_initial_value() { |
| 645 |
return numeric_limits<T>::max(); |
| 646 |
} |
| 647 |
template<typename T> |
| 648 |
static inline int cole_popcount(T v) { |
| 649 |
// Note: Only used with MSVC 9, which lacks intrinsics and fails to |
| 650 |
// calculate std::bitset::count for v > 32bit. Uses the generalized |
| 651 |
// approach by Eric Cole. |
| 652 |
// See https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSet64 |
| 653 |
v = v - ((v >> 1) & (T)~(T)0/3); |
| 654 |
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); |
| 655 |
v = (v + (v >> 4)) & (T)~(T)0/255*15; |
| 656 |
return (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * 8; |
| 657 |
} |
| 658 |
template<typename S, typename T> |
| 659 |
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { |
| 660 |
size_t dist = 0; |
| 661 |
for (int i = 0; i < f; i++) { |
| 662 |
dist += popcount(x->v[i] ^ y->v[i]); |
| 663 |
} |
| 664 |
return dist; |
| 665 |
} |
| 666 |
template<typename S, typename T> |
| 667 |
static inline bool margin(const Node<S, T>* n, const T* y, int f) { |
| 668 |
static const size_t n_bits = sizeof(T) * 8; |
| 669 |
T chunk = n->v[0] / n_bits; |
| 670 |
return (y[chunk] & (static_cast<T>(1) << (n_bits - 1 - (n->v[0] % n_bits)))) != 0; |
| 671 |
} |
| 672 |
template<typename S, typename T, typename Random> |
| 673 |
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { |
| 674 |
return margin(n, y, f); |
| 675 |
} |
| 676 |
template<typename S, typename T, typename Random> |
| 677 |
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { |
| 678 |
size_t cur_size = 0; |
| 679 |
size_t i = 0; |
| 680 |
int dim = f * 8 * sizeof(T); |
| 681 |
for (; i < max_iterations; i++) { |
| 682 |
// choose random position to split at |
| 683 |
n->v[0] = random.index(dim); |
| 684 |
cur_size = 0; |
| 685 |
for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { |
| 686 |
if (margin(n, (*it)->v, f)) { |
| 687 |
cur_size++; |
| 688 |
} |
| 689 |
} |
| 690 |
if (cur_size > 0 && cur_size < nodes.size()) { |
| 691 |
break; |
| 692 |
} |
| 693 |
} |
| 694 |
// brute-force search for splitting coordinate |
| 695 |
if (i == max_iterations) { |
| 696 |
int j = 0; |
| 697 |
for (; j < dim; j++) { |
| 698 |
n->v[0] = j; |
| 699 |
cur_size = 0; |
| 700 |
for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { |
| 701 |
if (margin(n, (*it)->v, f)) { |
| 702 |
cur_size++; |
| 703 |
} |
| 704 |
} |
| 705 |
if (cur_size > 0 && cur_size < nodes.size()) { |
| 706 |
break; |
| 707 |
} |
| 708 |
} |
| 709 |
} |
| 710 |
} |
| 711 |
template<typename T> |
| 712 |
static inline T normalized_distance(T distance) { |
| 713 |
return distance; |
| 714 |
} |
| 715 |
template<typename S, typename T> |
| 716 |
static inline void init_node(Node<S, T>* n, int f) { |
| 717 |
} |
| 718 |
static const char* name() { |
| 719 |
return "hamming"; |
| 720 |
} |
| 721 |
}; |
| 722 |
|
| 723 |
|
| 724 |
struct Minkowski : Base { |
| 725 |
template<typename S, typename T> |
| 726 |
struct Node { |
| 727 |
S n_descendants; |
| 728 |
T a; // need an extra constant term to determine the offset of the plane |
| 729 |
S children[2]; |
| 730 |
T v[V_ARRAY_SIZE]; |
| 731 |
}; |
| 732 |
template<typename S, typename T> |
| 733 |
static inline T margin(const Node<S, T>* n, const T* y, int f) { |
| 734 |
return n->a + dot(n->v, y, f); |
| 735 |
} |
| 736 |
template<typename S, typename T, typename Random> |
| 737 |
static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { |
| 738 |
T dot = margin(n, y, f); |
| 739 |
if (dot != 0) |
| 740 |
return (dot > 0); |
| 741 |
else |
| 742 |
return (bool)random.flip(); |
| 743 |
} |
| 744 |
template<typename T> |
| 745 |
static inline T pq_distance(T distance, T margin, int child_nr) { |
| 746 |
if (child_nr == 0) |
| 747 |
margin = -margin; |
| 748 |
return std::min(distance, margin); |
| 749 |
} |
| 750 |
template<typename T> |
| 751 |
static inline T pq_initial_value() { |
| 752 |
return numeric_limits<T>::infinity(); |
| 753 |
} |
| 754 |
}; |
| 755 |
|
| 756 |
|
| 757 |
struct Euclidean : Minkowski { |
| 758 |
template<typename S, typename T> |
| 759 |
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { |
| 760 |
return euclidean_distance(x->v, y->v, f); |
| 761 |
} |
| 762 |
template<typename S, typename T, typename Random> |
| 763 |
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { |
| 764 |
Node<S, T>* p = (Node<S, T>*)alloca(s); |
| 765 |
Node<S, T>* q = (Node<S, T>*)alloca(s); |
| 766 |
two_means<T, Random, Euclidean, Node<S, T> >(nodes, f, random, false, p, q); |
| 767 |
|
| 768 |
for (int z = 0; z < f; z++) |
| 769 |
n->v[z] = p->v[z] - q->v[z]; |
| 770 |
Base::normalize<T, Node<S, T> >(n, f); |
| 771 |
n->a = 0.0; |
| 772 |
for (int z = 0; z < f; z++) |
| 773 |
n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2; |
| 774 |
} |
| 775 |
template<typename T> |
| 776 |
static inline T normalized_distance(T distance) { |
| 777 |
return sqrt(std::max(distance, T(0))); |
| 778 |
} |
| 779 |
template<typename S, typename T> |
| 780 |
static inline void init_node(Node<S, T>* n, int f) { |
| 781 |
} |
| 782 |
static const char* name() { |
| 783 |
return "euclidean"; |
| 784 |
} |
| 785 |
|
| 786 |
}; |
| 787 |
|
| 788 |
struct Manhattan : Minkowski { |
| 789 |
template<typename S, typename T> |
| 790 |
static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { |
| 791 |
return manhattan_distance(x->v, y->v, f); |
| 792 |
} |
| 793 |
template<typename S, typename T, typename Random> |
| 794 |
static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { |
| 795 |
Node<S, T>* p = (Node<S, T>*)alloca(s); |
| 796 |
Node<S, T>* q = (Node<S, T>*)alloca(s); |
| 797 |
two_means<T, Random, Manhattan, Node<S, T> >(nodes, f, random, false, p, q); |
| 798 |
|
| 799 |
for (int z = 0; z < f; z++) |
| 800 |
n->v[z] = p->v[z] - q->v[z]; |
| 801 |
Base::normalize<T, Node<S, T> >(n, f); |
| 802 |
n->a = 0.0; |
| 803 |
for (int z = 0; z < f; z++) |
| 804 |
n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2; |
| 805 |
} |
| 806 |
template<typename T> |
| 807 |
static inline T normalized_distance(T distance) { |
| 808 |
return std::max(distance, T(0)); |
| 809 |
} |
| 810 |
template<typename S, typename T> |
| 811 |
static inline void init_node(Node<S, T>* n, int f) { |
| 812 |
} |
| 813 |
static const char* name() { |
| 814 |
return "manhattan"; |
| 815 |
} |
| 816 |
}; |
| 817 |
|
| 818 |
template<typename S, typename T> |
| 819 |
class AnnoyIndexInterface { |
| 820 |
public: |
| 821 |
// Note that the methods with an **error argument will allocate memory and write the pointer to that string if error is non-NULL |
| 822 |
virtual ~AnnoyIndexInterface() {}; |
| 823 |
virtual bool add_item(S item, const T* w, char** error=NULL) = 0; |
| 824 |
virtual bool build(int q, int n_threads=-1, char** error=NULL) = 0; |
| 825 |
virtual bool unbuild(char** error=NULL) = 0; |
| 826 |
virtual bool save(const char* filename, bool prefault=false, char** error=NULL) = 0; |
| 827 |
virtual void unload() = 0; |
| 828 |
virtual bool load(const char* filename, bool prefault=false, char** error=NULL) = 0; |
| 829 |
virtual T get_distance(S i, S j) const = 0; |
| 830 |
virtual void get_nns_by_item(S item, size_t n, int search_k, vector<S>* result, vector<T>* distances) const = 0; |
| 831 |
virtual void get_nns_by_vector(const T* w, size_t n, int search_k, vector<S>* result, vector<T>* distances) const = 0; |
| 832 |
virtual S get_n_items() const = 0; |
| 833 |
virtual S get_n_trees() const = 0; |
| 834 |
virtual void verbose(bool v) = 0; |
| 835 |
virtual void get_item(S item, T* v) const = 0; |
| 836 |
virtual void set_seed(int q) = 0; |
| 837 |
virtual bool on_disk_build(const char* filename, char** error=NULL) = 0; |
| 838 |
}; |
| 839 |
|
| 840 |
template<typename S, typename T, typename Distance, typename Random, class ThreadedBuildPolicy> |
| 841 |
class AnnoyIndex : public AnnoyIndexInterface<S, T> { |
| 842 |
/* |
| 843 |
* We use random projection to build a forest of binary trees of all items. |
| 844 |
* Basically just split the hyperspace into two sides by a hyperplane, |
| 845 |
* then recursively split each of those subtrees etc. |
| 846 |
* We create a tree like this q times. The default q is determined automatically |
| 847 |
* in such a way that we at most use 2x as much memory as the vectors take. |
| 848 |
*/ |
| 849 |
public: |
| 850 |
typedef Distance D; |
| 851 |
typedef typename D::template Node<S, T> Node; |
| 852 |
|
| 853 |
protected: |
| 854 |
const int _f; |
| 855 |
size_t _s; |
| 856 |
S _n_items; |
| 857 |
void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate |
| 858 |
S _n_nodes; |
| 859 |
S _nodes_size; |
| 860 |
vector<S> _roots; |
| 861 |
S _K; |
| 862 |
bool _is_seeded; |
| 863 |
int _seed; |
| 864 |
bool _loaded; |
| 865 |
bool _verbose; |
| 866 |
int _fd; |
| 867 |
bool _on_disk; |
| 868 |
bool _built; |
| 869 |
public: |
| 870 |
|
| 871 |
AnnoyIndex(int f) : _f(f) { |
| 872 |
_s = offsetof(Node, v) + _f * sizeof(T); // Size of each node |
| 873 |
_verbose = false; |
| 874 |
_built = false; |
| 875 |
_K = (S) (((size_t) (_s - offsetof(Node, children))) / sizeof(S)); // Max number of descendants to fit into node |
| 876 |
reinitialize(); // Reset everything |
| 877 |
} |
| 878 |
~AnnoyIndex() { |
| 879 |
unload(); |
| 880 |
} |
| 881 |
|
| 882 |
int get_f() const { |
| 883 |
return _f; |
| 884 |
} |
| 885 |
|
| 886 |
bool add_item(S item, const T* w, char** error=NULL) { |
| 887 |
return add_item_impl(item, w, error); |
| 888 |
} |
| 889 |
|
| 890 |
template<typename W> |
| 891 |
bool add_item_impl(S item, const W& w, char** error=NULL) { |
| 892 |
if (_loaded) { |
| 893 |
set_error_from_string(error, "You can't add an item to a loaded index"); |
| 894 |
return false; |
| 895 |
} |
| 896 |
_allocate_size(item + 1); |
| 897 |
Node* n = _get(item); |
| 898 |
|
| 899 |
D::zero_value(n); |
| 900 |
|
| 901 |
n->children[0] = 0; |
| 902 |
n->children[1] = 0; |
| 903 |
n->n_descendants = 1; |
| 904 |
|
| 905 |
for (int z = 0; z < _f; z++) |
| 906 |
n->v[z] = w[z]; |
| 907 |
|
| 908 |
D::init_node(n, _f); |
| 909 |
|
| 910 |
if (item >= _n_items) |
| 911 |
_n_items = item + 1; |
| 912 |
|
| 913 |
return true; |
| 914 |
} |
| 915 |
|
| 916 |
bool on_disk_build(const char* file, char** error=NULL) { |
| 917 |
_on_disk = true; |
| 918 |
_fd = open(file, O_RDWR | O_CREAT | O_TRUNC, (int) 0600); |
| 919 |
if (_fd == -1) { |
| 920 |
set_error_from_errno(error, "Unable to open"); |
| 921 |
_fd = 0; |
| 922 |
return false; |
| 923 |
} |
| 924 |
_nodes_size = 1; |
| 925 |
if (ftruncate(_fd, FTRUNCATE_SIZE(_s) * FTRUNCATE_SIZE(_nodes_size)) == -1) { |
| 926 |
set_error_from_errno(error, "Unable to truncate"); |
| 927 |
return false; |
| 928 |
} |
| 929 |
#ifdef MAP_POPULATE |
| 930 |
_nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0); |
| 931 |
#else |
| 932 |
_nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0); |
| 933 |
#endif |
| 934 |
return true; |
| 935 |
} |
| 936 |
|
| 937 |
bool build(int q, int n_threads=-1, char** error=NULL) { |
| 938 |
if (_loaded) { |
| 939 |
set_error_from_string(error, "You can't build a loaded index"); |
| 940 |
return false; |
| 941 |
} |
| 942 |
|
| 943 |
if (_built) { |
| 944 |
set_error_from_string(error, "You can't build a built index"); |
| 945 |
return false; |
| 946 |
} |
| 947 |
|
| 948 |
D::template preprocess<T, S, Node>(_nodes, _s, _n_items, _f); |
| 949 |
|
| 950 |
_n_nodes = _n_items; |
| 951 |
|
| 952 |
ThreadedBuildPolicy::template build<S, T>(this, q, n_threads); |
| 953 |
|
| 954 |
// Also, copy the roots into the last segment of the array |
| 955 |
// This way we can load them faster without reading the whole file |
| 956 |
_allocate_size(_n_nodes + (S)_roots.size()); |
| 957 |
for (size_t i = 0; i < _roots.size(); i++) |
| 958 |
memcpy(_get(_n_nodes + (S)i), _get(_roots[i]), _s); |
| 959 |
_n_nodes += _roots.size(); |
| 960 |
|
| 961 |
if (_verbose) showUpdate("has %d nodes\n", _n_nodes); |
| 962 |
|
| 963 |
if (_on_disk) { |
| 964 |
if (!remap_memory_and_truncate(&_nodes, _fd, |
| 965 |
static_cast<size_t>(_s) * static_cast<size_t>(_nodes_size), |
| 966 |
static_cast<size_t>(_s) * static_cast<size_t>(_n_nodes))) { |
| 967 |
// TODO: this probably creates an index in a corrupt state... not sure what to do |
| 968 |
set_error_from_errno(error, "Unable to truncate"); |
| 969 |
return false; |
| 970 |
} |
| 971 |
_nodes_size = _n_nodes; |
| 972 |
} |
| 973 |
_built = true; |
| 974 |
return true; |
| 975 |
} |
| 976 |
|
| 977 |
bool unbuild(char** error=NULL) { |
| 978 |
if (_loaded) { |
| 979 |
set_error_from_string(error, "You can't unbuild a loaded index"); |
| 980 |
return false; |
| 981 |
} |
| 982 |
|
| 983 |
_roots.clear(); |
| 984 |
_n_nodes = _n_items; |
| 985 |
_built = false; |
| 986 |
|
| 987 |
return true; |
| 988 |
} |
| 989 |
|
| 990 |
bool save(const char* filename, bool prefault=false, char** error=NULL) { |
| 991 |
if (!_built) { |
| 992 |
set_error_from_string(error, "You can't save an index that hasn't been built"); |
| 993 |
return false; |
| 994 |
} |
| 995 |
if (_on_disk) { |
| 996 |
return true; |
| 997 |
} else { |
| 998 |
// Delete file if it already exists (See issue #335) |
| 999 |
unlink(filename); |
| 1000 |
|
| 1001 |
FILE *f = fopen(filename, "wb"); |
| 1002 |
if (f == NULL) { |
| 1003 |
set_error_from_errno(error, "Unable to open"); |
| 1004 |
return false; |
| 1005 |
} |
| 1006 |
|
| 1007 |
if (fwrite(_nodes, _s, _n_nodes, f) != (size_t) _n_nodes) { |
| 1008 |
set_error_from_errno(error, "Unable to write"); |
| 1009 |
return false; |
| 1010 |
} |
| 1011 |
|
| 1012 |
if (fclose(f) == EOF) { |
| 1013 |
set_error_from_errno(error, "Unable to close"); |
| 1014 |
return false; |
| 1015 |
} |
| 1016 |
|
| 1017 |
unload(); |
| 1018 |
return load(filename, prefault, error); |
| 1019 |
} |
| 1020 |
} |
| 1021 |
|
| 1022 |
void reinitialize() { |
| 1023 |
_fd = 0; |
| 1024 |
_nodes = NULL; |
| 1025 |
_loaded = false; |
| 1026 |
_n_items = 0; |
| 1027 |
_n_nodes = 0; |
| 1028 |
_nodes_size = 0; |
| 1029 |
_on_disk = false; |
| 1030 |
_is_seeded = false; |
| 1031 |
_roots.clear(); |
| 1032 |
} |
| 1033 |
|
| 1034 |
void unload() { |
| 1035 |
if (_on_disk && _fd) { |
| 1036 |
close(_fd); |
| 1037 |
munmap(_nodes, _s * _nodes_size); |
| 1038 |
} else { |
| 1039 |
if (_fd) { |
| 1040 |
// we have mmapped data |
| 1041 |
close(_fd); |
| 1042 |
munmap(_nodes, _n_nodes * _s); |
| 1043 |
} else if (_nodes) { |
| 1044 |
// We have heap allocated data |
| 1045 |
free(_nodes); |
| 1046 |
} |
| 1047 |
} |
| 1048 |
reinitialize(); |
| 1049 |
if (_verbose) showUpdate("unloaded\n"); |
| 1050 |
} |
| 1051 |
|
| 1052 |
bool load(const char* filename, bool prefault=false, char** error=NULL) { |
| 1053 |
_fd = open(filename, O_RDONLY, (int)0400); |
| 1054 |
if (_fd == -1) { |
| 1055 |
set_error_from_errno(error, "Unable to open"); |
| 1056 |
_fd = 0; |
| 1057 |
return false; |
| 1058 |
} |
| 1059 |
off_t size = lseek_getsize(_fd); |
| 1060 |
if (size == -1) { |
| 1061 |
set_error_from_errno(error, "Unable to get size"); |
| 1062 |
return false; |
| 1063 |
} else if (size == 0) { |
| 1064 |
set_error_from_errno(error, "Size of file is zero"); |
| 1065 |
return false; |
| 1066 |
} else if (size % _s) { |
| 1067 |
// Something is fishy with this index! |
| 1068 |
set_error_from_errno(error, "Index size is not a multiple of vector size. Ensure you are opening using the same metric you used to create the index."); |
| 1069 |
return false; |
| 1070 |
} |
| 1071 |
|
| 1072 |
int flags = MAP_SHARED; |
| 1073 |
if (prefault) { |
| 1074 |
#ifdef MAP_POPULATE |
| 1075 |
flags |= MAP_POPULATE; |
| 1076 |
#else |
| 1077 |
showUpdate("prefault is set to true, but MAP_POPULATE is not defined on this platform"); |
| 1078 |
#endif |
| 1079 |
} |
| 1080 |
_nodes = (Node*)mmap(0, size, PROT_READ, flags, _fd, 0); |
| 1081 |
_n_nodes = (S)(size / _s); |
| 1082 |
|
| 1083 |
// Find the roots by scanning the end of the file and taking the nodes with most descendants |
| 1084 |
_roots.clear(); |
| 1085 |
S m = -1; |
| 1086 |
for (S i = _n_nodes - 1; i >= 0; i--) { |
| 1087 |
S k = _get(i)->n_descendants; |
| 1088 |
if (m == -1 || k == m) { |
| 1089 |
_roots.push_back(i); |
| 1090 |
m = k; |
| 1091 |
} else { |
| 1092 |
break; |
| 1093 |
} |
| 1094 |
} |
| 1095 |
// hacky fix: since the last root precedes the copy of all roots, delete it |
| 1096 |
if (_roots.size() > 1 && _get(_roots.front())->children[0] == _get(_roots.back())->children[0]) |
| 1097 |
_roots.pop_back(); |
| 1098 |
_loaded = true; |
| 1099 |
_built = true; |
| 1100 |
_n_items = m; |
| 1101 |
if (_verbose) showUpdate("found %lu roots with degree %d\n", _roots.size(), m); |
| 1102 |
return true; |
| 1103 |
} |
| 1104 |
|
| 1105 |
T get_distance(S i, S j) const { |
| 1106 |
return D::normalized_distance(D::distance(_get(i), _get(j), _f)); |
| 1107 |
} |
| 1108 |
|
| 1109 |
void get_nns_by_item(S item, size_t n, int search_k, vector<S>* result, vector<T>* distances) const { |
| 1110 |
// TODO: handle OOB |
| 1111 |
const Node* m = _get(item); |
| 1112 |
_get_all_nns(m->v, n, search_k, result, distances); |
| 1113 |
} |
| 1114 |
|
| 1115 |
void get_nns_by_vector(const T* w, size_t n, int search_k, vector<S>* result, vector<T>* distances) const { |
| 1116 |
_get_all_nns(w, n, search_k, result, distances); |
| 1117 |
} |
| 1118 |
|
| 1119 |
S get_n_items() const { |
| 1120 |
return _n_items; |
| 1121 |
} |
| 1122 |
|
| 1123 |
S get_n_trees() const { |
| 1124 |
return (S)_roots.size(); |
| 1125 |
} |
| 1126 |
|
| 1127 |
void verbose(bool v) { |
| 1128 |
_verbose = v; |
| 1129 |
} |
| 1130 |
|
| 1131 |
void get_item(S item, T* v) const { |
| 1132 |
// TODO: handle OOB |
| 1133 |
Node* m = _get(item); |
| 1134 |
memcpy(v, m->v, (_f) * sizeof(T)); |
| 1135 |
} |
| 1136 |
|
| 1137 |
void set_seed(int seed) { |
| 1138 |
_is_seeded = true; |
| 1139 |
_seed = seed; |
| 1140 |
} |
| 1141 |
|
| 1142 |
void thread_build(int q, int thread_idx, ThreadedBuildPolicy& threaded_build_policy) { |
| 1143 |
Random _random; |
| 1144 |
// Each thread needs its own seed, otherwise each thread would be building the same tree(s) |
| 1145 |
int seed = _is_seeded ? _seed + thread_idx : thread_idx; |
| 1146 |
_random.set_seed(seed); |
| 1147 |
|
| 1148 |
vector<S> thread_roots; |
| 1149 |
while (1) { |
| 1150 |
if (q == -1) { |
| 1151 |
threaded_build_policy.lock_n_nodes(); |
| 1152 |
if (_n_nodes >= 2 * _n_items) { |
| 1153 |
threaded_build_policy.unlock_n_nodes(); |
| 1154 |
break; |
| 1155 |
} |
| 1156 |
threaded_build_policy.unlock_n_nodes(); |
| 1157 |
} else { |
| 1158 |
if (thread_roots.size() >= (size_t)q) { |
| 1159 |
break; |
| 1160 |
} |
| 1161 |
} |
| 1162 |
|
| 1163 |
if (_verbose) showUpdate("pass %zd...\n", thread_roots.size()); |
| 1164 |
|
| 1165 |
vector<S> indices; |
| 1166 |
threaded_build_policy.lock_shared_nodes(); |
| 1167 |
for (S i = 0; i < _n_items; i++) { |
| 1168 |
if (_get(i)->n_descendants >= 1) { // Issue #223 |
| 1169 |
indices.push_back(i); |
| 1170 |
} |
| 1171 |
} |
| 1172 |
threaded_build_policy.unlock_shared_nodes(); |
| 1173 |
|
| 1174 |
thread_roots.push_back(_make_tree(indices, true, _random, threaded_build_policy)); |
| 1175 |
} |
| 1176 |
|
| 1177 |
threaded_build_policy.lock_roots(); |
| 1178 |
_roots.insert(_roots.end(), thread_roots.begin(), thread_roots.end()); |
| 1179 |
threaded_build_policy.unlock_roots(); |
| 1180 |
} |
| 1181 |
|
| 1182 |
protected: |
| 1183 |
void _reallocate_nodes(S n) { |
| 1184 |
const double reallocation_factor = 1.3; |
| 1185 |
S new_nodes_size = std::max(n, (S) ((_nodes_size + 1) * reallocation_factor)); |
| 1186 |
void *old = _nodes; |
| 1187 |
|
| 1188 |
if (_on_disk) { |
| 1189 |
if (!remap_memory_and_truncate(&_nodes, _fd, |
| 1190 |
static_cast<size_t>(_s) * static_cast<size_t>(_nodes_size), |
| 1191 |
static_cast<size_t>(_s) * static_cast<size_t>(new_nodes_size)) && |
| 1192 |
_verbose) |
| 1193 |
showUpdate("File truncation error\n"); |
| 1194 |
} else { |
| 1195 |
_nodes = realloc(_nodes, _s * new_nodes_size); |
| 1196 |
memset((char *) _nodes + (_nodes_size * _s) / sizeof(char), 0, (new_nodes_size - _nodes_size) * _s); |
| 1197 |
} |
| 1198 |
|
| 1199 |
_nodes_size = new_nodes_size; |
| 1200 |
if (_verbose) showUpdate("Reallocating to %d nodes: old_address=%p, new_address=%p\n", new_nodes_size, old, _nodes); |
| 1201 |
} |
| 1202 |
|
| 1203 |
void _allocate_size(S n, ThreadedBuildPolicy& threaded_build_policy) { |
| 1204 |
if (n > _nodes_size) { |
| 1205 |
threaded_build_policy.lock_nodes(); |
| 1206 |
_reallocate_nodes(n); |
| 1207 |
threaded_build_policy.unlock_nodes(); |
| 1208 |
} |
| 1209 |
} |
| 1210 |
|
| 1211 |
void _allocate_size(S n) { |
| 1212 |
if (n > _nodes_size) { |
| 1213 |
_reallocate_nodes(n); |
| 1214 |
} |
| 1215 |
} |
| 1216 |
|
| 1217 |
Node* _get(const S i) const { |
| 1218 |
return get_node_ptr<S, Node>(_nodes, _s, i); |
| 1219 |
} |
| 1220 |
|
| 1221 |
double _split_imbalance(const vector<S>& left_indices, const vector<S>& right_indices) { |
| 1222 |
double ls = (float)left_indices.size(); |
| 1223 |
double rs = (float)right_indices.size(); |
| 1224 |
float f = ls / (ls + rs + 1e-9); // Avoid 0/0 |
| 1225 |
return std::max(f, 1-f); |
| 1226 |
} |
| 1227 |
|
| 1228 |
S _make_tree(const vector<S>& indices, bool is_root, Random& _random, ThreadedBuildPolicy& threaded_build_policy) { |
| 1229 |
// The basic rule is that if we have <= _K items, then it's a leaf node, otherwise it's a split node. |
| 1230 |
// There's some regrettable complications caused by the problem that root nodes have to be "special": |
| 1231 |
// 1. We identify root nodes by the arguable logic that _n_items == n->n_descendants, regardless of how many descendants they actually have |
| 1232 |
// 2. Root nodes with only 1 child need to be a "dummy" parent |
| 1233 |
// 3. Due to the _n_items "hack", we need to be careful with the cases where _n_items <= _K or _n_items > _K |
| 1234 |
if (indices.size() == 1 && !is_root) |
| 1235 |
return indices[0]; |
| 1236 |
|
| 1237 |
if (indices.size() <= (size_t)_K && (!is_root || (size_t)_n_items <= (size_t)_K || indices.size() == 1)) { |
| 1238 |
threaded_build_policy.lock_n_nodes(); |
| 1239 |
_allocate_size(_n_nodes + 1, threaded_build_policy); |
| 1240 |
S item = _n_nodes++; |
| 1241 |
threaded_build_policy.unlock_n_nodes(); |
| 1242 |
|
| 1243 |
threaded_build_policy.lock_shared_nodes(); |
| 1244 |
Node* m = _get(item); |
| 1245 |
m->n_descendants = is_root ? _n_items : (S)indices.size(); |
| 1246 |
|
| 1247 |
// Using std::copy instead of a loop seems to resolve issues #3 and #13, |
| 1248 |
// probably because gcc 4.8 goes overboard with optimizations. |
| 1249 |
// Using memcpy instead of std::copy for MSVC compatibility. #235 |
| 1250 |
// Only copy when necessary to avoid crash in MSVC 9. #293 |
| 1251 |
if (!indices.empty()) |
| 1252 |
memcpy(m->children, &indices[0], indices.size() * sizeof(S)); |
| 1253 |
|
| 1254 |
threaded_build_policy.unlock_shared_nodes(); |
| 1255 |
return item; |
| 1256 |
} |
| 1257 |
|
| 1258 |
threaded_build_policy.lock_shared_nodes(); |
| 1259 |
vector<Node*> children; |
| 1260 |
for (size_t i = 0; i < indices.size(); i++) { |
| 1261 |
S j = indices[i]; |
| 1262 |
Node* n = _get(j); |
| 1263 |
if (n) |
| 1264 |
children.push_back(n); |
| 1265 |
} |
| 1266 |
|
| 1267 |
vector<S> children_indices[2]; |
| 1268 |
Node* m = (Node*)alloca(_s); |
| 1269 |
|
| 1270 |
for (int attempt = 0; attempt < 3; attempt++) { |
| 1271 |
children_indices[0].clear(); |
| 1272 |
children_indices[1].clear(); |
| 1273 |
D::create_split(children, _f, _s, _random, m); |
| 1274 |
|
| 1275 |
for (size_t i = 0; i < indices.size(); i++) { |
| 1276 |
S j = indices[i]; |
| 1277 |
Node* n = _get(j); |
| 1278 |
if (n) { |
| 1279 |
bool side = D::side(m, n->v, _f, _random); |
| 1280 |
children_indices[side].push_back(j); |
| 1281 |
} else { |
| 1282 |
showUpdate("No node for index %d?\n", j); |
| 1283 |
} |
| 1284 |
} |
| 1285 |
|
| 1286 |
if (_split_imbalance(children_indices[0], children_indices[1]) < 0.95) |
| 1287 |
break; |
| 1288 |
} |
| 1289 |
threaded_build_policy.unlock_shared_nodes(); |
| 1290 |
|
| 1291 |
// If we didn't find a hyperplane, just randomize sides as a last option |
| 1292 |
while (_split_imbalance(children_indices[0], children_indices[1]) > 0.99) { |
| 1293 |
if (_verbose) |
| 1294 |
showUpdate("\tNo hyperplane found (left has %ld children, right has %ld children)\n", |
| 1295 |
children_indices[0].size(), children_indices[1].size()); |
| 1296 |
|
| 1297 |
children_indices[0].clear(); |
| 1298 |
children_indices[1].clear(); |
| 1299 |
|
| 1300 |
// Set the vector to 0.0 |
| 1301 |
for (int z = 0; z < _f; z++) |
| 1302 |
m->v[z] = 0; |
| 1303 |
|
| 1304 |
for (size_t i = 0; i < indices.size(); i++) { |
| 1305 |
S j = indices[i]; |
| 1306 |
// Just randomize... |
| 1307 |
children_indices[_random.flip()].push_back(j); |
| 1308 |
} |
| 1309 |
} |
| 1310 |
|
| 1311 |
int flip = (children_indices[0].size() > children_indices[1].size()); |
| 1312 |
|
| 1313 |
m->n_descendants = is_root ? _n_items : (S)indices.size(); |
| 1314 |
for (int side = 0; side < 2; side++) { |
| 1315 |
// run _make_tree for the smallest child first (for cache locality) |
| 1316 |
m->children[side^flip] = _make_tree(children_indices[side^flip], false, _random, threaded_build_policy); |
| 1317 |
} |
| 1318 |
|
| 1319 |
threaded_build_policy.lock_n_nodes(); |
| 1320 |
_allocate_size(_n_nodes + 1, threaded_build_policy); |
| 1321 |
S item = _n_nodes++; |
| 1322 |
threaded_build_policy.unlock_n_nodes(); |
| 1323 |
|
| 1324 |
threaded_build_policy.lock_shared_nodes(); |
| 1325 |
memcpy(_get(item), m, _s); |
| 1326 |
threaded_build_policy.unlock_shared_nodes(); |
| 1327 |
|
| 1328 |
return item; |
| 1329 |
} |
| 1330 |
|
| 1331 |
void _get_all_nns(const T* v, size_t n, int search_k, vector<S>* result, vector<T>* distances) const { |
| 1332 |
Node* v_node = (Node *)alloca(_s); |
| 1333 |
D::template zero_value<Node>(v_node); |
| 1334 |
memcpy(v_node->v, v, sizeof(T) * _f); |
| 1335 |
D::init_node(v_node, _f); |
| 1336 |
|
| 1337 |
std::priority_queue<pair<T, S> > q; |
| 1338 |
|
| 1339 |
if (search_k == -1) { |
| 1340 |
search_k = n * _roots.size(); |
| 1341 |
} |
| 1342 |
|
| 1343 |
for (size_t i = 0; i < _roots.size(); i++) { |
| 1344 |
q.push(make_pair(Distance::template pq_initial_value<T>(), _roots[i])); |
| 1345 |
} |
| 1346 |
|
| 1347 |
std::vector<S> nns; |
| 1348 |
while (nns.size() < (size_t)search_k && !q.empty()) { |
| 1349 |
const pair<T, S>& top = q.top(); |
| 1350 |
T d = top.first; |
| 1351 |
S i = top.second; |
| 1352 |
Node* nd = _get(i); |
| 1353 |
q.pop(); |
| 1354 |
if (nd->n_descendants == 1 && i < _n_items) { |
| 1355 |
nns.push_back(i); |
| 1356 |
} else if (nd->n_descendants <= _K) { |
| 1357 |
const S* dst = nd->children; |
| 1358 |
nns.insert(nns.end(), dst, &dst[nd->n_descendants]); |
| 1359 |
} else { |
| 1360 |
T margin = D::margin(nd, v, _f); |
| 1361 |
q.push(make_pair(D::pq_distance(d, margin, 1), static_cast<S>(nd->children[1]))); |
| 1362 |
q.push(make_pair(D::pq_distance(d, margin, 0), static_cast<S>(nd->children[0]))); |
| 1363 |
} |
| 1364 |
} |
| 1365 |
|
| 1366 |
// Get distances for all items |
| 1367 |
// To avoid calculating distance multiple times for any items, sort by id |
| 1368 |
std::sort(nns.begin(), nns.end()); |
| 1369 |
vector<pair<T, S> > nns_dist; |
| 1370 |
S last = -1; |
| 1371 |
for (size_t i = 0; i < nns.size(); i++) { |
| 1372 |
S j = nns[i]; |
| 1373 |
if (j == last) |
| 1374 |
continue; |
| 1375 |
last = j; |
| 1376 |
if (_get(j)->n_descendants == 1) // This is only to guard a really obscure case, #284 |
| 1377 |
nns_dist.push_back(make_pair(D::distance(v_node, _get(j), _f), j)); |
| 1378 |
} |
| 1379 |
|
| 1380 |
size_t m = nns_dist.size(); |
| 1381 |
size_t p = n < m ? n : m; // Return this many items |
| 1382 |
std::partial_sort(nns_dist.begin(), nns_dist.begin() + p, nns_dist.end()); |
| 1383 |
for (size_t i = 0; i < p; i++) { |
| 1384 |
if (distances) |
| 1385 |
distances->push_back(D::normalized_distance(nns_dist[i].first)); |
| 1386 |
result->push_back(nns_dist[i].second); |
| 1387 |
} |
| 1388 |
} |
| 1389 |
}; |
| 1390 |
|
| 1391 |
class AnnoyIndexSingleThreadedBuildPolicy { |
| 1392 |
public: |
| 1393 |
template<typename S, typename T, typename D, typename Random> |
| 1394 |
static void build(AnnoyIndex<S, T, D, Random, AnnoyIndexSingleThreadedBuildPolicy>* annoy, int q, int n_threads) { |
| 1395 |
AnnoyIndexSingleThreadedBuildPolicy threaded_build_policy; |
| 1396 |
annoy->thread_build(q, 0, threaded_build_policy); |
| 1397 |
} |
| 1398 |
|
| 1399 |
void lock_n_nodes() {} |
| 1400 |
void unlock_n_nodes() {} |
| 1401 |
|
| 1402 |
void lock_nodes() {} |
| 1403 |
void unlock_nodes() {} |
| 1404 |
|
| 1405 |
void lock_shared_nodes() {} |
| 1406 |
void unlock_shared_nodes() {} |
| 1407 |
|
| 1408 |
void lock_roots() {} |
| 1409 |
void unlock_roots() {} |
| 1410 |
}; |
| 1411 |
|
| 1412 |
#ifdef ANNOYLIB_MULTITHREADED_BUILD |
| 1413 |
class AnnoyIndexMultiThreadedBuildPolicy { |
| 1414 |
private: |
| 1415 |
std::shared_timed_mutex nodes_mutex; |
| 1416 |
std::mutex n_nodes_mutex; |
| 1417 |
std::mutex roots_mutex; |
| 1418 |
|
| 1419 |
public: |
| 1420 |
template<typename S, typename T, typename D, typename Random> |
| 1421 |
static void build(AnnoyIndex<S, T, D, Random, AnnoyIndexMultiThreadedBuildPolicy>* annoy, int q, int n_threads) { |
| 1422 |
AnnoyIndexMultiThreadedBuildPolicy threaded_build_policy; |
| 1423 |
if (n_threads == -1) { |
| 1424 |
// If the hardware_concurrency() value is not well defined or not computable, it returns 0. |
| 1425 |
// We guard against this by using at least 1 thread. |
| 1426 |
n_threads = std::max(1, (int)std::thread::hardware_concurrency()); |
| 1427 |
} |
| 1428 |
|
| 1429 |
vector<std::thread> threads(n_threads); |
| 1430 |
|
| 1431 |
for (int thread_idx = 0; thread_idx < n_threads; thread_idx++) { |
| 1432 |
int trees_per_thread = q == -1 ? -1 : (int)floor((q + thread_idx) / n_threads); |
| 1433 |
|
| 1434 |
threads[thread_idx] = std::thread( |
| 1435 |
&AnnoyIndex<S, T, D, Random, AnnoyIndexMultiThreadedBuildPolicy>::thread_build, |
| 1436 |
annoy, |
| 1437 |
trees_per_thread, |
| 1438 |
thread_idx, |
| 1439 |
std::ref(threaded_build_policy) |
| 1440 |
); |
| 1441 |
} |
| 1442 |
|
| 1443 |
for (auto& thread : threads) { |
| 1444 |
thread.join(); |
| 1445 |
} |
| 1446 |
} |
| 1447 |
|
| 1448 |
void lock_n_nodes() { |
| 1449 |
n_nodes_mutex.lock(); |
| 1450 |
} |
| 1451 |
void unlock_n_nodes() { |
| 1452 |
n_nodes_mutex.unlock(); |
| 1453 |
} |
| 1454 |
|
| 1455 |
void lock_nodes() { |
| 1456 |
nodes_mutex.lock(); |
| 1457 |
} |
| 1458 |
void unlock_nodes() { |
| 1459 |
nodes_mutex.unlock(); |
| 1460 |
} |
| 1461 |
|
| 1462 |
void lock_shared_nodes() { |
| 1463 |
nodes_mutex.lock_shared(); |
| 1464 |
} |
| 1465 |
void unlock_shared_nodes() { |
| 1466 |
nodes_mutex.unlock_shared(); |
| 1467 |
} |
| 1468 |
|
| 1469 |
void lock_roots() { |
| 1470 |
roots_mutex.lock(); |
| 1471 |
} |
| 1472 |
void unlock_roots() { |
| 1473 |
roots_mutex.unlock(); |
| 1474 |
} |
| 1475 |
}; |
| 1476 |
#endif |
| 1477 |
|
| 1478 |
#endif |
| 1479 |
// vim: tabstop=2 shiftwidth=2 |