blob: 25a34e829e54b04aa7cb837a9a8cc6b3d4c3d3f6 [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
61 resizing_ops = set((Op.ResizeBilinear,))
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:
245 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize)
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200246 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bilinear_resize_attrs)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200247
248 # Vector Product specific checks:
249 for op_type in TFLiteSupportedOperators.fc_vector_products:
250 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
251 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
252 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
253 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
254
255 # Element-wise checks:
256 for op_type in TFLiteSupportedOperators.elem_wise_main_ops:
257 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_elemwise_batch_size)
258 # Binary Min/Max specific checks:
259 for op_type in TFLiteSupportedOperators.binary_elem_wise_min_max_ops:
260 self.specific_constraints[op_type].append(
261 TFLiteSupportedOperators.constraint_matching_quantization_parameters
262 )
263 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
264 # Binary Add/Mul/Sub specific checks:
265 for op_type in TFLiteSupportedOperators.binary_elem_wise_add_mul_sub:
266 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
267 # Binary Shift specific checks:
268 for op_type in TFLiteSupportedOperators.binary_elem_wise_shift_ops:
269 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_inputs_int32)
270 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
271
272 # SHL specific checks:
273 self.specific_constraints[Op.SHL].append(TFLiteSupportedOperators.constraint_output_int32)
274
275 # CLZ specific checks:
276 self.specific_constraints[Op.CLZ].append(TFLiteSupportedOperators.constraint_output_int32)
277
278 # StridedSlice specific checks:
279 self.specific_constraints[Op.StridedSlice].append(
280 TFLiteSupportedOperators.constraint_stridedslice_stride_values
281 )
282
283 # Pad specific checks:
284 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_shape)
285 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_padding_dimensions)
286 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_type)
287
288 # Mean specific checks:
Dwight Lidmanf54c18d2021-09-29 17:23:03 +0200289 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_batch_size)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200290 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_avgpool)
291 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product)
292 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_int8)
James Peet0bb7ad12022-02-15 15:07:54 +0000293 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_single_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200294
Tim Hall3584a9c2021-11-18 22:05:17 +0000295 # Reshape specific checks:
296 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
297
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200298 def is_operator_supported(self, op):
299 ext_type = optype_to_builtintype(op.type)
300 if op.type not in TFLiteSupportedOperators.supported_operators:
301 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
302 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
303 return False
304
305 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
306 valid, extra = constraint(op)
307 if not valid:
308 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
309 print(f" - {constraint.__doc__}")
310 if extra:
311 print(f" {extra}")
312 return False
313
314 return True
315
316 @classmethod
317 @docstring_format_args([list_formatter(supported_op_dtypes)])
318 def constraint_tens_dtype(cls, op):
319 "Tensors must be of type: {}"
320 valid = True
321 extra = []
322 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
323 if not tensors:
324 tensors = [tens for tens in op.inputs if tens]
325 for tens in tensors:
326 if tens.dtype not in cls.supported_op_dtypes:
327 valid = False
328 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
329 return valid, ", ".join(extra)
330
331 @classmethod
332 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
333 def constraint_tens_int32_ops(cls, op):
334 "Tensors which are int32 are only valid when op type is: {}"
335 valid = True
336 extra = []
337 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
338 if not tensors:
339 tensors = [tens for tens in op.inputs if tens]
340 for tens in tensors:
341 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
342 valid = False
343 extra.append(tens.name)
344 extra = ", ".join(extra)
345 return valid, f"Op has int32 tensor(s): {extra}"
346
347 @classmethod
348 @docstring_format_args(tens_dim_range)
349 def constraint_tens_dimension(cls, op):
350 "Tensor dimensions must be in the range [{}, {}]"
351 tens_min, tens_max = cls.tens_dim_range
352 valid = True
353 extra = []
354 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
355 if not tensors:
356 tensors = [tens for tens in op.inputs if tens]
357 for tens in tensors:
358 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
359 valid = False
360 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
361 return valid, ", ".join(extra)
362
363 @classmethod
364 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
365 def constraint_tens_quant_per_axis(cls, op):
366 "Per-axis quantization is only supported for the following op types: {}"
367 valid = True
368 extra = []
369 if op.type not in cls.per_axis_quant_ops:
370 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
371 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200372 if tens.quantization and tens.quantization.is_per_axis():
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200373 valid = False
374 extra.append(tens.name)
375 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
376
377 @classmethod
378 @docstring_format_args([_optype_formatter(supported_fused_activations)])
379 def constraint_faf(cls, op):
380 "The fused activation function (if present) must be one of type: {}"
381 if op.activation is None:
382 res = True, "Op has no fused activation function"
383 else:
384 faf = op.activation.op_type
385 valid = faf in cls.supported_fused_activations
386 res = valid, f"Op has its fused activation function as: {faf}"
387 return res
388
389 @classmethod
390 @docstring_format_args([list_formatter(supported_faf_dtypes)])
391 def constraint_faf_type(cls, op):
392 "If a fused activation function is present, the Output tensor must be one of type: {}"
393 if op.activation is None:
394 res = True, "Op has no fused activation function"
395 else:
396 valid = op.ofm.dtype in cls.supported_faf_dtypes
397 ext_type = optype_to_builtintype(op.activation.op_type)
398 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
399 return res
400
401 @classmethod
402 @docstring_format_args(stride_range)
403 def constraint_stride_range(cls, op):
404 "Stride values for both width and height must be in the range [{}, {}]"
405 w, h = op.get_kernel_stride()
406 stride_min, stride_max = cls.stride_range
407 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
408 return valid, f"Op has stride WxH as: {w}x{h}"
409
410 @classmethod
411 @docstring_format_args(dilation_range)
412 def constraint_dilation_range(cls, op):
413 "Dilation factor values for both width and height must be in the range [{}, {}]"
414 w, h = op.get_kernel_dilation()
415 dilation_min, dilation_max = cls.dilation_range
416 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
417 return valid, f"Op has dilation factor WxH as: {w}x{h}"
418
419 @classmethod
420 @docstring_format_args(dilated_height_range)
421 def constraint_dilated_height_range(cls, op):
422 "Dilated kernel height must be in the range [{}, {}]"
423 h = op.kernel.area_height()
424 dilated_height_min, dilated_height_max = cls.dilated_height_range
425 valid = dilated_height_min <= h <= dilated_height_max
426 return valid, f"Op has dilated kernel height as: {h}"
427
428 @classmethod
429 @docstring_format_args(dilated_product_range)
430 def constraint_dilated_product_range(cls, op):
431 "Product of dilated kernel width and height must be in the range [{}, {}]"
432 product = op.kernel.area_width() * op.kernel.area_height()
433 dilated_product_min, dilated_product_max = cls.dilated_product_range
434 valid = dilated_product_min <= product <= dilated_product_max
435 return valid, f"Op has product of dilated kernel width and height as: {product}"
436
437 @staticmethod
438 def constraint_weights_type(op):
439 "Weight tensor must be 8-bit"
440 weights = op.weights
441 valid = weights.element_size() == 1
442 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
443
444 @staticmethod
445 def constraint_weights_const(op):
446 "Weight tensor must be constant"
447 weights = op.weights
448 valid = weights.values is not None
449 return valid, f"Tensor '{weights.name}' has non-constant values"
450
451 @classmethod
452 @docstring_format_args([weights_limit])
453 def constraint_weights_limit(cls, op):
454 "The sum of the weights cannot exceed {}"
455 weights = op.weights
456 values = weights.values.astype(np.int64) - weights.quantization.zero_point
457 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
458 valid = limit <= cls.weights_limit
459 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
460
461 @classmethod
462 @docstring_format_args([list_formatter(supported_bias_dtypes)])
463 def constraint_bias_type(cls, op):
464 "Optional Bias tensor must be of type: {}"
465 bias = op.bias
466 if bias:
467 valid = bias.dtype in cls.supported_bias_dtypes
468 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
469 return True, "Op has no bias tensor"
470
471 @staticmethod
472 def constraint_bias_40bit(op):
473 "Optional Bias tensor values must fit within 40-bits"
474 bias = op.bias
475 if bias and bias.dtype == DataType.int64 and bias.values is not None:
Tim Hall8ae29292021-07-28 16:52:03 +0100476 valid = all(len(bin(value)[2:]) <= 40 for value in bias.values)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200477 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
478 return True, "Op has no bias tensor, or it fits in 40-bit"
479
480 @staticmethod
481 def constraint_batch_size(op):
482 "IFM Tensor batch size must be 1"
483 ifm = op.ifm
484 valid = ifm.shape[0] == 1
485 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
486
487 @staticmethod
488 def constraint_depth_multiplier(op):
489 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
490 depth_multiplier = op.attrs.get("depth_multiplier", 1)
491 if depth_multiplier > 1:
492 ifm_channels = op.ifm.shape[3]
493 ofm_channels = op.ofm.shape[3]
494 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
495 extra = (
496 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
497 f" and depth_multiplier={depth_multiplier}"
498 )
499 return valid, extra
500 return True, "Op has depth_multiplier=1"
501
502 @staticmethod
503 def constraint_tconv_stride(op):
504 "Stride values for both width and height must be 2"
505 w = op.kernel.stride.x
506 h = op.kernel.stride.y
507 valid = (w == 2) and (h == 2)
508 return valid, f"Op has stride WxH as: {w}x{h}"
509
510 @staticmethod
511 def constraint_tconv_same(op):
512 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
513 if op.attrs["padding"] == Padding.SAME:
514 w = op.kernel.stride.x
515 h = op.kernel.stride.y
516 ifm_shape = op.ifm.shape
517 ofm_shape = op.ofm.shape
518 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
519 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
520 return True, "Op has padding=VALID"
521
522 @staticmethod
523 def constraint_tconv_valid(op):
524 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200525 minus difference between kernel size and stride"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200526 if op.attrs["padding"] == Padding.VALID:
527 s_w = op.kernel.stride.x
528 s_h = op.kernel.stride.y
529 k_w = op.kernel.width
530 k_h = op.kernel.height
531 ifm_shape = op.ifm.shape
532 ofm_shape = op.ofm.shape
533 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
534 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
535 valid = height_check and width_check
536 extra = (
537 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
538 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
539 )
540 return valid, extra
541 return True, "Op has padding=SAME"
542
543 @classmethod
544 @docstring_format_args(filter_range)
545 def constraint_filter_range(cls, op):
546 "Kernel filter values for both width and height must be in the range [{}, {}]"
547 if op.attrs["padding"] == Padding.SAME:
548 w = op.kernel.width
549 h = op.kernel.height
550 filter_min, filter_max = cls.filter_range
551 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
552 return valid, f"Op has kernel filter WxH as: {w}x{h}"
553 return True, "Op has padding=VALID"
554
555 @classmethod
556 @docstring_format_args(filter_height_range)
557 def constraint_filter_height_range(cls, op):
558 "Kernel filter height must be in the range [{}, {}]"
559 h = op.kernel.height
560 filter_height_min, filter_height_max = cls.filter_height_range
561 valid = filter_height_min <= h <= filter_height_max
562 return valid, f"Op has kernel filter height as: {h}"
563
564 @classmethod
565 @docstring_format_args(filter_product_range)
566 def constraint_filter_product_range(cls, op):
567 "Product of kernel filter width and height must be in the range [{}, {}]"
568 product = op.kernel.elements_wh()
569 filter_product_min, filter_product_max = cls.filter_product_range
570 valid = filter_product_min <= product <= filter_product_max
571 return valid, f"Op has product of kernel filter width and height as: {product}"
572
573 @staticmethod
574 @docstring_format_args(filter_height_range)
575 def constraint_filter_height_range_valid_pad(op):
576 "VALID padding: Kernel filter height must be in the range [{}, {}]"
577 if op.attrs["padding"] == Padding.VALID:
578 return TFLiteSupportedOperators.constraint_filter_height_range(op)
579 return True, "Op has padding=SAME"
580
581 @staticmethod
582 @docstring_format_args(filter_product_range)
583 def constraint_filter_product_range_valid_pad(op):
584 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
585 if op.attrs["padding"] == Padding.VALID:
586 return TFLiteSupportedOperators.constraint_filter_product_range(op)
587 return True, "Op has padding=SAME"
588
589 @staticmethod
590 def constraint_resize(op):
591 """The width and height of the IFM and OFM must match one of the following criteria:
592 IFM W and H must both be 1
593 IFM must match OFM
Rickard Boline546def2022-01-25 15:45:00 +0000594 OFM W and H must be equal and 2/4/8x IFM -1, if align_corners is True
595 OFM W and H must be equal and 2/4/8x IFM, if align_corners is False"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200596 # Easier to start with False condition as very few cases result in a supported resize
597 valid = False
598 ifm_shape = op.ifm.shape
599 ofm_shape = op.ofm.shape
600 align_corners = op.attrs.get("align_corners", False)
601 if len(ifm_shape) == 4:
602 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
603 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
604 valid = True
605 else:
Rickard Boline546def2022-01-25 15:45:00 +0000606 # Valid if OFM is 2/4/8x IFM (-1 for align corners)
607 w_upscale_factor = (ofm_shape[1] + 1) / ifm_shape[1] if align_corners else ofm_shape[1] / ifm_shape[1]
608 h_upscale_factor = (ofm_shape[2] + 1) / ifm_shape[2] if align_corners else ofm_shape[2] / ifm_shape[2]
609
610 valid = w_upscale_factor == h_upscale_factor and w_upscale_factor in [2, 4, 8]
611
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200612 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
613
614 @staticmethod
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200615 def constraint_bilinear_resize_attrs(op):
616 "half_pixel_centers are not supported"
617 valid = True
618 if op.attrs.get("half_pixel_centers"):
619 valid = False
620 return valid, f"Op has half_pixel_centers set to {not valid}."
621
622 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200623 def constraint_pad_shape(op):
624 "The padding tensor must have the shape [3,2] or [4,2]"
625 valid = op.inputs[1].shape in ([3, 2], [4, 2])
626 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
627
628 @classmethod
629 @docstring_format_args([list_formatter(supported_pad_dtypes)])
630 def constraint_pad_type(cls, op):
631 "Pad tensor must be of type: {}"
632 pad_tensor = op.inputs[1]
633 valid = pad_tensor.dtype in cls.supported_pad_dtypes
634 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
635
636 @staticmethod
637 def constraint_padding_dimensions(op):
638 "The pad tensor can only pad width and height"
639 pad_tensor = op.inputs[1].values
640
641 valid = sum(pad_tensor[-1, :]) == 0
642 if valid and len(pad_tensor) > 3:
643 valid = sum(pad_tensor[0, :]) == 0
644 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
645
646 @staticmethod
647 def constraint_stridedslice_stride_values(op):
648 "All Strides values must be 1"
649 strides = op.inputs[3]
650 valid = all(stride == 1 for stride in strides.values)
651 return valid, f"Op has strides values {strides.values}"
652
653 @staticmethod
654 def constraint_inputs_int32(op):
655 "Both Input data types must be int32"
656 ifm_dtype = op.ifm.dtype
657 ifm2_dtype = op.ifm2.dtype
658 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
659 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
660
661 @staticmethod
662 def constraint_output_int32(op):
663 "OFM must be int32"
664 ofm_dtype = op.ofm.dtype
665 valid = ofm_dtype == DataType.int32
666 return valid, f"Op has ofm_dtype={ofm_dtype}"
667
668 @staticmethod
669 def constraint_matching_quantization_parameters(op):
670 "Both Input quantization parameters must match OFM quantization parameters"
671 valid = True
672 extra = []
673 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
674 valid = False
675 extra.append(op.ifm.name)
676 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
677 valid = False
678 extra.append(op.ifm2.name)
679 extra = ", ".join(extra)
680 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
681
682 @staticmethod
683 def constraint_elemwise_batch_size(op):
684 "Batch size must be 1 for Input tensors with more than 2 dimensions"
685 valid = True
686 extra = []
687 for tens in (op.ifm, op.ifm2):
688 # Unary ops have ifm2 as None
689 if tens is not None:
690 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
691 valid = False
692 extra.append(tens.name)
693 extra = ", ".join(extra)
694 return valid, f"Op has invalid input tensors: {extra}"
695
696 @staticmethod
697 def constraint_broadcast_shapes(op):
698 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
699 ifm_shape = op.ifm.shape
700 ifm2_shape = op.ifm2.shape if op.ifm2 else None
701 ofm_shape = op.ofm.shape
702 valid = True
703 if ifm_shape is not None and ifm2_shape is not None:
704 # align trailing dimensions
705 size = min(len(ifm_shape), len(ifm2_shape))
706 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
707 mi = max(i, i2)
708 # Input dimensions should match or one should be of dimension 1
709 # Output dimension should match the largest input dimension, together
710 # with constraint_match_either_shapes ensures broadcast from only one input
711 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
712 valid = False
713 break
714
715 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
716
717 @classmethod
718 @docstring_format_args([mean_kernel_product_avgpool])
719 def constraint_mean_height_width_product_avgpool(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000720 """Product of height and width must be no greater than {}"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200721 shape = op.inputs[0].shape
722 hi = 0 if len(shape) < 4 else 1
723 h, w = shape[hi : hi + 2]
724 max_prod = cls.mean_kernel_product_avgpool
725 return h * w <= max_prod, f"Product of height and width is {h * w}"
726
727 @classmethod
728 @docstring_format_args([mean_kernel_product])
729 def constraint_mean_height_width_product(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000730 """Product of height and width must be no greater than {} when:
731 IFM and OFM have different scale or zero point; or
732 'keep_dims' is True"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200733 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
734 keep_dims = op.attrs.get("keep_dims")
735 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
736 if not keep_dims and ifmq.scale_f32 == ofmq.scale_f32 and ifmq.zero_point == ofmq.zero_point:
737 return True, ""
738 shape = op.inputs[0].shape
739 hi = 0 if len(shape) < 4 else 1
740 h, w = shape[hi : hi + 2]
741 max_prod = cls.mean_kernel_product
742 return h * w <= max_prod, f"Product of height and width is {h * w}"
743
744 @classmethod
745 @docstring_format_args([mean_kernel_product_int8])
746 def constraint_mean_height_width_product_int8(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000747 """Product of IFM height and width must be no greater than {} when:
748 The IFM shape has 4 dimensions; and
749 The axis indices specify reduction across 2 dimensions; and
750 The axis indices correspond to the width and height dimensions of the IFM; and
751 'keep_dims' is True; and
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200752 IFM datatype is int8"""
753 shape = op.ifm.shape
754 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
755 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
756 # and constraint_mean_height_width_product
757 if (
758 len(shape) != 4
759 or op.ifm.dtype != DataType.int8
760 or not op.attrs.get("keep_dims")
761 or axis not in ([1, 2], [2, 1])
762 ):
763 return True, ""
James Peet0bb7ad12022-02-15 15:07:54 +0000764 h = shape[-3]
765 w = shape[-2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200766 max_prod = cls.mean_kernel_product_int8
767 return h * w <= max_prod, f"Product of height and width is {h * w}"
Tim Hall3584a9c2021-11-18 22:05:17 +0000768
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000769 @classmethod
James Peet0bb7ad12022-02-15 15:07:54 +0000770 @docstring_format_args([filter_height_range[1], dilated_height_range[1]])
771 def constraint_mean_height_single_axis(cls, op):
772 """For single axis averages across the height dimension:
773 IFM height must be no greater than {} if the IFM and OFM scale and zero point match; otherwise
774 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 +0000775 inp, axis = op.inputs
776 if axis.shape == [] or axis.shape[0] == 1: # single axis
777 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
778 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000779 # Multiple axes
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000780 return True, ""
781
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000782 shape = inp.shape
James Peet0bb7ad12022-02-15 15:07:54 +0000783 if len(shape) < 3:
784 # No height dimension present in IFM
785 return True, ""
786 if axis != len(shape) - 3:
787 # Not averaging across the height dimension
788 return True, ""
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000789
James Peet0bb7ad12022-02-15 15:07:54 +0000790 h = shape[axis]
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000791 ifm, ofm = op.get_ifm_ofm()
James Peet0bb7ad12022-02-15 15:07:54 +0000792
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000793 if check_quantized_tens_scaling_equal(ifm, ofm):
James Peet0bb7ad12022-02-15 15:07:54 +0000794 return h <= cls.filter_height_range[1], f"Height is {h}, IFM and OFM quantizations match"
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000795 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000796 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 +0000797
Tim Hall3584a9c2021-11-18 22:05:17 +0000798 @staticmethod
799 def constraint_reshape_shape_constant(op):
800 "Shape must be constant"
801 valid = True
802 extra = []
803
804 reshape_tens = op.inputs[1]
805 if reshape_tens is not None:
806 # constant inputs have either no driving operator or a const one
807 # create a list of non-constant inputs
808 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
809 valid = False
810 extra.append(reshape_tens.name)
811 extra = ", ".join(extra)
812
813 return valid, f"Op has non-const input(s): {extra}"