blob: 04cda1dad3081b5bc5dee744ba30d9e9e23d9f29 [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
Michael McGeagh219ec072020-11-09 11:11:26 +000028from .tflite_mapping import optype_to_builtintype
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020029
30
Michael McGeagh37ded342020-10-01 15:37:44 +010031# Custom decorator function to allow formatting docstrings containing "{}"
32def docstring_format_args(args):
33 def docstring(func):
34 func.__doc__ = func.__doc__.format(*args)
35 return func
36
37 return docstring
38
39
Tim Hall79d07d22020-04-27 18:20:16 +010040class SupportedOperators:
Michael McGeagh1eeea512020-09-30 14:23:09 +010041 # Categorised lists of supported operators
Louis Verhaardaee5d752020-09-30 09:01:52 +020042 npu_pre_ops = set((Op.SplitSliceRead,))
43 convolution_ops = set((Op.Conv2DBias, Op.Conv2D, Op.QuantizedConv2D,))
44 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
45 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010046 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
Louis Verhaardaee5d752020-09-30 09:01:52 +020047 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
48 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
49 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
50 resizing_ops = set((Op.ResizeBilinear,))
51 fc_vector_products = set((Op.QuantizedMatMul, Op.MatMul, Op.FullyConnected,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010052 mac_main_ops = (
53 # RNN/LSTM/GRU
Louis Verhaardaee5d752020-09-30 09:01:52 +020054 set((Op.BlockLSTM,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010055 # conv/depthwiseconv/transposeconv
56 | convolution_like_ops
Michael McGeagh1eeea512020-09-30 14:23:09 +010057 # pooling
58 | pooling_ops
59 # resizing/upscaling
60 | resizing_ops
61 # FC layers
62 | fc_vector_products
63 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020064 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
65 binary_elem_wise_min_max_ops = set((Op.Minimum, Op.Maximum,))
66 binary_elem_wise_shift_ops = set((Op.SHL, Op.SHR,))
67 binary_elem_wise_add_mul_sub = set((Op.Add, Op.Mul, Op.Sub,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010068 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
69 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010070 supported_int32_tensor_ops = (
Louis Verhaardaee5d752020-09-30 09:01:52 +020071 set((Op.ReduceSum, Op.CLZ,)) | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010072 )
Michael McGeagh65fd9982020-10-20 11:49:28 +010073 relu_ops = Op.op_set(Op.is_relu_op)
74 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010075 npu_post_ops = (
Michael McGeagh1eeea512020-09-30 14:23:09 +010076 # activation functions
Louis Verhaardaee5d752020-09-30 09:01:52 +020077 activation_ops
78 # concatenation write direction
79 | set((Op.ConcatSliceWrite,))
80 # Quantization
81 | set((Op.Quantize,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010082 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020083 split_ops = set((Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack,))
84 concat_ops = set((Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack,))
85 memory_only_ops = set((Op.Squeeze, Op.Reshape, Op.QuantizedReshape, Op.ExpandDims,)) | concat_ops | split_ops
86 shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV,))
Michael McGeagh65fd9982020-10-20 11:49:28 +010087 supported_fused_activations = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.LUT,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010088 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 +010089 # Supported data types
90 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
91 supported_bias_dtypes = set((DataType.int32, DataType.int64))
Michael McGeagh37ded342020-10-01 15:37:44 +010092 # Defined ranges for allowed values:
93 tens_dim_range = (1, 65535)
Michael McGeagh1f951fc2020-10-14 09:30:02 +010094 stride_range = (1, 3)
95 dilation_range = (1, 2)
96 dilated_height_range = (1, 64)
97 dilated_product_range = (1, 64 * 64)
98 weights_limit = 127 * 65536
Michael McGeagh65fd9982020-10-20 11:49:28 +010099 filter_range = (1, 8)
100 filter_height_range = (1, 256)
101 filter_product_range = (1, 256 * 256)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100102
Fredrik Svedberg880e7352020-08-25 11:31:47 +0200103 def __init__(self):
Michael McGeagh184b2502020-10-09 17:19:52 +0100104 # Setup the generic constraints. Note: the order matters
Michael McGeagh37ded342020-10-01 15:37:44 +0100105 self.generic_constraints = []
Michael McGeagh65fd9982020-10-20 11:49:28 +0100106 self.generic_constraints.append(SupportedOperators.constraint_tens_no_dynamic)
Michael McGeagh37ded342020-10-01 15:37:44 +0100107 self.generic_constraints.append(SupportedOperators.constraint_tens_defined_shape)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100108 self.generic_constraints.append(SupportedOperators.constraint_tens_output_scalar)
109 self.generic_constraints.append(SupportedOperators.constraint_tens_input_scalar)
Michael McGeagh37ded342020-10-01 15:37:44 +0100110 self.generic_constraints.append(SupportedOperators.constraint_tens_shape_size)
111 self.generic_constraints.append(SupportedOperators.constraint_tens_dtype)
Michael McGeagh184b2502020-10-09 17:19:52 +0100112 self.generic_constraints.append(SupportedOperators.constraint_tens_int32_ops)
Michael McGeagh37ded342020-10-01 15:37:44 +0100113 self.generic_constraints.append(SupportedOperators.constraint_tens_dimension)
Dwight Lidman8359a472020-09-28 15:53:40 +0200114 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_none_check)
Michael McGeagh184b2502020-10-09 17:19:52 +0100115 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_scale)
116 self.generic_constraints.append(SupportedOperators.constraint_faf)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100117
Michael McGeagh65fd9982020-10-20 11:49:28 +0100118 # Setup specific constraints. Note: the order matters
119 self.specific_constraints = defaultdict(list)
120
121 # Conv-like checks:
122 for op_type in SupportedOperators.convolution_like_ops:
123 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
124 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
125 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_type)
126 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_range)
127 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_height_range)
128 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_product_range)
129 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
130 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
131 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_limit)
132 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
133 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
134 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
135 # Depthwise Conv specific checks:
136 for op_type in SupportedOperators.depthwise_convolution_ops:
137 self.specific_constraints[op_type].append(SupportedOperators.constraint_depth_multiplier)
138 # Transpose Conv specific checks:
139 for op_type in SupportedOperators.transpose_convolution_ops:
140 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_stride)
141 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_same)
142 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_valid)
143
144 # Pooling checks:
145 for op_type in SupportedOperators.pooling_ops:
146 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
147 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
148 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
149 # AVG pooling specific checks:
150 for op_type in SupportedOperators.avg_pooling_ops:
151 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
152 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
153 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_range)
154 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range_valid_pad)
155 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range_valid_pad)
156 # MAX pooling specific checks:
157 for op_type in SupportedOperators.max_pooling_ops:
158 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
159 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
160 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range)
161 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range)
162 # TODO: Check ReduceSum restrictions
163
164 # Relu specific checks:
165 for op_type in SupportedOperators.relu_ops:
166 self.specific_constraints[op_type].append(SupportedOperators.constraint_quant_scale_inf)
167
168 # Resizing specific checks:
169 for op_type in SupportedOperators.resizing_ops:
170 self.specific_constraints[op_type].append(SupportedOperators.constraint_resize)
171
172 # Vector Product specific checks:
173 for op_type in SupportedOperators.fc_vector_products:
174 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
175 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
176 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
177 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
178
179 # Concat specific checks:
180 for op_type in (Op.Concat, Op.ConcatTFLite):
181 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_exists)
182 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_valid)
183 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_dimensionality)
184 self.specific_constraints[op_type].append(SupportedOperators.constraint_valid_dimensions)
185
186 # Element-wise checks:
187 for op_type in SupportedOperators.elem_wise_main_ops:
188 self.specific_constraints[op_type].append(SupportedOperators.constraint_elemwise_batch_size)
189 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_either_shapes)
190 # Unary specific checks:
191 for op_type in SupportedOperators.unary_elem_wise_main_ops:
192 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
193 # Binary Min/Max specific checks:
194 for op_type in SupportedOperators.binary_elem_wise_min_max_ops:
195 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
196 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_quantization_parameters)
197 # Binary Add/Mul/Sub specific checks:
198 for op_type in SupportedOperators.binary_elem_wise_add_mul_sub:
199 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_inputs_types)
200 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_signed)
201 self.specific_constraints[op_type].append(SupportedOperators.constraint_unsigned_valid)
202 # Binary Shift specific checks:
203 for op_type in SupportedOperators.binary_elem_wise_shift_ops:
204 self.specific_constraints[op_type].append(SupportedOperators.constraint_inputs_int32)
205
206 # SHL specific checks:
207 self.specific_constraints[Op.SHL].append(SupportedOperators.constraint_output_int32)
208
209 # CLZ specific checks:
210 self.specific_constraints[Op.CLZ].append(SupportedOperators.constraint_output_int32)
211
212 # Softmax specific checks:
213 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_shapes)
214 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_in_out_types)
215
216 # SplitV specific checks:
217 self.specific_constraints[Op.SplitV].append(SupportedOperators.constraint_splitv_inferred)
218
219 # StridedSlice specific checks:
220 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_input_count)
221 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_inputs_const)
222 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_tens_size_matches)
223 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_stride_values)
224 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_ellipsis_mask)
225 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_axis_masks)
226 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_slice_ranges)
227
228 # LeakyRelu specific checks:
229 self.specific_constraints[Op.LeakyRelu].append(SupportedOperators.constraint_alpha_valid)
Tim Hall79d07d22020-04-27 18:20:16 +0100230
231 def is_operator_supported(self, op):
Michael McGeagh219ec072020-11-09 11:11:26 +0000232 ext_type = optype_to_builtintype(op.type)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100233 if op.type not in SupportedOperators.supported_operators:
Louis Verhaard5f2ea2f2020-10-15 08:39:44 +0200234 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
Michael McGeagh219ec072020-11-09 11:11:26 +0000235 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
Tim Hall79d07d22020-04-27 18:20:16 +0100236 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100237
Michael McGeagh65fd9982020-10-20 11:49:28 +0100238 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
Michael McGeagh37ded342020-10-01 15:37:44 +0100239 valid, extra = constraint(op)
240 if not valid:
Michael McGeagh219ec072020-11-09 11:11:26 +0000241 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
Michael McGeagh65fd9982020-10-20 11:49:28 +0100242 print(f" - {constraint.__doc__}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100243 if extra:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100244 print(f" {extra}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100245 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100246
Tim Hall79d07d22020-04-27 18:20:16 +0100247 return True
248
Michael McGeagh37ded342020-10-01 15:37:44 +0100249 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100250 def constraint_tens_no_dynamic(op):
251 "Input(s) and Output tensors must not be dynamic"
252 valid = True
253 extra = []
254 tensors = [tens for tens in op.inputs + op.outputs if tens]
255 for tens in tensors:
256 if (tens.shape == []) and (tens.values is None):
257 valid = False
258 extra.append(tens.name)
259 extra = ", ".join(extra)
260 return valid, f"Op has dynamic tensor(s): {extra}"
261
262 @staticmethod
Michael McGeagh37ded342020-10-01 15:37:44 +0100263 def constraint_tens_defined_shape(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100264 "Input(s) and Output tensors must have a defined shape"
Michael McGeagh37ded342020-10-01 15:37:44 +0100265 valid = True
266 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100267 tensors = [tens for tens in op.inputs + op.outputs if tens]
268 for tens in tensors:
269 if not tens.has_fully_defined_shape():
270 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100271 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100272 return valid, ", ".join(extra)
Michael McGeagh37ded342020-10-01 15:37:44 +0100273
Michael McGeagh184b2502020-10-09 17:19:52 +0100274 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100275 def constraint_tens_output_scalar(op):
276 "Output tensors cannot be scalar"
277 ofm = op.ofm
278 valid = ofm.shape != []
279 return valid, f"Output Tensor '{ofm.name}' is scalar"
Michael McGeagh184b2502020-10-09 17:19:52 +0100280
281 @classmethod
282 @docstring_format_args([shapeless_input_ops])
Michael McGeagh65fd9982020-10-20 11:49:28 +0100283 def constraint_tens_input_scalar(cls, op):
284 "Scalar Input tensors are only valid for op type: {}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100285 valid = True
286 extra = []
287 tensors = [tens for tens in op.inputs if tens]
288 for tens in tensors:
289 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
290 valid = False
291 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100292 extra = ", ".join(extra)
293 return valid, f"Op has scalar input tensor(s): {extra}"
Tim Hall79d07d22020-04-27 18:20:16 +0100294
Michael McGeagh37ded342020-10-01 15:37:44 +0100295 @staticmethod
296 def constraint_tens_shape_size(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100297 "Input(s) and Output tensors must not be greater than 4D"
Michael McGeagh37ded342020-10-01 15:37:44 +0100298 valid = True
299 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100300 tensors = [tens for tens in op.inputs + op.outputs if tens]
301 for tens in tensors:
302 if len(tens.shape) > 4:
303 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100304 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100305 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100306
Michael McGeagh37ded342020-10-01 15:37:44 +0100307 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100308 @docstring_format_args([supported_op_dtypes])
Michael McGeagh37ded342020-10-01 15:37:44 +0100309 def constraint_tens_dtype(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100310 "Tensors must be of type: {}"
Michael McGeagh37ded342020-10-01 15:37:44 +0100311 valid = True
312 extra = []
313 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100314 if not tensors:
315 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100316 for tens in tensors:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100317 if tens.dtype not in cls.supported_op_dtypes:
Michael McGeagh184b2502020-10-09 17:19:52 +0100318 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100319 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100320 return valid, ", ".join(extra)
321
322 @classmethod
323 @docstring_format_args([supported_int32_tensor_ops])
324 def constraint_tens_int32_ops(cls, op):
325 "Tensors which are int32 are only valid when op type is: {}"
326 valid = True
327 extra = []
328 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100329 if not tensors:
330 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh184b2502020-10-09 17:19:52 +0100331 for tens in tensors:
332 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
333 valid = False
334 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100335 extra = ", ".join(extra)
336 return valid, f"Op has int32 tensor(s): {extra}"
Andreas Nevalaineneadb1662020-09-01 15:36:26 +0200337
Michael McGeagh37ded342020-10-01 15:37:44 +0100338 @classmethod
339 @docstring_format_args(tens_dim_range)
340 def constraint_tens_dimension(cls, op):
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100341 "Tensor dimensions must be in the range [{}, {}]"
Michael McGeagh37ded342020-10-01 15:37:44 +0100342 tens_min, tens_max = cls.tens_dim_range
343 valid = True
344 extra = []
345 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100346 if not tensors:
347 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100348 for tens in tensors:
Michael McGeagh184b2502020-10-09 17:19:52 +0100349 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
350 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100351 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100352 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100353
Dwight Lidman8359a472020-09-28 15:53:40 +0200354 @staticmethod
355 def constraint_tens_quant_none_check(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100356 "Input(s), Output and Weight tensors must have quantization parameters"
Dwight Lidman8359a472020-09-28 15:53:40 +0200357 valid = True
358 extra = []
359 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
360 for tens in tensors:
361 if tens.quantization is None:
362 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100363 extra.append(tens.name)
364 extra = ", ".join(extra)
365 return valid, f"Op has tensors with missing quantization parameters: {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200366
Michael McGeagh184b2502020-10-09 17:19:52 +0100367 @staticmethod
368 def constraint_tens_quant_scale(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100369 "Input(s), Output and Weight tensors with quantization scales must be finite"
Michael McGeagh184b2502020-10-09 17:19:52 +0100370 valid = True
371 extra = []
372 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
373 for tens in tensors:
374 if (tens.quantization.scale_f32 is not None) and np.isinf(tens.quantization.scale_f32).any():
375 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100376 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100377 return valid, ", ".join(extra)
378
379 @classmethod
380 @docstring_format_args([supported_fused_activations])
381 def constraint_faf(cls, op):
382 "The fused activation function (if present) must be one of type: {}"
383 faf = op.activation
384 valid = (faf is None) or (faf in cls.supported_fused_activations)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100385 return valid, f"Op has its fused activation function as: {faf}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100386
387 @staticmethod
388 def constraint_stride_type(op):
389 "Stride values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100390 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100391 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100392 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100393
Michael McGeagh1eeea512020-09-30 14:23:09 +0100394 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100395 @docstring_format_args(stride_range)
396 def constraint_stride_range(cls, op):
397 "Stride values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100398 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100399 stride_min, stride_max = cls.stride_range
400 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100401 return valid, f"Op has stride WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100402
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100403 @staticmethod
404 def constraint_dilation_type(op):
405 "Dilation factor values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100406 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100407 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100408 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100409
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100410 @classmethod
411 @docstring_format_args(dilation_range)
412 def constraint_dilation_range(cls, op):
413 "Dilation factor values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100414 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100415 dilation_min, dilation_max = cls.dilation_range
416 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100417 return valid, f"Op has dilation factor WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100418
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100419 @classmethod
420 @docstring_format_args(dilated_height_range)
421 def constraint_dilated_height_range(cls, op):
422 "Dilated kernel height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100423 h = op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100424 dilated_height_min, dilated_height_max = cls.dilated_height_range
425 valid = dilated_height_min <= h <= dilated_height_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100426 return valid, f"Op has dilated kernel height as: {h}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200427
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100428 @classmethod
429 @docstring_format_args(dilated_product_range)
430 def constraint_dilated_product_range(cls, op):
431 "Product of dilated kernel width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100432 product = op.kernel.area_width() * op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100433 dilated_product_min, dilated_product_max = cls.dilated_product_range
434 valid = dilated_product_min <= product <= dilated_product_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100435 return valid, f"Op has product of dilated kernel width and height as: {product}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200436
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100437 @staticmethod
438 def constraint_weights_type(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100439 "Weight tensor must be 8-bit"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100440 weights = op.weights
441 valid = weights.element_size() == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100442 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200443
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100444 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100445 def constraint_weights_const(op):
446 "Weight tensor must be constant"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100447 weights = op.weights
448 valid = weights.values is not None
Michael McGeagh65fd9982020-10-20 11:49:28 +0100449 return valid, f"Tensor '{weights.name}' has non-constant values"
Andreas Nevalainen8854dc92020-09-24 13:43:00 +0200450
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100451 @classmethod
452 @docstring_format_args([weights_limit])
453 def constraint_weights_limit(cls, op):
454 "The sum of the weights cannot exceed {}"
455 weights = op.weights
456 values = weights.quant_values.astype(np.int64) - weights.quantization.zero_point
457 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
458 valid = limit <= cls.weights_limit
Michael McGeagh65fd9982020-10-20 11:49:28 +0100459 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200460
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100461 @classmethod
462 @docstring_format_args([supported_bias_dtypes])
463 def constraint_bias_type(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100464 "Optional Bias tensor must be of type: {}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100465 bias = op.bias
466 if bias:
467 valid = bias.dtype in cls.supported_bias_dtypes
Michael McGeagh65fd9982020-10-20 11:49:28 +0100468 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
469 return True, "Op has no bias tensor"
Tim Hall79d07d22020-04-27 18:20:16 +0100470
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100471 @staticmethod
472 def constraint_bias_40bit(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100473 "Optional Bias tensor values must fit within 40-bits"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100474 bias = op.bias
475 if bias and bias.dtype == DataType.int64:
476 valid = all(len(bin(quant_value)[2:]) <= 40 for quant_value in bias.quant_values)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100477 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
478 return True, "Op has no bias tensor, or it fits in 40-bit"
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200479
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100480 @staticmethod
481 def constraint_batch_size(op):
482 "IFM Tensor batch size must be 1"
483 ifm = op.ifm
484 valid = ifm.shape[0] == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100485 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
486
487 @staticmethod
488 def constraint_quant_scale_inf(op):
489 "The IFM quantization scale divided by the OFM quantization scale must not be infinite"
490 ifm_scale = op.ifm.quantization.scale_f32
491 ofm_scale = op.ofm.quantization.scale_f32
492 valid = not np.isinf(ifm_scale / ofm_scale)
493 return valid, f"Op has infinite quantization scale. ifm_scale={ifm_scale} ofm_scale={ofm_scale}"
494
495 @staticmethod
496 def constraint_depth_multiplier(op):
497 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
498 depth_multiplier = op.attrs.get("depth_multiplier", 1)
499 if depth_multiplier > 1:
500 ifm_channels = op.ifm.shape[3]
501 ofm_channels = op.ofm.shape[3]
502 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
503 extra = (
504 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
505 f" and depth_multiplier={depth_multiplier}"
506 )
507 return valid, extra
508 return True, "Op has depth_multiplier=1"
509
510 @staticmethod
511 def constraint_tconv_stride(op):
512 "Stride values for both width and height must be 2"
513 w = op.kernel.stride.x
514 h = op.kernel.stride.y
515 valid = (w == 2) and (h == 2)
516 return valid, f"Op has stride WxH as: {w}x{h}"
517
518 @staticmethod
519 def constraint_tconv_same(op):
520 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
521 if op.attrs["padding"] == b"SAME":
522 w = op.kernel.stride.x
523 h = op.kernel.stride.y
524 ifm_shape = op.ifm.shape
525 ofm_shape = op.ofm.shape
526 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
527 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
528 return True, "Op has padding=VALID"
529
530 @staticmethod
531 def constraint_tconv_valid(op):
532 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
533 minus difference between kernel size and stride"""
534 if op.attrs["padding"] == b"VALID":
535 s_w = op.kernel.stride.x
536 s_h = op.kernel.stride.y
537 k_w = op.kernel.width
538 k_h = op.kernel.height
539 ifm_shape = op.ifm.shape
540 ofm_shape = op.ofm.shape
541 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
542 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
543 valid = height_check and width_check
544 extra = (
545 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
546 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
547 )
548 return valid, extra
549 return True, "Op has padding=SAME"
550
551 @staticmethod
552 def constraint_matching_in_out_types(op):
553 "IFM and OFM data types must match"
554 ifm_dtype = op.ifm.dtype
555 ofm_dtype = op.ofm.dtype
556 valid = ifm_dtype == ofm_dtype
557 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
558
559 @staticmethod
560 def constraint_filter_type(op):
561 "Kernel filter values for both width and height must be integer types"
562 w = op.kernel.width
563 h = op.kernel.height
564 valid = is_integer(w) and is_integer(h)
565 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
566
567 @classmethod
568 @docstring_format_args(filter_range)
569 def constraint_filter_range(cls, op):
570 "Kernel filter values for both width and height must be in the range [{}, {}]"
571 if op.attrs["padding"] == b"SAME":
572 w = op.kernel.width
573 h = op.kernel.height
574 filter_min, filter_max = cls.filter_range
575 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
576 return valid, f"Op has kernel filter WxH as: {w}x{h}"
577 return True, "Op has padding=VALID"
578
579 @classmethod
580 @docstring_format_args(filter_height_range)
581 def constraint_filter_height_range(cls, op):
582 "Kernel filter height must be in the range [{}, {}]"
583 h = op.kernel.height
584 filter_height_min, filter_height_max = cls.filter_height_range
585 valid = filter_height_min <= h <= filter_height_max
586 return valid, f"Op has kernel filter height as: {h}"
587
588 @classmethod
589 @docstring_format_args(filter_product_range)
590 def constraint_filter_product_range(cls, op):
591 "Product of kernel filter width and height must be in the range [{}, {}]"
592 product = op.kernel.elements_wh()
593 filter_product_min, filter_product_max = cls.filter_product_range
594 valid = filter_product_min <= product <= filter_product_max
595 return valid, f"Op has product of kernel filter width and height as: {product}"
596
597 @staticmethod
598 @docstring_format_args(filter_height_range)
599 def constraint_filter_height_range_valid_pad(op):
600 "VALID padding: Kernel filter height must be in the range [{}, {}]"
601 if op.attrs["padding"] == b"VALID":
602 return SupportedOperators.constraint_filter_height_range(op)
603 return True, "Op has padding=SAME"
604
605 @staticmethod
606 @docstring_format_args(filter_product_range)
607 def constraint_filter_product_range_valid_pad(op):
608 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
609 if op.attrs["padding"] == b"VALID":
610 return SupportedOperators.constraint_filter_product_range(op)
611 return True, "Op has padding=SAME"
612
613 @staticmethod
614 def constraint_resize(op):
615 """The width and height of the IFM and OFM must match one of the following criteria:
616 IFM W and H must both be 1
617 IFM must match OFM
618 OFM W and H must be 2x IFM -1, if align_corners is True
619 OFM W and H must be 2x IFM, if align_corners is False"""
620 # Easier to start with False condition as very few cases result in a supported resize
621 valid = False
622 ifm_shape = op.ifm.shape
623 ofm_shape = op.ofm.shape
624 align_corners = op.attrs.get("align_corners", False)
625 if len(ifm_shape) == 4:
626 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
627 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
628 valid = True
629 else:
630 upscaled_shape = np.array(ifm_shape[1:3])
631 out_shape = np.array(ofm_shape[1:3])
632 while (upscaled_shape < out_shape).all():
633 upscaled_shape *= 2
634 if align_corners:
635 upscaled_shape -= 1
636 # Valid if OFM is 2x IFM (-1 for align corners)
637 if np.array_equal(out_shape, upscaled_shape):
638 valid = True
639 break
640 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
641
642 @staticmethod
643 def constraint_matching_shapes(op):
644 "IFM and OFM shapes must match"
645 ifm_shape = op.ifm.shape
646 ofm_shape = op.ofm.shape
647 valid = ifm_shape == ofm_shape
648 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
649
650 @staticmethod
651 def constraint_splitv_inferred(op):
652 "Only one size is allowed to be inferred"
653 sizes = op.ifm2.values
654 valid = np.count_nonzero(sizes == -1) <= 1
655 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
656
657 @staticmethod
658 def constraint_axis_exists(op):
659 "Axis attribute must exist"
660 axis = op.attrs.get("axis")
661 valid = axis is not None
662 return valid, f"Op has axis={axis}"
663
664 @staticmethod
665 def constraint_axis_valid(op):
666 "Axis attribute must be in the range [0, <ofm_dimensions>)"
667 dims = len(op.ofm.shape)
668 axis = op.attrs["axis"]
669 axis += dims if axis < 0 else 0
670 valid = 0 <= axis < dims
671 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
672
673 @staticmethod
674 def constraint_matching_dimensionality(op):
675 "All Input dimensionalities must match OFM dimensionality"
676 valid = True
677 extra = []
678 ofm_dim = len(op.ofm.shape)
679 tensors = [tens for tens in op.inputs if tens]
680 for tens in tensors:
681 dim = len(tens.shape)
682 if dim != ofm_dim:
683 valid = False
684 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
685 extra = ", ".join(extra)
686 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
687
688 @staticmethod
689 def constraint_valid_dimensions(op):
690 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
691 valid = True
692 extra = []
693 ofm_shape = op.ofm.shape
694 ofm_dim = len(ofm_shape)
695 axis = op.attrs["axis"]
696 axis += ofm_dim if axis < 0 else 0
697 tensors = [tens for tens in op.inputs if tens]
698 for tens in tensors:
699 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
700 valid = False
701 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
702 extra = ", ".join(extra)
703 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
704
705 @staticmethod
706 def constraint_stridedslice_input_count(op):
707 "Exactly 4 Input tensors are required"
708 inputs = len(op.inputs)
709 valid = inputs == 4
710 return valid, f"Op has {inputs} inputs"
711
712 @staticmethod
713 def constraint_stridedslice_inputs_const(op):
714 "Begin, End and Stride Input tensors must be constant"
715 valid = True
716 extra = []
717 _, begin, end, strides = op.inputs
718 if begin.values is None:
719 valid = False
720 extra.append(f"Begin tensor '{begin.name}'")
721 if end.values is None:
722 valid = False
723 extra.append(f"End tensor '{end.name}'")
724 if strides.values is None:
725 valid = False
726 extra.append(f"Stride tensor '{strides.name}'")
727 extra = ", ".join(extra)
728 return valid, f"Op has non-constant tensors: {extra}"
729
730 @staticmethod
731 def constraint_stridedslice_tens_size_matches(op):
732 "All Input sizes must match OFM size"
733 ifm, begin, end, strides = op.inputs
734 ifm_size = len(ifm.shape)
735 ofm_size = len(op.ofm.shape)
736 begin_size = len(begin.values)
737 end_size = len(end.values)
738 strides_size = len(strides.values)
739 valid = ifm_size == ofm_size == begin_size == end_size == strides_size
740 extra = (
741 f"Op has ofm_size={ofm_size}, ifm_size={ifm_size},"
742 f" begin_size={begin_size}, end_size={end_size} and strides_size={strides_size}"
743 )
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100744 return valid, extra
Tim Hall79d07d22020-04-27 18:20:16 +0100745
Michael McGeagh65fd9982020-10-20 11:49:28 +0100746 @staticmethod
747 def constraint_stridedslice_stride_values(op):
748 "All Strides values must be 1"
749 strides = op.inputs[3]
750 valid = all(stride == 1 for stride in strides.values)
751 return valid, f"Op has strides values {strides.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100752
Michael McGeagh65fd9982020-10-20 11:49:28 +0100753 @staticmethod
754 def constraint_ellipsis_mask(op):
755 "ellipsis_mask must be 0"
756 ellipsis = op.attrs["ellipsis_mask"]
757 valid = ellipsis == 0
758 return valid, f"Op has ellipsis mask as: {ellipsis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200759
Michael McGeagh65fd9982020-10-20 11:49:28 +0100760 @staticmethod
761 def constraint_axis_masks(op):
762 "new_axis_mask and shrink_axis_mask cannot both be set"
763 new_axis = op.attrs["new_axis_mask"]
764 shrink_axis = op.attrs["shrink_axis_mask"]
765 valid = (new_axis == 0) or (shrink_axis == 0)
766 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200767
Michael McGeagh65fd9982020-10-20 11:49:28 +0100768 @staticmethod
769 def constraint_slice_ranges(op):
770 "Slice 'end' values must be greater than 'begin' values"
771 ifm, begin, end, _ = op.inputs
772 # Calculate offset begin/end
773 offset_begin = get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
774 offset_end = get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
775 # Check "end - begin" doesn't result in any zero or negative elements
776 valid = all((e - b) > 0 for b, e in zip(offset_begin, offset_end))
777 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100778
Michael McGeagh65fd9982020-10-20 11:49:28 +0100779 @staticmethod
780 def constraint_matching_inputs_types(op):
781 "Both Input data types must match"
782 ifm_dtype = op.ifm.dtype
783 ifm2_dtype = op.ifm2.dtype
784 valid = ifm_dtype == ifm2_dtype
785 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100786
Michael McGeagh65fd9982020-10-20 11:49:28 +0100787 @staticmethod
788 def constraint_matching_signed(op):
789 "For IFM that are signed, OFM must also be signed"
790 valid = True
791 ifm_dtype = op.ifm.dtype
792 ofm_dtype = op.ofm.dtype
793 if ifm_dtype.type & BaseType.Signed:
794 valid = bool(ofm_dtype.type & BaseType.Signed)
795 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100796
Michael McGeagh65fd9982020-10-20 11:49:28 +0100797 @staticmethod
798 def constraint_unsigned_valid(op):
799 "For IFM that are unsigned, OFM must either be the same type or int32"
800 valid = True
801 ifm_dtype = op.ifm.dtype
802 ofm_dtype = op.ofm.dtype
803 if ifm_dtype.type & BaseType.Unsigned:
804 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
805 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100806
Michael McGeagh65fd9982020-10-20 11:49:28 +0100807 @staticmethod
808 def constraint_inputs_int32(op):
809 "Both Input data types must be int32"
810 ifm_dtype = op.ifm.dtype
811 ifm2_dtype = op.ifm2.dtype
812 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
813 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100814
Michael McGeagh65fd9982020-10-20 11:49:28 +0100815 @staticmethod
816 def constraint_output_int32(op):
817 "OFM must be int32"
818 ofm_dtype = op.ofm.dtype
819 valid = ofm_dtype == DataType.int32
820 return valid, f"Op has ofm_dtype={ofm_dtype}"
Dwight Lidman42fed942020-05-29 09:37:03 +0200821
Michael McGeagh65fd9982020-10-20 11:49:28 +0100822 @staticmethod
823 def constraint_matching_quantization_parameters(op):
824 "Both Input quantization parameters must match OFM quantization parameters"
825 valid = True
826 extra = []
827 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
828 valid = False
829 extra.append(op.ifm.name)
830 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
831 valid = False
832 extra.append(op.ifm2.name)
833 extra = ", ".join(extra)
834 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200835
Michael McGeagh65fd9982020-10-20 11:49:28 +0100836 @staticmethod
837 def constraint_elemwise_batch_size(op):
838 "Batch size must be 1 for Input tensors with more than 2 dimensions"
839 valid = True
840 extra = []
841 for tens in (op.ifm, op.ifm2):
842 # Unary ops have ifm2 as None
843 if tens is not None:
844 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
845 valid = False
846 extra.append(tens.name)
847 extra = ", ".join(extra)
848 return valid, f"Op has invalid input tensors: {extra}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200849
Michael McGeagh65fd9982020-10-20 11:49:28 +0100850 @staticmethod
851 def constraint_matching_either_shapes(op):
852 "At least one Input's shape must match the OFM's shape"
853 ifm_shape = op.ifm.shape
854 ifm2_shape = op.ifm2.shape if op.ifm2 else None
855 ofm_shape = op.ofm.shape
856 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
857 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 +0200858
Michael McGeagh65fd9982020-10-20 11:49:28 +0100859 @staticmethod
860 def constraint_alpha_valid(op):
861 "Alpha must not be negative"
862 alpha = op.attrs["alpha"]
863 valid = alpha >= 0
864 return valid, f"Op has alpha={alpha}"