-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
test_quantized_op.py
4889 lines (4344 loc) · 220 KB
/
test_quantized_op.py
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
from builtins import round
import copy
import itertools
import numpy as np
import sys
import unittest
import operator
import torch
from torch import _VF
import torch.jit
import torch.nn.functional as F
from torch.nn.modules.utils import _single, _pair
from hypothesis import settings, HealthCheck
from hypothesis import assume, given, note
from hypothesis import strategies as st
import torch.testing._internal.hypothesis_utils as hu
hu.assert_deadline_disabled()
from torch.testing._internal.common_utils import TestCase
from torch.testing._internal.common_utils import IS_PPC, TEST_WITH_UBSAN, IS_MACOS
from torch.testing._internal.common_quantization import skipIfNoFBGEMM
from torch.testing._internal.common_quantized import _quantize, _dequantize, _calculate_dynamic_qparams, \
override_quantized_engine, supported_qengines, override_qengines, _snr
from torch.testing._internal.common_quantized import qengine_is_qnnpack
from torch.quantization import PerChannelMinMaxObserver
from typing import Optional
np_dtype = {
torch.quint8 : np.uint8,
torch.qint8 : np.int8,
torch.qint32 : np.int32
}
# Make sure we won't have overflows from vpmaddubsw instruction used in FBGEMM.
# On the current Intel x86 architecture, we need to utilize vpmaddubsw instruction
# for the 8-bit int multiplication. This instruction vertically multiplies each
# unsigned 8-bit integer from a with the corresponding signed 8-bit integer from
# b, producing intermediate signed 16-bit integers. This function modifies the
# weights to eliminate the overflow on the signed 16-bit integers.
def avoid_vpmaddubsw_overflow_linear(
batch_size, input_channels, output_channels, X, X_min, X_max, W, W_min, W_max
):
for i, j in np.ndindex((batch_size, output_channels)):
for k in range(0, input_channels // 2 * 2, 2):
x0 = X[i, k] - X_min
x1 = X[i, k + 1] - X_min
w0 = W[j, k] - 128 - W_min
w1 = W[j, k + 1] - 128 - W_min
if x0 * w0 + x1 * w1 < -(1 << 15):
w1_adjusted = (-(1 << 15) - float(x0) * w0) / x1
W[j, k + 1] = int(w1_adjusted) + 128 + W_min
elif x0 * w0 + x1 * w1 > (1 << 15) - 1:
w1_adjusted = ((1 << 15) - 1 - float(x0) * w0) / x1
W[j, k + 1] = int(w1_adjusted) + 128 + W_min
# Go through the same loop again to double check we don't have any overflow
for i, j in np.ndindex((batch_size, output_channels)):
for k in range(0, input_channels // 2 * 2, 2):
x0 = X[i, k] - X_min
x1 = X[i, k + 1] - X_min
w0 = W[j, k] - 128 - W_min
w1 = W[j, k + 1] - 128 - W_min
assert -(1 << 15) <= x0 * w0 + x1 * w1 < (1 << 15)
# Reference quantized Linear operator
def qlinear_ref(X_q, X_scale, X_zp, W_q, W_scale, W_zp, b_q, Y_scale, Y_zp):
X_q = np.reshape(X_q, (-1, X_q.shape[X_q.ndim - 1]))
row_offsets_ref = X_q.sum(axis=1).astype(np.int32).reshape((-1, 1))
col_offsets_ref = W_q.sum(axis=1).astype(np.int32).reshape((1, -1))
assert X_q.ndim == 2
batch_size, input_channels = X_q.shape
Prod_XqWq_ref = (
np.matmul(X_q.astype(np.int32), W_q.astype(np.int32).T)
- W_zp * row_offsets_ref
- X_zp * col_offsets_ref
+ input_channels * X_zp * W_zp
)
if b_q is not None:
Prod_XqWq_ref += b_q
Y_q_ref = _quantize(Prod_XqWq_ref, Y_scale / (X_scale * W_scale), Y_zp)
return Y_q_ref
"""Computes the output shape given pooling parameters."""
def pool_output_shape(input_size, kernel_size, padding, stride,
dilation, ceiling_mode=False):
if stride is None:
stride = kernel_size
output_size = (
(input_size + 2 * padding - dilation * (kernel_size - 1) - 1
+ (stride - 1 if ceiling_mode else 0)) // stride + 1)
if (ceiling_mode and
((output_size - 1) * stride >= input_size + padding)):
output_size -= 1
return output_size
"""
Util for creating a random tensor and quantization params when Hypothesis
is undesirable.
"""
def _get_random_tensor_and_q_params(shapes, rand_scale, torch_type):
X = (torch.rand(*shapes, dtype=torch.float) - 0.5) * rand_scale
# Calculate reasonable quantization params
min_val = torch.min(X)
max_val = torch.max(X)
if torch_type == torch.qint32:
X_zero_point = int(torch.randint(-1 * (2 ** 31), 2 ** 31 - 1, (1,)))
num_bins = 2 ** 32
X_scale = float(max_val - min_val) / num_bins
elif torch_type == torch.qint8:
X_zero_point = int(torch.randint(-128, 127, (1,)))
num_bins = 2 ** 8
X_scale = float(max_val - min_val) / num_bins
else: # torch.quint8
X_zero_point = 127
num_bins = 2 ** 8
X_scale = float(max_val - min_val) / num_bins
if X_scale == 0:
X_scale = 1e-10
return X, X_scale, X_zero_point
class TestQuantizedOps(TestCase):
"""Helper function to test quantized activation functions."""
def _test_activation_function(self, X, fn_name, test_configs):
r"""
When writing a unit test for the activation function,
instead of specifying the test routines only applicable to the activation function itself,
you utilize the _test_activation_function that provides general testing.
To utilize the helper function, a test config must be provided.
A test config is a list that contains metadata about the quantized activation
functions that will be tested and how the tests need to be set up; it allows simpler and
more concise unit tests to be written by specifying the configurations needed
and calling the provided helper function _test_activation_function.
Inside the list, each config (as a dictionary) represents a suite of tests that assert the
correctness of various quantization functions.
You can check out the test_qrelu, test_qrelu6, test_qsigmoid, and test_qhardsigmoid for
how their test configs are specified.
Here's a list of the fields that can be included in a test config:
quantized_fn: a list of the quantized functions to be tested
reference_fn: the original reference function to be called on the
the dequantized X
extra_kwargs: the additional keyword arguments
for each test entry in ops_under_test, it must have at least the fields
for quantized_fn and reference_fn.
output_range: the output range the operator will map to. By default, if it is
no specified, the range will not be controlled and depend on Xmin and Xmax.
change_zero_point: a boolean flag indicating if the zero point parameter should
be determined based on torch_type during quantization (see sigmoid/hardsigmoid for
examples). By default, if it is not specified, change_zero_point is assumed to be
False and zero point will just take on the default value from X.
`output_is_observed`: if specified and is True, we'll append extra
output_scale/output_zero_point keyword argument when calling quantized op
"""
# Retrives the default parameters from X.
X, (scale, zero_point, torch_type) = X
X = torch.from_numpy(X)
# Quantizes the reference to account for max error.
# q_min and q_max only depend on the initial torch_type.
q_min, q_max = torch.iinfo(torch_type).min, torch.iinfo(torch_type).max
for op_group in test_configs:
ref_op = op_group['reference_fn']
for q_op in op_group['quantized_fn']:
for memory_format in (torch.channels_last, torch.contiguous_format):
if memory_format == torch.channels_last and len(X.shape) != 4:
continue
X = X.to(memory_format=memory_format)
# Retrieves the inplace keyword arguments
# some functions require inplace=True to test in-place.
# copy.copy is needed because these are modified in place
extra_kwargs = \
copy.copy(op_group.get('extra_kwargs', dict()))
output_is_observed = \
copy.copy(op_group.get('output_is_observed', False))
# Quantizes and dequantizes to account for max error.
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,
dtype=torch_type)
dqX = qX.dequantize()
dqY_hat = ref_op(dqX.clone(), **extra_kwargs)
# Adjusts output_scale if needed.
# The output_scale determines the quantization scale for functions that
# have a constrained output range. e.x. sigmoid ranges from 0 to 1.
output_scale = scale
if 'output_range' in op_group:
(f_min, f_max) = op_group['output_range']
output_scale = (f_max - f_min) / (q_max - q_min + 1.0)
# Adjusts output_zero_point if needed (see explanation for the
# change_zero_point parameter above).
# output_zero_point determines the additional offset that will be
# added to a scaled value during quantization.
if op_group.get('change_zero_point', False):
output_zero_point = 0 if torch_type == torch.qint32 else q_min
else:
output_zero_point = zero_point
# Quantizes the dequantized version of Y_hat.
qY_hat = torch.quantize_per_tensor(dqY_hat, scale=output_scale,
zero_point=output_zero_point,
dtype=torch_type)
if output_is_observed:
extra_kwargs.update({'output_scale': output_scale, 'output_zero_point': output_zero_point})
# Finds qY using in-place or non-in-place quantized operators.
qY = q_op(qX, **extra_kwargs)
self.assertEqual(qY, qY_hat, msg='{} - {} failed: ({} vs. {})'.format(
fn_name, q_op, qY, qY_hat
))
"""Tests the correctness of the quantized::relu op."""
@override_qengines
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
qparams=hu.qparams()))
def test_qrelu(self, X):
relu_test_configs = [
{
'quantized_fn': [
torch.relu,
torch.relu_,
torch.nn.functional.relu,
torch.nn.functional.relu,
],
'reference_fn': torch.nn.functional.relu
},
{
'quantized_fn': [
torch.nn.functional.relu,
torch.nn.functional.relu,
],
'reference_fn': torch.nn.functional.relu,
'extra_kwargs': {
'inplace': True
}
}
]
self._test_activation_function(X, 'relu', relu_test_configs)
"""Tests the correctness of the quantized::relu6 op."""
@override_qengines
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
qparams=hu.qparams()))
def test_qrelu6(self, X):
relu6_test_configs = [
{
'quantized_fn': [
torch.ops.quantized.relu6,
torch.nn.quantized.ReLU6(inplace=False),
torch.nn.quantized.ReLU6(inplace=True)
],
'reference_fn': torch.nn.functional.relu6
}
]
self._test_activation_function(X, 'relu6', relu6_test_configs)
"""Tests the correctness of the quantized::sigmoid op."""
@override_qengines
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
qparams=hu.qparams()))
def test_sigmoid_non_observed(self, X):
sigmoid_test_configs = [
{
'quantized_fn': [
torch.sigmoid
],
'reference_fn': torch.sigmoid,
'output_range': (0.0, 1.0),
'change_zero_point': True
}
]
self._test_activation_function(X, 'sigmoid', sigmoid_test_configs)
"""Tests the correctness of the quantized::sigmoid op."""
# TODO: enable after observed output is supported in qnnpack
# @override_qengines
@skipIfNoFBGEMM
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
qparams=hu.qparams()))
def test_sigmoid(self, X):
sigmoid_test_configs = [
{
'quantized_fn': [
torch.ops.quantized.sigmoid
],
'reference_fn': torch.sigmoid,
'output_range': (0.0, 1.0),
'change_zero_point': True,
'output_is_observed': True,
}
]
self._test_activation_function(X, 'sigmoid', sigmoid_test_configs)
"""Tests the correctness of the quantized::hardsigmoid op."""
@override_qengines
def test_qhardsigmoid(self):
hardsigmoid_test_configs = [
{
'quantized_fn': [
torch.nn.quantized.functional.hardsigmoid
],
'reference_fn': torch.nn.functional.hardsigmoid,
'output_range': (0.0, 1.0),
'change_zero_point': True
}
]
shapes = ((4,), (4, 4), (4, 4, 4), (4, 4, 4, 4))
dtypes = (torch.quint8, torch.qint8)
test_cases = itertools.product(shapes, dtypes)
for shape, dtype in test_cases:
X = (np.random.rand(*shape).astype(np.float32), (1.0, 0, dtype))
self._test_activation_function(X, 'hardsigmoid', hardsigmoid_test_configs)
@override_qengines
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
qparams=hu.qparams()))
def test_leaky_relu_observed_output(self, X):
leaky_relu_test_configs = [
{
'quantized_fn': [
torch.ops.quantized.leaky_relu
],
'reference_fn': torch.nn.functional.leaky_relu,
'extra_kwargs': {
'negative_slope': 0.1,
'inplace': False,
},
'output_is_observed': True,
}
]
self._test_activation_function(X, 'leaky_relu', leaky_relu_test_configs)
"""Tests the correctness of the quantized::relu op."""
def test_leaky_relu(self):
shapes = ((4,), (4, 4), (4, 4, 4), (4, 4, 4, 4))
dtypes = (torch.quint8, torch.qint8)
memory_formats = (torch.channels_last, torch.contiguous_format)
test_cases = itertools.product(shapes, dtypes, memory_formats)
for shape, dtype, memory_format in test_cases:
if memory_format == torch.channels_last and len(shape) != 4:
continue
X, scale, zero_point, torch_type, alpha = \
torch.randn(*shape), 0.1, 0, dtype, 0.01
X = X.to(memory_format=memory_format)
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,
dtype=torch_type)
dqX = qX.dequantize()
# torch.nn.functional
op = torch.nn.functional.leaky_relu
dqY = op(dqX, negative_slope=alpha)
qY = torch.quantize_per_tensor(dqY, scale=scale, zero_point=zero_point,
dtype=torch_type)
qY_hat = op(qX, negative_slope=alpha)
self.assertEqual(qY.dequantize(), qY_hat.dequantize(),
msg="F.leaky_relu failed ({} vs {})".format(qY, qY_hat))
"""Tests the correctness of the quantized::elu op."""
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
elements=hu.floats(-1e3, 1e3, allow_nan=False, allow_infinity=False),
qparams=hu.qparams()),
alpha=st.floats(0.01, 10.0, allow_nan=False, allow_infinity=False))
def test_qelu(self, X, alpha):
X, (scale, zero_point, torch_type) = X
output_scale = 0.5
output_zero_point = 1
X = torch.from_numpy(X)
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,
dtype=torch_type)
# calculate ELU(dqX) and quantize
dqX = qX.dequantize()
dqY_hat = dqX.clone()
dqY_hat = torch.nn.functional.elu(dqX, alpha)
qY_hat = torch.quantize_per_tensor(dqY_hat, scale=output_scale, zero_point=output_zero_point,
dtype=torch_type)
qY = torch.nn.quantized.functional.elu(qX, output_scale, output_zero_point, alpha=alpha)
self.assertEqual(qY, qY_hat,
msg="F.elu failed ({} vs {})".format(qY, qY_hat))
"""Tests the correctness of the quantized::celu op."""
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
elements=hu.floats(-1e2, 1e2, allow_nan=False, allow_infinity=False),
qparams=hu.qparams(scale_max=9.999999747378752e-06)),
alpha=st.floats(0.01, 100.0, allow_nan=False, allow_infinity=False))
def test_qcelu(self, X, alpha):
X, (scale, zero_point, torch_type) = X
output_scale = 0.5
output_zero_point = 1
X = torch.from_numpy(X)
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,
dtype=torch_type)
# calculate CELU(dqX) and quantize
dqX = qX.dequantize()
dqY_hat = torch.nn.functional.celu(dqX, alpha)
qY_hat = torch.quantize_per_tensor(dqY_hat, scale=output_scale, zero_point=output_zero_point,
dtype=torch_type)
# test regular
qY = torch.ops.quantized.celu(qX, output_scale, output_zero_point, alpha=alpha)
self.assertEqual(qY, qY_hat,
msg="F.celu failed ({} vs {})".format(qY, qY_hat))
"""Tests the correctness of the quantized::qlayer_norm op."""
@skipIfNoFBGEMM
def test_qlayer_norm(self):
# hypothesis is flaky for this test, create test cases manually
side_lens = (1, 8, 11)
torch_types = (torch.qint8, torch.quint8)
y_scales = (0.1, 4.23)
y_zero_points = (0, 1)
channels_last_list = (True, False)
affine_list = (True, False)
combined = [side_lens, torch_types, y_scales, y_zero_points,
channels_last_list, affine_list]
test_cases = itertools.product(*combined)
with override_quantized_engine("fbgemm"):
for test_case in test_cases:
side_len, torch_type, Y_scale, Y_zero_point, channels_last, \
affine = test_case
shapes = [side_len] * 4
# In the FP kernel, mean and variance are calculated in floating point.
# In the quantized kernel, they are calculated in integer arithmetic.
# Because of this, the numerics do not always match exactly which is
# expected and acceptable. We do two things to allow this failure
# in this test:
# 1. do not use Hypothesis to generate the input tensor. Hypothesis
# favors homogeneous inputs in its search strategies which isn't
# representative of the inputs we care about, and tends to maximize
# this particular numerics difference.
# 2. allow a small % of off by Y_scale errors. Even when the
# variance of the input is high, there can be off by one errors
# in the result if the input value happens to fall exactly on
# the bin boundary of the output scale.
#
# If we want the numerics to match we could switch to calculating
# mean+var in floating point in the future, at the cost of speed.
X, X_scale, X_zero_point = \
_get_random_tensor_and_q_params(shapes, 1.0, torch_type)
qX = torch.quantize_per_tensor(X, scale=X_scale,
zero_point=X_zero_point,
dtype=torch_type)
if channels_last:
qX = qX.contiguous(memory_format=torch.channels_last)
dqX = qX.dequantize()
# Enforce non-homogeneous inputs
enough_unique_vals_in_each_layer = sum(
1 if (
dqX[i].shape[0] < 5 or
float(torch.unique(dqX[i]).shape[0]) / dqX[i].shape[0] > 0.01
) else 0
for i in range(dqX.shape[0])
) == dqX.shape[0]
assume(enough_unique_vals_in_each_layer)
# Initialize the weights non-randomly for reproducibility, to avoid
# flaky tests
if affine:
weight = torch.ones(*qX.size()[1:], dtype=torch.float) * 0.5
bias = torch.ones(*qX.size()[1:], dtype=torch.float) * 1
else:
weight = None
bias = None
epsilon = 1e-5
qY = torch.ops.quantized.layer_norm(
qX, qX.size()[1:], weight=weight, bias=bias, eps=epsilon,
output_scale=Y_scale, output_zero_point=Y_zero_point)
Y_hat = F.layer_norm(
dqX, dqX.size()[1:], weight=weight, bias=bias, eps=epsilon)
qY_hat = torch.quantize_per_tensor(
Y_hat, scale=Y_scale, zero_point=Y_zero_point, dtype=torch_type)
# Due to the numerics difference mentioned above between calculating
# the variance in float vs int, the results can still be slightly
# different.
dqY = qY.dequantize()
dqY_hat = qY_hat.dequantize()
diff = dqY - dqY_hat
# off-by-one errors are magnitude of Y_scale
num_diff = torch.sum(diff > Y_scale * 1.0001)
pct_diff = float(num_diff) / (diff.numel() + 1e-5)
num_diff_off_by_one = torch.sum((diff > 0) * (diff <= Y_scale))
pct_diff_off_by_one = float(num_diff_off_by_one) / (diff.numel() + 1e-5)
self.assertTrue(pct_diff < 1e-6)
self.assertTrue(pct_diff_off_by_one < 0.01)
"""Tests the correctness of the quantized::qnnpack_tanh op."""
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
qparams=hu.qparams()))
def test_qtanh(self, X):
# Note: QNNPACK is tested separately in TestQNNPackOps
X, (scale, zero_point, torch_type) = X
X = torch.from_numpy(X)
Y = torch.tanh(X)
qX = torch.quantize_per_tensor(X, scale=scale,
zero_point=zero_point,
dtype=torch_type)
# Quantize the reference to account for max error.
# Note that the output scale has +1, because we use scale of 2.0/2^BITS
# in the implementations.
f_min, f_max = -1.0, 1.0
q_min, q_max = torch.iinfo(torch_type).min, torch.iinfo(torch_type).max
output_scale = (f_max - f_min) / (q_max - q_min + 1.0)
output_zero_point = int(round((q_max + q_min) / 2.0))
qY = torch.quantize_per_tensor(Y, scale=output_scale,
zero_point=output_zero_point,
dtype=torch_type)
qY_hat = torch.tanh(qX)
self.assertEqual(qY, qY_hat,
msg="TanH failed: {} vs. {}".format(qY, qY_hat))
"""Tests the correctness of the quantized::threshold op."""
@given(X=hu.tensor(shapes=hu.array_shapes(1, 5, 1, 5),
elements=hu.floats(-1e3, 1e3, allow_nan=False, allow_infinity=False),
qparams=hu.qparams()),
threshold=hu.floats(-1e3, 1e3, allow_nan=False, allow_infinity=False),
value=hu.floats(-1e3, 1e3, allow_nan=False, allow_infinity=False))
def test_qthreshold(self, X, threshold, value):
X, (scale, zero_point, torch_type) = X
X = torch.from_numpy(X)
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,
dtype=torch_type)
# calculate threshold(dqX) and quantize
dqX = qX.dequantize()
dqY_hat = dqX.clone()
dqY_hat = torch.nn.functional.threshold(dqY_hat, threshold, value)
qY_hat = torch.quantize_per_tensor(dqY_hat, scale=scale, zero_point=zero_point,
dtype=torch_type)
ops_under_test = {
'native': torch.threshold,
'nn.functional': torch.nn.functional.threshold,
'nn.quantized.functional': torch.nn.quantized.functional.threshold
}
for name, op in ops_under_test.items():
qY = op(qX, threshold, value)
self.assertEqual(qY, qY_hat, msg="{} qthreshold failed".format(name))
"""Tests the correctness of the quantized::clamp op."""
@given(X=hu.tensor(shapes=hu.array_shapes(1, 8, 1, 8, max_numel=10**5),
elements=hu.floats(-1e6, 1e6, allow_nan=False),
qparams=hu.qparams()),
min_val=hu.floats(-1e6, 1e6, allow_nan=False),
max_val=hu.floats(-1e6, 1e6, allow_nan=False))
def test_qclamp(self, X, min_val, max_val):
X, (scale, zero_point, torch_type) = X
assume(min_val <= max_val)
Y_clamp = torch.clamp(torch.from_numpy(X), min=min_val, max=max_val)
qY_clamp = torch.quantize_per_tensor(Y_clamp, scale=scale,
zero_point=zero_point, dtype=torch_type)
X = torch.from_numpy(X)
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,
dtype=torch_type)
ops_under_test = {
'ops.quantized': torch.ops.quantized.clamp,
}
for name, op in ops_under_test.items():
qY_clamp_hat = op(qX, min=min_val, max=max_val)
self.assertEqual(qY_clamp, qY_clamp_hat, msg="{} qclamp failed".format(name))
if torch.backends.quantized.engine == 'fbgemm':
with override_quantized_engine('fbgemm'):
Y_min_clamp = torch.clamp(X, min=min_val)
Y_max_clamp = torch.clamp(X, max=max_val)
qY_min_clamp = torch.quantize_per_tensor(Y_min_clamp, scale=scale,
zero_point=zero_point, dtype=torch_type)
qY_max_clamp = torch.quantize_per_tensor(Y_max_clamp, scale=scale,
zero_point=zero_point, dtype=torch_type)
for name, op in ops_under_test.items():
qY_min_clamp_hat = op(qX, min=min_val)
self.assertEqual(qY_min_clamp, qY_min_clamp_hat, msg="{} qclamp failed".format(name))
qY_max_clamp_hat = op(qX, max=max_val)
self.assertEqual(qY_max_clamp, qY_max_clamp_hat, msg="{} qclamp failed".format(name))
"""Tests the correctness of the quantized::hardtanh op."""
@skipIfNoFBGEMM
@given(X=hu.tensor(shapes=hu.array_shapes(1, 8, 1, 8, max_numel=10**5),
elements=hu.floats(-1e6, 1e6, allow_nan=False, allow_infinity=False),
qparams=hu.qparams()),
min_val=hu.floats(-1e6, 1e6, allow_nan=False, allow_infinity=False),
max_val=hu.floats(-1e6, 1e6, allow_nan=False, allow_infinity=False))
def test_hardtanh(self, X, min_val, max_val):
with override_quantized_engine('fbgemm'):
X, (scale, zero_point, torch_type) = X
assume(min_val <= max_val)
Y = X.copy()
Y[Y < min_val] = min_val
Y[Y > max_val] = max_val
qY = torch.quantize_per_tensor(torch.from_numpy(Y), scale=scale,
zero_point=zero_point, dtype=torch_type)
X = torch.from_numpy(X)
qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,
dtype=torch_type)
ops_under_test = {
'nn.quantized.functional.hardtanh':
torch.nn.quantized.functional.hardtanh,
}
for name, op in ops_under_test.items():
qY_hat = op(qX, min_val, max_val)
self.assertEqual(qY, qY_hat, msg="{} hardtanh failed".format(name))
ops_under_test_inplace = {
'inplace nn.quantized.functional.hardtanh':
torch.nn.quantized.functional.hardtanh,
}
for name, op_ in ops_under_test_inplace.items():
qY_hat = qX.clone()
op_(qY_hat, min_val, max_val, inplace=True)
self.assertEqual(qY, qY_hat, msg="{} hardtanh failed".format(name))
"""Tests the correctness of the quantized::hardswish op."""
@override_qengines
def test_hardswish(self):
max_sides = (3, 4)
side_lens = (1, 7)
torch_types = (torch.quint8, torch.qint8)
y_scales = (0.1, )
y_zero_points = (1,)
combined = [max_sides, side_lens, torch_types, y_scales, y_zero_points]
test_cases = itertools.product(*combined)
for test_case in test_cases:
max_side, side_len, torch_type, Y_scale, Y_zero_point = test_case
if torch.backends.quantized.engine == 'qnnpack' and torch_type != torch.quint8:
continue
shapes = [side_len] * max_side
X, X_scale, X_zero_point = \
_get_random_tensor_and_q_params(shapes, 2.0, torch_type)
for memory_format in torch.channels_last, torch.contiguous_format:
if memory_format == torch.channels_last and len(shapes) == 4:
X = X.to(memory_format=memory_format)
qX = torch.quantize_per_tensor(X, scale=X_scale, zero_point=X_zero_point,
dtype=torch_type)
dqX = qX.dequantize()
dqY_hat = F.hardswish(dqX)
qY_hat = torch.quantize_per_tensor(dqY_hat, scale=Y_scale,
zero_point=Y_zero_point,
dtype=torch_type)
qY = torch.nn.quantized.functional.hardswish(
qX, scale=Y_scale, zero_point=Y_zero_point)
self.assertEqual(
qY, qY_hat,
msg="Hardswish failed: {} vs {}, {}".format(qY, qY_hat, torch.backends.quantized.engine))
"""Tests the correctness of the binary op + scalar."""
def _test_binary_op_scalar_relu(self, A, b, binary_op_name, binary_op, quantized_op, quantized_op_relu):
import copy
op_scalar = quantized_op
op_scalar_relu = quantized_op_relu
A, (scale, zero_point, dtype) = A
A = A.astype(np.float32)
qA = torch.quantize_per_tensor(torch.from_numpy(A), scale, zero_point, dtype)
if binary_op_name == 'add':
C = binary_op(qA.dequantize(), round(b / scale) * scale)
else:
C = binary_op(qA.dequantize(), b)
C_relu = copy.deepcopy(C)
C_relu[C_relu < 0] = 0
C_hat = op_scalar(qA, b)
C_ref = torch.quantize_per_tensor(C, C_hat.q_scale(), C_hat.q_zero_point(), dtype)
C_relu_hat = op_scalar_relu(qA, b)
C_relu_ref = torch.quantize_per_tensor(
C_relu, C_relu_hat.q_scale(), C_relu_hat.q_zero_point(), dtype)
self.assertEqual(C_ref.dequantize(), C_hat.dequantize(),
msg="{}_scalar results don't match: "
"{} vs {}".format(binary_op_name, C_ref.dequantize(), C_hat.dequantize()))
self.assertEqual(C_relu_ref.dequantize(), C_relu_hat.dequantize(),
msg="{}_scalar_relu results don't match: "
"{} vs {}".format(binary_op_name, C_relu_ref.dequantize(), C_relu_hat.dequantize()))
@unittest.skipIf(IS_MACOS, "skipping macos test")
@given(A=hu.tensor(shapes=hu.array_shapes(1, 4, 1, 5),
elements=hu.floats(-1e6, 1e6, allow_nan=False),
qparams=hu.qparams()),
b=hu.floats(-1e6, 1e6, allow_nan=False, allow_infinity=False))
def test_add_scalar_relu(self, A, b):
self._test_binary_op_scalar_relu(A, b, "add", operator.add, torch.ops.quantized.add, torch.ops.quantized.add_relu)
@unittest.skipIf(IS_MACOS, "skipping macos test")
@given(A=hu.tensor(shapes=hu.array_shapes(1, 4, 1, 5),
elements=hu.floats(-1e6, 1e6, allow_nan=False),
qparams=hu.qparams()),
b=hu.floats(-1e6, 1e6, allow_nan=False, allow_infinity=False))
def test_mul_scalar_relu(self, A, b):
self._test_binary_op_scalar_relu(A, b, "mul", operator.mul, torch.ops.quantized.mul, torch.ops.quantized.mul_relu)
"""Tests the correctness of the add and add_relu op."""
def test_qadd_relu_same_qparams(self):
for dtype in [torch.quint8, torch.qint8, torch.qint32]:
add_relu = torch.ops.quantized.add_relu
add = torch.ops.quantized.add
add_out = torch.ops.quantized.add
add_relu_out = torch.ops.quantized.add_relu
# NB: This is a strange size so that we exercise both the vectorized
# implementation (64-element chunks at at time) as well as the scalar
# implementation
A = torch.arange(-128, 130, dtype=torch.float)
B = torch.arange(-128, 130, dtype=torch.float)
scale = 2.0
zero_point = 127
qA = torch.quantize_per_tensor(A, scale=scale, zero_point=zero_point,
dtype=dtype)
qB = torch.quantize_per_tensor(B, scale=scale, zero_point=zero_point,
dtype=dtype)
# Add ReLU ground truth
C = (qA.dequantize() + qB.dequantize()).numpy()
qC = _quantize(C, scale, zero_point, dtype=np_dtype[dtype])
qC_hat = add(qA, qB, scale=scale, zero_point=zero_point)
np.testing.assert_equal(qC, qC_hat.int_repr(),
"Quantized addition failed.")
qC_out_hat = torch._empty_affine_quantized(qC.shape,
scale=scale,
zero_point=zero_point,
dtype=dtype)
add_out(qA, qB, out=qC_out_hat)
self.assertEqual(qC_hat, qC_out_hat, msg="Add.out failed")
# Add + ReLU ground truth
Crelu = C.copy()
Crelu[C < 0] = 0
qCrelu = _quantize(Crelu, scale, zero_point, dtype=np_dtype[dtype])
qCrelu_hat = add_relu(qA, qB, scale=scale, zero_point=zero_point)
np.testing.assert_equal(qCrelu, qCrelu_hat.int_repr(),
"Quantized addition with ReLU failed.")
qCrelu_out_hat = torch._empty_affine_quantized(qCrelu.shape,
scale=scale,
zero_point=zero_point,
dtype=dtype)
add_relu_out(qA, qB, out=qCrelu_out_hat)
self.assertEqual(qCrelu_hat, qCrelu_out_hat,
msg="AddReLU.out failed")
"""Tests the correctness of the add and add_relu op."""
def test_qadd_relu_different_qparams(self):
for dtype in [torch.quint8, torch.qint8, torch.qint32]:
add_relu = torch.ops.quantized.add_relu
add = torch.ops.quantized.add
add_out = torch.ops.quantized.add
add_relu_out = torch.ops.quantized.add_relu
# NB: This is a strange size so that we exercise both the vectorized
# implementation (64-element chunks at at time) as well as the scalar
# implementation
A = torch.arange(-128, 130, dtype=torch.float)
B = torch.arange(-128, 130, dtype=torch.float)
scale_A = 3.0
zero_point_A = 7
scale_B = 5.0
zero_point_B = 127
scale_C = 0.5
zero_point_C = 5
qA = torch.quantize_per_tensor(A, scale=scale_A, zero_point=zero_point_A,
dtype=dtype)
qB = torch.quantize_per_tensor(B, scale=scale_B, zero_point=zero_point_B,
dtype=dtype)
# Add ground truth
C = (qA.dequantize() + qB.dequantize()).numpy()
qC = _quantize(C, scale_C, zero_point_C, dtype=np_dtype[dtype])
qC_hat = add(qA, qB, scale=scale_C, zero_point=zero_point_C)
np.testing.assert_equal(qC, qC_hat.int_repr(),
"Quantized addition failed.")
qC_out_hat = torch._empty_affine_quantized(qC.shape,
scale=scale_C,
zero_point=zero_point_C,
dtype=dtype)
add_out(qA, qB, out=qC_out_hat)
self.assertEqual(qC_hat, qC_out_hat, msg="Add.out failed")
# Add + ReLU ground truth
Crelu = C.copy()
Crelu[C < 0] = 0
qCrelu = _quantize(Crelu, scale_C, zero_point_C, dtype=np_dtype[dtype])
qCrelu_hat = add_relu(qA, qB, scale=scale_C, zero_point=zero_point_C)
np.testing.assert_equal(qCrelu, qCrelu_hat.int_repr(),
"Quantized addition with ReLU failed.")
qCrelu_out_hat = torch._empty_affine_quantized(qCrelu.shape,
scale=scale_C,
zero_point=zero_point_C,
dtype=dtype)
add_relu_out(qA, qB, out=qCrelu_out_hat)
self.assertEqual(qCrelu_hat, qCrelu_out_hat,
msg="AddReLU.out failed")
"""Tests the correctness of the mul and mul_relu op."""
def test_qmul_relu_same_qparams(self):
for dtype in [torch.quint8, torch.qint8, torch.qint32]:
mul_relu = torch.ops.quantized.mul_relu
mul = torch.ops.quantized.mul
mul_out = torch.ops.quantized.mul
mul_relu_out = torch.ops.quantized.mul_relu
A = torch.arange(-100, 100, dtype=torch.float)
B = torch.arange(-100, 100, dtype=torch.float)
scale = 2.0
zero_point = 127
qA = torch.quantize_per_tensor(A, scale=scale, zero_point=zero_point,
dtype=dtype)
qB = torch.quantize_per_tensor(B, scale=scale, zero_point=zero_point,
dtype=dtype)
# mul ReLU ground truth
C = (qA.dequantize() * qB.dequantize()).numpy()
qC = _quantize(C, scale, zero_point, dtype=np_dtype[dtype])
qC_hat = mul(qA, qB, scale=scale, zero_point=zero_point)
np.testing.assert_equal(qC, qC_hat.int_repr(),
"Quantized mulition failed.")
qC_out_hat = torch._empty_affine_quantized(qC.shape,
scale=scale,
zero_point=zero_point,
dtype=dtype)
mul_out(qA, qB, out=qC_out_hat)
self.assertEqual(qC_hat, qC_out_hat, msg="mul.out failed")
# mul + ReLU ground truth
Crelu = C.copy()
Crelu[C < 0] = 0
qCrelu = _quantize(Crelu, scale, zero_point, dtype=np_dtype[dtype])
qCrelu_hat = mul_relu(qA, qB, scale=scale, zero_point=zero_point)
np.testing.assert_equal(qCrelu, qCrelu_hat.int_repr(),
"Quantized mulition with ReLU failed.")
qCrelu_out_hat = torch._empty_affine_quantized(qCrelu.shape,
scale=scale,
zero_point=zero_point,
dtype=dtype)
mul_relu_out(qA, qB, out=qCrelu_out_hat)
self.assertEqual(qCrelu_hat, qCrelu_out_hat,
msg="mulReLU.out failed")
# Scalar multiplication
for b in B:
C_ref = qA.dequantize().numpy() * b.item()
qC_hat = torch.ops.quantized.mul(qA, b.item())
self.assertEqual(C_ref, qC_hat.dequantize())
# Scalar multiplication + relu
for b in B:
C_ref = qA.dequantize().numpy() * b.item()
C_ref[C_ref < 0] = 0
qC_hat = torch.ops.quantized.mul_relu(qA, b.item())
self.assertEqual(C_ref, qC_hat.dequantize())
"""Tests the correctness of the mul and mul_relu op."""
def test_qmul_relu_different_qparams(self):
for dtype in [torch.quint8, torch.qint8, torch.qint32]:
mul_relu = torch.ops.quantized.mul_relu
mul = torch.ops.quantized.mul
mul_out = torch.ops.quantized.mul
mul_relu_out = torch.ops.quantized.mul_relu
A = torch.arange(-100, 100, dtype=torch.float)
B = torch.arange(-100, 100, dtype=torch.float)
scale_A = 3.0
zero_point_A = 7
scale_B = 5.0
zero_point_B = 127
scale_C = 0.5
zero_point_C = 5
qA = torch.quantize_per_tensor(A, scale=scale_A, zero_point=zero_point_A,
dtype=dtype)
qB = torch.quantize_per_tensor(B, scale=scale_B, zero_point=zero_point_B,
dtype=dtype)
# mul ground truth
C = (qA.dequantize() * qB.dequantize()).numpy()
qC = _quantize(C, scale_C, zero_point_C, dtype=np_dtype[dtype])
qC_hat = mul(qA, qB, scale=scale_C, zero_point=zero_point_C)
np.testing.assert_equal(qC, qC_hat.int_repr(),
"Quantized multiplication failed.")
qC_out_hat = torch._empty_affine_quantized(qC.shape,
scale=scale_C,
zero_point=zero_point_C,
dtype=dtype)
mul_out(qA, qB, out=qC_out_hat)
self.assertEqual(qC_hat, qC_out_hat, msg="mul.out failed")
# mul + ReLU ground truth
Crelu = C.copy()
Crelu[C < 0] = 0
qCrelu = _quantize(Crelu, scale_C, zero_point_C, dtype=np_dtype[dtype])
qCrelu_hat = mul_relu(qA, qB, scale=scale_C, zero_point=zero_point_C)
np.testing.assert_equal(qCrelu, qCrelu_hat.int_repr(),
"Quantized multiplication with ReLU failed.")
qCrelu_out_hat = torch._empty_affine_quantized(qCrelu.shape,
scale=scale_C,
zero_point=zero_point_C,
dtype=dtype)
mul_relu_out(qA, qB, out=qCrelu_out_hat)
self.assertEqual(qCrelu_hat, qCrelu_out_hat,
msg="mulReLU.out failed")
"""Tests the correctness of the mul and mul_relu op."""
def test_qmul_broadcast(self):
mul_relu = torch.ops.quantized.mul_relu
mul = torch.ops.quantized.mul
mul_out = torch.ops.quantized.mul
mul_relu_out = torch.ops.quantized.mul_relu
# A = torch.arange(-25, 25, dtype=torch.float)
# B = torch.arange(-25, 25, dtype=torch.float)
A = torch.randn(8, 1, 6, 1)
B = torch.randn(7, 1, 5)
scale_A = 3.0
zero_point_A = 7
scale_B = 5.0
zero_point_B = 127
scale_C = 0.5
zero_point_C = 5
qA = torch.quantize_per_tensor(A, scale=scale_A, zero_point=zero_point_A,
dtype=torch.quint8)
qB = torch.quantize_per_tensor(B, scale=scale_B, zero_point=zero_point_B,
dtype=torch.quint8)
# mul ground truth
C = (qA.dequantize() * qB.dequantize()).numpy()
qC = _quantize(C, scale_C, zero_point_C)
qC_hat = mul(qA, qB, scale=scale_C, zero_point=zero_point_C)
np.testing.assert_equal(qC, qC_hat.int_repr(),
"Quantized multiplication failed.")
"""Tests channel shuffle operation on quantized tensors."""
@given(X=hu.tensor(shapes=hu.array_shapes(min_dims=4, max_dims=4,
min_side=2, max_side=32, max_numel=10**5),
qparams=hu.qparams(dtypes=[torch.quint8])),
groups=st.integers(2, 6))
def test_channel_shuffle(self, X, groups):
X, (scale, zero_point, torch_type) = X
channels = X.shape[-3]
iH, iW = X.shape[-2:]
assume(channels % groups == 0)
a = torch.from_numpy(X)
a = torch.rand(a.shape)
a_out = torch.nn.functional.channel_shuffle(a, groups)
a_ref = torch.quantize_per_tensor(a_out, scale=scale,
zero_point=zero_point, dtype=torch_type)
a_ref = a_ref.dequantize()
qa = torch.quantize_per_tensor(a, scale=scale, zero_point=zero_point,
dtype=torch_type)