13 #include "VectorTransform.h"
20 #include "FaissAssert.h"
23 using namespace faiss;
37 const char *transa,
const char *transb, FINTEGER *m, FINTEGER *
38 n, FINTEGER *k,
const float *alpha,
const float *a,
39 FINTEGER *lda,
const float *b,
40 FINTEGER *ldb,
float *beta,
41 float *c, FINTEGER *ldc);
44 const char *uplo,
const char *trans, FINTEGER *n, FINTEGER *k,
45 float *alpha,
float *a, FINTEGER *lda,
46 float *beta,
float *c, FINTEGER *ldc);
51 const char *jobz,
const char *uplo, FINTEGER *n,
float *a,
52 FINTEGER *lda,
float *w,
float *work, FINTEGER *lwork,
56 const char *jobu,
const char *jobvt, FINTEGER *m, FINTEGER *n,
57 float *a, FINTEGER *lda,
float *s,
float *u, FINTEGER *ldu,
float *vt,
58 FINTEGER *ldvt,
float *work, FINTEGER *lwork, FINTEGER *info);
70 float * xt =
new float[n *
d_out];
82 idx_t ,
const float *,
85 FAISS_ASSERT (!
"reverse transform not implemented");
104 FAISS_ASSERT(
is_trained || !
"Transformation not trained yet");
108 FAISS_ASSERT (
b.size() ==
d_out || !
"Bias not initialized");
110 for (
int i = 0; i < n; i++)
111 for(
int j = 0; j <
d_out; j++)
118 FAISS_ASSERT (
A.size() ==
d_out * d_in ||
119 !
"Transformation matrix not initialized");
122 FINTEGER nbiti =
d_out, ni = n, di = d_in;
123 sgemm_ (
"Transposed",
"Not transposed",
125 &one,
A.data(), &di, x, &di, &c_factor, xt, &nbiti);
134 float *y_new =
new float [n *
d_out];
137 for (idx_t i = 0; i < n; i++) {
138 for (
int j = 0; j <
d_out; j++) {
139 *yw++ = *yr++ -
b [j];
146 FINTEGER dii = d_in, doi =
d_out, ni = n;
147 float one = 1.0, zero = 0.0;
148 sgemm_ (
"Not",
"Not", &dii, &ni, &doi,
149 &one,
A.data (), &dii, y, &doi, &zero, x, &dii);
152 if (have_bias)
delete [] y;
166 float_randn(q,
d_out * d_in, seed);
171 float_randn(q, d_out * d_out, seed);
175 for (i = 0; i <
d_out; i++) {
176 for(j = 0; j < d_in; j++) {
177 q[i * d_in + j] = q[i * d_out + j];
180 A.resize(d_in * d_out);
195 PCAMatrix::PCAMatrix (
int d_in,
int d_out,
196 float eigen_power,
bool random_rotation):
198 eigen_power(eigen_power), random_rotation(random_rotation)
201 max_points_per_d = 1000;
208 const float * x_in = x;
214 mean.clear();
mean.resize(d_in, 0.0);
217 for (
int i = 0; i < n; i++) {
218 for(
int j = 0; j < d_in; j++)
221 for(
int j = 0; j < d_in; j++)
226 for(
int j = 0; j < d_in; j++) printf(
"%g ",
mean[j]);
232 PCAMat.resize(d_in * d_in);
233 float * cov =
PCAMat.data();
236 for(
int i = 0; i < d_in; i++) {
237 for(
int j = 0; j < d_in; j++)
242 FINTEGER di = d_in, ni = n;
244 ssyrk_ (
"Up",
"Non transposed",
245 &di, &ni, &one, (
float*)x, &di, &one, cov, &di);
248 if(verbose && d_in <= 10) {
251 for(
int i = 0; i < d_in; i++) {
252 for(
int j = 0; j < d_in; j++)
253 printf(
"%10g ", *ci++);
260 FINTEGER info = 0, lwork = -1, di = d_in;
263 ssyev_ (
"Vectors as well",
"Upper",
264 &di, cov, &di,
eigenvalues.data(), &workq, &lwork, &info);
265 lwork = FINTEGER(workq);
266 float *work =
new float[lwork];
268 ssyev_ (
"Vectors as well",
"Upper",
269 &di, cov, &di,
eigenvalues.data(), work, &lwork, &info);
272 fprintf (stderr,
"WARN ssyev info returns %d, "
273 "a very bad PCA matrix is learnt\n",
280 if(verbose && d_in <= 10) {
281 printf(
"info=%ld new eigvals=[",
long(info));
282 for(
int j = 0; j < d_in; j++) printf(
"%g ",
eigenvalues[j]);
286 printf(
"eigenvecs=\n");
287 for(
int i = 0; i < d_in; i++) {
288 for(
int j = 0; j < d_in; j++)
289 printf(
"%10.4g ", *ci++);
298 for(
int i = 0; i < d_in / 2; i++) {
301 float *v1 = cov + i * d_in;
302 float *v2 = cov + (d_in - 1 - i) * d_in;
303 for(
int j = 0; j < d_in; j++)
304 std::swap(v1[j], v2[j]);
308 FAISS_ASSERT(!
"Gramm matrix version not implemented "
309 "-- provide more training examples than dimensions");
313 if (x != x_in)
delete [] x;
338 float *ai =
A.data();
339 for (
int i = 0; i <
d_out; i++) {
341 for(
int j = 0; j < d_in; j++)
349 std::vector <float> Ain;
357 for (
int i = 0; i <
d_out; i++) {
362 if (counter[j] < dsub && accu[j] < min_w) {
367 int row_dst = best_j * dsub + counter[best_j];
370 memcpy (&
A[row_dst * d_in], &Ain[i * d_in],
371 d_in *
sizeof (
A[0]));
375 printf(
" bin accu=[");
377 printf(
"%g ", accu[i]);
385 !
"both balancing bins and applying a random rotation "
386 "does not make sense");
393 for (
int i = 0; i <
d_out; i++) {
395 for(
int j = 0; j <
d_out; j++)
396 rr.
A[j * d_out + i] *= factor;
402 FINTEGER dii = d_in, doo =
d_out;
403 float one = 1.0, zero = 0.0;
405 sgemm_ (
"Not",
"Not", &dii, &doo, &doo,
406 &one,
PCAMat.data(), &dii, rr.
A.data(), &doo, &zero,
415 for (
int i = 0; i <
d_out; i++) {
417 for (
int j = 0; j < d_in; j++)
418 accu -=
mean[j] *
A[j + i * d_in];
428 !
"reverse only implemented for orthogonal transforms");
440 niter_pq (4), niter_pq_0 (40),
453 const float * x_in = x;
467 std::vector<float> r (d * d);
468 float * rotation = r.data();
469 float_randn (rotation, d * d, 1234);
470 printf(
"CS0: %016lx\n",
473 printf(
"CS1: %016lx\n",
480 printf (
"OPQMatrix::train: training an OPQ rotation matrix "
481 "for M=%d from %ld vectors in %dD -> %dD\n",
485 std::vector<float> xtrain (n * d);
488 std::vector<float> sum (d);
490 for (
size_t i = 0; i < n; i++) {
491 for (
int j = 0; j < d_in; j++)
494 for (
int i = 0; i < d; i++) sum[i] /= n;
495 float *yi = xtrain.data();
497 for (
size_t i = 0; i < n; i++) {
498 for (
int j = 0; j < d_in; j++)
499 *yi++ = *xi++ - sum[j];
505 if (
A.size () == 0) {
509 printf(
" OPQMatrix::train: making random %ld*%ld rotation\n",
511 float_randn (rotation, d * d, 1234);
516 FAISS_ASSERT (
A.size() == d * d2);
522 xproj (d2 * n), pq_recons (d2 * n), xxr (d * n),
525 std::vector<uint8_t> codes (
M * n);
528 for (
int iter = 0; iter <
niter; iter++) {
531 FINTEGER di = d, d2i = d2, ni = n;
532 float zero = 0, one = 1;
533 sgemm_ (
"Transposed",
"Not transposed",
537 &zero, xproj.data(), &d2i);
542 pq_regular.
cp.verbose = verbose;
543 pq_regular.train (n, xproj.data());
546 pq_regular.
decode (codes.data(), pq_recons.data(), n);
548 float pq_err =
fvec_L2sqr (pq_recons.data(), xproj.data(), n * d2) / n;
551 printf (
" Iteration %d (%d PQ iterations):"
552 "%.3f s, obj=%g\n", iter, pq_regular.
cp.
niter,
556 float *u = tmp.data(), *vt = &tmp [d * d];
557 float *sing_val = &tmp [2 * d * d];
558 FINTEGER di = d, d2i = d2, ni = n;
559 float one = 1, zero = 0;
562 sgemm_ (
"Not",
"Transposed",
564 &one, pq_recons.data(), &d2i,
566 &zero, xxr.data(), &d2i);
569 FINTEGER lwork = -1, info = -1;
572 sgesvd_ (
"All",
"All",
573 &d2i, &di, xxr.data(), &d2i,
576 &worksz, &lwork, &info);
579 std::vector<float> work (lwork);
581 sgesvd_ (
"All",
"All",
582 &d2i, &di, xxr.data(), &d2i,
585 work.data(), &lwork, &info);
587 sgemm_ (
"Transposed",
"Transposed",
589 &one, u, &di, vt, &d2i,
590 &zero, rotation, &di);
598 for (
long i = 0; i <
d_out; i++)
599 memmove (&
A[i * d_in], &
A[i * d],
sizeof(
A[0]) * d_in);
600 A.resize (d_in * d_out);
622 IndexPreTransform::IndexPreTransform ():
623 index(nullptr), own_fields (false)
628 IndexPreTransform::IndexPreTransform (
630 Index (index->d, index->metric_type),
631 index (index), own_fields (false)
640 IndexPreTransform::IndexPreTransform (
643 Index (index->d, index->metric_type),
644 index (index), own_fields (false)
647 prepend_transform (ltrans);
653 FAISS_ASSERT (ltrans->
d_out ==
d);
655 chain.insert (chain.begin(), ltrans);
661 void IndexPreTransform::set_typename ()
664 index_typename =
"PreLT[" +
index->index_typename +
"]";
668 IndexPreTransform::~IndexPreTransform ()
671 for (
int i = 0; i < chain.size(); i++)
682 int last_untrained = 0;
683 for (
int i = 0; i < chain.size(); i++)
684 if (!chain[i]->
is_trained) last_untrained = i;
686 const float *prev_x = x;
688 for (
int i = 0; i <= last_untrained; i++) {
689 if (i < chain.size()) {
692 ltrans->
train(n, prev_x);
696 if (i == last_untrained)
break;
698 float * xt = chain[i]->apply (n, prev_x);
699 if (prev_x != x)
delete [] prev_x;
703 if (prev_x != x)
delete [] prev_x;
710 const float *prev_x = x;
711 for (
int i = 0; i < chain.size(); i++) {
712 float * xt = chain[i]->apply (n, prev_x);
713 if (prev_x != x)
delete [] prev_x;
724 if (xt != x)
delete [] xt;
734 if (xt != x)
delete [] xt;
742 float *distances,
idx_t *labels)
const
747 if (xt != x)
delete [] xt;
765 float *x = chain.empty() ? recons :
new float [ni *
index->
d];
770 for (
int i = chain.size() - 1; i >= 0; i--) {
771 float *x_pre = i == 0 ? recons :
new float [chain[i]->d_in * ni];
772 chain [i]->reverse_transform (ni, x, x_pre);
785 RemapDimensionsTransform::RemapDimensionsTransform (
786 int d_in,
int d_out,
const int *map_in):
790 for (
int i = 0; i < d_out; i++) {
792 FAISS_ASSERT (map[i] == -1 || (map[i] >= 0 && map[i] < d_in));
796 RemapDimensionsTransform::RemapDimensionsTransform (
799 map.resize (d_out, -1);
803 for (
int i = 0; i < d_in; i++) {
804 map [i * d_out / d_in] = i;
807 for (
int i = 0; i <
d_out; i++) {
812 for (
int i = 0; i < d_in && i <
d_out; i++)
821 for (idx_t i = 0; i < n; i++) {
822 for (
int j = 0; j <
d_out; j++) {
823 xt[j] =
map[j] < 0 ? 0 : x[
map[j]];
833 memset (x, 0,
sizeof (*x) * n * d_in);
834 for (idx_t i = 0; i < n; i++) {
835 for (
int j = 0; j <
d_out; j++) {
836 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)
virtual 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
virtual 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
virtual 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.
virtual void reverse_transform(idx_t n, const float *xt, float *x) const override
virtual 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