blob: 722a973f08725d2447f0ca79ddcdb8fad23cb55a [file] [log] [blame]
Jerry Ge1eb85042023-01-06 14:19:14 -08001# Copyright (c) 2020-2023, ARM Limited.
Kevin Chengfea5a372021-10-11 18:38:47 +00002#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Kevin Chengfea5a372021-10-11 18:38:47 +000015import os
James Wardc15f7d52022-12-07 15:38:01 +000016import struct
17import serializer.tosa_serializer as ts
Kevin Chengfea5a372021-10-11 18:38:47 +000018import json
19import flatbuffers
20import numpy as np
Jeremy Johnson9b225172021-12-14 16:34:47 +000021from enum import IntEnum, unique
Kevin Chengfea5a372021-10-11 18:38:47 +000022from tosa import (
23 TosaGraph,
Jerry Ge1eb85042023-01-06 14:19:14 -080024 TosaRegion,
Kevin Chengfea5a372021-10-11 18:38:47 +000025 TosaBasicBlock,
26 TosaTensor,
27 TosaOperator,
Kevin Chengfea5a372021-10-11 18:38:47 +000028 Version,
29)
Jeremy Johnson9b225172021-12-14 16:34:47 +000030import tosa.DType as TosaDType
31import tosa.Op as TosaOp
Kevin Chengfea5a372021-10-11 18:38:47 +000032
Kevin Chenge6563f52021-10-20 12:12:02 -070033# Keep version number in sync with the version default value with schema/tosa.fbs
Kevin Chengb97cb1d2021-10-14 11:53:39 -070034TOSA_VERSION_MAJOR = 0
Eric Kunze8a270432023-06-01 20:08:17 +000035TOSA_VERSION_MINOR = 80
Kevin Chengb97cb1d2021-10-14 11:53:39 -070036TOSA_VERSION_PATCH = 0
Eric Kunze2d333852023-09-12 17:04:55 -070037TOSA_VERSION_DRAFT = False
Jeremy Johnson9b225172021-12-14 16:34:47 +000038TOSA_VERSION = [
39 TOSA_VERSION_MAJOR,
40 TOSA_VERSION_MINOR,
41 TOSA_VERSION_PATCH,
42 TOSA_VERSION_DRAFT,
43]
Eric Kunzee6596402022-06-09 21:27:36 +000044
45# File identifier needs to be kept in sync with schema/tosa.fbs
46TOSA_GRAPH_IDENTIFIER = b"\x54\x4F\x53\x41"
47
Kevin Chengfea5a372021-10-11 18:38:47 +000048# With the way flatc generates its python types, there is no programatic way
49# to get string names for the integer types. Manually maintain a string table
50# here.
Jeremy Johnson9b225172021-12-14 16:34:47 +000051DType = TosaDType.DType()
Kevin Chengfea5a372021-10-11 18:38:47 +000052DTypeNames = [
53 "UNKNOWN",
54 "BOOL",
55 "UINT8",
56 "INT4",
57 "INT8",
58 "INT16",
59 "INT32",
60 "INT48",
Jeremy Johnsone1072a92022-09-27 12:44:11 +010061 "FP32",
Jeremy Johnson41027732022-05-25 17:52:29 +010062 "UINT16",
James Ward485a11d2022-08-05 13:48:37 +010063 "FP16",
James Ward34a62792022-10-18 17:27:40 +010064 "BF16",
Won Jeon1adc5d02023-08-12 11:16:05 -070065 "SHAPE",
Kevin Chengfea5a372021-10-11 18:38:47 +000066]
67
68ByteMask = np.uint64(0xFF)
69
70
71def dtype_str_to_val(name):
72
73 for i in range(len(DTypeNames)):
74 if name.casefold() == DTypeNames[i].casefold():
75 return i
76 raise Exception("Unable to parse DType name {}".format(name))
77
78
79class TosaSerializerUnion:
80 """This class handles encapsulating and serializing union types into flatbuffers"""
81
82 def __init__(self):
83
Jeremy Johnson9b225172021-12-14 16:34:47 +000084 # A tuple of the start and end functions.
85 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000086 self.optFcns = None
87
Jeremy Johnson9b225172021-12-14 16:34:47 +000088 # The type from the tosa.Options enumeration.
89 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000090 self.utype = None
91
92 # Each of these lists is a tuple of the add function and the
93 # value being added. Set by the options constructors below.
94 self.ints = []
95 self.bools = []
96 self.floats = []
97 self.strings = []
TatWai Chong49b1ca62022-06-10 01:49:13 -070098 self.int16vecs = []
Kevin Chengfea5a372021-10-11 18:38:47 +000099 self.intvecs = []
100 self.fpvecs = []
101
102 def serialize(self, builder):
103
104 # We have to build strings and vectors first
105 strList = []
106 intVecList = []
107 fpVecList = []
108
109 for fcn, val in self.strings:
110 strList.append((fcn, builder.CreateString(val)))
111
112 for fcn, val in self.intvecs:
113 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
114
TatWai Chong49b1ca62022-06-10 01:49:13 -0700115 for fcn, val in self.int16vecs:
116 intVecList.append((fcn, TosaSerializer.serializeInt16Vec(builder, val)))
117
Kevin Chengfea5a372021-10-11 18:38:47 +0000118 for fcn, val in self.fpvecs:
119 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
120
121 startFcn, endFcn = self.optFcns
122
123 # Then serialize the options object from the list of primitives and
124 # other serialized values
125 startFcn(builder)
126 for fcn, val in self.ints:
127 fcn(builder, val)
128
129 for fcn, val in self.bools:
130 fcn(builder, val)
131
132 for fcn, val in self.floats:
133 fcn(builder, val)
134
135 for fcn, val in strList:
136 fcn(builder, val)
137
138 for fcn, val in intVecList:
139 fcn(builder, val)
140
141 for fcn, val in fpVecList:
142 fcn(builder, val)
143
144 return endFcn(builder)
145
146
147class TosaSerializerAttribute(TosaSerializerUnion):
148 """This class handles encapsulating all of the enumerated types for attributes"""
149
150 def __init__(self):
151 super().__init__()
152
James Ward485a11d2022-08-05 13:48:37 +0100153 def PoolAttribute(
154 self,
155 kernel,
156 stride,
157 pad,
158 input_zp,
159 output_zp,
160 accum_dtype,
161 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000162 from tosa import PoolAttribute as a, Attribute
163
164 self.utype = Attribute.Attribute().PoolAttribute
165
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800166 self.optFcns = (a.Start, a.End)
TatWai Chong7be71652022-05-10 17:26:20 -0700167 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800168 self.intvecs.append((a.AddKernel, kernel))
169 self.intvecs.append((a.AddStride, stride))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000170 self.ints.append((a.AddInputZp, input_zp))
171 self.ints.append((a.AddOutputZp, output_zp))
James Ward485a11d2022-08-05 13:48:37 +0100172 self.ints.append((a.AddAccumDtype, accum_dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000173
James Wardea00fd02023-01-20 16:03:50 +0000174 def ConvAttribute(self, pad, stride, dilation, input_zp, weight_zp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000175 from tosa import ConvAttribute as a, Attribute
176
177 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800178 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000179
TatWai Chong7be71652022-05-10 17:26:20 -0700180 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800181 self.intvecs.append((a.AddStride, stride))
182 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000183 self.ints.append((a.AddInputZp, input_zp))
184 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000185
James Wardea00fd02023-01-20 16:03:50 +0000186 def TransposeConvAttribute(self, outpad, stride, output_shape, input_zp, weight_zp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000187 from tosa import TransposeConvAttribute as a, Attribute
188
189 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800190 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000191
Eric Kunze4c3537d2022-06-13 17:21:48 -0700192 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800193 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800194 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000195 self.ints.append((a.AddInputZp, input_zp))
196 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000197
James Wardc15f7d52022-12-07 15:38:01 +0000198 def PadAttribute(self, serializer_builder, padding, pad_const_int, pad_const_fp):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700199 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000200
Kevin Cheng38d214c2021-10-15 15:49:19 -0700201 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800202 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000203
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800204 self.intvecs.append((a.AddPadding, padding))
205 self.ints.append((a.AddPadConstInt, pad_const_int))
James Wardc15f7d52022-12-07 15:38:01 +0000206
207 # pad_const_fp attribute serialized as uint8 vector
208 pad_const_float_as_bytes = struct.pack("<f", pad_const_fp)
209 serialized_pad_const_fp = ts.TosaSerializer.serializeUint8Vec(
210 serializer_builder, pad_const_float_as_bytes
211 )
212
213 self.floats.append((a.AddPadConstFp, serialized_pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000214
215 def AxisAttribute(self, axis):
216 from tosa import AxisAttribute as a, Attribute
217
218 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800219 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000220
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800221 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000222
TatWai Chong7be71652022-05-10 17:26:20 -0700223 def ReshapeAttribute(self, new_shape):
Kevin Chengfea5a372021-10-11 18:38:47 +0000224 from tosa import ReshapeAttribute as a, Attribute
225
226 self.utype = Attribute.Attribute().ReshapeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800227 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000228
TatWai Chong7be71652022-05-10 17:26:20 -0700229 self.intvecs.append((a.AddNewShape, new_shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000230
TatWai Chong7be71652022-05-10 17:26:20 -0700231 def SliceAttribute(self, start, size):
Kevin Chengfea5a372021-10-11 18:38:47 +0000232 from tosa import SliceAttribute as a, Attribute
233
234 self.utype = Attribute.Attribute().SliceAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800235 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000236
TatWai Chong7be71652022-05-10 17:26:20 -0700237 self.intvecs.append((a.AddStart, start))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800238 self.intvecs.append((a.AddSize, size))
Kevin Chengfea5a372021-10-11 18:38:47 +0000239
240 def TileAttribute(self, multiples):
241 from tosa import TileAttribute as a, Attribute
242
243 self.utype = Attribute.Attribute().TileAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800244 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000245
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800246 self.intvecs.append((a.AddMultiples, multiples))
Kevin Chengfea5a372021-10-11 18:38:47 +0000247
TatWai Chong49b1ca62022-06-10 01:49:13 -0700248 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000249 from tosa import ResizeAttribute as a, Attribute
250
251 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800252 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000253
TatWai Chong49b1ca62022-06-10 01:49:13 -0700254 self.int16vecs.append((a.AddScale, scale))
255 self.int16vecs.append((a.AddOffset, offset))
256 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800257 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000258
James Wardc15f7d52022-12-07 15:38:01 +0000259 def ClampAttribute(self, serializer_builder, minint, maxint, minfp, maxfp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000260 from tosa import ClampAttribute as a, Attribute
261
262 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800263 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000264
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800265 self.ints.append((a.AddMinInt, minint))
266 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000267
James Wardc15f7d52022-12-07 15:38:01 +0000268 # min/max float attributes serialized as uint8 vectors
269 minfp_bytes = struct.pack("<f", minfp)
270 maxfp_bytes = struct.pack("<f", maxfp)
271 serialized_minfp_bytes = ts.TosaSerializer.serializeUint8Vec(
272 serializer_builder, minfp_bytes
273 )
274 serialized_maxfp_bytes = ts.TosaSerializer.serializeUint8Vec(
275 serializer_builder, maxfp_bytes
276 )
277
278 self.floats.append((a.AddMinFp, serialized_minfp_bytes))
279 self.floats.append((a.AddMaxFp, serialized_maxfp_bytes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000280
281 def RescaleAttribute(
282 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
283 ):
284 from tosa import RescaleAttribute as a, Attribute
285
286 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800287 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000288
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800289 self.ints.append((a.AddInputZp, input_zp))
290 self.ints.append((a.AddOutputZp, output_zp))
291 self.intvecs.append((a.AddMultiplier, multiplier))
292 self.intvecs.append((a.AddShift, shift))
293 self.bools.append((a.AddScale32, scale32))
294 self.bools.append((a.AddDoubleRound, double_round))
295 self.bools.append((a.AddPerChannel, per_channel))
Kevin Chengfea5a372021-10-11 18:38:47 +0000296
297 def MulAttribute(self, shift):
298 from tosa import MulAttribute as a, Attribute
299
300 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800301 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000302
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800303 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000304
305 def ArithmeticRightShiftAttribute(self, round):
306 from tosa import ArithmeticRightShiftAttribute as a, Attribute
307
308 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
309 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800310 a.Start,
311 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000312 )
313
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800314 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000315
Kevin Chengfea5a372021-10-11 18:38:47 +0000316 def CondIfAttribute(self, then_branch, else_branch):
317 from tosa import CondIfAttribute as a, Attribute
318
319 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800320 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000321
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800322 self.strings.append((a.AddThenBranch, then_branch))
323 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000324
325 def WhileLoopAttribute(self, cond_branch, body_branch):
326 from tosa import WhileLoopAttribute as a, Attribute
327
328 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800329 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000330
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800331 self.strings.append((a.AddCondBranch, cond_branch))
332 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000333
TatWai Chong7be71652022-05-10 17:26:20 -0700334 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700335 from tosa import TransposeAttribute as a, Attribute
336
337 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800338 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700339
TatWai Chong7be71652022-05-10 17:26:20 -0700340 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700341
342 def TableAttribute(self, table):
343 from tosa import TableAttribute as a, Attribute
344
345 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800346 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700347
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800348 self.intvecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000349
James Wardea00fd02023-01-20 16:03:50 +0000350 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000351 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000352
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000353 self.utype = Attribute.Attribute().MatMulAttribute
354 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000355
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000356 self.ints.append((a.AddAZp, A_zp))
357 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000358
James Wardea00fd02023-01-20 16:03:50 +0000359 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000360 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000361
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000362 self.utype = Attribute.Attribute().FullyConnectedAttribute
363 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000364
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000365 self.ints.append((a.AddInputZp, input_zp))
366 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000367
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000368 def NegateAttribute(self, input1_zp, output_zp):
369 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000370
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000371 self.utype = Attribute.Attribute().NegateAttribute
372 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000373
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000374 self.ints.append((a.AddInput1Zp, input1_zp))
375 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000376
Luke Hutton5e268092023-01-12 22:20:53 +0000377 def FFTAttribute(self, inverse):
378 from tosa import FFTAttribute as a, Attribute
379
380 self.utype = Attribute.Attribute().FFTAttribute
381 self.optFcns = (a.Start, a.End)
382
383 self.bools.append((a.AddInverse, inverse))
384
Kevin Chengfea5a372021-10-11 18:38:47 +0000385
386class TosaSerializerTensor:
387 def __init__(
388 self,
389 name,
390 shape,
391 dtype,
392 data=None,
393 placeholderFilename=None,
394 ):
395 self.name = name
396
397 if isinstance(shape, np.ndarray):
398 shape = shape.astype(int).tolist()
399 shape = list(map(int, shape))
400
401 self.shape = shape
402 self.dtype = dtype
403
James Ward34a62792022-10-18 17:27:40 +0100404 if dtype == DType.FP32 or dtype == DType.BF16:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100405 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100406 elif dtype == DType.FP16:
407 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100408 else:
409 fntype = int
410
Kevin Chengfea5a372021-10-11 18:38:47 +0000411 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100412 data = data.flatten().astype(fntype).tolist()
413 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000414 self.data = data
415 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100416 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000417 self.data = data
418 else:
419 self.data = None
420
421 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000422 # process and are written to disk, but are considered input tensors by the
423 # network so they do not appear in the TOSA serialiazation. However, if we
424 # want to form a unit test around these input tensors, we can get the filename
425 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000426 self.placeholderFilename = placeholderFilename
427
428 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800429 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000430 self.name,
431 self.shape,
432 DTypeNames[self.dtype],
433 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800434 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000435
436 def setDtype(self, dtype):
437 self.dtype = dtype
438
439 def serialize(self, builder):
440 fb_name = builder.CreateString(self.name)
441 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
442 if self.data:
443 u8_data = list()
444 # little endianess
445 if self.dtype == DType.BOOL:
446 for val in self.data:
447 val_u8 = np.uint8(val)
448 u8_data.append(val_u8)
449 elif self.dtype == DType.INT4:
450 in_size = len(self.data)
451 out_size = (in_size + 1) // 2
452 for i in range(out_size):
453 val_0 = self.data[2 * i]
454 if (2 * i + 1) < in_size:
455 val_1 = self.data[2 * i + 1]
456 else:
457 val_1 = 0
458 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
459 val_u8 = np.uint8(val_i8)
460 u8_data.append(val_u8)
461 elif self.dtype == DType.INT8:
462 for val in self.data:
463 val_u8 = np.uint8(val)
464 u8_data.append(val_u8)
465 elif self.dtype == DType.INT16:
466 for val in self.data:
467 val_u16 = np.uint16(val)
468 b0 = val_u16 & ByteMask
469 b1 = (val_u16 >> np.uint16(8)) & ByteMask
470 u8_data.extend([b0, b1])
471 elif self.dtype == DType.INT32:
472 for val in self.data:
473 val_u32 = np.uint32(val)
474 b0 = val_u32 & ByteMask
475 b1 = (val_u32 >> np.uint32(8)) & ByteMask
476 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700477 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000478 u8_data.extend([b0, b1, b2, b3])
Won Jeon1adc5d02023-08-12 11:16:05 -0700479 elif self.dtype == DType.INT48 or self.dtype == DType.SHAPE:
Kevin Chengfea5a372021-10-11 18:38:47 +0000480 for val in self.data:
481 val_u64 = np.uint64(val)
482 b0 = val_u64 & ByteMask
483 b1 = (val_u64 >> np.uint64(8)) & ByteMask
484 b2 = (val_u64 >> np.uint64(16)) & ByteMask
485 b3 = (val_u64 >> np.uint64(24)) & ByteMask
486 b4 = (val_u64 >> np.uint64(32)) & ByteMask
487 b5 = (val_u64 >> np.uint64(40)) & ByteMask
488 u8_data.extend([b0, b1, b2, b3, b4, b5])
James Ward485a11d2022-08-05 13:48:37 +0100489 elif self.dtype == DType.FP16:
490 np_arr = np.array(self.data, dtype=np.float16)
491 u8_data.extend(np_arr.view(np.uint8))
James Ward34a62792022-10-18 17:27:40 +0100492 elif self.dtype == DType.FP32 or self.dtype == DType.BF16:
James Wardc15f7d52022-12-07 15:38:01 +0000493 # for val in self.data:
494 # b = struct.pack("!f", val)
495 # u8_data.extend([b[3], b[2], b[1], b[0]])
496 np_arr = np.array(self.data, dtype=np.float32)
497 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100498 elif self.dtype == TosaDType.DType:
499 # Serialize DType enum data as uint8 bytes
500 for val in self.data:
501 np_arr = np.array(self.data, dtype=np.uint32)
502 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000503 else:
504 raise Exception(
505 "unsupported data type {}".format(DTypeNames[self.dtype])
506 )
507 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
508
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800509 TosaTensor.Start(builder)
510 TosaTensor.AddName(builder, fb_name)
511 TosaTensor.AddShape(builder, fb_shapes)
512 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000513 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800514 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000515
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800516 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000517
518
519class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000520 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000521 self.op = op
522 self.attributes = attributes
523 self.inputs = TosaSerializer.toList(inputs)
524 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000525
526 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800527 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000528
529 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800530 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000531 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800532 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000533
Jerry Ge1eb85042023-01-06 14:19:14 -0800534 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000535
536 def serialize(self, builder):
537 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800538 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000539 )
540 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800541 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000542 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000543 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000544 if self.attributes is not None:
545 fb_attributes = self.attributes.serialize(builder)
546
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800547 TosaOperator.Start(builder)
548 TosaOperator.AddOp(builder, self.op)
549 TosaOperator.AddInputs(builder, fb_inputs)
550 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000551 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800552 TosaOperator.AddAttributeType(builder, self.attributes.utype)
553 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000554
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800555 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000556
557
558class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000559 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000560 self.name = name
561 self.operators = []
562
563 # Dict assures uniqueness, but allows us to look up by name
564 self.tensors = dict()
565
566 self.inputs = []
567 self.outputs = []
568
569 def addTensor(
570 self,
571 name,
572 shape,
573 dtype,
574 data=None,
575 placeholderFilename=None,
576 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000577 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000578 self.tensors[name] = TosaSerializerTensor(
579 name, shape, dtype, data, placeholderFilename
580 )
581
582 return self.tensors[name]
583
584 def addInput(self, name):
585 self.inputs.append(name)
586
587 def addOutput(self, name):
588 self.outputs.append(name)
589
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000590 def addOperator(self, op, inputs, outputs, attributes=None):
591 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000592
593 def serialize(self, builder):
594 fb_name = builder.CreateString(self.name)
595 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800596 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000597 )
598 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800599 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000600 )
601 fbv_tensors = TosaSerializer.serializeObjVec(
602 builder,
603 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800604 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000605 )
606 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800607 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000608 )
609
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800610 TosaBasicBlock.Start(builder)
611 TosaBasicBlock.AddName(builder, fb_name)
612 TosaBasicBlock.AddInputs(builder, fbv_inputs)
613 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
614 TosaBasicBlock.AddTensors(builder, fbv_tensors)
615 TosaBasicBlock.AddOperators(builder, fbv_operators)
616 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000617
618
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100619# How CONSTs are treated in the flatbuffer
620@unique
621class ConstMode(IntEnum):
622 EMBED = 0
623 EMBED_DUMP = 1
624 INPUTS = 2
625
626
Jerry Ge1eb85042023-01-06 14:19:14 -0800627class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100628 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800629 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000630 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000631 self.currInputIdx = 0
632 self.currConstIdx = 0
633 self.currLayerIdx = 1
634 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800635 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100636 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000637
Jerry Geca7ce0e2023-01-10 17:24:38 +0000638 def addBasicBlock(self, name):
639 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800640 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000641
Jerry Ge1eb85042023-01-06 14:19:14 -0800642 def serialize(self, builder):
643 fb_name = builder.CreateString(self.name)
644 fbv_basicBlocks = TosaSerializer.serializeObjVec(
645 builder, self.basicBlocks, TosaRegion.StartBlocksVector
646 )
647
648 TosaRegion.Start(builder)
649 TosaRegion.AddName(builder, fb_name)
650 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
651 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000652
653 def addPlaceholder(self, shape, dtype, vals):
654 if not self.currBasicBlock:
655 raise Exception("addTensor called without valid basic block")
656
657 name = "input-{}".format(self.currInputIdx)
658 filename = "{}.npy".format(name)
659 self.currInputIdx = self.currInputIdx + 1
660
661 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
662 # This is always an input to the block
663 self.currBasicBlock.addInput(name)
664
665 if vals is not None:
666 np.save(os.path.join(self.pathPrefix, filename), vals, False)
667
668 return tens
669
Jerry Ge53ceb482023-08-14 20:15:10 +0000670 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000671 if not self.currBasicBlock:
672 raise Exception("addTensor called without valid basic block")
673
Jerry Ge53ceb482023-08-14 20:15:10 +0000674 if name is None:
675 name = "const-{}".format(self.currInputIdx)
676 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000677
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100678 if self.constMode == ConstMode.INPUTS:
679 # Save const as input file
680 filename = "{}.npy".format(name)
681 tensor_vals = None
682 self.currBasicBlock.addInput(name)
683 else:
684 # Embed const in flatbuffer
685 filename = None
686 tensor_vals = vals
687
688 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000689 # Add the operator now
Jeremy Johnson9b225172021-12-14 16:34:47 +0000690 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000691
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100692 # Save the const data to file for debug or as input files
693 if vals is not None and self.constMode in [
694 ConstMode.EMBED_DUMP,
695 ConstMode.INPUTS,
696 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100697 filename = "{}.npy".format(name)
698 np.save(os.path.join(self.pathPrefix, filename), vals, False)
699
Kevin Chengfea5a372021-10-11 18:38:47 +0000700 return tens
701
702 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000703 if not self.currBasicBlock:
704 raise Exception("addTensor called without valid basic block")
705
706 name = "layer-{}".format(self.currLayerIdx)
707 self.currLayerIdx = self.currLayerIdx + 1
708
709 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
710
711 return tens
712
713 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700714 self.currBasicBlock.addTensor(
715 tensor.name,
716 tensor.shape,
717 tensor.dtype,
718 tensor.data,
719 tensor.placeholderFilename,
720 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000721 self.currBasicBlock.addInput(tensor.name)
722
723 def addOutputTensor(self, tensor):
724 self.currBasicBlock.addOutput(tensor.name)
725
726 def addOutput(self, shape, dtype):
727 if not self.currBasicBlock:
728 raise Exception("addTensor called without valid basic block")
729
730 name = "result-{}".format(self.currResultIdx)
731 self.currResultIdx = self.currResultIdx + 1
732
733 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
734 self.currBasicBlock.addOutput(name)
735 return tens
736
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000737 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000738 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000739 raise Exception("Use addConstTensor() to add CONST ops")
740
741 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000742 op,
743 inputs,
744 outputs,
745 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000746 )
747
Jerry Ge1eb85042023-01-06 14:19:14 -0800748
749@unique
750class TensorDir(IntEnum):
751 PLACEHOLDER = 0
752 CONST = 1
753 INTERMEDIATE = 2
754 RESULT = 3
755
756
757class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100758 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800759 self.builder = flatbuffers.Builder(0)
760
Jerry Ge1eb85042023-01-06 14:19:14 -0800761 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100762 self.constMode = constMode
763
764 self.regions = []
765 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800766
Jerry Geca7ce0e2023-01-10 17:24:38 +0000767 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800768
769 # Is this an illegal test that is expected to fail?
770 self.expectedReturnCode = 0
771 self.expectedFailure = False
772 self.expectedFailureDesc = ""
773
774 def __str__(self):
775 concatString = ""
776 for region in self.regions:
777 concatString = concatString + str(region)
778 return concatString
779
780 def addPlaceholder(self, shape, dtype, vals):
781 return self.currRegion.addPlaceholder(shape, dtype, vals)
782
Jerry Ge53ceb482023-08-14 20:15:10 +0000783 def addConst(self, shape, dtype, vals, name=None):
784 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800785
786 def addIntermediate(self, shape, dtype):
787 return self.currRegion.addIntermediate(shape, dtype)
788
789 def addInputTensor(self, tensor):
790 self.currRegion.addInputTensor(tensor)
791
792 def addOutputTensor(self, tensor):
793 self.currRegion.addOutputTensor(tensor)
794
795 def addOutput(self, shape, dtype):
796 return self.currRegion.addOutput(shape, dtype)
797
798 def addOperator(self, op, inputs, outputs, attributes=None):
799 return self.currRegion.addOperator(op, inputs, outputs, attributes)
800
Jerry Geca7ce0e2023-01-10 17:24:38 +0000801 def addBasicBlock(self, name):
802 self.currRegion.addBasicBlock(name)
803
Jeremy Johnson9b225172021-12-14 16:34:47 +0000804 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000805
806 self.expectedReturnCode = val
807 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000808 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000809
810 def serialize(self):
811
812 builder = self.builder
813
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800814 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000815 Version.Add_Major(builder, TOSA_VERSION[0])
816 Version.Add_Minor(builder, TOSA_VERSION[1])
817 Version.Add_Patch(builder, TOSA_VERSION[2])
818 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800819 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000820
Jerry Ge1eb85042023-01-06 14:19:14 -0800821 fbv_region = TosaSerializer.serializeObjVec(
822 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000823 )
824
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800825 TosaGraph.Start(builder)
826 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800827 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800828 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000829
Eric Kunzee6596402022-06-09 21:27:36 +0000830 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000831 return self.builder.Output()
832
833 def writeJson(self, tosa_filename):
834 """Write a json test file so that it is fairly easy to pick up the test
835 and generate commands for third party tool"""
836 test_desc = dict()
837
838 test_desc["tosa_file"] = tosa_filename
839 ifm_name = []
840 ifm_file = []
841 ofm_name = []
842 ofm_file = []
843
Jerry Ge1eb85042023-01-06 14:19:14 -0800844 for region in self.regions:
845 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000846 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800847 for i in block.inputs:
848 ifm_name.append(i)
849 ifm_file.append(block.tensors[i].placeholderFilename)
850 for o in block.outputs:
851 ofm_name.append(o)
852 # Make up an OFM filename here. One isn't generated until the
853 # reference tool is run, so any name is a good name
854 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000855
856 test_desc["ifm_name"] = ifm_name
857 test_desc["ifm_file"] = ifm_file
858 test_desc["ofm_name"] = ofm_name
859 test_desc["ofm_file"] = ofm_file
860 test_desc["expected_return_code"] = self.expectedReturnCode
861 test_desc["expected_failure"] = self.expectedFailure
862 if self.expectedFailureDesc:
863 test_desc["expected_failure_desc"] = self.expectedFailureDesc
864
865 return json.dumps(test_desc, indent=" ")
866
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100867 def startRegion(self, name, pathPrefix):
868 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800869 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000870
871 @staticmethod
872 def serializeStrVec(builder, vec, start_fcn):
873 fb_strs = [builder.CreateString(i) for i in vec]
874 start_fcn(builder, len(fb_strs))
875 for s in fb_strs[::-1]:
876 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700877 try:
878 return builder.EndVector()
879 except TypeError:
880 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000881
882 @staticmethod
883 def serializeUint8Vec(builder, vec):
884 builder.StartVector(1, len(vec), 8)
885 for v in vec[::-1]:
886 builder.PrependUint8(v)
887 try:
888 return builder.EndVector()
889 except TypeError:
890 return builder.EndVector(len(vec))
891
892 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700893 def serializeInt16Vec(builder, vec):
894 builder.StartVector(2, len(vec), 4)
895 for v in vec[::-1]:
896 builder.PrependInt16(v)
897 try:
898 return builder.EndVector()
899 except TypeError:
900 return builder.EndVector(len(vec))
901
902 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000903 def serializeInt32Vec(builder, vec):
904 builder.StartVector(4, len(vec), 4)
905 for v in vec[::-1]:
906 builder.PrependInt32(v)
907 try:
908 return builder.EndVector()
909 except TypeError:
910 return builder.EndVector(len(vec))
911
912 @staticmethod
913 def serializeFpVec(builder, vec):
914 builder.StartVector(4, len(vec), 4)
915 for v in vec[::-1]:
916 builder.PrependFloat32(v)
917 try:
918 return builder.EndVector()
919 except TypeError:
920 return builder.EndVector(len(vec))
921
922 @staticmethod
923 def serializeObjVec(builder, vec, start_fcn):
924 serialized_vec = []
925 for v in vec[::-1]:
926 serialized_vec.append(v.serialize(builder))
927
928 start_fcn(builder, len(vec))
929 for v in serialized_vec:
930 builder.PrependUOffsetTRelative(v)
931 try:
932 return builder.EndVector()
933 except TypeError:
934 return builder.EndVector(len(vec))
935
936 @staticmethod
937 def toList(val):
938 if isinstance(val, list):
939 return val
940 else:
941 return [val]