/
test_compile_torch.py
1467 lines (1255 loc) · 48.8 KB
/
test_compile_torch.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 torch to numpy module."""
# pylint: disable=too-many-lines
import io
import tempfile
import zipfile
from functools import partial
from inspect import signature
from pathlib import Path
import numpy
import onnx
import onnxruntime as ort
import pytest
import torch
import torch.quantization
from concrete.fhe import ParameterSelectionStrategy # pylint: disable=ungrouped-imports
from torch import nn
from concrete.ml.common.utils import (
array_allclose_and_same_shape,
manage_parameters_for_pbs_errors,
to_tuple,
)
from concrete.ml.onnx.convert import OPSET_VERSION_FOR_ONNX_EXPORT
from concrete.ml.pytest.torch_models import (
FC,
AddNet,
BranchingGemmModule,
BranchingModule,
CNNGrouped,
CNNOther,
ConcatFancyIndexing,
Conv1dModel,
DoubleQuantQATMixNet,
EncryptedMatrixMultiplicationModel,
ExpandModel,
FCSmall,
MultiInputNN,
MultiInputNNConfigurable,
MultiInputNNDifferentSize,
MultiOutputModel,
NetWithLoops,
PaddingNet,
ShapeOperationsNet,
SimpleQAT,
SingleMixNet,
StepActivationModule,
TinyQATCNN,
UnivariateModule,
)
from concrete.ml.quantization import QuantizedModule
# pylint sees separated imports from concrete but does not understand they come from two different
# packages/projects, disable the warning
# pylint: disable=ungrouped-imports
from concrete.ml.torch.compile import (
build_quantized_module,
compile_brevitas_qat_model,
compile_onnx_model,
compile_torch_model,
)
# pylint: enable=ungrouped-imports
def create_test_inputset(inputset, n_percent_inputset_examples_test):
"""Create a test input-set from a given input-set and percentage of examples."""
n_examples_test = int(n_percent_inputset_examples_test * to_tuple(inputset)[0].shape[0])
x_test = tuple(inputs[:n_examples_test] for inputs in to_tuple(inputset))
return x_test
def get_and_compile_quantized_module(model, inputset, import_qat, n_bits, configuration, verbose):
"""Get and compile the quantized module built from the given model."""
quantized_numpy_module = build_quantized_module(
model,
inputset,
import_qat=import_qat,
n_bits=n_bits,
)
p_error, global_p_error = manage_parameters_for_pbs_errors(None, None)
quantized_numpy_module.compile(
inputset,
configuration=configuration,
p_error=p_error,
global_p_error=global_p_error,
verbose=verbose,
)
return quantized_numpy_module
# pylint: disable-next=too-many-arguments, too-many-branches
def compile_and_test_torch_or_onnx( # pylint: disable=too-many-locals, too-many-statements
input_output_feature,
model_class,
activation_function,
qat_bits,
default_configuration,
simulate,
is_onnx,
check_is_good_execution_for_cml_vs_circuit,
dump_onnx=False,
expected_onnx_str=None,
verbose=False,
get_and_compile=False,
input_shape=None,
is_brevitas_qat=False,
) -> QuantizedModule:
"""Test the different model architecture from torch numpy."""
# Define an input shape (n_examples, n_features)
n_examples = 500
# Define the torch model
torch_model = model_class(
input_output=input_output_feature, activation_function=activation_function
)
num_inputs = len(signature(torch_model.forward).parameters)
# If no specific input shape is given, use the number of input/output features
if input_shape is None:
input_shape = input_output_feature
# Create random input
if num_inputs > 1:
inputset = tuple(
numpy.random.uniform(-100, 100, size=(n_examples, *to_tuple(input_shape[i])))
for i in range(num_inputs)
)
else:
inputset = (numpy.random.uniform(-100, 100, size=(n_examples, *to_tuple(input_shape))),)
# FHE vs Quantized are not done in the test anymore (see issue #177)
if not simulate:
n_bits = (
{"model_inputs": 2, "model_outputs": 2, "op_inputs": 2, "op_weights": 2}
if qat_bits == 0
else qat_bits
)
if is_onnx:
output_onnx_file_path = Path(tempfile.mkstemp(suffix=".onnx")[1])
dummy_input = tuple(torch.from_numpy(val[[0], ::]).float() for val in inputset)
torch.onnx.export(
torch_model,
dummy_input,
str(output_onnx_file_path),
opset_version=OPSET_VERSION_FOR_ONNX_EXPORT,
)
onnx_model = onnx.load_model(str(output_onnx_file_path))
onnx.checker.check_model(onnx_model)
if get_and_compile:
quantized_numpy_module = get_and_compile_quantized_module(
model=onnx_model,
inputset=inputset,
import_qat=qat_bits != 0,
n_bits=n_bits,
configuration=default_configuration,
verbose=verbose,
)
else:
quantized_numpy_module = compile_onnx_model(
onnx_model,
inputset,
import_qat=qat_bits != 0,
configuration=default_configuration,
n_bits=n_bits,
verbose=verbose,
)
else:
if is_brevitas_qat:
n_bits = qat_bits
quantized_numpy_module = compile_brevitas_qat_model(
torch_model=torch_model,
torch_inputset=inputset,
n_bits=n_bits,
configuration=default_configuration,
verbose=verbose,
)
elif get_and_compile:
quantized_numpy_module = get_and_compile_quantized_module(
model=torch_model,
inputset=inputset,
import_qat=qat_bits != 0,
n_bits=n_bits,
configuration=default_configuration,
verbose=verbose,
)
else:
quantized_numpy_module = compile_torch_model(
torch_model,
inputset,
import_qat=qat_bits != 0,
configuration=default_configuration,
n_bits=n_bits,
verbose=verbose,
)
n_examples_test = 1
# Use some input-set to test the inference.
# Using the input-set allows to remove any chance of overflow.
x_test = tuple(inputs[:n_examples_test] for inputs in inputset)
quantized_numpy_module.check_model_is_compiled()
# Make sure FHE simulation and quantized module forward give the same output.
check_is_good_execution_for_cml_vs_circuit(
x_test, model=quantized_numpy_module, simulate=simulate
)
else:
if is_brevitas_qat:
n_bits = qat_bits
quantized_numpy_module = compile_brevitas_qat_model(
torch_model=torch_model,
torch_inputset=inputset,
n_bits=n_bits,
configuration=default_configuration,
verbose=verbose,
)
else:
# Compile our network with 16-bits
# to compare to torch (8b weights + float 32 activations)
if qat_bits == 0:
n_bits_w_a = 4
else:
n_bits_w_a = qat_bits
n_bits = {
"model_inputs": 8,
"op_weights": n_bits_w_a,
"op_inputs": n_bits_w_a,
"model_outputs": 8,
}
if get_and_compile:
quantized_numpy_module = get_and_compile_quantized_module(
model=torch_model,
inputset=inputset,
import_qat=qat_bits != 0,
n_bits=n_bits,
configuration=default_configuration,
verbose=verbose,
)
else:
quantized_numpy_module = compile_torch_model(
torch_model,
inputset,
import_qat=qat_bits != 0,
configuration=default_configuration,
n_bits=n_bits,
verbose=verbose,
)
accuracy_test_rounding(
torch_model,
quantized_numpy_module,
inputset,
import_qat=qat_bits != 0,
configuration=default_configuration,
n_bits=n_bits,
simulate=simulate,
verbose=verbose,
check_is_good_execution_for_cml_vs_circuit=check_is_good_execution_for_cml_vs_circuit,
is_brevitas_qat=is_brevitas_qat,
)
if dump_onnx:
str_model = onnx.helper.printable_graph(quantized_numpy_module.onnx_model.graph)
print("ONNX model:")
print(str_model)
assert str_model == expected_onnx_str
return quantized_numpy_module
# pylint: disable-next=too-many-arguments,too-many-locals
def accuracy_test_rounding(
torch_model,
quantized_numpy_module,
inputset,
import_qat,
configuration,
n_bits,
simulate,
verbose,
check_is_good_execution_for_cml_vs_circuit,
is_brevitas_qat=False,
):
"""Check rounding behavior with both EXACT and APPROXIMATE methods.
The original quantized_numpy_module, compiled over the torch_model without rounding is
compared against quantized_numpy_module_round_low_precision and
quantized_numpy_module_round_high_precision, the torch_model compiled with a rounding threshold
of 2 bits and 8 bits respectively, using both EXACT and APPROXIMATE methods.
The final assertion tests whether the mean absolute error between
quantized_numpy_module_round_high_precision and quantized_numpy_module is lower than
quantized_numpy_module_round_low_precision and quantized_numpy_module making sure that the
rounding feature has the expected behavior on the model accuracy.
"""
# Check that the maximum_integer_bit_width is at least 4 bits to compare the rounding
# feature with enough precision.
assert quantized_numpy_module.fhe_circuit.graph.maximum_integer_bit_width() >= 4
# Define rounding thresholds for high and low precision with both EXACT and APPROXIMATE methods
rounding_thresholds = {
"high_exact": {"method": "EXACT", "n_bits": 8},
"low_exact": {"method": "EXACT", "n_bits": 2},
"high_approximate": {"method": "APPROXIMATE", "n_bits": 8},
"low_approximate": {"method": "APPROXIMATE", "n_bits": 2},
}
compiled_modules = {}
# Compile models with different rounding thresholds and methods
for key, rounding_threshold in rounding_thresholds.items():
if is_brevitas_qat:
compiled_modules[key] = compile_brevitas_qat_model(
torch_model,
inputset,
n_bits=n_bits,
configuration=configuration,
rounding_threshold_bits=rounding_threshold,
verbose=verbose,
)
else:
compiled_modules[key] = compile_torch_model(
torch_model,
inputset,
import_qat=import_qat,
configuration=configuration,
n_bits=n_bits,
rounding_threshold_bits=rounding_threshold,
verbose=verbose,
)
n_percent_inputset_examples_test = 0.1
# Using the input-set allows to remove any chance of overflow.
x_test = create_test_inputset(inputset, n_percent_inputset_examples_test)
# Make sure the modules have the same quantization result
qtest = to_tuple(quantized_numpy_module.quantize_input(*x_test))
for _, module in compiled_modules.items():
qtest_rounded = to_tuple(module.quantize_input(*x_test))
assert all(
numpy.array_equal(qtest_i, qtest_rounded_i)
for (qtest_i, qtest_rounded_i) in zip(qtest, qtest_rounded)
)
results: dict = {key: [] for key in compiled_modules}
for i in range(x_test[0].shape[0]):
q_x = tuple(q[[i]] for q in to_tuple(qtest))
for key, module in compiled_modules.items():
q_result = module.quantized_forward(*q_x, fhe="simulate")
result = module.dequantize_output(q_result)
results[key].append(result)
# Check modules predictions FHE simulation vs Concrete ML.
for key, module in compiled_modules.items():
# low bit-width rounding is not behaving as expected with new simulation
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/433
if "low" not in key:
check_is_good_execution_for_cml_vs_circuit(x_test, module, simulate=simulate)
# FIXME: The following MSE comparison is commented out due to instability issues.
# We will investigate a better way to assess the rounding feature's performance.
# https://github.com/zama-ai/concrete-ml-internal/issues/3662
# mse_results = {
# key: numpy.mean(numpy.square(numpy.subtract(results['original'], result_list)))
# for key, result_list in results.items()
# }
# assert (mse_results['high_exact'] <= mse_results['low_exact'],
# "Rounding is not working as expected.")
# assert (mse_results['high_approximate'] <= mse_results['low_approximate'],
# "Rounding is not working as expected.")
# This test is a known flaky
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/3429
@pytest.mark.flaky
@pytest.mark.parametrize(
"activation_function",
[
pytest.param(nn.ReLU, id="relu"),
],
)
@pytest.mark.parametrize(
"model, input_output_feature",
[
pytest.param(FCSmall, 5),
pytest.param(partial(NetWithLoops, n_fc_layers=2), 5),
pytest.param(BranchingModule, 5),
pytest.param(BranchingGemmModule, 5),
pytest.param(MultiInputNN, [5, 5]),
pytest.param(MultiInputNNDifferentSize, [5, 10]),
pytest.param(UnivariateModule, 5),
pytest.param(StepActivationModule, 5),
pytest.param(EncryptedMatrixMultiplicationModel, 5),
],
)
@pytest.mark.parametrize("simulate", [True, False], ids=["FHE_simulation", "FHE"])
@pytest.mark.parametrize("is_onnx", [True, False], ids=["is_onnx", ""])
@pytest.mark.parametrize("get_and_compile", [True, False], ids=["get_and_compile", "compile"])
def test_compile_torch_or_onnx_networks(
input_output_feature,
model,
activation_function,
default_configuration,
simulate,
is_onnx,
get_and_compile,
check_is_good_execution_for_cml_vs_circuit,
is_weekly_option,
):
"""Test the different model architecture from torch numpy."""
# Avoid too many tests
if not simulate and not is_weekly_option:
if model not in [FCSmall, BranchingModule]:
pytest.skip("Avoid too many tests")
# The QAT bits is set to 0 in order to signal that the network is not using QAT
qat_bits = 0
compile_and_test_torch_or_onnx(
input_output_feature=input_output_feature,
model_class=model,
activation_function=activation_function,
qat_bits=qat_bits,
default_configuration=default_configuration,
simulate=simulate,
is_onnx=is_onnx,
check_is_good_execution_for_cml_vs_circuit=check_is_good_execution_for_cml_vs_circuit,
verbose=False,
get_and_compile=get_and_compile,
)
# This test is a known flaky
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/3660
@pytest.mark.flaky
@pytest.mark.parametrize(
"activation_function",
[
pytest.param(nn.ReLU, id="relu"),
],
)
@pytest.mark.parametrize(
"model, is_1d",
[
pytest.param(CNNOther, False, id="CNN"),
pytest.param(partial(CNNGrouped, groups=3), False, id="CNN_grouped"),
pytest.param(Conv1dModel, True, id="CNN_conv1d"),
],
)
@pytest.mark.parametrize("simulate", [True, False])
@pytest.mark.parametrize("is_onnx", [True, False])
def test_compile_torch_or_onnx_conv_networks( # pylint: disable=unused-argument
model,
is_1d,
activation_function,
default_configuration,
simulate,
is_onnx,
check_graph_input_has_no_tlu,
check_graph_output_has_no_tlu,
check_is_good_execution_for_cml_vs_circuit,
):
"""Test the different model architecture from torch numpy."""
# The QAT bits is set to 0 in order to signal that the network is not using QAT
qat_bits = 0
input_shape = (6, 7) if is_1d else (6, 7, 7)
input_output = input_shape[0]
q_module = compile_and_test_torch_or_onnx(
input_output_feature=input_output,
model_class=model,
activation_function=activation_function,
qat_bits=qat_bits,
default_configuration=default_configuration,
simulate=simulate,
is_onnx=is_onnx,
check_is_good_execution_for_cml_vs_circuit=check_is_good_execution_for_cml_vs_circuit,
verbose=False,
input_shape=input_shape,
)
check_graph_input_has_no_tlu(q_module.fhe_circuit.graph)
check_graph_output_has_no_tlu(q_module.fhe_circuit.graph)
@pytest.mark.parametrize(
"activation_function",
[
pytest.param(nn.Sigmoid, id="sigmoid"),
pytest.param(nn.ReLU, id="relu"),
pytest.param(nn.ReLU6, id="relu6"),
pytest.param(nn.Tanh, id="tanh"),
pytest.param(nn.ELU, id="ELU"),
pytest.param(nn.Hardsigmoid, id="Hardsigmoid"),
pytest.param(nn.Hardtanh, id="Hardtanh"),
pytest.param(nn.LeakyReLU, id="LeakyReLU"),
pytest.param(nn.SELU, id="SELU"),
pytest.param(nn.CELU, id="CELU"),
pytest.param(nn.Softplus, id="Softplus"),
pytest.param(nn.PReLU, id="PReLU"),
pytest.param(nn.Hardswish, id="Hardswish"),
pytest.param(nn.SiLU, id="SiLU"),
pytest.param(nn.Mish, id="Mish"),
pytest.param(nn.Tanhshrink, id="Tanhshrink"),
pytest.param(partial(nn.Threshold, threshold=0, value=0), id="Threshold"),
pytest.param(nn.Softshrink, id="Softshrink"),
pytest.param(nn.Hardshrink, id="Hardshrink"),
pytest.param(nn.Softsign, id="Softsign"),
pytest.param(nn.GELU, id="GELU"),
pytest.param(nn.LogSigmoid, id="LogSigmoid"),
# Some issues are still encountered with some activations
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/335
#
# Other problems, certainly related to tests:
# Required positional arguments: 'embed_dim' and 'num_heads' and fails with a partial
# pytest.param(nn.MultiheadAttention, id="MultiheadAttention"),
# Activation with a RandomUniformLike
# pytest.param(nn.RReLU, id="RReLU"),
# Halving dimension must be even, but dimension 3 is size 3
# pytest.param(nn.GLU, id="GLU"),
],
)
@pytest.mark.parametrize(
"model, input_output_feature",
[
pytest.param(FCSmall, 5),
],
)
@pytest.mark.parametrize("simulate", [True, False])
@pytest.mark.parametrize("is_onnx", [True, False])
def test_compile_torch_or_onnx_activations(
input_output_feature,
model,
activation_function,
default_configuration,
simulate,
is_onnx,
check_is_good_execution_for_cml_vs_circuit,
):
"""Test the different model architecture from torch numpy."""
# The QAT bits is set to 0 in order to signal that the network is not using QAT
qat_bits = 0
compile_and_test_torch_or_onnx(
input_output_feature,
model,
activation_function,
qat_bits,
default_configuration,
simulate,
is_onnx,
check_is_good_execution_for_cml_vs_circuit,
verbose=False,
)
@pytest.mark.parametrize(
"model",
[
pytest.param(SimpleQAT),
],
)
@pytest.mark.parametrize(
"input_output_feature",
[pytest.param(input_output_feature) for input_output_feature in [2, 4]],
)
@pytest.mark.parametrize(
"n_bits",
[pytest.param(n_bits) for n_bits in [1, 2]],
)
@pytest.mark.parametrize("simulate", [True, False])
def test_compile_torch_qat(
input_output_feature,
model,
n_bits,
default_configuration,
simulate,
check_is_good_execution_for_cml_vs_circuit,
):
"""Test the different model architecture from torch numpy."""
model = partial(model, n_bits=n_bits)
# Import these networks from torch directly
is_onnx = False
qat_bits = n_bits
compile_and_test_torch_or_onnx(
input_output_feature,
model,
nn.Sigmoid,
qat_bits,
default_configuration,
simulate,
is_onnx,
check_is_good_execution_for_cml_vs_circuit,
verbose=False,
)
@pytest.mark.parametrize(
"model_class, input_output_feature, is_brevitas_qat",
[pytest.param(partial(MultiInputNNDifferentSize, is_brevitas_qat=True), [5, 10], True)],
)
@pytest.mark.parametrize(
"n_bits",
[pytest.param(n_bits) for n_bits in [2]],
)
@pytest.mark.parametrize("simulate", [True, False])
def test_compile_brevitas_qat(
model_class,
input_output_feature,
is_brevitas_qat,
n_bits,
simulate,
default_configuration,
check_is_good_execution_for_cml_vs_circuit,
):
"""Test compile_brevitas_qat_model."""
model_class = partial(model_class, n_bits=n_bits)
# If this is a Brevitas QAT model, use n_bits for QAT bits
if is_brevitas_qat:
qat_bits = n_bits
# The QAT bits is set to 0 in order to signal that the network is not using QAT
else:
qat_bits = 0
compile_and_test_torch_or_onnx(
input_output_feature=input_output_feature,
model_class=model_class,
activation_function=None,
qat_bits=qat_bits,
default_configuration=default_configuration,
simulate=simulate,
is_onnx=False,
check_is_good_execution_for_cml_vs_circuit=check_is_good_execution_for_cml_vs_circuit,
verbose=False,
is_brevitas_qat=is_brevitas_qat,
)
@pytest.mark.parametrize(
"model_class, expected_onnx_str",
[
pytest.param(
FC,
(
"""graph torch_jit (
%x[FLOAT, 1x7]
) initializers (
%fc1.weight[FLOAT, 128x7]
%fc1.bias[FLOAT, 128]
%fc2.weight[FLOAT, 64x128]
%fc2.bias[FLOAT, 64]
%fc3.weight[FLOAT, 64x64]
%fc3.bias[FLOAT, 64]
%fc4.weight[FLOAT, 64x64]
%fc4.bias[FLOAT, 64]
%fc5.weight[FLOAT, 10x64]
%fc5.bias[FLOAT, 10]
) {
%/fc1/Gemm_output_0 = Gemm[alpha = 1, beta = 1, transB = 1]"""
"""(%x, %fc1.weight, %fc1.bias)
%/act_1/Relu_output_0 = Relu(%/fc1/Gemm_output_0)
%/fc2/Gemm_output_0 = Gemm[alpha = 1, beta = 1, transB = 1]"""
"""(%/act_1/Relu_output_0, %fc2.weight, %fc2.bias)
%/act_2/Relu_output_0 = Relu(%/fc2/Gemm_output_0)
%/fc3/Gemm_output_0 = Gemm[alpha = 1, beta = 1, transB = 1]"""
"""(%/act_2/Relu_output_0, %fc3.weight, %fc3.bias)
%/act_3/Relu_output_0 = Relu(%/fc3/Gemm_output_0)
%/fc4/Gemm_output_0 = Gemm[alpha = 1, beta = 1, transB = 1]"""
"""(%/act_3/Relu_output_0, %fc4.weight, %fc4.bias)
%/act_4/Relu_output_0 = Relu(%/fc4/Gemm_output_0)
%19 = Gemm[alpha = 1, beta = 1, transB = 1](%/act_4/Relu_output_0, %fc5.weight, %fc5.bias)
return %19
}"""
),
),
],
)
@pytest.mark.parametrize(
"activation_function",
[
pytest.param(nn.ReLU, id="relu"),
],
)
def test_dump_torch_network(
model_class,
expected_onnx_str,
activation_function,
default_configuration,
check_is_good_execution_for_cml_vs_circuit,
):
"""This is a test which is equivalent to tests in test_dump_onnx.py, but for torch modules."""
input_output_feature = 7
simulate = True
is_onnx = False
qat_bits = 0
compile_and_test_torch_or_onnx(
input_output_feature,
model_class,
activation_function,
qat_bits,
default_configuration,
simulate,
is_onnx,
check_is_good_execution_for_cml_vs_circuit,
dump_onnx=True,
expected_onnx_str=expected_onnx_str,
verbose=False,
)
@pytest.mark.parametrize("verbose", [True, False], ids=["with_verbose", "without_verbose"])
# pylint: disable-next=too-many-locals
def test_pretrained_mnist_qat(
default_configuration,
check_accuracy,
verbose,
check_graph_output_has_no_tlu,
check_is_good_execution_for_cml_vs_circuit,
is_weekly_option,
):
"""Load a QAT MNIST model and confirm we get the same results in FHE simulation as with ONNX."""
if not is_weekly_option:
pytest.skip("Tests too long")
onnx_file_path = "tests/data/torch/mnist_2b_s1_1.zip"
mnist_test_path = "tests/data/torch/mnist_test_batch.zip"
# Load ONNX model from zip file
with zipfile.ZipFile(onnx_file_path, "r") as archive_model:
onnx_model_serialized = io.BytesIO(archive_model.read("mnist_2b_s1_1.onnx")).read()
onnx_model = onnx.load_model_from_string(onnx_model_serialized)
onnx.checker.check_model(onnx_model)
# Load test data and ground truth from zip file
with zipfile.ZipFile(mnist_test_path, "r") as archive_data:
mnist_data = numpy.load(
io.BytesIO(archive_data.read("mnist_test_batch.npy")), allow_pickle=True
).item()
# Get the test data
inputset = mnist_data["test_data"]
# Run through ONNX runtime and collect results
ort_session = ort.InferenceSession(onnx_model_serialized)
onnx_results = numpy.zeros((inputset.shape[0],), dtype=numpy.int64)
for i, x_test in enumerate(inputset):
onnx_outputs = ort_session.run(
None,
{onnx_model.graph.input[0].name: x_test.reshape(1, -1)},
)
onnx_results[i] = numpy.argmax(onnx_outputs[0])
# Compile to Concrete ML in FHE simulation mode, with a high bit-width
n_bits = {
"model_inputs": 16,
"op_weights": 2,
"op_inputs": 2,
"model_outputs": 16,
}
quantized_numpy_module = compile_onnx_model(
onnx_model,
inputset,
import_qat=True,
configuration=default_configuration,
n_bits=n_bits,
verbose=verbose,
)
quantized_numpy_module.check_model_is_compiled()
check_is_good_execution_for_cml_vs_circuit(inputset, quantized_numpy_module, simulate=True)
# Collect FHE simulation results
results = []
for i in range(inputset.shape[0]):
# Extract example i for each tensor in the tuple input-set
# while keeping the dimension of the original tensors.
# e.g., if input-set is a tuple of two (100, 10) tensors
# then q_x becomes a tuple of two tensors of shape (1, 10).
x = tuple(input[[i]] for input in to_tuple(inputset))
result = numpy.argmax(quantized_numpy_module.forward(*x, fhe="simulate"))
results.append(result)
# Compare ONNX runtime vs FHE simulation mode
check_accuracy(onnx_results, results, threshold=0.999)
# Make sure absolute accuracy is good, this model should have at least 90% accuracy
check_accuracy(mnist_data["gt"], results, threshold=0.9)
# Compile to Concrete ML using the FHE simulation mode and compatible bit-width
n_bits = {
"model_inputs": 7,
"op_weights": 2,
"op_inputs": 2,
"model_outputs": 7,
}
quantized_numpy_module = compile_onnx_model(
onnx_model,
inputset,
import_qat=True,
configuration=default_configuration,
n_bits=n_bits,
verbose=verbose,
)
# As this is a custom QAT network, the input goes through multiple univariate
# ops that form a quantizer. Thus it has input TLUs. But it should not have output TLUs
check_graph_output_has_no_tlu(quantized_numpy_module.fhe_circuit.graph)
assert quantized_numpy_module.fhe_circuit.graph.maximum_integer_bit_width() <= 8
def test_qat_import_bits_check(default_configuration):
"""Test that compile_brevitas_qat_model does not need an n_bits config."""
input_features = 10
model = SingleMixNet(False, True, 10, 2)
n_examples = 50
# All these n_bits configurations should be valid
# and produce the same result, as the input/output bit-widths for this network
# are ignored due to the input/output TLU elimination
n_bits_valid = [
4,
2,
{"model_inputs": 4, "model_outputs": 4},
{"model_inputs": 2, "model_outputs": 2},
]
# Create random input
inputset = numpy.random.uniform(-100, 100, size=(n_examples, input_features))
# Compile with no quantization bit-width, defaults are used
quantized_numpy_module = compile_brevitas_qat_model(
model,
inputset,
configuration=default_configuration,
)
n_percent_inputset_examples_test = 0.1
# Using the input-set allows to remove any chance of overflow.
x_test = create_test_inputset(inputset, n_percent_inputset_examples_test)
# The result of compiling without any n_bits (default)
predictions = quantized_numpy_module.forward(*x_test, fhe="disable")
# Compare the results of running with n_bits=None to the results running with
# all the other n_bits configs. The results should be the same as bit-widths
# are ignored for this network (they are overridden with Brevitas values stored in ONNX).
for n_bits in n_bits_valid:
quantized_numpy_module = compile_brevitas_qat_model(
model,
inputset,
n_bits=n_bits,
configuration=default_configuration,
)
new_predictions = quantized_numpy_module.forward(*x_test, fhe="disable")
assert numpy.all(predictions == new_predictions)
n_bits_invalid = [
{"XYZ": 8, "model_inputs": 8},
{"XYZ": 8},
]
# Test that giving a dictionary with invalid keys does not work
for n_bits in n_bits_invalid:
with pytest.raises(
AssertionError, match=".*n_bits should only contain the following keys.*"
):
quantized_numpy_module = compile_brevitas_qat_model(
model,
inputset,
n_bits=n_bits,
configuration=default_configuration,
)
def test_qat_import_check(default_configuration, check_is_good_execution_for_cml_vs_circuit):
"""Test two cases of custom (non brevitas) NNs where importing as QAT networks should fail."""
qat_bits = 4
simulate = True
error_message_pattern = "Error occurred during quantization aware training.*"
# This first test is trying to import a network that is QAT (has a quantizer in the graph)
# but the import bit-width is wrong (mismatch between bit-width specified in training
# and the bit-width specified during import). For NNs that are not built with Brevitas
# the bit-width must be manually specified and is used to infer quantization parameters.
with pytest.raises(ValueError, match=error_message_pattern):
compile_and_test_torch_or_onnx(
10,
partial(SimpleQAT, n_bits=6, disable_bit_check=True),
nn.ReLU,
qat_bits,
default_configuration,
simulate,
False,
check_is_good_execution_for_cml_vs_circuit,
)
input_shape = (1, 7, 7)
input_output = input_shape[0]
# The second case is a network that is not QAT but is being imported as a QAT network
with pytest.raises(ValueError, match=error_message_pattern):
compile_and_test_torch_or_onnx(
input_output,
CNNOther,
nn.ReLU,
qat_bits,
default_configuration,
simulate,
False,
check_is_good_execution_for_cml_vs_circuit,
input_shape=input_shape,
)
class AllZeroCNN(CNNOther):
"""A CNN class that has all zero weights and biases."""
def __init__(self, input_output, activation_function):
super().__init__(input_output, activation_function)
for module in self.modules():
# assert m.bias is not None
# Disable mypy as it properly detects that module's bias term is None end therefore
# does not have a `data` attribute but fails to take into consideration the fact
# that `torch.nn.init.constant_` actually handles such a case
if isinstance(module, (nn.Conv2d, nn.Linear)):
torch.nn.init.constant_(module.weight.data, 0)
torch.nn.init.constant_(module.bias.data, 0) # type: ignore[union-attr]
input_shape = (1, 7, 7)
input_output = input_shape[0]
# A network that may look like QAT but it just zeros all inputs
with pytest.raises(ValueError, match=error_message_pattern):
compile_and_test_torch_or_onnx(
input_output,
AllZeroCNN,
nn.ReLU,
qat_bits,
default_configuration,
simulate,
False,
check_is_good_execution_for_cml_vs_circuit,
input_shape=input_shape,
)
@pytest.mark.parametrize("n_bits", [2])
@pytest.mark.parametrize("use_qat", [True, False])
@pytest.mark.parametrize("force_tlu", [True, False])
@pytest.mark.parametrize(
"module, input_shape, num_inputs, is_fully_leveled",
[
(SingleMixNet, (1, 8, 8), 1, True),
(SingleMixNet, 10, 1, True),
(MultiInputNNConfigurable, 10, 2, False),