blob: dc3b81853f69b02f4c5cd765b4a35da97b9a5fbf [file] [log] [blame]
Rickard Bolinbc6ee582022-11-04 08:24:29 +00001# SPDX-FileCopyrightText: Copyright 2021-2022 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
26from .operation import get_slice_offsets
27from .operation import Op
28from .supported_operators_util import docstring_format_args
29from .supported_operators_util import list_formatter
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +020030from .tensor import check_quantized_tens_scaling_equal
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
Fredrik Svedberg11563172022-07-06 14:54:12 +020080 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 +020081 reshape_ops = set(
82 (
83 Op.Reshape,
84 Op.QuantizedReshape,
85 Op.Squeeze,
86 Op.ExpandDims,
87 )
88 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020089
90 def __init__(self):
91 # Setup the generic constraints. Note: the order matters
92 self.generic_constraints = []
93 self.generic_constraints.append(TFLiteSemantic.constraint_tens_no_dynamic)
94 self.generic_constraints.append(TFLiteSemantic.constraint_tens_defined_shape)
95 self.generic_constraints.append(TFLiteSemantic.constraint_tens_output_scalar)
96 self.generic_constraints.append(TFLiteSemantic.constraint_tens_input_scalar)
97 self.generic_constraints.append(TFLiteSemantic.constraint_tens_shape_size)
98
99 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_none_check)
100 self.generic_constraints.append(TFLiteSemantic.constraint_tens_quant_scale)
101 self.generic_constraints.append(TFLiteSemantic.constraint_quant_scale_inf)
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100102 self.generic_constraints.append(TFLiteSemantic.constraint_none_const_tensors)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200103
104 # Setup specific constraints. Note: the order matters
105 self.specific_constraints = defaultdict(list)
106
107 # Conv-like checks:
108 for op_type in TFLiteSemantic.convolution_like_ops:
109 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
Tim Hallea4ba662022-11-11 18:19:53 +0000110 if op_type not in TFLiteSemantic.transpose_convolution_ops:
111 # Transpose Conv does not contain dilation
112 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_dilation_type)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200113
114 # Pooling checks:
115 for op_type in TFLiteSemantic.pooling_ops:
116 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_stride_type)
117 # AVG pooling specific checks:
118 for op_type in TFLiteSemantic.avg_pooling_ops:
119 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
120 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
121 # MAX pooling specific checks:
122 for op_type in TFLiteSemantic.max_pooling_ops:
123 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
124 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_filter_type)
125
126 # Concat specific checks:
127 for op_type in (Op.Concat, Op.ConcatTFLite):
128 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_exists)
129 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_axis_valid)
130 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_dimensionality)
131 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions)
Johan Alfvénb3932512022-09-12 17:44:25 +0200132 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200133
134 # Element-wise checks:
135 for op_type in TFLiteSemantic.elem_wise_main_ops:
136 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_either_shapes)
137 # Unary specific checks:
138 for op_type in TFLiteSemantic.unary_elem_wise_main_ops:
139 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
140 # Binary Min/Max specific checks:
141 for op_type in TFLiteSemantic.binary_elem_wise_min_max_ops:
142 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_types)
143 # Binary Add/Mul/Sub specific checks:
144 for op_type in TFLiteSemantic.binary_elem_wise_add_mul_sub:
145 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_inputs_types)
146 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_signed)
147 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_unsigned_valid)
148
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200149 # Ops reshaping dimensions: Reshape, Squeeze and ExpandDims
150 for op_type in TFLiteSemantic.reshape_ops:
151 self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_quant)
152
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200153 # Softmax specific checks:
154 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_shapes)
155 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_in_out_types)
156 self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_beta_value_range)
157
158 # SplitV specific checks:
159 self.specific_constraints[Op.SplitV].append(TFLiteSemantic.constraint_splitv_inferred)
160
161 # StridedSlice specific checks:
162 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_input_count)
163 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_inputs_const)
164 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_ellipsis_mask)
165 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_axis_masks)
166 self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_slice_ranges)
167
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200168 # FullyConnected specific checks:
169 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_fc_output_2d)
170 self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_keep_dim_ifm_ofm)
171
172 # Pad specific checks:
173 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_input_count)
174 self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_constant)
175
176 # HardSwish specific checks:
177 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_input_8bit)
178 self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_matching_in_out_types)
Fredrik Svedberg701ba912022-09-07 16:01:15 +0200179
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200180 # Mean specific checks:
181 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_input_8bit)
182 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_input_dims)
183 self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_axis)
184
185 def is_operator_semantic_valid(self, op):
186 ext_type = optype_to_builtintype(op.type)
187
188 if op.type in (Op.Placeholder, Op.SubgraphInput, Op.Const):
189 return True
190
Ayaan Masood4965fae2022-06-29 11:30:57 +0100191 # Generic constraints list filtered out to exclude certain constraints depending on op.type
192 filtered_generic_constraints = []
193
194 for constraint in self.generic_constraints:
195 # Check constraint not in dictionary otherwise return empty array
196 if constraint not in self.get_generic_constraint_exclude_list().get(op.type, []):
197 filtered_generic_constraints.append(constraint)
198
199 for constraint in filtered_generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200200 valid, extra = constraint(op)
201 if not valid:
202 print(
Tim Hall3584a9c2021-11-18 22:05:17 +0000203 f"Warning: Unsupported TensorFlow Lite semantics for {ext_type} '{op.name}'. Placing on CPU instead"
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200204 )
205 print(f" - {constraint.__doc__}")
206 if extra:
207 print(f" {extra}")
208 return False
209
210 return True
211
212 @staticmethod
Ayaan Masood4965fae2022-06-29 11:30:57 +0100213 def get_generic_constraint_exclude_list():
214
215 # Not all generic constraints can be applied to each operator
216 generic_constraints_exclude_list = {
217 Op.Shape: [
218 TFLiteSemantic.constraint_tens_quant_none_check,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100219 ],
220 Op.Quantize: [
221 TFLiteSemantic.constraint_tens_no_dynamic,
222 TFLiteSemantic.constraint_tens_output_scalar,
Ayaan Masood25f48dd2022-06-29 18:16:04 +0100223 ],
Ayaan Masood4965fae2022-06-29 11:30:57 +0100224 }
225 return generic_constraints_exclude_list
226
227 @staticmethod
erik.andersson@arm.com3bbbed62021-12-20 14:14:16 +0100228 def constraint_none_const_tensors(op):
229 "Constant tensors should not have NoneType-values"
230 valid = True
231 extra = ""
232 for tens in filter(None, op.inputs):
233 if len(tens.ops) > 0 and tens.ops[0].type == Op.Const and tens.values is None:
234 valid = False
235 extra = str(tens.name)
236 return valid, f"Unexpected None value for constant tensor: {extra}"
237
238 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200239 def constraint_tens_no_dynamic(op):
240 "Input(s) and Output tensors must not be dynamic"
241 valid = True
242 extra = []
243 tensors = [tens for tens in op.inputs + op.outputs if tens]
244 for tens in tensors:
245 if (tens.shape == []) and (tens.values is None):
246 valid = False
247 extra.append(tens.name)
248 extra = ", ".join(extra)
249 return valid, f"Op has dynamic tensor(s): {extra}"
250
251 @staticmethod
252 def constraint_tens_defined_shape(op):
253 "Input(s) and Output tensors must have a defined shape"
254 valid = True
255 extra = []
256 tensors = [tens for tens in op.inputs + op.outputs if tens]
257 for tens in tensors:
258 if not tens.has_fully_defined_shape():
259 valid = False
260 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
261 return valid, ", ".join(extra)
262
263 @staticmethod
264 def constraint_tens_output_scalar(op):
265 "Output tensors cannot be scalar"
266 ofm = op.ofm
267 valid = ofm.shape != []
268 return valid, f"Output Tensor '{ofm.name}' is scalar"
269
270 @classmethod
271 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
272 def constraint_tens_input_scalar(cls, op):
273 "Scalar Input tensors are only valid for op type: {}"
274 valid = True
275 extra = []
276 tensors = [tens for tens in op.inputs if tens]
277 for tens in tensors:
278 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
279 valid = False
280 extra.append(tens.name)
281 extra = ", ".join(extra)
282 return valid, f"Op has scalar input tensor(s): {extra}"
283
284 @staticmethod
285 def constraint_tens_shape_size(op):
286 "Input(s) and Output tensors must not be greater than 4D"
287 valid = True
288 extra = []
289 tensors = [tens for tens in op.inputs + op.outputs if tens]
290 for tens in tensors:
291 if len(tens.shape) > 4:
292 valid = False
293 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
294 return valid, ", ".join(extra)
295
296 @staticmethod
297 def constraint_tens_quant_none_check(op):
298 "Input(s), Output and Weight tensors must have quantization parameters"
299 valid = True
300 extra = []
301 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
302 for tens in tensors:
303 if tens.quantization is None:
304 valid = False
305 extra.append(tens.name)
306 extra = ", ".join(extra)
307 return valid, f"Op has tensors with missing quantization parameters: {extra}"
308
309 @staticmethod
310 def constraint_tens_quant_scale(op):
311 "Input(s), Output and Weight tensors with quantization scales must be finite"
312 valid = True
313 extra = []
314 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
315 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200316 if (
317 tens.quantization
318 and tens.quantization.scale_f32 is not None
319 and np.isinf(tens.quantization.scale_f32).any()
320 ):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200321 valid = False
322 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
323 return valid, ", ".join(extra)
324
325 @staticmethod
326 def constraint_fc_output_2d(op):
Ayaan Masooda2ec5aa2022-04-21 14:28:03 +0100327 """The output tensor(s) must have 2D shape"""
328 valid = op.ifm.get_shape_as_2d(op.weights.shape[-2]) is not None
329 extra = f"Op has non-2D output tensor '{op.ofm.name}'" if not valid else ""
330
331 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200332
333 @staticmethod
334 def constraint_stride_type(op):
335 "Stride values for both width and height must be integer types"
336 w, h = op.get_kernel_stride()
337 valid = is_integer(w) and is_integer(h)
338 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
339
340 @staticmethod
341 def constraint_dilation_type(op):
342 "Dilation factor values for both width and height must be integer types"
343 w, h = op.get_kernel_dilation()
344 valid = is_integer(w) and is_integer(h)
345 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
346
347 @staticmethod
348 def constraint_quant_scale_inf(op):
349 "Input and Output tensors must have quantization scales that fit within float32 precision"
350 if op.ofm is not None and op.ofm.is_quantized():
351 ofm_scale = op.ofm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200352 if np.any(ofm_scale < np.finfo(np.float32).tiny):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200353 return (
354 False,
355 f"The quantization scale of the output tensor is {ofm_scale}, "
356 + f"minimum supported is: {np.finfo(np.float32).tiny}",
357 )
358 if op.ifm is not None and op.ifm.is_quantized():
359 ifm_scale = op.ifm.quantization.scale_f32
Dwight Lidman4caf29d2021-10-08 14:26:54 +0200360 if np.any(np.isinf(ifm_scale / ofm_scale)):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200361 return (
362 False,
363 f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}",
364 )
365 return True, "Op's quantization is ok"
366
367 @staticmethod
368 def constraint_matching_in_out_types(op):
369 "IFM and OFM data types must match"
370 ifm_dtype = op.ifm.dtype
371 ofm_dtype = op.ofm.dtype
372 valid = ifm_dtype == ofm_dtype
373 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
374
375 @staticmethod
376 def constraint_beta_value_range(op):
377 "Beta value needs to be positive"
378 beta = op.attrs.get("beta", 1.0)
379 valid = beta >= 0
380 return valid, f"Op has beta={beta}"
381
382 @staticmethod
383 def constraint_filter_type(op):
384 "Kernel filter values for both width and height must be integer types"
385 w = op.kernel.width
386 h = op.kernel.height
387 valid = is_integer(w) and is_integer(h)
388 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
389
390 @staticmethod
391 def constraint_matching_shapes(op):
392 "IFM and OFM shapes must match"
393 ifm_shape = op.ifm.shape
394 ofm_shape = op.ofm.shape
395 valid = ifm_shape == ofm_shape
396 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
397
398 @staticmethod
399 def constraint_splitv_inferred(op):
400 "Only one size is allowed to be inferred"
401 sizes = op.inputs[1].values
402 valid = np.count_nonzero(sizes == -1) <= 1
403 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
404
405 @staticmethod
406 def constraint_axis_exists(op):
407 "Axis attribute must exist"
408 axis = op.attrs.get("axis")
409 valid = axis is not None
410 return valid, f"Op has axis={axis}"
411
412 @staticmethod
413 def constraint_axis_valid(op):
414 "Axis attribute must be in the range [0, <ofm_dimensions>)"
415 dims = len(op.ofm.shape)
416 axis = op.attrs["axis"]
417 axis += dims if axis < 0 else 0
418 valid = 0 <= axis < dims
419 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
420
421 @staticmethod
422 def constraint_matching_dimensionality(op):
423 "All Input dimensionalities must match OFM dimensionality"
424 valid = True
425 extra = []
426 ofm_dim = len(op.ofm.shape)
427 tensors = [tens for tens in op.inputs if tens]
428 for tens in tensors:
429 dim = len(tens.shape)
430 if dim != ofm_dim:
431 valid = False
432 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
433 extra = ", ".join(extra)
434 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
435
436 @staticmethod
437 def constraint_valid_dimensions(op):
438 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
439 valid = True
440 extra = []
441 ofm_shape = op.ofm.shape
442 ofm_dim = len(ofm_shape)
443 axis = op.attrs["axis"]
444 axis += ofm_dim if axis < 0 else 0
445 tensors = [tens for tens in op.inputs if tens]
446 for tens in tensors:
447 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
448 valid = False
449 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
450 extra = ", ".join(extra)
451 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
452
453 @staticmethod
Johan Alfvénb3932512022-09-12 17:44:25 +0200454 def constraint_valid_dimensions_axis(op):
455 """The size of the OFM axis must match the sum of all IFM axis defined by the axis attribute"""
456 valid = True
457 extra = []
458 ofm_shape = op.ofm.shape
459 ofm_dim = len(ofm_shape)
460 axis = op.attrs["axis"]
461 axis += ofm_dim if axis < 0 else 0
462
463 sum_ifm_axis = 0
464 tensors = [tens for tens in op.inputs if tens]
465 for tens in tensors:
466 sum_ifm_axis += tens.shape[axis]
467 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
468
469 valid = sum_ifm_axis == ofm_shape[axis]
470 extra = ", ".join(extra)
471 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
472
473 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200474 def constraint_stridedslice_input_count(op):
475 "Exactly 4 Input tensors are required"
476 inputs = len(op.inputs)
477 valid = inputs == 4
478 return valid, f"Op has {inputs} inputs"
479
480 @staticmethod
481 def constraint_pad_input_count(op):
482 "Number of input tensors must be exactly 2"
483 inputs = len(op.inputs)
484 valid = inputs == 2
485 return valid, f"Op has {inputs} inputs"
486
487 @staticmethod
488 def constraint_pad_constant(op):
489 "The padding tensor must be constant"
490 pad_tensor = op.inputs[1].values
491 valid = pad_tensor is not None
492 return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}"
493
494 @staticmethod
495 def constraint_stridedslice_inputs_const(op):
496 "Begin, End and Stride Input tensors must be constant"
497 valid = True
498 extra = []
499 _, begin, end, strides = op.inputs
500 if begin.values is None:
501 valid = False
502 extra.append(f"Begin tensor '{begin.name}'")
503 if end.values is None:
504 valid = False
505 extra.append(f"End tensor '{end.name}'")
506 if strides.values is None:
507 valid = False
508 extra.append(f"Stride tensor '{strides.name}'")
509 extra = ", ".join(extra)
510 return valid, f"Op has non-constant tensors: {extra}"
511
512 @staticmethod
513 def constraint_ellipsis_mask(op):
514 "ellipsis_mask must be 0"
515 ellipsis = op.attrs["ellipsis_mask"]
516 valid = ellipsis == 0
517 return valid, f"Op has ellipsis mask as: {ellipsis}"
518
519 @staticmethod
520 def constraint_axis_masks(op):
521 "new_axis_mask and shrink_axis_mask cannot both be set"
522 new_axis = op.attrs["new_axis_mask"]
523 shrink_axis = op.attrs["shrink_axis_mask"]
524 valid = (new_axis == 0) or (shrink_axis == 0)
525 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
526
527 @staticmethod
528 def constraint_slice_ranges(op):
529 "Slice 'end' values must be greater than 'begin' values"
530 ifm, begin, end, _ = op.inputs
531 # Calculate offset begin/end
532 offset_begin = get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
533 offset_end = get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
534 # Check "end - begin" doesn't result in any zero or negative elements
535 valid = all((e - b) > 0 for b, e in zip(offset_begin, offset_end))
536 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
537
538 @staticmethod
539 def constraint_matching_inputs_types(op):
540 "Both Input data types must match"
541 ifm_dtype = op.ifm.dtype
542 ifm2_dtype = op.ifm2.dtype
543 valid = ifm_dtype == ifm2_dtype
544 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
545
546 @staticmethod
547 def constraint_matching_signed(op):
548 "For IFM that are signed, OFM must also be signed"
549 valid = True
550 ifm_dtype = op.ifm.dtype
551 ofm_dtype = op.ofm.dtype
552 if ifm_dtype.type & BaseType.Signed:
553 valid = bool(ofm_dtype.type & BaseType.Signed)
554 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
555
556 @staticmethod
557 def constraint_unsigned_valid(op):
558 "For IFM that are unsigned, OFM must either be the same type or int32"
559 valid = True
560 ifm_dtype = op.ifm.dtype
561 ofm_dtype = op.ofm.dtype
562 if ifm_dtype.type & BaseType.Unsigned:
563 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
564 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
565
566 @staticmethod
567 def constraint_input_8bit(op):
568 "IFM must be int8 or uint8"
569 ifm_dtype = op.ifm.dtype
570 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8)
571 return valid, f"Op has ifm_dtype={ifm_dtype}"
572
573 @staticmethod
574 def constraint_matching_either_shapes(op):
575 "At least one Input's shape must match the OFM's shape"
576 ifm_shape = op.ifm.shape
577 ifm2_shape = op.ifm2.shape if op.ifm2 else None
578 ofm_shape = op.ofm.shape
579 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
580 return valid, f"Op has ifm_shape={ifm_shape}, ifm2_shape={ifm2_shape} and ofm_shape={ofm_shape}"
581
582 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200583 def constraint_keep_dim_ifm_ofm(op):
584 "The IFM and OFM must have the same number of dimensions if keep_num_dims is set to true"
585 valid = True
586 if op.attrs.get("keep_num_dims"):
587 valid = len(op.ifm.shape) == len(op.ofm.shape)
588 return valid, f"Op has ifm shape={op.ifm.shape} and ofm shape={op.ofm.shape}"
589
590 @staticmethod
591 def constraint_mean_input_dims(op):
592 "Input tensor must be at least 2D"
593 dims = len(op.inputs[0].shape)
594 return 2 <= dims <= 4, f"Input is {dims}D"
595
596 @staticmethod
597 def constraint_mean_axis(op):
598 "Axis indices must correspond to height and width axes"
599 dims = len(op.inputs[0].shape)
600 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
601 if dims == 2 or dims == 3:
602 valid = axis in (0, 1, [0], [1], [0, 1], [1, 0])
603 elif dims == 4:
604 valid = axis in (1, 2, [1], [2], [1, 2], [2, 1])
605 return valid, f"Axis is {axis}"
606
Jonas Ohlsson0957e3e2021-09-01 15:57:21 +0200607 @staticmethod
608 def constraint_matching_in_out_quant(op):
609 "Input and output quantisation must match."
610 if not check_quantized_tens_scaling_equal(op.ifm, op.ofm):
611 return False, "IFM and OFM quantisation parameters are not equal."
612 return True, "IFM and OFM quantisation parameters matches."
613
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200614
615def tflite_semantic_checker(nng):
616 semantic_checker = TFLiteSemantic()
617 for sg in nng.subgraphs:
618 for op in sg.get_all_ops():
619 op.run_on_npu = semantic_checker.is_operator_semantic_valid(op)
620 return nng