blob: abbfb17127a835f6b8eb9103d86d01ddf47b4eb6 [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
Fredrik Svedberg88d5b122022-09-16 16:24:55 +020023from .numeric_util import full_shape
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020024from .operation import Op
25from .operation import Padding
26from .supported_operators_util import docstring_format_args
27from .supported_operators_util import list_formatter
28from .tensor import check_quantized_tens_scaling_equal
29from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
30from .tflite_mapping import optype_to_builtintype
31
32
33def _optype_formatter(op_list):
34 # Convert internal op types to external names
35 output = map(optype_to_builtintype, op_list)
36 # Remove UNKNOWNs
37 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
38 return list_formatter(output)
39
40
41class TFLiteSupportedOperators:
42 # Categorised lists of supported operators
Fredrik Svedberg11563172022-07-06 14:54:12 +020043 npu_pre_ops = set(
44 (
45 Op.SplitSliceRead,
46 Op.Shape,
47 )
48 )
Jonas Ohlssond8575072022-03-30 10:30:25 +020049 convolution_ops = set(
50 (
51 Op.Conv2DBias,
52 Op.Conv2D,
53 Op.QuantizedConv2D,
54 )
55 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020056 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
57 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
58 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
59 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
60 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
61 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
Tim Hall885033b2022-07-21 11:46:03 +010062 resizing_ops = Op.op_set(Op.is_resize_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020063 fc_vector_products = set(
64 (
65 Op.QuantizedMatMul,
66 Op.MatMul,
67 Op.FullyConnected,
68 )
69 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020070 mac_main_ops = (
71 # RNN/LSTM/GRU
72 set((Op.BlockLSTM,))
73 # conv/depthwiseconv/transposeconv
74 | convolution_like_ops
75 # pooling
76 | pooling_ops
77 # resizing/upscaling
78 | resizing_ops
79 # FC layers
80 | fc_vector_products
81 # Mean (converts to depthwise conv)
82 | set((Op.Mean,))
83 )
84 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020085 binary_elem_wise_min_max_ops = set(
86 (
87 Op.Minimum,
88 Op.Maximum,
89 )
90 )
91 binary_elem_wise_shift_ops = set(
92 (
93 Op.SHL,
94 Op.SHR,
95 )
96 )
97 binary_elem_wise_add_mul_sub = set(
98 (
99 Op.Add,
100 Op.Mul,
101 Op.Sub,
102 )
103 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200104 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
105 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
106 pad_ops = set((Op.Pad,))
107 supported_int32_tensor_ops = (
Jonas Ohlssond8575072022-03-30 10:30:25 +0200108 set(
109 (
110 Op.ReduceSum,
111 Op.CLZ,
Fredrik Svedberg11563172022-07-06 14:54:12 +0200112 Op.Shape,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200113 )
114 )
115 | binary_elem_wise_add_mul_sub
116 | binary_elem_wise_shift_ops
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200117 )
118
Jonas Ohlssond8575072022-03-30 10:30:25 +0200119 relu_ops = set(
120 (
121 Op.Relu,
122 Op.Relu6,
123 Op.ReluN1To1,
124 Op.Clip,
125 )
126 )
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200127 activation_ops = relu_ops | set(
128 (
129 Op.Tanh,
130 Op.Sigmoid,
131 Op.Softmax,
132 Op.HardSwish,
Fredrik Svedberg1cd39492022-09-23 15:38:03 +0200133 Op.LeakyRelu,
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200134 Op.Prelu,
135 )
136 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200137 npu_post_ops = (
138 # activation functions
139 activation_ops
140 # concatenation write direction
141 | set((Op.ConcatSliceWrite,))
142 # Quantization
143 | set((Op.Quantize,))
144 )
Jonas Ohlssond8575072022-03-30 10:30:25 +0200145 split_ops = set(
146 (
147 Op.Split,
148 Op.SplitV,
149 Op.StridedSlice,
150 Op.Slice,
151 Op.UnpackReshaped,
152 Op.Unpack,
153 )
154 )
155 concat_ops = set(
156 (
157 Op.Concat,
158 Op.ConcatTFLite,
159 Op.PackReshaped,
160 Op.Pack,
161 )
162 )
163 memory_only_ops = (
164 set(
165 (
166 Op.Reshape,
167 Op.QuantizedReshape,
168 Op.Squeeze,
169 Op.ExpandDims,
170 )
171 )
172 | concat_ops
173 | split_ops
174 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200175 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Jonas Ohlssond8575072022-03-30 10:30:25 +0200176 supported_fused_activations = relu_ops | set(
177 (
178 Op.Tanh,
179 Op.Sigmoid,
180 Op.LUT,
181 )
182 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200183 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
184 # Supported data types
185 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
186 supported_faf_dtypes = set((DataType.uint8, DataType.int8, DataType.int16))
187 supported_bias_dtypes = set((DataType.int32, DataType.int64))
188 supported_pad_dtypes = set((DataType.int32, DataType.int64))
189 # Defined ranges for allowed values:
190 tens_dim_range = (1, 65535)
191 stride_range = (1, 3)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200192 dilated_height_range = (1, 64)
193 dilated_product_range = (1, 64 * 64)
194 weights_limit = 127 * 65536
195 filter_range = (1, 8)
196 filter_height_range = (1, 256)
197 filter_product_range = (1, 256 * 256)
198 mean_kernel_product = 64 * 64
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200199 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)
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200208 self.generic_constraints.append(TFLiteSupportedOperators.constraint_batch_size)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200209 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf)
210 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf_type)
211
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200212 # Setup generic constraint exceptions
213 self.generic_constraints_exceptions = defaultdict(list)
214 self.generic_constraints_exceptions[Op.FullyConnected].append(TFLiteSupportedOperators.constraint_batch_size)
215 self.generic_constraints_exceptions[Op.Softmax].append(TFLiteSupportedOperators.constraint_batch_size)
216 self.generic_constraints_exceptions[Op.Reshape].append(TFLiteSupportedOperators.constraint_batch_size)
217 self.generic_constraints_exceptions[Op.Shape].append(TFLiteSupportedOperators.constraint_batch_size)
218 self.generic_constraints_exceptions[Op.Squeeze].append(TFLiteSupportedOperators.constraint_batch_size)
219 for op_type in TFLiteSupportedOperators.split_ops - set((Op.UnpackReshaped,)):
220 self.generic_constraints_exceptions[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
221
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200222 # Setup specific constraints. Note: the order matters
223 self.specific_constraints = defaultdict(list)
224
225 # Conv-like checks:
226 for op_type in TFLiteSupportedOperators.convolution_like_ops:
Tim Hallea4ba662022-11-11 18:19:53 +0000227 if op_type not in TFLiteSupportedOperators.transpose_convolution_ops:
228 # Transpose Conv has a specific stride constraint (see constraint_tconv_stride below)
229 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
230
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200231 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_height_range)
232 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_product_range)
233 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
234 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
235 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_limit)
236 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
237 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200238 # Transpose Conv specific checks:
239 for op_type in TFLiteSupportedOperators.transpose_convolution_ops:
240 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_stride)
241 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_same)
242 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_tconv_valid)
Tim Halld3d81b32022-10-18 19:14:04 +0100243 # Depthwise Conv specific checks:
244 for op_type in TFLiteSupportedOperators.depthwise_convolution_ops:
245 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_depth_multiplier)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200246
247 # Pooling checks:
248 for op_type in TFLiteSupportedOperators.pooling_ops:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200249 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
250 # AVG pooling specific checks:
251 for op_type in TFLiteSupportedOperators.avg_pooling_ops:
252 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_range)
253 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range_valid_pad)
254 self.specific_constraints[op_type].append(
255 TFLiteSupportedOperators.constraint_filter_product_range_valid_pad
256 )
257 # MAX pooling specific checks:
258 for op_type in TFLiteSupportedOperators.max_pooling_ops:
259 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range)
260 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_product_range)
261
262 # Resizing specific checks:
263 for op_type in TFLiteSupportedOperators.resizing_ops:
Tim Hall885033b2022-07-21 11:46:03 +0100264 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize)
265 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_size)
266 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_attrs)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200267
Rickard Bolinfea15162022-07-04 16:19:16 +0000268 # Resize Bilinear specific checks:
269 self.specific_constraints[Op.ResizeBilinear].append(
270 TFLiteSupportedOperators.constraint_resizebi_half_pixel_centers_dims
271 )
272
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200273 # Vector Product specific checks:
274 for op_type in TFLiteSupportedOperators.fc_vector_products:
275 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
276 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
277 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
278 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
279
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200280 # Element-wise checks
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200281 # Binary Min/Max specific checks:
282 for op_type in TFLiteSupportedOperators.binary_elem_wise_min_max_ops:
283 self.specific_constraints[op_type].append(
284 TFLiteSupportedOperators.constraint_matching_quantization_parameters
285 )
286 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
287 # Binary Add/Mul/Sub specific checks:
288 for op_type in TFLiteSupportedOperators.binary_elem_wise_add_mul_sub:
289 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
290 # Binary Shift specific checks:
291 for op_type in TFLiteSupportedOperators.binary_elem_wise_shift_ops:
292 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_inputs_int32)
293 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
294
295 # SHL specific checks:
296 self.specific_constraints[Op.SHL].append(TFLiteSupportedOperators.constraint_output_int32)
297
298 # CLZ specific checks:
299 self.specific_constraints[Op.CLZ].append(TFLiteSupportedOperators.constraint_output_int32)
300
301 # StridedSlice specific checks:
302 self.specific_constraints[Op.StridedSlice].append(
303 TFLiteSupportedOperators.constraint_stridedslice_stride_values
304 )
305
306 # Pad specific checks:
307 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_shape)
308 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_padding_dimensions)
309 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_type)
310
311 # Mean specific checks:
312 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product_avgpool)
313 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product)
James Peet0bb7ad12022-02-15 15:07:54 +0000314 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_single_axis)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200315
Tim Hall3584a9c2021-11-18 22:05:17 +0000316 # Reshape specific checks:
317 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
318
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200319 def is_operator_supported(self, op):
320 ext_type = optype_to_builtintype(op.type)
321 if op.type not in TFLiteSupportedOperators.supported_operators:
322 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
323 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
324 return False
325
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200326 op_exceptions = self.generic_constraints_exceptions[op.type]
327 generic_constraints = [constraint for constraint in self.generic_constraints if constraint not in op_exceptions]
328
329 for constraint in generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200330 valid, extra = constraint(op)
331 if not valid:
332 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
333 print(f" - {constraint.__doc__}")
334 if extra:
335 print(f" {extra}")
336 return False
337
338 return True
339
340 @classmethod
341 @docstring_format_args([list_formatter(supported_op_dtypes)])
342 def constraint_tens_dtype(cls, op):
343 "Tensors must be of type: {}"
344 valid = True
345 extra = []
346 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
347 if not tensors:
348 tensors = [tens for tens in op.inputs if tens]
349 for tens in tensors:
350 if tens.dtype not in cls.supported_op_dtypes:
351 valid = False
352 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
353 return valid, ", ".join(extra)
354
355 @classmethod
356 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
357 def constraint_tens_int32_ops(cls, op):
358 "Tensors which are int32 are only valid when op type is: {}"
359 valid = True
360 extra = []
361 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
362 if not tensors:
363 tensors = [tens for tens in op.inputs if tens]
364 for tens in tensors:
365 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
366 valid = False
367 extra.append(tens.name)
368 extra = ", ".join(extra)
369 return valid, f"Op has int32 tensor(s): {extra}"
370
371 @classmethod
372 @docstring_format_args(tens_dim_range)
373 def constraint_tens_dimension(cls, op):
374 "Tensor dimensions must be in the range [{}, {}]"
375 tens_min, tens_max = cls.tens_dim_range
376 valid = True
377 extra = []
378 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
379 if not tensors:
380 tensors = [tens for tens in op.inputs if tens]
381 for tens in tensors:
382 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
383 valid = False
384 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
385 return valid, ", ".join(extra)
386
387 @classmethod
388 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
389 def constraint_tens_quant_per_axis(cls, op):
390 "Per-axis quantization is only supported for the following op types: {}"
391 valid = True
392 extra = []
393 if op.type not in cls.per_axis_quant_ops:
394 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
395 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200396 if tens.quantization and tens.quantization.is_per_axis():
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200397 valid = False
398 extra.append(tens.name)
399 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
400
401 @classmethod
402 @docstring_format_args([_optype_formatter(supported_fused_activations)])
403 def constraint_faf(cls, op):
404 "The fused activation function (if present) must be one of type: {}"
405 if op.activation is None:
406 res = True, "Op has no fused activation function"
407 else:
408 faf = op.activation.op_type
409 valid = faf in cls.supported_fused_activations
410 res = valid, f"Op has its fused activation function as: {faf}"
411 return res
412
413 @classmethod
414 @docstring_format_args([list_formatter(supported_faf_dtypes)])
415 def constraint_faf_type(cls, op):
416 "If a fused activation function is present, the Output tensor must be one of type: {}"
417 if op.activation is None:
418 res = True, "Op has no fused activation function"
419 else:
420 valid = op.ofm.dtype in cls.supported_faf_dtypes
421 ext_type = optype_to_builtintype(op.activation.op_type)
422 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
423 return res
424
425 @classmethod
426 @docstring_format_args(stride_range)
427 def constraint_stride_range(cls, op):
428 "Stride values for both width and height must be in the range [{}, {}]"
429 w, h = op.get_kernel_stride()
430 stride_min, stride_max = cls.stride_range
431 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
432 return valid, f"Op has stride WxH as: {w}x{h}"
433
434 @classmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200435 @docstring_format_args(dilated_height_range)
436 def constraint_dilated_height_range(cls, op):
437 "Dilated kernel height must be in the range [{}, {}]"
438 h = op.kernel.area_height()
439 dilated_height_min, dilated_height_max = cls.dilated_height_range
440 valid = dilated_height_min <= h <= dilated_height_max
441 return valid, f"Op has dilated kernel height as: {h}"
442
443 @classmethod
444 @docstring_format_args(dilated_product_range)
445 def constraint_dilated_product_range(cls, op):
446 "Product of dilated kernel width and height must be in the range [{}, {}]"
447 product = op.kernel.area_width() * op.kernel.area_height()
448 dilated_product_min, dilated_product_max = cls.dilated_product_range
449 valid = dilated_product_min <= product <= dilated_product_max
450 return valid, f"Op has product of dilated kernel width and height as: {product}"
451
452 @staticmethod
453 def constraint_weights_type(op):
454 "Weight tensor must be 8-bit"
455 weights = op.weights
456 valid = weights.element_size() == 1
457 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
458
459 @staticmethod
460 def constraint_weights_const(op):
461 "Weight tensor must be constant"
462 weights = op.weights
463 valid = weights.values is not None
464 return valid, f"Tensor '{weights.name}' has non-constant values"
465
466 @classmethod
467 @docstring_format_args([weights_limit])
468 def constraint_weights_limit(cls, op):
469 "The sum of the weights cannot exceed {}"
470 weights = op.weights
471 values = weights.values.astype(np.int64) - weights.quantization.zero_point
472 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
473 valid = limit <= cls.weights_limit
474 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
475
476 @classmethod
477 @docstring_format_args([list_formatter(supported_bias_dtypes)])
478 def constraint_bias_type(cls, op):
479 "Optional Bias tensor must be of type: {}"
480 bias = op.bias
481 if bias:
482 valid = bias.dtype in cls.supported_bias_dtypes
483 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
484 return True, "Op has no bias tensor"
485
486 @staticmethod
487 def constraint_bias_40bit(op):
488 "Optional Bias tensor values must fit within 40-bits"
489 bias = op.bias
490 if bias and bias.dtype == DataType.int64 and bias.values is not None:
Tim Hall8ae29292021-07-28 16:52:03 +0100491 valid = all(len(bin(value)[2:]) <= 40 for value in bias.values)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200492 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
493 return True, "Op has no bias tensor, or it fits in 40-bit"
494
495 @staticmethod
496 def constraint_batch_size(op):
497 "IFM Tensor batch size must be 1"
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200498 valid = True
499 extra = []
500 for tens in (op.ifm, op.ifm2):
501 if tens is not None:
502 batch_size = full_shape(4, tens.shape, 1)[0]
503 if batch_size != 1:
504 valid = False
505 extra.append(f"Tensor '{tens.name}' has batch size: {batch_size}")
506 extra = "\n ".join(extra)
507 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200508
509 @staticmethod
510 def constraint_depth_multiplier(op):
511 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
512 depth_multiplier = op.attrs.get("depth_multiplier", 1)
513 if depth_multiplier > 1:
514 ifm_channels = op.ifm.shape[3]
515 ofm_channels = op.ofm.shape[3]
516 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
517 extra = (
518 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
519 f" and depth_multiplier={depth_multiplier}"
520 )
521 return valid, extra
522 return True, "Op has depth_multiplier=1"
523
524 @staticmethod
525 def constraint_tconv_stride(op):
526 "Stride values for both width and height must be 2"
527 w = op.kernel.stride.x
528 h = op.kernel.stride.y
529 valid = (w == 2) and (h == 2)
530 return valid, f"Op has stride WxH as: {w}x{h}"
531
532 @staticmethod
533 def constraint_tconv_same(op):
534 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
535 if op.attrs["padding"] == Padding.SAME:
536 w = op.kernel.stride.x
537 h = op.kernel.stride.y
538 ifm_shape = op.ifm.shape
539 ofm_shape = op.ofm.shape
540 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
541 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
542 return True, "Op has padding=VALID"
543
544 @staticmethod
545 def constraint_tconv_valid(op):
546 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200547 minus difference between kernel size and stride"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200548 if op.attrs["padding"] == Padding.VALID:
549 s_w = op.kernel.stride.x
550 s_h = op.kernel.stride.y
551 k_w = op.kernel.width
552 k_h = op.kernel.height
553 ifm_shape = op.ifm.shape
554 ofm_shape = op.ofm.shape
555 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
556 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
557 valid = height_check and width_check
558 extra = (
559 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
560 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
561 )
562 return valid, extra
563 return True, "Op has padding=SAME"
564
565 @classmethod
566 @docstring_format_args(filter_range)
567 def constraint_filter_range(cls, op):
568 "Kernel filter values for both width and height must be in the range [{}, {}]"
569 if op.attrs["padding"] == Padding.SAME:
570 w = op.kernel.width
571 h = op.kernel.height
572 filter_min, filter_max = cls.filter_range
573 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
574 return valid, f"Op has kernel filter WxH as: {w}x{h}"
575 return True, "Op has padding=VALID"
576
577 @classmethod
578 @docstring_format_args(filter_height_range)
579 def constraint_filter_height_range(cls, op):
580 "Kernel filter height must be in the range [{}, {}]"
581 h = op.kernel.height
582 filter_height_min, filter_height_max = cls.filter_height_range
583 valid = filter_height_min <= h <= filter_height_max
584 return valid, f"Op has kernel filter height as: {h}"
585
586 @classmethod
587 @docstring_format_args(filter_product_range)
588 def constraint_filter_product_range(cls, op):
589 "Product of kernel filter width and height must be in the range [{}, {}]"
590 product = op.kernel.elements_wh()
591 filter_product_min, filter_product_max = cls.filter_product_range
592 valid = filter_product_min <= product <= filter_product_max
593 return valid, f"Op has product of kernel filter width and height as: {product}"
594
595 @staticmethod
596 @docstring_format_args(filter_height_range)
597 def constraint_filter_height_range_valid_pad(op):
598 "VALID padding: Kernel filter height must be in the range [{}, {}]"
599 if op.attrs["padding"] == Padding.VALID:
600 return TFLiteSupportedOperators.constraint_filter_height_range(op)
601 return True, "Op has padding=SAME"
602
603 @staticmethod
604 @docstring_format_args(filter_product_range)
605 def constraint_filter_product_range_valid_pad(op):
606 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
607 if op.attrs["padding"] == Padding.VALID:
608 return TFLiteSupportedOperators.constraint_filter_product_range(op)
609 return True, "Op has padding=SAME"
610
611 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100612 def constraint_resize(op):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200613 """The width and height of the IFM and OFM must match one of the following criteria:
614 IFM W and H must both be 1
615 IFM must match OFM
Rickard Bolinfea15162022-07-04 16:19:16 +0000616 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
617 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 +0200618 # Easier to start with False condition as very few cases result in a supported resize
619 valid = False
620 ifm_shape = op.ifm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100621 ifm_shape_h = ifm_shape[1]
622 ifm_shape_w = ifm_shape[2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200623 ofm_shape = op.ofm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100624 ofm_shape_h = ofm_shape[1]
625 ofm_shape_w = ofm_shape[2]
626
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200627 align_corners = op.attrs.get("align_corners", False)
628 if len(ifm_shape) == 4:
629 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
Tim Hall47c76362022-07-18 21:26:47 +0100630 if ((ifm_shape_h == 1) and (ifm_shape_w == 1)) or (ifm_shape == ofm_shape):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200631 valid = True
632 else:
Rickard Boline546def2022-01-25 15:45:00 +0000633 # Valid if OFM is 2/4/8x IFM (-1 for align corners)
Tim Hall47c76362022-07-18 21:26:47 +0100634 if align_corners:
635 h_upscale_factor = (ofm_shape_h - 1) / (ifm_shape_h - 1)
636 w_upscale_factor = (ofm_shape_w - 1) / (ifm_shape_w - 1)
637 else:
638 h_upscale_factor = ofm_shape_h / ifm_shape_h
639 w_upscale_factor = ofm_shape_w / ifm_shape_w
Rickard Boline546def2022-01-25 15:45:00 +0000640
Tim Hall47c76362022-07-18 21:26:47 +0100641 # could use either height or width. save as int because it is more usable later in graph optimiser
642 op.attrs["upscale_factor"] = int(h_upscale_factor)
643 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 +0000644
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200645 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
646
647 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100648 def constraint_resize_size(op):
Tim Hall47c76362022-07-18 21:26:47 +0100649 "The size tensor must match the output tensor shape"
650 valid = False
651 ofm_shape = op.ofm.shape
652 size_h, size_w = None, None
653 # check that the size tensor (the second input) exists, is not none, and has the correct values
654 if len(op.inputs) == 2 and op.inputs[1] is not None and len(op.inputs[1].values) == 2:
655 size_h, size_w = op.inputs[1].values
656 # check size and output size match
657 if size_h == ofm_shape[1] and size_w == ofm_shape[2]:
658 valid = True
659
660 return valid, f"Op has size={size_h}x{size_w} and ofm_shape={ofm_shape}."
661
662 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100663 def constraint_resize_attrs(op):
Tim Hall47c76362022-07-18 21:26:47 +0100664 "Both align_corners and half_pixel_centers can't be True"
665 valid = True
666 align_corners = op.attrs.get("align_corners", False)
667 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
668
669 if align_corners and half_pixel_centers:
670 valid = False
671 return valid, "Op has both align_corners and half_pixel_centers set to True."
672
673 @staticmethod
Rickard Bolinfea15162022-07-04 16:19:16 +0000674 def constraint_resizebi_half_pixel_centers_dims(op):
675 """Half_pixel_centers for resize bilinear requires that OFM W and H is 2x IFM W and H"""
676 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
677 if not half_pixel_centers:
678 valid = True
679 elif len(op.ifm.shape) >= 3:
680 ifm_h, ifm_w = op.ifm.shape[-3:-1]
681 ofm_h, ofm_w = op.ofm.shape[-3:-1]
682 valid = ofm_h / ifm_h == 2 and ofm_w / ifm_w == 2
683 else:
684 # Unexpected IFM shape
685 valid = False
686 return (
687 valid,
688 f"Op has ifm_shape={op.ifm.shape}, ofm_shape={op.ofm.shape} and half_pixel_centers={half_pixel_centers}",
689 )
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200690
691 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200692 def constraint_pad_shape(op):
693 "The padding tensor must have the shape [3,2] or [4,2]"
694 valid = op.inputs[1].shape in ([3, 2], [4, 2])
695 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
696
697 @classmethod
698 @docstring_format_args([list_formatter(supported_pad_dtypes)])
699 def constraint_pad_type(cls, op):
700 "Pad tensor must be of type: {}"
701 pad_tensor = op.inputs[1]
702 valid = pad_tensor.dtype in cls.supported_pad_dtypes
703 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
704
705 @staticmethod
706 def constraint_padding_dimensions(op):
707 "The pad tensor can only pad width and height"
708 pad_tensor = op.inputs[1].values
709
710 valid = sum(pad_tensor[-1, :]) == 0
711 if valid and len(pad_tensor) > 3:
712 valid = sum(pad_tensor[0, :]) == 0
713 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
714
715 @staticmethod
716 def constraint_stridedslice_stride_values(op):
717 "All Strides values must be 1"
718 strides = op.inputs[3]
719 valid = all(stride == 1 for stride in strides.values)
720 return valid, f"Op has strides values {strides.values}"
721
722 @staticmethod
723 def constraint_inputs_int32(op):
724 "Both Input data types must be int32"
725 ifm_dtype = op.ifm.dtype
726 ifm2_dtype = op.ifm2.dtype
727 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
728 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
729
730 @staticmethod
731 def constraint_output_int32(op):
732 "OFM must be int32"
733 ofm_dtype = op.ofm.dtype
734 valid = ofm_dtype == DataType.int32
735 return valid, f"Op has ofm_dtype={ofm_dtype}"
736
737 @staticmethod
738 def constraint_matching_quantization_parameters(op):
739 "Both Input quantization parameters must match OFM quantization parameters"
740 valid = True
741 extra = []
742 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
743 valid = False
744 extra.append(op.ifm.name)
745 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
746 valid = False
747 extra.append(op.ifm2.name)
748 extra = ", ".join(extra)
749 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
750
751 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200752 def constraint_broadcast_shapes(op):
753 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
754 ifm_shape = op.ifm.shape
755 ifm2_shape = op.ifm2.shape if op.ifm2 else None
756 ofm_shape = op.ofm.shape
757 valid = True
758 if ifm_shape is not None and ifm2_shape is not None:
759 # align trailing dimensions
760 size = min(len(ifm_shape), len(ifm2_shape))
761 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
762 mi = max(i, i2)
763 # Input dimensions should match or one should be of dimension 1
764 # Output dimension should match the largest input dimension, together
765 # with constraint_match_either_shapes ensures broadcast from only one input
766 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
767 valid = False
768 break
769
770 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
771
772 @classmethod
773 @docstring_format_args([mean_kernel_product_avgpool])
774 def constraint_mean_height_width_product_avgpool(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000775 """Product of height and width must be no greater than {}"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200776 shape = op.inputs[0].shape
777 hi = 0 if len(shape) < 4 else 1
778 h, w = shape[hi : hi + 2]
779 max_prod = cls.mean_kernel_product_avgpool
780 return h * w <= max_prod, f"Product of height and width is {h * w}"
781
782 @classmethod
783 @docstring_format_args([mean_kernel_product])
784 def constraint_mean_height_width_product(cls, op):
James Peet0bb7ad12022-02-15 15:07:54 +0000785 """Product of height and width must be no greater than {} when:
786 IFM and OFM have different scale or zero point; or
787 'keep_dims' is True"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200788 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
789 keep_dims = op.attrs.get("keep_dims")
790 # doesn't apply, size is checked by constraint_mean_height_width_product_avgpool
791 if not keep_dims and ifmq.scale_f32 == ofmq.scale_f32 and ifmq.zero_point == ofmq.zero_point:
792 return True, ""
793 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
797 return h * w <= max_prod, f"Product of height and width is {h * w}"
798
Johan Alfvén05916632022-09-06 20:33:22 +0200799 @classmethod
James Peet0bb7ad12022-02-15 15:07:54 +0000800 @docstring_format_args([filter_height_range[1], dilated_height_range[1]])
801 def constraint_mean_height_single_axis(cls, op):
802 """For single axis averages across the height dimension:
803 IFM height must be no greater than {} if the IFM and OFM scale and zero point match; otherwise
804 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 +0000805 inp, axis = op.inputs
806 if axis.shape == [] or axis.shape[0] == 1: # single axis
807 axis = int(axis.values) if len(axis.shape) == 0 else int(axis.values[0])
808 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000809 # Multiple axes
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000810 return True, ""
811
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000812 shape = inp.shape
James Peet0bb7ad12022-02-15 15:07:54 +0000813 if len(shape) < 3:
814 # No height dimension present in IFM
815 return True, ""
816 if axis != len(shape) - 3:
817 # Not averaging across the height dimension
818 return True, ""
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000819
James Peet0bb7ad12022-02-15 15:07:54 +0000820 h = shape[axis]
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000821 ifm, ofm = op.get_ifm_ofm()
James Peet0bb7ad12022-02-15 15:07:54 +0000822
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000823 if check_quantized_tens_scaling_equal(ifm, ofm):
James Peet0bb7ad12022-02-15 15:07:54 +0000824 return h <= cls.filter_height_range[1], f"Height is {h}, IFM and OFM quantizations match"
Rickard Bolin7d7cb672021-12-07 09:09:14 +0000825 else:
James Peet0bb7ad12022-02-15 15:07:54 +0000826 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 +0000827
Tim Hall3584a9c2021-11-18 22:05:17 +0000828 @staticmethod
829 def constraint_reshape_shape_constant(op):
830 "Shape must be constant"
831 valid = True
832 extra = []
833
834 reshape_tens = op.inputs[1]
835 if reshape_tens is not None:
836 # constant inputs have either no driving operator or a const one
837 # create a list of non-constant inputs
838 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
839 valid = False
840 extra.append(reshape_tens.name)
841 extra = ", ".join(extra)
842
843 return valid, f"Op has non-const input(s): {extra}"