blob: 231970694cc95cc72d8ca76516e9e8abbe15f0b6 [file] [log] [blame]
Louis Verhaardebf4af62021-01-27 15:57:57 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# The SupportedOperators class which is a collection of all supported operators and parameter checks.
Michael McGeagh1f951fc2020-10-14 09:30:02 +010018from collections import defaultdict
19
Charles Xu87c13502020-08-06 12:17:26 +020020import numpy as np
21
Tim Hallc30f4952020-06-15 20:47:35 +010022from .data_type import BaseType
23from .data_type import DataType
Dwight Lidman8359a472020-09-28 15:53:40 +020024from .numeric_util import is_integer
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020025from .operation import get_slice_offsets
Louis Verhaardaee5d752020-09-30 09:01:52 +020026from .operation import Op
Michael McGeagh16895482020-12-14 15:51:20 +000027from .operation import Padding
Tim Hall93582962020-09-09 21:58:15 +010028from .tensor import check_quantized_tens_scaling_equal
Michael McGeagh837dc1b2020-11-10 12:38:25 +000029from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
Michael McGeagh219ec072020-11-09 11:11:26 +000030from .tflite_mapping import optype_to_builtintype
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020031
32
Michael McGeagh37ded342020-10-01 15:37:44 +010033# Custom decorator function to allow formatting docstrings containing "{}"
34def docstring_format_args(args):
35 def docstring(func):
36 func.__doc__ = func.__doc__.format(*args)
37 return func
38
39 return docstring
40
41
Michael McGeagh34d29172020-11-25 12:36:23 +000042def _list_formatter(arg):
43 # Order and join into a string representation
44 return ", ".join(sorted(map(str, arg)))
45
46
Michael McGeagh837dc1b2020-11-10 12:38:25 +000047def _optype_formatter(op_list):
48 # Convert internal op types to external names
49 output = map(optype_to_builtintype, op_list)
50 # Remove UNKNOWNs
51 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
Michael McGeagh34d29172020-11-25 12:36:23 +000052 return _list_formatter(output)
Michael McGeagh837dc1b2020-11-10 12:38:25 +000053
54
Tim Hall79d07d22020-04-27 18:20:16 +010055class SupportedOperators:
Michael McGeagh1eeea512020-09-30 14:23:09 +010056 # Categorised lists of supported operators
Louis Verhaardaee5d752020-09-30 09:01:52 +020057 npu_pre_ops = set((Op.SplitSliceRead,))
58 convolution_ops = set((Op.Conv2DBias, Op.Conv2D, Op.QuantizedConv2D,))
59 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
60 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010061 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
Louis Verhaardaee5d752020-09-30 09:01:52 +020062 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
63 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
64 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
65 resizing_ops = set((Op.ResizeBilinear,))
66 fc_vector_products = set((Op.QuantizedMatMul, Op.MatMul, Op.FullyConnected,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010067 mac_main_ops = (
68 # RNN/LSTM/GRU
Louis Verhaardaee5d752020-09-30 09:01:52 +020069 set((Op.BlockLSTM,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010070 # conv/depthwiseconv/transposeconv
71 | convolution_like_ops
Michael McGeagh1eeea512020-09-30 14:23:09 +010072 # pooling
73 | pooling_ops
74 # resizing/upscaling
75 | resizing_ops
76 # FC layers
77 | fc_vector_products
Dwight Lidman4f728c02020-12-17 15:14:45 +010078 # Mean (converts to depthwise conv)
79 | set((Op.Mean,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010080 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020081 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
82 binary_elem_wise_min_max_ops = set((Op.Minimum, Op.Maximum,))
83 binary_elem_wise_shift_ops = set((Op.SHL, Op.SHR,))
84 binary_elem_wise_add_mul_sub = set((Op.Add, Op.Mul, Op.Sub,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010085 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
86 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
Erik Anderssonf27a8b62020-12-10 14:58:23 +010087 pad_ops = set((Op.Pad,))
Michael McGeagh37ded342020-10-01 15:37:44 +010088 supported_int32_tensor_ops = (
Louis Verhaardaee5d752020-09-30 09:01:52 +020089 set((Op.ReduceSum, Op.CLZ,)) | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010090 )
Michael McGeagh65fd9982020-10-20 11:49:28 +010091 relu_ops = Op.op_set(Op.is_relu_op)
Diqing Zhong189f7482021-01-26 12:12:51 +010092 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax, Op.HardSwish))
Michael McGeagh1eeea512020-09-30 14:23:09 +010093 npu_post_ops = (
Michael McGeagh1eeea512020-09-30 14:23:09 +010094 # activation functions
Louis Verhaardaee5d752020-09-30 09:01:52 +020095 activation_ops
96 # concatenation write direction
97 | set((Op.ConcatSliceWrite,))
98 # Quantization
99 | set((Op.Quantize,))
Michael McGeagh1eeea512020-09-30 14:23:09 +0100100 )
Louis Verhaardaee5d752020-09-30 09:01:52 +0200101 split_ops = set((Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack,))
102 concat_ops = set((Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack,))
Louis Verhaard3d22f3c2021-02-03 08:43:54 +0100103 memory_only_ops = set((Op.Reshape, Op.QuantizedReshape,)) | concat_ops | split_ops
Dwight Lidman4f728c02020-12-17 15:14:45 +0100104 shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV, Op.Mean))
Dwight Lidmanc7187432020-11-16 17:40:46 +0100105 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Michael McGeagh65fd9982020-10-20 11:49:28 +0100106 supported_fused_activations = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.LUT,))
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100107 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100108 # Supported data types
109 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
Louis Verhaardc7761512021-02-03 10:22:38 +0100110 supported_faf_dtypes = set((DataType.uint8, DataType.int8, DataType.int16))
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100111 supported_bias_dtypes = set((DataType.int32, DataType.int64))
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100112 supported_pad_dtypes = set((DataType.int32, DataType.int64))
Michael McGeagh37ded342020-10-01 15:37:44 +0100113 # Defined ranges for allowed values:
114 tens_dim_range = (1, 65535)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100115 stride_range = (1, 3)
116 dilation_range = (1, 2)
117 dilated_height_range = (1, 64)
118 dilated_product_range = (1, 64 * 64)
119 weights_limit = 127 * 65536
Michael McGeagh65fd9982020-10-20 11:49:28 +0100120 filter_range = (1, 8)
121 filter_height_range = (1, 256)
122 filter_product_range = (1, 256 * 256)
Dwight Lidman4f728c02020-12-17 15:14:45 +0100123 mean_kernel_product = 64 * 64
124 mean_kernel_product_int8 = 16 * 16
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100125 # Supported consumers
Louis Verhaard1a92f782021-02-09 16:08:26 +0100126 supported_pad_consumers = convolution_ops | depthwise_convolution_ops | pooling_ops
Michael McGeagh1eeea512020-09-30 14:23:09 +0100127
Fredrik Svedberg880e7352020-08-25 11:31:47 +0200128 def __init__(self):
Michael McGeagh184b2502020-10-09 17:19:52 +0100129 # Setup the generic constraints. Note: the order matters
Michael McGeagh37ded342020-10-01 15:37:44 +0100130 self.generic_constraints = []
Michael McGeagh65fd9982020-10-20 11:49:28 +0100131 self.generic_constraints.append(SupportedOperators.constraint_tens_no_dynamic)
Michael McGeagh37ded342020-10-01 15:37:44 +0100132 self.generic_constraints.append(SupportedOperators.constraint_tens_defined_shape)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100133 self.generic_constraints.append(SupportedOperators.constraint_tens_output_scalar)
134 self.generic_constraints.append(SupportedOperators.constraint_tens_input_scalar)
Michael McGeagh37ded342020-10-01 15:37:44 +0100135 self.generic_constraints.append(SupportedOperators.constraint_tens_shape_size)
136 self.generic_constraints.append(SupportedOperators.constraint_tens_dtype)
Michael McGeagh184b2502020-10-09 17:19:52 +0100137 self.generic_constraints.append(SupportedOperators.constraint_tens_int32_ops)
Michael McGeagh37ded342020-10-01 15:37:44 +0100138 self.generic_constraints.append(SupportedOperators.constraint_tens_dimension)
Dwight Lidman8359a472020-09-28 15:53:40 +0200139 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_none_check)
Michael McGeagh184b2502020-10-09 17:19:52 +0100140 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_scale)
Dwight Lidmanc7187432020-11-16 17:40:46 +0100141 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_per_axis)
Michael McGeagh184b2502020-10-09 17:19:52 +0100142 self.generic_constraints.append(SupportedOperators.constraint_faf)
Louis Verhaardc7761512021-02-03 10:22:38 +0100143 self.generic_constraints.append(SupportedOperators.constraint_faf_type)
Louis Verhaard9a0cff12021-01-08 11:17:33 +0100144 self.generic_constraints.append(SupportedOperators.constraint_quant_scale_inf)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100145
Michael McGeagh65fd9982020-10-20 11:49:28 +0100146 # Setup specific constraints. Note: the order matters
147 self.specific_constraints = defaultdict(list)
148
149 # Conv-like checks:
150 for op_type in SupportedOperators.convolution_like_ops:
151 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
152 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
153 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_type)
154 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_range)
155 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_height_range)
156 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_product_range)
157 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
158 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
159 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_limit)
160 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
161 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
162 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
163 # Depthwise Conv specific checks:
164 for op_type in SupportedOperators.depthwise_convolution_ops:
165 self.specific_constraints[op_type].append(SupportedOperators.constraint_depth_multiplier)
166 # Transpose Conv specific checks:
167 for op_type in SupportedOperators.transpose_convolution_ops:
168 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_stride)
169 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_same)
170 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_valid)
171
172 # Pooling checks:
173 for op_type in SupportedOperators.pooling_ops:
174 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
175 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
176 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
177 # AVG pooling specific checks:
178 for op_type in SupportedOperators.avg_pooling_ops:
179 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
180 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
181 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_range)
182 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range_valid_pad)
183 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range_valid_pad)
184 # MAX pooling specific checks:
185 for op_type in SupportedOperators.max_pooling_ops:
186 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
187 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
188 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range)
189 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100190
191 # Resizing specific checks:
192 for op_type in SupportedOperators.resizing_ops:
193 self.specific_constraints[op_type].append(SupportedOperators.constraint_resize)
194
195 # Vector Product specific checks:
196 for op_type in SupportedOperators.fc_vector_products:
197 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
198 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
199 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
200 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
201
202 # Concat specific checks:
203 for op_type in (Op.Concat, Op.ConcatTFLite):
204 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_exists)
205 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_valid)
206 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_dimensionality)
207 self.specific_constraints[op_type].append(SupportedOperators.constraint_valid_dimensions)
208
209 # Element-wise checks:
210 for op_type in SupportedOperators.elem_wise_main_ops:
211 self.specific_constraints[op_type].append(SupportedOperators.constraint_elemwise_batch_size)
212 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_either_shapes)
213 # Unary specific checks:
214 for op_type in SupportedOperators.unary_elem_wise_main_ops:
215 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
216 # Binary Min/Max specific checks:
217 for op_type in SupportedOperators.binary_elem_wise_min_max_ops:
218 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
219 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_quantization_parameters)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100220 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100221 # Binary Add/Mul/Sub specific checks:
222 for op_type in SupportedOperators.binary_elem_wise_add_mul_sub:
223 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_inputs_types)
224 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_signed)
225 self.specific_constraints[op_type].append(SupportedOperators.constraint_unsigned_valid)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100226 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100227 # Binary Shift specific checks:
228 for op_type in SupportedOperators.binary_elem_wise_shift_ops:
229 self.specific_constraints[op_type].append(SupportedOperators.constraint_inputs_int32)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100230 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100231
232 # SHL specific checks:
233 self.specific_constraints[Op.SHL].append(SupportedOperators.constraint_output_int32)
234
235 # CLZ specific checks:
236 self.specific_constraints[Op.CLZ].append(SupportedOperators.constraint_output_int32)
237
238 # Softmax specific checks:
239 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_shapes)
240 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_in_out_types)
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100241 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_beta_value_range)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100242
243 # SplitV specific checks:
244 self.specific_constraints[Op.SplitV].append(SupportedOperators.constraint_splitv_inferred)
245
246 # StridedSlice specific checks:
247 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_input_count)
248 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_inputs_const)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100249 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_stride_values)
250 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_ellipsis_mask)
251 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_axis_masks)
252 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_slice_ranges)
253
254 # LeakyRelu specific checks:
255 self.specific_constraints[Op.LeakyRelu].append(SupportedOperators.constraint_alpha_valid)
Tim Hall79d07d22020-04-27 18:20:16 +0100256
Dwight Lidman0dd21c72020-11-24 13:45:50 +0100257 # FullyConnected specific checks:
258 self.specific_constraints[Op.FullyConnected].append(SupportedOperators.constraint_fc_output_2d)
erik.andersson@arm.com0cbb1662021-02-22 15:47:07 +0100259 self.specific_constraints[Op.FullyConnected].append(SupportedOperators.constraint_keep_dim_ifm_ofm)
Dwight Lidman0dd21c72020-11-24 13:45:50 +0100260
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100261 # Pad specific checks:
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100262 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_input_count)
263 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_shape)
264 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_padding_dimensions)
265 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_type)
266 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_constant)
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100267
Diqing Zhong189f7482021-01-26 12:12:51 +0100268 # HardSwish specific checks:
269 self.specific_constraints[Op.HardSwish].append(SupportedOperators.constraint_input_8bit)
270 self.specific_constraints[Op.HardSwish].append(SupportedOperators.constraint_matching_in_out_types)
Dwight Lidman4f728c02020-12-17 15:14:45 +0100271 # Mean specific checks:
272 self.specific_constraints[Op.Mean].append(SupportedOperators.constraint_input_8bit)
273 self.specific_constraints[Op.Mean].append(SupportedOperators.constraint_mean_properties)
274 self.specific_constraints[Op.Mean].append(SupportedOperators.constraint_mean_input_dims)
275 self.specific_constraints[Op.Mean].append(SupportedOperators.constraint_mean_axis)
276 self.specific_constraints[Op.Mean].append(SupportedOperators.constraint_mean_height_width_product)
277 self.specific_constraints[Op.Mean].append(SupportedOperators.constraint_mean_height_width_product_int8)
Diqing Zhong189f7482021-01-26 12:12:51 +0100278
Tim Hall79d07d22020-04-27 18:20:16 +0100279 def is_operator_supported(self, op):
Michael McGeagh219ec072020-11-09 11:11:26 +0000280 ext_type = optype_to_builtintype(op.type)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100281 if op.type not in SupportedOperators.supported_operators:
Louis Verhaard5f2ea2f2020-10-15 08:39:44 +0200282 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
Michael McGeagh219ec072020-11-09 11:11:26 +0000283 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
Tim Hall79d07d22020-04-27 18:20:16 +0100284 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100285
Michael McGeagh65fd9982020-10-20 11:49:28 +0100286 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
Michael McGeagh37ded342020-10-01 15:37:44 +0100287 valid, extra = constraint(op)
288 if not valid:
Michael McGeagh219ec072020-11-09 11:11:26 +0000289 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
Michael McGeagh65fd9982020-10-20 11:49:28 +0100290 print(f" - {constraint.__doc__}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100291 if extra:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100292 print(f" {extra}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100293 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100294
Tim Hall79d07d22020-04-27 18:20:16 +0100295 return True
296
Michael McGeagh37ded342020-10-01 15:37:44 +0100297 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100298 def constraint_tens_no_dynamic(op):
299 "Input(s) and Output tensors must not be dynamic"
300 valid = True
301 extra = []
302 tensors = [tens for tens in op.inputs + op.outputs if tens]
303 for tens in tensors:
304 if (tens.shape == []) and (tens.values is None):
305 valid = False
306 extra.append(tens.name)
307 extra = ", ".join(extra)
308 return valid, f"Op has dynamic tensor(s): {extra}"
309
310 @staticmethod
Michael McGeagh37ded342020-10-01 15:37:44 +0100311 def constraint_tens_defined_shape(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100312 "Input(s) and Output tensors must have a defined shape"
Michael McGeagh37ded342020-10-01 15:37:44 +0100313 valid = True
314 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100315 tensors = [tens for tens in op.inputs + op.outputs if tens]
316 for tens in tensors:
317 if not tens.has_fully_defined_shape():
318 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100319 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100320 return valid, ", ".join(extra)
Michael McGeagh37ded342020-10-01 15:37:44 +0100321
Michael McGeagh184b2502020-10-09 17:19:52 +0100322 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100323 def constraint_tens_output_scalar(op):
324 "Output tensors cannot be scalar"
325 ofm = op.ofm
326 valid = ofm.shape != []
327 return valid, f"Output Tensor '{ofm.name}' is scalar"
Michael McGeagh184b2502020-10-09 17:19:52 +0100328
329 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000330 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
Michael McGeagh65fd9982020-10-20 11:49:28 +0100331 def constraint_tens_input_scalar(cls, op):
332 "Scalar Input tensors are only valid for op type: {}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100333 valid = True
334 extra = []
335 tensors = [tens for tens in op.inputs if tens]
336 for tens in tensors:
337 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
338 valid = False
339 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100340 extra = ", ".join(extra)
341 return valid, f"Op has scalar input tensor(s): {extra}"
Tim Hall79d07d22020-04-27 18:20:16 +0100342
Michael McGeagh37ded342020-10-01 15:37:44 +0100343 @staticmethod
344 def constraint_tens_shape_size(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100345 "Input(s) and Output tensors must not be greater than 4D"
Michael McGeagh37ded342020-10-01 15:37:44 +0100346 valid = True
347 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100348 tensors = [tens for tens in op.inputs + op.outputs if tens]
349 for tens in tensors:
350 if len(tens.shape) > 4:
351 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100352 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100353 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100354
Michael McGeagh37ded342020-10-01 15:37:44 +0100355 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000356 @docstring_format_args([_list_formatter(supported_op_dtypes)])
Michael McGeagh37ded342020-10-01 15:37:44 +0100357 def constraint_tens_dtype(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100358 "Tensors must be of type: {}"
Michael McGeagh37ded342020-10-01 15:37:44 +0100359 valid = True
360 extra = []
361 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100362 if not tensors:
363 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100364 for tens in tensors:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100365 if tens.dtype not in cls.supported_op_dtypes:
Michael McGeagh184b2502020-10-09 17:19:52 +0100366 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100367 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100368 return valid, ", ".join(extra)
369
370 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000371 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
Michael McGeagh184b2502020-10-09 17:19:52 +0100372 def constraint_tens_int32_ops(cls, op):
373 "Tensors which are int32 are only valid when op type is: {}"
374 valid = True
375 extra = []
376 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100377 if not tensors:
378 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh184b2502020-10-09 17:19:52 +0100379 for tens in tensors:
380 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
381 valid = False
382 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100383 extra = ", ".join(extra)
384 return valid, f"Op has int32 tensor(s): {extra}"
Andreas Nevalaineneadb1662020-09-01 15:36:26 +0200385
Michael McGeagh37ded342020-10-01 15:37:44 +0100386 @classmethod
387 @docstring_format_args(tens_dim_range)
388 def constraint_tens_dimension(cls, op):
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100389 "Tensor dimensions must be in the range [{}, {}]"
Michael McGeagh37ded342020-10-01 15:37:44 +0100390 tens_min, tens_max = cls.tens_dim_range
391 valid = True
392 extra = []
393 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100394 if not tensors:
395 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100396 for tens in tensors:
Michael McGeagh184b2502020-10-09 17:19:52 +0100397 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
398 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100399 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100400 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100401
Dwight Lidman8359a472020-09-28 15:53:40 +0200402 @staticmethod
403 def constraint_tens_quant_none_check(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100404 "Input(s), Output and Weight tensors must have quantization parameters"
Dwight Lidman8359a472020-09-28 15:53:40 +0200405 valid = True
406 extra = []
407 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
408 for tens in tensors:
409 if tens.quantization is None:
410 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100411 extra.append(tens.name)
412 extra = ", ".join(extra)
413 return valid, f"Op has tensors with missing quantization parameters: {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200414
Michael McGeagh184b2502020-10-09 17:19:52 +0100415 @staticmethod
416 def constraint_tens_quant_scale(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100417 "Input(s), Output and Weight tensors with quantization scales must be finite"
Michael McGeagh184b2502020-10-09 17:19:52 +0100418 valid = True
419 extra = []
420 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
421 for tens in tensors:
422 if (tens.quantization.scale_f32 is not None) and np.isinf(tens.quantization.scale_f32).any():
423 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100424 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100425 return valid, ", ".join(extra)
426
427 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000428 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
Dwight Lidmanc7187432020-11-16 17:40:46 +0100429 def constraint_tens_quant_per_axis(cls, op):
430 "Per-axis quantization is only supported for the following op types: {}"
431 valid = True
432 extra = []
433 if op.type not in cls.per_axis_quant_ops:
434 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
435 for tens in tensors:
436 if tens.quantization.is_per_axis():
437 valid = False
438 extra.append(tens.name)
439 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
440
Dwight Lidman0dd21c72020-11-24 13:45:50 +0100441 @staticmethod
442 def constraint_fc_output_2d(op):
443 "The output tensor(s) must have 2D shape"
444 valid = True
445 extra = []
446 for tens in op.outputs:
447 if len(tens.shape) != 2:
448 valid = False
449 extra.append(f"Tensor '{tens.name}' is {len(tens.shape)}D")
450 return valid, ", ".join(extra)
451
Dwight Lidmanc7187432020-11-16 17:40:46 +0100452 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000453 @docstring_format_args([_optype_formatter(supported_fused_activations)])
Michael McGeagh184b2502020-10-09 17:19:52 +0100454 def constraint_faf(cls, op):
455 "The fused activation function (if present) must be one of type: {}"
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100456 if op.activation is None:
457 res = True, "Op has no fused activation function"
458 else:
459 faf = op.activation.op_type
460 valid = faf in cls.supported_fused_activations
461 res = valid, f"Op has its fused activation function as: {faf}"
462 return res
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100463
Louis Verhaardc7761512021-02-03 10:22:38 +0100464 @classmethod
465 @docstring_format_args([_list_formatter(supported_faf_dtypes)])
466 def constraint_faf_type(cls, op):
467 "If a fused activation function is present, the Output tensor must be one of type: {}"
468 if op.activation is None:
469 res = True, "Op has no fused activation function"
470 else:
471 valid = op.ofm.dtype in cls.supported_faf_dtypes
472 ext_type = optype_to_builtintype(op.activation.op_type)
473 res = valid, f"Op has fused activation function {ext_type}, and Output tensor data type: {op.ofm.dtype}"
474 return res
475
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100476 @staticmethod
477 def constraint_stride_type(op):
478 "Stride values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100479 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100480 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100481 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100482
Michael McGeagh1eeea512020-09-30 14:23:09 +0100483 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100484 @docstring_format_args(stride_range)
485 def constraint_stride_range(cls, op):
486 "Stride values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100487 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100488 stride_min, stride_max = cls.stride_range
489 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100490 return valid, f"Op has stride WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100491
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100492 @staticmethod
493 def constraint_dilation_type(op):
494 "Dilation factor values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100495 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100496 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100497 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100498
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100499 @classmethod
500 @docstring_format_args(dilation_range)
501 def constraint_dilation_range(cls, op):
502 "Dilation factor values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100503 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100504 dilation_min, dilation_max = cls.dilation_range
505 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100506 return valid, f"Op has dilation factor WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100507
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100508 @classmethod
509 @docstring_format_args(dilated_height_range)
510 def constraint_dilated_height_range(cls, op):
511 "Dilated kernel height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100512 h = op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100513 dilated_height_min, dilated_height_max = cls.dilated_height_range
514 valid = dilated_height_min <= h <= dilated_height_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100515 return valid, f"Op has dilated kernel height as: {h}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200516
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100517 @classmethod
518 @docstring_format_args(dilated_product_range)
519 def constraint_dilated_product_range(cls, op):
520 "Product of dilated kernel width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100521 product = op.kernel.area_width() * op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100522 dilated_product_min, dilated_product_max = cls.dilated_product_range
523 valid = dilated_product_min <= product <= dilated_product_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100524 return valid, f"Op has product of dilated kernel width and height as: {product}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200525
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100526 @staticmethod
527 def constraint_weights_type(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100528 "Weight tensor must be 8-bit"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100529 weights = op.weights
530 valid = weights.element_size() == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100531 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200532
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100533 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100534 def constraint_weights_const(op):
535 "Weight tensor must be constant"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100536 weights = op.weights
537 valid = weights.values is not None
Michael McGeagh65fd9982020-10-20 11:49:28 +0100538 return valid, f"Tensor '{weights.name}' has non-constant values"
Andreas Nevalainen8854dc92020-09-24 13:43:00 +0200539
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100540 @classmethod
541 @docstring_format_args([weights_limit])
542 def constraint_weights_limit(cls, op):
543 "The sum of the weights cannot exceed {}"
544 weights = op.weights
545 values = weights.quant_values.astype(np.int64) - weights.quantization.zero_point
546 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
547 valid = limit <= cls.weights_limit
Michael McGeagh65fd9982020-10-20 11:49:28 +0100548 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200549
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100550 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000551 @docstring_format_args([_list_formatter(supported_bias_dtypes)])
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100552 def constraint_bias_type(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100553 "Optional Bias tensor must be of type: {}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100554 bias = op.bias
555 if bias:
556 valid = bias.dtype in cls.supported_bias_dtypes
Michael McGeagh65fd9982020-10-20 11:49:28 +0100557 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
558 return True, "Op has no bias tensor"
Tim Hall79d07d22020-04-27 18:20:16 +0100559
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100560 @staticmethod
561 def constraint_bias_40bit(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100562 "Optional Bias tensor values must fit within 40-bits"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100563 bias = op.bias
Fredrik Svedbergbdf09f92020-11-18 11:30:21 +0100564 if bias and bias.dtype == DataType.int64 and bias.quant_values is not None:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100565 valid = all(len(bin(quant_value)[2:]) <= 40 for quant_value in bias.quant_values)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100566 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
567 return True, "Op has no bias tensor, or it fits in 40-bit"
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200568
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100569 @staticmethod
570 def constraint_batch_size(op):
571 "IFM Tensor batch size must be 1"
572 ifm = op.ifm
573 valid = ifm.shape[0] == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100574 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
575
576 @staticmethod
577 def constraint_quant_scale_inf(op):
Louis Verhaard9a0cff12021-01-08 11:17:33 +0100578 "Input and Output tensors must have quantization scales that fit within float32 precision"
579 if op.ofm is not None and op.ofm.is_quantized():
580 ofm_scale = op.ofm.quantization.scale_f32
581 if ofm_scale < np.finfo(np.float32).tiny:
582 return (
583 False,
584 f"The quantization scale of the output tensor is {ofm_scale}, "
585 + f"minimum supported is: {np.finfo(np.float32).tiny}",
586 )
587 if op.ifm is not None and op.ifm.is_quantized():
588 ifm_scale = op.ifm.quantization.scale_f32
589 if np.isinf(ifm_scale / ofm_scale):
590 return (
591 False,
592 f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}",
593 )
594 return True, "Op's quantization is ok"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100595
596 @staticmethod
597 def constraint_depth_multiplier(op):
598 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
599 depth_multiplier = op.attrs.get("depth_multiplier", 1)
600 if depth_multiplier > 1:
601 ifm_channels = op.ifm.shape[3]
602 ofm_channels = op.ofm.shape[3]
603 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
604 extra = (
605 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
606 f" and depth_multiplier={depth_multiplier}"
607 )
608 return valid, extra
609 return True, "Op has depth_multiplier=1"
610
611 @staticmethod
612 def constraint_tconv_stride(op):
613 "Stride values for both width and height must be 2"
614 w = op.kernel.stride.x
615 h = op.kernel.stride.y
616 valid = (w == 2) and (h == 2)
617 return valid, f"Op has stride WxH as: {w}x{h}"
618
619 @staticmethod
620 def constraint_tconv_same(op):
621 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
Michael McGeagh16895482020-12-14 15:51:20 +0000622 if op.attrs["padding"] == Padding.SAME:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100623 w = op.kernel.stride.x
624 h = op.kernel.stride.y
625 ifm_shape = op.ifm.shape
626 ofm_shape = op.ofm.shape
627 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
628 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
629 return True, "Op has padding=VALID"
630
631 @staticmethod
632 def constraint_tconv_valid(op):
633 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
634 minus difference between kernel size and stride"""
Michael McGeagh16895482020-12-14 15:51:20 +0000635 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100636 s_w = op.kernel.stride.x
637 s_h = op.kernel.stride.y
638 k_w = op.kernel.width
639 k_h = op.kernel.height
640 ifm_shape = op.ifm.shape
641 ofm_shape = op.ofm.shape
642 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
643 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
644 valid = height_check and width_check
645 extra = (
646 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
647 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
648 )
649 return valid, extra
650 return True, "Op has padding=SAME"
651
652 @staticmethod
653 def constraint_matching_in_out_types(op):
654 "IFM and OFM data types must match"
655 ifm_dtype = op.ifm.dtype
656 ofm_dtype = op.ofm.dtype
657 valid = ifm_dtype == ofm_dtype
658 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
659
660 @staticmethod
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100661 def constraint_beta_value_range(op):
662 "Beta value needs to be positive"
663 beta = op.attrs.get("beta", 1.0)
664 valid = beta >= 0
665 return valid, f"Op has beta={beta}"
666
667 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100668 def constraint_filter_type(op):
669 "Kernel filter values for both width and height must be integer types"
670 w = op.kernel.width
671 h = op.kernel.height
672 valid = is_integer(w) and is_integer(h)
673 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
674
675 @classmethod
676 @docstring_format_args(filter_range)
677 def constraint_filter_range(cls, op):
678 "Kernel filter values for both width and height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000679 if op.attrs["padding"] == Padding.SAME:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100680 w = op.kernel.width
681 h = op.kernel.height
682 filter_min, filter_max = cls.filter_range
683 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
684 return valid, f"Op has kernel filter WxH as: {w}x{h}"
685 return True, "Op has padding=VALID"
686
687 @classmethod
688 @docstring_format_args(filter_height_range)
689 def constraint_filter_height_range(cls, op):
690 "Kernel filter height must be in the range [{}, {}]"
691 h = op.kernel.height
692 filter_height_min, filter_height_max = cls.filter_height_range
693 valid = filter_height_min <= h <= filter_height_max
694 return valid, f"Op has kernel filter height as: {h}"
695
696 @classmethod
697 @docstring_format_args(filter_product_range)
698 def constraint_filter_product_range(cls, op):
699 "Product of kernel filter width and height must be in the range [{}, {}]"
700 product = op.kernel.elements_wh()
701 filter_product_min, filter_product_max = cls.filter_product_range
702 valid = filter_product_min <= product <= filter_product_max
703 return valid, f"Op has product of kernel filter width and height as: {product}"
704
705 @staticmethod
706 @docstring_format_args(filter_height_range)
707 def constraint_filter_height_range_valid_pad(op):
708 "VALID padding: Kernel filter height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000709 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100710 return SupportedOperators.constraint_filter_height_range(op)
711 return True, "Op has padding=SAME"
712
713 @staticmethod
714 @docstring_format_args(filter_product_range)
715 def constraint_filter_product_range_valid_pad(op):
716 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000717 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100718 return SupportedOperators.constraint_filter_product_range(op)
719 return True, "Op has padding=SAME"
720
721 @staticmethod
722 def constraint_resize(op):
723 """The width and height of the IFM and OFM must match one of the following criteria:
724 IFM W and H must both be 1
725 IFM must match OFM
726 OFM W and H must be 2x IFM -1, if align_corners is True
727 OFM W and H must be 2x IFM, if align_corners is False"""
728 # Easier to start with False condition as very few cases result in a supported resize
729 valid = False
730 ifm_shape = op.ifm.shape
731 ofm_shape = op.ofm.shape
732 align_corners = op.attrs.get("align_corners", False)
733 if len(ifm_shape) == 4:
734 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
735 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
736 valid = True
737 else:
738 upscaled_shape = np.array(ifm_shape[1:3])
739 out_shape = np.array(ofm_shape[1:3])
740 while (upscaled_shape < out_shape).all():
741 upscaled_shape *= 2
742 if align_corners:
743 upscaled_shape -= 1
744 # Valid if OFM is 2x IFM (-1 for align corners)
745 if np.array_equal(out_shape, upscaled_shape):
746 valid = True
747 break
748 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
749
750 @staticmethod
751 def constraint_matching_shapes(op):
752 "IFM and OFM shapes must match"
753 ifm_shape = op.ifm.shape
754 ofm_shape = op.ofm.shape
755 valid = ifm_shape == ofm_shape
756 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
757
758 @staticmethod
759 def constraint_splitv_inferred(op):
760 "Only one size is allowed to be inferred"
Jacob Bohline3de4e52020-11-27 14:52:06 +0100761 sizes = op.inputs[1].values
Michael McGeagh65fd9982020-10-20 11:49:28 +0100762 valid = np.count_nonzero(sizes == -1) <= 1
763 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
764
765 @staticmethod
766 def constraint_axis_exists(op):
767 "Axis attribute must exist"
768 axis = op.attrs.get("axis")
769 valid = axis is not None
770 return valid, f"Op has axis={axis}"
771
772 @staticmethod
773 def constraint_axis_valid(op):
774 "Axis attribute must be in the range [0, <ofm_dimensions>)"
775 dims = len(op.ofm.shape)
776 axis = op.attrs["axis"]
777 axis += dims if axis < 0 else 0
778 valid = 0 <= axis < dims
779 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
780
781 @staticmethod
782 def constraint_matching_dimensionality(op):
783 "All Input dimensionalities must match OFM dimensionality"
784 valid = True
785 extra = []
786 ofm_dim = len(op.ofm.shape)
787 tensors = [tens for tens in op.inputs if tens]
788 for tens in tensors:
789 dim = len(tens.shape)
790 if dim != ofm_dim:
791 valid = False
792 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
793 extra = ", ".join(extra)
794 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
795
796 @staticmethod
797 def constraint_valid_dimensions(op):
798 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
799 valid = True
800 extra = []
801 ofm_shape = op.ofm.shape
802 ofm_dim = len(ofm_shape)
803 axis = op.attrs["axis"]
804 axis += ofm_dim if axis < 0 else 0
805 tensors = [tens for tens in op.inputs if tens]
806 for tens in tensors:
807 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
808 valid = False
809 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
810 extra = ", ".join(extra)
811 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
812
813 @staticmethod
814 def constraint_stridedslice_input_count(op):
815 "Exactly 4 Input tensors are required"
816 inputs = len(op.inputs)
817 valid = inputs == 4
818 return valid, f"Op has {inputs} inputs"
819
820 @staticmethod
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100821 def constraint_pad_input_count(op):
822 "Number of input tensors must be exactly 2"
823 inputs = len(op.inputs)
824 valid = inputs == 2
825 return valid, f"Op has {inputs} inputs"
826
827 @staticmethod
828 def constraint_pad_shape(op):
Louis Verhaardc822d622021-03-11 14:59:06 +0100829 "The padding tensor must have the shape [3,2] or [4,2]"
830 valid = op.inputs[1].shape in ([3, 2], [4, 2])
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100831 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
832
833 @classmethod
834 @docstring_format_args([_list_formatter(supported_pad_dtypes)])
835 def constraint_pad_type(cls, op):
836 "Pad tensor must be of type: {}"
837 pad_tensor = op.inputs[1]
838 valid = pad_tensor.dtype in cls.supported_pad_dtypes
839 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
840
841 @staticmethod
842 def constraint_padding_dimensions(op):
843 "The pad tensor can only pad width and height"
844 pad_tensor = op.inputs[1].values
Louis Verhaardc822d622021-03-11 14:59:06 +0100845
846 valid = sum(pad_tensor[-1, :]) == 0
847 if valid and len(pad_tensor) > 3:
848 valid = sum(pad_tensor[0, :]) == 0
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100849 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
850
851 @staticmethod
852 def constraint_pad_constant(op):
Louis Verhaard3d22f3c2021-02-03 08:43:54 +0100853 "The padding tensor must be constant"
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100854 pad_tensor = op.inputs[1].values
855 valid = pad_tensor is not None
856 return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}"
857
Louis Verhaardebf4af62021-01-27 15:57:57 +0100858 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100859 def constraint_stridedslice_inputs_const(op):
860 "Begin, End and Stride Input tensors must be constant"
861 valid = True
862 extra = []
863 _, begin, end, strides = op.inputs
864 if begin.values is None:
865 valid = False
866 extra.append(f"Begin tensor '{begin.name}'")
867 if end.values is None:
868 valid = False
869 extra.append(f"End tensor '{end.name}'")
870 if strides.values is None:
871 valid = False
872 extra.append(f"Stride tensor '{strides.name}'")
873 extra = ", ".join(extra)
874 return valid, f"Op has non-constant tensors: {extra}"
875
876 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100877 def constraint_stridedslice_stride_values(op):
878 "All Strides values must be 1"
879 strides = op.inputs[3]
880 valid = all(stride == 1 for stride in strides.values)
881 return valid, f"Op has strides values {strides.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100882
Michael McGeagh65fd9982020-10-20 11:49:28 +0100883 @staticmethod
884 def constraint_ellipsis_mask(op):
885 "ellipsis_mask must be 0"
886 ellipsis = op.attrs["ellipsis_mask"]
887 valid = ellipsis == 0
888 return valid, f"Op has ellipsis mask as: {ellipsis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200889
Michael McGeagh65fd9982020-10-20 11:49:28 +0100890 @staticmethod
891 def constraint_axis_masks(op):
892 "new_axis_mask and shrink_axis_mask cannot both be set"
893 new_axis = op.attrs["new_axis_mask"]
894 shrink_axis = op.attrs["shrink_axis_mask"]
895 valid = (new_axis == 0) or (shrink_axis == 0)
896 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200897
Michael McGeagh65fd9982020-10-20 11:49:28 +0100898 @staticmethod
899 def constraint_slice_ranges(op):
900 "Slice 'end' values must be greater than 'begin' values"
901 ifm, begin, end, _ = op.inputs
902 # Calculate offset begin/end
903 offset_begin = get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
904 offset_end = get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
905 # Check "end - begin" doesn't result in any zero or negative elements
906 valid = all((e - b) > 0 for b, e in zip(offset_begin, offset_end))
907 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100908
Michael McGeagh65fd9982020-10-20 11:49:28 +0100909 @staticmethod
910 def constraint_matching_inputs_types(op):
911 "Both Input data types must match"
912 ifm_dtype = op.ifm.dtype
913 ifm2_dtype = op.ifm2.dtype
914 valid = ifm_dtype == ifm2_dtype
915 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100916
Michael McGeagh65fd9982020-10-20 11:49:28 +0100917 @staticmethod
918 def constraint_matching_signed(op):
919 "For IFM that are signed, OFM must also be signed"
920 valid = True
921 ifm_dtype = op.ifm.dtype
922 ofm_dtype = op.ofm.dtype
923 if ifm_dtype.type & BaseType.Signed:
924 valid = bool(ofm_dtype.type & BaseType.Signed)
925 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100926
Michael McGeagh65fd9982020-10-20 11:49:28 +0100927 @staticmethod
928 def constraint_unsigned_valid(op):
929 "For IFM that are unsigned, OFM must either be the same type or int32"
930 valid = True
931 ifm_dtype = op.ifm.dtype
932 ofm_dtype = op.ofm.dtype
933 if ifm_dtype.type & BaseType.Unsigned:
934 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
935 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100936
Michael McGeagh65fd9982020-10-20 11:49:28 +0100937 @staticmethod
938 def constraint_inputs_int32(op):
939 "Both Input data types must be int32"
940 ifm_dtype = op.ifm.dtype
941 ifm2_dtype = op.ifm2.dtype
942 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
943 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100944
Michael McGeagh65fd9982020-10-20 11:49:28 +0100945 @staticmethod
946 def constraint_output_int32(op):
947 "OFM must be int32"
948 ofm_dtype = op.ofm.dtype
949 valid = ofm_dtype == DataType.int32
950 return valid, f"Op has ofm_dtype={ofm_dtype}"
Dwight Lidman42fed942020-05-29 09:37:03 +0200951
Michael McGeagh65fd9982020-10-20 11:49:28 +0100952 @staticmethod
Diqing Zhong189f7482021-01-26 12:12:51 +0100953 def constraint_input_8bit(op):
954 "IFM must be int8 or uint8"
955 ifm_dtype = op.ifm.dtype
956 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8)
957 return valid, f"Op has ifm_dtype={ifm_dtype}"
958
959 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100960 def constraint_matching_quantization_parameters(op):
961 "Both Input quantization parameters must match OFM quantization parameters"
962 valid = True
963 extra = []
964 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
965 valid = False
966 extra.append(op.ifm.name)
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100967 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100968 valid = False
969 extra.append(op.ifm2.name)
970 extra = ", ".join(extra)
971 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200972
Michael McGeagh65fd9982020-10-20 11:49:28 +0100973 @staticmethod
974 def constraint_elemwise_batch_size(op):
975 "Batch size must be 1 for Input tensors with more than 2 dimensions"
976 valid = True
977 extra = []
978 for tens in (op.ifm, op.ifm2):
979 # Unary ops have ifm2 as None
980 if tens is not None:
981 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
982 valid = False
983 extra.append(tens.name)
984 extra = ", ".join(extra)
985 return valid, f"Op has invalid input tensors: {extra}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200986
Michael McGeagh65fd9982020-10-20 11:49:28 +0100987 @staticmethod
988 def constraint_matching_either_shapes(op):
989 "At least one Input's shape must match the OFM's shape"
990 ifm_shape = op.ifm.shape
991 ifm2_shape = op.ifm2.shape if op.ifm2 else None
992 ofm_shape = op.ofm.shape
993 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
994 return valid, f"Op has ifm_shape={ifm_shape}, ifm2_shape={ifm2_shape} and ofm_shape={ofm_shape}"
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200995
Michael McGeagh65fd9982020-10-20 11:49:28 +0100996 @staticmethod
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100997 def constraint_broadcast_shapes(op):
998 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
999 ifm_shape = op.ifm.shape
1000 ifm2_shape = op.ifm2.shape if op.ifm2 else None
1001 ofm_shape = op.ofm.shape
1002 valid = True
1003 if ifm_shape is not None and ifm2_shape is not None:
1004 # align trailing dimensions
1005 size = min(len(ifm_shape), len(ifm2_shape))
1006 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
1007 mi = max(i, i2)
1008 # Input dimensions should match or one should be of dimension 1
1009 # Output dimension should match the largest input dimension, together
1010 # with constraint_match_either_shapes ensures broadcast from only one input
1011 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
1012 valid = False
1013 break
1014
1015 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
1016
1017 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +01001018 def constraint_alpha_valid(op):
1019 "Alpha must not be negative"
1020 alpha = op.attrs["alpha"]
1021 valid = alpha >= 0
1022 return valid, f"Op has alpha={alpha}"
erik.andersson@arm.com0cbb1662021-02-22 15:47:07 +01001023
1024 @staticmethod
1025 def constraint_keep_dim_ifm_ofm(op):
1026 "The IFM and OFM must have the same number of dimensions if keep_num_dims is set to true"
1027 valid = True
1028 if op.attrs.get("keep_num_dims"):
1029 valid = len(op.ifm.shape) == len(op.ofm.shape)
1030 return valid, f"Op has ifm shape={op.ifm.shape} and ofm shape={op.ofm.shape}"
Dwight Lidman4f728c02020-12-17 15:14:45 +01001031
1032 def constraint_mean_input_dims(op):
1033 "Input tensor must be at least 2D"
1034 dims = len(op.inputs[0].shape)
1035 return 2 <= dims <= 4, f"Input is {dims}D"
1036
1037 @staticmethod
1038 def constraint_mean_axis(op):
1039 "Axis indices must correspond to height and width axes"
1040 dims = len(op.inputs[0].shape)
1041 axis = op.inputs[1].values if op.inputs[1].shape == [] else list(op.inputs[1].values)
1042 if dims == 2 or dims == 3:
1043 valid = axis in (0, 1, [0, 1], [1, 0])
1044 elif dims == 4:
1045 valid = axis in (1, 2, [1, 2], [2, 1])
1046 return valid, f"Axis is {axis}"
1047
1048 @classmethod
1049 @docstring_format_args([mean_kernel_product])
1050 def constraint_mean_height_width_product(cls, op):
1051 "Product of height and width can be at most {}"
1052 shape = op.inputs[0].shape
1053 hi = 0 if len(shape) < 4 else 1
1054 h, w = shape[hi : hi + 2]
1055 max_prod = cls.mean_kernel_product
1056 return h * w <= max_prod, f"Product of height and width is {h * w}"
1057
1058 @classmethod
1059 @docstring_format_args([mean_kernel_product_int8])
1060 def constraint_mean_height_width_product_int8(cls, op):
1061 """Product of IFM height and width can be at most {} when the following are true:
1062 IFM dimensions are 4,
1063 Axis indices are 1 and 2,
1064 keep_dims is set to True and
1065 IFM datatype is int8"""
1066 shape = op.ifm.shape
1067 axis = op.inputs[1].values if op.inputs[1].shape == [] else list(op.inputs[1].values)
1068 if (
1069 len(shape) != 4
1070 or op.ifm.dtype != DataType.int8
1071 or not op.attrs.get("keep_dims")
1072 or axis not in ([1, 2], [2, 1])
1073 ):
1074 return True, ""
1075 hi = 0 if len(shape) < 4 else 1
1076 h, w = shape[hi : hi + 2]
1077 max_prod = cls.mean_kernel_product_int8
1078 return h * w <= max_prod, f"Product of height and width is {h * w}"
1079
1080 @staticmethod
1081 def constraint_mean_properties(op):
1082 """Every constraint in either one (or both) of the following sets of constraints must be fulfilled:
1083 Set A:
1084 IFM dimensions are 4,
1085 Axis indices are 1 and 2,
1086 keep_dims is set to True
1087 Set B:
1088 IFM zero point and OFM zero point are the same,
1089 IFM scale and OFM scale are the same"""
1090 seta, setb = True, True
1091 extra = []
1092 axis = op.inputs[1].values if op.inputs[1].shape == [] else list(op.inputs[1].values)
1093 if len(op.ifm.shape) != 4:
1094 seta = False
1095 extra.append(f"IFM shape is {op.ifm.shape}")
1096 if not any(np.array_equal(axis, ax) for ax in ([1, 2], [2, 1])):
1097 seta = False
1098 extra.append(f"Axis is {axis}")
1099 if not op.attrs.get("keep_dims"):
1100 seta = False
1101 extra.append("keep_dims is False")
1102 ifmq, ofmq = op.ifm.quantization, op.ofm.quantization
1103 if ifmq.zero_point != ofmq.zero_point:
1104 setb = False
1105 extra.append("IFM zero point does not match OFM zero point")
1106 if ifmq.scale_f32 != ofmq.scale_f32:
1107 setb = False
1108 extra.append("IFM scale does not match OFM scale")
1109 extra = ", ".join(extra)
1110 return seta or setb, f"The following constraints were not fulfilled: {extra}"