blob: 6328a4e5b95124ecbc06be9dc2f6c04114c2913e [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
42 npu_pre_ops = set((Op.SplitSliceRead,))
Jonas Ohlssond8575072022-03-30 10:30:25 +020043 convolution_ops = set(
44 (
45 Op.Conv2DBias,
46 Op.Conv2D,
47 Op.QuantizedConv2D,
48 )
49 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020050 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
51 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
52 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
53 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
54 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
55 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
56 resizing_ops = set((Op.ResizeBilinear,))
Jonas Ohlssond8575072022-03-30 10:30:25 +020057 fc_vector_products = set(
58 (
59 Op.QuantizedMatMul,
60 Op.MatMul,
61 Op.FullyConnected,
62 )
63 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020064 mac_main_ops = (
65 # RNN/LSTM/GRU
66 set((Op.BlockLSTM,))
67 # conv/depthwiseconv/transposeconv
68 | convolution_like_ops
69 # pooling
70 | pooling_ops
71 # resizing/upscaling
72 | resizing_ops
73 # FC layers
74 | fc_vector_products
75 # Mean (converts to depthwise conv)
76 | set((Op.Mean,))
77 )
78 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020079 binary_elem_wise_min_max_ops = set(
80 (
81 Op.Minimum,
82 Op.Maximum,
83 )
84 )
85 binary_elem_wise_shift_ops = set(
86 (
87 Op.SHL,
88 Op.SHR,
89 )
90 )
91 binary_elem_wise_add_mul_sub = set(
92 (
93 Op.Add,
94 Op.Mul,
95 Op.Sub,
96 )
97 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020098 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
99 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
100 pad_ops = set((Op.Pad,))
101 supported_int32_tensor_ops = (
Jonas Ohlssond8575072022-03-30 10:30:25 +0200102 set(
103 (
104 Op.ReduceSum,
105 Op.CLZ,
106 )
107 )
108 | binary_elem_wise_add_mul_sub
109 | binary_elem_wise_shift_ops
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200110 )
111
Jonas Ohlssond8575072022-03-30 10:30:25 +0200112 relu_ops = set(
113 (
114 Op.Relu,
115 Op.Relu6,
116 Op.ReluN1To1,
117 Op.Clip,
118 )
119 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200120 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax, Op.HardSwish))
121 npu_post_ops = (
122 # activation functions
123 activation_ops
124 # concatenation write direction
125 | set((Op.ConcatSliceWrite,))
126 # Quantization
127 | set((Op.Quantize,))
128 )
Jonas Ohlssond8575072022-03-30 10:30:25 +0200129 split_ops = set(
130 (
131 Op.Split,
132 Op.SplitV,
133 Op.StridedSlice,
134 Op.Slice,
135 Op.UnpackReshaped,
136 Op.Unpack,
137 )
138 )
139 concat_ops = set(
140 (
141 Op.Concat,
142 Op.ConcatTFLite,
143 Op.PackReshaped,
144 Op.Pack,
145 )
146 )
147 memory_only_ops = (
148 set(
149 (
150 Op.Reshape,
151 Op.QuantizedReshape,
152 Op.Squeeze,
153 Op.ExpandDims,
154 )
155 )
156 | concat_ops
157 | split_ops
158 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200159 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Jonas Ohlssond8575072022-03-30 10:30:25 +0200160 supported_fused_activations = relu_ops | set(
161 (
162 Op.Tanh,
163 Op.Sigmoid,
164 Op.LUT,
165 )
166 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200167 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
168 # Supported data types
169 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
170 supported_faf_dtypes = set((DataType.uint8, DataType.int8, DataType.int16))
171 supported_bias_dtypes = set((DataType.int32, DataType.int64))
172 supported_pad_dtypes = set((DataType.int32, DataType.int64))
173 # Defined ranges for allowed values:
174 tens_dim_range = (1, 65535)
175 stride_range = (1, 3)
176 dilation_range = (1, 2)
177 dilated_height_range = (1, 64)
178 dilated_product_range = (1, 64 * 64)
179 weights_limit = 127 * 65536
180 filter_range = (1, 8)
181 filter_height_range = (1, 256)
182 filter_product_range = (1, 256 * 256)
183 mean_kernel_product = 64 * 64
184 mean_kernel_product_int8 = 16 * 16
185 mean_kernel_product_avgpool = 256 * 256
186
187 def __init__(self):
188 # Setup the generic constraints. Note: the order matters
189 self.generic_constraints = []
190 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dtype)
191 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_int32_ops)
192 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dimension)
193 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_quant_per_axis)
194 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf)
195 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf_type)
196
197 # Setup specific constraints. Note: the order matters
198 self.specific_constraints = defaultdict(list)
199
200 # Conv-like checks:
201 for op_type in TFLiteSupportedOperators.convolution_like_ops:
202 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
203 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilation_range)
204 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_height_range)
205 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_product_range)
206 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
207 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
208 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_limit)
209 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
210 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
211 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
212 # Depthwise Conv specific checks:
213 for op_type in TFLiteSupportedOperators.depthwise_convolution_ops:
214 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_depth_multiplier)
215 # Transpose Conv specific checks:
216 for op_type in TFLiteSupportedOperators.transpose_convolution_ops:
217 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_stride)
218 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_same)
219 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_valid)
220
221 # Pooling checks:
222 for op_type in TFLiteSupportedOperators.pooling_ops:
223 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
224 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
225 # AVG pooling specific checks:
226 for op_type in TFLiteSupportedOperators.avg_pooling_ops:
227 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_range)
228 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range_valid_pad)
229 self.specific_constraints[op_type].append(
230 TFLiteSupportedOperators.constraint_filter_product_range_valid_pad
231 )
232 # MAX pooling specific checks:
233 for op_type in TFLiteSupportedOperators.max_pooling_ops:
234 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range)
235 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_product_range)
236
237 # Resizing specific checks:
238 for op_type in TFLiteSupportedOperators.resizing_ops:
239 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize)
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200240 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bilinear_resize_attrs)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200241
242 # Vector Product specific checks:
243 for op_type in TFLiteSupportedOperators.fc_vector_products:
244 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
245 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
246 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
247 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
248
249 # Element-wise checks:
250 for op_type in TFLiteSupportedOperators.elem_wise_main_ops:
251 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_elemwise_batch_size)
252 # Binary Min/Max specific checks:
253 for op_type in TFLiteSupportedOperators.binary_elem_wise_min_max_ops:
254 self.specific_constraints[op_type].append(
255 TFLiteSupportedOperators.constraint_matching_quantization_parameters
256 )
257 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
258 # Binary Add/Mul/Sub specific checks:
259 for op_type in TFLiteSupportedOperators.binary_elem_wise_add_mul_sub:
260 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
261 # Binary Shift specific checks:
262 for op_type in TFLiteSupportedOperators.binary_elem_wise_shift_ops:
263 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_inputs_int32)
264 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
265
266 # SHL specific checks:
267 self.specific_constraints[Op.SHL].append(TFLiteSupportedOperators.constraint_output_int32)
268
269 # CLZ specific checks:
270 self.specific_constraints[Op.CLZ].append(TFLiteSupportedOperators.constraint_output_int32)
271
272 # StridedSlice specific checks:
273 self.specific_constraints[Op.StridedSlice].append(
274 TFLiteSupportedOperators.constraint_stridedslice_stride_values
275 )
276
277 # Pad specific checks:
278 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_shape)
279 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_padding_dimensions)
280 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_type)
281
282 # Mean specific checks:
Dwight Lidmanf54c18d2021-09-29 17:23:03 +0200283 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_batch_size)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200284 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_avgpool)
285 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product)
286 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_int8)
James Peet0bb7ad12022-02-15 15:07:54 +0000287 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_single_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200288
Tim Hall3584a9c2021-11-18 22:05:17 +0000289 # Reshape specific checks:
290 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
291
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200292 def is_operator_supported(self, op):
293 ext_type = optype_to_builtintype(op.type)
294 if op.type not in TFLiteSupportedOperators.supported_operators:
295 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
296 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
297 return False
298
299 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
300 valid, extra = constraint(op)
301 if not valid:
302 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
303 print(f" - {constraint.__doc__}")
304 if extra:
305 print(f" {extra}")
306 return False
307
308 return True
309
310 @classmethod
311 @docstring_format_args([list_formatter(supported_op_dtypes)])
312 def constraint_tens_dtype(cls, op):
313 "Tensors must be of type: {}"
314 valid = True
315 extra = []
316 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
317 if not tensors:
318 tensors = [tens for tens in op.inputs if tens]
319 for tens in tensors:
320 if tens.dtype not in cls.supported_op_dtypes:
321 valid = False
322 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
323 return valid, ", ".join(extra)
324
325 @classmethod
326 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
327 def constraint_tens_int32_ops(cls, op):
328 "Tensors which are int32 are only valid when op type is: {}"
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 == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
336 valid = False
337 extra.append(tens.name)
338 extra = ", ".join(extra)
339 return valid, f"Op has int32 tensor(s): {extra}"
340
341 @classmethod
342 @docstring_format_args(tens_dim_range)
343 def constraint_tens_dimension(cls, op):
344 "Tensor dimensions must be in the range [{}, {}]"
345 tens_min, tens_max = cls.tens_dim_range
346 valid = True
347 extra = []
348 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
349 if not tensors:
350 tensors = [tens for tens in op.inputs if tens]
351 for tens in tensors:
352 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
353 valid = False
354 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
355 return valid, ", ".join(extra)
356
357 @classmethod
358 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
359 def constraint_tens_quant_per_axis(cls, op):
360 "Per-axis quantization is only supported for the following op types: {}"
361 valid = True
362 extra = []
363 if op.type not in cls.per_axis_quant_ops:
364 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
365 for tens in tensors:
366 if tens.quantization.is_per_axis():
367 valid = False
368 extra.append(tens.name)
369 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
370
371 @classmethod
372 @docstring_format_args([_optype_formatter(supported_fused_activations)])
373 def constraint_faf(cls, op):
374 "The fused activation function (if present) must be one of type: {}"
375 if op.activation is None:
376 res = True, "Op has no fused activation function"
377 else:
378 faf = op.activation.op_type
379 valid = faf in cls.supported_fused_activations
380 res = valid, f"Op has its fused activation function as: {faf}"
381 return res
382
383 @classmethod
384 @docstring_format_args([list_formatter(supported_faf_dtypes)])
385 def constraint_faf_type(cls, op):
386 "If a fused activation function is present, the Output tensor must be one of type: {}"
387 if op.activation is None:
388 res = True, "Op has no fused activation function"
389 else:
390 valid = op.ofm.dtype in cls.supported_faf_dtypes
391 ext_type = optype_to_builtintype(op.activation.op_type)
392 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
393 return res
394
395 @classmethod
396 @docstring_format_args(stride_range)
397 def constraint_stride_range(cls, op):
398 "Stride values for both width and height must be in the range [{}, {}]"
399 w, h = op.get_kernel_stride()
400 stride_min, stride_max = cls.stride_range
401 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
402 return valid, f"Op has stride WxH as: {w}x{h}"
403
404 @classmethod
405 @docstring_format_args(dilation_range)
406 def constraint_dilation_range(cls, op):
407 "Dilation factor values for both width and height must be in the range [{}, {}]"
408 w, h = op.get_kernel_dilation()
409 dilation_min, dilation_max = cls.dilation_range
410 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
411 return valid, f"Op has dilation factor WxH as: {w}x{h}"
412
413 @classmethod
414 @docstring_format_args(dilated_height_range)
415 def constraint_dilated_height_range(cls, op):
416 "Dilated kernel height must be in the range [{}, {}]"
417 h = op.kernel.area_height()
418 dilated_height_min, dilated_height_max = cls.dilated_height_range
419 valid = dilated_height_min <= h <= dilated_height_max
420 return valid, f"Op has dilated kernel height as: {h}"
421
422 @classmethod
423 @docstring_format_args(dilated_product_range)
424 def constraint_dilated_product_range(cls, op):
425 "Product of dilated kernel width and height must be in the range [{}, {}]"
426 product = op.kernel.area_width() * op.kernel.area_height()
427 dilated_product_min, dilated_product_max = cls.dilated_product_range
428 valid = dilated_product_min <= product <= dilated_product_max
429 return valid, f"Op has product of dilated kernel width and height as: {product}"
430
431 @staticmethod
432 def constraint_weights_type(op):
433 "Weight tensor must be 8-bit"
434 weights = op.weights
435 valid = weights.element_size() == 1
436 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
437
438 @staticmethod
439 def constraint_weights_const(op):
440 "Weight tensor must be constant"
441 weights = op.weights
442 valid = weights.values is not None
443 return valid, f"Tensor '{weights.name}' has non-constant values"
444
445 @classmethod
446 @docstring_format_args([weights_limit])
447 def constraint_weights_limit(cls, op):
448 "The sum of the weights cannot exceed {}"
449 weights = op.weights
450 values = weights.values.astype(np.int64) - weights.quantization.zero_point
451 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
452 valid = limit <= cls.weights_limit
453 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
454
455 @classmethod
456 @docstring_format_args([list_formatter(supported_bias_dtypes)])
457 def constraint_bias_type(cls, op):
458 "Optional Bias tensor must be of type: {}"
459 bias = op.bias
460 if bias:
461 valid = bias.dtype in cls.supported_bias_dtypes
462 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
463 return True, "Op has no bias tensor"
464
465 @staticmethod
466 def constraint_bias_40bit(op):
467 "Optional Bias tensor values must fit within 40-bits"
468 bias = op.bias
469 if bias and bias.dtype == DataType.int64 and bias.values is not None:
Tim Hall8ae29292021-07-28 16:52:03 +0100470 valid = all(len(bin(value)[2:]) <= 40 for value in bias.values)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200471 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
472 return True, "Op has no bias tensor, or it fits in 40-bit"
473
474 @staticmethod
475 def constraint_batch_size(op):
476 "IFM Tensor batch size must be 1"
477 ifm = op.ifm
478 valid = ifm.shape[0] == 1
479 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
480
481 @staticmethod
482 def constraint_depth_multiplier(op):
483 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
484 depth_multiplier = op.attrs.get("depth_multiplier", 1)
485 if depth_multiplier > 1:
486 ifm_channels = op.ifm.shape[3]
487 ofm_channels = op.ofm.shape[3]
488 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
489 extra = (
490 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
491 f" and depth_multiplier={depth_multiplier}"
492 )
493 return valid, extra
494 return True, "Op has depth_multiplier=1"
495
496 @staticmethod
497 def constraint_tconv_stride(op):
498 "Stride values for both width and height must be 2"
499 w = op.kernel.stride.x
500 h = op.kernel.stride.y
501 valid = (w == 2) and (h == 2)
502 return valid, f"Op has stride WxH as: {w}x{h}"
503
504 @staticmethod
505 def constraint_tconv_same(op):
506 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
507 if op.attrs["padding"] == Padding.SAME:
508 w = op.kernel.stride.x
509 h = op.kernel.stride.y
510 ifm_shape = op.ifm.shape
511 ofm_shape = op.ofm.shape
512 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
513 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
514 return True, "Op has padding=VALID"
515
516 @staticmethod
517 def constraint_tconv_valid(op):
518 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200519 minus difference between kernel size and stride"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200520 if op.attrs["padding"] == Padding.VALID:
521 s_w = op.kernel.stride.x
522 s_h = op.kernel.stride.y
523 k_w = op.kernel.width
524 k_h = op.kernel.height
525 ifm_shape = op.ifm.shape
526 ofm_shape = op.ofm.shape
527 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
528 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
529 valid = height_check and width_check
530 extra = (
531 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
532 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
533 )
534 return valid, extra
535 return True, "Op has padding=SAME"
536
537 @classmethod
538 @docstring_format_args(filter_range)
539 def constraint_filter_range(cls, op):
540 "Kernel filter values for both width and height must be in the range [{}, {}]"
541 if op.attrs["padding"] == Padding.SAME:
542 w = op.kernel.width
543 h = op.kernel.height
544 filter_min, filter_max = cls.filter_range
545 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
546 return valid, f"Op has kernel filter WxH as: {w}x{h}"
547 return True, "Op has padding=VALID"
548
549 @classmethod
550 @docstring_format_args(filter_height_range)
551 def constraint_filter_height_range(cls, op):
552 "Kernel filter height must be in the range [{}, {}]"
553 h = op.kernel.height
554 filter_height_min, filter_height_max = cls.filter_height_range
555 valid = filter_height_min <= h <= filter_height_max
556 return valid, f"Op has kernel filter height as: {h}"
557
558 @classmethod
559 @docstring_format_args(filter_product_range)
560 def constraint_filter_product_range(cls, op):
561 "Product of kernel filter width and height must be in the range [{}, {}]"
562 product = op.kernel.elements_wh()
563 filter_product_min, filter_product_max = cls.filter_product_range
564 valid = filter_product_min <= product <= filter_product_max
565 return valid, f"Op has product of kernel filter width and height as: {product}"
566
567 @staticmethod
568 @docstring_format_args(filter_height_range)
569 def constraint_filter_height_range_valid_pad(op):
570 "VALID padding: Kernel filter height must be in the range [{}, {}]"
571 if op.attrs["padding"] == Padding.VALID:
572 return TFLiteSupportedOperators.constraint_filter_height_range(op)
573 return True, "Op has padding=SAME"
574
575 @staticmethod
576 @docstring_format_args(filter_product_range)
577 def constraint_filter_product_range_valid_pad(op):
578 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
579 if op.attrs["padding"] == Padding.VALID:
580 return TFLiteSupportedOperators.constraint_filter_product_range(op)
581 return True, "Op has padding=SAME"
582
583 @staticmethod
584 def constraint_resize(op):
585 """The width and height of the IFM and OFM must match one of the following criteria:
586 IFM W and H must both be 1
587 IFM must match OFM
Rickard Boline546def2022-01-25 15:45:00 +0000588 OFM W and H must be equal and 2/4/8x IFM -1, if align_corners is True
589 OFM W and H must be equal and 2/4/8x IFM, if align_corners is False"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200590 # Easier to start with False condition as very few cases result in a supported resize
591 valid = False
592 ifm_shape = op.ifm.shape
593 ofm_shape = op.ofm.shape
594 align_corners = op.attrs.get("align_corners", False)
595 if len(ifm_shape) == 4:
596 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
597 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
598 valid = True
599 else:
Rickard Boline546def2022-01-25 15:45:00 +0000600 # Valid if OFM is 2/4/8x IFM (-1 for align corners)
601 w_upscale_factor = (ofm_shape[1] + 1) / ifm_shape[1] if align_corners else ofm_shape[1] / ifm_shape[1]
602 h_upscale_factor = (ofm_shape[2] + 1) / ifm_shape[2] if align_corners else ofm_shape[2] / ifm_shape[2]
603
604 valid = w_upscale_factor == h_upscale_factor and w_upscale_factor in [2, 4, 8]
605
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200606 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
607
608 @staticmethod
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200609 def constraint_bilinear_resize_attrs(op):
610 "half_pixel_centers are not supported"
611 valid = True
612 if op.attrs.get("half_pixel_centers"):
613 valid = False
614 return valid, f"Op has half_pixel_centers set to {not valid}."
615
616 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200617 def constraint_pad_shape(op):
618 "The padding tensor must have the shape [3,2] or [4,2]"
619 valid = op.inputs[1].shape in ([3, 2], [4, 2])
620 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
621
622 @classmethod
623 @docstring_format_args([list_formatter(supported_pad_dtypes)])
624 def constraint_pad_type(cls, op):
625 "Pad tensor must be of type: {}"
626 pad_tensor = op.inputs[1]
627 valid = pad_tensor.dtype in cls.supported_pad_dtypes
628 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
629
630 @staticmethod
631 def constraint_padding_dimensions(op):
632 "The pad tensor can only pad width and height"
633 pad_tensor = op.inputs[1].values
634
635 valid = sum(pad_tensor[-1, :]) == 0
636 if valid and len(pad_tensor) > 3:
637 valid = sum(pad_tensor[0, :]) == 0
638 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
639
640 @staticmethod
641 def constraint_stridedslice_stride_values(op):
642 "All Strides values must be 1"
643 strides = op.inputs[3]
644 valid = all(stride == 1 for stride in strides.values)
645 return valid, f"Op has strides values {strides.values}"
646
647 @staticmethod
648 def constraint_inputs_int32(op):
649 "Both Input data types must be int32"
650 ifm_dtype = op.ifm.dtype
651 ifm2_dtype = op.ifm2.dtype
652 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
653 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
654
655 @staticmethod
656 def constraint_output_int32(op):
657 "OFM must be int32"
658 ofm_dtype = op.ofm.dtype
659 valid = ofm_dtype == DataType.int32
660 return valid, f"Op has ofm_dtype={ofm_dtype}"
661
662 @staticmethod
663 def constraint_matching_quantization_parameters(op):
664 "Both Input quantization parameters must match OFM quantization parameters"
665 valid = True
666 extra = []
667 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
668 valid = False
669 extra.append(op.ifm.name)
670 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
671 valid = False
672 extra.append(op.ifm2.name)
673 extra = ", ".join(extra)
674 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
675
676 @staticmethod
677 def constraint_elemwise_batch_size(op):
678 "Batch size must be 1 for Input tensors with more than 2 dimensions"
679 valid = True
680 extra = []
681 for tens in (op.ifm, op.ifm2):
682 # Unary ops have ifm2 as None
683 if tens is not None:
684 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
685 valid = False
686 extra.append(tens.name)
687 extra = ", ".join(extra)
688 return valid, f"Op has invalid input tensors: {extra}"
689
690 @staticmethod
691 def constraint_broadcast_shapes(op):
692 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
693 ifm_shape = op.ifm.shape
694 ifm2_shape = op.ifm2.shape if op.ifm2 else None
695 ofm_shape = op.ofm.shape
696 valid = True
697 if ifm_shape is not None and ifm2_shape is not None:
698 # align trailing dimensions
699 size = min(len(ifm_shape), len(ifm2_shape))
700 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
701 mi = max(i, i2)
702 # Input dimensions should match or one should be of dimension 1
703 # Output dimension should match the largest input dimension, together
704 # with constraint_match_either_shapes ensures broadcast from only one input
705 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
706 valid = False
707 break
708
709 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
710
711 @classmethod
712 @docstring_format_args([mean_kernel_product_avgpool])
713 def constraint_mean_height_width_product_avgpool(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000714 """Product of height and width must be no greater than {}"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200715 shape = op.inputs[0].shape
716 hi = 0 if len(shape) < 4 else 1
717 h, w = shape[hi : hi + 2]
718 max_prod = cls.mean_kernel_product_avgpool
719 return h * w <= max_prod, f"Product of height and width is {h * w}"
720
721 @classmethod
722 @docstring_format_args([mean_kernel_product])
723 def constraint_mean_height_width_product(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000724 """Product of height and width must be no greater than {} when:
725 IFM and OFM have different scale or zero point; or
726 'keep_dims' is True"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200727 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
728 keep_dims = op.attrs.get("keep_dims")
729 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
730 if not keep_dims and ifmq.scale_f32 == ofmq.scale_f32 and ifmq.zero_point == ofmq.zero_point:
731 return True, ""
732 shape = op.inputs[0].shape
733 hi = 0 if len(shape) < 4 else 1
734 h, w = shape[hi : hi + 2]
735 max_prod = cls.mean_kernel_product
736 return h * w <= max_prod, f"Product of height and width is {h * w}"
737
738 @classmethod
739 @docstring_format_args([mean_kernel_product_int8])
740 def constraint_mean_height_width_product_int8(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000741 """Product of IFM height and width must be no greater than {} when:
742 The IFM shape has 4 dimensions; and
743 The axis indices specify reduction across 2 dimensions; and
744 The axis indices correspond to the width and height dimensions of the IFM; and
745 'keep_dims' is True; and
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200746 IFM datatype is int8"""
747 shape = op.ifm.shape
748 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
749 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
750 # and constraint_mean_height_width_product
751 if (
752 len(shape) != 4
753 or op.ifm.dtype != DataType.int8
754 or not op.attrs.get("keep_dims")
755 or axis not in ([1, 2], [2, 1])
756 ):
757 return True, ""
James Peet0bb7ad12022-02-15 15:07:54 +0000758 h = shape[-3]
759 w = shape[-2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200760 max_prod = cls.mean_kernel_product_int8
761 return h * w <= max_prod, f"Product of height and width is {h * w}"
Tim Hall3584a9c2021-11-18 22:05:17 +0000762
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000763 @classmethod
James Peet0bb7ad12022-02-15 15:07:54 +0000764 @docstring_format_args([filter_height_range[1], dilated_height_range[1]])
765 def constraint_mean_height_single_axis(cls, op):
766 """For single axis averages across the height dimension:
767 IFM height must be no greater than {} if the IFM and OFM scale and zero point match; otherwise
768 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 +0000769 inp, axis = op.inputs
770 if axis.shape == [] or axis.shape[0] == 1: # single axis
771 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
772 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000773 # Multiple axes
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000774 return True, ""
775
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000776 shape = inp.shape
James Peet0bb7ad12022-02-15 15:07:54 +0000777 if len(shape) < 3:
778 # No height dimension present in IFM
779 return True, ""
780 if axis != len(shape) - 3:
781 # Not averaging across the height dimension
782 return True, ""
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000783
James Peet0bb7ad12022-02-15 15:07:54 +0000784 h = shape[axis]
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000785 ifm, ofm = op.get_ifm_ofm()
James Peet0bb7ad12022-02-15 15:07:54 +0000786
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000787 if check_quantized_tens_scaling_equal(ifm, ofm):
James Peet0bb7ad12022-02-15 15:07:54 +0000788 return h <= cls.filter_height_range[1], f"Height is {h}, IFM and OFM quantizations match"
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000789 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000790 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 +0000791
Tim Hall3584a9c2021-11-18 22:05:17 +0000792 @staticmethod
793 def constraint_reshape_shape_constant(op):
794 "Shape must be constant"
795 valid = True
796 extra = []
797
798 reshape_tens = op.inputs[1]
799 if reshape_tens is not None:
800 # constant inputs have either no driving operator or a const one
801 # create a list of non-constant inputs
802 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
803 valid = False
804 extra.append(reshape_tens.name)
805 extra = ", ".join(extra)
806
807 return valid, f"Op has non-const input(s): {extra}"