blob: 70700e7130e0d8d36445a317e5870ef3c66bac84 [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 Hall79d07d22020-04-27 18:20:16 +010018from .data_type import BaseType
19
20
21class SupportedOperators:
22 def __init__(self):
23 # Categorised lists of supported operators
24 self.npu_pre_ops = set(("QuantizedResizeBilinear", "SplitSliceRead"))
25 self.convolution_ops = set(("Conv2DBiasAct", "Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitched"))
26 self.depthwise_convolution_ops = set(
27 ("DepthwiseConv2dBiasAct", "DepthwiseConv2dNative", "QuantizedDepthwiseConv2D")
28 )
29 self.max_pooling_ops = set(("QuantizedMaxPool", "MaxPool", "MaxPoolAct"))
30 self.avg_pooling_ops = set(("QuantizedAvgPool", "AvgPool", "AvgPoolAct"))
31 self.pooling_ops = self.max_pooling_ops | self.avg_pooling_ops
32 self.fc_vector_products = set(("QuantizedMatMul", "MatMul", "FullyConnectedAct"))
33 self.mac_main_ops = (
34 # convolutions
35 self.convolution_ops
36 # depth-wise convolutions
37 | self.depthwise_convolution_ops
38 # pooling
39 | self.pooling_ops
40 # FC layers
41 | self.fc_vector_products
42 # RNN/LSTM/GRU
43 | set(("BlockLSTM"))
Dwight Lidman3ec04ac2020-04-30 11:54:48 +020044 # deconvolution
45 | set(("ResizeBilinear",))
Tim Hall79d07d22020-04-27 18:20:16 +010046 )
Dwight Lidmanf995db72020-04-27 11:15:12 +020047 self.unary_elem_wise_main_ops = set(("LeakyRelu", "Abs"))
48 self.binary_elem_wise_main_ops = set(
Tim Hall79d07d22020-04-27 18:20:16 +010049 (
Dwight Lidmanf995db72020-04-27 11:15:12 +020050 # binary element-wise
Tim Hall79d07d22020-04-27 18:20:16 +010051 "AddAct",
52 "MulAct",
53 "SubAct",
54 "QuantizedAdd",
55 "QuantizedSub",
56 "QuantizedMul",
57 "Mul",
58 "Add",
59 "Sub",
60 "Minimum",
61 "Maximum",
62 )
63 )
Dwight Lidmanf995db72020-04-27 11:15:12 +020064 self.elem_wise_main_ops = self.binary_elem_wise_main_ops | self.unary_elem_wise_main_ops
Tim Hall79d07d22020-04-27 18:20:16 +010065 self.activation_ops = set(
66 ("QuantizedRelu", "QuantizedRelu1", "QuantizedRelu6", "Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh")
67 )
68 self.npu_post_ops = (
69 # activation functions
70 self.activation_ops
71 # concatenation write direction
72 | set(("ConcatSliceWrite"))
73 # bias add and batch norm
74 | set(("QuantizedBiasAdd", "Requantize", "QuantizedBatchNorm", "BiasAdd", "FusedBatchNorm"))
75 )
76 self.split_ops = set(("Split", "StridedSlice", "Slice", "UnpackReshaped", "Unpack"))
77 self.concat_ops = set(("Concat", "ConcatV2", "QuantizedConcat", "ConcatTFLite", "PackReshaped", "Pack"))
78 self.memory_only_ops = (
79 set(("Squeeze", "Reshape", "QuantizedReshape", "ExpandDims")) | self.concat_ops | self.split_ops
80 )
81 self.supported_fused_activations = set(("Relu", "Relu6", "ReluN1To1", "Tanh", "Sigmoid"))
82 self.supported_operators = (
83 self.npu_pre_ops | self.mac_main_ops | self.elem_wise_main_ops | self.npu_post_ops | self.memory_only_ops
84 )
85 # Setup supported operator restriction checkers
86 self.supported_operator_restrictions = {}
87 self.supported_operator_restrictions.update(
88 {op: self.check_convolution_restrictions for op in self.convolution_ops}
89 )
90 self.supported_operator_restrictions.update(
91 {op: self.check_depthwise_convolution_restrictions for op in self.depthwise_convolution_ops}
92 )
93 self.supported_operator_restrictions.update({op: self.check_pooling_restrictions for op in self.pooling_ops})
94 self.supported_operator_restrictions.update(
95 {op: self.check_vector_product_restrictions for op in self.fc_vector_products}
96 )
97 self.supported_operator_restrictions.update(
98 {op: self.check_element_wise_restrictions for op in self.elem_wise_main_ops}
99 )
100 self.supported_operator_restrictions.update(
101 {op: self.check_memory_only_restrictions for op in self.memory_only_ops}
102 )
103
104 def is_operator_supported(self, op):
105 if op.type not in self.supported_operators:
106 return False
107 if not self.check_generic_restrictions(op):
108 return False
109 if op.type in self.supported_operator_restrictions:
110 return self.supported_operator_restrictions[op.type](op)
111 return True
112
113 def check_generic_restrictions(self, op):
114 # check fully defined shapes
115 for t in op.inputs + op.outputs:
116 if not t.has_fully_defined_shape():
117 print("Warning:", op, "has inputs/outputs of undefined shape, placing on CPU")
118 return False
119
120 # check data type
121 tensors = [t for t in op.get_ifm_ifm2_weights_ofm() if t is not None]
122 if not tensors:
123 tensors = op.inputs
124 for t in tensors:
125 if not (t.dtype.type & BaseType.Int):
126 return False
127 if t.element_size() > 2 and op.type != "Requantize":
128 return False
129 # check size
130 if any(dim > 65536 for dim in t.shape):
131 return False
132
133 # check fused activations
134 if (
135 "fused_activation_function" in op.attrs
136 and op.attrs["fused_activation_function"] is not None
137 and op.attrs["fused_activation_function"] not in self.supported_fused_activations
138 ):
139 return False
140 return True
141
142 def check_convolution_restrictions(self, op):
143 # check stride
Dwight Lidman0538a772020-05-06 14:09:17 +0200144 if op.attrs["stride_w"] > 3 or op.attrs["stride_h"] > 3:
Tim Hall79d07d22020-04-27 18:20:16 +0100145 return False
146
147 # check dilation
148 dilation_w_factor = op.attrs.get("dilation_w_factor", 1)
149 dilation_h_factor = op.attrs.get("dilation_h_factor", 1)
150 if dilation_w_factor > 2 or dilation_h_factor > 2:
151 return False
152
153 # check data type
154 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
155 if weight_tensor.element_size() > 1:
156 return False
157
158 # check kernel size
159 dilated_weight_w = weight_tensor.shape[0] + (weight_tensor.shape[0] - 1) * (dilation_w_factor - 1)
160 dilated_weight_h = weight_tensor.shape[1] + (weight_tensor.shape[1] - 1) * (dilation_h_factor - 1)
161 if (
162 dilated_weight_w > 64
163 or dilated_weight_h > 64
164 or dilated_weight_w * dilated_weight_h * weight_tensor.shape[2] > 127 * 65536
165 ):
166 return False
167
168 # check batch size
169 if ifm_tensor.shape[0] != 1:
170 return False
171 return True
172
173 def check_depthwise_convolution_restrictions(self, op):
174 # check depth
175 ifm_tensor, _, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
176 if op.attrs["depth_multiplier"] > 1 and not (
177 (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"])
178 ):
179 return False
180 return self.check_convolution_restrictions(op)
181
182 def check_pooling_restrictions(self, op):
183 # check stride
Dwight Lidman0538a772020-05-06 14:09:17 +0200184 if op.attrs["stride_w"] > 3 or op.attrs["stride_h"] > 3:
Tim Hall79d07d22020-04-27 18:20:16 +0100185 return False
186
187 # check data type
188 ifm_tensor, _, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
189 if ifm_tensor.dtype != ofm_tensor.dtype:
190 return False
191
192 # check batch size
193 if ifm_tensor.shape[0] != 1:
194 return False
195
196 if op.type in self.avg_pooling_ops:
197 # check kernel size
198 if op.attrs["padding"] == b"SAME" and (op.attrs["filter_width"] > 8 or op.attrs["filter_height"] > 8):
199 return False
200 if op.attrs["padding"] == b"VALID" and (op.attrs["filter_width"] > 256 or op.attrs["filter_height"] > 256):
201 return False
202
203 if op.type in self.max_pooling_ops:
204 # check data type
205 if not ifm_tensor.dtype == ofm_tensor.dtype:
206 return False
207 # check kernel size
208 if op.attrs["filter_width"] > 256 or op.attrs["filter_height"] > 256: # any padding
209 return False
210 return True
211
212 def check_vector_product_restrictions(self, op):
213 # check data type
214 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
215 if weight_tensor.element_size() > 1:
216 return False
217
218 return True
219
220 def check_element_wise_restrictions(self, op):
221 # check data type
222 ifm_tensor, ifm2_tensor, _, ofm_tensor = op.get_ifm_ifm2_weights_ofm()
223 if op.type in ("Minimum", "Maximum") and ifm_tensor.dtype != ofm_tensor.dtype:
224 return False
225
226 # check batch size
Dwight Lidmanf995db72020-04-27 11:15:12 +0200227 if len(ifm_tensor.shape) > 2 and ifm_tensor.shape[0] != 1:
228 return False
229 if op.type in self.binary_elem_wise_main_ops: # if op type is unary, ifm2_tensor is None
230 if len(ifm2_tensor.shape) > 2 and ifm2_tensor.shape[0] != 1:
231 return False
Tim Hall79d07d22020-04-27 18:20:16 +0100232
233 # check scalar size
Dwight Lidmanf995db72020-04-27 11:15:12 +0200234 if hasattr(ifm_tensor.values, "__len__") and len(ifm_tensor.values) > 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100235 return False
Dwight Lidmanf995db72020-04-27 11:15:12 +0200236 if op.type in self.binary_elem_wise_main_ops: # same as above
237 if hasattr(ifm2_tensor.values, "__len__") and len(ifm2_tensor.values) > 1:
238 return False
Tim Hall79d07d22020-04-27 18:20:16 +0100239 return True
240
241 def check_memory_only_restrictions(self, op):
Tim Hall79d07d22020-04-27 18:20:16 +0100242 if op.type == "StridedSlice":
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200243 # check stride size
Tim Hall79d07d22020-04-27 18:20:16 +0100244 if len(op.inputs) > 3 and any(stride != 1 for stride in op.inputs[3].values):
245 return False
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200246 # check ellipsis_mask
247 if op.attrs["ellipsis_mask"] != 0:
248 return False
249 # check if both new_axis_mask and shrink_axis_mask have bit set
250 if op.attrs["new_axis_mask"] != 0 and op.attrs["shrink_axis_mask"] != 0:
251 return False
Tim Hall79d07d22020-04-27 18:20:16 +0100252 return True