blob: ddfb8ed9d1106a2dbf4f49adeca673b8b15b5b12 [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
Tim Hall93582962020-09-09 21:58:15 +010027from .tensor import check_quantized_tens_scaling_equal
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020028
29
Michael McGeagh37ded342020-10-01 15:37:44 +010030# Custom decorator function to allow formatting docstrings containing "{}"
31def docstring_format_args(args):
32 def docstring(func):
33 func.__doc__ = func.__doc__.format(*args)
34 return func
35
36 return docstring
37
38
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020039def warn_cpu(op, msg):
40 print("Warning: {} {}, placing on CPU".format(op.type, msg))
Tim Hall79d07d22020-04-27 18:20:16 +010041
42
43class SupportedOperators:
Michael McGeagh1eeea512020-09-30 14:23:09 +010044 # Categorised lists of supported operators
Louis Verhaardaee5d752020-09-30 09:01:52 +020045 npu_pre_ops = set((Op.SplitSliceRead,))
46 convolution_ops = set((Op.Conv2DBias, Op.Conv2D, Op.QuantizedConv2D,))
47 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
48 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010049 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
Louis Verhaardaee5d752020-09-30 09:01:52 +020050 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
51 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
52 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
53 resizing_ops = set((Op.ResizeBilinear,))
54 fc_vector_products = set((Op.QuantizedMatMul, Op.MatMul, Op.FullyConnected,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010055 mac_main_ops = (
56 # RNN/LSTM/GRU
Louis Verhaardaee5d752020-09-30 09:01:52 +020057 set((Op.BlockLSTM,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010058 # conv/depthwiseconv/transposeconv
59 | convolution_like_ops
Michael McGeagh1eeea512020-09-30 14:23:09 +010060 # pooling
61 | pooling_ops
62 # resizing/upscaling
63 | resizing_ops
64 # FC layers
65 | fc_vector_products
66 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020067 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
68 binary_elem_wise_min_max_ops = set((Op.Minimum, Op.Maximum,))
69 binary_elem_wise_shift_ops = set((Op.SHL, Op.SHR,))
70 binary_elem_wise_add_mul_sub = set((Op.Add, Op.Mul, Op.Sub,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010071 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
72 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010073 supported_int32_tensor_ops = (
Louis Verhaardaee5d752020-09-30 09:01:52 +020074 set((Op.ReduceSum, Op.CLZ,)) | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010075 )
Michael McGeagh65fd9982020-10-20 11:49:28 +010076 relu_ops = Op.op_set(Op.is_relu_op)
77 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010078 npu_post_ops = (
Michael McGeagh1eeea512020-09-30 14:23:09 +010079 # activation functions
Louis Verhaardaee5d752020-09-30 09:01:52 +020080 activation_ops
81 # concatenation write direction
82 | set((Op.ConcatSliceWrite,))
83 # Quantization
84 | set((Op.Quantize,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010085 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020086 split_ops = set((Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack,))
87 concat_ops = set((Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack,))
88 memory_only_ops = set((Op.Squeeze, Op.Reshape, Op.QuantizedReshape, Op.ExpandDims,)) | concat_ops | split_ops
89 shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV,))
Michael McGeagh65fd9982020-10-20 11:49:28 +010090 supported_fused_activations = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.LUT,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010091 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 +010092 # Supported data types
93 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
94 supported_bias_dtypes = set((DataType.int32, DataType.int64))
Michael McGeagh37ded342020-10-01 15:37:44 +010095 # Defined ranges for allowed values:
96 tens_dim_range = (1, 65535)
Michael McGeagh1f951fc2020-10-14 09:30:02 +010097 stride_range = (1, 3)
98 dilation_range = (1, 2)
99 dilated_height_range = (1, 64)
100 dilated_product_range = (1, 64 * 64)
101 weights_limit = 127 * 65536
Michael McGeagh65fd9982020-10-20 11:49:28 +0100102 filter_range = (1, 8)
103 filter_height_range = (1, 256)
104 filter_product_range = (1, 256 * 256)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100105
Fredrik Svedberg880e7352020-08-25 11:31:47 +0200106 def __init__(self):
Michael McGeagh184b2502020-10-09 17:19:52 +0100107 # Setup the generic constraints. Note: the order matters
Michael McGeagh37ded342020-10-01 15:37:44 +0100108 self.generic_constraints = []
Michael McGeagh65fd9982020-10-20 11:49:28 +0100109 self.generic_constraints.append(SupportedOperators.constraint_tens_no_dynamic)
Michael McGeagh37ded342020-10-01 15:37:44 +0100110 self.generic_constraints.append(SupportedOperators.constraint_tens_defined_shape)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100111 self.generic_constraints.append(SupportedOperators.constraint_tens_output_scalar)
112 self.generic_constraints.append(SupportedOperators.constraint_tens_input_scalar)
Michael McGeagh37ded342020-10-01 15:37:44 +0100113 self.generic_constraints.append(SupportedOperators.constraint_tens_shape_size)
114 self.generic_constraints.append(SupportedOperators.constraint_tens_dtype)
Michael McGeagh184b2502020-10-09 17:19:52 +0100115 self.generic_constraints.append(SupportedOperators.constraint_tens_int32_ops)
Michael McGeagh37ded342020-10-01 15:37:44 +0100116 self.generic_constraints.append(SupportedOperators.constraint_tens_dimension)
Dwight Lidman8359a472020-09-28 15:53:40 +0200117 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_none_check)
Michael McGeagh184b2502020-10-09 17:19:52 +0100118 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_scale)
119 self.generic_constraints.append(SupportedOperators.constraint_faf)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100120
Michael McGeagh65fd9982020-10-20 11:49:28 +0100121 # Setup specific constraints. Note: the order matters
122 self.specific_constraints = defaultdict(list)
123
124 # Conv-like checks:
125 for op_type in SupportedOperators.convolution_like_ops:
126 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
127 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
128 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_type)
129 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_range)
130 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_height_range)
131 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_product_range)
132 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
133 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
134 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_limit)
135 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
136 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
137 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
138 # Depthwise Conv specific checks:
139 for op_type in SupportedOperators.depthwise_convolution_ops:
140 self.specific_constraints[op_type].append(SupportedOperators.constraint_depth_multiplier)
141 # Transpose Conv specific checks:
142 for op_type in SupportedOperators.transpose_convolution_ops:
143 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_stride)
144 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_same)
145 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_valid)
146
147 # Pooling checks:
148 for op_type in SupportedOperators.pooling_ops:
149 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
150 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
151 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
152 # AVG pooling specific checks:
153 for op_type in SupportedOperators.avg_pooling_ops:
154 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
155 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
156 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_range)
157 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range_valid_pad)
158 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range_valid_pad)
159 # MAX pooling specific checks:
160 for op_type in SupportedOperators.max_pooling_ops:
161 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
162 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
163 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range)
164 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range)
165 # TODO: Check ReduceSum restrictions
166
167 # Relu specific checks:
168 for op_type in SupportedOperators.relu_ops:
169 self.specific_constraints[op_type].append(SupportedOperators.constraint_quant_scale_inf)
170
171 # Resizing specific checks:
172 for op_type in SupportedOperators.resizing_ops:
173 self.specific_constraints[op_type].append(SupportedOperators.constraint_resize)
174
175 # Vector Product specific checks:
176 for op_type in SupportedOperators.fc_vector_products:
177 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
178 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
179 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
180 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
181
182 # Concat specific checks:
183 for op_type in (Op.Concat, Op.ConcatTFLite):
184 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_exists)
185 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_valid)
186 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_dimensionality)
187 self.specific_constraints[op_type].append(SupportedOperators.constraint_valid_dimensions)
188
189 # Element-wise checks:
190 for op_type in SupportedOperators.elem_wise_main_ops:
191 self.specific_constraints[op_type].append(SupportedOperators.constraint_elemwise_batch_size)
192 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_either_shapes)
193 # Unary specific checks:
194 for op_type in SupportedOperators.unary_elem_wise_main_ops:
195 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
196 # Binary Min/Max specific checks:
197 for op_type in SupportedOperators.binary_elem_wise_min_max_ops:
198 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
199 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_quantization_parameters)
200 # Binary Add/Mul/Sub specific checks:
201 for op_type in SupportedOperators.binary_elem_wise_add_mul_sub:
202 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_inputs_types)
203 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_signed)
204 self.specific_constraints[op_type].append(SupportedOperators.constraint_unsigned_valid)
205 # Binary Shift specific checks:
206 for op_type in SupportedOperators.binary_elem_wise_shift_ops:
207 self.specific_constraints[op_type].append(SupportedOperators.constraint_inputs_int32)
208
209 # SHL specific checks:
210 self.specific_constraints[Op.SHL].append(SupportedOperators.constraint_output_int32)
211
212 # CLZ specific checks:
213 self.specific_constraints[Op.CLZ].append(SupportedOperators.constraint_output_int32)
214
215 # Softmax specific checks:
216 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_shapes)
217 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_in_out_types)
218
219 # SplitV specific checks:
220 self.specific_constraints[Op.SplitV].append(SupportedOperators.constraint_splitv_inferred)
221
222 # StridedSlice specific checks:
223 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_input_count)
224 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_inputs_const)
225 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_tens_size_matches)
226 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_stride_values)
227 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_ellipsis_mask)
228 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_axis_masks)
229 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_slice_ranges)
230
231 # LeakyRelu specific checks:
232 self.specific_constraints[Op.LeakyRelu].append(SupportedOperators.constraint_alpha_valid)
Tim Hall79d07d22020-04-27 18:20:16 +0100233
234 def is_operator_supported(self, op):
Michael McGeagh1eeea512020-09-30 14:23:09 +0100235 if op.type not in SupportedOperators.supported_operators:
Louis Verhaard5f2ea2f2020-10-15 08:39:44 +0200236 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100237 print(f"Info: {op.type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
Tim Hall79d07d22020-04-27 18:20:16 +0100238 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100239
Michael McGeagh65fd9982020-10-20 11:49:28 +0100240 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
Michael McGeagh37ded342020-10-01 15:37:44 +0100241 valid, extra = constraint(op)
242 if not valid:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100243 print(f"Warning: {op.type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
244 print(f" - {constraint.__doc__}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100245 if extra:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100246 print(f" {extra}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100247 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100248
Tim Hall79d07d22020-04-27 18:20:16 +0100249 return True
250
Michael McGeagh37ded342020-10-01 15:37:44 +0100251 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100252 def constraint_tens_no_dynamic(op):
253 "Input(s) and Output tensors must not be dynamic"
254 valid = True
255 extra = []
256 tensors = [tens for tens in op.inputs + op.outputs if tens]
257 for tens in tensors:
258 if (tens.shape == []) and (tens.values is None):
259 valid = False
260 extra.append(tens.name)
261 extra = ", ".join(extra)
262 return valid, f"Op has dynamic tensor(s): {extra}"
263
264 @staticmethod
Michael McGeagh37ded342020-10-01 15:37:44 +0100265 def constraint_tens_defined_shape(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100266 "Input(s) and Output tensors must have a defined shape"
Michael McGeagh37ded342020-10-01 15:37:44 +0100267 valid = True
268 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100269 tensors = [tens for tens in op.inputs + op.outputs if tens]
270 for tens in tensors:
271 if not tens.has_fully_defined_shape():
272 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100273 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100274 return valid, ", ".join(extra)
Michael McGeagh37ded342020-10-01 15:37:44 +0100275
Michael McGeagh184b2502020-10-09 17:19:52 +0100276 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100277 def constraint_tens_output_scalar(op):
278 "Output tensors cannot be scalar"
279 ofm = op.ofm
280 valid = ofm.shape != []
281 return valid, f"Output Tensor '{ofm.name}' is scalar"
Michael McGeagh184b2502020-10-09 17:19:52 +0100282
283 @classmethod
284 @docstring_format_args([shapeless_input_ops])
Michael McGeagh65fd9982020-10-20 11:49:28 +0100285 def constraint_tens_input_scalar(cls, op):
286 "Scalar Input tensors are only valid for op type: {}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100287 valid = True
288 extra = []
289 tensors = [tens for tens in op.inputs if tens]
290 for tens in tensors:
291 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
292 valid = False
293 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100294 extra = ", ".join(extra)
295 return valid, f"Op has scalar input tensor(s): {extra}"
Tim Hall79d07d22020-04-27 18:20:16 +0100296
Michael McGeagh37ded342020-10-01 15:37:44 +0100297 @staticmethod
298 def constraint_tens_shape_size(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100299 "Input(s) and Output tensors must not be greater than 4D"
Michael McGeagh37ded342020-10-01 15:37:44 +0100300 valid = True
301 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100302 tensors = [tens for tens in op.inputs + op.outputs if tens]
303 for tens in tensors:
304 if len(tens.shape) > 4:
305 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100306 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100307 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100308
Michael McGeagh37ded342020-10-01 15:37:44 +0100309 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100310 @docstring_format_args([supported_op_dtypes])
Michael McGeagh37ded342020-10-01 15:37:44 +0100311 def constraint_tens_dtype(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100312 "Tensors must be of type: {}"
Michael McGeagh37ded342020-10-01 15:37:44 +0100313 valid = True
314 extra = []
315 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100316 if not tensors:
317 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100318 for tens in tensors:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100319 if tens.dtype not in cls.supported_op_dtypes:
Michael McGeagh184b2502020-10-09 17:19:52 +0100320 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100321 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100322 return valid, ", ".join(extra)
323
324 @classmethod
325 @docstring_format_args([supported_int32_tensor_ops])
326 def constraint_tens_int32_ops(cls, op):
327 "Tensors which are int32 are only valid when op type is: {}"
328 valid = True
329 extra = []
330 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100331 if not tensors:
332 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh184b2502020-10-09 17:19:52 +0100333 for tens in tensors:
334 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
335 valid = False
336 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100337 extra = ", ".join(extra)
338 return valid, f"Op has int32 tensor(s): {extra}"
Andreas Nevalaineneadb1662020-09-01 15:36:26 +0200339
Michael McGeagh37ded342020-10-01 15:37:44 +0100340 @classmethod
341 @docstring_format_args(tens_dim_range)
342 def constraint_tens_dimension(cls, op):
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100343 "Tensor dimensions must be in the range [{}, {}]"
Michael McGeagh37ded342020-10-01 15:37:44 +0100344 tens_min, tens_max = cls.tens_dim_range
345 valid = True
346 extra = []
347 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100348 if not tensors:
349 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100350 for tens in tensors:
Michael McGeagh184b2502020-10-09 17:19:52 +0100351 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
352 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100353 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100354 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100355
Dwight Lidman8359a472020-09-28 15:53:40 +0200356 @staticmethod
357 def constraint_tens_quant_none_check(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100358 "Input(s), Output and Weight tensors must have quantization parameters"
Dwight Lidman8359a472020-09-28 15:53:40 +0200359 valid = True
360 extra = []
361 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
362 for tens in tensors:
363 if tens.quantization is None:
364 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100365 extra.append(tens.name)
366 extra = ", ".join(extra)
367 return valid, f"Op has tensors with missing quantization parameters: {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200368
Michael McGeagh184b2502020-10-09 17:19:52 +0100369 @staticmethod
370 def constraint_tens_quant_scale(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100371 "Input(s), Output and Weight tensors with quantization scales must be finite"
Michael McGeagh184b2502020-10-09 17:19:52 +0100372 valid = True
373 extra = []
374 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
375 for tens in tensors:
376 if (tens.quantization.scale_f32 is not None) and np.isinf(tens.quantization.scale_f32).any():
377 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100378 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100379 return valid, ", ".join(extra)
380
381 @classmethod
382 @docstring_format_args([supported_fused_activations])
383 def constraint_faf(cls, op):
384 "The fused activation function (if present) must be one of type: {}"
385 faf = op.activation
386 valid = (faf is None) or (faf in cls.supported_fused_activations)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100387 return valid, f"Op has its fused activation function as: {faf}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100388
389 @staticmethod
390 def constraint_stride_type(op):
391 "Stride values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100392 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100393 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100394 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100395
Michael McGeagh1eeea512020-09-30 14:23:09 +0100396 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100397 @docstring_format_args(stride_range)
398 def constraint_stride_range(cls, op):
399 "Stride values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100400 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100401 stride_min, stride_max = cls.stride_range
402 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100403 return valid, f"Op has stride WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100404
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100405 @staticmethod
406 def constraint_dilation_type(op):
407 "Dilation factor values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100408 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100409 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100410 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100411
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100412 @classmethod
413 @docstring_format_args(dilation_range)
414 def constraint_dilation_range(cls, op):
415 "Dilation factor values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100416 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100417 dilation_min, dilation_max = cls.dilation_range
418 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100419 return valid, f"Op has dilation factor WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100420
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100421 @classmethod
422 @docstring_format_args(dilated_height_range)
423 def constraint_dilated_height_range(cls, op):
424 "Dilated kernel height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100425 h = op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100426 dilated_height_min, dilated_height_max = cls.dilated_height_range
427 valid = dilated_height_min <= h <= dilated_height_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100428 return valid, f"Op has dilated kernel height as: {h}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200429
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100430 @classmethod
431 @docstring_format_args(dilated_product_range)
432 def constraint_dilated_product_range(cls, op):
433 "Product of dilated kernel width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100434 product = op.kernel.area_width() * op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100435 dilated_product_min, dilated_product_max = cls.dilated_product_range
436 valid = dilated_product_min <= product <= dilated_product_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100437 return valid, f"Op has product of dilated kernel width and height as: {product}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200438
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100439 @staticmethod
440 def constraint_weights_type(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100441 "Weight tensor must be 8-bit"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100442 weights = op.weights
443 valid = weights.element_size() == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100444 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200445
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100446 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100447 def constraint_weights_const(op):
448 "Weight tensor must be constant"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100449 weights = op.weights
450 valid = weights.values is not None
Michael McGeagh65fd9982020-10-20 11:49:28 +0100451 return valid, f"Tensor '{weights.name}' has non-constant values"
Andreas Nevalainen8854dc92020-09-24 13:43:00 +0200452
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100453 @classmethod
454 @docstring_format_args([weights_limit])
455 def constraint_weights_limit(cls, op):
456 "The sum of the weights cannot exceed {}"
457 weights = op.weights
458 values = weights.quant_values.astype(np.int64) - weights.quantization.zero_point
459 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
460 valid = limit <= cls.weights_limit
Michael McGeagh65fd9982020-10-20 11:49:28 +0100461 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200462
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100463 @classmethod
464 @docstring_format_args([supported_bias_dtypes])
465 def constraint_bias_type(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100466 "Optional Bias tensor must be of type: {}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100467 bias = op.bias
468 if bias:
469 valid = bias.dtype in cls.supported_bias_dtypes
Michael McGeagh65fd9982020-10-20 11:49:28 +0100470 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
471 return True, "Op has no bias tensor"
Tim Hall79d07d22020-04-27 18:20:16 +0100472
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100473 @staticmethod
474 def constraint_bias_40bit(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100475 "Optional Bias tensor values must fit within 40-bits"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100476 bias = op.bias
477 if bias and bias.dtype == DataType.int64:
478 valid = all(len(bin(quant_value)[2:]) <= 40 for quant_value in bias.quant_values)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100479 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
480 return True, "Op has no bias tensor, or it fits in 40-bit"
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200481
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100482 @staticmethod
483 def constraint_batch_size(op):
484 "IFM Tensor batch size must be 1"
485 ifm = op.ifm
486 valid = ifm.shape[0] == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100487 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
488
489 @staticmethod
490 def constraint_quant_scale_inf(op):
491 "The IFM quantization scale divided by the OFM quantization scale must not be infinite"
492 ifm_scale = op.ifm.quantization.scale_f32
493 ofm_scale = op.ofm.quantization.scale_f32
494 valid = not np.isinf(ifm_scale / ofm_scale)
495 return valid, f"Op has infinite quantization scale. ifm_scale={ifm_scale} ofm_scale={ofm_scale}"
496
497 @staticmethod
498 def constraint_depth_multiplier(op):
499 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
500 depth_multiplier = op.attrs.get("depth_multiplier", 1)
501 if depth_multiplier > 1:
502 ifm_channels = op.ifm.shape[3]
503 ofm_channels = op.ofm.shape[3]
504 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
505 extra = (
506 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
507 f" and depth_multiplier={depth_multiplier}"
508 )
509 return valid, extra
510 return True, "Op has depth_multiplier=1"
511
512 @staticmethod
513 def constraint_tconv_stride(op):
514 "Stride values for both width and height must be 2"
515 w = op.kernel.stride.x
516 h = op.kernel.stride.y
517 valid = (w == 2) and (h == 2)
518 return valid, f"Op has stride WxH as: {w}x{h}"
519
520 @staticmethod
521 def constraint_tconv_same(op):
522 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
523 if op.attrs["padding"] == b"SAME":
524 w = op.kernel.stride.x
525 h = op.kernel.stride.y
526 ifm_shape = op.ifm.shape
527 ofm_shape = op.ofm.shape
528 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
529 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
530 return True, "Op has padding=VALID"
531
532 @staticmethod
533 def constraint_tconv_valid(op):
534 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
535 minus difference between kernel size and stride"""
536 if op.attrs["padding"] == b"VALID":
537 s_w = op.kernel.stride.x
538 s_h = op.kernel.stride.y
539 k_w = op.kernel.width
540 k_h = op.kernel.height
541 ifm_shape = op.ifm.shape
542 ofm_shape = op.ofm.shape
543 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
544 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
545 valid = height_check and width_check
546 extra = (
547 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
548 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
549 )
550 return valid, extra
551 return True, "Op has padding=SAME"
552
553 @staticmethod
554 def constraint_matching_in_out_types(op):
555 "IFM and OFM data types must match"
556 ifm_dtype = op.ifm.dtype
557 ofm_dtype = op.ofm.dtype
558 valid = ifm_dtype == ofm_dtype
559 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
560
561 @staticmethod
562 def constraint_filter_type(op):
563 "Kernel filter values for both width and height must be integer types"
564 w = op.kernel.width
565 h = op.kernel.height
566 valid = is_integer(w) and is_integer(h)
567 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
568
569 @classmethod
570 @docstring_format_args(filter_range)
571 def constraint_filter_range(cls, op):
572 "Kernel filter values for both width and height must be in the range [{}, {}]"
573 if op.attrs["padding"] == b"SAME":
574 w = op.kernel.width
575 h = op.kernel.height
576 filter_min, filter_max = cls.filter_range
577 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
578 return valid, f"Op has kernel filter WxH as: {w}x{h}"
579 return True, "Op has padding=VALID"
580
581 @classmethod
582 @docstring_format_args(filter_height_range)
583 def constraint_filter_height_range(cls, op):
584 "Kernel filter height must be in the range [{}, {}]"
585 h = op.kernel.height
586 filter_height_min, filter_height_max = cls.filter_height_range
587 valid = filter_height_min <= h <= filter_height_max
588 return valid, f"Op has kernel filter height as: {h}"
589
590 @classmethod
591 @docstring_format_args(filter_product_range)
592 def constraint_filter_product_range(cls, op):
593 "Product of kernel filter width and height must be in the range [{}, {}]"
594 product = op.kernel.elements_wh()
595 filter_product_min, filter_product_max = cls.filter_product_range
596 valid = filter_product_min <= product <= filter_product_max
597 return valid, f"Op has product of kernel filter width and height as: {product}"
598
599 @staticmethod
600 @docstring_format_args(filter_height_range)
601 def constraint_filter_height_range_valid_pad(op):
602 "VALID padding: Kernel filter height must be in the range [{}, {}]"
603 if op.attrs["padding"] == b"VALID":
604 return SupportedOperators.constraint_filter_height_range(op)
605 return True, "Op has padding=SAME"
606
607 @staticmethod
608 @docstring_format_args(filter_product_range)
609 def constraint_filter_product_range_valid_pad(op):
610 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
611 if op.attrs["padding"] == b"VALID":
612 return SupportedOperators.constraint_filter_product_range(op)
613 return True, "Op has padding=SAME"
614
615 @staticmethod
616 def constraint_resize(op):
617 """The width and height of the IFM and OFM must match one of the following criteria:
618 IFM W and H must both be 1
619 IFM must match OFM
620 OFM W and H must be 2x IFM -1, if align_corners is True
621 OFM W and H must be 2x IFM, if align_corners is False"""
622 # Easier to start with False condition as very few cases result in a supported resize
623 valid = False
624 ifm_shape = op.ifm.shape
625 ofm_shape = op.ofm.shape
626 align_corners = op.attrs.get("align_corners", False)
627 if len(ifm_shape) == 4:
628 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
629 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
630 valid = True
631 else:
632 upscaled_shape = np.array(ifm_shape[1:3])
633 out_shape = np.array(ofm_shape[1:3])
634 while (upscaled_shape < out_shape).all():
635 upscaled_shape *= 2
636 if align_corners:
637 upscaled_shape -= 1
638 # Valid if OFM is 2x IFM (-1 for align corners)
639 if np.array_equal(out_shape, upscaled_shape):
640 valid = True
641 break
642 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
643
644 @staticmethod
645 def constraint_matching_shapes(op):
646 "IFM and OFM shapes must match"
647 ifm_shape = op.ifm.shape
648 ofm_shape = op.ofm.shape
649 valid = ifm_shape == ofm_shape
650 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
651
652 @staticmethod
653 def constraint_splitv_inferred(op):
654 "Only one size is allowed to be inferred"
655 sizes = op.ifm2.values
656 valid = np.count_nonzero(sizes == -1) <= 1
657 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
658
659 @staticmethod
660 def constraint_axis_exists(op):
661 "Axis attribute must exist"
662 axis = op.attrs.get("axis")
663 valid = axis is not None
664 return valid, f"Op has axis={axis}"
665
666 @staticmethod
667 def constraint_axis_valid(op):
668 "Axis attribute must be in the range [0, <ofm_dimensions>)"
669 dims = len(op.ofm.shape)
670 axis = op.attrs["axis"]
671 axis += dims if axis < 0 else 0
672 valid = 0 <= axis < dims
673 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
674
675 @staticmethod
676 def constraint_matching_dimensionality(op):
677 "All Input dimensionalities must match OFM dimensionality"
678 valid = True
679 extra = []
680 ofm_dim = len(op.ofm.shape)
681 tensors = [tens for tens in op.inputs if tens]
682 for tens in tensors:
683 dim = len(tens.shape)
684 if dim != ofm_dim:
685 valid = False
686 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
687 extra = ", ".join(extra)
688 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
689
690 @staticmethod
691 def constraint_valid_dimensions(op):
692 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
693 valid = True
694 extra = []
695 ofm_shape = op.ofm.shape
696 ofm_dim = len(ofm_shape)
697 axis = op.attrs["axis"]
698 axis += ofm_dim if axis < 0 else 0
699 tensors = [tens for tens in op.inputs if tens]
700 for tens in tensors:
701 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
702 valid = False
703 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
704 extra = ", ".join(extra)
705 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
706
707 @staticmethod
708 def constraint_stridedslice_input_count(op):
709 "Exactly 4 Input tensors are required"
710 inputs = len(op.inputs)
711 valid = inputs == 4
712 return valid, f"Op has {inputs} inputs"
713
714 @staticmethod
715 def constraint_stridedslice_inputs_const(op):
716 "Begin, End and Stride Input tensors must be constant"
717 valid = True
718 extra = []
719 _, begin, end, strides = op.inputs
720 if begin.values is None:
721 valid = False
722 extra.append(f"Begin tensor '{begin.name}'")
723 if end.values is None:
724 valid = False
725 extra.append(f"End tensor '{end.name}'")
726 if strides.values is None:
727 valid = False
728 extra.append(f"Stride tensor '{strides.name}'")
729 extra = ", ".join(extra)
730 return valid, f"Op has non-constant tensors: {extra}"
731
732 @staticmethod
733 def constraint_stridedslice_tens_size_matches(op):
734 "All Input sizes must match OFM size"
735 ifm, begin, end, strides = op.inputs
736 ifm_size = len(ifm.shape)
737 ofm_size = len(op.ofm.shape)
738 begin_size = len(begin.values)
739 end_size = len(end.values)
740 strides_size = len(strides.values)
741 valid = ifm_size == ofm_size == begin_size == end_size == strides_size
742 extra = (
743 f"Op has ofm_size={ofm_size}, ifm_size={ifm_size},"
744 f" begin_size={begin_size}, end_size={end_size} and strides_size={strides_size}"
745 )
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100746 return valid, extra
Tim Hall79d07d22020-04-27 18:20:16 +0100747
Michael McGeagh65fd9982020-10-20 11:49:28 +0100748 @staticmethod
749 def constraint_stridedslice_stride_values(op):
750 "All Strides values must be 1"
751 strides = op.inputs[3]
752 valid = all(stride == 1 for stride in strides.values)
753 return valid, f"Op has strides values {strides.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100754
Michael McGeagh65fd9982020-10-20 11:49:28 +0100755 @staticmethod
756 def constraint_ellipsis_mask(op):
757 "ellipsis_mask must be 0"
758 ellipsis = op.attrs["ellipsis_mask"]
759 valid = ellipsis == 0
760 return valid, f"Op has ellipsis mask as: {ellipsis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200761
Michael McGeagh65fd9982020-10-20 11:49:28 +0100762 @staticmethod
763 def constraint_axis_masks(op):
764 "new_axis_mask and shrink_axis_mask cannot both be set"
765 new_axis = op.attrs["new_axis_mask"]
766 shrink_axis = op.attrs["shrink_axis_mask"]
767 valid = (new_axis == 0) or (shrink_axis == 0)
768 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200769
Michael McGeagh65fd9982020-10-20 11:49:28 +0100770 @staticmethod
771 def constraint_slice_ranges(op):
772 "Slice 'end' values must be greater than 'begin' values"
773 ifm, begin, end, _ = op.inputs
774 # Calculate offset begin/end
775 offset_begin = get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
776 offset_end = get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
777 # Check "end - begin" doesn't result in any zero or negative elements
778 valid = all((e - b) > 0 for b, e in zip(offset_begin, offset_end))
779 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100780
Michael McGeagh65fd9982020-10-20 11:49:28 +0100781 @staticmethod
782 def constraint_matching_inputs_types(op):
783 "Both Input data types must match"
784 ifm_dtype = op.ifm.dtype
785 ifm2_dtype = op.ifm2.dtype
786 valid = ifm_dtype == ifm2_dtype
787 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100788
Michael McGeagh65fd9982020-10-20 11:49:28 +0100789 @staticmethod
790 def constraint_matching_signed(op):
791 "For IFM that are signed, OFM must also be signed"
792 valid = True
793 ifm_dtype = op.ifm.dtype
794 ofm_dtype = op.ofm.dtype
795 if ifm_dtype.type & BaseType.Signed:
796 valid = bool(ofm_dtype.type & BaseType.Signed)
797 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100798
Michael McGeagh65fd9982020-10-20 11:49:28 +0100799 @staticmethod
800 def constraint_unsigned_valid(op):
801 "For IFM that are unsigned, OFM must either be the same type or int32"
802 valid = True
803 ifm_dtype = op.ifm.dtype
804 ofm_dtype = op.ofm.dtype
805 if ifm_dtype.type & BaseType.Unsigned:
806 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
807 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100808
Michael McGeagh65fd9982020-10-20 11:49:28 +0100809 @staticmethod
810 def constraint_inputs_int32(op):
811 "Both Input data types must be int32"
812 ifm_dtype = op.ifm.dtype
813 ifm2_dtype = op.ifm2.dtype
814 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
815 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100816
Michael McGeagh65fd9982020-10-20 11:49:28 +0100817 @staticmethod
818 def constraint_output_int32(op):
819 "OFM must be int32"
820 ofm_dtype = op.ofm.dtype
821 valid = ofm_dtype == DataType.int32
822 return valid, f"Op has ofm_dtype={ofm_dtype}"
Dwight Lidman42fed942020-05-29 09:37:03 +0200823
Michael McGeagh65fd9982020-10-20 11:49:28 +0100824 @staticmethod
825 def constraint_matching_quantization_parameters(op):
826 "Both Input quantization parameters must match OFM quantization parameters"
827 valid = True
828 extra = []
829 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
830 valid = False
831 extra.append(op.ifm.name)
832 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
833 valid = False
834 extra.append(op.ifm2.name)
835 extra = ", ".join(extra)
836 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200837
Michael McGeagh65fd9982020-10-20 11:49:28 +0100838 @staticmethod
839 def constraint_elemwise_batch_size(op):
840 "Batch size must be 1 for Input tensors with more than 2 dimensions"
841 valid = True
842 extra = []
843 for tens in (op.ifm, op.ifm2):
844 # Unary ops have ifm2 as None
845 if tens is not None:
846 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
847 valid = False
848 extra.append(tens.name)
849 extra = ", ".join(extra)
850 return valid, f"Op has invalid input tensors: {extra}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200851
Michael McGeagh65fd9982020-10-20 11:49:28 +0100852 @staticmethod
853 def constraint_matching_either_shapes(op):
854 "At least one Input's shape must match the OFM's shape"
855 ifm_shape = op.ifm.shape
856 ifm2_shape = op.ifm2.shape if op.ifm2 else None
857 ofm_shape = op.ofm.shape
858 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
859 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 +0200860
Michael McGeagh65fd9982020-10-20 11:49:28 +0100861 @staticmethod
862 def constraint_alpha_valid(op):
863 "Alpha must not be negative"
864 alpha = op.attrs["alpha"]
865 valid = alpha >= 0
866 return valid, f"Op has alpha={alpha}"