blob: 6264891426e5135f908c9bec7b85b3cb3df1364d [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 = []
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)
187
188 # HardSwish specific checks:
189 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_input_8bit)
190 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_matching_in_out_types)
Fredrik Svedberg701ba912022-09-07 16:01:15 +0200191
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200192 # Mean specific checks:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200193 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_input_dims)
194 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_axis)
195
Rickard Bolin6986a072022-12-19 12:33:40 +0000196 # ArgMax specific checks:
197 self.specific_constraints[Op.ArgMax].append(TFLiteSemantic.constraint_input_8bit)
Johan Alfvenc1ad80b2023-03-31 10:19:23 +0200198 self.specific_constraints[Op.ArgMax].append(TFLiteSemantic.constraint_argmax_output)
Rickard Bolin6986a072022-12-19 12:33:40 +0000199
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200200 # UnidirectionalSequenceLstm specific checks:
201 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_input_signed)
202 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_matching_in_out_types)
203 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_dimensions)
204 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_inputs)
205 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_intermediates)
206 self.specific_constraints[Op.UnidirectionalSequenceLstm].append(TFLiteSemantic.constraint_lstm_variables)
207
Johan Alfvence502732023-04-24 13:35:40 +0200208 # Exp specific checks
209 self.specific_constraints[Op.Exp].append(TFLiteSemantic.constraint_input_signed)
210
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200211 def is_operator_semantic_valid(self, op):
212 ext_type = optype_to_builtintype(op.type)
213
214 if op.type in (Op.Placeholder, Op.SubgraphInput, Op.Const):
215 return True
216
Ayaan Masood4965fae2022-06-29 11:30:57 +0100217 # Generic constraints list filtered out to exclude certain constraints depending on op.type
218 filtered_generic_constraints = []
219
220 for constraint in self.generic_constraints:
221 # Check constraint not in dictionary otherwise return empty array
222 if constraint not in self.get_generic_constraint_exclude_list().get(op.type, []):
223 filtered_generic_constraints.append(constraint)
224
225 for constraint in filtered_generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200226 valid, extra = constraint(op)
227 if not valid:
228 print(
Tim Hall3584a9c2021-11-18 22:05:17 +0000229 f"Warning: Unsupported TensorFlow Lite semantics for {ext_type} '{op.name}'. Placing on CPU instead"
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200230 )
231 print(f" - {constraint.__doc__}")
232 if extra:
233 print(f" {extra}")
234 return False
235
236 return True
237
238 @staticmethod
Ayaan Masood4965fae2022-06-29 11:30:57 +0100239 def get_generic_constraint_exclude_list():
240
241 # Not all generic constraints can be applied to each operator
242 generic_constraints_exclude_list = {
243 Op.Shape: [
244 TFLiteSemantic.constraint_tens_quant_none_check,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100245 ],
246 Op.Quantize: [
247 TFLiteSemantic.constraint_tens_no_dynamic,
248 TFLiteSemantic.constraint_tens_output_scalar,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100249 ],
Rickard Bolin6986a072022-12-19 12:33:40 +0000250 Op.ArgMax: [
251 TFLiteSemantic.constraint_tens_quant_none_check,
252 ],
Ayaan Masood4965fae2022-06-29 11:30:57 +0100253 }
254 return generic_constraints_exclude_list
255
256 @staticmethod
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100257 def constraint_none_const_tensors(op):
258 "Constant tensors should not have NoneType-values"
259 valid = True
260 extra = ""
261 for tens in filter(None, op.inputs):
262 if len(tens.ops) > 0 and tens.ops[0].type == Op.Const and tens.values is None:
263 valid = False
264 extra = str(tens.name)
265 return valid, f"Unexpected None value for constant tensor: {extra}"
266
267 @staticmethod
Tim Hall2180a172023-03-10 18:11:34 +0000268 def constraint_attributes_specified(op):
269 "All required operator attributes must be specified"
270 # operators that have been created internally (i.e. not created as part of reading an input network) may not
271 # have the read error attribute
272 attribute_read_error = op.attrs.get("attribute_read_error", [])
273 valid = len(attribute_read_error) == 0
274 extra = ", ".join(attribute_read_error)
275 return valid, f"Op has missing attributes: {extra}"
276
277 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200278 def constraint_tens_no_dynamic(op):
279 "Input(s) and Output tensors must not be dynamic"
280 valid = True
281 extra = []
282 tensors = [tens for tens in op.inputs + op.outputs if tens]
283 for tens in tensors:
284 if (tens.shape == []) and (tens.values is None):
285 valid = False
286 extra.append(tens.name)
287 extra = ", ".join(extra)
288 return valid, f"Op has dynamic tensor(s): {extra}"
289
290 @staticmethod
291 def constraint_tens_defined_shape(op):
292 "Input(s) and Output tensors must have a defined shape"
293 valid = True
294 extra = []
295 tensors = [tens for tens in op.inputs + op.outputs if tens]
296 for tens in tensors:
297 if not tens.has_fully_defined_shape():
298 valid = False
299 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
300 return valid, ", ".join(extra)
301
302 @staticmethod
303 def constraint_tens_output_scalar(op):
304 "Output tensors cannot be scalar"
305 ofm = op.ofm
306 valid = ofm.shape != []
307 return valid, f"Output Tensor '{ofm.name}' is scalar"
308
309 @classmethod
310 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
311 def constraint_tens_input_scalar(cls, op):
312 "Scalar Input tensors are only valid for op type: {}"
313 valid = True
314 extra = []
315 tensors = [tens for tens in op.inputs if tens]
316 for tens in tensors:
317 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
318 valid = False
319 extra.append(tens.name)
320 extra = ", ".join(extra)
321 return valid, f"Op has scalar input tensor(s): {extra}"
322
323 @staticmethod
324 def constraint_tens_shape_size(op):
325 "Input(s) and Output tensors must not be greater than 4D"
326 valid = True
327 extra = []
328 tensors = [tens for tens in op.inputs + op.outputs if tens]
329 for tens in tensors:
330 if len(tens.shape) > 4:
331 valid = False
332 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
333 return valid, ", ".join(extra)
334
335 @staticmethod
336 def constraint_tens_quant_none_check(op):
337 "Input(s), Output and Weight tensors must have quantization parameters"
338 valid = True
339 extra = []
340 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
341 for tens in tensors:
342 if tens.quantization is None:
343 valid = False
344 extra.append(tens.name)
345 extra = ", ".join(extra)
346 return valid, f"Op has tensors with missing quantization parameters: {extra}"
347
348 @staticmethod
349 def constraint_tens_quant_scale(op):
350 "Input(s), Output and Weight tensors with quantization scales must be finite"
351 valid = True
352 extra = []
353 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
354 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200355 if (
356 tens.quantization
357 and tens.quantization.scale_f32 is not None
358 and np.isinf(tens.quantization.scale_f32).any()
359 ):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200360 valid = False
361 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
362 return valid, ", ".join(extra)
363
364 @staticmethod
365 def constraint_fc_output_2d(op):
Ayaan Masooda2ec5aa2022-04-21 14:28:03 +0100366 """The output tensor(s) must have 2D shape"""
367 valid = op.ifm.get_shape_as_2d(op.weights.shape[-2]) is not None
368 extra = f"Op has non-2D output tensor '{op.ofm.name}'" if not valid else ""
369
370 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200371
372 @staticmethod
373 def constraint_stride_type(op):
374 "Stride values for both width and height must be integer types"
375 w, h = op.get_kernel_stride()
376 valid = is_integer(w) and is_integer(h)
377 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
378
379 @staticmethod
Tim Hall9cf63a32023-06-27 12:07:49 +0100380 def constraint_conv_groups_ifm_depth(op):
381 """IFM depth must be a whole multiple of the filter kernel depth"""
382 ifm_depth = op.ifm.shape[-1] # nhwc
383 kernel_ic = op.weights.shape[-2] # hwio
384 num_conv_groups = ifm_depth // kernel_ic
385
386 if ifm_depth % kernel_ic == 0:
387 op.attrs["num_conv_groups"] = num_conv_groups
388 valid = True
389 else:
390 valid = False
391
392 return valid, f"IFM depth = {ifm_depth} and filter kernel depth = {kernel_ic}"
393
394 @staticmethod
395 def constraint_conv_groups_num_filters(op):
396 """Number of filter kernels must be equally divisible by the number of convolution groups"""
397 ifm_depth = op.ifm.shape[-1] # nhwc
398 kernel_ic = op.weights.shape[-2] # hwio
399 kernel_oc = op.weights.shape[-1] # hwio
400 num_conv_groups = ifm_depth // kernel_ic
401
402 if kernel_oc % num_conv_groups == 0:
403 valid = True
404 else:
405 valid = False
406
407 return valid, f"Filter kernels = {kernel_oc} and convolution groups = {num_conv_groups}"
408
409 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200410 def constraint_dilation_type(op):
411 "Dilation factor values for both width and height must be integer types"
412 w, h = op.get_kernel_dilation()
413 valid = is_integer(w) and is_integer(h)
414 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
415
416 @staticmethod
417 def constraint_quant_scale_inf(op):
418 "Input and Output tensors must have quantization scales that fit within float32 precision"
419 if op.ofm is not None and op.ofm.is_quantized():
420 ofm_scale = op.ofm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200421 if np.any(ofm_scale < np.finfo(np.float32).tiny):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200422 return (
423 False,
424 f"The quantization scale of the output tensor is {ofm_scale}, "
425 + f"minimum supported is: {np.finfo(np.float32).tiny}",
426 )
427 if op.ifm is not None and op.ifm.is_quantized():
428 ifm_scale = op.ifm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200429 if np.any(np.isinf(ifm_scale / ofm_scale)):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200430 return (
431 False,
432 f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}",
433 )
434 return True, "Op's quantization is ok"
435
436 @staticmethod
437 def constraint_matching_in_out_types(op):
438 "IFM and OFM data types must match"
439 ifm_dtype = op.ifm.dtype
440 ofm_dtype = op.ofm.dtype
441 valid = ifm_dtype == ofm_dtype
442 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
443
444 @staticmethod
445 def constraint_beta_value_range(op):
446 "Beta value needs to be positive"
447 beta = op.attrs.get("beta", 1.0)
448 valid = beta >= 0
449 return valid, f"Op has beta={beta}"
450
451 @staticmethod
452 def constraint_filter_type(op):
453 "Kernel filter values for both width and height must be integer types"
454 w = op.kernel.width
455 h = op.kernel.height
456 valid = is_integer(w) and is_integer(h)
457 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
458
459 @staticmethod
460 def constraint_matching_shapes(op):
461 "IFM and OFM shapes must match"
462 ifm_shape = op.ifm.shape
463 ofm_shape = op.ofm.shape
464 valid = ifm_shape == ofm_shape
465 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
466
467 @staticmethod
Johan Alfven12e48112023-01-31 10:26:26 +0100468 def constraint_split_axis(op):
469 "Axis value must be in the range [-RANK(IFM) to +RANK(IFM))"
470 axis_tens = op.inputs[0]
471 input_tens = op.inputs[1]
472 dims = len(input_tens.shape)
Tim Hall762d3ac2023-07-06 11:42:02 +0100473 # handle axis being a scalar or 1-D array
474 axis = int(axis_tens.values) if len(axis_tens.values.shape) == 0 else int(axis_tens.values[0])
Johan Alfven12e48112023-01-31 10:26:26 +0100475 axis += dims if axis < 0 else 0
476 valid = 0 <= axis < dims
477 return valid, f"Op has ifm_dimensions={dims} and axis value is: {axis}"
478
479 @staticmethod
480 def constraint_split_num_splits(op):
481 "Axis must be divisible by number of splits"
482 num_splits = op.attrs.get("num_splits")
483 axis_tens = op.inputs[0]
484 input_tens = op.inputs[1]
485 dims = len(input_tens.shape)
Tim Hall762d3ac2023-07-06 11:42:02 +0100486 # handle axis being a scalar or 1-D array
487 axis = int(axis_tens.values) if len(axis_tens.values.shape) == 0 else int(axis_tens.values[0])
Johan Alfven12e48112023-01-31 10:26:26 +0100488 axis += dims if axis < 0 else 0
489 valid = input_tens.shape[axis] % num_splits == 0
490 return valid, f"Op has ifm shape={input_tens.shape} axis={axis} num_splits={num_splits}"
491
492 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200493 def constraint_splitv_inferred(op):
494 "Only one size is allowed to be inferred"
495 sizes = op.inputs[1].values
496 valid = np.count_nonzero(sizes == -1) <= 1
497 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
498
499 @staticmethod
500 def constraint_axis_exists(op):
501 "Axis attribute must exist"
502 axis = op.attrs.get("axis")
503 valid = axis is not None
504 return valid, f"Op has axis={axis}"
505
506 @staticmethod
507 def constraint_axis_valid(op):
508 "Axis attribute must be in the range [0, <ofm_dimensions>)"
509 dims = len(op.ofm.shape)
510 axis = op.attrs["axis"]
511 axis += dims if axis < 0 else 0
512 valid = 0 <= axis < dims
513 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
514
515 @staticmethod
516 def constraint_matching_dimensionality(op):
517 "All Input dimensionalities must match OFM dimensionality"
518 valid = True
519 extra = []
520 ofm_dim = len(op.ofm.shape)
521 tensors = [tens for tens in op.inputs if tens]
522 for tens in tensors:
523 dim = len(tens.shape)
524 if dim != ofm_dim:
525 valid = False
526 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
527 extra = ", ".join(extra)
528 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
529
530 @staticmethod
531 def constraint_valid_dimensions(op):
532 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
533 valid = True
534 extra = []
535 ofm_shape = op.ofm.shape
536 ofm_dim = len(ofm_shape)
537 axis = op.attrs["axis"]
538 axis += ofm_dim if axis < 0 else 0
539 tensors = [tens for tens in op.inputs if tens]
540 for tens in tensors:
541 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
542 valid = False
543 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
544 extra = ", ".join(extra)
545 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
546
547 @staticmethod
Johan Alfvénb3932512022-09-12 17:44:25 +0200548 def constraint_valid_dimensions_axis(op):
549 """The size of the OFM axis must match the sum of all IFM axis defined by the axis attribute"""
550 valid = True
551 extra = []
552 ofm_shape = op.ofm.shape
553 ofm_dim = len(ofm_shape)
554 axis = op.attrs["axis"]
555 axis += ofm_dim if axis < 0 else 0
556
557 sum_ifm_axis = 0
558 tensors = [tens for tens in op.inputs if tens]
559 for tens in tensors:
560 sum_ifm_axis += tens.shape[axis]
561 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
562
563 valid = sum_ifm_axis == ofm_shape[axis]
564 extra = ", ".join(extra)
565 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
566
567 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200568 def constraint_stridedslice_input_count(op):
569 "Exactly 4 Input tensors are required"
570 inputs = len(op.inputs)
571 valid = inputs == 4
572 return valid, f"Op has {inputs} inputs"
573
574 @staticmethod
575 def constraint_pad_input_count(op):
576 "Number of input tensors must be exactly 2"
577 inputs = len(op.inputs)
578 valid = inputs == 2
579 return valid, f"Op has {inputs} inputs"
580
581 @staticmethod
582 def constraint_pad_constant(op):
583 "The padding tensor must be constant"
584 pad_tensor = op.inputs[1].values
585 valid = pad_tensor is not None
586 return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}"
587
588 @staticmethod
589 def constraint_stridedslice_inputs_const(op):
590 "Begin, End and Stride Input tensors must be constant"
591 valid = True
592 extra = []
593 _, begin, end, strides = op.inputs
594 if begin.values is None:
595 valid = False
596 extra.append(f"Begin tensor '{begin.name}'")
597 if end.values is None:
598 valid = False
599 extra.append(f"End tensor '{end.name}'")
600 if strides.values is None:
601 valid = False
602 extra.append(f"Stride tensor '{strides.name}'")
603 extra = ", ".join(extra)
604 return valid, f"Op has non-constant tensors: {extra}"
605
606 @staticmethod
607 def constraint_ellipsis_mask(op):
608 "ellipsis_mask must be 0"
609 ellipsis = op.attrs["ellipsis_mask"]
610 valid = ellipsis == 0
611 return valid, f"Op has ellipsis mask as: {ellipsis}"
612
613 @staticmethod
614 def constraint_axis_masks(op):
615 "new_axis_mask and shrink_axis_mask cannot both be set"
616 new_axis = op.attrs["new_axis_mask"]
617 shrink_axis = op.attrs["shrink_axis_mask"]
618 valid = (new_axis == 0) or (shrink_axis == 0)
619 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
620
Tim Halld0e41cf2023-02-14 14:54:18 +0000621 def _get_slice_offsets(input_shape, offset_tens, offset_mask, is_begin=True):
622 # For strided slice operator: get start or end offsets
623 # input_shape: List[int], offset_tens: Tensor, offset_mask: int, is_begin: bool = True
624 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
625 for idx in range(len(input_shape)):
626 # If the i:th bit in the mask is not set then the value in offset_tens[i] should be used, otherwise it
627 # should be ignored
628 if (offset_mask & (1 << idx)) == 0:
629 offsets[idx] = offset_tens.values[idx]
630 if offsets[idx] < 0:
631 # Convert negative indexing to positive ones
632 offsets[idx] += input_shape[idx]
633 return offsets
634
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200635 @staticmethod
636 def constraint_slice_ranges(op):
637 "Slice 'end' values must be greater than 'begin' values"
638 ifm, begin, end, _ = op.inputs
Tim Halld0e41cf2023-02-14 14:54:18 +0000639 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200640 # Calculate offset begin/end
Tim Halld0e41cf2023-02-14 14:54:18 +0000641 offset_begin = TFLiteSemantic._get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
642 offset_end = TFLiteSemantic._get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200643 # Check "end - begin" doesn't result in any zero or negative elements
Tim Halld0e41cf2023-02-14 14:54:18 +0000644 valid = True
645 # if a shrink mask bit is set then the end position provided by the operation should be ignored, and instead a
646 # new end position should be calculated so that calculations in the graph optimiser, such as (end - start),
647 # result in the correct value. otherwise, we just need to check that the begin and end values are valid
648 for i in range(len(ifm.shape)):
649 if (shrink_axis_mask & (1 << i)) != 0:
650 offset_end[i] = offset_begin[i] + 1
651 else:
652 if offset_end[i] <= offset_begin[i]:
653 valid = False
654
655 op.attrs["offset_begin"] = offset_begin
656 op.attrs["offset_end"] = offset_end
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200657 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
658
659 @staticmethod
660 def constraint_matching_inputs_types(op):
661 "Both Input data types must match"
662 ifm_dtype = op.ifm.dtype
663 ifm2_dtype = op.ifm2.dtype
664 valid = ifm_dtype == ifm2_dtype
665 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
666
667 @staticmethod
668 def constraint_matching_signed(op):
669 "For IFM that are signed, OFM must also be signed"
670 valid = True
671 ifm_dtype = op.ifm.dtype
672 ofm_dtype = op.ofm.dtype
673 if ifm_dtype.type & BaseType.Signed:
674 valid = bool(ofm_dtype.type & BaseType.Signed)
675 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
676
677 @staticmethod
678 def constraint_unsigned_valid(op):
679 "For IFM that are unsigned, OFM must either be the same type or int32"
680 valid = True
681 ifm_dtype = op.ifm.dtype
682 ofm_dtype = op.ofm.dtype
683 if ifm_dtype.type & BaseType.Unsigned:
684 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
685 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
686
687 @staticmethod
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200688 def constraint_input_signed(op):
689 "IFM must be int8 or int16"
690 ifm_dtype = op.ifm.dtype
691 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.int16)
692 return valid, f"Op has ifm_dtype={ifm_dtype}"
693
694 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200695 def constraint_input_8bit(op):
696 "IFM must be int8 or uint8"
697 ifm_dtype = op.ifm.dtype
698 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8)
699 return valid, f"Op has ifm_dtype={ifm_dtype}"
700
701 @staticmethod
Johan Alfvenc1ad80b2023-03-31 10:19:23 +0200702 def constraint_argmax_output(op):
703 "OFM must be int32 or int64"
704 ofm_dtype = op.ofm.dtype
705 valid = ofm_dtype in (DataType.int32, DataType.int64)
706 return valid, f"Op has ofm_dtype={ofm_dtype}"
707
708 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200709 def constraint_matching_either_shapes(op):
710 "At least one Input's shape must match the OFM's shape"
711 ifm_shape = op.ifm.shape
712 ifm2_shape = op.ifm2.shape if op.ifm2 else None
713 ofm_shape = op.ofm.shape
714 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
715 return valid, f"Op has ifm_shape={ifm_shape}, ifm2_shape={ifm2_shape} and ofm_shape={ofm_shape}"
716
717 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200718 def constraint_keep_dim_ifm_ofm(op):
719 "The IFM and OFM must have the same number of dimensions if keep_num_dims is set to true"
720 valid = True
721 if op.attrs.get("keep_num_dims"):
722 valid = len(op.ifm.shape) == len(op.ofm.shape)
723 return valid, f"Op has ifm shape={op.ifm.shape} and ofm shape={op.ofm.shape}"
724
725 @staticmethod
726 def constraint_mean_input_dims(op):
727 "Input tensor must be at least 2D"
728 dims = len(op.inputs[0].shape)
729 return 2 <= dims <= 4, f"Input is {dims}D"
730
731 @staticmethod
732 def constraint_mean_axis(op):
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000733 """Requirements for axis parameter:
734 When IFM tensor is 2D:
735 - Reduction in both axes is supported.
736 When IFM tensor is 3D or 4D:
737 - Reduction in Batch axis is only supported if batch size is 1.
738 - Reduction in both Height and Width axes is supported.
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000739 - 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 +0000740 input_shape = op.inputs[0].shape
741 dims = len(input_shape)
742 if op.inputs[1].shape == []:
743 axis = [int(op.inputs[1].values)]
744 else:
745 axis = list(op.inputs[1].values)
746 valid = True
747
748 for ax in axis:
749 if ax < 0 or ax >= dims:
750 return False, "Axis parameter is out of bounds. axis: {axis}, dims: {dims}. "
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000751
752 # Batch is only supported if batch shape is 1
753 if dims == 4 and ax == 0:
754 if input_shape[0] != 1:
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000755 valid = False
756 break
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000757
758 # Depth is supported if any of h,w,c == 1
759 if dims == 3:
760 if ax == 2 and not any([s == 1 for s in input_shape]):
761 valid = False
762 break
763
764 # Depth is supported if any of h,w,c == 1
765 if dims == 4:
766 if ax == 3 and not any([s == 1 for s in input_shape[1:]]):
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000767 valid = False
768 break
769
770 return valid, f"Shape is {input_shape}, Axis is {axis}."
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200771
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200772 @staticmethod
773 def constraint_matching_in_out_quant(op):
774 "Input and output quantisation must match."
775 if not check_quantized_tens_scaling_equal(op.ifm, op.ofm):
776 return False, "IFM and OFM quantisation parameters are not equal."
777 return True, "IFM and OFM quantisation parameters matches."
778
Johan Alfven3ac03be2023-03-01 09:53:35 +0100779 @staticmethod
780 def constraint_matching_in_out_elements(op):
781 "Input and output number of elements must match."
782 if shape_num_elements(op.ifm.shape) != shape_num_elements(op.ofm.shape):
783 return False, f"IFM {op.ifm.shape} and OFM {op.ofm.shape} number of elements are not equal."
784 return True, "IFM and OFM number of elements are equal."
785
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200786 @staticmethod
787 def constraint_lstm_dimensions(op):
788 "IFM and OFM must have 3D shape"
789 valid = len(op.ifm.shape) == len(op.ofm.shape) == 3
790 return valid, f"Op has ifm shape {op.ifm.shape} and ofm shape {op.ofm.shape}"
791
792 @staticmethod
793 def constraint_lstm_inputs(op):
794 "Must have 24 input tensors"
795 n_inputs = len(op.inputs)
796 return n_inputs == 24, f"Op has {n_inputs} inputs"
797
798 @staticmethod
799 def constraint_lstm_intermediates(op):
800 "Must have 5 intermediate tensors"
801 n_intermediates = len(op.intermediates)
802 return n_intermediates == 5, f"Op has {n_intermediates} intermediates"
803
804 @staticmethod
805 def constraint_lstm_variables(op):
806 "State tensors must be variable"
807 valid = True
808 extra = []
809 for tens in op.inputs[18:20]:
810 if not tens.is_variable:
811 valid = False
812 extra.append(tens.name)
813 extra = ", ".join(extra)
814 return valid, f"Op has non-variable state tensor(s): {extra}"
815
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200816
817def tflite_semantic_checker(nng):
818 semantic_checker = TFLiteSemantic()
819 for sg in nng.subgraphs:
820 for op in sg.get_all_ops():
821 op.run_on_npu = semantic_checker.is_operator_semantic_valid(op)
822 return nng