blob: 546de7dea1732f38b0e7e0ffa32f7c4000b8f216 [file] [log] [blame]
Won Jeona029f1f2023-12-29 22:43:11 +00001# Copyright (c) 2020-2024, 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 Kunze8137a432024-02-02 21:33:22 +000035TOSA_VERSION_MINOR = 100
Kevin Chengb97cb1d2021-10-14 11:53:39 -070036TOSA_VERSION_PATCH = 0
Eric Kunze8a270432023-06-01 20:08:17 +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",
Won Jeon1adc5d02023-08-12 11:16:05 -070065 "SHAPE",
Won Jeona029f1f2023-12-29 22:43:11 +000066 "FP8E4M3",
67 "FP8E5M2",
Kevin Chengfea5a372021-10-11 18:38:47 +000068]
69
70ByteMask = np.uint64(0xFF)
71
72
73def dtype_str_to_val(name):
74
75 for i in range(len(DTypeNames)):
76 if name.casefold() == DTypeNames[i].casefold():
77 return i
78 raise Exception("Unable to parse DType name {}".format(name))
79
80
81class TosaSerializerUnion:
82 """This class handles encapsulating and serializing union types into flatbuffers"""
83
84 def __init__(self):
85
Jeremy Johnson9b225172021-12-14 16:34:47 +000086 # A tuple of the start and end functions.
87 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000088 self.optFcns = None
89
Jeremy Johnson9b225172021-12-14 16:34:47 +000090 # The type from the tosa.Options enumeration.
91 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000092 self.utype = None
93
94 # Each of these lists is a tuple of the add function and the
95 # value being added. Set by the options constructors below.
96 self.ints = []
97 self.bools = []
98 self.floats = []
99 self.strings = []
TatWai Chong49b1ca62022-06-10 01:49:13 -0700100 self.int16vecs = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000101 self.intvecs = []
102 self.fpvecs = []
103
104 def serialize(self, builder):
105
106 # We have to build strings and vectors first
107 strList = []
108 intVecList = []
109 fpVecList = []
110
111 for fcn, val in self.strings:
112 strList.append((fcn, builder.CreateString(val)))
113
114 for fcn, val in self.intvecs:
115 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
116
TatWai Chong49b1ca62022-06-10 01:49:13 -0700117 for fcn, val in self.int16vecs:
118 intVecList.append((fcn, TosaSerializer.serializeInt16Vec(builder, val)))
119
Kevin Chengfea5a372021-10-11 18:38:47 +0000120 for fcn, val in self.fpvecs:
121 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
122
123 startFcn, endFcn = self.optFcns
124
125 # Then serialize the options object from the list of primitives and
126 # other serialized values
127 startFcn(builder)
128 for fcn, val in self.ints:
129 fcn(builder, val)
130
131 for fcn, val in self.bools:
132 fcn(builder, val)
133
134 for fcn, val in self.floats:
135 fcn(builder, val)
136
137 for fcn, val in strList:
138 fcn(builder, val)
139
140 for fcn, val in intVecList:
141 fcn(builder, val)
142
143 for fcn, val in fpVecList:
144 fcn(builder, val)
145
146 return endFcn(builder)
147
148
149class TosaSerializerAttribute(TosaSerializerUnion):
150 """This class handles encapsulating all of the enumerated types for attributes"""
151
152 def __init__(self):
153 super().__init__()
154
James Ward485a11d2022-08-05 13:48:37 +0100155 def PoolAttribute(
156 self,
157 kernel,
158 stride,
159 pad,
160 input_zp,
161 output_zp,
Tai Ly81db8ee2024-02-14 19:57:38 +0000162 acc_type,
James Ward485a11d2022-08-05 13:48:37 +0100163 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000164 from tosa import PoolAttribute as a, Attribute
165
166 self.utype = Attribute.Attribute().PoolAttribute
167
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800168 self.optFcns = (a.Start, a.End)
TatWai Chong7be71652022-05-10 17:26:20 -0700169 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800170 self.intvecs.append((a.AddKernel, kernel))
171 self.intvecs.append((a.AddStride, stride))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000172 self.ints.append((a.AddInputZp, input_zp))
173 self.ints.append((a.AddOutputZp, output_zp))
Tai Ly81db8ee2024-02-14 19:57:38 +0000174 self.ints.append((a.AddAccType, acc_type))
Kevin Chengfea5a372021-10-11 18:38:47 +0000175
Tai Lyf5dfad12023-11-15 21:09:58 +0000176 def ConvAttribute(self, pad, stride, dilation, input_zp, weight_zp, local_bound):
Kevin Chengfea5a372021-10-11 18:38:47 +0000177 from tosa import ConvAttribute as a, Attribute
178
179 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800180 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000181
TatWai Chong7be71652022-05-10 17:26:20 -0700182 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800183 self.intvecs.append((a.AddStride, stride))
184 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000185 self.ints.append((a.AddInputZp, input_zp))
186 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000187 self.bools.append((a.AddLocalBound, local_bound))
Kevin Chengfea5a372021-10-11 18:38:47 +0000188
Tai Lyf5dfad12023-11-15 21:09:58 +0000189 def TransposeConvAttribute(
190 self, outpad, stride, output_shape, input_zp, weight_zp, local_bound
191 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000192 from tosa import TransposeConvAttribute as a, Attribute
193
194 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800195 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000196
Eric Kunze4c3537d2022-06-13 17:21:48 -0700197 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800198 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800199 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000200 self.ints.append((a.AddInputZp, input_zp))
201 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000202 self.bools.append((a.AddLocalBound, local_bound))
Kevin Chengfea5a372021-10-11 18:38:47 +0000203
James Wardc15f7d52022-12-07 15:38:01 +0000204 def PadAttribute(self, serializer_builder, padding, pad_const_int, pad_const_fp):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700205 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000206
Kevin Cheng38d214c2021-10-15 15:49:19 -0700207 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800208 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000209
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800210 self.intvecs.append((a.AddPadding, padding))
211 self.ints.append((a.AddPadConstInt, pad_const_int))
James Wardc15f7d52022-12-07 15:38:01 +0000212
213 # pad_const_fp attribute serialized as uint8 vector
214 pad_const_float_as_bytes = struct.pack("<f", pad_const_fp)
215 serialized_pad_const_fp = ts.TosaSerializer.serializeUint8Vec(
216 serializer_builder, pad_const_float_as_bytes
217 )
218
219 self.floats.append((a.AddPadConstFp, serialized_pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000220
221 def AxisAttribute(self, axis):
222 from tosa import AxisAttribute as a, Attribute
223
224 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800225 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000226
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800227 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000228
TatWai Chong49b1ca62022-06-10 01:49:13 -0700229 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000230 from tosa import ResizeAttribute as a, Attribute
231
232 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800233 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000234
TatWai Chong49b1ca62022-06-10 01:49:13 -0700235 self.int16vecs.append((a.AddScale, scale))
236 self.int16vecs.append((a.AddOffset, offset))
237 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800238 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000239
James Wardc15f7d52022-12-07 15:38:01 +0000240 def ClampAttribute(self, serializer_builder, minint, maxint, minfp, maxfp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000241 from tosa import ClampAttribute as a, Attribute
242
243 self.utype = Attribute.Attribute().ClampAttribute
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.ints.append((a.AddMinInt, minint))
247 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000248
James Wardc15f7d52022-12-07 15:38:01 +0000249 # min/max float attributes serialized as uint8 vectors
250 minfp_bytes = struct.pack("<f", minfp)
251 maxfp_bytes = struct.pack("<f", maxfp)
252 serialized_minfp_bytes = ts.TosaSerializer.serializeUint8Vec(
253 serializer_builder, minfp_bytes
254 )
255 serialized_maxfp_bytes = ts.TosaSerializer.serializeUint8Vec(
256 serializer_builder, maxfp_bytes
257 )
258
259 self.floats.append((a.AddMinFp, serialized_minfp_bytes))
260 self.floats.append((a.AddMaxFp, serialized_maxfp_bytes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000261
262 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000263 self,
264 input_zp,
265 output_zp,
266 multiplier,
267 shift,
268 scale32,
269 double_round,
270 per_channel,
271 input_unsigned,
272 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000273 ):
274 from tosa import RescaleAttribute as a, Attribute
275
276 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800277 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000278
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800279 self.ints.append((a.AddInputZp, input_zp))
280 self.ints.append((a.AddOutputZp, output_zp))
281 self.intvecs.append((a.AddMultiplier, multiplier))
282 self.intvecs.append((a.AddShift, shift))
283 self.bools.append((a.AddScale32, scale32))
284 self.bools.append((a.AddDoubleRound, double_round))
285 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000286 self.bools.append((a.AddInputUnsigned, input_unsigned))
287 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000288
289 def MulAttribute(self, shift):
290 from tosa import MulAttribute as a, Attribute
291
292 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800293 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000294
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800295 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000296
297 def ArithmeticRightShiftAttribute(self, round):
298 from tosa import ArithmeticRightShiftAttribute as a, Attribute
299
300 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
301 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800302 a.Start,
303 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000304 )
305
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800306 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000307
Tai Ly81db8ee2024-02-14 19:57:38 +0000308 def CondIfAttribute(self, then_graph, else_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000309 from tosa import CondIfAttribute as a, Attribute
310
311 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800312 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000313
Tai Ly81db8ee2024-02-14 19:57:38 +0000314 self.strings.append((a.AddThenGraph, then_graph))
315 self.strings.append((a.AddElseGraph, else_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000316
Tai Ly81db8ee2024-02-14 19:57:38 +0000317 def WhileLoopAttribute(self, cond_graph, body_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000318 from tosa import WhileLoopAttribute as a, Attribute
319
320 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800321 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000322
Tai Ly81db8ee2024-02-14 19:57:38 +0000323 self.strings.append((a.AddCondGraph, cond_graph))
324 self.strings.append((a.AddBodyGraph, body_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000325
TatWai Chong7be71652022-05-10 17:26:20 -0700326 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700327 from tosa import TransposeAttribute as a, Attribute
328
329 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800330 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700331
TatWai Chong7be71652022-05-10 17:26:20 -0700332 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700333
334 def TableAttribute(self, table):
335 from tosa import TableAttribute as a, Attribute
336
337 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800338 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700339
Jerry Gee7b8eb72023-09-15 17:19:50 +0000340 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000341
James Wardea00fd02023-01-20 16:03:50 +0000342 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000343 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000344
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000345 self.utype = Attribute.Attribute().MatMulAttribute
346 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000347
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000348 self.ints.append((a.AddAZp, A_zp))
349 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000350
James Wardea00fd02023-01-20 16:03:50 +0000351 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000352 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000353
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000354 self.utype = Attribute.Attribute().FullyConnectedAttribute
355 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000356
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000357 self.ints.append((a.AddInputZp, input_zp))
358 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000359
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000360 def NegateAttribute(self, input1_zp, output_zp):
361 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000362
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000363 self.utype = Attribute.Attribute().NegateAttribute
364 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000365
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000366 self.ints.append((a.AddInput1Zp, input1_zp))
367 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000368
Tai Lyf5dfad12023-11-15 21:09:58 +0000369 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000370 from tosa import FFTAttribute as a, Attribute
371
372 self.utype = Attribute.Attribute().FFTAttribute
373 self.optFcns = (a.Start, a.End)
374
375 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000376 self.bools.append((a.AddLocalBound, local_bound))
377
378 def RFFTAttribute(self, local_bound):
379 from tosa import RFFTAttribute as a, Attribute
380
381 self.utype = Attribute.Attribute().RFFTAttribute
382 self.optFcns = (a.Start, a.End)
383
384 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000385
Kevin Chengfea5a372021-10-11 18:38:47 +0000386
387class TosaSerializerTensor:
388 def __init__(
389 self,
390 name,
391 shape,
392 dtype,
393 data=None,
394 placeholderFilename=None,
395 ):
396 self.name = name
397
398 if isinstance(shape, np.ndarray):
399 shape = shape.astype(int).tolist()
400 shape = list(map(int, shape))
401
402 self.shape = shape
403 self.dtype = dtype
404
Won Jeona029f1f2023-12-29 22:43:11 +0000405 if (
406 dtype == DType.FP32
407 or dtype == DType.BF16
408 or dtype == DType.FP8E4M3
409 or dtype == DType.FP8E5M2
410 ):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100411 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100412 elif dtype == DType.FP16:
413 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100414 else:
415 fntype = int
416
Kevin Chengfea5a372021-10-11 18:38:47 +0000417 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100418 data = data.flatten().astype(fntype).tolist()
419 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000420 self.data = data
421 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100422 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000423 self.data = data
424 else:
425 self.data = None
426
427 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000428 # process and are written to disk, but are considered input tensors by the
429 # network so they do not appear in the TOSA serialiazation. However, if we
430 # want to form a unit test around these input tensors, we can get the filename
431 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000432 self.placeholderFilename = placeholderFilename
433
434 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800435 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000436 self.name,
437 self.shape,
438 DTypeNames[self.dtype],
439 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800440 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000441
442 def setDtype(self, dtype):
443 self.dtype = dtype
444
445 def serialize(self, builder):
446 fb_name = builder.CreateString(self.name)
447 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
448 if self.data:
449 u8_data = list()
450 # little endianess
451 if self.dtype == DType.BOOL:
452 for val in self.data:
453 val_u8 = np.uint8(val)
454 u8_data.append(val_u8)
455 elif self.dtype == DType.INT4:
456 in_size = len(self.data)
457 out_size = (in_size + 1) // 2
458 for i in range(out_size):
459 val_0 = self.data[2 * i]
460 if (2 * i + 1) < in_size:
461 val_1 = self.data[2 * i + 1]
462 else:
463 val_1 = 0
464 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
465 val_u8 = np.uint8(val_i8)
466 u8_data.append(val_u8)
467 elif self.dtype == DType.INT8:
468 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700469 val_u8 = np.array(val).astype(dtype=np.uint8)
Kevin Chengfea5a372021-10-11 18:38:47 +0000470 u8_data.append(val_u8)
471 elif self.dtype == DType.INT16:
472 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700473 val_u16 = np.array(val).astype(dtype=np.uint16)
Kevin Chengfea5a372021-10-11 18:38:47 +0000474 b0 = val_u16 & ByteMask
475 b1 = (val_u16 >> np.uint16(8)) & ByteMask
476 u8_data.extend([b0, b1])
477 elif self.dtype == DType.INT32:
478 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700479 val_u32 = np.array(val).astype(dtype=np.uint32)
Kevin Chengfea5a372021-10-11 18:38:47 +0000480 b0 = val_u32 & ByteMask
481 b1 = (val_u32 >> np.uint32(8)) & ByteMask
482 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700483 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000484 u8_data.extend([b0, b1, b2, b3])
Won Jeon7c22d772024-01-23 07:46:08 +0000485 elif self.dtype == DType.INT48:
Kevin Chengfea5a372021-10-11 18:38:47 +0000486 for val in self.data:
487 val_u64 = np.uint64(val)
488 b0 = val_u64 & ByteMask
489 b1 = (val_u64 >> np.uint64(8)) & ByteMask
490 b2 = (val_u64 >> np.uint64(16)) & ByteMask
491 b3 = (val_u64 >> np.uint64(24)) & ByteMask
492 b4 = (val_u64 >> np.uint64(32)) & ByteMask
493 b5 = (val_u64 >> np.uint64(40)) & ByteMask
494 u8_data.extend([b0, b1, b2, b3, b4, b5])
Won Jeon7c22d772024-01-23 07:46:08 +0000495 elif self.dtype == DType.SHAPE:
496 for val in self.data:
497 val_u64 = np.uint64(val)
498 b0 = val_u64 & ByteMask
499 b1 = (val_u64 >> np.uint64(8)) & ByteMask
500 b2 = (val_u64 >> np.uint64(16)) & ByteMask
501 b3 = (val_u64 >> np.uint64(24)) & ByteMask
502 b4 = (val_u64 >> np.uint64(32)) & ByteMask
503 b5 = (val_u64 >> np.uint64(40)) & ByteMask
504 b6 = (val_u64 >> np.uint64(48)) & ByteMask
505 b7 = (val_u64 >> np.uint64(56)) & ByteMask
506 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
James Ward485a11d2022-08-05 13:48:37 +0100507 elif self.dtype == DType.FP16:
508 np_arr = np.array(self.data, dtype=np.float16)
509 u8_data.extend(np_arr.view(np.uint8))
Won Jeona029f1f2023-12-29 22:43:11 +0000510 elif (
511 self.dtype == DType.FP32
512 or self.dtype == DType.BF16
513 or self.dtype == DType.FP8E4M3
514 or self.dtype == DType.FP8E5M2
515 ):
James Wardc15f7d52022-12-07 15:38:01 +0000516 # for val in self.data:
517 # b = struct.pack("!f", val)
518 # u8_data.extend([b[3], b[2], b[1], b[0]])
519 np_arr = np.array(self.data, dtype=np.float32)
520 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100521 elif self.dtype == TosaDType.DType:
522 # Serialize DType enum data as uint8 bytes
523 for val in self.data:
524 np_arr = np.array(self.data, dtype=np.uint32)
525 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000526 else:
527 raise Exception(
528 "unsupported data type {}".format(DTypeNames[self.dtype])
529 )
530 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
531
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800532 TosaTensor.Start(builder)
533 TosaTensor.AddName(builder, fb_name)
534 TosaTensor.AddShape(builder, fb_shapes)
535 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000536 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800537 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000538
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800539 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000540
541
542class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000543 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000544 self.op = op
545 self.attributes = attributes
546 self.inputs = TosaSerializer.toList(inputs)
547 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000548
549 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800550 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000551
552 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800553 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000554 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800555 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000556
Jerry Ge1eb85042023-01-06 14:19:14 -0800557 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000558
559 def serialize(self, builder):
560 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800561 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000562 )
563 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800564 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000565 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000566 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000567 if self.attributes is not None:
568 fb_attributes = self.attributes.serialize(builder)
569
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800570 TosaOperator.Start(builder)
571 TosaOperator.AddOp(builder, self.op)
572 TosaOperator.AddInputs(builder, fb_inputs)
573 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000574 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800575 TosaOperator.AddAttributeType(builder, self.attributes.utype)
576 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000577
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800578 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000579
580
581class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000582 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000583 self.name = name
584 self.operators = []
585
586 # Dict assures uniqueness, but allows us to look up by name
587 self.tensors = dict()
588
589 self.inputs = []
590 self.outputs = []
591
592 def addTensor(
593 self,
594 name,
595 shape,
596 dtype,
597 data=None,
598 placeholderFilename=None,
599 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000600 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000601 self.tensors[name] = TosaSerializerTensor(
602 name, shape, dtype, data, placeholderFilename
603 )
604
605 return self.tensors[name]
606
607 def addInput(self, name):
608 self.inputs.append(name)
609
610 def addOutput(self, name):
611 self.outputs.append(name)
612
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000613 def addOperator(self, op, inputs, outputs, attributes=None):
614 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000615
616 def serialize(self, builder):
617 fb_name = builder.CreateString(self.name)
618 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800619 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000620 )
621 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800622 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000623 )
624 fbv_tensors = TosaSerializer.serializeObjVec(
625 builder,
626 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800627 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000628 )
629 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800630 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000631 )
632
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800633 TosaBasicBlock.Start(builder)
634 TosaBasicBlock.AddName(builder, fb_name)
635 TosaBasicBlock.AddInputs(builder, fbv_inputs)
636 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
637 TosaBasicBlock.AddTensors(builder, fbv_tensors)
638 TosaBasicBlock.AddOperators(builder, fbv_operators)
639 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000640
641
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100642# How CONSTs are treated in the flatbuffer
643@unique
644class ConstMode(IntEnum):
645 EMBED = 0
646 EMBED_DUMP = 1
647 INPUTS = 2
648
649
Jerry Ge1eb85042023-01-06 14:19:14 -0800650class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100651 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800652 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000653 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000654 self.currInputIdx = 0
655 self.currConstIdx = 0
656 self.currLayerIdx = 1
657 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800658 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100659 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000660
Jerry Geca7ce0e2023-01-10 17:24:38 +0000661 def addBasicBlock(self, name):
662 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800663 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000664
Jerry Ge1eb85042023-01-06 14:19:14 -0800665 def serialize(self, builder):
666 fb_name = builder.CreateString(self.name)
667 fbv_basicBlocks = TosaSerializer.serializeObjVec(
668 builder, self.basicBlocks, TosaRegion.StartBlocksVector
669 )
670
671 TosaRegion.Start(builder)
672 TosaRegion.AddName(builder, fb_name)
673 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
674 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000675
676 def addPlaceholder(self, shape, dtype, vals):
677 if not self.currBasicBlock:
678 raise Exception("addTensor called without valid basic block")
679
680 name = "input-{}".format(self.currInputIdx)
681 filename = "{}.npy".format(name)
682 self.currInputIdx = self.currInputIdx + 1
683
684 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
685 # This is always an input to the block
686 self.currBasicBlock.addInput(name)
687
688 if vals is not None:
689 np.save(os.path.join(self.pathPrefix, filename), vals, False)
690
691 return tens
692
Jerry Ge53ceb482023-08-14 20:15:10 +0000693 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000694 if not self.currBasicBlock:
695 raise Exception("addTensor called without valid basic block")
696
Jerry Ge53ceb482023-08-14 20:15:10 +0000697 if name is None:
698 name = "const-{}".format(self.currInputIdx)
699 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000700
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100701 if self.constMode == ConstMode.INPUTS:
702 # Save const as input file
703 filename = "{}.npy".format(name)
704 tensor_vals = None
705 self.currBasicBlock.addInput(name)
706 else:
707 # Embed const in flatbuffer
708 filename = None
709 tensor_vals = vals
710
711 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000712 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000713 if dtype == DType.SHAPE:
714 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
715 else:
716 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000717
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100718 # Save the const data to file for debug or as input files
719 if vals is not None and self.constMode in [
720 ConstMode.EMBED_DUMP,
721 ConstMode.INPUTS,
722 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100723 filename = "{}.npy".format(name)
724 np.save(os.path.join(self.pathPrefix, filename), vals, False)
725
Kevin Chengfea5a372021-10-11 18:38:47 +0000726 return tens
727
728 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000729 if not self.currBasicBlock:
730 raise Exception("addTensor called without valid basic block")
731
732 name = "layer-{}".format(self.currLayerIdx)
733 self.currLayerIdx = self.currLayerIdx + 1
734
735 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
736
737 return tens
738
739 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700740 self.currBasicBlock.addTensor(
741 tensor.name,
742 tensor.shape,
743 tensor.dtype,
744 tensor.data,
745 tensor.placeholderFilename,
746 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000747 self.currBasicBlock.addInput(tensor.name)
748
749 def addOutputTensor(self, tensor):
750 self.currBasicBlock.addOutput(tensor.name)
751
752 def addOutput(self, shape, dtype):
753 if not self.currBasicBlock:
754 raise Exception("addTensor called without valid basic block")
755
756 name = "result-{}".format(self.currResultIdx)
757 self.currResultIdx = self.currResultIdx + 1
758
759 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
760 self.currBasicBlock.addOutput(name)
761 return tens
762
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000763 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000764 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000765 raise Exception("Use addConstTensor() to add CONST ops")
766
767 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000768 op,
769 inputs,
770 outputs,
771 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000772 )
773
Jerry Ge1eb85042023-01-06 14:19:14 -0800774
775@unique
776class TensorDir(IntEnum):
777 PLACEHOLDER = 0
778 CONST = 1
779 INTERMEDIATE = 2
780 RESULT = 3
781
782
783class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100784 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800785 self.builder = flatbuffers.Builder(0)
786
Jerry Ge1eb85042023-01-06 14:19:14 -0800787 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100788 self.constMode = constMode
789
790 self.regions = []
791 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800792
Jerry Geca7ce0e2023-01-10 17:24:38 +0000793 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800794
795 # Is this an illegal test that is expected to fail?
796 self.expectedReturnCode = 0
797 self.expectedFailure = False
798 self.expectedFailureDesc = ""
799
800 def __str__(self):
801 concatString = ""
802 for region in self.regions:
803 concatString = concatString + str(region)
804 return concatString
805
806 def addPlaceholder(self, shape, dtype, vals):
807 return self.currRegion.addPlaceholder(shape, dtype, vals)
808
Jerry Ge53ceb482023-08-14 20:15:10 +0000809 def addConst(self, shape, dtype, vals, name=None):
810 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800811
812 def addIntermediate(self, shape, dtype):
813 return self.currRegion.addIntermediate(shape, dtype)
814
815 def addInputTensor(self, tensor):
816 self.currRegion.addInputTensor(tensor)
817
818 def addOutputTensor(self, tensor):
819 self.currRegion.addOutputTensor(tensor)
820
821 def addOutput(self, shape, dtype):
822 return self.currRegion.addOutput(shape, dtype)
823
824 def addOperator(self, op, inputs, outputs, attributes=None):
825 return self.currRegion.addOperator(op, inputs, outputs, attributes)
826
Jerry Geca7ce0e2023-01-10 17:24:38 +0000827 def addBasicBlock(self, name):
828 self.currRegion.addBasicBlock(name)
829
Jeremy Johnson9b225172021-12-14 16:34:47 +0000830 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000831
832 self.expectedReturnCode = val
833 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000834 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000835
836 def serialize(self):
837
838 builder = self.builder
839
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800840 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000841 Version.Add_Major(builder, TOSA_VERSION[0])
842 Version.Add_Minor(builder, TOSA_VERSION[1])
843 Version.Add_Patch(builder, TOSA_VERSION[2])
844 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800845 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000846
Jerry Ge1eb85042023-01-06 14:19:14 -0800847 fbv_region = TosaSerializer.serializeObjVec(
848 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000849 )
850
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800851 TosaGraph.Start(builder)
852 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800853 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800854 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000855
Eric Kunzee6596402022-06-09 21:27:36 +0000856 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000857 return self.builder.Output()
858
859 def writeJson(self, tosa_filename):
860 """Write a json test file so that it is fairly easy to pick up the test
861 and generate commands for third party tool"""
862 test_desc = dict()
863
864 test_desc["tosa_file"] = tosa_filename
865 ifm_name = []
866 ifm_file = []
867 ofm_name = []
868 ofm_file = []
869
Jerry Ge1eb85042023-01-06 14:19:14 -0800870 for region in self.regions:
871 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000872 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800873 for i in block.inputs:
874 ifm_name.append(i)
875 ifm_file.append(block.tensors[i].placeholderFilename)
876 for o in block.outputs:
877 ofm_name.append(o)
878 # Make up an OFM filename here. One isn't generated until the
879 # reference tool is run, so any name is a good name
880 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000881
882 test_desc["ifm_name"] = ifm_name
883 test_desc["ifm_file"] = ifm_file
884 test_desc["ofm_name"] = ofm_name
885 test_desc["ofm_file"] = ofm_file
886 test_desc["expected_return_code"] = self.expectedReturnCode
887 test_desc["expected_failure"] = self.expectedFailure
888 if self.expectedFailureDesc:
889 test_desc["expected_failure_desc"] = self.expectedFailureDesc
890
891 return json.dumps(test_desc, indent=" ")
892
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100893 def startRegion(self, name, pathPrefix):
894 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800895 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000896
897 @staticmethod
898 def serializeStrVec(builder, vec, start_fcn):
899 fb_strs = [builder.CreateString(i) for i in vec]
900 start_fcn(builder, len(fb_strs))
901 for s in fb_strs[::-1]:
902 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700903 try:
904 return builder.EndVector()
905 except TypeError:
906 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000907
908 @staticmethod
909 def serializeUint8Vec(builder, vec):
910 builder.StartVector(1, len(vec), 8)
911 for v in vec[::-1]:
912 builder.PrependUint8(v)
913 try:
914 return builder.EndVector()
915 except TypeError:
916 return builder.EndVector(len(vec))
917
918 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700919 def serializeInt16Vec(builder, vec):
920 builder.StartVector(2, len(vec), 4)
921 for v in vec[::-1]:
922 builder.PrependInt16(v)
923 try:
924 return builder.EndVector()
925 except TypeError:
926 return builder.EndVector(len(vec))
927
928 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000929 def serializeInt32Vec(builder, vec):
930 builder.StartVector(4, len(vec), 4)
931 for v in vec[::-1]:
932 builder.PrependInt32(v)
933 try:
934 return builder.EndVector()
935 except TypeError:
936 return builder.EndVector(len(vec))
937
938 @staticmethod
939 def serializeFpVec(builder, vec):
940 builder.StartVector(4, len(vec), 4)
941 for v in vec[::-1]:
942 builder.PrependFloat32(v)
943 try:
944 return builder.EndVector()
945 except TypeError:
946 return builder.EndVector(len(vec))
947
948 @staticmethod
949 def serializeObjVec(builder, vec, start_fcn):
950 serialized_vec = []
951 for v in vec[::-1]:
952 serialized_vec.append(v.serialize(builder))
953
954 start_fcn(builder, len(vec))
955 for v in serialized_vec:
956 builder.PrependUOffsetTRelative(v)
957 try:
958 return builder.EndVector()
959 except TypeError:
960 return builder.EndVector(len(vec))
961
962 @staticmethod
963 def toList(val):
964 if isinstance(val, list):
965 return val
966 else:
967 return [val]