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);
376 PCAMat.resize(d_in * d_in);
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);
397 if(verbose && d_in <= 10) {
398 float *ci =
PCAMat.data();
400 for(
int i = 0; i < n; i++) {
401 for(
int j = 0; j < d_in; j++)
402 printf(
"%10g ", *ci++);
406 fvec_renorm_L2 (d_in, n,
PCAMat.data());
435 float *ai =
A.data();
436 for (
int i = 0; i <
d_out; i++) {
438 for(
int j = 0; j < d_in; j++)
446 std::vector <float> Ain;
454 for (
int i = 0; i <
d_out; i++) {
459 if (counter[j] < dsub && accu[j] < min_w) {
464 int row_dst = best_j * dsub + counter[best_j];
465 accu[best_j] += eigenvalues[i];
467 memcpy (&
A[row_dst * d_in], &Ain[i * d_in],
468 d_in *
sizeof (
A[0]));
472 printf(
" bin accu=[");
474 printf(
"%g ", accu[i]);
482 "both balancing bins and applying a random rotation "
483 "does not make sense");
490 for (
int i = 0; i <
d_out; i++) {
492 for(
int j = 0; j <
d_out; j++)
493 rr.
A[j * d_out + i] *= factor;
499 FINTEGER dii = d_in, doo =
d_out;
500 float one = 1.0, zero = 0.0;
502 sgemm_ (
"Not",
"Not", &dii, &doo, &doo,
503 &one,
PCAMat.data(), &dii, rr.
A.data(), &doo, &zero,
512 for (
int i = 0; i <
d_out; i++) {
514 for (
int j = 0; j < d_in; j++)
515 accu -=
mean[j] *
A[j + i * d_in];
525 "reverse only implemented for orthogonal transforms");
537 niter_pq (4), niter_pq_0 (40),
550 const float * x_in = x;
566 std::vector<float> r (d * d);
567 float * rotation = r.data();
568 float_randn (rotation, d * d, 1234);
569 printf(
"CS0: %016lx\n",
572 printf(
"CS1: %016lx\n",
579 printf (
"OPQMatrix::train: training an OPQ rotation matrix "
580 "for M=%d from %ld vectors in %dD -> %dD\n",
584 std::vector<float> xtrain (n * d);
587 std::vector<float> sum (d);
589 for (
size_t i = 0; i < n; i++) {
590 for (
int j = 0; j < d_in; j++)
593 for (
int i = 0; i < d; i++) sum[i] /= n;
594 float *yi = xtrain.data();
596 for (
size_t i = 0; i < n; i++) {
597 for (
int j = 0; j < d_in; j++)
598 *yi++ = *xi++ - sum[j];
604 if (
A.size () == 0) {
608 printf(
" OPQMatrix::train: making random %ld*%ld rotation\n",
610 float_randn (rotation, d * d, 1234);
615 FAISS_THROW_IF_NOT (
A.size() == d * d2);
621 xproj (d2 * n), pq_recons (d2 * n), xxr (d * n),
624 std::vector<uint8_t> codes (
M * n);
627 for (
int iter = 0; iter <
niter; iter++) {
630 FINTEGER di = d, d2i = d2, ni = n;
631 float zero = 0, one = 1;
632 sgemm_ (
"Transposed",
"Not transposed",
636 &zero, xproj.data(), &d2i);
641 pq_regular.
cp.verbose = verbose;
642 pq_regular.train (n, xproj.data());
645 pq_regular.
decode (codes.data(), pq_recons.data(), n);
647 float pq_err =
fvec_L2sqr (pq_recons.data(), xproj.data(), n * d2) / n;
650 printf (
" Iteration %d (%d PQ iterations):"
651 "%.3f s, obj=%g\n", iter, pq_regular.
cp.
niter,
655 float *u = tmp.data(), *vt = &tmp [d * d];
656 float *sing_val = &tmp [2 * d * d];
657 FINTEGER di = d, d2i = d2, ni = n;
658 float one = 1, zero = 0;
661 sgemm_ (
"Not",
"Transposed",
663 &one, pq_recons.data(), &d2i,
665 &zero, xxr.data(), &d2i);
668 FINTEGER lwork = -1, info = -1;
671 sgesvd_ (
"All",
"All",
672 &d2i, &di, xxr.data(), &d2i,
675 &worksz, &lwork, &info);
678 std::vector<float> work (lwork);
680 sgesvd_ (
"All",
"All",
681 &d2i, &di, xxr.data(), &d2i,
684 work.data(), &lwork, &info);
686 sgemm_ (
"Transposed",
"Transposed",
688 &one, u, &di, vt, &d2i,
689 &zero, rotation, &di);
697 for (
long i = 0; i <
d_out; i++)
698 memmove (&
A[i * d_in], &
A[i * d],
sizeof(
A[0]) * d_in);
699 A.resize (d_in * d_out);
719 NormalizationTransform::NormalizationTransform (
int d,
float norm):
724 NormalizationTransform::NormalizationTransform ():
730 (idx_t n,
const float* x,
float* xt)
const
733 memcpy (xt, x,
sizeof (x[0]) * n * d_in);
734 fvec_renorm_L2 (d_in, n, xt);
736 FAISS_THROW_MSG (
"not implemented");
744 IndexPreTransform::IndexPreTransform ():
745 index(nullptr), own_fields (false)
750 IndexPreTransform::IndexPreTransform (
752 Index (index->d, index->metric_type),
753 index (index), own_fields (false)
759 IndexPreTransform::IndexPreTransform (
762 Index (index->d, index->metric_type),
763 index (index), own_fields (false)
766 prepend_transform (ltrans);
771 FAISS_THROW_IF_NOT (ltrans->
d_out ==
d);
773 chain.insert (chain.begin(), ltrans);
778 IndexPreTransform::~IndexPreTransform ()
781 for (
int i = 0; i < chain.size(); i++)
792 int last_untrained = 0;
794 last_untrained = chain.size();
796 for (
int i = chain.size() - 1; i >= 0; i--) {
803 const float *prev_x = x;
806 for (
int i = 0; i <= last_untrained; i++) {
807 if (i < chain.size()) {
810 ltrans->
train(n, prev_x);
814 if (i == last_untrained)
break;
816 float * xt = chain[i]->apply (n, prev_x);
817 if (prev_x != x)
delete prev_x;
828 const float *prev_x = x;
831 for (
int i = 0; i < chain.size(); i++) {
832 float * xt = chain[i]->apply (n, prev_x);
864 float *distances,
idx_t *labels)
const
887 float *x = chain.empty() ? recons :
new float [ni *
index->
d];
893 for (
int i = chain.size() - 1; i >= 0; i--) {
894 float *x_pre = i == 0 ? recons :
new float [chain[i]->d_in * ni];
896 chain [i]->reverse_transform (ni, x, x_pre);
909 RemapDimensionsTransform::RemapDimensionsTransform (
910 int d_in,
int d_out,
const int *map_in):
914 for (
int i = 0; i < d_out; i++) {
916 FAISS_THROW_IF_NOT (map[i] == -1 || (map[i] >= 0 && map[i] < d_in));
920 RemapDimensionsTransform::RemapDimensionsTransform (
923 map.resize (d_out, -1);
927 for (
int i = 0; i < d_in; i++) {
928 map [i * d_out / d_in] = i;
931 for (
int i = 0; i <
d_out; i++) {
936 for (
int i = 0; i < d_in && i <
d_out; i++)
945 for (idx_t i = 0; i < n; i++) {
946 for (
int j = 0; j <
d_out; j++) {
947 xt[j] =
map[j] < 0 ? 0 : x[
map[j]];
957 memset (x, 0,
sizeof (*x) * n * d_in);
958 for (idx_t i = 0; i < n; i++) {
959 for (
int j = 0; j <
d_out; j++) {
960 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 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)
virtual void train(idx_t n, const float *x)
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