blob: 298907e997061994c72f02193bf0ac7831b1ad05 [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
Tai Lyce911a22024-03-21 17:01:14 +000020import struct
Jeremy Johnson9b225172021-12-14 16:34:47 +000021from enum import IntEnum, unique
Kevin Chengfea5a372021-10-11 18:38:47 +000022from tosa import (
23 TosaGraph,
Jerry Ge1eb85042023-01-06 14:19:14 -080024 TosaRegion,
Kevin Chengfea5a372021-10-11 18:38:47 +000025 TosaBasicBlock,
26 TosaTensor,
27 TosaOperator,
Kevin Chengfea5a372021-10-11 18:38:47 +000028 Version,
29)
Jeremy Johnson9b225172021-12-14 16:34:47 +000030import tosa.DType as TosaDType
31import tosa.Op as TosaOp
Kevin Chengfea5a372021-10-11 18:38:47 +000032
Kevin Chenge6563f52021-10-20 12:12:02 -070033# Keep version number in sync with the version default value with schema/tosa.fbs
Kevin Chengb97cb1d2021-10-14 11:53:39 -070034TOSA_VERSION_MAJOR = 0
Eric Kunze8137a432024-02-02 21:33:22 +000035TOSA_VERSION_MINOR = 100
Kevin Chengb97cb1d2021-10-14 11:53:39 -070036TOSA_VERSION_PATCH = 0
Eric Kunze8a270432023-06-01 20:08:17 +000037TOSA_VERSION_DRAFT = True
Jeremy Johnson9b225172021-12-14 16:34:47 +000038TOSA_VERSION = [
39 TOSA_VERSION_MAJOR,
40 TOSA_VERSION_MINOR,
41 TOSA_VERSION_PATCH,
42 TOSA_VERSION_DRAFT,
43]
Eric Kunzee6596402022-06-09 21:27:36 +000044
45# File identifier needs to be kept in sync with schema/tosa.fbs
46TOSA_GRAPH_IDENTIFIER = b"\x54\x4F\x53\x41"
47
Kevin Chengfea5a372021-10-11 18:38:47 +000048# With the way flatc generates its python types, there is no programatic way
49# to get string names for the integer types. Manually maintain a string table
50# here.
Jeremy Johnson9b225172021-12-14 16:34:47 +000051DType = TosaDType.DType()
Kevin Chengfea5a372021-10-11 18:38:47 +000052DTypeNames = [
53 "UNKNOWN",
54 "BOOL",
55 "UINT8",
56 "INT4",
57 "INT8",
58 "INT16",
59 "INT32",
60 "INT48",
Jeremy Johnsone1072a92022-09-27 12:44:11 +010061 "FP32",
Jeremy Johnson41027732022-05-25 17:52:29 +010062 "UINT16",
James Ward485a11d2022-08-05 13:48:37 +010063 "FP16",
James Ward34a62792022-10-18 17:27:40 +010064 "BF16",
Won Jeon1adc5d02023-08-12 11:16:05 -070065 "SHAPE",
Won Jeona029f1f2023-12-29 22:43:11 +000066 "FP8E4M3",
67 "FP8E5M2",
Kevin Chengfea5a372021-10-11 18:38:47 +000068]
69
70ByteMask = np.uint64(0xFF)
71
72
73def dtype_str_to_val(name):
74
75 for i in range(len(DTypeNames)):
76 if name.casefold() == DTypeNames[i].casefold():
77 return i
78 raise Exception("Unable to parse DType name {}".format(name))
79
80
81class TosaSerializerUnion:
82 """This class handles encapsulating and serializing union types into flatbuffers"""
83
84 def __init__(self):
85
Jeremy Johnson9b225172021-12-14 16:34:47 +000086 # A tuple of the start and end functions.
87 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000088 self.optFcns = None
89
Jeremy Johnson9b225172021-12-14 16:34:47 +000090 # The type from the tosa.Options enumeration.
91 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000092 self.utype = None
93
94 # Each of these lists is a tuple of the add function and the
95 # value being added. Set by the options constructors below.
96 self.ints = []
97 self.bools = []
98 self.floats = []
99 self.strings = []
TatWai Chong49b1ca62022-06-10 01:49:13 -0700100 self.int16vecs = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000101 self.intvecs = []
102 self.fpvecs = []
103
104 def serialize(self, builder):
105
106 # We have to build strings and vectors first
107 strList = []
108 intVecList = []
109 fpVecList = []
110
111 for fcn, val in self.strings:
112 strList.append((fcn, builder.CreateString(val)))
113
114 for fcn, val in self.intvecs:
115 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
116
TatWai Chong49b1ca62022-06-10 01:49:13 -0700117 for fcn, val in self.int16vecs:
118 intVecList.append((fcn, TosaSerializer.serializeInt16Vec(builder, val)))
119
Kevin Chengfea5a372021-10-11 18:38:47 +0000120 for fcn, val in self.fpvecs:
121 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
122
123 startFcn, endFcn = self.optFcns
124
125 # Then serialize the options object from the list of primitives and
126 # other serialized values
127 startFcn(builder)
128 for fcn, val in self.ints:
129 fcn(builder, val)
130
131 for fcn, val in self.bools:
132 fcn(builder, val)
133
134 for fcn, val in self.floats:
135 fcn(builder, val)
136
137 for fcn, val in strList:
138 fcn(builder, val)
139
140 for fcn, val in intVecList:
141 fcn(builder, val)
142
143 for fcn, val in fpVecList:
144 fcn(builder, val)
145
146 return endFcn(builder)
147
148
149class TosaSerializerAttribute(TosaSerializerUnion):
150 """This class handles encapsulating all of the enumerated types for attributes"""
151
152 def __init__(self):
153 super().__init__()
154
James Ward485a11d2022-08-05 13:48:37 +0100155 def PoolAttribute(
156 self,
157 kernel,
158 stride,
159 pad,
160 input_zp,
161 output_zp,
Tai Ly81db8ee2024-02-14 19:57:38 +0000162 acc_type,
James Ward485a11d2022-08-05 13:48:37 +0100163 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000164 from tosa import PoolAttribute as a, Attribute
165
166 self.utype = Attribute.Attribute().PoolAttribute
167
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800168 self.optFcns = (a.Start, a.End)
TatWai Chong7be71652022-05-10 17:26:20 -0700169 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800170 self.intvecs.append((a.AddKernel, kernel))
171 self.intvecs.append((a.AddStride, stride))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000172 self.ints.append((a.AddInputZp, input_zp))
173 self.ints.append((a.AddOutputZp, output_zp))
Tai Ly81db8ee2024-02-14 19:57:38 +0000174 self.ints.append((a.AddAccType, acc_type))
Kevin Chengfea5a372021-10-11 18:38:47 +0000175
Tai Lyad78daa2024-03-13 18:52:45 +0000176 def ConvAttribute(
177 self, pad, stride, dilation, input_zp, weight_zp, local_bound, acc_type
178 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000179 from tosa import ConvAttribute as a, Attribute
180
181 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800182 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000183
TatWai Chong7be71652022-05-10 17:26:20 -0700184 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800185 self.intvecs.append((a.AddStride, stride))
186 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000187 self.ints.append((a.AddInputZp, input_zp))
188 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000189 self.bools.append((a.AddLocalBound, local_bound))
Tai Lyad78daa2024-03-13 18:52:45 +0000190 self.ints.append((a.AddAccType, acc_type))
Kevin Chengfea5a372021-10-11 18:38:47 +0000191
Tai Lyf5dfad12023-11-15 21:09:58 +0000192 def TransposeConvAttribute(
Tai Lyad78daa2024-03-13 18:52:45 +0000193 self, outpad, stride, output_shape, input_zp, weight_zp, local_bound, acc_type
Tai Lyf5dfad12023-11-15 21:09:58 +0000194 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000195 from tosa import TransposeConvAttribute as a, Attribute
196
197 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800198 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000199
Eric Kunze4c3537d2022-06-13 17:21:48 -0700200 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800201 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800202 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000203 self.ints.append((a.AddInputZp, input_zp))
204 self.ints.append((a.AddWeightZp, weight_zp))
Tai Lyf5dfad12023-11-15 21:09:58 +0000205 self.bools.append((a.AddLocalBound, local_bound))
Tai Lyad78daa2024-03-13 18:52:45 +0000206 self.ints.append((a.AddAccType, acc_type))
Kevin Chengfea5a372021-10-11 18:38:47 +0000207
Tai Lyce911a22024-03-21 17:01:14 +0000208 def PadAttribute(self, serializer_builder, pad_const_val_as_bytes, dtype):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700209 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000210
Kevin Cheng38d214c2021-10-15 15:49:19 -0700211 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800212 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000213
Tai Ly0b6d7c22024-03-08 17:03:25 +0000214 # serialize pad_const_val_as_bytes as uint8 vector
215 serialized_pad_const_val = ts.TosaSerializer.serializeUint8Vec(
216 serializer_builder, pad_const_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000217 )
218
Tai Ly0b6d7c22024-03-08 17:03:25 +0000219 self.floats.append((a.AddPadConst, serialized_pad_const_val))
Tai Lyce911a22024-03-21 17:01:14 +0000220 self.ints.append((a.AddType, dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000221
222 def AxisAttribute(self, axis):
223 from tosa import AxisAttribute as a, Attribute
224
225 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800226 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000227
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800228 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000229
TatWai Chong49b1ca62022-06-10 01:49:13 -0700230 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000231 from tosa import ResizeAttribute as a, Attribute
232
233 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800234 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000235
TatWai Chong49b1ca62022-06-10 01:49:13 -0700236 self.int16vecs.append((a.AddScale, scale))
237 self.int16vecs.append((a.AddOffset, offset))
238 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800239 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000240
Tai Lyce911a22024-03-21 17:01:14 +0000241 def ClampAttribute(
242 self, serializer_builder, min_val_as_bytes, max_val_as_bytes, dtype
243 ):
Kevin Chengfea5a372021-10-11 18:38:47 +0000244 from tosa import ClampAttribute as a, Attribute
245
246 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800247 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000248
James Wardc15f7d52022-12-07 15:38:01 +0000249 # min/max float attributes serialized as uint8 vectors
Tai Ly0b6d7c22024-03-08 17:03:25 +0000250 serialized_min_val = ts.TosaSerializer.serializeUint8Vec(
251 serializer_builder, min_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000252 )
Tai Ly0b6d7c22024-03-08 17:03:25 +0000253 serialized_max_val = ts.TosaSerializer.serializeUint8Vec(
254 serializer_builder, max_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000255 )
256
Tai Ly0b6d7c22024-03-08 17:03:25 +0000257 self.floats.append((a.AddMinVal, serialized_min_val))
258 self.floats.append((a.AddMaxVal, serialized_max_val))
Tai Lyce911a22024-03-21 17:01:14 +0000259 self.ints.append((a.AddType, dtype))
Kevin Chengfea5a372021-10-11 18:38:47 +0000260
261 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000262 self,
263 input_zp,
264 output_zp,
James Ward92358fc2023-11-21 18:14:43 +0000265 scale32,
266 double_round,
267 per_channel,
268 input_unsigned,
269 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000270 ):
271 from tosa import RescaleAttribute as a, Attribute
272
273 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800274 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000275
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800276 self.ints.append((a.AddInputZp, input_zp))
277 self.ints.append((a.AddOutputZp, output_zp))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800278 self.bools.append((a.AddScale32, scale32))
279 self.bools.append((a.AddDoubleRound, double_round))
280 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000281 self.bools.append((a.AddInputUnsigned, input_unsigned))
282 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000283
284 def MulAttribute(self, shift):
285 from tosa import MulAttribute as a, Attribute
286
287 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800288 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000289
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800290 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000291
292 def ArithmeticRightShiftAttribute(self, round):
293 from tosa import ArithmeticRightShiftAttribute as a, Attribute
294
295 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
296 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800297 a.Start,
298 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000299 )
300
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800301 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000302
Tai Ly81db8ee2024-02-14 19:57:38 +0000303 def CondIfAttribute(self, then_graph, else_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000304 from tosa import CondIfAttribute as a, Attribute
305
306 self.utype = Attribute.Attribute().CondIfAttribute
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.AddThenGraph, then_graph))
310 self.strings.append((a.AddElseGraph, else_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000311
Tai Ly81db8ee2024-02-14 19:57:38 +0000312 def WhileLoopAttribute(self, cond_graph, body_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000313 from tosa import WhileLoopAttribute as a, Attribute
314
315 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800316 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000317
Tai Ly81db8ee2024-02-14 19:57:38 +0000318 self.strings.append((a.AddCondGraph, cond_graph))
319 self.strings.append((a.AddBodyGraph, body_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000320
TatWai Chong7be71652022-05-10 17:26:20 -0700321 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700322 from tosa import TransposeAttribute as a, Attribute
323
324 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800325 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700326
TatWai Chong7be71652022-05-10 17:26:20 -0700327 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700328
329 def TableAttribute(self, table):
330 from tosa import TableAttribute as a, Attribute
331
332 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800333 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700334
Jerry Gee7b8eb72023-09-15 17:19:50 +0000335 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000336
James Wardea00fd02023-01-20 16:03:50 +0000337 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000338 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000339
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000340 self.utype = Attribute.Attribute().MatMulAttribute
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.AddAZp, A_zp))
344 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000345
James Wardea00fd02023-01-20 16:03:50 +0000346 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000347 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000348
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000349 self.utype = Attribute.Attribute().FullyConnectedAttribute
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.AddInputZp, input_zp))
353 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000354
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000355 def NegateAttribute(self, input1_zp, output_zp):
356 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000357
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000358 self.utype = Attribute.Attribute().NegateAttribute
359 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000360
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000361 self.ints.append((a.AddInput1Zp, input1_zp))
362 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000363
Tai Lyf5dfad12023-11-15 21:09:58 +0000364 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000365 from tosa import FFTAttribute as a, Attribute
366
367 self.utype = Attribute.Attribute().FFTAttribute
368 self.optFcns = (a.Start, a.End)
369
370 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000371 self.bools.append((a.AddLocalBound, local_bound))
372
373 def RFFTAttribute(self, local_bound):
374 from tosa import RFFTAttribute as a, Attribute
375
376 self.utype = Attribute.Attribute().RFFTAttribute
377 self.optFcns = (a.Start, a.End)
378
379 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000380
Kevin Chengfea5a372021-10-11 18:38:47 +0000381
382class TosaSerializerTensor:
383 def __init__(
384 self,
385 name,
386 shape,
387 dtype,
388 data=None,
389 placeholderFilename=None,
390 ):
391 self.name = name
392
393 if isinstance(shape, np.ndarray):
394 shape = shape.astype(int).tolist()
395 shape = list(map(int, shape))
396
397 self.shape = shape
398 self.dtype = dtype
399
Won Jeona029f1f2023-12-29 22:43:11 +0000400 if (
401 dtype == DType.FP32
402 or dtype == DType.BF16
403 or dtype == DType.FP8E4M3
404 or dtype == DType.FP8E5M2
405 ):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100406 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100407 elif dtype == DType.FP16:
408 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100409 else:
410 fntype = int
411
Kevin Chengfea5a372021-10-11 18:38:47 +0000412 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100413 data = data.flatten().astype(fntype).tolist()
414 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000415 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100416 data = list(map(fntype, data))
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100417 elif data is not None:
418 # Assume data is rank 0 data type
419 data = list(map(fntype, [data]))
Kevin Chengfea5a372021-10-11 18:38:47 +0000420 else:
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100421 data = None
422
423 self.data = data
Kevin Chengfea5a372021-10-11 18:38:47 +0000424
425 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000426 # process and are written to disk, but are considered input tensors by the
427 # network so they do not appear in the TOSA serialiazation. However, if we
428 # want to form a unit test around these input tensors, we can get the filename
429 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000430 self.placeholderFilename = placeholderFilename
431
432 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800433 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000434 self.name,
435 self.shape,
436 DTypeNames[self.dtype],
437 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800438 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000439
440 def setDtype(self, dtype):
441 self.dtype = dtype
442
443 def serialize(self, builder):
444 fb_name = builder.CreateString(self.name)
445 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
446 if self.data:
Tai Lyce911a22024-03-21 17:01:14 +0000447 u8_data = TosaSerializer.convertDataToUint8Vec(self.dtype, self.data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000448 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
449
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800450 TosaTensor.Start(builder)
451 TosaTensor.AddName(builder, fb_name)
452 TosaTensor.AddShape(builder, fb_shapes)
453 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000454 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800455 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000456
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800457 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000458
459
460class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000461 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000462 self.op = op
463 self.attributes = attributes
464 self.inputs = TosaSerializer.toList(inputs)
465 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000466
467 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800468 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000469
470 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800471 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000472 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800473 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000474
Jerry Ge1eb85042023-01-06 14:19:14 -0800475 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000476
477 def serialize(self, builder):
478 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800479 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000480 )
481 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800482 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000483 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000484 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000485 if self.attributes is not None:
486 fb_attributes = self.attributes.serialize(builder)
487
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800488 TosaOperator.Start(builder)
489 TosaOperator.AddOp(builder, self.op)
490 TosaOperator.AddInputs(builder, fb_inputs)
491 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000492 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800493 TosaOperator.AddAttributeType(builder, self.attributes.utype)
494 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000495
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800496 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000497
498
499class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000500 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000501 self.name = name
502 self.operators = []
503
504 # Dict assures uniqueness, but allows us to look up by name
505 self.tensors = dict()
506
507 self.inputs = []
508 self.outputs = []
509
510 def addTensor(
511 self,
512 name,
513 shape,
514 dtype,
515 data=None,
516 placeholderFilename=None,
517 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000518 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000519 self.tensors[name] = TosaSerializerTensor(
520 name, shape, dtype, data, placeholderFilename
521 )
522
523 return self.tensors[name]
524
525 def addInput(self, name):
526 self.inputs.append(name)
527
528 def addOutput(self, name):
529 self.outputs.append(name)
530
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000531 def addOperator(self, op, inputs, outputs, attributes=None):
532 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000533
534 def serialize(self, builder):
535 fb_name = builder.CreateString(self.name)
536 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800537 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000538 )
539 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800540 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000541 )
542 fbv_tensors = TosaSerializer.serializeObjVec(
543 builder,
544 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800545 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000546 )
547 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800548 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000549 )
550
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800551 TosaBasicBlock.Start(builder)
552 TosaBasicBlock.AddName(builder, fb_name)
553 TosaBasicBlock.AddInputs(builder, fbv_inputs)
554 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
555 TosaBasicBlock.AddTensors(builder, fbv_tensors)
556 TosaBasicBlock.AddOperators(builder, fbv_operators)
557 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000558
559
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100560# How CONSTs are treated in the flatbuffer
561@unique
562class ConstMode(IntEnum):
563 EMBED = 0
564 EMBED_DUMP = 1
565 INPUTS = 2
566
567
Jerry Ge1eb85042023-01-06 14:19:14 -0800568class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100569 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800570 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000571 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000572 self.currInputIdx = 0
573 self.currConstIdx = 0
574 self.currLayerIdx = 1
575 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800576 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100577 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000578
Jerry Geca7ce0e2023-01-10 17:24:38 +0000579 def addBasicBlock(self, name):
580 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800581 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000582
Jerry Ge1eb85042023-01-06 14:19:14 -0800583 def serialize(self, builder):
584 fb_name = builder.CreateString(self.name)
585 fbv_basicBlocks = TosaSerializer.serializeObjVec(
586 builder, self.basicBlocks, TosaRegion.StartBlocksVector
587 )
588
589 TosaRegion.Start(builder)
590 TosaRegion.AddName(builder, fb_name)
591 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
592 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000593
594 def addPlaceholder(self, shape, dtype, vals):
595 if not self.currBasicBlock:
596 raise Exception("addTensor called without valid basic block")
597
598 name = "input-{}".format(self.currInputIdx)
599 filename = "{}.npy".format(name)
600 self.currInputIdx = self.currInputIdx + 1
601
602 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
603 # This is always an input to the block
604 self.currBasicBlock.addInput(name)
605
606 if vals is not None:
607 np.save(os.path.join(self.pathPrefix, filename), vals, False)
608
609 return tens
610
Jerry Ge53ceb482023-08-14 20:15:10 +0000611 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000612 if not self.currBasicBlock:
613 raise Exception("addTensor called without valid basic block")
614
Jerry Ge53ceb482023-08-14 20:15:10 +0000615 if name is None:
616 name = "const-{}".format(self.currInputIdx)
617 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000618
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100619 if self.constMode == ConstMode.INPUTS:
620 # Save const as input file
621 filename = "{}.npy".format(name)
622 tensor_vals = None
623 self.currBasicBlock.addInput(name)
624 else:
625 # Embed const in flatbuffer
626 filename = None
627 tensor_vals = vals
628
629 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000630 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000631 if dtype == DType.SHAPE:
632 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
633 else:
634 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000635
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100636 # Save the const data to file for debug or as input files
637 if vals is not None and self.constMode in [
638 ConstMode.EMBED_DUMP,
639 ConstMode.INPUTS,
640 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100641 filename = "{}.npy".format(name)
642 np.save(os.path.join(self.pathPrefix, filename), vals, False)
643
Kevin Chengfea5a372021-10-11 18:38:47 +0000644 return tens
645
646 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000647 if not self.currBasicBlock:
648 raise Exception("addTensor called without valid basic block")
649
650 name = "layer-{}".format(self.currLayerIdx)
651 self.currLayerIdx = self.currLayerIdx + 1
652
653 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
654
655 return tens
656
657 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700658 self.currBasicBlock.addTensor(
659 tensor.name,
660 tensor.shape,
661 tensor.dtype,
662 tensor.data,
663 tensor.placeholderFilename,
664 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000665 self.currBasicBlock.addInput(tensor.name)
666
667 def addOutputTensor(self, tensor):
668 self.currBasicBlock.addOutput(tensor.name)
669
670 def addOutput(self, shape, dtype):
671 if not self.currBasicBlock:
672 raise Exception("addTensor called without valid basic block")
673
674 name = "result-{}".format(self.currResultIdx)
675 self.currResultIdx = self.currResultIdx + 1
676
677 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
678 self.currBasicBlock.addOutput(name)
679 return tens
680
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000681 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000682 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000683 raise Exception("Use addConstTensor() to add CONST ops")
684
685 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000686 op,
687 inputs,
688 outputs,
689 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000690 )
691
Jerry Ge1eb85042023-01-06 14:19:14 -0800692
693@unique
694class TensorDir(IntEnum):
695 PLACEHOLDER = 0
696 CONST = 1
697 INTERMEDIATE = 2
698 RESULT = 3
699
700
701class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100702 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800703 self.builder = flatbuffers.Builder(0)
704
Jerry Ge1eb85042023-01-06 14:19:14 -0800705 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100706 self.constMode = constMode
707
708 self.regions = []
709 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800710
Jerry Geca7ce0e2023-01-10 17:24:38 +0000711 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800712
713 # Is this an illegal test that is expected to fail?
714 self.expectedReturnCode = 0
715 self.expectedFailure = False
716 self.expectedFailureDesc = ""
717
718 def __str__(self):
719 concatString = ""
720 for region in self.regions:
721 concatString = concatString + str(region)
722 return concatString
723
724 def addPlaceholder(self, shape, dtype, vals):
725 return self.currRegion.addPlaceholder(shape, dtype, vals)
726
Jerry Ge53ceb482023-08-14 20:15:10 +0000727 def addConst(self, shape, dtype, vals, name=None):
728 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800729
730 def addIntermediate(self, shape, dtype):
731 return self.currRegion.addIntermediate(shape, dtype)
732
733 def addInputTensor(self, tensor):
734 self.currRegion.addInputTensor(tensor)
735
736 def addOutputTensor(self, tensor):
737 self.currRegion.addOutputTensor(tensor)
738
739 def addOutput(self, shape, dtype):
740 return self.currRegion.addOutput(shape, dtype)
741
742 def addOperator(self, op, inputs, outputs, attributes=None):
743 return self.currRegion.addOperator(op, inputs, outputs, attributes)
744
Jerry Geca7ce0e2023-01-10 17:24:38 +0000745 def addBasicBlock(self, name):
746 self.currRegion.addBasicBlock(name)
747
Jeremy Johnson9b225172021-12-14 16:34:47 +0000748 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000749
750 self.expectedReturnCode = val
751 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000752 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000753
754 def serialize(self):
755
756 builder = self.builder
757
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800758 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000759 Version.Add_Major(builder, TOSA_VERSION[0])
760 Version.Add_Minor(builder, TOSA_VERSION[1])
761 Version.Add_Patch(builder, TOSA_VERSION[2])
762 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800763 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000764
Jerry Ge1eb85042023-01-06 14:19:14 -0800765 fbv_region = TosaSerializer.serializeObjVec(
766 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000767 )
768
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800769 TosaGraph.Start(builder)
770 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800771 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800772 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000773
Eric Kunzee6596402022-06-09 21:27:36 +0000774 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000775 return self.builder.Output()
776
777 def writeJson(self, tosa_filename):
778 """Write a json test file so that it is fairly easy to pick up the test
779 and generate commands for third party tool"""
780 test_desc = dict()
781
782 test_desc["tosa_file"] = tosa_filename
783 ifm_name = []
784 ifm_file = []
785 ofm_name = []
786 ofm_file = []
787
Jerry Ge1eb85042023-01-06 14:19:14 -0800788 for region in self.regions:
789 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000790 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800791 for i in block.inputs:
792 ifm_name.append(i)
793 ifm_file.append(block.tensors[i].placeholderFilename)
794 for o in block.outputs:
795 ofm_name.append(o)
796 # Make up an OFM filename here. One isn't generated until the
797 # reference tool is run, so any name is a good name
798 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000799
800 test_desc["ifm_name"] = ifm_name
801 test_desc["ifm_file"] = ifm_file
802 test_desc["ofm_name"] = ofm_name
803 test_desc["ofm_file"] = ofm_file
804 test_desc["expected_return_code"] = self.expectedReturnCode
805 test_desc["expected_failure"] = self.expectedFailure
806 if self.expectedFailureDesc:
807 test_desc["expected_failure_desc"] = self.expectedFailureDesc
808
809 return json.dumps(test_desc, indent=" ")
810
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100811 def startRegion(self, name, pathPrefix):
812 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800813 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000814
815 @staticmethod
816 def serializeStrVec(builder, vec, start_fcn):
817 fb_strs = [builder.CreateString(i) for i in vec]
818 start_fcn(builder, len(fb_strs))
819 for s in fb_strs[::-1]:
820 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700821 try:
822 return builder.EndVector()
823 except TypeError:
824 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000825
826 @staticmethod
827 def serializeUint8Vec(builder, vec):
828 builder.StartVector(1, len(vec), 8)
829 for v in vec[::-1]:
830 builder.PrependUint8(v)
831 try:
832 return builder.EndVector()
833 except TypeError:
834 return builder.EndVector(len(vec))
835
836 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700837 def serializeInt16Vec(builder, vec):
838 builder.StartVector(2, len(vec), 4)
839 for v in vec[::-1]:
840 builder.PrependInt16(v)
841 try:
842 return builder.EndVector()
843 except TypeError:
844 return builder.EndVector(len(vec))
845
846 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000847 def serializeInt32Vec(builder, vec):
848 builder.StartVector(4, len(vec), 4)
849 for v in vec[::-1]:
850 builder.PrependInt32(v)
851 try:
852 return builder.EndVector()
853 except TypeError:
854 return builder.EndVector(len(vec))
855
856 @staticmethod
857 def serializeFpVec(builder, vec):
858 builder.StartVector(4, len(vec), 4)
859 for v in vec[::-1]:
860 builder.PrependFloat32(v)
861 try:
862 return builder.EndVector()
863 except TypeError:
864 return builder.EndVector(len(vec))
865
866 @staticmethod
867 def serializeObjVec(builder, vec, start_fcn):
868 serialized_vec = []
869 for v in vec[::-1]:
870 serialized_vec.append(v.serialize(builder))
871
872 start_fcn(builder, len(vec))
873 for v in serialized_vec:
874 builder.PrependUOffsetTRelative(v)
875 try:
876 return builder.EndVector()
877 except TypeError:
878 return builder.EndVector(len(vec))
879
880 @staticmethod
881 def toList(val):
882 if isinstance(val, list):
883 return val
884 else:
885 return [val]
Tai Lyce911a22024-03-21 17:01:14 +0000886
887 @staticmethod
888 def convertDataToUint8Vec(dtype, data):
889 u8_data = list()
890 # little endianess
891 if dtype == DType.BOOL:
892 for val in data:
893 val_u8 = np.uint8(val)
894 u8_data.append(val_u8)
895 elif dtype == DType.INT4:
896 in_size = len(data)
897 out_size = (in_size + 1) // 2
898 for i in range(out_size):
899 val_0 = data[2 * i]
900 if (2 * i + 1) < in_size:
901 val_1 = data[2 * i + 1]
902 else:
903 val_1 = 0
904 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
905 val_u8 = np.uint8(val_i8)
906 u8_data.append(val_u8)
907 elif dtype == DType.INT8:
908 for val in data:
909 val_u8 = np.array(val).astype(dtype=np.uint8)
910 u8_data.append(val_u8)
911 elif dtype == DType.INT16:
912 for val in data:
913 val_u16 = np.array(val).astype(dtype=np.uint16)
914 b0 = val_u16 & ByteMask
915 b1 = (val_u16 >> np.uint16(8)) & ByteMask
916 u8_data.extend([b0, b1])
917 elif dtype == DType.INT32:
918 for val in data:
919 val_u32 = np.array(val).astype(dtype=np.uint32)
920 b0 = val_u32 & ByteMask
921 b1 = (val_u32 >> np.uint32(8)) & ByteMask
922 b2 = (val_u32 >> np.uint32(16)) & ByteMask
923 b3 = (val_u32 >> np.uint32(24)) & ByteMask
924 u8_data.extend([b0, b1, b2, b3])
925 elif dtype == DType.INT48:
926 for val in data:
927 val_u64 = np.uint64(val)
928 b0 = val_u64 & ByteMask
929 b1 = (val_u64 >> np.uint64(8)) & ByteMask
930 b2 = (val_u64 >> np.uint64(16)) & ByteMask
931 b3 = (val_u64 >> np.uint64(24)) & ByteMask
932 b4 = (val_u64 >> np.uint64(32)) & ByteMask
933 b5 = (val_u64 >> np.uint64(40)) & ByteMask
934 u8_data.extend([b0, b1, b2, b3, b4, b5])
935 elif dtype == DType.SHAPE:
936 for val in data:
937 val_u64 = np.uint64(val)
938 b0 = val_u64 & ByteMask
939 b1 = (val_u64 >> np.uint64(8)) & ByteMask
940 b2 = (val_u64 >> np.uint64(16)) & ByteMask
941 b3 = (val_u64 >> np.uint64(24)) & ByteMask
942 b4 = (val_u64 >> np.uint64(32)) & ByteMask
943 b5 = (val_u64 >> np.uint64(40)) & ByteMask
944 b6 = (val_u64 >> np.uint64(48)) & ByteMask
945 b7 = (val_u64 >> np.uint64(56)) & ByteMask
946 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
947 elif dtype == DType.FP16:
948 np_arr = np.array(data, dtype=np.float16)
949 u8_data.extend(np_arr.view(np.uint8))
950 elif dtype == DType.FP32:
951 # for val in data:
952 # b = struct.pack("!f", val)
953 # u8_data.extend([b[3], b[2], b[1], b[0]])
954 np_arr = np.array(data, dtype=np.float32)
955 u8_data.extend(np_arr.view(np.uint8))
956 elif dtype == DType.BF16:
957 for val in data:
958 # convert val to little endian byte arrays b
959 b = struct.pack("<f", val)
960 # val => [ b[3], b[2], b[1], b[0] ]
961 # keep only most significant 2 bytes for bf16
962 # in little endian ordering
963 u8_data.extend([b[2], b[3]])
964 elif dtype == DType.FP8E4M3:
965 for val in data:
966 # convert val to fp8_bits then to single byte
967 f32_as_int = struct.unpack(">L", struct.pack(">f", val))[0]
968 f32_bits = f"{f32_as_int:032b}"
969 fp8_bits = f32_bits[0] + f32_bits[1:5] + f32_bits[9:12]
970 fp8_bytes = int(fp8_bits, 2).to_bytes(1, byteorder="little")
971 u8_data.extend(fp8_bytes)
972 elif dtype == DType.FP8E5M2:
973 for val in data:
974 # convert val to fp8_bits then to single byte
975 f32_as_int = struct.unpack(">L", struct.pack(">f", val))[0]
976 f32_bits = f"{f32_as_int:032b}"
977 fp8_bits = f32_bits[0] + f32_bits[1:6] + f32_bits[9:11]
978 fp8_bytes = int(fp8_bits, 2).to_bytes(1, byteorder="little")
979 u8_data.extend(fp8_bytes)
980 elif dtype == TosaDType.DType:
981 # Serialize DType enum data as uint8 bytes
982 for val in data:
983 np_arr = np.array(data, dtype=np.uint32)
984 u8_data.extend(np_arr.view(np.uint8))
985 else:
986 raise Exception("unsupported data type {}".format(DTypeNames[dtype]))
987 return u8_data