blob: 60bc6fd0961d70de4b58be410715d05d47d41e8d [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)
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000212 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_depthwise_conv_height_single_axis)
213 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_avgpool_height_single_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200214
Tim Hall3584a9c2021-11-18 22:05:17 +0000215 # Reshape specific checks:
216 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
217
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200218 def is_operator_supported(self, op):
219 ext_type = optype_to_builtintype(op.type)
220 if op.type not in TFLiteSupportedOperators.supported_operators:
221 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
222 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
223 return False
224
225 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
226 valid, extra = constraint(op)
227 if not valid:
228 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
229 print(f" - {constraint.__doc__}")
230 if extra:
231 print(f" {extra}")
232 return False
233
234 return True
235
236 @classmethod
237 @docstring_format_args([list_formatter(supported_op_dtypes)])
238 def constraint_tens_dtype(cls, op):
239 "Tensors must be of type: {}"
240 valid = True
241 extra = []
242 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
243 if not tensors:
244 tensors = [tens for tens in op.inputs if tens]
245 for tens in tensors:
246 if tens.dtype not in cls.supported_op_dtypes:
247 valid = False
248 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
249 return valid, ", ".join(extra)
250
251 @classmethod
252 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
253 def constraint_tens_int32_ops(cls, op):
254 "Tensors which are int32 are only valid when op type is: {}"
255 valid = True
256 extra = []
257 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
258 if not tensors:
259 tensors = [tens for tens in op.inputs if tens]
260 for tens in tensors:
261 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
262 valid = False
263 extra.append(tens.name)
264 extra = ", ".join(extra)
265 return valid, f"Op has int32 tensor(s): {extra}"
266
267 @classmethod
268 @docstring_format_args(tens_dim_range)
269 def constraint_tens_dimension(cls, op):
270 "Tensor dimensions must be in the range [{}, {}]"
271 tens_min, tens_max = cls.tens_dim_range
272 valid = True
273 extra = []
274 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
275 if not tensors:
276 tensors = [tens for tens in op.inputs if tens]
277 for tens in tensors:
278 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
279 valid = False
280 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
281 return valid, ", ".join(extra)
282
283 @classmethod
284 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
285 def constraint_tens_quant_per_axis(cls, op):
286 "Per-axis quantization is only supported for the following op types: {}"
287 valid = True
288 extra = []
289 if op.type not in cls.per_axis_quant_ops:
290 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
291 for tens in tensors:
292 if tens.quantization.is_per_axis():
293 valid = False
294 extra.append(tens.name)
295 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
296
297 @classmethod
298 @docstring_format_args([_optype_formatter(supported_fused_activations)])
299 def constraint_faf(cls, op):
300 "The fused activation function (if present) must be one of type: {}"
301 if op.activation is None:
302 res = True, "Op has no fused activation function"
303 else:
304 faf = op.activation.op_type
305 valid = faf in cls.supported_fused_activations
306 res = valid, f"Op has its fused activation function as: {faf}"
307 return res
308
309 @classmethod
310 @docstring_format_args([list_formatter(supported_faf_dtypes)])
311 def constraint_faf_type(cls, op):
312 "If a fused activation function is present, the Output tensor must be one of type: {}"
313 if op.activation is None:
314 res = True, "Op has no fused activation function"
315 else:
316 valid = op.ofm.dtype in cls.supported_faf_dtypes
317 ext_type = optype_to_builtintype(op.activation.op_type)
318 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
319 return res
320
321 @classmethod
322 @docstring_format_args(stride_range)
323 def constraint_stride_range(cls, op):
324 "Stride values for both width and height must be in the range [{}, {}]"
325 w, h = op.get_kernel_stride()
326 stride_min, stride_max = cls.stride_range
327 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
328 return valid, f"Op has stride WxH as: {w}x{h}"
329
330 @classmethod
331 @docstring_format_args(dilation_range)
332 def constraint_dilation_range(cls, op):
333 "Dilation factor values for both width and height must be in the range [{}, {}]"
334 w, h = op.get_kernel_dilation()
335 dilation_min, dilation_max = cls.dilation_range
336 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
337 return valid, f"Op has dilation factor WxH as: {w}x{h}"
338
339 @classmethod
340 @docstring_format_args(dilated_height_range)
341 def constraint_dilated_height_range(cls, op):
342 "Dilated kernel height must be in the range [{}, {}]"
343 h = op.kernel.area_height()
344 dilated_height_min, dilated_height_max = cls.dilated_height_range
345 valid = dilated_height_min <= h <= dilated_height_max
346 return valid, f"Op has dilated kernel height as: {h}"
347
348 @classmethod
349 @docstring_format_args(dilated_product_range)
350 def constraint_dilated_product_range(cls, op):
351 "Product of dilated kernel width and height must be in the range [{}, {}]"
352 product = op.kernel.area_width() * op.kernel.area_height()
353 dilated_product_min, dilated_product_max = cls.dilated_product_range
354 valid = dilated_product_min <= product <= dilated_product_max
355 return valid, f"Op has product of dilated kernel width and height as: {product}"
356
357 @staticmethod
358 def constraint_weights_type(op):
359 "Weight tensor must be 8-bit"
360 weights = op.weights
361 valid = weights.element_size() == 1
362 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
363
364 @staticmethod
365 def constraint_weights_const(op):
366 "Weight tensor must be constant"
367 weights = op.weights
368 valid = weights.values is not None
369 return valid, f"Tensor '{weights.name}' has non-constant values"
370
371 @classmethod
372 @docstring_format_args([weights_limit])
373 def constraint_weights_limit(cls, op):
374 "The sum of the weights cannot exceed {}"
375 weights = op.weights
376 values = weights.values.astype(np.int64) - weights.quantization.zero_point
377 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
378 valid = limit <= cls.weights_limit
379 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
380
381 @classmethod
382 @docstring_format_args([list_formatter(supported_bias_dtypes)])
383 def constraint_bias_type(cls, op):
384 "Optional Bias tensor must be of type: {}"
385 bias = op.bias
386 if bias:
387 valid = bias.dtype in cls.supported_bias_dtypes
388 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
389 return True, "Op has no bias tensor"
390
391 @staticmethod
392 def constraint_bias_40bit(op):
393 "Optional Bias tensor values must fit within 40-bits"
394 bias = op.bias
395 if bias and bias.dtype == DataType.int64 and bias.values is not None:
Tim Hall8ae29292021-07-28 16:52:03 +0100396 valid = all(len(bin(value)[2:]) <= 40 for value in bias.values)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200397 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
398 return True, "Op has no bias tensor, or it fits in 40-bit"
399
400 @staticmethod
401 def constraint_batch_size(op):
402 "IFM Tensor batch size must be 1"
403 ifm = op.ifm
404 valid = ifm.shape[0] == 1
405 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
406
407 @staticmethod
408 def constraint_depth_multiplier(op):
409 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
410 depth_multiplier = op.attrs.get("depth_multiplier", 1)
411 if depth_multiplier > 1:
412 ifm_channels = op.ifm.shape[3]
413 ofm_channels = op.ofm.shape[3]
414 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
415 extra = (
416 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
417 f" and depth_multiplier={depth_multiplier}"
418 )
419 return valid, extra
420 return True, "Op has depth_multiplier=1"
421
422 @staticmethod
423 def constraint_tconv_stride(op):
424 "Stride values for both width and height must be 2"
425 w = op.kernel.stride.x
426 h = op.kernel.stride.y
427 valid = (w == 2) and (h == 2)
428 return valid, f"Op has stride WxH as: {w}x{h}"
429
430 @staticmethod
431 def constraint_tconv_same(op):
432 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
433 if op.attrs["padding"] == Padding.SAME:
434 w = op.kernel.stride.x
435 h = op.kernel.stride.y
436 ifm_shape = op.ifm.shape
437 ofm_shape = op.ofm.shape
438 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
439 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
440 return True, "Op has padding=VALID"
441
442 @staticmethod
443 def constraint_tconv_valid(op):
444 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
445 minus difference between kernel size and stride"""
446 if op.attrs["padding"] == Padding.VALID:
447 s_w = op.kernel.stride.x
448 s_h = op.kernel.stride.y
449 k_w = op.kernel.width
450 k_h = op.kernel.height
451 ifm_shape = op.ifm.shape
452 ofm_shape = op.ofm.shape
453 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
454 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
455 valid = height_check and width_check
456 extra = (
457 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
458 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
459 )
460 return valid, extra
461 return True, "Op has padding=SAME"
462
463 @classmethod
464 @docstring_format_args(filter_range)
465 def constraint_filter_range(cls, op):
466 "Kernel filter values for both width and height must be in the range [{}, {}]"
467 if op.attrs["padding"] == Padding.SAME:
468 w = op.kernel.width
469 h = op.kernel.height
470 filter_min, filter_max = cls.filter_range
471 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
472 return valid, f"Op has kernel filter WxH as: {w}x{h}"
473 return True, "Op has padding=VALID"
474
475 @classmethod
476 @docstring_format_args(filter_height_range)
477 def constraint_filter_height_range(cls, op):
478 "Kernel filter height must be in the range [{}, {}]"
479 h = op.kernel.height
480 filter_height_min, filter_height_max = cls.filter_height_range
481 valid = filter_height_min <= h <= filter_height_max
482 return valid, f"Op has kernel filter height as: {h}"
483
484 @classmethod
485 @docstring_format_args(filter_product_range)
486 def constraint_filter_product_range(cls, op):
487 "Product of kernel filter width and height must be in the range [{}, {}]"
488 product = op.kernel.elements_wh()
489 filter_product_min, filter_product_max = cls.filter_product_range
490 valid = filter_product_min <= product <= filter_product_max
491 return valid, f"Op has product of kernel filter width and height as: {product}"
492
493 @staticmethod
494 @docstring_format_args(filter_height_range)
495 def constraint_filter_height_range_valid_pad(op):
496 "VALID padding: Kernel filter height must be in the range [{}, {}]"
497 if op.attrs["padding"] == Padding.VALID:
498 return TFLiteSupportedOperators.constraint_filter_height_range(op)
499 return True, "Op has padding=SAME"
500
501 @staticmethod
502 @docstring_format_args(filter_product_range)
503 def constraint_filter_product_range_valid_pad(op):
504 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
505 if op.attrs["padding"] == Padding.VALID:
506 return TFLiteSupportedOperators.constraint_filter_product_range(op)
507 return True, "Op has padding=SAME"
508
509 @staticmethod
510 def constraint_resize(op):
511 """The width and height of the IFM and OFM must match one of the following criteria:
512 IFM W and H must both be 1
513 IFM must match OFM
514 OFM W and H must be 2x IFM -1, if align_corners is True
515 OFM W and H must be 2x IFM, if align_corners is False"""
516 # Easier to start with False condition as very few cases result in a supported resize
517 valid = False
518 ifm_shape = op.ifm.shape
519 ofm_shape = op.ofm.shape
520 align_corners = op.attrs.get("align_corners", False)
521 if len(ifm_shape) == 4:
522 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
523 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
524 valid = True
525 else:
526 upscaled_shape = np.array(ifm_shape[1:3])
527 out_shape = np.array(ofm_shape[1:3])
528 while (upscaled_shape < out_shape).all():
529 upscaled_shape *= 2
530 if align_corners:
531 upscaled_shape -= 1
532 # Valid if OFM is 2x IFM (-1 for align corners)
533 if np.array_equal(out_shape, upscaled_shape):
534 valid = True
535 break
536 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
537
538 @staticmethod
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200539 def constraint_bilinear_resize_attrs(op):
540 "half_pixel_centers are not supported"
541 valid = True
542 if op.attrs.get("half_pixel_centers"):
543 valid = False
544 return valid, f"Op has half_pixel_centers set to {not valid}."
545
546 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200547 def constraint_pad_shape(op):
548 "The padding tensor must have the shape [3,2] or [4,2]"
549 valid = op.inputs[1].shape in ([3, 2], [4, 2])
550 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
551
552 @classmethod
553 @docstring_format_args([list_formatter(supported_pad_dtypes)])
554 def constraint_pad_type(cls, op):
555 "Pad tensor must be of type: {}"
556 pad_tensor = op.inputs[1]
557 valid = pad_tensor.dtype in cls.supported_pad_dtypes
558 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
559
560 @staticmethod
561 def constraint_padding_dimensions(op):
562 "The pad tensor can only pad width and height"
563 pad_tensor = op.inputs[1].values
564
565 valid = sum(pad_tensor[-1, :]) == 0
566 if valid and len(pad_tensor) > 3:
567 valid = sum(pad_tensor[0, :]) == 0
568 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
569
570 @staticmethod
571 def constraint_stridedslice_stride_values(op):
572 "All Strides values must be 1"
573 strides = op.inputs[3]
574 valid = all(stride == 1 for stride in strides.values)
575 return valid, f"Op has strides values {strides.values}"
576
577 @staticmethod
578 def constraint_inputs_int32(op):
579 "Both Input data types must be int32"
580 ifm_dtype = op.ifm.dtype
581 ifm2_dtype = op.ifm2.dtype
582 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
583 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
584
585 @staticmethod
586 def constraint_output_int32(op):
587 "OFM must be int32"
588 ofm_dtype = op.ofm.dtype
589 valid = ofm_dtype == DataType.int32
590 return valid, f"Op has ofm_dtype={ofm_dtype}"
591
592 @staticmethod
593 def constraint_matching_quantization_parameters(op):
594 "Both Input quantization parameters must match OFM quantization parameters"
595 valid = True
596 extra = []
597 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
598 valid = False
599 extra.append(op.ifm.name)
600 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
601 valid = False
602 extra.append(op.ifm2.name)
603 extra = ", ".join(extra)
604 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
605
606 @staticmethod
607 def constraint_elemwise_batch_size(op):
608 "Batch size must be 1 for Input tensors with more than 2 dimensions"
609 valid = True
610 extra = []
611 for tens in (op.ifm, op.ifm2):
612 # Unary ops have ifm2 as None
613 if tens is not None:
614 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
615 valid = False
616 extra.append(tens.name)
617 extra = ", ".join(extra)
618 return valid, f"Op has invalid input tensors: {extra}"
619
620 @staticmethod
621 def constraint_broadcast_shapes(op):
622 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
623 ifm_shape = op.ifm.shape
624 ifm2_shape = op.ifm2.shape if op.ifm2 else None
625 ofm_shape = op.ofm.shape
626 valid = True
627 if ifm_shape is not None and ifm2_shape is not None:
628 # align trailing dimensions
629 size = min(len(ifm_shape), len(ifm2_shape))
630 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
631 mi = max(i, i2)
632 # Input dimensions should match or one should be of dimension 1
633 # Output dimension should match the largest input dimension, together
634 # with constraint_match_either_shapes ensures broadcast from only one input
635 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
636 valid = False
637 break
638
639 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
640
641 @classmethod
642 @docstring_format_args([mean_kernel_product_avgpool])
643 def constraint_mean_height_width_product_avgpool(cls, op):
644 """Product of height and width can be at most {}"""
645 shape = op.inputs[0].shape
646 hi = 0 if len(shape) < 4 else 1
647 h, w = shape[hi : hi + 2]
648 max_prod = cls.mean_kernel_product_avgpool
649 return h * w <= max_prod, f"Product of height and width is {h * w}"
650
651 @classmethod
652 @docstring_format_args([mean_kernel_product])
653 def constraint_mean_height_width_product(cls, op):
654 """Product of height and width can be at most {} when IFM and OFM have different scale or zero point,
655 or keep_dims is True"""
656 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
657 keep_dims = op.attrs.get("keep_dims")
658 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
659 if not keep_dims and ifmq.scale_f32 == ofmq.scale_f32 and ifmq.zero_point == ofmq.zero_point:
660 return True, ""
661 shape = op.inputs[0].shape
662 hi = 0 if len(shape) < 4 else 1
663 h, w = shape[hi : hi + 2]
664 max_prod = cls.mean_kernel_product
665 return h * w <= max_prod, f"Product of height and width is {h * w}"
666
667 @classmethod
668 @docstring_format_args([mean_kernel_product_int8])
669 def constraint_mean_height_width_product_int8(cls, op):
670 """Product of IFM height and width can be at most {} when the following are true:
671 IFM dimensions are 4,
672 Axis indices are 1 and 2,
673 keep_dims is set to True and
674 IFM datatype is int8"""
675 shape = op.ifm.shape
676 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
677 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
678 # and constraint_mean_height_width_product
679 if (
680 len(shape) != 4
681 or op.ifm.dtype != DataType.int8
682 or not op.attrs.get("keep_dims")
683 or axis not in ([1, 2], [2, 1])
684 ):
685 return True, ""
686 hi = 0 if len(shape) < 4 else 1
687 h, w = shape[hi : hi + 2]
688 max_prod = cls.mean_kernel_product_int8
689 return h * w <= max_prod, f"Product of height and width is {h * w}"
Tim Hall3584a9c2021-11-18 22:05:17 +0000690
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000691 @classmethod
692 @docstring_format_args([dilated_height_range[1]])
693 def constraint_depthwise_conv_height_single_axis(cls, op):
694 """Height can be at most {} for single axis when axis is 1."""
695 inp, axis = op.inputs
696 if axis.shape == [] or axis.shape[0] == 1: # single axis
697 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
698 else:
699 # Multiple axes, constraint does not apply
700 return True, ""
701
702 # Height and width axes have different index depending on dimensions
703 shape = inp.shape
704 h = shape[0] if len(shape) < 4 else shape[1]
705
706 # If quantization is the same across IFM and OFM op will become avgpool and this constraint does not apply.
707 ifm, ofm = op.get_ifm_ofm()
708 if check_quantized_tens_scaling_equal(ifm, ofm):
709 return True, ""
710
711 return h <= 64 or axis != 1, f"Height is {h} and axis is {axis}."
712
713 @classmethod
714 @docstring_format_args([filter_height_range[1]])
715 def constraint_avgpool_height_single_axis(cls, op):
716 """Avgpool height can be at most {} for single axis when axis is 1."""
717 inp, axis = op.inputs
718 if axis.shape == [] or axis.shape[0] == 1: # single axis
719 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
720 else:
721 # Multiple axes, constraint does not apply
722 return True, ""
723
724 # Height and width axes have different index depending on dimensions
725 shape = inp.shape
726 h = shape[0] if len(shape) < 4 else shape[1]
727 ifm, ofm = op.get_ifm_ofm()
728 scaling_equal = check_quantized_tens_scaling_equal(ifm, ofm)
729
730 return h <= 256 or axis != 1 or not scaling_equal, f"Height is {h} and axis is {axis}"
731
Tim Hall3584a9c2021-11-18 22:05:17 +0000732 @staticmethod
733 def constraint_reshape_shape_constant(op):
734 "Shape must be constant"
735 valid = True
736 extra = []
737
738 reshape_tens = op.inputs[1]
739 if reshape_tens is not None:
740 # constant inputs have either no driving operator or a const one
741 # create a list of non-constant inputs
742 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
743 valid = False
744 extra.append(reshape_tens.name)
745 extra = ", ".join(extra)
746
747 return valid, f"Op has non-const input(s): {extra}"