blob: 9aa174de6e507cba42b252b17d87e4253cb43d04 [file] [log] [blame]
Rickard Bolinfea15162022-07-04 16:19:16 +00001# Copyright (C) 2020-2022 Arm Limited or its affiliates. All rights reserved.
Jonas Ohlsson45e653d2021-07-26 16:13:12 +02002#
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 )
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200126 activation_ops = relu_ops | set(
127 (
128 Op.Tanh,
129 Op.Sigmoid,
130 Op.Softmax,
131 Op.HardSwish,
132 Op.Prelu,
133 )
134 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200135 npu_post_ops = (
136 # activation functions
137 activation_ops
138 # concatenation write direction
139 | set((Op.ConcatSliceWrite,))
140 # Quantization
141 | set((Op.Quantize,))
142 )
Jonas Ohlssond8575072022-03-30 10:30:25 +0200143 split_ops = set(
144 (
145 Op.Split,
146 Op.SplitV,
147 Op.StridedSlice,
148 Op.Slice,
149 Op.UnpackReshaped,
150 Op.Unpack,
151 )
152 )
153 concat_ops = set(
154 (
155 Op.Concat,
156 Op.ConcatTFLite,
157 Op.PackReshaped,
158 Op.Pack,
159 )
160 )
161 memory_only_ops = (
162 set(
163 (
164 Op.Reshape,
165 Op.QuantizedReshape,
166 Op.Squeeze,
167 Op.ExpandDims,
168 )
169 )
170 | concat_ops
171 | split_ops
172 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200173 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Jonas Ohlssond8575072022-03-30 10:30:25 +0200174 supported_fused_activations = relu_ops | set(
175 (
176 Op.Tanh,
177 Op.Sigmoid,
178 Op.LUT,
179 )
180 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200181 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
182 # Supported data types
183 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
184 supported_faf_dtypes = set((DataType.uint8, DataType.int8, DataType.int16))
185 supported_bias_dtypes = set((DataType.int32, DataType.int64))
186 supported_pad_dtypes = set((DataType.int32, DataType.int64))
187 # Defined ranges for allowed values:
188 tens_dim_range = (1, 65535)
189 stride_range = (1, 3)
190 dilation_range = (1, 2)
191 dilated_height_range = (1, 64)
192 dilated_product_range = (1, 64 * 64)
193 weights_limit = 127 * 65536
194 filter_range = (1, 8)
195 filter_height_range = (1, 256)
196 filter_product_range = (1, 256 * 256)
197 mean_kernel_product = 64 * 64
198 mean_kernel_product_int8 = 16 * 16
199 mean_kernel_product_avgpool = 256 * 256
200
201 def __init__(self):
202 # Setup the generic constraints. Note: the order matters
203 self.generic_constraints = []
204 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dtype)
205 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_int32_ops)
206 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dimension)
207 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_quant_per_axis)
208 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf)
209 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf_type)
210
211 # Setup specific constraints. Note: the order matters
212 self.specific_constraints = defaultdict(list)
213
214 # Conv-like checks:
215 for op_type in TFLiteSupportedOperators.convolution_like_ops:
216 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
217 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilation_range)
218 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_height_range)
219 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_product_range)
220 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
221 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
222 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_limit)
223 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
224 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
225 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
226 # Depthwise Conv specific checks:
227 for op_type in TFLiteSupportedOperators.depthwise_convolution_ops:
228 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_depth_multiplier)
229 # Transpose Conv specific checks:
230 for op_type in TFLiteSupportedOperators.transpose_convolution_ops:
231 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_stride)
232 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_same)
233 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_valid)
234
235 # Pooling checks:
236 for op_type in TFLiteSupportedOperators.pooling_ops:
237 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
238 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
239 # AVG pooling specific checks:
240 for op_type in TFLiteSupportedOperators.avg_pooling_ops:
241 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_range)
242 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range_valid_pad)
243 self.specific_constraints[op_type].append(
244 TFLiteSupportedOperators.constraint_filter_product_range_valid_pad
245 )
246 # MAX pooling specific checks:
247 for op_type in TFLiteSupportedOperators.max_pooling_ops:
248 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range)
249 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_product_range)
250
251 # Resizing specific checks:
252 for op_type in TFLiteSupportedOperators.resizing_ops:
Tim Hall885033b2022-07-21 11:46:03 +0100253 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize)
254 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_size)
255 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_attrs)
256 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_half_pixel_centers)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200257
Rickard Bolinfea15162022-07-04 16:19:16 +0000258 # Resize Bilinear specific checks:
259 self.specific_constraints[Op.ResizeBilinear].append(
260 TFLiteSupportedOperators.constraint_resizebi_half_pixel_centers_dims
261 )
262
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200263 # Vector Product specific checks:
264 for op_type in TFLiteSupportedOperators.fc_vector_products:
265 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
266 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
267 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
268 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
269
270 # Element-wise checks:
271 for op_type in TFLiteSupportedOperators.elem_wise_main_ops:
272 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_elemwise_batch_size)
273 # Binary Min/Max specific checks:
274 for op_type in TFLiteSupportedOperators.binary_elem_wise_min_max_ops:
275 self.specific_constraints[op_type].append(
276 TFLiteSupportedOperators.constraint_matching_quantization_parameters
277 )
278 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
279 # Binary Add/Mul/Sub specific checks:
280 for op_type in TFLiteSupportedOperators.binary_elem_wise_add_mul_sub:
281 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
282 # Binary Shift specific checks:
283 for op_type in TFLiteSupportedOperators.binary_elem_wise_shift_ops:
284 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_inputs_int32)
285 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
286
287 # SHL specific checks:
288 self.specific_constraints[Op.SHL].append(TFLiteSupportedOperators.constraint_output_int32)
289
290 # CLZ specific checks:
291 self.specific_constraints[Op.CLZ].append(TFLiteSupportedOperators.constraint_output_int32)
292
293 # StridedSlice specific checks:
294 self.specific_constraints[Op.StridedSlice].append(
295 TFLiteSupportedOperators.constraint_stridedslice_stride_values
296 )
297
298 # Pad specific checks:
299 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_shape)
300 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_padding_dimensions)
301 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_type)
302
303 # Mean specific checks:
Dwight Lidmanf54c18d2021-09-29 17:23:03 +0200304 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_batch_size)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200305 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_avgpool)
306 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product)
307 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_int8)
James Peet0bb7ad12022-02-15 15:07:54 +0000308 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_single_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200309
Tim Hall3584a9c2021-11-18 22:05:17 +0000310 # Reshape specific checks:
311 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
Johan Alfvén17009392022-08-30 09:14:56 +0200312 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_before_mean)
Tim Hall3584a9c2021-11-18 22:05:17 +0000313
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200314 def is_operator_supported(self, op):
315 ext_type = optype_to_builtintype(op.type)
316 if op.type not in TFLiteSupportedOperators.supported_operators:
317 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
318 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
319 return False
320
321 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
322 valid, extra = constraint(op)
323 if not valid:
324 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
325 print(f" - {constraint.__doc__}")
326 if extra:
327 print(f" {extra}")
328 return False
329
330 return True
331
332 @classmethod
333 @docstring_format_args([list_formatter(supported_op_dtypes)])
334 def constraint_tens_dtype(cls, op):
335 "Tensors must be of type: {}"
336 valid = True
337 extra = []
338 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
339 if not tensors:
340 tensors = [tens for tens in op.inputs if tens]
341 for tens in tensors:
342 if tens.dtype not in cls.supported_op_dtypes:
343 valid = False
344 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
345 return valid, ", ".join(extra)
346
347 @classmethod
348 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
349 def constraint_tens_int32_ops(cls, op):
350 "Tensors which are int32 are only valid when op type is: {}"
351 valid = True
352 extra = []
353 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
354 if not tensors:
355 tensors = [tens for tens in op.inputs if tens]
356 for tens in tensors:
357 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
358 valid = False
359 extra.append(tens.name)
360 extra = ", ".join(extra)
361 return valid, f"Op has int32 tensor(s): {extra}"
362
363 @classmethod
364 @docstring_format_args(tens_dim_range)
365 def constraint_tens_dimension(cls, op):
366 "Tensor dimensions must be in the range [{}, {}]"
367 tens_min, tens_max = cls.tens_dim_range
368 valid = True
369 extra = []
370 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
371 if not tensors:
372 tensors = [tens for tens in op.inputs if tens]
373 for tens in tensors:
374 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
375 valid = False
376 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
377 return valid, ", ".join(extra)
378
379 @classmethod
380 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
381 def constraint_tens_quant_per_axis(cls, op):
382 "Per-axis quantization is only supported for the following op types: {}"
383 valid = True
384 extra = []
385 if op.type not in cls.per_axis_quant_ops:
386 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
387 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200388 if tens.quantization and tens.quantization.is_per_axis():
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200389 valid = False
390 extra.append(tens.name)
391 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
392
393 @classmethod
394 @docstring_format_args([_optype_formatter(supported_fused_activations)])
395 def constraint_faf(cls, op):
396 "The fused activation function (if present) must be one of type: {}"
397 if op.activation is None:
398 res = True, "Op has no fused activation function"
399 else:
400 faf = op.activation.op_type
401 valid = faf in cls.supported_fused_activations
402 res = valid, f"Op has its fused activation function as: {faf}"
403 return res
404
405 @classmethod
406 @docstring_format_args([list_formatter(supported_faf_dtypes)])
407 def constraint_faf_type(cls, op):
408 "If a fused activation function is present, the Output tensor must be one of type: {}"
409 if op.activation is None:
410 res = True, "Op has no fused activation function"
411 else:
412 valid = op.ofm.dtype in cls.supported_faf_dtypes
413 ext_type = optype_to_builtintype(op.activation.op_type)
414 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
415 return res
416
417 @classmethod
418 @docstring_format_args(stride_range)
419 def constraint_stride_range(cls, op):
420 "Stride values for both width and height must be in the range [{}, {}]"
421 w, h = op.get_kernel_stride()
422 stride_min, stride_max = cls.stride_range
423 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
424 return valid, f"Op has stride WxH as: {w}x{h}"
425
426 @classmethod
427 @docstring_format_args(dilation_range)
428 def constraint_dilation_range(cls, op):
429 "Dilation factor values for both width and height must be in the range [{}, {}]"
430 w, h = op.get_kernel_dilation()
431 dilation_min, dilation_max = cls.dilation_range
432 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
433 return valid, f"Op has dilation factor WxH as: {w}x{h}"
434
435 @classmethod
436 @docstring_format_args(dilated_height_range)
437 def constraint_dilated_height_range(cls, op):
438 "Dilated kernel height must be in the range [{}, {}]"
439 h = op.kernel.area_height()
440 dilated_height_min, dilated_height_max = cls.dilated_height_range
441 valid = dilated_height_min <= h <= dilated_height_max
442 return valid, f"Op has dilated kernel height as: {h}"
443
444 @classmethod
445 @docstring_format_args(dilated_product_range)
446 def constraint_dilated_product_range(cls, op):
447 "Product of dilated kernel width and height must be in the range [{}, {}]"
448 product = op.kernel.area_width() * op.kernel.area_height()
449 dilated_product_min, dilated_product_max = cls.dilated_product_range
450 valid = dilated_product_min <= product <= dilated_product_max
451 return valid, f"Op has product of dilated kernel width and height as: {product}"
452
453 @staticmethod
454 def constraint_weights_type(op):
455 "Weight tensor must be 8-bit"
456 weights = op.weights
457 valid = weights.element_size() == 1
458 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
459
460 @staticmethod
461 def constraint_weights_const(op):
462 "Weight tensor must be constant"
463 weights = op.weights
464 valid = weights.values is not None
465 return valid, f"Tensor '{weights.name}' has non-constant values"
466
467 @classmethod
468 @docstring_format_args([weights_limit])
469 def constraint_weights_limit(cls, op):
470 "The sum of the weights cannot exceed {}"
471 weights = op.weights
472 values = weights.values.astype(np.int64) - weights.quantization.zero_point
473 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
474 valid = limit <= cls.weights_limit
475 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
476
477 @classmethod
478 @docstring_format_args([list_formatter(supported_bias_dtypes)])
479 def constraint_bias_type(cls, op):
480 "Optional Bias tensor must be of type: {}"
481 bias = op.bias
482 if bias:
483 valid = bias.dtype in cls.supported_bias_dtypes
484 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
485 return True, "Op has no bias tensor"
486
487 @staticmethod
488 def constraint_bias_40bit(op):
489 "Optional Bias tensor values must fit within 40-bits"
490 bias = op.bias
491 if bias and bias.dtype == DataType.int64 and bias.values is not None:
Tim Hall8ae29292021-07-28 16:52:03 +0100492 valid = all(len(bin(value)[2:]) <= 40 for value in bias.values)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200493 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
494 return True, "Op has no bias tensor, or it fits in 40-bit"
495
496 @staticmethod
497 def constraint_batch_size(op):
498 "IFM Tensor batch size must be 1"
499 ifm = op.ifm
500 valid = ifm.shape[0] == 1
501 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
502
503 @staticmethod
504 def constraint_depth_multiplier(op):
505 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
506 depth_multiplier = op.attrs.get("depth_multiplier", 1)
507 if depth_multiplier > 1:
508 ifm_channels = op.ifm.shape[3]
509 ofm_channels = op.ofm.shape[3]
510 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
511 extra = (
512 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
513 f" and depth_multiplier={depth_multiplier}"
514 )
515 return valid, extra
516 return True, "Op has depth_multiplier=1"
517
518 @staticmethod
519 def constraint_tconv_stride(op):
520 "Stride values for both width and height must be 2"
521 w = op.kernel.stride.x
522 h = op.kernel.stride.y
523 valid = (w == 2) and (h == 2)
524 return valid, f"Op has stride WxH as: {w}x{h}"
525
526 @staticmethod
527 def constraint_tconv_same(op):
528 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
529 if op.attrs["padding"] == Padding.SAME:
530 w = op.kernel.stride.x
531 h = op.kernel.stride.y
532 ifm_shape = op.ifm.shape
533 ofm_shape = op.ofm.shape
534 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
535 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
536 return True, "Op has padding=VALID"
537
538 @staticmethod
539 def constraint_tconv_valid(op):
540 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200541 minus difference between kernel size and stride"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200542 if op.attrs["padding"] == Padding.VALID:
543 s_w = op.kernel.stride.x
544 s_h = op.kernel.stride.y
545 k_w = op.kernel.width
546 k_h = op.kernel.height
547 ifm_shape = op.ifm.shape
548 ofm_shape = op.ofm.shape
549 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
550 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
551 valid = height_check and width_check
552 extra = (
553 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
554 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
555 )
556 return valid, extra
557 return True, "Op has padding=SAME"
558
559 @classmethod
560 @docstring_format_args(filter_range)
561 def constraint_filter_range(cls, op):
562 "Kernel filter values for both width and height must be in the range [{}, {}]"
563 if op.attrs["padding"] == Padding.SAME:
564 w = op.kernel.width
565 h = op.kernel.height
566 filter_min, filter_max = cls.filter_range
567 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
568 return valid, f"Op has kernel filter WxH as: {w}x{h}"
569 return True, "Op has padding=VALID"
570
571 @classmethod
572 @docstring_format_args(filter_height_range)
573 def constraint_filter_height_range(cls, op):
574 "Kernel filter height must be in the range [{}, {}]"
575 h = op.kernel.height
576 filter_height_min, filter_height_max = cls.filter_height_range
577 valid = filter_height_min <= h <= filter_height_max
578 return valid, f"Op has kernel filter height as: {h}"
579
580 @classmethod
581 @docstring_format_args(filter_product_range)
582 def constraint_filter_product_range(cls, op):
583 "Product of kernel filter width and height must be in the range [{}, {}]"
584 product = op.kernel.elements_wh()
585 filter_product_min, filter_product_max = cls.filter_product_range
586 valid = filter_product_min <= product <= filter_product_max
587 return valid, f"Op has product of kernel filter width and height as: {product}"
588
589 @staticmethod
590 @docstring_format_args(filter_height_range)
591 def constraint_filter_height_range_valid_pad(op):
592 "VALID padding: Kernel filter height must be in the range [{}, {}]"
593 if op.attrs["padding"] == Padding.VALID:
594 return TFLiteSupportedOperators.constraint_filter_height_range(op)
595 return True, "Op has padding=SAME"
596
597 @staticmethod
598 @docstring_format_args(filter_product_range)
599 def constraint_filter_product_range_valid_pad(op):
600 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
601 if op.attrs["padding"] == Padding.VALID:
602 return TFLiteSupportedOperators.constraint_filter_product_range(op)
603 return True, "Op has padding=SAME"
604
605 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100606 def constraint_resize(op):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200607 """The width and height of the IFM and OFM must match one of the following criteria:
608 IFM W and H must both be 1
609 IFM must match OFM
Rickard Bolinfea15162022-07-04 16:19:16 +0000610 W and H scaling 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
611 W and H scaling 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 +0200612 # Easier to start with False condition as very few cases result in a supported resize
613 valid = False
614 ifm_shape = op.ifm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100615 ifm_shape_h = ifm_shape[1]
616 ifm_shape_w = ifm_shape[2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200617 ofm_shape = op.ofm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100618 ofm_shape_h = ofm_shape[1]
619 ofm_shape_w = ofm_shape[2]
620
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200621 align_corners = op.attrs.get("align_corners", False)
622 if len(ifm_shape) == 4:
623 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
Tim Hall47c76362022-07-18 21:26:47 +0100624 if ((ifm_shape_h == 1) and (ifm_shape_w == 1)) or (ifm_shape == ofm_shape):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200625 valid = True
626 else:
Rickard Boline546def2022-01-25 15:45:00 +0000627 # Valid if OFM is 2/4/8x IFM (-1 for align corners)
Tim Hall47c76362022-07-18 21:26:47 +0100628 if align_corners:
629 h_upscale_factor = (ofm_shape_h - 1) / (ifm_shape_h - 1)
630 w_upscale_factor = (ofm_shape_w - 1) / (ifm_shape_w - 1)
631 else:
632 h_upscale_factor = ofm_shape_h / ifm_shape_h
633 w_upscale_factor = ofm_shape_w / ifm_shape_w
Rickard Boline546def2022-01-25 15:45:00 +0000634
Tim Hall47c76362022-07-18 21:26:47 +0100635 # could use either height or width. save as int because it is more usable later in graph optimiser
636 op.attrs["upscale_factor"] = int(h_upscale_factor)
637 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 +0000638
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200639 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
640
641 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100642 def constraint_resize_size(op):
Tim Hall47c76362022-07-18 21:26:47 +0100643 "The size tensor must match the output tensor shape"
644 valid = False
645 ofm_shape = op.ofm.shape
646 size_h, size_w = None, None
647 # check that the size tensor (the second input) exists, is not none, and has the correct values
648 if len(op.inputs) == 2 and op.inputs[1] is not None and len(op.inputs[1].values) == 2:
649 size_h, size_w = op.inputs[1].values
650 # check size and output size match
651 if size_h == ofm_shape[1] and size_w == ofm_shape[2]:
652 valid = True
653
654 return valid, f"Op has size={size_h}x{size_w} and ofm_shape={ofm_shape}."
655
656 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100657 def constraint_resize_attrs(op):
Tim Hall47c76362022-07-18 21:26:47 +0100658 "Both align_corners and half_pixel_centers can't be True"
659 valid = True
660 align_corners = op.attrs.get("align_corners", False)
661 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
662
663 if align_corners and half_pixel_centers:
664 valid = False
665 return valid, "Op has both align_corners and half_pixel_centers set to True."
666
667 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100668 def constraint_resize_half_pixel_centers(op):
Rickard Bolinfea15162022-07-04 16:19:16 +0000669 """Half_pixel_centers are only supported for resize bilinear with IFM dtype int8 or uint8"""
670 valid = op.ifm.dtype in (DataType.int8, DataType.uint8)
671 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
672 if half_pixel_centers and op.type != Op.ResizeBilinear:
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200673 valid = False
Rickard Bolinfea15162022-07-04 16:19:16 +0000674 return valid, f"Op type={op.type}, ifm dtype={op.ifm.dtype} and half_pixel_centers={half_pixel_centers}"
675
676 @staticmethod
677 def constraint_resizebi_half_pixel_centers_dims(op):
678 """Half_pixel_centers for resize bilinear requires that OFM W and H is 2x IFM W and H"""
679 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
680 if not half_pixel_centers:
681 valid = True
682 elif len(op.ifm.shape) >= 3:
683 ifm_h, ifm_w = op.ifm.shape[-3:-1]
684 ofm_h, ofm_w = op.ofm.shape[-3:-1]
685 valid = ofm_h / ifm_h == 2 and ofm_w / ifm_w == 2
686 else:
687 # Unexpected IFM shape
688 valid = False
689 return (
690 valid,
691 f"Op has ifm_shape={op.ifm.shape}, ofm_shape={op.ofm.shape} and half_pixel_centers={half_pixel_centers}",
692 )
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200693
694 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200695 def constraint_pad_shape(op):
696 "The padding tensor must have the shape [3,2] or [4,2]"
697 valid = op.inputs[1].shape in ([3, 2], [4, 2])
698 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
699
700 @classmethod
701 @docstring_format_args([list_formatter(supported_pad_dtypes)])
702 def constraint_pad_type(cls, op):
703 "Pad tensor must be of type: {}"
704 pad_tensor = op.inputs[1]
705 valid = pad_tensor.dtype in cls.supported_pad_dtypes
706 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
707
708 @staticmethod
709 def constraint_padding_dimensions(op):
710 "The pad tensor can only pad width and height"
711 pad_tensor = op.inputs[1].values
712
713 valid = sum(pad_tensor[-1, :]) == 0
714 if valid and len(pad_tensor) > 3:
715 valid = sum(pad_tensor[0, :]) == 0
716 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
717
718 @staticmethod
719 def constraint_stridedslice_stride_values(op):
720 "All Strides values must be 1"
721 strides = op.inputs[3]
722 valid = all(stride == 1 for stride in strides.values)
723 return valid, f"Op has strides values {strides.values}"
724
725 @staticmethod
726 def constraint_inputs_int32(op):
727 "Both Input data types must be int32"
728 ifm_dtype = op.ifm.dtype
729 ifm2_dtype = op.ifm2.dtype
730 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
731 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
732
733 @staticmethod
734 def constraint_output_int32(op):
735 "OFM must be int32"
736 ofm_dtype = op.ofm.dtype
737 valid = ofm_dtype == DataType.int32
738 return valid, f"Op has ofm_dtype={ofm_dtype}"
739
740 @staticmethod
741 def constraint_matching_quantization_parameters(op):
742 "Both Input quantization parameters must match OFM quantization parameters"
743 valid = True
744 extra = []
745 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
746 valid = False
747 extra.append(op.ifm.name)
748 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
749 valid = False
750 extra.append(op.ifm2.name)
751 extra = ", ".join(extra)
752 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
753
754 @staticmethod
755 def constraint_elemwise_batch_size(op):
756 "Batch size must be 1 for Input tensors with more than 2 dimensions"
757 valid = True
758 extra = []
759 for tens in (op.ifm, op.ifm2):
760 # Unary ops have ifm2 as None
761 if tens is not None:
762 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
763 valid = False
764 extra.append(tens.name)
765 extra = ", ".join(extra)
766 return valid, f"Op has invalid input tensors: {extra}"
767
768 @staticmethod
769 def constraint_broadcast_shapes(op):
770 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
771 ifm_shape = op.ifm.shape
772 ifm2_shape = op.ifm2.shape if op.ifm2 else None
773 ofm_shape = op.ofm.shape
774 valid = True
775 if ifm_shape is not None and ifm2_shape is not None:
776 # align trailing dimensions
777 size = min(len(ifm_shape), len(ifm2_shape))
778 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
779 mi = max(i, i2)
780 # Input dimensions should match or one should be of dimension 1
781 # Output dimension should match the largest input dimension, together
782 # with constraint_match_either_shapes ensures broadcast from only one input
783 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
784 valid = False
785 break
786
787 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
788
789 @classmethod
790 @docstring_format_args([mean_kernel_product_avgpool])
791 def constraint_mean_height_width_product_avgpool(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000792 """Product of height and width must be no greater than {}"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200793 shape = op.inputs[0].shape
794 hi = 0 if len(shape) < 4 else 1
795 h, w = shape[hi : hi + 2]
796 max_prod = cls.mean_kernel_product_avgpool
797 return h * w <= max_prod, f"Product of height and width is {h * w}"
798
799 @classmethod
800 @docstring_format_args([mean_kernel_product])
801 def constraint_mean_height_width_product(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000802 """Product of height and width must be no greater than {} when:
803 IFM and OFM have different scale or zero point; or
804 'keep_dims' is True"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200805 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
806 keep_dims = op.attrs.get("keep_dims")
807 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
808 if not keep_dims and ifmq.scale_f32 == ofmq.scale_f32 and ifmq.zero_point == ofmq.zero_point:
809 return True, ""
810 shape = op.inputs[0].shape
811 hi = 0 if len(shape) < 4 else 1
812 h, w = shape[hi : hi + 2]
813 max_prod = cls.mean_kernel_product
814 return h * w <= max_prod, f"Product of height and width is {h * w}"
815
Johan Alfvén05916632022-09-06 20:33:22 +0200816 @classmethod
817 @docstring_format_args([mean_kernel_product_int8])
818 def constraint_mean_height_width_product_int8(cls, op):
819 """Product of IFM height and width must be no greater than {} when:
James Peet0bb7ad12022-02-15 15:07:54 +0000820 The IFM shape has 4 dimensions; and
821 The axis indices specify reduction across 2 dimensions; and
822 The axis indices correspond to the width and height dimensions of the IFM; and
823 'keep_dims' is True; and
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200824 IFM datatype is int8"""
825 shape = op.ifm.shape
826 axis = int(op.inputs[1].values) if op.inputs[1].shape == [] else list(op.inputs[1].values)
827 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
828 # and constraint_mean_height_width_product
829 if (
830 len(shape) != 4
831 or op.ifm.dtype != DataType.int8
832 or not op.attrs.get("keep_dims")
833 or axis not in ([1, 2], [2, 1])
834 ):
835 return True, ""
James Peet0bb7ad12022-02-15 15:07:54 +0000836 h = shape[-3]
837 w = shape[-2]
Johan Alfvén05916632022-09-06 20:33:22 +0200838 max_prod = cls.mean_kernel_product_int8
839 return h * w <= max_prod, f"Product of height and width is {h * w}"
Tim Hall3584a9c2021-11-18 22:05:17 +0000840
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000841 @classmethod
James Peet0bb7ad12022-02-15 15:07:54 +0000842 @docstring_format_args([filter_height_range[1], dilated_height_range[1]])
843 def constraint_mean_height_single_axis(cls, op):
844 """For single axis averages across the height dimension:
845 IFM height must be no greater than {} if the IFM and OFM scale and zero point match; otherwise
846 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 +0000847 inp, axis = op.inputs
848 if axis.shape == [] or axis.shape[0] == 1: # single axis
849 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
850 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000851 # Multiple axes
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000852 return True, ""
853
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000854 shape = inp.shape
James Peet0bb7ad12022-02-15 15:07:54 +0000855 if len(shape) < 3:
856 # No height dimension present in IFM
857 return True, ""
858 if axis != len(shape) - 3:
859 # Not averaging across the height dimension
860 return True, ""
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000861
James Peet0bb7ad12022-02-15 15:07:54 +0000862 h = shape[axis]
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000863 ifm, ofm = op.get_ifm_ofm()
James Peet0bb7ad12022-02-15 15:07:54 +0000864
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000865 if check_quantized_tens_scaling_equal(ifm, ofm):
James Peet0bb7ad12022-02-15 15:07:54 +0000866 return h <= cls.filter_height_range[1], f"Height is {h}, IFM and OFM quantizations match"
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000867 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000868 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 +0000869
Tim Hall3584a9c2021-11-18 22:05:17 +0000870 @staticmethod
871 def constraint_reshape_shape_constant(op):
872 "Shape must be constant"
873 valid = True
874 extra = []
875
876 reshape_tens = op.inputs[1]
877 if reshape_tens is not None:
878 # constant inputs have either no driving operator or a const one
879 # create a list of non-constant inputs
880 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
881 valid = False
882 extra.append(reshape_tens.name)
883 extra = ", ".join(extra)
884
885 return valid, f"Op has non-const input(s): {extra}"
Johan Alfvén8e1352a2022-08-16 13:04:17 +0200886
887 @staticmethod
Johan Alfvén17009392022-08-30 09:14:56 +0200888 def constraint_reshape_before_mean(op):
889 "Reshape on NPU not supported before MEAN operator"
890 for next_op in op.outputs[0].consumers():
891 if next_op is not None and next_op.type == Op.Mean:
892 return False, ""
893 return True, ""