-
Notifications
You must be signed in to change notification settings - Fork 21.3k
/
QuantizedOpKernels.cpp
2849 lines (2644 loc) · 101 KB
/
QuantizedOpKernels.cpp
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
#include <ATen/ATen.h>
#include <ATen/Dispatch.h>
#include <ATen/Parallel.h>
#include <ATen/native/SortingUtils.h>
#include <ATen/native/TensorIterator.h>
#include <ATen/native/UpSample.h>
#include <ATen/native/cpu/Loops.h>
#include <ATen/native/quantized/affine_quantizer.h>
#include <ATen/native/quantized/cpu/quantized_ops.h>
#include <cmath>
#ifdef USE_FBGEMM
#include <fbgemm/QuantUtils.h>
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
#if defined(__ARM_NEON__) || defined(__aarch64__)
#include <ATen/quantized/Quantizer.h>
#include <arm_neon.h>
#endif
namespace at {
namespace native {
namespace {
void check_tensor_memory_format(const Tensor& ref, const Tensor& other) {
TORCH_CHECK(
ref.is_contiguous(ref.suggest_memory_format()),
"Quantized tensor should be contiguous");
TORCH_CHECK(
other.is_contiguous(ref.suggest_memory_format()),
"Float tensor should be contiguous "
"in same memory format as quantizd tensor");
}
// ****************** HEY YOU! YES YOU! Read this! ********************
//
// Please read the README.md in this directory before editing this file
template <bool ReLUFused = false>
Tensor qcat_nhwc_kernel(
const c10::List<Tensor>& qxs,
int64_t dim,
double scale,
int64_t zero_point) {
const at::Tensor& qx0 = qxs[0];
int64_t C_out = 0;
std::vector<int64_t> Cs_in;
// Prefix sum of input channels for fast indexing
std::vector<int64_t> Cs_sum;
std::vector<double> scales;
std::vector<int64_t> zero_pts;
std::vector<void*> data_ptrs;
for (const at::Tensor& qx : qxs) {
TORCH_CHECK(
qx.dim() == qx0.dim(),
"Tensors must have the same number of dimensions: got ",
qx.dim(),
" and ",
qx0.dim());
#define CHECK_DIM(d) \
TORCH_CHECK( \
qx.size(d) == qx0.size(d), \
"Sizes of tensors must match expect in dimension 1. Got", \
qx.size(d), \
" and ", \
qx0.size(d));
CHECK_DIM(0);
CHECK_DIM(2);
CHECK_DIM(3);
TORCH_CHECK(
qx.scalar_type() == qx0.scalar_type(),
"Expected object of scalar type ",
toString(qx0.scalar_type()),
" but got scalar type ",
toString(qx.scalar_type()));
Cs_in.push_back(qx.size(1));
Cs_sum.push_back(C_out);
C_out += qx.size(1);
scales.push_back(qx.q_scale());
zero_pts.push_back(qx.q_zero_point());
data_ptrs.push_back(qx.data_ptr());
}
const int64_t N = qx0.size(0);
const int64_t H = qx0.size(2);
const int64_t W = qx0.size(3);
float inv_scale = 1.0 / scale;
auto output = at::_empty_affine_quantized(
{N, C_out, H, W},
qx0.options().memory_format(MemoryFormat::ChannelsLast),
scale,
zero_point,
c10::nullopt);
// N, H, and W are explicitly captured here because there's a bug in GCC5
// which causes an internal compiler error if they're not
AT_DISPATCH_QINT_TYPES(output.scalar_type(), "qcat_nhwc", [&, N, H, W]() {
using Vec = Vec256<scalar_t>;
for (int64_t batch = 0; batch < N; ++batch) {
for (int64_t row = 0; row < H; ++row) {
for (int64_t col = 0; col < W; ++col) {
// loop over input tensors
for (int64_t tidx = 0; tidx < Cs_in.size(); ++tidx) {
scalar_t::underlying* optr =
reinterpret_cast<scalar_t::underlying*>(output.data_ptr()) +
batch * H * W * C_out + row * W * C_out + col * C_out +
Cs_sum[tidx];
auto curr_C = Cs_in[tidx];
float curr_scale = scales[tidx];
int64_t curr_zero_pt = zero_pts[tidx];
scalar_t::underlying* iptr =
reinterpret_cast<scalar_t::underlying*>(data_ptrs[tidx]) +
batch * H * W * curr_C + row * W * curr_C + col * curr_C;
constexpr int64_t VLEN = Vec::size();
int64_t c = 0;
// Vectorized loop
if (c + VLEN <= curr_C) {
auto curr_scale_vec = Vec256<float>(curr_scale);
auto curr_zero_pt_vec = Vec256<float>((float)curr_zero_pt);
auto scale_neg_zp_premul = curr_scale_vec * curr_zero_pt_vec.neg();
for (; c + VLEN <= curr_C; c += VLEN) {
auto inp_vec = Vec::loadu(iptr + c);
auto float_values = inp_vec.dequantize(
curr_scale_vec, curr_zero_pt_vec, scale_neg_zp_premul);
Vec::float_vec_return_type retvals;
for (int i = 0; i < Vec::float_num_vecs(); ++i) {
if (ReLUFused) {
retvals[i] =
vec256::maximum(float_values[i], Vec256<float>(0.0f));
} else {
retvals[i] = float_values[i];
}
}
auto quantized =
Vec::quantize(retvals, scale, zero_point, inv_scale);
quantized.store(optr + c);
}
}
// Scalar loop
for (; c < curr_C; ++c) {
auto float_val = at::native::dequantize_val(
curr_scale,
curr_zero_pt,
reinterpret_cast<scalar_t*>(iptr)[c]);
if (ReLUFused) {
float_val = std::max(0.0f, float_val);
}
optr[c] = at::native::quantize_val<scalar_t>(
scale, zero_point, float_val)
.val_;
} // for c
} // for tidx
} // for col
} // for row
} // for b
});
return output;
}
// horizontal sum over a range of uint8_t
int64_t hsum(const uint8_t* A, int len) {
int64_t row_sum = 0;
int i = 0;
#ifdef CPU_CAPABILITY_AVX2
__m256i sum_v = _mm256_setzero_si256();
__m256i one_epi16_v = _mm256_set1_epi16(1);
__m256i one_epi8_v = _mm256_set1_epi8(1);
// vectorized
for (; i < len / 32 * 32; i += 32) {
__m256i src_v = _mm256_loadu_si256(reinterpret_cast<__m256i const*>(A + i));
sum_v = _mm256_add_epi32(
sum_v,
_mm256_madd_epi16(
// first argument is unsigned, second is signed
_mm256_maddubs_epi16(src_v, one_epi8_v),
one_epi16_v)
);
}
alignas(64) int32_t temp[8];
_mm256_store_si256(reinterpret_cast<__m256i*>(temp), sum_v);
for (int k = 0; k < 8; ++k) {
row_sum += temp[k];
}
#endif // CPU_CAPABILITY_AVX2
// scalar
for (; i < len; ++i) {
row_sum += A[i];
}
return row_sum;
}
// horizontal sum over a range of int8_t
int64_t hsum(const int8_t* A, int len) {
int64_t row_sum = 0;
int i = 0;
#ifdef CPU_CAPABILITY_AVX2
__m256i sum_v = _mm256_setzero_si256();
__m256i one_epi16_v = _mm256_set1_epi16(1);
__m256i one_epi8_v = _mm256_set1_epi8(1);
// vectorized
for (; i < len / 32 * 32; i += 32) {
__m256i src_v = _mm256_loadu_si256(reinterpret_cast<__m256i const*>(A + i));
sum_v = _mm256_add_epi32(
sum_v,
_mm256_madd_epi16(
// first argument is unsigned, second is signed
_mm256_maddubs_epi16(one_epi8_v, src_v),
one_epi16_v)
);
}
alignas(64) int32_t temp[8];
_mm256_store_si256(reinterpret_cast<__m256i*>(temp), sum_v);
for (int k = 0; k < 8; ++k) {
row_sum += temp[k];
}
#endif // CPU_CAPABILITY_AVX2
// scalar
for (; i < len; ++i) {
row_sum += A[i];
}
return row_sum;
}
// horizontal sum over a range of int32_t
int64_t hsum(const int32_t* A, int len) {
int64_t row_sum = 0;
int i = 0;
#ifdef CPU_CAPABILITY_AVX2
__m256i sum_epi64 = _mm256_setzero_si256();
// vectorized
for (; i < len / 8 * 8; i += 8) {
__m256i src_epi32 = _mm256_loadu_si256(reinterpret_cast<__m256i const*>(A + i));
// widen
__m128i src_lo_epi32 = _mm256_castsi256_si128(src_epi32);
__m128i src_hi_epi32 = _mm256_extractf128_si256(src_epi32, 1);
__m256i src_lo_epi64 = _mm256_cvtepi32_epi64(src_lo_epi32);
__m256i src_hi_epi64 = _mm256_cvtepi32_epi64(src_hi_epi32);
// add
sum_epi64 = _mm256_add_epi64(sum_epi64, src_lo_epi64);
sum_epi64 = _mm256_add_epi64(sum_epi64, src_hi_epi64);
}
alignas(64) int64_t temp[4];
_mm256_store_si256(reinterpret_cast<__m256i*>(temp), sum_epi64);
for (int k = 0; k < 4; ++k) {
row_sum += temp[k];
}
#endif // CPU_CAPABILITY_AVX2
// scalar
for (; i < len; ++i) {
row_sum += A[i];
}
return row_sum;
}
// horizontal sum of squares over a range of uint8_t
int64_t hsum_sq(const uint8_t* A, int len) {
int64_t row_sum = 0;
int i = 0;
#ifdef CPU_CAPABILITY_AVX2
__m256i sum_v_epu32 = _mm256_setzero_si256();
// vectorized
for (; i < len / 16 * 16; i += 16) {
// (i15, ..., i0)
__m128i src_epu8 = _mm_loadu_si128(reinterpret_cast<__m128i const*>(A + i));
__m256i src_epu16 = _mm256_cvtepu8_epi16(src_epu8);
// (i15 ^ 2, ..., i0 ^ 2)
__m256i sq_epu16 = _mm256_mullo_epi16(src_epu16, src_epu16);
// (i7 ^ 2, ..., i0 ^ 2)
__m128i sq_lo_epu16 = _mm256_castsi256_si128(sq_epu16);
// (i15 ^ 2, ..., i8 ^ 2)
__m128i sq_hi_epu16 = _mm256_extractf128_si256(sq_epu16, 1);
// widen to epu32
__m256i sq_lo_epu32 = _mm256_cvtepu16_epi32(sq_lo_epu16);
__m256i sq_hi_epu32 = _mm256_cvtepu16_epi32(sq_hi_epu16);
// add to running sum
sum_v_epu32 = _mm256_add_epi32(sum_v_epu32, sq_lo_epu32);
sum_v_epu32 = _mm256_add_epi32(sum_v_epu32, sq_hi_epu32);
}
alignas(64) int32_t temp[8];
_mm256_store_si256(reinterpret_cast<__m256i*>(temp), sum_v_epu32);
for (int k = 0; k < 8; ++k) {
row_sum += temp[k];
}
#endif // CPU_CAPABILITY_AVX2
// scalar
for (; i < len; ++i) {
row_sum += A[i] * A[i];
}
return row_sum;
}
// horizontal sum of squares over a range of int8_t
int64_t hsum_sq(const int8_t* A, int len) {
int64_t row_sum = 0;
int i = 0;
#ifdef CPU_CAPABILITY_AVX2
__m256i sum_v_epi32 = _mm256_setzero_si256();
// vectorized
for (; i < len / 16 * 16; i += 16) {
// (i15, ..., i0)
__m128i src_epi8 = _mm_loadu_si128(reinterpret_cast<__m128i const*>(A + i));
__m256i src_epi16 = _mm256_cvtepi8_epi16(src_epi8);
// (i15 ^ 2, ..., i0 ^ 2)
__m256i sq_epi16 = _mm256_mullo_epi16(src_epi16, src_epi16);
// (i7 ^ 2, ..., i0 ^ 2)
__m128i sq_lo_epi16 = _mm256_castsi256_si128(sq_epi16);
// (i15 ^ 2, ..., i8 ^ 2)
__m128i sq_hi_epi16 = _mm256_extractf128_si256(sq_epi16, 1);
// widen to epi32
__m256i sq_lo_epi32 = _mm256_cvtepi16_epi32(sq_lo_epi16);
__m256i sq_hi_epi32 = _mm256_cvtepi16_epi32(sq_hi_epi16);
// add to running sum
sum_v_epi32 = _mm256_add_epi32(sum_v_epi32, sq_lo_epi32);
sum_v_epi32 = _mm256_add_epi32(sum_v_epi32, sq_hi_epi32);
}
alignas(64) int32_t temp[8];
_mm256_store_si256(reinterpret_cast<__m256i*>(temp), sum_v_epi32);
for (int k = 0; k < 8; ++k) {
row_sum += temp[k];
}
#endif // CPU_CAPABILITY_AVX2
// scalar
for (; i < len; ++i) {
row_sum += A[i] * A[i];
}
return row_sum;
}
// horizontal sum os squares over a range of int32_t
// floats throughout are necessary to prevent overflow
float hsum_sq(const int32_t* A, int len) {
float row_sum = 0;
int i = 0;
#ifdef CPU_CAPABILITY_AVX2
__m256 sum_ps = _mm256_setzero_ps();
// vectorized
for (; i < len / 8 * 8; i += 8) {
__m256i src_epi32 = _mm256_loadu_si256(reinterpret_cast<__m256i const*>(A + i));
__m256 src_ps = _mm256_cvtepi32_ps(src_epi32);
sum_ps = _mm256_add_ps(sum_ps, _mm256_mul_ps(src_ps, src_ps));
}
alignas(64) float temp[8];
_mm256_store_ps(temp, sum_ps);
for (int k = 0; k < 8; ++k) {
row_sum += static_cast<float>(temp[k]);
}
#endif // CPU_CAPABILITY_AVX2
// scalar
for (; i < len; ++i) {
int64_t cur = static_cast<int64_t>(A[i]);
row_sum += (float)cur * (float)cur;
}
return row_sum;
}
void qrelu_kernel(const Tensor& qx, Tensor& qy) {
const auto zero_point = qx.q_zero_point();
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qrelu", [&]() {
qy = at::_empty_affine_quantized(
qx.sizes(),
at::device(kCPU).dtype(SCALAR_TYPE).memory_format(qx.suggest_memory_format()),
qx.q_scale(),
qx.q_zero_point(),
c10::nullopt);
using Vec = Vec256<scalar_t>;
auto zero_point_vec = Vec(scalar_t(zero_point));
auto iter = TensorIterator::unary_op(qy, qx);
cpu_kernel_vec(
iter,
[&](scalar_t value) -> scalar_t {
return scalar_t(std::max<underlying_t>(value.val_, zero_point));
},
[&](Vec value) -> Vec { return value.relu(zero_point_vec); });
});
}
void qrelu6_kernel(const Tensor& qx, Tensor& qy) {
const auto zero_point = qx.q_zero_point();
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qrelu6", [&]() {
qy = at::_empty_affine_quantized(
qx.sizes(),
at::device(kCPU).dtype(SCALAR_TYPE).memory_format(qx.suggest_memory_format()),
qx.q_scale(),
qx.q_zero_point(),
c10::nullopt);
using Vec = Vec256<scalar_t>;
auto iter = TensorIterator::unary_op(qy, qx);
scalar_t six = at::native::quantize_val<scalar_t>(
qx.q_scale(), qx.q_zero_point(), 6.0);
auto zero_point_vec = Vec(scalar_t(zero_point));
auto six_vec = Vec(six);
cpu_kernel_vec(
iter,
[&](scalar_t value) -> scalar_t {
underlying_t relu_val =
std::max<underlying_t>(value.val_, zero_point);
return scalar_t(std::min<underlying_t>(relu_val, six.val_));
},
[&](Vec val) -> Vec { return val.relu6(zero_point_vec, six_vec); });
});
}
static void leaky_qrelu_out_kernel(Tensor& out, const Tensor& qx,
Scalar negval_) {
int64_t i_zp = qx.q_zero_point();
float i_scale = qx.q_scale();
int64_t o_zp = out.q_zero_point();
float o_scale = out.q_scale();
float o_inv_scale = 1.0f / o_scale;
float negval = negval_.to<float>();
AT_DISPATCH_QINT_TYPES(out.scalar_type(), "leaky_qrelu", [&] {
using Vec = Vec256<float>; // Naive implementation uses dequant/quant loop.
using qVec = Vec256<scalar_t>;
Vec zero_vec = Vec(0.0f);
Vec one_vec = Vec(1.0f);
Vec i_scale_vec = Vec((float)i_scale);
Vec i_zp_vec = Vec((float)i_zp);
Vec i_scale_zp_neg_premul_vec = i_scale_vec * i_zp_vec.neg();
Vec negval_vec = Vec(negval);
auto iter = TensorIterator::unary_op(out, qx);
cpu_kernel_vec(
iter,
[&](scalar_t value_qx) -> scalar_t {
auto value_dx = at::native::dequantize_val(i_scale, i_zp, value_qx);
auto value_dy = value_dx > 0 ? value_dx : value_dx * negval;
return at::native::quantize_val<scalar_t>(o_scale, o_zp, value_dy);
},
[&](qVec qx_vec) -> qVec {
/* Vectorized implementation creates a multiplicand vector, which has
* "alpha" for all negative dx values and ones-vector for all
* positive values of dx. The multiplicand then is multiplied by the
* input.
*/
auto dx_vec_vec = qx_vec.dequantize(i_scale_vec, i_zp_vec,
i_scale_zp_neg_premul_vec);
for (int idx = 0; idx < dx_vec_vec.size(); ++idx) {
const auto dx_vec = dx_vec_vec[idx];
const auto multiplicand = Vec::blendv(negval_vec, one_vec,
dx_vec > zero_vec);
dx_vec_vec[idx] = dx_vec * multiplicand;
}
return qVec::quantize(dx_vec_vec, o_scale, o_zp, o_inv_scale);
});
});
}
void qsigmoid_kernel(
const Tensor& qx, Tensor& qy, double output_scale, int64_t output_zero_point ) {
int64_t zero_point = qx.q_zero_point();
float scale = qx.q_scale();
auto scale_vec = Vec256<float>(scale);
auto zero_point_vec = Vec256<float>((float)zero_point);
auto scale_neg_zp_premul_vec = scale_vec * zero_point_vec.neg();
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qsigmoid", [&]() {
float inv_output_scale = 1.0 / output_scale;
qy = at::_empty_affine_quantized(
qx.sizes(),
at::device(kCPU).dtype(SCALAR_TYPE).memory_format(qx.suggest_memory_format()),
output_scale,
output_zero_point,
c10::nullopt);
auto iter = TensorIterator::unary_op(qy, qx);
using Vec = Vec256<scalar_t>;
cpu_kernel_vec(
iter,
[&](scalar_t value_qx) -> scalar_t {
const auto value_dx =
at::native::dequantize_val(scale, zero_point, value_qx);
const auto value_dy = 1.0f / (1.0 + std::exp((-value_dx)));
return at::native::quantize_val<scalar_t>(
output_scale, output_zero_point, value_dy);
},
[&](Vec value_qx) -> Vec {
auto value_dx = value_qx.dequantize(
scale_vec, zero_point_vec, scale_neg_zp_premul_vec);
for (int idx = 0; idx < value_dx.size(); ++idx) {
value_dx[idx] = value_dx[idx].neg();
value_dx[idx] = value_dx[idx].exp();
value_dx[idx] = Vec256<float>(1.0f) + value_dx[idx];
value_dx[idx] = value_dx[idx].reciprocal();
}
return Vec::quantize(
value_dx, output_scale, output_zero_point, inv_output_scale);
});
});
}
void qhardsigmoid_kernel(const Tensor& qx, Tensor& qy) {
int64_t zero_point = qx.q_zero_point();
float scale = qx.q_scale();
auto scale_vec = Vec256<float>(scale);
auto zero_point_vec = Vec256<float>((float)zero_point);
auto scale_neg_zp_premul_vec = scale_vec * zero_point_vec.neg();
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qhardsigmoid", [&]() {
// - Output scale is set to 1.0 / 2^(BIT_NUM)
float output_scale = 0.00390625; // 1.0 / 2^8
if (SCALAR_TYPE == at::kQInt32) {
output_scale = 2.3283064365386963e-10; // 1.0 / 2^32
}
float inv_output_scale = 1.0 / output_scale;
// The default zero-point is zero. As a one-off optimization for
// kQInt8, we set the zero-point to -128 to maximize precision in the
// [0, 1] output range. kQInt32 can be handled in a future PR if needed.
int64_t output_zero_point = 0;
if (SCALAR_TYPE == at::kQInt8) {
output_zero_point = -128;
}
qy = at::_empty_affine_quantized(
qx.sizes(),
at::device(kCPU).dtype(SCALAR_TYPE),
output_scale,
output_zero_point,
qx.suggest_memory_format());
auto iter = TensorIterator::unary_op(qy, qx);
using qVec = Vec256<scalar_t>;
using fVec = Vec256<float>;
fVec kZeroVec(0.0f);
fVec kThreeVec(3.0f);
fVec kSixVec(6.0f);
// Naive implemenentation: uses dequantize/execute/quantize routine
cpu_kernel_vec(
iter,
[&](scalar_t qx) -> scalar_t {
auto x = at::native::dequantize_val(scale, zero_point, qx);
const auto y = std::min(std::max(x + 3.0f, 0.0f), 6.0f) / 6.0f;
return at::native::quantize_val<scalar_t>(
output_scale, output_zero_point, y);
},
[&](qVec value_qx) -> qVec {
auto value_dx = value_qx.dequantize(
scale_vec, zero_point_vec, scale_neg_zp_premul_vec);
for (int idx = 0; idx < value_dx.size(); ++idx) {
value_dx[idx] =
vec256::minimum(
vec256::maximum(value_dx[idx] + kThreeVec, kZeroVec),
kSixVec) /
kSixVec;
}
return qVec::quantize(
value_dx, output_scale, output_zero_point, inv_output_scale);
});
});
}
void qclamp_kernel(
const Tensor& qx,
Scalar min_scalar,
Scalar max_scalar,
Tensor& qy) {
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qclamp", [&]() {
qy = at::_empty_affine_quantized(
qx.sizes(),
at::device(kCPU).dtype(SCALAR_TYPE).memory_format(qx.suggest_memory_format()),
qx.q_scale(),
qx.q_zero_point(),
c10::nullopt);
using Vec = Vec256<scalar_t>;
auto iter = TensorIterator::unary_op(qy, qx);
auto min = min_scalar.to<float>();
auto max = max_scalar.to<float>();
scalar_t min_q = at::native::quantize_val<scalar_t>(
qx.q_scale(), qx.q_zero_point(), min);
scalar_t max_q = at::native::quantize_val<scalar_t>(
qx.q_scale(), qx.q_zero_point(), max);
auto min_vec = Vec(min_q);
auto max_vec = Vec(max_q);
cpu_kernel_vec(
iter,
[&](scalar_t value) -> scalar_t {
underlying_t min_clamped =
std::max<underlying_t>(value.val_, min_q.val_);
return scalar_t(std::min<underlying_t>(min_clamped, max_q.val_));
},
[&](Vec val) -> Vec {
auto min_clamped = val.maximum(min_vec);
return min_clamped.minimum(max_vec);
});
});
}
void qthreshold_kernel(
// TODO: For future tasks, since output quantization parameters are set equal to
// the input ones, it might make sense to implement this completely in the
// quantized domain.
const Tensor& qx,
Scalar threshold_scalar,
Scalar value_scalar,
Tensor& qy) {
// defines input and output scales and zero_points
int64_t input_zero_point = qx.q_zero_point();
float input_scale = qx.q_scale();
int64_t output_zero_point = qy.q_zero_point();
float output_scale = qy.q_scale();
float inv_output_scale = 1.0 / output_scale;
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qthreshold", [&]() {
qy = at::_empty_affine_quantized(
qx.sizes(),
at::device(kCPU).dtype(SCALAR_TYPE).memory_format(qx.suggest_memory_format()),
qx.q_scale(),
qx.q_zero_point(),
c10::nullopt);
// vectorized
using Vec = Vec256<float>;
using qVec = Vec256<scalar_t>;
// defines the iterator
auto iter = TensorIterator::unary_op(qy, qx);
// defines the vectorized versions
Vec input_scale_vec = Vec(input_scale);
Vec input_zero_point_vec = Vec(input_zero_point);
Vec input_scale_neg_zp_premul_vec = input_scale_vec * input_zero_point_vec.neg();
// defines the floating-point versions of threshold and value
float threshold_float = threshold_scalar.to<float>();
float value_float = value_scalar.to<float>();
Vec threshold_vec = Vec(threshold_float);
Vec value_vec = Vec(value_float);
// Naive implemenentation: uses dequantize/execute/quantize routine
cpu_kernel_vec(
iter,
[&](scalar_t value_qx) -> scalar_t {
// dequantize
const auto x = at::native::dequantize_val(input_scale, input_zero_point, value_qx);
// Applies the Threshold operation
const auto y = x > threshold_float ? x : value_float;
// quantize
return at::native::quantize_val<scalar_t>(output_scale, output_zero_point, y);
},
[&](qVec value_qx) -> qVec {
// dequantize
auto dx_vec = value_qx.dequantize(
input_scale_vec, input_zero_point_vec, input_scale_neg_zp_premul_vec);
for (int idx = 0; idx < dx_vec.size(); ++idx) {
// check if any elements are below threshold
auto cmp_to_threshold = dx_vec[idx] > threshold_vec;
if (cmp_to_threshold.zero_mask()) {
// blend
dx_vec[idx] = Vec::blendv(value_vec, dx_vec[idx], cmp_to_threshold);
}
}
// quantize
return qVec::quantize(dx_vec, output_scale, output_zero_point, inv_output_scale);
});
});
}
void qhardswish_kernel(const Tensor& qx, Tensor& qy) {
const auto i_scale = qx.q_scale();
const auto i_zero_point = qx.q_zero_point();
const auto o_scale = qy.q_scale();
const auto o_zero_point = qy.q_zero_point();
const float o_inv_scale = 1.0 / o_scale;
using fVec = Vec256<float>;
fVec i_scale_vec(i_scale);
fVec i_zero_point_vec(i_zero_point);
fVec i_scale_neg_zp_premul_vec = i_scale_vec * i_zero_point_vec.neg();
fVec zero_vec(0.0f);
fVec three_vec(3.0f);
fVec six_vec(6.0f);
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qhardswish", [&]() {
using qVec = Vec256<scalar_t>;
auto iter = TensorIterator::unary_op(qy, qx);
cpu_kernel_vec(
iter,
[&](scalar_t value) -> scalar_t {
const auto x =
at::native::dequantize_val(i_scale, i_zero_point, value);
const auto y = x * std::min(std::max(x + 3.0f, 0.0f), 6.0f) / 6.0f;
return at::native::quantize_val<scalar_t>(o_scale, o_zero_point, y);
},
[&](qVec value) -> qVec {
auto value_dx = value.dequantize(i_scale_vec, i_zero_point_vec,
i_scale_neg_zp_premul_vec);
for (int idx = 0; idx < value_dx.size(); idx++) {
value_dx[idx] = value_dx[idx] * vec256::minimum(
vec256::maximum(value_dx[idx] + three_vec, zero_vec),
six_vec
) / six_vec;
}
return qVec::quantize(value_dx, o_scale, o_zero_point, o_inv_scale);
});
});
}
void qtanh_kernel(const Tensor& qx, Tensor& qy) {
int64_t zero_point = qx.q_zero_point();
float scale = qx.q_scale();
auto scale_vec = Vec256<float>(scale);
auto zero_point_vec = Vec256<float>((float)zero_point);
auto scale_neg_zp_premul_vec = scale_vec * zero_point_vec.neg();
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qtanh", [&]() {
// Naive implemenentation: uses dequantize/execute/quantize routine
// - Output scale is set to 2.0 / 2^(BIT_NUM)
// - For signed types output zero point is set to 0
// - For unsigned types output zero point is set to (qmax + qmin) / 2.0
float output_scale = 0.0078125; // 2.0 / 512
int64_t output_zero_point = 0;
if (SCALAR_TYPE == at::kQInt32) {
output_scale = 4.656612873077393e-10; // 2.0 / 2^32
} else if (SCALAR_TYPE == at::kQUInt8) {
output_zero_point = 128;
}
float inv_output_scale = 1.0 / output_scale;
qy = at::_empty_affine_quantized(
qx.sizes(),
at::device(kCPU).dtype(SCALAR_TYPE).memory_format(qx.suggest_memory_format()),
output_scale,
output_zero_point,
c10::nullopt);
auto iter = TensorIterator::unary_op(qy, qx);
using Vec = Vec256<scalar_t>;
cpu_kernel_vec(
iter,
[&](scalar_t value_qx) -> scalar_t {
const auto value_dx =
at::native::dequantize_val(scale, zero_point, value_qx);
return at::native::quantize_val<scalar_t>(
output_scale, output_zero_point, std::tanh(value_dx));
},
[&](Vec value_qx) -> Vec {
const auto value_dx = value_qx.dequantize(
scale_vec, zero_point_vec, scale_neg_zp_premul_vec);
Vec::float_vec_return_type retvals;
for (int idx = 0; idx < Vec::float_num_vecs(); ++idx) {
retvals[idx] = value_dx[idx].tanh();
}
return Vec::quantize(
retvals, output_scale, output_zero_point, inv_output_scale);
});
});
}
void qelu_kernel(
const Tensor& qx,
Scalar alpha,
Scalar scale,
Scalar input_scale,
Tensor& qy) {
// scale and input_scale arguments refer to a generalized ELU formula
// if x >= 0, ELU(x) = x * scale
// if x <= 0, ELU(x) = (exp(x * input_scale) - 1) * scale
// in the normal ELU formula, both are equal to 1
// they are NOT related to the quantization scale term
int64_t i_zp = qx.q_zero_point();
float i_scale = qx.q_scale();
// In a future PR, we can improve on output scale and zero_point
// selection.
int64_t o_zp = qy.q_zero_point();
float o_scale = qy.q_scale();
float inv_o_scale = 1.0 / o_scale;
float alpha_float = alpha.to<float>();
float scale_coef = scale.to<float>();
float input_scale_coef = input_scale.to<float>();
AT_DISPATCH_QINT_TYPES(qx.scalar_type(), "qelu_kernel", [&] {
auto iter = TensorIterator::unary_op(qy, qx);
// vectorized
using Vec = Vec256<float>;
using qVec = Vec256<scalar_t>;
Vec zero_vec = Vec(0.0f);
Vec one_vec = Vec(1.0f);
Vec alpha_vec = Vec(alpha_float);
Vec scale_coef_vec = Vec(scale_coef);
Vec input_scale_coef_vec = Vec(input_scale_coef);
Vec i_scale_vec = Vec(i_scale);
Vec i_zero_point_vec = Vec((float)i_zp);
Vec i_scale_neg_zp_premul_vec = i_scale_vec * i_zero_point_vec.neg();
cpu_kernel_vec(
iter,
[&](scalar_t value_qx) -> scalar_t {
// dequantize
const auto x = at::native::dequantize_val(i_scale, i_zp, value_qx);
// ELU
const auto y = x >= 0
? x * scale_coef
: ((std::exp(x * input_scale_coef) - 1) * alpha_float * scale_coef);
// quantize
return at::native::quantize_val<scalar_t>(o_scale, o_zp, y);
},
[&](qVec value_qx) -> qVec {
// dequantize
auto dx_vec_vec = value_qx.dequantize(i_scale_vec, i_zero_point_vec,
i_scale_neg_zp_premul_vec);
for (int idx = 0; idx < dx_vec_vec.size(); idx++) {
// quickly check if any elements are below zero
auto cmp_to_zero = dx_vec_vec[idx] > zero_vec;
if (cmp_to_zero.zero_mask()) {
Vec dx_vec_copy_neg_elu = dx_vec_vec[idx] * one_vec;
// calculate the negative part of ELU on the copy
dx_vec_copy_neg_elu = dx_vec_copy_neg_elu * input_scale_coef_vec;
dx_vec_copy_neg_elu = dx_vec_copy_neg_elu.exp();
dx_vec_copy_neg_elu = dx_vec_copy_neg_elu - one_vec;
dx_vec_copy_neg_elu = dx_vec_copy_neg_elu * alpha_vec;
// blend
dx_vec_vec[idx] = Vec::blendv(dx_vec_copy_neg_elu, dx_vec_vec[idx],
dx_vec_vec[idx] > zero_vec);
}
dx_vec_vec[idx] = dx_vec_vec[idx] * scale_coef_vec;
}
// quantize
return qVec::quantize(dx_vec_vec, o_scale, o_zp, inv_o_scale);
}
);
});
}
// Note: out is assumed to be the same size as self and other.
// Note: Addition is only supported when self and out are of the same dtype.
// Note: other is already assumed to be in int32, i.e., it's
// round(float/self_scale)
template <bool ReLUFused = false>
void qadd_scalar_kernel(Tensor& out, const Tensor& self, Scalar other) {
int64_t zero_point = out.q_zero_point();
float scale = out.q_scale();
float inv_scale = 1.0f / scale;
int64_t self_zero_point = self.q_zero_point();
float self_scale = self.q_scale();
float multiplier = self_scale * inv_scale;
AT_DISPATCH_QINT_TYPES(self.scalar_type(), "qadd_scalar", [&]() {
using Vec = Vec256<scalar_t>;
auto iter = TensorIterator::unary_op(out, self);
auto other_val = other.to<int32_t>();
auto other_vec = Vec256<c10::qint32>(static_cast<c10::qint32>(other_val));
cpu_kernel_vec(
iter,
[&](scalar_t a) -> scalar_t {
int32_t a_sub_z = static_cast<int32_t>(a.val_) -
static_cast<int32_t>(self_zero_point);
int32_t c = a_sub_z + other_val;
scalar_t res = at::native::requantize_from_int<scalar_t>(
multiplier, zero_point, c);
if (ReLUFused) {
res.val_ = std::max<scalar_t::underlying>(res.val_, zero_point);
}
return res;
},
[&](Vec a) -> Vec {
Vec::int_vec_return_type a_sub_z =
a.widening_subtract(Vec(static_cast<scalar_t>(self_zero_point)));
Vec::int_vec_return_type c;
for (int i = 0; i < Vec::int_num_vecs(); ++i) {
c[i] = a_sub_z[i] + other_vec;
}
Vec rv = Vec::requantize_from_int(c, multiplier, zero_point);
if (ReLUFused) {
rv = rv.maximum(Vec(static_cast<scalar_t>(zero_point)));
}
return rv;
});
});
}
// Note: out is assumed to be the same size as self and other.
// Note: Addition is only supported when self, other, out are of the same dtype.
template <bool ReLUFused = false>
void qadd_kernel(Tensor& out, const Tensor& self, const Tensor& other) {
int64_t zero_point = out.q_zero_point();
float scale = out.q_scale();
float inv_scale = 1.0f / scale;
int64_t self_zero_point = self.q_zero_point();
float self_scale = self.q_scale();
int64_t other_zero_point = other.q_zero_point();
float other_scale = other.q_scale();
// Broadcast out the parameters here to amortize out that cost across
// loop iterations.
// TODO: we can optimize dequantization by doing a premultiplication
// of the zero point by scale and doing FMA on scale*x_q - (scale*zero_point)
auto self_zero_point_vec = Vec256<float>((float)self_zero_point);
auto self_scale_vec = Vec256<float>(self_scale);
auto other_zero_point_vec = Vec256<float>((float)other_zero_point);
auto other_scale_vec = Vec256<float>(other_scale);
auto self_scale_neg_zp_premul_vec = self_scale_vec * self_zero_point_vec.neg();
auto other_scale_zp_premul_vec = other_scale_vec * other_zero_point_vec.neg();
auto iter = TensorIterator::binary_op(out, self, other);
AT_DISPATCH_QINT_TYPES(out.scalar_type(), "qadd", [&]() {
using Vec = Vec256<scalar_t>;
cpu_kernel_vec(
iter,
[&](scalar_t a, scalar_t b) -> scalar_t {
const auto da =
at::native::dequantize_val(self_scale, self_zero_point, a);
const auto db =
at::native::dequantize_val(other_scale, other_zero_point, b);
float c = da + db;
if (ReLUFused) {
c = std::max<float>(c, 0.0);
}
return at::native::quantize_val<scalar_t>(scale, zero_point, c);
},
[&](Vec a, Vec b) -> Vec {
const auto da = a.dequantize(
self_scale_vec, self_zero_point_vec, self_scale_neg_zp_premul_vec);
const auto db = b.dequantize(
other_scale_vec, other_zero_point_vec, other_scale_zp_premul_vec);
Vec::float_vec_return_type retvals;
for (int i = 0; i < Vec::float_num_vecs(); ++i) {
auto c = da[i] + db[i];
if (ReLUFused) {
c = vec256::maximum(c, Vec256<float>(0.0f));
}
retvals[i] = c;
}
// TODO: fbgemm::Quantize doesn't support taking in the
// pre-broadcasted parameters. We might be able to save some cycles by
// enabling that in the API.
// TODO: specialize fbgemm::Quantize for a single vector and make it
// inlineable. This could help with interleaving as suggested by the
// TensorIterator implementations
auto rv = Vec::quantize(retvals, scale, zero_point, inv_scale);
return rv;
});
});
}
// Note: out is assumed to be the same size as self and other.
// Note: Multiplication is only supported when self, other, out are of the same
// dtype.
template <bool ReLUFused = false>
void qmul_kernel(Tensor& out, const Tensor& self, const Tensor& other) {
int64_t zero_point = out.q_zero_point();
float scale = out.q_scale();