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");
103 is_orthonormal (false), verbose (false)
109 FAISS_THROW_IF_NOT_MSG(
is_trained,
"Transformation not trained yet");
113 FAISS_THROW_IF_NOT_MSG (
b.size() ==
d_out,
"Bias not initialized");
115 for (
int i = 0; i < n; i++)
116 for(
int j = 0; j <
d_out; j++)
123 FAISS_THROW_IF_NOT_MSG (
A.size() ==
d_out * d_in,
124 "Transformation matrix not initialized");
127 FINTEGER nbiti =
d_out, ni = n, di = d_in;
128 sgemm_ (
"Transposed",
"Not transposed",
130 &one,
A.data(), &di, x, &di, &c_factor, xt, &nbiti);
139 float *y_new =
new float [n *
d_out];
142 for (idx_t i = 0; i < n; i++) {
143 for (
int j = 0; j <
d_out; j++) {
144 *yw++ = *yr++ -
b [j];
151 FINTEGER dii = d_in, doi =
d_out, ni = n;
152 float one = 1.0, zero = 0.0;
153 sgemm_ (
"Not",
"Not", &dii, &ni, &doi,
154 &one,
A.data (), &dii, y, &doi, &zero, x, &dii);
157 if (have_bias)
delete [] y;
173 FAISS_ASSERT(
A.size() >=
d_out * d_in);
176 FINTEGER dii = d_in, doi =
d_out;
177 float one = 1.0, zero = 0.0;
179 sgemm_ (
"Transposed",
"Not", &doi, &doi, &dii,
180 &one,
A.data (), &dii,
182 &zero, ATA.data(), &doi);
185 for (
long i = 0; i <
d_out; i++) {
186 for (
long j = 0; j <
d_out; j++) {
187 float v = ATA[i + j *
d_out];
190 is_orthonormal =
false;
205 FAISS_THROW_MSG (
"reverse transform not implemented for non-orthonormal matrices");
221 float_randn(q,
d_out * d_in, seed);
226 float_randn(q, d_out * d_out, seed);
230 for (i = 0; i <
d_out; i++) {
231 for(j = 0; j < d_in; j++) {
232 q[i * d_in + j] = q[i * d_out + j];
235 A.resize(d_in * d_out);
244 PCAMatrix::PCAMatrix (
int d_in,
int d_out,
245 float eigen_power,
bool random_rotation):
247 eigen_power(eigen_power), random_rotation(random_rotation)
250 max_points_per_d = 1000;
260 void eig(
size_t d_in,
double *cov,
double *eigenvalues,
int verbose)
263 FINTEGER info = 0, lwork = -1, di = d_in;
266 dsyev_ (
"Vectors as well",
"Upper",
267 &di, cov, &di, eigenvalues, &workq, &lwork, &info);
268 lwork = FINTEGER(workq);
269 double *work =
new double[lwork];
271 dsyev_ (
"Vectors as well",
"Upper",
272 &di, cov, &di, eigenvalues, work, &lwork, &info);
277 fprintf (stderr,
"WARN ssyev info returns %d, "
278 "a very bad PCA matrix is learnt\n",
284 if(verbose && d_in <= 10) {
285 printf(
"info=%ld new eigvals=[",
long(info));
286 for(
int j = 0; j < d_in; j++) printf(
"%g ", eigenvalues[j]);
290 printf(
"eigenvecs=\n");
291 for(
int i = 0; i < d_in; i++) {
292 for(
int j = 0; j < d_in; j++)
293 printf(
"%10.4g ", *ci++);
302 for(
int i = 0; i < d_in / 2; i++) {
304 std::swap(eigenvalues[i], eigenvalues[d_in - 1 - i]);
305 double *v1 = cov + i * d_in;
306 double *v2 = cov + (d_in - 1 - i) * d_in;
307 for(
int j = 0; j < d_in; j++)
308 std::swap(v1[j], v2[j]);
318 const float * x_in = x;
326 mean.clear();
mean.resize(d_in, 0.0);
329 for (
int i = 0; i < n; i++) {
330 for(
int j = 0; j < d_in; j++)
333 for(
int j = 0; j < d_in; j++)
338 for(
int j = 0; j < d_in; j++) printf(
"%g ",
mean[j]);
344 PCAMat.resize(d_in * d_in);
345 float * cov =
PCAMat.data();
348 for(
int i = 0; i < d_in; i++) {
349 for(
int j = 0; j < d_in; j++)
354 FINTEGER di = d_in, ni = n;
356 ssyrk_ (
"Up",
"Non transposed",
357 &di, &ni, &one, (
float*)x, &di, &one, cov, &di);
360 if(verbose && d_in <= 10) {
363 for(
int i = 0; i < d_in; i++) {
364 for(
int j = 0; j < d_in; j++)
365 printf(
"%10g ", *ci++);
370 std::vector<double> covd (d_in * d_in);
371 for (
size_t i = 0; i < d_in * d_in; i++) covd [i] = cov [i];
373 std::vector<double> eigenvaluesd (d_in);
375 eig (d_in, covd.data (), eigenvaluesd.data (), verbose);
377 for (
size_t i = 0; i < d_in * d_in; i++)
PCAMat [i] = covd [i];
378 eigenvalues.resize (d_in);
380 for (
size_t i = 0; i < d_in; i++)
381 eigenvalues [i] = eigenvaluesd [i];
386 std::vector<float> xc (n * d_in);
388 for (
size_t i = 0; i < n; i++)
389 for(
size_t j = 0; j < d_in; j++)
390 xc [i * d_in + j] = x [i * d_in + j] -
mean[j];
393 std::vector<float> gram (n * n);
395 FINTEGER di = d_in, ni = n;
396 float one = 1.0, zero = 0.0;
397 ssyrk_ (
"Up",
"Transposed",
398 &ni, &di, &one, xc.data(), &di, &zero, gram.data(), &ni);
401 if(verbose && d_in <= 10) {
402 float *ci = gram.data();
404 for(
int i = 0; i < n; i++) {
405 for(
int j = 0; j < n; j++)
406 printf(
"%10g ", *ci++);
411 std::vector<double> gramd (n * n);
412 for (
size_t i = 0; i < n * n; i++)
413 gramd [i] = gram [i];
415 std::vector<double> eigenvaluesd (n);
419 eig (n, gramd.data (), eigenvaluesd.data (), verbose);
423 for (
size_t i = 0; i < n * n; i++)
424 gram [i] = gramd [i];
426 eigenvalues.resize (d_in);
428 for (
size_t i = 0; i < n; i++)
429 eigenvalues [i] = eigenvaluesd [i];
432 FINTEGER di = d_in, ni = n;
435 sgemm_ (
"Non",
"Non Trans",
437 &one, xc.data(), &di, gram.data(), &ni,
438 &one,
PCAMat.data(), &di);
441 if(verbose && d_in <= 10) {
442 float *ci =
PCAMat.data();
444 for(
int i = 0; i < n; i++) {
445 for(
int j = 0; j < d_in; j++)
446 printf(
"%10g ", *ci++);
450 fvec_renorm_L2 (d_in, n,
PCAMat.data());
470 FAISS_THROW_IF_NOT_FMT (
472 "PCA matrix cannot output %d dimensions from %d ",
481 float *ai =
A.data();
482 for (
int i = 0; i <
d_out; i++) {
484 for(
int j = 0; j < d_in; j++)
492 std::vector <float> Ain;
500 for (
int i = 0; i <
d_out; i++) {
505 if (counter[j] < dsub && accu[j] < min_w) {
510 int row_dst = best_j * dsub + counter[best_j];
511 accu[best_j] += eigenvalues[i];
513 memcpy (&
A[row_dst * d_in], &Ain[i * d_in],
514 d_in *
sizeof (
A[0]));
518 printf(
" bin accu=[");
520 printf(
"%g ", accu[i]);
528 "both balancing bins and applying a random rotation "
529 "does not make sense");
536 for (
int i = 0; i <
d_out; i++) {
538 for(
int j = 0; j <
d_out; j++)
539 rr.
A[j * d_out + i] *= factor;
545 FINTEGER dii = d_in, doo =
d_out;
546 float one = 1.0, zero = 0.0;
548 sgemm_ (
"Not",
"Not", &dii, &doo, &doo,
549 &one,
PCAMat.data(), &dii, rr.
A.data(), &doo, &zero,
558 for (
int i = 0; i <
d_out; i++) {
560 for (
int j = 0; j < d_in; j++)
561 accu -=
mean[j] *
A[j + i * d_in];
577 niter_pq (4), niter_pq_0 (40),
592 const float * x_in = x;
608 std::vector<float> r (d * d);
609 float * rotation = r.data();
610 float_randn (rotation, d * d, 1234);
611 printf(
"CS0: %016lx\n",
614 printf(
"CS1: %016lx\n",
621 printf (
"OPQMatrix::train: training an OPQ rotation matrix "
622 "for M=%d from %ld vectors in %dD -> %dD\n",
626 std::vector<float> xtrain (n * d);
629 std::vector<float> sum (d);
631 for (
size_t i = 0; i < n; i++) {
632 for (
int j = 0; j < d_in; j++)
635 for (
int i = 0; i < d; i++) sum[i] /= n;
636 float *yi = xtrain.data();
638 for (
size_t i = 0; i < n; i++) {
639 for (
int j = 0; j < d_in; j++)
640 *yi++ = *xi++ - sum[j];
646 if (
A.size () == 0) {
650 printf(
" OPQMatrix::train: making random %ld*%ld rotation\n",
652 float_randn (rotation, d * d, 1234);
657 FAISS_THROW_IF_NOT (
A.size() == d * d2);
662 xproj (d2 * n), pq_recons (d2 * n), xxr (d * n),
665 std::vector<uint8_t> codes (
M * n);
669 pq ? *
pq : pq_default;
671 for (
int iter = 0; iter <
niter; iter++) {
674 FINTEGER di = d, d2i = d2, ni = n;
675 float zero = 0, one = 1;
676 sgemm_ (
"Transposed",
"Not transposed",
680 &zero, xproj.data(), &d2i);
685 pq_regular.
cp.verbose = verbose;
686 pq_regular.train (n, xproj.data());
689 pq_regular.
decode (codes.data(), pq_recons.data(), n);
691 float pq_err =
fvec_L2sqr (pq_recons.data(), xproj.data(), n * d2) / n;
694 printf (
" Iteration %d (%d PQ iterations):"
695 "%.3f s, obj=%g\n", iter, pq_regular.
cp.
niter,
699 float *u = tmp.data(), *vt = &tmp [d * d];
700 float *sing_val = &tmp [2 * d * d];
701 FINTEGER di = d, d2i = d2, ni = n;
702 float one = 1, zero = 0;
705 sgemm_ (
"Not",
"Transposed",
707 &one, pq_recons.data(), &d2i,
709 &zero, xxr.data(), &d2i);
712 FINTEGER lwork = -1, info = -1;
715 sgesvd_ (
"All",
"All",
716 &d2i, &di, xxr.data(), &d2i,
719 &worksz, &lwork, &info);
722 std::vector<float> work (lwork);
724 sgesvd_ (
"All",
"All",
725 &d2i, &di, xxr.data(), &d2i,
728 work.data(), &lwork, &info);
730 sgemm_ (
"Transposed",
"Transposed",
732 &one, u, &di, vt, &d2i,
733 &zero, rotation, &di);
741 for (
long i = 0; i <
d_out; i++)
742 memmove (&
A[i * d_in], &
A[i * d],
sizeof(
A[0]) * d_in);
743 A.resize (d_in * d_out);
755 NormalizationTransform::NormalizationTransform (
int d,
float norm):
760 NormalizationTransform::NormalizationTransform ():
766 (idx_t n,
const float* x,
float* xt)
const
769 memcpy (xt, x,
sizeof (x[0]) * n * d_in);
770 fvec_renorm_L2 (d_in, n, xt);
772 FAISS_THROW_MSG (
"not implemented");
779 memcpy (x, xt,
sizeof (xt[0]) * n * d_in);
786 IndexPreTransform::IndexPreTransform ():
787 index(nullptr), own_fields (false)
792 IndexPreTransform::IndexPreTransform (
794 Index (index->d, index->metric_type),
795 index (index), own_fields (false)
801 IndexPreTransform::IndexPreTransform (
804 Index (index->d, index->metric_type),
805 index (index), own_fields (false)
808 prepend_transform (ltrans);
813 FAISS_THROW_IF_NOT (ltrans->
d_out ==
d);
815 chain.insert (chain.begin(), ltrans);
820 IndexPreTransform::~IndexPreTransform ()
823 for (
int i = 0; i < chain.size(); i++)
834 int last_untrained = 0;
836 last_untrained = chain.size();
838 for (
int i = chain.size() - 1; i >= 0; i--) {
845 const float *prev_x = x;
849 printf(
"IndexPreTransform::train: training chain 0 to %d\n",
853 for (
int i = 0; i <= last_untrained; i++) {
855 if (i < chain.size()) {
859 printf(
" Training chain component %d/%zd\n",
861 if (
OPQMatrix *opqm = dynamic_cast<OPQMatrix*>(ltrans)) {
862 opqm->verbose =
true;
865 ltrans->
train (n, prev_x);
869 printf(
" Training sub-index\n");
873 if (i == last_untrained)
break;
875 printf(
" Applying transform %d/%zd\n",
879 float * xt = chain[i]->apply (n, prev_x);
881 if (prev_x != x)
delete [] prev_x;
892 const float *prev_x = x;
895 for (
int i = 0; i < chain.size(); i++) {
896 float * xt = chain[i]->apply (n, prev_x);
907 const float* next_x = xt;
910 for (
int i = chain.size() - 1; i >= 0; i--) {
911 float* prev_x = (i == 0) ? x :
new float [n * chain[i]->d_in];
913 chain [i]->reverse_transform (n, next_x, prev_x);
942 float *distances,
idx_t *labels)
const
965 float *x = chain.empty() ? recons :
new float [
index->
d];
977 float *x = chain.empty() ? recons :
new float [ni *
index->
d];
989 float *distances,
idx_t *labels,
float* recons)
const
996 float* recons_temp = chain.empty() ? recons :
new float [n * k *
index->
d];
1010 RemapDimensionsTransform::RemapDimensionsTransform (
1011 int d_in,
int d_out,
const int *map_in):
1015 for (
int i = 0; i < d_out; i++) {
1017 FAISS_THROW_IF_NOT (map[i] == -1 || (map[i] >= 0 && map[i] < d_in));
1021 RemapDimensionsTransform::RemapDimensionsTransform (
1024 map.resize (d_out, -1);
1028 for (
int i = 0; i < d_in; i++) {
1029 map [i * d_out / d_in] = i;
1032 for (
int i = 0; i <
d_out; i++) {
1037 for (
int i = 0; i < d_in && i <
d_out; i++)
1046 for (idx_t i = 0; i < n; i++) {
1047 for (
int j = 0; j <
d_out; j++) {
1048 xt[j] =
map[j] < 0 ? 0 : x[
map[j]];
1058 memset (x, 0,
sizeof (*x) * n * d_in);
1059 for (idx_t i = 0; i < n; i++) {
1060 for (
int j = 0; j <
d_out; j++) {
1061 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.
virtual void search_and_reconstruct(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels, float *recons) const
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 n, const float *x)
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
ClusteringParameters cp
parameters used during clustering
size_t ivec_checksum(size_t n, const int *a)
compute a checksum on a table.
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)
virtual void reconstruct(idx_t key, float *recons) const
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