blob: 922da0b887e44ce4bb5adccedaed700e2ae3dded [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 Kunzedce6ceb2023-03-16 18:44:26 +000035TOSA_VERSION_MINOR = 70
Kevin Chengb97cb1d2021-10-14 11:53:39 -070036TOSA_VERSION_PATCH = 0
Eric Kunze63d45ab2023-05-25 16:18:02 -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",
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 Wardea00fd02023-01-20 16:03:50 +0000173 def ConvAttribute(self, pad, stride, dilation, input_zp, weight_zp):
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))
Kevin Chengfea5a372021-10-11 18:38:47 +0000184
James Wardea00fd02023-01-20 16:03:50 +0000185 def TransposeConvAttribute(self, outpad, stride, output_shape, input_zp, weight_zp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000186 from tosa import TransposeConvAttribute as a, Attribute
187
188 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800189 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000190
Eric Kunze4c3537d2022-06-13 17:21:48 -0700191 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800192 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800193 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000194 self.ints.append((a.AddInputZp, input_zp))
195 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000196
James Wardc15f7d52022-12-07 15:38:01 +0000197 def PadAttribute(self, serializer_builder, padding, pad_const_int, pad_const_fp):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700198 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000199
Kevin Cheng38d214c2021-10-15 15:49:19 -0700200 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800201 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000202
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800203 self.intvecs.append((a.AddPadding, padding))
204 self.ints.append((a.AddPadConstInt, pad_const_int))
James Wardc15f7d52022-12-07 15:38:01 +0000205
206 # pad_const_fp attribute serialized as uint8 vector
207 pad_const_float_as_bytes = struct.pack("<f", pad_const_fp)
208 serialized_pad_const_fp = ts.TosaSerializer.serializeUint8Vec(
209 serializer_builder, pad_const_float_as_bytes
210 )
211
212 self.floats.append((a.AddPadConstFp, serialized_pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000213
214 def AxisAttribute(self, axis):
215 from tosa import AxisAttribute as a, Attribute
216
217 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800218 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000219
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800220 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000221
TatWai Chong7be71652022-05-10 17:26:20 -0700222 def ReshapeAttribute(self, new_shape):
Kevin Chengfea5a372021-10-11 18:38:47 +0000223 from tosa import ReshapeAttribute as a, Attribute
224
225 self.utype = Attribute.Attribute().ReshapeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800226 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000227
TatWai Chong7be71652022-05-10 17:26:20 -0700228 self.intvecs.append((a.AddNewShape, new_shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000229
TatWai Chong7be71652022-05-10 17:26:20 -0700230 def SliceAttribute(self, start, size):
Kevin Chengfea5a372021-10-11 18:38:47 +0000231 from tosa import SliceAttribute as a, Attribute
232
233 self.utype = Attribute.Attribute().SliceAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800234 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000235
TatWai Chong7be71652022-05-10 17:26:20 -0700236 self.intvecs.append((a.AddStart, start))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800237 self.intvecs.append((a.AddSize, size))
Kevin Chengfea5a372021-10-11 18:38:47 +0000238
239 def TileAttribute(self, multiples):
240 from tosa import TileAttribute as a, Attribute
241
242 self.utype = Attribute.Attribute().TileAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800243 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000244
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800245 self.intvecs.append((a.AddMultiples, multiples))
Kevin Chengfea5a372021-10-11 18:38:47 +0000246
TatWai Chong49b1ca62022-06-10 01:49:13 -0700247 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000248 from tosa import ResizeAttribute as a, Attribute
249
250 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800251 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000252
TatWai Chong49b1ca62022-06-10 01:49:13 -0700253 self.int16vecs.append((a.AddScale, scale))
254 self.int16vecs.append((a.AddOffset, offset))
255 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800256 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000257
James Wardc15f7d52022-12-07 15:38:01 +0000258 def ClampAttribute(self, serializer_builder, minint, maxint, minfp, maxfp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000259 from tosa import ClampAttribute as a, Attribute
260
261 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800262 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000263
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800264 self.ints.append((a.AddMinInt, minint))
265 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000266
James Wardc15f7d52022-12-07 15:38:01 +0000267 # min/max float attributes serialized as uint8 vectors
268 minfp_bytes = struct.pack("<f", minfp)
269 maxfp_bytes = struct.pack("<f", maxfp)
270 serialized_minfp_bytes = ts.TosaSerializer.serializeUint8Vec(
271 serializer_builder, minfp_bytes
272 )
273 serialized_maxfp_bytes = ts.TosaSerializer.serializeUint8Vec(
274 serializer_builder, maxfp_bytes
275 )
276
277 self.floats.append((a.AddMinFp, serialized_minfp_bytes))
278 self.floats.append((a.AddMaxFp, serialized_maxfp_bytes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000279
280 def RescaleAttribute(
281 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
282 ):
283 from tosa import RescaleAttribute as a, Attribute
284
285 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800286 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000287
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800288 self.ints.append((a.AddInputZp, input_zp))
289 self.ints.append((a.AddOutputZp, output_zp))
290 self.intvecs.append((a.AddMultiplier, multiplier))
291 self.intvecs.append((a.AddShift, shift))
292 self.bools.append((a.AddScale32, scale32))
293 self.bools.append((a.AddDoubleRound, double_round))
294 self.bools.append((a.AddPerChannel, per_channel))
Kevin Chengfea5a372021-10-11 18:38:47 +0000295
296 def MulAttribute(self, shift):
297 from tosa import MulAttribute as a, Attribute
298
299 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800300 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000301
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800302 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000303
304 def ArithmeticRightShiftAttribute(self, round):
305 from tosa import ArithmeticRightShiftAttribute as a, Attribute
306
307 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
308 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800309 a.Start,
310 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000311 )
312
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800313 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000314
Kevin Chengfea5a372021-10-11 18:38:47 +0000315 def CondIfAttribute(self, then_branch, else_branch):
316 from tosa import CondIfAttribute as a, Attribute
317
318 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800319 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000320
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800321 self.strings.append((a.AddThenBranch, then_branch))
322 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000323
324 def WhileLoopAttribute(self, cond_branch, body_branch):
325 from tosa import WhileLoopAttribute as a, Attribute
326
327 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800328 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000329
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800330 self.strings.append((a.AddCondBranch, cond_branch))
331 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000332
TatWai Chong7be71652022-05-10 17:26:20 -0700333 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700334 from tosa import TransposeAttribute as a, Attribute
335
336 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800337 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700338
TatWai Chong7be71652022-05-10 17:26:20 -0700339 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700340
341 def TableAttribute(self, table):
342 from tosa import TableAttribute as a, Attribute
343
344 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800345 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700346
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800347 self.intvecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000348
James Wardea00fd02023-01-20 16:03:50 +0000349 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000350 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000351
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000352 self.utype = Attribute.Attribute().MatMulAttribute
353 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000354
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000355 self.ints.append((a.AddAZp, A_zp))
356 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000357
James Wardea00fd02023-01-20 16:03:50 +0000358 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000359 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000360
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000361 self.utype = Attribute.Attribute().FullyConnectedAttribute
362 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000363
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000364 self.ints.append((a.AddInputZp, input_zp))
365 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000366
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000367 def NegateAttribute(self, input1_zp, output_zp):
368 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000369
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000370 self.utype = Attribute.Attribute().NegateAttribute
371 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000372
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000373 self.ints.append((a.AddInput1Zp, input1_zp))
374 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000375
Luke Hutton5e268092023-01-12 22:20:53 +0000376 def FFTAttribute(self, inverse):
377 from tosa import FFTAttribute as a, Attribute
378
379 self.utype = Attribute.Attribute().FFTAttribute
380 self.optFcns = (a.Start, a.End)
381
382 self.bools.append((a.AddInverse, inverse))
383
Kevin Chengfea5a372021-10-11 18:38:47 +0000384
385class TosaSerializerTensor:
386 def __init__(
387 self,
388 name,
389 shape,
390 dtype,
391 data=None,
392 placeholderFilename=None,
393 ):
394 self.name = name
395
396 if isinstance(shape, np.ndarray):
397 shape = shape.astype(int).tolist()
398 shape = list(map(int, shape))
399
400 self.shape = shape
401 self.dtype = dtype
402
James Ward34a62792022-10-18 17:27:40 +0100403 if dtype == DType.FP32 or dtype == DType.BF16:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100404 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100405 elif dtype == DType.FP16:
406 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100407 else:
408 fntype = int
409
Kevin Chengfea5a372021-10-11 18:38:47 +0000410 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100411 data = data.flatten().astype(fntype).tolist()
412 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000413 self.data = data
414 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100415 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000416 self.data = data
417 else:
418 self.data = None
419
420 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000421 # process and are written to disk, but are considered input tensors by the
422 # network so they do not appear in the TOSA serialiazation. However, if we
423 # want to form a unit test around these input tensors, we can get the filename
424 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000425 self.placeholderFilename = placeholderFilename
426
427 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800428 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000429 self.name,
430 self.shape,
431 DTypeNames[self.dtype],
432 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800433 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000434
435 def setDtype(self, dtype):
436 self.dtype = dtype
437
438 def serialize(self, builder):
439 fb_name = builder.CreateString(self.name)
440 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
441 if self.data:
442 u8_data = list()
443 # little endianess
444 if self.dtype == DType.BOOL:
445 for val in self.data:
446 val_u8 = np.uint8(val)
447 u8_data.append(val_u8)
448 elif self.dtype == DType.INT4:
449 in_size = len(self.data)
450 out_size = (in_size + 1) // 2
451 for i in range(out_size):
452 val_0 = self.data[2 * i]
453 if (2 * i + 1) < in_size:
454 val_1 = self.data[2 * i + 1]
455 else:
456 val_1 = 0
457 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
458 val_u8 = np.uint8(val_i8)
459 u8_data.append(val_u8)
460 elif self.dtype == DType.INT8:
461 for val in self.data:
462 val_u8 = np.uint8(val)
463 u8_data.append(val_u8)
464 elif self.dtype == DType.INT16:
465 for val in self.data:
466 val_u16 = np.uint16(val)
467 b0 = val_u16 & ByteMask
468 b1 = (val_u16 >> np.uint16(8)) & ByteMask
469 u8_data.extend([b0, b1])
470 elif self.dtype == DType.INT32:
471 for val in self.data:
472 val_u32 = np.uint32(val)
473 b0 = val_u32 & ByteMask
474 b1 = (val_u32 >> np.uint32(8)) & ByteMask
475 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700476 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000477 u8_data.extend([b0, b1, b2, b3])
478 elif self.dtype == DType.INT48:
479 for val in self.data:
480 val_u64 = np.uint64(val)
481 b0 = val_u64 & ByteMask
482 b1 = (val_u64 >> np.uint64(8)) & ByteMask
483 b2 = (val_u64 >> np.uint64(16)) & ByteMask
484 b3 = (val_u64 >> np.uint64(24)) & ByteMask
485 b4 = (val_u64 >> np.uint64(32)) & ByteMask
486 b5 = (val_u64 >> np.uint64(40)) & ByteMask
487 u8_data.extend([b0, b1, b2, b3, b4, b5])
James Ward485a11d2022-08-05 13:48:37 +0100488 elif self.dtype == DType.FP16:
489 np_arr = np.array(self.data, dtype=np.float16)
490 u8_data.extend(np_arr.view(np.uint8))
James Ward34a62792022-10-18 17:27:40 +0100491 elif self.dtype == DType.FP32 or self.dtype == DType.BF16:
James Wardc15f7d52022-12-07 15:38:01 +0000492 # for val in self.data:
493 # b = struct.pack("!f", val)
494 # u8_data.extend([b[3], b[2], b[1], b[0]])
495 np_arr = np.array(self.data, dtype=np.float32)
496 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100497 elif self.dtype == TosaDType.DType:
498 # Serialize DType enum data as uint8 bytes
499 for val in self.data:
500 np_arr = np.array(self.data, dtype=np.uint32)
501 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000502 else:
503 raise Exception(
504 "unsupported data type {}".format(DTypeNames[self.dtype])
505 )
506 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
507
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800508 TosaTensor.Start(builder)
509 TosaTensor.AddName(builder, fb_name)
510 TosaTensor.AddShape(builder, fb_shapes)
511 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000512 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800513 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000514
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800515 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000516
517
518class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000519 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000520 self.op = op
521 self.attributes = attributes
522 self.inputs = TosaSerializer.toList(inputs)
523 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000524
525 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800526 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000527
528 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800529 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000530 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800531 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000532
Jerry Ge1eb85042023-01-06 14:19:14 -0800533 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000534
535 def serialize(self, builder):
536 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800537 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000538 )
539 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800540 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000541 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000542 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000543 if self.attributes is not None:
544 fb_attributes = self.attributes.serialize(builder)
545
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800546 TosaOperator.Start(builder)
547 TosaOperator.AddOp(builder, self.op)
548 TosaOperator.AddInputs(builder, fb_inputs)
549 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000550 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800551 TosaOperator.AddAttributeType(builder, self.attributes.utype)
552 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000553
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800554 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000555
556
557class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000558 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000559 self.name = name
560 self.operators = []
561
562 # Dict assures uniqueness, but allows us to look up by name
563 self.tensors = dict()
564
565 self.inputs = []
566 self.outputs = []
567
568 def addTensor(
569 self,
570 name,
571 shape,
572 dtype,
573 data=None,
574 placeholderFilename=None,
575 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000576 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000577 self.tensors[name] = TosaSerializerTensor(
578 name, shape, dtype, data, placeholderFilename
579 )
580
581 return self.tensors[name]
582
583 def addInput(self, name):
584 self.inputs.append(name)
585
586 def addOutput(self, name):
587 self.outputs.append(name)
588
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000589 def addOperator(self, op, inputs, outputs, attributes=None):
590 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000591
592 def serialize(self, builder):
593 fb_name = builder.CreateString(self.name)
594 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800595 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000596 )
597 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800598 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000599 )
600 fbv_tensors = TosaSerializer.serializeObjVec(
601 builder,
602 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800603 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000604 )
605 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800606 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000607 )
608
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800609 TosaBasicBlock.Start(builder)
610 TosaBasicBlock.AddName(builder, fb_name)
611 TosaBasicBlock.AddInputs(builder, fbv_inputs)
612 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
613 TosaBasicBlock.AddTensors(builder, fbv_tensors)
614 TosaBasicBlock.AddOperators(builder, fbv_operators)
615 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000616
617
Jerry Ge1eb85042023-01-06 14:19:14 -0800618class TosaSerializerRegion:
619 def __init__(self, name, pathPrefix, saveConstsToFile=False):
620 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000621 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000622 self.currInputIdx = 0
623 self.currConstIdx = 0
624 self.currLayerIdx = 1
625 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800626 self.pathPrefix = pathPrefix
627 self.saveConstsToFile = saveConstsToFile
Kevin Chengfea5a372021-10-11 18:38:47 +0000628
Jerry Geca7ce0e2023-01-10 17:24:38 +0000629 def addBasicBlock(self, name):
630 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800631 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000632
Jerry Ge1eb85042023-01-06 14:19:14 -0800633 def serialize(self, builder):
634 fb_name = builder.CreateString(self.name)
635 fbv_basicBlocks = TosaSerializer.serializeObjVec(
636 builder, self.basicBlocks, TosaRegion.StartBlocksVector
637 )
638
639 TosaRegion.Start(builder)
640 TosaRegion.AddName(builder, fb_name)
641 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
642 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000643
644 def addPlaceholder(self, shape, dtype, vals):
645 if not self.currBasicBlock:
646 raise Exception("addTensor called without valid basic block")
647
648 name = "input-{}".format(self.currInputIdx)
649 filename = "{}.npy".format(name)
650 self.currInputIdx = self.currInputIdx + 1
651
652 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
653 # This is always an input to the block
654 self.currBasicBlock.addInput(name)
655
656 if vals is not None:
657 np.save(os.path.join(self.pathPrefix, filename), vals, False)
658
659 return tens
660
661 def addConst(self, shape, dtype, vals):
662 if not self.currBasicBlock:
663 raise Exception("addTensor called without valid basic block")
664
665 name = "const-{}".format(self.currInputIdx)
Kevin Chengfea5a372021-10-11 18:38:47 +0000666 self.currInputIdx = self.currInputIdx + 1
667
668 tens = self.currBasicBlock.addTensor(name, shape, dtype, vals)
669 # Add the operator now
Jeremy Johnson9b225172021-12-14 16:34:47 +0000670 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000671
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100672 if self.saveConstsToFile:
673 filename = "{}.npy".format(name)
674 np.save(os.path.join(self.pathPrefix, filename), vals, False)
675
Kevin Chengfea5a372021-10-11 18:38:47 +0000676 return tens
677
678 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000679 if not self.currBasicBlock:
680 raise Exception("addTensor called without valid basic block")
681
682 name = "layer-{}".format(self.currLayerIdx)
683 self.currLayerIdx = self.currLayerIdx + 1
684
685 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
686
687 return tens
688
689 def addInputTensor(self, tensor):
690 self.currBasicBlock.addTensor(tensor.name, tensor.shape, tensor.dtype)
691 self.currBasicBlock.addInput(tensor.name)
692
693 def addOutputTensor(self, tensor):
694 self.currBasicBlock.addOutput(tensor.name)
695
696 def addOutput(self, shape, dtype):
697 if not self.currBasicBlock:
698 raise Exception("addTensor called without valid basic block")
699
700 name = "result-{}".format(self.currResultIdx)
701 self.currResultIdx = self.currResultIdx + 1
702
703 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
704 self.currBasicBlock.addOutput(name)
705 return tens
706
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000707 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000708 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000709 raise Exception("Use addConstTensor() to add CONST ops")
710
711 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000712 op,
713 inputs,
714 outputs,
715 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000716 )
717
Jerry Ge1eb85042023-01-06 14:19:14 -0800718
719@unique
720class TensorDir(IntEnum):
721 PLACEHOLDER = 0
722 CONST = 1
723 INTERMEDIATE = 2
724 RESULT = 3
725
726
727class TosaSerializer:
728 def __init__(self, pathPrefix, saveConstsToFile=False):
Jerry Ge1eb85042023-01-06 14:19:14 -0800729 self.builder = flatbuffers.Builder(0)
730
731 self.regions = []
732 self.startRegion("main", pathPrefix, saveConstsToFile)
733
734 # Enables inspection of constant data outside of graph
735 self.saveConstsToFile = saveConstsToFile
736
Jerry Geca7ce0e2023-01-10 17:24:38 +0000737 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800738
739 # Is this an illegal test that is expected to fail?
740 self.expectedReturnCode = 0
741 self.expectedFailure = False
742 self.expectedFailureDesc = ""
743
744 def __str__(self):
745 concatString = ""
746 for region in self.regions:
747 concatString = concatString + str(region)
748 return concatString
749
750 def addPlaceholder(self, shape, dtype, vals):
751 return self.currRegion.addPlaceholder(shape, dtype, vals)
752
753 def addConst(self, shape, dtype, vals):
754 return self.currRegion.addConst(shape, dtype, vals)
755
756 def addIntermediate(self, shape, dtype):
757 return self.currRegion.addIntermediate(shape, dtype)
758
759 def addInputTensor(self, tensor):
760 self.currRegion.addInputTensor(tensor)
761
762 def addOutputTensor(self, tensor):
763 self.currRegion.addOutputTensor(tensor)
764
765 def addOutput(self, shape, dtype):
766 return self.currRegion.addOutput(shape, dtype)
767
768 def addOperator(self, op, inputs, outputs, attributes=None):
769 return self.currRegion.addOperator(op, inputs, outputs, attributes)
770
Jerry Geca7ce0e2023-01-10 17:24:38 +0000771 def addBasicBlock(self, name):
772 self.currRegion.addBasicBlock(name)
773
Jeremy Johnson9b225172021-12-14 16:34:47 +0000774 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000775
776 self.expectedReturnCode = val
777 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000778 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000779
780 def serialize(self):
781
782 builder = self.builder
783
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800784 Version.Start(builder)
785 Version.Add_major(builder, TOSA_VERSION[0])
786 Version.Add_minor(builder, TOSA_VERSION[1])
787 Version.Add_patch(builder, TOSA_VERSION[2])
788 Version.Add_draft(builder, TOSA_VERSION[3])
789 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000790
Jerry Ge1eb85042023-01-06 14:19:14 -0800791 fbv_region = TosaSerializer.serializeObjVec(
792 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000793 )
794
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800795 TosaGraph.Start(builder)
796 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800797 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800798 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000799
Eric Kunzee6596402022-06-09 21:27:36 +0000800 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000801 return self.builder.Output()
802
803 def writeJson(self, tosa_filename):
804 """Write a json test file so that it is fairly easy to pick up the test
805 and generate commands for third party tool"""
806 test_desc = dict()
807
808 test_desc["tosa_file"] = tosa_filename
809 ifm_name = []
810 ifm_file = []
811 ofm_name = []
812 ofm_file = []
813
Jerry Ge1eb85042023-01-06 14:19:14 -0800814 for region in self.regions:
815 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000816 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800817 for i in block.inputs:
818 ifm_name.append(i)
819 ifm_file.append(block.tensors[i].placeholderFilename)
820 for o in block.outputs:
821 ofm_name.append(o)
822 # Make up an OFM filename here. One isn't generated until the
823 # reference tool is run, so any name is a good name
824 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000825
826 test_desc["ifm_name"] = ifm_name
827 test_desc["ifm_file"] = ifm_file
828 test_desc["ofm_name"] = ofm_name
829 test_desc["ofm_file"] = ofm_file
830 test_desc["expected_return_code"] = self.expectedReturnCode
831 test_desc["expected_failure"] = self.expectedFailure
832 if self.expectedFailureDesc:
833 test_desc["expected_failure_desc"] = self.expectedFailureDesc
834
835 return json.dumps(test_desc, indent=" ")
836
Jerry Ge1eb85042023-01-06 14:19:14 -0800837 def startRegion(self, name, pathPrefix, saveConstsToFile):
838 self.currRegion = TosaSerializerRegion(name, pathPrefix, saveConstsToFile)
839 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000840
841 @staticmethod
842 def serializeStrVec(builder, vec, start_fcn):
843 fb_strs = [builder.CreateString(i) for i in vec]
844 start_fcn(builder, len(fb_strs))
845 for s in fb_strs[::-1]:
846 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700847 try:
848 return builder.EndVector()
849 except TypeError:
850 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000851
852 @staticmethod
853 def serializeUint8Vec(builder, vec):
854 builder.StartVector(1, len(vec), 8)
855 for v in vec[::-1]:
856 builder.PrependUint8(v)
857 try:
858 return builder.EndVector()
859 except TypeError:
860 return builder.EndVector(len(vec))
861
862 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700863 def serializeInt16Vec(builder, vec):
864 builder.StartVector(2, len(vec), 4)
865 for v in vec[::-1]:
866 builder.PrependInt16(v)
867 try:
868 return builder.EndVector()
869 except TypeError:
870 return builder.EndVector(len(vec))
871
872 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000873 def serializeInt32Vec(builder, vec):
874 builder.StartVector(4, len(vec), 4)
875 for v in vec[::-1]:
876 builder.PrependInt32(v)
877 try:
878 return builder.EndVector()
879 except TypeError:
880 return builder.EndVector(len(vec))
881
882 @staticmethod
883 def serializeFpVec(builder, vec):
884 builder.StartVector(4, len(vec), 4)
885 for v in vec[::-1]:
886 builder.PrependFloat32(v)
887 try:
888 return builder.EndVector()
889 except TypeError:
890 return builder.EndVector(len(vec))
891
892 @staticmethod
893 def serializeObjVec(builder, vec, start_fcn):
894 serialized_vec = []
895 for v in vec[::-1]:
896 serialized_vec.append(v.serialize(builder))
897
898 start_fcn(builder, len(vec))
899 for v in serialized_vec:
900 builder.PrependUOffsetTRelative(v)
901 try:
902 return builder.EndVector()
903 except TypeError:
904 return builder.EndVector(len(vec))
905
906 @staticmethod
907 def toList(val):
908 if isinstance(val, list):
909 return val
910 else:
911 return [val]