-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
tflite.py
4222 lines (3546 loc) · 173 KB
/
tflite.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=invalid-name, unused-argument, too-many-lines
# pylint: disable=import-outside-toplevel, use-list-literal
"""Tensorflow lite frontend."""
import itertools
import math
import numpy as np
import tvm
from tvm import relay
from tvm.ir import IRModule
from tvm.runtime.name_transforms import sanitize_name
from ... import nd as _nd
from .. import analysis
from .. import expr as _expr
from .. import function as _function
from .. import op as _op
from .. import qnn as _qnn
from .common import ExprTable
from .common import fold_constant as _fold_constant
from .common import infer_shape as _infer_shape
from .common import infer_type as _infer_type
from .common import lstm_cell, to_int_list, shape_of, try_infer_value
from .common import set_span
from .tflite_flexbuffer import FlexBufferDecoder
__all__ = ["from_tflite"]
class TensorWrapper(object):
"""Tensor wrapper for TFLite Tensor"""
def __init__(self, tensor_idx, tensor, buffer, qnn_params=None):
self.tensor_idx = tensor_idx
self.tensor = tensor
self.buffer = buffer
self.qnn_params = qnn_params
class OperatorConverter(object):
"""Operator Converted for converting TFLite ops to Relay ops"""
def __init__(self, model, subgraph, exp_tab):
try:
from tflite.ActivationFunctionType import ActivationFunctionType
from tflite.BuiltinOperator import BuiltinOperator
from tflite.BuiltinOptions import BuiltinOptions
except ImportError:
raise ImportError("The tflite package must be installed")
self.model = model
self.subgraph = subgraph
self.exp_tab = exp_tab
self.builtin_op_code = build_str_map(BuiltinOperator())
self.activation_fn_type = build_str_map(ActivationFunctionType())
self.builtin_options = build_str_map(BuiltinOptions())
self.prefetched_nodes = {}
self.allow_custom_ops = False
# Add more operators
self.convert_map = {
"ABS": self.convert_abs,
"ADD": self.convert_add,
"ADD_N": self.convert_add_n,
"ARG_MAX": self.convert_arg_max,
"ARG_MIN": self.convert_arg_min,
"AVERAGE_POOL_2D": self.convert_average_pool2d,
"BATCH_TO_SPACE_ND": self.convert_batch_to_space_nd,
"BATCH_MATMUL": self.convert_batch_matmul,
"CAST": self.convert_cast,
"CEIL": self.convert_ceil,
"CONCATENATION": self.convert_concatenation,
"CONV_2D": self.convert_conv2d,
"COS": self.convert_cos,
"DENSIFY": self.convert_densify,
"DEPTH_TO_SPACE": self.convert_depth_to_space,
"DEPTHWISE_CONV_2D": self.convert_depthwise_conv2d,
"DEQUANTIZE": self.convert_dequantize,
"DETECTION_POSTPROCESS": self.convert_detection_postprocess,
"DIV": self.convert_div,
"ELU": self.convert_elu,
"EQUAL": self.convert_equal,
"EXP": self.convert_exp,
"EXPAND_DIMS": self.convert_expand_dims,
"FAKE_QUANT": self.convert_fake_quant,
"FILL": self.convert_fill,
"FLOOR_DIV": self.convert_floor_div,
"FLOOR_MOD": self.convert_floor_mod,
"FLOOR": self.convert_floor,
"FULLY_CONNECTED": self.convert_fully_connected,
"GATHER": self.convert_gather,
"GATHER_ND": self.convert_gather_nd,
"GREATER_EQUAL": self.convert_greater_equal,
"GREATER": self.convert_greater,
"HARD_SWISH": self.convert_hard_swish,
"L2_NORMALIZATION": self.convert_l2_normalization,
"L2_POOL_2D": self.convert_l2_pool2d,
"LEAKY_RELU": self.convert_leaky_relu,
"LESS_EQUAL": self.convert_less_equal,
"LESS": self.convert_less,
"LOCAL_RESPONSE_NORMALIZATION": self.convert_lrn,
"LOG": self.convert_log,
"LOG_SOFTMAX": self.convert_log_softmax,
"LOGICAL_AND": self.convert_logical_and,
"LOGICAL_NOT": self.convert_logical_not,
"LOGICAL_OR": self.convert_logical_or,
"LOGISTIC": self.convert_logistic,
"MATRIX_DIAG": self.convert_matrix_diag,
"MATRIX_SET_DIAG": self.convert_matrix_set_diag,
"MAX_POOL_2D": self.convert_max_pool2d,
"MAXIMUM": self.convert_maximum,
"MEAN": self.convert_reduce_mean,
"MINIMUM": self.convert_minimum,
"MIRROR_PAD": self.convert_mirror_pad,
"MUL": self.convert_mul,
"NEG": self.convert_neg,
"NOT_EQUAL": self.convert_not_equal,
"ONE_HOT": self.convert_one_hot,
"PACK": self.convert_pack,
"PAD": self.convert_pad,
"PADV2": self.convert_pad,
"POW": self.convert_pow,
"PRELU": self.convert_prelu,
"RANGE": self.convert_range,
"QUANTIZE": self.convert_quantize,
"REDUCE_ANY": self.convert_reduce_any,
"REDUCE_MAX": self.convert_reduce_max,
"REDUCE_MIN": self.convert_reduce_min,
"REDUCE_PROD": self.convert_reduce_prod,
"RELU": self.convert_relu,
"RELU6": self.convert_relu6,
"RELU_N1_TO_1": self.convert_relu_n1_to_1,
"RESHAPE": self.convert_reshape,
"RESIZE_BILINEAR": self.convert_resize_bilinear,
"RESIZE_NEAREST_NEIGHBOR": self.convert_resize_nearest_neighbor,
"ROUND": self.convert_round,
"RSQRT": self.convert_rsqrt,
"REVERSE_SEQUENCE": self.convert_reverse_sequence,
"REVERSE_V2": self.convert_reverse_v2,
"SELECT": self.convert_select,
"SHAPE": self.convert_shape,
"SIN": self.convert_sin,
"SLICE": self.convert_slice,
"SOFTMAX": self.convert_softmax,
"SPACE_TO_BATCH_ND": self.convert_space_to_batch_nd,
"SPACE_TO_DEPTH": self.convert_space_to_depth,
"SPARSE_TO_DENSE": self.convert_sparse_to_dense,
"SPLIT": self.convert_split,
"SPLIT_V": self.convert_split_v,
"SQRT": self.convert_sqrt,
"SQUARE": self.convert_square,
"SQUARED_DIFFERENCE": self.convert_squared_difference,
"SQUEEZE": self.convert_squeeze,
"STRIDED_SLICE": self.convert_strided_slice,
"SUB": self.convert_sub,
"SUM": self.convert_reduce_sum,
"TAN": self.convert_tan,
"TANH": self.convert_tanh,
"TILE": self.convert_tile,
"TOPK_V2": self.convert_topk_v2,
"TRANSPOSE_CONV": self.convert_transpose_conv,
"TRANSPOSE": self.convert_transpose,
"UNPACK": self.convert_unpack,
"UNIDIRECTIONAL_SEQUENCE_LSTM": self.convert_unidirectional_sequence_lstm,
"WHERE": self.convert_select,
"ZEROS_LIKE": self.convert_zeros_like,
"NON_MAX_SUPPRESSION_V5": self.convert_nms_v5,
}
def check_unsupported_ops(self):
"""Check unsupported TFLite ops in our converter."""
unsupported_ops_set = set()
dynamic_range_ops_set = set()
for op_idx in range(self.subgraph.OperatorsLength()):
op = self.subgraph.Operators(op_idx)
op_code_str = self.get_op_code_str(op)
if op_code_str not in self.convert_map:
unsupported_ops_set.add(op_code_str)
continue
# Trying to exclude "dynamic range quantization" optimized ops as not supported in TVM
qnn_in_cnt = len(
[_.qnn_params for _ in self.get_input_tensors(op)[0:1] if _.qnn_params is not None]
)
qnn_weight_cnt = len(
[_.qnn_params for _ in self.get_input_tensors(op)[1:] if _.qnn_params is not None]
)
qnn_out_cnt = len(
[_.qnn_params for _ in self.get_output_tensors(op) if _.qnn_params is not None]
)
if qnn_in_cnt == 0 and qnn_out_cnt == 0 and qnn_weight_cnt > 0:
dynamic_range_ops_set.add(op_code_str)
raise_msg = ""
if unsupported_ops_set:
ops = str(list(unsupported_ops_set)).strip("[,]")
raise_msg += f"The following operators are not supported in frontend TFLite: {ops}\n"
if dynamic_range_ops_set:
ops = str(list(dynamic_range_ops_set)).strip("[,]")
raise_msg += (
f"The following operators are likely to have dynamic range quantization: {ops}. "
f"If you are running an optimized graph, please turn off dynamic range "
f"quantization or use full integer quantization"
)
if len(raise_msg) > 0:
raise tvm.error.OpNotImplemented(raise_msg)
def unbind(self, data, axis=1):
"""
This is a modified version compared to the one in common.py.
The onnx version takes a relay.Expr.Call, the tflite
version a TensorWrapper. Also this version by default splits
along axis 1 and not axis 0 as the onnx version.
Parameters
----------
data : tvm.relay.frontend.tflite.TensorWrapper
Input tensor
axis : int
Axis along which tensor is split.
Returns
-------
result : List[relay.Expr]
The sequence of computed tensors
"""
shape = to_int_list(self.get_tensor_shape(data))
if axis >= len(shape):
msg = "Please check input dim, it shouldn't be greater than or equal to rank."
raise AttributeError(msg)
selections = shape[axis]
shape.pop(axis)
timestep = 0 # Reshape to make time step as the first dim
shape.insert(timestep, selections)
res_split = _op.split(
_op.reshape(self.get_expr(data.tensor_idx), tuple(shape)), selections, timestep
)
ret = []
for i in range(selections):
ret.append(_op.squeeze(res_split[i], axis=[timestep]))
return _expr.TupleWrapper(_expr.Tuple(ret), selections)
def convert_op_to_relay(self):
"""Convert TFLite ops to relay ops"""
for op_idx in range(self.subgraph.OperatorsLength()):
op = self.subgraph.Operators(op_idx)
op_code_str = self.get_op_code_str(op)
output_tensors = self.get_output_tensors(op)
try:
from tflite.Operator import Operator
except ImportError:
raise ImportError("The tflite package must be installed")
assert isinstance(op, Operator)
ret = self.convert_map[op_code_str](op)
# In case the Op can be prefetched, the output can be optimized out
if ret is None:
continue
output_names = ", ".join(
[get_tensor_name(self.subgraph, tensor.tensor_idx) for tensor in output_tensors]
)
ret = set_span(ret, f"{output_names}")
if len(output_tensors) == 1:
tensor_idx = output_tensors[0].tensor_idx
self.exp_tab.set_expr(get_tensor_name(self.subgraph, tensor_idx), ret)
else:
for idx, output_tensor in enumerate(output_tensors):
self.exp_tab.set_expr(
get_tensor_name(self.subgraph, output_tensor.tensor_idx), ret[idx]
)
def get_op_code_str(self, op):
"""Get TFLite ops string representation"""
try:
from tflite.BuiltinOperator import BuiltinOperator
except ImportError:
raise ImportError("The tflite package must be installed")
op_code_list_idx = op.OpcodeIndex()
op_c = self.model.OperatorCodes(op_code_list_idx)
# In TFlite 2.4.x there was a change where the type of the field that contained
# the builtin code changed from int8 to int32 in the flat buffer representation.
# However, to retain support for old flat buffers that were created, they retained
# the original 8 bit field, but named it "deprecated_builtin_code" in TFLite 2.4.
# This means that the API function BuiltinCode() which originally returned the value
# of the 8 bit field would now look for the value in the new int32 field in the
# schema and DeprecatedBuiltinCode() will look at the old 8 bit field.
# In TFLite 2.4, if the opcode value is less than 127, it can be in either field
# (however, if it is only in the "builtin_code" field, the model is not backward
# compatible), so similarly to TFLite 2.4 reader, we'll pick the higher value of the
# two fields.
# Remember however that this value came into existence only after Tensorflow
# lite 2.4.x and hence encase it in a try -except block.
# Phew !
try:
opc = max(op_c.DeprecatedBuiltinCode(), op_c.BuiltinCode())
except AttributeError:
# In versions before 2.4 the int8 field that holds the builtin code is accessed
# by BuiltinCode() and DeprecatedBuiltinCode() doesn't exist
opc = op_c.BuiltinCode()
op_code_id = opc
try:
op_code_str = self.builtin_op_code[op_code_id]
except KeyError:
raise NotImplementedError(
"TFLite operator with code "
+ str(op_code_id)
+ " is not supported by this version of the fbs schema."
)
if op_code_id == BuiltinOperator.CUSTOM:
# Custom operator
custom_op_code_str = self.model.OperatorCodes(op_code_list_idx).CustomCode()
if self.allow_custom_ops:
return "CUSTOM"
if custom_op_code_str == b"TFLite_Detection_PostProcess":
return "DETECTION_POSTPROCESS"
raise NotImplementedError("Custom operators are currently not supported")
return op_code_str
def get_input_tensors(self, op):
operator_inputs = op.InputsAsNumpy()
return self.get_tensors(operator_inputs)
def get_output_tensors(self, op):
operator_outputs = op.OutputsAsNumpy()
return self.get_tensors(operator_outputs)
def get_tensors(self, tensors_idx_list):
"""Get tensor wrapper list from given TFLite tensor index list"""
return_list = list()
for tensor_idx in tensors_idx_list:
if tensor_idx < 0:
return_list.append(TensorWrapper(tensor_idx, 0, 0))
continue
tensor = self.subgraph.Tensors(tensor_idx)
buffer_idx = tensor.Buffer()
buffer = self.model.Buffers(buffer_idx)
# Check if the tensors are quantized. Parse if yes.
qnn_params = None
tflite_qnn_params = tensor.Quantization()
if tflite_qnn_params is not None:
# TFLite supports both per-tensor and per-axis (aka channel) quantization. For
# per-tensor quantization, scale and zero points are scalar values. For per-axis
# quantization, scale and zero points for the weights are tensors (activations are
# per-tensor quantized). However, the TFLite quantization spec puts restrictions on
# zero points for per-axis quantization. Specifically, the zero point is a tensor
# but all values are 0. More information can be found here -
# https://www.tensorflow.org/lite/performance/quantization_spec
tflite_scale = tflite_qnn_params.ScaleAsNumpy()
tflite_zero_point = tflite_qnn_params.ZeroPointAsNumpy()
is_qnn_params_valid = True
# Handle Per-axis and per-tensor cases
if isinstance(tflite_scale, np.ndarray):
assert isinstance(tflite_zero_point, np.ndarray)
# Tensor - Per-axis quantization
if tflite_scale.size != 1 and tflite_zero_point.size != 1:
scale = tflite_scale
# Ensure that all zero points are zeros
zero_point = tflite_zero_point
if not np.all(zero_point == 0):
raise tvm.error.OpAttributeInvalid(
"TFLite per-axis quantization restricts all zero points to be"
+ " 0, but a non-zero value is observed"
)
zero_point = int(zero_point[0])
# Scalar - Per-tensor quantization
elif tflite_scale.size == 1 and tflite_zero_point.size == 1:
scale = float(tflite_scale[0])
zero_point = int(tflite_zero_point[0])
else:
raise NotImplementedError(
f"Quantized type {type(tflite_scale)} (scale) and "
f"{type(tflite_zero_point)} (zero point) not supported"
)
elif tflite_scale == 0 and tflite_zero_point == 0:
# Handle corner case for ops like quantized reshape whose second operand (shape)
# has zero scale and zero zero point. This is not used.
is_qnn_params_valid = False
else:
raise NotImplementedError(f"Quantized type {type(tflite_scale)} not supported")
# Check that the scale and zero points are valid.
if is_qnn_params_valid:
qnn_params = dict()
qnn_params["scale"] = relay.const(scale, "float32")
qnn_params["zero_point"] = relay.const(zero_point, "int32")
return_list.append(TensorWrapper(tensor_idx, tensor, buffer, qnn_params))
return return_list
def get_tensor_type_as_numpy(self, tensor_wrapper):
"""Returns np.dtype out of TensorType"""
assert isinstance(tensor_wrapper, TensorWrapper)
try:
from tflite.TensorType import TensorType
return {
TensorType.UINT8: np.uint8,
TensorType.INT8: np.int8,
TensorType.INT16: np.int16,
TensorType.FLOAT16: np.float16,
TensorType.FLOAT32: np.float32,
TensorType.INT32: np.int32,
TensorType.INT64: np.int64,
TensorType.BOOL: np.bool_,
}[tensor_wrapper.tensor.Type()]
except ImportError:
raise ImportError("The tflite package must be installed")
except KeyError:
raise NotImplementedError(
f"Tensor type '{tensor_wrapper.tensor.Type()}' currently not supported"
)
# pylint: disable=no-else-return
def get_tensor_value(self, tensor_wrapper, is_sparse=False):
"""Get tensor buffer value from given tensor wrapper"""
assert isinstance(tensor_wrapper, TensorWrapper)
dtype = self.get_tensor_type_as_numpy(tensor_wrapper)
data = tensor_wrapper.buffer.DataAsNumpy()
if tensor_wrapper.tensor.ShapeLength() != 0:
shape = to_int_list(self.get_tensor_shape(tensor_wrapper))
else:
shape = []
if is_sparse:
return np.frombuffer(data, dtype=dtype)
else:
return np.frombuffer(data, dtype=dtype).reshape(shape)
def get_tensor_type_str(self, tensor_type):
"""Get tensor type string representation when given TFLite tensor type"""
try:
from tflite.TensorType import TensorType
except ImportError:
raise ImportError("The tflite package must be installed")
if tensor_type == TensorType.INT8:
return "int8"
if tensor_type == TensorType.INT16:
return "int16"
if tensor_type == TensorType.UINT8:
return "uint8"
if tensor_type == TensorType.FLOAT16:
return "float16"
if tensor_type == TensorType.FLOAT32:
return "float32"
if tensor_type == TensorType.INT32:
return "int32"
if tensor_type == TensorType.INT64:
return "int64"
if tensor_type == TensorType.BOOL:
return "bool"
raise NotImplementedError(f"Tensor type {str(tensor_type)} is currently not supported")
def flatten_to_nd(self, x, x_shape, nd=3):
"""Flatten input tensor to nd rank"""
ndims = _infer_shape(x_shape)[0]
if ndims == nd:
return x
newshape = _op.concatenate(
[
_expr.const([-1], dtype=_infer_type(x_shape).checked_type.dtype),
_op.strided_slice(x_shape, [ndims - nd + 1], [ndims]),
],
0,
)
out = _op.reshape(x, _fold_constant(newshape))
return out
def has_same_qnn_params(self, lhs_tensor, rhs_tensor):
lhs_scale = lhs_tensor.qnn_params["scale"]
rhs_scale = rhs_tensor.qnn_params["scale"]
lhs_zero_point = lhs_tensor.qnn_params["zero_point"]
rhs_zero_point = rhs_tensor.qnn_params["zero_point"]
# 0.1 + 0.2 != 0.3
return np.allclose(
lhs_scale.data.numpy(), rhs_scale.data.numpy(), rtol=1e-5, atol=1e-5
) and np.allclose(
lhs_zero_point.data.numpy(), rhs_zero_point.data.numpy(), rtol=1e-5, atol=1e-5
)
def is_quantized(self, op):
"""Check if an input tensor is quantized."""
input_tensors = self.get_input_tensors(op)
first_tensor = input_tensors[0]
return first_tensor.qnn_params is not None
def quantize(self, expr, tensor_to_quantize):
"""Helper function to quantize a tensor with Relay"""
tensor_type = tensor_to_quantize.tensor.Type()
tensor_type_str = self.get_tensor_type_str(tensor_type)
quantized = _qnn.op.quantize(
data=expr,
output_scale=tensor_to_quantize.qnn_params["scale"],
output_zero_point=tensor_to_quantize.qnn_params["zero_point"],
out_dtype=tensor_type_str,
)
return quantized
def dequantize(self, expr, tensor):
"""Helper function to dequantize a tensor with Relay"""
dequantized = _qnn.op.dequantize(
data=expr,
input_scale=tensor.qnn_params["scale"],
input_zero_point=tensor.qnn_params["zero_point"],
)
return dequantized
def convert_qnn_fused_activation_function(
self, expr, fused_activation_fn, scale, zero_point, dtype
):
"""Convert TFLite fused activation function. The expr is an input quantized tensor with
scale and zero point"""
try:
from tflite.ActivationFunctionType import ActivationFunctionType
except ImportError:
raise ImportError("The tflite package must be installed")
# Quantize a float value to an quantized integer value
quantize = lambda x: float(int(round(x / scale)) + zero_point)
# Get min/max of the output dtype. This will be used to ensure that clip a_min/a_max are not
# beyond the dtype range.
qmin = float(tvm.tir.op.min_value(dtype).value)
qmax = float(tvm.tir.op.max_value(dtype).value)
# The input expr is a quantized tensor with its scale and zero point. We calculate the
# suitable clip off points based on these scale and zero point.
if fused_activation_fn == ActivationFunctionType.NONE:
return expr
if fused_activation_fn == ActivationFunctionType.RELU6:
return _op.clip(expr, a_min=max(qmin, quantize(0)), a_max=min(qmax, quantize(6.0)))
if fused_activation_fn == ActivationFunctionType.RELU_N1_TO_1:
return _op.clip(expr, a_min=max(qmin, quantize(-1.0)), a_max=min(qmax, quantize(1.0)))
if fused_activation_fn == ActivationFunctionType.RELU:
return _op.clip(expr, a_min=max(qmin, quantize(0.0)), a_max=qmax)
fused_activation_fn_str = self.activation_fn_type[fused_activation_fn]
raise tvm.error.OpNotImplemented(
f"Quantized activation {fused_activation_fn_str} is not supported yet."
)
def convert_conv2d(self, op):
"""Convert TFLite conv2d"""
return self.convert_conv(op, "conv2d")
def convert_depthwise_conv2d(self, op):
"""Convert TFLite depthwise conv2d"""
return self.convert_conv(op, "depthwise")
def convert_average_pool2d(self, op):
"""Convert TFLite average pool2d"""
return self.convert_pool2d(op, "average")
def convert_max_pool2d(self, op):
"""Convert TFLite max pool2d"""
return self.convert_pool2d(op, "max")
def convert_l2_pool2d(self, op):
"""Convert TFLite l2 pool2d"""
return self.convert_pool2d(op, "l2")
def convert_reshape(self, op):
"""Convert TFLite reshape"""
try:
from tflite.BuiltinOptions import BuiltinOptions
from tflite.ReshapeOptions import ReshapeOptions
except ImportError:
raise ImportError("The tflite package must be installed")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) in (1, 2), "input tensors should not be empty"
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "There should be only 1 output tensor"
input_tensor = input_tensors[0]
input_tensor_idx = input_tensor.tensor_idx
if len(input_tensors) == 2:
shape_tensor = input_tensors[1]
if self.has_expr(shape_tensor.tensor_idx):
target_expr = self.get_expr(shape_tensor.tensor_idx)
target_value, success = try_infer_value(
target_expr,
parameters={k: _nd.array(np.array(v)) for k, v in self.exp_tab.params.items()},
)
if success:
# convert to flattened list
from itertools import chain
try:
target_shape = list(chain(*target_value))
except TypeError:
target_shape = list(chain(target_value))
else:
target_shape = target_expr
else:
target_shape = self.get_tensor_value(shape_tensor)
# convert to flattened list
from itertools import chain
try:
target_shape = list(chain(*target_shape))
except TypeError:
target_shape = list(chain(target_shape))
else:
assert op.BuiltinOptionsType() == BuiltinOptions.ReshapeOptions
op_options = op.BuiltinOptions()
reshape_options = ReshapeOptions()
reshape_options.Init(op_options.Bytes, op_options.Pos)
target_shape = to_int_list(reshape_options.NewShapeAsNumpy())
in_expr = self.get_expr(input_tensor_idx)
# If the tensors are quantized, ensure that input/output qnn params are same.
input_tensor_type_str = self.get_tensor_type_str(input_tensor.tensor.Type())
if input_tensor.qnn_params and input_tensor_type_str == "int8":
# TFLite 2.x quantization spec requires qnn params to be same and dtype to be int8.
# For TFLite 1.x, dtype can be uint8 and qnn params can be different
output_tensor = output_tensors[0]
assert self.has_same_qnn_params(
input_tensor, output_tensor
), "TFLite reshape requires input and output scale and zero points to be equal"
out = _op.reshape(in_expr, newshape=target_shape)
if input_tensor.qnn_params and input_tensor_type_str == "uint8":
output_tensor = output_tensors[0]
if not self.has_same_qnn_params(input_tensor, output_tensor):
output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())
out = _qnn.op.requantize(
out,
input_scale=input_tensor.qnn_params["scale"],
input_zero_point=input_tensor.qnn_params["zero_point"],
output_scale=output_tensor.qnn_params["scale"],
output_zero_point=output_tensor.qnn_params["zero_point"],
out_dtype=output_tensor_type_str,
)
return out
def _convert_resize(self, method, op):
"""Generic method to Convert TFLite RESIZE operators"""
try:
from tflite.BuiltinOptions import BuiltinOptions
from tflite.ResizeBilinearOptions import ResizeBilinearOptions
# ResizeNearestNeighborOptions was added in tflite v1.13
tflite_ver = 1120
if "ResizeNearestNeighborOptions" in dir(BuiltinOptions):
from tflite.ResizeNearestNeighborOptions import ResizeNearestNeighborOptions
tflite_ver = 1130
except ImportError:
raise ImportError("The tflite package must be installed")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 2, "input tensors length should be 2"
# images, 4-D Tensor with shape NHWC.
input_tensor = input_tensors[0]
in_expr = self.get_expr(input_tensor.tensor_idx)
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
output_tensor = output_tensors[0]
# size - 1-D int32 Tensor of 2 elements: new_height, new_width
target_size = tuple(self.get_tensor_value(input_tensors[1]))
# Options - align_corners (bool)
resize_options = None
align_corners = False
bilinear_method = method == "linear"
if bilinear_method:
assert op.BuiltinOptionsType() == BuiltinOptions.ResizeBilinearOptions
resize_options = ResizeBilinearOptions()
elif tflite_ver >= 1130:
assert op.BuiltinOptionsType() == BuiltinOptions.ResizeNearestNeighborOptions
resize_options = ResizeNearestNeighborOptions()
if resize_options is not None:
op_options = op.BuiltinOptions()
resize_options.Init(op_options.Bytes, op_options.Pos)
align_corners = resize_options.AlignCorners()
half_pixel_centers = resize_options.HalfPixelCenters()
# Use layout NHWC
coord_trans = "align_corners" if align_corners else "asymmetric"
coord_trans = "half_pixel" if half_pixel_centers else coord_trans
rounding_method = ""
if method == "nearest_neighbor":
if not align_corners and half_pixel_centers:
rounding_method = "round_prefer_ceil"
if bilinear_method and input_tensor.qnn_params:
in_expr = self.dequantize(in_expr, input_tensor)
out = _op.image.resize2d(
in_expr, target_size, None, "NHWC", method, coord_trans, rounding_method
)
if bilinear_method and output_tensor.qnn_params:
out = self.quantize(out, output_tensor)
return out
def convert_resize_bilinear(self, op):
"""Convert TFLite RESIZE_BILINEAR"""
return self._convert_resize("linear", op)
def convert_resize_nearest_neighbor(self, op):
"""Convert TFLite RESIZE_NEAREST_NEIGHBOR"""
return self._convert_resize("nearest_neighbor", op)
def convert_l2_normalization(self, op):
"""Convert TFLite L2_NORMALIZATION"""
try:
from tflite.BuiltinOptions import BuiltinOptions
from tflite.L2NormOptions import L2NormOptions
except ImportError:
raise ImportError("The tflite package must be installed")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
input_tensor = input_tensors[0]
in_expr = self.get_expr(input_tensor.tensor_idx)
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
output_tensor = output_tensors[0]
assert op.BuiltinOptionsType() == BuiltinOptions.L2NormOptions
op_options = op.BuiltinOptions()
l2_norm_options = L2NormOptions()
l2_norm_options.Init(op_options.Bytes, op_options.Pos)
fused_activation_fn = l2_norm_options.FusedActivationFunction()
# TFLite supports normalization only over the last dim
input_tensor_rank = len(input_tensor.tensor.ShapeAsNumpy())
if self.is_quantized(op):
raise tvm.error.OpNotImplemented(
"TFLite quantized L2_NORMALIZATION operator is not supported yet."
)
# TFL uses only the default epsilon value
out = _op.nn.l2_normalize(in_expr, eps=1e-12, axis=[input_tensor_rank - 1])
# if we have fused activation fn
if output_tensor.qnn_params:
raise tvm.error.OpNotImplemented(
"TFLite quantized L2_NORMALIZATION operator is not supported yet."
)
out = self.convert_fused_activation_function(out, fused_activation_fn)
return out
def convert_lrn(self, op):
"""Convert TFLite LOCAL_RESPONSE_NORMALIZATION"""
try:
from tflite.BuiltinOptions import BuiltinOptions
from tflite.LocalResponseNormalizationOptions import LocalResponseNormalizationOptions
except ImportError:
raise ImportError("The tflite package must be installed")
if self.is_quantized(op):
raise tvm.error.OpNotImplemented("TFlite quantized LRN operator is not supported yet.")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
input_tensor = input_tensors[0]
in_expr = self.get_expr(input_tensor.tensor_idx)
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
assert op.BuiltinOptionsType() == BuiltinOptions.LocalResponseNormalizationOptions
op_options = op.BuiltinOptions()
lrn_options = LocalResponseNormalizationOptions()
lrn_options.Init(op_options.Bytes, op_options.Pos)
radius = lrn_options.Radius()
bias = lrn_options.Bias()
alpha = lrn_options.Alpha()
beta = lrn_options.Beta()
size = (radius * 2) + 1
alpha = alpha * size
axis = 3 # NHWC format
out = _op.nn.lrn(in_expr, size=size, axis=axis, bias=bias, alpha=alpha, beta=beta)
return out
def convert_logistic(self, op):
"""Convert TFLite LOGISTIC"""
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
input_tensor = input_tensors[0]
in_expr = self.get_expr(input_tensor.tensor_idx)
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
output_tensor = output_tensors[0]
if input_tensor.qnn_params:
in_expr = self.dequantize(in_expr, input_tensor)
out = _op.sigmoid(in_expr)
if output_tensor.qnn_params:
out = self.quantize(out, output_tensor)
return out
def convert_softmax(self, op):
"""Convert TFLite softmax"""
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
input_tensor = input_tensors[0]
input_tensor_idx = input_tensor.tensor_idx
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
output_tensor = output_tensors[0]
params = {"axis": -1} # -1 is channel
in_expr = self.get_expr(input_tensor_idx)
# TODO - Naive softmax int8 implementation leads to bad accuracy. Currently, we can
# dequantize to FP32 and perform softmax on FP32. We can investigate an integer only softmax
# implementation in future.
if input_tensor.qnn_params:
in_expr = self.dequantize(in_expr, input_tensor)
out = _op.nn.softmax(in_expr, **params)
# Go back to integer dataype if the original operator was quantized.
if output_tensor.qnn_params:
out = self.quantize(out, output_tensor)
return out
def convert_tanh(self, op):
"""Convert TFLite TANH"""
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
input_tensor = input_tensors[0]
in_expr = self.get_expr(input_tensor.tensor_idx)
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
output_tensor = output_tensors[0]
if input_tensor.qnn_params:
in_expr = self.dequantize(in_expr, input_tensor)
out = _op.tanh(in_expr)
if output_tensor.qnn_params:
out = self.quantize(out, output_tensor)
return out
def convert_range(self, op):
"""Convert TFLite Range"""
try:
from tflite.TensorType import TensorType
except ImportError:
raise ImportError("The tflite package must be installed")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 3, "input tensors length should be 3"
start, limit, delta = input_tensors[0], input_tensors[1], input_tensors[2]
expressions = [self.get_tensor_expr(t) for t in [start, limit, delta]]
# out type inference
if delta.tensor.Type() == TensorType.FLOAT32:
out_type = self.get_tensor_type_str(delta.tensor.Type())
else:
out_type = self.get_tensor_type_str(start.tensor.Type())
out = _op.arange(expressions[0], expressions[1], expressions[2], out_type)
return out
def convert_shape(self, op):
"""Convert TFLite Shape"""
try:
from tflite.BuiltinOptions import BuiltinOptions
from tflite.ShapeOptions import ShapeOptions
except ImportError:
raise ImportError("The tflite package must be installed")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
assert op.BuiltinOptionsType() == BuiltinOptions.ShapeOptions
op_options = op.BuiltinOptions()
shape_options = ShapeOptions()
shape_options.Init(op_options.Bytes, op_options.Pos)
out_type = self.get_tensor_type_str(shape_options.OutType())
out = shape_of(self.get_tensor_expr(input_tensors[0]), dtype=out_type)
return out
def convert_relu(self, op):
"""Convert TFLite ReLU"""
try:
from tflite.ActivationFunctionType import ActivationFunctionType
except ImportError:
raise ImportError("The tflite package must be installed")
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
input_tensor = input_tensors[0]
in_expr = self.get_expr(input_tensor.tensor_idx)
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
output_tensor = output_tensors[0]
if input_tensor.qnn_params:
# Quantize a float value to an quantized integer value
scale_val = get_scalar_from_constant(input_tensor.qnn_params["scale"])
zero_point_val = get_scalar_from_constant(input_tensor.qnn_params["zero_point"])
output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())
out = self.convert_qnn_fused_activation_function(
expr=in_expr,
fused_activation_fn=ActivationFunctionType.RELU,
scale=scale_val,
zero_point=zero_point_val,
dtype=output_tensor_type_str,
)
else:
out = _op.nn.relu(in_expr)
if output_tensor.qnn_params:
output_tensor_type_str = self.get_tensor_type_str(output_tensor.tensor.Type())
out = _qnn.op.requantize(
out,
input_scale=input_tensor.qnn_params["scale"],
input_zero_point=input_tensor.qnn_params["zero_point"],
output_scale=output_tensor.qnn_params["scale"],
output_zero_point=output_tensor.qnn_params["zero_point"],
out_dtype=output_tensor_type_str,
)
return out
def convert_hard_swish(self, op):
"""Convert TFLite Hard swish"""
input_tensors = self.get_input_tensors(op)
assert len(input_tensors) == 1, "input tensors length should be 1"
input_tensor = input_tensors[0]
in_expr = self.get_expr(input_tensor.tensor_idx)
output_tensors = self.get_output_tensors(op)
assert len(output_tensors) == 1, "output tensors length should be 1"
output_tensor = output_tensors[0]
def _relu6(data):
return _op.tensor.clip(data, 0.0, 6.0)