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