blob: 5d25e37b3b9cd093d400a4e0646b58ff536f493d [file] [log] [blame]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +02001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
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.
16# Description:
17# The TFLiteSupportedOperators class which is a collection of all TFLite supported operators and parameter checks.
18from collections import defaultdict
19
20import numpy as np
21
22from .data_type import DataType
23from .operation import Op
24from .operation import Padding
25from .supported_operators_util import docstring_format_args
26from .supported_operators_util import list_formatter
27from .tensor import check_quantized_tens_scaling_equal
28from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
29from .tflite_mapping import optype_to_builtintype
30
31
32def _optype_formatter(op_list):
33 # Convert internal op types to external names
34 output = map(optype_to_builtintype, op_list)
35 # Remove UNKNOWNs
36 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
37 return list_formatter(output)
38
39
40class TFLiteSupportedOperators:
41 # Categorised lists of supported operators
Fredrik Svedberg11563172022-07-06 14:54:12 +020042 npu_pre_ops = set(
43 (
44 Op.SplitSliceRead,
45 Op.Shape,
46 )
47 )
Jonas Ohlssond8575072022-03-30 10:30:25 +020048 convolution_ops = set(
49 (
50 Op.Conv2DBias,
51 Op.Conv2D,
52 Op.QuantizedConv2D,
53 )
54 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020055 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
56 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
57 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
58 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
59 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
60 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
Tim Hall885033b2022-07-21 11:46:03 +010061 resizing_ops = Op.op_set(Op.is_resize_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020062 fc_vector_products = set(
63 (
64 Op.QuantizedMatMul,
65 Op.MatMul,
66 Op.FullyConnected,
67 )
68 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020069 mac_main_ops = (
70 # RNN/LSTM/GRU
71 set((Op.BlockLSTM,))
72 # conv/depthwiseconv/transposeconv
73 | convolution_like_ops
74 # pooling
75 | pooling_ops
76 # resizing/upscaling
77 | resizing_ops
78 # FC layers
79 | fc_vector_products
80 # Mean (converts to depthwise conv)
81 | set((Op.Mean,))
82 )
83 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020084 binary_elem_wise_min_max_ops = set(
85 (
86 Op.Minimum,
87 Op.Maximum,
88 )
89 )
90 binary_elem_wise_shift_ops = set(
91 (
92 Op.SHL,
93 Op.SHR,
94 )
95 )
96 binary_elem_wise_add_mul_sub = set(
97 (
98 Op.Add,
99 Op.Mul,
100 Op.Sub,
101 )
102 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200103 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
104 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
105 pad_ops = set((Op.Pad,))
106 supported_int32_tensor_ops = (
Jonas Ohlssond8575072022-03-30 10:30:25 +0200107 set(
108 (
109 Op.ReduceSum,
110 Op.CLZ,
Fredrik Svedberg11563172022-07-06 14:54:12 +0200111 Op.Shape,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200112 )
113 )
114 | binary_elem_wise_add_mul_sub
115 | binary_elem_wise_shift_ops
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200116 )
117
Jonas Ohlssond8575072022-03-30 10:30:25 +0200118 relu_ops = set(
119 (
120 Op.Relu,
121 Op.Relu6,
122 Op.ReluN1To1,
123 Op.Clip,
124 )
125 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200126 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax, Op.HardSwish))
127 npu_post_ops = (
128 # activation functions
129 activation_ops
130 # concatenation write direction
131 | set((Op.ConcatSliceWrite,))
132 # Quantization
133 | set((Op.Quantize,))
134 )
Jonas Ohlssond8575072022-03-30 10:30:25 +0200135 split_ops = set(
136 (
137 Op.Split,
138 Op.SplitV,
139 Op.StridedSlice,
140 Op.Slice,
141 Op.UnpackReshaped,
142 Op.Unpack,
143 )
144 )
145 concat_ops = set(
146 (
147 Op.Concat,
148 Op.ConcatTFLite,
149 Op.PackReshaped,
150 Op.Pack,
151 )
152 )
153 memory_only_ops = (
154 set(
155 (
156 Op.Reshape,
157 Op.QuantizedReshape,
158 Op.Squeeze,
159 Op.ExpandDims,
160 )
161 )
162 | concat_ops
163 | split_ops
164 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200165 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Jonas Ohlssond8575072022-03-30 10:30:25 +0200166 supported_fused_activations = relu_ops | set(
167 (
168 Op.Tanh,
169 Op.Sigmoid,
170 Op.LUT,
171 )
172 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200173 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
174 # Supported data types
175 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
176 supported_faf_dtypes = set((DataType.uint8, DataType.int8, DataType.int16))
177 supported_bias_dtypes = set((DataType.int32, DataType.int64))
178 supported_pad_dtypes = set((DataType.int32, DataType.int64))
179 # Defined ranges for allowed values:
180 tens_dim_range = (1, 65535)
181 stride_range = (1, 3)
182 dilation_range = (1, 2)
183 dilated_height_range = (1, 64)
184 dilated_product_range = (1, 64 * 64)
185 weights_limit = 127 * 65536
186 filter_range = (1, 8)
187 filter_height_range = (1, 256)
188 filter_product_range = (1, 256 * 256)
189 mean_kernel_product = 64 * 64
190 mean_kernel_product_int8 = 16 * 16
191 mean_kernel_product_avgpool = 256 * 256
192
193 def __init__(self):
194 # Setup the generic constraints. Note: the order matters
195 self.generic_constraints = []
196 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dtype)
197 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_int32_ops)
198 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dimension)
199 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_quant_per_axis)
200 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf)
201 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf_type)
202
203 # Setup specific constraints. Note: the order matters
204 self.specific_constraints = defaultdict(list)
205
206 # Conv-like checks:
207 for op_type in TFLiteSupportedOperators.convolution_like_ops:
208 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
209 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilation_range)
210 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_height_range)
211 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_product_range)
212 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
213 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
214 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_limit)
215 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
216 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
217 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
218 # Depthwise Conv specific checks:
219 for op_type in TFLiteSupportedOperators.depthwise_convolution_ops:
220 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_depth_multiplier)
221 # Transpose Conv specific checks:
222 for op_type in TFLiteSupportedOperators.transpose_convolution_ops:
223 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_stride)
224 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_same)
225 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_valid)
226
227 # Pooling checks:
228 for op_type in TFLiteSupportedOperators.pooling_ops:
229 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
230 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
231 # AVG pooling specific checks:
232 for op_type in TFLiteSupportedOperators.avg_pooling_ops:
233 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_range)
234 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range_valid_pad)
235 self.specific_constraints[op_type].append(
236 TFLiteSupportedOperators.constraint_filter_product_range_valid_pad
237 )
238 # MAX pooling specific checks:
239 for op_type in TFLiteSupportedOperators.max_pooling_ops:
240 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range)
241 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_product_range)
242
243 # Resizing specific checks:
244 for op_type in TFLiteSupportedOperators.resizing_ops:
Tim Hall885033b2022-07-21 11:46:03 +0100245 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize)
246 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_size)
247 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_attrs)
248 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_half_pixel_centers)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200249
250 # Vector Product specific checks:
251 for op_type in TFLiteSupportedOperators.fc_vector_products:
252 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
253 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
254 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
255 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
256
257 # Element-wise checks:
258 for op_type in TFLiteSupportedOperators.elem_wise_main_ops:
259 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_elemwise_batch_size)
260 # Binary Min/Max specific checks:
261 for op_type in TFLiteSupportedOperators.binary_elem_wise_min_max_ops:
262 self.specific_constraints[op_type].append(
263 TFLiteSupportedOperators.constraint_matching_quantization_parameters
264 )
265 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
266 # Binary Add/Mul/Sub specific checks:
267 for op_type in TFLiteSupportedOperators.binary_elem_wise_add_mul_sub:
268 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
269 # Binary Shift specific checks:
270 for op_type in TFLiteSupportedOperators.binary_elem_wise_shift_ops:
271 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_inputs_int32)
272 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
273
274 # SHL specific checks:
275 self.specific_constraints[Op.SHL].append(TFLiteSupportedOperators.constraint_output_int32)
276
277 # CLZ specific checks:
278 self.specific_constraints[Op.CLZ].append(TFLiteSupportedOperators.constraint_output_int32)
279
280 # StridedSlice specific checks:
281 self.specific_constraints[Op.StridedSlice].append(
282 TFLiteSupportedOperators.constraint_stridedslice_stride_values
283 )
284
285 # Pad specific checks:
286 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_shape)
287 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_padding_dimensions)
288 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_type)
289
290 # Mean specific checks:
Dwight Lidmanf54c18d2021-09-29 17:23:03 +0200291 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_batch_size)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200292 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_avgpool)
293 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product)
294 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_int8)
James Peet0bb7ad12022-02-15 15:07:54 +0000295 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_single_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200296
Tim Hall3584a9c2021-11-18 22:05:17 +0000297 # Reshape specific checks:
298 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
299
Johan Alfvén8e1352a2022-08-16 13:04:17 +0200300 # Concat specific checks:
301 for op_type in (Op.Concat, Op.ConcatTFLite):
302 self.specific_constraints[op_type].append(
303 TFLiteSupportedOperators.constraint_concat_valid_dimensions_non_axis
304 )
305 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_concat_valid_dimensions_axis)
306
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200307 def is_operator_supported(self, op):
308 ext_type = optype_to_builtintype(op.type)
309 if op.type not in TFLiteSupportedOperators.supported_operators:
310 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
311 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
312 return False
313
314 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
315 valid, extra = constraint(op)
316 if not valid:
317 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
318 print(f" - {constraint.__doc__}")
319 if extra:
320 print(f" {extra}")
321 return False
322
323 return True
324
325 @classmethod
326 @docstring_format_args([list_formatter(supported_op_dtypes)])
327 def constraint_tens_dtype(cls, op):
328 "Tensors must be of type: {}"
329 valid = True
330 extra = []
331 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
332 if not tensors:
333 tensors = [tens for tens in op.inputs if tens]
334 for tens in tensors:
335 if tens.dtype not in cls.supported_op_dtypes:
336 valid = False
337 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
338 return valid, ", ".join(extra)
339
340 @classmethod
341 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
342 def constraint_tens_int32_ops(cls, op):
343 "Tensors which are int32 are only valid when op type is: {}"
344 valid = True
345 extra = []
346 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
347 if not tensors:
348 tensors = [tens for tens in op.inputs if tens]
349 for tens in tensors:
350 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
351 valid = False
352 extra.append(tens.name)
353 extra = ", ".join(extra)
354 return valid, f"Op has int32 tensor(s): {extra}"
355
356 @classmethod
357 @docstring_format_args(tens_dim_range)
358 def constraint_tens_dimension(cls, op):
359 "Tensor dimensions must be in the range [{}, {}]"
360 tens_min, tens_max = cls.tens_dim_range
361 valid = True
362 extra = []
363 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
364 if not tensors:
365 tensors = [tens for tens in op.inputs if tens]
366 for tens in tensors:
367 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
368 valid = False
369 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
370 return valid, ", ".join(extra)
371
372 @classmethod
373 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
374 def constraint_tens_quant_per_axis(cls, op):
375 "Per-axis quantization is only supported for the following op types: {}"
376 valid = True
377 extra = []
378 if op.type not in cls.per_axis_quant_ops:
379 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
380 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200381 if tens.quantization and tens.quantization.is_per_axis():
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200382 valid = False
383 extra.append(tens.name)
384 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
385
386 @classmethod
387 @docstring_format_args([_optype_formatter(supported_fused_activations)])
388 def constraint_faf(cls, op):
389 "The fused activation function (if present) must be one of type: {}"
390 if op.activation is None:
391 res = True, "Op has no fused activation function"
392 else:
393 faf = op.activation.op_type
394 valid = faf in cls.supported_fused_activations
395 res = valid, f"Op has its fused activation function as: {faf}"
396 return res
397
398 @classmethod
399 @docstring_format_args([list_formatter(supported_faf_dtypes)])
400 def constraint_faf_type(cls, op):
401 "If a fused activation function is present, the Output tensor must be one of type: {}"
402 if op.activation is None:
403 res = True, "Op has no fused activation function"
404 else:
405 valid = op.ofm.dtype in cls.supported_faf_dtypes
406 ext_type = optype_to_builtintype(op.activation.op_type)
407 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
408 return res
409
410 @classmethod
411 @docstring_format_args(stride_range)
412 def constraint_stride_range(cls, op):
413 "Stride values for both width and height must be in the range [{}, {}]"
414 w, h = op.get_kernel_stride()
415 stride_min, stride_max = cls.stride_range
416 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
417 return valid, f"Op has stride WxH as: {w}x{h}"
418
419 @classmethod
420 @docstring_format_args(dilation_range)
421 def constraint_dilation_range(cls, op):
422 "Dilation factor values for both width and height must be in the range [{}, {}]"
423 w, h = op.get_kernel_dilation()
424 dilation_min, dilation_max = cls.dilation_range
425 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
426 return valid, f"Op has dilation factor WxH as: {w}x{h}"
427
428 @classmethod
429 @docstring_format_args(dilated_height_range)
430 def constraint_dilated_height_range(cls, op):
431 "Dilated kernel height must be in the range [{}, {}]"
432 h = op.kernel.area_height()
433 dilated_height_min, dilated_height_max = cls.dilated_height_range
434 valid = dilated_height_min <= h <= dilated_height_max
435 return valid, f"Op has dilated kernel height as: {h}"
436
437 @classmethod
438 @docstring_format_args(dilated_product_range)
439 def constraint_dilated_product_range(cls, op):
440 "Product of dilated kernel width and height must be in the range [{}, {}]"
441 product = op.kernel.area_width() * op.kernel.area_height()
442 dilated_product_min, dilated_product_max = cls.dilated_product_range
443 valid = dilated_product_min <= product <= dilated_product_max
444 return valid, f"Op has product of dilated kernel width and height as: {product}"
445
446 @staticmethod
447 def constraint_weights_type(op):
448 "Weight tensor must be 8-bit"
449 weights = op.weights
450 valid = weights.element_size() == 1
451 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
452
453 @staticmethod
454 def constraint_weights_const(op):
455 "Weight tensor must be constant"
456 weights = op.weights
457 valid = weights.values is not None
458 return valid, f"Tensor '{weights.name}' has non-constant values"
459
460 @classmethod
461 @docstring_format_args([weights_limit])
462 def constraint_weights_limit(cls, op):
463 "The sum of the weights cannot exceed {}"
464 weights = op.weights
465 values = weights.values.astype(np.int64) - weights.quantization.zero_point
466 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
467 valid = limit <= cls.weights_limit
468 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
469
470 @classmethod
471 @docstring_format_args([list_formatter(supported_bias_dtypes)])
472 def constraint_bias_type(cls, op):
473 "Optional Bias tensor must be of type: {}"
474 bias = op.bias
475 if bias:
476 valid = bias.dtype in cls.supported_bias_dtypes
477 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
478 return True, "Op has no bias tensor"
479
480 @staticmethod
481 def constraint_bias_40bit(op):
482 "Optional Bias tensor values must fit within 40-bits"
483 bias = op.bias
484 if bias and bias.dtype == DataType.int64 and bias.values is not None:
Tim Hall8ae29292021-07-28 16:52:03 +0100485 valid = all(len(bin(value)[2:]) <= 40 for value in bias.values)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200486 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
487 return True, "Op has no bias tensor, or it fits in 40-bit"
488
489 @staticmethod
490 def constraint_batch_size(op):
491 "IFM Tensor batch size must be 1"
492 ifm = op.ifm
493 valid = ifm.shape[0] == 1
494 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
495
496 @staticmethod
497 def constraint_depth_multiplier(op):
498 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
499 depth_multiplier = op.attrs.get("depth_multiplier", 1)
500 if depth_multiplier > 1:
501 ifm_channels = op.ifm.shape[3]
502 ofm_channels = op.ofm.shape[3]
503 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
504 extra = (
505 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
506 f" and depth_multiplier={depth_multiplier}"
507 )
508 return valid, extra
509 return True, "Op has depth_multiplier=1"
510
511 @staticmethod
512 def constraint_tconv_stride(op):
513 "Stride values for both width and height must be 2"
514 w = op.kernel.stride.x
515 h = op.kernel.stride.y
516 valid = (w == 2) and (h == 2)
517 return valid, f"Op has stride WxH as: {w}x{h}"
518
519 @staticmethod
520 def constraint_tconv_same(op):
521 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
522 if op.attrs["padding"] == Padding.SAME:
523 w = op.kernel.stride.x
524 h = op.kernel.stride.y
525 ifm_shape = op.ifm.shape
526 ofm_shape = op.ofm.shape
527 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
528 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
529 return True, "Op has padding=VALID"
530
531 @staticmethod
532 def constraint_tconv_valid(op):
533 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200534 minus difference between kernel size and stride"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200535 if op.attrs["padding"] == Padding.VALID:
536 s_w = op.kernel.stride.x
537 s_h = op.kernel.stride.y
538 k_w = op.kernel.width
539 k_h = op.kernel.height
540 ifm_shape = op.ifm.shape
541 ofm_shape = op.ofm.shape
542 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
543 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
544 valid = height_check and width_check
545 extra = (
546 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
547 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
548 )
549 return valid, extra
550 return True, "Op has padding=SAME"
551
552 @classmethod
553 @docstring_format_args(filter_range)
554 def constraint_filter_range(cls, op):
555 "Kernel filter values for both width and height must be in the range [{}, {}]"
556 if op.attrs["padding"] == Padding.SAME:
557 w = op.kernel.width
558 h = op.kernel.height
559 filter_min, filter_max = cls.filter_range
560 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
561 return valid, f"Op has kernel filter WxH as: {w}x{h}"
562 return True, "Op has padding=VALID"
563
564 @classmethod
565 @docstring_format_args(filter_height_range)
566 def constraint_filter_height_range(cls, op):
567 "Kernel filter height must be in the range [{}, {}]"
568 h = op.kernel.height
569 filter_height_min, filter_height_max = cls.filter_height_range
570 valid = filter_height_min <= h <= filter_height_max
571 return valid, f"Op has kernel filter height as: {h}"
572
573 @classmethod
574 @docstring_format_args(filter_product_range)
575 def constraint_filter_product_range(cls, op):
576 "Product of kernel filter width and height must be in the range [{}, {}]"
577 product = op.kernel.elements_wh()
578 filter_product_min, filter_product_max = cls.filter_product_range
579 valid = filter_product_min <= product <= filter_product_max
580 return valid, f"Op has product of kernel filter width and height as: {product}"
581
582 @staticmethod
583 @docstring_format_args(filter_height_range)
584 def constraint_filter_height_range_valid_pad(op):
585 "VALID padding: Kernel filter height must be in the range [{}, {}]"
586 if op.attrs["padding"] == Padding.VALID:
587 return TFLiteSupportedOperators.constraint_filter_height_range(op)
588 return True, "Op has padding=SAME"
589
590 @staticmethod
591 @docstring_format_args(filter_product_range)
592 def constraint_filter_product_range_valid_pad(op):
593 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
594 if op.attrs["padding"] == Padding.VALID:
595 return TFLiteSupportedOperators.constraint_filter_product_range(op)
596 return True, "Op has padding=SAME"
597
598 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100599 def constraint_resize(op):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200600 """The width and height of the IFM and OFM must match one of the following criteria:
601 IFM W and H must both be 1
602 IFM must match OFM
Tim Hall47c76362022-07-18 21:26:47 +0100603 OFM W and H must be equal and OFM W-1 and H-1 must be 2x/4x/8x IFM W-1 and H-1, if align_corners is True
604 OFM W and H must be equal and OFM W and H must be 2x/4x/8x IFM W and H, if align_corners is False"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200605 # Easier to start with False condition as very few cases result in a supported resize
606 valid = False
607 ifm_shape = op.ifm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100608 ifm_shape_h = ifm_shape[1]
609 ifm_shape_w = ifm_shape[2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200610 ofm_shape = op.ofm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100611 ofm_shape_h = ofm_shape[1]
612 ofm_shape_w = ofm_shape[2]
613
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200614 align_corners = op.attrs.get("align_corners", False)
615 if len(ifm_shape) == 4:
616 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
Tim Hall47c76362022-07-18 21:26:47 +0100617 if ((ifm_shape_h == 1) and (ifm_shape_w == 1)) or (ifm_shape == ofm_shape):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200618 valid = True
619 else:
Rickard Boline546def2022-01-25 15:45:00 +0000620 # Valid if OFM is 2/4/8x IFM (-1 for align corners)
Tim Hall47c76362022-07-18 21:26:47 +0100621 if align_corners:
622 h_upscale_factor = (ofm_shape_h - 1) / (ifm_shape_h - 1)
623 w_upscale_factor = (ofm_shape_w - 1) / (ifm_shape_w - 1)
624 else:
625 h_upscale_factor = ofm_shape_h / ifm_shape_h
626 w_upscale_factor = ofm_shape_w / ifm_shape_w
Rickard Boline546def2022-01-25 15:45:00 +0000627
Tim Hall47c76362022-07-18 21:26:47 +0100628 # could use either height or width. save as int because it is more usable later in graph optimiser
629 op.attrs["upscale_factor"] = int(h_upscale_factor)
630 valid = h_upscale_factor == w_upscale_factor and h_upscale_factor in (2.0, 4.0, 8.0)
Rickard Boline546def2022-01-25 15:45:00 +0000631
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200632 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
633
634 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100635 def constraint_resize_size(op):
Tim Hall47c76362022-07-18 21:26:47 +0100636 "The size tensor must match the output tensor shape"
637 valid = False
638 ofm_shape = op.ofm.shape
639 size_h, size_w = None, None
640 # check that the size tensor (the second input) exists, is not none, and has the correct values
641 if len(op.inputs) == 2 and op.inputs[1] is not None and len(op.inputs[1].values) == 2:
642 size_h, size_w = op.inputs[1].values
643 # check size and output size match
644 if size_h == ofm_shape[1] and size_w == ofm_shape[2]:
645 valid = True
646
647 return valid, f"Op has size={size_h}x{size_w} and ofm_shape={ofm_shape}."
648
649 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100650 def constraint_resize_attrs(op):
Tim Hall47c76362022-07-18 21:26:47 +0100651 "Both align_corners and half_pixel_centers can't be True"
652 valid = True
653 align_corners = op.attrs.get("align_corners", False)
654 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
655
656 if align_corners and half_pixel_centers:
657 valid = False
658 return valid, "Op has both align_corners and half_pixel_centers set to True."
659
660 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100661 def constraint_resize_half_pixel_centers(op):
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200662 "half_pixel_centers are not supported"
663 valid = True
Tim Hall47c76362022-07-18 21:26:47 +0100664 if op.attrs.get("half_pixel_centers", False):
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200665 valid = False
666 return valid, f"Op has half_pixel_centers set to {not valid}."
667
668 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200669 def constraint_pad_shape(op):
670 "The padding tensor must have the shape [3,2] or [4,2]"
671 valid = op.inputs[1].shape in ([3, 2], [4, 2])
672 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
673
674 @classmethod
675 @docstring_format_args([list_formatter(supported_pad_dtypes)])
676 def constraint_pad_type(cls, op):
677 "Pad tensor must be of type: {}"
678 pad_tensor = op.inputs[1]
679 valid = pad_tensor.dtype in cls.supported_pad_dtypes
680 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
681
682 @staticmethod
683 def constraint_padding_dimensions(op):
684 "The pad tensor can only pad width and height"
685 pad_tensor = op.inputs[1].values
686
687 valid = sum(pad_tensor[-1, :]) == 0
688 if valid and len(pad_tensor) > 3:
689 valid = sum(pad_tensor[0, :]) == 0
690 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
691
692 @staticmethod
693 def constraint_stridedslice_stride_values(op):
694 "All Strides values must be 1"
695 strides = op.inputs[3]
696 valid = all(stride == 1 for stride in strides.values)
697 return valid, f"Op has strides values {strides.values}"
698
699 @staticmethod
700 def constraint_inputs_int32(op):
701 "Both Input data types must be int32"
702 ifm_dtype = op.ifm.dtype
703 ifm2_dtype = op.ifm2.dtype
704 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
705 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
706
707 @staticmethod
708 def constraint_output_int32(op):
709 "OFM must be int32"
710 ofm_dtype = op.ofm.dtype
711 valid = ofm_dtype == DataType.int32
712 return valid, f"Op has ofm_dtype={ofm_dtype}"
713
714 @staticmethod
715 def constraint_matching_quantization_parameters(op):
716 "Both Input quantization parameters must match OFM quantization parameters"
717 valid = True
718 extra = []
719 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
720 valid = False
721 extra.append(op.ifm.name)
722 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
723 valid = False
724 extra.append(op.ifm2.name)
725 extra = ", ".join(extra)
726 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
727
728 @staticmethod
729 def constraint_elemwise_batch_size(op):
730 "Batch size must be 1 for Input tensors with more than 2 dimensions"
731 valid = True
732 extra = []
733 for tens in (op.ifm, op.ifm2):
734 # Unary ops have ifm2 as None
735 if tens is not None:
736 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
737 valid = False
738 extra.append(tens.name)
739 extra = ", ".join(extra)
740 return valid, f"Op has invalid input tensors: {extra}"
741
742 @staticmethod
743 def constraint_broadcast_shapes(op):
744 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
745 ifm_shape = op.ifm.shape
746 ifm2_shape = op.ifm2.shape if op.ifm2 else None
747 ofm_shape = op.ofm.shape
748 valid = True
749 if ifm_shape is not None and ifm2_shape is not None:
750 # align trailing dimensions
751 size = min(len(ifm_shape), len(ifm2_shape))
752 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
753 mi = max(i, i2)
754 # Input dimensions should match or one should be of dimension 1
755 # Output dimension should match the largest input dimension, together
756 # with constraint_match_either_shapes ensures broadcast from only one input
757 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
758 valid = False
759 break
760
761 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
762
763 @classmethod
764 @docstring_format_args([mean_kernel_product_avgpool])
765 def constraint_mean_height_width_product_avgpool(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000766 """Product of height and width must be no greater than {}"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200767 shape = op.inputs[0].shape
768 hi = 0 if len(shape) < 4 else 1
769 h, w = shape[hi : hi + 2]
770 max_prod = cls.mean_kernel_product_avgpool
771 return h * w <= max_prod, f"Product of height and width is {h * w}"
772
773 @classmethod
774 @docstring_format_args([mean_kernel_product])
775 def constraint_mean_height_width_product(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000776 """Product of height and width must be no greater than {} when:
777 IFM and OFM have different scale or zero point; or
778 'keep_dims' is True"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200779 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
780 keep_dims = op.attrs.get("keep_dims")
781 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
782 if not keep_dims and ifmq.scale_f32 == ofmq.scale_f32 and ifmq.zero_point == ofmq.zero_point:
783 return True, ""
784 shape = op.inputs[0].shape
785 hi = 0 if len(shape) < 4 else 1
786 h, w = shape[hi : hi + 2]
787 max_prod = cls.mean_kernel_product
788 return h * w <= max_prod, f"Product of height and width is {h * w}"
789
790 @classmethod
791 @docstring_format_args([mean_kernel_product_int8])
792 def constraint_mean_height_width_product_int8(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000793 """Product of IFM height and width must be no greater than {} when:
794 The IFM shape has 4 dimensions; and
795 The axis indices specify reduction across 2 dimensions; and
796 The axis indices correspond to the width and height dimensions of the IFM; and
797 'keep_dims' is True; and
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200798 IFM datatype is int8"""
799 shape = op.ifm.shape
800 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
801 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
802 # and constraint_mean_height_width_product
803 if (
804 len(shape) != 4
805 or op.ifm.dtype != DataType.int8
806 or not op.attrs.get("keep_dims")
807 or axis not in ([1, 2], [2, 1])
808 ):
809 return True, ""
James Peet0bb7ad12022-02-15 15:07:54 +0000810 h = shape[-3]
811 w = shape[-2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200812 max_prod = cls.mean_kernel_product_int8
813 return h * w <= max_prod, f"Product of height and width is {h * w}"
Tim Hall3584a9c2021-11-18 22:05:17 +0000814
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000815 @classmethod
James Peet0bb7ad12022-02-15 15:07:54 +0000816 @docstring_format_args([filter_height_range[1], dilated_height_range[1]])
817 def constraint_mean_height_single_axis(cls, op):
818 """For single axis averages across the height dimension:
819 IFM height must be no greater than {} if the IFM and OFM scale and zero point match; otherwise
820 IFM height must be no greater than {} if the IFM and OFM scale or zero point do not match"""
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000821 inp, axis = op.inputs
822 if axis.shape == [] or axis.shape[0] == 1: # single axis
823 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
824 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000825 # Multiple axes
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000826 return True, ""
827
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000828 shape = inp.shape
James Peet0bb7ad12022-02-15 15:07:54 +0000829 if len(shape) < 3:
830 # No height dimension present in IFM
831 return True, ""
832 if axis != len(shape) - 3:
833 # Not averaging across the height dimension
834 return True, ""
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000835
James Peet0bb7ad12022-02-15 15:07:54 +0000836 h = shape[axis]
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000837 ifm, ofm = op.get_ifm_ofm()
James Peet0bb7ad12022-02-15 15:07:54 +0000838
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000839 if check_quantized_tens_scaling_equal(ifm, ofm):
James Peet0bb7ad12022-02-15 15:07:54 +0000840 return h <= cls.filter_height_range[1], f"Height is {h}, IFM and OFM quantizations match"
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000841 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000842 return h <= cls.dilated_height_range[1], f"Height is {h}, IFM and OFM quantizations do not match"
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000843
Tim Hall3584a9c2021-11-18 22:05:17 +0000844 @staticmethod
845 def constraint_reshape_shape_constant(op):
846 "Shape must be constant"
847 valid = True
848 extra = []
849
850 reshape_tens = op.inputs[1]
851 if reshape_tens is not None:
852 # constant inputs have either no driving operator or a const one
853 # create a list of non-constant inputs
854 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
855 valid = False
856 extra.append(reshape_tens.name)
857 extra = ", ".join(extra)
858
859 return valid, f"Op has non-const input(s): {extra}"
Johan Alfvén8e1352a2022-08-16 13:04:17 +0200860
861 @staticmethod
862 def constraint_concat_valid_dimensions_non_axis(op):
863 """All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"""
864 valid = True
865 extra = []
866 ofm_shape = op.ofm.shape
867 ofm_dim = len(ofm_shape)
868 axis = op.attrs["axis"]
869 axis += ofm_dim if axis < 0 else 0
870
871 tensors = [tens for tens in op.inputs if tens]
872 for tens in tensors:
873 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
874 valid = False
875 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
876
877 extra = ", ".join(extra)
878 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
879
880 @staticmethod
881 def constraint_concat_valid_dimensions_axis(op):
882 """The size of the OFM axis must match the sum of all IFM axis defined by the axis attribute"""
883 valid = True
884 extra = []
885 ofm_shape = op.ofm.shape
886 ofm_dim = len(ofm_shape)
887 axis = op.attrs["axis"]
888 axis += ofm_dim if axis < 0 else 0
889
890 sum_ifm_axis = 0
891 tensors = [tens for tens in op.inputs if tens]
892 for tens in tensors:
893 sum_ifm_axis += tens.shape[axis]
894 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
895
896 valid = sum_ifm_axis == ofm_shape[axis]
897 extra = ", ".join(extra)
898 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"