blob: 6efc4791e9860c19c09687e93ba9900fa2833770 [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"))
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"))
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,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200198 TosaOp.POW,
199 TosaOp.TABLE,
200 TosaOp.ABS,
201 TosaOp.BITWISE_NOT,
202 TosaOp.CEIL,
203 TosaOp.CLZ,
204 TosaOp.EXP,
205 TosaOp.FLOOR,
206 TosaOp.LOG,
207 TosaOp.LOGICAL_NOT,
208 TosaOp.NEGATE,
209 TosaOp.RECIPROCAL,
210 TosaOp.RSQRT,
211 TosaOp.SELECT,
212 TosaOp.EQUAL,
213 TosaOp.GREATER,
214 TosaOp.GREATER_EQUAL,
215 TosaOp.REDUCE_ANY,
216 TosaOp.REDUCE_ALL,
217 TosaOp.REDUCE_MAX,
218 TosaOp.REDUCE_MIN,
219 TosaOp.REDUCE_PRODUCT,
220 TosaOp.REDUCE_SUM,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200221 TosaOp.PAD,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200222 TosaOp.REVERSE,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200223 TosaOp.TILE,
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200224 TosaOp.GATHER,
225 TosaOp.SCATTER,
226 TosaOp.RESIZE,
227 TosaOp.CAST,
228 TosaOp.IDENTITY,
229 TosaOp.CUSTOM,
230 TosaOp.COND_IF,
231 TosaOp.WHILE_LOOP,
232}
233
234
235TOSA_NO_INDICES = TensorIndices([], [], [])
236TOSA_IFM_INDICES = TensorIndices([0], [], [])
237# TOSA_IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
238TOSA_IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
239TOSA_IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
240# TOSA_CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
241# TOSA_TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200242TOSA_CONCAT_INDICES = TensorIndices([1, 2], [], [])
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200243# TOSA_SPLIT_IFM_INDICES = TensorIndices([1], [], [])
244# TOSA_BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
245
246
247tosa_operator_map = {
248 # TosaOp.UNKNOWN: (),
249 # TODO TosaOp.ARGMAX: (Op.ArgMax, axis_attrs, None),
250 TosaOp.AVG_POOL2D: (Op.AvgPool, pool2d_attrs, unary_quant_info, TOSA_IFM_INDICES),
251 TosaOp.CONV2D: (Op.Conv2DBias, conv2d_attrs, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
252 # TODO TosaOp.CONV3D:
253 TosaOp.DEPTHWISE_CONV2D: (Op.DepthwiseConv2DBias, conv2d_attrs, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
254 TosaOp.FULLY_CONNECTED: (Op.FullyConnected, None, conv_quant_info, TOSA_IFM_WEIGHTS_BIAS_INDICES),
255 # TODO TosaOp.MATMUL:
256 TosaOp.MAX_POOL2D: (Op.MaxPool, pool2d_attrs, None, TOSA_IFM_INDICES),
257 # TODO TosaOp.TRANSPOSE_CONV2D: (Op.Conv2DBackpropInput, transpose_conv2d_attrs, conv_quant_info)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200258 TosaOp.CLAMP: (Op.Clamp, clamp_attrs, None, TOSA_IFM_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200259 TosaOp.RELUN: (Op.ReluN, relun_attrs, None, TOSA_IFM_INDICES),
260 # TODO TosaOp.SIGMOID
261 # TODO TosaOp.TANH
262 TosaOp.ADD: (Op.Add, None, None, TOSA_IFM_IFM2_INDICES),
263 TosaOp.ARITHMETIC_RIGHT_SHIFT: (Op.SHR, ars_attrs, None, TOSA_IFM_IFM2_INDICES),
264 # TODO TosaOp.BITWISE_AND
265 # TODO TosaOp.BITWISE_OR
266 # TODO TosaOp.BITWISE_XOR
267 # TODO TosaOp.DIV
268 # TODO TosaOp.LOGICAL_AND
269 # TODO TosaOp.LOGICAL_LEFT_SHIFT
270 # TODO TosaOp.LOGICAL_RIGHT_SHIFT
271 # TODO TosaOp.LOGICAL_OR
272 # TODO TosaOp.LOGICAL_XOR
273 # TODO TosaOp.MAXIMUM
274 # TODO TosaOp.MINIMUM
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200275 TosaOp.MUL: (Op.Mul, mul_attrs, None, TOSA_IFM_IFM2_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200276 # TODO TosaOp.POW
277 TosaOp.SUB: (Op.Sub, None, None, TOSA_IFM_IFM2_INDICES),
278 # TODO TosaOp.TABLE
279 # TODO TosaOp.ABS
280 # TODO TosaOp.BITWISE_NOT
281 # TODO TosaOp.CEIL
282 # TODO TosaOp.CLZ
283 # TODO TosaOp.EXP
284 # TODO TosaOp.FLOOR
285 # TODO TosaOp.LOG
286 # TODO TosaOp.LOGICAL_NOT
287 # TODO TosaOp.NEGATE
288 # TODO TosaOp.RECIPROCAL
289 # TODO TosaOp.RSQRT
290 # TODO TosaOp.SELECT
291 # TODO TosaOp.EQUAL
292 # TODO TosaOp.GREATER
293 # TODO TosaOp.GREATER_EQUAL
294 # TODO TosaOp.REDUCE_ANY
295 # TODO TosaOp.REDUCE_ALL
296 # TODO TosaOp.REDUCE_MAX
297 # TODO TosaOp.REDUCE_MIN
298 # TODO TosaOp.REDUCE_PRODUCT
299 # TODO TosaOp.REDUCE_SUM
Patrik Gustavssonf1580f02021-09-01 12:43:02 +0200300 TosaOp.CONCAT: (Op.Concat, axis_attrs, None, TOSA_CONCAT_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200301 # TODO TosaOp.PAD
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 Gustavssondf995102021-08-23 15:33:59 +0200306 TosaOp.TRANSPOSE: (Op.Transpose, None, None, TOSA_IFM_IFM2_INDICES),
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200307 # TODO TosaOp.GATHER
308 # TODO TosaOp.SCATTER
309 # TODO TosaOp.RESIZE
310 # TODO TosaOp.CAST
311 TosaOp.RESCALE: (Op.Rescale, rescale_attrs, None, TOSA_IFM_INDICES),
312 TosaOp.CONST: (Op.Const, None, None, TOSA_NO_INDICES),
313 # TODO TosaOp.IDENTITY
314 # TODO TosaOp.CUSTOM
315 # TODO TosaOp.COND_IF
316 # TODO TosaOp.WHILE_LOOP
317}
318
319tosa_operator_inv_map = {v[0]: (k, v[1]) for k, v in tosa_operator_map.items()}
320
321
322def tosa_type_name(builtin):
323 return next(k for k, v in vars(TosaOp).items() if v == builtin)
324
325
326# TODO will return UNKNOWN for the once that have not yet been defined in tosa_operator_map
327def optype_to_tosa_op_type(op_type):
328 if op_type in tosa_operator_inv_map:
329 return tosa_type_name(tosa_operator_inv_map[op_type][0])
330 else:
331 return TosaOp.UNKNOWN