Faiss
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
/data/users/matthijs/github_faiss/faiss/VectorTransform.h
1 /**
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD+Patents license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 // Copyright 2004-present Facebook. All Rights Reserved.
10 // -*- c++ -*-
11 
12 #ifndef FAISS_VECTOR_TRANSFORM_H
13 #define FAISS_VECTOR_TRANSFORM_H
14 
15 /** Defines a few objects that apply transformations to a set of
16  * vectors Often these are pre-processing steps.
17  */
18 
19 #include <vector>
20 
21 #include "Index.h"
22 
23 
24 namespace faiss {
25 
26 
27 /** Any transformation applied on a set of vectors */
29 
30  typedef Index::idx_t idx_t;
31 
32  int d_in; ///! input dimension
33  int d_out; ///! output dimension
34 
35  explicit VectorTransform (int d_in = 0, int d_out = 0):
36  d_in(d_in), d_out(d_out), is_trained(true)
37  {}
38 
39 
40  /// set if the VectorTransform does not require training, or if
41  /// training is done already
42  bool is_trained;
43 
44 
45  /** Perform training on a representative set of vectors. Does
46  * nothing by default.
47  *
48  * @param n nb of training vectors
49  * @param x training vecors, size n * d
50  */
51  virtual void train (idx_t n, const float *x);
52 
53  /** apply the random roation, return new allocated matrix
54  * @param x size n * d_in
55  * @return size n * d_out
56  */
57  float *apply (idx_t n, const float * x) const;
58 
59  /// same as apply, but result is pre-allocated
60  virtual void apply_noalloc (idx_t n, const float * x,
61  float *xt) const = 0;
62 
63  /// reverse transformation. May not be implemented or may return
64  /// approximate result
65  virtual void reverse_transform (idx_t n, const float * xt,
66  float *x) const;
67 
68  virtual ~VectorTransform () {}
69 
70 };
71 
72 
73 
74 /** Generic linear transformation, with bias term applied on output
75  * y = A * x + b
76  */
78 
79  bool have_bias; ///! whether to use the bias term
80 
81  /// check if matrix A is orthonormal (enables reverse_transform)
83 
84  /// Transformation matrix, size d_out * d_in
85  std::vector<float> A;
86 
87  /// bias vector, size d_out
88  std::vector<float> b;
89 
90  /// both d_in > d_out and d_out < d_in are supported
91  explicit LinearTransform (int d_in = 0, int d_out = 0,
92  bool have_bias = false);
93 
94  /// same as apply, but result is pre-allocated
95  void apply_noalloc(idx_t n, const float* x, float* xt) const override;
96 
97  /// compute x = A^T * (x - b)
98  /// is reverse transform if A has orthonormal lines
99  void transform_transpose (idx_t n, const float * y,
100  float *x) const;
101 
102  /// works only if is_orthonormal
103  void reverse_transform (idx_t n, const float * xt,
104  float *x) const override;
105 
106  /// compute A^T * A to set the is_orthonormal flag
107  void set_is_orthonormal ();
108 
109  bool verbose;
110 
111  ~LinearTransform() override {}
112 };
113 
114 
115 
116 /// Randomly rotate a set of vectors
118 
119  /// both d_in > d_out and d_out < d_in are supported
120  RandomRotationMatrix (int d_in, int d_out):
121  LinearTransform(d_in, d_out, false) {}
122 
123  /// must be called before the transform is used
124  void init(int seed);
125 
127 };
128 
129 
130 /** Applies a principal component analysis on a set of vectors,
131  * with optionally whitening and random rotation. */
133 
134  /** after transformation the components are multiplied by
135  * eigenvalues^eigen_power
136  *
137  * =0: no whitening
138  * =-2: full whitening
139  */
140  float eigen_power;
141 
142  /// random rotation after PCA
144 
145  /// ratio between # training vectors and dimension
147 
148  /// try to distribute output eigenvectors in this many bins
150 
151  /// Mean, size d_in
152  std::vector<float> mean;
153 
154  /// eigenvalues of covariance matrix (= squared singular values)
155  std::vector<float> eigenvalues;
156 
157  /// PCA matrix, size d_in * d_in
158  std::vector<float> PCAMat;
159 
160  // the final matrix is computed after random rotation and/or whitening
161  explicit PCAMatrix (int d_in = 0, int d_out = 0,
162  float eigen_power = 0, bool random_rotation = false);
163 
164  /// train on n vectors. If n < d_in then the eigenvector matrix
165  /// will be completed with 0s
166  void train(Index::idx_t n, const float* x) override;
167 
168  /// copy pre-trained PCA matrix
169  void copy_from (const PCAMatrix & other);
170 
171  /// called after mean, PCAMat and eigenvalues are computed
172  void prepare_Ab();
173 
174 };
175 
176 
177 struct ProductQuantizer;
178 
179 /** Applies a rotation to align the dimensions with a PQ to minimize
180  * the reconstruction error. Can be used before an IndexPQ or an
181  * IndexIVFPQ. The method is the non-parametric version described in:
182  *
183  * "Optimized Product Quantization for Approximate Nearest Neighbor Search"
184  * Tiezheng Ge, Kaiming He, Qifa Ke, Jian Sun, CVPR'13
185  *
186  */
188 
189  int M; ///< nb of subquantizers
190  int niter; ///< Number of outer training iterations
191  int niter_pq; ///< Number of training iterations for the PQ
192  int niter_pq_0; ///< same, for the first outer iteration
193 
194  /// if there are too many training points, resample
196  bool verbose;
197 
198  /// if non-NULL, use this product quantizer for training
199  /// should be constructed with (d_out, M, _)
201 
202  /// if d2 != -1, output vectors of this dimension
203  explicit OPQMatrix (int d = 0, int M = 1, int d2 = -1);
204 
205  void train(Index::idx_t n, const float* x) override;
206 };
207 
208 
209 /** remap dimensions for intput vectors, possibly inserting 0s
210  * strictly speaking this is also a linear transform but we don't want
211  * to compute it with matrix multiplies */
213 
214  /// map from output dimension to input, size d_out
215  /// -1 -> set output to 0
216  std::vector<int> map;
217 
218  RemapDimensionsTransform (int d_in, int d_out, const int *map);
219 
220  /// remap input to output, skipping or inserting dimensions as needed
221  /// if uniform: distribute dimensions uniformly
222  /// otherwise just take the d_out first ones.
223  RemapDimensionsTransform (int d_in, int d_out, bool uniform = true);
224 
225  void apply_noalloc(idx_t n, const float* x, float* xt) const override;
226 
227  /// reverse transform correct only when the mapping is a permuation
228  void reverse_transform(idx_t n, const float* xt, float* x) const override;
229 
231 };
232 
233 
234 /** per-vector normalization */
236  float norm;
237 
238  explicit NormalizationTransform (int d, float norm = 2.0);
240 
241  void apply_noalloc(idx_t n, const float* x, float* xt) const override;
242 
243  /// Identity transform since norm is not revertible
244  void reverse_transform(idx_t n, const float* xt, float* x) const override;
245 };
246 
247 
248 
249 /** Index that applies a LinearTransform transform on vectors before
250  * handing them over to a sub-index */
252 
253  std::vector<VectorTransform *> chain; ///! chain of tranforms
254  Index * index; ///! the sub-index
255 
256  bool own_fields; ///! whether pointers are deleted in destructor
257 
258  explicit IndexPreTransform (Index *index);
259 
261 
262  /// ltrans is the last transform before the index
264 
265  void prepend_transform (VectorTransform * ltrans);
266 
267  void train(idx_t n, const float* x) override;
268 
269  void add(idx_t n, const float* x) override;
270 
271  void add_with_ids(idx_t n, const float* x, const long* xids) override;
272 
273  void reset() override;
274 
275  /** removes IDs from the index. Not supported by all indexes.
276  */
277  long remove_ids(const IDSelector& sel) override;
278 
279  void search(
280  idx_t n,
281  const float* x,
282  idx_t k,
283  float* distances,
284  idx_t* labels) const override;
285 
286  void reconstruct (idx_t key, float * recons) const override;
287 
288  void reconstruct_n (idx_t i0, idx_t ni, float *recons)
289  const override;
290 
291  void search_and_reconstruct (idx_t n, const float *x, idx_t k,
292  float *distances, idx_t *labels,
293  float *recons) const override;
294 
295  /// apply the transforms in the chain. The returned float * may be
296  /// equal to x, otherwise it should be deallocated.
297  const float * apply_chain (idx_t n, const float *x) const;
298 
299  /// Reverse the transforms in the chain. May not be implemented for
300  /// all transforms in the chain or may return approximate results.
301  void reverse_chain (idx_t n, const float* xt, float* x) const;
302 
303  ~IndexPreTransform() override;
304 };
305 
306 
307 
308 } // namespace faiss
309 
310 
311 
312 #endif
void transform_transpose(idx_t n, const float *y, float *x) const
Index * index
! chain of tranforms
Randomly rotate a set of vectors.
int niter
Number of outer training iterations.
RandomRotationMatrix(int d_in, int d_out)
both d_in &gt; d_out and d_out &lt; d_in are supported
void init(int seed)
must be called before the transform is used
void reset() override
removes all elements from the database.
int niter_pq
Number of training iterations for the PQ.
std::vector< float > A
Transformation matrix, size d_out * d_in.
LinearTransform(int d_in=0, int d_out=0, bool have_bias=false)
both d_in &gt; d_out and d_out &lt; d_in are supported
VectorTransform(int d_in=0, int d_out=0)
! output dimension
void set_is_orthonormal()
compute A^T * A to set the is_orthonormal flag
ProductQuantizer * pq
void train(Index::idx_t n, const float *x) override
std::vector< float > mean
Mean, size d_in.
const float * apply_chain(idx_t n, const float *x) const
std::vector< float > PCAMat
PCA matrix, size d_in * d_in.
void train(idx_t n, const float *x) override
std::vector< float > b
bias vector, size d_out
void reverse_transform(idx_t n, const float *xt, float *x) const override
works only if is_orthonormal
void reverse_transform(idx_t n, const float *xt, float *x) const override
Identity transform since norm is not revertible.
void train(Index::idx_t n, const float *x) override
int balanced_bins
try to distribute output eigenvectors in this many bins
long idx_t
all indices are this type
Definition: Index.h:62
void reconstruct_n(idx_t i0, idx_t ni, float *recons) const override
void apply_noalloc(idx_t n, const float *x, float *xt) const override
same as apply, but result is pre-allocated
bool own_fields
! the sub-index
int niter_pq_0
same, for the first outer iteration
virtual void train(idx_t n, const float *x)
virtual void reverse_transform(idx_t n, const float *xt, float *x) const
void search_and_reconstruct(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels, float *recons) const override
void reverse_transform(idx_t n, const float *xt, float *x) const override
reverse transform correct only when the mapping is a permuation
size_t max_train_points
if there are too many training points, resample
void copy_from(const PCAMatrix &other)
copy pre-trained PCA matrix
int d_out
! input dimension
OPQMatrix(int d=0, int M=1, int d2=-1)
if d2 != -1, output vectors of this dimension
void prepare_Ab()
called after mean, PCAMat and eigenvalues are computed
void add(idx_t n, const float *x) override
void apply_noalloc(idx_t n, const float *x, float *xt) const override
same as apply, but result is pre-allocated
void reverse_chain(idx_t n, const float *xt, float *x) const
bool is_orthonormal
! whether to use the bias term
std::vector< float > eigenvalues
eigenvalues of covariance matrix (= squared singular values)
void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const override
void add_with_ids(idx_t n, const float *x, const long *xids) override
bool random_rotation
random rotation after PCA
size_t max_points_per_d
ratio between # training vectors and dimension
float * apply(idx_t n, const float *x) const
long remove_ids(const IDSelector &sel) override
virtual void apply_noalloc(idx_t n, const float *x, float *xt) const =0
same as apply, but result is pre-allocated
void reconstruct(idx_t key, float *recons) const override
int M
nb of subquantizers
void apply_noalloc(idx_t n, const float *x, float *xt) const override
same as apply, but result is pre-allocated