blob: 9658edfe041ee36c324f50f2953f0d1c6ad08a42 [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 Lyad78daa2024-03-13 18:52:45 +0000175 def ConvAttribute(
176 self, pad, stride, dilation, input_zp, weight_zp, local_bound, acc_type
177 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000178 from tosa import ConvAttribute as a, Attribute
179
180 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800181 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000182
TatWai Chong7be71652022-05-10 17:26:20 -0700183 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800184 self.intvecs.append((a.AddStride, stride))
185 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000186 self.ints.append((a.AddInputZp, input_zp))
187 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000188 self.bools.append((a.AddLocalBound, local_bound))
Tai Lyad78daa2024-03-13 18:52:45 +0000189 self.ints.append((a.AddAccType, acc_type))
Kevin Chengfea5a372021-10-11 18:38:47 +0000190
Tai Lyf5dfad12023-11-15 21:09:58 +0000191 def TransposeConvAttribute(
Tai Lyad78daa2024-03-13 18:52:45 +0000192 self, outpad, stride, output_shape, input_zp, weight_zp, local_bound, acc_type
Tai Lyf5dfad12023-11-15 21:09:58 +0000193 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000194 from tosa import TransposeConvAttribute as a, Attribute
195
196 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800197 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000198
Eric Kunze4c3537d2022-06-13 17:21:48 -0700199 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800200 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800201 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000202 self.ints.append((a.AddInputZp, input_zp))
203 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000204 self.bools.append((a.AddLocalBound, local_bound))
Tai Lyad78daa2024-03-13 18:52:45 +0000205 self.ints.append((a.AddAccType, acc_type))
Kevin Chengfea5a372021-10-11 18:38:47 +0000206
Tai Ly0b6d7c22024-03-08 17:03:25 +0000207 def PadAttribute(self, serializer_builder, pad_const_val_as_bytes):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700208 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000209
Kevin Cheng38d214c2021-10-15 15:49:19 -0700210 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800211 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000212
Tai Ly0b6d7c22024-03-08 17:03:25 +0000213 # serialize pad_const_val_as_bytes as uint8 vector
214 serialized_pad_const_val = ts.TosaSerializer.serializeUint8Vec(
215 serializer_builder, pad_const_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000216 )
217
Tai Ly0b6d7c22024-03-08 17:03:25 +0000218 self.floats.append((a.AddPadConst, serialized_pad_const_val))
Kevin Chengfea5a372021-10-11 18:38:47 +0000219
220 def AxisAttribute(self, axis):
221 from tosa import AxisAttribute as a, Attribute
222
223 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800224 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000225
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800226 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000227
TatWai Chong49b1ca62022-06-10 01:49:13 -0700228 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000229 from tosa import ResizeAttribute as a, Attribute
230
231 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800232 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000233
TatWai Chong49b1ca62022-06-10 01:49:13 -0700234 self.int16vecs.append((a.AddScale, scale))
235 self.int16vecs.append((a.AddOffset, offset))
236 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800237 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000238
Tai Ly0b6d7c22024-03-08 17:03:25 +0000239 def ClampAttribute(self, serializer_builder, min_val_as_bytes, max_val_as_bytes):
Kevin Chengfea5a372021-10-11 18:38:47 +0000240 from tosa import ClampAttribute as a, Attribute
241
242 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800243 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000244
James Wardc15f7d52022-12-07 15:38:01 +0000245 # min/max float attributes serialized as uint8 vectors
Tai Ly0b6d7c22024-03-08 17:03:25 +0000246 serialized_min_val = ts.TosaSerializer.serializeUint8Vec(
247 serializer_builder, min_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000248 )
Tai Ly0b6d7c22024-03-08 17:03:25 +0000249 serialized_max_val = ts.TosaSerializer.serializeUint8Vec(
250 serializer_builder, max_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000251 )
252
Tai Ly0b6d7c22024-03-08 17:03:25 +0000253 self.floats.append((a.AddMinVal, serialized_min_val))
254 self.floats.append((a.AddMaxVal, serialized_max_val))
Kevin Chengfea5a372021-10-11 18:38:47 +0000255
256 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000257 self,
258 input_zp,
259 output_zp,
James Ward92358fc2023-11-21 18:14:43 +0000260 scale32,
261 double_round,
262 per_channel,
263 input_unsigned,
264 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000265 ):
266 from tosa import RescaleAttribute as a, Attribute
267
268 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800269 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000270
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800271 self.ints.append((a.AddInputZp, input_zp))
272 self.ints.append((a.AddOutputZp, output_zp))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800273 self.bools.append((a.AddScale32, scale32))
274 self.bools.append((a.AddDoubleRound, double_round))
275 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000276 self.bools.append((a.AddInputUnsigned, input_unsigned))
277 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000278
279 def MulAttribute(self, shift):
280 from tosa import MulAttribute as a, Attribute
281
282 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800283 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000284
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800285 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000286
287 def ArithmeticRightShiftAttribute(self, round):
288 from tosa import ArithmeticRightShiftAttribute as a, Attribute
289
290 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
291 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800292 a.Start,
293 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000294 )
295
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800296 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000297
Tai Ly81db8ee2024-02-14 19:57:38 +0000298 def CondIfAttribute(self, then_graph, else_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000299 from tosa import CondIfAttribute as a, Attribute
300
301 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800302 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000303
Tai Ly81db8ee2024-02-14 19:57:38 +0000304 self.strings.append((a.AddThenGraph, then_graph))
305 self.strings.append((a.AddElseGraph, else_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000306
Tai Ly81db8ee2024-02-14 19:57:38 +0000307 def WhileLoopAttribute(self, cond_graph, body_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000308 from tosa import WhileLoopAttribute as a, Attribute
309
310 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800311 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000312
Tai Ly81db8ee2024-02-14 19:57:38 +0000313 self.strings.append((a.AddCondGraph, cond_graph))
314 self.strings.append((a.AddBodyGraph, body_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000315
TatWai Chong7be71652022-05-10 17:26:20 -0700316 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700317 from tosa import TransposeAttribute as a, Attribute
318
319 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800320 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700321
TatWai Chong7be71652022-05-10 17:26:20 -0700322 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700323
324 def TableAttribute(self, table):
325 from tosa import TableAttribute as a, Attribute
326
327 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800328 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700329
Jerry Gee7b8eb72023-09-15 17:19:50 +0000330 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000331
James Wardea00fd02023-01-20 16:03:50 +0000332 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000333 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000334
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000335 self.utype = Attribute.Attribute().MatMulAttribute
336 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000337
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000338 self.ints.append((a.AddAZp, A_zp))
339 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000340
James Wardea00fd02023-01-20 16:03:50 +0000341 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000342 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000343
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000344 self.utype = Attribute.Attribute().FullyConnectedAttribute
345 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000346
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000347 self.ints.append((a.AddInputZp, input_zp))
348 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000349
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000350 def NegateAttribute(self, input1_zp, output_zp):
351 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000352
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000353 self.utype = Attribute.Attribute().NegateAttribute
354 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000355
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000356 self.ints.append((a.AddInput1Zp, input1_zp))
357 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000358
Tai Lyf5dfad12023-11-15 21:09:58 +0000359 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000360 from tosa import FFTAttribute as a, Attribute
361
362 self.utype = Attribute.Attribute().FFTAttribute
363 self.optFcns = (a.Start, a.End)
364
365 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000366 self.bools.append((a.AddLocalBound, local_bound))
367
368 def RFFTAttribute(self, local_bound):
369 from tosa import RFFTAttribute as a, Attribute
370
371 self.utype = Attribute.Attribute().RFFTAttribute
372 self.optFcns = (a.Start, a.End)
373
374 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000375
Kevin Chengfea5a372021-10-11 18:38:47 +0000376
377class TosaSerializerTensor:
378 def __init__(
379 self,
380 name,
381 shape,
382 dtype,
383 data=None,
384 placeholderFilename=None,
385 ):
386 self.name = name
387
388 if isinstance(shape, np.ndarray):
389 shape = shape.astype(int).tolist()
390 shape = list(map(int, shape))
391
392 self.shape = shape
393 self.dtype = dtype
394
Won Jeona029f1f2023-12-29 22:43:11 +0000395 if (
396 dtype == DType.FP32
397 or dtype == DType.BF16
398 or dtype == DType.FP8E4M3
399 or dtype == DType.FP8E5M2
400 ):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100401 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100402 elif dtype == DType.FP16:
403 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100404 else:
405 fntype = int
406
Kevin Chengfea5a372021-10-11 18:38:47 +0000407 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100408 data = data.flatten().astype(fntype).tolist()
409 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000410 self.data = data
411 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100412 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000413 self.data = data
414 else:
415 self.data = None
416
417 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000418 # process and are written to disk, but are considered input tensors by the
419 # network so they do not appear in the TOSA serialiazation. However, if we
420 # want to form a unit test around these input tensors, we can get the filename
421 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000422 self.placeholderFilename = placeholderFilename
423
424 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800425 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000426 self.name,
427 self.shape,
428 DTypeNames[self.dtype],
429 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800430 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000431
432 def setDtype(self, dtype):
433 self.dtype = dtype
434
435 def serialize(self, builder):
436 fb_name = builder.CreateString(self.name)
437 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
438 if self.data:
439 u8_data = list()
440 # little endianess
441 if self.dtype == DType.BOOL:
442 for val in self.data:
443 val_u8 = np.uint8(val)
444 u8_data.append(val_u8)
445 elif self.dtype == DType.INT4:
446 in_size = len(self.data)
447 out_size = (in_size + 1) // 2
448 for i in range(out_size):
449 val_0 = self.data[2 * i]
450 if (2 * i + 1) < in_size:
451 val_1 = self.data[2 * i + 1]
452 else:
453 val_1 = 0
454 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
455 val_u8 = np.uint8(val_i8)
456 u8_data.append(val_u8)
457 elif self.dtype == DType.INT8:
458 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700459 val_u8 = np.array(val).astype(dtype=np.uint8)
Kevin Chengfea5a372021-10-11 18:38:47 +0000460 u8_data.append(val_u8)
461 elif self.dtype == DType.INT16:
462 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700463 val_u16 = np.array(val).astype(dtype=np.uint16)
Kevin Chengfea5a372021-10-11 18:38:47 +0000464 b0 = val_u16 & ByteMask
465 b1 = (val_u16 >> np.uint16(8)) & ByteMask
466 u8_data.extend([b0, b1])
467 elif self.dtype == DType.INT32:
468 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700469 val_u32 = np.array(val).astype(dtype=np.uint32)
Kevin Chengfea5a372021-10-11 18:38:47 +0000470 b0 = val_u32 & ByteMask
471 b1 = (val_u32 >> np.uint32(8)) & ByteMask
472 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700473 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000474 u8_data.extend([b0, b1, b2, b3])
Won Jeon7c22d772024-01-23 07:46:08 +0000475 elif self.dtype == DType.INT48:
Kevin Chengfea5a372021-10-11 18:38:47 +0000476 for val in self.data:
477 val_u64 = np.uint64(val)
478 b0 = val_u64 & ByteMask
479 b1 = (val_u64 >> np.uint64(8)) & ByteMask
480 b2 = (val_u64 >> np.uint64(16)) & ByteMask
481 b3 = (val_u64 >> np.uint64(24)) & ByteMask
482 b4 = (val_u64 >> np.uint64(32)) & ByteMask
483 b5 = (val_u64 >> np.uint64(40)) & ByteMask
484 u8_data.extend([b0, b1, b2, b3, b4, b5])
Won Jeon7c22d772024-01-23 07:46:08 +0000485 elif self.dtype == DType.SHAPE:
486 for val in self.data:
487 val_u64 = np.uint64(val)
488 b0 = val_u64 & ByteMask
489 b1 = (val_u64 >> np.uint64(8)) & ByteMask
490 b2 = (val_u64 >> np.uint64(16)) & ByteMask
491 b3 = (val_u64 >> np.uint64(24)) & ByteMask
492 b4 = (val_u64 >> np.uint64(32)) & ByteMask
493 b5 = (val_u64 >> np.uint64(40)) & ByteMask
494 b6 = (val_u64 >> np.uint64(48)) & ByteMask
495 b7 = (val_u64 >> np.uint64(56)) & ByteMask
496 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
James Ward485a11d2022-08-05 13:48:37 +0100497 elif self.dtype == DType.FP16:
498 np_arr = np.array(self.data, dtype=np.float16)
499 u8_data.extend(np_arr.view(np.uint8))
Won Jeona029f1f2023-12-29 22:43:11 +0000500 elif (
501 self.dtype == DType.FP32
502 or self.dtype == DType.BF16
503 or self.dtype == DType.FP8E4M3
504 or self.dtype == DType.FP8E5M2
505 ):
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
Won Jeon7c22d772024-01-23 07:46:08 +0000703 if dtype == DType.SHAPE:
704 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
705 else:
706 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000707
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100708 # Save the const data to file for debug or as input files
709 if vals is not None and self.constMode in [
710 ConstMode.EMBED_DUMP,
711 ConstMode.INPUTS,
712 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100713 filename = "{}.npy".format(name)
714 np.save(os.path.join(self.pathPrefix, filename), vals, False)
715
Kevin Chengfea5a372021-10-11 18:38:47 +0000716 return tens
717
718 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000719 if not self.currBasicBlock:
720 raise Exception("addTensor called without valid basic block")
721
722 name = "layer-{}".format(self.currLayerIdx)
723 self.currLayerIdx = self.currLayerIdx + 1
724
725 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
726
727 return tens
728
729 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700730 self.currBasicBlock.addTensor(
731 tensor.name,
732 tensor.shape,
733 tensor.dtype,
734 tensor.data,
735 tensor.placeholderFilename,
736 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000737 self.currBasicBlock.addInput(tensor.name)
738
739 def addOutputTensor(self, tensor):
740 self.currBasicBlock.addOutput(tensor.name)
741
742 def addOutput(self, shape, dtype):
743 if not self.currBasicBlock:
744 raise Exception("addTensor called without valid basic block")
745
746 name = "result-{}".format(self.currResultIdx)
747 self.currResultIdx = self.currResultIdx + 1
748
749 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
750 self.currBasicBlock.addOutput(name)
751 return tens
752
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000753 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000754 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000755 raise Exception("Use addConstTensor() to add CONST ops")
756
757 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000758 op,
759 inputs,
760 outputs,
761 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000762 )
763
Jerry Ge1eb85042023-01-06 14:19:14 -0800764
765@unique
766class TensorDir(IntEnum):
767 PLACEHOLDER = 0
768 CONST = 1
769 INTERMEDIATE = 2
770 RESULT = 3
771
772
773class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100774 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800775 self.builder = flatbuffers.Builder(0)
776
Jerry Ge1eb85042023-01-06 14:19:14 -0800777 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100778 self.constMode = constMode
779
780 self.regions = []
781 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800782
Jerry Geca7ce0e2023-01-10 17:24:38 +0000783 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800784
785 # Is this an illegal test that is expected to fail?
786 self.expectedReturnCode = 0
787 self.expectedFailure = False
788 self.expectedFailureDesc = ""
789
790 def __str__(self):
791 concatString = ""
792 for region in self.regions:
793 concatString = concatString + str(region)
794 return concatString
795
796 def addPlaceholder(self, shape, dtype, vals):
797 return self.currRegion.addPlaceholder(shape, dtype, vals)
798
Jerry Ge53ceb482023-08-14 20:15:10 +0000799 def addConst(self, shape, dtype, vals, name=None):
800 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800801
802 def addIntermediate(self, shape, dtype):
803 return self.currRegion.addIntermediate(shape, dtype)
804
805 def addInputTensor(self, tensor):
806 self.currRegion.addInputTensor(tensor)
807
808 def addOutputTensor(self, tensor):
809 self.currRegion.addOutputTensor(tensor)
810
811 def addOutput(self, shape, dtype):
812 return self.currRegion.addOutput(shape, dtype)
813
814 def addOperator(self, op, inputs, outputs, attributes=None):
815 return self.currRegion.addOperator(op, inputs, outputs, attributes)
816
Jerry Geca7ce0e2023-01-10 17:24:38 +0000817 def addBasicBlock(self, name):
818 self.currRegion.addBasicBlock(name)
819
Jeremy Johnson9b225172021-12-14 16:34:47 +0000820 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000821
822 self.expectedReturnCode = val
823 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000824 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000825
826 def serialize(self):
827
828 builder = self.builder
829
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800830 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000831 Version.Add_Major(builder, TOSA_VERSION[0])
832 Version.Add_Minor(builder, TOSA_VERSION[1])
833 Version.Add_Patch(builder, TOSA_VERSION[2])
834 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800835 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000836
Jerry Ge1eb85042023-01-06 14:19:14 -0800837 fbv_region = TosaSerializer.serializeObjVec(
838 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000839 )
840
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800841 TosaGraph.Start(builder)
842 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800843 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800844 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000845
Eric Kunzee6596402022-06-09 21:27:36 +0000846 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000847 return self.builder.Output()
848
849 def writeJson(self, tosa_filename):
850 """Write a json test file so that it is fairly easy to pick up the test
851 and generate commands for third party tool"""
852 test_desc = dict()
853
854 test_desc["tosa_file"] = tosa_filename
855 ifm_name = []
856 ifm_file = []
857 ofm_name = []
858 ofm_file = []
859
Jerry Ge1eb85042023-01-06 14:19:14 -0800860 for region in self.regions:
861 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000862 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800863 for i in block.inputs:
864 ifm_name.append(i)
865 ifm_file.append(block.tensors[i].placeholderFilename)
866 for o in block.outputs:
867 ofm_name.append(o)
868 # Make up an OFM filename here. One isn't generated until the
869 # reference tool is run, so any name is a good name
870 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000871
872 test_desc["ifm_name"] = ifm_name
873 test_desc["ifm_file"] = ifm_file
874 test_desc["ofm_name"] = ofm_name
875 test_desc["ofm_file"] = ofm_file
876 test_desc["expected_return_code"] = self.expectedReturnCode
877 test_desc["expected_failure"] = self.expectedFailure
878 if self.expectedFailureDesc:
879 test_desc["expected_failure_desc"] = self.expectedFailureDesc
880
881 return json.dumps(test_desc, indent=" ")
882
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100883 def startRegion(self, name, pathPrefix):
884 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800885 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000886
887 @staticmethod
888 def serializeStrVec(builder, vec, start_fcn):
889 fb_strs = [builder.CreateString(i) for i in vec]
890 start_fcn(builder, len(fb_strs))
891 for s in fb_strs[::-1]:
892 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700893 try:
894 return builder.EndVector()
895 except TypeError:
896 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000897
898 @staticmethod
899 def serializeUint8Vec(builder, vec):
900 builder.StartVector(1, len(vec), 8)
901 for v in vec[::-1]:
902 builder.PrependUint8(v)
903 try:
904 return builder.EndVector()
905 except TypeError:
906 return builder.EndVector(len(vec))
907
908 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700909 def serializeInt16Vec(builder, vec):
910 builder.StartVector(2, len(vec), 4)
911 for v in vec[::-1]:
912 builder.PrependInt16(v)
913 try:
914 return builder.EndVector()
915 except TypeError:
916 return builder.EndVector(len(vec))
917
918 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000919 def serializeInt32Vec(builder, vec):
920 builder.StartVector(4, len(vec), 4)
921 for v in vec[::-1]:
922 builder.PrependInt32(v)
923 try:
924 return builder.EndVector()
925 except TypeError:
926 return builder.EndVector(len(vec))
927
928 @staticmethod
929 def serializeFpVec(builder, vec):
930 builder.StartVector(4, len(vec), 4)
931 for v in vec[::-1]:
932 builder.PrependFloat32(v)
933 try:
934 return builder.EndVector()
935 except TypeError:
936 return builder.EndVector(len(vec))
937
938 @staticmethod
939 def serializeObjVec(builder, vec, start_fcn):
940 serialized_vec = []
941 for v in vec[::-1]:
942 serialized_vec.append(v.serialize(builder))
943
944 start_fcn(builder, len(vec))
945 for v in serialized_vec:
946 builder.PrependUOffsetTRelative(v)
947 try:
948 return builder.EndVector()
949 except TypeError:
950 return builder.EndVector(len(vec))
951
952 @staticmethod
953 def toList(val):
954 if isinstance(val, list):
955 return val
956 else:
957 return [val]