blob: 495d71a6d144eb678402820696c0a57754708c9f [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
79 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
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 = []
95 self.generic_constraints.append(TFLiteSemantic.constraint_tens_no_dynamic)
96 self.generic_constraints.append(TFLiteSemantic.constraint_tens_defined_shape)
97 self.generic_constraints.append(TFLiteSemantic.constraint_tens_output_scalar)
98 self.generic_constraints.append(TFLiteSemantic.constraint_tens_input_scalar)
99 self.generic_constraints.append(TFLiteSemantic.constraint_tens_shape_size)
100
101 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_none_check)
102 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_scale)
103 self.generic_constraints.append(TFLiteSemantic.constraint_quant_scale_inf)
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100104 self.generic_constraints.append(TFLiteSemantic.constraint_none_const_tensors)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200105
106 # Setup specific constraints. Note: the order matters
107 self.specific_constraints = defaultdict(list)
108
109 # Conv-like checks:
110 for op_type in TFLiteSemantic.convolution_like_ops:
111 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
Tim Hallea4ba662022-11-11 18:19:53 +0000112 if op_type not in TFLiteSemantic.transpose_convolution_ops:
113 # Transpose Conv does not contain dilation
114 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_dilation_type)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200115
116 # Pooling checks:
117 for op_type in TFLiteSemantic.pooling_ops:
118 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
119 # AVG pooling specific checks:
120 for op_type in TFLiteSemantic.avg_pooling_ops:
121 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
122 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
123 # MAX pooling specific checks:
124 for op_type in TFLiteSemantic.max_pooling_ops:
125 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
126 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
127
128 # Concat specific checks:
129 for op_type in (Op.Concat, Op.ConcatTFLite):
130 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_exists)
131 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_valid)
132 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_dimensionality)
133 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions)
Johan Alfvénb3932512022-09-12 17:44:25 +0200134 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200135
136 # Element-wise checks:
137 for op_type in TFLiteSemantic.elem_wise_main_ops:
138 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_either_shapes)
139 # Unary specific checks:
140 for op_type in TFLiteSemantic.unary_elem_wise_main_ops:
141 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
142 # Binary Min/Max specific checks:
143 for op_type in TFLiteSemantic.binary_elem_wise_min_max_ops:
144 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
145 # Binary Add/Mul/Sub specific checks:
146 for op_type in TFLiteSemantic.binary_elem_wise_add_mul_sub:
147 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_inputs_types)
148 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_signed)
149 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_unsigned_valid)
150
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200151 # Ops reshaping dimensions: Reshape, Squeeze and ExpandDims
152 for op_type in TFLiteSemantic.reshape_ops:
153 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_quant)
Johan Alfven3ac03be2023-03-01 09:53:35 +0100154 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_elements)
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200155
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200156 # Softmax specific checks:
157 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_shapes)
158 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_in_out_types)
159 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_beta_value_range)
160
Johan Alfven12e48112023-01-31 10:26:26 +0100161 # Split specific checks:
162 self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_axis)
163 self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_num_splits)
164
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200165 # SplitV specific checks:
166 self.specific_constraints[Op.SplitV].append(TFLiteSemantic.constraint_splitv_inferred)
167
168 # StridedSlice specific checks:
169 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_input_count)
170 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_inputs_const)
171 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_ellipsis_mask)
172 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_axis_masks)
173 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_slice_ranges)
174
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200175 # FullyConnected specific checks:
176 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_fc_output_2d)
177 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_keep_dim_ifm_ofm)
178
179 # Pad specific checks:
180 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_input_count)
181 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_constant)
182
183 # HardSwish specific checks:
184 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_input_8bit)
185 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_matching_in_out_types)
Fredrik Svedberg701ba912022-09-07 16:01:15 +0200186
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200187 # Mean specific checks:
188 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_input_8bit)
189 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_input_dims)
190 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_axis)
191
Rickard Bolin6986a072022-12-19 12:33:40 +0000192 # ArgMax specific checks:
193 self.specific_constraints[Op.ArgMax].append(TFLiteSemantic.constraint_input_8bit)
194
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200195 def is_operator_semantic_valid(self, op):
196 ext_type = optype_to_builtintype(op.type)
197
198 if op.type in (Op.Placeholder, Op.SubgraphInput, Op.Const):
199 return True
200
Ayaan Masood4965fae2022-06-29 11:30:57 +0100201 # Generic constraints list filtered out to exclude certain constraints depending on op.type
202 filtered_generic_constraints = []
203
204 for constraint in self.generic_constraints:
205 # Check constraint not in dictionary otherwise return empty array
206 if constraint not in self.get_generic_constraint_exclude_list().get(op.type, []):
207 filtered_generic_constraints.append(constraint)
208
209 for constraint in filtered_generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200210 valid, extra = constraint(op)
211 if not valid:
212 print(
Tim Hall3584a9c2021-11-18 22:05:17 +0000213 f"Warning: Unsupported TensorFlow Lite semantics for {ext_type} '{op.name}'. Placing on CPU instead"
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200214 )
215 print(f" - {constraint.__doc__}")
216 if extra:
217 print(f" {extra}")
218 return False
219
220 return True
221
222 @staticmethod
Ayaan Masood4965fae2022-06-29 11:30:57 +0100223 def get_generic_constraint_exclude_list():
224
225 # Not all generic constraints can be applied to each operator
226 generic_constraints_exclude_list = {
227 Op.Shape: [
228 TFLiteSemantic.constraint_tens_quant_none_check,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100229 ],
230 Op.Quantize: [
231 TFLiteSemantic.constraint_tens_no_dynamic,
232 TFLiteSemantic.constraint_tens_output_scalar,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100233 ],
Rickard Bolin6986a072022-12-19 12:33:40 +0000234 Op.ArgMax: [
235 TFLiteSemantic.constraint_tens_quant_none_check,
236 ],
Ayaan Masood4965fae2022-06-29 11:30:57 +0100237 }
238 return generic_constraints_exclude_list
239
240 @staticmethod
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100241 def constraint_none_const_tensors(op):
242 "Constant tensors should not have NoneType-values"
243 valid = True
244 extra = ""
245 for tens in filter(None, op.inputs):
246 if len(tens.ops) > 0 and tens.ops[0].type == Op.Const and tens.values is None:
247 valid = False
248 extra = str(tens.name)
249 return valid, f"Unexpected None value for constant tensor: {extra}"
250
251 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200252 def constraint_tens_no_dynamic(op):
253 "Input(s) and Output tensors must not be dynamic"
254 valid = True
255 extra = []
256 tensors = [tens for tens in op.inputs + op.outputs if tens]
257 for tens in tensors:
258 if (tens.shape == []) and (tens.values is None):
259 valid = False
260 extra.append(tens.name)
261 extra = ", ".join(extra)
262 return valid, f"Op has dynamic tensor(s): {extra}"
263
264 @staticmethod
265 def constraint_tens_defined_shape(op):
266 "Input(s) and Output tensors must have a defined shape"
267 valid = True
268 extra = []
269 tensors = [tens for tens in op.inputs + op.outputs if tens]
270 for tens in tensors:
271 if not tens.has_fully_defined_shape():
272 valid = False
273 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
274 return valid, ", ".join(extra)
275
276 @staticmethod
277 def constraint_tens_output_scalar(op):
278 "Output tensors cannot be scalar"
279 ofm = op.ofm
280 valid = ofm.shape != []
281 return valid, f"Output Tensor '{ofm.name}' is scalar"
282
283 @classmethod
284 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
285 def constraint_tens_input_scalar(cls, op):
286 "Scalar Input tensors are only valid for op type: {}"
287 valid = True
288 extra = []
289 tensors = [tens for tens in op.inputs if tens]
290 for tens in tensors:
291 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
292 valid = False
293 extra.append(tens.name)
294 extra = ", ".join(extra)
295 return valid, f"Op has scalar input tensor(s): {extra}"
296
297 @staticmethod
298 def constraint_tens_shape_size(op):
299 "Input(s) and Output tensors must not be greater than 4D"
300 valid = True
301 extra = []
302 tensors = [tens for tens in op.inputs + op.outputs if tens]
303 for tens in tensors:
304 if len(tens.shape) > 4:
305 valid = False
306 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
307 return valid, ", ".join(extra)
308
309 @staticmethod
310 def constraint_tens_quant_none_check(op):
311 "Input(s), Output and Weight tensors must have quantization parameters"
312 valid = True
313 extra = []
314 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
315 for tens in tensors:
316 if tens.quantization is None:
317 valid = False
318 extra.append(tens.name)
319 extra = ", ".join(extra)
320 return valid, f"Op has tensors with missing quantization parameters: {extra}"
321
322 @staticmethod
323 def constraint_tens_quant_scale(op):
324 "Input(s), Output and Weight tensors with quantization scales must be finite"
325 valid = True
326 extra = []
327 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
328 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200329 if (
330 tens.quantization
331 and tens.quantization.scale_f32 is not None
332 and np.isinf(tens.quantization.scale_f32).any()
333 ):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200334 valid = False
335 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
336 return valid, ", ".join(extra)
337
338 @staticmethod
339 def constraint_fc_output_2d(op):
Ayaan Masooda2ec5aa2022-04-21 14:28:03 +0100340 """The output tensor(s) must have 2D shape"""
341 valid = op.ifm.get_shape_as_2d(op.weights.shape[-2]) is not None
342 extra = f"Op has non-2D output tensor '{op.ofm.name}'" if not valid else ""
343
344 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200345
346 @staticmethod
347 def constraint_stride_type(op):
348 "Stride values for both width and height must be integer types"
349 w, h = op.get_kernel_stride()
350 valid = is_integer(w) and is_integer(h)
351 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
352
353 @staticmethod
354 def constraint_dilation_type(op):
355 "Dilation factor values for both width and height must be integer types"
356 w, h = op.get_kernel_dilation()
357 valid = is_integer(w) and is_integer(h)
358 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
359
360 @staticmethod
361 def constraint_quant_scale_inf(op):
362 "Input and Output tensors must have quantization scales that fit within float32 precision"
363 if op.ofm is not None and op.ofm.is_quantized():
364 ofm_scale = op.ofm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200365 if np.any(ofm_scale < np.finfo(np.float32).tiny):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200366 return (
367 False,
368 f"The quantization scale of the output tensor is {ofm_scale}, "
369 + f"minimum supported is: {np.finfo(np.float32).tiny}",
370 )
371 if op.ifm is not None and op.ifm.is_quantized():
372 ifm_scale = op.ifm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200373 if np.any(np.isinf(ifm_scale / ofm_scale)):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200374 return (
375 False,
376 f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}",
377 )
378 return True, "Op's quantization is ok"
379
380 @staticmethod
381 def constraint_matching_in_out_types(op):
382 "IFM and OFM data types must match"
383 ifm_dtype = op.ifm.dtype
384 ofm_dtype = op.ofm.dtype
385 valid = ifm_dtype == ofm_dtype
386 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
387
388 @staticmethod
389 def constraint_beta_value_range(op):
390 "Beta value needs to be positive"
391 beta = op.attrs.get("beta", 1.0)
392 valid = beta >= 0
393 return valid, f"Op has beta={beta}"
394
395 @staticmethod
396 def constraint_filter_type(op):
397 "Kernel filter values for both width and height must be integer types"
398 w = op.kernel.width
399 h = op.kernel.height
400 valid = is_integer(w) and is_integer(h)
401 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
402
403 @staticmethod
404 def constraint_matching_shapes(op):
405 "IFM and OFM shapes must match"
406 ifm_shape = op.ifm.shape
407 ofm_shape = op.ofm.shape
408 valid = ifm_shape == ofm_shape
409 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
410
411 @staticmethod
Johan Alfven12e48112023-01-31 10:26:26 +0100412 def constraint_split_axis(op):
413 "Axis value must be in the range [-RANK(IFM) to +RANK(IFM))"
414 axis_tens = op.inputs[0]
415 input_tens = op.inputs[1]
416 dims = len(input_tens.shape)
417 axis = int(axis_tens.values)
418 axis += dims if axis < 0 else 0
419 valid = 0 <= axis < dims
420 return valid, f"Op has ifm_dimensions={dims} and axis value is: {axis}"
421
422 @staticmethod
423 def constraint_split_num_splits(op):
424 "Axis must be divisible by number of splits"
425 num_splits = op.attrs.get("num_splits")
426 axis_tens = op.inputs[0]
427 input_tens = op.inputs[1]
428 dims = len(input_tens.shape)
429 axis = int(axis_tens.values)
430 axis += dims if axis < 0 else 0
431 valid = input_tens.shape[axis] % num_splits == 0
432 return valid, f"Op has ifm shape={input_tens.shape} axis={axis} num_splits={num_splits}"
433
434 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200435 def constraint_splitv_inferred(op):
436 "Only one size is allowed to be inferred"
437 sizes = op.inputs[1].values
438 valid = np.count_nonzero(sizes == -1) <= 1
439 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
440
441 @staticmethod
442 def constraint_axis_exists(op):
443 "Axis attribute must exist"
444 axis = op.attrs.get("axis")
445 valid = axis is not None
446 return valid, f"Op has axis={axis}"
447
448 @staticmethod
449 def constraint_axis_valid(op):
450 "Axis attribute must be in the range [0, <ofm_dimensions>)"
451 dims = len(op.ofm.shape)
452 axis = op.attrs["axis"]
453 axis += dims if axis < 0 else 0
454 valid = 0 <= axis < dims
455 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
456
457 @staticmethod
458 def constraint_matching_dimensionality(op):
459 "All Input dimensionalities must match OFM dimensionality"
460 valid = True
461 extra = []
462 ofm_dim = len(op.ofm.shape)
463 tensors = [tens for tens in op.inputs if tens]
464 for tens in tensors:
465 dim = len(tens.shape)
466 if dim != ofm_dim:
467 valid = False
468 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
469 extra = ", ".join(extra)
470 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
471
472 @staticmethod
473 def constraint_valid_dimensions(op):
474 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
475 valid = True
476 extra = []
477 ofm_shape = op.ofm.shape
478 ofm_dim = len(ofm_shape)
479 axis = op.attrs["axis"]
480 axis += ofm_dim if axis < 0 else 0
481 tensors = [tens for tens in op.inputs if tens]
482 for tens in tensors:
483 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
484 valid = False
485 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
486 extra = ", ".join(extra)
487 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
488
489 @staticmethod
Johan Alfvénb3932512022-09-12 17:44:25 +0200490 def constraint_valid_dimensions_axis(op):
491 """The size of the OFM axis must match the sum of all IFM axis defined by the axis attribute"""
492 valid = True
493 extra = []
494 ofm_shape = op.ofm.shape
495 ofm_dim = len(ofm_shape)
496 axis = op.attrs["axis"]
497 axis += ofm_dim if axis < 0 else 0
498
499 sum_ifm_axis = 0
500 tensors = [tens for tens in op.inputs if tens]
501 for tens in tensors:
502 sum_ifm_axis += tens.shape[axis]
503 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
504
505 valid = sum_ifm_axis == ofm_shape[axis]
506 extra = ", ".join(extra)
507 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
508
509 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200510 def constraint_stridedslice_input_count(op):
511 "Exactly 4 Input tensors are required"
512 inputs = len(op.inputs)
513 valid = inputs == 4
514 return valid, f"Op has {inputs} inputs"
515
516 @staticmethod
517 def constraint_pad_input_count(op):
518 "Number of input tensors must be exactly 2"
519 inputs = len(op.inputs)
520 valid = inputs == 2
521 return valid, f"Op has {inputs} inputs"
522
523 @staticmethod
524 def constraint_pad_constant(op):
525 "The padding tensor must be constant"
526 pad_tensor = op.inputs[1].values
527 valid = pad_tensor is not None
528 return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}"
529
530 @staticmethod
531 def constraint_stridedslice_inputs_const(op):
532 "Begin, End and Stride Input tensors must be constant"
533 valid = True
534 extra = []
535 _, begin, end, strides = op.inputs
536 if begin.values is None:
537 valid = False
538 extra.append(f"Begin tensor '{begin.name}'")
539 if end.values is None:
540 valid = False
541 extra.append(f"End tensor '{end.name}'")
542 if strides.values is None:
543 valid = False
544 extra.append(f"Stride tensor '{strides.name}'")
545 extra = ", ".join(extra)
546 return valid, f"Op has non-constant tensors: {extra}"
547
548 @staticmethod
549 def constraint_ellipsis_mask(op):
550 "ellipsis_mask must be 0"
551 ellipsis = op.attrs["ellipsis_mask"]
552 valid = ellipsis == 0
553 return valid, f"Op has ellipsis mask as: {ellipsis}"
554
555 @staticmethod
556 def constraint_axis_masks(op):
557 "new_axis_mask and shrink_axis_mask cannot both be set"
558 new_axis = op.attrs["new_axis_mask"]
559 shrink_axis = op.attrs["shrink_axis_mask"]
560 valid = (new_axis == 0) or (shrink_axis == 0)
561 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
562
Tim Halld0e41cf2023-02-14 14:54:18 +0000563 def _get_slice_offsets(input_shape, offset_tens, offset_mask, is_begin=True):
564 # For strided slice operator: get start or end offsets
565 # input_shape: List[int], offset_tens: Tensor, offset_mask: int, is_begin: bool = True
566 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
567 for idx in range(len(input_shape)):
568 # If the i:th bit in the mask is not set then the value in offset_tens[i] should be used, otherwise it
569 # should be ignored
570 if (offset_mask & (1 << idx)) == 0:
571 offsets[idx] = offset_tens.values[idx]
572 if offsets[idx] < 0:
573 # Convert negative indexing to positive ones
574 offsets[idx] += input_shape[idx]
575 return offsets
576
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200577 @staticmethod
578 def constraint_slice_ranges(op):
579 "Slice 'end' values must be greater than 'begin' values"
580 ifm, begin, end, _ = op.inputs
Tim Halld0e41cf2023-02-14 14:54:18 +0000581 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200582 # Calculate offset begin/end
Tim Halld0e41cf2023-02-14 14:54:18 +0000583 offset_begin = TFLiteSemantic._get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
584 offset_end = TFLiteSemantic._get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200585 # Check "end - begin" doesn't result in any zero or negative elements
Tim Halld0e41cf2023-02-14 14:54:18 +0000586 valid = True
587 # if a shrink mask bit is set then the end position provided by the operation should be ignored, and instead a
588 # new end position should be calculated so that calculations in the graph optimiser, such as (end - start),
589 # result in the correct value. otherwise, we just need to check that the begin and end values are valid
590 for i in range(len(ifm.shape)):
591 if (shrink_axis_mask & (1 << i)) != 0:
592 offset_end[i] = offset_begin[i] + 1
593 else:
594 if offset_end[i] <= offset_begin[i]:
595 valid = False
596
597 op.attrs["offset_begin"] = offset_begin
598 op.attrs["offset_end"] = offset_end
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200599 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
600
601 @staticmethod
602 def constraint_matching_inputs_types(op):
603 "Both Input data types must match"
604 ifm_dtype = op.ifm.dtype
605 ifm2_dtype = op.ifm2.dtype
606 valid = ifm_dtype == ifm2_dtype
607 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
608
609 @staticmethod
610 def constraint_matching_signed(op):
611 "For IFM that are signed, OFM must also be signed"
612 valid = True
613 ifm_dtype = op.ifm.dtype
614 ofm_dtype = op.ofm.dtype
615 if ifm_dtype.type & BaseType.Signed:
616 valid = bool(ofm_dtype.type & BaseType.Signed)
617 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
618
619 @staticmethod
620 def constraint_unsigned_valid(op):
621 "For IFM that are unsigned, OFM must either be the same type or int32"
622 valid = True
623 ifm_dtype = op.ifm.dtype
624 ofm_dtype = op.ofm.dtype
625 if ifm_dtype.type & BaseType.Unsigned:
626 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
627 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
628
629 @staticmethod
630 def constraint_input_8bit(op):
631 "IFM must be int8 or uint8"
632 ifm_dtype = op.ifm.dtype
633 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8)
634 return valid, f"Op has ifm_dtype={ifm_dtype}"
635
636 @staticmethod
637 def constraint_matching_either_shapes(op):
638 "At least one Input's shape must match the OFM's shape"
639 ifm_shape = op.ifm.shape
640 ifm2_shape = op.ifm2.shape if op.ifm2 else None
641 ofm_shape = op.ofm.shape
642 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
643 return valid, f"Op has ifm_shape={ifm_shape}, ifm2_shape={ifm2_shape} and ofm_shape={ofm_shape}"
644
645 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200646 def constraint_keep_dim_ifm_ofm(op):
647 "The IFM and OFM must have the same number of dimensions if keep_num_dims is set to true"
648 valid = True
649 if op.attrs.get("keep_num_dims"):
650 valid = len(op.ifm.shape) == len(op.ofm.shape)
651 return valid, f"Op has ifm shape={op.ifm.shape} and ofm shape={op.ofm.shape}"
652
653 @staticmethod
654 def constraint_mean_input_dims(op):
655 "Input tensor must be at least 2D"
656 dims = len(op.inputs[0].shape)
657 return 2 <= dims <= 4, f"Input is {dims}D"
658
659 @staticmethod
660 def constraint_mean_axis(op):
661 "Axis indices must correspond to height and width axes"
662 dims = len(op.inputs[0].shape)
663 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
664 if dims == 2 or dims == 3:
665 valid = axis in (0, 1, [0], [1], [0, 1], [1, 0])
666 elif dims == 4:
667 valid = axis in (1, 2, [1], [2], [1, 2], [2, 1])
668 return valid, f"Axis is {axis}"
669
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200670 @staticmethod
671 def constraint_matching_in_out_quant(op):
672 "Input and output quantisation must match."
673 if not check_quantized_tens_scaling_equal(op.ifm, op.ofm):
674 return False, "IFM and OFM quantisation parameters are not equal."
675 return True, "IFM and OFM quantisation parameters matches."
676
Johan Alfven3ac03be2023-03-01 09:53:35 +0100677 @staticmethod
678 def constraint_matching_in_out_elements(op):
679 "Input and output number of elements must match."
680 if shape_num_elements(op.ifm.shape) != shape_num_elements(op.ofm.shape):
681 return False, f"IFM {op.ifm.shape} and OFM {op.ofm.shape} number of elements are not equal."
682 return True, "IFM and OFM number of elements are equal."
683
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200684
685def tflite_semantic_checker(nng):
686 semantic_checker = TFLiteSemantic()
687 for sg in nng.subgraphs:
688 for op in sg.get_all_ops():
689 op.run_on_npu = semantic_checker.is_operator_semantic_valid(op)
690 return nng