forked from facebookresearch/faiss
-
Notifications
You must be signed in to change notification settings - Fork 5
/
VecProductQuantizer.h
3035 lines (2399 loc) · 113 KB
/
VecProductQuantizer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2018-present, Thomson Licensing, SAS.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* Modifications related the introduction of Quicker ADC (Vectorized Product Quantization)
* are licensed under the Clear BSD license found in the LICENSE file in the root directory
* of this source tree.
*
* The rest of the source code is licensed under the BSD+Patents license found in the
* LICENSE file in the root directory of this source tree
*/
// -*- c++ -*-
#ifndef FAISS_VEC_PRODUCT_QUANTIZER_H
#define FAISS_VEC_PRODUCT_QUANTIZER_H
#include <stdint.h>
#include <vector>
#include "Clustering.h"
#include "Heap.h"
#include <cstddef>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include "FaissAssert.h"
#include "VectorTransform.h"
#include "IndexFlat.h"
#include "utils.h"
#include <immintrin.h>
#include <x86intrin.h>
#include <iostream>
#include <boost/align/aligned_allocator.hpp>
#include <mkl.h>
#include <iomanip>
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define FORCE_INLINE __attribute__((always_inline))
extern "C" {
// this is to keep the clang syntax checker happy
#ifndef FINTEGER
#define FINTEGER int
#endif
#ifdef ECLIPSE
#define __AVX512F__
#endif
/* declare BLAS functions, see http://www.netlib.org/clapack/cblas/ */
int sgemm_ (
const char *transa, const char *transb, FINTEGER *m, FINTEGER *
n, FINTEGER *k, const float *alpha, const float *a,
FINTEGER *lda, const float *b,
FINTEGER *ldb, float *beta,
float *c, FINTEGER *ldc);
}
namespace faiss {
static void init_hypercube (int d, int nbits,
int n, const float * x,
float *centroids)
{
std::vector<float> mean (d);
for (int i = 0; i < n; i++)
for (int j = 0; j < d; j++)
mean [j] += x[i * d + j];
float maxm = 0;
for (int j = 0; j < d; j++) {
mean [j] /= n;
if (fabs(mean[j]) > maxm) maxm = fabs(mean[j]);
}
for (int i = 0; i < (1 << nbits); i++) {
float * cent = centroids + i * d;
for (int j = 0; j < nbits; j++)
cent[j] = mean [j] + (((i >> j) & 1) ? 1 : -1) * maxm;
for (int j = nbits; j < d; j++)
cent[j] = mean [j];
}
}
static void init_hypercube_pca (int d, int nbits,
int n, const float * x,
float *centroids)
{
PCAMatrix pca (d, nbits);
pca.train (n, x);
for (int i = 0; i < (1 << nbits); i++) {
float * cent = centroids + i * d;
for (int j = 0; j < d; j++) {
cent[j] = pca.mean[j];
float f = 1.0;
for (int k = 0; k < nbits; k++)
cent[j] += f *
sqrt (pca.eigenvalues [k]) *
(((i >> k) & 1) ? 1 : -1) *
pca.PCAMat [j + k * d];
}
}
}
/*
* Epu16 "extended" intrisics
* Public domain from http://www.alfredklomp.com/programming/sse-intrinsics/
*/
static inline __m128i _mm_cmple_epu8 (__m128i x, __m128i y) {
// Returns 0xFF where x <= y:
return _mm_cmpeq_epi8(_mm_min_epu8(x, y), x);
}
static inline __m128i _mm_cmpge_epu8 (__m128i x, __m128i y) {
// Returns 0xFF where x >= y:
return _mm_cmple_epu8(y, x);
}
static inline __m128i _mm_cmpgt_epu8 (__m128i x, __m128i y) {
// Returns 0xFF where x > y:
return _mm_andnot_si128(
_mm_cmpeq_epi8(x, y),
_mm_cmpeq_epi8(_mm_max_epu8(x, y), x)
);
}
static inline __m128i _mm_cmplt_epu8 (__m128i x, __m128i y) {
// Returns 0xFF where x < y:
return _mm_cmpgt_epu8(y, x);
}
static inline __m128i _mm_cmple_epu16 (__m128i x, __m128i y) {
// Returns 0xFFFF where x <= y:
return _mm_cmpeq_epi16(_mm_subs_epu16(x, y), _mm_setzero_si128());
}
static inline __m128i _mm_cmpge_epu16 (__m128i x, __m128i y) {
// Returns 0xFFFF where x >= y:
return _mm_cmple_epu16(y, x);
}
static inline __m128i _mm_cmpgt_epu16 (__m128i x, __m128i y) {
// Returns 0xFFFF where x > y:
return _mm_andnot_si128(_mm_cmpeq_epi16(x, y), _mm_cmple_epu16(y, x));
}
static inline __m128i _mm_cmplt_epu16 (__m128i x, __m128i y) {
// Returns 0xFFFF where x < y:
return _mm_cmpgt_epu16(y, x);
}
/*
* End of EPU16 extended intrisics
*/
template<class T_TSC>
struct QuantizerMAX {
std::vector<float> min;
float min_sum;
float max;
int M;
float delta;
float inv_delta;
//float gmin;
//float gmin_sum;
T_TSC QMAX;
QuantizerMAX(float *min_,float min_sum_, float max_, int M_): min(), min_sum(min_sum_), max(max_), M(M_) {
QMAX = std::numeric_limits<T_TSC>::max();
//gmin = std::numeric_limits<float>::max();
min.resize(M);
for(int m=0;m<M;m++){
min[m]= min_[m];
FAISS_THROW_IF_NOT_MSG(max > min[m], "Max value to quantize must be larger than min value to quantize");
//gmin = std::min(gmin, min[m]);
}
//gmin_sum=gmin*M;
FAISS_THROW_IF_NOT_MSG(max > min_sum, "Max value to quantize must be larger than min value to quantize");
delta = (max - min_sum) / QMAX;
inv_delta = 1.0f/delta;
//printf("[%f -- %f] (delta: %g, inv_delta: %g\n)",gmin,max,delta,inv_delta);
}
void quantize_val(float val, T_TSC* qval, int m) const {
if(val >= max) {
*qval = QMAX;
return;
}
*qval = static_cast<T_TSC>(((val - min[m])*inv_delta));
}
void quantize_sum(float val, T_TSC* qval) const {
if(val >= max) {
*qval = QMAX;
return;
}
*qval = static_cast<T_TSC>(((val - min_sum)*inv_delta));
}
float unquantize_sum(T_TSC qval) const {
float fval=qval+0.5;
return (fval*delta)+min_sum;
}
inline void quantize_val_simd(const float* val, int8_t* qval, const int table_size, const int ksub, const int m) const {
FAISS_THROW_IF_NOT_MSG(ksub%16 == 0 && table_size%16 == 0 , "Requires table size and ksub to be multiples of of 16");
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
const __m256 min_r = _mm256_set1_ps(min[m]);
const __m256 inv_delta_r = _mm256_set1_ps(inv_delta);
const __m128i shuf_r = _mm_set_epi8(15,14,13,12, 7,6,5,4 ,11,10,9,8, 3,2,1,0);
for(int i=0;i<ksub/16;i++){
__m128i * t = (__m128i*)&qval[i*16];
float * f1 = (float*)&val[i*16];
float * f2 = (float*)&val[i*16+8];
__m256 low = _mm256_loadu_ps(f1); // 8x32
__m256 high = _mm256_loadu_ps(f2); // 8x32
low = _mm256_sub_ps(low, min_r);
high = _mm256_sub_ps(high, min_r);
low = _mm256_mul_ps(low, inv_delta_r);
high = _mm256_mul_ps(high, inv_delta_r);
__m256i lowi = _mm256_cvtps_epi32(low);
__m256i highi = _mm256_cvtps_epi32(high);
__m256i packed16_interleaved4 = _mm256_packs_epi32(lowi, highi); // A B A B
__m128i p16i_l = _mm256_extracti128_si256(packed16_interleaved4,0); // A B
__m128i p16i_h = _mm256_extracti128_si256(packed16_interleaved4,1); // A B
__m128i packed8_interleaved4 = _mm_packs_epi16(p16i_l, p16i_h); // A B A B
// Reorganize...
__m128i packed8 = _mm_shuffle_epi8(packed8_interleaved4, shuf_r); // A A A A B B B B
_mm_store_si128(t,packed8);
}
for(int i=ksub/16;i<table_size/16;i++){
// Set to zero
__m128i * t = (__m128i*)&qval[i*16];
_mm_store_si128(t, _mm_set1_epi8(0));
}
}
inline void quantize_val_simd(const float* val, int16_t* qval, const int table_size, const int ksub, const int m) const {
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
FAISS_THROW_IF_NOT_MSG(ksub%16 == 0 && table_size%16 == 0, "Requires table size and ksub to be multiples of of 16");
//FIXME Update to use AVX512
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
const __m256 min_r = _mm256_set1_ps(min[m]);
const __m256 inv_delta_r = _mm256_set1_ps(inv_delta);
for(int i=0;i<ksub/16;i++){
__m256i * t = (__m256i*)&qval[i*16];
float * f1 = (float*)&val[i*16];
float * f2 = (float*)&val[i*16+8];
__m256 low = _mm256_loadu_ps(f1); // 8x32
__m256 high = _mm256_loadu_ps(f2); // 8x32
low = _mm256_sub_ps(low, min_r);
high = _mm256_sub_ps(high, min_r);
low = _mm256_mul_ps(low, inv_delta_r);
high = _mm256_mul_ps(high, inv_delta_r);
__m256i lowi = _mm256_cvtps_epi32(low);
__m256i highi = _mm256_cvtps_epi32(high);
__m256i packed16_interleaved4 = _mm256_packs_epi32(lowi, highi); // A B A B
__m256i packed16 = _mm256_permute4x64_epi64(packed16_interleaved4,0b11011000); // A A B B
_mm256_store_si256(t,packed16);
}
for(int i=ksub/16;i<table_size/16;i++){
// Set to zero
__m256i * t = (__m256i*)&qval[i*16];
_mm256_store_si256(t, _mm256_set1_epi16(0));
}
}
};
template<>
struct QuantizerMAX<uint8_t> {
std::vector<float> min;
float min_sum;
float max;
int M;
float delta;
float inv_delta;
//float gmin;
//float gmin_sum;
uint8_t QMAX;
QuantizerMAX(float *min_,float min_sum_, float max_, int M_): min(), min_sum(min_sum_), max(max_*1.001), M(M_) {
QMAX = std::numeric_limits<uint8_t>::max() - M - 1;
//gmin = std::numeric_limits<float>::max();
min.resize(M);
for(int m=0;m<M;m++){
min[m]= min_[m];
FAISS_THROW_IF_NOT_MSG(max > min[m], "Max value to quantize must be larger than min value to quantize");
//gmin = std::min(gmin, min[m]);
}
//gmin_sum=gmin*M;
FAISS_THROW_IF_NOT_MSG(max > min_sum, "Max value to quantize must be larger than min value to quantize");
delta = (max - min_sum) / QMAX;
inv_delta = 1.0f/delta;
//printf("[%f -- %f] (delta: %g, inv_delta: %g\n)",gmin,max,delta,inv_delta);
}
void quantize_val(float val, uint8_t* qval, int m) const {
if(val >= max) {
*qval = QMAX + M + 1; // Sum will be shifted by M (to the limit of uint8_t)
return;
}
*qval = static_cast<uint8_t>(((val - min[m])*inv_delta)) + 1; // Shift by 1 as zero is a sticky in saturated arithmetic
}
void quantize_sum(float val, uint8_t* qval) const {
if(val >= max) {
*qval = QMAX + M + 1;
return;
}
*qval = static_cast<uint8_t>(((val - min_sum)*inv_delta)) + M;
}
float unquantize_sum(uint8_t qval) const {
float fval=qval+0.5-M-1;
return (fval*delta)+min_sum;
}
inline void quantize_val_simd(const float* val, uint8_t* qval, const int table_size, const int ksub, const int m) const {
FAISS_THROW_IF_NOT_MSG(ksub%16 == 0 && table_size%16 == 0 , "Requires table size and ksub to be multiples of of 16");
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
const __m256 min_r = _mm256_set1_ps(min[m]);
const __m256 inv_delta_r = _mm256_set1_ps(inv_delta);
const __m128i shuf_r = _mm_set_epi8(15,14,13,12, 7,6,5,4 ,11,10,9,8, 3,2,1,0);
for(int i=0;i<ksub/16;i++){
__m128i * t = (__m128i*)&qval[i*16];
float * f1 = (float*)&val[i*16];
float * f2 = (float*)&val[i*16+8];
__m256 low = _mm256_loadu_ps(f1); // 8x32
__m256 high = _mm256_loadu_ps(f2); // 8x32
low = _mm256_sub_ps(low, min_r);
high = _mm256_sub_ps(high, min_r);
low = _mm256_mul_ps(low, inv_delta_r);
high = _mm256_mul_ps(high, inv_delta_r);
__m256i lowi = _mm256_cvtps_epi32(low);
__m256i highi = _mm256_cvtps_epi32(high);
__m256i packed16_interleaved4 = _mm256_packs_epi32(lowi, highi); // A B A B
__m128i p16i_l = _mm256_extracti128_si256(packed16_interleaved4,0); // A B
__m128i p16i_h = _mm256_extracti128_si256(packed16_interleaved4,1); // A B
__m128i packed8_interleaved4 = _mm_packus_epi16(p16i_l, p16i_h); // A B A B
// Reorganize...
__m128i packed8 = _mm_shuffle_epi8(packed8_interleaved4, shuf_r); // A A A A B B B B
__m128i offset8 = _mm_add_epi8(packed8, _mm_set1_epi8(1));
_mm_store_si128(t,offset8);
}
for(int i=ksub/16;i<table_size/16;i++){
// Set to zero
__m128i * t = (__m128i*)&qval[i*16];
_mm_store_si128(t, _mm_set1_epi8(1));
}
}
};
template<>
struct QuantizerMAX<uint16_t> {
std::vector<float> min;
float min_sum;
float max;
int M;
float delta;
float inv_delta;
//float gmin;
//float gmin_sum;
uint16_t QMAX;
QuantizerMAX(float *min_,float min_sum_, float max_, int M_): min(), min_sum(min_sum_), max(max_*1.001), M(M_) {
QMAX = std::numeric_limits<uint16_t>::max() - M - 1;
//gmin = std::numeric_limits<float>::max();
min.resize(M);
for(int m=0;m<M;m++){
min[m]= min_[m];
FAISS_THROW_IF_NOT_MSG(max > min[m], "Max value to quantize must be larger than min value to quantize");
//gmin = std::min(gmin, min[m]);
}
//gmin_sum=gmin*M;
FAISS_THROW_IF_NOT_MSG(max > min_sum, "Max value to quantize must be larger than min value to quantize");
delta = (max - min_sum) / QMAX;
inv_delta = 1.0f/delta;
//printf("[%f -- %f] (delta: %g, inv_delta: %g\n)",gmin,max,delta,inv_delta);
}
void quantize_val(float val, uint16_t* qval, int m) const {
if(val >= max) {
*qval = QMAX + M + 1; // Sum will be shifted by M (to the limit of uint8_t)
return;
}
*qval = static_cast<uint16_t>(((val - min[m])*inv_delta)) + 1; // Shift by 1 as zero is a sticky in saturated arithmetic
}
void quantize_sum(float val, uint16_t* qval) const {
if(val >= max) {
*qval = QMAX + M + 1;
return;
}
*qval = static_cast<uint16_t>(((val - min_sum)*inv_delta)) + M;
}
float unquantize_sum(uint16_t qval) const {
float fval=qval+0.5-M-1;
return (fval*delta)+min_sum;
}
#if 0
inline void quantize_val_simd(const float* val, uint16_t* qval, const int table_size, const int ksub, const int m) const {
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
FAISS_THROW_IF_NOT_MSG(ksub%16 == 0 && table_size%16 == 0, "Requires table size and ksub to be multiples of of 16");
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
const __m512 min_r = _mm512_set1_ps(min[m]);
const __m512 inv_delta_r = _mm512_set1_ps(inv_delta);
for(int i=0;i<ksub/16;i++){
__m512i * t = (__m512i*)&qval[i*16];
float * f1 = (float*)&val[i*16];
__m512 all = _mm512_loadu_ps(f1); // 8x32
all = _mm512_sub_ps(all, min_r);
all = _mm512_mul_ps(all, inv_delta_r);
__m512i alli = _mm512_cvt_roundps_epi32(all,_MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC);
__m256i lowi = _mm512_extract;
__m256i highi = _mm512_extract;
__m256i packed16_interleaved4 = _mm256_packs_epi32(lowi, highi); // A B A B
__m256i packed16 = _mm256_permute4x64_epi64(packed16_interleaved4,0b11011000); // A A B B
__m256i offset16 = _mm256_add_epi16(packed16, _mm256_set1_epi16(1));
_mm256_store_si256(t,offset16);
}
for(int i=ksub/16;i<table_size/16;i++){
// Set to zero
__m256i * t = (__m256i*)&qval[i*16];
_mm256_store_si256(t, _mm256_set1_epi16(1));
}
}
#else
inline void quantize_val_simd(const float* val, uint16_t* qval, const int table_size, const int ksub, const int m) const {
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
FAISS_THROW_IF_NOT_MSG(ksub%16 == 0 && table_size%16 == 0, "Requires table size and ksub to be multiples of of 16");
// Set values 0 to ksub to their quantized values and values table_size to ksub-1, if any, to zero
const __m256 min_r = _mm256_set1_ps(min[m]);
const __m256 inv_delta_r = _mm256_set1_ps(inv_delta);
for(int i=0;i<ksub/16;i++){
__m256i * t = (__m256i*)&qval[i*16];
float * f1 = (float*)&val[i*16];
float * f2 = (float*)&val[i*16+8];
__m256 low = _mm256_loadu_ps(f1); // 8x32
__m256 high = _mm256_loadu_ps(f2); // 8x32
low = _mm256_sub_ps(low, min_r);
high = _mm256_sub_ps(high, min_r);
low = _mm256_mul_ps(low, inv_delta_r);
high = _mm256_mul_ps(high, inv_delta_r);
__m256i lowi = _mm256_cvtps_epi32(low);
__m256i highi = _mm256_cvtps_epi32(high);
__m256i packed16_interleaved4 = _mm256_packus_epi32(lowi, highi); // A B A B
__m256i packed16 = _mm256_permute4x64_epi64(packed16_interleaved4,0b11011000); // A A B B
__m256i offset16 = _mm256_add_epi16(packed16, _mm256_set1_epi16(1));
_mm256_store_si256(t,offset16);
}
for(int i=ksub/16;i<table_size/16;i++){
// Set to zero
__m256i * t = (__m256i*)&qval[i*16];
_mm256_store_si256(t, _mm256_set1_epi16(1));
}
}
#endif
};
/**
* Vectorized Product Quantizer. Implemented only for METRIC_L2
* This is a templated class supporting different SIMD width, and supporting different type of quantizers.
* A few example instantiations are given bellow.
*
* VecProductQuantizer<12,3,6,6,4,0,uint16_t,__m512i,__m512i> // AVX512 - 16 bits distances
* VecProductQuantizer<12,3,5,5,5,0,uint16_t,__m512i,__m512i> // AVX512 - 16 bits distances
* VecProductQuantizer<12,3,6,5,5,0,uint16_t,__m512i,__m512i> // AVX512 - 16 bits distances
* VecProductQuantizer<16,2,4,4,0,0,uint8_t,__m128i,__m128i> // SSE4.2 - 8 bits distances
* VecProductQuantizer<16,2,4,4,0,0,int8_t,_mm128i,__m256i> // AVX256 - 8 bits distances (AVX 256 <- use two 128-bit lanes)
* VecProductQuantizer<16,2,4,4,0,0,int8_t,_mm128i,__m512i> // AVX512 - 8 bits distances (AVX 512 <- use four 128-bit lanes)
* VecProductQuantizer<8,1,8,0,0,0,int8_t,_mm512i,__m512i> // AVX512 - 8 bits distances (256 element table)
*
* Note, it is prefered to put {6,6,4} for quantizer specification, rather than {4,6,6} due to the way remaining dsubs are allocated.
*
*
* @tparam T_M Number of sub_quantizers
* @tparam T_P Number of sub quantizers code that can be stored in a single SIMD element (epi16 or epi8)
* @tparam T_PG_0 Layout in term of bits between subquantizers within a SIMD element (array whose value sum up to the width a of single element)
* @tparam T_PG_1 Layout in term of bits between subquantizers within a SIMD element (array whose value sum up to the width a of single element)
* @tparam T_PG_2 Layout in term of bits between subquantizers within a SIMD element (array whose value sum up to the width a of single element)
* @tparam T_PG_3 Layout in term of bits between subquantizers within a SIMD element (array whose value sum up to the width a of single element)
* @tparam T_TSC Basic type correspond to elements (uint16_t for epi16)
* @tparam T_TSCMM SIMD type desired (__m512i for AVX-512)
* @tparam T_TSCMMXL Specification of cross lanes type (e.g., AVX-256 works as two independent 128-bit lanes, other examples use a single 128 or 512-bit lane).
*/
template<int T_M,int T_P,int T_PG_0, int T_PG_1, int T_PG_2, int T_PG_3, class T_TSC, class T_TSCMM, class T_TSCMMXL> struct AbstractVecProductQuantizer {
typedef CMax<float, long> CHeap;
public:
static constexpr size_t M = T_M; ///< number of subquantizers
// Variants:
// A: 6,6,4 = 16 bits
// B: 5,5,5 = 15 bits + 1 bit padding
// C: 5,5,6 = 16 bits
// D: 4,4 (AVX 256)
// => Repeated M times.
// Interleaving
static constexpr size_t simd_lanes = sizeof(T_TSCMM)/sizeof(T_TSC);
static constexpr size_t simd_lane_width_bits = 8*sizeof(T_TSC);
static constexpr size_t simd_width_bits = simd_lanes * simd_lane_width_bits; // 512
static constexpr size_t simd_width_bytes = simd_width_bits / 8;
static constexpr size_t simd_lane_width_bytes = simd_lane_width_bits / 8;
// Derived values
static constexpr size_t subcodes_per_lane = T_P;
static constexpr size_t lanes_per_code = T_M/subcodes_per_lane;
static constexpr size_t codes_per_group = simd_lanes;
static constexpr size_t group_size_bytes = lanes_per_code * codes_per_group * simd_lane_width_bits;
static constexpr size_t cross_lane=sizeof(T_TSCMMXL)/sizeof(T_TSCMM);
struct group {
union {
T_TSC c[lanes_per_code*codes_per_group] ;
T_TSCMM mm[lanes_per_code];
T_TSCMMXL mmxl[lanes_per_code/cross_lane];
};
};
static_assert(sizeof(T_TSC)*lanes_per_code*codes_per_group == sizeof(T_TSCMM)*lanes_per_code, "Incorrect layout specification");
static_assert(sizeof(T_TSC)*lanes_per_code*codes_per_group == sizeof(T_TSCMMXL)*lanes_per_code/cross_lane, "Incorrect layout specification");
size_t d; ///< size of the input vectors
// Layout (exemple for AVX512 - 16 bit distances)
// a1a2a3 b1b2b3 c1c2c3 ... z1z2z3 = 16 bits x 32 = 512 bits
// a4a5a6 b4b5b6 c4c5c6 ... z4z5z6 = 16 bits x 32 = 512 bits
// a7a8a9 b7b8b9 c7c8c9 ... z7z8z9 = 16 bits x 32 = 512 bits
// axaxax bxbxbx cxcxcx ... zxzxzx = 16 bits x 32 = 512 bits
// Group : 4 (4x3 = 12 subquantizers)
// Layout (example for SSE 4.2 - 8 bit distances)
// a1a2 b1b2 c1c2 ... p1p2 = 8 bits x 16 = 128 bits
// a3a4 b3b4 c3c4 ... p3p4 = 8 bits x 16 = 128 bits
// ...
// axax bxbx cxcx ... pxpx = 8 bits x 16 = 128 bits
// Group : 8 (8x2=16 subquantizers)
// Offset for accessing/reconstructing real vectors.
size_t dsub[T_M]; ///< dimensionality of each subvector
size_t dsub_offset[T_M];
size_t dsub_total;
// Total uncompressed = 128
// * compressed: ceil( 128 * x*6/(x*6 + y*4))=a => encode to y vectors of a/y (rest on last)
// * compressed: 128-a => encode to z vectors of b/z (rest on last)
// Variables for accessing the
size_t csub_nbits[T_M];
size_t csub_register[T_M];
size_t csub_mask_inlane[T_M]; // (mask with offset already applied)
size_t csub_offset_inlane[T_M];
size_t ksub[T_M]; // Number of centroids for each subquantizer
size_t ksub_offset[T_M];
size_t ksub_total;
size_t ksub_sq[T_M]; // Number of centroids for each subquantizer
size_t ksub_sq_offset[T_M];
size_t ksub_sq_total;
size_t dt_lanes[T_M/cross_lane]; // Number of lanes needed for holding distance table (1 or 2)
size_t dt_lanes_offset[T_M/cross_lane]; // Offset of given lanes
size_t dt_lanes_total; // Total number of lanes
// values derived from the above
//size_t byte_per_idx; ///< nb bytes per code component (1 or 2)
//size_t code_size; ///< byte per indexed vector
bool verbose; ///< verbose during training?
bool ultra_verbose; ///< verbose during setup ?
/// initialization
enum train_type_t {
Train_default,
Train_hot_start, ///< the centroids are already initialized
Train_shared, ///< share dictionary accross PQ segments
Train_hypercube, ///< intialize centroids with nbits-D hypercube
Train_hypercube_pca, ///< intialize centroids with nbits-D hypercube
};
train_type_t train_type;
ClusteringParameters cp; ///< parameters used during clustering
/// Centroid table, size Sum(ksub[i]*dsub[i])
std::vector<float> centroids;
size_t centroids_offset[T_M];
size_t centroids_size[T_M];
size_t centroids_total_size; // Sum_i ( ksub[i] * dsub[i]) -- use as a matrix size
/// return the centroids associated with subvector m
float * get_centroids (size_t m, size_t i) {
return ¢roids[centroids_offset[m] + dsub[m]*i];
}
const float * get_centroids (size_t m, size_t i) const {
return ¢roids[centroids_offset[m] + dsub[m]*i];
}
// Train the product quantizer on a set of points. A clustering
// can be set on input to define non-default clustering parameters
void train (int n, const float *x) {
if (train_type != Train_shared) {
train_type_t final_train_type;
final_train_type = train_type;
if (train_type == Train_hypercube ||
train_type == Train_hypercube_pca) {
if (d < T_M/T_P*8*sizeof(T_TSC)) {
final_train_type = Train_default;
printf ("cannot train hypercube: nbits=%ld > log2(d=%ld)\n",
T_M/T_P*8*sizeof(T_TSC), d);
}
}
for (int m = 0; m < M; m++) {
float * xslice = new float[n * dsub[m]];
ScopeDeleter<float> del (xslice);
for (int j = 0; j < n; j++)
memcpy (xslice + j * dsub[m],
x + j * d + dsub_offset[m],
dsub[m] * sizeof(float));
Clustering clus (dsub[m], ksub[m], cp);
// we have some initialization for the centroids
if (final_train_type != Train_default) {
clus.centroids.resize (dsub[m] * ksub[m]);
}
switch (final_train_type) {
case Train_hypercube:
init_hypercube (dsub[m],csub_nbits[m] , n, xslice,
clus.centroids.data ());
break;
case Train_hypercube_pca:
init_hypercube_pca (dsub[m], csub_nbits[m], n, xslice,
clus.centroids.data ());
break;
case Train_hot_start:
memcpy (clus.centroids.data(),
get_centroids (m, 0),
dsub[m] * ksub[m] * sizeof (float));
break;
default: ;
}
if(verbose) {
clus.verbose = true;
printf ("Training PQ slice %d/%zd\n", m, M);
}
IndexFlatL2 index (dsub[m]);
clus.train (n, xslice, index);
set_params (clus.centroids.data(), m);
}
} else {
FAISS_THROW_IF_NOT (false);
#if 0
// This code path has not been updated for PQ with sub quantizers of unequal width.
Clustering clus (dsub, ksub, cp);
if(verbose) {
clus.verbose = true;
printf ("Training all PQ slices at once\n");
}
IndexFlatL2 index (dsub);
clus.train (n * M, x, index);
for (int m = 0; m < M; m++) {
set_params (clus.centroids.data(), m);
}
#endif
}
}
AbstractVecProductQuantizer(size_t d) : /* dimensionality of the input vectors */
d(d) {
set_derived_values();
}
AbstractVecProductQuantizer () :
d(0)
{
set_derived_values();
}
virtual ~AbstractVecProductQuantizer ()
{ }
inline int t_pg(int i){
switch(i){
case 0: return T_PG_0;
case 1: return T_PG_1;
case 2: return T_PG_2;
case 3: return T_PG_3;
default: FAISS_THROW_MSG("UNSUPPORT T_P SPECIFICATION");
}
}
inline int t_pgp(int i){
//return std::pow((double)t_pg(i),(double)1.25);
return t_pg(i);
}
/* Number of groups needed for storing n vectors */
static size_t nb_groups(size_t n){
return (n+codes_per_group-1)/codes_per_group;
}
/// compute derived values when d, M and nbits have been set
void set_derived_values () {
verbose = false;
ultra_verbose = false;
// quite a few derived values
// FAISS_THROW_IF_NOT (d % M == 0); // To support 12 sub quantizers, we have to deal with such case.
FAISS_THROW_IF_NOT (d % lanes_per_code == 0);
size_t dsub_per_lane = d / lanes_per_code;
if(ultra_verbose) std::cout << "d " << d << std::endl;
size_t bits_per_lane = t_pgp(0)+t_pgp(1)+t_pgp(2)+t_pgp(3);
//size_t bits_per_lane = T_PG_0 + T_PG_1 + T_PG_2 + T_PG_3;
size_t dsub_per_bit = dsub_per_lane / bits_per_lane;
size_t dsub_lane[T_P];
size_t consumed_dsubs=0;
for(size_t i=0;i<T_P;i++){
dsub_lane[i]=dsub_per_bit * t_pgp(i);
// dsub_lane[i]=dsub_per_bit * t_pg(i);
consumed_dsubs += dsub_lane[i];
}
// Assign remaining dsubs
for(size_t i=0; consumed_dsubs < dsub_per_lane ; i=(i+1)%T_P){
dsub_lane[i] += 1;
consumed_dsubs += 1;
}
if(ultra_verbose){
for(size_t i=0;i<T_P;i++){
std::cout << "dsub_lane[" << i<<"] " << dsub_lane[i] << std::endl;
}
}
// Compute the dsub_offsets;
size_t current_centroid_offset_inlane=0;
dsub_total=0;
ksub_total=0;
dt_lanes_total=0;
ksub_sq_total=0;
centroids_total_size=0;
for(size_t i=0,j=0;i<M;i++,j=i%T_P){
dsub[i]=dsub_lane[j];
dsub_offset[i]=dsub_total;
dsub_total+=dsub[i];
ksub[i]=1 << t_pg(j);
ksub_offset[i]=ksub_total;
ksub_total+=ksub[i];
ksub_sq[i]=ksub[i]*ksub[i];
ksub_sq_offset[i]=ksub_sq_total;
ksub_sq_total+=ksub_sq[i];
centroids_offset[i]=centroids_total_size;
centroids_size[i]=dsub[i]*ksub[i];
centroids_total_size+=dsub[i]*ksub[i];
csub_nbits[i] = t_pg(j);
csub_register[i] = i/T_P;
csub_offset_inlane[i] = current_centroid_offset_inlane;
csub_mask_inlane[i] = ((1 << t_pg(j)) - 1) << current_centroid_offset_inlane;
current_centroid_offset_inlane= j == T_P-1 ? 0 : current_centroid_offset_inlane + t_pg(j);
if(ultra_verbose){
std::cout << "dsub[" << i << "] " << dsub[i] << std::endl;
std::cout << "dsub_offset[" << i << "]" << dsub_offset[i] << std::endl;
std::cout << "ksub[" << i << "] " << ksub[i] << std::endl;
std::cout << "ksub_offset[" << i << "] " << ksub_offset[i] << std::endl;
std::cout << "ksub_sq[" << i << "] " << ksub_sq[i] << std::endl;
std::cout << "ksub_sq_offset[" << i << "] " << ksub_sq_offset[i] << std::endl;
std::cout << "centroids_offset[" << i << "] " << centroids_offset[i] << std::endl;
std::cout << "centroids_size[" << i << "] " << centroids_size[i] << std::endl;
std::cout << "csub_nbits[" << i << "] " << csub_nbits[i] << std::endl;
std::cout << "csub_register[" << i << "] " << csub_register[i] << std::endl;
std::cout << "csub_offset_inlane[" << i << "] " << csub_offset_inlane[i] << std::endl;
std::cout << "csub_mask_inlane[" << i << "] " << std::hex << csub_mask_inlane[i] << std::dec << std::endl;
}
}
for(size_t i=0;i<M/T_P/cross_lane;i++){
for(size_t j=0;j<T_P;j++){
dt_lanes[i*T_P+j]=(ksub[i*cross_lane*T_P+j]+simd_lanes-1)/simd_lanes*cross_lane;
dt_lanes_offset[i*T_P+j]=dt_lanes_total;
dt_lanes_total+=dt_lanes[i*T_P+j];
}
if(ultra_verbose){
for(size_t j=0;j<T_P;j++){
std::cout << "dt_lanes[" << i*T_P+j << "] " << dt_lanes[i*T_P+j] << std::endl;
std::cout << "dt_lanes_offset[" << i*T_P+j << "] " << dt_lanes_offset[i*T_P+j] << std::endl;
}
}
}
//byte_per_idx = (nbits + 7) / 8;
//code_size = byte_per_idx * M;
if(ultra_verbose){
std::cout << "dsub_total: " << dsub_total << std::endl;
std::cout << "ksub_total " << ksub_total << std::endl;
std::cout << "ksub_sq_total " << ksub_sq_total << std::endl;
std::cout << "centroids_total_size " << centroids_total_size << std::endl;
std::cout << "dt_lanes_total " << dt_lanes_total << std::endl;
}
centroids.resize(centroids_total_size);
train_type = Train_default;
}
/// Define the centroids for subquantizer m
void set_params (const float * centroids_, int m){
memcpy (get_centroids(m, 0), centroids_,
ksub[m] * dsub[m] * sizeof (centroids_[0]));
}
inline void set_code_component(group * codes, size_t idx, size_t m, unsigned val) const {
/* Merge with other subquantizer indexes */
int group_index = idx / codes_per_group;
int index_in_group = idx % codes_per_group;
T_TSC c = codes[group_index].c[codes_per_group*csub_register[m]+index_in_group];
c = c & ~csub_mask_inlane[m];
c = c | (val << csub_offset_inlane[m]);
codes[group_index].c[codes_per_group*csub_register[m]+index_in_group] = c;
}
inline unsigned get_code_component(const group * codes, size_t idx, size_t m) const {
/* Merge with other subquantizer indexes */
int group_index = idx / codes_per_group;
int index_in_group = idx % codes_per_group;
T_TSC c = codes[group_index].c[codes_per_group*csub_register[m]+index_in_group];
return (c & csub_mask_inlane[m]) >> csub_offset_inlane[m];
}
/// Quantize one vector with the product quantizer
void encode (const float * x, group * codes, size_t idx) const {
for (size_t m = 0; m < M; m++) {
float distances [ksub[m]];
float mindis = 1e20;
unsigned idxm = 0;
const float * xsub = x + dsub_offset[m];
fvec_L2sqr_ny (distances, xsub, get_centroids(m, 0), dsub[m], ksub[m]);
/* Find best centroid */
size_t i;
for (i = 0; i < ksub[m]; i++) {
float dis = distances [i];
if (dis < mindis) {
mindis = dis;
idxm = i;
}
}
set_code_component(codes, idx, m, idxm);
}
}
/// same as compute_code for several vectors
void encode_multiple (const float * x,
group * codes, size_t offset_idx,
size_t n) const {
if (d/M < 16) { // simple direct computation
#pragma omp parallel for
for (size_t i = 0; i < n; i++)
encode(x + i * d, codes, i+offset_idx);
} else { // worthwile to use BLAS
float *dis_tables = new float [n * ksub_total];
ScopeDeleter<float> del (dis_tables);
compute_distance_tables (n, x, dis_tables);
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
const float * tab = dis_tables + i * ksub_total;
encode_from_distance_table (tab, codes, i+offset_idx);
}
}
}
void copy_code(group * codes_dst, size_t offset_dst, const group* codes_src, size_t offset_src, size_t n) {
for(size_t i=0;i<n;i++){
for(size_t m=0;m < M; m++){
set_code_component(codes_dst, i+offset_dst, m, get_code_component(codes_src, i+offset_src, m));
}
}
}
void append_codes(std::vector<group, boost::alignment::aligned_allocator<group, 64>>& codes_dst,size_t * count_dst, const group* codes_src, size_t offset_src, size_t n) {
if(codes_dst.size() < nb_groups(n+*count_dst)) codes_dst.resize(nb_groups(n+*count_dst));
copy_code(codes_dst.data(),*count_dst,codes_src,offset_src,n);
(*count_dst)+=n;
}
/// decode a vector from a given code (or n vectors if third argument)
void decode(const group *codes, float *x, size_t idx) const{
for (size_t m = 0; m < M; m++) {
memcpy(x + dsub_offset[m], get_centroids(m, get_code_component(codes, idx, m)),
sizeof(float) * dsub[m]);
}
}
void decode_multiple(const group *codes, float *x, size_t offset_idx, size_t n) const{
for (size_t i = 0; i < n; i++) {
this->decode(codes, x + d * i, i+offset_idx);
}
}
/// If we happen to have the distance tables precomputed, this is
/// more efficient to compute the codes.
inline void encode_from_distance_table (const float *tab,
group *codes, size_t idx) const {
for (size_t m = 0; m < M; m++) {
float mindis = 1e20;
unsigned idxm = 0;
/* Find best centroid */
for (size_t j = 0; j < ksub[m]; j++) {
float dis = *tab++;
if (dis < mindis) {