blob: ccf61042b920520f2dd109ea2977592cea1578c8 [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 McGeagh837dc1b2020-11-10 12:38:25 +000028from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
Michael McGeagh219ec072020-11-09 11:11:26 +000029from .tflite_mapping import optype_to_builtintype
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020030
31
Michael McGeagh37ded342020-10-01 15:37:44 +010032# Custom decorator function to allow formatting docstrings containing "{}"
33def docstring_format_args(args):
34 def docstring(func):
35 func.__doc__ = func.__doc__.format(*args)
36 return func
37
38 return docstring
39
40
Michael McGeagh837dc1b2020-11-10 12:38:25 +000041def _optype_formatter(op_list):
42 # Convert internal op types to external names
43 output = map(optype_to_builtintype, op_list)
44 # Remove UNKNOWNs
45 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
46 # Order alphabetically
47 return sorted(output)
48
49
Tim Hall79d07d22020-04-27 18:20:16 +010050class SupportedOperators:
Michael McGeagh1eeea512020-09-30 14:23:09 +010051 # Categorised lists of supported operators
Louis Verhaardaee5d752020-09-30 09:01:52 +020052 npu_pre_ops = set((Op.SplitSliceRead,))
53 convolution_ops = set((Op.Conv2DBias, Op.Conv2D, Op.QuantizedConv2D,))
54 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
55 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010056 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
Louis Verhaardaee5d752020-09-30 09:01:52 +020057 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
58 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
59 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
60 resizing_ops = set((Op.ResizeBilinear,))
61 fc_vector_products = set((Op.QuantizedMatMul, Op.MatMul, Op.FullyConnected,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010062 mac_main_ops = (
63 # RNN/LSTM/GRU
Louis Verhaardaee5d752020-09-30 09:01:52 +020064 set((Op.BlockLSTM,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010065 # conv/depthwiseconv/transposeconv
66 | convolution_like_ops
Michael McGeagh1eeea512020-09-30 14:23:09 +010067 # pooling
68 | pooling_ops
69 # resizing/upscaling
70 | resizing_ops
71 # FC layers
72 | fc_vector_products
73 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020074 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
75 binary_elem_wise_min_max_ops = set((Op.Minimum, Op.Maximum,))
76 binary_elem_wise_shift_ops = set((Op.SHL, Op.SHR,))
77 binary_elem_wise_add_mul_sub = set((Op.Add, Op.Mul, Op.Sub,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010078 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
79 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010080 supported_int32_tensor_ops = (
Louis Verhaardaee5d752020-09-30 09:01:52 +020081 set((Op.ReduceSum, Op.CLZ,)) | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010082 )
Michael McGeagh65fd9982020-10-20 11:49:28 +010083 relu_ops = Op.op_set(Op.is_relu_op)
84 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010085 npu_post_ops = (
Michael McGeagh1eeea512020-09-30 14:23:09 +010086 # activation functions
Louis Verhaardaee5d752020-09-30 09:01:52 +020087 activation_ops
88 # concatenation write direction
89 | set((Op.ConcatSliceWrite,))
90 # Quantization
91 | set((Op.Quantize,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010092 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020093 split_ops = set((Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack,))
94 concat_ops = set((Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack,))
95 memory_only_ops = set((Op.Squeeze, Op.Reshape, Op.QuantizedReshape, Op.ExpandDims,)) | concat_ops | split_ops
96 shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV,))
Michael McGeagh65fd9982020-10-20 11:49:28 +010097 supported_fused_activations = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.LUT,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010098 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 +010099 # Supported data types
100 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
101 supported_bias_dtypes = set((DataType.int32, DataType.int64))
Michael McGeagh37ded342020-10-01 15:37:44 +0100102 # Defined ranges for allowed values:
103 tens_dim_range = (1, 65535)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100104 stride_range = (1, 3)
105 dilation_range = (1, 2)
106 dilated_height_range = (1, 64)
107 dilated_product_range = (1, 64 * 64)
108 weights_limit = 127 * 65536
Michael McGeagh65fd9982020-10-20 11:49:28 +0100109 filter_range = (1, 8)
110 filter_height_range = (1, 256)
111 filter_product_range = (1, 256 * 256)
Michael McGeagh837dc1b2020-11-10 12:38:25 +0000112 # Ordered, external names of op types for the constraint reasons
113 docstring_shapeless_input_ops = _optype_formatter(shapeless_input_ops)
114 docstring_supported_int32_tensor_ops = _optype_formatter(supported_int32_tensor_ops)
115 docstring_supported_fused_activations = _optype_formatter(supported_fused_activations)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100116
Fredrik Svedberg880e7352020-08-25 11:31:47 +0200117 def __init__(self):
Michael McGeagh184b2502020-10-09 17:19:52 +0100118 # Setup the generic constraints. Note: the order matters
Michael McGeagh37ded342020-10-01 15:37:44 +0100119 self.generic_constraints = []
Michael McGeagh65fd9982020-10-20 11:49:28 +0100120 self.generic_constraints.append(SupportedOperators.constraint_tens_no_dynamic)
Michael McGeagh37ded342020-10-01 15:37:44 +0100121 self.generic_constraints.append(SupportedOperators.constraint_tens_defined_shape)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100122 self.generic_constraints.append(SupportedOperators.constraint_tens_output_scalar)
123 self.generic_constraints.append(SupportedOperators.constraint_tens_input_scalar)
Michael McGeagh37ded342020-10-01 15:37:44 +0100124 self.generic_constraints.append(SupportedOperators.constraint_tens_shape_size)
125 self.generic_constraints.append(SupportedOperators.constraint_tens_dtype)
Michael McGeagh184b2502020-10-09 17:19:52 +0100126 self.generic_constraints.append(SupportedOperators.constraint_tens_int32_ops)
Michael McGeagh37ded342020-10-01 15:37:44 +0100127 self.generic_constraints.append(SupportedOperators.constraint_tens_dimension)
Dwight Lidman8359a472020-09-28 15:53:40 +0200128 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_none_check)
Michael McGeagh184b2502020-10-09 17:19:52 +0100129 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_scale)
130 self.generic_constraints.append(SupportedOperators.constraint_faf)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100131
Michael McGeagh65fd9982020-10-20 11:49:28 +0100132 # Setup specific constraints. Note: the order matters
133 self.specific_constraints = defaultdict(list)
134
135 # Conv-like checks:
136 for op_type in SupportedOperators.convolution_like_ops:
137 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
138 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
139 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_type)
140 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_range)
141 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_height_range)
142 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_product_range)
143 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
144 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
145 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_limit)
146 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
147 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
148 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
149 # Depthwise Conv specific checks:
150 for op_type in SupportedOperators.depthwise_convolution_ops:
151 self.specific_constraints[op_type].append(SupportedOperators.constraint_depth_multiplier)
152 # Transpose Conv specific checks:
153 for op_type in SupportedOperators.transpose_convolution_ops:
154 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_stride)
155 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_same)
156 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_valid)
157
158 # Pooling checks:
159 for op_type in SupportedOperators.pooling_ops:
160 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
161 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
162 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
163 # AVG pooling specific checks:
164 for op_type in SupportedOperators.avg_pooling_ops:
165 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
166 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
167 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_range)
168 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range_valid_pad)
169 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range_valid_pad)
170 # MAX pooling specific checks:
171 for op_type in SupportedOperators.max_pooling_ops:
172 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
173 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
174 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range)
175 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range)
176 # TODO: Check ReduceSum restrictions
177
178 # Relu specific checks:
179 for op_type in SupportedOperators.relu_ops:
180 self.specific_constraints[op_type].append(SupportedOperators.constraint_quant_scale_inf)
181
182 # Resizing specific checks:
183 for op_type in SupportedOperators.resizing_ops:
184 self.specific_constraints[op_type].append(SupportedOperators.constraint_resize)
185
186 # Vector Product specific checks:
187 for op_type in SupportedOperators.fc_vector_products:
188 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
189 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
190 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
191 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
192
193 # Concat specific checks:
194 for op_type in (Op.Concat, Op.ConcatTFLite):
195 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_exists)
196 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_valid)
197 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_dimensionality)
198 self.specific_constraints[op_type].append(SupportedOperators.constraint_valid_dimensions)
199
200 # Element-wise checks:
201 for op_type in SupportedOperators.elem_wise_main_ops:
202 self.specific_constraints[op_type].append(SupportedOperators.constraint_elemwise_batch_size)
203 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_either_shapes)
204 # Unary specific checks:
205 for op_type in SupportedOperators.unary_elem_wise_main_ops:
206 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
207 # Binary Min/Max specific checks:
208 for op_type in SupportedOperators.binary_elem_wise_min_max_ops:
209 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
210 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_quantization_parameters)
211 # Binary Add/Mul/Sub specific checks:
212 for op_type in SupportedOperators.binary_elem_wise_add_mul_sub:
213 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_inputs_types)
214 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_signed)
215 self.specific_constraints[op_type].append(SupportedOperators.constraint_unsigned_valid)
216 # Binary Shift specific checks:
217 for op_type in SupportedOperators.binary_elem_wise_shift_ops:
218 self.specific_constraints[op_type].append(SupportedOperators.constraint_inputs_int32)
219
220 # SHL specific checks:
221 self.specific_constraints[Op.SHL].append(SupportedOperators.constraint_output_int32)
222
223 # CLZ specific checks:
224 self.specific_constraints[Op.CLZ].append(SupportedOperators.constraint_output_int32)
225
226 # Softmax specific checks:
227 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_shapes)
228 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_in_out_types)
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100229 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_beta_value_range)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100230
231 # SplitV specific checks:
232 self.specific_constraints[Op.SplitV].append(SupportedOperators.constraint_splitv_inferred)
233
234 # StridedSlice specific checks:
235 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_input_count)
236 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_inputs_const)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100237 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_stride_values)
238 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_ellipsis_mask)
239 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_axis_masks)
240 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_slice_ranges)
241
242 # LeakyRelu specific checks:
243 self.specific_constraints[Op.LeakyRelu].append(SupportedOperators.constraint_alpha_valid)
Tim Hall79d07d22020-04-27 18:20:16 +0100244
245 def is_operator_supported(self, op):
Michael McGeagh219ec072020-11-09 11:11:26 +0000246 ext_type = optype_to_builtintype(op.type)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100247 if op.type not in SupportedOperators.supported_operators:
Louis Verhaard5f2ea2f2020-10-15 08:39:44 +0200248 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
Michael McGeagh219ec072020-11-09 11:11:26 +0000249 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
Tim Hall79d07d22020-04-27 18:20:16 +0100250 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100251
Michael McGeagh65fd9982020-10-20 11:49:28 +0100252 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
Michael McGeagh37ded342020-10-01 15:37:44 +0100253 valid, extra = constraint(op)
254 if not valid:
Michael McGeagh219ec072020-11-09 11:11:26 +0000255 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
Michael McGeagh65fd9982020-10-20 11:49:28 +0100256 print(f" - {constraint.__doc__}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100257 if extra:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100258 print(f" {extra}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100259 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100260
Tim Hall79d07d22020-04-27 18:20:16 +0100261 return True
262
Michael McGeagh37ded342020-10-01 15:37:44 +0100263 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100264 def constraint_tens_no_dynamic(op):
265 "Input(s) and Output tensors must not be dynamic"
266 valid = True
267 extra = []
268 tensors = [tens for tens in op.inputs + op.outputs if tens]
269 for tens in tensors:
270 if (tens.shape == []) and (tens.values is None):
271 valid = False
272 extra.append(tens.name)
273 extra = ", ".join(extra)
274 return valid, f"Op has dynamic tensor(s): {extra}"
275
276 @staticmethod
Michael McGeagh37ded342020-10-01 15:37:44 +0100277 def constraint_tens_defined_shape(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100278 "Input(s) and Output tensors must have a defined shape"
Michael McGeagh37ded342020-10-01 15:37:44 +0100279 valid = True
280 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100281 tensors = [tens for tens in op.inputs + op.outputs if tens]
282 for tens in tensors:
283 if not tens.has_fully_defined_shape():
284 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100285 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100286 return valid, ", ".join(extra)
Michael McGeagh37ded342020-10-01 15:37:44 +0100287
Michael McGeagh184b2502020-10-09 17:19:52 +0100288 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100289 def constraint_tens_output_scalar(op):
290 "Output tensors cannot be scalar"
291 ofm = op.ofm
292 valid = ofm.shape != []
293 return valid, f"Output Tensor '{ofm.name}' is scalar"
Michael McGeagh184b2502020-10-09 17:19:52 +0100294
295 @classmethod
Michael McGeagh837dc1b2020-11-10 12:38:25 +0000296 @docstring_format_args([docstring_shapeless_input_ops])
Michael McGeagh65fd9982020-10-20 11:49:28 +0100297 def constraint_tens_input_scalar(cls, op):
298 "Scalar Input tensors are only valid for op type: {}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100299 valid = True
300 extra = []
301 tensors = [tens for tens in op.inputs if tens]
302 for tens in tensors:
303 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
304 valid = False
305 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100306 extra = ", ".join(extra)
307 return valid, f"Op has scalar input tensor(s): {extra}"
Tim Hall79d07d22020-04-27 18:20:16 +0100308
Michael McGeagh37ded342020-10-01 15:37:44 +0100309 @staticmethod
310 def constraint_tens_shape_size(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100311 "Input(s) and Output tensors must not be greater than 4D"
Michael McGeagh37ded342020-10-01 15:37:44 +0100312 valid = True
313 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100314 tensors = [tens for tens in op.inputs + op.outputs if tens]
315 for tens in tensors:
316 if len(tens.shape) > 4:
317 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100318 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100319 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100320
Michael McGeagh37ded342020-10-01 15:37:44 +0100321 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100322 @docstring_format_args([supported_op_dtypes])
Michael McGeagh37ded342020-10-01 15:37:44 +0100323 def constraint_tens_dtype(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100324 "Tensors must be of type: {}"
Michael McGeagh37ded342020-10-01 15:37:44 +0100325 valid = True
326 extra = []
327 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100328 if not tensors:
329 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100330 for tens in tensors:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100331 if tens.dtype not in cls.supported_op_dtypes:
Michael McGeagh184b2502020-10-09 17:19:52 +0100332 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100333 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100334 return valid, ", ".join(extra)
335
336 @classmethod
Michael McGeagh837dc1b2020-11-10 12:38:25 +0000337 @docstring_format_args([docstring_supported_int32_tensor_ops])
Michael McGeagh184b2502020-10-09 17:19:52 +0100338 def constraint_tens_int32_ops(cls, op):
339 "Tensors which are int32 are only valid when op type is: {}"
340 valid = True
341 extra = []
342 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100343 if not tensors:
344 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh184b2502020-10-09 17:19:52 +0100345 for tens in tensors:
346 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
347 valid = False
348 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100349 extra = ", ".join(extra)
350 return valid, f"Op has int32 tensor(s): {extra}"
Andreas Nevalaineneadb1662020-09-01 15:36:26 +0200351
Michael McGeagh37ded342020-10-01 15:37:44 +0100352 @classmethod
353 @docstring_format_args(tens_dim_range)
354 def constraint_tens_dimension(cls, op):
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100355 "Tensor dimensions must be in the range [{}, {}]"
Michael McGeagh37ded342020-10-01 15:37:44 +0100356 tens_min, tens_max = cls.tens_dim_range
357 valid = True
358 extra = []
359 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100360 if not tensors:
361 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100362 for tens in tensors:
Michael McGeagh184b2502020-10-09 17:19:52 +0100363 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
364 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100365 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100366 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100367
Dwight Lidman8359a472020-09-28 15:53:40 +0200368 @staticmethod
369 def constraint_tens_quant_none_check(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100370 "Input(s), Output and Weight tensors must have quantization parameters"
Dwight Lidman8359a472020-09-28 15:53:40 +0200371 valid = True
372 extra = []
373 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
374 for tens in tensors:
375 if tens.quantization is None:
376 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100377 extra.append(tens.name)
378 extra = ", ".join(extra)
379 return valid, f"Op has tensors with missing quantization parameters: {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200380
Michael McGeagh184b2502020-10-09 17:19:52 +0100381 @staticmethod
382 def constraint_tens_quant_scale(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100383 "Input(s), Output and Weight tensors with quantization scales must be finite"
Michael McGeagh184b2502020-10-09 17:19:52 +0100384 valid = True
385 extra = []
386 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
387 for tens in tensors:
388 if (tens.quantization.scale_f32 is not None) and np.isinf(tens.quantization.scale_f32).any():
389 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100390 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100391 return valid, ", ".join(extra)
392
393 @classmethod
Michael McGeagh837dc1b2020-11-10 12:38:25 +0000394 @docstring_format_args([docstring_supported_fused_activations])
Michael McGeagh184b2502020-10-09 17:19:52 +0100395 def constraint_faf(cls, op):
396 "The fused activation function (if present) must be one of type: {}"
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100397 if op.activation is None:
398 res = True, "Op has no fused activation function"
399 else:
400 faf = op.activation.op_type
401 valid = faf in cls.supported_fused_activations
402 res = valid, f"Op has its fused activation function as: {faf}"
403 return res
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100404
405 @staticmethod
406 def constraint_stride_type(op):
407 "Stride values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100408 w, h = op.get_kernel_stride()
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 stride WxH as: {repr(w)}x{repr(h)}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100411
Michael McGeagh1eeea512020-09-30 14:23:09 +0100412 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100413 @docstring_format_args(stride_range)
414 def constraint_stride_range(cls, op):
415 "Stride values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100416 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100417 stride_min, stride_max = cls.stride_range
418 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100419 return valid, f"Op has stride WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100420
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100421 @staticmethod
422 def constraint_dilation_type(op):
423 "Dilation factor values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100424 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100425 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100426 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100427
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100428 @classmethod
429 @docstring_format_args(dilation_range)
430 def constraint_dilation_range(cls, op):
431 "Dilation factor values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100432 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100433 dilation_min, dilation_max = cls.dilation_range
434 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100435 return valid, f"Op has dilation factor WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100436
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100437 @classmethod
438 @docstring_format_args(dilated_height_range)
439 def constraint_dilated_height_range(cls, op):
440 "Dilated kernel height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100441 h = op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100442 dilated_height_min, dilated_height_max = cls.dilated_height_range
443 valid = dilated_height_min <= h <= dilated_height_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100444 return valid, f"Op has dilated kernel height as: {h}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200445
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100446 @classmethod
447 @docstring_format_args(dilated_product_range)
448 def constraint_dilated_product_range(cls, op):
449 "Product of dilated kernel width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100450 product = op.kernel.area_width() * op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100451 dilated_product_min, dilated_product_max = cls.dilated_product_range
452 valid = dilated_product_min <= product <= dilated_product_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100453 return valid, f"Op has product of dilated kernel width and height as: {product}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200454
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100455 @staticmethod
456 def constraint_weights_type(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100457 "Weight tensor must be 8-bit"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100458 weights = op.weights
459 valid = weights.element_size() == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100460 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200461
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100462 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100463 def constraint_weights_const(op):
464 "Weight tensor must be constant"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100465 weights = op.weights
466 valid = weights.values is not None
Michael McGeagh65fd9982020-10-20 11:49:28 +0100467 return valid, f"Tensor '{weights.name}' has non-constant values"
Andreas Nevalainen8854dc92020-09-24 13:43:00 +0200468
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100469 @classmethod
470 @docstring_format_args([weights_limit])
471 def constraint_weights_limit(cls, op):
472 "The sum of the weights cannot exceed {}"
473 weights = op.weights
474 values = weights.quant_values.astype(np.int64) - weights.quantization.zero_point
475 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
476 valid = limit <= cls.weights_limit
Michael McGeagh65fd9982020-10-20 11:49:28 +0100477 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200478
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100479 @classmethod
480 @docstring_format_args([supported_bias_dtypes])
481 def constraint_bias_type(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100482 "Optional Bias tensor must be of type: {}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100483 bias = op.bias
484 if bias:
485 valid = bias.dtype in cls.supported_bias_dtypes
Michael McGeagh65fd9982020-10-20 11:49:28 +0100486 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
487 return True, "Op has no bias tensor"
Tim Hall79d07d22020-04-27 18:20:16 +0100488
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100489 @staticmethod
490 def constraint_bias_40bit(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100491 "Optional Bias tensor values must fit within 40-bits"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100492 bias = op.bias
493 if bias and bias.dtype == DataType.int64:
494 valid = all(len(bin(quant_value)[2:]) <= 40 for quant_value in bias.quant_values)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100495 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
496 return True, "Op has no bias tensor, or it fits in 40-bit"
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200497
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100498 @staticmethod
499 def constraint_batch_size(op):
500 "IFM Tensor batch size must be 1"
501 ifm = op.ifm
502 valid = ifm.shape[0] == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100503 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
504
505 @staticmethod
506 def constraint_quant_scale_inf(op):
507 "The IFM quantization scale divided by the OFM quantization scale must not be infinite"
508 ifm_scale = op.ifm.quantization.scale_f32
509 ofm_scale = op.ofm.quantization.scale_f32
510 valid = not np.isinf(ifm_scale / ofm_scale)
511 return valid, f"Op has infinite quantization scale. ifm_scale={ifm_scale} ofm_scale={ofm_scale}"
512
513 @staticmethod
514 def constraint_depth_multiplier(op):
515 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
516 depth_multiplier = op.attrs.get("depth_multiplier", 1)
517 if depth_multiplier > 1:
518 ifm_channels = op.ifm.shape[3]
519 ofm_channels = op.ofm.shape[3]
520 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
521 extra = (
522 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
523 f" and depth_multiplier={depth_multiplier}"
524 )
525 return valid, extra
526 return True, "Op has depth_multiplier=1"
527
528 @staticmethod
529 def constraint_tconv_stride(op):
530 "Stride values for both width and height must be 2"
531 w = op.kernel.stride.x
532 h = op.kernel.stride.y
533 valid = (w == 2) and (h == 2)
534 return valid, f"Op has stride WxH as: {w}x{h}"
535
536 @staticmethod
537 def constraint_tconv_same(op):
538 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
539 if op.attrs["padding"] == b"SAME":
540 w = op.kernel.stride.x
541 h = op.kernel.stride.y
542 ifm_shape = op.ifm.shape
543 ofm_shape = op.ofm.shape
544 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
545 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
546 return True, "Op has padding=VALID"
547
548 @staticmethod
549 def constraint_tconv_valid(op):
550 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
551 minus difference between kernel size and stride"""
552 if op.attrs["padding"] == b"VALID":
553 s_w = op.kernel.stride.x
554 s_h = op.kernel.stride.y
555 k_w = op.kernel.width
556 k_h = op.kernel.height
557 ifm_shape = op.ifm.shape
558 ofm_shape = op.ofm.shape
559 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
560 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
561 valid = height_check and width_check
562 extra = (
563 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
564 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
565 )
566 return valid, extra
567 return True, "Op has padding=SAME"
568
569 @staticmethod
570 def constraint_matching_in_out_types(op):
571 "IFM and OFM data types must match"
572 ifm_dtype = op.ifm.dtype
573 ofm_dtype = op.ofm.dtype
574 valid = ifm_dtype == ofm_dtype
575 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
576
577 @staticmethod
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100578 def constraint_beta_value_range(op):
579 "Beta value needs to be positive"
580 beta = op.attrs.get("beta", 1.0)
581 valid = beta >= 0
582 return valid, f"Op has beta={beta}"
583
584 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100585 def constraint_filter_type(op):
586 "Kernel filter values for both width and height must be integer types"
587 w = op.kernel.width
588 h = op.kernel.height
589 valid = is_integer(w) and is_integer(h)
590 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
591
592 @classmethod
593 @docstring_format_args(filter_range)
594 def constraint_filter_range(cls, op):
595 "Kernel filter values for both width and height must be in the range [{}, {}]"
596 if op.attrs["padding"] == b"SAME":
597 w = op.kernel.width
598 h = op.kernel.height
599 filter_min, filter_max = cls.filter_range
600 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
601 return valid, f"Op has kernel filter WxH as: {w}x{h}"
602 return True, "Op has padding=VALID"
603
604 @classmethod
605 @docstring_format_args(filter_height_range)
606 def constraint_filter_height_range(cls, op):
607 "Kernel filter height must be in the range [{}, {}]"
608 h = op.kernel.height
609 filter_height_min, filter_height_max = cls.filter_height_range
610 valid = filter_height_min <= h <= filter_height_max
611 return valid, f"Op has kernel filter height as: {h}"
612
613 @classmethod
614 @docstring_format_args(filter_product_range)
615 def constraint_filter_product_range(cls, op):
616 "Product of kernel filter width and height must be in the range [{}, {}]"
617 product = op.kernel.elements_wh()
618 filter_product_min, filter_product_max = cls.filter_product_range
619 valid = filter_product_min <= product <= filter_product_max
620 return valid, f"Op has product of kernel filter width and height as: {product}"
621
622 @staticmethod
623 @docstring_format_args(filter_height_range)
624 def constraint_filter_height_range_valid_pad(op):
625 "VALID padding: Kernel filter height must be in the range [{}, {}]"
626 if op.attrs["padding"] == b"VALID":
627 return SupportedOperators.constraint_filter_height_range(op)
628 return True, "Op has padding=SAME"
629
630 @staticmethod
631 @docstring_format_args(filter_product_range)
632 def constraint_filter_product_range_valid_pad(op):
633 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
634 if op.attrs["padding"] == b"VALID":
635 return SupportedOperators.constraint_filter_product_range(op)
636 return True, "Op has padding=SAME"
637
638 @staticmethod
639 def constraint_resize(op):
640 """The width and height of the IFM and OFM must match one of the following criteria:
641 IFM W and H must both be 1
642 IFM must match OFM
643 OFM W and H must be 2x IFM -1, if align_corners is True
644 OFM W and H must be 2x IFM, if align_corners is False"""
645 # Easier to start with False condition as very few cases result in a supported resize
646 valid = False
647 ifm_shape = op.ifm.shape
648 ofm_shape = op.ofm.shape
649 align_corners = op.attrs.get("align_corners", False)
650 if len(ifm_shape) == 4:
651 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
652 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
653 valid = True
654 else:
655 upscaled_shape = np.array(ifm_shape[1:3])
656 out_shape = np.array(ofm_shape[1:3])
657 while (upscaled_shape < out_shape).all():
658 upscaled_shape *= 2
659 if align_corners:
660 upscaled_shape -= 1
661 # Valid if OFM is 2x IFM (-1 for align corners)
662 if np.array_equal(out_shape, upscaled_shape):
663 valid = True
664 break
665 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
666
667 @staticmethod
668 def constraint_matching_shapes(op):
669 "IFM and OFM shapes must match"
670 ifm_shape = op.ifm.shape
671 ofm_shape = op.ofm.shape
672 valid = ifm_shape == ofm_shape
673 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
674
675 @staticmethod
676 def constraint_splitv_inferred(op):
677 "Only one size is allowed to be inferred"
678 sizes = op.ifm2.values
679 valid = np.count_nonzero(sizes == -1) <= 1
680 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
681
682 @staticmethod
683 def constraint_axis_exists(op):
684 "Axis attribute must exist"
685 axis = op.attrs.get("axis")
686 valid = axis is not None
687 return valid, f"Op has axis={axis}"
688
689 @staticmethod
690 def constraint_axis_valid(op):
691 "Axis attribute must be in the range [0, <ofm_dimensions>)"
692 dims = len(op.ofm.shape)
693 axis = op.attrs["axis"]
694 axis += dims if axis < 0 else 0
695 valid = 0 <= axis < dims
696 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
697
698 @staticmethod
699 def constraint_matching_dimensionality(op):
700 "All Input dimensionalities must match OFM dimensionality"
701 valid = True
702 extra = []
703 ofm_dim = len(op.ofm.shape)
704 tensors = [tens for tens in op.inputs if tens]
705 for tens in tensors:
706 dim = len(tens.shape)
707 if dim != ofm_dim:
708 valid = False
709 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
710 extra = ", ".join(extra)
711 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
712
713 @staticmethod
714 def constraint_valid_dimensions(op):
715 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
716 valid = True
717 extra = []
718 ofm_shape = op.ofm.shape
719 ofm_dim = len(ofm_shape)
720 axis = op.attrs["axis"]
721 axis += ofm_dim if axis < 0 else 0
722 tensors = [tens for tens in op.inputs if tens]
723 for tens in tensors:
724 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
725 valid = False
726 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
727 extra = ", ".join(extra)
728 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
729
730 @staticmethod
731 def constraint_stridedslice_input_count(op):
732 "Exactly 4 Input tensors are required"
733 inputs = len(op.inputs)
734 valid = inputs == 4
735 return valid, f"Op has {inputs} inputs"
736
737 @staticmethod
738 def constraint_stridedslice_inputs_const(op):
739 "Begin, End and Stride Input tensors must be constant"
740 valid = True
741 extra = []
742 _, begin, end, strides = op.inputs
743 if begin.values is None:
744 valid = False
745 extra.append(f"Begin tensor '{begin.name}'")
746 if end.values is None:
747 valid = False
748 extra.append(f"End tensor '{end.name}'")
749 if strides.values is None:
750 valid = False
751 extra.append(f"Stride tensor '{strides.name}'")
752 extra = ", ".join(extra)
753 return valid, f"Op has non-constant tensors: {extra}"
754
755 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100756 def constraint_stridedslice_stride_values(op):
757 "All Strides values must be 1"
758 strides = op.inputs[3]
759 valid = all(stride == 1 for stride in strides.values)
760 return valid, f"Op has strides values {strides.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100761
Michael McGeagh65fd9982020-10-20 11:49:28 +0100762 @staticmethod
763 def constraint_ellipsis_mask(op):
764 "ellipsis_mask must be 0"
765 ellipsis = op.attrs["ellipsis_mask"]
766 valid = ellipsis == 0
767 return valid, f"Op has ellipsis mask as: {ellipsis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200768
Michael McGeagh65fd9982020-10-20 11:49:28 +0100769 @staticmethod
770 def constraint_axis_masks(op):
771 "new_axis_mask and shrink_axis_mask cannot both be set"
772 new_axis = op.attrs["new_axis_mask"]
773 shrink_axis = op.attrs["shrink_axis_mask"]
774 valid = (new_axis == 0) or (shrink_axis == 0)
775 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200776
Michael McGeagh65fd9982020-10-20 11:49:28 +0100777 @staticmethod
778 def constraint_slice_ranges(op):
779 "Slice 'end' values must be greater than 'begin' values"
780 ifm, begin, end, _ = op.inputs
781 # Calculate offset begin/end
782 offset_begin = get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
783 offset_end = get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
784 # Check "end - begin" doesn't result in any zero or negative elements
785 valid = all((e - b) > 0 for b, e in zip(offset_begin, offset_end))
786 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100787
Michael McGeagh65fd9982020-10-20 11:49:28 +0100788 @staticmethod
789 def constraint_matching_inputs_types(op):
790 "Both Input data types must match"
791 ifm_dtype = op.ifm.dtype
792 ifm2_dtype = op.ifm2.dtype
793 valid = ifm_dtype == ifm2_dtype
794 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100795
Michael McGeagh65fd9982020-10-20 11:49:28 +0100796 @staticmethod
797 def constraint_matching_signed(op):
798 "For IFM that are signed, OFM must also be signed"
799 valid = True
800 ifm_dtype = op.ifm.dtype
801 ofm_dtype = op.ofm.dtype
802 if ifm_dtype.type & BaseType.Signed:
803 valid = bool(ofm_dtype.type & BaseType.Signed)
804 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100805
Michael McGeagh65fd9982020-10-20 11:49:28 +0100806 @staticmethod
807 def constraint_unsigned_valid(op):
808 "For IFM that are unsigned, OFM must either be the same type or int32"
809 valid = True
810 ifm_dtype = op.ifm.dtype
811 ofm_dtype = op.ofm.dtype
812 if ifm_dtype.type & BaseType.Unsigned:
813 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
814 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100815
Michael McGeagh65fd9982020-10-20 11:49:28 +0100816 @staticmethod
817 def constraint_inputs_int32(op):
818 "Both Input data types must be int32"
819 ifm_dtype = op.ifm.dtype
820 ifm2_dtype = op.ifm2.dtype
821 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
822 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100823
Michael McGeagh65fd9982020-10-20 11:49:28 +0100824 @staticmethod
825 def constraint_output_int32(op):
826 "OFM must be int32"
827 ofm_dtype = op.ofm.dtype
828 valid = ofm_dtype == DataType.int32
829 return valid, f"Op has ofm_dtype={ofm_dtype}"
Dwight Lidman42fed942020-05-29 09:37:03 +0200830
Michael McGeagh65fd9982020-10-20 11:49:28 +0100831 @staticmethod
832 def constraint_matching_quantization_parameters(op):
833 "Both Input quantization parameters must match OFM quantization parameters"
834 valid = True
835 extra = []
836 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
837 valid = False
838 extra.append(op.ifm.name)
839 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
840 valid = False
841 extra.append(op.ifm2.name)
842 extra = ", ".join(extra)
843 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200844
Michael McGeagh65fd9982020-10-20 11:49:28 +0100845 @staticmethod
846 def constraint_elemwise_batch_size(op):
847 "Batch size must be 1 for Input tensors with more than 2 dimensions"
848 valid = True
849 extra = []
850 for tens in (op.ifm, op.ifm2):
851 # Unary ops have ifm2 as None
852 if tens is not None:
853 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
854 valid = False
855 extra.append(tens.name)
856 extra = ", ".join(extra)
857 return valid, f"Op has invalid input tensors: {extra}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200858
Michael McGeagh65fd9982020-10-20 11:49:28 +0100859 @staticmethod
860 def constraint_matching_either_shapes(op):
861 "At least one Input's shape must match the OFM's shape"
862 ifm_shape = op.ifm.shape
863 ifm2_shape = op.ifm2.shape if op.ifm2 else None
864 ofm_shape = op.ofm.shape
865 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
866 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 +0200867
Michael McGeagh65fd9982020-10-20 11:49:28 +0100868 @staticmethod
869 def constraint_alpha_valid(op):
870 "Alpha must not be negative"
871 alpha = op.attrs["alpha"]
872 valid = alpha >= 0
873 return valid, f"Op has alpha={alpha}"