/
quantized_ops.py
2215 lines (1731 loc) · 79.1 KB
/
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
"""Quantized versions of the ONNX operators for post training quantization."""
# pylint: disable=too-many-lines
# This file is too long and should be split
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/1018
from typing import Any, Dict, Optional, Sequence, Set, Union
import numpy
from concrete.fhe import conv as cnp_conv
from concrete.fhe import maxpool as cnp_maxpool
from concrete.fhe import tag
from typing_extensions import SupportsIndex
from ..common.debugging import assert_false, assert_true
from ..onnx.onnx_impl_utils import (
compute_onnx_pool_padding,
numpy_onnx_pad,
onnx_avgpool_compute_norm_const,
)
from ..onnx.ops_impl import RawOpOutput
from .base_quantized_op import (
ONNXOpInputOutputType,
QuantizedMixingOp,
QuantizedOp,
QuantizedOpUnivariateOfEncrypted,
)
from .quantizers import QuantizationOptions, QuantizedArray, UniformQuantizationParameters
def _check_op_input_zero_point(zero_point: Any, op_name: Optional[str]):
"""Check that an operation's quantized input zero-point is a single value.
Args:
zero_point (Any): The input zero-point
op_name (str): The name of the operation that is checking its input
"""
# Checks with assert to also to ensure type safety
assert zero_point is not None and (
isinstance(zero_point, (int, float))
or numpy.isscalar(zero_point)
or (isinstance(zero_point, numpy.ndarray) and zero_point.size == 1)
), (
f"Operation {op_name} is trying to use an input with a zero-point that is "
"not a single value. Only model output quantizers can have zero-points that are arrays. "
)
class QuantizedSigmoid(QuantizedOp):
"""Quantized sigmoid op."""
_impl_for_op_named: str = "Sigmoid"
class QuantizedHardSigmoid(QuantizedOp):
"""Quantized HardSigmoid op."""
_impl_for_op_named: str = "HardSigmoid"
class QuantizedRelu(QuantizedOp):
"""Quantized Relu op."""
_impl_for_op_named: str = "Relu"
class QuantizedPRelu(QuantizedOp):
"""Quantized PRelu op."""
_impl_for_op_named: str = "PRelu"
class QuantizedLeakyRelu(QuantizedOp):
"""Quantized LeakyRelu op."""
_impl_for_op_named: str = "LeakyRelu"
class QuantizedHardSwish(QuantizedOp):
"""Quantized Hardswish op."""
_impl_for_op_named: str = "HardSwish"
class QuantizedElu(QuantizedOp):
"""Quantized Elu op."""
_impl_for_op_named: str = "Elu"
class QuantizedSelu(QuantizedOp):
"""Quantized Selu op."""
_impl_for_op_named: str = "Selu"
class QuantizedCelu(QuantizedOp):
"""Quantized Celu op."""
_impl_for_op_named: str = "Celu"
class QuantizedClip(QuantizedOp):
"""Quantized clip op."""
_impl_for_op_named: str = "Clip"
class QuantizedRound(QuantizedOp):
"""Quantized round op."""
_impl_for_op_named: str = "Round"
class QuantizedPow(QuantizedOpUnivariateOfEncrypted, QuantizedOp):
"""Quantized pow op.
Only works for a float constant power. This operation will be fused to a (potentially
larger) TLU.
"""
_impl_for_op_named: str = "Pow"
class QuantizedGemm(QuantizedMixingOp):
"""Quantized Gemm op."""
_impl_for_op_named: str = "Gemm"
def __init__(
self,
n_bits_output: int,
op_instance_name: str,
int_input_names: Set[str] = None,
constant_inputs: Optional[Union[Dict[str, Any], Dict[int, Any]]] = None,
input_quant_opts: QuantizationOptions = None,
**attrs,
) -> None:
super().__init__(
n_bits_output,
op_instance_name,
int_input_names,
constant_inputs,
input_quant_opts,
**attrs,
)
alpha = self.attrs.get("alpha", 1)
beta = self.attrs.get("beta", 1)
assert_true(
alpha == 1 and beta in [0, 1],
f"{self.__class__.__name__} currently only supports alpha == 1 and beta in [0, 1].\n"
f"Got alpha == {alpha} and beta == {beta}.",
)
assert_true(
1 in self.constant_inputs,
f"{self.__class__.__name__} currently only supports quantizing "
f"{self._impl_for_op_named} if weights are provided as the 'b' constant input.",
)
def q_impl(
self,
*q_inputs: ONNXOpInputOutputType,
calibrate_rounding: bool = False,
**attrs,
) -> ONNXOpInputOutputType:
alpha = self.attrs.get("alpha", 1)
beta = self.attrs.get("beta", 1)
# If alpha != 1 or beta not in [0, 1], this function must be modified
assert_true(alpha == 1)
assert_true(beta in [0, 1])
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=True
)
q_input: QuantizedArray = prepared_inputs[0]
q_weights: QuantizedArray = prepared_inputs[1]
q_bias: Optional[numpy.ndarray] = (
None if len(prepared_inputs) == 2 or beta == 0 else prepared_inputs[2]
)
# Using snake case here to please the Python format, the original attrs don't have the '_'
# Use default false so we also support MatMul impl, MatMul does not have these flags
transpose_inputs = attrs.get("transA", False)
transpose_w = attrs.get("transB", False)
with tag(self.op_instance_name + ".input"):
input_q_values = (
numpy.transpose(q_input.qvalues) if transpose_inputs else q_input.qvalues
)
weights_q_values = numpy.transpose(q_weights.qvalues) if transpose_w else q_weights.qvalues
# For mypy
assert self.output_quant_params is not None
assert self.output_quant_params.scale is not None
assert self.output_quant_params.zero_point is not None
assert q_weights.quantizer.scale is not None
assert q_weights.quantizer.zero_point is not None
assert q_input.quantizer.scale is not None
assert q_input.quantizer.zero_point is not None
# The following MatMul is done with integers, and thus, does not use of any PBS.
# Rescaling the output of the integer MatMul to handle scale changes is done
# in float and will thus be fused with any float processing that follows this layer.
# Here we follow Eq.7 in https://arxiv.org/abs/1712.05877 to split the core computation
# from the zero points and scales.
p = weights_q_values.shape[0]
# Core matmul operation in full integers with a shape change (INTEGERS)
with tag(self.op_instance_name + ".matmul"):
matmul = input_q_values @ weights_q_values
# If the weights have symmetric quantization, their zero point will be 0
# The following check avoids the computation of the sum of the inputs, which may have
# large bit-width, in the case where it would be multiplied by zero
if q_weights.quantizer.zero_point != 0:
# Sum operation in full integers resulting in large integers (INTEGERS)
with tag(self.op_instance_name + ".matmul_inputsum"):
sum_input = -q_weights.quantizer.zero_point * numpy.sum(
input_q_values, axis=1, keepdims=True
)
with tag(self.op_instance_name + ".matmul_add_inputsum"):
# Last part that has to be done in integer
numpy_q_out = matmul + sum_input
else:
numpy_q_out = matmul
if self.debug_value_tracker is not None:
# pylint: disable-next=unsubscriptable-object
self.debug_value_tracker[self.op_instance_name]["output"] = numpy_q_out # type: ignore
# sum_weights is a constant
sum_weights = q_input.quantizer.zero_point * numpy.sum(
weights_q_values, axis=0, keepdims=True
)
final_term = p * q_input.quantizer.zero_point * q_weights.quantizer.zero_point
# Note that here we do not rescale to the output_scale and we do not add a zero-point
# Any following Gemm/MatMul/Conv layers will do the rescaling (during re-quantization)
# by calling _prepare_inputs_with_constants(...quantize_real_values=True)
m_matmul = q_input.quantizer.scale * q_weights.quantizer.scale
# If this operation's result are network outputs, return
# directly the integer values and a appropriate quantization parameters that
# allow direct in-the-clear de-quantization, including the bias
if self.produces_graph_output:
out_zp: Union[int, numpy.ndarray] = sum_weights - final_term
if q_bias is not None:
# Make mypy happy
assert q_bias is not None
# Reshape the biases to broadcast them to each neuron
out_zp = out_zp + q_bias / (-m_matmul)
# We identify terms in the above equation to determine what
# the scale/zero-point of the in-the-clear quantizer should be
# to properly de-quantize numpy_q_out
return self.make_output_quant_parameters(numpy_q_out, m_matmul, out_zp)
with tag(self.op_instance_name + ".matmul_rounding"):
# Apply Concrete rounding (if relevant)
numpy_q_out = self.cnp_round(numpy_q_out, calibrate_rounding)
# Quantization scales and zero points (FLOATS involved)
# This is going to be compiled with a PBS (along with the following activation function)
numpy_q_out = numpy_q_out.astype(numpy.float64) + final_term - sum_weights
numpy_q_out = m_matmul * numpy_q_out
if q_bias is not None:
# The bias is handled as a float and will be fused
numpy_q_out = numpy_q_out + q_bias
# Return the float values, so that Concrete can fuse any following float operations
# We also keep track of the scaling factor and zero-point, since these will be
# applied by the following layers.
return QuantizedArray(
self.n_bits,
numpy_q_out,
value_is_float=True,
options=self._get_output_quant_opts(),
stats=self.output_quant_stats,
params=self.output_quant_params,
)
class QuantizedMatMul(QuantizedGemm):
"""Quantized MatMul op."""
_impl_for_op_named: str = "MatMul"
class QuantizedAdd(QuantizedOp):
"""Quantized Addition operator.
Can add either two variables (both encrypted) or a variable and a constant
"""
_impl_for_op_named: str = "Add"
b_sign: int = 1
def q_impl(
self,
*q_inputs: ONNXOpInputOutputType,
**attrs,
) -> ONNXOpInputOutputType:
# If operating over all raw inputs, just perform the op in the clear
if all(isinstance(q_input, RawOpOutput) for q_input in q_inputs):
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=False
)
return self.call_impl(*prepared_inputs, **attrs).view(RawOpOutput)
# For mypy
assert self.output_quant_params is not None
assert self.output_quant_params.scale is not None
assert self.output_quant_params.zero_point is not None
# Optimize computation when adding constants, or tensors obtained from a unique integer
# tensor. Optimization allows univariate float subgraph fusion to a TLU
execute_in_float = len(self.constant_inputs) > 0 or self.can_fuse()
assert_true(
len(self.constant_inputs) < 2,
"Constant folding should have eliminated a two constant-input add node",
)
if execute_in_float:
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=False
)
return QuantizedArray(
self.n_bits,
prepared_inputs[0] + self.b_sign * prepared_inputs[1],
value_is_float=True,
options=self._get_output_quant_opts(),
stats=self.output_quant_stats,
params=self.output_quant_params,
)
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=True
)
q_input_0: QuantizedArray = prepared_inputs[0]
q_input_1: QuantizedArray = prepared_inputs[1]
assert q_input_0.quantizer.scale is not None
assert q_input_0.quantizer.zero_point is not None
assert q_input_1.quantizer.scale is not None
assert q_input_1.quantizer.zero_point is not None
# De-quantize with input params and re-quantize with output parameters
# This will use TLUs over each element of the two inputs
# We do the de-quantization directly, instead of q_inputs[0].dequant(),
# So that we do not lose precision in the computation
rescale_q0 = numpy.rint(
q_input_0.quantizer.scale
/ self.output_quant_params.scale
* (q_input_0.qvalues + (-q_input_0.quantizer.zero_point))
).astype(numpy.int64)
rescale_q1 = numpy.rint(
q_input_1.quantizer.scale
/ self.output_quant_params.scale
* (q_input_1.qvalues + (-q_input_1.quantizer.zero_point))
).astype(numpy.int64)
# The sum of quantized encrypted integer values
# This sum has << max(in_bits0, in_bits1) + 1 >> bits
# Moreover, the zero-point will be sum of input zero-points
assert self.b_sign in [-1, 1]
# This lines will be simplified into
# sum_q = rescale_q0 + self.b_sign * rescale_q1
# when zama-ai/concrete-numpy-internal#1749 is done
if self.b_sign == 1:
sum_q = rescale_q0 + rescale_q1
elif self.b_sign == -1:
sum_q = rescale_q0 - rescale_q1
# But we would like the output to have n_bits, so we de-quantize
dequant_sum = self.output_quant_params.scale * sum_q
# Return the raw float values without re-quantizing them to the new scale, as any
# following Gemm/Add/Conv will quantize them with _prepare_inputs_with_constants(...)
return QuantizedArray(
self.n_bits,
dequant_sum,
value_is_float=True,
options=self._get_output_quant_opts(),
stats=self.output_quant_stats,
params=self.output_quant_params,
)
def can_fuse(self) -> bool:
"""Determine if this op can be fused.
Add operation can be computed in float and fused if it operates over inputs produced
by a single integer tensor. For example the expression x + x * 1.75, where x is
an encrypted tensor, can be computed with a single TLU.
Returns:
bool: Whether the number of integer input tensors allows computing this op as a TLU
"""
return len(self._int_input_names) == 1
class QuantizedTanh(QuantizedOp):
"""Quantized Tanh op."""
_impl_for_op_named: str = "Tanh"
class QuantizedSoftplus(QuantizedOp):
"""Quantized Softplus op."""
_impl_for_op_named: str = "Softplus"
class QuantizedExp(QuantizedOp):
"""Quantized Exp op."""
_impl_for_op_named: str = "Exp"
class QuantizedLog(QuantizedOp):
"""Quantized Log op."""
_impl_for_op_named: str = "Log"
class QuantizedAbs(QuantizedOp):
"""Quantized Abs op."""
_impl_for_op_named: str = "Abs"
class QuantizedIdentity(QuantizedOp):
"""Quantized Identity op."""
_impl_for_op_named: str = "Identity"
def q_impl(
self,
*q_inputs: ONNXOpInputOutputType,
**attrs,
) -> ONNXOpInputOutputType:
assert_true(len(q_inputs) == 1, "Identity does not work with multiple QuantizedArray")
# This op takes only encrypted inputs in the form of QuantizedArray
assert isinstance(q_inputs[0], QuantizedArray)
self.output_quant_params = q_inputs[0].quantizer.quant_params
return super().q_impl(*q_inputs, **attrs)
class QuantizedReshape(QuantizedOp):
"""Quantized Reshape op."""
_impl_for_op_named: str = "Reshape"
quantize_inputs_with_model_outputs_precision = True
def q_impl(
self,
*q_inputs: ONNXOpInputOutputType,
**attrs,
) -> ONNXOpInputOutputType:
"""Reshape the input integer encrypted tensor.
Args:
q_inputs: an encrypted integer tensor at index 0 and one constant shape at index 1
attrs: additional optional reshape options
Returns:
result (QuantizedArray): reshaped encrypted integer tensor
"""
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=True
)
# This op takes only encrypted inputs in the form of QuantizedArray
assert isinstance(q_inputs[0], QuantizedArray)
newshape = prepared_inputs[1]
assert_true(numpy.issubdtype(newshape.dtype, numpy.integer))
# Return a new quantized array with the same quantization parameters
return QuantizedArray(
q_inputs[0].quantizer.n_bits,
self.call_impl(prepared_inputs[0].qvalues, newshape, **attrs),
value_is_float=False,
options=prepared_inputs[0].quantizer.quant_options,
stats=prepared_inputs[0].quantizer.quant_stats,
params=prepared_inputs[0].quantizer.quant_params,
)
def can_fuse(self) -> bool:
"""Determine if this op can be fused.
Max Pooling operation can not be fused since it must be performed over integer tensors and
it combines different elements of the input tensors.
Returns:
bool: False, this operation can not be fused as it adds different encrypted integers
"""
return False
class QuantizedConv(QuantizedMixingOp):
"""Quantized Conv op."""
_impl_for_op_named: str = "Conv"
def __init__(
self,
n_bits_output: int,
op_instance_name: str,
int_input_names: Set[str] = None,
constant_inputs: Optional[Union[Dict[str, Any], Dict[int, Any]]] = None,
input_quant_opts: QuantizationOptions = None,
**attrs,
) -> None:
"""Construct the quantized convolution operator and retrieve parameters.
Args:
n_bits_output: number of bits for the quantization of the outputs of this operator
op_instance_name (str): The name that should be assigned to this operation, used
to retrieve it later or get debugging information about this op (bit-width, value
range, integer intermediary values, op-specific error messages). Usually this name
is the same as the ONNX operation name for which this operation is constructed.
int_input_names: names of integer tensors that are taken as input for this operation
constant_inputs: the weights and activations
input_quant_opts: options for the input quantizer
attrs: convolution options
dilations (Tuple[int]): dilation of the kernel. Default to 1 on all dimensions.
group (int): number of convolution groups. Default to 1.
kernel_shape (Tuple[int]): shape of the kernel. Should have 2 elements for 2d conv
pads (Tuple[int]): padding in ONNX format (begin, end) on each axis
strides (Tuple[int]): stride of the convolution on each axis
"""
super().__init__(
n_bits_output,
op_instance_name,
int_input_names,
constant_inputs,
input_quant_opts,
**attrs,
)
# Get the ONNX parameters
self.group = attrs.get("group", 1)
self.kernel_shape = attrs.get("kernel_shape", None)
self.pads = attrs.get("pads", tuple([0] * 2 * (len(self.kernel_shape) - 2)))
self.dilations = attrs.get("dilations", tuple([1] * len(self.kernel_shape)))
self.strides = attrs.get("strides", tuple([1] * len(self.kernel_shape)))
# Validate the parameters
assert_true(
len(self.kernel_shape) == 2,
"The convolution operator currently supports only 2d",
)
assert_true(
len(self.kernel_shape) == len(self.strides),
"The convolution operator requires the number of strides to "
"be the same as the number of kernel dimensions",
)
assert_true(
bool(numpy.all(numpy.asarray(self.dilations) == 1)),
"The convolution operator in Concrete does not suppport dilation",
)
assert_true(
len(self.pads) == 2 * len(self.kernel_shape),
"The convolution operator in Concrete ML requires padding to be specified as "
" (pad_left_dim1, pad_right_dim1, pad_left_dim2, pad_right_dim2, ...), following ONNX"
" standard",
)
def q_impl(
self,
*q_inputs: ONNXOpInputOutputType,
calibrate_rounding: bool = False,
**attrs,
) -> ONNXOpInputOutputType:
"""Compute the quantized convolution between two quantized tensors.
Allows an optional quantized bias.
Args:
q_inputs: input tuple, contains
x (numpy.ndarray): input data. Shape is N x C x H x W for 2d
w (numpy.ndarray): weights tensor. Shape is (O x I x Kh x Kw) for 2d
b (numpy.ndarray, Optional): bias tensor, Shape is (O,)
calibrate_rounding (bool): Whether to calibrate rounding
attrs: convolution options handled in constructor
Returns:
res (QuantizedArray): result of the quantized integer convolution
"""
# For mypy
assert self.output_quant_params is not None
assert self.output_quant_params.scale is not None
assert self.output_quant_params.zero_point is not None
# Retrieve the quantized inputs
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=True
)
q_input: QuantizedArray = prepared_inputs[0]
q_weights: QuantizedArray = prepared_inputs[1]
q_bias: Optional[numpy.ndarray] = None if len(prepared_inputs) == 2 else prepared_inputs[2]
in_channels = q_input.values.shape[1]
weight_channels = q_weights.values.shape[1]
assert_true(
weight_channels == in_channels / self.group,
f"Expected number of channels in weight to be {in_channels / self.group} "
f"(C / group). Got {weight_channels}.",
)
out_channels = q_weights.values.shape[0]
assert_true(
out_channels % self.group == 0,
f"Expected number of output channels O ({out_channels}) to be a multiple of "
f"group ({self.group}).",
)
# Prepare a constant tensor to compute the sum of the inputs
q_weights_1 = numpy.ones_like(q_weights.qvalues)
assert q_weights.quantizer.scale is not None
assert q_weights.quantizer.zero_point is not None
assert q_input.quantizer.scale is not None
assert q_input.quantizer.zero_point is not None
# Can only pad with scalar zero-points, but zero-points can be float in special cases
# for output layers
_check_op_input_zero_point(q_input.quantizer.zero_point, self.op_instance_name)
pad_value = int(q_input.quantizer.zero_point)
q_input_pad = numpy_onnx_pad(q_input.qvalues, self.pads, pad_value, True)
# We follow the Quantized Gemm implementation
# which in turn follows Eq.7 in https://arxiv.org/abs/1712.05877
# to split the core computation from the zero points and scales.
# Compute the first encrypted term that convolves weights and inputs
# Force padding to 0 as padding needs to use a custom padding initializer
# and is thus manually performed in the code above
fake_pads = [0] * len(self.pads)
with tag(self.op_instance_name + ".conv"):
conv_wx = cnp_conv(
q_input_pad,
q_weights.qvalues,
bias=None,
pads=fake_pads,
strides=self.strides,
dilations=self.dilations,
group=self.group,
)
# The total number of elements that are convolved by the application of a single kernel
n_weights = numpy.prod(q_weights.qvalues.shape[1:])
# If the weights have symmetric quantization, their zero point will be 0
# The following check avoids the computation of the sum of the inputs, which may have
# large bit-width, in the case where it would be multiplied by zero
if q_weights.quantizer.zero_point != 0:
# Compute the sum of the inputs (second encrypted term)
assert_true(
isinstance(q_weights.quantizer.zero_point, (int, numpy.int_)),
f"Zero point of weights tensor in {self.op_type} "
f"op {self.op_instance_name} must be integer",
)
with tag(self.op_instance_name + ".conv_inputsum"):
zw_conv_1x = -q_weights.quantizer.zero_point * cnp_conv(
q_input_pad,
q_weights_1,
bias=None,
pads=[0, 0, 0, 0],
strides=self.strides,
dilations=self.dilations,
group=self.group,
)
with tag(self.op_instance_name + ".conv_add_inputsum"):
numpy_q_out = conv_wx + zw_conv_1x
else:
numpy_q_out = conv_wx
if self.debug_value_tracker is not None:
# pylint: disable-next=unsubscriptable-object
self.debug_value_tracker[self.op_instance_name]["output"] = numpy_q_out
# Compute the third term, the sum of the weights which is a constant
sum_weights = q_input.quantizer.zero_point * numpy.sum(
q_weights.qvalues, axis=(1, 2, 3), keepdims=True
).transpose(1, 0, 2, 3)
# Compute the forth term which is a constant
final_term = n_weights * q_input.quantizer.zero_point * q_weights.quantizer.zero_point
# Compute the rescaling factor that de-quantizes the input
# This is going to be compiled with a PBS (along with the following activation function)
# Note that we don't re-quantize the output of the conv, this will be done by
# any Gemm/Add/Conv layers that follow
m_matmul = q_input.quantizer.scale * q_weights.quantizer.scale
# If this operation's result are network outputs, return
# directly the integer values and an appropriate quantization parameters that
# allow direct in-the-clear de-quantization, including the bias
if self.produces_graph_output:
# Note that to use the bias, we need to rescale it to the output scale
# For Eq. 7 in https://arxiv.org/abs/1712.05877, we can write:
# S_out(q_out - zp_out) = S_x * S_w (multisum + bias / (S_x * S_w))
# where multisum is the dot product of quantized inputs and quantized weights
# Then we identify terms:
# S_out = S_x * S_w
# q_out = multisum terms involving inputs
# zp_out = -(multisum terms involving weights + bias / (S_x * S_w))
out_zp: Union[int, numpy.ndarray] = sum_weights - final_term
if q_bias is not None:
# Reshape the biases to broadcast them to each channel
out_zp = out_zp - q_bias.reshape((1, -1, 1, 1)) / m_matmul
# We identify terms in the above equation to determine what
# the scale/zero-point of the in-the-clear quantizer should be
# to properly de-quantize numpy_q_out
return self.make_output_quant_parameters(numpy_q_out, m_matmul, out_zp)
with tag(self.op_instance_name + ".conv_rounding"):
# Apply Concrete rounding (if relevant)
numpy_q_out = self.cnp_round(numpy_q_out, calibrate_rounding)
# Now compute the whole sum (sum of the four terms)
numpy_q_out = numpy_q_out.astype(numpy.float64) + final_term - sum_weights
# Rescale from scale=scale_inputs x scale_outputs to output scale
numpy_q_out = m_matmul * numpy_q_out
if q_bias is not None:
# The bias addition is handled in float and will be fused into a TLU
# Reshape the biases to broadcast them to each channel
numpy_q_out = numpy_q_out + q_bias.reshape((1, -1, 1, 1)) # bias_part
# And return as a QuantizedArray initialized from the float data, keeping
# track of the quantization parameters
return QuantizedArray(
self.n_bits,
numpy_q_out,
value_is_float=True,
options=self._get_output_quant_opts(),
stats=self.output_quant_stats,
params=self.output_quant_params,
)
class QuantizedAvgPool(QuantizedMixingOp):
"""Quantized Average Pooling op."""
_impl_for_op_named: str = "AveragePool"
# Since this op takes a single input, we can set int_input_names to a single default id
def __init__(
self,
n_bits_output: int,
op_instance_name: str,
int_input_names: Set[str] = None,
constant_inputs: Optional[Union[Dict[str, Any], Dict[int, Any]]] = None,
input_quant_opts: QuantizationOptions = None,
**attrs,
) -> None:
super().__init__(
n_bits_output,
op_instance_name,
int_input_names,
constant_inputs,
input_quant_opts,
**attrs,
)
# Get the ONNX parameters
self.ceil_mode = attrs.get("ceil_mode", None)
self.kernel_shape = attrs.get("kernel_shape", None)
self.pads = attrs.get("pads", tuple([0] * 2 * (len(self.kernel_shape) - 2)))
self.dilations = attrs.get("dilations", tuple([1] * len(self.kernel_shape)))
self.strides = attrs.get("strides", tuple([1] * len(self.kernel_shape)))
# Validate the parameters
assert_true(
len(self.kernel_shape) == 2,
"The Average Pool operator currently supports only 2d",
)
assert_true(
len(self.kernel_shape) == len(self.strides),
"The Average Pool operator requires the number of strides to "
"be the same as the number of kernel dimensions",
)
assert_true(
len(self.pads) == 2 * len(self.kernel_shape),
"The Average Pool operator in Concrete ML requires padding to be specified as "
" (pad_left_dim1, pad_right_dim1, pad_left_dim2, pad_right_dim2, ...), following ONNX"
" standard",
)
self.kernel: Union[numpy.ndarray, None] = None
self.norm_const: Union[float, None] = None
def q_impl(
self,
*q_inputs: ONNXOpInputOutputType,
calibrate_rounding: bool = False,
**attrs,
) -> ONNXOpInputOutputType:
# Retrieve the quantized inputs
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=True
)
q_input: QuantizedArray = prepared_inputs[0]
n_in_channels = q_input.qvalues.shape[1]
kernel = numpy.zeros(
(n_in_channels, n_in_channels, self.kernel_shape[0], self.kernel_shape[1]),
dtype=numpy.int64,
)
for i in range(n_in_channels):
kernel[i, i, ::] = 1
norm_const = 1.0 / onnx_avgpool_compute_norm_const(
q_input.qvalues.shape,
self.kernel_shape,
self.pads,
self.strides,
self.ceil_mode,
)
# for mypy: The Quantized ops can only run on QuantizedArray that have quantization
# parameters (i.e., were fully constructed). This should always be the case, except
# during the UniformQuantizer initialization when the zero_point can exist as None
assert q_input.quantizer.zero_point is not None
# Compute padding with floor and apply it to the input, pad with the input zero-point
pool_pads = compute_onnx_pool_padding(
q_input.qvalues.shape, self.kernel_shape, self.pads, self.strides, 0
)
# Can only pad with scalar zero-points, but zero-points can be float in special cases
# for output layers
_check_op_input_zero_point(q_input.quantizer.zero_point, self.op_instance_name)
pad_value = int(q_input.quantizer.zero_point)
q_input_pad = numpy_onnx_pad(q_input.qvalues, pool_pads, pad_value, int_only=True)
if self.ceil_mode == 1:
# Padding for TensorFlow style
# Compute padding with ceil and apply it to the input, pad with zeros, the zeros
# will be ignored in the computation
pool_pads_ceil = compute_onnx_pool_padding(
q_input.qvalues.shape, self.kernel_shape, self.pads, self.strides, 1
)
# Can only pad with scalar zero-points, but zero-points can be float in special cases
# for output layers
q_input_pad_ceil = numpy_onnx_pad(q_input.qvalues, pool_pads_ceil, 0, True)
# Copy the PyTorch style padded input to the larger 0 padded tensor
q_input_pad_ceil[:, :, 0 : q_input_pad.shape[2], 0 : q_input_pad.shape[3]] = q_input_pad
q_input_pad = q_input_pad_ceil
# Remark that here, we are _not_ using Concrete pad, since it would pad with
# 0's while we want to pad with zero-point's. So, instead, he have done the padding
# on our side, with q_input_pad
fake_pads = [0] * len(self.pads)
with tag(self.op_instance_name + ".avgpool"):
sum_result = cnp_conv(q_input_pad, kernel, None, fake_pads, self.strides)
with tag(self.op_instance_name + ".avgpool_rounding"):
# Apply Concrete rounding (if relevant)
sum_result = self.cnp_round(sum_result, calibrate_rounding)
if self.debug_value_tracker is not None:
# pylint: disable-next=unsubscriptable-object
self.debug_value_tracker[self.op_instance_name]["output"] = sum_result
result = (
sum_result.astype(numpy.float64) * norm_const - q_input.quantizer.zero_point
) * q_input.quantizer.scale
return QuantizedArray(
self.n_bits,
result,
value_is_float=True,
options=self._get_output_quant_opts(),
stats=self.output_quant_stats,
params=self.output_quant_params,
)
class QuantizedMaxPool(QuantizedOp):
"""Quantized Max Pooling op."""
_impl_for_op_named: str = "MaxPool"
# Since this op takes a single input, we can set int_input_names to a single default id
def __init__(
self,
n_bits_output: int,
op_instance_name: str,
int_input_names: Set[str] = None,
constant_inputs: Optional[Union[Dict[str, Any], Dict[int, Any]]] = None,
input_quant_opts: QuantizationOptions = None,
**attrs,
) -> None:
super().__init__(
n_bits_output,
op_instance_name,
int_input_names,
constant_inputs,
input_quant_opts,
**attrs,
)
# Get the ONNX parameters
self.auto_pad = attrs.get("auto_pad", "NOTSET")
self.ceil_mode = attrs.get("ceil_mode", 0)
self.kernel_shape = attrs.get("kernel_shape", None)
self.storage_order = attrs.get("storage_order", 0)
self.pads = attrs.get("pads", tuple([0] * 2 * (len(self.kernel_shape) - 2)))
self.dilations = attrs.get("dilations", tuple([1] * len(self.kernel_shape)))
self.strides = attrs.get("strides", tuple([1] * len(self.kernel_shape)))
# Validate the parameters
assert_true(self.ceil_mode == 0, "Only ceil_mode = 0 is supported by Concrete for now")
# Validate the parameters
assert_true(
len(self.kernel_shape) == 2,
"The Max Pool operator currently supports only 2d",
)
assert_true(
len(self.kernel_shape) == len(self.strides),
"The Max Pool operator requires the number of strides to "
"be the same as the number of kernel dimensions",
)
assert_true(
len(self.pads) == 2 * len(self.kernel_shape),
"The Max Pool operator in Concrete ML requires padding to be specified as "
" (pad_left_dim1, pad_right_dim1, pad_left_dim2, pad_right_dim2, ...), following ONNX"
" standard",
)
def q_impl(
self,
*q_inputs: ONNXOpInputOutputType,
**attrs,
) -> ONNXOpInputOutputType:
# Retrieve the quantized inputs
prepared_inputs = self._prepare_inputs_with_constants(
*q_inputs, calibrate=False, quantize_actual_values=True
)
q_input: QuantizedArray = prepared_inputs[0]
# for mypy: The Quantized ops can only run on QuantizedArray that have quantization
# parameters (i.e., were fully constructed). This should always be the case, except
# during the UniformQuantizer initialization when the zero_point can exist as None
assert q_input.quantizer.zero_point is not None
assert_true(
self.ceil_mode == 0,
"Only ceil_mode = 0 is supported by Concrete for now",
)
# Simple padding for PyTorch style
pool_pads = compute_onnx_pool_padding(
q_input.qvalues.shape,