blob: f579df2ce76c2861af7653344b07d76dff99617c [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 Kunze6388a092022-12-07 21:59:31 +000035TOSA_VERSION_MINOR = 51
Kevin Chengb97cb1d2021-10-14 11:53:39 -070036TOSA_VERSION_PATCH = 0
Eric Kunze6388a092022-12-07 21:59:31 +000037TOSA_VERSION_DRAFT = True
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",
Kevin Chengfea5a372021-10-11 18:38:47 +000065]
66
67ByteMask = np.uint64(0xFF)
68
69
70def dtype_str_to_val(name):
71
72 for i in range(len(DTypeNames)):
73 if name.casefold() == DTypeNames[i].casefold():
74 return i
75 raise Exception("Unable to parse DType name {}".format(name))
76
77
78class TosaSerializerUnion:
79 """This class handles encapsulating and serializing union types into flatbuffers"""
80
81 def __init__(self):
82
Jeremy Johnson9b225172021-12-14 16:34:47 +000083 # A tuple of the start and end functions.
84 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000085 self.optFcns = None
86
Jeremy Johnson9b225172021-12-14 16:34:47 +000087 # The type from the tosa.Options enumeration.
88 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000089 self.utype = None
90
91 # Each of these lists is a tuple of the add function and the
92 # value being added. Set by the options constructors below.
93 self.ints = []
94 self.bools = []
95 self.floats = []
96 self.strings = []
TatWai Chong49b1ca62022-06-10 01:49:13 -070097 self.int16vecs = []
Kevin Chengfea5a372021-10-11 18:38:47 +000098 self.intvecs = []
99 self.fpvecs = []
100
101 def serialize(self, builder):
102
103 # We have to build strings and vectors first
104 strList = []
105 intVecList = []
106 fpVecList = []
107
108 for fcn, val in self.strings:
109 strList.append((fcn, builder.CreateString(val)))
110
111 for fcn, val in self.intvecs:
112 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
113
TatWai Chong49b1ca62022-06-10 01:49:13 -0700114 for fcn, val in self.int16vecs:
115 intVecList.append((fcn, TosaSerializer.serializeInt16Vec(builder, val)))
116
Kevin Chengfea5a372021-10-11 18:38:47 +0000117 for fcn, val in self.fpvecs:
118 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
119
120 startFcn, endFcn = self.optFcns
121
122 # Then serialize the options object from the list of primitives and
123 # other serialized values
124 startFcn(builder)
125 for fcn, val in self.ints:
126 fcn(builder, val)
127
128 for fcn, val in self.bools:
129 fcn(builder, val)
130
131 for fcn, val in self.floats:
132 fcn(builder, val)
133
134 for fcn, val in strList:
135 fcn(builder, val)
136
137 for fcn, val in intVecList:
138 fcn(builder, val)
139
140 for fcn, val in fpVecList:
141 fcn(builder, val)
142
143 return endFcn(builder)
144
145
146class TosaSerializerAttribute(TosaSerializerUnion):
147 """This class handles encapsulating all of the enumerated types for attributes"""
148
149 def __init__(self):
150 super().__init__()
151
James Ward485a11d2022-08-05 13:48:37 +0100152 def PoolAttribute(
153 self,
154 kernel,
155 stride,
156 pad,
157 input_zp,
158 output_zp,
159 accum_dtype,
160 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000161 from tosa import PoolAttribute as a, Attribute
162
163 self.utype = Attribute.Attribute().PoolAttribute
164
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800165 self.optFcns = (a.Start, a.End)
TatWai Chong7be71652022-05-10 17:26:20 -0700166 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800167 self.intvecs.append((a.AddKernel, kernel))
168 self.intvecs.append((a.AddStride, stride))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000169 self.ints.append((a.AddInputZp, input_zp))
170 self.ints.append((a.AddOutputZp, output_zp))
James Ward485a11d2022-08-05 13:48:37 +0100171 self.ints.append((a.AddAccumDtype, accum_dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000172
James Ward485a11d2022-08-05 13:48:37 +0100173 def ConvAttribute(self, pad, stride, dilation, input_zp, weight_zp, accum_dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000174 from tosa import ConvAttribute as a, Attribute
175
176 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800177 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000178
TatWai Chong7be71652022-05-10 17:26:20 -0700179 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800180 self.intvecs.append((a.AddStride, stride))
181 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000182 self.ints.append((a.AddInputZp, input_zp))
183 self.ints.append((a.AddWeightZp, weight_zp))
James Ward485a11d2022-08-05 13:48:37 +0100184 self.ints.append((a.AddAccumDtype, accum_dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000185
James Ward485a11d2022-08-05 13:48:37 +0100186 def TransposeConvAttribute(
187 self, outpad, stride, output_shape, input_zp, weight_zp, accum_dtype
188 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000189 from tosa import TransposeConvAttribute as a, Attribute
190
191 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800192 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000193
Eric Kunze4c3537d2022-06-13 17:21:48 -0700194 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800195 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800196 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000197 self.ints.append((a.AddInputZp, input_zp))
198 self.ints.append((a.AddWeightZp, weight_zp))
James Ward485a11d2022-08-05 13:48:37 +0100199 self.ints.append((a.AddAccumDtype, accum_dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000200
James Wardc15f7d52022-12-07 15:38:01 +0000201 def PadAttribute(self, serializer_builder, padding, pad_const_int, pad_const_fp):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700202 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000203
Kevin Cheng38d214c2021-10-15 15:49:19 -0700204 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800205 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000206
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800207 self.intvecs.append((a.AddPadding, padding))
208 self.ints.append((a.AddPadConstInt, pad_const_int))
James Wardc15f7d52022-12-07 15:38:01 +0000209
210 # pad_const_fp attribute serialized as uint8 vector
211 pad_const_float_as_bytes = struct.pack("<f", pad_const_fp)
212 serialized_pad_const_fp = ts.TosaSerializer.serializeUint8Vec(
213 serializer_builder, pad_const_float_as_bytes
214 )
215
216 self.floats.append((a.AddPadConstFp, serialized_pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000217
218 def AxisAttribute(self, axis):
219 from tosa import AxisAttribute as a, Attribute
220
221 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800222 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000223
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800224 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000225
TatWai Chong7be71652022-05-10 17:26:20 -0700226 def ReshapeAttribute(self, new_shape):
Kevin Chengfea5a372021-10-11 18:38:47 +0000227 from tosa import ReshapeAttribute as a, Attribute
228
229 self.utype = Attribute.Attribute().ReshapeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800230 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000231
TatWai Chong7be71652022-05-10 17:26:20 -0700232 self.intvecs.append((a.AddNewShape, new_shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000233
TatWai Chong7be71652022-05-10 17:26:20 -0700234 def SliceAttribute(self, start, size):
Kevin Chengfea5a372021-10-11 18:38:47 +0000235 from tosa import SliceAttribute as a, Attribute
236
237 self.utype = Attribute.Attribute().SliceAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800238 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000239
TatWai Chong7be71652022-05-10 17:26:20 -0700240 self.intvecs.append((a.AddStart, start))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800241 self.intvecs.append((a.AddSize, size))
Kevin Chengfea5a372021-10-11 18:38:47 +0000242
243 def TileAttribute(self, multiples):
244 from tosa import TileAttribute as a, Attribute
245
246 self.utype = Attribute.Attribute().TileAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800247 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000248
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800249 self.intvecs.append((a.AddMultiples, multiples))
Kevin Chengfea5a372021-10-11 18:38:47 +0000250
TatWai Chong49b1ca62022-06-10 01:49:13 -0700251 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000252 from tosa import ResizeAttribute as a, Attribute
253
254 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800255 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000256
TatWai Chong49b1ca62022-06-10 01:49:13 -0700257 self.int16vecs.append((a.AddScale, scale))
258 self.int16vecs.append((a.AddOffset, offset))
259 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800260 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000261
James Wardc15f7d52022-12-07 15:38:01 +0000262 def ClampAttribute(self, serializer_builder, minint, maxint, minfp, maxfp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000263 from tosa import ClampAttribute as a, Attribute
264
265 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800266 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000267
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800268 self.ints.append((a.AddMinInt, minint))
269 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000270
James Wardc15f7d52022-12-07 15:38:01 +0000271 # min/max float attributes serialized as uint8 vectors
272 minfp_bytes = struct.pack("<f", minfp)
273 maxfp_bytes = struct.pack("<f", maxfp)
274 serialized_minfp_bytes = ts.TosaSerializer.serializeUint8Vec(
275 serializer_builder, minfp_bytes
276 )
277 serialized_maxfp_bytes = ts.TosaSerializer.serializeUint8Vec(
278 serializer_builder, maxfp_bytes
279 )
280
281 self.floats.append((a.AddMinFp, serialized_minfp_bytes))
282 self.floats.append((a.AddMaxFp, serialized_maxfp_bytes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000283
284 def RescaleAttribute(
285 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
286 ):
287 from tosa import RescaleAttribute as a, Attribute
288
289 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800290 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000291
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800292 self.ints.append((a.AddInputZp, input_zp))
293 self.ints.append((a.AddOutputZp, output_zp))
294 self.intvecs.append((a.AddMultiplier, multiplier))
295 self.intvecs.append((a.AddShift, shift))
296 self.bools.append((a.AddScale32, scale32))
297 self.bools.append((a.AddDoubleRound, double_round))
298 self.bools.append((a.AddPerChannel, per_channel))
Kevin Chengfea5a372021-10-11 18:38:47 +0000299
300 def MulAttribute(self, shift):
301 from tosa import MulAttribute as a, Attribute
302
303 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800304 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000305
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800306 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000307
308 def ArithmeticRightShiftAttribute(self, round):
309 from tosa import ArithmeticRightShiftAttribute as a, Attribute
310
311 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
312 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800313 a.Start,
314 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000315 )
316
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800317 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000318
Kevin Chengfea5a372021-10-11 18:38:47 +0000319 def CondIfAttribute(self, then_branch, else_branch):
320 from tosa import CondIfAttribute as a, Attribute
321
322 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800323 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000324
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800325 self.strings.append((a.AddThenBranch, then_branch))
326 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000327
328 def WhileLoopAttribute(self, cond_branch, body_branch):
329 from tosa import WhileLoopAttribute as a, Attribute
330
331 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800332 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000333
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800334 self.strings.append((a.AddCondBranch, cond_branch))
335 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000336
TatWai Chong7be71652022-05-10 17:26:20 -0700337 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700338 from tosa import TransposeAttribute as a, Attribute
339
340 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800341 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700342
TatWai Chong7be71652022-05-10 17:26:20 -0700343 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700344
345 def TableAttribute(self, table):
346 from tosa import TableAttribute as a, Attribute
347
348 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800349 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700350
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800351 self.intvecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000352
James Ward485a11d2022-08-05 13:48:37 +0100353 def MatMulAttribute(self, A_zp, B_zp, accum_dtype):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000354 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000355
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000356 self.utype = Attribute.Attribute().MatMulAttribute
357 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000358
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000359 self.ints.append((a.AddAZp, A_zp))
360 self.ints.append((a.AddBZp, B_zp))
James Ward485a11d2022-08-05 13:48:37 +0100361 self.ints.append((a.AddAccumDtype, accum_dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000362
James Ward485a11d2022-08-05 13:48:37 +0100363 def FullyConnectedAttribute(self, input_zp, weight_zp, accum_dtype):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000364 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000365
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000366 self.utype = Attribute.Attribute().FullyConnectedAttribute
367 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000368
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000369 self.ints.append((a.AddInputZp, input_zp))
370 self.ints.append((a.AddWeightZp, weight_zp))
James Ward485a11d2022-08-05 13:48:37 +0100371 self.ints.append((a.AddAccumDtype, accum_dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000372
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000373 def NegateAttribute(self, input1_zp, output_zp):
374 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000375
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000376 self.utype = Attribute.Attribute().NegateAttribute
377 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000378
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000379 self.ints.append((a.AddInput1Zp, input1_zp))
380 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000381
Luke Hutton5e268092023-01-12 22:20:53 +0000382 def FFTAttribute(self, inverse):
383 from tosa import FFTAttribute as a, Attribute
384
385 self.utype = Attribute.Attribute().FFTAttribute
386 self.optFcns = (a.Start, a.End)
387
388 self.bools.append((a.AddInverse, inverse))
389
Kevin Chengfea5a372021-10-11 18:38:47 +0000390
391class TosaSerializerTensor:
392 def __init__(
393 self,
394 name,
395 shape,
396 dtype,
397 data=None,
398 placeholderFilename=None,
399 ):
400 self.name = name
401
402 if isinstance(shape, np.ndarray):
403 shape = shape.astype(int).tolist()
404 shape = list(map(int, shape))
405
406 self.shape = shape
407 self.dtype = dtype
408
James Ward34a62792022-10-18 17:27:40 +0100409 if dtype == DType.FP32 or dtype == DType.BF16:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100410 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100411 elif dtype == DType.FP16:
412 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100413 else:
414 fntype = int
415
Kevin Chengfea5a372021-10-11 18:38:47 +0000416 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100417 data = data.flatten().astype(fntype).tolist()
418 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000419 self.data = data
420 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100421 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000422 self.data = data
423 else:
424 self.data = None
425
426 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000427 # process and are written to disk, but are considered input tensors by the
428 # network so they do not appear in the TOSA serialiazation. However, if we
429 # want to form a unit test around these input tensors, we can get the filename
430 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000431 self.placeholderFilename = placeholderFilename
432
433 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800434 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000435 self.name,
436 self.shape,
437 DTypeNames[self.dtype],
438 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800439 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000440
441 def setDtype(self, dtype):
442 self.dtype = dtype
443
444 def serialize(self, builder):
445 fb_name = builder.CreateString(self.name)
446 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
447 if self.data:
448 u8_data = list()
449 # little endianess
450 if self.dtype == DType.BOOL:
451 for val in self.data:
452 val_u8 = np.uint8(val)
453 u8_data.append(val_u8)
454 elif self.dtype == DType.INT4:
455 in_size = len(self.data)
456 out_size = (in_size + 1) // 2
457 for i in range(out_size):
458 val_0 = self.data[2 * i]
459 if (2 * i + 1) < in_size:
460 val_1 = self.data[2 * i + 1]
461 else:
462 val_1 = 0
463 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
464 val_u8 = np.uint8(val_i8)
465 u8_data.append(val_u8)
466 elif self.dtype == DType.INT8:
467 for val in self.data:
468 val_u8 = np.uint8(val)
469 u8_data.append(val_u8)
470 elif self.dtype == DType.INT16:
471 for val in self.data:
472 val_u16 = np.uint16(val)
473 b0 = val_u16 & ByteMask
474 b1 = (val_u16 >> np.uint16(8)) & ByteMask
475 u8_data.extend([b0, b1])
476 elif self.dtype == DType.INT32:
477 for val in self.data:
478 val_u32 = np.uint32(val)
479 b0 = val_u32 & ByteMask
480 b1 = (val_u32 >> np.uint32(8)) & ByteMask
481 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700482 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000483 u8_data.extend([b0, b1, b2, b3])
484 elif self.dtype == DType.INT48:
485 for val in self.data:
486 val_u64 = np.uint64(val)
487 b0 = val_u64 & ByteMask
488 b1 = (val_u64 >> np.uint64(8)) & ByteMask
489 b2 = (val_u64 >> np.uint64(16)) & ByteMask
490 b3 = (val_u64 >> np.uint64(24)) & ByteMask
491 b4 = (val_u64 >> np.uint64(32)) & ByteMask
492 b5 = (val_u64 >> np.uint64(40)) & ByteMask
493 u8_data.extend([b0, b1, b2, b3, b4, b5])
James Ward485a11d2022-08-05 13:48:37 +0100494 elif self.dtype == DType.FP16:
495 np_arr = np.array(self.data, dtype=np.float16)
496 u8_data.extend(np_arr.view(np.uint8))
James Ward34a62792022-10-18 17:27:40 +0100497 elif self.dtype == DType.FP32 or self.dtype == DType.BF16:
James Wardc15f7d52022-12-07 15:38:01 +0000498 # for val in self.data:
499 # b = struct.pack("!f", val)
500 # u8_data.extend([b[3], b[2], b[1], b[0]])
501 np_arr = np.array(self.data, dtype=np.float32)
502 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100503 elif self.dtype == TosaDType.DType:
504 # Serialize DType enum data as uint8 bytes
505 for val in self.data:
506 np_arr = np.array(self.data, dtype=np.uint32)
507 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000508 else:
509 raise Exception(
510 "unsupported data type {}".format(DTypeNames[self.dtype])
511 )
512 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
513
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800514 TosaTensor.Start(builder)
515 TosaTensor.AddName(builder, fb_name)
516 TosaTensor.AddShape(builder, fb_shapes)
517 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000518 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800519 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000520
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800521 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000522
523
524class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000525 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000526 self.op = op
527 self.attributes = attributes
528 self.inputs = TosaSerializer.toList(inputs)
529 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000530
531 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800532 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000533
534 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800535 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000536 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800537 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000538
Jerry Ge1eb85042023-01-06 14:19:14 -0800539 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000540
541 def serialize(self, builder):
542 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800543 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000544 )
545 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800546 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000547 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000548 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000549 if self.attributes is not None:
550 fb_attributes = self.attributes.serialize(builder)
551
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800552 TosaOperator.Start(builder)
553 TosaOperator.AddOp(builder, self.op)
554 TosaOperator.AddInputs(builder, fb_inputs)
555 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000556 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800557 TosaOperator.AddAttributeType(builder, self.attributes.utype)
558 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000559
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800560 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000561
562
563class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000564 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000565 self.name = name
566 self.operators = []
567
568 # Dict assures uniqueness, but allows us to look up by name
569 self.tensors = dict()
570
571 self.inputs = []
572 self.outputs = []
573
574 def addTensor(
575 self,
576 name,
577 shape,
578 dtype,
579 data=None,
580 placeholderFilename=None,
581 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000582 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000583 self.tensors[name] = TosaSerializerTensor(
584 name, shape, dtype, data, placeholderFilename
585 )
586
587 return self.tensors[name]
588
589 def addInput(self, name):
590 self.inputs.append(name)
591
592 def addOutput(self, name):
593 self.outputs.append(name)
594
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000595 def addOperator(self, op, inputs, outputs, attributes=None):
596 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000597
598 def serialize(self, builder):
599 fb_name = builder.CreateString(self.name)
600 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800601 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000602 )
603 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800604 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000605 )
606 fbv_tensors = TosaSerializer.serializeObjVec(
607 builder,
608 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800609 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000610 )
611 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800612 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000613 )
614
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800615 TosaBasicBlock.Start(builder)
616 TosaBasicBlock.AddName(builder, fb_name)
617 TosaBasicBlock.AddInputs(builder, fbv_inputs)
618 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
619 TosaBasicBlock.AddTensors(builder, fbv_tensors)
620 TosaBasicBlock.AddOperators(builder, fbv_operators)
621 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000622
623
Jerry Ge1eb85042023-01-06 14:19:14 -0800624class TosaSerializerRegion:
625 def __init__(self, name, pathPrefix, saveConstsToFile=False):
626 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000627 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000628 self.currInputIdx = 0
629 self.currConstIdx = 0
630 self.currLayerIdx = 1
631 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800632 self.pathPrefix = pathPrefix
633 self.saveConstsToFile = saveConstsToFile
Kevin Chengfea5a372021-10-11 18:38:47 +0000634
Jerry Geca7ce0e2023-01-10 17:24:38 +0000635 def addBasicBlock(self, name):
636 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800637 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000638
Jerry Ge1eb85042023-01-06 14:19:14 -0800639 def serialize(self, builder):
640 fb_name = builder.CreateString(self.name)
641 fbv_basicBlocks = TosaSerializer.serializeObjVec(
642 builder, self.basicBlocks, TosaRegion.StartBlocksVector
643 )
644
645 TosaRegion.Start(builder)
646 TosaRegion.AddName(builder, fb_name)
647 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
648 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000649
650 def addPlaceholder(self, shape, dtype, vals):
651 if not self.currBasicBlock:
652 raise Exception("addTensor called without valid basic block")
653
654 name = "input-{}".format(self.currInputIdx)
655 filename = "{}.npy".format(name)
656 self.currInputIdx = self.currInputIdx + 1
657
658 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
659 # This is always an input to the block
660 self.currBasicBlock.addInput(name)
661
662 if vals is not None:
663 np.save(os.path.join(self.pathPrefix, filename), vals, False)
664
665 return tens
666
667 def addConst(self, shape, dtype, vals):
668 if not self.currBasicBlock:
669 raise Exception("addTensor called without valid basic block")
670
671 name = "const-{}".format(self.currInputIdx)
Kevin Chengfea5a372021-10-11 18:38:47 +0000672 self.currInputIdx = self.currInputIdx + 1
673
674 tens = self.currBasicBlock.addTensor(name, shape, dtype, vals)
675 # Add the operator now
Jeremy Johnson9b225172021-12-14 16:34:47 +0000676 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000677
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100678 if self.saveConstsToFile:
679 filename = "{}.npy".format(name)
680 np.save(os.path.join(self.pathPrefix, filename), vals, False)
681
Kevin Chengfea5a372021-10-11 18:38:47 +0000682 return tens
683
684 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000685 if not self.currBasicBlock:
686 raise Exception("addTensor called without valid basic block")
687
688 name = "layer-{}".format(self.currLayerIdx)
689 self.currLayerIdx = self.currLayerIdx + 1
690
691 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
692
693 return tens
694
695 def addInputTensor(self, tensor):
696 self.currBasicBlock.addTensor(tensor.name, tensor.shape, tensor.dtype)
697 self.currBasicBlock.addInput(tensor.name)
698
699 def addOutputTensor(self, tensor):
700 self.currBasicBlock.addOutput(tensor.name)
701
702 def addOutput(self, shape, dtype):
703 if not self.currBasicBlock:
704 raise Exception("addTensor called without valid basic block")
705
706 name = "result-{}".format(self.currResultIdx)
707 self.currResultIdx = self.currResultIdx + 1
708
709 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
710 self.currBasicBlock.addOutput(name)
711 return tens
712
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000713 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000714 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000715 raise Exception("Use addConstTensor() to add CONST ops")
716
717 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000718 op,
719 inputs,
720 outputs,
721 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000722 )
723
Jerry Ge1eb85042023-01-06 14:19:14 -0800724
725@unique
726class TensorDir(IntEnum):
727 PLACEHOLDER = 0
728 CONST = 1
729 INTERMEDIATE = 2
730 RESULT = 3
731
732
733class TosaSerializer:
734 def __init__(self, pathPrefix, saveConstsToFile=False):
Jerry Ge1eb85042023-01-06 14:19:14 -0800735 self.builder = flatbuffers.Builder(0)
736
737 self.regions = []
738 self.startRegion("main", pathPrefix, saveConstsToFile)
739
740 # Enables inspection of constant data outside of graph
741 self.saveConstsToFile = saveConstsToFile
742
Jerry Geca7ce0e2023-01-10 17:24:38 +0000743 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800744
745 # Is this an illegal test that is expected to fail?
746 self.expectedReturnCode = 0
747 self.expectedFailure = False
748 self.expectedFailureDesc = ""
749
750 def __str__(self):
751 concatString = ""
752 for region in self.regions:
753 concatString = concatString + str(region)
754 return concatString
755
756 def addPlaceholder(self, shape, dtype, vals):
757 return self.currRegion.addPlaceholder(shape, dtype, vals)
758
759 def addConst(self, shape, dtype, vals):
760 return self.currRegion.addConst(shape, dtype, vals)
761
762 def addIntermediate(self, shape, dtype):
763 return self.currRegion.addIntermediate(shape, dtype)
764
765 def addInputTensor(self, tensor):
766 self.currRegion.addInputTensor(tensor)
767
768 def addOutputTensor(self, tensor):
769 self.currRegion.addOutputTensor(tensor)
770
771 def addOutput(self, shape, dtype):
772 return self.currRegion.addOutput(shape, dtype)
773
774 def addOperator(self, op, inputs, outputs, attributes=None):
775 return self.currRegion.addOperator(op, inputs, outputs, attributes)
776
Jerry Geca7ce0e2023-01-10 17:24:38 +0000777 def addBasicBlock(self, name):
778 self.currRegion.addBasicBlock(name)
779
Jeremy Johnson9b225172021-12-14 16:34:47 +0000780 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000781
782 self.expectedReturnCode = val
783 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000784 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000785
786 def serialize(self):
787
788 builder = self.builder
789
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800790 Version.Start(builder)
791 Version.Add_major(builder, TOSA_VERSION[0])
792 Version.Add_minor(builder, TOSA_VERSION[1])
793 Version.Add_patch(builder, TOSA_VERSION[2])
794 Version.Add_draft(builder, TOSA_VERSION[3])
795 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000796
Jerry Ge1eb85042023-01-06 14:19:14 -0800797 fbv_region = TosaSerializer.serializeObjVec(
798 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000799 )
800
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800801 TosaGraph.Start(builder)
802 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800803 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800804 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000805
Eric Kunzee6596402022-06-09 21:27:36 +0000806 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000807 return self.builder.Output()
808
809 def writeJson(self, tosa_filename):
810 """Write a json test file so that it is fairly easy to pick up the test
811 and generate commands for third party tool"""
812 test_desc = dict()
813
814 test_desc["tosa_file"] = tosa_filename
815 ifm_name = []
816 ifm_file = []
817 ofm_name = []
818 ofm_file = []
819
Jerry Ge1eb85042023-01-06 14:19:14 -0800820 for region in self.regions:
821 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000822 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800823 for i in block.inputs:
824 ifm_name.append(i)
825 ifm_file.append(block.tensors[i].placeholderFilename)
826 for o in block.outputs:
827 ofm_name.append(o)
828 # Make up an OFM filename here. One isn't generated until the
829 # reference tool is run, so any name is a good name
830 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000831
832 test_desc["ifm_name"] = ifm_name
833 test_desc["ifm_file"] = ifm_file
834 test_desc["ofm_name"] = ofm_name
835 test_desc["ofm_file"] = ofm_file
836 test_desc["expected_return_code"] = self.expectedReturnCode
837 test_desc["expected_failure"] = self.expectedFailure
838 if self.expectedFailureDesc:
839 test_desc["expected_failure_desc"] = self.expectedFailureDesc
840
841 return json.dumps(test_desc, indent=" ")
842
Jerry Ge1eb85042023-01-06 14:19:14 -0800843 def startRegion(self, name, pathPrefix, saveConstsToFile):
844 self.currRegion = TosaSerializerRegion(name, pathPrefix, saveConstsToFile)
845 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000846
847 @staticmethod
848 def serializeStrVec(builder, vec, start_fcn):
849 fb_strs = [builder.CreateString(i) for i in vec]
850 start_fcn(builder, len(fb_strs))
851 for s in fb_strs[::-1]:
852 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700853 try:
854 return builder.EndVector()
855 except TypeError:
856 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000857
858 @staticmethod
859 def serializeUint8Vec(builder, vec):
860 builder.StartVector(1, len(vec), 8)
861 for v in vec[::-1]:
862 builder.PrependUint8(v)
863 try:
864 return builder.EndVector()
865 except TypeError:
866 return builder.EndVector(len(vec))
867
868 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700869 def serializeInt16Vec(builder, vec):
870 builder.StartVector(2, len(vec), 4)
871 for v in vec[::-1]:
872 builder.PrependInt16(v)
873 try:
874 return builder.EndVector()
875 except TypeError:
876 return builder.EndVector(len(vec))
877
878 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000879 def serializeInt32Vec(builder, vec):
880 builder.StartVector(4, len(vec), 4)
881 for v in vec[::-1]:
882 builder.PrependInt32(v)
883 try:
884 return builder.EndVector()
885 except TypeError:
886 return builder.EndVector(len(vec))
887
888 @staticmethod
889 def serializeFpVec(builder, vec):
890 builder.StartVector(4, len(vec), 4)
891 for v in vec[::-1]:
892 builder.PrependFloat32(v)
893 try:
894 return builder.EndVector()
895 except TypeError:
896 return builder.EndVector(len(vec))
897
898 @staticmethod
899 def serializeObjVec(builder, vec, start_fcn):
900 serialized_vec = []
901 for v in vec[::-1]:
902 serialized_vec.append(v.serialize(builder))
903
904 start_fcn(builder, len(vec))
905 for v in serialized_vec:
906 builder.PrependUOffsetTRelative(v)
907 try:
908 return builder.EndVector()
909 except TypeError:
910 return builder.EndVector(len(vec))
911
912 @staticmethod
913 def toList(val):
914 if isinstance(val, list):
915 return val
916 else:
917 return [val]