blob: 99a4ba109e22bd310fd8d622c39bcf79c8fbad2a [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# The SupportedOperators class which is a collection of all supported operators and parameter checks.
Michael McGeagh1f951fc2020-10-14 09:30:02 +010018from collections import defaultdict
19
Charles Xu87c13502020-08-06 12:17:26 +020020import numpy as np
21
Tim Hallc30f4952020-06-15 20:47:35 +010022from .data_type import BaseType
23from .data_type import DataType
Dwight Lidman8359a472020-09-28 15:53:40 +020024from .numeric_util import is_integer
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020025from .operation import get_slice_offsets
Louis Verhaardaee5d752020-09-30 09:01:52 +020026from .operation import Op
Michael McGeagh16895482020-12-14 15:51:20 +000027from .operation import Padding
Tim Hall93582962020-09-09 21:58:15 +010028from .tensor import check_quantized_tens_scaling_equal
Michael McGeagh837dc1b2020-11-10 12:38:25 +000029from .tflite_mapping import BUILTIN_OPERATOR_UNKNOWN
Michael McGeagh219ec072020-11-09 11:11:26 +000030from .tflite_mapping import optype_to_builtintype
Louis Verhaardfa2f92a2020-09-21 11:56:18 +020031
32
Michael McGeagh37ded342020-10-01 15:37:44 +010033# Custom decorator function to allow formatting docstrings containing "{}"
34def docstring_format_args(args):
35 def docstring(func):
36 func.__doc__ = func.__doc__.format(*args)
37 return func
38
39 return docstring
40
41
Michael McGeagh34d29172020-11-25 12:36:23 +000042def _list_formatter(arg):
43 # Order and join into a string representation
44 return ", ".join(sorted(map(str, arg)))
45
46
Michael McGeagh837dc1b2020-11-10 12:38:25 +000047def _optype_formatter(op_list):
48 # Convert internal op types to external names
49 output = map(optype_to_builtintype, op_list)
50 # Remove UNKNOWNs
51 output = (x for x in output if x is not BUILTIN_OPERATOR_UNKNOWN)
Michael McGeagh34d29172020-11-25 12:36:23 +000052 return _list_formatter(output)
Michael McGeagh837dc1b2020-11-10 12:38:25 +000053
54
Tim Hall79d07d22020-04-27 18:20:16 +010055class SupportedOperators:
Michael McGeagh1eeea512020-09-30 14:23:09 +010056 # Categorised lists of supported operators
Louis Verhaardaee5d752020-09-30 09:01:52 +020057 npu_pre_ops = set((Op.SplitSliceRead,))
58 convolution_ops = set((Op.Conv2DBias, Op.Conv2D, Op.QuantizedConv2D,))
59 depthwise_convolution_ops = set((Op.DepthwiseConv2DBias,))
60 transpose_convolution_ops = set((Op.Conv2DBackpropInput,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010061 convolution_like_ops = convolution_ops | depthwise_convolution_ops | transpose_convolution_ops
Louis Verhaardaee5d752020-09-30 09:01:52 +020062 max_pooling_ops = Op.op_set(Op.is_maxpool_op)
63 avg_pooling_ops = Op.op_set(Op.is_avgpool_op)
64 pooling_ops = set((Op.ReduceSum,)) | max_pooling_ops | avg_pooling_ops
65 resizing_ops = set((Op.ResizeBilinear,))
66 fc_vector_products = set((Op.QuantizedMatMul, Op.MatMul, Op.FullyConnected,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010067 mac_main_ops = (
68 # RNN/LSTM/GRU
Louis Verhaardaee5d752020-09-30 09:01:52 +020069 set((Op.BlockLSTM,))
Michael McGeagh1f951fc2020-10-14 09:30:02 +010070 # conv/depthwiseconv/transposeconv
71 | convolution_like_ops
Michael McGeagh1eeea512020-09-30 14:23:09 +010072 # pooling
73 | pooling_ops
74 # resizing/upscaling
75 | resizing_ops
76 # FC layers
77 | fc_vector_products
78 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020079 unary_elem_wise_main_ops = Op.op_set(Op.is_unary_elementwise_op)
80 binary_elem_wise_min_max_ops = set((Op.Minimum, Op.Maximum,))
81 binary_elem_wise_shift_ops = set((Op.SHL, Op.SHR,))
82 binary_elem_wise_add_mul_sub = set((Op.Add, Op.Mul, Op.Sub,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010083 binary_elem_wise_main_ops = binary_elem_wise_min_max_ops | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
84 elem_wise_main_ops = binary_elem_wise_main_ops | unary_elem_wise_main_ops
Erik Anderssonf27a8b62020-12-10 14:58:23 +010085 pad_ops = set((Op.Pad,))
Michael McGeagh37ded342020-10-01 15:37:44 +010086 supported_int32_tensor_ops = (
Louis Verhaardaee5d752020-09-30 09:01:52 +020087 set((Op.ReduceSum, Op.CLZ,)) | binary_elem_wise_add_mul_sub | binary_elem_wise_shift_ops
Michael McGeagh37ded342020-10-01 15:37:44 +010088 )
Michael McGeagh65fd9982020-10-20 11:49:28 +010089 relu_ops = Op.op_set(Op.is_relu_op)
Diqing Zhong189f7482021-01-26 12:12:51 +010090 activation_ops = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.Softmax, Op.HardSwish))
Michael McGeagh1eeea512020-09-30 14:23:09 +010091 npu_post_ops = (
Michael McGeagh1eeea512020-09-30 14:23:09 +010092 # activation functions
Louis Verhaardaee5d752020-09-30 09:01:52 +020093 activation_ops
94 # concatenation write direction
95 | set((Op.ConcatSliceWrite,))
96 # Quantization
97 | set((Op.Quantize,))
Michael McGeagh1eeea512020-09-30 14:23:09 +010098 )
Louis Verhaardaee5d752020-09-30 09:01:52 +020099 split_ops = set((Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack,))
100 concat_ops = set((Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack,))
Michael McGeagha648aa92020-11-18 15:44:05 +0000101 memory_only_ops = set((Op.Squeeze, Op.Reshape, Op.QuantizedReshape,)) | concat_ops | split_ops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200102 shapeless_input_ops = binary_elem_wise_main_ops | set((Op.Split, Op.SplitV,))
Dwight Lidmanc7187432020-11-16 17:40:46 +0100103 per_axis_quant_ops = convolution_like_ops # per-axis/channel quantization only currently supported for conv ops
Michael McGeagh65fd9982020-10-20 11:49:28 +0100104 supported_fused_activations = relu_ops | set((Op.Tanh, Op.Sigmoid, Op.LUT,))
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100105 supported_operators = npu_pre_ops | mac_main_ops | elem_wise_main_ops | pad_ops | npu_post_ops | memory_only_ops
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100106 # Supported data types
107 supported_op_dtypes = set((DataType.uint8, DataType.int8, DataType.int16, DataType.int32))
108 supported_bias_dtypes = set((DataType.int32, DataType.int64))
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100109 supported_pad_dtypes = set((DataType.int32, DataType.int64))
Michael McGeagh37ded342020-10-01 15:37:44 +0100110 # Defined ranges for allowed values:
111 tens_dim_range = (1, 65535)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100112 stride_range = (1, 3)
113 dilation_range = (1, 2)
114 dilated_height_range = (1, 64)
115 dilated_product_range = (1, 64 * 64)
116 weights_limit = 127 * 65536
Michael McGeagh65fd9982020-10-20 11:49:28 +0100117 filter_range = (1, 8)
118 filter_height_range = (1, 256)
119 filter_product_range = (1, 256 * 256)
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100120 # Supported consumers
121 supported_pad_consumers = convolution_ops | depthwise_convolution_ops
Michael McGeagh1eeea512020-09-30 14:23:09 +0100122
Fredrik Svedberg880e7352020-08-25 11:31:47 +0200123 def __init__(self):
Michael McGeagh184b2502020-10-09 17:19:52 +0100124 # Setup the generic constraints. Note: the order matters
Michael McGeagh37ded342020-10-01 15:37:44 +0100125 self.generic_constraints = []
Michael McGeagh65fd9982020-10-20 11:49:28 +0100126 self.generic_constraints.append(SupportedOperators.constraint_tens_no_dynamic)
Michael McGeagh37ded342020-10-01 15:37:44 +0100127 self.generic_constraints.append(SupportedOperators.constraint_tens_defined_shape)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100128 self.generic_constraints.append(SupportedOperators.constraint_tens_output_scalar)
129 self.generic_constraints.append(SupportedOperators.constraint_tens_input_scalar)
Michael McGeagh37ded342020-10-01 15:37:44 +0100130 self.generic_constraints.append(SupportedOperators.constraint_tens_shape_size)
131 self.generic_constraints.append(SupportedOperators.constraint_tens_dtype)
Michael McGeagh184b2502020-10-09 17:19:52 +0100132 self.generic_constraints.append(SupportedOperators.constraint_tens_int32_ops)
Michael McGeagh37ded342020-10-01 15:37:44 +0100133 self.generic_constraints.append(SupportedOperators.constraint_tens_dimension)
Dwight Lidman8359a472020-09-28 15:53:40 +0200134 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_none_check)
Michael McGeagh184b2502020-10-09 17:19:52 +0100135 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_scale)
Dwight Lidmanc7187432020-11-16 17:40:46 +0100136 self.generic_constraints.append(SupportedOperators.constraint_tens_quant_per_axis)
Michael McGeagh184b2502020-10-09 17:19:52 +0100137 self.generic_constraints.append(SupportedOperators.constraint_faf)
Louis Verhaard9a0cff12021-01-08 11:17:33 +0100138 self.generic_constraints.append(SupportedOperators.constraint_quant_scale_inf)
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100139
Michael McGeagh65fd9982020-10-20 11:49:28 +0100140 # Setup specific constraints. Note: the order matters
141 self.specific_constraints = defaultdict(list)
142
143 # Conv-like checks:
144 for op_type in SupportedOperators.convolution_like_ops:
145 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
146 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
147 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_type)
148 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilation_range)
149 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_height_range)
150 self.specific_constraints[op_type].append(SupportedOperators.constraint_dilated_product_range)
151 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
152 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
153 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_limit)
154 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
155 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
156 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
157 # Depthwise Conv specific checks:
158 for op_type in SupportedOperators.depthwise_convolution_ops:
159 self.specific_constraints[op_type].append(SupportedOperators.constraint_depth_multiplier)
160 # Transpose Conv specific checks:
161 for op_type in SupportedOperators.transpose_convolution_ops:
162 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_stride)
163 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_same)
164 self.specific_constraints[op_type].append(SupportedOperators.constraint_tconv_valid)
165
166 # Pooling checks:
167 for op_type in SupportedOperators.pooling_ops:
168 self.specific_constraints[op_type].append(SupportedOperators.constraint_batch_size)
169 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_type)
170 self.specific_constraints[op_type].append(SupportedOperators.constraint_stride_range)
171 # AVG pooling specific checks:
172 for op_type in SupportedOperators.avg_pooling_ops:
173 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
174 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
175 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_range)
176 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range_valid_pad)
177 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range_valid_pad)
178 # MAX pooling specific checks:
179 for op_type in SupportedOperators.max_pooling_ops:
180 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
181 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_type)
182 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_height_range)
183 self.specific_constraints[op_type].append(SupportedOperators.constraint_filter_product_range)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100184
185 # Resizing specific checks:
186 for op_type in SupportedOperators.resizing_ops:
187 self.specific_constraints[op_type].append(SupportedOperators.constraint_resize)
188
189 # Vector Product specific checks:
190 for op_type in SupportedOperators.fc_vector_products:
191 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_type)
192 self.specific_constraints[op_type].append(SupportedOperators.constraint_weights_const)
193 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_type)
194 self.specific_constraints[op_type].append(SupportedOperators.constraint_bias_40bit)
195
196 # Concat specific checks:
197 for op_type in (Op.Concat, Op.ConcatTFLite):
198 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_exists)
199 self.specific_constraints[op_type].append(SupportedOperators.constraint_axis_valid)
200 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_dimensionality)
201 self.specific_constraints[op_type].append(SupportedOperators.constraint_valid_dimensions)
202
203 # Element-wise checks:
204 for op_type in SupportedOperators.elem_wise_main_ops:
205 self.specific_constraints[op_type].append(SupportedOperators.constraint_elemwise_batch_size)
206 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_either_shapes)
207 # Unary specific checks:
208 for op_type in SupportedOperators.unary_elem_wise_main_ops:
209 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
210 # Binary Min/Max specific checks:
211 for op_type in SupportedOperators.binary_elem_wise_min_max_ops:
212 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_in_out_types)
213 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_quantization_parameters)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100214 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100215 # Binary Add/Mul/Sub specific checks:
216 for op_type in SupportedOperators.binary_elem_wise_add_mul_sub:
217 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_inputs_types)
218 self.specific_constraints[op_type].append(SupportedOperators.constraint_matching_signed)
219 self.specific_constraints[op_type].append(SupportedOperators.constraint_unsigned_valid)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100220 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100221 # Binary Shift specific checks:
222 for op_type in SupportedOperators.binary_elem_wise_shift_ops:
223 self.specific_constraints[op_type].append(SupportedOperators.constraint_inputs_int32)
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100224 self.specific_constraints[op_type].append(SupportedOperators.constraint_broadcast_shapes)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100225
226 # SHL specific checks:
227 self.specific_constraints[Op.SHL].append(SupportedOperators.constraint_output_int32)
228
229 # CLZ specific checks:
230 self.specific_constraints[Op.CLZ].append(SupportedOperators.constraint_output_int32)
231
232 # Softmax specific checks:
233 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_shapes)
234 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_matching_in_out_types)
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100235 self.specific_constraints[Op.Softmax].append(SupportedOperators.constraint_beta_value_range)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100236
237 # SplitV specific checks:
238 self.specific_constraints[Op.SplitV].append(SupportedOperators.constraint_splitv_inferred)
239
240 # StridedSlice specific checks:
241 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_input_count)
242 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_inputs_const)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100243 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_stridedslice_stride_values)
244 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_ellipsis_mask)
245 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_axis_masks)
246 self.specific_constraints[Op.StridedSlice].append(SupportedOperators.constraint_slice_ranges)
247
248 # LeakyRelu specific checks:
249 self.specific_constraints[Op.LeakyRelu].append(SupportedOperators.constraint_alpha_valid)
Tim Hall79d07d22020-04-27 18:20:16 +0100250
Dwight Lidman0dd21c72020-11-24 13:45:50 +0100251 # FullyConnected specific checks:
252 self.specific_constraints[Op.FullyConnected].append(SupportedOperators.constraint_fc_output_2d)
253
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100254 # Pad specific checks:
255 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_matching_in_out_types)
256 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_matching_quantization_parameters)
257 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_input_count)
258 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_shape)
259 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_padding_dimensions)
260 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_type)
261 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_constant)
262 self.specific_constraints[Op.Pad].append(SupportedOperators.constraint_pad_ofm)
263
Diqing Zhong189f7482021-01-26 12:12:51 +0100264 # HardSwish specific checks:
265 self.specific_constraints[Op.HardSwish].append(SupportedOperators.constraint_input_8bit)
266 self.specific_constraints[Op.HardSwish].append(SupportedOperators.constraint_matching_in_out_types)
267
Tim Hall79d07d22020-04-27 18:20:16 +0100268 def is_operator_supported(self, op):
Michael McGeagh219ec072020-11-09 11:11:26 +0000269 ext_type = optype_to_builtintype(op.type)
Michael McGeagh1eeea512020-09-30 14:23:09 +0100270 if op.type not in SupportedOperators.supported_operators:
Louis Verhaard5f2ea2f2020-10-15 08:39:44 +0200271 if op.type not in (Op.Placeholder, Op.SubgraphInput, Op.Const):
Michael McGeagh219ec072020-11-09 11:11:26 +0000272 print(f"Info: {ext_type} '{op.name}' is a CPU only op")
Tim Hall79d07d22020-04-27 18:20:16 +0100273 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100274
Michael McGeagh65fd9982020-10-20 11:49:28 +0100275 for constraint in self.generic_constraints + self.specific_constraints[op.type]:
Michael McGeagh37ded342020-10-01 15:37:44 +0100276 valid, extra = constraint(op)
277 if not valid:
Michael McGeagh219ec072020-11-09 11:11:26 +0000278 print(f"Warning: {ext_type} '{op.name}' is not supported on the NPU. Placing on CPU instead")
Michael McGeagh65fd9982020-10-20 11:49:28 +0100279 print(f" - {constraint.__doc__}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100280 if extra:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100281 print(f" {extra}")
Michael McGeagh37ded342020-10-01 15:37:44 +0100282 return False
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100283
Tim Hall79d07d22020-04-27 18:20:16 +0100284 return True
285
Michael McGeagh37ded342020-10-01 15:37:44 +0100286 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100287 def constraint_tens_no_dynamic(op):
288 "Input(s) and Output tensors must not be dynamic"
289 valid = True
290 extra = []
291 tensors = [tens for tens in op.inputs + op.outputs if tens]
292 for tens in tensors:
293 if (tens.shape == []) and (tens.values is None):
294 valid = False
295 extra.append(tens.name)
296 extra = ", ".join(extra)
297 return valid, f"Op has dynamic tensor(s): {extra}"
298
299 @staticmethod
Michael McGeagh37ded342020-10-01 15:37:44 +0100300 def constraint_tens_defined_shape(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100301 "Input(s) and Output tensors must have a defined shape"
Michael McGeagh37ded342020-10-01 15:37:44 +0100302 valid = True
303 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100304 tensors = [tens for tens in op.inputs + op.outputs if tens]
305 for tens in tensors:
306 if not tens.has_fully_defined_shape():
307 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100308 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100309 return valid, ", ".join(extra)
Michael McGeagh37ded342020-10-01 15:37:44 +0100310
Michael McGeagh184b2502020-10-09 17:19:52 +0100311 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100312 def constraint_tens_output_scalar(op):
313 "Output tensors cannot be scalar"
314 ofm = op.ofm
315 valid = ofm.shape != []
316 return valid, f"Output Tensor '{ofm.name}' is scalar"
Michael McGeagh184b2502020-10-09 17:19:52 +0100317
318 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000319 @docstring_format_args([_optype_formatter(shapeless_input_ops)])
Michael McGeagh65fd9982020-10-20 11:49:28 +0100320 def constraint_tens_input_scalar(cls, op):
321 "Scalar Input tensors are only valid for op type: {}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100322 valid = True
323 extra = []
324 tensors = [tens for tens in op.inputs if tens]
325 for tens in tensors:
326 if (tens.shape == []) and (op.type not in cls.shapeless_input_ops):
327 valid = False
328 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100329 extra = ", ".join(extra)
330 return valid, f"Op has scalar input tensor(s): {extra}"
Tim Hall79d07d22020-04-27 18:20:16 +0100331
Michael McGeagh37ded342020-10-01 15:37:44 +0100332 @staticmethod
333 def constraint_tens_shape_size(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100334 "Input(s) and Output tensors must not be greater than 4D"
Michael McGeagh37ded342020-10-01 15:37:44 +0100335 valid = True
336 extra = []
Michael McGeagh184b2502020-10-09 17:19:52 +0100337 tensors = [tens for tens in op.inputs + op.outputs if tens]
338 for tens in tensors:
339 if len(tens.shape) > 4:
340 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100341 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100342 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100343
Michael McGeagh37ded342020-10-01 15:37:44 +0100344 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000345 @docstring_format_args([_list_formatter(supported_op_dtypes)])
Michael McGeagh37ded342020-10-01 15:37:44 +0100346 def constraint_tens_dtype(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100347 "Tensors must be of type: {}"
Michael McGeagh37ded342020-10-01 15:37:44 +0100348 valid = True
349 extra = []
350 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100351 if not tensors:
352 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100353 for tens in tensors:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100354 if tens.dtype not in cls.supported_op_dtypes:
Michael McGeagh184b2502020-10-09 17:19:52 +0100355 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100356 extra.append(f"Tensor '{tens.name}' has data type: {tens.dtype}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100357 return valid, ", ".join(extra)
358
359 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000360 @docstring_format_args([_optype_formatter(supported_int32_tensor_ops)])
Michael McGeagh184b2502020-10-09 17:19:52 +0100361 def constraint_tens_int32_ops(cls, op):
362 "Tensors which are int32 are only valid when op type is: {}"
363 valid = True
364 extra = []
365 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100366 if not tensors:
367 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh184b2502020-10-09 17:19:52 +0100368 for tens in tensors:
369 if (tens.dtype == DataType.int32) and (op.type not in cls.supported_int32_tensor_ops):
370 valid = False
371 extra.append(tens.name)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100372 extra = ", ".join(extra)
373 return valid, f"Op has int32 tensor(s): {extra}"
Andreas Nevalaineneadb1662020-09-01 15:36:26 +0200374
Michael McGeagh37ded342020-10-01 15:37:44 +0100375 @classmethod
376 @docstring_format_args(tens_dim_range)
377 def constraint_tens_dimension(cls, op):
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100378 "Tensor dimensions must be in the range [{}, {}]"
Michael McGeagh37ded342020-10-01 15:37:44 +0100379 tens_min, tens_max = cls.tens_dim_range
380 valid = True
381 extra = []
382 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
Michael McGeagh65fd9982020-10-20 11:49:28 +0100383 if not tensors:
384 tensors = [tens for tens in op.inputs if tens]
Michael McGeagh37ded342020-10-01 15:37:44 +0100385 for tens in tensors:
Michael McGeagh184b2502020-10-09 17:19:52 +0100386 if not all(tens_min <= dim <= tens_max for dim in tens.shape):
387 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100388 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100389 return valid, ", ".join(extra)
Tim Hall79d07d22020-04-27 18:20:16 +0100390
Dwight Lidman8359a472020-09-28 15:53:40 +0200391 @staticmethod
392 def constraint_tens_quant_none_check(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100393 "Input(s), Output and Weight tensors must have quantization parameters"
Dwight Lidman8359a472020-09-28 15:53:40 +0200394 valid = True
395 extra = []
396 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
397 for tens in tensors:
398 if tens.quantization is None:
399 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100400 extra.append(tens.name)
401 extra = ", ".join(extra)
402 return valid, f"Op has tensors with missing quantization parameters: {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200403
Michael McGeagh184b2502020-10-09 17:19:52 +0100404 @staticmethod
405 def constraint_tens_quant_scale(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100406 "Input(s), Output and Weight tensors with quantization scales must be finite"
Michael McGeagh184b2502020-10-09 17:19:52 +0100407 valid = True
408 extra = []
409 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
410 for tens in tensors:
411 if (tens.quantization.scale_f32 is not None) and np.isinf(tens.quantization.scale_f32).any():
412 valid = False
Michael McGeagh65fd9982020-10-20 11:49:28 +0100413 extra.append(f"Tensor '{tens.name}' has quantization scale: {tens.quantization.scale_f32}")
Michael McGeagh184b2502020-10-09 17:19:52 +0100414 return valid, ", ".join(extra)
415
416 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000417 @docstring_format_args([_optype_formatter(per_axis_quant_ops)])
Dwight Lidmanc7187432020-11-16 17:40:46 +0100418 def constraint_tens_quant_per_axis(cls, op):
419 "Per-axis quantization is only supported for the following op types: {}"
420 valid = True
421 extra = []
422 if op.type not in cls.per_axis_quant_ops:
423 tensors = [tens for tens in op.get_ifm_ifm2_weights_ofm() if tens]
424 for tens in tensors:
425 if tens.quantization.is_per_axis():
426 valid = False
427 extra.append(tens.name)
428 return valid, "The following tensor(s) have per-axis quantization parameters: " + ", ".join(extra)
429
Dwight Lidman0dd21c72020-11-24 13:45:50 +0100430 @staticmethod
431 def constraint_fc_output_2d(op):
432 "The output tensor(s) must have 2D shape"
433 valid = True
434 extra = []
435 for tens in op.outputs:
436 if len(tens.shape) != 2:
437 valid = False
438 extra.append(f"Tensor '{tens.name}' is {len(tens.shape)}D")
439 return valid, ", ".join(extra)
440
Dwight Lidmanc7187432020-11-16 17:40:46 +0100441 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000442 @docstring_format_args([_optype_formatter(supported_fused_activations)])
Michael McGeagh184b2502020-10-09 17:19:52 +0100443 def constraint_faf(cls, op):
444 "The fused activation function (if present) must be one of type: {}"
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100445 if op.activation is None:
446 res = True, "Op has no fused activation function"
447 else:
448 faf = op.activation.op_type
449 valid = faf in cls.supported_fused_activations
450 res = valid, f"Op has its fused activation function as: {faf}"
451 return res
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100452
453 @staticmethod
454 def constraint_stride_type(op):
455 "Stride values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100456 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100457 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100458 return valid, f"Op has stride WxH as: {repr(w)}x{repr(h)}"
Michael McGeagh184b2502020-10-09 17:19:52 +0100459
Michael McGeagh1eeea512020-09-30 14:23:09 +0100460 @classmethod
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100461 @docstring_format_args(stride_range)
462 def constraint_stride_range(cls, op):
463 "Stride values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100464 w, h = op.get_kernel_stride()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100465 stride_min, stride_max = cls.stride_range
466 valid = (stride_min <= w <= stride_max) and (stride_min <= h <= stride_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100467 return valid, f"Op has stride WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100468
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100469 @staticmethod
470 def constraint_dilation_type(op):
471 "Dilation factor values for both width and height must be integer types"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100472 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100473 valid = is_integer(w) and is_integer(h)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100474 return valid, f"Op has dilation factor WxH as: {repr(w)}x{repr(h)}"
Tim Hall79d07d22020-04-27 18:20:16 +0100475
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100476 @classmethod
477 @docstring_format_args(dilation_range)
478 def constraint_dilation_range(cls, op):
479 "Dilation factor values for both width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100480 w, h = op.get_kernel_dilation()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100481 dilation_min, dilation_max = cls.dilation_range
482 valid = (dilation_min <= w <= dilation_max) and (dilation_min <= h <= dilation_max)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100483 return valid, f"Op has dilation factor WxH as: {w}x{h}"
Tim Hall79d07d22020-04-27 18:20:16 +0100484
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100485 @classmethod
486 @docstring_format_args(dilated_height_range)
487 def constraint_dilated_height_range(cls, op):
488 "Dilated kernel height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100489 h = op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100490 dilated_height_min, dilated_height_max = cls.dilated_height_range
491 valid = dilated_height_min <= h <= dilated_height_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100492 return valid, f"Op has dilated kernel height as: {h}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200493
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100494 @classmethod
495 @docstring_format_args(dilated_product_range)
496 def constraint_dilated_product_range(cls, op):
497 "Product of dilated kernel width and height must be in the range [{}, {}]"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100498 product = op.kernel.area_width() * op.kernel.area_height()
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100499 dilated_product_min, dilated_product_max = cls.dilated_product_range
500 valid = dilated_product_min <= product <= dilated_product_max
Michael McGeagh65fd9982020-10-20 11:49:28 +0100501 return valid, f"Op has product of dilated kernel width and height as: {product}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200502
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100503 @staticmethod
504 def constraint_weights_type(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100505 "Weight tensor must be 8-bit"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100506 weights = op.weights
507 valid = weights.element_size() == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100508 return valid, f"Tensor '{weights.name}' is {int(weights.element_size() * 8)}-bit"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200509
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100510 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100511 def constraint_weights_const(op):
512 "Weight tensor must be constant"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100513 weights = op.weights
514 valid = weights.values is not None
Michael McGeagh65fd9982020-10-20 11:49:28 +0100515 return valid, f"Tensor '{weights.name}' has non-constant values"
Andreas Nevalainen8854dc92020-09-24 13:43:00 +0200516
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100517 @classmethod
518 @docstring_format_args([weights_limit])
519 def constraint_weights_limit(cls, op):
520 "The sum of the weights cannot exceed {}"
521 weights = op.weights
522 values = weights.quant_values.astype(np.int64) - weights.quantization.zero_point
523 limit = np.amax(np.sum(np.absolute(values), axis=(0, 1, 2)))
524 valid = limit <= cls.weights_limit
Michael McGeagh65fd9982020-10-20 11:49:28 +0100525 return valid, f"Tensor '{weights.name}' has the sum of weights: {limit}"
Andreas Nevalainenf0c59bf2020-08-26 10:56:23 +0200526
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100527 @classmethod
Michael McGeagh34d29172020-11-25 12:36:23 +0000528 @docstring_format_args([_list_formatter(supported_bias_dtypes)])
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100529 def constraint_bias_type(cls, op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100530 "Optional Bias tensor must be of type: {}"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100531 bias = op.bias
532 if bias:
533 valid = bias.dtype in cls.supported_bias_dtypes
Michael McGeagh65fd9982020-10-20 11:49:28 +0100534 return valid, f"Tensor '{bias.name}' has data type: {bias.dtype}"
535 return True, "Op has no bias tensor"
Tim Hall79d07d22020-04-27 18:20:16 +0100536
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100537 @staticmethod
538 def constraint_bias_40bit(op):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100539 "Optional Bias tensor values must fit within 40-bits"
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100540 bias = op.bias
Fredrik Svedbergbdf09f92020-11-18 11:30:21 +0100541 if bias and bias.dtype == DataType.int64 and bias.quant_values is not None:
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100542 valid = all(len(bin(quant_value)[2:]) <= 40 for quant_value in bias.quant_values)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100543 return valid, f"Tensor '{bias.name}' has values larger than 40-bits"
544 return True, "Op has no bias tensor, or it fits in 40-bit"
Andreas Nevalainend8c032d2020-09-11 10:25:09 +0200545
Michael McGeagh1f951fc2020-10-14 09:30:02 +0100546 @staticmethod
547 def constraint_batch_size(op):
548 "IFM Tensor batch size must be 1"
549 ifm = op.ifm
550 valid = ifm.shape[0] == 1
Michael McGeagh65fd9982020-10-20 11:49:28 +0100551 return valid, f"Tensor '{ifm.name}' has batch size: {ifm.shape[0]}"
552
553 @staticmethod
554 def constraint_quant_scale_inf(op):
Louis Verhaard9a0cff12021-01-08 11:17:33 +0100555 "Input and Output tensors must have quantization scales that fit within float32 precision"
556 if op.ofm is not None and op.ofm.is_quantized():
557 ofm_scale = op.ofm.quantization.scale_f32
558 if ofm_scale < np.finfo(np.float32).tiny:
559 return (
560 False,
561 f"The quantization scale of the output tensor is {ofm_scale}, "
562 + f"minimum supported is: {np.finfo(np.float32).tiny}",
563 )
564 if op.ifm is not None and op.ifm.is_quantized():
565 ifm_scale = op.ifm.quantization.scale_f32
566 if np.isinf(ifm_scale / ofm_scale):
567 return (
568 False,
569 f"IFM scale divided by OFM scale is infinite, ifm_scale={ifm_scale} ofm_scale={ofm_scale}",
570 )
571 return True, "Op's quantization is ok"
Michael McGeagh65fd9982020-10-20 11:49:28 +0100572
573 @staticmethod
574 def constraint_depth_multiplier(op):
575 "For depth multipliers > 1, IFM channels must be 1 and OFM channels must be equal to the depth multiplier"
576 depth_multiplier = op.attrs.get("depth_multiplier", 1)
577 if depth_multiplier > 1:
578 ifm_channels = op.ifm.shape[3]
579 ofm_channels = op.ofm.shape[3]
580 valid = (ifm_channels == 1) and (ofm_channels == depth_multiplier)
581 extra = (
582 f"Op has ifm_channels={ifm_channels}, ofm_channels={ofm_channels}"
583 f" and depth_multiplier={depth_multiplier}"
584 )
585 return valid, extra
586 return True, "Op has depth_multiplier=1"
587
588 @staticmethod
589 def constraint_tconv_stride(op):
590 "Stride values for both width and height must be 2"
591 w = op.kernel.stride.x
592 h = op.kernel.stride.y
593 valid = (w == 2) and (h == 2)
594 return valid, f"Op has stride WxH as: {w}x{h}"
595
596 @staticmethod
597 def constraint_tconv_same(op):
598 "SAME padding: OFM dimensions must equal IFM dimensions multiplied by stride"
Michael McGeagh16895482020-12-14 15:51:20 +0000599 if op.attrs["padding"] == Padding.SAME:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100600 w = op.kernel.stride.x
601 h = op.kernel.stride.y
602 ifm_shape = op.ifm.shape
603 ofm_shape = op.ofm.shape
604 valid = (ofm_shape[1] == (ifm_shape[1] * h)) and (ofm_shape[2] == (ifm_shape[2] * w))
605 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and stride WxH as {w}x{h}"
606 return True, "Op has padding=VALID"
607
608 @staticmethod
609 def constraint_tconv_valid(op):
610 """VALID padding: OFM dimensions must equal IFM dimensions multiplied by stride,
611 minus difference between kernel size and stride"""
Michael McGeagh16895482020-12-14 15:51:20 +0000612 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100613 s_w = op.kernel.stride.x
614 s_h = op.kernel.stride.y
615 k_w = op.kernel.width
616 k_h = op.kernel.height
617 ifm_shape = op.ifm.shape
618 ofm_shape = op.ofm.shape
619 height_check = ofm_shape[1] == (ifm_shape[1] * s_h + max(k_h - s_h, 0))
620 width_check = ofm_shape[2] == (ifm_shape[2] * s_w + max(k_w - s_w, 0))
621 valid = height_check and width_check
622 extra = (
623 f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape},"
624 f" stride WxH as {s_w}x{s_h} and kernel WxH as {k_w}x{k_h}"
625 )
626 return valid, extra
627 return True, "Op has padding=SAME"
628
629 @staticmethod
630 def constraint_matching_in_out_types(op):
631 "IFM and OFM data types must match"
632 ifm_dtype = op.ifm.dtype
633 ofm_dtype = op.ofm.dtype
634 valid = ifm_dtype == ofm_dtype
635 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
636
637 @staticmethod
Patrik Gustavsson2fa15882020-11-13 09:02:31 +0100638 def constraint_beta_value_range(op):
639 "Beta value needs to be positive"
640 beta = op.attrs.get("beta", 1.0)
641 valid = beta >= 0
642 return valid, f"Op has beta={beta}"
643
644 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100645 def constraint_filter_type(op):
646 "Kernel filter values for both width and height must be integer types"
647 w = op.kernel.width
648 h = op.kernel.height
649 valid = is_integer(w) and is_integer(h)
650 return valid, f"Op has kernel filter WxH as: {repr(w)}x{repr(h)}"
651
652 @classmethod
653 @docstring_format_args(filter_range)
654 def constraint_filter_range(cls, op):
655 "Kernel filter values for both width and height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000656 if op.attrs["padding"] == Padding.SAME:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100657 w = op.kernel.width
658 h = op.kernel.height
659 filter_min, filter_max = cls.filter_range
660 valid = (filter_min <= w <= filter_max) and (filter_min <= h <= filter_max)
661 return valid, f"Op has kernel filter WxH as: {w}x{h}"
662 return True, "Op has padding=VALID"
663
664 @classmethod
665 @docstring_format_args(filter_height_range)
666 def constraint_filter_height_range(cls, op):
667 "Kernel filter height must be in the range [{}, {}]"
668 h = op.kernel.height
669 filter_height_min, filter_height_max = cls.filter_height_range
670 valid = filter_height_min <= h <= filter_height_max
671 return valid, f"Op has kernel filter height as: {h}"
672
673 @classmethod
674 @docstring_format_args(filter_product_range)
675 def constraint_filter_product_range(cls, op):
676 "Product of kernel filter width and height must be in the range [{}, {}]"
677 product = op.kernel.elements_wh()
678 filter_product_min, filter_product_max = cls.filter_product_range
679 valid = filter_product_min <= product <= filter_product_max
680 return valid, f"Op has product of kernel filter width and height as: {product}"
681
682 @staticmethod
683 @docstring_format_args(filter_height_range)
684 def constraint_filter_height_range_valid_pad(op):
685 "VALID padding: Kernel filter height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000686 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100687 return SupportedOperators.constraint_filter_height_range(op)
688 return True, "Op has padding=SAME"
689
690 @staticmethod
691 @docstring_format_args(filter_product_range)
692 def constraint_filter_product_range_valid_pad(op):
693 "VALID padding: Product of kernel filter width and height must be in the range [{}, {}]"
Michael McGeagh16895482020-12-14 15:51:20 +0000694 if op.attrs["padding"] == Padding.VALID:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100695 return SupportedOperators.constraint_filter_product_range(op)
696 return True, "Op has padding=SAME"
697
698 @staticmethod
699 def constraint_resize(op):
700 """The width and height of the IFM and OFM must match one of the following criteria:
701 IFM W and H must both be 1
702 IFM must match OFM
703 OFM W and H must be 2x IFM -1, if align_corners is True
704 OFM W and H must be 2x IFM, if align_corners is False"""
705 # Easier to start with False condition as very few cases result in a supported resize
706 valid = False
707 ifm_shape = op.ifm.shape
708 ofm_shape = op.ofm.shape
709 align_corners = op.attrs.get("align_corners", False)
710 if len(ifm_shape) == 4:
711 # Valid if IFM W and H are both 1, or IFM and OFM shape are the same
712 if ((ifm_shape[1] == 1) and (ifm_shape[2] == 1)) or (ifm_shape == ofm_shape):
713 valid = True
714 else:
715 upscaled_shape = np.array(ifm_shape[1:3])
716 out_shape = np.array(ofm_shape[1:3])
717 while (upscaled_shape < out_shape).all():
718 upscaled_shape *= 2
719 if align_corners:
720 upscaled_shape -= 1
721 # Valid if OFM is 2x IFM (-1 for align corners)
722 if np.array_equal(out_shape, upscaled_shape):
723 valid = True
724 break
725 return valid, f"Op has ifm_shape={ifm_shape}, ofm_shape={ofm_shape} and align_corners={align_corners}"
726
727 @staticmethod
728 def constraint_matching_shapes(op):
729 "IFM and OFM shapes must match"
730 ifm_shape = op.ifm.shape
731 ofm_shape = op.ofm.shape
732 valid = ifm_shape == ofm_shape
733 return valid, f"Op has ifm_shape={ifm_shape} and ofm_shape={ofm_shape}"
734
735 @staticmethod
736 def constraint_splitv_inferred(op):
737 "Only one size is allowed to be inferred"
Jacob Bohline3de4e52020-11-27 14:52:06 +0100738 sizes = op.inputs[1].values
Michael McGeagh65fd9982020-10-20 11:49:28 +0100739 valid = np.count_nonzero(sizes == -1) <= 1
740 return valid, f"Op has multiple inferred sizes (-1): {sizes}"
741
742 @staticmethod
743 def constraint_axis_exists(op):
744 "Axis attribute must exist"
745 axis = op.attrs.get("axis")
746 valid = axis is not None
747 return valid, f"Op has axis={axis}"
748
749 @staticmethod
750 def constraint_axis_valid(op):
751 "Axis attribute must be in the range [0, <ofm_dimensions>)"
752 dims = len(op.ofm.shape)
753 axis = op.attrs["axis"]
754 axis += dims if axis < 0 else 0
755 valid = 0 <= axis < dims
756 return valid, f"Op has ofm_dimensions={dims} and axis attribute is: {axis}"
757
758 @staticmethod
759 def constraint_matching_dimensionality(op):
760 "All Input dimensionalities must match OFM dimensionality"
761 valid = True
762 extra = []
763 ofm_dim = len(op.ofm.shape)
764 tensors = [tens for tens in op.inputs if tens]
765 for tens in tensors:
766 dim = len(tens.shape)
767 if dim != ofm_dim:
768 valid = False
769 extra.append(f"Tensor '{tens.name}' has dimension: {dim}")
770 extra = ", ".join(extra)
771 return valid, f"Op has ofm_dimension={ofm_dim} and the list of mismatching inputs are: {extra}"
772
773 @staticmethod
774 def constraint_valid_dimensions(op):
775 "All Input dimensions must match OFM dimension in all axes except the one defined by the axis attribute"
776 valid = True
777 extra = []
778 ofm_shape = op.ofm.shape
779 ofm_dim = len(ofm_shape)
780 axis = op.attrs["axis"]
781 axis += ofm_dim if axis < 0 else 0
782 tensors = [tens for tens in op.inputs if tens]
783 for tens in tensors:
784 if any(tens.shape[dim] != ofm_shape[dim] for dim in range(ofm_dim) if dim != axis):
785 valid = False
786 extra.append(f"Tensor '{tens.name}' has shape: {tens.shape}")
787 extra = ", ".join(extra)
788 return valid, f"Op has axis={axis}, ofm_shape={ofm_shape} and the list of mismatching inputs are: {extra}"
789
790 @staticmethod
791 def constraint_stridedslice_input_count(op):
792 "Exactly 4 Input tensors are required"
793 inputs = len(op.inputs)
794 valid = inputs == 4
795 return valid, f"Op has {inputs} inputs"
796
797 @staticmethod
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100798 def constraint_pad_input_count(op):
799 "Number of input tensors must be exactly 2"
800 inputs = len(op.inputs)
801 valid = inputs == 2
802 return valid, f"Op has {inputs} inputs"
803
804 @staticmethod
805 def constraint_pad_shape(op):
806 "The padding tensor must have the shape [4,2]"
807 valid = op.inputs[1].shape == [4, 2]
808 return valid, f"The pad tensor has the shape: {op.inputs[1].shape}"
809
810 @classmethod
811 @docstring_format_args([_list_formatter(supported_pad_dtypes)])
812 def constraint_pad_type(cls, op):
813 "Pad tensor must be of type: {}"
814 pad_tensor = op.inputs[1]
815 valid = pad_tensor.dtype in cls.supported_pad_dtypes
816 return valid, f"Tensor '{pad_tensor.name}' has data type: {pad_tensor.dtype}"
817
818 @staticmethod
819 def constraint_padding_dimensions(op):
820 "The pad tensor can only pad width and height"
821 pad_tensor = op.inputs[1].values
822 valid = sum(pad_tensor[0, :]) + sum(pad_tensor[-1, :]) == 0
823 return valid, f"First dimension padding: {pad_tensor[0,:]}, last dimension padding: {pad_tensor[-1,:]}"
824
825 @staticmethod
826 def constraint_pad_constant(op):
827 pad_tensor = op.inputs[1].values
828 valid = pad_tensor is not None
829 return valid, f"Op has non-constant padding tensor: {op.inputs[1].values}"
830
831 @classmethod
832 @docstring_format_args([_optype_formatter(supported_pad_consumers)])
833 def constraint_pad_ofm(cls, op):
834 "Must be followed by one of the following operator types: {}"
835 consumers = op.ofm.consumers()
erik.andersson@arm.com7b676492021-01-18 14:23:12 +0100836 unsupported_consumers = [
837 cons.type
838 for cons in consumers
839 if cons is not None
840 if cons.type not in cls.supported_pad_consumers or cons.attrs["padding"] != Padding.VALID
841 ] + [None for cons in consumers if cons is None]
842 none_string = ", ".join(["NoneType" for cons in consumers if cons is None])
843 valid = len(unsupported_consumers) == 0
844 return valid, f"PAD operator is followed by: {_optype_formatter(unsupported_consumers)+none_string}"
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100845
846 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100847 def constraint_stridedslice_inputs_const(op):
848 "Begin, End and Stride Input tensors must be constant"
849 valid = True
850 extra = []
851 _, begin, end, strides = op.inputs
852 if begin.values is None:
853 valid = False
854 extra.append(f"Begin tensor '{begin.name}'")
855 if end.values is None:
856 valid = False
857 extra.append(f"End tensor '{end.name}'")
858 if strides.values is None:
859 valid = False
860 extra.append(f"Stride tensor '{strides.name}'")
861 extra = ", ".join(extra)
862 return valid, f"Op has non-constant tensors: {extra}"
863
864 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100865 def constraint_stridedslice_stride_values(op):
866 "All Strides values must be 1"
867 strides = op.inputs[3]
868 valid = all(stride == 1 for stride in strides.values)
869 return valid, f"Op has strides values {strides.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100870
Michael McGeagh65fd9982020-10-20 11:49:28 +0100871 @staticmethod
872 def constraint_ellipsis_mask(op):
873 "ellipsis_mask must be 0"
874 ellipsis = op.attrs["ellipsis_mask"]
875 valid = ellipsis == 0
876 return valid, f"Op has ellipsis mask as: {ellipsis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200877
Michael McGeagh65fd9982020-10-20 11:49:28 +0100878 @staticmethod
879 def constraint_axis_masks(op):
880 "new_axis_mask and shrink_axis_mask cannot both be set"
881 new_axis = op.attrs["new_axis_mask"]
882 shrink_axis = op.attrs["shrink_axis_mask"]
883 valid = (new_axis == 0) or (shrink_axis == 0)
884 return valid, f"Op has new_axis_mask={new_axis} and shrink_axis_mask={shrink_axis}"
Jacob Bohlincf7da102020-05-20 09:03:40 +0200885
Michael McGeagh65fd9982020-10-20 11:49:28 +0100886 @staticmethod
887 def constraint_slice_ranges(op):
888 "Slice 'end' values must be greater than 'begin' values"
889 ifm, begin, end, _ = op.inputs
890 # Calculate offset begin/end
891 offset_begin = get_slice_offsets(ifm.shape, begin, op.attrs["begin_mask"], is_begin=True)
892 offset_end = get_slice_offsets(ifm.shape, end, op.attrs["end_mask"], is_begin=False)
893 # Check "end - begin" doesn't result in any zero or negative elements
894 valid = all((e - b) > 0 for b, e in zip(offset_begin, offset_end))
895 return valid, f"Op has begin_values={begin.values} and end_values={end.values}"
Tim Hall79d07d22020-04-27 18:20:16 +0100896
Michael McGeagh65fd9982020-10-20 11:49:28 +0100897 @staticmethod
898 def constraint_matching_inputs_types(op):
899 "Both Input data types must match"
900 ifm_dtype = op.ifm.dtype
901 ifm2_dtype = op.ifm2.dtype
902 valid = ifm_dtype == ifm2_dtype
903 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100904
Michael McGeagh65fd9982020-10-20 11:49:28 +0100905 @staticmethod
906 def constraint_matching_signed(op):
907 "For IFM that are signed, OFM must also be signed"
908 valid = True
909 ifm_dtype = op.ifm.dtype
910 ofm_dtype = op.ofm.dtype
911 if ifm_dtype.type & BaseType.Signed:
912 valid = bool(ofm_dtype.type & BaseType.Signed)
913 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100914
Michael McGeagh65fd9982020-10-20 11:49:28 +0100915 @staticmethod
916 def constraint_unsigned_valid(op):
917 "For IFM that are unsigned, OFM must either be the same type or int32"
918 valid = True
919 ifm_dtype = op.ifm.dtype
920 ofm_dtype = op.ofm.dtype
921 if ifm_dtype.type & BaseType.Unsigned:
922 valid = (ifm_dtype == ofm_dtype) or (ofm_dtype == DataType.int32)
923 return valid, f"Op has ifm_dtype={ifm_dtype} and ofm_dtype={ofm_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100924
Michael McGeagh65fd9982020-10-20 11:49:28 +0100925 @staticmethod
926 def constraint_inputs_int32(op):
927 "Both Input data types must be int32"
928 ifm_dtype = op.ifm.dtype
929 ifm2_dtype = op.ifm2.dtype
930 valid = (ifm_dtype == DataType.int32) and (ifm2_dtype == DataType.int32)
931 return valid, f"Op has ifm_dtype={ifm_dtype} and ifm2_dtype={ifm2_dtype}"
Tim Hall79d07d22020-04-27 18:20:16 +0100932
Michael McGeagh65fd9982020-10-20 11:49:28 +0100933 @staticmethod
934 def constraint_output_int32(op):
935 "OFM must be int32"
936 ofm_dtype = op.ofm.dtype
937 valid = ofm_dtype == DataType.int32
938 return valid, f"Op has ofm_dtype={ofm_dtype}"
Dwight Lidman42fed942020-05-29 09:37:03 +0200939
Michael McGeagh65fd9982020-10-20 11:49:28 +0100940 @staticmethod
Diqing Zhong189f7482021-01-26 12:12:51 +0100941 def constraint_input_8bit(op):
942 "IFM must be int8 or uint8"
943 ifm_dtype = op.ifm.dtype
944 valid = (ifm_dtype == DataType.int8) or (ifm_dtype == DataType.uint8)
945 return valid, f"Op has ifm_dtype={ifm_dtype}"
946
947 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +0100948 def constraint_matching_quantization_parameters(op):
949 "Both Input quantization parameters must match OFM quantization parameters"
950 valid = True
951 extra = []
952 if not check_quantized_tens_scaling_equal(op.ofm, op.ifm):
953 valid = False
954 extra.append(op.ifm.name)
Erik Anderssonf27a8b62020-12-10 14:58:23 +0100955 if op.ifm2 is not None and not check_quantized_tens_scaling_equal(op.ofm, op.ifm2):
Michael McGeagh65fd9982020-10-20 11:49:28 +0100956 valid = False
957 extra.append(op.ifm2.name)
958 extra = ", ".join(extra)
959 return valid, f"Op has tensors with different quantization parameters to the OFM '{op.ofm.name}': {extra}"
Dwight Lidman8359a472020-09-28 15:53:40 +0200960
Michael McGeagh65fd9982020-10-20 11:49:28 +0100961 @staticmethod
962 def constraint_elemwise_batch_size(op):
963 "Batch size must be 1 for Input tensors with more than 2 dimensions"
964 valid = True
965 extra = []
966 for tens in (op.ifm, op.ifm2):
967 # Unary ops have ifm2 as None
968 if tens is not None:
969 if (len(tens.shape) > 2) and (tens.shape[0] != 1):
970 valid = False
971 extra.append(tens.name)
972 extra = ", ".join(extra)
973 return valid, f"Op has invalid input tensors: {extra}"
Jacob Bohlin49d92122020-08-19 14:36:46 +0200974
Michael McGeagh65fd9982020-10-20 11:49:28 +0100975 @staticmethod
976 def constraint_matching_either_shapes(op):
977 "At least one Input's shape must match the OFM's shape"
978 ifm_shape = op.ifm.shape
979 ifm2_shape = op.ifm2.shape if op.ifm2 else None
980 ofm_shape = op.ofm.shape
981 valid = (ifm_shape == ofm_shape) or (ifm2_shape == ofm_shape)
982 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 +0200983
Michael McGeagh65fd9982020-10-20 11:49:28 +0100984 @staticmethod
Andreas Nevalainend059d8b2020-11-19 14:40:35 +0100985 def constraint_broadcast_shapes(op):
986 "Broadcasting is only allowed for rank indices with dimension 1, from either IFM1 or IFM2"
987 ifm_shape = op.ifm.shape
988 ifm2_shape = op.ifm2.shape if op.ifm2 else None
989 ofm_shape = op.ofm.shape
990 valid = True
991 if ifm_shape is not None and ifm2_shape is not None:
992 # align trailing dimensions
993 size = min(len(ifm_shape), len(ifm2_shape))
994 for i, i2, o in zip(ifm_shape[-size:], ifm2_shape[-size:], ofm_shape[-size:]):
995 mi = max(i, i2)
996 # Input dimensions should match or one should be of dimension 1
997 # Output dimension should match the largest input dimension, together
998 # with constraint_match_either_shapes ensures broadcast from only one input
999 if not (i == i2 or i == 1 or i2 == 1) or o != mi:
1000 valid = False
1001 break
1002
1003 return valid, f"Op has ifm_shape={ifm_shape} and ifm2_shape={ifm2_shape}"
1004
1005 @staticmethod
Michael McGeagh65fd9982020-10-20 11:49:28 +01001006 def constraint_alpha_valid(op):
1007 "Alpha must not be negative"
1008 alpha = op.attrs["alpha"]
1009 valid = alpha >= 0
1010 return valid, f"Op has alpha={alpha}"