Faiss

- Main Page
- Namespaces
- Classes
- Files

- File List

All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
/data/users/matthijs/github_faiss/faiss/utils.h
1
2 /**
3 * Copyright (c) 2015-present, Facebook, Inc.
4 * All rights reserved.
5 *
6 * This source code is licensed under the CC-by-NC license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10 /** Copyright 2004-present Facebook. All Rights Reserved
11 * -*- c++ -*-
12 *
13 * A few utilitary functions for similarity search:
14 * - random generators
15 * - optimized exhaustive distance and knn search functions
16 * - some functions reimplemented from torch for speed
17 */
18
19 #ifndef FAISS_utils_h
20 #define FAISS_utils_h
21
22 #include <stdint.h>
23 // for the random data struct
24 #include <cstdlib>
25
26 #include "Heap.h"
27
28
29 namespace faiss {
30
31
32 /**************************************************
33 * Get some stats about the system
34 **************************************************/
35
36
37 /// ms elapsed since some arbitrary epoch
38 double getmillisecs ();
39
40 /// get current RSS usage in kB
41 size_t get_mem_usage_kb ();
42
43
44 /**************************************************
45 * Random data generation functions
46 **************************************************/
47
48 /// random generator that can be used in multithreaded contexts
49 struct RandomGenerator {
50
51 #ifdef __linux__
52 char rand_state [8];
53 struct random_data rand_data;
54 #elif __APPLE__
55 unsigned rand_state;
56 #endif
57
58 /// random 31-bit positive integer
59 int rand_int ();
60
61 /// random long < 2 ^ 62
62 long rand_long ();
63
64 /// generate random number between 0 and max-1
65 int rand_int (int max);
66
67 /// between 0 and 1
68 float rand_float ();
69
70
71 double rand_double ();
72
73 /// initialize
74 explicit RandomGenerator (long seed = 1234);
75
76 /// default copy constructor messes up pointer in rand_data
77 RandomGenerator (const RandomGenerator & other);
78
79 };
80
81 /* Generate an array of uniform random floats / multi-threaded implementation */
82 void float_rand (float * x, size_t n, long seed);
83 void float_randn (float * x, size_t n, long seed);
84 void long_rand (long * x, size_t n, long seed);
85 void byte_rand (uint8_t * x, size_t n, long seed);
86
87 /* random permutation */
88 void rand_perm (int * perm, size_t n, long seed);
89
90
91 /*********************************************************
92 * Optimized distance/norm/inner prod computations
93 *********************************************************/
94
95
96 /// Squared L2 distance between two vectors
97 float fvec_L2sqr (
98 const float * x,
99 const float * y,
100 size_t d);
101
102 /* SSE-implementation of inner product and L2 distance */
103 float fvec_inner_product (
104 const float * x,
105 const float * y,
106 size_t d);
107
108
109 /// a balanced assignment has a IF of 1
110 double imbalance_factor (int n, int k, const long *assign);
111
112 /// same, takes a histogram as input
113 double imbalance_factor (int k, const int *hist);
114
115 /** Compute pairwise distances between sets of vectors
116 *
117 * @param d dimension of the vectors
118 * @param nq nb of query vectors
119 * @param nb nb of database vectors
120 * @param xq query vectors (size nq * d)
121 * @param xb database vectros (size nb * d)
122 * @param dis output distances (size nq * nb)
123 * @param ldq,ldb, ldd strides for the matrices
124 */
125 void pairwise_L2sqr (long d,
126 long nq, const float *xq,
127 long nb, const float *xb,
128 float *dis,
129 long ldq = -1, long ldb = -1, long ldd = -1);
130
131
132 /* compute the inner product between nx vectors x and one y */
133 void fvec_inner_products_ny (
134 float * ip, /* output inner product */
135 const float * x,
136 const float * y,
137 size_t d, size_t ny);
138
139 /* compute ny square L2 distance bewteen x and a set of contiguous y vectors */
140 void fvec_L2sqr_ny (
141 float * __restrict dis,
142 const float * x,
143 const float * y,
144 size_t d, size_t ny);
145
146
147 /** squared norm of a vector */
148 float fvec_norm_L2sqr (const float * x,
149 size_t d);
150
151 /** compute the L2 norms for a set of vectors
152 *
153 * @param ip output norms, size nx
154 * @param x set of vectors, size nx * d
155 */
156 void fvec_norms_L2 (float * ip, const float * x, size_t d, size_t nx);
157
158 /// same as fvec_norms_L2, but computes square norms
159 void fvec_norms_L2sqr (float * ip, const float * x, size_t d, size_t nx);
160
161 /* L2-renormalize a set of vector. Nothing done if the vector is 0-normed */
162 void fvec_renorm_L2 (size_t d, size_t nx, float * x);
163
164
165 /* This function exists because the Torch counterpart is extremly slow
166 (not multi-threaded + unexpected overhead even in single thread).
167 It is here to implement the usual property |x-y|^2=|x|^2+|y|^2-2<x|y> */
168 void inner_product_to_L2sqr (float * __restrict dis,
169 const float * nr1,
170 const float * nr2,
171 size_t n1, size_t n2);
172
173 /***************************************************************************
174 * Compute a subset of distances
175 ***************************************************************************/
176
177 /* compute the inner product between x and a subset y of ny vectors,
178 whose indices are given by idy. */
179 void fvec_inner_products_by_idx (
180 float * __restrict ip,
181 const float * x,
182 const float * y,
183 const long * __restrict ids,
184 size_t d, size_t nx, size_t ny);
185
186 /* same but for a subset in y indexed by idsy (ny vectors in total) */
187 void fvec_L2sqr_by_idx (
188 float * __restrict dis,
189 const float * x,
190 const float * y,
191 const long * __restrict ids, /* ids of y vecs */
192 size_t d, size_t nx, size_t ny);
193
194 /***************************************************************************
195 * KNN functions
196 ***************************************************************************/
197
198
199 /** Return the k nearest neighors of each of the nx vectors x among the ny
200 * vector y, w.r.t to max inner product
201 *
202 * @param x query vectors, size nx * d
203 * @param y database vectors, size ny * d
204 * @param res result array, which also provides k. Sorted on output
205 */
206 void knn_inner_product (
207 const float * x,
208 const float * y,
209 size_t d, size_t nx, size_t ny,
210 float_minheap_array_t * res);
211
212 /** Same as knn_inner_product, for the L2 distance */
213 void knn_L2sqr (
214 const float * x,
215 const float * y,
216 size_t d, size_t nx, size_t ny,
217 float_maxheap_array_t * res);
218
219 /** same as knn_L2sqr, but base_shift[bno] is subtracted to all
220 * computed distances.
221 *
222 * @param base_shift size ny
223 */
224 void knn_L2sqr_base_shift (
225 const float * x,
226 const float * y,
227 size_t d, size_t nx, size_t ny,
228 float_maxheap_array_t * res,
229 const float *base_shift);
230
231
232 void knn_inner_products_by_idx (
233 const float * x,
234 const float * y,
235 const long * __restrict ids,
236 size_t d, size_t nx, size_t ny,
237 float_minheap_array_t * res);
238
239 void knn_L2sqr_by_idx (const float * x,
240 const float * y,
241 const long * __restrict ids,
242 size_t d, size_t nx, size_t ny,
243 float_maxheap_array_t * res);
244
245 /***************************************************************************
246 * Range search
247 ***************************************************************************/
248
249
250
251 /// Forward declaration, see AuxIndexStructures.h
252 struct RangeSearchResult;
253
254 /** Return the k nearest neighors of each of the nx vectors x among the ny
255 * vector y, w.r.t to max inner product
256 *
257 * @param x query vectors, size nx * d
258 * @param y database vectors, size ny * d
259 * @param radius search radius around the x vectors
260 * @param result result structure
261 */
262 void range_search_L2sqr (
263 const float * x,
264 const float * y,
265 size_t d, size_t nx, size_t ny,
266 float radius,
267 RangeSearchResult *result);
268
269 /// same as range_search_L2sqr for the inner product similarity
270 void range_search_inner_product (
271 const float * x,
272 const float * y,
273 size_t d, size_t nx, size_t ny,
274 float radius,
275 RangeSearchResult *result);
276
277
278
279
280
281 /***************************************************************************
282 * Misc matrix and vector manipulation functions
283 ***************************************************************************/
284
285
286 /** compute c := a + bf * b for a, b and c tables
287 *
288 * @param n size of the tables
289 * @param a size n
290 * @param b size n
291 * @param c restult table, size n
292 */
293 void fvec_madd (size_t n, const float *a,
294 float bf, const float *b, float *c);
295
296
297 /** same as fvec_madd, also return index of the min of the result table
298 * @return index of the min of table c
299 */
300 int fvec_madd_and_argmin (size_t n, const float *a,
301 float bf, const float *b, float *c);
302
303
304 /* perform a reflection (not an efficient implementation, just for test ) */
305 void reflection (const float * u, float * x, size_t n, size_t d, size_t nu);
306
307
308 /** For k-means: update stage. Returns nb of split clusters. */
309 int km_update_centroids (
310 const float * x,
311 float * centroids,
312 long * assign,
313 size_t d, size_t k, size_t n);
314
315 /** compute the Q of the QR decomposition for m > n
316 * @param a size n * m: input matrix and output Q
317 */
318 void matrix_qr (int m, int n, float *a);
319
320 /** distances are supposed to be sorted. Sorts indices with same distance*/
321 void ranklist_handle_ties (int k, long *idx, const float *dis);
322
323 /** count the number of comon elements between v1 and v2
324 * algorithm = sorting + bissection to avoid double-counting duplicates
325 */
326 size_t ranklist_intersection_size (size_t k1, const long *v1,
327 size_t k2, const long *v2);
328
329
330 void fvec_argsort (size_t n, const float *vals,
331 size_t *perm);
332
333 void fvec_argsort_parallel (size_t n, const float *vals,
334 size_t *perm);
335
336
337 /// compute histogram on v
338 int ivec_hist (size_t n, const int * v, int vmax, int *hist);
339
340 /** Compute histogram of bits on a code array
341 *
342 * @param codes size(n, nbits / 8)
343 * @param hist size(nbits): nb of 1s in the array of codes
344 */
345 void bincode_hist(size_t n, size_t nbits, const uint8_t *codes, int *hist);
346
347
348 /// compute a checksum on a table.
349 size_t ivec_checksum (size_t n, const int *a);
350
351
352 } // namspace faiss
353
354
355 #endif /* FAISS_utils_h */
faiss::RandomGenerator
random generator that can be used in multithreaded contexts
Definition: utils.h:49
faiss::knn_L2sqr_base_shift
void knn_L2sqr_base_shift(const float *x, const float *y, size_t d, size_t nx, size_t ny, float_maxheap_array_t *res, const float *base_shift)
Definition: utils.cpp:870
faiss::RandomGenerator::RandomGenerator
RandomGenerator(long seed=1234)
initialize
faiss::km_update_centroids
int km_update_centroids(const float *x, float *centroids, long *assign, size_t d, size_t k, size_t n)
Definition: utils.cpp:1286
faiss::fvec_L2sqr
float fvec_L2sqr(const float *x, const float *y, size_t d)
Squared L2 distance between two vectors.
Definition: utils.cpp:430
faiss::bincode_hist
void bincode_hist(size_t n, size_t nbits, const uint8_t *codes, int *hist)
Definition: utils.cpp:1467
faiss::ranklist_handle_ties
void ranklist_handle_ties(int k, long *idx, const float *dis)
Definition: utils.cpp:1378
faiss::RandomGenerator::rand_float
float rand_float()
between 0 and 1
Definition: utils.cpp:208
faiss::fvec_madd
void fvec_madd(size_t n, const float *a, float bf, const float *b, float *c)
Definition: utils.cpp:1707
faiss::get_mem_usage_kb
size_t get_mem_usage_kb()
get current RSS usage in kB
faiss::ivec_hist
int ivec_hist(size_t n, const int *v, int vmax, int *hist)
compute histogram on v
Definition: utils.cpp:1456
faiss::RandomGenerator::rand_long
long rand_long()
random long &lt; 2 ^ 62
faiss::RandomGenerator::rand_int
int rand_int()
random 31-bit positive integer
faiss::HeapArray
Definition: Heap.h:351
faiss::ranklist_intersection_size
size_t ranklist_intersection_size(size_t k1, const long *v1, size_t k2, const long *v2_in)
Definition: utils.cpp:1394
faiss::pairwise_L2sqr
void pairwise_L2sqr(long d, long nq, const float *xq, long nb, const float *xb, float *dis, long ldq, long ldb, long ldd)
Definition: utils.cpp:1228
faiss::range_search_inner_product
void range_search_inner_product(const float *x, const float *y, size_t d, size_t nx, size_t ny, float radius, RangeSearchResult *res)
same as range_search_L2sqr for the inner product similarity
Definition: utils.cpp:1166
faiss::knn_inner_product
void knn_inner_product(const float *x, const float *y, size_t d, size_t nx, size_t ny, float_minheap_array_t *res)
Definition: utils.cpp:830
faiss::getmillisecs
double getmillisecs()
ms elapsed since some arbitrary epoch
Definition: utils.cpp:71
faiss::imbalance_factor
double imbalance_factor(int k, const int *hist)
same, takes a histogram as input
Definition: utils.cpp:1432
faiss::fvec_norm_L2sqr
float fvec_norm_L2sqr(const float *x, size_t d)
Definition: utils.cpp:511
faiss::range_search_L2sqr
void range_search_L2sqr(const float *x, const float *y, size_t d, size_t nx, size_t ny, float radius, RangeSearchResult *res)
Definition: utils.cpp:1151
faiss::matrix_qr
void matrix_qr(int m, int n, float *a)
Definition: utils.cpp:1206
faiss::RangeSearchResult
Definition: AuxIndexStructures.h:35
faiss::ivec_checksum
size_t ivec_checksum(size_t n, const int *a)
compute a checksum on a table.
Definition: utils.cpp:1490
faiss::fvec_madd_and_argmin
int fvec_madd_and_argmin(size_t n, const float *a, float bf, const float *b, float *c)
Definition: utils.cpp:1781
faiss::knn_L2sqr
void knn_L2sqr(const float *x, const float *y, size_t d, size_t nx, size_t ny, float_maxheap_array_t *res)
Definition: utils.cpp:850