blob: 9e415b514d9cb7b084d8fba2c2fafb6bb481d136 [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.
Tim Hallc30f4952020-06-15 20:47:35 +010018from .data_type import BaseType
19from .data_type import DataType
Tim Hall79d07d22020-04-27 18:20:16 +010020
21
22class SupportedOperators:
Fredrik Svedberga0c36242020-06-03 15:43:31 +020023 def __init__(self, softmax_support):
24 self.softmax_support = softmax_support
Tim Hall79d07d22020-04-27 18:20:16 +010025 # Categorised lists of supported operators
Fredrik Svedberga0c36242020-06-03 15:43:31 +020026 self.npu_pre_ops = set(("QuantizedResizeBilinear", "SplitSliceRead",))
27 self.convolution_ops = set(("Conv2DBiasAct", "Conv2D", "QuantizedConv2D",))
Tim Hall79d07d22020-04-27 18:20:16 +010028 self.depthwise_convolution_ops = set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +020029 ("DepthwiseConv2dBiasAct", "DepthwiseConv2dNative", "QuantizedDepthwiseConv2D,")
Tim Hall79d07d22020-04-27 18:20:16 +010030 )
Jacob Bohlincf7da102020-05-20 09:03:40 +020031 self.transpose_convolution_ops = set(("Conv2DBackpropInput",))
Fredrik Svedberga0c36242020-06-03 15:43:31 +020032 self.max_pooling_ops = set(("QuantizedMaxPool", "MaxPool", "MaxPoolAct",))
33 self.avg_pooling_ops = set(("QuantizedAvgPool", "AvgPool", "AvgPoolAct",))
34 self.pooling_ops = set(("ReduceSum",)) | self.max_pooling_ops | self.avg_pooling_ops
Dwight Lidman42fed942020-05-29 09:37:03 +020035 self.resizing_ops = set(("ResizeBilinear",))
Fredrik Svedberga0c36242020-06-03 15:43:31 +020036 self.fc_vector_products = set(("QuantizedMatMul", "MatMul", "FullyConnectedAct",))
Tim Hall79d07d22020-04-27 18:20:16 +010037 self.mac_main_ops = (
38 # convolutions
39 self.convolution_ops
40 # depth-wise convolutions
41 | self.depthwise_convolution_ops
Jacob Bohlincf7da102020-05-20 09:03:40 +020042 # transpose convolutions
43 | self.transpose_convolution_ops
Tim Hall79d07d22020-04-27 18:20:16 +010044 # pooling
45 | self.pooling_ops
Dwight Lidman42fed942020-05-29 09:37:03 +020046 # resizing/upscaling
47 | self.resizing_ops
Tim Hall79d07d22020-04-27 18:20:16 +010048 # FC layers
49 | self.fc_vector_products
50 # RNN/LSTM/GRU
Fredrik Svedberga0c36242020-06-03 15:43:31 +020051 | set(("BlockLSTM",))
Tim Hall79d07d22020-04-27 18:20:16 +010052 )
Fredrik Svedberga0c36242020-06-03 15:43:31 +020053 self.unary_elem_wise_main_ops = set(("LeakyRelu", "Abs", "CLZ",))
54 self.binary_elem_wise_min_max_ops = set(("Minimum", "Maximum",))
Fredrik Svedberg597fd3f2020-08-13 10:02:53 +020055 self.binary_elem_wise_shift_ops = set(("SHL", "SHR",))
Fredrik Svedberg388e9c22020-05-25 16:32:00 +020056 self.binary_elem_wise_add_mul_sub = set(
Fredrik Svedberg1575b942020-08-18 13:19:18 +020057 ("AddAct", "MulAct", "SubAct", "QuantizedAdd", "QuantizedSub", "QuantizedMul", "Mul", "Add", "Sub",)
Tim Hall79d07d22020-04-27 18:20:16 +010058 )
Fredrik Svedberg1575b942020-08-18 13:19:18 +020059 self.binary_elem_wise_main_ops = (
60 self.binary_elem_wise_min_max_ops | self.binary_elem_wise_add_mul_sub | self.binary_elem_wise_shift_ops
61 )
Dwight Lidmanf995db72020-04-27 11:15:12 +020062 self.elem_wise_main_ops = self.binary_elem_wise_main_ops | self.unary_elem_wise_main_ops
Tim Hall79d07d22020-04-27 18:20:16 +010063 self.activation_ops = set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +020064 (
65 "QuantizedRelu",
66 "QuantizedRelu1",
67 "QuantizedRelu6",
68 "Relu",
69 "Relu6",
70 "ReluN1To1",
71 "Sigmoid",
72 "Tanh",
73 "Softmax",
74 )
Tim Hall79d07d22020-04-27 18:20:16 +010075 )
76 self.npu_post_ops = (
77 # activation functions
78 self.activation_ops
79 # concatenation write direction
Fredrik Svedberga0c36242020-06-03 15:43:31 +020080 | set(("ConcatSliceWrite",))
Tim Hall79d07d22020-04-27 18:20:16 +010081 # bias add and batch norm
Fredrik Svedberga0c36242020-06-03 15:43:31 +020082 | set(("QuantizedBiasAdd", "Requantize", "QuantizedBatchNorm", "BiasAdd", "FusedBatchNorm",))
Jacob Bohlin9fbc4912020-06-29 11:58:50 +020083 # Quantization
84 | set(("Quantize",))
Tim Hall79d07d22020-04-27 18:20:16 +010085 )
Fredrik Svedberga0c36242020-06-03 15:43:31 +020086 self.split_ops = set(("Split", "SplitV", "StridedSlice", "Slice", "UnpackReshaped", "Unpack",))
87 self.concat_ops = set(("Concat", "ConcatV2", "QuantizedConcat", "ConcatTFLite", "PackReshaped", "Pack",))
Tim Hall79d07d22020-04-27 18:20:16 +010088 self.memory_only_ops = (
Fredrik Svedberga0c36242020-06-03 15:43:31 +020089 set(("Squeeze", "Reshape", "QuantizedReshape", "ExpandDims",)) | self.concat_ops | self.split_ops
Tim Hall79d07d22020-04-27 18:20:16 +010090 )
Fredrik Svedberga0c36242020-06-03 15:43:31 +020091 self.supported_fused_activations = set(("Relu", "Relu6", "ReluN1To1", "Tanh", "Sigmoid", "LUT",))
Tim Hall79d07d22020-04-27 18:20:16 +010092 self.supported_operators = (
93 self.npu_pre_ops | self.mac_main_ops | self.elem_wise_main_ops | self.npu_post_ops | self.memory_only_ops
94 )
95 # Setup supported operator restriction checkers
96 self.supported_operator_restrictions = {}
97 self.supported_operator_restrictions.update(
98 {op: self.check_convolution_restrictions for op in self.convolution_ops}
99 )
100 self.supported_operator_restrictions.update(
101 {op: self.check_depthwise_convolution_restrictions for op in self.depthwise_convolution_ops}
102 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200103 self.supported_operator_restrictions.update(
104 {op: self.check_transpose_convolution_restrictions for op in self.transpose_convolution_ops}
105 )
Tim Hall79d07d22020-04-27 18:20:16 +0100106 self.supported_operator_restrictions.update({op: self.check_pooling_restrictions for op in self.pooling_ops})
Dwight Lidman42fed942020-05-29 09:37:03 +0200107 self.supported_operator_restrictions.update({op: self.check_resize_restrictions for op in self.resizing_ops})
Tim Hall79d07d22020-04-27 18:20:16 +0100108 self.supported_operator_restrictions.update(
109 {op: self.check_vector_product_restrictions for op in self.fc_vector_products}
110 )
111 self.supported_operator_restrictions.update(
112 {op: self.check_element_wise_restrictions for op in self.elem_wise_main_ops}
113 )
114 self.supported_operator_restrictions.update(
115 {op: self.check_memory_only_restrictions for op in self.memory_only_ops}
116 )
Dwight Lidmanebe26c72020-06-09 11:40:54 +0200117 self.supported_operator_restrictions.update(
118 {op: self.check_quantization_restrictions for op in self.binary_elem_wise_min_max_ops}
119 )
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200120 self.supported_operator_restrictions.update({op: self.check_activation_ops for op in self.activation_ops})
Tim Hall79d07d22020-04-27 18:20:16 +0100121
122 def is_operator_supported(self, op):
123 if op.type not in self.supported_operators:
124 return False
125 if not self.check_generic_restrictions(op):
126 return False
127 if op.type in self.supported_operator_restrictions:
128 return self.supported_operator_restrictions[op.type](op)
129 return True
130
131 def check_generic_restrictions(self, op):
132 # check fully defined shapes
Dwight Lidman25733112020-08-17 11:56:10 +0200133 for t in op.inputs:
Tim Hall79d07d22020-04-27 18:20:16 +0100134 if not t.has_fully_defined_shape():
Dwight Lidman25733112020-08-17 11:56:10 +0200135 print("Warning:", op.type, "has input(s) of undefined shape, placing on CPU")
136 return False
137 if t.shape == [] and op.type not in self.binary_elem_wise_main_ops:
138 print("Warning:", op.type, "has input(s) of shape [].",
139 "Scalar input or broadcasting is not supported for this operator,",
140 "placing on CPU")
141 return False
142 for t in op.outputs:
143 if not t.has_fully_defined_shape():
144 print("Warning:", op.type, "has output(s) of undefined shape, placing on CPU")
145 return False
146 if t.shape == []:
147 print("Warning:", op.type, "has output(s) of shape [].",
148 "Scalar input or broadcasting is not supported for this operator,",
149 "placing on CPU")
Tim Hall79d07d22020-04-27 18:20:16 +0100150 return False
151
152 # check data type
153 tensors = [t for t in op.get_ifm_ifm2_weights_ofm() if t is not None]
154 if not tensors:
155 tensors = op.inputs
156 for t in tensors:
157 if not (t.dtype.type & BaseType.Int):
158 return False
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200159 if (
160 t.element_size() > 2
Fredrik Svedberg1575b942020-08-18 13:19:18 +0200161 and op.type
162 not in set(("Requantize", "ReduceSum", "CLZ",))
163 | self.binary_elem_wise_add_mul_sub
164 | self.binary_elem_wise_shift_ops
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200165 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100166 return False
167 # check size
168 if any(dim > 65536 for dim in t.shape):
169 return False
170
171 # check fused activations
172 if (
173 "fused_activation_function" in op.attrs
174 and op.attrs["fused_activation_function"] is not None
175 and op.attrs["fused_activation_function"] not in self.supported_fused_activations
176 ):
177 return False
178 return True
179
180 def check_convolution_restrictions(self, op):
181 # check stride
Dwight Lidman0538a772020-05-06 14:09:17 +0200182 if op.attrs["stride_w"] > 3 or op.attrs["stride_h"] > 3:
Tim Hall79d07d22020-04-27 18:20:16 +0100183 return False
184
185 # check dilation
186 dilation_w_factor = op.attrs.get("dilation_w_factor", 1)
187 dilation_h_factor = op.attrs.get("dilation_h_factor", 1)
188 if dilation_w_factor > 2 or dilation_h_factor > 2:
189 return False
190
191 # check data type
192 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
193 if weight_tensor.element_size() > 1:
194 return False
195
196 # check kernel size
197 dilated_weight_w = weight_tensor.shape[0] + (weight_tensor.shape[0] - 1) * (dilation_w_factor - 1)
198 dilated_weight_h = weight_tensor.shape[1] + (weight_tensor.shape[1] - 1) * (dilation_h_factor - 1)
199 if (
200 dilated_weight_w > 64
201 or dilated_weight_h > 64
202 or dilated_weight_w * dilated_weight_h * weight_tensor.shape[2] > 127 * 65536
203 ):
204 return False
205
206 # check batch size
207 if ifm_tensor.shape[0] != 1:
208 return False
209 return True
210
211 def check_depthwise_convolution_restrictions(self, op):
212 # check depth
213 ifm_tensor, _, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
214 if op.attrs["depth_multiplier"] > 1 and not (
215 (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"])
216 ):
217 return False
218 return self.check_convolution_restrictions(op)
219
Jacob Bohlincf7da102020-05-20 09:03:40 +0200220 def check_transpose_convolution_restrictions(self, op):
221 # check stride
222 stride_h, stride_w = op.attrs["stride_h"], op.attrs["stride_w"]
223 if stride_h != stride_w != 2:
224 return False
225
226 # check output dimensions
227 ifm_tensor, weight_tensor, _, ofm_tensor = op.get_ifm_weights_biases_ofm()
228 ifm_h, ifm_w = ifm_tensor.shape[1], ifm_tensor.shape[2]
229 ofm_h, ofm_w = ofm_tensor.shape[1], ofm_tensor.shape[2]
230 if op.attrs["padding"] == b"SAME":
231 if (ofm_h != ifm_h * stride_h) or (ofm_w != ifm_w * stride_w):
232 return False
233 elif op.attrs["padding"] == b"VALID":
234 kernel_h, kernel_w = weight_tensor.shape[0], weight_tensor.shape[1]
Tim Hallc30f4952020-06-15 20:47:35 +0100235 if (ofm_h != (ifm_h) * stride_h + max(kernel_h - stride_h, 0)) or (
236 ofm_w != (ifm_w) * stride_w + max(kernel_w - stride_w, 0)
237 ):
Jacob Bohlincf7da102020-05-20 09:03:40 +0200238 return False
239
240 return self.check_convolution_restrictions(op)
241
Tim Hall79d07d22020-04-27 18:20:16 +0100242 def check_pooling_restrictions(self, op):
243 # check stride
Dwight Lidman0538a772020-05-06 14:09:17 +0200244 if op.attrs["stride_w"] > 3 or op.attrs["stride_h"] > 3:
Tim Hall79d07d22020-04-27 18:20:16 +0100245 return False
246
247 # check data type
248 ifm_tensor, _, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
249 if ifm_tensor.dtype != ofm_tensor.dtype:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200250 if op.type != "ReduceSum":
251 return False
252 # TODO: else check ReduceSum restrictions.
Tim Hall79d07d22020-04-27 18:20:16 +0100253
254 # check batch size
255 if ifm_tensor.shape[0] != 1:
256 return False
257
258 if op.type in self.avg_pooling_ops:
259 # check kernel size
260 if op.attrs["padding"] == b"SAME" and (op.attrs["filter_width"] > 8 or op.attrs["filter_height"] > 8):
261 return False
Tim Hallc30f4952020-06-15 20:47:35 +0100262 if op.attrs["padding"] == b"VALID" and (
263 op.attrs["filter_width"] * op.attrs["filter_height"] > 256 * 256 or op.attrs["filter_height"] > 256
264 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100265 return False
266
267 if op.type in self.max_pooling_ops:
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200268 # check kernel size (any padding)
269 if op.attrs["filter_width"] * op.attrs["filter_height"] > 256 * 256 or op.attrs["filter_height"] > 256:
Tim Hall79d07d22020-04-27 18:20:16 +0100270 return False
271 return True
272
Dwight Lidman42fed942020-05-29 09:37:03 +0200273 def check_resize_restrictions(self, op):
274 # check unsupported upscaling factor
275 if op.type == "ResizeBilinear":
Charles Xu9a03fdf2020-07-02 15:12:40 +0200276 if op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
277 return True
Charles Xu36ffaf32020-08-05 15:40:44 +0200278 if op.inputs[0].shape == op.outputs[0].shape:
279 return True
Dwight Lidman42fed942020-05-29 09:37:03 +0200280 upscaled_shape = [op.inputs[0].shape[1] * 2, op.inputs[0].shape[2] * 2]
281 out_shape = op.outputs[0].shape[1:3]
282 if not op.attrs["align_corners"] and out_shape != upscaled_shape:
283 return False
284 elif op.attrs["align_corners"] and out_shape != [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
285 return False
286 return True
287
Tim Hall79d07d22020-04-27 18:20:16 +0100288 def check_vector_product_restrictions(self, op):
289 # check data type
290 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
291 if weight_tensor.element_size() > 1:
292 return False
293
294 return True
295
296 def check_element_wise_restrictions(self, op):
297 # check data type
298 ifm_tensor, ifm2_tensor, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200299 # input and output datatype must match for these operators
Tim Hallc30f4952020-06-15 20:47:35 +0100300 if (
301 op.type in self.binary_elem_wise_min_max_ops | self.unary_elem_wise_main_ops
302 and ifm_tensor.dtype != ofm_tensor.dtype
303 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100304 return False
Tim Hallc30f4952020-06-15 20:47:35 +0100305 if op.type in self.binary_elem_wise_add_mul_sub:
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200306 # both inputs must have same type
Tim Hallc30f4952020-06-15 20:47:35 +0100307 if ifm_tensor.dtype != ifm2_tensor.dtype:
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200308 return False
309 # signed input check
Tim Hallc30f4952020-06-15 20:47:35 +0100310 if ifm_tensor.dtype.type & BaseType.Signed:
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200311 # output must be signed
Tim Hallc30f4952020-06-15 20:47:35 +0100312 if ofm_tensor.dtype.type & BaseType.Unsigned:
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200313 return False
314 # and 8, 16 or 32-bit
Tim Hallc30f4952020-06-15 20:47:35 +0100315 if ofm_tensor.element_size() not in (1, 2, 4):
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200316 return False
317 # unsigned input check, output must be same type or int32
Tim Hallc30f4952020-06-15 20:47:35 +0100318 if ifm_tensor.dtype.type & BaseType.Unsigned and not (
319 ifm_tensor.dtype == ofm_tensor.dtype or ofm_tensor.dtype == DataType.int32
320 ):
Fredrik Svedberg388e9c22020-05-25 16:32:00 +0200321 return False
Fredrik Svedberg597fd3f2020-08-13 10:02:53 +0200322 elif op.type in self.binary_elem_wise_shift_ops | set(("CLZ")):
323 if ifm_tensor.dtype != DataType.int32 or ifm2_tensor.dtype != DataType.int32:
324 return False
325 if op.type in ("CLZ", "SHL") and ofm_tensor.dtype != DataType.int32:
326 return False
Tim Hall79d07d22020-04-27 18:20:16 +0100327
328 # check batch size
Dwight Lidmanf995db72020-04-27 11:15:12 +0200329 if len(ifm_tensor.shape) > 2 and ifm_tensor.shape[0] != 1:
Tim Hallc30f4952020-06-15 20:47:35 +0100330 return False
331 if op.type in self.binary_elem_wise_main_ops: # if op type is unary, ifm2_tensor is None
Dwight Lidmanf995db72020-04-27 11:15:12 +0200332 if len(ifm2_tensor.shape) > 2 and ifm2_tensor.shape[0] != 1:
333 return False
Dwight Lidman332a7042020-06-11 15:32:42 +0200334
335 # negative alpha values are not supported
336 if op.type == "LeakyRelu" and op.attrs["alpha"] < 0:
337 return False
338
Tim Hall79d07d22020-04-27 18:20:16 +0100339 return True
340
341 def check_memory_only_restrictions(self, op):
Tim Hall79d07d22020-04-27 18:20:16 +0100342 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200343 # check stride size
Tim Hall79d07d22020-04-27 18:20:16 +0100344 if len(op.inputs) > 3 and any(stride != 1 for stride in op.inputs[3].values):
345 return False
Michael McGeaghecd20522020-07-31 16:59:45 +0100346 # check "end - begin" doesnt result in any zero or negative elements
347 if any((end - begin) <= 0 for begin, end in zip(op.inputs[1].values, op.inputs[2].values)):
348 return False
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200349 # check ellipsis_mask
350 if op.attrs["ellipsis_mask"] != 0:
351 return False
352 # check if both new_axis_mask and shrink_axis_mask have bit set
353 if op.attrs["new_axis_mask"] != 0 and op.attrs["shrink_axis_mask"] != 0:
354 return False
Tim Hall79d07d22020-04-27 18:20:16 +0100355 return True
Dwight Lidmanebe26c72020-06-09 11:40:54 +0200356
357 def check_quantization_restrictions(self, op):
358 # makes sure IFM1, IFM2 and OFM quantization are equal for binary ops
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200359 if (
360 len(op.inputs) == 2
361 and not op.inputs[0].quantization == op.inputs[1].quantization == op.outputs[0].quantization
362 ):
363 print(
364 "Warning: Input/output tensors with different quantization is unsupported for the", op.type, "operator"
365 )
Dwight Lidmanebe26c72020-06-09 11:40:54 +0200366 return False
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200367 return True
368
369 def check_activation_ops(self, op):
370 if op.type == "Softmax":
371 if not self.softmax_support:
372 return False
373
374 ifm_tensor = op.inputs[0]
375 ofm_tensor = op.outputs[0]
376
377 # check data type
378 if ifm_tensor.dtype != ofm_tensor.dtype:
379 return False
380
Fredrik Svedberg597fd3f2020-08-13 10:02:53 +0200381 if ifm_tensor.dtype not in (DataType.uint8, DataType.int8, DataType.int16):
382 return False
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200383
384 # check batch size
385 if len(ifm_tensor.shape) in (2, 4) and ifm_tensor.shape[0] != 1:
386 return False
387
388 return True