/
test_quantized_ops.py
2164 lines (1840 loc) · 67.3 KB
/
test_quantized_ops.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
"""Tests for the quantized ONNX ops."""
# The test_all_ops_were_tested needs all the tests that it references to be in a single file
# pylint: disable=too-many-lines
import io
from collections import OrderedDict
from functools import partial
from typing import Callable, Optional, Tuple, Union
import numpy
import onnx
import onnx.checker
import onnx.helper
import onnx.mapping
import onnxruntime as ort
import pytest
import torch
from concrete.ml.common.utils import MAX_BITWIDTH_BACKWARD_COMPATIBLE
from concrete.ml.pytest.utils import check_serialization, values_are_equal
from concrete.ml.quantization import QuantizedArray
from concrete.ml.quantization.base_quantized_op import ALL_QUANTIZED_OPS
from concrete.ml.quantization.quantized_ops import (
ONNXConstantOfShape,
ONNXGather,
ONNXShape,
ONNXSlice,
QuantizedAbs,
QuantizedAdd,
QuantizedAvgPool,
QuantizedBatchNormalization,
QuantizedBrevitasQuant,
QuantizedCast,
QuantizedCelu,
QuantizedClip,
QuantizedConcat,
QuantizedConv,
QuantizedDiv,
QuantizedElu,
QuantizedEqual,
QuantizedErf,
QuantizedExp,
QuantizedExpand,
QuantizedFlatten,
QuantizedFloor,
QuantizedGemm,
QuantizedGreater,
QuantizedGreaterOrEqual,
QuantizedHardSigmoid,
QuantizedHardSwish,
QuantizedIdentity,
QuantizedLeakyRelu,
QuantizedLess,
QuantizedLessOrEqual,
QuantizedLog,
QuantizedMatMul,
QuantizedMax,
QuantizedMaxPool,
QuantizedMin,
QuantizedMul,
QuantizedNeg,
QuantizedNot,
QuantizedOp,
QuantizedOr,
QuantizedPad,
QuantizedPow,
QuantizedPRelu,
QuantizedReduceSum,
QuantizedRelu,
QuantizedReshape,
QuantizedRound,
QuantizedSelu,
QuantizedSigmoid,
QuantizedSign,
QuantizedSoftplus,
QuantizedSqueeze,
QuantizedSub,
QuantizedTanh,
QuantizedTranspose,
QuantizedUnfold,
QuantizedUnsqueeze,
QuantizedWhere,
)
N_BITS_LIST = [20, 16, 8]
INPUT_RANGES = [
pytest.param((-1, 1)),
pytest.param((-2, 2)),
pytest.param((-10, 10)),
pytest.param((0, 20)),
]
IS_SIGNED = [pytest.param(True), pytest.param(False)]
OP_DEBUG_NAME = "Test_"
def quantized_op_results_are_equal(
quantized_op_1: QuantizedOp,
quantized_op_2: QuantizedOp,
q_input: Optional[numpy.ndarray] = None,
):
"""Check if two quantized operator instances are equal.
Args:
quantized_op_1 (QuantizedOp): The first quantized operator object to consider.
quantized_op_2 (QuantizedOp): The second quantized operator object to consider.
x (numpy.ndarray): The input to use for running the call.
Returns:
bool: If both instances are equal.
"""
if q_input is None:
value_1, value_2 = quantized_op_1(), quantized_op_2()
elif isinstance(q_input, tuple):
value_1, value_2 = quantized_op_1(*q_input), quantized_op_2(*q_input)
else:
value_1, value_2 = quantized_op_1(q_input), quantized_op_2(q_input)
return values_are_equal(value_1, value_2)
@pytest.mark.parametrize(
"n_bits",
[pytest.param(n_bits) for n_bits in N_BITS_LIST],
)
@pytest.mark.parametrize(
"input_range",
INPUT_RANGES,
)
@pytest.mark.parametrize(
"input_shape",
[pytest.param((10, 40, 20)), pytest.param((100, 400))],
)
@pytest.mark.parametrize(
"quantized_op_type",
[
QuantizedRelu,
QuantizedTanh,
QuantizedSigmoid,
QuantizedHardSigmoid,
QuantizedLeakyRelu,
QuantizedElu,
QuantizedSelu,
QuantizedCelu,
QuantizedSoftplus,
QuantizedAbs,
QuantizedLog,
QuantizedHardSwish,
QuantizedRound,
QuantizedErf,
QuantizedNot,
QuantizedSign,
QuantizedNeg,
QuantizedFloor,
],
)
@pytest.mark.parametrize("is_signed", IS_SIGNED)
def test_univariate_ops_no_attrs(
quantized_op_type: QuantizedOp,
input_shape: Tuple[int, ...],
input_range: Tuple[int, int],
n_bits: int,
is_signed: bool,
check_r2_score: Callable,
):
"""Test activation functions."""
values = numpy.random.uniform(input_range[0], input_range[1], size=input_shape)
q_inputs = QuantizedArray(n_bits, values, is_signed=is_signed)
quantized_op = quantized_op_type(n_bits, quantized_op_type.__name__)
expected_output = quantized_op.calibrate(values)
q_output = quantized_op(q_inputs)
qvalues = q_output.qvalues
# Quantized values must be contained between 0 and 2**n_bits - 1.
assert numpy.max(qvalues) <= 2**n_bits - 1
assert numpy.min(qvalues) >= 0
# De-quantized values must be close to original values
dequant_values = q_output.dequant()
# Check that all values are close
check_r2_score(dequant_values, expected_output)
# Manage ranges/improve tests for exponential
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/229
@pytest.mark.parametrize(
"n_bits",
[pytest.param(n_bits) for n_bits in N_BITS_LIST],
)
@pytest.mark.parametrize(
"input_range",
[pytest.param((-1, 1)), pytest.param((-2, 2))],
)
@pytest.mark.parametrize(
"input_shape",
[pytest.param((10, 40, 20)), pytest.param((100, 400))],
)
@pytest.mark.parametrize("is_signed", IS_SIGNED)
def test_exp_op(
input_shape: Tuple[int, ...],
input_range: Tuple[int, int],
n_bits: int,
is_signed: bool,
check_r2_score: Callable,
):
"""Test activation functions."""
values = numpy.random.uniform(input_range[0], input_range[1], size=input_shape)
q_inputs = QuantizedArray(n_bits, values, is_signed=is_signed)
quantized_op = QuantizedExp(n_bits, OP_DEBUG_NAME + "QuantizedExp")
expected_output = quantized_op.calibrate(values)
q_output = quantized_op(q_inputs)
qvalues = q_output.qvalues
# Quantized values must be contained between 0 and 2**n_bits - 1.
assert numpy.max(qvalues) <= 2**n_bits - 1
assert numpy.min(qvalues) >= 0
# De-quantized values must be close to original values
dequant_values = q_output.dequant()
# Check that all values are close
check_r2_score(dequant_values, expected_output)
# Test the serialization of QuantizedExp
check_serialization(
quantized_op,
QuantizedExp,
equal_method=partial(quantized_op_results_are_equal, q_input=q_inputs),
)
@pytest.mark.parametrize(
"n_bits",
[pytest.param(n_bits) for n_bits in N_BITS_LIST],
)
@pytest.mark.parametrize("input_range", INPUT_RANGES)
@pytest.mark.parametrize("is_signed", IS_SIGNED)
@pytest.mark.parametrize(
"input_shape",
[pytest.param((10, 40, 20)), pytest.param((100, 400))],
)
@pytest.mark.parametrize("cst_inputs", [(-100, 1), (0, 100), (-2.48, 4.67), (-1, 1), (0, 1)])
def test_clip_op(
input_shape: Tuple[int, ...],
input_range: Tuple[int, int],
n_bits: int,
is_signed: bool,
cst_inputs: Tuple[Union[int, float], Union[int, float]],
check_r2_score: Callable,
):
"""Test for clip op."""
values = numpy.random.uniform(input_range[0], input_range[1], size=input_shape)
q_inputs = QuantizedArray(n_bits, values, is_signed=is_signed)
q_cst_inputs = (numpy.asarray([inp_value]) for inp_value in cst_inputs)
quantized_op = QuantizedClip(
n_bits, OP_DEBUG_NAME + "QuantizedClip", constant_inputs=dict(zip([1, 2], q_cst_inputs))
)
expected_output = quantized_op.calibrate(values)
q_output = quantized_op(q_inputs)
qvalues = q_output.qvalues
# Quantized values must be contained between 0 and 2**n_bits - 1.
assert numpy.max(qvalues) <= 2**n_bits - 1
assert numpy.min(qvalues) >= 0
# De-quantized values must be close to original values
dequant_values = q_output.dequant()
# Check that all values are close
check_r2_score(dequant_values, expected_output)
# Test the serialization of QuantizedClip
check_serialization(
quantized_op,
QuantizedClip,
equal_method=partial(quantized_op_results_are_equal, q_input=q_inputs),
)
ARITH_N_BITS_LIST = [20, 16, 8]
@pytest.mark.parametrize(
"operator, supports_enc_with_enc",
[
(QuantizedAdd, True),
(QuantizedSub, True),
(QuantizedMul, False),
(QuantizedPow, False),
(QuantizedOr, False),
(QuantizedDiv, False),
(QuantizedMin, False),
(QuantizedMax, False),
],
)
@pytest.mark.parametrize("n_bits", ARITH_N_BITS_LIST)
@pytest.mark.parametrize(
"params_a, params_b, n_dims",
[
pytest.param((-10, 1), (5, 10), 10),
pytest.param((20, 10), (0, 0.2), 20),
pytest.param((40, 2), (-10, 50), 30),
pytest.param((-10, 1), (20, 1), 10),
pytest.param((0, 0.1), (0, 0.1), 5),
],
)
@pytest.mark.parametrize(
"generator",
[
partial(numpy.random.uniform, 0, 1),
partial(numpy.random.normal, 0, 1),
partial(numpy.random.gamma, 1, 2),
],
)
@pytest.mark.parametrize("is_signed", IS_SIGNED)
def test_all_arith_ops(
operator: QuantizedOp,
supports_enc_with_enc: bool,
n_bits: int,
is_signed: bool,
params_a: Tuple[float, float],
params_b: Tuple[float, float],
n_dims: int,
generator: Callable,
check_r2_score: Callable,
check_float_array_equal: Callable,
):
"""Test all quantized arithmetic ops"""
# Generate inputs with specific distribution
# But vary the dynamic range and the support of the distributions
input_0 = generator(size=(n_dims, n_dims)) * params_a[1] + params_a[0]
input_1 = generator(size=(n_dims, n_dims)) * params_b[1] + params_b[0]
if operator is QuantizedPow:
# Positive values for base
input_0 = numpy.maximum(input_0, 0)
# Small range for power
input_1 = numpy.clip(input_0, 0, 5)
# Quantize the inputs with n_bits
q_inputs_0 = QuantizedArray(n_bits, input_0, is_signed=is_signed)
q_inputs_1 = QuantizedArray(n_bits, input_1, is_signed=is_signed)
# Create the op with the same n_bits as output
# Using n_bits is not always desirable in practice as the output could feed into another TLU
# So using n_bits would waste precision, but we test the worst case scenario here
if supports_enc_with_enc:
# Variable+Variable (V+V) test
q_op = operator(n_bits, operator.__name__, int_input_names={"0", "1"})
# Calibrate the layer
raw_output_vv = q_op.calibrate(input_0, input_1)
# Compute the quantized operator result
quantized_output_vv = q_op(q_inputs_0, q_inputs_1).dequant()
# Check the R2 of raw output and quantized output
check_r2_score(raw_output_vv, quantized_output_vv)
# Test the serialization of all arithmetic operators that supports enc x enc
check_serialization(
q_op,
operator,
equal_method=partial(quantized_op_results_are_equal, q_input=(q_inputs_0, q_inputs_1)),
)
else:
with pytest.raises(
AssertionError, match="Do not support this type of operation between encrypted tensors"
):
# Variable+Variable (V+V) test
q_op = operator(n_bits, operator.__name__, int_input_names={"0", "1"})
# Variable + Constant test (V+C)
q_op = operator(
n_bits, operator.__name__, int_input_names={"0"}, constant_inputs={"b": q_inputs_1}
)
# Calibrate the layer
raw_output_vc = q_op.calibrate(input_0)
# Compute the quantized operator result
quantized_output_vc = q_op(q_inputs_0).dequant()
# Check the R2 of raw output and quantized output (V+C)
check_r2_score(raw_output_vc, quantized_output_vc)
# Constant + Variable test (C+V)
q_op = operator(
n_bits, operator.__name__, int_input_names={"0"}, constant_inputs={"a": q_inputs_0}
)
# Calibrate the layer
raw_output_cv = q_op.calibrate(input_1)
# Compute the quantized operator result
quantized_output_cv = q_op(q_inputs_1).dequant()
# Check the R2 of raw output and quantized output (C+V)
check_r2_score(raw_output_cv, quantized_output_cv)
# Check that we get the same fp32 results in V+V (if supported), V+C and C+V modes
if supports_enc_with_enc:
check_float_array_equal(raw_output_vv, raw_output_vc)
check_float_array_equal(raw_output_cv, raw_output_vc)
# Check that V+C and C+V is symmetric (int+float mode)
check_float_array_equal(quantized_output_cv, quantized_output_vc)
# As V+C and C+V work on float values they will not be exactly equal to
# the V+V case which works in quantized, we only check R2 for a high bit-width in this case
if supports_enc_with_enc:
check_r2_score(quantized_output_vc, quantized_output_vv)
# Test the serialization of all arithmetic operators
check_serialization(
q_op, operator, equal_method=partial(quantized_op_results_are_equal, q_input=q_inputs_1)
)
@pytest.mark.parametrize("n_bits", N_BITS_LIST)
@pytest.mark.parametrize("batch_size", [None, 10, 100])
@pytest.mark.parametrize(
"n_examples, n_features, n_neurons",
[
pytest.param(50, 3, 4),
pytest.param(20, 50, 30),
pytest.param(10, 20, 1),
pytest.param(10, 100, 10),
],
)
@pytest.mark.parametrize(
"generator",
[
partial(numpy.random.uniform, 0, 1),
partial(numpy.random.normal, 0, 1),
partial(numpy.random.gamma, 1, 2),
],
)
@pytest.mark.parametrize("is_signed", IS_SIGNED)
@pytest.mark.parametrize("produces_output", [True, False])
def test_all_gemm_ops(
n_bits: int,
is_signed: bool,
produces_output: bool,
batch_size: int,
n_examples: int,
n_features: int,
n_neurons: int,
generator: Callable,
check_r2_score: Callable,
check_array_equal: Callable,
):
"""Test for gemm style ops."""
if batch_size is None:
inputs_shape = (n_examples, n_features)
else:
inputs_shape = (batch_size, n_examples, n_features)
inputs = generator(size=inputs_shape)
weights_shape = (n_features, n_neurons)
weights = generator(size=weights_shape)
# We can assume uniform distribution for the bias without loss of generality
bias = numpy.random.uniform(size=(1, n_neurons))
# Quantize the inputs and weights
q_inputs = QuantizedArray(n_bits, inputs)
q_weights = QuantizedArray(n_bits, weights, is_signed=is_signed)
q_bias = QuantizedArray(n_bits, bias)
# 1- Test our QuantizedGemm layer
q_gemm = QuantizedGemm(
n_bits,
OP_DEBUG_NAME + "QuantizedGemm",
int_input_names={"0"},
constant_inputs={"b": q_weights, "c": q_bias},
)
q_gemm.produces_graph_output = produces_output
# Calibrate the Quantized layer
expected_gemm_outputs = q_gemm.calibrate(inputs)
actual_gemm_output = q_gemm(q_inputs).dequant()
check_r2_score(expected_gemm_outputs, actual_gemm_output)
# Test the serialization of QuantizedGemm
check_serialization(
q_gemm,
QuantizedGemm,
equal_method=partial(quantized_op_results_are_equal, q_input=q_inputs),
)
# 2- Same test without bias
q_gemm = QuantizedGemm(
n_bits,
OP_DEBUG_NAME + "QuantizedGemm",
int_input_names={"0"},
constant_inputs={"b": q_weights},
)
q_gemm.produces_graph_output = produces_output
q_mm = QuantizedMatMul(
n_bits,
OP_DEBUG_NAME + "QuantizedMatmul",
int_input_names={"0"},
constant_inputs={"b": q_weights},
)
q_mm.produces_graph_output = produces_output
# Calibrate the quantized layers
expected_gemm_outputs = q_gemm.calibrate(inputs)
expected_mm_outputs = q_mm.calibrate(inputs)
actual_gemm_output = q_gemm(q_inputs).dequant()
actual_mm_output = q_mm(q_inputs).dequant()
# Now check that the quantized results are close to non quantized
check_r2_score(expected_gemm_outputs, actual_gemm_output)
check_r2_score(expected_mm_outputs, actual_mm_output)
# Test the serialization of QuantizedGemm without bias
check_serialization(
q_gemm,
QuantizedGemm,
equal_method=partial(quantized_op_results_are_equal, q_input=q_inputs),
)
# 3- Same test but with (alpha, beta) = (1, 0)
q_gemm = QuantizedGemm(
n_bits,
OP_DEBUG_NAME + "QuantizedGemm",
int_input_names={"0"},
constant_inputs={"b": q_weights, "c": q_bias},
alpha=1,
beta=0,
)
q_gemm.produces_graph_output = produces_output
# Calibrate the Quantized layer
expected_gemm_outputs = q_gemm.calibrate(inputs)
actual_gemm_output = q_gemm(q_inputs).dequant()
check_r2_score(expected_gemm_outputs, actual_gemm_output)
# Without a bias, MatMul and Gemm should give the same output
check_array_equal(actual_mm_output, actual_gemm_output)
# Test the serialization of QuantizedGemm with (alpha, beta) = (1, 0)
check_serialization(
q_gemm,
QuantizedGemm,
equal_method=partial(quantized_op_results_are_equal, q_input=q_inputs),
)
# 4- Test with 2 int_input_names and empty constant_inputs (encrypted gemm)
q_gemm = QuantizedGemm(
n_bits,
OP_DEBUG_NAME + "QuantizedGemm",
int_input_names={"0", "1"},
constant_inputs={},
)
q_gemm.produces_graph_output = produces_output
expected_gemm_outputs = q_gemm.calibrate(*(inputs, weights))
actual_gemm_output = q_gemm(q_inputs, q_weights).dequant()
check_r2_score(expected_gemm_outputs, actual_gemm_output)
check_serialization(
q_gemm,
QuantizedGemm,
equal_method=partial(quantized_op_results_are_equal, q_input=(q_inputs, q_weights)),
)
@pytest.mark.parametrize("n_bits", [1, 2, 3, 4, 5, 6])
@pytest.mark.parametrize("x", [numpy.random.randn(100)])
def test_identity_op(x, n_bits):
"""Tests for the identity op"""
q_x = QuantizedArray(n_bits=n_bits, values=x)
quantized_identity = QuantizedIdentity(n_bits, OP_DEBUG_NAME + "QuantizedIdentity")
qx_bis = quantized_identity(q_x)
assert numpy.array_equal(qx_bis.qvalues, q_x.qvalues)
# Test the serialization of QuantizedIdentity
check_serialization(
quantized_identity,
QuantizedIdentity,
equal_method=partial(quantized_op_results_are_equal, q_input=q_x),
)
@pytest.mark.parametrize("n_bits", [16])
@pytest.mark.parametrize(
# Convolution parameters: inputs, weights, biases, strides, padding
# Inputs has size: N (batch) x C (input channels) x H x W
# Weights has size: O (output channels) x I (input channels) x Kh x Kw
# Biases has size: O (output channels)
# Strides and padding have size 2 (padding/stride on y and x)
# Group is either 1 or a multiple of both C and 0, so that I = C / group
"params",
[
(
(1, 3, 32, 32),
4,
(3, 3, 3, 3),
3,
(3,),
0.01,
5,
(2, 2),
(0, 0, 0, 0),
1,
),
(
(10, 1, 16, 16),
0.2,
(16, 1, 3, 3),
0.25,
(16,),
5,
0,
(1, 1),
(0, 0, 0, 0),
1,
),
(
(2, 32, 4, 4),
1,
(3, 32, 2, 2),
1,
(3,),
1,
0,
(1, 1),
(1, 1, 1, 1),
1,
),
(
(2, 32, 4, 4),
1,
(3, 32, 2, 2),
1,
(3,),
1,
0,
(1, 1),
(1, 1, 1, 1),
1,
),
(
(2, 2, 32, 32),
-1,
(3, 2, 2, 2),
1,
(3,),
1,
0,
(4, 4),
(7, 1, 7, 1),
1,
),
(
(1, 4, 32, 32),
-1,
(6, 2, 2, 2),
1,
(6,),
1,
0,
(4, 4),
(7, 1, 7, 1),
2,
),
(
(1, 3, 32, 32),
-1,
(3, 1, 2, 2),
1,
(3,),
1,
0,
(4, 4),
(7, 1, 7, 1),
3,
),
],
)
@pytest.mark.parametrize("produces_output", [True, False], ids=["produces_output", ""])
@pytest.mark.parametrize("is_conv1d", [True, False], ids=["is_conv1d", "is_conv2d"])
# @pytest.mark.parametrize("is_conv1d", [True], ids=["is_conv1d"])
# pylint: disable-next=too-many-locals
def test_quantized_conv(
params, n_bits, produces_output, is_conv1d, check_r2_score, check_float_array_equal
):
"""Test the quantized convolution operator."""
# Retrieve arguments
(
size_input,
scale_input,
size_weights,
scale_weights,
size_bias,
scale_bias,
offset_bias,
strides,
pads,
group,
) = params
# If testing the conv1d operator, make the parameters represent 1D inputs
if is_conv1d:
size_input = size_input[:3]
size_weights = size_weights[:3]
strides = strides[:1]
pads = pads[:2]
dilations = (1,)
conv_torch_op = torch.conv1d
else:
dilations = (1, 1) # type: ignore[assignment]
conv_torch_op = torch.conv2d
net_input = numpy.random.uniform(size=size_input) * scale_input
weights = numpy.random.randn(*size_weights) * scale_weights
biases = numpy.random.uniform(size=size_bias) * scale_bias + offset_bias
# Create quantized data
q_input = QuantizedArray(n_bits, net_input, is_signed=False)
q_weights = QuantizedArray(n_bits, weights, is_signed=True)
q_bias = QuantizedArray(n_bits, biases)
# Create the operator, specifying weights & biases as constants
q_op = QuantizedConv(
n_bits,
OP_DEBUG_NAME + "QuantizedConv",
int_input_names={"0"},
constant_inputs={1: q_weights, 2: q_bias},
strides=strides,
pads=pads,
kernel_shape=weights.shape[2:],
dilations=dilations,
group=group,
)
q_op.produces_graph_output = produces_output
# Compute the result in floating point
expected_result = q_op.calibrate(net_input)
# For Conv1d, torch and ONNX both follow the same padding convention
if is_conv1d:
input_padded = torch.nn.functional.pad(torch.Tensor(net_input.copy()), pads)
# For Conv2d, torch uses padding (padding_left, padding_right, padding_top, padding_bottom)
# While ONNX and Concrete ML use (padding_top, padding_left, padding_bottom, padding_right)
else:
input_padded = torch.nn.functional.pad(
torch.Tensor(net_input.copy()), (pads[1], pads[3], pads[0], pads[2])
)
# Compute the reference result using the torch convolution operator
torch_res = conv_torch_op(
input=input_padded,
weight=torch.Tensor(weights.copy()),
bias=torch.Tensor(biases.squeeze().copy()) if biases is not None else None,
stride=strides,
groups=group,
).numpy()
check_float_array_equal(torch_res, expected_result)
# Compute the quantized result
result = q_op(q_input).dequant()
# The fp32 and quantized results should be very similar when quantization precision is high
check_r2_score(result, expected_result)
# Test the serialization of QuantizedConv
check_serialization(
q_op, QuantizedConv, equal_method=partial(quantized_op_results_are_equal, q_input=q_input)
)
@pytest.mark.parametrize("n_bits", [16])
@pytest.mark.parametrize(
"params",
[
(
numpy.random.uniform(low=-2.0, high=2.0, size=(1, 1, 32, 32)),
(3, 3),
(2, 2),
(0, 0, 0, 0),
0,
),
(
numpy.random.uniform(low=-1.2, high=0.2, size=(10, 1, 16, 16)),
(2, 2),
(1, 1),
(0, 0, 0, 0),
0,
),
(
numpy.random.uniform(low=-2.0, high=2.0, size=(2, 32, 4, 4)),
(2, 2),
(1, 1),
(0, 0, 0, 0),
0,
),
(
numpy.random.uniform(low=-2.0, high=2.0, size=(2, 32, 4, 4)),
(2, 4),
(1, 1),
(1, 2, 1, 2),
1,
),
(
numpy.random.uniform(low=-2.0, high=2.0, size=(2, 32, 4, 4)),
(2, 4),
(1, 1),
(0, 2, 0, 2),
1,
),
(
numpy.random.uniform(low=-2.0, high=2.0, size=(2, 32, 5, 5)),
(3, 3),
(1, 1),
(1, 1, 1, 1),
1,
),
(
numpy.random.uniform(low=-2.0, high=2.0, size=(2, 1, 7, 5)),
(5, 1),
(1, 1),
(1, 2, 0, 4),
1,
),
(
numpy.random.uniform(low=-2.0, high=2.0, size=(1, 1, 16, 16)),
(2, 2),
(4, 4),
(1, 2, 0, 4),
1,
),
],
)
@pytest.mark.parametrize("is_signed", [True, False])
def test_quantized_avg_pool(params, n_bits, is_signed, check_r2_score, check_float_array_equal):
"""Test the quantized average pool operator."""
# Retrieve arguments
net_input, kernel_shape, strides, pads, ceil_mode = params
# Create quantized data
q_input = QuantizedArray(n_bits, net_input, is_signed=is_signed)
q_op = QuantizedAvgPool(
n_bits,
OP_DEBUG_NAME + "QuantizedAvgPool",
strides=strides,
pads=pads,
kernel_shape=kernel_shape,
ceil_mode=ceil_mode,
input_quant_opts=q_input.quantizer.quant_options,
)
# Compute the result in floating point
expected_result = q_op.calibrate(net_input)
# Pad the input if needed
tinputs = torch.Tensor(net_input.copy())
# Torch uses padding (padding_left,padding_right, padding_top,padding_bottom)
# While ONNX and Concrete ML use (padding_top, padding_left, padding_bottom, padding_right)
tx_pad = torch.nn.functional.pad(tinputs, (pads[1], pads[3], pads[0], pads[2]))
# Compute the torch average pool
bceil_mode = bool(ceil_mode)
torch_res = torch.nn.functional.avg_pool2d(tx_pad, kernel_shape, strides, 0, bceil_mode).numpy()
check_float_array_equal(torch_res, expected_result)
# Compute the quantized result
result = q_op(q_input).dequant()
# The fp32 and quantized results should be very similar when quantization precision is high
check_r2_score(expected_result, result)
# Test the serialization of QuantizedAvgPool
check_serialization(
q_op,
QuantizedAvgPool,
equal_method=partial(quantized_op_results_are_equal, q_input=q_input),
)
def test_quantized_avg_pool_args():
"""Check that unsupported parameters for AvgPool properly raise errors."""
n_bits = 2
with pytest.raises(AssertionError, match=r"Setting parameter 'kernel_shape' is required."):
QuantizedAvgPool(
n_bits,
OP_DEBUG_NAME + "QuantizedAvgPool",
)
with pytest.raises(AssertionError, match=r"The 'auto_pad' parameter is not supported.*"):
QuantizedAvgPool(
n_bits,
OP_DEBUG_NAME + "QuantizedAvgPool",
kernel_shape=(1, 1),
auto_pad="SAME_UPPER",
)
with pytest.raises(
AssertionError, match=r"The Average Pool operator currently supports only 2d kernels."
):
QuantizedAvgPool(
n_bits,
OP_DEBUG_NAME + "QuantizedAvgPool",
kernel_shape=(1,),
)
with pytest.raises(
AssertionError, match=r"Pad pixels must be included when calculating values on the edges.*"
):
QuantizedAvgPool(
n_bits,
OP_DEBUG_NAME + "QuantizedAvgPool",
kernel_shape=(1, 1),
count_include_pad=0,
)
with pytest.raises(
AssertionError,
match=r"The Average Pool operator requires the number of strides to be the same.*",
):
QuantizedAvgPool(
n_bits,
OP_DEBUG_NAME + "QuantizedAvgPool",
kernel_shape=(1, 1),
strides=(1,),
)
with pytest.raises(
AssertionError, match=r"The Average Pool operator in Concrete ML requires padding.*"
):
QuantizedAvgPool(
n_bits,
OP_DEBUG_NAME + "QuantizedAvgPool",
kernel_shape=(1, 1),
pads=(0, 0),
)
@pytest.mark.parametrize("n_bits", [16])
@pytest.mark.parametrize(
"params",
[
(
numpy.random.uniform(low=-4.0, high=4.0, size=(1, 1, 32, 32)),
(3, 3),
(2, 2),
(0, 0, 0, 0),
1,
0,
),
(
numpy.random.uniform(low=-0.2, high=0.2, size=(10, 1, 16, 16)),
(2, 2),
(1, 1),
(0, 0, 0, 0),
1,
0,
),
(
numpy.random.uniform(low=-5.0, high=3.0, size=(2, 32, 4, 4)),
(2, 2),
(1, 1),
(0, 0, 0, 0),
1,
0,
),
(
numpy.random.uniform(low=-1.0, high=1.0, size=(1, 1, 6, 7)),
(2, 4),
(1, 1),
(1, 2, 1, 2),
2,
0,