blob: e6ab3d0707c431bcb33aa935bdd0577391bb7a1c [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 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100411 data = list(map(fntype, data))
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100412 elif data is not None:
413 # Assume data is rank 0 data type
414 data = list(map(fntype, [data]))
Kevin Chengfea5a372021-10-11 18:38:47 +0000415 else:
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100416 data = None
417
418 self.data = data
Kevin Chengfea5a372021-10-11 18:38:47 +0000419
420 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000421 # process and are written to disk, but are considered input tensors by the
422 # network so they do not appear in the TOSA serialiazation. However, if we
423 # want to form a unit test around these input tensors, we can get the filename
424 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000425 self.placeholderFilename = placeholderFilename
426
427 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800428 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000429 self.name,
430 self.shape,
431 DTypeNames[self.dtype],
432 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800433 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000434
435 def setDtype(self, dtype):
436 self.dtype = dtype
437
438 def serialize(self, builder):
439 fb_name = builder.CreateString(self.name)
440 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
441 if self.data:
442 u8_data = list()
443 # little endianess
444 if self.dtype == DType.BOOL:
445 for val in self.data:
446 val_u8 = np.uint8(val)
447 u8_data.append(val_u8)
448 elif self.dtype == DType.INT4:
449 in_size = len(self.data)
450 out_size = (in_size + 1) // 2
451 for i in range(out_size):
452 val_0 = self.data[2 * i]
453 if (2 * i + 1) < in_size:
454 val_1 = self.data[2 * i + 1]
455 else:
456 val_1 = 0
457 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
458 val_u8 = np.uint8(val_i8)
459 u8_data.append(val_u8)
460 elif self.dtype == DType.INT8:
461 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700462 val_u8 = np.array(val).astype(dtype=np.uint8)
Kevin Chengfea5a372021-10-11 18:38:47 +0000463 u8_data.append(val_u8)
464 elif self.dtype == DType.INT16:
465 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700466 val_u16 = np.array(val).astype(dtype=np.uint16)
Kevin Chengfea5a372021-10-11 18:38:47 +0000467 b0 = val_u16 & ByteMask
468 b1 = (val_u16 >> np.uint16(8)) & ByteMask
469 u8_data.extend([b0, b1])
470 elif self.dtype == DType.INT32:
471 for val in self.data:
Won Jeon924f3092023-09-15 08:42:28 -0700472 val_u32 = np.array(val).astype(dtype=np.uint32)
Kevin Chengfea5a372021-10-11 18:38:47 +0000473 b0 = val_u32 & ByteMask
474 b1 = (val_u32 >> np.uint32(8)) & ByteMask
475 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700476 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000477 u8_data.extend([b0, b1, b2, b3])
Won Jeon7c22d772024-01-23 07:46:08 +0000478 elif self.dtype == DType.INT48:
Kevin Chengfea5a372021-10-11 18:38:47 +0000479 for val in self.data:
480 val_u64 = np.uint64(val)
481 b0 = val_u64 & ByteMask
482 b1 = (val_u64 >> np.uint64(8)) & ByteMask
483 b2 = (val_u64 >> np.uint64(16)) & ByteMask
484 b3 = (val_u64 >> np.uint64(24)) & ByteMask
485 b4 = (val_u64 >> np.uint64(32)) & ByteMask
486 b5 = (val_u64 >> np.uint64(40)) & ByteMask
487 u8_data.extend([b0, b1, b2, b3, b4, b5])
Won Jeon7c22d772024-01-23 07:46:08 +0000488 elif self.dtype == DType.SHAPE:
489 for val in self.data:
490 val_u64 = np.uint64(val)
491 b0 = val_u64 & ByteMask
492 b1 = (val_u64 >> np.uint64(8)) & ByteMask
493 b2 = (val_u64 >> np.uint64(16)) & ByteMask
494 b3 = (val_u64 >> np.uint64(24)) & ByteMask
495 b4 = (val_u64 >> np.uint64(32)) & ByteMask
496 b5 = (val_u64 >> np.uint64(40)) & ByteMask
497 b6 = (val_u64 >> np.uint64(48)) & ByteMask
498 b7 = (val_u64 >> np.uint64(56)) & ByteMask
499 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
James Ward485a11d2022-08-05 13:48:37 +0100500 elif self.dtype == DType.FP16:
501 np_arr = np.array(self.data, dtype=np.float16)
502 u8_data.extend(np_arr.view(np.uint8))
Won Jeona029f1f2023-12-29 22:43:11 +0000503 elif (
504 self.dtype == DType.FP32
505 or self.dtype == DType.BF16
506 or self.dtype == DType.FP8E4M3
507 or self.dtype == DType.FP8E5M2
508 ):
James Wardc15f7d52022-12-07 15:38:01 +0000509 # for val in self.data:
510 # b = struct.pack("!f", val)
511 # u8_data.extend([b[3], b[2], b[1], b[0]])
512 np_arr = np.array(self.data, dtype=np.float32)
513 u8_data.extend(np_arr.view(np.uint8))
James Ward485a11d2022-08-05 13:48:37 +0100514 elif self.dtype == TosaDType.DType:
515 # Serialize DType enum data as uint8 bytes
516 for val in self.data:
517 np_arr = np.array(self.data, dtype=np.uint32)
518 u8_data.extend(np_arr.view(np.uint8))
Kevin Chengfea5a372021-10-11 18:38:47 +0000519 else:
520 raise Exception(
521 "unsupported data type {}".format(DTypeNames[self.dtype])
522 )
523 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
524
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800525 TosaTensor.Start(builder)
526 TosaTensor.AddName(builder, fb_name)
527 TosaTensor.AddShape(builder, fb_shapes)
528 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000529 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800530 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000531
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800532 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000533
534
535class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000536 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000537 self.op = op
538 self.attributes = attributes
539 self.inputs = TosaSerializer.toList(inputs)
540 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000541
542 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800543 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000544
545 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800546 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000547 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800548 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000549
Jerry Ge1eb85042023-01-06 14:19:14 -0800550 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000551
552 def serialize(self, builder):
553 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800554 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000555 )
556 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800557 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000558 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000559 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000560 if self.attributes is not None:
561 fb_attributes = self.attributes.serialize(builder)
562
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800563 TosaOperator.Start(builder)
564 TosaOperator.AddOp(builder, self.op)
565 TosaOperator.AddInputs(builder, fb_inputs)
566 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000567 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800568 TosaOperator.AddAttributeType(builder, self.attributes.utype)
569 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000570
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800571 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000572
573
574class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000575 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000576 self.name = name
577 self.operators = []
578
579 # Dict assures uniqueness, but allows us to look up by name
580 self.tensors = dict()
581
582 self.inputs = []
583 self.outputs = []
584
585 def addTensor(
586 self,
587 name,
588 shape,
589 dtype,
590 data=None,
591 placeholderFilename=None,
592 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000593 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000594 self.tensors[name] = TosaSerializerTensor(
595 name, shape, dtype, data, placeholderFilename
596 )
597
598 return self.tensors[name]
599
600 def addInput(self, name):
601 self.inputs.append(name)
602
603 def addOutput(self, name):
604 self.outputs.append(name)
605
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000606 def addOperator(self, op, inputs, outputs, attributes=None):
607 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000608
609 def serialize(self, builder):
610 fb_name = builder.CreateString(self.name)
611 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800612 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000613 )
614 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800615 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000616 )
617 fbv_tensors = TosaSerializer.serializeObjVec(
618 builder,
619 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800620 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000621 )
622 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800623 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000624 )
625
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800626 TosaBasicBlock.Start(builder)
627 TosaBasicBlock.AddName(builder, fb_name)
628 TosaBasicBlock.AddInputs(builder, fbv_inputs)
629 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
630 TosaBasicBlock.AddTensors(builder, fbv_tensors)
631 TosaBasicBlock.AddOperators(builder, fbv_operators)
632 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000633
634
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100635# How CONSTs are treated in the flatbuffer
636@unique
637class ConstMode(IntEnum):
638 EMBED = 0
639 EMBED_DUMP = 1
640 INPUTS = 2
641
642
Jerry Ge1eb85042023-01-06 14:19:14 -0800643class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100644 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800645 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000646 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000647 self.currInputIdx = 0
648 self.currConstIdx = 0
649 self.currLayerIdx = 1
650 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800651 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100652 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000653
Jerry Geca7ce0e2023-01-10 17:24:38 +0000654 def addBasicBlock(self, name):
655 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800656 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000657
Jerry Ge1eb85042023-01-06 14:19:14 -0800658 def serialize(self, builder):
659 fb_name = builder.CreateString(self.name)
660 fbv_basicBlocks = TosaSerializer.serializeObjVec(
661 builder, self.basicBlocks, TosaRegion.StartBlocksVector
662 )
663
664 TosaRegion.Start(builder)
665 TosaRegion.AddName(builder, fb_name)
666 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
667 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000668
669 def addPlaceholder(self, shape, dtype, vals):
670 if not self.currBasicBlock:
671 raise Exception("addTensor called without valid basic block")
672
673 name = "input-{}".format(self.currInputIdx)
674 filename = "{}.npy".format(name)
675 self.currInputIdx = self.currInputIdx + 1
676
677 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
678 # This is always an input to the block
679 self.currBasicBlock.addInput(name)
680
681 if vals is not None:
682 np.save(os.path.join(self.pathPrefix, filename), vals, False)
683
684 return tens
685
Jerry Ge53ceb482023-08-14 20:15:10 +0000686 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000687 if not self.currBasicBlock:
688 raise Exception("addTensor called without valid basic block")
689
Jerry Ge53ceb482023-08-14 20:15:10 +0000690 if name is None:
691 name = "const-{}".format(self.currInputIdx)
692 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000693
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100694 if self.constMode == ConstMode.INPUTS:
695 # Save const as input file
696 filename = "{}.npy".format(name)
697 tensor_vals = None
698 self.currBasicBlock.addInput(name)
699 else:
700 # Embed const in flatbuffer
701 filename = None
702 tensor_vals = vals
703
704 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000705 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000706 if dtype == DType.SHAPE:
707 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
708 else:
709 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000710
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100711 # Save the const data to file for debug or as input files
712 if vals is not None and self.constMode in [
713 ConstMode.EMBED_DUMP,
714 ConstMode.INPUTS,
715 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100716 filename = "{}.npy".format(name)
717 np.save(os.path.join(self.pathPrefix, filename), vals, False)
718
Kevin Chengfea5a372021-10-11 18:38:47 +0000719 return tens
720
721 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000722 if not self.currBasicBlock:
723 raise Exception("addTensor called without valid basic block")
724
725 name = "layer-{}".format(self.currLayerIdx)
726 self.currLayerIdx = self.currLayerIdx + 1
727
728 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
729
730 return tens
731
732 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700733 self.currBasicBlock.addTensor(
734 tensor.name,
735 tensor.shape,
736 tensor.dtype,
737 tensor.data,
738 tensor.placeholderFilename,
739 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000740 self.currBasicBlock.addInput(tensor.name)
741
742 def addOutputTensor(self, tensor):
743 self.currBasicBlock.addOutput(tensor.name)
744
745 def addOutput(self, shape, dtype):
746 if not self.currBasicBlock:
747 raise Exception("addTensor called without valid basic block")
748
749 name = "result-{}".format(self.currResultIdx)
750 self.currResultIdx = self.currResultIdx + 1
751
752 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
753 self.currBasicBlock.addOutput(name)
754 return tens
755
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000756 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000757 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000758 raise Exception("Use addConstTensor() to add CONST ops")
759
760 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000761 op,
762 inputs,
763 outputs,
764 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000765 )
766
Jerry Ge1eb85042023-01-06 14:19:14 -0800767
768@unique
769class TensorDir(IntEnum):
770 PLACEHOLDER = 0
771 CONST = 1
772 INTERMEDIATE = 2
773 RESULT = 3
774
775
776class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100777 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800778 self.builder = flatbuffers.Builder(0)
779
Jerry Ge1eb85042023-01-06 14:19:14 -0800780 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100781 self.constMode = constMode
782
783 self.regions = []
784 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800785
Jerry Geca7ce0e2023-01-10 17:24:38 +0000786 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800787
788 # Is this an illegal test that is expected to fail?
789 self.expectedReturnCode = 0
790 self.expectedFailure = False
791 self.expectedFailureDesc = ""
792
793 def __str__(self):
794 concatString = ""
795 for region in self.regions:
796 concatString = concatString + str(region)
797 return concatString
798
799 def addPlaceholder(self, shape, dtype, vals):
800 return self.currRegion.addPlaceholder(shape, dtype, vals)
801
Jerry Ge53ceb482023-08-14 20:15:10 +0000802 def addConst(self, shape, dtype, vals, name=None):
803 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800804
805 def addIntermediate(self, shape, dtype):
806 return self.currRegion.addIntermediate(shape, dtype)
807
808 def addInputTensor(self, tensor):
809 self.currRegion.addInputTensor(tensor)
810
811 def addOutputTensor(self, tensor):
812 self.currRegion.addOutputTensor(tensor)
813
814 def addOutput(self, shape, dtype):
815 return self.currRegion.addOutput(shape, dtype)
816
817 def addOperator(self, op, inputs, outputs, attributes=None):
818 return self.currRegion.addOperator(op, inputs, outputs, attributes)
819
Jerry Geca7ce0e2023-01-10 17:24:38 +0000820 def addBasicBlock(self, name):
821 self.currRegion.addBasicBlock(name)
822
Jeremy Johnson9b225172021-12-14 16:34:47 +0000823 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000824
825 self.expectedReturnCode = val
826 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000827 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000828
829 def serialize(self):
830
831 builder = self.builder
832
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800833 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000834 Version.Add_Major(builder, TOSA_VERSION[0])
835 Version.Add_Minor(builder, TOSA_VERSION[1])
836 Version.Add_Patch(builder, TOSA_VERSION[2])
837 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800838 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000839
Jerry Ge1eb85042023-01-06 14:19:14 -0800840 fbv_region = TosaSerializer.serializeObjVec(
841 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000842 )
843
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800844 TosaGraph.Start(builder)
845 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800846 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800847 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000848
Eric Kunzee6596402022-06-09 21:27:36 +0000849 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000850 return self.builder.Output()
851
852 def writeJson(self, tosa_filename):
853 """Write a json test file so that it is fairly easy to pick up the test
854 and generate commands for third party tool"""
855 test_desc = dict()
856
857 test_desc["tosa_file"] = tosa_filename
858 ifm_name = []
859 ifm_file = []
860 ofm_name = []
861 ofm_file = []
862
Jerry Ge1eb85042023-01-06 14:19:14 -0800863 for region in self.regions:
864 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000865 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800866 for i in block.inputs:
867 ifm_name.append(i)
868 ifm_file.append(block.tensors[i].placeholderFilename)
869 for o in block.outputs:
870 ofm_name.append(o)
871 # Make up an OFM filename here. One isn't generated until the
872 # reference tool is run, so any name is a good name
873 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000874
875 test_desc["ifm_name"] = ifm_name
876 test_desc["ifm_file"] = ifm_file
877 test_desc["ofm_name"] = ofm_name
878 test_desc["ofm_file"] = ofm_file
879 test_desc["expected_return_code"] = self.expectedReturnCode
880 test_desc["expected_failure"] = self.expectedFailure
881 if self.expectedFailureDesc:
882 test_desc["expected_failure_desc"] = self.expectedFailureDesc
883
884 return json.dumps(test_desc, indent=" ")
885
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100886 def startRegion(self, name, pathPrefix):
887 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800888 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000889
890 @staticmethod
891 def serializeStrVec(builder, vec, start_fcn):
892 fb_strs = [builder.CreateString(i) for i in vec]
893 start_fcn(builder, len(fb_strs))
894 for s in fb_strs[::-1]:
895 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700896 try:
897 return builder.EndVector()
898 except TypeError:
899 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000900
901 @staticmethod
902 def serializeUint8Vec(builder, vec):
903 builder.StartVector(1, len(vec), 8)
904 for v in vec[::-1]:
905 builder.PrependUint8(v)
906 try:
907 return builder.EndVector()
908 except TypeError:
909 return builder.EndVector(len(vec))
910
911 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700912 def serializeInt16Vec(builder, vec):
913 builder.StartVector(2, len(vec), 4)
914 for v in vec[::-1]:
915 builder.PrependInt16(v)
916 try:
917 return builder.EndVector()
918 except TypeError:
919 return builder.EndVector(len(vec))
920
921 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000922 def serializeInt32Vec(builder, vec):
923 builder.StartVector(4, len(vec), 4)
924 for v in vec[::-1]:
925 builder.PrependInt32(v)
926 try:
927 return builder.EndVector()
928 except TypeError:
929 return builder.EndVector(len(vec))
930
931 @staticmethod
932 def serializeFpVec(builder, vec):
933 builder.StartVector(4, len(vec), 4)
934 for v in vec[::-1]:
935 builder.PrependFloat32(v)
936 try:
937 return builder.EndVector()
938 except TypeError:
939 return builder.EndVector(len(vec))
940
941 @staticmethod
942 def serializeObjVec(builder, vec, start_fcn):
943 serialized_vec = []
944 for v in vec[::-1]:
945 serialized_vec.append(v.serialize(builder))
946
947 start_fcn(builder, len(vec))
948 for v in serialized_vec:
949 builder.PrependUOffsetTRelative(v)
950 try:
951 return builder.EndVector()
952 except TypeError:
953 return builder.EndVector(len(vec))
954
955 @staticmethod
956 def toList(val):
957 if isinstance(val, list):
958 return val
959 else:
960 return [val]