blob: f2c2eb9eefd3ea4d00576220566fb5ea4adc9e1c [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
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
78 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020079 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
80 binary_elem_wise_min_max_ops = set((Op.Minimum, Op.Maximum,))
81 binary_elem_wise_shift_ops = set((Op.SHL, Op.SHR,))
82 binary_elem_wise_add_mul_sub = set((Op.Add, Op.Mul, Op.Sub,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010083 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
84 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010085 supported_int32_tensor_ops = (
Louis Verhaardaee5d752020-09-30 09:01:52 +020086 set((Op.ReduceSum, Op.CLZ,)) | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010087 )
Michael McGeagh65fd9982020-10-20 11:49:28 +010088 relu_ops = Op.op_set(Op.is_relu_op)
89 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010090 npu_post_ops = (
Michael McGeagh1eeea512020-09-30 14:23:09 +010091 # activation functions
Louis Verhaardaee5d752020-09-30 09:01:52 +020092 activation_ops
93 # concatenation write direction
94 | set((Op.ConcatSliceWrite,))
95 # Quantization
96 | set((Op.Quantize,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010097 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020098 split_ops = set((Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack,))
99 concat_ops = set((Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack,))
Michael McGeagha648aa92020-11-18 15:44:05 +0000100 memory_only_ops = set((Op.Squeeze, Op.Reshape, Op.QuantizedReshape,)) | concat_ops | split_ops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200101 shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV,))
Dwight Lidmanc7187432020-11-16 17:40:46 +0100102 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Michael McGeagh65fd9982020-10-20 11:49:28 +0100103 supported_fused_activations = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.LUT,))
Michael McGeagh1eeea512020-09-30 14:23:09 +0100104 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | npu_post_ops | memory_only_ops
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100105 # Supported data types
106 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
107 supported_bias_dtypes = set((DataType.int32, DataType.int64))
Michael McGeagh37ded342020-10-01 15:37:44 +0100108 # Defined ranges for allowed values:
109 tens_dim_range = (1, 65535)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100110 stride_range = (1, 3)
111 dilation_range = (1, 2)
112 dilated_height_range = (1, 64)
113 dilated_product_range = (1, 64 * 64)
114 weights_limit = 127 * 65536
Michael McGeagh65fd9982020-10-20 11:49:28 +0100115 filter_range = (1, 8)
116 filter_height_range = (1, 256)
117 filter_product_range = (1, 256 * 256)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100118
Fredrik Svedberg880e7352020-08-25 11:31:47 +0200119 def __init__(self):
Michael McGeagh184b2502020-10-09 17:19:52 +0100120 # Setup the generic constraints. Note: the order matters
Michael McGeagh37ded342020-10-01 15:37:44 +0100121 self.generic_constraints = []
Michael McGeagh65fd9982020-10-20 11:49:28 +0100122 self.generic_constraints.append(SupportedOperators.constraint_tens_no_dynamic)
Michael McGeagh37ded342020-10-01 15:37:44 +0100123 self.generic_constraints.append(SupportedOperators.constraint_tens_defined_shape)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100124 self.generic_constraints.append(SupportedOperators.constraint_tens_output_scalar)
125 self.generic_constraints.append(SupportedOperators.constraint_tens_input_scalar)
Michael McGeagh37ded342020-10-01 15:37:44 +0100126 self.generic_constraints.append(SupportedOperators.constraint_tens_shape_size)
127 self.generic_constraints.append(SupportedOperators.constraint_tens_dtype)
Michael McGeagh184b2502020-10-09 17:19:52 +0100128 self.generic_constraints.append(SupportedOperators.constraint_tens_int32_ops)
Michael McGeagh37ded342020-10-01 15:37:44 +0100129 self.generic_constraints.append(SupportedOperators.constraint_tens_dimension)
Dwight Lidman8359a472020-09-28 15:53:40 +0200130 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_none_check)
Michael McGeagh184b2502020-10-09 17:19:52 +0100131 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_scale)
Dwight Lidmanc7187432020-11-16 17:40:46 +0100132 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_per_axis)
Michael McGeagh184b2502020-10-09 17:19:52 +0100133 self.generic_constraints.append(SupportedOperators.constraint_faf)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100134
Michael McGeagh65fd9982020-10-20 11:49:28 +0100135 # Setup specific constraints. Note: the order matters
136 self.specific_constraints = defaultdict(list)
137
138 # Conv-like checks:
139 for op_type in SupportedOperators.convolution_like_ops:
140 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
141 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
142 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_type)
143 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_range)
144 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_height_range)
145 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_product_range)
146 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
147 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
148 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_limit)
149 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
150 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
151 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
152 # Depthwise Conv specific checks:
153 for op_type in SupportedOperators.depthwise_convolution_ops:
154 self.specific_constraints[op_type].append(SupportedOperators.constraint_depth_multiplier)
155 # Transpose Conv specific checks:
156 for op_type in SupportedOperators.transpose_convolution_ops:
157 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_stride)
158 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_same)
159 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_valid)
160
161 # Pooling checks:
162 for op_type in SupportedOperators.pooling_ops:
163 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
164 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
165 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
166 # AVG pooling specific checks:
167 for op_type in SupportedOperators.avg_pooling_ops:
168 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
169 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
170 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_range)
171 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range_valid_pad)
172 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range_valid_pad)
173 # MAX pooling specific checks:
174 for op_type in SupportedOperators.max_pooling_ops:
175 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
176 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
177 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range)
178 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range)
179 # TODO: Check ReduceSum restrictions
180
181 # Relu specific checks:
182 for op_type in SupportedOperators.relu_ops:
183 self.specific_constraints[op_type].append(SupportedOperators.constraint_quant_scale_inf)
184
185 # Resizing specific checks:
186 for op_type in SupportedOperators.resizing_ops:
187 self.specific_constraints[op_type].append(SupportedOperators.constraint_resize)
188
189 # Vector Product specific checks:
190 for op_type in SupportedOperators.fc_vector_products:
191 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
192 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
193 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
194 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
195
196 # Concat specific checks:
197 for op_type in (Op.Concat, Op.ConcatTFLite):
198 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_exists)
199 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_valid)
200 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_dimensionality)
201 self.specific_constraints[op_type].append(SupportedOperators.constraint_valid_dimensions)
202
203 # Element-wise checks:
204 for op_type in SupportedOperators.elem_wise_main_ops:
205 self.specific_constraints[op_type].append(SupportedOperators.constraint_elemwise_batch_size)
206 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_either_shapes)
207 # Unary specific checks:
208 for op_type in SupportedOperators.unary_elem_wise_main_ops:
209 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
210 # Binary Min/Max specific checks:
211 for op_type in SupportedOperators.binary_elem_wise_min_max_ops:
212 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
213 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_quantization_parameters)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100214 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100215 # Binary Add/Mul/Sub specific checks:
216 for op_type in SupportedOperators.binary_elem_wise_add_mul_sub:
217 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_inputs_types)
218 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_signed)
219 self.specific_constraints[op_type].append(SupportedOperators.constraint_unsigned_valid)
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 Shift specific checks:
222 for op_type in SupportedOperators.binary_elem_wise_shift_ops:
223 self.specific_constraints[op_type].append(SupportedOperators.constraint_inputs_int32)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100224 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100225
226 # SHL specific checks:
227 self.specific_constraints[Op.SHL].append(SupportedOperators.constraint_output_int32)
228
229 # CLZ specific checks:
230 self.specific_constraints[Op.CLZ].append(SupportedOperators.constraint_output_int32)
231
232 # Softmax specific checks:
233 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_shapes)
234 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_in_out_types)
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100235 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_beta_value_range)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100236
237 # SplitV specific checks:
238 self.specific_constraints[Op.SplitV].append(SupportedOperators.constraint_splitv_inferred)
239
240 # StridedSlice specific checks:
241 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_input_count)
242 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_inputs_const)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100243 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_stride_values)
244 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_ellipsis_mask)
245 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_axis_masks)
246 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_slice_ranges)
247
248 # LeakyRelu specific checks:
249 self.specific_constraints[Op.LeakyRelu].append(SupportedOperators.constraint_alpha_valid)
Tim Hall79d07d22020-04-27 18:20:16 +0100250
Dwight Lidman0dd21c72020-11-24 13:45:50 +0100251 # FullyConnected specific checks:
252 self.specific_constraints[Op.FullyConnected].append(SupportedOperators.constraint_fc_output_2d)
253
Tim Hall79d07d22020-04-27 18:20:16 +0100254 def is_operator_supported(self, op):
Michael McGeagh219ec072020-11-09 11:11:26 +0000255 ext_type = optype_to_builtintype(op.type)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100256 if op.type not in SupportedOperators.supported_operators:
Louis Verhaard5f2ea2f2020-10-15 08:39:44 +0200257 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
Michael McGeagh219ec072020-11-09 11:11:26 +0000258 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
Tim Hall79d07d22020-04-27 18:20:16 +0100259 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100260
Michael McGeagh65fd9982020-10-20 11:49:28 +0100261 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
Michael McGeagh37ded342020-10-01 15:37:44 +0100262 valid, extra = constraint(op)
263 if not valid:
Michael McGeagh219ec072020-11-09 11:11:26 +0000264 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
Michael McGeagh65fd9982020-10-20 11:49:28 +0100265 print(f" - {constraint.__doc__}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100266 if extra:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100267 print(f" {extra}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100268 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100269
Tim Hall79d07d22020-04-27 18:20:16 +0100270 return True
271
Michael McGeagh37ded342020-10-01 15:37:44 +0100272 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100273 def constraint_tens_no_dynamic(op):
274 "Input(s) and Output tensors must not be dynamic"
275 valid = True
276 extra = []
277 tensors = [tens for tens in op.inputs + op.outputs if tens]
278 for tens in tensors:
279 if (tens.shape == []) and (tens.values is None):
280 valid = False
281 extra.append(tens.name)
282 extra = ", ".join(extra)
283 return valid, f"Op has dynamic tensor(s): {extra}"
284
285 @staticmethod
Michael McGeagh37ded342020-10-01 15:37:44 +0100286 def constraint_tens_defined_shape(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100287 "Input(s) and Output tensors must have a defined shape"
Michael McGeagh37ded342020-10-01 15:37:44 +0100288 valid = True
289 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100290 tensors = [tens for tens in op.inputs + op.outputs if tens]
291 for tens in tensors:
292 if not tens.has_fully_defined_shape():
293 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100294 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100295 return valid, ", ".join(extra)
Michael McGeagh37ded342020-10-01 15:37:44 +0100296
Michael McGeagh184b2502020-10-09 17:19:52 +0100297 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100298 def constraint_tens_output_scalar(op):
299 "Output tensors cannot be scalar"
300 ofm = op.ofm
301 valid = ofm.shape != []
302 return valid, f"Output Tensor '{ofm.name}' is scalar"
Michael McGeagh184b2502020-10-09 17:19:52 +0100303
304 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000305 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
Michael McGeagh65fd9982020-10-20 11:49:28 +0100306 def constraint_tens_input_scalar(cls, op):
307 "Scalar Input tensors are only valid for op type: {}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100308 valid = True
309 extra = []
310 tensors = [tens for tens in op.inputs if tens]
311 for tens in tensors:
312 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
313 valid = False
314 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100315 extra = ", ".join(extra)
316 return valid, f"Op has scalar input tensor(s): {extra}"
Tim Hall79d07d22020-04-27 18:20:16 +0100317
Michael McGeagh37ded342020-10-01 15:37:44 +0100318 @staticmethod
319 def constraint_tens_shape_size(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100320 "Input(s) and Output tensors must not be greater than 4D"
Michael McGeagh37ded342020-10-01 15:37:44 +0100321 valid = True
322 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100323 tensors = [tens for tens in op.inputs + op.outputs if tens]
324 for tens in tensors:
325 if len(tens.shape) > 4:
326 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100327 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100328 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100329
Michael McGeagh37ded342020-10-01 15:37:44 +0100330 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000331 @docstring_format_args([_list_formatter(supported_op_dtypes)])
Michael McGeagh37ded342020-10-01 15:37:44 +0100332 def constraint_tens_dtype(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100333 "Tensors must be of type: {}"
Michael McGeagh37ded342020-10-01 15:37:44 +0100334 valid = True
335 extra = []
336 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100337 if not tensors:
338 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100339 for tens in tensors:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100340 if tens.dtype not in cls.supported_op_dtypes:
Michael McGeagh184b2502020-10-09 17:19:52 +0100341 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100342 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100343 return valid, ", ".join(extra)
344
345 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000346 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
Michael McGeagh184b2502020-10-09 17:19:52 +0100347 def constraint_tens_int32_ops(cls, op):
348 "Tensors which are int32 are only valid when op type is: {}"
349 valid = True
350 extra = []
351 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100352 if not tensors:
353 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh184b2502020-10-09 17:19:52 +0100354 for tens in tensors:
355 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
356 valid = False
357 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100358 extra = ", ".join(extra)
359 return valid, f"Op has int32 tensor(s): {extra}"
Andreas Nevalaineneadb1662020-09-01 15:36:26 +0200360
Michael McGeagh37ded342020-10-01 15:37:44 +0100361 @classmethod
362 @docstring_format_args(tens_dim_range)
363 def constraint_tens_dimension(cls, op):
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100364 "Tensor dimensions must be in the range [{}, {}]"
Michael McGeagh37ded342020-10-01 15:37:44 +0100365 tens_min, tens_max = cls.tens_dim_range
366 valid = True
367 extra = []
368 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100369 if not tensors:
370 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100371 for tens in tensors:
Michael McGeagh184b2502020-10-09 17:19:52 +0100372 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
373 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100374 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100375 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100376
Dwight Lidman8359a472020-09-28 15:53:40 +0200377 @staticmethod
378 def constraint_tens_quant_none_check(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100379 "Input(s), Output and Weight tensors must have quantization parameters"
Dwight Lidman8359a472020-09-28 15:53:40 +0200380 valid = True
381 extra = []
382 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
383 for tens in tensors:
384 if tens.quantization is None:
385 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100386 extra.append(tens.name)
387 extra = ", ".join(extra)
388 return valid, f"Op has tensors with missing quantization parameters: {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200389
Michael McGeagh184b2502020-10-09 17:19:52 +0100390 @staticmethod
391 def constraint_tens_quant_scale(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100392 "Input(s), Output and Weight tensors with quantization scales must be finite"
Michael McGeagh184b2502020-10-09 17:19:52 +0100393 valid = True
394 extra = []
395 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
396 for tens in tensors:
397 if (tens.quantization.scale_f32 is not None) and np.isinf(tens.quantization.scale_f32).any():
398 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100399 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100400 return valid, ", ".join(extra)
401
402 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000403 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
Dwight Lidmanc7187432020-11-16 17:40:46 +0100404 def constraint_tens_quant_per_axis(cls, op):
405 "Per-axis quantization is only supported for the following op types: {}"
406 valid = True
407 extra = []
408 if op.type not in cls.per_axis_quant_ops:
409 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
410 for tens in tensors:
411 if tens.quantization.is_per_axis():
412 valid = False
413 extra.append(tens.name)
414 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
415
Dwight Lidman0dd21c72020-11-24 13:45:50 +0100416 @staticmethod
417 def constraint_fc_output_2d(op):
418 "The output tensor(s) must have 2D shape"
419 valid = True
420 extra = []
421 for tens in op.outputs:
422 if len(tens.shape) != 2:
423 valid = False
424 extra.append(f"Tensor '{tens.name}' is {len(tens.shape)}D")
425 return valid, ", ".join(extra)
426
Dwight Lidmanc7187432020-11-16 17:40:46 +0100427 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000428 @docstring_format_args([_optype_formatter(supported_fused_activations)])
Michael McGeagh184b2502020-10-09 17:19:52 +0100429 def constraint_faf(cls, op):
430 "The fused activation function (if present) must be one of type: {}"
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100431 if op.activation is None:
432 res = True, "Op has no fused activation function"
433 else:
434 faf = op.activation.op_type
435 valid = faf in cls.supported_fused_activations
436 res = valid, f"Op has its fused activation function as: {faf}"
437 return res
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100438
439 @staticmethod
440 def constraint_stride_type(op):
441 "Stride values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100442 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100443 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100444 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100445
Michael McGeagh1eeea512020-09-30 14:23:09 +0100446 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100447 @docstring_format_args(stride_range)
448 def constraint_stride_range(cls, op):
449 "Stride values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100450 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100451 stride_min, stride_max = cls.stride_range
452 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100453 return valid, f"Op has stride WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100454
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100455 @staticmethod
456 def constraint_dilation_type(op):
457 "Dilation factor values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100458 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100459 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100460 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100461
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100462 @classmethod
463 @docstring_format_args(dilation_range)
464 def constraint_dilation_range(cls, op):
465 "Dilation factor values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100466 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100467 dilation_min, dilation_max = cls.dilation_range
468 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100469 return valid, f"Op has dilation factor WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100470
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100471 @classmethod
472 @docstring_format_args(dilated_height_range)
473 def constraint_dilated_height_range(cls, op):
474 "Dilated kernel height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100475 h = op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100476 dilated_height_min, dilated_height_max = cls.dilated_height_range
477 valid = dilated_height_min <= h <= dilated_height_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100478 return valid, f"Op has dilated kernel height as: {h}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200479
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100480 @classmethod
481 @docstring_format_args(dilated_product_range)
482 def constraint_dilated_product_range(cls, op):
483 "Product of dilated kernel width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100484 product = op.kernel.area_width() * op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100485 dilated_product_min, dilated_product_max = cls.dilated_product_range
486 valid = dilated_product_min <= product <= dilated_product_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100487 return valid, f"Op has product of dilated kernel width and height as: {product}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200488
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100489 @staticmethod
490 def constraint_weights_type(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100491 "Weight tensor must be 8-bit"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100492 weights = op.weights
493 valid = weights.element_size() == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100494 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200495
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100496 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100497 def constraint_weights_const(op):
498 "Weight tensor must be constant"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100499 weights = op.weights
500 valid = weights.values is not None
Michael McGeagh65fd9982020-10-20 11:49:28 +0100501 return valid, f"Tensor '{weights.name}' has non-constant values"
Andreas Nevalainen8854dc92020-09-24 13:43:00 +0200502
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100503 @classmethod
504 @docstring_format_args([weights_limit])
505 def constraint_weights_limit(cls, op):
506 "The sum of the weights cannot exceed {}"
507 weights = op.weights
508 values = weights.quant_values.astype(np.int64) - weights.quantization.zero_point
509 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
510 valid = limit <= cls.weights_limit
Michael McGeagh65fd9982020-10-20 11:49:28 +0100511 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200512
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100513 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000514 @docstring_format_args([_list_formatter(supported_bias_dtypes)])
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100515 def constraint_bias_type(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100516 "Optional Bias tensor must be of type: {}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100517 bias = op.bias
518 if bias:
519 valid = bias.dtype in cls.supported_bias_dtypes
Michael McGeagh65fd9982020-10-20 11:49:28 +0100520 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
521 return True, "Op has no bias tensor"
Tim Hall79d07d22020-04-27 18:20:16 +0100522
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100523 @staticmethod
524 def constraint_bias_40bit(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100525 "Optional Bias tensor values must fit within 40-bits"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100526 bias = op.bias
Fredrik Svedbergbdf09f92020-11-18 11:30:21 +0100527 if bias and bias.dtype == DataType.int64 and bias.quant_values is not None:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100528 valid = all(len(bin(quant_value)[2:]) <= 40 for quant_value in bias.quant_values)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100529 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
530 return True, "Op has no bias tensor, or it fits in 40-bit"
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200531
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100532 @staticmethod
533 def constraint_batch_size(op):
534 "IFM Tensor batch size must be 1"
535 ifm = op.ifm
536 valid = ifm.shape[0] == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100537 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
538
539 @staticmethod
540 def constraint_quant_scale_inf(op):
541 "The IFM quantization scale divided by the OFM quantization scale must not be infinite"
542 ifm_scale = op.ifm.quantization.scale_f32
543 ofm_scale = op.ofm.quantization.scale_f32
544 valid = not np.isinf(ifm_scale / ofm_scale)
545 return valid, f"Op has infinite quantization scale. ifm_scale={ifm_scale} ofm_scale={ofm_scale}"
546
547 @staticmethod
548 def constraint_depth_multiplier(op):
549 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
550 depth_multiplier = op.attrs.get("depth_multiplier", 1)
551 if depth_multiplier > 1:
552 ifm_channels = op.ifm.shape[3]
553 ofm_channels = op.ofm.shape[3]
554 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
555 extra = (
556 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
557 f" and depth_multiplier={depth_multiplier}"
558 )
559 return valid, extra
560 return True, "Op has depth_multiplier=1"
561
562 @staticmethod
563 def constraint_tconv_stride(op):
564 "Stride values for both width and height must be 2"
565 w = op.kernel.stride.x
566 h = op.kernel.stride.y
567 valid = (w == 2) and (h == 2)
568 return valid, f"Op has stride WxH as: {w}x{h}"
569
570 @staticmethod
571 def constraint_tconv_same(op):
572 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
Michael McGeagh16895482020-12-14 15:51:20 +0000573 if op.attrs["padding"] == Padding.SAME:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100574 w = op.kernel.stride.x
575 h = op.kernel.stride.y
576 ifm_shape = op.ifm.shape
577 ofm_shape = op.ofm.shape
578 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
579 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
580 return True, "Op has padding=VALID"
581
582 @staticmethod
583 def constraint_tconv_valid(op):
584 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
585 minus difference between kernel size and stride"""
Michael McGeagh16895482020-12-14 15:51:20 +0000586 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100587 s_w = op.kernel.stride.x
588 s_h = op.kernel.stride.y
589 k_w = op.kernel.width
590 k_h = op.kernel.height
591 ifm_shape = op.ifm.shape
592 ofm_shape = op.ofm.shape
593 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
594 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
595 valid = height_check and width_check
596 extra = (
597 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
598 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
599 )
600 return valid, extra
601 return True, "Op has padding=SAME"
602
603 @staticmethod
604 def constraint_matching_in_out_types(op):
605 "IFM and OFM data types must match"
606 ifm_dtype = op.ifm.dtype
607 ofm_dtype = op.ofm.dtype
608 valid = ifm_dtype == ofm_dtype
609 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
610
611 @staticmethod
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100612 def constraint_beta_value_range(op):
613 "Beta value needs to be positive"
614 beta = op.attrs.get("beta", 1.0)
615 valid = beta >= 0
616 return valid, f"Op has beta={beta}"
617
618 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100619 def constraint_filter_type(op):
620 "Kernel filter values for both width and height must be integer types"
621 w = op.kernel.width
622 h = op.kernel.height
623 valid = is_integer(w) and is_integer(h)
624 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
625
626 @classmethod
627 @docstring_format_args(filter_range)
628 def constraint_filter_range(cls, op):
629 "Kernel filter values for both width and height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000630 if op.attrs["padding"] == Padding.SAME:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100631 w = op.kernel.width
632 h = op.kernel.height
633 filter_min, filter_max = cls.filter_range
634 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
635 return valid, f"Op has kernel filter WxH as: {w}x{h}"
636 return True, "Op has padding=VALID"
637
638 @classmethod
639 @docstring_format_args(filter_height_range)
640 def constraint_filter_height_range(cls, op):
641 "Kernel filter height must be in the range [{}, {}]"
642 h = op.kernel.height
643 filter_height_min, filter_height_max = cls.filter_height_range
644 valid = filter_height_min <= h <= filter_height_max
645 return valid, f"Op has kernel filter height as: {h}"
646
647 @classmethod
648 @docstring_format_args(filter_product_range)
649 def constraint_filter_product_range(cls, op):
650 "Product of kernel filter width and height must be in the range [{}, {}]"
651 product = op.kernel.elements_wh()
652 filter_product_min, filter_product_max = cls.filter_product_range
653 valid = filter_product_min <= product <= filter_product_max
654 return valid, f"Op has product of kernel filter width and height as: {product}"
655
656 @staticmethod
657 @docstring_format_args(filter_height_range)
658 def constraint_filter_height_range_valid_pad(op):
659 "VALID padding: Kernel filter height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000660 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100661 return SupportedOperators.constraint_filter_height_range(op)
662 return True, "Op has padding=SAME"
663
664 @staticmethod
665 @docstring_format_args(filter_product_range)
666 def constraint_filter_product_range_valid_pad(op):
667 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000668 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100669 return SupportedOperators.constraint_filter_product_range(op)
670 return True, "Op has padding=SAME"
671
672 @staticmethod
673 def constraint_resize(op):
674 """The width and height of the IFM and OFM must match one of the following criteria:
675 IFM W and H must both be 1
676 IFM must match OFM
677 OFM W and H must be 2x IFM -1, if align_corners is True
678 OFM W and H must be 2x IFM, if align_corners is False"""
679 # Easier to start with False condition as very few cases result in a supported resize
680 valid = False
681 ifm_shape = op.ifm.shape
682 ofm_shape = op.ofm.shape
683 align_corners = op.attrs.get("align_corners", False)
684 if len(ifm_shape) == 4:
685 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
686 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
687 valid = True
688 else:
689 upscaled_shape = np.array(ifm_shape[1:3])
690 out_shape = np.array(ofm_shape[1:3])
691 while (upscaled_shape < out_shape).all():
692 upscaled_shape *= 2
693 if align_corners:
694 upscaled_shape -= 1
695 # Valid if OFM is 2x IFM (-1 for align corners)
696 if np.array_equal(out_shape, upscaled_shape):
697 valid = True
698 break
699 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
700
701 @staticmethod
702 def constraint_matching_shapes(op):
703 "IFM and OFM shapes must match"
704 ifm_shape = op.ifm.shape
705 ofm_shape = op.ofm.shape
706 valid = ifm_shape == ofm_shape
707 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
708
709 @staticmethod
710 def constraint_splitv_inferred(op):
711 "Only one size is allowed to be inferred"
Jacob Bohline3de4e52020-11-27 14:52:06 +0100712 sizes = op.inputs[1].values
Michael McGeagh65fd9982020-10-20 11:49:28 +0100713 valid = np.count_nonzero(sizes == -1) <= 1
714 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
715
716 @staticmethod
717 def constraint_axis_exists(op):
718 "Axis attribute must exist"
719 axis = op.attrs.get("axis")
720 valid = axis is not None
721 return valid, f"Op has axis={axis}"
722
723 @staticmethod
724 def constraint_axis_valid(op):
725 "Axis attribute must be in the range [0, <ofm_dimensions>)"
726 dims = len(op.ofm.shape)
727 axis = op.attrs["axis"]
728 axis += dims if axis < 0 else 0
729 valid = 0 <= axis < dims
730 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
731
732 @staticmethod
733 def constraint_matching_dimensionality(op):
734 "All Input dimensionalities must match OFM dimensionality"
735 valid = True
736 extra = []
737 ofm_dim = len(op.ofm.shape)
738 tensors = [tens for tens in op.inputs if tens]
739 for tens in tensors:
740 dim = len(tens.shape)
741 if dim != ofm_dim:
742 valid = False
743 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
744 extra = ", ".join(extra)
745 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
746
747 @staticmethod
748 def constraint_valid_dimensions(op):
749 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
750 valid = True
751 extra = []
752 ofm_shape = op.ofm.shape
753 ofm_dim = len(ofm_shape)
754 axis = op.attrs["axis"]
755 axis += ofm_dim if axis < 0 else 0
756 tensors = [tens for tens in op.inputs if tens]
757 for tens in tensors:
758 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
759 valid = False
760 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
761 extra = ", ".join(extra)
762 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
763
764 @staticmethod
765 def constraint_stridedslice_input_count(op):
766 "Exactly 4 Input tensors are required"
767 inputs = len(op.inputs)
768 valid = inputs == 4
769 return valid, f"Op has {inputs} inputs"
770
771 @staticmethod
772 def constraint_stridedslice_inputs_const(op):
773 "Begin, End and Stride Input tensors must be constant"
774 valid = True
775 extra = []
776 _, begin, end, strides = op.inputs
777 if begin.values is None:
778 valid = False
779 extra.append(f"Begin tensor '{begin.name}'")
780 if end.values is None:
781 valid = False
782 extra.append(f"End tensor '{end.name}'")
783 if strides.values is None:
784 valid = False
785 extra.append(f"Stride tensor '{strides.name}'")
786 extra = ", ".join(extra)
787 return valid, f"Op has non-constant tensors: {extra}"
788
789 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100790 def constraint_stridedslice_stride_values(op):
791 "All Strides values must be 1"
792 strides = op.inputs[3]
793 valid = all(stride == 1 for stride in strides.values)
794 return valid, f"Op has strides values {strides.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100795
Michael McGeagh65fd9982020-10-20 11:49:28 +0100796 @staticmethod
797 def constraint_ellipsis_mask(op):
798 "ellipsis_mask must be 0"
799 ellipsis = op.attrs["ellipsis_mask"]
800 valid = ellipsis == 0
801 return valid, f"Op has ellipsis mask as: {ellipsis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200802
Michael McGeagh65fd9982020-10-20 11:49:28 +0100803 @staticmethod
804 def constraint_axis_masks(op):
805 "new_axis_mask and shrink_axis_mask cannot both be set"
806 new_axis = op.attrs["new_axis_mask"]
807 shrink_axis = op.attrs["shrink_axis_mask"]
808 valid = (new_axis == 0) or (shrink_axis == 0)
809 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200810
Michael McGeagh65fd9982020-10-20 11:49:28 +0100811 @staticmethod
812 def constraint_slice_ranges(op):
813 "Slice 'end' values must be greater than 'begin' values"
814 ifm, begin, end, _ = op.inputs
815 # Calculate offset begin/end
816 offset_begin = get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
817 offset_end = get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
818 # Check "end - begin" doesn't result in any zero or negative elements
819 valid = all((e - b) > 0 for b, e in zip(offset_begin, offset_end))
820 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100821
Michael McGeagh65fd9982020-10-20 11:49:28 +0100822 @staticmethod
823 def constraint_matching_inputs_types(op):
824 "Both Input data types must match"
825 ifm_dtype = op.ifm.dtype
826 ifm2_dtype = op.ifm2.dtype
827 valid = ifm_dtype == ifm2_dtype
828 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100829
Michael McGeagh65fd9982020-10-20 11:49:28 +0100830 @staticmethod
831 def constraint_matching_signed(op):
832 "For IFM that are signed, OFM must also be signed"
833 valid = True
834 ifm_dtype = op.ifm.dtype
835 ofm_dtype = op.ofm.dtype
836 if ifm_dtype.type & BaseType.Signed:
837 valid = bool(ofm_dtype.type & BaseType.Signed)
838 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100839
Michael McGeagh65fd9982020-10-20 11:49:28 +0100840 @staticmethod
841 def constraint_unsigned_valid(op):
842 "For IFM that are unsigned, OFM must either be the same type or int32"
843 valid = True
844 ifm_dtype = op.ifm.dtype
845 ofm_dtype = op.ofm.dtype
846 if ifm_dtype.type & BaseType.Unsigned:
847 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
848 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100849
Michael McGeagh65fd9982020-10-20 11:49:28 +0100850 @staticmethod
851 def constraint_inputs_int32(op):
852 "Both Input data types must be int32"
853 ifm_dtype = op.ifm.dtype
854 ifm2_dtype = op.ifm2.dtype
855 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
856 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100857
Michael McGeagh65fd9982020-10-20 11:49:28 +0100858 @staticmethod
859 def constraint_output_int32(op):
860 "OFM must be int32"
861 ofm_dtype = op.ofm.dtype
862 valid = ofm_dtype == DataType.int32
863 return valid, f"Op has ofm_dtype={ofm_dtype}"
Dwight Lidman42fed942020-05-29 09:37:03 +0200864
Michael McGeagh65fd9982020-10-20 11:49:28 +0100865 @staticmethod
866 def constraint_matching_quantization_parameters(op):
867 "Both Input quantization parameters must match OFM quantization parameters"
868 valid = True
869 extra = []
870 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
871 valid = False
872 extra.append(op.ifm.name)
873 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
874 valid = False
875 extra.append(op.ifm2.name)
876 extra = ", ".join(extra)
877 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200878
Michael McGeagh65fd9982020-10-20 11:49:28 +0100879 @staticmethod
880 def constraint_elemwise_batch_size(op):
881 "Batch size must be 1 for Input tensors with more than 2 dimensions"
882 valid = True
883 extra = []
884 for tens in (op.ifm, op.ifm2):
885 # Unary ops have ifm2 as None
886 if tens is not None:
887 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
888 valid = False
889 extra.append(tens.name)
890 extra = ", ".join(extra)
891 return valid, f"Op has invalid input tensors: {extra}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200892
Michael McGeagh65fd9982020-10-20 11:49:28 +0100893 @staticmethod
894 def constraint_matching_either_shapes(op):
895 "At least one Input's shape must match the OFM's shape"
896 ifm_shape = op.ifm.shape
897 ifm2_shape = op.ifm2.shape if op.ifm2 else None
898 ofm_shape = op.ofm.shape
899 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
900 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 +0200901
Michael McGeagh65fd9982020-10-20 11:49:28 +0100902 @staticmethod
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100903 def constraint_broadcast_shapes(op):
904 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
905 ifm_shape = op.ifm.shape
906 ifm2_shape = op.ifm2.shape if op.ifm2 else None
907 ofm_shape = op.ofm.shape
908 valid = True
909 if ifm_shape is not None and ifm2_shape is not None:
910 # align trailing dimensions
911 size = min(len(ifm_shape), len(ifm2_shape))
912 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
913 mi = max(i, i2)
914 # Input dimensions should match or one should be of dimension 1
915 # Output dimension should match the largest input dimension, together
916 # with constraint_match_either_shapes ensures broadcast from only one input
917 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
918 valid = False
919 break
920
921 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
922
923 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100924 def constraint_alpha_valid(op):
925 "Alpha must not be negative"
926 alpha = op.attrs["alpha"]
927 valid = alpha >= 0
928 return valid, f"Op has alpha={alpha}"