blob: 2c7996ac20d89e89352c8e1d0818e4df88d80710 [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 serializer.tosa_serializer as ts
Kevin Chengfea5a372021-10-11 18:38:47 +000017import json
18import flatbuffers
19import numpy as np
Jeremy Johnson9b225172021-12-14 16:34:47 +000020from enum import IntEnum, unique
Kevin Chengfea5a372021-10-11 18:38:47 +000021from tosa import (
22 TosaGraph,
Jerry Ge1eb85042023-01-06 14:19:14 -080023 TosaRegion,
Kevin Chengfea5a372021-10-11 18:38:47 +000024 TosaBasicBlock,
25 TosaTensor,
26 TosaOperator,
Kevin Chengfea5a372021-10-11 18:38:47 +000027 Version,
28)
Jeremy Johnson9b225172021-12-14 16:34:47 +000029import tosa.DType as TosaDType
30import tosa.Op as TosaOp
Kevin Chengfea5a372021-10-11 18:38:47 +000031
Kevin Chenge6563f52021-10-20 12:12:02 -070032# Keep version number in sync with the version default value with schema/tosa.fbs
Kevin Chengb97cb1d2021-10-14 11:53:39 -070033TOSA_VERSION_MAJOR = 0
Eric Kunze8137a432024-02-02 21:33:22 +000034TOSA_VERSION_MINOR = 100
Kevin Chengb97cb1d2021-10-14 11:53:39 -070035TOSA_VERSION_PATCH = 0
Eric Kunze8a270432023-06-01 20:08:17 +000036TOSA_VERSION_DRAFT = True
Jeremy Johnson9b225172021-12-14 16:34:47 +000037TOSA_VERSION = [
38 TOSA_VERSION_MAJOR,
39 TOSA_VERSION_MINOR,
40 TOSA_VERSION_PATCH,
41 TOSA_VERSION_DRAFT,
42]
Eric Kunzee6596402022-06-09 21:27:36 +000043
44# File identifier needs to be kept in sync with schema/tosa.fbs
45TOSA_GRAPH_IDENTIFIER = b"\x54\x4F\x53\x41"
46
Kevin Chengfea5a372021-10-11 18:38:47 +000047# With the way flatc generates its python types, there is no programatic way
48# to get string names for the integer types. Manually maintain a string table
49# here.
Jeremy Johnson9b225172021-12-14 16:34:47 +000050DType = TosaDType.DType()
Kevin Chengfea5a372021-10-11 18:38:47 +000051DTypeNames = [
52 "UNKNOWN",
53 "BOOL",
54 "UINT8",
55 "INT4",
56 "INT8",
57 "INT16",
58 "INT32",
59 "INT48",
Jeremy Johnsone1072a92022-09-27 12:44:11 +010060 "FP32",
Jeremy Johnson41027732022-05-25 17:52:29 +010061 "UINT16",
James Ward485a11d2022-08-05 13:48:37 +010062 "FP16",
James Ward34a62792022-10-18 17:27:40 +010063 "BF16",
Won Jeon1adc5d02023-08-12 11:16:05 -070064 "SHAPE",
Won Jeona029f1f2023-12-29 22:43:11 +000065 "FP8E4M3",
66 "FP8E5M2",
Kevin Chengfea5a372021-10-11 18:38:47 +000067]
68
69ByteMask = np.uint64(0xFF)
70
71
72def dtype_str_to_val(name):
73
74 for i in range(len(DTypeNames)):
75 if name.casefold() == DTypeNames[i].casefold():
76 return i
77 raise Exception("Unable to parse DType name {}".format(name))
78
79
80class TosaSerializerUnion:
81 """This class handles encapsulating and serializing union types into flatbuffers"""
82
83 def __init__(self):
84
Jeremy Johnson9b225172021-12-14 16:34:47 +000085 # A tuple of the start and end functions.
86 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000087 self.optFcns = None
88
Jeremy Johnson9b225172021-12-14 16:34:47 +000089 # The type from the tosa.Options enumeration.
90 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000091 self.utype = None
92
93 # Each of these lists is a tuple of the add function and the
94 # value being added. Set by the options constructors below.
95 self.ints = []
96 self.bools = []
97 self.floats = []
98 self.strings = []
TatWai Chong49b1ca62022-06-10 01:49:13 -070099 self.int16vecs = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000100 self.intvecs = []
101 self.fpvecs = []
102
103 def serialize(self, builder):
104
105 # We have to build strings and vectors first
106 strList = []
107 intVecList = []
108 fpVecList = []
109
110 for fcn, val in self.strings:
111 strList.append((fcn, builder.CreateString(val)))
112
113 for fcn, val in self.intvecs:
114 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
115
TatWai Chong49b1ca62022-06-10 01:49:13 -0700116 for fcn, val in self.int16vecs:
117 intVecList.append((fcn, TosaSerializer.serializeInt16Vec(builder, val)))
118
Kevin Chengfea5a372021-10-11 18:38:47 +0000119 for fcn, val in self.fpvecs:
120 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
121
122 startFcn, endFcn = self.optFcns
123
124 # Then serialize the options object from the list of primitives and
125 # other serialized values
126 startFcn(builder)
127 for fcn, val in self.ints:
128 fcn(builder, val)
129
130 for fcn, val in self.bools:
131 fcn(builder, val)
132
133 for fcn, val in self.floats:
134 fcn(builder, val)
135
136 for fcn, val in strList:
137 fcn(builder, val)
138
139 for fcn, val in intVecList:
140 fcn(builder, val)
141
142 for fcn, val in fpVecList:
143 fcn(builder, val)
144
145 return endFcn(builder)
146
147
148class TosaSerializerAttribute(TosaSerializerUnion):
149 """This class handles encapsulating all of the enumerated types for attributes"""
150
151 def __init__(self):
152 super().__init__()
153
James Ward485a11d2022-08-05 13:48:37 +0100154 def PoolAttribute(
155 self,
156 kernel,
157 stride,
158 pad,
159 input_zp,
160 output_zp,
Tai Ly81db8ee2024-02-14 19:57:38 +0000161 acc_type,
James Ward485a11d2022-08-05 13:48:37 +0100162 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000163 from tosa import PoolAttribute as a, Attribute
164
165 self.utype = Attribute.Attribute().PoolAttribute
166
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800167 self.optFcns = (a.Start, a.End)
TatWai Chong7be71652022-05-10 17:26:20 -0700168 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800169 self.intvecs.append((a.AddKernel, kernel))
170 self.intvecs.append((a.AddStride, stride))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000171 self.ints.append((a.AddInputZp, input_zp))
172 self.ints.append((a.AddOutputZp, output_zp))
Tai Ly81db8ee2024-02-14 19:57:38 +0000173 self.ints.append((a.AddAccType, acc_type))
Kevin Chengfea5a372021-10-11 18:38:47 +0000174
Tai Lyf5dfad12023-11-15 21:09:58 +0000175 def ConvAttribute(self, pad, stride, dilation, input_zp, weight_zp, local_bound):
Kevin Chengfea5a372021-10-11 18:38:47 +0000176 from tosa import ConvAttribute as a, Attribute
177
178 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800179 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000180
TatWai Chong7be71652022-05-10 17:26:20 -0700181 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800182 self.intvecs.append((a.AddStride, stride))
183 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000184 self.ints.append((a.AddInputZp, input_zp))
185 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000186 self.bools.append((a.AddLocalBound, local_bound))
Kevin Chengfea5a372021-10-11 18:38:47 +0000187
Tai Lyf5dfad12023-11-15 21:09:58 +0000188 def TransposeConvAttribute(
189 self, outpad, stride, output_shape, input_zp, weight_zp, local_bound
190 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000191 from tosa import TransposeConvAttribute as a, Attribute
192
193 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800194 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000195
Eric Kunze4c3537d2022-06-13 17:21:48 -0700196 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800197 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800198 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000199 self.ints.append((a.AddInputZp, input_zp))
200 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000201 self.bools.append((a.AddLocalBound, local_bound))
Kevin Chengfea5a372021-10-11 18:38:47 +0000202
Tai Ly0b6d7c22024-03-08 17:03:25 +0000203 def PadAttribute(self, serializer_builder, pad_const_val_as_bytes):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700204 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000205
Kevin Cheng38d214c2021-10-15 15:49:19 -0700206 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800207 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000208
Tai Ly0b6d7c22024-03-08 17:03:25 +0000209 # serialize pad_const_val_as_bytes as uint8 vector
210 serialized_pad_const_val = ts.TosaSerializer.serializeUint8Vec(
211 serializer_builder, pad_const_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000212 )
213
Tai Ly0b6d7c22024-03-08 17:03:25 +0000214 self.floats.append((a.AddPadConst, serialized_pad_const_val))
Kevin Chengfea5a372021-10-11 18:38:47 +0000215
216 def AxisAttribute(self, axis):
217 from tosa import AxisAttribute as a, Attribute
218
219 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800220 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000221
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800222 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000223
TatWai Chong49b1ca62022-06-10 01:49:13 -0700224 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000225 from tosa import ResizeAttribute as a, Attribute
226
227 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800228 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000229
TatWai Chong49b1ca62022-06-10 01:49:13 -0700230 self.int16vecs.append((a.AddScale, scale))
231 self.int16vecs.append((a.AddOffset, offset))
232 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800233 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000234
Tai Ly0b6d7c22024-03-08 17:03:25 +0000235 def ClampAttribute(self, serializer_builder, min_val_as_bytes, max_val_as_bytes):
Kevin Chengfea5a372021-10-11 18:38:47 +0000236 from tosa import ClampAttribute as a, Attribute
237
238 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800239 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000240
James Wardc15f7d52022-12-07 15:38:01 +0000241 # min/max float attributes serialized as uint8 vectors
Tai Ly0b6d7c22024-03-08 17:03:25 +0000242 serialized_min_val = ts.TosaSerializer.serializeUint8Vec(
243 serializer_builder, min_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000244 )
Tai Ly0b6d7c22024-03-08 17:03:25 +0000245 serialized_max_val = ts.TosaSerializer.serializeUint8Vec(
246 serializer_builder, max_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000247 )
248
Tai Ly0b6d7c22024-03-08 17:03:25 +0000249 self.floats.append((a.AddMinVal, serialized_min_val))
250 self.floats.append((a.AddMaxVal, serialized_max_val))
Kevin Chengfea5a372021-10-11 18:38:47 +0000251
252 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000253 self,
254 input_zp,
255 output_zp,
James Ward92358fc2023-11-21 18:14:43 +0000256 scale32,
257 double_round,
258 per_channel,
259 input_unsigned,
260 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000261 ):
262 from tosa import RescaleAttribute as a, Attribute
263
264 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800265 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000266
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800267 self.ints.append((a.AddInputZp, input_zp))
268 self.ints.append((a.AddOutputZp, output_zp))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800269 self.bools.append((a.AddScale32, scale32))
270 self.bools.append((a.AddDoubleRound, double_round))
271 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000272 self.bools.append((a.AddInputUnsigned, input_unsigned))
273 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000274
275 def MulAttribute(self, shift):
276 from tosa import MulAttribute as a, Attribute
277
278 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800279 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000280
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800281 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000282
283 def ArithmeticRightShiftAttribute(self, round):
284 from tosa import ArithmeticRightShiftAttribute as a, Attribute
285
286 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
287 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800288 a.Start,
289 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000290 )
291
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800292 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000293
Tai Ly81db8ee2024-02-14 19:57:38 +0000294 def CondIfAttribute(self, then_graph, else_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000295 from tosa import CondIfAttribute as a, Attribute
296
297 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800298 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000299
Tai Ly81db8ee2024-02-14 19:57:38 +0000300 self.strings.append((a.AddThenGraph, then_graph))
301 self.strings.append((a.AddElseGraph, else_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000302
Tai Ly81db8ee2024-02-14 19:57:38 +0000303 def WhileLoopAttribute(self, cond_graph, body_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000304 from tosa import WhileLoopAttribute as a, Attribute
305
306 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800307 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000308
Tai Ly81db8ee2024-02-14 19:57:38 +0000309 self.strings.append((a.AddCondGraph, cond_graph))
310 self.strings.append((a.AddBodyGraph, body_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000311
TatWai Chong7be71652022-05-10 17:26:20 -0700312 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700313 from tosa import TransposeAttribute as a, Attribute
314
315 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800316 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700317
TatWai Chong7be71652022-05-10 17:26:20 -0700318 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700319
320 def TableAttribute(self, table):
321 from tosa import TableAttribute as a, Attribute
322
323 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800324 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700325
Jerry Gee7b8eb72023-09-15 17:19:50 +0000326 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000327
James Wardea00fd02023-01-20 16:03:50 +0000328 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000329 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000330
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000331 self.utype = Attribute.Attribute().MatMulAttribute
332 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000333
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000334 self.ints.append((a.AddAZp, A_zp))
335 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000336
James Wardea00fd02023-01-20 16:03:50 +0000337 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000338 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000339
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000340 self.utype = Attribute.Attribute().FullyConnectedAttribute
341 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000342
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000343 self.ints.append((a.AddInputZp, input_zp))
344 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000345
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000346 def NegateAttribute(self, input1_zp, output_zp):
347 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000348
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000349 self.utype = Attribute.Attribute().NegateAttribute
350 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000351
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000352 self.ints.append((a.AddInput1Zp, input1_zp))
353 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000354
Tai Lyf5dfad12023-11-15 21:09:58 +0000355 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000356 from tosa import FFTAttribute as a, Attribute
357
358 self.utype = Attribute.Attribute().FFTAttribute
359 self.optFcns = (a.Start, a.End)
360
361 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000362 self.bools.append((a.AddLocalBound, local_bound))
363
364 def RFFTAttribute(self, local_bound):
365 from tosa import RFFTAttribute as a, Attribute
366
367 self.utype = Attribute.Attribute().RFFTAttribute
368 self.optFcns = (a.Start, a.End)
369
370 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000371
Kevin Chengfea5a372021-10-11 18:38:47 +0000372
373class TosaSerializerTensor:
374 def __init__(
375 self,
376 name,
377 shape,
378 dtype,
379 data=None,
380 placeholderFilename=None,
381 ):
382 self.name = name
383
384 if isinstance(shape, np.ndarray):
385 shape = shape.astype(int).tolist()
386 shape = list(map(int, shape))
387
388 self.shape = shape
389 self.dtype = dtype
390
Won Jeona029f1f2023-12-29 22:43:11 +0000391 if (
392 dtype == DType.FP32
393 or dtype == DType.BF16
394 or dtype == DType.FP8E4M3
395 or dtype == DType.FP8E5M2
396 ):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100397 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100398 elif dtype == DType.FP16:
399 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100400 else:
401 fntype = int
402
Kevin Chengfea5a372021-10-11 18:38:47 +0000403 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100404 data = data.flatten().astype(fntype).tolist()
405 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000406 self.data = data
407 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100408 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000409 self.data = data
410 else:
411 self.data = None
412
413 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000414 # process and are written to disk, but are considered input tensors by the
415 # network so they do not appear in the TOSA serialiazation. However, if we
416 # want to form a unit test around these input tensors, we can get the filename
417 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000418 self.placeholderFilename = placeholderFilename
419
420 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800421 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000422 self.name,
423 self.shape,
424 DTypeNames[self.dtype],
425 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800426 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000427
428 def setDtype(self, dtype):
429 self.dtype = dtype
430
431 def serialize(self, builder):
432 fb_name = builder.CreateString(self.name)
433 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
434 if self.data:
435 u8_data = list()
436 # little endianess
437 if self.dtype == DType.BOOL:
438 for val in self.data:
439 val_u8 = np.uint8(val)
440 u8_data.append(val_u8)
441 elif self.dtype == DType.INT4:
442 in_size = len(self.data)
443 out_size = (in_size + 1) // 2
444 for i in range(out_size):
445 val_0 = self.data[2 * i]
446 if (2 * i + 1) < in_size:
447 val_1 = self.data[2 * i + 1]
448 else:
449 val_1 = 0
450 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
451 val_u8 = np.uint8(val_i8)
452 u8_data.append(val_u8)
453 elif self.dtype == DType.INT8:
454 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700455 val_u8 = np.array(val).astype(dtype=np.uint8)
Kevin Chengfea5a372021-10-11 18:38:47 +0000456 u8_data.append(val_u8)
457 elif self.dtype == DType.INT16:
458 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700459 val_u16 = np.array(val).astype(dtype=np.uint16)
Kevin Chengfea5a372021-10-11 18:38:47 +0000460 b0 = val_u16 & ByteMask
461 b1 = (val_u16 >> np.uint16(8)) & ByteMask
462 u8_data.extend([b0, b1])
463 elif self.dtype == DType.INT32:
464 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700465 val_u32 = np.array(val).astype(dtype=np.uint32)
Kevin Chengfea5a372021-10-11 18:38:47 +0000466 b0 = val_u32 & ByteMask
467 b1 = (val_u32 >> np.uint32(8)) & ByteMask
468 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700469 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000470 u8_data.extend([b0, b1, b2, b3])
Won Jeon7c22d772024-01-23 07:46:08 +0000471 elif self.dtype == DType.INT48:
Kevin Chengfea5a372021-10-11 18:38:47 +0000472 for val in self.data:
473 val_u64 = np.uint64(val)
474 b0 = val_u64 & ByteMask
475 b1 = (val_u64 >> np.uint64(8)) & ByteMask
476 b2 = (val_u64 >> np.uint64(16)) & ByteMask
477 b3 = (val_u64 >> np.uint64(24)) & ByteMask
478 b4 = (val_u64 >> np.uint64(32)) & ByteMask
479 b5 = (val_u64 >> np.uint64(40)) & ByteMask
480 u8_data.extend([b0, b1, b2, b3, b4, b5])
Won Jeon7c22d772024-01-23 07:46:08 +0000481 elif self.dtype == DType.SHAPE:
482 for val in self.data:
483 val_u64 = np.uint64(val)
484 b0 = val_u64 & ByteMask
485 b1 = (val_u64 >> np.uint64(8)) & ByteMask
486 b2 = (val_u64 >> np.uint64(16)) & ByteMask
487 b3 = (val_u64 >> np.uint64(24)) & ByteMask
488 b4 = (val_u64 >> np.uint64(32)) & ByteMask
489 b5 = (val_u64 >> np.uint64(40)) & ByteMask
490 b6 = (val_u64 >> np.uint64(48)) & ByteMask
491 b7 = (val_u64 >> np.uint64(56)) & ByteMask
492 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
James Ward485a11d2022-08-05 13:48:37 +0100493 elif self.dtype == DType.FP16:
494 np_arr = np.array(self.data, dtype=np.float16)
495 u8_data.extend(np_arr.view(np.uint8))
Won Jeona029f1f2023-12-29 22:43:11 +0000496 elif (
497 self.dtype == DType.FP32
498 or self.dtype == DType.BF16
499 or self.dtype == DType.FP8E4M3
500 or self.dtype == DType.FP8E5M2
501 ):
James Wardc15f7d52022-12-07 15:38:01 +0000502 # for val in self.data:
503 # b = struct.pack("!f", val)
504 # u8_data.extend([b[3], b[2], b[1], b[0]])
505 np_arr = np.array(self.data, dtype=np.float32)
506 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100507 elif self.dtype == TosaDType.DType:
508 # Serialize DType enum data as uint8 bytes
509 for val in self.data:
510 np_arr = np.array(self.data, dtype=np.uint32)
511 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000512 else:
513 raise Exception(
514 "unsupported data type {}".format(DTypeNames[self.dtype])
515 )
516 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
517
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800518 TosaTensor.Start(builder)
519 TosaTensor.AddName(builder, fb_name)
520 TosaTensor.AddShape(builder, fb_shapes)
521 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000522 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800523 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000524
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800525 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000526
527
528class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000529 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000530 self.op = op
531 self.attributes = attributes
532 self.inputs = TosaSerializer.toList(inputs)
533 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000534
535 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800536 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000537
538 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800539 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000540 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800541 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000542
Jerry Ge1eb85042023-01-06 14:19:14 -0800543 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000544
545 def serialize(self, builder):
546 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800547 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000548 )
549 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800550 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000551 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000552 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000553 if self.attributes is not None:
554 fb_attributes = self.attributes.serialize(builder)
555
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800556 TosaOperator.Start(builder)
557 TosaOperator.AddOp(builder, self.op)
558 TosaOperator.AddInputs(builder, fb_inputs)
559 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000560 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800561 TosaOperator.AddAttributeType(builder, self.attributes.utype)
562 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000563
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800564 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000565
566
567class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000568 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000569 self.name = name
570 self.operators = []
571
572 # Dict assures uniqueness, but allows us to look up by name
573 self.tensors = dict()
574
575 self.inputs = []
576 self.outputs = []
577
578 def addTensor(
579 self,
580 name,
581 shape,
582 dtype,
583 data=None,
584 placeholderFilename=None,
585 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000586 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000587 self.tensors[name] = TosaSerializerTensor(
588 name, shape, dtype, data, placeholderFilename
589 )
590
591 return self.tensors[name]
592
593 def addInput(self, name):
594 self.inputs.append(name)
595
596 def addOutput(self, name):
597 self.outputs.append(name)
598
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000599 def addOperator(self, op, inputs, outputs, attributes=None):
600 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000601
602 def serialize(self, builder):
603 fb_name = builder.CreateString(self.name)
604 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800605 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000606 )
607 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800608 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000609 )
610 fbv_tensors = TosaSerializer.serializeObjVec(
611 builder,
612 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800613 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000614 )
615 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800616 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000617 )
618
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800619 TosaBasicBlock.Start(builder)
620 TosaBasicBlock.AddName(builder, fb_name)
621 TosaBasicBlock.AddInputs(builder, fbv_inputs)
622 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
623 TosaBasicBlock.AddTensors(builder, fbv_tensors)
624 TosaBasicBlock.AddOperators(builder, fbv_operators)
625 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000626
627
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100628# How CONSTs are treated in the flatbuffer
629@unique
630class ConstMode(IntEnum):
631 EMBED = 0
632 EMBED_DUMP = 1
633 INPUTS = 2
634
635
Jerry Ge1eb85042023-01-06 14:19:14 -0800636class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100637 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800638 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000639 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000640 self.currInputIdx = 0
641 self.currConstIdx = 0
642 self.currLayerIdx = 1
643 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800644 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100645 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000646
Jerry Geca7ce0e2023-01-10 17:24:38 +0000647 def addBasicBlock(self, name):
648 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800649 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000650
Jerry Ge1eb85042023-01-06 14:19:14 -0800651 def serialize(self, builder):
652 fb_name = builder.CreateString(self.name)
653 fbv_basicBlocks = TosaSerializer.serializeObjVec(
654 builder, self.basicBlocks, TosaRegion.StartBlocksVector
655 )
656
657 TosaRegion.Start(builder)
658 TosaRegion.AddName(builder, fb_name)
659 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
660 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000661
662 def addPlaceholder(self, shape, dtype, vals):
663 if not self.currBasicBlock:
664 raise Exception("addTensor called without valid basic block")
665
666 name = "input-{}".format(self.currInputIdx)
667 filename = "{}.npy".format(name)
668 self.currInputIdx = self.currInputIdx + 1
669
670 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
671 # This is always an input to the block
672 self.currBasicBlock.addInput(name)
673
674 if vals is not None:
675 np.save(os.path.join(self.pathPrefix, filename), vals, False)
676
677 return tens
678
Jerry Ge53ceb482023-08-14 20:15:10 +0000679 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000680 if not self.currBasicBlock:
681 raise Exception("addTensor called without valid basic block")
682
Jerry Ge53ceb482023-08-14 20:15:10 +0000683 if name is None:
684 name = "const-{}".format(self.currInputIdx)
685 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000686
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100687 if self.constMode == ConstMode.INPUTS:
688 # Save const as input file
689 filename = "{}.npy".format(name)
690 tensor_vals = None
691 self.currBasicBlock.addInput(name)
692 else:
693 # Embed const in flatbuffer
694 filename = None
695 tensor_vals = vals
696
697 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000698 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000699 if dtype == DType.SHAPE:
700 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
701 else:
702 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000703
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100704 # Save the const data to file for debug or as input files
705 if vals is not None and self.constMode in [
706 ConstMode.EMBED_DUMP,
707 ConstMode.INPUTS,
708 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100709 filename = "{}.npy".format(name)
710 np.save(os.path.join(self.pathPrefix, filename), vals, False)
711
Kevin Chengfea5a372021-10-11 18:38:47 +0000712 return tens
713
714 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000715 if not self.currBasicBlock:
716 raise Exception("addTensor called without valid basic block")
717
718 name = "layer-{}".format(self.currLayerIdx)
719 self.currLayerIdx = self.currLayerIdx + 1
720
721 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
722
723 return tens
724
725 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700726 self.currBasicBlock.addTensor(
727 tensor.name,
728 tensor.shape,
729 tensor.dtype,
730 tensor.data,
731 tensor.placeholderFilename,
732 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000733 self.currBasicBlock.addInput(tensor.name)
734
735 def addOutputTensor(self, tensor):
736 self.currBasicBlock.addOutput(tensor.name)
737
738 def addOutput(self, shape, dtype):
739 if not self.currBasicBlock:
740 raise Exception("addTensor called without valid basic block")
741
742 name = "result-{}".format(self.currResultIdx)
743 self.currResultIdx = self.currResultIdx + 1
744
745 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
746 self.currBasicBlock.addOutput(name)
747 return tens
748
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000749 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000750 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000751 raise Exception("Use addConstTensor() to add CONST ops")
752
753 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000754 op,
755 inputs,
756 outputs,
757 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000758 )
759
Jerry Ge1eb85042023-01-06 14:19:14 -0800760
761@unique
762class TensorDir(IntEnum):
763 PLACEHOLDER = 0
764 CONST = 1
765 INTERMEDIATE = 2
766 RESULT = 3
767
768
769class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100770 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800771 self.builder = flatbuffers.Builder(0)
772
Jerry Ge1eb85042023-01-06 14:19:14 -0800773 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100774 self.constMode = constMode
775
776 self.regions = []
777 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800778
Jerry Geca7ce0e2023-01-10 17:24:38 +0000779 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800780
781 # Is this an illegal test that is expected to fail?
782 self.expectedReturnCode = 0
783 self.expectedFailure = False
784 self.expectedFailureDesc = ""
785
786 def __str__(self):
787 concatString = ""
788 for region in self.regions:
789 concatString = concatString + str(region)
790 return concatString
791
792 def addPlaceholder(self, shape, dtype, vals):
793 return self.currRegion.addPlaceholder(shape, dtype, vals)
794
Jerry Ge53ceb482023-08-14 20:15:10 +0000795 def addConst(self, shape, dtype, vals, name=None):
796 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800797
798 def addIntermediate(self, shape, dtype):
799 return self.currRegion.addIntermediate(shape, dtype)
800
801 def addInputTensor(self, tensor):
802 self.currRegion.addInputTensor(tensor)
803
804 def addOutputTensor(self, tensor):
805 self.currRegion.addOutputTensor(tensor)
806
807 def addOutput(self, shape, dtype):
808 return self.currRegion.addOutput(shape, dtype)
809
810 def addOperator(self, op, inputs, outputs, attributes=None):
811 return self.currRegion.addOperator(op, inputs, outputs, attributes)
812
Jerry Geca7ce0e2023-01-10 17:24:38 +0000813 def addBasicBlock(self, name):
814 self.currRegion.addBasicBlock(name)
815
Jeremy Johnson9b225172021-12-14 16:34:47 +0000816 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000817
818 self.expectedReturnCode = val
819 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000820 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000821
822 def serialize(self):
823
824 builder = self.builder
825
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800826 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000827 Version.Add_Major(builder, TOSA_VERSION[0])
828 Version.Add_Minor(builder, TOSA_VERSION[1])
829 Version.Add_Patch(builder, TOSA_VERSION[2])
830 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800831 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000832
Jerry Ge1eb85042023-01-06 14:19:14 -0800833 fbv_region = TosaSerializer.serializeObjVec(
834 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000835 )
836
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800837 TosaGraph.Start(builder)
838 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800839 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800840 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000841
Eric Kunzee6596402022-06-09 21:27:36 +0000842 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000843 return self.builder.Output()
844
845 def writeJson(self, tosa_filename):
846 """Write a json test file so that it is fairly easy to pick up the test
847 and generate commands for third party tool"""
848 test_desc = dict()
849
850 test_desc["tosa_file"] = tosa_filename
851 ifm_name = []
852 ifm_file = []
853 ofm_name = []
854 ofm_file = []
855
Jerry Ge1eb85042023-01-06 14:19:14 -0800856 for region in self.regions:
857 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000858 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800859 for i in block.inputs:
860 ifm_name.append(i)
861 ifm_file.append(block.tensors[i].placeholderFilename)
862 for o in block.outputs:
863 ofm_name.append(o)
864 # Make up an OFM filename here. One isn't generated until the
865 # reference tool is run, so any name is a good name
866 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000867
868 test_desc["ifm_name"] = ifm_name
869 test_desc["ifm_file"] = ifm_file
870 test_desc["ofm_name"] = ofm_name
871 test_desc["ofm_file"] = ofm_file
872 test_desc["expected_return_code"] = self.expectedReturnCode
873 test_desc["expected_failure"] = self.expectedFailure
874 if self.expectedFailureDesc:
875 test_desc["expected_failure_desc"] = self.expectedFailureDesc
876
877 return json.dumps(test_desc, indent=" ")
878
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100879 def startRegion(self, name, pathPrefix):
880 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800881 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000882
883 @staticmethod
884 def serializeStrVec(builder, vec, start_fcn):
885 fb_strs = [builder.CreateString(i) for i in vec]
886 start_fcn(builder, len(fb_strs))
887 for s in fb_strs[::-1]:
888 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700889 try:
890 return builder.EndVector()
891 except TypeError:
892 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000893
894 @staticmethod
895 def serializeUint8Vec(builder, vec):
896 builder.StartVector(1, len(vec), 8)
897 for v in vec[::-1]:
898 builder.PrependUint8(v)
899 try:
900 return builder.EndVector()
901 except TypeError:
902 return builder.EndVector(len(vec))
903
904 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700905 def serializeInt16Vec(builder, vec):
906 builder.StartVector(2, len(vec), 4)
907 for v in vec[::-1]:
908 builder.PrependInt16(v)
909 try:
910 return builder.EndVector()
911 except TypeError:
912 return builder.EndVector(len(vec))
913
914 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000915 def serializeInt32Vec(builder, vec):
916 builder.StartVector(4, len(vec), 4)
917 for v in vec[::-1]:
918 builder.PrependInt32(v)
919 try:
920 return builder.EndVector()
921 except TypeError:
922 return builder.EndVector(len(vec))
923
924 @staticmethod
925 def serializeFpVec(builder, vec):
926 builder.StartVector(4, len(vec), 4)
927 for v in vec[::-1]:
928 builder.PrependFloat32(v)
929 try:
930 return builder.EndVector()
931 except TypeError:
932 return builder.EndVector(len(vec))
933
934 @staticmethod
935 def serializeObjVec(builder, vec, start_fcn):
936 serialized_vec = []
937 for v in vec[::-1]:
938 serialized_vec.append(v.serialize(builder))
939
940 start_fcn(builder, len(vec))
941 for v in serialized_vec:
942 builder.PrependUOffsetTRelative(v)
943 try:
944 return builder.EndVector()
945 except TypeError:
946 return builder.EndVector(len(vec))
947
948 @staticmethod
949 def toList(val):
950 if isinstance(val, list):
951 return val
952 else:
953 return [val]