blob: 563bc0095cbffc3226683eaa2ceacbeef0e3e784 [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 Kunzec0a60302023-09-13 17:04:21 -070035TOSA_VERSION_MINOR = 90
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",
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(
286 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
287 ):
288 from tosa import RescaleAttribute as a, Attribute
289
290 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800291 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000292
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800293 self.ints.append((a.AddInputZp, input_zp))
294 self.ints.append((a.AddOutputZp, output_zp))
295 self.intvecs.append((a.AddMultiplier, multiplier))
296 self.intvecs.append((a.AddShift, shift))
297 self.bools.append((a.AddScale32, scale32))
298 self.bools.append((a.AddDoubleRound, double_round))
299 self.bools.append((a.AddPerChannel, per_channel))
Kevin Chengfea5a372021-10-11 18:38:47 +0000300
301 def MulAttribute(self, shift):
302 from tosa import MulAttribute as a, Attribute
303
304 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800305 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000306
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800307 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000308
309 def ArithmeticRightShiftAttribute(self, round):
310 from tosa import ArithmeticRightShiftAttribute as a, Attribute
311
312 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
313 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800314 a.Start,
315 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000316 )
317
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800318 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000319
Kevin Chengfea5a372021-10-11 18:38:47 +0000320 def CondIfAttribute(self, then_branch, else_branch):
321 from tosa import CondIfAttribute as a, Attribute
322
323 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800324 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000325
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800326 self.strings.append((a.AddThenBranch, then_branch))
327 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000328
329 def WhileLoopAttribute(self, cond_branch, body_branch):
330 from tosa import WhileLoopAttribute as a, Attribute
331
332 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800333 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000334
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800335 self.strings.append((a.AddCondBranch, cond_branch))
336 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000337
TatWai Chong7be71652022-05-10 17:26:20 -0700338 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700339 from tosa import TransposeAttribute as a, Attribute
340
341 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800342 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700343
TatWai Chong7be71652022-05-10 17:26:20 -0700344 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700345
346 def TableAttribute(self, table):
347 from tosa import TableAttribute as a, Attribute
348
349 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800350 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700351
Jerry Gee7b8eb72023-09-15 17:19:50 +0000352 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000353
James Wardea00fd02023-01-20 16:03:50 +0000354 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000355 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000356
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000357 self.utype = Attribute.Attribute().MatMulAttribute
358 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000359
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000360 self.ints.append((a.AddAZp, A_zp))
361 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000362
James Wardea00fd02023-01-20 16:03:50 +0000363 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000364 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000365
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000366 self.utype = Attribute.Attribute().FullyConnectedAttribute
367 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000368
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000369 self.ints.append((a.AddInputZp, input_zp))
370 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000371
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000372 def NegateAttribute(self, input1_zp, output_zp):
373 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000374
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000375 self.utype = Attribute.Attribute().NegateAttribute
376 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000377
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000378 self.ints.append((a.AddInput1Zp, input1_zp))
379 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000380
Tai Lyf5dfad12023-11-15 21:09:58 +0000381 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000382 from tosa import FFTAttribute as a, Attribute
383
384 self.utype = Attribute.Attribute().FFTAttribute
385 self.optFcns = (a.Start, a.End)
386
387 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000388 self.bools.append((a.AddLocalBound, local_bound))
389
390 def RFFTAttribute(self, local_bound):
391 from tosa import RFFTAttribute as a, Attribute
392
393 self.utype = Attribute.Attribute().RFFTAttribute
394 self.optFcns = (a.Start, a.End)
395
396 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000397
Kevin Chengfea5a372021-10-11 18:38:47 +0000398
399class TosaSerializerTensor:
400 def __init__(
401 self,
402 name,
403 shape,
404 dtype,
405 data=None,
406 placeholderFilename=None,
407 ):
408 self.name = name
409
410 if isinstance(shape, np.ndarray):
411 shape = shape.astype(int).tolist()
412 shape = list(map(int, shape))
413
414 self.shape = shape
415 self.dtype = dtype
416
James Ward34a62792022-10-18 17:27:40 +0100417 if dtype == DType.FP32 or dtype == DType.BF16:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100418 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100419 elif dtype == DType.FP16:
420 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100421 else:
422 fntype = int
423
Kevin Chengfea5a372021-10-11 18:38:47 +0000424 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100425 data = data.flatten().astype(fntype).tolist()
426 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000427 self.data = data
428 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100429 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000430 self.data = data
431 else:
432 self.data = None
433
434 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000435 # process and are written to disk, but are considered input tensors by the
436 # network so they do not appear in the TOSA serialiazation. However, if we
437 # want to form a unit test around these input tensors, we can get the filename
438 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000439 self.placeholderFilename = placeholderFilename
440
441 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800442 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000443 self.name,
444 self.shape,
445 DTypeNames[self.dtype],
446 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800447 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000448
449 def setDtype(self, dtype):
450 self.dtype = dtype
451
452 def serialize(self, builder):
453 fb_name = builder.CreateString(self.name)
454 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
455 if self.data:
456 u8_data = list()
457 # little endianess
458 if self.dtype == DType.BOOL:
459 for val in self.data:
460 val_u8 = np.uint8(val)
461 u8_data.append(val_u8)
462 elif self.dtype == DType.INT4:
463 in_size = len(self.data)
464 out_size = (in_size + 1) // 2
465 for i in range(out_size):
466 val_0 = self.data[2 * i]
467 if (2 * i + 1) < in_size:
468 val_1 = self.data[2 * i + 1]
469 else:
470 val_1 = 0
471 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
472 val_u8 = np.uint8(val_i8)
473 u8_data.append(val_u8)
474 elif self.dtype == DType.INT8:
475 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700476 val_u8 = np.array(val).astype(dtype=np.uint8)
Kevin Chengfea5a372021-10-11 18:38:47 +0000477 u8_data.append(val_u8)
478 elif self.dtype == DType.INT16:
479 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700480 val_u16 = np.array(val).astype(dtype=np.uint16)
Kevin Chengfea5a372021-10-11 18:38:47 +0000481 b0 = val_u16 & ByteMask
482 b1 = (val_u16 >> np.uint16(8)) & ByteMask
483 u8_data.extend([b0, b1])
484 elif self.dtype == DType.INT32:
485 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700486 val_u32 = np.array(val).astype(dtype=np.uint32)
Kevin Chengfea5a372021-10-11 18:38:47 +0000487 b0 = val_u32 & ByteMask
488 b1 = (val_u32 >> np.uint32(8)) & ByteMask
489 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700490 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000491 u8_data.extend([b0, b1, b2, b3])
Won Jeon1adc5d02023-08-12 11:16:05 -0700492 elif self.dtype == DType.INT48 or self.dtype == DType.SHAPE:
Kevin Chengfea5a372021-10-11 18:38:47 +0000493 for val in self.data:
494 val_u64 = np.uint64(val)
495 b0 = val_u64 & ByteMask
496 b1 = (val_u64 >> np.uint64(8)) & ByteMask
497 b2 = (val_u64 >> np.uint64(16)) & ByteMask
498 b3 = (val_u64 >> np.uint64(24)) & ByteMask
499 b4 = (val_u64 >> np.uint64(32)) & ByteMask
500 b5 = (val_u64 >> np.uint64(40)) & ByteMask
501 u8_data.extend([b0, b1, b2, b3, b4, b5])
James Ward485a11d2022-08-05 13:48:37 +0100502 elif self.dtype == DType.FP16:
503 np_arr = np.array(self.data, dtype=np.float16)
504 u8_data.extend(np_arr.view(np.uint8))
James Ward34a62792022-10-18 17:27:40 +0100505 elif self.dtype == DType.FP32 or self.dtype == DType.BF16:
James Wardc15f7d52022-12-07 15:38:01 +0000506 # for val in self.data:
507 # b = struct.pack("!f", val)
508 # u8_data.extend([b[3], b[2], b[1], b[0]])
509 np_arr = np.array(self.data, dtype=np.float32)
510 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100511 elif self.dtype == TosaDType.DType:
512 # Serialize DType enum data as uint8 bytes
513 for val in self.data:
514 np_arr = np.array(self.data, dtype=np.uint32)
515 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000516 else:
517 raise Exception(
518 "unsupported data type {}".format(DTypeNames[self.dtype])
519 )
520 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
521
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800522 TosaTensor.Start(builder)
523 TosaTensor.AddName(builder, fb_name)
524 TosaTensor.AddShape(builder, fb_shapes)
525 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000526 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800527 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000528
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800529 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000530
531
532class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000533 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000534 self.op = op
535 self.attributes = attributes
536 self.inputs = TosaSerializer.toList(inputs)
537 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000538
539 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800540 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000541
542 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800543 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000544 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800545 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000546
Jerry Ge1eb85042023-01-06 14:19:14 -0800547 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000548
549 def serialize(self, builder):
550 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800551 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000552 )
553 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800554 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000555 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000556 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000557 if self.attributes is not None:
558 fb_attributes = self.attributes.serialize(builder)
559
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800560 TosaOperator.Start(builder)
561 TosaOperator.AddOp(builder, self.op)
562 TosaOperator.AddInputs(builder, fb_inputs)
563 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000564 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800565 TosaOperator.AddAttributeType(builder, self.attributes.utype)
566 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000567
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800568 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000569
570
571class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000572 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000573 self.name = name
574 self.operators = []
575
576 # Dict assures uniqueness, but allows us to look up by name
577 self.tensors = dict()
578
579 self.inputs = []
580 self.outputs = []
581
582 def addTensor(
583 self,
584 name,
585 shape,
586 dtype,
587 data=None,
588 placeholderFilename=None,
589 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000590 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000591 self.tensors[name] = TosaSerializerTensor(
592 name, shape, dtype, data, placeholderFilename
593 )
594
595 return self.tensors[name]
596
597 def addInput(self, name):
598 self.inputs.append(name)
599
600 def addOutput(self, name):
601 self.outputs.append(name)
602
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000603 def addOperator(self, op, inputs, outputs, attributes=None):
604 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000605
606 def serialize(self, builder):
607 fb_name = builder.CreateString(self.name)
608 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800609 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000610 )
611 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800612 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000613 )
614 fbv_tensors = TosaSerializer.serializeObjVec(
615 builder,
616 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800617 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000618 )
619 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800620 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000621 )
622
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800623 TosaBasicBlock.Start(builder)
624 TosaBasicBlock.AddName(builder, fb_name)
625 TosaBasicBlock.AddInputs(builder, fbv_inputs)
626 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
627 TosaBasicBlock.AddTensors(builder, fbv_tensors)
628 TosaBasicBlock.AddOperators(builder, fbv_operators)
629 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000630
631
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100632# How CONSTs are treated in the flatbuffer
633@unique
634class ConstMode(IntEnum):
635 EMBED = 0
636 EMBED_DUMP = 1
637 INPUTS = 2
638
639
Jerry Ge1eb85042023-01-06 14:19:14 -0800640class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100641 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800642 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000643 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000644 self.currInputIdx = 0
645 self.currConstIdx = 0
646 self.currLayerIdx = 1
647 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800648 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100649 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000650
Jerry Geca7ce0e2023-01-10 17:24:38 +0000651 def addBasicBlock(self, name):
652 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800653 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000654
Jerry Ge1eb85042023-01-06 14:19:14 -0800655 def serialize(self, builder):
656 fb_name = builder.CreateString(self.name)
657 fbv_basicBlocks = TosaSerializer.serializeObjVec(
658 builder, self.basicBlocks, TosaRegion.StartBlocksVector
659 )
660
661 TosaRegion.Start(builder)
662 TosaRegion.AddName(builder, fb_name)
663 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
664 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000665
666 def addPlaceholder(self, shape, dtype, vals):
667 if not self.currBasicBlock:
668 raise Exception("addTensor called without valid basic block")
669
670 name = "input-{}".format(self.currInputIdx)
671 filename = "{}.npy".format(name)
672 self.currInputIdx = self.currInputIdx + 1
673
674 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
675 # This is always an input to the block
676 self.currBasicBlock.addInput(name)
677
678 if vals is not None:
679 np.save(os.path.join(self.pathPrefix, filename), vals, False)
680
681 return tens
682
Jerry Ge53ceb482023-08-14 20:15:10 +0000683 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000684 if not self.currBasicBlock:
685 raise Exception("addTensor called without valid basic block")
686
Jerry Ge53ceb482023-08-14 20:15:10 +0000687 if name is None:
688 name = "const-{}".format(self.currInputIdx)
689 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000690
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100691 if self.constMode == ConstMode.INPUTS:
692 # Save const as input file
693 filename = "{}.npy".format(name)
694 tensor_vals = None
695 self.currBasicBlock.addInput(name)
696 else:
697 # Embed const in flatbuffer
698 filename = None
699 tensor_vals = vals
700
701 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000702 # Add the operator now
Jeremy Johnson9b225172021-12-14 16:34:47 +0000703 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000704
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100705 # Save the const data to file for debug or as input files
706 if vals is not None and self.constMode in [
707 ConstMode.EMBED_DUMP,
708 ConstMode.INPUTS,
709 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100710 filename = "{}.npy".format(name)
711 np.save(os.path.join(self.pathPrefix, filename), vals, False)
712
Kevin Chengfea5a372021-10-11 18:38:47 +0000713 return tens
714
715 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000716 if not self.currBasicBlock:
717 raise Exception("addTensor called without valid basic block")
718
719 name = "layer-{}".format(self.currLayerIdx)
720 self.currLayerIdx = self.currLayerIdx + 1
721
722 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
723
724 return tens
725
726 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700727 self.currBasicBlock.addTensor(
728 tensor.name,
729 tensor.shape,
730 tensor.dtype,
731 tensor.data,
732 tensor.placeholderFilename,
733 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000734 self.currBasicBlock.addInput(tensor.name)
735
736 def addOutputTensor(self, tensor):
737 self.currBasicBlock.addOutput(tensor.name)
738
739 def addOutput(self, shape, dtype):
740 if not self.currBasicBlock:
741 raise Exception("addTensor called without valid basic block")
742
743 name = "result-{}".format(self.currResultIdx)
744 self.currResultIdx = self.currResultIdx + 1
745
746 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
747 self.currBasicBlock.addOutput(name)
748 return tens
749
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000750 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000751 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000752 raise Exception("Use addConstTensor() to add CONST ops")
753
754 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000755 op,
756 inputs,
757 outputs,
758 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000759 )
760
Jerry Ge1eb85042023-01-06 14:19:14 -0800761
762@unique
763class TensorDir(IntEnum):
764 PLACEHOLDER = 0
765 CONST = 1
766 INTERMEDIATE = 2
767 RESULT = 3
768
769
770class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100771 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800772 self.builder = flatbuffers.Builder(0)
773
Jerry Ge1eb85042023-01-06 14:19:14 -0800774 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100775 self.constMode = constMode
776
777 self.regions = []
778 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800779
Jerry Geca7ce0e2023-01-10 17:24:38 +0000780 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800781
782 # Is this an illegal test that is expected to fail?
783 self.expectedReturnCode = 0
784 self.expectedFailure = False
785 self.expectedFailureDesc = ""
786
787 def __str__(self):
788 concatString = ""
789 for region in self.regions:
790 concatString = concatString + str(region)
791 return concatString
792
793 def addPlaceholder(self, shape, dtype, vals):
794 return self.currRegion.addPlaceholder(shape, dtype, vals)
795
Jerry Ge53ceb482023-08-14 20:15:10 +0000796 def addConst(self, shape, dtype, vals, name=None):
797 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800798
799 def addIntermediate(self, shape, dtype):
800 return self.currRegion.addIntermediate(shape, dtype)
801
802 def addInputTensor(self, tensor):
803 self.currRegion.addInputTensor(tensor)
804
805 def addOutputTensor(self, tensor):
806 self.currRegion.addOutputTensor(tensor)
807
808 def addOutput(self, shape, dtype):
809 return self.currRegion.addOutput(shape, dtype)
810
811 def addOperator(self, op, inputs, outputs, attributes=None):
812 return self.currRegion.addOperator(op, inputs, outputs, attributes)
813
Jerry Geca7ce0e2023-01-10 17:24:38 +0000814 def addBasicBlock(self, name):
815 self.currRegion.addBasicBlock(name)
816
Jeremy Johnson9b225172021-12-14 16:34:47 +0000817 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000818
819 self.expectedReturnCode = val
820 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000821 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000822
823 def serialize(self):
824
825 builder = self.builder
826
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800827 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000828 Version.Add_Major(builder, TOSA_VERSION[0])
829 Version.Add_Minor(builder, TOSA_VERSION[1])
830 Version.Add_Patch(builder, TOSA_VERSION[2])
831 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800832 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000833
Jerry Ge1eb85042023-01-06 14:19:14 -0800834 fbv_region = TosaSerializer.serializeObjVec(
835 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000836 )
837
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800838 TosaGraph.Start(builder)
839 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800840 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800841 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000842
Eric Kunzee6596402022-06-09 21:27:36 +0000843 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000844 return self.builder.Output()
845
846 def writeJson(self, tosa_filename):
847 """Write a json test file so that it is fairly easy to pick up the test
848 and generate commands for third party tool"""
849 test_desc = dict()
850
851 test_desc["tosa_file"] = tosa_filename
852 ifm_name = []
853 ifm_file = []
854 ofm_name = []
855 ofm_file = []
856
Jerry Ge1eb85042023-01-06 14:19:14 -0800857 for region in self.regions:
858 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000859 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800860 for i in block.inputs:
861 ifm_name.append(i)
862 ifm_file.append(block.tensors[i].placeholderFilename)
863 for o in block.outputs:
864 ofm_name.append(o)
865 # Make up an OFM filename here. One isn't generated until the
866 # reference tool is run, so any name is a good name
867 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000868
869 test_desc["ifm_name"] = ifm_name
870 test_desc["ifm_file"] = ifm_file
871 test_desc["ofm_name"] = ofm_name
872 test_desc["ofm_file"] = ofm_file
873 test_desc["expected_return_code"] = self.expectedReturnCode
874 test_desc["expected_failure"] = self.expectedFailure
875 if self.expectedFailureDesc:
876 test_desc["expected_failure_desc"] = self.expectedFailureDesc
877
878 return json.dumps(test_desc, indent=" ")
879
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100880 def startRegion(self, name, pathPrefix):
881 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800882 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000883
884 @staticmethod
885 def serializeStrVec(builder, vec, start_fcn):
886 fb_strs = [builder.CreateString(i) for i in vec]
887 start_fcn(builder, len(fb_strs))
888 for s in fb_strs[::-1]:
889 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700890 try:
891 return builder.EndVector()
892 except TypeError:
893 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000894
895 @staticmethod
896 def serializeUint8Vec(builder, vec):
897 builder.StartVector(1, len(vec), 8)
898 for v in vec[::-1]:
899 builder.PrependUint8(v)
900 try:
901 return builder.EndVector()
902 except TypeError:
903 return builder.EndVector(len(vec))
904
905 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700906 def serializeInt16Vec(builder, vec):
907 builder.StartVector(2, len(vec), 4)
908 for v in vec[::-1]:
909 builder.PrependInt16(v)
910 try:
911 return builder.EndVector()
912 except TypeError:
913 return builder.EndVector(len(vec))
914
915 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000916 def serializeInt32Vec(builder, vec):
917 builder.StartVector(4, len(vec), 4)
918 for v in vec[::-1]:
919 builder.PrependInt32(v)
920 try:
921 return builder.EndVector()
922 except TypeError:
923 return builder.EndVector(len(vec))
924
925 @staticmethod
926 def serializeFpVec(builder, vec):
927 builder.StartVector(4, len(vec), 4)
928 for v in vec[::-1]:
929 builder.PrependFloat32(v)
930 try:
931 return builder.EndVector()
932 except TypeError:
933 return builder.EndVector(len(vec))
934
935 @staticmethod
936 def serializeObjVec(builder, vec, start_fcn):
937 serialized_vec = []
938 for v in vec[::-1]:
939 serialized_vec.append(v.serialize(builder))
940
941 start_fcn(builder, len(vec))
942 for v in serialized_vec:
943 builder.PrependUOffsetTRelative(v)
944 try:
945 return builder.EndVector()
946 except TypeError:
947 return builder.EndVector(len(vec))
948
949 @staticmethod
950 def toList(val):
951 if isinstance(val, list):
952 return val
953 else:
954 return [val]