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