blob: 23a1a2b7aaa2b69fb0f1e2921a3dca7915b48eb4 [file] [log] [blame]
erik.andersson@arm.com460c6892021-02-24 14:38:09 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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# TensorFlow Lite mapping functions used by both reader and writer.
18# Contains a mapping from the various TensorFlow Lite enums and options structs, generated by the FlatBuffer code
19# generator, to Vela's internal format.
Tim Hall79d07d22020-04-27 18:20:16 +010020import struct
21
Diego Russoea6111a2020-04-14 18:41:58 +010022import numpy as np
23
Tim Hall79d07d22020-04-27 18:20:16 +010024from .data_type import DataType
Louis Verhaardaee5d752020-09-30 09:01:52 +020025from .operation import CustomType
26from .operation import Op
Michael McGeagh16895482020-12-14 15:51:20 +000027from .operation import Padding as opPad
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +020028from .operation import TensorIndices
Diego Russoe8a10452020-04-21 17:39:10 +010029from .tflite import AbsOptions
30from .tflite import AddNOptions
Tim Hall79d07d22020-04-27 18:20:16 +010031from .tflite import AddOptions
Tim Hall79d07d22020-04-27 18:20:16 +010032from .tflite import ArgMaxOptions
Tim Hall79d07d22020-04-27 18:20:16 +010033from .tflite import ArgMinOptions
Jacob Bohlin8daf6b72020-09-15 16:28:35 +020034from .tflite import BatchMatMulOptions
Diego Russoe8a10452020-04-21 17:39:10 +010035from .tflite import BatchToSpaceNDOptions
Tim Hall79d07d22020-04-27 18:20:16 +010036from .tflite import BidirectionalSequenceLSTMOptions
37from .tflite import BidirectionalSequenceRNNOptions
Diego Russoe8a10452020-04-21 17:39:10 +010038from .tflite import CallOptions
39from .tflite import CastOptions
40from .tflite import ConcatEmbeddingsOptions
41from .tflite import ConcatenationOptions
42from .tflite import Conv2DOptions
Tim Hall79d07d22020-04-27 18:20:16 +010043from .tflite import CosOptions
Tim Hall42abec12021-02-04 21:31:57 +000044from .tflite import CumsumOptions
Tim Hall79d07d22020-04-27 18:20:16 +010045from .tflite import DensifyOptions
46from .tflite import DepthToSpaceOptions
Diego Russoe8a10452020-04-21 17:39:10 +010047from .tflite import DepthwiseConv2DOptions
48from .tflite import DequantizeOptions
49from .tflite import DivOptions
50from .tflite import EmbeddingLookupSparseOptions
51from .tflite import EqualOptions
52from .tflite import ExpandDimsOptions
53from .tflite import ExpOptions
54from .tflite import FakeQuantOptions
55from .tflite import FillOptions
56from .tflite import FloorDivOptions
57from .tflite import FloorModOptions
58from .tflite import FullyConnectedOptions
59from .tflite import GatherNdOptions
60from .tflite import GatherOptions
61from .tflite import GreaterEqualOptions
62from .tflite import GreaterOptions
Louis Verhaard678645b2020-06-15 15:22:47 +020063from .tflite import HardSwishOptions
Tim Hall79d07d22020-04-27 18:20:16 +010064from .tflite import IfOptions
Diego Russoe8a10452020-04-21 17:39:10 +010065from .tflite import L2NormOptions
66from .tflite import LeakyReluOptions
67from .tflite import LessEqualOptions
68from .tflite import LessOptions
69from .tflite import LocalResponseNormalizationOptions
70from .tflite import LogicalAndOptions
71from .tflite import LogicalNotOptions
72from .tflite import LogicalOrOptions
73from .tflite import LogSoftmaxOptions
74from .tflite import LSHProjectionOptions
75from .tflite import LSTMOptions
76from .tflite import MatrixDiagOptions
77from .tflite import MatrixSetDiagOptions
78from .tflite import MaximumMinimumOptions
79from .tflite import MirrorPadOptions
80from .tflite import MulOptions
81from .tflite import NegOptions
Tim Hall79d07d22020-04-27 18:20:16 +010082from .tflite import NonMaxSuppressionV4Options
83from .tflite import NonMaxSuppressionV5Options
Diego Russoe8a10452020-04-21 17:39:10 +010084from .tflite import NotEqualOptions
85from .tflite import OneHotOptions
86from .tflite import PackOptions
87from .tflite import PadOptions
88from .tflite import PadV2Options
89from .tflite import Pool2DOptions
90from .tflite import PowOptions
91from .tflite import QuantizeOptions
92from .tflite import RangeOptions
93from .tflite import RankOptions
94from .tflite import ReducerOptions
95from .tflite import ReshapeOptions
96from .tflite import ResizeBilinearOptions
97from .tflite import ResizeNearestNeighborOptions
98from .tflite import ReverseSequenceOptions
99from .tflite import ReverseV2Options
100from .tflite import RNNOptions
Tim Hall79d07d22020-04-27 18:20:16 +0100101from .tflite import ScatterNdOptions
102from .tflite import SegmentSumOptions
Diego Russoe8a10452020-04-21 17:39:10 +0100103from .tflite import SelectOptions
Tim Hall79d07d22020-04-27 18:20:16 +0100104from .tflite import SelectV2Options
Diego Russoe8a10452020-04-21 17:39:10 +0100105from .tflite import SequenceRNNOptions
106from .tflite import ShapeOptions
107from .tflite import SkipGramOptions
108from .tflite import SliceOptions
109from .tflite import SoftmaxOptions
110from .tflite import SpaceToBatchNDOptions
111from .tflite import SpaceToDepthOptions
112from .tflite import SparseToDenseOptions
113from .tflite import SplitOptions
114from .tflite import SplitVOptions
115from .tflite import SquaredDifferenceOptions
116from .tflite import SquareOptions
117from .tflite import SqueezeOptions
118from .tflite import StridedSliceOptions
119from .tflite import SubOptions
120from .tflite import SVDFOptions
121from .tflite import TileOptions
122from .tflite import TopKV2Options
123from .tflite import TransposeConvOptions
124from .tflite import TransposeOptions
125from .tflite import UnidirectionalSequenceLSTMOptions
126from .tflite import UniqueOptions
127from .tflite import UnpackOptions
128from .tflite import WhereOptions
Tim Hall79d07d22020-04-27 18:20:16 +0100129from .tflite import WhileOptions
Diego Russoe8a10452020-04-21 17:39:10 +0100130from .tflite import ZerosLikeOptions
131from .tflite.ActivationFunctionType import ActivationFunctionType
Diego Russoea6111a2020-04-14 18:41:58 +0100132from .tflite.BuiltinOperator import BuiltinOperator
133from .tflite.BuiltinOptions import BuiltinOptions
134from .tflite.Padding import Padding
Diego Russoe8a10452020-04-21 17:39:10 +0100135from .tflite.TensorType import TensorType
Tim Hall79d07d22020-04-27 18:20:16 +0100136
137
138def inverse_map(map):
139 return {v: k for k, v in map.items()}
140
141
142datatype_map = {
143 TensorType.UINT8: DataType.uint8,
144 TensorType.INT8: DataType.int8,
145 TensorType.INT16: DataType.int16,
146 TensorType.INT32: DataType.int32,
147 TensorType.INT64: DataType.int64,
148 TensorType.FLOAT16: DataType.float16,
149 TensorType.FLOAT32: DataType.float32,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200150 TensorType.FLOAT64: DataType.float64,
Tim Hall79d07d22020-04-27 18:20:16 +0100151 TensorType.STRING: DataType.string,
152 TensorType.BOOL: DataType.bool,
Jacob Bohlinf767b932020-08-13 15:32:45 +0200153 TensorType.COMPLEX64: DataType.complex64,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200154 TensorType.COMPLEX128: DataType.complex128,
Tim Hall79d07d22020-04-27 18:20:16 +0100155}
156
157datatype_inv_map = inverse_map(datatype_map)
158datatype_inv_map[DataType.quint8] = TensorType.UINT8
159
160datatype_inv_map[DataType.qint8] = TensorType.INT8
161datatype_inv_map[DataType.qint16] = TensorType.INT16
162datatype_inv_map[DataType.qint32] = TensorType.INT32
163
164
165datatype_map_numpy = {
166 TensorType.UINT8: np.uint8,
167 TensorType.INT8: np.int8,
168 TensorType.INT16: np.int16,
169 TensorType.INT32: np.int32,
170 TensorType.INT64: np.int64,
171 TensorType.FLOAT16: np.float16,
172 TensorType.FLOAT32: np.float32,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200173 TensorType.FLOAT64: np.float64,
Tim Hall79d07d22020-04-27 18:20:16 +0100174 TensorType.BOOL: np.bool,
Jacob Bohlinf767b932020-08-13 15:32:45 +0200175 TensorType.COMPLEX64: np.complex64,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200176 TensorType.COMPLEX128: np.complex128,
Louis Verhaardf4e12be2020-12-18 14:23:06 +0100177 TensorType.STRING: np.uint8,
Tim Hall79d07d22020-04-27 18:20:16 +0100178}
179
180
181builtin_options_map = {
182 BuiltinOptions.Conv2DOptions: Conv2DOptions.Conv2DOptions,
183 BuiltinOptions.DepthwiseConv2DOptions: DepthwiseConv2DOptions.DepthwiseConv2DOptions,
184 BuiltinOptions.ConcatEmbeddingsOptions: ConcatEmbeddingsOptions.ConcatEmbeddingsOptions,
185 BuiltinOptions.LSHProjectionOptions: LSHProjectionOptions.LSHProjectionOptions,
186 BuiltinOptions.Pool2DOptions: Pool2DOptions.Pool2DOptions,
187 BuiltinOptions.SVDFOptions: SVDFOptions.SVDFOptions,
188 BuiltinOptions.RNNOptions: RNNOptions.RNNOptions,
189 BuiltinOptions.FullyConnectedOptions: FullyConnectedOptions.FullyConnectedOptions,
190 BuiltinOptions.SoftmaxOptions: SoftmaxOptions.SoftmaxOptions,
191 BuiltinOptions.ConcatenationOptions: ConcatenationOptions.ConcatenationOptions,
192 BuiltinOptions.AddOptions: AddOptions.AddOptions,
193 BuiltinOptions.L2NormOptions: L2NormOptions.L2NormOptions,
194 BuiltinOptions.LocalResponseNormalizationOptions: LocalResponseNormalizationOptions.LocalResponseNormalizationOptions, # noqa: E501
195 BuiltinOptions.LSTMOptions: LSTMOptions.LSTMOptions,
196 BuiltinOptions.ResizeBilinearOptions: ResizeBilinearOptions.ResizeBilinearOptions,
197 BuiltinOptions.CallOptions: CallOptions.CallOptions,
198 BuiltinOptions.ReshapeOptions: ReshapeOptions.ReshapeOptions,
199 BuiltinOptions.SkipGramOptions: SkipGramOptions.SkipGramOptions,
200 BuiltinOptions.SpaceToDepthOptions: SpaceToDepthOptions.SpaceToDepthOptions,
201 BuiltinOptions.EmbeddingLookupSparseOptions: EmbeddingLookupSparseOptions.EmbeddingLookupSparseOptions,
202 BuiltinOptions.MulOptions: MulOptions.MulOptions,
203 BuiltinOptions.PadOptions: PadOptions.PadOptions,
204 BuiltinOptions.GatherOptions: GatherOptions.GatherOptions,
205 BuiltinOptions.BatchToSpaceNDOptions: BatchToSpaceNDOptions.BatchToSpaceNDOptions,
206 BuiltinOptions.SpaceToBatchNDOptions: SpaceToBatchNDOptions.SpaceToBatchNDOptions,
207 BuiltinOptions.TransposeOptions: TransposeOptions.TransposeOptions,
208 BuiltinOptions.ReducerOptions: ReducerOptions.ReducerOptions,
209 BuiltinOptions.SubOptions: SubOptions.SubOptions,
210 BuiltinOptions.DivOptions: DivOptions.DivOptions,
211 BuiltinOptions.SqueezeOptions: SqueezeOptions.SqueezeOptions,
212 BuiltinOptions.SequenceRNNOptions: SequenceRNNOptions.SequenceRNNOptions,
213 BuiltinOptions.StridedSliceOptions: StridedSliceOptions.StridedSliceOptions,
214 BuiltinOptions.ExpOptions: ExpOptions.ExpOptions,
215 BuiltinOptions.TopKV2Options: TopKV2Options.TopKV2Options,
216 BuiltinOptions.SplitOptions: SplitOptions.SplitOptions,
217 BuiltinOptions.LogSoftmaxOptions: LogSoftmaxOptions.LogSoftmaxOptions,
218 BuiltinOptions.CastOptions: CastOptions.CastOptions,
219 BuiltinOptions.DequantizeOptions: DequantizeOptions.DequantizeOptions,
220 BuiltinOptions.MaximumMinimumOptions: MaximumMinimumOptions.MaximumMinimumOptions,
221 BuiltinOptions.ArgMaxOptions: ArgMaxOptions.ArgMaxOptions,
222 BuiltinOptions.LessOptions: LessOptions.LessOptions,
223 BuiltinOptions.NegOptions: NegOptions.NegOptions,
224 BuiltinOptions.PadV2Options: PadV2Options.PadV2Options,
225 BuiltinOptions.GreaterOptions: GreaterOptions.GreaterOptions,
226 BuiltinOptions.GreaterEqualOptions: GreaterEqualOptions.GreaterEqualOptions,
227 BuiltinOptions.LessEqualOptions: LessEqualOptions.LessEqualOptions,
228 BuiltinOptions.SelectOptions: SelectOptions.SelectOptions,
229 BuiltinOptions.SliceOptions: SliceOptions.SliceOptions,
230 BuiltinOptions.TransposeConvOptions: TransposeConvOptions.TransposeConvOptions,
231 BuiltinOptions.SparseToDenseOptions: SparseToDenseOptions.SparseToDenseOptions,
232 BuiltinOptions.TileOptions: TileOptions.TileOptions,
233 BuiltinOptions.ExpandDimsOptions: ExpandDimsOptions.ExpandDimsOptions,
234 BuiltinOptions.EqualOptions: EqualOptions.EqualOptions,
235 BuiltinOptions.NotEqualOptions: NotEqualOptions.NotEqualOptions,
236 BuiltinOptions.ShapeOptions: ShapeOptions.ShapeOptions,
237 BuiltinOptions.PowOptions: PowOptions.PowOptions,
238 BuiltinOptions.ArgMinOptions: ArgMinOptions.ArgMinOptions,
239 BuiltinOptions.FakeQuantOptions: FakeQuantOptions.FakeQuantOptions,
240 BuiltinOptions.PackOptions: PackOptions.PackOptions,
241 BuiltinOptions.LogicalOrOptions: LogicalOrOptions.LogicalOrOptions,
242 BuiltinOptions.OneHotOptions: OneHotOptions.OneHotOptions,
243 BuiltinOptions.LogicalAndOptions: LogicalAndOptions.LogicalAndOptions,
244 BuiltinOptions.LogicalNotOptions: LogicalNotOptions.LogicalNotOptions,
245 BuiltinOptions.UnpackOptions: UnpackOptions.UnpackOptions,
246 BuiltinOptions.FloorDivOptions: FloorDivOptions.FloorDivOptions,
247 BuiltinOptions.SquareOptions: SquareOptions.SquareOptions,
248 BuiltinOptions.ZerosLikeOptions: ZerosLikeOptions.ZerosLikeOptions,
249 BuiltinOptions.FillOptions: FillOptions.FillOptions,
250 BuiltinOptions.BidirectionalSequenceLSTMOptions: BidirectionalSequenceLSTMOptions.BidirectionalSequenceLSTMOptions,
251 BuiltinOptions.BidirectionalSequenceRNNOptions: BidirectionalSequenceRNNOptions.BidirectionalSequenceRNNOptions,
252 BuiltinOptions.UnidirectionalSequenceLSTMOptions: UnidirectionalSequenceLSTMOptions.UnidirectionalSequenceLSTMOptions, # noqa: E501
253 BuiltinOptions.FloorModOptions: FloorModOptions.FloorModOptions,
254 BuiltinOptions.RangeOptions: RangeOptions.RangeOptions,
255 BuiltinOptions.ResizeNearestNeighborOptions: ResizeNearestNeighborOptions.ResizeNearestNeighborOptions,
256 BuiltinOptions.LeakyReluOptions: LeakyReluOptions.LeakyReluOptions,
257 BuiltinOptions.SquaredDifferenceOptions: SquaredDifferenceOptions.SquaredDifferenceOptions,
258 BuiltinOptions.MirrorPadOptions: MirrorPadOptions.MirrorPadOptions,
259 BuiltinOptions.AbsOptions: AbsOptions.AbsOptions,
260 BuiltinOptions.SplitVOptions: SplitVOptions.SplitVOptions,
261 BuiltinOptions.UniqueOptions: UniqueOptions.UniqueOptions,
262 BuiltinOptions.ReverseV2Options: ReverseV2Options.ReverseV2Options,
263 BuiltinOptions.AddNOptions: AddNOptions.AddNOptions,
264 BuiltinOptions.GatherNdOptions: GatherNdOptions.GatherNdOptions,
265 BuiltinOptions.CosOptions: CosOptions.CosOptions,
266 BuiltinOptions.WhereOptions: WhereOptions.WhereOptions,
267 BuiltinOptions.RankOptions: RankOptions.RankOptions,
268 BuiltinOptions.ReverseSequenceOptions: ReverseSequenceOptions.ReverseSequenceOptions,
269 BuiltinOptions.MatrixDiagOptions: MatrixDiagOptions.MatrixDiagOptions,
270 BuiltinOptions.QuantizeOptions: QuantizeOptions.QuantizeOptions,
271 BuiltinOptions.MatrixSetDiagOptions: MatrixSetDiagOptions.MatrixSetDiagOptions,
272 BuiltinOptions.DensifyOptions: DensifyOptions.DensifyOptions,
273 BuiltinOptions.DepthToSpaceOptions: DepthToSpaceOptions.DepthToSpaceOptions,
Louis Verhaard678645b2020-06-15 15:22:47 +0200274 BuiltinOptions.HardSwishOptions: HardSwishOptions.HardSwishOptions,
Tim Hall79d07d22020-04-27 18:20:16 +0100275 BuiltinOptions.IfOptions: IfOptions.IfOptions,
276 BuiltinOptions.NonMaxSuppressionV4Options: NonMaxSuppressionV4Options.NonMaxSuppressionV4Options,
277 BuiltinOptions.NonMaxSuppressionV5Options: NonMaxSuppressionV5Options.NonMaxSuppressionV5Options,
278 BuiltinOptions.ScatterNdOptions: ScatterNdOptions.ScatterNdOptions,
279 BuiltinOptions.SegmentSumOptions: SegmentSumOptions.SegmentSumOptions,
280 BuiltinOptions.SelectV2Options: SelectV2Options.SelectV2Options,
281 BuiltinOptions.WhileOptions: WhileOptions.WhileOptions,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200282 BuiltinOptions.BatchMatMulOptions: BatchMatMulOptions.BatchMatMulOptions,
Tim Hall42abec12021-02-04 21:31:57 +0000283 BuiltinOptions.CumsumOptions: CumsumOptions.CumsumOptions,
Tim Hall79d07d22020-04-27 18:20:16 +0100284}
285
286builtin_options_inv_map = inverse_map(builtin_options_map)
287
288
289def underscore_to_camel_case(s):
290 return "".join(x.title() for x in s.split("_"))
291
292
293def padding_deserialize(x):
294 return padding_map[x]
295
296
297def padding_serialize(builder, x):
298 return padding_inv_map[x]
299
300
301def activation_deserialize(x):
302 return activation_function_map[x]
303
304
305def activation_serialize(builder, x):
306 return activation_function_inv_map[x]
307
308
309def datatype_deserialize(x):
310 return datatype_map[x]
311
312
313def datatype_serialize(builder, x):
314 return datatype_inv_map[x]
315
316
317def identity(x):
318 return x
319
320
321def identity_serialize(builder, x):
322 return x
323
324
325def write_byte_vector(builder, v):
326 builder.StartVector(1, len(v), 1)
327 for e in v[::-1]:
328 builder.PrependByte(e)
329 return builder.EndVector(len(v))
330
331
332def write_int_vector(builder, v):
333 builder.StartVector(4, len(v), 4)
334 for e in v[::-1]:
335 builder.PrependInt32(e)
336 return builder.EndVector(len(v))
337
338
339class OptionsSerializer:
Michael McGeagh6f725262020-12-03 15:21:36 +0000340 def __init__(self, name, members=None):
Tim Hall79d07d22020-04-27 18:20:16 +0100341 self.name = name
342 self.module = globals()[self.name]
343 self.cls = getattr(self.module, self.name)
344 self.builtin_opt_type = builtin_options_inv_map[self.cls]
Tim Hall79d07d22020-04-27 18:20:16 +0100345 self.members = []
Michael McGeagh6f725262020-12-03 15:21:36 +0000346 if members is not None:
347 for mem in members:
348 deserialize = identity
349 serialize = identity_serialize
350 is_vector = False
351 if isinstance(mem, tuple):
352 if len(mem) == 3:
353 mem, deserialize, serialize = mem
354 elif len(mem) == 2:
355 mem, is_vector = mem
356 deserialize = tuple
357 serialize = write_int_vector
358 else:
359 assert 0
360 underscore_mem = mem
361 camelcase_mem = underscore_to_camel_case(mem)
362 self.members.append((underscore_mem, camelcase_mem, deserialize, serialize, is_vector))
Tim Hall79d07d22020-04-27 18:20:16 +0100363
Tim Hallc8310b12020-06-17 14:53:11 +0100364 def deserialize(self, op_data):
365 builtin_options = op_data.BuiltinOptions()
Tim Hall79d07d22020-04-27 18:20:16 +0100366 attrs = {}
Tim Hallc8310b12020-06-17 14:53:11 +0100367 if builtin_options:
Tim Hall79d07d22020-04-27 18:20:16 +0100368 tfattrs = self.cls()
Tim Hallc8310b12020-06-17 14:53:11 +0100369 tfattrs.Init(builtin_options.Bytes, builtin_options.Pos)
Tim Hall79d07d22020-04-27 18:20:16 +0100370 for underscore_mem, camelcase_mem, deserialize, serialize, is_vector in self.members:
371 fun = camelcase_mem
372 if is_vector:
373 fun += "AsNumpy"
374
Fredrik Svedberg4bb989b2020-11-16 15:32:25 +0100375 attr = getattr(tfattrs, fun)()
376 try:
377 attrs[underscore_mem] = deserialize(attr)
378 except TypeError:
379 print("Warning: {0} could not read attribute '{1}'.".format(self.name, underscore_mem))
380
Tim Hall79d07d22020-04-27 18:20:16 +0100381 return attrs
382
383 def serialize(self, builder, attrs):
384 ser_attrs = []
385 for underscore_mem, camelcase_mem, deserialize, serialize, is_vector in self.members:
386 a = serialize(builder, attrs[underscore_mem])
387 ser_attrs.append((camelcase_mem, a))
388
389 getattr(self.module, self.name + "Start")(builder)
390
391 for camelcase_mem, a in ser_attrs:
392 getattr(self.module, self.name + "Add" + camelcase_mem)(builder, a)
393
394 return getattr(self.module, self.name + "End")(builder), None
395
396
397class CustomOptionsSerializer:
Tim Hallc8310b12020-06-17 14:53:11 +0100398 CUSTOM_OPTIONS_NPU_OP = [0x01, 0x04, 0x01] # NpuOp=1, FlexbufferFormat.UINT8=4, byte length=1
399 CUSTOM_OPTIONS_FORMAT_DEFAULT = 0
400
Tim Hall79d07d22020-04-27 18:20:16 +0100401 def __init__(self):
Tim Hall79d07d22020-04-27 18:20:16 +0100402 self.custom_opt_format = 0
403
Tim Hallc8310b12020-06-17 14:53:11 +0100404 def deserialize(self, op_data):
Tim Hall79d07d22020-04-27 18:20:16 +0100405 attrs = {}
Tim Hallc8310b12020-06-17 14:53:11 +0100406 custom_options = op_data.CustomOptionsAsNumpy()
407 attrs["custom_options"] = custom_options
408 attrs["custom_options_format"] = op_data.CustomOptionsFormat()
409
410 if np.array_equal(custom_options, self.CUSTOM_OPTIONS_NPU_OP):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200411 attrs["custom_type"] = CustomType.ExistingNpuOp
Tim Hallc8310b12020-06-17 14:53:11 +0100412
Tim Hall79d07d22020-04-27 18:20:16 +0100413 return attrs
414
415 def serialize(self, builder, attrs):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200416 custom_type = attrs.get("custom_type", CustomType.ThirdPartyOp)
Tim Hallc8310b12020-06-17 14:53:11 +0100417 self.custom_opt_format = attrs.get("custom_options_format", self.CUSTOM_OPTIONS_FORMAT_DEFAULT)
Tim Hall79d07d22020-04-27 18:20:16 +0100418
419 # Set NPU op custom options for the TensorFlow Lite custom operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200420 if custom_type == CustomType.NpuOp:
Tim Hallc8310b12020-06-17 14:53:11 +0100421 custom_options = self.CUSTOM_OPTIONS_NPU_OP
422 else:
423 custom_options = attrs.get("custom_options", [])
Tim Hall79d07d22020-04-27 18:20:16 +0100424
Tim Hallc8310b12020-06-17 14:53:11 +0100425 custom_options_bytes = struct.pack("<{0}B".format(len(custom_options)), *custom_options)
426 custom_offset = write_byte_vector(builder, custom_options_bytes)
Tim Hall79d07d22020-04-27 18:20:16 +0100427
428 return None, custom_offset
429
430
431padding_map = {
Michael McGeagh16895482020-12-14 15:51:20 +0000432 Padding.SAME: opPad.SAME,
433 Padding.VALID: opPad.VALID,
Tim Hall79d07d22020-04-27 18:20:16 +0100434}
435
436padding_inv_map = inverse_map(padding_map)
437
438
439activation_function_map = {
440 ActivationFunctionType.NONE: None,
Louis Verhaardaee5d752020-09-30 09:01:52 +0200441 ActivationFunctionType.RELU: Op.Relu,
442 ActivationFunctionType.RELU_N1_TO_1: Op.ReluN1To1,
443 ActivationFunctionType.RELU6: Op.Relu6,
444 ActivationFunctionType.TANH: Op.Tanh,
445 ActivationFunctionType.SIGN_BIT: Op.SignBit,
Tim Hall79d07d22020-04-27 18:20:16 +0100446}
447
448activation_function_inv_map = inverse_map(activation_function_map)
449
450fused_act = ("fused_activation_function", activation_deserialize, activation_serialize)
451padding = ("padding", padding_deserialize, padding_serialize)
452
453pool2d_opts = OptionsSerializer(
454 "Pool2DOptions", (padding, "stride_w", "stride_h", "filter_width", "filter_height", fused_act,)
455)
456
457depthwise_opts = OptionsSerializer(
458 "DepthwiseConv2DOptions",
459 (padding, "stride_w", "stride_h", "depth_multiplier", fused_act, "dilation_w_factor", "dilation_h_factor",),
460)
461
462conv2d_opts = OptionsSerializer(
463 "Conv2DOptions", (padding, "stride_w", "stride_h", fused_act, "dilation_w_factor", "dilation_h_factor",)
464)
465
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200466lstm_opts = OptionsSerializer(
467 "LSTMOptions", (fused_act, "cell_clip", "proj_clip", "kernel_type", "asymmetric_quantize_inputs")
468)
Tim Hall79d07d22020-04-27 18:20:16 +0100469
470unidir_seq_lstm_opts = OptionsSerializer(
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200471 "UnidirectionalSequenceLSTMOptions",
472 (fused_act, "cell_clip", "proj_clip", "time_major", "asymmetric_quantize_inputs",),
Tim Hall79d07d22020-04-27 18:20:16 +0100473)
474
475bidir_seq_lstm_opts = OptionsSerializer(
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200476 "BidirectionalSequenceLSTMOptions",
477 (fused_act, "cell_clip", "proj_clip", "merge_outputs", "time_major", "asymmetric_quantize_inputs"),
Tim Hall79d07d22020-04-27 18:20:16 +0100478)
479
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200480rnn_opts = OptionsSerializer("RNNOptions", (fused_act, "asymmetric_quantize_inputs"))
Tim Hall79d07d22020-04-27 18:20:16 +0100481
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200482seq_rnn_opts = OptionsSerializer("SequenceRNNOptions", ("time_major", fused_act, "asymmetric_quantize_inputs",))
Tim Hall79d07d22020-04-27 18:20:16 +0100483
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200484bidir_seq_rnn_opts = OptionsSerializer(
485 "BidirectionalSequenceRNNOptions", ("time_major", fused_act, "merge_outputs", "asymmetric_quantize_inputs")
486)
Tim Hall79d07d22020-04-27 18:20:16 +0100487
488
489reducer_opts = OptionsSerializer("ReducerOptions", ("keep_dims",))
490
491is_int_vec = True
492
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200493TFLITE_NO_INDICES = TensorIndices([], [], [])
494TFLITE_IFM_INDICES = TensorIndices([0], [], [])
495TFLITE_IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
496TFLITE_IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
497TFLITE_IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
498TFLITE_CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
499TFLITE_TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
500TFLITE_CONCAT_INDICES = TensorIndices([1, 2], [], [])
501TFLITE_SPLIT_IFM_INDICES = TensorIndices([1], [], [])
502TFLITE_BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
503
Tim Hall79d07d22020-04-27 18:20:16 +0100504builtin_operator_map = {
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200505 BuiltinOperator.ADD: (
506 Op.Add,
507 OptionsSerializer("AddOptions", (fused_act, "pot_scale_int16")),
508 TFLITE_IFM_IFM2_INDICES,
509 ),
510 BuiltinOperator.AVERAGE_POOL_2D: (Op.AvgPool, pool2d_opts, TFLITE_IFM_INDICES),
511 BuiltinOperator.CONCATENATION: (
512 Op.ConcatTFLite,
513 OptionsSerializer("ConcatenationOptions", ("axis", fused_act)),
514 TFLITE_CONCAT_INDICES,
515 ),
516 BuiltinOperator.CONV_2D: (Op.Conv2DBias, conv2d_opts, TFLITE_IFM_WEIGHTS_BIAS_INDICES),
517 BuiltinOperator.DEPTHWISE_CONV_2D: (Op.DepthwiseConv2DBias, depthwise_opts, TFLITE_IFM_WEIGHTS_BIAS_INDICES),
518 BuiltinOperator.DEPTH_TO_SPACE: (
519 Op.DepthToSpace,
520 OptionsSerializer("DepthToSpaceOptions", ("block_size",)),
521 TFLITE_NO_INDICES,
522 ),
523 BuiltinOperator.DEQUANTIZE: (Op.Dequantize, OptionsSerializer("DequantizeOptions"), TFLITE_IFM_INDICES),
524 BuiltinOperator.EMBEDDING_LOOKUP: (Op.EmbeddingLookup, None, TFLITE_NO_INDICES),
525 BuiltinOperator.FLOOR: (Op.Floor, None, TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100526 BuiltinOperator.FULLY_CONNECTED: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200527 Op.FullyConnected,
erik.andersson@arm.com0cbb1662021-02-22 15:47:07 +0100528 OptionsSerializer(
529 "FullyConnectedOptions", (fused_act, "weights_format", "asymmetric_quantize_inputs", "keep_num_dims")
530 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200531 TFLITE_IFM_WEIGHTS_BIAS_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100532 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200533 BuiltinOperator.HASHTABLE_LOOKUP: (Op.HashtableLookup, None, TFLITE_NO_INDICES),
534 BuiltinOperator.L2_NORMALIZATION: (Op.L2Norm, OptionsSerializer("L2NormOptions", (fused_act,)), TFLITE_NO_INDICES),
535 BuiltinOperator.L2_POOL_2D: (Op.L2Pool2D, pool2d_opts, TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100536 BuiltinOperator.LOCAL_RESPONSE_NORMALIZATION: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200537 Op.LRN,
Tim Hall79d07d22020-04-27 18:20:16 +0100538 OptionsSerializer("LocalResponseNormalizationOptions", ("radius", "bias", "alpha", "beta")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200539 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100540 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200541 BuiltinOperator.LOGISTIC: (Op.Sigmoid, None, TFLITE_IFM_INDICES),
542 BuiltinOperator.LSH_PROJECTION: (
543 Op.LSHProjection,
544 OptionsSerializer("LSHProjectionOptions", ("type",)),
545 TFLITE_NO_INDICES,
546 ),
547 BuiltinOperator.LSTM: (Op.Lstm, lstm_opts, TFLITE_IFM_WEIGHTS_INDICES),
548 BuiltinOperator.MAX_POOL_2D: (Op.MaxPool, pool2d_opts, TFLITE_IFM_INDICES),
549 BuiltinOperator.MUL: (Op.Mul, OptionsSerializer("MulOptions", (fused_act,)), TFLITE_IFM_IFM2_INDICES),
550 BuiltinOperator.RELU: (Op.Relu, None, TFLITE_IFM_INDICES),
551 BuiltinOperator.RELU_N1_TO_1: (Op.ReluN1To1, None, TFLITE_IFM_INDICES),
552 BuiltinOperator.RELU6: (Op.Relu6, None, TFLITE_IFM_INDICES),
553 BuiltinOperator.RESHAPE: (
554 Op.Reshape,
555 OptionsSerializer("ReshapeOptions", (("new_shape", is_int_vec),)),
556 TFLITE_IFM_INDICES,
557 ),
Tim Hall79d07d22020-04-27 18:20:16 +0100558 BuiltinOperator.RESIZE_BILINEAR: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200559 Op.ResizeBilinear,
Tim Hall79d07d22020-04-27 18:20:16 +0100560 OptionsSerializer("ResizeBilinearOptions", ("align_corners", "half_pixel_centers")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200561 TFLITE_IFM_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100562 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200563 BuiltinOperator.RNN: (Op.Rnn, rnn_opts, TFLITE_IFM_WEIGHTS_INDICES),
564 BuiltinOperator.SOFTMAX: (Op.Softmax, OptionsSerializer("SoftmaxOptions", ("beta",)), TFLITE_IFM_INDICES),
565 BuiltinOperator.SPACE_TO_DEPTH: (
566 Op.SpaceToDepth,
567 OptionsSerializer("SpaceToDepthOptions", ("block_size",)),
568 TFLITE_NO_INDICES,
569 ),
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200570 BuiltinOperator.SVDF: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200571 Op.Svdf,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200572 OptionsSerializer("SVDFOptions", ("rank", fused_act, "asymmetric_quantize_inputs")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200573 TFLITE_NO_INDICES,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200574 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200575 BuiltinOperator.TANH: (Op.Tanh, None, TFLITE_IFM_INDICES),
Dwight Lidmand2a972d2020-08-18 14:08:10 +0200576 BuiltinOperator.CONCAT_EMBEDDINGS: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200577 Op.ConcatEmbeddings,
Dwight Lidmand2a972d2020-08-18 14:08:10 +0200578 OptionsSerializer(
579 "ConcatEmbeddingsOptions",
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200580 (
581 "num_channels",
582 "num_columns_per_channel",
583 "num_columns_per_channel_as_numpy",
584 "num_columns_per_channel_as_length",
585 "embedding_dim_per_channel",
586 "embedding_dim_per_channel_as_numpy",
587 "embedding_dim_per_channel_as_length",
588 ),
Dwight Lidmand2a972d2020-08-18 14:08:10 +0200589 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200590 TFLITE_NO_INDICES,
Dwight Lidmand2a972d2020-08-18 14:08:10 +0200591 ),
592 BuiltinOperator.SKIP_GRAM: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200593 Op.SkipGram,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200594 OptionsSerializer("SkipGramOptions", ("ngram_size", "max_skip_size", "include_all_ngrams")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200595 TFLITE_NO_INDICES,
Dwight Lidmand2a972d2020-08-18 14:08:10 +0200596 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200597 BuiltinOperator.CALL: (Op.Call, OptionsSerializer("CallOptions", ("subgraph",)), TFLITE_NO_INDICES),
Dwight Lidmand2a972d2020-08-18 14:08:10 +0200598 BuiltinOperator.EMBEDDING_LOOKUP_SPARSE: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200599 Op.EmbeddingLookupSparse,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200600 OptionsSerializer("EmbeddingLookupSparseOptions", ("combiner",)),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200601 TFLITE_NO_INDICES,
Dwight Lidmand2a972d2020-08-18 14:08:10 +0200602 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200603 BuiltinOperator.PAD: (Op.Pad, OptionsSerializer("PadOptions"), TFLITE_IFM_INDICES),
604 BuiltinOperator.UNIDIRECTIONAL_SEQUENCE_RNN: (
605 Op.UnidirectionalSequenceRnn,
606 seq_rnn_opts,
607 TFLITE_IFM_WEIGHTS_INDICES,
608 ),
609 BuiltinOperator.GATHER: (Op.GatherV2, OptionsSerializer("GatherOptions", ("axis",)), TFLITE_NO_INDICES),
610 BuiltinOperator.BATCH_TO_SPACE_ND: (
611 Op.BatchToSpaceND,
612 OptionsSerializer("BatchToSpaceNDOptions"),
613 TFLITE_NO_INDICES,
614 ),
615 BuiltinOperator.SPACE_TO_BATCH_ND: (
616 Op.SpaceToBatchND,
617 OptionsSerializer("SpaceToBatchNDOptions"),
618 TFLITE_NO_INDICES,
619 ),
620 BuiltinOperator.TRANSPOSE: (Op.Transpose, OptionsSerializer("TransposeOptions"), TFLITE_NO_INDICES),
621 BuiltinOperator.MEAN: (Op.Mean, reducer_opts, TFLITE_IFM_INDICES),
622 BuiltinOperator.SUB: (
623 Op.Sub,
624 OptionsSerializer("SubOptions", (fused_act, "pot_scale_int16",)),
625 TFLITE_IFM_IFM2_INDICES,
626 ),
627 BuiltinOperator.DIV: (Op.Div, OptionsSerializer("DivOptions", (fused_act,)), TFLITE_NO_INDICES),
628 BuiltinOperator.SQUEEZE: (
629 Op.Squeeze,
630 OptionsSerializer("SqueezeOptions", (("squeeze_dims", is_int_vec),)),
631 TFLITE_IFM_INDICES,
632 ),
633 BuiltinOperator.UNIDIRECTIONAL_SEQUENCE_LSTM: (
634 Op.UnidirectionalSequenceLstm,
635 unidir_seq_lstm_opts,
636 TFLITE_IFM_WEIGHTS_INDICES,
637 ),
Tim Hall79d07d22020-04-27 18:20:16 +0100638 BuiltinOperator.STRIDED_SLICE: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200639 Op.StridedSlice,
Tim Hall79d07d22020-04-27 18:20:16 +0100640 OptionsSerializer(
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200641 "StridedSliceOptions", ("begin_mask", "end_mask", "ellipsis_mask", "new_axis_mask", "shrink_axis_mask"),
Tim Hall79d07d22020-04-27 18:20:16 +0100642 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200643 TFLITE_IFM_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100644 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200645 BuiltinOperator.BIDIRECTIONAL_SEQUENCE_RNN: (
646 Op.BidirectionalSequenceRnn,
647 bidir_seq_rnn_opts,
648 TFLITE_IFM_WEIGHTS_INDICES,
649 ),
650 BuiltinOperator.EXP: (Op.Exp, OptionsSerializer("ExpOptions"), TFLITE_IFM_INDICES),
651 BuiltinOperator.TOPK_V2: (Op.TopKV2, OptionsSerializer("TopKV2Options"), TFLITE_NO_INDICES),
652 BuiltinOperator.SPLIT: (Op.Split, OptionsSerializer("SplitOptions", ("num_splits",)), TFLITE_SPLIT_IFM_INDICES),
653 BuiltinOperator.LOG_SOFTMAX: (Op.LogSoftmax, OptionsSerializer("LogSoftmaxOptions"), TFLITE_NO_INDICES),
654 BuiltinOperator.DELEGATE: (Op.Delegate, None, TFLITE_NO_INDICES),
655 BuiltinOperator.BIDIRECTIONAL_SEQUENCE_LSTM: (
656 Op.BidirectionalSequenceLstm,
657 bidir_seq_lstm_opts,
658 TFLITE_IFM_WEIGHTS_INDICES,
659 ),
Tim Hall79d07d22020-04-27 18:20:16 +0100660 BuiltinOperator.CAST: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200661 Op.Cast,
Tim Hall79d07d22020-04-27 18:20:16 +0100662 OptionsSerializer(
663 "CastOptions",
664 (
665 ("in_data_type", datatype_deserialize, datatype_serialize),
666 ("out_data_type", datatype_deserialize, datatype_serialize),
667 ),
668 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200669 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100670 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200671 BuiltinOperator.PRELU: (Op.Prelu, None, TFLITE_NO_INDICES),
672 BuiltinOperator.MAXIMUM: (Op.Maximum, OptionsSerializer("MaximumMinimumOptions"), TFLITE_IFM_IFM2_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100673 BuiltinOperator.ARG_MAX: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200674 Op.ArgMax,
Tim Hall79d07d22020-04-27 18:20:16 +0100675 OptionsSerializer("ArgMaxOptions", (("output_type", datatype_deserialize, datatype_serialize),)),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200676 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100677 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200678 BuiltinOperator.MINIMUM: (Op.Minimum, OptionsSerializer("MaximumMinimumOptions"), TFLITE_IFM_IFM2_INDICES),
679 BuiltinOperator.LESS: (Op.Less, OptionsSerializer("LessOptions"), TFLITE_NO_INDICES),
680 BuiltinOperator.NEG: (Op.Neg, OptionsSerializer("NegOptions"), TFLITE_NO_INDICES),
681 BuiltinOperator.PADV2: (Op.PadV2, OptionsSerializer("PadV2Options"), TFLITE_NO_INDICES),
682 BuiltinOperator.GREATER: (Op.Greater, OptionsSerializer("GreaterOptions"), TFLITE_NO_INDICES),
683 BuiltinOperator.GREATER_EQUAL: (Op.GreaterEqual, OptionsSerializer("GreaterEqualOptions"), TFLITE_NO_INDICES),
684 BuiltinOperator.LESS_EQUAL: (Op.LessEqual, OptionsSerializer("LessEqualOptions"), TFLITE_NO_INDICES),
685 BuiltinOperator.SELECT: (Op.Select, OptionsSerializer("SelectOptions"), TFLITE_NO_INDICES),
686 BuiltinOperator.SLICE: (Op.Slice, OptionsSerializer("SliceOptions"), TFLITE_IFM_INDICES),
687 BuiltinOperator.SIN: (Op.Sin, None, TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100688 BuiltinOperator.TRANSPOSE_CONV: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200689 Op.Conv2DBackpropInput,
Tim Hall79d07d22020-04-27 18:20:16 +0100690 OptionsSerializer("TransposeConvOptions", (padding, "stride_w", "stride_h")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200691 TFLITE_CONV2D_BACKPROP_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100692 ),
693 BuiltinOperator.SPARSE_TO_DENSE: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200694 Op.SparseToDense,
Tim Hall79d07d22020-04-27 18:20:16 +0100695 OptionsSerializer("SparseToDenseOptions", ("validate_indices",)),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200696 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100697 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200698 BuiltinOperator.TILE: (Op.Tile, OptionsSerializer("TileOptions"), TFLITE_NO_INDICES),
699 BuiltinOperator.EXPAND_DIMS: (Op.ExpandDims, OptionsSerializer("ExpandDimsOptions"), TFLITE_IFM_INDICES),
700 BuiltinOperator.EQUAL: (Op.Equal, OptionsSerializer("EqualOptions"), TFLITE_NO_INDICES),
701 BuiltinOperator.NOT_EQUAL: (Op.NotEqual, OptionsSerializer("NotEqualOptions"), TFLITE_NO_INDICES),
702 BuiltinOperator.LOG: (Op.Log, None, TFLITE_NO_INDICES),
703 BuiltinOperator.SUM: (Op.Sum, reducer_opts, TFLITE_NO_INDICES),
704 BuiltinOperator.SQRT: (Op.Sqrt, None, TFLITE_NO_INDICES),
705 BuiltinOperator.RSQRT: (Op.Rsqrt, None, TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100706 BuiltinOperator.SHAPE: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200707 Op.Shape,
Tim Hall79d07d22020-04-27 18:20:16 +0100708 OptionsSerializer("ShapeOptions", (("out_type", datatype_deserialize, datatype_serialize),)),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200709 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100710 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200711 BuiltinOperator.POW: (Op.Pow, OptionsSerializer("PowOptions"), TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100712 BuiltinOperator.ARG_MIN: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200713 Op.ArgMin,
Tim Hall79d07d22020-04-27 18:20:16 +0100714 OptionsSerializer("ArgMinOptions", (("output_type", datatype_deserialize, datatype_serialize),)),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200715 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100716 ),
717 BuiltinOperator.FAKE_QUANT: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200718 Op.FakeQuantWithMinMaxArgs,
Tim Hall79d07d22020-04-27 18:20:16 +0100719 OptionsSerializer("FakeQuantOptions", ("min", "max", "num_bits", "narrow_range")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200720 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100721 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200722 BuiltinOperator.REDUCE_PROD: (Op.Prod, reducer_opts, TFLITE_NO_INDICES),
723 BuiltinOperator.REDUCE_MAX: (Op.Max, reducer_opts, TFLITE_NO_INDICES),
724 BuiltinOperator.PACK: (Op.Pack, OptionsSerializer("PackOptions", ("values_count", "axis")), TFLITE_IFM_INDICES),
725 BuiltinOperator.LOGICAL_OR: (Op.LogicalOr, OptionsSerializer("LogicalOrOptions"), TFLITE_NO_INDICES),
726 BuiltinOperator.ONE_HOT: (Op.OneHot, OptionsSerializer("OneHotOptions", ("axis",)), TFLITE_NO_INDICES),
727 BuiltinOperator.LOGICAL_AND: (Op.LogicalAnd, OptionsSerializer("LogicalAndOptions"), TFLITE_NO_INDICES),
728 BuiltinOperator.LOGICAL_NOT: (Op.LogicalNot, OptionsSerializer("LogicalNotOptions"), TFLITE_NO_INDICES),
729 BuiltinOperator.UNPACK: (Op.Unpack, OptionsSerializer("UnpackOptions", ("num", "axis")), TFLITE_IFM_INDICES),
730 BuiltinOperator.REDUCE_MIN: (Op.Min, reducer_opts, TFLITE_NO_INDICES),
731 BuiltinOperator.FLOOR_DIV: (Op.FloorDiv, OptionsSerializer("FloorDivOptions"), TFLITE_NO_INDICES),
732 BuiltinOperator.REDUCE_ANY: (Op.Any, reducer_opts, TFLITE_NO_INDICES),
733 BuiltinOperator.SQUARE: (Op.Square, OptionsSerializer("SquareOptions"), TFLITE_NO_INDICES),
734 BuiltinOperator.ZEROS_LIKE: (Op.ZerosLike, OptionsSerializer("ZerosLikeOptions"), TFLITE_NO_INDICES),
735 BuiltinOperator.FILL: (Op.Fill, OptionsSerializer("FillOptions"), TFLITE_NO_INDICES),
736 BuiltinOperator.FLOOR_MOD: (Op.FloorMod, OptionsSerializer("FloorModOptions"), TFLITE_NO_INDICES),
737 BuiltinOperator.RANGE: (Op.Range, OptionsSerializer("RangeOptions"), TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100738 BuiltinOperator.RESIZE_NEAREST_NEIGHBOR: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200739 Op.ResizeNearestNeighbor,
Jacob Bohlin8daf6b72020-09-15 16:28:35 +0200740 OptionsSerializer("ResizeNearestNeighborOptions", ("align_corners", "half_pixel_centers")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200741 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100742 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200743 BuiltinOperator.LEAKY_RELU: (Op.LeakyRelu, OptionsSerializer("LeakyReluOptions", ("alpha",)), TFLITE_IFM_INDICES),
744 BuiltinOperator.SQUARED_DIFFERENCE: (
745 Op.SquaredDifference,
746 OptionsSerializer("SquaredDifferenceOptions"),
747 TFLITE_NO_INDICES,
748 ),
749 BuiltinOperator.MIRROR_PAD: (Op.MirrorPad, OptionsSerializer("MirrorPadOptions", ("mode",)), TFLITE_NO_INDICES),
750 BuiltinOperator.ABS: (Op.Abs, OptionsSerializer("AbsOptions"), TFLITE_IFM_INDICES),
751 BuiltinOperator.SPLIT_V: (Op.SplitV, OptionsSerializer("SplitVOptions", ("num_splits",)), TFLITE_IFM_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100752 BuiltinOperator.UNIQUE: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200753 Op.Unique,
Tim Hall79d07d22020-04-27 18:20:16 +0100754 OptionsSerializer("UniqueOptions", (("idx_out_type", datatype_deserialize, datatype_serialize),)),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200755 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100756 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200757 BuiltinOperator.CEIL: (Op.Ceil, None, TFLITE_NO_INDICES),
758 BuiltinOperator.REVERSE_V2: (Op.ReverseV2, OptionsSerializer("ReverseV2Options"), TFLITE_NO_INDICES),
759 BuiltinOperator.ADD_N: (Op.AddN, OptionsSerializer("AddNOptions"), TFLITE_NO_INDICES),
760 BuiltinOperator.GATHER_ND: (Op.GatherNd, OptionsSerializer("GatherNdOptions"), TFLITE_NO_INDICES),
761 BuiltinOperator.COS: (Op.Cos, OptionsSerializer("CosOptions"), TFLITE_NO_INDICES),
762 BuiltinOperator.WHERE: (Op.Where, OptionsSerializer("WhereOptions"), TFLITE_NO_INDICES),
763 BuiltinOperator.RANK: (Op.Rank, OptionsSerializer("RankOptions"), TFLITE_NO_INDICES),
764 BuiltinOperator.ELU: (Op.Elu, None, TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100765 BuiltinOperator.REVERSE_SEQUENCE: (
Louis Verhaardaee5d752020-09-30 09:01:52 +0200766 Op.ReverseSequence,
Tim Hall79d07d22020-04-27 18:20:16 +0100767 OptionsSerializer("ReverseSequenceOptions", ("seq_dim", "batch_dim")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200768 TFLITE_NO_INDICES,
Tim Hall79d07d22020-04-27 18:20:16 +0100769 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200770 BuiltinOperator.MATRIX_DIAG: (Op.MatrixDiag, OptionsSerializer("MatrixDiagOptions"), TFLITE_NO_INDICES),
771 BuiltinOperator.QUANTIZE: (Op.Quantize, OptionsSerializer("QuantizeOptions"), TFLITE_IFM_INDICES),
772 BuiltinOperator.MATRIX_SET_DIAG: (Op.MatrixSetDiag, OptionsSerializer("MatrixSetDiagOptions"), TFLITE_NO_INDICES),
773 BuiltinOperator.ROUND: (Op.Round, None, TFLITE_NO_INDICES),
774 BuiltinOperator.HARD_SWISH: (Op.HardSwish, OptionsSerializer("HardSwishOptions"), TFLITE_IFM_INDICES),
775 BuiltinOperator.IF: (
776 Op.If,
777 OptionsSerializer("IfOptions", ("then_subgraph_index", "else_subgraph_index")),
778 TFLITE_NO_INDICES,
779 ),
Louis Verhaardaee5d752020-09-30 09:01:52 +0200780 BuiltinOperator.WHILE: (
781 Op.While,
782 OptionsSerializer("WhileOptions", ("cond_subgraph_index", "body_subgraph_index")),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200783 TFLITE_NO_INDICES,
Louis Verhaardaee5d752020-09-30 09:01:52 +0200784 ),
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200785 BuiltinOperator.NON_MAX_SUPPRESSION_V4: (
786 Op.NonMaxSuppressionV4,
787 OptionsSerializer("NonMaxSuppressionV4Options"),
788 TFLITE_NO_INDICES,
789 ),
790 BuiltinOperator.NON_MAX_SUPPRESSION_V5: (
791 Op.NonMaxSuppressionV5,
792 OptionsSerializer("NonMaxSuppressionV5Options"),
793 TFLITE_NO_INDICES,
794 ),
795 BuiltinOperator.SCATTER_ND: (Op.ScatterNd, OptionsSerializer("ScatterNdOptions"), TFLITE_NO_INDICES),
796 BuiltinOperator.SELECT_V2: (Op.SelectV2, OptionsSerializer("SelectV2Options"), TFLITE_NO_INDICES),
797 BuiltinOperator.DENSIFY: (Op.Densify, OptionsSerializer("DensifyOptions"), TFLITE_NO_INDICES),
798 BuiltinOperator.SEGMENT_SUM: (Op.SegmentSum, OptionsSerializer("SegmentSumOptions"), TFLITE_NO_INDICES),
799 BuiltinOperator.BATCH_MATMUL: (
800 Op.BatchMatMul,
801 OptionsSerializer("BatchMatMulOptions", ("adj_x", "adj_y")),
802 TFLITE_NO_INDICES,
803 ),
804 BuiltinOperator.CUMSUM: (
805 Op.Cumsum,
806 OptionsSerializer("CumsumOptions", ("exclusive", "reverse")),
807 TFLITE_NO_INDICES,
808 ),
809 BuiltinOperator.CUSTOM: (Op.Custom, CustomOptionsSerializer(), TFLITE_NO_INDICES),
Tim Hall79d07d22020-04-27 18:20:16 +0100810}
811
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200812builtin_operator_inv_map = {v[0]: (k, v[1], v[2]) for k, v in builtin_operator_map.items()}
Tim Hall79d07d22020-04-27 18:20:16 +0100813
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200814builtin_operator_inv_map[Op.CustomNpuOp] = (BuiltinOperator.CUSTOM, CustomOptionsSerializer(), TFLITE_NO_INDICES)
Michael McGeagh219ec072020-11-09 11:11:26 +0000815
Michael McGeagh837dc1b2020-11-10 12:38:25 +0000816BUILTIN_OPERATOR_UNKNOWN = "UNKNOWN"
817
818
819def builtin_type_name(builtin):
820 return next(k for k, v in vars(BuiltinOperator).items() if v == builtin)
821
Michael McGeagh219ec072020-11-09 11:11:26 +0000822
823def optype_to_builtintype(op_type):
824 if op_type in builtin_operator_inv_map:
Michael McGeagh837dc1b2020-11-10 12:38:25 +0000825 return builtin_type_name(builtin_operator_inv_map[op_type][0])
Michael McGeagh219ec072020-11-09 11:11:26 +0000826 else:
Michael McGeagh837dc1b2020-11-10 12:38:25 +0000827 return BUILTIN_OPERATOR_UNKNOWN