blob: cbef086fe414cfdbba7dce51e5d1ff5526b5b95d [file] [log] [blame]
Jerry Ge1eb85042023-01-06 14:19:14 -08001# Copyright (c) 2020-2023, ARM Limited.
Kevin Chengfea5a372021-10-11 18:38:47 +00002#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Kevin Chengfea5a372021-10-11 18:38:47 +000015import os
James Wardc15f7d52022-12-07 15:38:01 +000016import struct
17import serializer.tosa_serializer as ts
Kevin Chengfea5a372021-10-11 18:38:47 +000018import json
19import flatbuffers
20import numpy as np
Jeremy Johnson9b225172021-12-14 16:34:47 +000021from enum import IntEnum, unique
Kevin Chengfea5a372021-10-11 18:38:47 +000022from tosa import (
23 TosaGraph,
Jerry Ge1eb85042023-01-06 14:19:14 -080024 TosaRegion,
Kevin Chengfea5a372021-10-11 18:38:47 +000025 TosaBasicBlock,
26 TosaTensor,
27 TosaOperator,
Kevin Chengfea5a372021-10-11 18:38:47 +000028 Version,
29)
Jeremy Johnson9b225172021-12-14 16:34:47 +000030import tosa.DType as TosaDType
31import tosa.Op as TosaOp
Kevin Chengfea5a372021-10-11 18:38:47 +000032
Kevin Chenge6563f52021-10-20 12:12:02 -070033# Keep version number in sync with the version default value with schema/tosa.fbs
Kevin Chengb97cb1d2021-10-14 11:53:39 -070034TOSA_VERSION_MAJOR = 0
Eric Kunze8a270432023-06-01 20:08:17 +000035TOSA_VERSION_MINOR = 80
Eric Kunzee29a1cd2023-12-14 19:44:11 +000036TOSA_VERSION_PATCH = 1
Eric Kunze2d333852023-09-12 17:04:55 -070037TOSA_VERSION_DRAFT = False
Jeremy Johnson9b225172021-12-14 16:34:47 +000038TOSA_VERSION = [
39 TOSA_VERSION_MAJOR,
40 TOSA_VERSION_MINOR,
41 TOSA_VERSION_PATCH,
42 TOSA_VERSION_DRAFT,
43]
Eric Kunzee6596402022-06-09 21:27:36 +000044
45# File identifier needs to be kept in sync with schema/tosa.fbs
46TOSA_GRAPH_IDENTIFIER = b"\x54\x4F\x53\x41"
47
Kevin Chengfea5a372021-10-11 18:38:47 +000048# With the way flatc generates its python types, there is no programatic way
49# to get string names for the integer types. Manually maintain a string table
50# here.
Jeremy Johnson9b225172021-12-14 16:34:47 +000051DType = TosaDType.DType()
Kevin Chengfea5a372021-10-11 18:38:47 +000052DTypeNames = [
53 "UNKNOWN",
54 "BOOL",
55 "UINT8",
56 "INT4",
57 "INT8",
58 "INT16",
59 "INT32",
60 "INT48",
Jeremy Johnsone1072a92022-09-27 12:44:11 +010061 "FP32",
Jeremy Johnson41027732022-05-25 17:52:29 +010062 "UINT16",
James Ward485a11d2022-08-05 13:48:37 +010063 "FP16",
James Ward34a62792022-10-18 17:27:40 +010064 "BF16",
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 Lycce787e2023-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 Lycce787e2023-11-15 21:09:58 +0000185 self.bools.append((a.AddLocalBound, local_bound))
Kevin Chengfea5a372021-10-11 18:38:47 +0000186
Tai Lycce787e2023-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 Lycce787e2023-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 Ward0925d402023-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 Ward0925d402023-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 Geb4d75022023-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 Lycce787e2023-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 Lycce787e2023-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
James Ward34a62792022-10-18 17:27:40 +0100428 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 Jeon187af0d2023-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 Jeon187af0d2023-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 Jeon187af0d2023-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 Jeon1adc5d02023-08-12 11:16:05 -0700503 elif self.dtype == DType.INT48 or self.dtype == DType.SHAPE:
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])
James Ward485a11d2022-08-05 13:48:37 +0100513 elif self.dtype == DType.FP16:
514 np_arr = np.array(self.data, dtype=np.float16)
515 u8_data.extend(np_arr.view(np.uint8))
James Ward34a62792022-10-18 17:27:40 +0100516 elif self.dtype == DType.FP32 or self.dtype == DType.BF16:
James Wardc15f7d52022-12-07 15:38:01 +0000517 # for val in self.data:
518 # b = struct.pack("!f", val)
519 # u8_data.extend([b[3], b[2], b[1], b[0]])
520 np_arr = np.array(self.data, dtype=np.float32)
521 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100522 elif self.dtype == TosaDType.DType:
523 # Serialize DType enum data as uint8 bytes
524 for val in self.data:
525 np_arr = np.array(self.data, dtype=np.uint32)
526 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000527 else:
528 raise Exception(
529 "unsupported data type {}".format(DTypeNames[self.dtype])
530 )
531 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
532
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800533 TosaTensor.Start(builder)
534 TosaTensor.AddName(builder, fb_name)
535 TosaTensor.AddShape(builder, fb_shapes)
536 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000537 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800538 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000539
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800540 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000541
542
543class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000544 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000545 self.op = op
546 self.attributes = attributes
547 self.inputs = TosaSerializer.toList(inputs)
548 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000549
550 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800551 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000552
553 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800554 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000555 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800556 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000557
Jerry Ge1eb85042023-01-06 14:19:14 -0800558 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000559
560 def serialize(self, builder):
561 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800562 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000563 )
564 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800565 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000566 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000567 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000568 if self.attributes is not None:
569 fb_attributes = self.attributes.serialize(builder)
570
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800571 TosaOperator.Start(builder)
572 TosaOperator.AddOp(builder, self.op)
573 TosaOperator.AddInputs(builder, fb_inputs)
574 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000575 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800576 TosaOperator.AddAttributeType(builder, self.attributes.utype)
577 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000578
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800579 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000580
581
582class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000583 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000584 self.name = name
585 self.operators = []
586
587 # Dict assures uniqueness, but allows us to look up by name
588 self.tensors = dict()
589
590 self.inputs = []
591 self.outputs = []
592
593 def addTensor(
594 self,
595 name,
596 shape,
597 dtype,
598 data=None,
599 placeholderFilename=None,
600 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000601 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000602 self.tensors[name] = TosaSerializerTensor(
603 name, shape, dtype, data, placeholderFilename
604 )
605
606 return self.tensors[name]
607
608 def addInput(self, name):
609 self.inputs.append(name)
610
611 def addOutput(self, name):
612 self.outputs.append(name)
613
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000614 def addOperator(self, op, inputs, outputs, attributes=None):
615 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000616
617 def serialize(self, builder):
618 fb_name = builder.CreateString(self.name)
619 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800620 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000621 )
622 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800623 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000624 )
625 fbv_tensors = TosaSerializer.serializeObjVec(
626 builder,
627 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800628 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000629 )
630 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800631 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000632 )
633
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800634 TosaBasicBlock.Start(builder)
635 TosaBasicBlock.AddName(builder, fb_name)
636 TosaBasicBlock.AddInputs(builder, fbv_inputs)
637 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
638 TosaBasicBlock.AddTensors(builder, fbv_tensors)
639 TosaBasicBlock.AddOperators(builder, fbv_operators)
640 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000641
642
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100643# How CONSTs are treated in the flatbuffer
644@unique
645class ConstMode(IntEnum):
646 EMBED = 0
647 EMBED_DUMP = 1
648 INPUTS = 2
649
650
Jerry Ge1eb85042023-01-06 14:19:14 -0800651class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100652 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800653 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000654 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000655 self.currInputIdx = 0
656 self.currConstIdx = 0
657 self.currLayerIdx = 1
658 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800659 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100660 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000661
Jerry Geca7ce0e2023-01-10 17:24:38 +0000662 def addBasicBlock(self, name):
663 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800664 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000665
Jerry Ge1eb85042023-01-06 14:19:14 -0800666 def serialize(self, builder):
667 fb_name = builder.CreateString(self.name)
668 fbv_basicBlocks = TosaSerializer.serializeObjVec(
669 builder, self.basicBlocks, TosaRegion.StartBlocksVector
670 )
671
672 TosaRegion.Start(builder)
673 TosaRegion.AddName(builder, fb_name)
674 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
675 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000676
677 def addPlaceholder(self, shape, dtype, vals):
678 if not self.currBasicBlock:
679 raise Exception("addTensor called without valid basic block")
680
681 name = "input-{}".format(self.currInputIdx)
682 filename = "{}.npy".format(name)
683 self.currInputIdx = self.currInputIdx + 1
684
685 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
686 # This is always an input to the block
687 self.currBasicBlock.addInput(name)
688
689 if vals is not None:
690 np.save(os.path.join(self.pathPrefix, filename), vals, False)
691
692 return tens
693
Jerry Ge53ceb482023-08-14 20:15:10 +0000694 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000695 if not self.currBasicBlock:
696 raise Exception("addTensor called without valid basic block")
697
Jerry Ge53ceb482023-08-14 20:15:10 +0000698 if name is None:
699 name = "const-{}".format(self.currInputIdx)
700 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000701
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100702 if self.constMode == ConstMode.INPUTS:
703 # Save const as input file
704 filename = "{}.npy".format(name)
705 tensor_vals = None
706 self.currBasicBlock.addInput(name)
707 else:
708 # Embed const in flatbuffer
709 filename = None
710 tensor_vals = vals
711
712 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000713 # Add the operator now
Jeremy Johnson9b225172021-12-14 16:34:47 +0000714 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000715
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100716 # Save the const data to file for debug or as input files
717 if vals is not None and self.constMode in [
718 ConstMode.EMBED_DUMP,
719 ConstMode.INPUTS,
720 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100721 filename = "{}.npy".format(name)
722 np.save(os.path.join(self.pathPrefix, filename), vals, False)
723
Kevin Chengfea5a372021-10-11 18:38:47 +0000724 return tens
725
726 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000727 if not self.currBasicBlock:
728 raise Exception("addTensor called without valid basic block")
729
730 name = "layer-{}".format(self.currLayerIdx)
731 self.currLayerIdx = self.currLayerIdx + 1
732
733 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
734
735 return tens
736
737 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700738 self.currBasicBlock.addTensor(
739 tensor.name,
740 tensor.shape,
741 tensor.dtype,
742 tensor.data,
743 tensor.placeholderFilename,
744 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000745 self.currBasicBlock.addInput(tensor.name)
746
747 def addOutputTensor(self, tensor):
748 self.currBasicBlock.addOutput(tensor.name)
749
750 def addOutput(self, shape, dtype):
751 if not self.currBasicBlock:
752 raise Exception("addTensor called without valid basic block")
753
754 name = "result-{}".format(self.currResultIdx)
755 self.currResultIdx = self.currResultIdx + 1
756
757 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
758 self.currBasicBlock.addOutput(name)
759 return tens
760
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000761 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000762 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000763 raise Exception("Use addConstTensor() to add CONST ops")
764
765 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000766 op,
767 inputs,
768 outputs,
769 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000770 )
771
Jerry Ge1eb85042023-01-06 14:19:14 -0800772
773@unique
774class TensorDir(IntEnum):
775 PLACEHOLDER = 0
776 CONST = 1
777 INTERMEDIATE = 2
778 RESULT = 3
779
780
781class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100782 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800783 self.builder = flatbuffers.Builder(0)
784
Jerry Ge1eb85042023-01-06 14:19:14 -0800785 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100786 self.constMode = constMode
787
788 self.regions = []
789 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800790
Jerry Geca7ce0e2023-01-10 17:24:38 +0000791 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800792
793 # Is this an illegal test that is expected to fail?
794 self.expectedReturnCode = 0
795 self.expectedFailure = False
796 self.expectedFailureDesc = ""
797
798 def __str__(self):
799 concatString = ""
800 for region in self.regions:
801 concatString = concatString + str(region)
802 return concatString
803
804 def addPlaceholder(self, shape, dtype, vals):
805 return self.currRegion.addPlaceholder(shape, dtype, vals)
806
Jerry Ge53ceb482023-08-14 20:15:10 +0000807 def addConst(self, shape, dtype, vals, name=None):
808 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800809
810 def addIntermediate(self, shape, dtype):
811 return self.currRegion.addIntermediate(shape, dtype)
812
813 def addInputTensor(self, tensor):
814 self.currRegion.addInputTensor(tensor)
815
816 def addOutputTensor(self, tensor):
817 self.currRegion.addOutputTensor(tensor)
818
819 def addOutput(self, shape, dtype):
820 return self.currRegion.addOutput(shape, dtype)
821
822 def addOperator(self, op, inputs, outputs, attributes=None):
823 return self.currRegion.addOperator(op, inputs, outputs, attributes)
824
Jerry Geca7ce0e2023-01-10 17:24:38 +0000825 def addBasicBlock(self, name):
826 self.currRegion.addBasicBlock(name)
827
Jeremy Johnson9b225172021-12-14 16:34:47 +0000828 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000829
830 self.expectedReturnCode = val
831 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000832 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000833
834 def serialize(self):
835
836 builder = self.builder
837
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800838 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000839 Version.Add_Major(builder, TOSA_VERSION[0])
840 Version.Add_Minor(builder, TOSA_VERSION[1])
841 Version.Add_Patch(builder, TOSA_VERSION[2])
842 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800843 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000844
Jerry Ge1eb85042023-01-06 14:19:14 -0800845 fbv_region = TosaSerializer.serializeObjVec(
846 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000847 )
848
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800849 TosaGraph.Start(builder)
850 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800851 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800852 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000853
Eric Kunzee6596402022-06-09 21:27:36 +0000854 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000855 return self.builder.Output()
856
857 def writeJson(self, tosa_filename):
858 """Write a json test file so that it is fairly easy to pick up the test
859 and generate commands for third party tool"""
860 test_desc = dict()
861
862 test_desc["tosa_file"] = tosa_filename
863 ifm_name = []
864 ifm_file = []
865 ofm_name = []
866 ofm_file = []
867
Jerry Ge1eb85042023-01-06 14:19:14 -0800868 for region in self.regions:
869 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000870 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800871 for i in block.inputs:
872 ifm_name.append(i)
873 ifm_file.append(block.tensors[i].placeholderFilename)
874 for o in block.outputs:
875 ofm_name.append(o)
876 # Make up an OFM filename here. One isn't generated until the
877 # reference tool is run, so any name is a good name
878 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000879
880 test_desc["ifm_name"] = ifm_name
881 test_desc["ifm_file"] = ifm_file
882 test_desc["ofm_name"] = ofm_name
883 test_desc["ofm_file"] = ofm_file
884 test_desc["expected_return_code"] = self.expectedReturnCode
885 test_desc["expected_failure"] = self.expectedFailure
886 if self.expectedFailureDesc:
887 test_desc["expected_failure_desc"] = self.expectedFailureDesc
888
889 return json.dumps(test_desc, indent=" ")
890
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100891 def startRegion(self, name, pathPrefix):
892 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800893 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000894
895 @staticmethod
896 def serializeStrVec(builder, vec, start_fcn):
897 fb_strs = [builder.CreateString(i) for i in vec]
898 start_fcn(builder, len(fb_strs))
899 for s in fb_strs[::-1]:
900 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700901 try:
902 return builder.EndVector()
903 except TypeError:
904 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000905
906 @staticmethod
907 def serializeUint8Vec(builder, vec):
908 builder.StartVector(1, len(vec), 8)
909 for v in vec[::-1]:
910 builder.PrependUint8(v)
911 try:
912 return builder.EndVector()
913 except TypeError:
914 return builder.EndVector(len(vec))
915
916 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700917 def serializeInt16Vec(builder, vec):
918 builder.StartVector(2, len(vec), 4)
919 for v in vec[::-1]:
920 builder.PrependInt16(v)
921 try:
922 return builder.EndVector()
923 except TypeError:
924 return builder.EndVector(len(vec))
925
926 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000927 def serializeInt32Vec(builder, vec):
928 builder.StartVector(4, len(vec), 4)
929 for v in vec[::-1]:
930 builder.PrependInt32(v)
931 try:
932 return builder.EndVector()
933 except TypeError:
934 return builder.EndVector(len(vec))
935
936 @staticmethod
937 def serializeFpVec(builder, vec):
938 builder.StartVector(4, len(vec), 4)
939 for v in vec[::-1]:
940 builder.PrependFloat32(v)
941 try:
942 return builder.EndVector()
943 except TypeError:
944 return builder.EndVector(len(vec))
945
946 @staticmethod
947 def serializeObjVec(builder, vec, start_fcn):
948 serialized_vec = []
949 for v in vec[::-1]:
950 serialized_vec.append(v.serialize(builder))
951
952 start_fcn(builder, len(vec))
953 for v in serialized_vec:
954 builder.PrependUOffsetTRelative(v)
955 try:
956 return builder.EndVector()
957 except TypeError:
958 return builder.EndVector(len(vec))
959
960 @staticmethod
961 def toList(val):
962 if isinstance(val, list):
963 return val
964 else:
965 return [val]