blob: d9ace1e8ac596f187bcba2f8ff158ee74fee9fe4 [file] [log] [blame]
Johan Alfven12e48112023-01-31 10:26:26 +01001# SPDX-FileCopyrightText: Copyright 2021-2023 Arm Limited and/or its affiliates <open-source-office@arm.com>
Jonas Ohlsson45e653d2021-07-26 16:13:12 +02002#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Rickard Bolinbc6ee582022-11-04 08:24:29 +000016#
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020017# Description:
18# The TFLiteSemantic class which is a collection of TensorFlow lite model semantic checks.
19from collections import defaultdict
20
21import numpy as np
22
23from .data_type import BaseType
24from .data_type import DataType
25from .numeric_util import is_integer
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020026from .operation import Op
27from .supported_operators_util import docstring_format_args
28from .supported_operators_util import list_formatter
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020029from .tensor import check_quantized_tens_scaling_equal
Johan Alfven3ac03be2023-03-01 09:53:35 +010030from .tensor import shape_num_elements
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020031from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
32from .tflite_mapping import optype_to_builtintype
33
34
35def _optype_formatter(op_list):
36 # Convert internal op types to external names
37 output = map(optype_to_builtintype, op_list)
38 # Remove UNKNOWNs
39 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
40 return list_formatter(output)
41
42
43class TFLiteSemantic:
44 # Categorised lists of operators
Jonas Ohlssond8575072022-03-30 10:30:25 +020045 convolution_ops = set(
46 (
47 Op.Conv2DBias,
48 Op.Conv2D,
49 Op.QuantizedConv2D,
50 )
51 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020052 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
53 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
54 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
55 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
56 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
57 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
58 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020059 binary_elem_wise_min_max_ops = set(
60 (
61 Op.Minimum,
62 Op.Maximum,
63 )
64 )
65 binary_elem_wise_shift_ops = set(
66 (
67 Op.SHL,
68 Op.SHR,
69 )
70 )
71 binary_elem_wise_add_mul_sub = set(
72 (
73 Op.Add,
74 Op.Mul,
75 Op.Sub,
76 )
77 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020078 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Johan Alfven906c9e82023-05-25 11:18:50 +020079 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops | set((Op.SquaredDifference,))
Rickard Bolin6986a072022-12-19 12:33:40 +000080 shapeless_input_ops = binary_elem_wise_main_ops | set(
81 (Op.Split, Op.SplitV, Op.Mean, Op.ExpandDims, Op.Quantize, Op.ArgMax)
82 )
Jonas Ohlssond8575072022-03-30 10:30:25 +020083 reshape_ops = set(
84 (
85 Op.Reshape,
86 Op.QuantizedReshape,
87 Op.Squeeze,
88 Op.ExpandDims,
89 )
90 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020091
92 def __init__(self):
93 # Setup the generic constraints. Note: the order matters
94 self.generic_constraints = []
Tim Hall2180a172023-03-10 18:11:34 +000095 self.generic_constraints.append(TFLiteSemantic.constraint_attributes_specified)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020096 self.generic_constraints.append(TFLiteSemantic.constraint_tens_no_dynamic)
97 self.generic_constraints.append(TFLiteSemantic.constraint_tens_defined_shape)
98 self.generic_constraints.append(TFLiteSemantic.constraint_tens_output_scalar)
99 self.generic_constraints.append(TFLiteSemantic.constraint_tens_input_scalar)
100 self.generic_constraints.append(TFLiteSemantic.constraint_tens_shape_size)
101
102 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_none_check)
103 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_scale)
104 self.generic_constraints.append(TFLiteSemantic.constraint_quant_scale_inf)
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100105 self.generic_constraints.append(TFLiteSemantic.constraint_none_const_tensors)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200106
107 # Setup specific constraints. Note: the order matters
108 self.specific_constraints = defaultdict(list)
109
110 # Conv-like checks:
111 for op_type in TFLiteSemantic.convolution_like_ops:
112 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
Tim Hall9cf63a32023-06-27 12:07:49 +0100113 if op_type in TFLiteSemantic.convolution_ops:
114 # Only Conv has groups
115 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_conv_groups_ifm_depth)
116 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_conv_groups_num_filters)
Tim Hallea4ba662022-11-11 18:19:53 +0000117 if op_type not in TFLiteSemantic.transpose_convolution_ops:
118 # Transpose Conv does not contain dilation
119 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_dilation_type)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200120
121 # Pooling checks:
122 for op_type in TFLiteSemantic.pooling_ops:
123 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
124 # AVG pooling specific checks:
125 for op_type in TFLiteSemantic.avg_pooling_ops:
126 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
127 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
128 # MAX pooling specific checks:
129 for op_type in TFLiteSemantic.max_pooling_ops:
130 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
131 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
132
133 # Concat specific checks:
134 for op_type in (Op.Concat, Op.ConcatTFLite):
135 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_exists)
136 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_valid)
137 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_dimensionality)
138 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions)
Johan Alfvénb3932512022-09-12 17:44:25 +0200139 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200140
141 # Element-wise checks:
142 for op_type in TFLiteSemantic.elem_wise_main_ops:
143 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_either_shapes)
144 # Unary specific checks:
145 for op_type in TFLiteSemantic.unary_elem_wise_main_ops:
146 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
147 # Binary Min/Max specific checks:
148 for op_type in TFLiteSemantic.binary_elem_wise_min_max_ops:
149 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
150 # Binary Add/Mul/Sub specific checks:
151 for op_type in TFLiteSemantic.binary_elem_wise_add_mul_sub:
152 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_inputs_types)
153 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_signed)
154 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_unsigned_valid)
155
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200156 # Ops reshaping dimensions: Reshape, Squeeze and ExpandDims
157 for op_type in TFLiteSemantic.reshape_ops:
158 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_quant)
Johan Alfven3ac03be2023-03-01 09:53:35 +0100159 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_elements)
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200160
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200161 # Softmax specific checks:
162 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_shapes)
163 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_in_out_types)
164 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_beta_value_range)
165
Johan Alfven12e48112023-01-31 10:26:26 +0100166 # Split specific checks:
167 self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_axis)
168 self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_num_splits)
169
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200170 # SplitV specific checks:
171 self.specific_constraints[Op.SplitV].append(TFLiteSemantic.constraint_splitv_inferred)
172
173 # StridedSlice specific checks:
174 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_input_count)
175 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_inputs_const)
176 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_ellipsis_mask)
177 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_axis_masks)
178 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_slice_ranges)
179
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200180 # FullyConnected specific checks:
181 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_fc_output_2d)
182 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_keep_dim_ifm_ofm)
183
184 # Pad specific checks:
185 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_input_count)
186 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_constant)
Johan Gunnarsson81b765d2023-08-04 17:16:29 +0200187 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_output_shape)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200188
189 # HardSwish specific checks:
190 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_input_8bit)
191 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_matching_in_out_types)
Fredrik Svedberg701ba912022-09-07 16:01:15 +0200192
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200193 # Mean specific checks:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200194 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_input_dims)
195 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_axis)
196
Rickard Bolin6986a072022-12-19 12:33:40 +0000197 # ArgMax specific checks:
198 self.specific_constraints[Op.ArgMax].append(TFLiteSemantic.constraint_input_8bit)
Johan Alfvenc1ad80b2023-03-31 10:19:23 +0200199 self.specific_constraints[Op.ArgMax].append(TFLiteSemantic.constraint_argmax_output)
Rickard Bolin6986a072022-12-19 12:33:40 +0000200
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200201 # UnidirectionalSequenceLstm specific checks:
202 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_input_signed)
203 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_matching_in_out_types)
204 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_dimensions)
205 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_inputs)
206 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_intermediates)
207 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_variables)
208
Johan Alfvence502732023-04-24 13:35:40 +0200209 # Exp specific checks
210 self.specific_constraints[Op.Exp].append(TFLiteSemantic.constraint_input_signed)
211
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200212 def is_operator_semantic_valid(self, op):
213 ext_type = optype_to_builtintype(op.type)
214
215 if op.type in (Op.Placeholder, Op.SubgraphInput, Op.Const):
216 return True
217
Ayaan Masood4965fae2022-06-29 11:30:57 +0100218 # Generic constraints list filtered out to exclude certain constraints depending on op.type
219 filtered_generic_constraints = []
220
221 for constraint in self.generic_constraints:
222 # Check constraint not in dictionary otherwise return empty array
223 if constraint not in self.get_generic_constraint_exclude_list().get(op.type, []):
224 filtered_generic_constraints.append(constraint)
225
226 for constraint in filtered_generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200227 valid, extra = constraint(op)
228 if not valid:
229 print(
Tim Hall3584a9c2021-11-18 22:05:17 +0000230 f"Warning: Unsupported TensorFlow Lite semantics for {ext_type} '{op.name}'. Placing on CPU instead"
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200231 )
232 print(f" - {constraint.__doc__}")
233 if extra:
234 print(f" {extra}")
235 return False
236
237 return True
238
239 @staticmethod
Ayaan Masood4965fae2022-06-29 11:30:57 +0100240 def get_generic_constraint_exclude_list():
241
242 # Not all generic constraints can be applied to each operator
243 generic_constraints_exclude_list = {
244 Op.Shape: [
245 TFLiteSemantic.constraint_tens_quant_none_check,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100246 ],
247 Op.Quantize: [
248 TFLiteSemantic.constraint_tens_no_dynamic,
249 TFLiteSemantic.constraint_tens_output_scalar,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100250 ],
Rickard Bolin6986a072022-12-19 12:33:40 +0000251 Op.ArgMax: [
252 TFLiteSemantic.constraint_tens_quant_none_check,
253 ],
Johan Alfvena8fda882023-10-28 16:04:46 +0200254 Op.Transpose: [
255 TFLiteSemantic.constraint_tens_quant_none_check,
256 ],
Ayaan Masood4965fae2022-06-29 11:30:57 +0100257 }
258 return generic_constraints_exclude_list
259
260 @staticmethod
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100261 def constraint_none_const_tensors(op):
262 "Constant tensors should not have NoneType-values"
263 valid = True
264 extra = ""
265 for tens in filter(None, op.inputs):
266 if len(tens.ops) > 0 and tens.ops[0].type == Op.Const and tens.values is None:
267 valid = False
268 extra = str(tens.name)
269 return valid, f"Unexpected None value for constant tensor: {extra}"
270
271 @staticmethod
Tim Hall2180a172023-03-10 18:11:34 +0000272 def constraint_attributes_specified(op):
273 "All required operator attributes must be specified"
274 # operators that have been created internally (i.e. not created as part of reading an input network) may not
275 # have the read error attribute
276 attribute_read_error = op.attrs.get("attribute_read_error", [])
277 valid = len(attribute_read_error) == 0
278 extra = ", ".join(attribute_read_error)
279 return valid, f"Op has missing attributes: {extra}"
280
281 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200282 def constraint_tens_no_dynamic(op):
283 "Input(s) and Output tensors must not be dynamic"
284 valid = True
285 extra = []
286 tensors = [tens for tens in op.inputs + op.outputs if tens]
287 for tens in tensors:
288 if (tens.shape == []) and (tens.values is None):
289 valid = False
290 extra.append(tens.name)
291 extra = ", ".join(extra)
292 return valid, f"Op has dynamic tensor(s): {extra}"
293
294 @staticmethod
295 def constraint_tens_defined_shape(op):
296 "Input(s) and Output tensors must have a defined shape"
297 valid = True
298 extra = []
299 tensors = [tens for tens in op.inputs + op.outputs if tens]
300 for tens in tensors:
301 if not tens.has_fully_defined_shape():
302 valid = False
303 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
304 return valid, ", ".join(extra)
305
306 @staticmethod
307 def constraint_tens_output_scalar(op):
308 "Output tensors cannot be scalar"
309 ofm = op.ofm
310 valid = ofm.shape != []
311 return valid, f"Output Tensor '{ofm.name}' is scalar"
312
313 @classmethod
314 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
315 def constraint_tens_input_scalar(cls, op):
316 "Scalar Input tensors are only valid for op type: {}"
317 valid = True
318 extra = []
319 tensors = [tens for tens in op.inputs if tens]
320 for tens in tensors:
321 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
322 valid = False
323 extra.append(tens.name)
324 extra = ", ".join(extra)
325 return valid, f"Op has scalar input tensor(s): {extra}"
326
327 @staticmethod
328 def constraint_tens_shape_size(op):
329 "Input(s) and Output tensors must not be greater than 4D"
330 valid = True
331 extra = []
332 tensors = [tens for tens in op.inputs + op.outputs if tens]
333 for tens in tensors:
334 if len(tens.shape) > 4:
335 valid = False
336 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
337 return valid, ", ".join(extra)
338
339 @staticmethod
340 def constraint_tens_quant_none_check(op):
341 "Input(s), Output and Weight tensors must have quantization parameters"
342 valid = True
343 extra = []
344 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
345 for tens in tensors:
346 if tens.quantization is None:
347 valid = False
348 extra.append(tens.name)
349 extra = ", ".join(extra)
350 return valid, f"Op has tensors with missing quantization parameters: {extra}"
351
352 @staticmethod
353 def constraint_tens_quant_scale(op):
354 "Input(s), Output and Weight tensors with quantization scales must be finite"
355 valid = True
356 extra = []
357 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
358 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200359 if (
360 tens.quantization
361 and tens.quantization.scale_f32 is not None
362 and np.isinf(tens.quantization.scale_f32).any()
363 ):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200364 valid = False
365 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
366 return valid, ", ".join(extra)
367
368 @staticmethod
369 def constraint_fc_output_2d(op):
Ayaan Masooda2ec5aa2022-04-21 14:28:03 +0100370 """The output tensor(s) must have 2D shape"""
371 valid = op.ifm.get_shape_as_2d(op.weights.shape[-2]) is not None
372 extra = f"Op has non-2D output tensor '{op.ofm.name}'" if not valid else ""
373
374 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200375
376 @staticmethod
377 def constraint_stride_type(op):
378 "Stride values for both width and height must be integer types"
379 w, h = op.get_kernel_stride()
380 valid = is_integer(w) and is_integer(h)
381 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
382
383 @staticmethod
Tim Hall9cf63a32023-06-27 12:07:49 +0100384 def constraint_conv_groups_ifm_depth(op):
385 """IFM depth must be a whole multiple of the filter kernel depth"""
386 ifm_depth = op.ifm.shape[-1] # nhwc
387 kernel_ic = op.weights.shape[-2] # hwio
388 num_conv_groups = ifm_depth // kernel_ic
389
390 if ifm_depth % kernel_ic == 0:
391 op.attrs["num_conv_groups"] = num_conv_groups
392 valid = True
393 else:
394 valid = False
395
396 return valid, f"IFM depth = {ifm_depth} and filter kernel depth = {kernel_ic}"
397
398 @staticmethod
399 def constraint_conv_groups_num_filters(op):
400 """Number of filter kernels must be equally divisible by the number of convolution groups"""
401 ifm_depth = op.ifm.shape[-1] # nhwc
402 kernel_ic = op.weights.shape[-2] # hwio
403 kernel_oc = op.weights.shape[-1] # hwio
404 num_conv_groups = ifm_depth // kernel_ic
405
406 if kernel_oc % num_conv_groups == 0:
407 valid = True
408 else:
409 valid = False
410
411 return valid, f"Filter kernels = {kernel_oc} and convolution groups = {num_conv_groups}"
412
413 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200414 def constraint_dilation_type(op):
415 "Dilation factor values for both width and height must be integer types"
416 w, h = op.get_kernel_dilation()
417 valid = is_integer(w) and is_integer(h)
418 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
419
420 @staticmethod
421 def constraint_quant_scale_inf(op):
422 "Input and Output tensors must have quantization scales that fit within float32 precision"
423 if op.ofm is not None and op.ofm.is_quantized():
424 ofm_scale = op.ofm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200425 if np.any(ofm_scale < np.finfo(np.float32).tiny):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200426 return (
427 False,
428 f"The quantization scale of the output tensor is {ofm_scale}, "
429 + f"minimum supported is: {np.finfo(np.float32).tiny}",
430 )
431 if op.ifm is not None and op.ifm.is_quantized():
432 ifm_scale = op.ifm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200433 if np.any(np.isinf(ifm_scale / ofm_scale)):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200434 return (
435 False,
436 f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}",
437 )
438 return True, "Op's quantization is ok"
439
440 @staticmethod
441 def constraint_matching_in_out_types(op):
442 "IFM and OFM data types must match"
443 ifm_dtype = op.ifm.dtype
444 ofm_dtype = op.ofm.dtype
445 valid = ifm_dtype == ofm_dtype
446 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
447
448 @staticmethod
449 def constraint_beta_value_range(op):
450 "Beta value needs to be positive"
451 beta = op.attrs.get("beta", 1.0)
452 valid = beta >= 0
453 return valid, f"Op has beta={beta}"
454
455 @staticmethod
456 def constraint_filter_type(op):
457 "Kernel filter values for both width and height must be integer types"
458 w = op.kernel.width
459 h = op.kernel.height
460 valid = is_integer(w) and is_integer(h)
461 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
462
463 @staticmethod
464 def constraint_matching_shapes(op):
465 "IFM and OFM shapes must match"
466 ifm_shape = op.ifm.shape
467 ofm_shape = op.ofm.shape
468 valid = ifm_shape == ofm_shape
469 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
470
471 @staticmethod
Johan Alfven12e48112023-01-31 10:26:26 +0100472 def constraint_split_axis(op):
473 "Axis value must be in the range [-RANK(IFM) to +RANK(IFM))"
474 axis_tens = op.inputs[0]
475 input_tens = op.inputs[1]
476 dims = len(input_tens.shape)
Tim Hall762d3ac2023-07-06 11:42:02 +0100477 # handle axis being a scalar or 1-D array
William Isaksson75d34022023-08-10 12:22:44 +0000478 if axis_tens.values.ndim == 0:
479 axis = int(axis_tens.values)
480 else:
481 axis = int(axis_tens.values[0])
Johan Alfven12e48112023-01-31 10:26:26 +0100482 axis += dims if axis < 0 else 0
483 valid = 0 <= axis < dims
484 return valid, f"Op has ifm_dimensions={dims} and axis value is: {axis}"
485
486 @staticmethod
487 def constraint_split_num_splits(op):
488 "Axis must be divisible by number of splits"
489 num_splits = op.attrs.get("num_splits")
490 axis_tens = op.inputs[0]
491 input_tens = op.inputs[1]
492 dims = len(input_tens.shape)
Tim Hall762d3ac2023-07-06 11:42:02 +0100493 # handle axis being a scalar or 1-D array
William Isaksson75d34022023-08-10 12:22:44 +0000494 if axis_tens.values.ndim == 0:
495 axis = int(axis_tens.values)
496 else:
497 axis = int(axis_tens.values[0])
Johan Alfven12e48112023-01-31 10:26:26 +0100498 axis += dims if axis < 0 else 0
499 valid = input_tens.shape[axis] % num_splits == 0
500 return valid, f"Op has ifm shape={input_tens.shape} axis={axis} num_splits={num_splits}"
501
502 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200503 def constraint_splitv_inferred(op):
504 "Only one size is allowed to be inferred"
505 sizes = op.inputs[1].values
506 valid = np.count_nonzero(sizes == -1) <= 1
507 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
508
509 @staticmethod
510 def constraint_axis_exists(op):
511 "Axis attribute must exist"
512 axis = op.attrs.get("axis")
513 valid = axis is not None
514 return valid, f"Op has axis={axis}"
515
516 @staticmethod
517 def constraint_axis_valid(op):
518 "Axis attribute must be in the range [0, <ofm_dimensions>)"
519 dims = len(op.ofm.shape)
520 axis = op.attrs["axis"]
521 axis += dims if axis < 0 else 0
522 valid = 0 <= axis < dims
523 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
524
525 @staticmethod
526 def constraint_matching_dimensionality(op):
527 "All Input dimensionalities must match OFM dimensionality"
528 valid = True
529 extra = []
530 ofm_dim = len(op.ofm.shape)
531 tensors = [tens for tens in op.inputs if tens]
532 for tens in tensors:
533 dim = len(tens.shape)
534 if dim != ofm_dim:
535 valid = False
536 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
537 extra = ", ".join(extra)
538 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
539
540 @staticmethod
541 def constraint_valid_dimensions(op):
542 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
543 valid = True
544 extra = []
545 ofm_shape = op.ofm.shape
546 ofm_dim = len(ofm_shape)
547 axis = op.attrs["axis"]
548 axis += ofm_dim if axis < 0 else 0
549 tensors = [tens for tens in op.inputs if tens]
550 for tens in tensors:
551 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
552 valid = False
553 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
554 extra = ", ".join(extra)
555 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
556
557 @staticmethod
Johan Alfvénb3932512022-09-12 17:44:25 +0200558 def constraint_valid_dimensions_axis(op):
559 """The size of the OFM axis must match the sum of all IFM axis defined by the axis attribute"""
560 valid = True
561 extra = []
562 ofm_shape = op.ofm.shape
563 ofm_dim = len(ofm_shape)
564 axis = op.attrs["axis"]
565 axis += ofm_dim if axis < 0 else 0
566
567 sum_ifm_axis = 0
568 tensors = [tens for tens in op.inputs if tens]
569 for tens in tensors:
570 sum_ifm_axis += tens.shape[axis]
571 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
572
573 valid = sum_ifm_axis == ofm_shape[axis]
574 extra = ", ".join(extra)
575 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
576
577 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200578 def constraint_stridedslice_input_count(op):
579 "Exactly 4 Input tensors are required"
580 inputs = len(op.inputs)
581 valid = inputs == 4
582 return valid, f"Op has {inputs} inputs"
583
584 @staticmethod
585 def constraint_pad_input_count(op):
586 "Number of input tensors must be exactly 2"
587 inputs = len(op.inputs)
588 valid = inputs == 2
589 return valid, f"Op has {inputs} inputs"
590
591 @staticmethod
592 def constraint_pad_constant(op):
593 "The padding tensor must be constant"
594 pad_tensor = op.inputs[1].values
595 valid = pad_tensor is not None
596 return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}"
597
598 @staticmethod
Johan Gunnarsson81b765d2023-08-04 17:16:29 +0200599 def constraint_pad_output_shape(op):
600 "Shape of output tensor must equal to size of input tensor plus padding"
601 input_shape = op.inputs[0].shape
602 expected_output_shape = op.outputs[0].shape
603 pad_tensor = op.inputs[1].values
604 actual_output_shape = input_shape + pad_tensor.T[0] + pad_tensor.T[1]
605 valid = np.array_equal(actual_output_shape, expected_output_shape)
606 return valid, f"Op has wrong output tensor shape: {expected_output_shape}, has shape: {actual_output_shape}"
607
608 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200609 def constraint_stridedslice_inputs_const(op):
610 "Begin, End and Stride Input tensors must be constant"
611 valid = True
612 extra = []
613 _, begin, end, strides = op.inputs
614 if begin.values is None:
615 valid = False
616 extra.append(f"Begin tensor '{begin.name}'")
617 if end.values is None:
618 valid = False
619 extra.append(f"End tensor '{end.name}'")
620 if strides.values is None:
621 valid = False
622 extra.append(f"Stride tensor '{strides.name}'")
623 extra = ", ".join(extra)
624 return valid, f"Op has non-constant tensors: {extra}"
625
626 @staticmethod
627 def constraint_ellipsis_mask(op):
628 "ellipsis_mask must be 0"
629 ellipsis = op.attrs["ellipsis_mask"]
630 valid = ellipsis == 0
631 return valid, f"Op has ellipsis mask as: {ellipsis}"
632
633 @staticmethod
634 def constraint_axis_masks(op):
635 "new_axis_mask and shrink_axis_mask cannot both be set"
636 new_axis = op.attrs["new_axis_mask"]
637 shrink_axis = op.attrs["shrink_axis_mask"]
638 valid = (new_axis == 0) or (shrink_axis == 0)
639 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
640
Tim Halld0e41cf2023-02-14 14:54:18 +0000641 def _get_slice_offsets(input_shape, offset_tens, offset_mask, is_begin=True):
642 # For strided slice operator: get start or end offsets
643 # input_shape: List[int], offset_tens: Tensor, offset_mask: int, is_begin: bool = True
644 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
645 for idx in range(len(input_shape)):
646 # If the i:th bit in the mask is not set then the value in offset_tens[i] should be used, otherwise it
647 # should be ignored
648 if (offset_mask & (1 << idx)) == 0:
649 offsets[idx] = offset_tens.values[idx]
650 if offsets[idx] < 0:
651 # Convert negative indexing to positive ones
652 offsets[idx] += input_shape[idx]
653 return offsets
654
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200655 @staticmethod
656 def constraint_slice_ranges(op):
657 "Slice 'end' values must be greater than 'begin' values"
658 ifm, begin, end, _ = op.inputs
Tim Halld0e41cf2023-02-14 14:54:18 +0000659 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200660 # Calculate offset begin/end
Tim Halld0e41cf2023-02-14 14:54:18 +0000661 offset_begin = TFLiteSemantic._get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
662 offset_end = TFLiteSemantic._get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200663 # Check "end - begin" doesn't result in any zero or negative elements
Tim Halld0e41cf2023-02-14 14:54:18 +0000664 valid = True
665 # if a shrink mask bit is set then the end position provided by the operation should be ignored, and instead a
666 # new end position should be calculated so that calculations in the graph optimiser, such as (end - start),
667 # result in the correct value. otherwise, we just need to check that the begin and end values are valid
668 for i in range(len(ifm.shape)):
669 if (shrink_axis_mask & (1 << i)) != 0:
670 offset_end[i] = offset_begin[i] + 1
671 else:
672 if offset_end[i] <= offset_begin[i]:
673 valid = False
674
675 op.attrs["offset_begin"] = offset_begin
676 op.attrs["offset_end"] = offset_end
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200677 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
678
679 @staticmethod
680 def constraint_matching_inputs_types(op):
681 "Both Input data types must match"
682 ifm_dtype = op.ifm.dtype
683 ifm2_dtype = op.ifm2.dtype
684 valid = ifm_dtype == ifm2_dtype
685 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
686
687 @staticmethod
688 def constraint_matching_signed(op):
689 "For IFM that are signed, OFM must also be signed"
690 valid = True
691 ifm_dtype = op.ifm.dtype
692 ofm_dtype = op.ofm.dtype
693 if ifm_dtype.type & BaseType.Signed:
694 valid = bool(ofm_dtype.type & BaseType.Signed)
695 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
696
697 @staticmethod
698 def constraint_unsigned_valid(op):
699 "For IFM that are unsigned, OFM must either be the same type or int32"
700 valid = True
701 ifm_dtype = op.ifm.dtype
702 ofm_dtype = op.ofm.dtype
703 if ifm_dtype.type & BaseType.Unsigned:
704 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
705 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
706
707 @staticmethod
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200708 def constraint_input_signed(op):
709 "IFM must be int8 or int16"
710 ifm_dtype = op.ifm.dtype
711 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.int16)
712 return valid, f"Op has ifm_dtype={ifm_dtype}"
713
714 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200715 def constraint_input_8bit(op):
716 "IFM must be int8 or uint8"
717 ifm_dtype = op.ifm.dtype
718 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8)
719 return valid, f"Op has ifm_dtype={ifm_dtype}"
720
721 @staticmethod
Johan Alfvenc1ad80b2023-03-31 10:19:23 +0200722 def constraint_argmax_output(op):
723 "OFM must be int32 or int64"
724 ofm_dtype = op.ofm.dtype
725 valid = ofm_dtype in (DataType.int32, DataType.int64)
726 return valid, f"Op has ofm_dtype={ofm_dtype}"
727
728 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200729 def constraint_matching_either_shapes(op):
730 "At least one Input's shape must match the OFM's shape"
731 ifm_shape = op.ifm.shape
732 ifm2_shape = op.ifm2.shape if op.ifm2 else None
733 ofm_shape = op.ofm.shape
734 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
735 return valid, f"Op has ifm_shape={ifm_shape}, ifm2_shape={ifm2_shape} and ofm_shape={ofm_shape}"
736
737 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200738 def constraint_keep_dim_ifm_ofm(op):
739 "The IFM and OFM must have the same number of dimensions if keep_num_dims is set to true"
740 valid = True
741 if op.attrs.get("keep_num_dims"):
742 valid = len(op.ifm.shape) == len(op.ofm.shape)
743 return valid, f"Op has ifm shape={op.ifm.shape} and ofm shape={op.ofm.shape}"
744
745 @staticmethod
746 def constraint_mean_input_dims(op):
747 "Input tensor must be at least 2D"
748 dims = len(op.inputs[0].shape)
749 return 2 <= dims <= 4, f"Input is {dims}D"
750
751 @staticmethod
752 def constraint_mean_axis(op):
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000753 """Requirements for axis parameter:
754 When IFM tensor is 2D:
755 - Reduction in both axes is supported.
756 When IFM tensor is 3D or 4D:
757 - Reduction in Batch axis is only supported if batch size is 1.
758 - Reduction in both Height and Width axes is supported.
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000759 - Reduction in Depth axis is supported if at least one of H,W,C are of size 1."""
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000760 input_shape = op.inputs[0].shape
761 dims = len(input_shape)
762 if op.inputs[1].shape == []:
763 axis = [int(op.inputs[1].values)]
764 else:
765 axis = list(op.inputs[1].values)
766 valid = True
767
768 for ax in axis:
769 if ax < 0 or ax >= dims:
770 return False, "Axis parameter is out of bounds. axis: {axis}, dims: {dims}. "
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000771
772 # Batch is only supported if batch shape is 1
773 if dims == 4 and ax == 0:
774 if input_shape[0] != 1:
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000775 valid = False
776 break
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000777
778 # Depth is supported if any of h,w,c == 1
779 if dims == 3:
780 if ax == 2 and not any([s == 1 for s in input_shape]):
781 valid = False
782 break
783
784 # Depth is supported if any of h,w,c == 1
785 if dims == 4:
786 if ax == 3 and not any([s == 1 for s in input_shape[1:]]):
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000787 valid = False
788 break
789
790 return valid, f"Shape is {input_shape}, Axis is {axis}."
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200791
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200792 @staticmethod
793 def constraint_matching_in_out_quant(op):
794 "Input and output quantisation must match."
795 if not check_quantized_tens_scaling_equal(op.ifm, op.ofm):
796 return False, "IFM and OFM quantisation parameters are not equal."
797 return True, "IFM and OFM quantisation parameters matches."
798
Johan Alfven3ac03be2023-03-01 09:53:35 +0100799 @staticmethod
800 def constraint_matching_in_out_elements(op):
801 "Input and output number of elements must match."
802 if shape_num_elements(op.ifm.shape) != shape_num_elements(op.ofm.shape):
803 return False, f"IFM {op.ifm.shape} and OFM {op.ofm.shape} number of elements are not equal."
804 return True, "IFM and OFM number of elements are equal."
805
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200806 @staticmethod
807 def constraint_lstm_dimensions(op):
808 "IFM and OFM must have 3D shape"
809 valid = len(op.ifm.shape) == len(op.ofm.shape) == 3
810 return valid, f"Op has ifm shape {op.ifm.shape} and ofm shape {op.ofm.shape}"
811
812 @staticmethod
813 def constraint_lstm_inputs(op):
814 "Must have 24 input tensors"
815 n_inputs = len(op.inputs)
816 return n_inputs == 24, f"Op has {n_inputs} inputs"
817
818 @staticmethod
819 def constraint_lstm_intermediates(op):
820 "Must have 5 intermediate tensors"
821 n_intermediates = len(op.intermediates)
822 return n_intermediates == 5, f"Op has {n_intermediates} intermediates"
823
824 @staticmethod
825 def constraint_lstm_variables(op):
826 "State tensors must be variable"
827 valid = True
828 extra = []
829 for tens in op.inputs[18:20]:
830 if not tens.is_variable:
831 valid = False
832 extra.append(tens.name)
833 extra = ", ".join(extra)
834 return valid, f"Op has non-variable state tensor(s): {extra}"
835
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200836
837def tflite_semantic_checker(nng):
838 semantic_checker = TFLiteSemantic()
839 for sg in nng.subgraphs:
840 for op in sg.get_all_ops():
841 op.run_on_npu = semantic_checker.is_operator_semantic_valid(op)
842 return nng