blob: aabe8130f4ac77a9b493152102b7d92bb1bd8e9c [file] [log] [blame]
Rickard Bolinbc6ee582022-11-04 08:24:29 +00001# SPDX-FileCopyrightText: Copyright 2020-2022 Arm Limited and/or its affiliates <open-source-office@arm.com>
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.
Rickard Bolinbc6ee582022-11-04 08:24:29 +000016#
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020017# Description:
18# The TFLiteSupportedOperators class which is a collection of all TFLite supported operators and parameter checks.
19from collections import defaultdict
20
21import numpy as np
22
23from .data_type import DataType
Fredrik Svedberg88d5b122022-09-16 16:24:55 +020024from .numeric_util import full_shape
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020025from .operation import Op
26from .operation import Padding
27from .supported_operators_util import docstring_format_args
28from .supported_operators_util import list_formatter
29from .tensor import check_quantized_tens_scaling_equal
30from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
31from .tflite_mapping import optype_to_builtintype
32
33
34def _optype_formatter(op_list):
35 # Convert internal op types to external names
36 output = map(optype_to_builtintype, op_list)
37 # Remove UNKNOWNs
38 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
39 return list_formatter(output)
40
41
42class TFLiteSupportedOperators:
43 # Categorised lists of supported operators
Fredrik Svedberg11563172022-07-06 14:54:12 +020044 npu_pre_ops = set(
45 (
46 Op.SplitSliceRead,
47 Op.Shape,
48 )
49 )
Jonas Ohlssond8575072022-03-30 10:30:25 +020050 convolution_ops = set(
51 (
52 Op.Conv2DBias,
53 Op.Conv2D,
54 Op.QuantizedConv2D,
55 )
56 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020057 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
58 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
59 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
60 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
61 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
62 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
Tim Hall885033b2022-07-21 11:46:03 +010063 resizing_ops = Op.op_set(Op.is_resize_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020064 fc_vector_products = set(
65 (
66 Op.QuantizedMatMul,
67 Op.MatMul,
68 Op.FullyConnected,
69 )
70 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020071 mac_main_ops = (
72 # RNN/LSTM/GRU
73 set((Op.BlockLSTM,))
74 # conv/depthwiseconv/transposeconv
75 | convolution_like_ops
76 # pooling
77 | pooling_ops
78 # resizing/upscaling
79 | resizing_ops
80 # FC layers
81 | fc_vector_products
82 # Mean (converts to depthwise conv)
83 | set((Op.Mean,))
84 )
85 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020086 binary_elem_wise_min_max_ops = set(
87 (
88 Op.Minimum,
89 Op.Maximum,
90 )
91 )
92 binary_elem_wise_shift_ops = set(
93 (
94 Op.SHL,
95 Op.SHR,
96 )
97 )
98 binary_elem_wise_add_mul_sub = set(
99 (
100 Op.Add,
101 Op.Mul,
102 Op.Sub,
103 )
104 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200105 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
106 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
107 pad_ops = set((Op.Pad,))
108 supported_int32_tensor_ops = (
Jonas Ohlssond8575072022-03-30 10:30:25 +0200109 set(
110 (
111 Op.ReduceSum,
112 Op.CLZ,
Fredrik Svedberg11563172022-07-06 14:54:12 +0200113 Op.Shape,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200114 )
115 )
116 | binary_elem_wise_add_mul_sub
117 | binary_elem_wise_shift_ops
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200118 )
119
Jonas Ohlssond8575072022-03-30 10:30:25 +0200120 relu_ops = set(
121 (
122 Op.Relu,
123 Op.Relu6,
124 Op.ReluN1To1,
125 Op.Clip,
126 )
127 )
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200128 activation_ops = relu_ops | set(
129 (
130 Op.Tanh,
131 Op.Sigmoid,
132 Op.Softmax,
133 Op.HardSwish,
Fredrik Svedberg1cd39492022-09-23 15:38:03 +0200134 Op.LeakyRelu,
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200135 Op.Prelu,
136 )
137 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200138 npu_post_ops = (
139 # activation functions
140 activation_ops
141 # concatenation write direction
142 | set((Op.ConcatSliceWrite,))
143 # Quantization
144 | set((Op.Quantize,))
145 )
Jonas Ohlssond8575072022-03-30 10:30:25 +0200146 split_ops = set(
147 (
148 Op.Split,
149 Op.SplitV,
150 Op.StridedSlice,
151 Op.Slice,
152 Op.UnpackReshaped,
153 Op.Unpack,
154 )
155 )
156 concat_ops = set(
157 (
158 Op.Concat,
159 Op.ConcatTFLite,
160 Op.PackReshaped,
161 Op.Pack,
162 )
163 )
164 memory_only_ops = (
165 set(
166 (
167 Op.Reshape,
168 Op.QuantizedReshape,
169 Op.Squeeze,
170 Op.ExpandDims,
171 )
172 )
173 | concat_ops
174 | split_ops
175 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200176 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Jonas Ohlssond8575072022-03-30 10:30:25 +0200177 supported_fused_activations = relu_ops | set(
178 (
179 Op.Tanh,
180 Op.Sigmoid,
181 Op.LUT,
182 )
183 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200184 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
185 # Supported data types
186 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
187 supported_faf_dtypes = set((DataType.uint8, DataType.int8, DataType.int16))
188 supported_bias_dtypes = set((DataType.int32, DataType.int64))
189 supported_pad_dtypes = set((DataType.int32, DataType.int64))
190 # Defined ranges for allowed values:
191 tens_dim_range = (1, 65535)
192 stride_range = (1, 3)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200193 dilated_height_range = (1, 64)
194 dilated_product_range = (1, 64 * 64)
195 weights_limit = 127 * 65536
196 filter_range = (1, 8)
197 filter_height_range = (1, 256)
198 filter_product_range = (1, 256 * 256)
199 mean_kernel_product = 64 * 64
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200200 mean_kernel_product_avgpool = 256 * 256
201
202 def __init__(self):
203 # Setup the generic constraints. Note: the order matters
204 self.generic_constraints = []
205 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dtype)
206 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_int32_ops)
207 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dimension)
208 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_quant_per_axis)
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200209 self.generic_constraints.append(TFLiteSupportedOperators.constraint_batch_size)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200210 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf)
211 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf_type)
212
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200213 # Setup generic constraint exceptions
214 self.generic_constraints_exceptions = defaultdict(list)
215 self.generic_constraints_exceptions[Op.FullyConnected].append(TFLiteSupportedOperators.constraint_batch_size)
216 self.generic_constraints_exceptions[Op.Softmax].append(TFLiteSupportedOperators.constraint_batch_size)
217 self.generic_constraints_exceptions[Op.Reshape].append(TFLiteSupportedOperators.constraint_batch_size)
218 self.generic_constraints_exceptions[Op.Shape].append(TFLiteSupportedOperators.constraint_batch_size)
219 self.generic_constraints_exceptions[Op.Squeeze].append(TFLiteSupportedOperators.constraint_batch_size)
220 for op_type in TFLiteSupportedOperators.split_ops - set((Op.UnpackReshaped,)):
221 self.generic_constraints_exceptions[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
222
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200223 # Setup specific constraints. Note: the order matters
224 self.specific_constraints = defaultdict(list)
225
226 # Conv-like checks:
227 for op_type in TFLiteSupportedOperators.convolution_like_ops:
Tim Hallea4ba662022-11-11 18:19:53 +0000228 if op_type not in TFLiteSupportedOperators.transpose_convolution_ops:
229 # Transpose Conv has a specific stride constraint (see constraint_tconv_stride below)
230 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
231
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200232 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_height_range)
233 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_product_range)
234 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
235 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
236 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_limit)
237 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
238 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200239 # Transpose Conv specific checks:
240 for op_type in TFLiteSupportedOperators.transpose_convolution_ops:
241 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_stride)
242 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_same)
243 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_valid)
Tim Halld3d81b32022-10-18 19:14:04 +0100244 # Depthwise Conv specific checks:
245 for op_type in TFLiteSupportedOperators.depthwise_convolution_ops:
246 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_depth_multiplier)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200247
248 # Pooling checks:
249 for op_type in TFLiteSupportedOperators.pooling_ops:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200250 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
251 # AVG pooling specific checks:
252 for op_type in TFLiteSupportedOperators.avg_pooling_ops:
253 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_range)
254 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range_valid_pad)
255 self.specific_constraints[op_type].append(
256 TFLiteSupportedOperators.constraint_filter_product_range_valid_pad
257 )
258 # MAX pooling specific checks:
259 for op_type in TFLiteSupportedOperators.max_pooling_ops:
260 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range)
261 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_product_range)
262
263 # Resizing specific checks:
264 for op_type in TFLiteSupportedOperators.resizing_ops:
Tim Hall885033b2022-07-21 11:46:03 +0100265 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize)
266 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_size)
267 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_attrs)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200268
Rickard Bolinfea15162022-07-04 16:19:16 +0000269 # Resize Bilinear specific checks:
270 self.specific_constraints[Op.ResizeBilinear].append(
271 TFLiteSupportedOperators.constraint_resizebi_half_pixel_centers_dims
272 )
273
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200274 # Vector Product specific checks:
275 for op_type in TFLiteSupportedOperators.fc_vector_products:
276 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
277 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
278 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
279 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
280
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200281 # Element-wise checks
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200282 # Binary Min/Max specific checks:
283 for op_type in TFLiteSupportedOperators.binary_elem_wise_min_max_ops:
284 self.specific_constraints[op_type].append(
285 TFLiteSupportedOperators.constraint_matching_quantization_parameters
286 )
287 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
288 # Binary Add/Mul/Sub specific checks:
289 for op_type in TFLiteSupportedOperators.binary_elem_wise_add_mul_sub:
290 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
291 # Binary Shift specific checks:
292 for op_type in TFLiteSupportedOperators.binary_elem_wise_shift_ops:
293 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_inputs_int32)
294 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
295
296 # SHL specific checks:
297 self.specific_constraints[Op.SHL].append(TFLiteSupportedOperators.constraint_output_int32)
298
299 # CLZ specific checks:
300 self.specific_constraints[Op.CLZ].append(TFLiteSupportedOperators.constraint_output_int32)
301
302 # StridedSlice specific checks:
303 self.specific_constraints[Op.StridedSlice].append(
304 TFLiteSupportedOperators.constraint_stridedslice_stride_values
305 )
306
307 # Pad specific checks:
308 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_shape)
309 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_padding_dimensions)
310 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_type)
311
312 # Mean specific checks:
313 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_avgpool)
314 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product)
James Peet0bb7ad12022-02-15 15:07:54 +0000315 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_single_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200316
Tim Hall3584a9c2021-11-18 22:05:17 +0000317 # Reshape specific checks:
318 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
319
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200320 def is_operator_supported(self, op):
321 ext_type = optype_to_builtintype(op.type)
322 if op.type not in TFLiteSupportedOperators.supported_operators:
323 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
324 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
325 return False
326
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200327 op_exceptions = self.generic_constraints_exceptions[op.type]
328 generic_constraints = [constraint for constraint in self.generic_constraints if constraint not in op_exceptions]
329
330 for constraint in generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200331 valid, extra = constraint(op)
332 if not valid:
333 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
334 print(f" - {constraint.__doc__}")
335 if extra:
336 print(f" {extra}")
337 return False
338
339 return True
340
341 @classmethod
342 @docstring_format_args([list_formatter(supported_op_dtypes)])
343 def constraint_tens_dtype(cls, op):
344 "Tensors must be of type: {}"
345 valid = True
346 extra = []
347 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
348 if not tensors:
349 tensors = [tens for tens in op.inputs if tens]
350 for tens in tensors:
351 if tens.dtype not in cls.supported_op_dtypes:
352 valid = False
353 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
354 return valid, ", ".join(extra)
355
356 @classmethod
357 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
358 def constraint_tens_int32_ops(cls, op):
359 "Tensors which are int32 are only valid when op type is: {}"
360 valid = True
361 extra = []
362 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
363 if not tensors:
364 tensors = [tens for tens in op.inputs if tens]
365 for tens in tensors:
366 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
367 valid = False
368 extra.append(tens.name)
369 extra = ", ".join(extra)
370 return valid, f"Op has int32 tensor(s): {extra}"
371
372 @classmethod
373 @docstring_format_args(tens_dim_range)
374 def constraint_tens_dimension(cls, op):
375 "Tensor dimensions must be in the range [{}, {}]"
376 tens_min, tens_max = cls.tens_dim_range
377 valid = True
378 extra = []
379 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
380 if not tensors:
381 tensors = [tens for tens in op.inputs if tens]
382 for tens in tensors:
383 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
384 valid = False
385 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
386 return valid, ", ".join(extra)
387
388 @classmethod
389 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
390 def constraint_tens_quant_per_axis(cls, op):
391 "Per-axis quantization is only supported for the following op types: {}"
392 valid = True
393 extra = []
394 if op.type not in cls.per_axis_quant_ops:
395 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
396 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200397 if tens.quantization and tens.quantization.is_per_axis():
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200398 valid = False
399 extra.append(tens.name)
400 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
401
402 @classmethod
403 @docstring_format_args([_optype_formatter(supported_fused_activations)])
404 def constraint_faf(cls, op):
405 "The fused activation function (if present) must be one of type: {}"
406 if op.activation is None:
407 res = True, "Op has no fused activation function"
408 else:
409 faf = op.activation.op_type
410 valid = faf in cls.supported_fused_activations
411 res = valid, f"Op has its fused activation function as: {faf}"
412 return res
413
414 @classmethod
415 @docstring_format_args([list_formatter(supported_faf_dtypes)])
416 def constraint_faf_type(cls, op):
417 "If a fused activation function is present, the Output tensor must be one of type: {}"
418 if op.activation is None:
419 res = True, "Op has no fused activation function"
420 else:
421 valid = op.ofm.dtype in cls.supported_faf_dtypes
422 ext_type = optype_to_builtintype(op.activation.op_type)
423 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
424 return res
425
426 @classmethod
427 @docstring_format_args(stride_range)
428 def constraint_stride_range(cls, op):
429 "Stride values for both width and height must be in the range [{}, {}]"
430 w, h = op.get_kernel_stride()
431 stride_min, stride_max = cls.stride_range
432 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
433 return valid, f"Op has stride WxH as: {w}x{h}"
434
435 @classmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200436 @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"
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200499 valid = True
500 extra = []
501 for tens in (op.ifm, op.ifm2):
502 if tens is not None:
503 batch_size = full_shape(4, tens.shape, 1)[0]
504 if batch_size != 1:
505 valid = False
506 extra.append(f"Tensor '{tens.name}' has batch size: {batch_size}")
507 extra = "\n ".join(extra)
508 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200509
510 @staticmethod
511 def constraint_depth_multiplier(op):
512 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
513 depth_multiplier = op.attrs.get("depth_multiplier", 1)
514 if depth_multiplier > 1:
515 ifm_channels = op.ifm.shape[3]
516 ofm_channels = op.ofm.shape[3]
517 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
518 extra = (
519 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
520 f" and depth_multiplier={depth_multiplier}"
521 )
522 return valid, extra
523 return True, "Op has depth_multiplier=1"
524
525 @staticmethod
526 def constraint_tconv_stride(op):
527 "Stride values for both width and height must be 2"
528 w = op.kernel.stride.x
529 h = op.kernel.stride.y
530 valid = (w == 2) and (h == 2)
531 return valid, f"Op has stride WxH as: {w}x{h}"
532
533 @staticmethod
534 def constraint_tconv_same(op):
535 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
536 if op.attrs["padding"] == Padding.SAME:
537 w = op.kernel.stride.x
538 h = op.kernel.stride.y
539 ifm_shape = op.ifm.shape
540 ofm_shape = op.ofm.shape
541 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
542 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
543 return True, "Op has padding=VALID"
544
545 @staticmethod
546 def constraint_tconv_valid(op):
547 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200548 minus difference between kernel size and stride"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200549 if op.attrs["padding"] == Padding.VALID:
550 s_w = op.kernel.stride.x
551 s_h = op.kernel.stride.y
552 k_w = op.kernel.width
553 k_h = op.kernel.height
554 ifm_shape = op.ifm.shape
555 ofm_shape = op.ofm.shape
556 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
557 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
558 valid = height_check and width_check
559 extra = (
560 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
561 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
562 )
563 return valid, extra
564 return True, "Op has padding=SAME"
565
566 @classmethod
567 @docstring_format_args(filter_range)
568 def constraint_filter_range(cls, op):
569 "Kernel filter values for both width and height must be in the range [{}, {}]"
570 if op.attrs["padding"] == Padding.SAME:
571 w = op.kernel.width
572 h = op.kernel.height
573 filter_min, filter_max = cls.filter_range
574 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
575 return valid, f"Op has kernel filter WxH as: {w}x{h}"
576 return True, "Op has padding=VALID"
577
578 @classmethod
579 @docstring_format_args(filter_height_range)
580 def constraint_filter_height_range(cls, op):
581 "Kernel filter height must be in the range [{}, {}]"
582 h = op.kernel.height
583 filter_height_min, filter_height_max = cls.filter_height_range
584 valid = filter_height_min <= h <= filter_height_max
585 return valid, f"Op has kernel filter height as: {h}"
586
587 @classmethod
588 @docstring_format_args(filter_product_range)
589 def constraint_filter_product_range(cls, op):
590 "Product of kernel filter width and height must be in the range [{}, {}]"
591 product = op.kernel.elements_wh()
592 filter_product_min, filter_product_max = cls.filter_product_range
593 valid = filter_product_min <= product <= filter_product_max
594 return valid, f"Op has product of kernel filter width and height as: {product}"
595
596 @staticmethod
597 @docstring_format_args(filter_height_range)
598 def constraint_filter_height_range_valid_pad(op):
599 "VALID padding: Kernel filter height must be in the range [{}, {}]"
600 if op.attrs["padding"] == Padding.VALID:
601 return TFLiteSupportedOperators.constraint_filter_height_range(op)
602 return True, "Op has padding=SAME"
603
604 @staticmethod
605 @docstring_format_args(filter_product_range)
606 def constraint_filter_product_range_valid_pad(op):
607 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
608 if op.attrs["padding"] == Padding.VALID:
609 return TFLiteSupportedOperators.constraint_filter_product_range(op)
610 return True, "Op has padding=SAME"
611
612 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100613 def constraint_resize(op):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200614 """The width and height of the IFM and OFM must match one of the following criteria:
615 IFM W and H must both be 1
616 IFM must match OFM
Rickard Bolinfea15162022-07-04 16:19:16 +0000617 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
618 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 +0200619 # Easier to start with False condition as very few cases result in a supported resize
620 valid = False
621 ifm_shape = op.ifm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100622 ifm_shape_h = ifm_shape[1]
623 ifm_shape_w = ifm_shape[2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200624 ofm_shape = op.ofm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100625 ofm_shape_h = ofm_shape[1]
626 ofm_shape_w = ofm_shape[2]
627
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200628 align_corners = op.attrs.get("align_corners", False)
629 if len(ifm_shape) == 4:
630 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
Tim Hall47c76362022-07-18 21:26:47 +0100631 if ((ifm_shape_h == 1) and (ifm_shape_w == 1)) or (ifm_shape == ofm_shape):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200632 valid = True
633 else:
Rickard Boline546def2022-01-25 15:45:00 +0000634 # Valid if OFM is 2/4/8x IFM (-1 for align corners)
Tim Hall47c76362022-07-18 21:26:47 +0100635 if align_corners:
636 h_upscale_factor = (ofm_shape_h - 1) / (ifm_shape_h - 1)
637 w_upscale_factor = (ofm_shape_w - 1) / (ifm_shape_w - 1)
638 else:
639 h_upscale_factor = ofm_shape_h / ifm_shape_h
640 w_upscale_factor = ofm_shape_w / ifm_shape_w
Rickard Boline546def2022-01-25 15:45:00 +0000641
Tim Hall47c76362022-07-18 21:26:47 +0100642 # could use either height or width. save as int because it is more usable later in graph optimiser
643 op.attrs["upscale_factor"] = int(h_upscale_factor)
644 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 +0000645
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200646 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
647
648 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100649 def constraint_resize_size(op):
Tim Hall47c76362022-07-18 21:26:47 +0100650 "The size tensor must match the output tensor shape"
651 valid = False
652 ofm_shape = op.ofm.shape
653 size_h, size_w = None, None
654 # check that the size tensor (the second input) exists, is not none, and has the correct values
655 if len(op.inputs) == 2 and op.inputs[1] is not None and len(op.inputs[1].values) == 2:
656 size_h, size_w = op.inputs[1].values
657 # check size and output size match
658 if size_h == ofm_shape[1] and size_w == ofm_shape[2]:
659 valid = True
660
661 return valid, f"Op has size={size_h}x{size_w} and ofm_shape={ofm_shape}."
662
663 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100664 def constraint_resize_attrs(op):
Tim Hall47c76362022-07-18 21:26:47 +0100665 "Both align_corners and half_pixel_centers can't be True"
666 valid = True
667 align_corners = op.attrs.get("align_corners", False)
668 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
669
670 if align_corners and half_pixel_centers:
671 valid = False
672 return valid, "Op has both align_corners and half_pixel_centers set to True."
673
674 @staticmethod
Rickard Bolinfea15162022-07-04 16:19:16 +0000675 def constraint_resizebi_half_pixel_centers_dims(op):
676 """Half_pixel_centers for resize bilinear requires that OFM W and H is 2x IFM W and H"""
677 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
678 if not half_pixel_centers:
679 valid = True
680 elif len(op.ifm.shape) >= 3:
681 ifm_h, ifm_w = op.ifm.shape[-3:-1]
682 ofm_h, ofm_w = op.ofm.shape[-3:-1]
683 valid = ofm_h / ifm_h == 2 and ofm_w / ifm_w == 2
684 else:
685 # Unexpected IFM shape
686 valid = False
687 return (
688 valid,
689 f"Op has ifm_shape={op.ifm.shape}, ofm_shape={op.ofm.shape} and half_pixel_centers={half_pixel_centers}",
690 )
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200691
692 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200693 def constraint_pad_shape(op):
694 "The padding tensor must have the shape [3,2] or [4,2]"
695 valid = op.inputs[1].shape in ([3, 2], [4, 2])
696 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
697
698 @classmethod
699 @docstring_format_args([list_formatter(supported_pad_dtypes)])
700 def constraint_pad_type(cls, op):
701 "Pad tensor must be of type: {}"
702 pad_tensor = op.inputs[1]
703 valid = pad_tensor.dtype in cls.supported_pad_dtypes
704 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
705
706 @staticmethod
707 def constraint_padding_dimensions(op):
708 "The pad tensor can only pad width and height"
709 pad_tensor = op.inputs[1].values
710
711 valid = sum(pad_tensor[-1, :]) == 0
712 if valid and len(pad_tensor) > 3:
713 valid = sum(pad_tensor[0, :]) == 0
714 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
715
716 @staticmethod
717 def constraint_stridedslice_stride_values(op):
718 "All Strides values must be 1"
719 strides = op.inputs[3]
720 valid = all(stride == 1 for stride in strides.values)
721 return valid, f"Op has strides values {strides.values}"
722
723 @staticmethod
724 def constraint_inputs_int32(op):
725 "Both Input data types must be int32"
726 ifm_dtype = op.ifm.dtype
727 ifm2_dtype = op.ifm2.dtype
728 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
729 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
730
731 @staticmethod
732 def constraint_output_int32(op):
733 "OFM must be int32"
734 ofm_dtype = op.ofm.dtype
735 valid = ofm_dtype == DataType.int32
736 return valid, f"Op has ofm_dtype={ofm_dtype}"
737
738 @staticmethod
739 def constraint_matching_quantization_parameters(op):
740 "Both Input quantization parameters must match OFM quantization parameters"
741 valid = True
742 extra = []
743 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
744 valid = False
745 extra.append(op.ifm.name)
746 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
747 valid = False
748 extra.append(op.ifm2.name)
749 extra = ", ".join(extra)
750 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
751
752 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200753 def constraint_broadcast_shapes(op):
754 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
755 ifm_shape = op.ifm.shape
756 ifm2_shape = op.ifm2.shape if op.ifm2 else None
757 ofm_shape = op.ofm.shape
758 valid = True
759 if ifm_shape is not None and ifm2_shape is not None:
760 # align trailing dimensions
761 size = min(len(ifm_shape), len(ifm2_shape))
762 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
763 mi = max(i, i2)
764 # Input dimensions should match or one should be of dimension 1
765 # Output dimension should match the largest input dimension, together
766 # with constraint_match_either_shapes ensures broadcast from only one input
767 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
768 valid = False
769 break
770
771 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
772
773 @classmethod
774 @docstring_format_args([mean_kernel_product_avgpool])
775 def constraint_mean_height_width_product_avgpool(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000776 """Product of height and width must be no greater than {}"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200777 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_avgpool
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])
785 def constraint_mean_height_width_product(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000786 """Product of height and width must be no greater than {} when:
787 IFM and OFM have different scale or zero point; or
788 'keep_dims' is True"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200789 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
790 keep_dims = op.attrs.get("keep_dims")
791 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
792 if not keep_dims and ifmq.scale_f32 == ofmq.scale_f32 and ifmq.zero_point == ofmq.zero_point:
793 return True, ""
794 shape = op.inputs[0].shape
795 hi = 0 if len(shape) < 4 else 1
796 h, w = shape[hi : hi + 2]
797 max_prod = cls.mean_kernel_product
798 return h * w <= max_prod, f"Product of height and width is {h * w}"
799
Johan Alfvén05916632022-09-06 20:33:22 +0200800 @classmethod
James Peet0bb7ad12022-02-15 15:07:54 +0000801 @docstring_format_args([filter_height_range[1], dilated_height_range[1]])
802 def constraint_mean_height_single_axis(cls, op):
803 """For single axis averages across the height dimension:
804 IFM height must be no greater than {} if the IFM and OFM scale and zero point match; otherwise
805 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 +0000806 inp, axis = op.inputs
807 if axis.shape == [] or axis.shape[0] == 1: # single axis
808 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
809 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000810 # Multiple axes
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000811 return True, ""
812
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000813 shape = inp.shape
James Peet0bb7ad12022-02-15 15:07:54 +0000814 if len(shape) < 3:
815 # No height dimension present in IFM
816 return True, ""
817 if axis != len(shape) - 3:
818 # Not averaging across the height dimension
819 return True, ""
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000820
James Peet0bb7ad12022-02-15 15:07:54 +0000821 h = shape[axis]
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000822 ifm, ofm = op.get_ifm_ofm()
James Peet0bb7ad12022-02-15 15:07:54 +0000823
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000824 if check_quantized_tens_scaling_equal(ifm, ofm):
James Peet0bb7ad12022-02-15 15:07:54 +0000825 return h <= cls.filter_height_range[1], f"Height is {h}, IFM and OFM quantizations match"
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000826 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000827 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 +0000828
Tim Hall3584a9c2021-11-18 22:05:17 +0000829 @staticmethod
830 def constraint_reshape_shape_constant(op):
831 "Shape must be constant"
832 valid = True
833 extra = []
834
835 reshape_tens = op.inputs[1]
836 if reshape_tens is not None:
837 # constant inputs have either no driving operator or a const one
838 # create a list of non-constant inputs
839 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
840 valid = False
841 extra.append(reshape_tens.name)
842 extra = ", ".join(extra)
843
844 return valid, f"Op has non-const input(s): {extra}"