-
Notifications
You must be signed in to change notification settings - Fork 121
/
quantized_ops.py
2697 lines (2114 loc) · 97.9 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 fhe_conv
from concrete.fhe import maxpool as fhe_maxpool
from concrete.fhe import tag, univariate, zeros
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,
UniformQuantizer,
)
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: Optional[Set[str]] = None,
constant_inputs: Optional[Union[Dict[str, Any], Dict[int, Any]]] = None,
input_quant_opts: Optional[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}.",
)
# pylint: disable-next=too-many-statements,too-many-locals
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 self.constant_inputs is empty this is an encrypted gemm
# There might be caveats here
# (for example when one of the input is passed in clear with encrypted statuses.)
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/4132
is_encrypted_gemm = isinstance(self.constant_inputs, dict) and not self.constant_inputs
# 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_input1 = prepared_inputs[0]
assert isinstance(q_input1, QuantizedArray)
q_input2 = prepared_inputs[1]
assert isinstance(q_input2, QuantizedArray)
# In the operation Y = alpha * A' * B' + beta * C, q_bias is used for
# generalised matrix multiplication. q_bias is set to None for standard
# matrix multiplication (beta == 0 or only two inputs)
q_bias = None if len(prepared_inputs) == 2 or beta == 0 else prepared_inputs[2]
assert isinstance(q_bias, (type(None), QuantizedArray))
# 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_inputs1 = attrs.get("transA", False)
transpose_inputs2 = attrs.get("transB", False)
with tag(self.op_instance_name + ".input"):
input1_q_values = (
numpy.transpose(q_input1.qvalues) if transpose_inputs1 else q_input1.qvalues
)
input2_q_values = (
numpy.transpose(q_input2.qvalues) if transpose_inputs2 else q_input2.qvalues
)
assert_true(
input2_q_values.ndim in {2, 3},
f"Unsupported dimension for the weight input of the gemm: {input2_q_values.ndim}",
)
# 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_input2.quantizer.scale is not None
assert q_input2.quantizer.zero_point is not None
assert q_input1.quantizer.scale is not None
assert q_input1.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 = input2_q_values.shape[-2]
# Remove the manual matrix multiplication when we can handle input precision with rounding
# FIXME: https://github.com/zama-ai/concrete-internal/issues/512
def enc_mul(x, y):
r"""Encrypted multiplication of two input arrays.
This function computes the encrypted multiplication of two numpy arrays.
It uses the following equality:
\[
(x + y)^2 - (x - y)^2 = 4xy
\]
This equation simplifies to the standard multiplication operation.
In TFHE, this allows to do encrypted multiplication with 2 PBS.
Args:
x (numpy.ndarray): The first input numpy array.
y (numpy.ndarray): The second input numpy array.
Returns:
numpy.ndarray: The result of the encrypted multiplication.
"""
with tag("pbs_multiplication"):
# Compute sum and difference of x and y
add = x + y
sub = x - y
# Apply Concrete rounding to the addition and substraction
with tag(self.op_instance_name + ".pbs_matmul_rounding_add"):
add = self.cnp_round(add, calibrate_rounding, rounding_operation_id="add")
with tag(self.op_instance_name + ".pbs_matmul_rounding_sub"):
sub = self.cnp_round(sub, calibrate_rounding, rounding_operation_id="sub")
# Square the rounded sums and differences, and divide by 4
add_pow = (add.astype(numpy.float64)) ** 2
sub_pow = (sub.astype(numpy.float64)) ** 2
add_pow_divide = (add_pow / 4.0).astype(numpy.int64)
sub_pow_divide = (sub_pow / 4.0).astype(numpy.int64)
# Return the result of the multiplication
return add_pow_divide - sub_pow_divide
# Remove the manual matrix multiplication when we can handle input precision with rounding
# FIXME: https://github.com/zama-ai/concrete-internal/issues/512
def matmul(a, b):
"""Matrix multiplication of two input arrays, supporting 2D or 3D.
This function performs matrix multiplication on either 2D or 3D numpy arrays.
It supports batch processing, where either or both inputs can be a batch
(3D array), and handles the reshaping and summation operations required
for matrix multiplication.
Args:
a (numpy.ndarray): The first input array, can be 2D or 3D.
b (numpy.ndarray): The second input array, can be 2D or 3D.
Returns:
numpy.ndarray: The result of the matrix multiplication.
"""
with tag("encrypted_matmul"):
# Determine the dimensions of inputs and handle 3D (batch) inputs
a_3d = a.ndim == 3
b_3d = b.ndim == 3
# Extract shapes and batch sizes
if a_3d:
batch_a, m, n = a.shape
else:
m, n = a.shape
batch_a = 1
if b_3d:
batch_b, n_b, p = b.shape
else:
n_b, p = b.shape
batch_b = 1
# Check for dimension compatibility
assert_true(n == n_b, "Inner dimensions do not match for matrix multiplication")
assert (
batch_a == batch_b or batch_a == 1 or batch_b == 1
), "Batch sizes must be equal or one must be 1"
# Determine the batch size for the operation
batch_size = batch_a
c = zeros(shape=(batch_size, m, p))
# Perform batched matrix multiplication
for i in range(batch_size):
# Slice the batch or use the whole array if not batched
a_slice = a[i] if a_3d else a
b_slice = b[i] if b_3d else b
# Reshape for element-wise multiplication
a_reshaped = a_slice.reshape((m, n, 1))
b_reshaped = b_slice.reshape((1, n, p))
# Perform encrypted multiplication and sum along the axis
enc_mul_result = enc_mul(a_reshaped, b_reshaped)
c[i] = numpy.sum(enc_mul_result, axis=1)
# Squeeze the first dimension if both inputs were 2D
if not a_3d and not b_3d:
c = numpy.squeeze(c, axis=0)
# Return the result of matrix multiplication
return c
# Remove the manual matrix multiplication when we can handle input precision with rounding
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/4127
@univariate
def copy_function(x):
return x
# Copy trick explanation:
# The copy_function is used to preserve the original precision of input values across
# various operations. Operations like addition, subtraction, sum, and matmul can
# unintentionally increase precision ('precision raising').
#
# Precision raising in one of these operations can inadvertently affect the precision of
# the same value in other branches of the code. By creating copies of the input values,
# any precision changes are limited to these copies, not the original values.
#
# This strategy is particularly important to make sure PBS in all branches are done on the
# pre-defined precision. The use of the copy is conditional, applied only when needed
# to optimize performance.
input1_q_values_copy = (
copy_function(input1_q_values) if is_encrypted_gemm else input1_q_values
)
input2_q_values_copy = (
copy_function(input2_q_values) if is_encrypted_gemm else input2_q_values
)
# Core matmul operation in full integers with a shape change (INTEGERS)
with tag(self.op_instance_name + ".matmul"):
# We implement our own encrypted matmul to be able to round before PBS
if is_encrypted_gemm:
matmul = matmul(input1_q_values_copy, input2_q_values_copy)
# Otherwise we let concrete do it
else:
matmul = input1_q_values_copy @ input2_q_values_copy
input1_q_values_copy = (
copy_function(input1_q_values) if is_encrypted_gemm else input1_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_input2.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_input2.quantizer.zero_point * numpy.sum(
input1_q_values_copy, 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
input2_q_values_copy = (
copy_function(input2_q_values) if is_encrypted_gemm else input2_q_values
)
with tag(self.op_instance_name + ".sum_weights_times_zero_point"):
# sum_weights is a constant
sum_weights = q_input1.quantizer.zero_point * numpy.sum(
input2_q_values_copy, axis=-2, keepdims=True
)
final_term = p * q_input1.quantizer.zero_point * q_input2.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_input1.quantizer.scale * q_input2.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 and not is_encrypted_gemm:
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
bias_out = q_bias.values if isinstance(q_bias, QuantizedArray) else q_bias
out_zp = out_zp + bias_out / (-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)
# Integer biases are only supported for Brevitas QAT which sets is_precomputed_qat to true
# These biases are produced by QuantizedBrevitasQuant ops
if q_bias is not None and q_bias.quantizer.is_precomputed_qat:
# Make sure the scale was correctly matching during training
# The bias scale should be the same scale as the one of the weights * inputs
assert q_bias.quantizer.scale is not None
assert numpy.isclose(q_bias.quantizer.scale, m_matmul)
numpy_q_out += q_bias.qvalues
# If weights are not encrypted then we can round as the next
# line is going to be done in a PBS
if not is_encrypted_gemm:
with tag(self.op_instance_name + ".matmul_rounding"):
# Apply Concrete rounding (if relevant)
numpy_q_out = self.cnp_round(
numpy_q_out, calibrate_rounding, rounding_operation_id="matmul"
)
# Force a PBS with astype float64
numpy_q_out = numpy_q_out.astype(numpy.float64)
# Quantization scales and zero points
# This is done in a PBS if is_encrypted_gemm == False
# (along with the following activation function)
# Otherwise it is done in FHE
numpy_q_out = numpy_q_out + final_term - sum_weights
if is_encrypted_gemm:
with tag(self.op_instance_name + ".matmul_rounding"):
# Apply Concrete rounding (if relevant)
numpy_q_out = self.cnp_round(
numpy_q_out, calibrate_rounding, rounding_operation_id="matmul"
)
numpy_q_out = m_matmul * numpy_q_out
if q_bias is not None and not q_bias.quantizer.is_precomputed_qat:
# The bias is handled as a float and will be fused
numpy_q_out = numpy_q_out + q_bias.values
# 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(QuantizedMixingOp):
"""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
# Dequantize
input_0 = q_input_0.dequant()
input_1 = q_input_1.dequant()
# If this operator is the last one in the graph,
# we rescale using the smallest scale to keep all information
if self.produces_graph_output:
common_scale = min(q_input_0.quantizer.scale, q_input_1.quantizer.scale)
# Otherwise we use the output op quantization scale
else:
common_scale = self.output_quant_params.scale
common_zero_point = 0
offset = 0
output_quant_params = UniformQuantizationParameters(
scale=common_scale,
zero_point=common_zero_point,
offset=offset,
)
quantizer = UniformQuantizer(params=output_quant_params, no_clipping=True)
# Re-quantize using the common quantization paramaters
q_input_0_rescaled = quantizer.quant(input_0)
q_input_1_rescaled = quantizer.quant(input_1)
# 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]
sum_q = q_input_0_rescaled + self.b_sign * q_input_1_rescaled
if self.produces_graph_output:
return self.make_output_quant_parameters(sum_q, common_scale, common_zero_point)
# But we would like the output to have n_bits, so we de-quantize
dequant_sum = quantizer.dequant(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.
Reshape operation can not be fused since it must be performed over integer tensors.
Returns:
bool: False, this operation can not be fused.
"""
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) in (1, 2),
"The convolution operator currently only supports 1d or 2d. "
f"Got {len(self.kernel_shape)}-d",
)
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 support 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",
)
# pylint: disable-next=too-many-statements, too-many-locals
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[QuantizedArray] = 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}).",
)
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)
is_conv1d = len(self.kernel_shape) == 1
q_weights_values = q_weights.qvalues
kernel_shape = self.kernel_shape
strides = self.strides
dilations = self.dilations
# Workaround for handling torch's Conv1d operator until it is supported by Concrete Python
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/4117
if is_conv1d:
q_input_pad = numpy.expand_dims(q_input_pad, axis=-2)
q_weights_values = numpy.expand_dims(q_weights_values, axis=-2)
kernel_shape = (1, kernel_shape[0])
strides = (1, strides[0])
dilations = (1, dilations[0])
# Prepare a constant tensor to compute the sum of the inputs
q_weights_1 = numpy.ones_like(q_weights_values)
# 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, 0] * len(kernel_shape)
with tag(self.op_instance_name + ".conv"):
conv_wx = fhe_conv(
q_input_pad,
q_weights_values,
bias=None,
pads=fake_pads,
kernel_shape=kernel_shape,
strides=strides,
dilations=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_values.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 * fhe_conv(
q_input_pad,
q_weights_1,
bias=None,
pads=fake_pads,
kernel_shape=kernel_shape,
strides=strides,
dilations=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
# Workaround for handling torch's Conv1d operator until it is supported by Concrete Python
# FIXME: https://github.com/zama-ai/concrete-ml-internal/issues/4117
if is_conv1d:
numpy_q_out = numpy.squeeze(numpy_q_out, axis=-2)
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
weight_sum_axes = (1, 2) if is_conv1d else (1, 2, 3)
weight_transpose_axes = (1, 0, 2) if is_conv1d else (1, 0, 2, 3)
# 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=weight_sum_axes, keepdims=True
).transpose(*weight_transpose_axes)
# 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
bias_shape = (1, -1, 1) if is_conv1d else (1, -1, 1, 1)
# 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.values.reshape(bias_shape) / 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)
if q_bias is not None and q_bias.quantizer.is_precomputed_qat:
# Make sure the scale was correctly matching during training
# The bias scale should be the same scale as the one of the weights * inputs
assert q_bias.quantizer.scale is not None
assert numpy.isclose(q_bias.quantizer.scale, m_matmul)
numpy_q_out += q_bias.qvalues.reshape(bias_shape)
with tag(self.op_instance_name + ".conv_rounding"):
# Apply Concrete rounding (if relevant)
numpy_q_out = self.cnp_round(
numpy_q_out, calibrate_rounding, rounding_operation_id="matmul"
)
# 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