12 #include "VectorTransform.h"
19 #include "FaissAssert.h"
22 using namespace faiss;
36 const char *transa,
const char *transb, FINTEGER *m, FINTEGER *
37 n, FINTEGER *k,
const float *alpha,
const float *a,
38 FINTEGER *lda,
const float *b,
39 FINTEGER *ldb,
float *beta,
40 float *c, FINTEGER *ldc);
43 const char *uplo,
const char *trans, FINTEGER *n, FINTEGER *k,
44 float *alpha,
float *a, FINTEGER *lda,
45 float *beta,
float *c, FINTEGER *ldc);
50 const char *jobz,
const char *uplo, FINTEGER *n,
float *a,
51 FINTEGER *lda,
float *w,
float *work, FINTEGER *lwork,
55 const char *jobz,
const char *uplo, FINTEGER *n,
double *a,
56 FINTEGER *lda,
double *w,
double *work, FINTEGER *lwork,
60 const char *jobu,
const char *jobvt, FINTEGER *m, FINTEGER *n,
61 float *a, FINTEGER *lda,
float *s,
float *u, FINTEGER *ldu,
float *vt,
62 FINTEGER *ldvt,
float *work, FINTEGER *lwork, FINTEGER *info);
74 float * xt =
new float[n *
d_out];
86 idx_t ,
const float *,
89 FAISS_THROW_MSG (
"reverse transform not implemented");
108 FAISS_THROW_IF_NOT_MSG(
is_trained,
"Transformation not trained yet");
112 FAISS_THROW_IF_NOT_MSG (
b.size() ==
d_out,
"Bias not initialized");
114 for (
int i = 0; i < n; i++)
115 for(
int j = 0; j <
d_out; j++)
122 FAISS_THROW_IF_NOT_MSG (
A.size() ==
d_out * d_in,
123 "Transformation matrix not initialized");
126 FINTEGER nbiti =
d_out, ni = n, di = d_in;
127 sgemm_ (
"Transposed",
"Not transposed",
129 &one,
A.data(), &di, x, &di, &c_factor, xt, &nbiti);
138 float *y_new =
new float [n *
d_out];
141 for (idx_t i = 0; i < n; i++) {
142 for (
int j = 0; j <
d_out; j++) {
143 *yw++ = *yr++ -
b [j];
150 FINTEGER dii = d_in, doi =
d_out, ni = n;
151 float one = 1.0, zero = 0.0;
152 sgemm_ (
"Not",
"Not", &dii, &ni, &doi,
153 &one,
A.data (), &dii, y, &doi, &zero, x, &dii);
156 if (have_bias)
delete [] y;
170 float_randn(q,
d_out * d_in, seed);
175 float_randn(q, d_out * d_out, seed);
179 for (i = 0; i <
d_out; i++) {
180 for(j = 0; j < d_in; j++) {
181 q[i * d_in + j] = q[i * d_out + j];
184 A.resize(d_in * d_out);
199 PCAMatrix::PCAMatrix (
int d_in,
int d_out,
200 float eigen_power,
bool random_rotation):
202 eigen_power(eigen_power), random_rotation(random_rotation)
205 max_points_per_d = 1000;
215 void eig(
size_t d_in,
double *cov,
double *eigenvalues,
int verbose)
218 FINTEGER info = 0, lwork = -1, di = d_in;
221 dsyev_ (
"Vectors as well",
"Upper",
222 &di, cov, &di, eigenvalues, &workq, &lwork, &info);
223 lwork = FINTEGER(workq);
224 double *work =
new double[lwork];
226 dsyev_ (
"Vectors as well",
"Upper",
227 &di, cov, &di, eigenvalues, work, &lwork, &info);
232 fprintf (stderr,
"WARN ssyev info returns %d, "
233 "a very bad PCA matrix is learnt\n",
239 if(verbose && d_in <= 10) {
240 printf(
"info=%ld new eigvals=[",
long(info));
241 for(
int j = 0; j < d_in; j++) printf(
"%g ", eigenvalues[j]);
245 printf(
"eigenvecs=\n");
246 for(
int i = 0; i < d_in; i++) {
247 for(
int j = 0; j < d_in; j++)
248 printf(
"%10.4g ", *ci++);
257 for(
int i = 0; i < d_in / 2; i++) {
259 std::swap(eigenvalues[i], eigenvalues[d_in - 1 - i]);
260 double *v1 = cov + i * d_in;
261 double *v2 = cov + (d_in - 1 - i) * d_in;
262 for(
int j = 0; j < d_in; j++)
263 std::swap(v1[j], v2[j]);
273 const float * x_in = x;
281 mean.clear();
mean.resize(d_in, 0.0);
284 for (
int i = 0; i < n; i++) {
285 for(
int j = 0; j < d_in; j++)
288 for(
int j = 0; j < d_in; j++)
293 for(
int j = 0; j < d_in; j++) printf(
"%g ",
mean[j]);
299 PCAMat.resize(d_in * d_in);
300 float * cov =
PCAMat.data();
303 for(
int i = 0; i < d_in; i++) {
304 for(
int j = 0; j < d_in; j++)
309 FINTEGER di = d_in, ni = n;
311 ssyrk_ (
"Up",
"Non transposed",
312 &di, &ni, &one, (
float*)x, &di, &one, cov, &di);
315 if(verbose && d_in <= 10) {
318 for(
int i = 0; i < d_in; i++) {
319 for(
int j = 0; j < d_in; j++)
320 printf(
"%10g ", *ci++);
325 std::vector<double> covd (d_in * d_in);
326 for (
size_t i = 0; i < d_in * d_in; i++) covd [i] = cov [i];
328 std::vector<double> eigenvaluesd (d_in);
330 eig (d_in, covd.data (), eigenvaluesd.data (), verbose);
332 for (
size_t i = 0; i < d_in * d_in; i++)
PCAMat [i] = covd [i];
333 eigenvalues.resize (d_in);
335 for (
size_t i = 0; i < d_in; i++)
336 eigenvalues [i] = eigenvaluesd [i];
341 std::vector<float> xc (n * d_in);
343 for (
size_t i = 0; i < n; i++)
344 for(
size_t j = 0; j < d_in; j++)
345 xc [i * d_in + j] = x [i * d_in + j] -
mean[j];
348 std::vector<float> gram (n * n);
350 FINTEGER di = d_in, ni = n;
351 float one = 1.0, zero = 0.0;
352 ssyrk_ (
"Up",
"Transposed",
353 &ni, &di, &one, xc.data(), &di, &zero, gram.data(), &ni);
356 if(verbose && d_in <= 10) {
357 float *ci = gram.data();
359 for(
int i = 0; i < n; i++) {
360 for(
int j = 0; j < n; j++)
361 printf(
"%10g ", *ci++);
366 std::vector<double> gramd (n * n);
367 for (
size_t i = 0; i < n * n; i++)
368 gramd [i] = gram [i];
370 std::vector<double> eigenvaluesd (n);
374 eig (n, gramd.data (), eigenvaluesd.data (), verbose);
378 for (
size_t i = 0; i < n * n; i++)
379 gram [i] = gramd [i];
381 eigenvalues.resize (d_in);
383 for (
size_t i = 0; i < n; i++)
384 eigenvalues [i] = eigenvaluesd [i];
387 FINTEGER di = d_in, ni = n;
390 sgemm_ (
"Non",
"Non Trans",
392 &one, xc.data(), &di, gram.data(), &ni,
393 &one,
PCAMat.data(), &di);
396 if(verbose && d_in <= 10) {
397 float *ci =
PCAMat.data();
399 for(
int i = 0; i < n; i++) {
400 for(
int j = 0; j < d_in; j++)
401 printf(
"%10g ", *ci++);
405 fvec_renorm_L2 (d_in, n,
PCAMat.data());
427 FAISS_THROW_IF_NOT_MSG (
429 "PCA matrix was trained on too few examples "
430 "to output this number of dimensions");
432 A.resize(
d_out * d_in);
436 float *ai = A.data();
437 for (
int i = 0; i <
d_out; i++) {
439 for(
int j = 0; j < d_in; j++)
447 std::vector <float> Ain;
449 A.resize(
d_out * d_in);
455 for (
int i = 0; i <
d_out; i++) {
460 if (counter[j] < dsub && accu[j] < min_w) {
465 int row_dst = best_j * dsub + counter[best_j];
466 accu[best_j] += eigenvalues[i];
468 memcpy (&A[row_dst * d_in], &Ain[i * d_in],
469 d_in *
sizeof (A[0]));
473 printf(
" bin accu=[");
475 printf(
"%g ", accu[i]);
483 "both balancing bins and applying a random rotation "
484 "does not make sense");
491 for (
int i = 0; i <
d_out; i++) {
493 for(
int j = 0; j <
d_out; j++)
494 rr.
A[j * d_out + i] *= factor;
500 FINTEGER dii = d_in, doo =
d_out;
501 float one = 1.0, zero = 0.0;
503 sgemm_ (
"Not",
"Not", &dii, &doo, &doo,
504 &one,
PCAMat.data(), &dii, rr.
A.data(), &doo, &zero,
513 for (
int i = 0; i <
d_out; i++) {
515 for (
int j = 0; j < d_in; j++)
516 accu -=
mean[j] *
A[j + i * d_in];
526 "reverse only implemented for orthogonal transforms");
538 niter_pq (4), niter_pq_0 (40),
551 const float * x_in = x;
567 std::vector<float> r (d * d);
568 float * rotation = r.data();
569 float_randn (rotation, d * d, 1234);
570 printf(
"CS0: %016lx\n",
573 printf(
"CS1: %016lx\n",
580 printf (
"OPQMatrix::train: training an OPQ rotation matrix "
581 "for M=%d from %ld vectors in %dD -> %dD\n",
585 std::vector<float> xtrain (n * d);
588 std::vector<float> sum (d);
590 for (
size_t i = 0; i < n; i++) {
591 for (
int j = 0; j < d_in; j++)
594 for (
int i = 0; i < d; i++) sum[i] /= n;
595 float *yi = xtrain.data();
597 for (
size_t i = 0; i < n; i++) {
598 for (
int j = 0; j < d_in; j++)
599 *yi++ = *xi++ - sum[j];
605 if (
A.size () == 0) {
609 printf(
" OPQMatrix::train: making random %ld*%ld rotation\n",
611 float_randn (rotation, d * d, 1234);
616 FAISS_THROW_IF_NOT (
A.size() == d * d2);
622 xproj (d2 * n), pq_recons (d2 * n), xxr (d * n),
625 std::vector<uint8_t> codes (
M * n);
628 for (
int iter = 0; iter <
niter; iter++) {
631 FINTEGER di = d, d2i = d2, ni = n;
632 float zero = 0, one = 1;
633 sgemm_ (
"Transposed",
"Not transposed",
637 &zero, xproj.data(), &d2i);
642 pq_regular.
cp.verbose = verbose;
643 pq_regular.train (n, xproj.data());
646 pq_regular.
decode (codes.data(), pq_recons.data(), n);
648 float pq_err =
fvec_L2sqr (pq_recons.data(), xproj.data(), n * d2) / n;
651 printf (
" Iteration %d (%d PQ iterations):"
652 "%.3f s, obj=%g\n", iter, pq_regular.
cp.
niter,
656 float *u = tmp.data(), *vt = &tmp [d * d];
657 float *sing_val = &tmp [2 * d * d];
658 FINTEGER di = d, d2i = d2, ni = n;
659 float one = 1, zero = 0;
662 sgemm_ (
"Not",
"Transposed",
664 &one, pq_recons.data(), &d2i,
666 &zero, xxr.data(), &d2i);
669 FINTEGER lwork = -1, info = -1;
672 sgesvd_ (
"All",
"All",
673 &d2i, &di, xxr.data(), &d2i,
676 &worksz, &lwork, &info);
679 std::vector<float> work (lwork);
681 sgesvd_ (
"All",
"All",
682 &d2i, &di, xxr.data(), &d2i,
685 work.data(), &lwork, &info);
687 sgemm_ (
"Transposed",
"Transposed",
689 &one, u, &di, vt, &d2i,
690 &zero, rotation, &di);
698 for (
long i = 0; i <
d_out; i++)
699 memmove (&
A[i * d_in], &
A[i * d],
sizeof(
A[0]) * d_in);
700 A.resize (d_in * d_out);
720 NormalizationTransform::NormalizationTransform (
int d,
float norm):
725 NormalizationTransform::NormalizationTransform ():
731 (idx_t n,
const float* x,
float* xt)
const
734 memcpy (xt, x,
sizeof (x[0]) * n * d_in);
735 fvec_renorm_L2 (d_in, n, xt);
737 FAISS_THROW_MSG (
"not implemented");
745 IndexPreTransform::IndexPreTransform ():
746 index(nullptr), own_fields (false)
751 IndexPreTransform::IndexPreTransform (
753 Index (index->d, index->metric_type),
754 index (index), own_fields (false)
760 IndexPreTransform::IndexPreTransform (
763 Index (index->d, index->metric_type),
764 index (index), own_fields (false)
767 prepend_transform (ltrans);
772 FAISS_THROW_IF_NOT (ltrans->
d_out ==
d);
774 chain.insert (chain.begin(), ltrans);
779 IndexPreTransform::~IndexPreTransform ()
782 for (
int i = 0; i < chain.size(); i++)
793 int last_untrained = 0;
795 last_untrained = chain.size();
797 for (
int i = chain.size() - 1; i >= 0; i--) {
804 const float *prev_x = x;
807 for (
int i = 0; i <= last_untrained; i++) {
808 if (i < chain.size()) {
811 ltrans->
train(n, prev_x);
815 if (i == last_untrained)
break;
817 float * xt = chain[i]->apply (n, prev_x);
818 if (prev_x != x)
delete prev_x;
829 const float *prev_x = x;
832 for (
int i = 0; i < chain.size(); i++) {
833 float * xt = chain[i]->apply (n, prev_x);
865 float *distances,
idx_t *labels)
const
888 float *x = chain.empty() ? recons :
new float [ni *
index->
d];
894 for (
int i = chain.size() - 1; i >= 0; i--) {
895 float *x_pre = i == 0 ? recons :
new float [chain[i]->d_in * ni];
897 chain [i]->reverse_transform (ni, x, x_pre);
910 RemapDimensionsTransform::RemapDimensionsTransform (
911 int d_in,
int d_out,
const int *map_in):
915 for (
int i = 0; i < d_out; i++) {
917 FAISS_THROW_IF_NOT (map[i] == -1 || (map[i] >= 0 && map[i] < d_in));
921 RemapDimensionsTransform::RemapDimensionsTransform (
924 map.resize (d_out, -1);
928 for (
int i = 0; i < d_in; i++) {
929 map [i * d_out / d_in] = i;
932 for (
int i = 0; i <
d_out; i++) {
937 for (
int i = 0; i < d_in && i <
d_out; i++)
946 for (idx_t i = 0; i < n; i++) {
947 for (
int j = 0; j <
d_out; j++) {
948 xt[j] =
map[j] < 0 ? 0 : x[
map[j]];
958 memset (x, 0,
sizeof (*x) * n * d_in);
959 for (idx_t i = 0; i < n; i++) {
960 for (
int j = 0; j <
d_out; j++) {
961 if (
map[j] >= 0) x[
map[j]] = xt[j];
Randomly rotate a set of vectors.
int niter
clustering iterations
int niter
Number of outer training iterations.
void decode(const uint8_t *code, float *x) const
decode a vector from a given code (or n vectors if third argument)
float fvec_L2sqr(const float *x, const float *y, size_t d)
Squared L2 distance between two vectors.
void init(int seed)
must be called before the transform is used
virtual void reset()=0
removes all elements from the database.
int niter_pq
Number of training iterations for the PQ.
const float * fvecs_maybe_subsample(size_t d, size_t *n, size_t nmax, const float *x, bool verbose, long seed)
virtual void train(idx_t, const float *)
virtual void add_with_ids(idx_t n, const float *x, const long *xids)
void train(Index::idx_t n, const float *x) override
std::vector< float > mean
Mean, size d_in.
std::vector< float > PCAMat
PCA matrix, size d_in * d_in.
void compute_codes(const float *x, uint8_t *codes, size_t n) const
same as compute_code for several vectors
virtual void reconstruct_n(idx_t i0, idx_t ni, float *recons) const
virtual void add(idx_t n, const float *x)=0
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
idx_t ntotal
total nb of indexed vectors
the centroids are already initialized
double getmillisecs()
ms elapsed since some arbitrary epoch
virtual long remove_ids(const IDSelector &sel)
virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const =0
void matrix_qr(int m, int n, float *a)
int niter_pq_0
same, for the first outer iteration
void reverse_transform(idx_t n, const float *xt, float *x) const override
ClusteringParameters cp
parameters used during clustering
size_t ivec_checksum(size_t n, const int *a)
compute a checksum on a table.
void reverse_transform(idx_t n, const float *xt, float *x) const override
void reverse_transform(idx_t n, const float *xt, float *x) const override
size_t max_train_points
if there are too many training points, resample
void copy_from(const PCAMatrix &other)
copy pre-trained PCA matrix
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
bool is_trained
set if the Index does not require training, or if training is done already
std::vector< float > eigenvalues
eigenvalues of covariance matrix (= squared singular values)
bool random_rotation
random rotation after PCA
size_t max_points_per_d
ratio between # training vectors and dimension
int max_points_per_centroid
to limit size of dataset