blob: 723c5f2258b83a0b61f9d9fab2af6c01c01054cd [file] [log] [blame]
Raul Farkas090f18a2023-01-24 16:29:06 +00001# SPDX-FileCopyrightText: Copyright 2020-2023 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
Raul Farkas3b64f062023-05-16 17:18:31 +010032from .utils import calc_resize_factor
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020033
34
35def _optype_formatter(op_list):
36 # Convert internal op types to external names
37 output = map(optype_to_builtintype, op_list)
38 # Remove UNKNOWNs
39 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
40 return list_formatter(output)
41
42
43class TFLiteSupportedOperators:
44 # Categorised lists of supported operators
Fredrik Svedberg11563172022-07-06 14:54:12 +020045 npu_pre_ops = set(
46 (
47 Op.SplitSliceRead,
48 Op.Shape,
49 )
50 )
Jonas Ohlssond8575072022-03-30 10:30:25 +020051 convolution_ops = set(
52 (
53 Op.Conv2DBias,
54 Op.Conv2D,
55 Op.QuantizedConv2D,
56 )
57 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020058 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
59 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
60 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
61 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
62 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
63 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
Tim Hall885033b2022-07-21 11:46:03 +010064 resizing_ops = Op.op_set(Op.is_resize_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020065 fc_vector_products = set(
66 (
67 Op.QuantizedMatMul,
68 Op.MatMul,
69 Op.FullyConnected,
70 )
71 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020072 mac_main_ops = (
Fredrik Svedberg0ac08042023-04-11 22:35:04 +020073 # LSTM
74 set((Op.UnidirectionalSequenceLstm,))
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020075 # conv/depthwiseconv/transposeconv
76 | convolution_like_ops
77 # pooling
78 | pooling_ops
79 # resizing/upscaling
80 | resizing_ops
81 # FC layers
82 | fc_vector_products
83 # Mean (converts to depthwise conv)
84 | set((Op.Mean,))
Rickard Bolin6986a072022-12-19 12:33:40 +000085 # ArgMax (converts to depthwise conv and maxpool)
86 | set((Op.ArgMax,))
Jonas Ohlsson45e653d2021-07-26 16:13:12 +020087 )
88 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
Jonas Ohlssond8575072022-03-30 10:30:25 +020089 binary_elem_wise_min_max_ops = set(
90 (
91 Op.Minimum,
92 Op.Maximum,
93 )
94 )
95 binary_elem_wise_shift_ops = set(
96 (
97 Op.SHL,
98 Op.SHR,
99 )
100 )
101 binary_elem_wise_add_mul_sub = set(
102 (
103 Op.Add,
104 Op.Mul,
105 Op.Sub,
106 )
107 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200108 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
109 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
110 pad_ops = set((Op.Pad,))
111 supported_int32_tensor_ops = (
Rickard Bolin6986a072022-12-19 12:33:40 +0000112 set((Op.ReduceSum, Op.CLZ, Op.Shape, Op.ArgMax)) | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200113 )
114
Jonas Ohlssond8575072022-03-30 10:30:25 +0200115 relu_ops = set(
116 (
117 Op.Relu,
118 Op.Relu6,
119 Op.ReluN1To1,
120 Op.Clip,
121 )
122 )
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200123 activation_ops = relu_ops | set(
124 (
125 Op.Tanh,
126 Op.Sigmoid,
127 Op.Softmax,
128 Op.HardSwish,
Fredrik Svedberg1cd39492022-09-23 15:38:03 +0200129 Op.LeakyRelu,
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200130 Op.Prelu,
131 )
132 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200133 npu_post_ops = (
134 # activation functions
135 activation_ops
136 # concatenation write direction
137 | set((Op.ConcatSliceWrite,))
138 # Quantization
139 | set((Op.Quantize,))
140 )
Jonas Ohlssond8575072022-03-30 10:30:25 +0200141 split_ops = set(
142 (
143 Op.Split,
144 Op.SplitV,
145 Op.StridedSlice,
146 Op.Slice,
147 Op.UnpackReshaped,
148 Op.Unpack,
149 )
150 )
151 concat_ops = set(
152 (
153 Op.Concat,
154 Op.ConcatTFLite,
155 Op.PackReshaped,
156 Op.Pack,
157 )
158 )
159 memory_only_ops = (
160 set(
161 (
162 Op.Reshape,
163 Op.QuantizedReshape,
164 Op.Squeeze,
165 Op.ExpandDims,
166 )
167 )
168 | concat_ops
169 | split_ops
170 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200171 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Jonas Ohlssond8575072022-03-30 10:30:25 +0200172 supported_fused_activations = relu_ops | set(
173 (
174 Op.Tanh,
175 Op.Sigmoid,
176 Op.LUT,
177 )
178 )
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200179 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
180 # Supported data types
181 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
182 supported_faf_dtypes = set((DataType.uint8, DataType.int8, DataType.int16))
183 supported_bias_dtypes = set((DataType.int32, DataType.int64))
184 supported_pad_dtypes = set((DataType.int32, DataType.int64))
185 # Defined ranges for allowed values:
186 tens_dim_range = (1, 65535)
187 stride_range = (1, 3)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200188 dilated_height_range = (1, 64)
189 dilated_product_range = (1, 64 * 64)
190 weights_limit = 127 * 65536
191 filter_range = (1, 8)
192 filter_height_range = (1, 256)
193 filter_product_range = (1, 256 * 256)
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000194 mean_reduced_axis_max_size = 64 * 64
Alexander Hansson90c34b52023-05-31 15:03:03 +0000195 mean_kernel_product_int8 = 2 ** (24)
196 mean_kernel_product_uint8 = 2 ** (23)
197 mean_kernel_product_int16 = 2 ** (16)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200198
199 def __init__(self):
200 # Setup the generic constraints. Note: the order matters
201 self.generic_constraints = []
202 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dtype)
203 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_int32_ops)
204 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_dimension)
205 self.generic_constraints.append(TFLiteSupportedOperators.constraint_tens_quant_per_axis)
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200206 self.generic_constraints.append(TFLiteSupportedOperators.constraint_batch_size)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200207 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf)
208 self.generic_constraints.append(TFLiteSupportedOperators.constraint_faf_type)
209
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200210 # Setup generic constraint exceptions
211 self.generic_constraints_exceptions = defaultdict(list)
Johan Alfvenc1ad80b2023-03-31 10:19:23 +0200212 self.generic_constraints_exceptions[Op.ArgMax].append(TFLiteSupportedOperators.constraint_tens_dtype)
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200213 self.generic_constraints_exceptions[Op.FullyConnected].append(TFLiteSupportedOperators.constraint_batch_size)
214 self.generic_constraints_exceptions[Op.Softmax].append(TFLiteSupportedOperators.constraint_batch_size)
215 self.generic_constraints_exceptions[Op.Reshape].append(TFLiteSupportedOperators.constraint_batch_size)
216 self.generic_constraints_exceptions[Op.Shape].append(TFLiteSupportedOperators.constraint_batch_size)
217 self.generic_constraints_exceptions[Op.Squeeze].append(TFLiteSupportedOperators.constraint_batch_size)
218 for op_type in TFLiteSupportedOperators.split_ops - set((Op.UnpackReshaped,)):
219 self.generic_constraints_exceptions[op_type].append(TFLiteSupportedOperators.constraint_batch_size)
220
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200221 # Setup specific constraints. Note: the order matters
222 self.specific_constraints = defaultdict(list)
223
Raul Farkas090f18a2023-01-24 16:29:06 +0000224 # Conv specific ops:
225 for op_type in TFLiteSupportedOperators.convolution_ops:
Raul Farkas3e7157b2023-05-09 09:09:17 +0100226 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_width_no_upper_limit)
Raul Farkas090f18a2023-01-24 16:29:06 +0000227
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200228 # Conv-like checks:
229 for op_type in TFLiteSupportedOperators.convolution_like_ops:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200230 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_height_range)
231 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_dilated_product_range)
232 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
233 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
234 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_limit)
Johan Alfvénfaa4b782022-12-07 13:56:17 +0100235 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_shape)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200236 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
237 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
Raul Farkas090f18a2023-01-24 16:29:06 +0000238
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:
Raul Farkas090f18a2023-01-24 16:29:06 +0000246 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_depthwise_conv_stride)
Tim Halld3d81b32022-10-18 19:14:04 +0100247 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_depth_multiplier)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200248
249 # Pooling checks:
Raul Farkas3e7157b2023-05-09 09:09:17 +0100250 for op_type in TFLiteSupportedOperators.pooling_ops - TFLiteSupportedOperators.avg_pooling_ops:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200251 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range)
252 # AVG pooling specific checks:
253 for op_type in TFLiteSupportedOperators.avg_pooling_ops:
Raul Farkas3e7157b2023-05-09 09:09:17 +0100254 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_stride_range_no_padding)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200255 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_range)
256 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range_valid_pad)
257 self.specific_constraints[op_type].append(
258 TFLiteSupportedOperators.constraint_filter_product_range_valid_pad
259 )
260 # MAX pooling specific checks:
261 for op_type in TFLiteSupportedOperators.max_pooling_ops:
262 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_height_range)
263 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_filter_product_range)
264
265 # Resizing specific checks:
266 for op_type in TFLiteSupportedOperators.resizing_ops:
Tim Hall885033b2022-07-21 11:46:03 +0100267 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize)
268 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_size)
269 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_resize_attrs)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200270
Rickard Bolinfea15162022-07-04 16:19:16 +0000271 # Resize Bilinear specific checks:
272 self.specific_constraints[Op.ResizeBilinear].append(
273 TFLiteSupportedOperators.constraint_resizebi_half_pixel_centers_dims
274 )
275
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200276 # Vector Product specific checks:
277 for op_type in TFLiteSupportedOperators.fc_vector_products:
278 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_type)
279 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_weights_const)
Johan Alfvénfaa4b782022-12-07 13:56:17 +0100280 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_shape)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200281 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_type)
282 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_bias_40bit)
283
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200284 # Element-wise checks
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200285 # Binary Min/Max specific checks:
286 for op_type in TFLiteSupportedOperators.binary_elem_wise_min_max_ops:
287 self.specific_constraints[op_type].append(
288 TFLiteSupportedOperators.constraint_matching_quantization_parameters
289 )
290 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
291 # Binary Add/Mul/Sub specific checks:
292 for op_type in TFLiteSupportedOperators.binary_elem_wise_add_mul_sub:
293 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
294 # Binary Shift specific checks:
295 for op_type in TFLiteSupportedOperators.binary_elem_wise_shift_ops:
296 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_inputs_int32)
297 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_broadcast_shapes)
298
299 # SHL specific checks:
300 self.specific_constraints[Op.SHL].append(TFLiteSupportedOperators.constraint_output_int32)
301
302 # CLZ specific checks:
303 self.specific_constraints[Op.CLZ].append(TFLiteSupportedOperators.constraint_output_int32)
304
305 # StridedSlice specific checks:
306 self.specific_constraints[Op.StridedSlice].append(
307 TFLiteSupportedOperators.constraint_stridedslice_stride_values
308 )
309
310 # Pad specific checks:
311 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_shape)
312 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_padding_dimensions)
313 self.specific_constraints[Op.Pad].append(TFLiteSupportedOperators.constraint_pad_type)
314
315 # Mean specific checks:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200316 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_height_width_product)
Alexander Hansson90c34b52023-05-31 15:03:03 +0000317 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_width)
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000318 self.specific_constraints[Op.Mean].append(TFLiteSupportedOperators.constraint_mean_depth)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200319
Tim Hall3584a9c2021-11-18 22:05:17 +0000320 # Reshape specific checks:
321 self.specific_constraints[Op.Reshape].append(TFLiteSupportedOperators.constraint_reshape_shape_constant)
322
Rickard Bolin6986a072022-12-19 12:33:40 +0000323 # ArgMax specific checks:
Rickard Bolin6986a072022-12-19 12:33:40 +0000324 self.specific_constraints[Op.ArgMax].append(TFLiteSupportedOperators.constraint_argmax_axis)
325 self.specific_constraints[Op.ArgMax].append(TFLiteSupportedOperators.constraint_argmax_depth)
326
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200327 # UnidirectionalSequenceLstm specific checks:
328 op_type = Op.UnidirectionalSequenceLstm
329 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_lstm_no_cifg)
330 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_lstm_no_peep_hole)
331 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_lstm_no_projection)
332 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_lstm_no_normalisation)
333 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_lstm_weights)
William Isaksson2f9b6872023-07-17 13:03:09 +0000334 self.specific_constraints[op_type].append(TFLiteSupportedOperators.constraint_lstm_weight_dimensions)
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200335
Johan Alfven8e525ca2023-05-07 13:12:37 +0200336 # Rsqrt specific checks
337 self.specific_constraints[Op.Rsqrt].append(TFLiteSupportedOperators.constraint_rsqrt_input_int8)
338
Johan Alfven85b77902023-06-15 09:24:01 +0200339 # Slice specific checks:
340 self.specific_constraints[Op.Slice].append(TFLiteSupportedOperators.constraint_slice_inputs_const)
341
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200342 def is_operator_supported(self, op):
343 ext_type = optype_to_builtintype(op.type)
344 if op.type not in TFLiteSupportedOperators.supported_operators:
345 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
346 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
347 return False
348
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200349 op_exceptions = self.generic_constraints_exceptions[op.type]
350 generic_constraints = [constraint for constraint in self.generic_constraints if constraint not in op_exceptions]
351
352 for constraint in generic_constraints + self.specific_constraints[op.type]:
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200353 valid, extra = constraint(op)
354 if not valid:
355 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
356 print(f" - {constraint.__doc__}")
357 if extra:
358 print(f" {extra}")
359 return False
360
361 return True
362
363 @classmethod
364 @docstring_format_args([list_formatter(supported_op_dtypes)])
365 def constraint_tens_dtype(cls, op):
366 "Tensors must be of type: {}"
367 valid = True
368 extra = []
369 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
370 if not tensors:
371 tensors = [tens for tens in op.inputs if tens]
372 for tens in tensors:
373 if tens.dtype not in cls.supported_op_dtypes:
374 valid = False
375 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
376 return valid, ", ".join(extra)
377
378 @classmethod
379 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
380 def constraint_tens_int32_ops(cls, op):
381 "Tensors which are int32 are only valid when op type is: {}"
382 valid = True
383 extra = []
384 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
385 if not tensors:
386 tensors = [tens for tens in op.inputs if tens]
387 for tens in tensors:
388 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
389 valid = False
390 extra.append(tens.name)
391 extra = ", ".join(extra)
392 return valid, f"Op has int32 tensor(s): {extra}"
393
394 @classmethod
395 @docstring_format_args(tens_dim_range)
396 def constraint_tens_dimension(cls, op):
397 "Tensor dimensions must be in the range [{}, {}]"
398 tens_min, tens_max = cls.tens_dim_range
399 valid = True
400 extra = []
401 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
402 if not tensors:
403 tensors = [tens for tens in op.inputs if tens]
404 for tens in tensors:
405 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
406 valid = False
407 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
408 return valid, ", ".join(extra)
409
410 @classmethod
411 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
412 def constraint_tens_quant_per_axis(cls, op):
413 "Per-axis quantization is only supported for the following op types: {}"
414 valid = True
415 extra = []
416 if op.type not in cls.per_axis_quant_ops:
417 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
418 for tens in tensors:
Fredrik Svedberg11563172022-07-06 14:54:12 +0200419 if tens.quantization and tens.quantization.is_per_axis():
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200420 valid = False
421 extra.append(tens.name)
422 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
423
424 @classmethod
425 @docstring_format_args([_optype_formatter(supported_fused_activations)])
426 def constraint_faf(cls, op):
427 "The fused activation function (if present) must be one of type: {}"
428 if op.activation is None:
429 res = True, "Op has no fused activation function"
430 else:
431 faf = op.activation.op_type
432 valid = faf in cls.supported_fused_activations
433 res = valid, f"Op has its fused activation function as: {faf}"
434 return res
435
436 @classmethod
437 @docstring_format_args([list_formatter(supported_faf_dtypes)])
438 def constraint_faf_type(cls, op):
439 "If a fused activation function is present, the Output tensor must be one of type: {}"
440 if op.activation is None:
441 res = True, "Op has no fused activation function"
442 else:
443 valid = op.ofm.dtype in cls.supported_faf_dtypes
444 ext_type = optype_to_builtintype(op.activation.op_type)
445 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
446 return res
447
448 @classmethod
449 @docstring_format_args(stride_range)
450 def constraint_stride_range(cls, op):
451 "Stride values for both width and height must be in the range [{}, {}]"
452 w, h = op.get_kernel_stride()
453 stride_min, stride_max = cls.stride_range
454 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
455 return valid, f"Op has stride WxH as: {w}x{h}"
456
457 @classmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200458 @docstring_format_args(dilated_height_range)
459 def constraint_dilated_height_range(cls, op):
460 "Dilated kernel height must be in the range [{}, {}]"
461 h = op.kernel.area_height()
462 dilated_height_min, dilated_height_max = cls.dilated_height_range
463 valid = dilated_height_min <= h <= dilated_height_max
464 return valid, f"Op has dilated kernel height as: {h}"
465
466 @classmethod
467 @docstring_format_args(dilated_product_range)
468 def constraint_dilated_product_range(cls, op):
469 "Product of dilated kernel width and height must be in the range [{}, {}]"
470 product = op.kernel.area_width() * op.kernel.area_height()
471 dilated_product_min, dilated_product_max = cls.dilated_product_range
472 valid = dilated_product_min <= product <= dilated_product_max
473 return valid, f"Op has product of dilated kernel width and height as: {product}"
474
475 @staticmethod
476 def constraint_weights_type(op):
477 "Weight tensor must be 8-bit"
478 weights = op.weights
479 valid = weights.element_size() == 1
480 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
481
482 @staticmethod
483 def constraint_weights_const(op):
484 "Weight tensor must be constant"
485 weights = op.weights
486 valid = weights.values is not None
487 return valid, f"Tensor '{weights.name}' has non-constant values"
488
489 @classmethod
490 @docstring_format_args([weights_limit])
491 def constraint_weights_limit(cls, op):
492 "The sum of the weights cannot exceed {}"
493 weights = op.weights
494 values = weights.values.astype(np.int64) - weights.quantization.zero_point
495 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
496 valid = limit <= cls.weights_limit
497 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
498
Johan Alfvénfaa4b782022-12-07 13:56:17 +0100499 @staticmethod
500 def constraint_bias_shape(op):
501 "Optional Bias tensor must be of shape: 1D"
502 bias = op.bias
503 if bias:
504 valid = len(bias.shape) == 1
505 return valid, f"Tensor '{bias.name}' has shape: {bias.shape}"
506 return True, "Op has no bias tensor"
507
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200508 @classmethod
509 @docstring_format_args([list_formatter(supported_bias_dtypes)])
510 def constraint_bias_type(cls, op):
511 "Optional Bias tensor must be of type: {}"
512 bias = op.bias
513 if bias:
514 valid = bias.dtype in cls.supported_bias_dtypes
515 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
516 return True, "Op has no bias tensor"
517
518 @staticmethod
519 def constraint_bias_40bit(op):
520 "Optional Bias tensor values must fit within 40-bits"
521 bias = op.bias
522 if bias and bias.dtype == DataType.int64 and bias.values is not None:
Tim Hall8ae29292021-07-28 16:52:03 +0100523 valid = all(len(bin(value)[2:]) <= 40 for value in bias.values)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200524 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
525 return True, "Op has no bias tensor, or it fits in 40-bit"
526
527 @staticmethod
528 def constraint_batch_size(op):
529 "IFM Tensor batch size must be 1"
Fredrik Svedberg88d5b122022-09-16 16:24:55 +0200530 valid = True
531 extra = []
532 for tens in (op.ifm, op.ifm2):
533 if tens is not None:
534 batch_size = full_shape(4, tens.shape, 1)[0]
535 if batch_size != 1:
536 valid = False
537 extra.append(f"Tensor '{tens.name}' has batch size: {batch_size}")
538 extra = "\n ".join(extra)
539 return valid, extra
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200540
541 @staticmethod
542 def constraint_depth_multiplier(op):
543 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
544 depth_multiplier = op.attrs.get("depth_multiplier", 1)
545 if depth_multiplier > 1:
546 ifm_channels = op.ifm.shape[3]
547 ofm_channels = op.ofm.shape[3]
548 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
549 extra = (
550 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
551 f" and depth_multiplier={depth_multiplier}"
552 )
553 return valid, extra
554 return True, "Op has depth_multiplier=1"
555
556 @staticmethod
Raul Farkas3e7157b2023-05-09 09:09:17 +0100557 def constraint_stride_width_no_upper_limit(op):
Raul Farkas3b64f062023-05-16 17:18:31 +0100558 """Stride width must be greater than or equal to 1.
559 For stride widths greater than 3, the post-optimization stride needs to be less than or equal to 3.
560 Stride height must be between 1 and 3."""
Raul Farkas090f18a2023-01-24 16:29:06 +0000561 w, h = op.get_kernel_stride()
Raul Farkas10d6b3b2023-01-30 12:58:46 +0000562 stride_min = 1
Raul Farkas59b9ab92023-02-09 10:03:27 +0000563 stride_max_h = 3
Raul Farkas3b64f062023-05-16 17:18:31 +0100564 ifm_width = op.ifm.shape[2]
565 _, optimized_stride = calc_resize_factor(ifm_width, w) if w > 1 else (1, w)
566 # Optimized stride indicates the final Conv2D stride width after all optimizations are performed
567 can_optimize_stride_width_gt_3 = optimized_stride <= 3
568 valid = (stride_min <= w) and (stride_min <= h <= stride_max_h) and can_optimize_stride_width_gt_3
569
Raul Farkas090f18a2023-01-24 16:29:06 +0000570 return valid, f"Op has stride WxH as: {w}x{h}"
571
572 @staticmethod
Raul Farkas3e7157b2023-05-09 09:09:17 +0100573 def constraint_stride_range_no_padding(op):
574 """Stride width must be greater than or equal to 1.
575 For stride width greater than 3, valid padding needs to be used."""
576 w, _ = op.get_kernel_stride()
577 valid, message = TFLiteSupportedOperators.constraint_stride_width_no_upper_limit(op)
578 padding = op.attrs.get("padding", None)
579 is_optimized_with_valid_padding = padding in (None, Padding.VALID) or w <= 3
580 valid = valid and is_optimized_with_valid_padding
581 return valid, f"{message}, padding: {padding}"
582
583 @staticmethod
Raul Farkas090f18a2023-01-24 16:29:06 +0000584 def constraint_depthwise_conv_stride(op):
585 "Stride values for both width and height must be between 1 and 3"
586 w, h = op.get_kernel_stride()
587 stride_min, stride_max = 1, 3
588 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
589 return valid, f"Op has stride WxH as: {w}x{h}"
590
591 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200592 def constraint_tconv_stride(op):
593 "Stride values for both width and height must be 2"
594 w = op.kernel.stride.x
595 h = op.kernel.stride.y
596 valid = (w == 2) and (h == 2)
597 return valid, f"Op has stride WxH as: {w}x{h}"
598
599 @staticmethod
600 def constraint_tconv_same(op):
601 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
602 if op.attrs["padding"] == Padding.SAME:
603 w = op.kernel.stride.x
604 h = op.kernel.stride.y
605 ifm_shape = op.ifm.shape
606 ofm_shape = op.ofm.shape
607 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
608 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
609 return True, "Op has padding=VALID"
610
611 @staticmethod
612 def constraint_tconv_valid(op):
613 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
Jonas Ohlssond8575072022-03-30 10:30:25 +0200614 minus difference between kernel size and stride"""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200615 if op.attrs["padding"] == Padding.VALID:
616 s_w = op.kernel.stride.x
617 s_h = op.kernel.stride.y
618 k_w = op.kernel.width
619 k_h = op.kernel.height
620 ifm_shape = op.ifm.shape
621 ofm_shape = op.ofm.shape
622 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
623 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
624 valid = height_check and width_check
625 extra = (
626 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
627 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
628 )
629 return valid, extra
630 return True, "Op has padding=SAME"
631
632 @classmethod
633 @docstring_format_args(filter_range)
634 def constraint_filter_range(cls, op):
635 "Kernel filter values for both width and height must be in the range [{}, {}]"
636 if op.attrs["padding"] == Padding.SAME:
Raul Farkas3e7157b2023-05-09 09:09:17 +0100637 sw, _ = op.get_kernel_stride()
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200638 w = op.kernel.width
639 h = op.kernel.height
640 filter_min, filter_max = cls.filter_range
Raul Farkas3e7157b2023-05-09 09:09:17 +0100641 valid = ((filter_min <= w <= filter_max) or sw == w) and (filter_min <= h <= filter_max)
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200642 return valid, f"Op has kernel filter WxH as: {w}x{h}"
643 return True, "Op has padding=VALID"
644
645 @classmethod
646 @docstring_format_args(filter_height_range)
647 def constraint_filter_height_range(cls, op):
648 "Kernel filter height must be in the range [{}, {}]"
649 h = op.kernel.height
650 filter_height_min, filter_height_max = cls.filter_height_range
651 valid = filter_height_min <= h <= filter_height_max
652 return valid, f"Op has kernel filter height as: {h}"
653
654 @classmethod
655 @docstring_format_args(filter_product_range)
656 def constraint_filter_product_range(cls, op):
657 "Product of kernel filter width and height must be in the range [{}, {}]"
658 product = op.kernel.elements_wh()
659 filter_product_min, filter_product_max = cls.filter_product_range
660 valid = filter_product_min <= product <= filter_product_max
661 return valid, f"Op has product of kernel filter width and height as: {product}"
662
663 @staticmethod
664 @docstring_format_args(filter_height_range)
665 def constraint_filter_height_range_valid_pad(op):
666 "VALID padding: Kernel filter height must be in the range [{}, {}]"
667 if op.attrs["padding"] == Padding.VALID:
668 return TFLiteSupportedOperators.constraint_filter_height_range(op)
669 return True, "Op has padding=SAME"
670
671 @staticmethod
672 @docstring_format_args(filter_product_range)
673 def constraint_filter_product_range_valid_pad(op):
674 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
675 if op.attrs["padding"] == Padding.VALID:
676 return TFLiteSupportedOperators.constraint_filter_product_range(op)
677 return True, "Op has padding=SAME"
678
679 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100680 def constraint_resize(op):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200681 """The width and height of the IFM and OFM must match one of the following criteria:
682 IFM W and H must both be 1
683 IFM must match OFM
Rickard Bolinfea15162022-07-04 16:19:16 +0000684 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
685 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 +0200686 # Easier to start with False condition as very few cases result in a supported resize
687 valid = False
688 ifm_shape = op.ifm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100689 ifm_shape_h = ifm_shape[1]
690 ifm_shape_w = ifm_shape[2]
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200691 ofm_shape = op.ofm.shape
Tim Hall47c76362022-07-18 21:26:47 +0100692 ofm_shape_h = ofm_shape[1]
693 ofm_shape_w = ofm_shape[2]
694
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200695 align_corners = op.attrs.get("align_corners", False)
696 if len(ifm_shape) == 4:
697 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
Tim Hall47c76362022-07-18 21:26:47 +0100698 if ((ifm_shape_h == 1) and (ifm_shape_w == 1)) or (ifm_shape == ofm_shape):
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200699 valid = True
700 else:
Rickard Boline546def2022-01-25 15:45:00 +0000701 # Valid if OFM is 2/4/8x IFM (-1 for align corners)
Tim Hall47c76362022-07-18 21:26:47 +0100702 if align_corners:
703 h_upscale_factor = (ofm_shape_h - 1) / (ifm_shape_h - 1)
704 w_upscale_factor = (ofm_shape_w - 1) / (ifm_shape_w - 1)
705 else:
706 h_upscale_factor = ofm_shape_h / ifm_shape_h
707 w_upscale_factor = ofm_shape_w / ifm_shape_w
Rickard Boline546def2022-01-25 15:45:00 +0000708
Tim Hall47c76362022-07-18 21:26:47 +0100709 # could use either height or width. save as int because it is more usable later in graph optimiser
710 op.attrs["upscale_factor"] = int(h_upscale_factor)
711 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 +0000712
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200713 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
714
715 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100716 def constraint_resize_size(op):
Tim Hall47c76362022-07-18 21:26:47 +0100717 "The size tensor must match the output tensor shape"
718 valid = False
719 ofm_shape = op.ofm.shape
720 size_h, size_w = None, None
721 # check that the size tensor (the second input) exists, is not none, and has the correct values
722 if len(op.inputs) == 2 and op.inputs[1] is not None and len(op.inputs[1].values) == 2:
723 size_h, size_w = op.inputs[1].values
724 # check size and output size match
725 if size_h == ofm_shape[1] and size_w == ofm_shape[2]:
726 valid = True
727
728 return valid, f"Op has size={size_h}x{size_w} and ofm_shape={ofm_shape}."
729
730 @staticmethod
Tim Hall885033b2022-07-21 11:46:03 +0100731 def constraint_resize_attrs(op):
Tim Hall47c76362022-07-18 21:26:47 +0100732 "Both align_corners and half_pixel_centers can't be True"
733 valid = True
734 align_corners = op.attrs.get("align_corners", False)
735 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
736
737 if align_corners and half_pixel_centers:
738 valid = False
739 return valid, "Op has both align_corners and half_pixel_centers set to True."
740
741 @staticmethod
Rickard Bolinfea15162022-07-04 16:19:16 +0000742 def constraint_resizebi_half_pixel_centers_dims(op):
Tim Hallfd271112023-05-17 13:19:12 +0100743 """For half_pixel_centers the width and height of the IFM and OFM must match one of the following criteria:
Alexander Hanssone8fc2142023-05-11 16:01:39 +0000744 IFM W and H are both 1
745 OFM W and H is 2x IFM W and H"""
Rickard Bolinfea15162022-07-04 16:19:16 +0000746 half_pixel_centers = op.attrs.get("half_pixel_centers", False)
747 if not half_pixel_centers:
748 valid = True
749 elif len(op.ifm.shape) >= 3:
750 ifm_h, ifm_w = op.ifm.shape[-3:-1]
751 ofm_h, ofm_w = op.ofm.shape[-3:-1]
Alexander Hanssone8fc2142023-05-11 16:01:39 +0000752 if ifm_h == 1 and ifm_w == 1:
753 valid = True
754 else:
755 valid = ofm_h / ifm_h == 2 and ofm_w / ifm_w == 2
Rickard Bolinfea15162022-07-04 16:19:16 +0000756 else:
757 # Unexpected IFM shape
758 valid = False
759 return (
760 valid,
761 f"Op has ifm_shape={op.ifm.shape}, ofm_shape={op.ofm.shape} and half_pixel_centers={half_pixel_centers}",
762 )
erik.andersson@arm.comba2555e2021-10-28 14:08:52 +0200763
764 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200765 def constraint_pad_shape(op):
766 "The padding tensor must have the shape [3,2] or [4,2]"
767 valid = op.inputs[1].shape in ([3, 2], [4, 2])
768 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
769
770 @classmethod
771 @docstring_format_args([list_formatter(supported_pad_dtypes)])
772 def constraint_pad_type(cls, op):
773 "Pad tensor must be of type: {}"
774 pad_tensor = op.inputs[1]
775 valid = pad_tensor.dtype in cls.supported_pad_dtypes
776 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
777
778 @staticmethod
779 def constraint_padding_dimensions(op):
780 "The pad tensor can only pad width and height"
781 pad_tensor = op.inputs[1].values
782
783 valid = sum(pad_tensor[-1, :]) == 0
784 if valid and len(pad_tensor) > 3:
785 valid = sum(pad_tensor[0, :]) == 0
786 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
787
788 @staticmethod
789 def constraint_stridedslice_stride_values(op):
790 "All Strides values must be 1"
791 strides = op.inputs[3]
792 valid = all(stride == 1 for stride in strides.values)
793 return valid, f"Op has strides values {strides.values}"
794
795 @staticmethod
796 def constraint_inputs_int32(op):
797 "Both Input data types must be int32"
798 ifm_dtype = op.ifm.dtype
799 ifm2_dtype = op.ifm2.dtype
800 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
801 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
802
803 @staticmethod
804 def constraint_output_int32(op):
805 "OFM must be int32"
806 ofm_dtype = op.ofm.dtype
807 valid = ofm_dtype == DataType.int32
808 return valid, f"Op has ofm_dtype={ofm_dtype}"
809
810 @staticmethod
811 def constraint_matching_quantization_parameters(op):
812 "Both Input quantization parameters must match OFM quantization parameters"
813 valid = True
814 extra = []
815 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
816 valid = False
817 extra.append(op.ifm.name)
818 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
819 valid = False
820 extra.append(op.ifm2.name)
821 extra = ", ".join(extra)
822 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
823
824 @staticmethod
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200825 def constraint_broadcast_shapes(op):
826 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
827 ifm_shape = op.ifm.shape
828 ifm2_shape = op.ifm2.shape if op.ifm2 else None
829 ofm_shape = op.ofm.shape
830 valid = True
831 if ifm_shape is not None and ifm2_shape is not None:
832 # align trailing dimensions
833 size = min(len(ifm_shape), len(ifm2_shape))
834 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
835 mi = max(i, i2)
836 # Input dimensions should match or one should be of dimension 1
837 # Output dimension should match the largest input dimension, together
838 # with constraint_match_either_shapes ensures broadcast from only one input
839 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
840 valid = False
841 break
842
843 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
844
845 @classmethod
Alexander Hansson90c34b52023-05-31 15:03:03 +0000846 @docstring_format_args([mean_kernel_product_int8, mean_kernel_product_uint8, mean_kernel_product_int16])
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200847 def constraint_mean_height_width_product(cls, op):
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000848 """Product of reduced axes must be no greater than:
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000849 - {} for signed 8-bit inputs.
850 - {} for unsigned 8-bit inputs.
851 - {} for signed 16-bit inputs."""
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200852 shape = op.inputs[0].shape
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000853 if op.inputs[1].shape == []:
854 axis = [int(op.inputs[1].values)]
855 else:
856 axis = list(op.inputs[1].values)
857
858 # compute the product of the shape of all reduced axes
859 axis_shapes = [shape[ax] for ax in axis]
860 prod = np.prod(axis_shapes)
861
Alexander Hansson90c34b52023-05-31 15:03:03 +0000862 if op.ifm.dtype == DataType.int16:
863 max_prod = cls.mean_kernel_product_int16
864 datatype = "int16"
865 elif op.ifm.dtype == DataType.uint8:
866 max_prod = cls.mean_kernel_product_uint8
867 datatype = "uint8"
868 else:
869 max_prod = cls.mean_kernel_product_int8
870 datatype = "int8"
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000871 return prod <= max_prod, f"Datatype is {datatype}, product of axes is {prod}"
Alexander Hansson90c34b52023-05-31 15:03:03 +0000872
873 @classmethod
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000874 @docstring_format_args([mean_reduced_axis_max_size])
Alexander Hansson90c34b52023-05-31 15:03:03 +0000875 def constraint_mean_width(cls, op):
Alexander Hansson1d5e8592023-06-27 12:36:25 +0000876 """If Width axis is reduced its shape must be no greater than {}."""
Alexander Hansson90c34b52023-05-31 15:03:03 +0000877 shape = op.inputs[0].shape
878 hi = 0 if len(shape) < 4 else 1
879 h, w = shape[hi : hi + 2]
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000880 max_width = cls.mean_reduced_axis_max_size
Alexander Hansson90c34b52023-05-31 15:03:03 +0000881 return w <= max_width, f"Width is {w}"
Jonas Ohlsson45e653d2021-07-26 16:13:12 +0200882
Alexander Hanssonda8741a2023-06-30 15:41:13 +0000883 @classmethod
884 @docstring_format_args([mean_reduced_axis_max_size])
885 def constraint_mean_depth(cls, op):
886 """If Depth axis is reduced its shape must be no greater than {}."""
887 max_depth = cls.mean_reduced_axis_max_size
888 shape = op.inputs[0].shape
889
890 if op.inputs[1].shape == []:
891 axis = [int(op.inputs[1].values)]
892 else:
893 axis = list(op.inputs[1].values)
894
895 depth_idx = len(shape) - 1
896
897 supported = True
898 if depth_idx in axis and shape[-1] > max_depth:
899 supported = False
900
901 return supported, f"Depth is {shape[-1]}, shape is {shape}, axis is {axis}"
902
Tim Hall3584a9c2021-11-18 22:05:17 +0000903 @staticmethod
904 def constraint_reshape_shape_constant(op):
905 "Shape must be constant"
906 valid = True
907 extra = []
908
Tim Hall2180a172023-03-10 18:11:34 +0000909 # if a reshape tensor is specified then it must be constant
910 if len(op.inputs) > 1:
911 reshape_tens = op.inputs[1]
912 if reshape_tens is not None:
913 # constant inputs have either no driving operator or a const one
914 # create a list of non-constant inputs
915 if not (len(reshape_tens.ops) == 0 or reshape_tens.ops[0].type == Op.Const):
916 valid = False
917 extra.append(reshape_tens.name)
Tim Hall3584a9c2021-11-18 22:05:17 +0000918 extra = ", ".join(extra)
919
920 return valid, f"Op has non-const input(s): {extra}"
Rickard Bolin6986a072022-12-19 12:33:40 +0000921
922 @staticmethod
923 def constraint_argmax_axis(op):
924 "Operation must be performed along the depth axis"
925 inp_dims = len(op.inputs[0].shape)
926 axis = op.inputs[1].values
927 return (
Johan Alfven56811e62023-03-27 11:33:50 +0200928 axis in (inp_dims - 1, -1),
Rickard Bolin6986a072022-12-19 12:33:40 +0000929 f"Axis is {axis} and number of input dimensions is {inp_dims}",
930 )
931
932 @staticmethod
Rickard Bolin6986a072022-12-19 12:33:40 +0000933 def constraint_argmax_depth(op):
934 "IFM depth must be no greater than 127"
935 ifm_depth = op.inputs[0].shape[-1]
936 return ifm_depth <= 127, f"IFM depth is {ifm_depth}"
Fredrik Svedberg0ac08042023-04-11 22:35:04 +0200937
938 @staticmethod
939 def constraint_lstm_no_cifg(op):
940 "Must not use CIFG"
941 cifg = None not in op.inputs[2:5] + op.inputs[6:9]
942 cifg = cifg and op.inputs[1] is None
943 cifg = cifg and op.inputs[5] is None
944 return not cifg, "Op uses CIFG"
945
946 @staticmethod
947 def constraint_lstm_no_peep_hole(op):
948 "Must not use Peephole"
949 valid = all([tens is None for tens in op.inputs[9:12]])
950 return valid, "Op uses peephole"
951
952 @staticmethod
953 def constraint_lstm_no_projection(op):
954 "Must not use Projection"
955 valid = all([tens is None for tens in op.inputs[16:18]])
956 return valid, "Op uses projection"
957
958 @staticmethod
959 def constraint_lstm_no_normalisation(op):
960 "Must not use Normalisation"
961 valid = all([tens is None for tens in op.inputs[20:24]])
962 return valid, "Op uses normalisation"
963
964 @staticmethod
965 def constraint_lstm_weights(op):
966 "All input and recurrent weights must be available"
967 valid = None not in op.inputs[1:9]
968 return valid, "Op has missing weights"
Johan Alfven8e525ca2023-05-07 13:12:37 +0200969
970 @staticmethod
William Isaksson2f9b6872023-07-17 13:03:09 +0000971 def constraint_lstm_weight_dimensions(op):
972 "All recurrent weights must be 2D"
973 valid = all([len(input.shape) == 2 for input in op.inputs[5:9]])
974 return valid, "Op recurrent weights are not 2D"
975
976 @staticmethod
Johan Alfven8e525ca2023-05-07 13:12:37 +0200977 def constraint_rsqrt_input_int8(op):
978 "IFM must be int8"
979 ifm_dtype = op.ifm.dtype
980 valid = ifm_dtype == DataType.int8
981 return valid, f"Op has ifm_dtype={ifm_dtype}"
Johan Alfven85b77902023-06-15 09:24:01 +0200982
983 @staticmethod
984 def constraint_slice_inputs_const(op):
985 "Begin and Size Input tensors must be constant"
986 valid = True
987 extra = []
988 _, begin, sizes = op.inputs
989 if begin.values is None:
990 valid = False
991 extra.append(f"Begin tensor '{begin.name}'")
992 if sizes.values is None:
993 valid = False
994 extra.append(f"Size tensor '{sizes.name}'")
995 extra = ", ".join(extra)
996 return valid, f"Op has non-constant tensors: {extra}"