blob: f635e4a6f995404709ea0294b441abb9f37ebf3f [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
Patrik Gustavsson85f61172021-10-01 08:15:06 +020029from .tosa import ConvAttribute # noqa: F401
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020030from .tosa import ConvQuantInfo # noqa: F401
31from .tosa import MatMulQuantInfo # noqa: F401
32from .tosa import MulAttribute # noqa: F401
33from .tosa import PadQuantInfo # noqa: F401
Patrik Gustavsson85f61172021-10-01 08:15:06 +020034from .tosa import PoolAttribute # noqa: F401
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020035from .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
Patrik Gustavsson85f61172021-10-01 08:15:06 +020041from .tosa import TransposeConvAttribute # noqa: F401
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +020042from .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
Patrik Gustavsson85f61172021-10-01 08:15:06 +0200151pool_attrs = AttrSerializer("PoolAttribute", (("padding", is_vec), ("kernel", is_vec), ("stride", is_vec)))
152conv_attrs = AttrSerializer("ConvAttribute", (("padding", is_vec), ("stride", is_vec), ("dilation", is_vec)))
153transpose_conv_attrs = AttrSerializer(
154 "TransposeConvAttribute", (("outpad", is_vec), ("stride", is_vec), ("dilation", is_vec), ("out_shape", is_vec))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200155)
156relun_attrs = AttrSerializer("ReluNAttribute", ("max_int"))
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200157axis_attrs = AttrSerializer("AxisAttribute", ("axis",))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200158reshape_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)
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200169mul_attrs = AttrSerializer("MulAttribute", ("shift",))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200170ars_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"))
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200177pad_quant_info = QuantSerializer("PadQuantInfo", ("input_zp",))
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200178
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,
Patrik Gustavsson85f61172021-10-01 08:15:06 +0200190 TosaOp.INTDIV,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200191 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,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200198 TosaOp.POW,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200199 TosaOp.ABS,
200 TosaOp.BITWISE_NOT,
201 TosaOp.CEIL,
202 TosaOp.CLZ,
203 TosaOp.EXP,
204 TosaOp.FLOOR,
205 TosaOp.LOG,
206 TosaOp.LOGICAL_NOT,
207 TosaOp.NEGATE,
208 TosaOp.RECIPROCAL,
209 TosaOp.RSQRT,
210 TosaOp.SELECT,
211 TosaOp.EQUAL,
212 TosaOp.GREATER,
213 TosaOp.GREATER_EQUAL,
214 TosaOp.REDUCE_ANY,
215 TosaOp.REDUCE_ALL,
216 TosaOp.REDUCE_MAX,
217 TosaOp.REDUCE_MIN,
218 TosaOp.REDUCE_PRODUCT,
219 TosaOp.REDUCE_SUM,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200220 TosaOp.REVERSE,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200221 TosaOp.TILE,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200222 TosaOp.GATHER,
223 TosaOp.SCATTER,
224 TosaOp.RESIZE,
225 TosaOp.CAST,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200226 TosaOp.CUSTOM,
227 TosaOp.COND_IF,
228 TosaOp.WHILE_LOOP,
229}
230
231
232TOSA_NO_INDICES = TensorIndices([], [], [])
233TOSA_IFM_INDICES = TensorIndices([0], [], [])
234# TOSA_IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
235TOSA_IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
236TOSA_IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
237# TOSA_CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
238# TOSA_TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200239TOSA_CONCAT_INDICES = TensorIndices([1, 2], [], [])
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200240# TOSA_SPLIT_IFM_INDICES = TensorIndices([1], [], [])
241# TOSA_BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
242
243
244tosa_operator_map = {
245 # TosaOp.UNKNOWN: (),
246 # TODO TosaOp.ARGMAX: (Op.ArgMax, axis_attrs, None),
Patrik Gustavsson85f61172021-10-01 08:15:06 +0200247 TosaOp.AVG_POOL2D: (Op.AvgPool, pool_attrs, unary_quant_info, TOSA_IFM_INDICES),
248 TosaOp.CONV2D: (Op.Conv2DBias, conv_attrs, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200249 # TODO TosaOp.CONV3D:
Patrik Gustavsson85f61172021-10-01 08:15:06 +0200250 TosaOp.DEPTHWISE_CONV2D: (Op.DepthwiseConv2DBias, conv_attrs, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200251 TosaOp.FULLY_CONNECTED: (Op.FullyConnected, None, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
252 # TODO TosaOp.MATMUL:
Patrik Gustavsson85f61172021-10-01 08:15:06 +0200253 TosaOp.MAX_POOL2D: (Op.MaxPool, pool_attrs, None, TOSA_IFM_INDICES),
254 # TODO TosaOp.TRANSPOSE_CONV2D: (Op.Conv2DBackpropInput, transpose_conv_attrs, conv_quant_info)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200255 TosaOp.CLAMP: (Op.Clamp, clamp_attrs, None, TOSA_IFM_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200256 TosaOp.RELUN: (Op.ReluN, relun_attrs, None, TOSA_IFM_INDICES),
257 # TODO TosaOp.SIGMOID
258 # TODO TosaOp.TANH
259 TosaOp.ADD: (Op.Add, None, None, TOSA_IFM_IFM2_INDICES),
260 TosaOp.ARITHMETIC_RIGHT_SHIFT: (Op.SHR, ars_attrs, None, TOSA_IFM_IFM2_INDICES),
261 # TODO TosaOp.BITWISE_AND
262 # TODO TosaOp.BITWISE_OR
263 # TODO TosaOp.BITWISE_XOR
Patrik Gustavsson85f61172021-10-01 08:15:06 +0200264 # TODO TosaOp.INTDIV
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200265 # TODO TosaOp.LOGICAL_AND
266 # TODO TosaOp.LOGICAL_LEFT_SHIFT
267 # TODO TosaOp.LOGICAL_RIGHT_SHIFT
268 # TODO TosaOp.LOGICAL_OR
269 # TODO TosaOp.LOGICAL_XOR
270 # TODO TosaOp.MAXIMUM
271 # TODO TosaOp.MINIMUM
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200272 TosaOp.MUL: (Op.Mul, mul_attrs, None, TOSA_IFM_IFM2_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200273 # TODO TosaOp.POW
274 TosaOp.SUB: (Op.Sub, None, None, TOSA_IFM_IFM2_INDICES),
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200275 # TODO is table content in input[1] always constant?
276 TosaOp.TABLE: (Op.Table, None, None, TOSA_IFM_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200277 # TODO TosaOp.ABS
278 # TODO TosaOp.BITWISE_NOT
279 # TODO TosaOp.CEIL
280 # TODO TosaOp.CLZ
281 # TODO TosaOp.EXP
282 # TODO TosaOp.FLOOR
283 # TODO TosaOp.LOG
284 # TODO TosaOp.LOGICAL_NOT
285 # TODO TosaOp.NEGATE
286 # TODO TosaOp.RECIPROCAL
287 # TODO TosaOp.RSQRT
288 # TODO TosaOp.SELECT
289 # TODO TosaOp.EQUAL
290 # TODO TosaOp.GREATER
291 # TODO TosaOp.GREATER_EQUAL
292 # TODO TosaOp.REDUCE_ANY
293 # TODO TosaOp.REDUCE_ALL
294 # TODO TosaOp.REDUCE_MAX
295 # TODO TosaOp.REDUCE_MIN
296 # TODO TosaOp.REDUCE_PRODUCT
297 # TODO TosaOp.REDUCE_SUM
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200298 TosaOp.CONCAT: (Op.Concat, axis_attrs, None, TOSA_CONCAT_INDICES),
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200299 # TODO Is the padding intended to be dynamic input, TOSA spec state it as attribute
300 # Handled as for TFLite for now
301 TosaOp.PAD: (Op.Pad, None, pad_quant_info, TOSA_IFM_INDICES),
Patrik Gustavssondf995102021-08-23 15:33:59 +0200302 TosaOp.RESHAPE: (Op.Reshape, reshape_attrs, None, TOSA_IFM_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200303 # TODO TosaOp.REVERSE
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200304 TosaOp.SLICE: (Op.SplitSliceRead, slice_attrs, None, TOSA_IFM_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200305 # TODO TosaOp.TILE
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200306 TosaOp.TRANSPOSE: (
307 Op.Transpose,
308 None,
309 None,
310 TOSA_IFM_IFM2_INDICES,
311 ), # TODO Is the perms intended to be dynamic input, TOSA spec state it as attribute
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200312 # 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),
Patrik Gustavssonef3ebdd2021-10-01 11:10:25 +0200318 TosaOp.IDENTITY: (Op.Identity, None, None, TOSA_IFM_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200319 # 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
Tim Halla3fe6652022-03-03 17:43:16 +0000326tosa_operator_name_map = {v: k for k, v in vars(TosaOp).items()}
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200327
328
329# TODO will return UNKNOWN for the once that have not yet been defined in tosa_operator_map
Tim Halla3fe6652022-03-03 17:43:16 +0000330def optype_to_tosa_op_type(op_type: Op):
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200331 if op_type in tosa_operator_inv_map:
Tim Halla3fe6652022-03-03 17:43:16 +0000332 return tosa_operator_name_map[tosa_operator_inv_map[op_type][0]]
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200333 else:
334 return TosaOp.UNKNOWN