blob: 0c2086c3a8a5d48571e2f2e3b339014d77104389 [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
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020030from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
31from .tflite_mapping import optype_to_builtintype
32
33
34def _optype_formatter(op_list):
35 # Convert internal op types to external names
36 output = map(optype_to_builtintype, op_list)
37 # Remove UNKNOWNs
38 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
39 return list_formatter(output)
40
41
42class TFLiteSemantic:
43 # Categorised lists of operators
Jonas Ohlssond8575072022-03-30 10:30:25 +020044 convolution_ops = set(
45 (
46 Op.Conv2DBias,
47 Op.Conv2D,
48 Op.QuantizedConv2D,
49 )
50 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020051 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
52 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
53 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
54 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
55 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
56 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
57 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020058 binary_elem_wise_min_max_ops = set(
59 (
60 Op.Minimum,
61 Op.Maximum,
62 )
63 )
64 binary_elem_wise_shift_ops = set(
65 (
66 Op.SHL,
67 Op.SHR,
68 )
69 )
70 binary_elem_wise_add_mul_sub = set(
71 (
72 Op.Add,
73 Op.Mul,
74 Op.Sub,
75 )
76 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020077 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
78 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
Fredrik Svedberg11563172022-07-06 14:54:12 +020079 shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV, Op.Mean, Op.ExpandDims, Op.Quantize))
Jonas Ohlssond8575072022-03-30 10:30:25 +020080 reshape_ops = set(
81 (
82 Op.Reshape,
83 Op.QuantizedReshape,
84 Op.Squeeze,
85 Op.ExpandDims,
86 )
87 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020088
89 def __init__(self):
90 # Setup the generic constraints. Note: the order matters
91 self.generic_constraints = []
92 self.generic_constraints.append(TFLiteSemantic.constraint_tens_no_dynamic)
93 self.generic_constraints.append(TFLiteSemantic.constraint_tens_defined_shape)
94 self.generic_constraints.append(TFLiteSemantic.constraint_tens_output_scalar)
95 self.generic_constraints.append(TFLiteSemantic.constraint_tens_input_scalar)
96 self.generic_constraints.append(TFLiteSemantic.constraint_tens_shape_size)
97
98 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_none_check)
99 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_scale)
100 self.generic_constraints.append(TFLiteSemantic.constraint_quant_scale_inf)
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100101 self.generic_constraints.append(TFLiteSemantic.constraint_none_const_tensors)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200102
103 # Setup specific constraints. Note: the order matters
104 self.specific_constraints = defaultdict(list)
105
106 # Conv-like checks:
107 for op_type in TFLiteSemantic.convolution_like_ops:
108 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
Tim Hallea4ba662022-11-11 18:19:53 +0000109 if op_type not in TFLiteSemantic.transpose_convolution_ops:
110 # Transpose Conv does not contain dilation
111 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_dilation_type)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200112
113 # Pooling checks:
114 for op_type in TFLiteSemantic.pooling_ops:
115 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
116 # AVG pooling specific checks:
117 for op_type in TFLiteSemantic.avg_pooling_ops:
118 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
119 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
120 # MAX pooling specific checks:
121 for op_type in TFLiteSemantic.max_pooling_ops:
122 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
123 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
124
125 # Concat specific checks:
126 for op_type in (Op.Concat, Op.ConcatTFLite):
127 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_exists)
128 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_valid)
129 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_dimensionality)
130 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions)
Johan Alfvénb3932512022-09-12 17:44:25 +0200131 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200132
133 # Element-wise checks:
134 for op_type in TFLiteSemantic.elem_wise_main_ops:
135 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_either_shapes)
136 # Unary specific checks:
137 for op_type in TFLiteSemantic.unary_elem_wise_main_ops:
138 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
139 # Binary Min/Max specific checks:
140 for op_type in TFLiteSemantic.binary_elem_wise_min_max_ops:
141 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
142 # Binary Add/Mul/Sub specific checks:
143 for op_type in TFLiteSemantic.binary_elem_wise_add_mul_sub:
144 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_inputs_types)
145 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_signed)
146 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_unsigned_valid)
147
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200148 # Ops reshaping dimensions: Reshape, Squeeze and ExpandDims
149 for op_type in TFLiteSemantic.reshape_ops:
150 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_quant)
151
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200152 # Softmax specific checks:
153 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_shapes)
154 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_in_out_types)
155 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_beta_value_range)
156
Johan Alfven12e48112023-01-31 10:26:26 +0100157 # Split specific checks:
158 self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_axis)
159 self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_num_splits)
160
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200161 # SplitV specific checks:
162 self.specific_constraints[Op.SplitV].append(TFLiteSemantic.constraint_splitv_inferred)
163
164 # StridedSlice specific checks:
165 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_input_count)
166 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_inputs_const)
167 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_ellipsis_mask)
168 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_axis_masks)
169 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_slice_ranges)
170
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200171 # FullyConnected specific checks:
172 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_fc_output_2d)
173 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_keep_dim_ifm_ofm)
174
175 # Pad specific checks:
176 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_input_count)
177 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_constant)
178
179 # HardSwish specific checks:
180 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_input_8bit)
181 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_matching_in_out_types)
Fredrik Svedberg701ba912022-09-07 16:01:15 +0200182
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200183 # Mean specific checks:
184 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_input_8bit)
185 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_input_dims)
186 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_axis)
187
188 def is_operator_semantic_valid(self, op):
189 ext_type = optype_to_builtintype(op.type)
190
191 if op.type in (Op.Placeholder, Op.SubgraphInput, Op.Const):
192 return True
193
Ayaan Masood4965fae2022-06-29 11:30:57 +0100194 # Generic constraints list filtered out to exclude certain constraints depending on op.type
195 filtered_generic_constraints = []
196
197 for constraint in self.generic_constraints:
198 # Check constraint not in dictionary otherwise return empty array
199 if constraint not in self.get_generic_constraint_exclude_list().get(op.type, []):
200 filtered_generic_constraints.append(constraint)
201
202 for constraint in filtered_generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200203 valid, extra = constraint(op)
204 if not valid:
205 print(
Tim Hall3584a9c2021-11-18 22:05:17 +0000206 f"Warning: Unsupported TensorFlow Lite semantics for {ext_type} '{op.name}'. Placing on CPU instead"
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200207 )
208 print(f" - {constraint.__doc__}")
209 if extra:
210 print(f" {extra}")
211 return False
212
213 return True
214
215 @staticmethod
Ayaan Masood4965fae2022-06-29 11:30:57 +0100216 def get_generic_constraint_exclude_list():
217
218 # Not all generic constraints can be applied to each operator
219 generic_constraints_exclude_list = {
220 Op.Shape: [
221 TFLiteSemantic.constraint_tens_quant_none_check,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100222 ],
223 Op.Quantize: [
224 TFLiteSemantic.constraint_tens_no_dynamic,
225 TFLiteSemantic.constraint_tens_output_scalar,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100226 ],
Ayaan Masood4965fae2022-06-29 11:30:57 +0100227 }
228 return generic_constraints_exclude_list
229
230 @staticmethod
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100231 def constraint_none_const_tensors(op):
232 "Constant tensors should not have NoneType-values"
233 valid = True
234 extra = ""
235 for tens in filter(None, op.inputs):
236 if len(tens.ops) > 0 and tens.ops[0].type == Op.Const and tens.values is None:
237 valid = False
238 extra = str(tens.name)
239 return valid, f"Unexpected None value for constant tensor: {extra}"
240
241 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200242 def constraint_tens_no_dynamic(op):
243 "Input(s) and Output tensors must not be dynamic"
244 valid = True
245 extra = []
246 tensors = [tens for tens in op.inputs + op.outputs if tens]
247 for tens in tensors:
248 if (tens.shape == []) and (tens.values is None):
249 valid = False
250 extra.append(tens.name)
251 extra = ", ".join(extra)
252 return valid, f"Op has dynamic tensor(s): {extra}"
253
254 @staticmethod
255 def constraint_tens_defined_shape(op):
256 "Input(s) and Output tensors must have a defined shape"
257 valid = True
258 extra = []
259 tensors = [tens for tens in op.inputs + op.outputs if tens]
260 for tens in tensors:
261 if not tens.has_fully_defined_shape():
262 valid = False
263 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
264 return valid, ", ".join(extra)
265
266 @staticmethod
267 def constraint_tens_output_scalar(op):
268 "Output tensors cannot be scalar"
269 ofm = op.ofm
270 valid = ofm.shape != []
271 return valid, f"Output Tensor '{ofm.name}' is scalar"
272
273 @classmethod
274 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
275 def constraint_tens_input_scalar(cls, op):
276 "Scalar Input tensors are only valid for op type: {}"
277 valid = True
278 extra = []
279 tensors = [tens for tens in op.inputs if tens]
280 for tens in tensors:
281 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
282 valid = False
283 extra.append(tens.name)
284 extra = ", ".join(extra)
285 return valid, f"Op has scalar input tensor(s): {extra}"
286
287 @staticmethod
288 def constraint_tens_shape_size(op):
289 "Input(s) and Output tensors must not be greater than 4D"
290 valid = True
291 extra = []
292 tensors = [tens for tens in op.inputs + op.outputs if tens]
293 for tens in tensors:
294 if len(tens.shape) > 4:
295 valid = False
296 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
297 return valid, ", ".join(extra)
298
299 @staticmethod
300 def constraint_tens_quant_none_check(op):
301 "Input(s), Output and Weight tensors must have quantization parameters"
302 valid = True
303 extra = []
304 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
305 for tens in tensors:
306 if tens.quantization is None:
307 valid = False
308 extra.append(tens.name)
309 extra = ", ".join(extra)
310 return valid, f"Op has tensors with missing quantization parameters: {extra}"
311
312 @staticmethod
313 def constraint_tens_quant_scale(op):
314 "Input(s), Output and Weight tensors with quantization scales must be finite"
315 valid = True
316 extra = []
317 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
318 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200319 if (
320 tens.quantization
321 and tens.quantization.scale_f32 is not None
322 and np.isinf(tens.quantization.scale_f32).any()
323 ):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200324 valid = False
325 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
326 return valid, ", ".join(extra)
327
328 @staticmethod
329 def constraint_fc_output_2d(op):
Ayaan Masooda2ec5aa2022-04-21 14:28:03 +0100330 """The output tensor(s) must have 2D shape"""
331 valid = op.ifm.get_shape_as_2d(op.weights.shape[-2]) is not None
332 extra = f"Op has non-2D output tensor '{op.ofm.name}'" if not valid else ""
333
334 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200335
336 @staticmethod
337 def constraint_stride_type(op):
338 "Stride values for both width and height must be integer types"
339 w, h = op.get_kernel_stride()
340 valid = is_integer(w) and is_integer(h)
341 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
342
343 @staticmethod
344 def constraint_dilation_type(op):
345 "Dilation factor values for both width and height must be integer types"
346 w, h = op.get_kernel_dilation()
347 valid = is_integer(w) and is_integer(h)
348 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
349
350 @staticmethod
351 def constraint_quant_scale_inf(op):
352 "Input and Output tensors must have quantization scales that fit within float32 precision"
353 if op.ofm is not None and op.ofm.is_quantized():
354 ofm_scale = op.ofm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200355 if np.any(ofm_scale < np.finfo(np.float32).tiny):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200356 return (
357 False,
358 f"The quantization scale of the output tensor is {ofm_scale}, "
359 + f"minimum supported is: {np.finfo(np.float32).tiny}",
360 )
361 if op.ifm is not None and op.ifm.is_quantized():
362 ifm_scale = op.ifm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200363 if np.any(np.isinf(ifm_scale / ofm_scale)):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200364 return (
365 False,
366 f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}",
367 )
368 return True, "Op's quantization is ok"
369
370 @staticmethod
371 def constraint_matching_in_out_types(op):
372 "IFM and OFM data types must match"
373 ifm_dtype = op.ifm.dtype
374 ofm_dtype = op.ofm.dtype
375 valid = ifm_dtype == ofm_dtype
376 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
377
378 @staticmethod
379 def constraint_beta_value_range(op):
380 "Beta value needs to be positive"
381 beta = op.attrs.get("beta", 1.0)
382 valid = beta >= 0
383 return valid, f"Op has beta={beta}"
384
385 @staticmethod
386 def constraint_filter_type(op):
387 "Kernel filter values for both width and height must be integer types"
388 w = op.kernel.width
389 h = op.kernel.height
390 valid = is_integer(w) and is_integer(h)
391 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
392
393 @staticmethod
394 def constraint_matching_shapes(op):
395 "IFM and OFM shapes must match"
396 ifm_shape = op.ifm.shape
397 ofm_shape = op.ofm.shape
398 valid = ifm_shape == ofm_shape
399 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
400
401 @staticmethod
Johan Alfven12e48112023-01-31 10:26:26 +0100402 def constraint_split_axis(op):
403 "Axis value must be in the range [-RANK(IFM) to +RANK(IFM))"
404 axis_tens = op.inputs[0]
405 input_tens = op.inputs[1]
406 dims = len(input_tens.shape)
407 axis = int(axis_tens.values)
408 axis += dims if axis < 0 else 0
409 valid = 0 <= axis < dims
410 return valid, f"Op has ifm_dimensions={dims} and axis value is: {axis}"
411
412 @staticmethod
413 def constraint_split_num_splits(op):
414 "Axis must be divisible by number of splits"
415 num_splits = op.attrs.get("num_splits")
416 axis_tens = op.inputs[0]
417 input_tens = op.inputs[1]
418 dims = len(input_tens.shape)
419 axis = int(axis_tens.values)
420 axis += dims if axis < 0 else 0
421 valid = input_tens.shape[axis] % num_splits == 0
422 return valid, f"Op has ifm shape={input_tens.shape} axis={axis} num_splits={num_splits}"
423
424 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200425 def constraint_splitv_inferred(op):
426 "Only one size is allowed to be inferred"
427 sizes = op.inputs[1].values
428 valid = np.count_nonzero(sizes == -1) <= 1
429 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
430
431 @staticmethod
432 def constraint_axis_exists(op):
433 "Axis attribute must exist"
434 axis = op.attrs.get("axis")
435 valid = axis is not None
436 return valid, f"Op has axis={axis}"
437
438 @staticmethod
439 def constraint_axis_valid(op):
440 "Axis attribute must be in the range [0, <ofm_dimensions>)"
441 dims = len(op.ofm.shape)
442 axis = op.attrs["axis"]
443 axis += dims if axis < 0 else 0
444 valid = 0 <= axis < dims
445 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
446
447 @staticmethod
448 def constraint_matching_dimensionality(op):
449 "All Input dimensionalities must match OFM dimensionality"
450 valid = True
451 extra = []
452 ofm_dim = len(op.ofm.shape)
453 tensors = [tens for tens in op.inputs if tens]
454 for tens in tensors:
455 dim = len(tens.shape)
456 if dim != ofm_dim:
457 valid = False
458 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
459 extra = ", ".join(extra)
460 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
461
462 @staticmethod
463 def constraint_valid_dimensions(op):
464 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
465 valid = True
466 extra = []
467 ofm_shape = op.ofm.shape
468 ofm_dim = len(ofm_shape)
469 axis = op.attrs["axis"]
470 axis += ofm_dim if axis < 0 else 0
471 tensors = [tens for tens in op.inputs if tens]
472 for tens in tensors:
473 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
474 valid = False
475 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
476 extra = ", ".join(extra)
477 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
478
479 @staticmethod
Johan Alfvénb3932512022-09-12 17:44:25 +0200480 def constraint_valid_dimensions_axis(op):
481 """The size of the OFM axis must match the sum of all IFM axis defined by the axis attribute"""
482 valid = True
483 extra = []
484 ofm_shape = op.ofm.shape
485 ofm_dim = len(ofm_shape)
486 axis = op.attrs["axis"]
487 axis += ofm_dim if axis < 0 else 0
488
489 sum_ifm_axis = 0
490 tensors = [tens for tens in op.inputs if tens]
491 for tens in tensors:
492 sum_ifm_axis += tens.shape[axis]
493 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
494
495 valid = sum_ifm_axis == ofm_shape[axis]
496 extra = ", ".join(extra)
497 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
498
499 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200500 def constraint_stridedslice_input_count(op):
501 "Exactly 4 Input tensors are required"
502 inputs = len(op.inputs)
503 valid = inputs == 4
504 return valid, f"Op has {inputs} inputs"
505
506 @staticmethod
507 def constraint_pad_input_count(op):
508 "Number of input tensors must be exactly 2"
509 inputs = len(op.inputs)
510 valid = inputs == 2
511 return valid, f"Op has {inputs} inputs"
512
513 @staticmethod
514 def constraint_pad_constant(op):
515 "The padding tensor must be constant"
516 pad_tensor = op.inputs[1].values
517 valid = pad_tensor is not None
518 return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}"
519
520 @staticmethod
521 def constraint_stridedslice_inputs_const(op):
522 "Begin, End and Stride Input tensors must be constant"
523 valid = True
524 extra = []
525 _, begin, end, strides = op.inputs
526 if begin.values is None:
527 valid = False
528 extra.append(f"Begin tensor '{begin.name}'")
529 if end.values is None:
530 valid = False
531 extra.append(f"End tensor '{end.name}'")
532 if strides.values is None:
533 valid = False
534 extra.append(f"Stride tensor '{strides.name}'")
535 extra = ", ".join(extra)
536 return valid, f"Op has non-constant tensors: {extra}"
537
538 @staticmethod
539 def constraint_ellipsis_mask(op):
540 "ellipsis_mask must be 0"
541 ellipsis = op.attrs["ellipsis_mask"]
542 valid = ellipsis == 0
543 return valid, f"Op has ellipsis mask as: {ellipsis}"
544
545 @staticmethod
546 def constraint_axis_masks(op):
547 "new_axis_mask and shrink_axis_mask cannot both be set"
548 new_axis = op.attrs["new_axis_mask"]
549 shrink_axis = op.attrs["shrink_axis_mask"]
550 valid = (new_axis == 0) or (shrink_axis == 0)
551 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
552
Tim Halld0e41cf2023-02-14 14:54:18 +0000553 def _get_slice_offsets(input_shape, offset_tens, offset_mask, is_begin=True):
554 # For strided slice operator: get start or end offsets
555 # input_shape: List[int], offset_tens: Tensor, offset_mask: int, is_begin: bool = True
556 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
557 for idx in range(len(input_shape)):
558 # If the i:th bit in the mask is not set then the value in offset_tens[i] should be used, otherwise it
559 # should be ignored
560 if (offset_mask & (1 << idx)) == 0:
561 offsets[idx] = offset_tens.values[idx]
562 if offsets[idx] < 0:
563 # Convert negative indexing to positive ones
564 offsets[idx] += input_shape[idx]
565 return offsets
566
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200567 @staticmethod
568 def constraint_slice_ranges(op):
569 "Slice 'end' values must be greater than 'begin' values"
570 ifm, begin, end, _ = op.inputs
Tim Halld0e41cf2023-02-14 14:54:18 +0000571 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200572 # Calculate offset begin/end
Tim Halld0e41cf2023-02-14 14:54:18 +0000573 offset_begin = TFLiteSemantic._get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
574 offset_end = TFLiteSemantic._get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200575 # Check "end - begin" doesn't result in any zero or negative elements
Tim Halld0e41cf2023-02-14 14:54:18 +0000576 valid = True
577 # if a shrink mask bit is set then the end position provided by the operation should be ignored, and instead a
578 # new end position should be calculated so that calculations in the graph optimiser, such as (end - start),
579 # result in the correct value. otherwise, we just need to check that the begin and end values are valid
580 for i in range(len(ifm.shape)):
581 if (shrink_axis_mask & (1 << i)) != 0:
582 offset_end[i] = offset_begin[i] + 1
583 else:
584 if offset_end[i] <= offset_begin[i]:
585 valid = False
586
587 op.attrs["offset_begin"] = offset_begin
588 op.attrs["offset_end"] = offset_end
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200589 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
590
591 @staticmethod
592 def constraint_matching_inputs_types(op):
593 "Both Input data types must match"
594 ifm_dtype = op.ifm.dtype
595 ifm2_dtype = op.ifm2.dtype
596 valid = ifm_dtype == ifm2_dtype
597 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
598
599 @staticmethod
600 def constraint_matching_signed(op):
601 "For IFM that are signed, OFM must also be signed"
602 valid = True
603 ifm_dtype = op.ifm.dtype
604 ofm_dtype = op.ofm.dtype
605 if ifm_dtype.type & BaseType.Signed:
606 valid = bool(ofm_dtype.type & BaseType.Signed)
607 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
608
609 @staticmethod
610 def constraint_unsigned_valid(op):
611 "For IFM that are unsigned, OFM must either be the same type or int32"
612 valid = True
613 ifm_dtype = op.ifm.dtype
614 ofm_dtype = op.ofm.dtype
615 if ifm_dtype.type & BaseType.Unsigned:
616 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
617 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
618
619 @staticmethod
620 def constraint_input_8bit(op):
621 "IFM must be int8 or uint8"
622 ifm_dtype = op.ifm.dtype
623 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8)
624 return valid, f"Op has ifm_dtype={ifm_dtype}"
625
626 @staticmethod
627 def constraint_matching_either_shapes(op):
628 "At least one Input's shape must match the OFM's shape"
629 ifm_shape = op.ifm.shape
630 ifm2_shape = op.ifm2.shape if op.ifm2 else None
631 ofm_shape = op.ofm.shape
632 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
633 return valid, f"Op has ifm_shape={ifm_shape}, ifm2_shape={ifm2_shape} and ofm_shape={ofm_shape}"
634
635 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200636 def constraint_keep_dim_ifm_ofm(op):
637 "The IFM and OFM must have the same number of dimensions if keep_num_dims is set to true"
638 valid = True
639 if op.attrs.get("keep_num_dims"):
640 valid = len(op.ifm.shape) == len(op.ofm.shape)
641 return valid, f"Op has ifm shape={op.ifm.shape} and ofm shape={op.ofm.shape}"
642
643 @staticmethod
644 def constraint_mean_input_dims(op):
645 "Input tensor must be at least 2D"
646 dims = len(op.inputs[0].shape)
647 return 2 <= dims <= 4, f"Input is {dims}D"
648
649 @staticmethod
650 def constraint_mean_axis(op):
651 "Axis indices must correspond to height and width axes"
652 dims = len(op.inputs[0].shape)
653 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
654 if dims == 2 or dims == 3:
655 valid = axis in (0, 1, [0], [1], [0, 1], [1, 0])
656 elif dims == 4:
657 valid = axis in (1, 2, [1], [2], [1, 2], [2, 1])
658 return valid, f"Axis is {axis}"
659
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200660 @staticmethod
661 def constraint_matching_in_out_quant(op):
662 "Input and output quantisation must match."
663 if not check_quantized_tens_scaling_equal(op.ifm, op.ofm):
664 return False, "IFM and OFM quantisation parameters are not equal."
665 return True, "IFM and OFM quantisation parameters matches."
666
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200667
668def tflite_semantic_checker(nng):
669 semantic_checker = TFLiteSemantic()
670 for sg in nng.subgraphs:
671 for op in sg.get_all_ops():
672 op.run_on_npu = semantic_checker.is_operator_semantic_valid(op)
673 return nng