blob: 9096b4a36b04de5533a5b66e8727197b5a02f29f [file] [log] [blame]
Eric Kunzec53436e2024-03-19 13:55:38 -07001# 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 Kunzec3badae2024-03-19 13:55:49 -070035TOSA_VERSION_MINOR = 90
Kevin Chengb97cb1d2021-10-14 11:53:39 -070036TOSA_VERSION_PATCH = 0
Eric Kunze881b56f2024-03-19 20:58:08 +000037TOSA_VERSION_DRAFT = False
Jeremy Johnson9b225172021-12-14 16:34:47 +000038TOSA_VERSION = [
39 TOSA_VERSION_MAJOR,
40 TOSA_VERSION_MINOR,
41 TOSA_VERSION_PATCH,
42 TOSA_VERSION_DRAFT,
43]
Eric Kunzee6596402022-06-09 21:27:36 +000044
45# File identifier needs to be kept in sync with schema/tosa.fbs
46TOSA_GRAPH_IDENTIFIER = b"\x54\x4F\x53\x41"
47
Kevin Chengfea5a372021-10-11 18:38:47 +000048# With the way flatc generates its python types, there is no programatic way
49# to get string names for the integer types. Manually maintain a string table
50# here.
Jeremy Johnson9b225172021-12-14 16:34:47 +000051DType = TosaDType.DType()
Kevin Chengfea5a372021-10-11 18:38:47 +000052DTypeNames = [
53 "UNKNOWN",
54 "BOOL",
55 "UINT8",
56 "INT4",
57 "INT8",
58 "INT16",
59 "INT32",
60 "INT48",
Jeremy Johnsone1072a92022-09-27 12:44:11 +010061 "FP32",
Jeremy Johnson41027732022-05-25 17:52:29 +010062 "UINT16",
James Ward485a11d2022-08-05 13:48:37 +010063 "FP16",
James Ward34a62792022-10-18 17:27:40 +010064 "BF16",
Won Jeon1adc5d02023-08-12 11:16:05 -070065 "SHAPE",
Kevin Chengfea5a372021-10-11 18:38:47 +000066]
67
68ByteMask = np.uint64(0xFF)
69
70
71def dtype_str_to_val(name):
72
73 for i in range(len(DTypeNames)):
74 if name.casefold() == DTypeNames[i].casefold():
75 return i
76 raise Exception("Unable to parse DType name {}".format(name))
77
78
79class TosaSerializerUnion:
80 """This class handles encapsulating and serializing union types into flatbuffers"""
81
82 def __init__(self):
83
Jeremy Johnson9b225172021-12-14 16:34:47 +000084 # A tuple of the start and end functions.
85 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000086 self.optFcns = None
87
Jeremy Johnson9b225172021-12-14 16:34:47 +000088 # The type from the tosa.Options enumeration.
89 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000090 self.utype = None
91
92 # Each of these lists is a tuple of the add function and the
93 # value being added. Set by the options constructors below.
94 self.ints = []
95 self.bools = []
96 self.floats = []
97 self.strings = []
TatWai Chong49b1ca62022-06-10 01:49:13 -070098 self.int16vecs = []
Kevin Chengfea5a372021-10-11 18:38:47 +000099 self.intvecs = []
100 self.fpvecs = []
101
102 def serialize(self, builder):
103
104 # We have to build strings and vectors first
105 strList = []
106 intVecList = []
107 fpVecList = []
108
109 for fcn, val in self.strings:
110 strList.append((fcn, builder.CreateString(val)))
111
112 for fcn, val in self.intvecs:
113 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
114
TatWai Chong49b1ca62022-06-10 01:49:13 -0700115 for fcn, val in self.int16vecs:
116 intVecList.append((fcn, TosaSerializer.serializeInt16Vec(builder, val)))
117
Kevin Chengfea5a372021-10-11 18:38:47 +0000118 for fcn, val in self.fpvecs:
119 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
120
121 startFcn, endFcn = self.optFcns
122
123 # Then serialize the options object from the list of primitives and
124 # other serialized values
125 startFcn(builder)
126 for fcn, val in self.ints:
127 fcn(builder, val)
128
129 for fcn, val in self.bools:
130 fcn(builder, val)
131
132 for fcn, val in self.floats:
133 fcn(builder, val)
134
135 for fcn, val in strList:
136 fcn(builder, val)
137
138 for fcn, val in intVecList:
139 fcn(builder, val)
140
141 for fcn, val in fpVecList:
142 fcn(builder, val)
143
144 return endFcn(builder)
145
146
147class TosaSerializerAttribute(TosaSerializerUnion):
148 """This class handles encapsulating all of the enumerated types for attributes"""
149
150 def __init__(self):
151 super().__init__()
152
James Ward485a11d2022-08-05 13:48:37 +0100153 def PoolAttribute(
154 self,
155 kernel,
156 stride,
157 pad,
158 input_zp,
159 output_zp,
160 accum_dtype,
161 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000162 from tosa import PoolAttribute as a, Attribute
163
164 self.utype = Attribute.Attribute().PoolAttribute
165
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800166 self.optFcns = (a.Start, a.End)
TatWai Chong7be71652022-05-10 17:26:20 -0700167 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800168 self.intvecs.append((a.AddKernel, kernel))
169 self.intvecs.append((a.AddStride, stride))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000170 self.ints.append((a.AddInputZp, input_zp))
171 self.ints.append((a.AddOutputZp, output_zp))
James Ward485a11d2022-08-05 13:48:37 +0100172 self.ints.append((a.AddAccumDtype, accum_dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000173
Tai Lyf5dfad12023-11-15 21:09:58 +0000174 def ConvAttribute(self, pad, stride, dilation, input_zp, weight_zp, local_bound):
Kevin Chengfea5a372021-10-11 18:38:47 +0000175 from tosa import ConvAttribute as a, Attribute
176
177 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800178 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000179
TatWai Chong7be71652022-05-10 17:26:20 -0700180 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800181 self.intvecs.append((a.AddStride, stride))
182 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000183 self.ints.append((a.AddInputZp, input_zp))
184 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000185 self.bools.append((a.AddLocalBound, local_bound))
Kevin Chengfea5a372021-10-11 18:38:47 +0000186
Tai Lyf5dfad12023-11-15 21:09:58 +0000187 def TransposeConvAttribute(
188 self, outpad, stride, output_shape, input_zp, weight_zp, local_bound
189 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000190 from tosa import TransposeConvAttribute as a, Attribute
191
192 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800193 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000194
Eric Kunze4c3537d2022-06-13 17:21:48 -0700195 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800196 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800197 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000198 self.ints.append((a.AddInputZp, input_zp))
199 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000200 self.bools.append((a.AddLocalBound, local_bound))
Kevin Chengfea5a372021-10-11 18:38:47 +0000201
James Wardc15f7d52022-12-07 15:38:01 +0000202 def PadAttribute(self, serializer_builder, padding, pad_const_int, pad_const_fp):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700203 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000204
Kevin Cheng38d214c2021-10-15 15:49:19 -0700205 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800206 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000207
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800208 self.intvecs.append((a.AddPadding, padding))
209 self.ints.append((a.AddPadConstInt, pad_const_int))
James Wardc15f7d52022-12-07 15:38:01 +0000210
211 # pad_const_fp attribute serialized as uint8 vector
212 pad_const_float_as_bytes = struct.pack("<f", pad_const_fp)
213 serialized_pad_const_fp = ts.TosaSerializer.serializeUint8Vec(
214 serializer_builder, pad_const_float_as_bytes
215 )
216
217 self.floats.append((a.AddPadConstFp, serialized_pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000218
219 def AxisAttribute(self, axis):
220 from tosa import AxisAttribute as a, Attribute
221
222 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800223 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000224
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800225 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000226
TatWai Chong7be71652022-05-10 17:26:20 -0700227 def ReshapeAttribute(self, new_shape):
Kevin Chengfea5a372021-10-11 18:38:47 +0000228 from tosa import ReshapeAttribute as a, Attribute
229
230 self.utype = Attribute.Attribute().ReshapeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800231 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000232
TatWai Chong7be71652022-05-10 17:26:20 -0700233 self.intvecs.append((a.AddNewShape, new_shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000234
TatWai Chong7be71652022-05-10 17:26:20 -0700235 def SliceAttribute(self, start, size):
Kevin Chengfea5a372021-10-11 18:38:47 +0000236 from tosa import SliceAttribute as a, Attribute
237
238 self.utype = Attribute.Attribute().SliceAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800239 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000240
TatWai Chong7be71652022-05-10 17:26:20 -0700241 self.intvecs.append((a.AddStart, start))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800242 self.intvecs.append((a.AddSize, size))
Kevin Chengfea5a372021-10-11 18:38:47 +0000243
244 def TileAttribute(self, multiples):
245 from tosa import TileAttribute as a, Attribute
246
247 self.utype = Attribute.Attribute().TileAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800248 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000249
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800250 self.intvecs.append((a.AddMultiples, multiples))
Kevin Chengfea5a372021-10-11 18:38:47 +0000251
TatWai Chong49b1ca62022-06-10 01:49:13 -0700252 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000253 from tosa import ResizeAttribute as a, Attribute
254
255 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800256 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000257
TatWai Chong49b1ca62022-06-10 01:49:13 -0700258 self.int16vecs.append((a.AddScale, scale))
259 self.int16vecs.append((a.AddOffset, offset))
260 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800261 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000262
James Wardc15f7d52022-12-07 15:38:01 +0000263 def ClampAttribute(self, serializer_builder, minint, maxint, minfp, maxfp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000264 from tosa import ClampAttribute as a, Attribute
265
266 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800267 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000268
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800269 self.ints.append((a.AddMinInt, minint))
270 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000271
James Wardc15f7d52022-12-07 15:38:01 +0000272 # min/max float attributes serialized as uint8 vectors
273 minfp_bytes = struct.pack("<f", minfp)
274 maxfp_bytes = struct.pack("<f", maxfp)
275 serialized_minfp_bytes = ts.TosaSerializer.serializeUint8Vec(
276 serializer_builder, minfp_bytes
277 )
278 serialized_maxfp_bytes = ts.TosaSerializer.serializeUint8Vec(
279 serializer_builder, maxfp_bytes
280 )
281
282 self.floats.append((a.AddMinFp, serialized_minfp_bytes))
283 self.floats.append((a.AddMaxFp, serialized_maxfp_bytes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000284
285 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000286 self,
287 input_zp,
288 output_zp,
289 multiplier,
290 shift,
291 scale32,
292 double_round,
293 per_channel,
294 input_unsigned,
295 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000296 ):
297 from tosa import RescaleAttribute as a, Attribute
298
299 self.utype = Attribute.Attribute().RescaleAttribute
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.AddInputZp, input_zp))
303 self.ints.append((a.AddOutputZp, output_zp))
304 self.intvecs.append((a.AddMultiplier, multiplier))
305 self.intvecs.append((a.AddShift, shift))
306 self.bools.append((a.AddScale32, scale32))
307 self.bools.append((a.AddDoubleRound, double_round))
308 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000309 self.bools.append((a.AddInputUnsigned, input_unsigned))
310 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000311
312 def MulAttribute(self, shift):
313 from tosa import MulAttribute as a, Attribute
314
315 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800316 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000317
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800318 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000319
320 def ArithmeticRightShiftAttribute(self, round):
321 from tosa import ArithmeticRightShiftAttribute as a, Attribute
322
323 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
324 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800325 a.Start,
326 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000327 )
328
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800329 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000330
Kevin Chengfea5a372021-10-11 18:38:47 +0000331 def CondIfAttribute(self, then_branch, else_branch):
332 from tosa import CondIfAttribute as a, Attribute
333
334 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800335 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000336
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800337 self.strings.append((a.AddThenBranch, then_branch))
338 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000339
340 def WhileLoopAttribute(self, cond_branch, body_branch):
341 from tosa import WhileLoopAttribute as a, Attribute
342
343 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800344 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000345
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800346 self.strings.append((a.AddCondBranch, cond_branch))
347 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000348
TatWai Chong7be71652022-05-10 17:26:20 -0700349 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700350 from tosa import TransposeAttribute as a, Attribute
351
352 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800353 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700354
TatWai Chong7be71652022-05-10 17:26:20 -0700355 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700356
357 def TableAttribute(self, table):
358 from tosa import TableAttribute as a, Attribute
359
360 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800361 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700362
Jerry Gee7b8eb72023-09-15 17:19:50 +0000363 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000364
James Wardea00fd02023-01-20 16:03:50 +0000365 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000366 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000367
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000368 self.utype = Attribute.Attribute().MatMulAttribute
369 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000370
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000371 self.ints.append((a.AddAZp, A_zp))
372 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000373
James Wardea00fd02023-01-20 16:03:50 +0000374 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000375 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000376
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000377 self.utype = Attribute.Attribute().FullyConnectedAttribute
378 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000379
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000380 self.ints.append((a.AddInputZp, input_zp))
381 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000382
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000383 def NegateAttribute(self, input1_zp, output_zp):
384 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000385
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000386 self.utype = Attribute.Attribute().NegateAttribute
387 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000388
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000389 self.ints.append((a.AddInput1Zp, input1_zp))
390 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000391
Tai Lyf5dfad12023-11-15 21:09:58 +0000392 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000393 from tosa import FFTAttribute as a, Attribute
394
395 self.utype = Attribute.Attribute().FFTAttribute
396 self.optFcns = (a.Start, a.End)
397
398 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000399 self.bools.append((a.AddLocalBound, local_bound))
400
401 def RFFTAttribute(self, local_bound):
402 from tosa import RFFTAttribute as a, Attribute
403
404 self.utype = Attribute.Attribute().RFFTAttribute
405 self.optFcns = (a.Start, a.End)
406
407 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000408
Kevin Chengfea5a372021-10-11 18:38:47 +0000409
410class TosaSerializerTensor:
411 def __init__(
412 self,
413 name,
414 shape,
415 dtype,
416 data=None,
417 placeholderFilename=None,
418 ):
419 self.name = name
420
421 if isinstance(shape, np.ndarray):
422 shape = shape.astype(int).tolist()
423 shape = list(map(int, shape))
424
425 self.shape = shape
426 self.dtype = dtype
427
Eric Kunzec53436e2024-03-19 13:55:38 -0700428 if dtype == DType.FP32 or dtype == DType.BF16:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100429 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100430 elif dtype == DType.FP16:
431 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100432 else:
433 fntype = int
434
Kevin Chengfea5a372021-10-11 18:38:47 +0000435 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100436 data = data.flatten().astype(fntype).tolist()
437 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000438 self.data = data
439 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100440 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000441 self.data = data
442 else:
443 self.data = None
444
445 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000446 # process and are written to disk, but are considered input tensors by the
447 # network so they do not appear in the TOSA serialiazation. However, if we
448 # want to form a unit test around these input tensors, we can get the filename
449 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000450 self.placeholderFilename = placeholderFilename
451
452 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800453 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000454 self.name,
455 self.shape,
456 DTypeNames[self.dtype],
457 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800458 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000459
460 def setDtype(self, dtype):
461 self.dtype = dtype
462
463 def serialize(self, builder):
464 fb_name = builder.CreateString(self.name)
465 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
466 if self.data:
467 u8_data = list()
468 # little endianess
469 if self.dtype == DType.BOOL:
470 for val in self.data:
471 val_u8 = np.uint8(val)
472 u8_data.append(val_u8)
473 elif self.dtype == DType.INT4:
474 in_size = len(self.data)
475 out_size = (in_size + 1) // 2
476 for i in range(out_size):
477 val_0 = self.data[2 * i]
478 if (2 * i + 1) < in_size:
479 val_1 = self.data[2 * i + 1]
480 else:
481 val_1 = 0
482 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
483 val_u8 = np.uint8(val_i8)
484 u8_data.append(val_u8)
485 elif self.dtype == DType.INT8:
486 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700487 val_u8 = np.array(val).astype(dtype=np.uint8)
Kevin Chengfea5a372021-10-11 18:38:47 +0000488 u8_data.append(val_u8)
489 elif self.dtype == DType.INT16:
490 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700491 val_u16 = np.array(val).astype(dtype=np.uint16)
Kevin Chengfea5a372021-10-11 18:38:47 +0000492 b0 = val_u16 & ByteMask
493 b1 = (val_u16 >> np.uint16(8)) & ByteMask
494 u8_data.extend([b0, b1])
495 elif self.dtype == DType.INT32:
496 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700497 val_u32 = np.array(val).astype(dtype=np.uint32)
Kevin Chengfea5a372021-10-11 18:38:47 +0000498 b0 = val_u32 & ByteMask
499 b1 = (val_u32 >> np.uint32(8)) & ByteMask
500 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700501 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000502 u8_data.extend([b0, b1, b2, b3])
Won Jeon7c22d772024-01-23 07:46:08 +0000503 elif self.dtype == DType.INT48:
Kevin Chengfea5a372021-10-11 18:38:47 +0000504 for val in self.data:
505 val_u64 = np.uint64(val)
506 b0 = val_u64 & ByteMask
507 b1 = (val_u64 >> np.uint64(8)) & ByteMask
508 b2 = (val_u64 >> np.uint64(16)) & ByteMask
509 b3 = (val_u64 >> np.uint64(24)) & ByteMask
510 b4 = (val_u64 >> np.uint64(32)) & ByteMask
511 b5 = (val_u64 >> np.uint64(40)) & ByteMask
512 u8_data.extend([b0, b1, b2, b3, b4, b5])
Won Jeon7c22d772024-01-23 07:46:08 +0000513 elif self.dtype == DType.SHAPE:
514 for val in self.data:
515 val_u64 = np.uint64(val)
516 b0 = val_u64 & ByteMask
517 b1 = (val_u64 >> np.uint64(8)) & ByteMask
518 b2 = (val_u64 >> np.uint64(16)) & ByteMask
519 b3 = (val_u64 >> np.uint64(24)) & ByteMask
520 b4 = (val_u64 >> np.uint64(32)) & ByteMask
521 b5 = (val_u64 >> np.uint64(40)) & ByteMask
522 b6 = (val_u64 >> np.uint64(48)) & ByteMask
523 b7 = (val_u64 >> np.uint64(56)) & ByteMask
524 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
James Ward485a11d2022-08-05 13:48:37 +0100525 elif self.dtype == DType.FP16:
526 np_arr = np.array(self.data, dtype=np.float16)
527 u8_data.extend(np_arr.view(np.uint8))
Eric Kunzec53436e2024-03-19 13:55:38 -0700528 elif self.dtype == DType.FP32 or self.dtype == DType.BF16:
James Wardc15f7d52022-12-07 15:38:01 +0000529 # for val in self.data:
530 # b = struct.pack("!f", val)
531 # u8_data.extend([b[3], b[2], b[1], b[0]])
532 np_arr = np.array(self.data, dtype=np.float32)
533 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100534 elif self.dtype == TosaDType.DType:
535 # Serialize DType enum data as uint8 bytes
536 for val in self.data:
537 np_arr = np.array(self.data, dtype=np.uint32)
538 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000539 else:
540 raise Exception(
541 "unsupported data type {}".format(DTypeNames[self.dtype])
542 )
543 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
544
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800545 TosaTensor.Start(builder)
546 TosaTensor.AddName(builder, fb_name)
547 TosaTensor.AddShape(builder, fb_shapes)
548 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000549 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800550 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000551
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800552 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000553
554
555class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000556 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000557 self.op = op
558 self.attributes = attributes
559 self.inputs = TosaSerializer.toList(inputs)
560 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000561
562 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800563 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000564
565 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800566 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000567 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800568 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000569
Jerry Ge1eb85042023-01-06 14:19:14 -0800570 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000571
572 def serialize(self, builder):
573 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800574 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000575 )
576 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800577 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000578 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000579 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000580 if self.attributes is not None:
581 fb_attributes = self.attributes.serialize(builder)
582
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800583 TosaOperator.Start(builder)
584 TosaOperator.AddOp(builder, self.op)
585 TosaOperator.AddInputs(builder, fb_inputs)
586 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000587 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800588 TosaOperator.AddAttributeType(builder, self.attributes.utype)
589 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000590
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800591 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000592
593
594class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000595 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000596 self.name = name
597 self.operators = []
598
599 # Dict assures uniqueness, but allows us to look up by name
600 self.tensors = dict()
601
602 self.inputs = []
603 self.outputs = []
604
605 def addTensor(
606 self,
607 name,
608 shape,
609 dtype,
610 data=None,
611 placeholderFilename=None,
612 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000613 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000614 self.tensors[name] = TosaSerializerTensor(
615 name, shape, dtype, data, placeholderFilename
616 )
617
618 return self.tensors[name]
619
620 def addInput(self, name):
621 self.inputs.append(name)
622
623 def addOutput(self, name):
624 self.outputs.append(name)
625
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000626 def addOperator(self, op, inputs, outputs, attributes=None):
627 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000628
629 def serialize(self, builder):
630 fb_name = builder.CreateString(self.name)
631 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800632 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000633 )
634 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800635 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000636 )
637 fbv_tensors = TosaSerializer.serializeObjVec(
638 builder,
639 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800640 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000641 )
642 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800643 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000644 )
645
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800646 TosaBasicBlock.Start(builder)
647 TosaBasicBlock.AddName(builder, fb_name)
648 TosaBasicBlock.AddInputs(builder, fbv_inputs)
649 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
650 TosaBasicBlock.AddTensors(builder, fbv_tensors)
651 TosaBasicBlock.AddOperators(builder, fbv_operators)
652 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000653
654
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100655# How CONSTs are treated in the flatbuffer
656@unique
657class ConstMode(IntEnum):
658 EMBED = 0
659 EMBED_DUMP = 1
660 INPUTS = 2
661
662
Jerry Ge1eb85042023-01-06 14:19:14 -0800663class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100664 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800665 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000666 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000667 self.currInputIdx = 0
668 self.currConstIdx = 0
669 self.currLayerIdx = 1
670 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800671 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100672 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000673
Jerry Geca7ce0e2023-01-10 17:24:38 +0000674 def addBasicBlock(self, name):
675 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800676 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000677
Jerry Ge1eb85042023-01-06 14:19:14 -0800678 def serialize(self, builder):
679 fb_name = builder.CreateString(self.name)
680 fbv_basicBlocks = TosaSerializer.serializeObjVec(
681 builder, self.basicBlocks, TosaRegion.StartBlocksVector
682 )
683
684 TosaRegion.Start(builder)
685 TosaRegion.AddName(builder, fb_name)
686 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
687 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000688
689 def addPlaceholder(self, shape, dtype, vals):
690 if not self.currBasicBlock:
691 raise Exception("addTensor called without valid basic block")
692
693 name = "input-{}".format(self.currInputIdx)
694 filename = "{}.npy".format(name)
695 self.currInputIdx = self.currInputIdx + 1
696
697 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
698 # This is always an input to the block
699 self.currBasicBlock.addInput(name)
700
701 if vals is not None:
702 np.save(os.path.join(self.pathPrefix, filename), vals, False)
703
704 return tens
705
Jerry Ge53ceb482023-08-14 20:15:10 +0000706 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000707 if not self.currBasicBlock:
708 raise Exception("addTensor called without valid basic block")
709
Jerry Ge53ceb482023-08-14 20:15:10 +0000710 if name is None:
711 name = "const-{}".format(self.currInputIdx)
712 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000713
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100714 if self.constMode == ConstMode.INPUTS:
715 # Save const as input file
716 filename = "{}.npy".format(name)
717 tensor_vals = None
718 self.currBasicBlock.addInput(name)
719 else:
720 # Embed const in flatbuffer
721 filename = None
722 tensor_vals = vals
723
724 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000725 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000726 if dtype == DType.SHAPE:
727 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
728 else:
729 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000730
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100731 # Save the const data to file for debug or as input files
732 if vals is not None and self.constMode in [
733 ConstMode.EMBED_DUMP,
734 ConstMode.INPUTS,
735 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100736 filename = "{}.npy".format(name)
737 np.save(os.path.join(self.pathPrefix, filename), vals, False)
738
Kevin Chengfea5a372021-10-11 18:38:47 +0000739 return tens
740
741 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000742 if not self.currBasicBlock:
743 raise Exception("addTensor called without valid basic block")
744
745 name = "layer-{}".format(self.currLayerIdx)
746 self.currLayerIdx = self.currLayerIdx + 1
747
748 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
749
750 return tens
751
752 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700753 self.currBasicBlock.addTensor(
754 tensor.name,
755 tensor.shape,
756 tensor.dtype,
757 tensor.data,
758 tensor.placeholderFilename,
759 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000760 self.currBasicBlock.addInput(tensor.name)
761
762 def addOutputTensor(self, tensor):
763 self.currBasicBlock.addOutput(tensor.name)
764
765 def addOutput(self, shape, dtype):
766 if not self.currBasicBlock:
767 raise Exception("addTensor called without valid basic block")
768
769 name = "result-{}".format(self.currResultIdx)
770 self.currResultIdx = self.currResultIdx + 1
771
772 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
773 self.currBasicBlock.addOutput(name)
774 return tens
775
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000776 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000777 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000778 raise Exception("Use addConstTensor() to add CONST ops")
779
780 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000781 op,
782 inputs,
783 outputs,
784 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000785 )
786
Jerry Ge1eb85042023-01-06 14:19:14 -0800787
788@unique
789class TensorDir(IntEnum):
790 PLACEHOLDER = 0
791 CONST = 1
792 INTERMEDIATE = 2
793 RESULT = 3
794
795
796class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100797 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800798 self.builder = flatbuffers.Builder(0)
799
Jerry Ge1eb85042023-01-06 14:19:14 -0800800 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100801 self.constMode = constMode
802
803 self.regions = []
804 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800805
Jerry Geca7ce0e2023-01-10 17:24:38 +0000806 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800807
808 # Is this an illegal test that is expected to fail?
809 self.expectedReturnCode = 0
810 self.expectedFailure = False
811 self.expectedFailureDesc = ""
812
813 def __str__(self):
814 concatString = ""
815 for region in self.regions:
816 concatString = concatString + str(region)
817 return concatString
818
819 def addPlaceholder(self, shape, dtype, vals):
820 return self.currRegion.addPlaceholder(shape, dtype, vals)
821
Jerry Ge53ceb482023-08-14 20:15:10 +0000822 def addConst(self, shape, dtype, vals, name=None):
823 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800824
825 def addIntermediate(self, shape, dtype):
826 return self.currRegion.addIntermediate(shape, dtype)
827
828 def addInputTensor(self, tensor):
829 self.currRegion.addInputTensor(tensor)
830
831 def addOutputTensor(self, tensor):
832 self.currRegion.addOutputTensor(tensor)
833
834 def addOutput(self, shape, dtype):
835 return self.currRegion.addOutput(shape, dtype)
836
837 def addOperator(self, op, inputs, outputs, attributes=None):
838 return self.currRegion.addOperator(op, inputs, outputs, attributes)
839
Jerry Geca7ce0e2023-01-10 17:24:38 +0000840 def addBasicBlock(self, name):
841 self.currRegion.addBasicBlock(name)
842
Jeremy Johnson9b225172021-12-14 16:34:47 +0000843 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000844
845 self.expectedReturnCode = val
846 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000847 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000848
849 def serialize(self):
850
851 builder = self.builder
852
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800853 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000854 Version.Add_Major(builder, TOSA_VERSION[0])
855 Version.Add_Minor(builder, TOSA_VERSION[1])
856 Version.Add_Patch(builder, TOSA_VERSION[2])
857 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800858 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000859
Jerry Ge1eb85042023-01-06 14:19:14 -0800860 fbv_region = TosaSerializer.serializeObjVec(
861 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000862 )
863
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800864 TosaGraph.Start(builder)
865 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800866 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800867 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000868
Eric Kunzee6596402022-06-09 21:27:36 +0000869 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000870 return self.builder.Output()
871
872 def writeJson(self, tosa_filename):
873 """Write a json test file so that it is fairly easy to pick up the test
874 and generate commands for third party tool"""
875 test_desc = dict()
876
877 test_desc["tosa_file"] = tosa_filename
878 ifm_name = []
879 ifm_file = []
880 ofm_name = []
881 ofm_file = []
882
Jerry Ge1eb85042023-01-06 14:19:14 -0800883 for region in self.regions:
884 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000885 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800886 for i in block.inputs:
887 ifm_name.append(i)
888 ifm_file.append(block.tensors[i].placeholderFilename)
889 for o in block.outputs:
890 ofm_name.append(o)
891 # Make up an OFM filename here. One isn't generated until the
892 # reference tool is run, so any name is a good name
893 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000894
895 test_desc["ifm_name"] = ifm_name
896 test_desc["ifm_file"] = ifm_file
897 test_desc["ofm_name"] = ofm_name
898 test_desc["ofm_file"] = ofm_file
899 test_desc["expected_return_code"] = self.expectedReturnCode
900 test_desc["expected_failure"] = self.expectedFailure
901 if self.expectedFailureDesc:
902 test_desc["expected_failure_desc"] = self.expectedFailureDesc
903
904 return json.dumps(test_desc, indent=" ")
905
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100906 def startRegion(self, name, pathPrefix):
907 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800908 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000909
910 @staticmethod
911 def serializeStrVec(builder, vec, start_fcn):
912 fb_strs = [builder.CreateString(i) for i in vec]
913 start_fcn(builder, len(fb_strs))
914 for s in fb_strs[::-1]:
915 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700916 try:
917 return builder.EndVector()
918 except TypeError:
919 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000920
921 @staticmethod
922 def serializeUint8Vec(builder, vec):
923 builder.StartVector(1, len(vec), 8)
924 for v in vec[::-1]:
925 builder.PrependUint8(v)
926 try:
927 return builder.EndVector()
928 except TypeError:
929 return builder.EndVector(len(vec))
930
931 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700932 def serializeInt16Vec(builder, vec):
933 builder.StartVector(2, len(vec), 4)
934 for v in vec[::-1]:
935 builder.PrependInt16(v)
936 try:
937 return builder.EndVector()
938 except TypeError:
939 return builder.EndVector(len(vec))
940
941 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000942 def serializeInt32Vec(builder, vec):
943 builder.StartVector(4, len(vec), 4)
944 for v in vec[::-1]:
945 builder.PrependInt32(v)
946 try:
947 return builder.EndVector()
948 except TypeError:
949 return builder.EndVector(len(vec))
950
951 @staticmethod
952 def serializeFpVec(builder, vec):
953 builder.StartVector(4, len(vec), 4)
954 for v in vec[::-1]:
955 builder.PrependFloat32(v)
956 try:
957 return builder.EndVector()
958 except TypeError:
959 return builder.EndVector(len(vec))
960
961 @staticmethod
962 def serializeObjVec(builder, vec, start_fcn):
963 serialized_vec = []
964 for v in vec[::-1]:
965 serialized_vec.append(v.serialize(builder))
966
967 start_fcn(builder, len(vec))
968 for v in serialized_vec:
969 builder.PrependUOffsetTRelative(v)
970 try:
971 return builder.EndVector()
972 except TypeError:
973 return builder.EndVector(len(vec))
974
975 @staticmethod
976 def toList(val):
977 if isinstance(val, list):
978 return val
979 else:
980 return [val]