Johan Alfven | 12e4811 | 2023-01-31 10:26:26 +0100 | [diff] [blame] | 1 | # SPDX-FileCopyrightText: Copyright 2021-2023 Arm Limited and/or its affiliates <open-source-office@arm.com> |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 2 | # |
| 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 Bolin | bc6ee58 | 2022-11-04 08:24:29 +0000 | [diff] [blame] | 16 | # |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 17 | # Description: |
| 18 | # The TFLiteSemantic class which is a collection of TensorFlow lite model semantic checks. |
| 19 | from collections import defaultdict |
| 20 | |
| 21 | import numpy as np |
| 22 | |
| 23 | from .data_type import BaseType |
| 24 | from .data_type import DataType |
| 25 | from .numeric_util import is_integer |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 26 | from .operation import Op |
| 27 | from .supported_operators_util import docstring_format_args |
| 28 | from .supported_operators_util import list_formatter |
Jonas Ohlsson | 0957e3e | 2021-09-01 15:57:21 +0200 | [diff] [blame] | 29 | from .tensor import check_quantized_tens_scaling_equal |
Johan Alfven | 3ac03be | 2023-03-01 09:53:35 +0100 | [diff] [blame^] | 30 | from .tensor import shape_num_elements |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 31 | from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN |
| 32 | from .tflite_mapping import optype_to_builtintype |
| 33 | |
| 34 | |
| 35 | def _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 | |
| 43 | class TFLiteSemantic: |
| 44 | # Categorised lists of operators |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 45 | convolution_ops = set( |
| 46 | ( |
| 47 | Op.Conv2DBias, |
| 48 | Op.Conv2D, |
| 49 | Op.QuantizedConv2D, |
| 50 | ) |
| 51 | ) |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 52 | 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 Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 59 | 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 Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 78 | 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 Svedberg | 1156317 | 2022-07-06 14:54:12 +0200 | [diff] [blame] | 80 | shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV, Op.Mean, Op.ExpandDims, Op.Quantize)) |
Jonas Ohlsson | d857507 | 2022-03-30 10:30:25 +0200 | [diff] [blame] | 81 | reshape_ops = set( |
| 82 | ( |
| 83 | Op.Reshape, |
| 84 | Op.QuantizedReshape, |
| 85 | Op.Squeeze, |
| 86 | Op.ExpandDims, |
| 87 | ) |
| 88 | ) |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 89 | |
| 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.com | 3bbbed6 | 2021-12-20 14:14:16 +0100 | [diff] [blame] | 102 | self.generic_constraints.append(TFLiteSemantic.constraint_none_const_tensors) |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 103 | |
| 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 Hall | ea4ba66 | 2022-11-11 18:19:53 +0000 | [diff] [blame] | 110 | 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 Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 113 | |
| 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én | b393251 | 2022-09-12 17:44:25 +0200 | [diff] [blame] | 132 | self.specific_constraints[op_type].append(TFLiteSemantic.constraint_valid_dimensions_axis) |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 133 | |
| 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 Ohlsson | 0957e3e | 2021-09-01 15:57:21 +0200 | [diff] [blame] | 149 | # 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) |
Johan Alfven | 3ac03be | 2023-03-01 09:53:35 +0100 | [diff] [blame^] | 152 | self.specific_constraints[op_type].append(TFLiteSemantic.constraint_matching_in_out_elements) |
Jonas Ohlsson | 0957e3e | 2021-09-01 15:57:21 +0200 | [diff] [blame] | 153 | |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 154 | # Softmax specific checks: |
| 155 | self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_shapes) |
| 156 | self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_matching_in_out_types) |
| 157 | self.specific_constraints[Op.Softmax].append(TFLiteSemantic.constraint_beta_value_range) |
| 158 | |
Johan Alfven | 12e4811 | 2023-01-31 10:26:26 +0100 | [diff] [blame] | 159 | # Split specific checks: |
| 160 | self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_axis) |
| 161 | self.specific_constraints[Op.Split].append(TFLiteSemantic.constraint_split_num_splits) |
| 162 | |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 163 | # SplitV specific checks: |
| 164 | self.specific_constraints[Op.SplitV].append(TFLiteSemantic.constraint_splitv_inferred) |
| 165 | |
| 166 | # StridedSlice specific checks: |
| 167 | self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_input_count) |
| 168 | self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_stridedslice_inputs_const) |
| 169 | self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_ellipsis_mask) |
| 170 | self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_axis_masks) |
| 171 | self.specific_constraints[Op.StridedSlice].append(TFLiteSemantic.constraint_slice_ranges) |
| 172 | |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 173 | # FullyConnected specific checks: |
| 174 | self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_fc_output_2d) |
| 175 | self.specific_constraints[Op.FullyConnected].append(TFLiteSemantic.constraint_keep_dim_ifm_ofm) |
| 176 | |
| 177 | # Pad specific checks: |
| 178 | self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_input_count) |
| 179 | self.specific_constraints[Op.Pad].append(TFLiteSemantic.constraint_pad_constant) |
| 180 | |
| 181 | # HardSwish specific checks: |
| 182 | self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_input_8bit) |
| 183 | self.specific_constraints[Op.HardSwish].append(TFLiteSemantic.constraint_matching_in_out_types) |
Fredrik Svedberg | 701ba91 | 2022-09-07 16:01:15 +0200 | [diff] [blame] | 184 | |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 185 | # Mean specific checks: |
| 186 | self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_input_8bit) |
| 187 | self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_input_dims) |
| 188 | self.specific_constraints[Op.Mean].append(TFLiteSemantic.constraint_mean_axis) |
| 189 | |
| 190 | def is_operator_semantic_valid(self, op): |
| 191 | ext_type = optype_to_builtintype(op.type) |
| 192 | |
| 193 | if op.type in (Op.Placeholder, Op.SubgraphInput, Op.Const): |
| 194 | return True |
| 195 | |
Ayaan Masood | 4965fae | 2022-06-29 11:30:57 +0100 | [diff] [blame] | 196 | # Generic constraints list filtered out to exclude certain constraints depending on op.type |
| 197 | filtered_generic_constraints = [] |
| 198 | |
| 199 | for constraint in self.generic_constraints: |
| 200 | # Check constraint not in dictionary otherwise return empty array |
| 201 | if constraint not in self.get_generic_constraint_exclude_list().get(op.type, []): |
| 202 | filtered_generic_constraints.append(constraint) |
| 203 | |
| 204 | for constraint in filtered_generic_constraints + self.specific_constraints[op.type]: |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 205 | valid, extra = constraint(op) |
| 206 | if not valid: |
| 207 | print( |
Tim Hall | 3584a9c | 2021-11-18 22:05:17 +0000 | [diff] [blame] | 208 | f"Warning: Unsupported TensorFlow Lite semantics for {ext_type} '{op.name}'. Placing on CPU instead" |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 209 | ) |
| 210 | print(f" - {constraint.__doc__}") |
| 211 | if extra: |
| 212 | print(f" {extra}") |
| 213 | return False |
| 214 | |
| 215 | return True |
| 216 | |
| 217 | @staticmethod |
Ayaan Masood | 4965fae | 2022-06-29 11:30:57 +0100 | [diff] [blame] | 218 | def get_generic_constraint_exclude_list(): |
| 219 | |
| 220 | # Not all generic constraints can be applied to each operator |
| 221 | generic_constraints_exclude_list = { |
| 222 | Op.Shape: [ |
| 223 | TFLiteSemantic.constraint_tens_quant_none_check, |
Ayaan Masood | 25f48dd | 2022-06-29 18:16:04 +0100 | [diff] [blame] | 224 | ], |
| 225 | Op.Quantize: [ |
| 226 | TFLiteSemantic.constraint_tens_no_dynamic, |
| 227 | TFLiteSemantic.constraint_tens_output_scalar, |
Ayaan Masood | 25f48dd | 2022-06-29 18:16:04 +0100 | [diff] [blame] | 228 | ], |
Ayaan Masood | 4965fae | 2022-06-29 11:30:57 +0100 | [diff] [blame] | 229 | } |
| 230 | return generic_constraints_exclude_list |
| 231 | |
| 232 | @staticmethod |
erik.andersson@arm.com | 3bbbed6 | 2021-12-20 14:14:16 +0100 | [diff] [blame] | 233 | def constraint_none_const_tensors(op): |
| 234 | "Constant tensors should not have NoneType-values" |
| 235 | valid = True |
| 236 | extra = "" |
| 237 | for tens in filter(None, op.inputs): |
| 238 | if len(tens.ops) > 0 and tens.ops[0].type == Op.Const and tens.values is None: |
| 239 | valid = False |
| 240 | extra = str(tens.name) |
| 241 | return valid, f"Unexpected None value for constant tensor: {extra}" |
| 242 | |
| 243 | @staticmethod |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 244 | def constraint_tens_no_dynamic(op): |
| 245 | "Input(s) and Output tensors must not be dynamic" |
| 246 | valid = True |
| 247 | extra = [] |
| 248 | tensors = [tens for tens in op.inputs + op.outputs if tens] |
| 249 | for tens in tensors: |
| 250 | if (tens.shape == []) and (tens.values is None): |
| 251 | valid = False |
| 252 | extra.append(tens.name) |
| 253 | extra = ", ".join(extra) |
| 254 | return valid, f"Op has dynamic tensor(s): {extra}" |
| 255 | |
| 256 | @staticmethod |
| 257 | def constraint_tens_defined_shape(op): |
| 258 | "Input(s) and Output tensors must have a defined shape" |
| 259 | valid = True |
| 260 | extra = [] |
| 261 | tensors = [tens for tens in op.inputs + op.outputs if tens] |
| 262 | for tens in tensors: |
| 263 | if not tens.has_fully_defined_shape(): |
| 264 | valid = False |
| 265 | extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}") |
| 266 | return valid, ", ".join(extra) |
| 267 | |
| 268 | @staticmethod |
| 269 | def constraint_tens_output_scalar(op): |
| 270 | "Output tensors cannot be scalar" |
| 271 | ofm = op.ofm |
| 272 | valid = ofm.shape != [] |
| 273 | return valid, f"Output Tensor '{ofm.name}' is scalar" |
| 274 | |
| 275 | @classmethod |
| 276 | @docstring_format_args([_optype_formatter(shapeless_input_ops)]) |
| 277 | def constraint_tens_input_scalar(cls, op): |
| 278 | "Scalar Input tensors are only valid for op type: {}" |
| 279 | valid = True |
| 280 | extra = [] |
| 281 | tensors = [tens for tens in op.inputs if tens] |
| 282 | for tens in tensors: |
| 283 | if (tens.shape == []) and (op.type not in cls.shapeless_input_ops): |
| 284 | valid = False |
| 285 | extra.append(tens.name) |
| 286 | extra = ", ".join(extra) |
| 287 | return valid, f"Op has scalar input tensor(s): {extra}" |
| 288 | |
| 289 | @staticmethod |
| 290 | def constraint_tens_shape_size(op): |
| 291 | "Input(s) and Output tensors must not be greater than 4D" |
| 292 | valid = True |
| 293 | extra = [] |
| 294 | tensors = [tens for tens in op.inputs + op.outputs if tens] |
| 295 | for tens in tensors: |
| 296 | if len(tens.shape) > 4: |
| 297 | valid = False |
| 298 | extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}") |
| 299 | return valid, ", ".join(extra) |
| 300 | |
| 301 | @staticmethod |
| 302 | def constraint_tens_quant_none_check(op): |
| 303 | "Input(s), Output and Weight tensors must have quantization parameters" |
| 304 | valid = True |
| 305 | extra = [] |
| 306 | tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens] |
| 307 | for tens in tensors: |
| 308 | if tens.quantization is None: |
| 309 | valid = False |
| 310 | extra.append(tens.name) |
| 311 | extra = ", ".join(extra) |
| 312 | return valid, f"Op has tensors with missing quantization parameters: {extra}" |
| 313 | |
| 314 | @staticmethod |
| 315 | def constraint_tens_quant_scale(op): |
| 316 | "Input(s), Output and Weight tensors with quantization scales must be finite" |
| 317 | valid = True |
| 318 | extra = [] |
| 319 | tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens] |
| 320 | for tens in tensors: |
Fredrik Svedberg | 1156317 | 2022-07-06 14:54:12 +0200 | [diff] [blame] | 321 | if ( |
| 322 | tens.quantization |
| 323 | and tens.quantization.scale_f32 is not None |
| 324 | and np.isinf(tens.quantization.scale_f32).any() |
| 325 | ): |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 326 | valid = False |
| 327 | extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}") |
| 328 | return valid, ", ".join(extra) |
| 329 | |
| 330 | @staticmethod |
| 331 | def constraint_fc_output_2d(op): |
Ayaan Masood | a2ec5aa | 2022-04-21 14:28:03 +0100 | [diff] [blame] | 332 | """The output tensor(s) must have 2D shape""" |
| 333 | valid = op.ifm.get_shape_as_2d(op.weights.shape[-2]) is not None |
| 334 | extra = f"Op has non-2D output tensor '{op.ofm.name}'" if not valid else "" |
| 335 | |
| 336 | return valid, extra |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 337 | |
| 338 | @staticmethod |
| 339 | def constraint_stride_type(op): |
| 340 | "Stride values for both width and height must be integer types" |
| 341 | w, h = op.get_kernel_stride() |
| 342 | valid = is_integer(w) and is_integer(h) |
| 343 | return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}" |
| 344 | |
| 345 | @staticmethod |
| 346 | def constraint_dilation_type(op): |
| 347 | "Dilation factor values for both width and height must be integer types" |
| 348 | w, h = op.get_kernel_dilation() |
| 349 | valid = is_integer(w) and is_integer(h) |
| 350 | return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}" |
| 351 | |
| 352 | @staticmethod |
| 353 | def constraint_quant_scale_inf(op): |
| 354 | "Input and Output tensors must have quantization scales that fit within float32 precision" |
| 355 | if op.ofm is not None and op.ofm.is_quantized(): |
| 356 | ofm_scale = op.ofm.quantization.scale_f32 |
Dwight Lidman | 4caf29d | 2021-10-08 14:26:54 +0200 | [diff] [blame] | 357 | if np.any(ofm_scale < np.finfo(np.float32).tiny): |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 358 | return ( |
| 359 | False, |
| 360 | f"The quantization scale of the output tensor is {ofm_scale}, " |
| 361 | + f"minimum supported is: {np.finfo(np.float32).tiny}", |
| 362 | ) |
| 363 | if op.ifm is not None and op.ifm.is_quantized(): |
| 364 | ifm_scale = op.ifm.quantization.scale_f32 |
Dwight Lidman | 4caf29d | 2021-10-08 14:26:54 +0200 | [diff] [blame] | 365 | if np.any(np.isinf(ifm_scale / ofm_scale)): |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 366 | return ( |
| 367 | False, |
| 368 | f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}", |
| 369 | ) |
| 370 | return True, "Op's quantization is ok" |
| 371 | |
| 372 | @staticmethod |
| 373 | def constraint_matching_in_out_types(op): |
| 374 | "IFM and OFM data types must match" |
| 375 | ifm_dtype = op.ifm.dtype |
| 376 | ofm_dtype = op.ofm.dtype |
| 377 | valid = ifm_dtype == ofm_dtype |
| 378 | return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}" |
| 379 | |
| 380 | @staticmethod |
| 381 | def constraint_beta_value_range(op): |
| 382 | "Beta value needs to be positive" |
| 383 | beta = op.attrs.get("beta", 1.0) |
| 384 | valid = beta >= 0 |
| 385 | return valid, f"Op has beta={beta}" |
| 386 | |
| 387 | @staticmethod |
| 388 | def constraint_filter_type(op): |
| 389 | "Kernel filter values for both width and height must be integer types" |
| 390 | w = op.kernel.width |
| 391 | h = op.kernel.height |
| 392 | valid = is_integer(w) and is_integer(h) |
| 393 | return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}" |
| 394 | |
| 395 | @staticmethod |
| 396 | def constraint_matching_shapes(op): |
| 397 | "IFM and OFM shapes must match" |
| 398 | ifm_shape = op.ifm.shape |
| 399 | ofm_shape = op.ofm.shape |
| 400 | valid = ifm_shape == ofm_shape |
| 401 | return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}" |
| 402 | |
| 403 | @staticmethod |
Johan Alfven | 12e4811 | 2023-01-31 10:26:26 +0100 | [diff] [blame] | 404 | def constraint_split_axis(op): |
| 405 | "Axis value must be in the range [-RANK(IFM) to +RANK(IFM))" |
| 406 | axis_tens = op.inputs[0] |
| 407 | input_tens = op.inputs[1] |
| 408 | dims = len(input_tens.shape) |
| 409 | axis = int(axis_tens.values) |
| 410 | axis += dims if axis < 0 else 0 |
| 411 | valid = 0 <= axis < dims |
| 412 | return valid, f"Op has ifm_dimensions={dims} and axis value is: {axis}" |
| 413 | |
| 414 | @staticmethod |
| 415 | def constraint_split_num_splits(op): |
| 416 | "Axis must be divisible by number of splits" |
| 417 | num_splits = op.attrs.get("num_splits") |
| 418 | axis_tens = op.inputs[0] |
| 419 | input_tens = op.inputs[1] |
| 420 | dims = len(input_tens.shape) |
| 421 | axis = int(axis_tens.values) |
| 422 | axis += dims if axis < 0 else 0 |
| 423 | valid = input_tens.shape[axis] % num_splits == 0 |
| 424 | return valid, f"Op has ifm shape={input_tens.shape} axis={axis} num_splits={num_splits}" |
| 425 | |
| 426 | @staticmethod |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 427 | def constraint_splitv_inferred(op): |
| 428 | "Only one size is allowed to be inferred" |
| 429 | sizes = op.inputs[1].values |
| 430 | valid = np.count_nonzero(sizes == -1) <= 1 |
| 431 | return valid, f"Op has multiple inferred sizes (-1): {sizes}" |
| 432 | |
| 433 | @staticmethod |
| 434 | def constraint_axis_exists(op): |
| 435 | "Axis attribute must exist" |
| 436 | axis = op.attrs.get("axis") |
| 437 | valid = axis is not None |
| 438 | return valid, f"Op has axis={axis}" |
| 439 | |
| 440 | @staticmethod |
| 441 | def constraint_axis_valid(op): |
| 442 | "Axis attribute must be in the range [0, <ofm_dimensions>)" |
| 443 | dims = len(op.ofm.shape) |
| 444 | axis = op.attrs["axis"] |
| 445 | axis += dims if axis < 0 else 0 |
| 446 | valid = 0 <= axis < dims |
| 447 | return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}" |
| 448 | |
| 449 | @staticmethod |
| 450 | def constraint_matching_dimensionality(op): |
| 451 | "All Input dimensionalities must match OFM dimensionality" |
| 452 | valid = True |
| 453 | extra = [] |
| 454 | ofm_dim = len(op.ofm.shape) |
| 455 | tensors = [tens for tens in op.inputs if tens] |
| 456 | for tens in tensors: |
| 457 | dim = len(tens.shape) |
| 458 | if dim != ofm_dim: |
| 459 | valid = False |
| 460 | extra.append(f"Tensor '{tens.name}' has dimension: {dim}") |
| 461 | extra = ", ".join(extra) |
| 462 | return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}" |
| 463 | |
| 464 | @staticmethod |
| 465 | def constraint_valid_dimensions(op): |
| 466 | "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute" |
| 467 | valid = True |
| 468 | extra = [] |
| 469 | ofm_shape = op.ofm.shape |
| 470 | ofm_dim = len(ofm_shape) |
| 471 | axis = op.attrs["axis"] |
| 472 | axis += ofm_dim if axis < 0 else 0 |
| 473 | tensors = [tens for tens in op.inputs if tens] |
| 474 | for tens in tensors: |
| 475 | if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis): |
| 476 | valid = False |
| 477 | extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}") |
| 478 | extra = ", ".join(extra) |
| 479 | return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}" |
| 480 | |
| 481 | @staticmethod |
Johan Alfvén | b393251 | 2022-09-12 17:44:25 +0200 | [diff] [blame] | 482 | def constraint_valid_dimensions_axis(op): |
| 483 | """The size of the OFM axis must match the sum of all IFM axis defined by the axis attribute""" |
| 484 | valid = True |
| 485 | extra = [] |
| 486 | ofm_shape = op.ofm.shape |
| 487 | ofm_dim = len(ofm_shape) |
| 488 | axis = op.attrs["axis"] |
| 489 | axis += ofm_dim if axis < 0 else 0 |
| 490 | |
| 491 | sum_ifm_axis = 0 |
| 492 | tensors = [tens for tens in op.inputs if tens] |
| 493 | for tens in tensors: |
| 494 | sum_ifm_axis += tens.shape[axis] |
| 495 | extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}") |
| 496 | |
| 497 | valid = sum_ifm_axis == ofm_shape[axis] |
| 498 | extra = ", ".join(extra) |
| 499 | return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}" |
| 500 | |
| 501 | @staticmethod |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 502 | def constraint_stridedslice_input_count(op): |
| 503 | "Exactly 4 Input tensors are required" |
| 504 | inputs = len(op.inputs) |
| 505 | valid = inputs == 4 |
| 506 | return valid, f"Op has {inputs} inputs" |
| 507 | |
| 508 | @staticmethod |
| 509 | def constraint_pad_input_count(op): |
| 510 | "Number of input tensors must be exactly 2" |
| 511 | inputs = len(op.inputs) |
| 512 | valid = inputs == 2 |
| 513 | return valid, f"Op has {inputs} inputs" |
| 514 | |
| 515 | @staticmethod |
| 516 | def constraint_pad_constant(op): |
| 517 | "The padding tensor must be constant" |
| 518 | pad_tensor = op.inputs[1].values |
| 519 | valid = pad_tensor is not None |
| 520 | return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}" |
| 521 | |
| 522 | @staticmethod |
| 523 | def constraint_stridedslice_inputs_const(op): |
| 524 | "Begin, End and Stride Input tensors must be constant" |
| 525 | valid = True |
| 526 | extra = [] |
| 527 | _, begin, end, strides = op.inputs |
| 528 | if begin.values is None: |
| 529 | valid = False |
| 530 | extra.append(f"Begin tensor '{begin.name}'") |
| 531 | if end.values is None: |
| 532 | valid = False |
| 533 | extra.append(f"End tensor '{end.name}'") |
| 534 | if strides.values is None: |
| 535 | valid = False |
| 536 | extra.append(f"Stride tensor '{strides.name}'") |
| 537 | extra = ", ".join(extra) |
| 538 | return valid, f"Op has non-constant tensors: {extra}" |
| 539 | |
| 540 | @staticmethod |
| 541 | def constraint_ellipsis_mask(op): |
| 542 | "ellipsis_mask must be 0" |
| 543 | ellipsis = op.attrs["ellipsis_mask"] |
| 544 | valid = ellipsis == 0 |
| 545 | return valid, f"Op has ellipsis mask as: {ellipsis}" |
| 546 | |
| 547 | @staticmethod |
| 548 | def constraint_axis_masks(op): |
| 549 | "new_axis_mask and shrink_axis_mask cannot both be set" |
| 550 | new_axis = op.attrs["new_axis_mask"] |
| 551 | shrink_axis = op.attrs["shrink_axis_mask"] |
| 552 | valid = (new_axis == 0) or (shrink_axis == 0) |
| 553 | return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}" |
| 554 | |
Tim Hall | d0e41cf | 2023-02-14 14:54:18 +0000 | [diff] [blame] | 555 | def _get_slice_offsets(input_shape, offset_tens, offset_mask, is_begin=True): |
| 556 | # For strided slice operator: get start or end offsets |
| 557 | # input_shape: List[int], offset_tens: Tensor, offset_mask: int, is_begin: bool = True |
| 558 | offsets = len(input_shape) * [0] if is_begin else input_shape[:] |
| 559 | for idx in range(len(input_shape)): |
| 560 | # If the i:th bit in the mask is not set then the value in offset_tens[i] should be used, otherwise it |
| 561 | # should be ignored |
| 562 | if (offset_mask & (1 << idx)) == 0: |
| 563 | offsets[idx] = offset_tens.values[idx] |
| 564 | if offsets[idx] < 0: |
| 565 | # Convert negative indexing to positive ones |
| 566 | offsets[idx] += input_shape[idx] |
| 567 | return offsets |
| 568 | |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 569 | @staticmethod |
| 570 | def constraint_slice_ranges(op): |
| 571 | "Slice 'end' values must be greater than 'begin' values" |
| 572 | ifm, begin, end, _ = op.inputs |
Tim Hall | d0e41cf | 2023-02-14 14:54:18 +0000 | [diff] [blame] | 573 | shrink_axis_mask = op.attrs["shrink_axis_mask"] |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 574 | # Calculate offset begin/end |
Tim Hall | d0e41cf | 2023-02-14 14:54:18 +0000 | [diff] [blame] | 575 | offset_begin = TFLiteSemantic._get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True) |
| 576 | offset_end = TFLiteSemantic._get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False) |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 577 | # Check "end - begin" doesn't result in any zero or negative elements |
Tim Hall | d0e41cf | 2023-02-14 14:54:18 +0000 | [diff] [blame] | 578 | valid = True |
| 579 | # if a shrink mask bit is set then the end position provided by the operation should be ignored, and instead a |
| 580 | # new end position should be calculated so that calculations in the graph optimiser, such as (end - start), |
| 581 | # result in the correct value. otherwise, we just need to check that the begin and end values are valid |
| 582 | for i in range(len(ifm.shape)): |
| 583 | if (shrink_axis_mask & (1 << i)) != 0: |
| 584 | offset_end[i] = offset_begin[i] + 1 |
| 585 | else: |
| 586 | if offset_end[i] <= offset_begin[i]: |
| 587 | valid = False |
| 588 | |
| 589 | op.attrs["offset_begin"] = offset_begin |
| 590 | op.attrs["offset_end"] = offset_end |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 591 | return valid, f"Op has begin_values={begin.values} and end_values={end.values}" |
| 592 | |
| 593 | @staticmethod |
| 594 | def constraint_matching_inputs_types(op): |
| 595 | "Both Input data types must match" |
| 596 | ifm_dtype = op.ifm.dtype |
| 597 | ifm2_dtype = op.ifm2.dtype |
| 598 | valid = ifm_dtype == ifm2_dtype |
| 599 | return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}" |
| 600 | |
| 601 | @staticmethod |
| 602 | def constraint_matching_signed(op): |
| 603 | "For IFM that are signed, OFM must also be signed" |
| 604 | valid = True |
| 605 | ifm_dtype = op.ifm.dtype |
| 606 | ofm_dtype = op.ofm.dtype |
| 607 | if ifm_dtype.type & BaseType.Signed: |
| 608 | valid = bool(ofm_dtype.type & BaseType.Signed) |
| 609 | return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}" |
| 610 | |
| 611 | @staticmethod |
| 612 | def constraint_unsigned_valid(op): |
| 613 | "For IFM that are unsigned, OFM must either be the same type or int32" |
| 614 | valid = True |
| 615 | ifm_dtype = op.ifm.dtype |
| 616 | ofm_dtype = op.ofm.dtype |
| 617 | if ifm_dtype.type & BaseType.Unsigned: |
| 618 | valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32) |
| 619 | return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}" |
| 620 | |
| 621 | @staticmethod |
| 622 | def constraint_input_8bit(op): |
| 623 | "IFM must be int8 or uint8" |
| 624 | ifm_dtype = op.ifm.dtype |
| 625 | valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8) |
| 626 | return valid, f"Op has ifm_dtype={ifm_dtype}" |
| 627 | |
| 628 | @staticmethod |
| 629 | def constraint_matching_either_shapes(op): |
| 630 | "At least one Input's shape must match the OFM's shape" |
| 631 | ifm_shape = op.ifm.shape |
| 632 | ifm2_shape = op.ifm2.shape if op.ifm2 else None |
| 633 | ofm_shape = op.ofm.shape |
| 634 | valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape) |
| 635 | return valid, f"Op has ifm_shape={ifm_shape}, ifm2_shape={ifm2_shape} and ofm_shape={ofm_shape}" |
| 636 | |
| 637 | @staticmethod |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 638 | def constraint_keep_dim_ifm_ofm(op): |
| 639 | "The IFM and OFM must have the same number of dimensions if keep_num_dims is set to true" |
| 640 | valid = True |
| 641 | if op.attrs.get("keep_num_dims"): |
| 642 | valid = len(op.ifm.shape) == len(op.ofm.shape) |
| 643 | return valid, f"Op has ifm shape={op.ifm.shape} and ofm shape={op.ofm.shape}" |
| 644 | |
| 645 | @staticmethod |
| 646 | def constraint_mean_input_dims(op): |
| 647 | "Input tensor must be at least 2D" |
| 648 | dims = len(op.inputs[0].shape) |
| 649 | return 2 <= dims <= 4, f"Input is {dims}D" |
| 650 | |
| 651 | @staticmethod |
| 652 | def constraint_mean_axis(op): |
| 653 | "Axis indices must correspond to height and width axes" |
| 654 | dims = len(op.inputs[0].shape) |
| 655 | axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values) |
| 656 | if dims == 2 or dims == 3: |
| 657 | valid = axis in (0, 1, [0], [1], [0, 1], [1, 0]) |
| 658 | elif dims == 4: |
| 659 | valid = axis in (1, 2, [1], [2], [1, 2], [2, 1]) |
| 660 | return valid, f"Axis is {axis}" |
| 661 | |
Jonas Ohlsson | 0957e3e | 2021-09-01 15:57:21 +0200 | [diff] [blame] | 662 | @staticmethod |
| 663 | def constraint_matching_in_out_quant(op): |
| 664 | "Input and output quantisation must match." |
| 665 | if not check_quantized_tens_scaling_equal(op.ifm, op.ofm): |
| 666 | return False, "IFM and OFM quantisation parameters are not equal." |
| 667 | return True, "IFM and OFM quantisation parameters matches." |
| 668 | |
Johan Alfven | 3ac03be | 2023-03-01 09:53:35 +0100 | [diff] [blame^] | 669 | @staticmethod |
| 670 | def constraint_matching_in_out_elements(op): |
| 671 | "Input and output number of elements must match." |
| 672 | if shape_num_elements(op.ifm.shape) != shape_num_elements(op.ofm.shape): |
| 673 | return False, f"IFM {op.ifm.shape} and OFM {op.ofm.shape} number of elements are not equal." |
| 674 | return True, "IFM and OFM number of elements are equal." |
| 675 | |
Jonas Ohlsson | 45e653d | 2021-07-26 16:13:12 +0200 | [diff] [blame] | 676 | |
| 677 | def tflite_semantic_checker(nng): |
| 678 | semantic_checker = TFLiteSemantic() |
| 679 | for sg in nng.subgraphs: |
| 680 | for op in sg.get_all_ops(): |
| 681 | op.run_on_npu = semantic_checker.is_operator_semantic_valid(op) |
| 682 | return nng |