blob: 75ca43efcd81b7f83936c88a00cfd96ad9b31c2c [file] [log] [blame]
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +02001# Copyright (C) 2021 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.
16# Description:
17# TOSA mapping functions used by reader.
18# Contains a mapping from the various TOSA enums and options structs, generated by the FlatBuffer code
19# generator, to Vela's internal format.
Patrik Gustavssond15866c2021-08-10 13:56:34 +020020import numpy as np
21
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020022from .data_type import DataType
23from .operation import Op
24from .operation import TensorIndices
25from .tosa import ArithmeticRightShiftAttribute # noqa: F401
26from .tosa import AxisAttribute # noqa: F401
27from .tosa import ClampAttribute # noqa: F401
28from .tosa import CondIfAttribute # noqa: F401
29from .tosa import Conv2dAttribute # noqa: F401
30from .tosa import ConvQuantInfo # noqa: F401
31from .tosa import MatMulQuantInfo # noqa: F401
32from .tosa import MulAttribute # noqa: F401
33from .tosa import PadQuantInfo # noqa: F401
34from .tosa import Pool2dAttribute # noqa: F401
35from .tosa import ReluNAttribute # noqa: F401
36from .tosa import RescaleAttribute # noqa: F401
37from .tosa import ReshapeAttribute # noqa: F401
38from .tosa import ResizeAttribute # noqa: F401
39from .tosa import SliceAttribute # noqa: F401
40from .tosa import TileAttribute # noqa: F401
41from .tosa import TransposeConv2dAttribute # noqa: F401
42from .tosa import UnaryQuantInfo # noqa: F401
43from .tosa import WhileLoopAttribute # noqa: F401
44from .tosa.DType import DType
45from .tosa.Op import Op as TosaOp
46
47
48datatype_map = {
49 DType.BOOL: DataType.bool,
50 DType.UINT8: DataType.uint8,
51 DType.INT4: DataType.int4,
52 DType.INT8: DataType.int8,
53 DType.INT16: DataType.int16,
54 DType.INT32: DataType.int32,
55 DType.INT48: DataType.int48,
56 DType.FLOAT: DataType.float32,
57}
58
Patrik Gustavssond15866c2021-08-10 13:56:34 +020059datatype_map_numpy = {
60 DType.BOOL: np.bool,
61 DType.UINT8: np.uint8,
62 DType.INT8: np.int8,
63 DType.INT16: np.int16,
64 DType.INT32: np.int32,
65 DType.FLOAT: np.float32,
66}
67
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020068
69# TODO duplicate of tflite_mapping
70def underscore_to_camel_case(s):
71 return "".join(x.title() for x in s.split("_"))
72
73
74# TODO duplicate of tflite_mapping
75def identity(x):
76 return x
77
78
79class AttrSerializer:
80 def __init__(self, name, members=None):
81 self.name = name
82 self.module = globals()[self.name]
83 self.cls = getattr(self.module, self.name)
84 self.members = []
85 if members is not None:
86 for mem in members:
87 deserialize = identity
88 is_vector = False
89 if isinstance(mem, tuple):
90 if len(mem) == 2:
91 mem, is_vector = mem
92 deserialize = tuple
93 else:
94 assert 0
95 underscore_mem = mem
96 camelcase_mem = underscore_to_camel_case(mem)
97 self.members.append((underscore_mem, camelcase_mem, deserialize, is_vector))
98
99 def deserialize(self, op_data):
100 attr_type = op_data.AttributeType()
101 attr = op_data.Attribute()
102 attrs = {}
103 if attr_type:
104 tosa_attrs = self.cls()
105 tosa_attrs.Init(attr.Bytes, attr.Pos)
106 for underscore_mem, camelcase_mem, deserialize, is_vector in self.members:
107 fun = camelcase_mem
108 if is_vector:
109 fun += "AsNumpy"
110
111 attr = getattr(tosa_attrs, fun)()
112 try:
113 attrs[underscore_mem] = deserialize(attr)
114 except TypeError:
115 print("Warning: {0} could not read attribute '{1}'.".format(self.name, underscore_mem))
116
117 return attrs
118
119
120class QuantSerializer:
121 def __init__(self, name, members=None):
122 self.name = name
123 self.module = globals()[self.name]
124 self.cls = getattr(self.module, self.name)
125 self.members = []
126 if members is not None:
127 for mem in members:
128 deserialize = identity
129 underscore_mem = mem
130 camelcase_mem = underscore_to_camel_case(mem)
131 self.members.append((underscore_mem, camelcase_mem, deserialize))
132
133 def deserialize(self, op_data):
134 quant_info_type = op_data.QuantInfoType()
135 quant_info = op_data.QuantInfo()
136 quant = {}
137 if quant_info_type:
138 tosa_quant = self.cls()
139 tosa_quant.Init(quant_info.Bytes, quant_info.Pos)
140 for underscore_mem, camelcase_mem, deserialize in self.members:
141 attr = getattr(tosa_quant, camelcase_mem)()
142 try:
143 quant[underscore_mem] = deserialize(attr)
144 except TypeError:
145 print("Warning: {0} could not read quant info '{1}'.".format(self.name, underscore_mem))
146
147 return quant
148
149
150is_vec = True
151pool2d_attrs = AttrSerializer("Pool2dAttribute", (("padding", is_vec), ("kernel", is_vec), ("stride", is_vec)))
152conv2d_attrs = AttrSerializer("Conv2dAttribute", (("padding", is_vec), ("stride", is_vec), ("dilation", is_vec)))
153transpose_conv2d_attrs = AttrSerializer(
154 "TransposeConv2dAttribute", (("outpad", is_vec), ("stride", is_vec), ("dilation", is_vec), ("out_shape", is_vec))
155)
156relun_attrs = AttrSerializer("ReluNAttribute", ("max_int"))
157axis_attrs = AttrSerializer("AxisAttribute", ("axis"))
158reshape_attrs = AttrSerializer("ReshapeAttribute", (("shape", is_vec),))
159slice_attrs = AttrSerializer("SliceAttribute", (("begin", is_vec), ("size", is_vec)))
160tile_attrs = AttrSerializer("TileAttribute", (("multiplies", is_vec),))
161resize_attrs = AttrSerializer(
162 "ResizeAttribute", (("output_size", is_vec), ("stride", is_vec), ("offset", is_vec), ("shift"))
163)
164clamp_attrs = AttrSerializer("ClampAttribute", (("min_int"), ("max_int")))
165rescale_attrs = AttrSerializer(
166 "RescaleAttribute",
167 ("input_zp", "output_zp", ("multiplier", is_vec), ("shift", is_vec), "scale32", "double_round", "per_channel"),
168)
169mul_attrs = AttrSerializer("MulAttribute", ("shift"))
170ars_attrs = AttrSerializer("ArithmeticRightShiftAttribute", ("round",))
171condif_attrs = AttrSerializer("CondIfAttribute", (("then_branch"), ("else_branch"))) # TODO these are references
172while_attrs = AttrSerializer("WhileLoopAttribute", (("cond_branch"), ("body_branch"))) # TODO these are references
173
174unary_quant_info = QuantSerializer("UnaryQuantInfo", ("input_zp", "output_zp"))
175conv_quant_info = QuantSerializer("ConvQuantInfo", ("input_zp", "weight_zp"))
176matmul_quant_info = QuantSerializer("MatMulQuantInfo", ("a_zp", "b_zp"))
177pad_quant_info = QuantSerializer("PadQuantInfo", ("input_zp"))
178
179unsupported_tosa_operators = {
180 TosaOp.UNKNOWN,
181 TosaOp.ARGMAX,
182 TosaOp.CONV3D,
183 TosaOp.MATMUL,
184 TosaOp.TRANSPOSE_CONV2D,
185 TosaOp.SIGMOID,
186 TosaOp.TANH,
187 TosaOp.BITWISE_AND,
188 TosaOp.BITWISE_OR,
189 TosaOp.BITWISE_XOR,
190 TosaOp.DIV,
191 TosaOp.LOGICAL_AND,
192 TosaOp.LOGICAL_LEFT_SHIFT,
193 TosaOp.LOGICAL_RIGHT_SHIFT,
194 TosaOp.LOGICAL_OR,
195 TosaOp.LOGICAL_XOR,
196 TosaOp.MAXIMUM,
197 TosaOp.MINIMUM,
198 TosaOp.MUL,
199 TosaOp.POW,
200 TosaOp.TABLE,
201 TosaOp.ABS,
202 TosaOp.BITWISE_NOT,
203 TosaOp.CEIL,
204 TosaOp.CLZ,
205 TosaOp.EXP,
206 TosaOp.FLOOR,
207 TosaOp.LOG,
208 TosaOp.LOGICAL_NOT,
209 TosaOp.NEGATE,
210 TosaOp.RECIPROCAL,
211 TosaOp.RSQRT,
212 TosaOp.SELECT,
213 TosaOp.EQUAL,
214 TosaOp.GREATER,
215 TosaOp.GREATER_EQUAL,
216 TosaOp.REDUCE_ANY,
217 TosaOp.REDUCE_ALL,
218 TosaOp.REDUCE_MAX,
219 TosaOp.REDUCE_MIN,
220 TosaOp.REDUCE_PRODUCT,
221 TosaOp.REDUCE_SUM,
222 TosaOp.CONCAT,
223 TosaOp.PAD,
224 TosaOp.RESHAPE,
225 TosaOp.REVERSE,
226 TosaOp.SLICE,
227 TosaOp.TILE,
228 TosaOp.TRANSPOSE,
229 TosaOp.GATHER,
230 TosaOp.SCATTER,
231 TosaOp.RESIZE,
232 TosaOp.CAST,
233 TosaOp.IDENTITY,
234 TosaOp.CUSTOM,
235 TosaOp.COND_IF,
236 TosaOp.WHILE_LOOP,
237}
238
239
240TOSA_NO_INDICES = TensorIndices([], [], [])
241TOSA_IFM_INDICES = TensorIndices([0], [], [])
242# TOSA_IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
243TOSA_IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
244TOSA_IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
245# TOSA_CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
246# TOSA_TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
247# TOSA_CONCAT_INDICES = TensorIndices([1, 2], [], [])
248# TOSA_SPLIT_IFM_INDICES = TensorIndices([1], [], [])
249# TOSA_BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
250
251
252tosa_operator_map = {
253 # TosaOp.UNKNOWN: (),
254 # TODO TosaOp.ARGMAX: (Op.ArgMax, axis_attrs, None),
255 TosaOp.AVG_POOL2D: (Op.AvgPool, pool2d_attrs, unary_quant_info, TOSA_IFM_INDICES),
256 TosaOp.CONV2D: (Op.Conv2DBias, conv2d_attrs, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
257 # TODO TosaOp.CONV3D:
258 TosaOp.DEPTHWISE_CONV2D: (Op.DepthwiseConv2DBias, conv2d_attrs, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
259 TosaOp.FULLY_CONNECTED: (Op.FullyConnected, None, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
260 # TODO TosaOp.MATMUL:
261 TosaOp.MAX_POOL2D: (Op.MaxPool, pool2d_attrs, None, TOSA_IFM_INDICES),
262 # TODO TosaOp.TRANSPOSE_CONV2D: (Op.Conv2DBackpropInput, transpose_conv2d_attrs, conv_quant_info)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200263 TosaOp.CLAMP: (Op.Clamp, clamp_attrs, None, TOSA_IFM_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200264 TosaOp.RELUN: (Op.ReluN, relun_attrs, None, TOSA_IFM_INDICES),
265 # TODO TosaOp.SIGMOID
266 # TODO TosaOp.TANH
267 TosaOp.ADD: (Op.Add, None, None, TOSA_IFM_IFM2_INDICES),
268 TosaOp.ARITHMETIC_RIGHT_SHIFT: (Op.SHR, ars_attrs, None, TOSA_IFM_IFM2_INDICES),
269 # TODO TosaOp.BITWISE_AND
270 # TODO TosaOp.BITWISE_OR
271 # TODO TosaOp.BITWISE_XOR
272 # TODO TosaOp.DIV
273 # TODO TosaOp.LOGICAL_AND
274 # TODO TosaOp.LOGICAL_LEFT_SHIFT
275 # TODO TosaOp.LOGICAL_RIGHT_SHIFT
276 # TODO TosaOp.LOGICAL_OR
277 # TODO TosaOp.LOGICAL_XOR
278 # TODO TosaOp.MAXIMUM
279 # TODO TosaOp.MINIMUM
280 # TODO TosaOp.MUL
281 # TODO TosaOp.POW
282 TosaOp.SUB: (Op.Sub, None, None, TOSA_IFM_IFM2_INDICES),
283 # TODO TosaOp.TABLE
284 # TODO TosaOp.ABS
285 # TODO TosaOp.BITWISE_NOT
286 # TODO TosaOp.CEIL
287 # TODO TosaOp.CLZ
288 # TODO TosaOp.EXP
289 # TODO TosaOp.FLOOR
290 # TODO TosaOp.LOG
291 # TODO TosaOp.LOGICAL_NOT
292 # TODO TosaOp.NEGATE
293 # TODO TosaOp.RECIPROCAL
294 # TODO TosaOp.RSQRT
295 # TODO TosaOp.SELECT
296 # TODO TosaOp.EQUAL
297 # TODO TosaOp.GREATER
298 # TODO TosaOp.GREATER_EQUAL
299 # TODO TosaOp.REDUCE_ANY
300 # TODO TosaOp.REDUCE_ALL
301 # TODO TosaOp.REDUCE_MAX
302 # TODO TosaOp.REDUCE_MIN
303 # TODO TosaOp.REDUCE_PRODUCT
304 # TODO TosaOp.REDUCE_SUM
305 # TODO TosaOp.CONCAT
306 # TODO TosaOp.PAD
307 # TODO TosaOp.RESHAPE
308 # TODO TosaOp.REVERSE
309 # TODO TosaOp.SLICE
310 # TODO TosaOp.TILE
311 # TODO TosaOp.TRANSPOSE
312 # TODO TosaOp.GATHER
313 # TODO TosaOp.SCATTER
314 # TODO TosaOp.RESIZE
315 # TODO TosaOp.CAST
316 TosaOp.RESCALE: (Op.Rescale, rescale_attrs, None, TOSA_IFM_INDICES),
317 TosaOp.CONST: (Op.Const, None, None, TOSA_NO_INDICES),
318 # TODO TosaOp.IDENTITY
319 # TODO TosaOp.CUSTOM
320 # TODO TosaOp.COND_IF
321 # TODO TosaOp.WHILE_LOOP
322}
323
324tosa_operator_inv_map = {v[0]: (k, v[1]) for k, v in tosa_operator_map.items()}
325
326
327def tosa_type_name(builtin):
328 return next(k for k, v in vars(TosaOp).items() if v == builtin)
329
330
331# TODO will return UNKNOWN for the once that have not yet been defined in tosa_operator_map
332def optype_to_tosa_op_type(op_type):
333 if op_type in tosa_operator_inv_map:
334 return tosa_type_name(tosa_operator_inv_map[op_type][0])
335 else:
336 return TosaOp.UNKNOWN