blob: 1aadbffcd68c68acaa35e7806c7ebda7e30c1230 [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,
162 accum_dtype,
163 ):
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))
James Ward485a11d2022-08-05 13:48:37 +0100174 self.ints.append((a.AddAccumDtype, accum_dtype))
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 Chong7be71652022-05-10 17:26:20 -0700229 def ReshapeAttribute(self, new_shape):
Kevin Chengfea5a372021-10-11 18:38:47 +0000230 from tosa import ReshapeAttribute as a, Attribute
231
232 self.utype = Attribute.Attribute().ReshapeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800233 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000234
TatWai Chong7be71652022-05-10 17:26:20 -0700235 self.intvecs.append((a.AddNewShape, new_shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000236
TatWai Chong7be71652022-05-10 17:26:20 -0700237 def SliceAttribute(self, start, size):
Kevin Chengfea5a372021-10-11 18:38:47 +0000238 from tosa import SliceAttribute as a, Attribute
239
240 self.utype = Attribute.Attribute().SliceAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800241 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000242
TatWai Chong7be71652022-05-10 17:26:20 -0700243 self.intvecs.append((a.AddStart, start))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800244 self.intvecs.append((a.AddSize, size))
Kevin Chengfea5a372021-10-11 18:38:47 +0000245
246 def TileAttribute(self, multiples):
247 from tosa import TileAttribute as a, Attribute
248
249 self.utype = Attribute.Attribute().TileAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800250 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000251
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800252 self.intvecs.append((a.AddMultiples, multiples))
Kevin Chengfea5a372021-10-11 18:38:47 +0000253
TatWai Chong49b1ca62022-06-10 01:49:13 -0700254 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000255 from tosa import ResizeAttribute as a, Attribute
256
257 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800258 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000259
TatWai Chong49b1ca62022-06-10 01:49:13 -0700260 self.int16vecs.append((a.AddScale, scale))
261 self.int16vecs.append((a.AddOffset, offset))
262 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800263 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000264
James Wardc15f7d52022-12-07 15:38:01 +0000265 def ClampAttribute(self, serializer_builder, minint, maxint, minfp, maxfp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000266 from tosa import ClampAttribute as a, Attribute
267
268 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800269 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000270
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800271 self.ints.append((a.AddMinInt, minint))
272 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000273
James Wardc15f7d52022-12-07 15:38:01 +0000274 # min/max float attributes serialized as uint8 vectors
275 minfp_bytes = struct.pack("<f", minfp)
276 maxfp_bytes = struct.pack("<f", maxfp)
277 serialized_minfp_bytes = ts.TosaSerializer.serializeUint8Vec(
278 serializer_builder, minfp_bytes
279 )
280 serialized_maxfp_bytes = ts.TosaSerializer.serializeUint8Vec(
281 serializer_builder, maxfp_bytes
282 )
283
284 self.floats.append((a.AddMinFp, serialized_minfp_bytes))
285 self.floats.append((a.AddMaxFp, serialized_maxfp_bytes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000286
287 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000288 self,
289 input_zp,
290 output_zp,
291 multiplier,
292 shift,
293 scale32,
294 double_round,
295 per_channel,
296 input_unsigned,
297 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000298 ):
299 from tosa import RescaleAttribute as a, Attribute
300
301 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800302 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000303
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800304 self.ints.append((a.AddInputZp, input_zp))
305 self.ints.append((a.AddOutputZp, output_zp))
306 self.intvecs.append((a.AddMultiplier, multiplier))
307 self.intvecs.append((a.AddShift, shift))
308 self.bools.append((a.AddScale32, scale32))
309 self.bools.append((a.AddDoubleRound, double_round))
310 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000311 self.bools.append((a.AddInputUnsigned, input_unsigned))
312 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000313
314 def MulAttribute(self, shift):
315 from tosa import MulAttribute as a, Attribute
316
317 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800318 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000319
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800320 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000321
322 def ArithmeticRightShiftAttribute(self, round):
323 from tosa import ArithmeticRightShiftAttribute as a, Attribute
324
325 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
326 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800327 a.Start,
328 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000329 )
330
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800331 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000332
Kevin Chengfea5a372021-10-11 18:38:47 +0000333 def CondIfAttribute(self, then_branch, else_branch):
334 from tosa import CondIfAttribute as a, Attribute
335
336 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800337 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000338
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800339 self.strings.append((a.AddThenBranch, then_branch))
340 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000341
342 def WhileLoopAttribute(self, cond_branch, body_branch):
343 from tosa import WhileLoopAttribute as a, Attribute
344
345 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800346 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000347
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800348 self.strings.append((a.AddCondBranch, cond_branch))
349 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000350
TatWai Chong7be71652022-05-10 17:26:20 -0700351 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700352 from tosa import TransposeAttribute as a, Attribute
353
354 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800355 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700356
TatWai Chong7be71652022-05-10 17:26:20 -0700357 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700358
359 def TableAttribute(self, table):
360 from tosa import TableAttribute as a, Attribute
361
362 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800363 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700364
Jerry Gee7b8eb72023-09-15 17:19:50 +0000365 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000366
James Wardea00fd02023-01-20 16:03:50 +0000367 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000368 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000369
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000370 self.utype = Attribute.Attribute().MatMulAttribute
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.AddAZp, A_zp))
374 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000375
James Wardea00fd02023-01-20 16:03:50 +0000376 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000377 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000378
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000379 self.utype = Attribute.Attribute().FullyConnectedAttribute
380 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000381
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000382 self.ints.append((a.AddInputZp, input_zp))
383 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000384
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000385 def NegateAttribute(self, input1_zp, output_zp):
386 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000387
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000388 self.utype = Attribute.Attribute().NegateAttribute
389 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000390
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000391 self.ints.append((a.AddInput1Zp, input1_zp))
392 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000393
Tai Lyf5dfad12023-11-15 21:09:58 +0000394 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000395 from tosa import FFTAttribute as a, Attribute
396
397 self.utype = Attribute.Attribute().FFTAttribute
398 self.optFcns = (a.Start, a.End)
399
400 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000401 self.bools.append((a.AddLocalBound, local_bound))
402
403 def RFFTAttribute(self, local_bound):
404 from tosa import RFFTAttribute as a, Attribute
405
406 self.utype = Attribute.Attribute().RFFTAttribute
407 self.optFcns = (a.Start, a.End)
408
409 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000410
Kevin Chengfea5a372021-10-11 18:38:47 +0000411
412class TosaSerializerTensor:
413 def __init__(
414 self,
415 name,
416 shape,
417 dtype,
418 data=None,
419 placeholderFilename=None,
420 ):
421 self.name = name
422
423 if isinstance(shape, np.ndarray):
424 shape = shape.astype(int).tolist()
425 shape = list(map(int, shape))
426
427 self.shape = shape
428 self.dtype = dtype
429
Won Jeona029f1f2023-12-29 22:43:11 +0000430 if (
431 dtype == DType.FP32
432 or dtype == DType.BF16
433 or dtype == DType.FP8E4M3
434 or dtype == DType.FP8E5M2
435 ):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100436 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100437 elif dtype == DType.FP16:
438 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100439 else:
440 fntype = int
441
Kevin Chengfea5a372021-10-11 18:38:47 +0000442 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100443 data = data.flatten().astype(fntype).tolist()
444 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000445 self.data = data
446 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100447 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000448 self.data = data
449 else:
450 self.data = None
451
452 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000453 # process and are written to disk, but are considered input tensors by the
454 # network so they do not appear in the TOSA serialiazation. However, if we
455 # want to form a unit test around these input tensors, we can get the filename
456 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000457 self.placeholderFilename = placeholderFilename
458
459 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800460 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000461 self.name,
462 self.shape,
463 DTypeNames[self.dtype],
464 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800465 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000466
467 def setDtype(self, dtype):
468 self.dtype = dtype
469
470 def serialize(self, builder):
471 fb_name = builder.CreateString(self.name)
472 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
473 if self.data:
474 u8_data = list()
475 # little endianess
476 if self.dtype == DType.BOOL:
477 for val in self.data:
478 val_u8 = np.uint8(val)
479 u8_data.append(val_u8)
480 elif self.dtype == DType.INT4:
481 in_size = len(self.data)
482 out_size = (in_size + 1) // 2
483 for i in range(out_size):
484 val_0 = self.data[2 * i]
485 if (2 * i + 1) < in_size:
486 val_1 = self.data[2 * i + 1]
487 else:
488 val_1 = 0
489 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
490 val_u8 = np.uint8(val_i8)
491 u8_data.append(val_u8)
492 elif self.dtype == DType.INT8:
493 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700494 val_u8 = np.array(val).astype(dtype=np.uint8)
Kevin Chengfea5a372021-10-11 18:38:47 +0000495 u8_data.append(val_u8)
496 elif self.dtype == DType.INT16:
497 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700498 val_u16 = np.array(val).astype(dtype=np.uint16)
Kevin Chengfea5a372021-10-11 18:38:47 +0000499 b0 = val_u16 & ByteMask
500 b1 = (val_u16 >> np.uint16(8)) & ByteMask
501 u8_data.extend([b0, b1])
502 elif self.dtype == DType.INT32:
503 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700504 val_u32 = np.array(val).astype(dtype=np.uint32)
Kevin Chengfea5a372021-10-11 18:38:47 +0000505 b0 = val_u32 & ByteMask
506 b1 = (val_u32 >> np.uint32(8)) & ByteMask
507 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700508 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000509 u8_data.extend([b0, b1, b2, b3])
Won Jeon7c22d772024-01-23 07:46:08 +0000510 elif self.dtype == DType.INT48:
Kevin Chengfea5a372021-10-11 18:38:47 +0000511 for val in self.data:
512 val_u64 = np.uint64(val)
513 b0 = val_u64 & ByteMask
514 b1 = (val_u64 >> np.uint64(8)) & ByteMask
515 b2 = (val_u64 >> np.uint64(16)) & ByteMask
516 b3 = (val_u64 >> np.uint64(24)) & ByteMask
517 b4 = (val_u64 >> np.uint64(32)) & ByteMask
518 b5 = (val_u64 >> np.uint64(40)) & ByteMask
519 u8_data.extend([b0, b1, b2, b3, b4, b5])
Won Jeon7c22d772024-01-23 07:46:08 +0000520 elif self.dtype == DType.SHAPE:
521 for val in self.data:
522 val_u64 = np.uint64(val)
523 b0 = val_u64 & ByteMask
524 b1 = (val_u64 >> np.uint64(8)) & ByteMask
525 b2 = (val_u64 >> np.uint64(16)) & ByteMask
526 b3 = (val_u64 >> np.uint64(24)) & ByteMask
527 b4 = (val_u64 >> np.uint64(32)) & ByteMask
528 b5 = (val_u64 >> np.uint64(40)) & ByteMask
529 b6 = (val_u64 >> np.uint64(48)) & ByteMask
530 b7 = (val_u64 >> np.uint64(56)) & ByteMask
531 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
James Ward485a11d2022-08-05 13:48:37 +0100532 elif self.dtype == DType.FP16:
533 np_arr = np.array(self.data, dtype=np.float16)
534 u8_data.extend(np_arr.view(np.uint8))
Won Jeona029f1f2023-12-29 22:43:11 +0000535 elif (
536 self.dtype == DType.FP32
537 or self.dtype == DType.BF16
538 or self.dtype == DType.FP8E4M3
539 or self.dtype == DType.FP8E5M2
540 ):
James Wardc15f7d52022-12-07 15:38:01 +0000541 # for val in self.data:
542 # b = struct.pack("!f", val)
543 # u8_data.extend([b[3], b[2], b[1], b[0]])
544 np_arr = np.array(self.data, dtype=np.float32)
545 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100546 elif self.dtype == TosaDType.DType:
547 # Serialize DType enum data as uint8 bytes
548 for val in self.data:
549 np_arr = np.array(self.data, dtype=np.uint32)
550 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000551 else:
552 raise Exception(
553 "unsupported data type {}".format(DTypeNames[self.dtype])
554 )
555 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
556
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800557 TosaTensor.Start(builder)
558 TosaTensor.AddName(builder, fb_name)
559 TosaTensor.AddShape(builder, fb_shapes)
560 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000561 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800562 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000563
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800564 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000565
566
567class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000568 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000569 self.op = op
570 self.attributes = attributes
571 self.inputs = TosaSerializer.toList(inputs)
572 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000573
574 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800575 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000576
577 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800578 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000579 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800580 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000581
Jerry Ge1eb85042023-01-06 14:19:14 -0800582 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000583
584 def serialize(self, builder):
585 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800586 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000587 )
588 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800589 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000590 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000591 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000592 if self.attributes is not None:
593 fb_attributes = self.attributes.serialize(builder)
594
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800595 TosaOperator.Start(builder)
596 TosaOperator.AddOp(builder, self.op)
597 TosaOperator.AddInputs(builder, fb_inputs)
598 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000599 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800600 TosaOperator.AddAttributeType(builder, self.attributes.utype)
601 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000602
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800603 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000604
605
606class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000607 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000608 self.name = name
609 self.operators = []
610
611 # Dict assures uniqueness, but allows us to look up by name
612 self.tensors = dict()
613
614 self.inputs = []
615 self.outputs = []
616
617 def addTensor(
618 self,
619 name,
620 shape,
621 dtype,
622 data=None,
623 placeholderFilename=None,
624 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000625 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000626 self.tensors[name] = TosaSerializerTensor(
627 name, shape, dtype, data, placeholderFilename
628 )
629
630 return self.tensors[name]
631
632 def addInput(self, name):
633 self.inputs.append(name)
634
635 def addOutput(self, name):
636 self.outputs.append(name)
637
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000638 def addOperator(self, op, inputs, outputs, attributes=None):
639 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000640
641 def serialize(self, builder):
642 fb_name = builder.CreateString(self.name)
643 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800644 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000645 )
646 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800647 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000648 )
649 fbv_tensors = TosaSerializer.serializeObjVec(
650 builder,
651 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800652 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000653 )
654 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800655 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000656 )
657
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800658 TosaBasicBlock.Start(builder)
659 TosaBasicBlock.AddName(builder, fb_name)
660 TosaBasicBlock.AddInputs(builder, fbv_inputs)
661 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
662 TosaBasicBlock.AddTensors(builder, fbv_tensors)
663 TosaBasicBlock.AddOperators(builder, fbv_operators)
664 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000665
666
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100667# How CONSTs are treated in the flatbuffer
668@unique
669class ConstMode(IntEnum):
670 EMBED = 0
671 EMBED_DUMP = 1
672 INPUTS = 2
673
674
Jerry Ge1eb85042023-01-06 14:19:14 -0800675class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100676 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800677 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000678 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000679 self.currInputIdx = 0
680 self.currConstIdx = 0
681 self.currLayerIdx = 1
682 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800683 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100684 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000685
Jerry Geca7ce0e2023-01-10 17:24:38 +0000686 def addBasicBlock(self, name):
687 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800688 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000689
Jerry Ge1eb85042023-01-06 14:19:14 -0800690 def serialize(self, builder):
691 fb_name = builder.CreateString(self.name)
692 fbv_basicBlocks = TosaSerializer.serializeObjVec(
693 builder, self.basicBlocks, TosaRegion.StartBlocksVector
694 )
695
696 TosaRegion.Start(builder)
697 TosaRegion.AddName(builder, fb_name)
698 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
699 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000700
701 def addPlaceholder(self, shape, dtype, vals):
702 if not self.currBasicBlock:
703 raise Exception("addTensor called without valid basic block")
704
705 name = "input-{}".format(self.currInputIdx)
706 filename = "{}.npy".format(name)
707 self.currInputIdx = self.currInputIdx + 1
708
709 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
710 # This is always an input to the block
711 self.currBasicBlock.addInput(name)
712
713 if vals is not None:
714 np.save(os.path.join(self.pathPrefix, filename), vals, False)
715
716 return tens
717
Jerry Ge53ceb482023-08-14 20:15:10 +0000718 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000719 if not self.currBasicBlock:
720 raise Exception("addTensor called without valid basic block")
721
Jerry Ge53ceb482023-08-14 20:15:10 +0000722 if name is None:
723 name = "const-{}".format(self.currInputIdx)
724 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000725
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100726 if self.constMode == ConstMode.INPUTS:
727 # Save const as input file
728 filename = "{}.npy".format(name)
729 tensor_vals = None
730 self.currBasicBlock.addInput(name)
731 else:
732 # Embed const in flatbuffer
733 filename = None
734 tensor_vals = vals
735
736 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000737 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000738 if dtype == DType.SHAPE:
739 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
740 else:
741 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000742
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100743 # Save the const data to file for debug or as input files
744 if vals is not None and self.constMode in [
745 ConstMode.EMBED_DUMP,
746 ConstMode.INPUTS,
747 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100748 filename = "{}.npy".format(name)
749 np.save(os.path.join(self.pathPrefix, filename), vals, False)
750
Kevin Chengfea5a372021-10-11 18:38:47 +0000751 return tens
752
753 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000754 if not self.currBasicBlock:
755 raise Exception("addTensor called without valid basic block")
756
757 name = "layer-{}".format(self.currLayerIdx)
758 self.currLayerIdx = self.currLayerIdx + 1
759
760 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
761
762 return tens
763
764 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700765 self.currBasicBlock.addTensor(
766 tensor.name,
767 tensor.shape,
768 tensor.dtype,
769 tensor.data,
770 tensor.placeholderFilename,
771 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000772 self.currBasicBlock.addInput(tensor.name)
773
774 def addOutputTensor(self, tensor):
775 self.currBasicBlock.addOutput(tensor.name)
776
777 def addOutput(self, shape, dtype):
778 if not self.currBasicBlock:
779 raise Exception("addTensor called without valid basic block")
780
781 name = "result-{}".format(self.currResultIdx)
782 self.currResultIdx = self.currResultIdx + 1
783
784 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
785 self.currBasicBlock.addOutput(name)
786 return tens
787
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000788 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000789 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000790 raise Exception("Use addConstTensor() to add CONST ops")
791
792 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000793 op,
794 inputs,
795 outputs,
796 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000797 )
798
Jerry Ge1eb85042023-01-06 14:19:14 -0800799
800@unique
801class TensorDir(IntEnum):
802 PLACEHOLDER = 0
803 CONST = 1
804 INTERMEDIATE = 2
805 RESULT = 3
806
807
808class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100809 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800810 self.builder = flatbuffers.Builder(0)
811
Jerry Ge1eb85042023-01-06 14:19:14 -0800812 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100813 self.constMode = constMode
814
815 self.regions = []
816 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800817
Jerry Geca7ce0e2023-01-10 17:24:38 +0000818 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800819
820 # Is this an illegal test that is expected to fail?
821 self.expectedReturnCode = 0
822 self.expectedFailure = False
823 self.expectedFailureDesc = ""
824
825 def __str__(self):
826 concatString = ""
827 for region in self.regions:
828 concatString = concatString + str(region)
829 return concatString
830
831 def addPlaceholder(self, shape, dtype, vals):
832 return self.currRegion.addPlaceholder(shape, dtype, vals)
833
Jerry Ge53ceb482023-08-14 20:15:10 +0000834 def addConst(self, shape, dtype, vals, name=None):
835 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800836
837 def addIntermediate(self, shape, dtype):
838 return self.currRegion.addIntermediate(shape, dtype)
839
840 def addInputTensor(self, tensor):
841 self.currRegion.addInputTensor(tensor)
842
843 def addOutputTensor(self, tensor):
844 self.currRegion.addOutputTensor(tensor)
845
846 def addOutput(self, shape, dtype):
847 return self.currRegion.addOutput(shape, dtype)
848
849 def addOperator(self, op, inputs, outputs, attributes=None):
850 return self.currRegion.addOperator(op, inputs, outputs, attributes)
851
Jerry Geca7ce0e2023-01-10 17:24:38 +0000852 def addBasicBlock(self, name):
853 self.currRegion.addBasicBlock(name)
854
Jeremy Johnson9b225172021-12-14 16:34:47 +0000855 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000856
857 self.expectedReturnCode = val
858 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000859 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000860
861 def serialize(self):
862
863 builder = self.builder
864
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800865 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000866 Version.Add_Major(builder, TOSA_VERSION[0])
867 Version.Add_Minor(builder, TOSA_VERSION[1])
868 Version.Add_Patch(builder, TOSA_VERSION[2])
869 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800870 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000871
Jerry Ge1eb85042023-01-06 14:19:14 -0800872 fbv_region = TosaSerializer.serializeObjVec(
873 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000874 )
875
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800876 TosaGraph.Start(builder)
877 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800878 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800879 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000880
Eric Kunzee6596402022-06-09 21:27:36 +0000881 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000882 return self.builder.Output()
883
884 def writeJson(self, tosa_filename):
885 """Write a json test file so that it is fairly easy to pick up the test
886 and generate commands for third party tool"""
887 test_desc = dict()
888
889 test_desc["tosa_file"] = tosa_filename
890 ifm_name = []
891 ifm_file = []
892 ofm_name = []
893 ofm_file = []
894
Jerry Ge1eb85042023-01-06 14:19:14 -0800895 for region in self.regions:
896 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000897 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800898 for i in block.inputs:
899 ifm_name.append(i)
900 ifm_file.append(block.tensors[i].placeholderFilename)
901 for o in block.outputs:
902 ofm_name.append(o)
903 # Make up an OFM filename here. One isn't generated until the
904 # reference tool is run, so any name is a good name
905 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000906
907 test_desc["ifm_name"] = ifm_name
908 test_desc["ifm_file"] = ifm_file
909 test_desc["ofm_name"] = ofm_name
910 test_desc["ofm_file"] = ofm_file
911 test_desc["expected_return_code"] = self.expectedReturnCode
912 test_desc["expected_failure"] = self.expectedFailure
913 if self.expectedFailureDesc:
914 test_desc["expected_failure_desc"] = self.expectedFailureDesc
915
916 return json.dumps(test_desc, indent=" ")
917
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100918 def startRegion(self, name, pathPrefix):
919 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800920 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000921
922 @staticmethod
923 def serializeStrVec(builder, vec, start_fcn):
924 fb_strs = [builder.CreateString(i) for i in vec]
925 start_fcn(builder, len(fb_strs))
926 for s in fb_strs[::-1]:
927 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700928 try:
929 return builder.EndVector()
930 except TypeError:
931 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000932
933 @staticmethod
934 def serializeUint8Vec(builder, vec):
935 builder.StartVector(1, len(vec), 8)
936 for v in vec[::-1]:
937 builder.PrependUint8(v)
938 try:
939 return builder.EndVector()
940 except TypeError:
941 return builder.EndVector(len(vec))
942
943 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700944 def serializeInt16Vec(builder, vec):
945 builder.StartVector(2, len(vec), 4)
946 for v in vec[::-1]:
947 builder.PrependInt16(v)
948 try:
949 return builder.EndVector()
950 except TypeError:
951 return builder.EndVector(len(vec))
952
953 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000954 def serializeInt32Vec(builder, vec):
955 builder.StartVector(4, len(vec), 4)
956 for v in vec[::-1]:
957 builder.PrependInt32(v)
958 try:
959 return builder.EndVector()
960 except TypeError:
961 return builder.EndVector(len(vec))
962
963 @staticmethod
964 def serializeFpVec(builder, vec):
965 builder.StartVector(4, len(vec), 4)
966 for v in vec[::-1]:
967 builder.PrependFloat32(v)
968 try:
969 return builder.EndVector()
970 except TypeError:
971 return builder.EndVector(len(vec))
972
973 @staticmethod
974 def serializeObjVec(builder, vec, start_fcn):
975 serialized_vec = []
976 for v in vec[::-1]:
977 serialized_vec.append(v.serialize(builder))
978
979 start_fcn(builder, len(vec))
980 for v in serialized_vec:
981 builder.PrependUOffsetTRelative(v)
982 try:
983 return builder.EndVector()
984 except TypeError:
985 return builder.EndVector(len(vec))
986
987 @staticmethod
988 def toList(val):
989 if isinstance(val, list):
990 return val
991 else:
992 return [val]