blob: c417fcec480b7d541d0b5708dacf9e5d8d1e7ed6 [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
Won Jeona8141522024-04-29 23:57:27 +000020from ml_dtypes import bfloat16, float8_e4m3fn, float8_e5m2
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
Eric Kunze816f60e2024-04-19 19:31:31 +000034TOSA_VERSION_MAJOR = 1
Eric Kunze36ced1d2024-04-25 04:23:50 +000035TOSA_VERSION_MINOR = 1
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(
Suraj Sudhir50256e12024-03-14 23:44:54 +0000193 self, outpad, stride, 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))
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 Ly57d78182024-04-09 19:31:24 +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
Tai Lyad228702024-05-16 17:31:42 +0000228 def ResizeAttribute(self, 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
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800234 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000235
Tai Ly57d78182024-04-09 19:31:24 +0000236 def ClampAttribute(self, serializer_builder, min_val_as_bytes, max_val_as_bytes):
Kevin Chengfea5a372021-10-11 18:38:47 +0000237 from tosa import ClampAttribute as a, Attribute
238
239 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800240 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000241
James Wardc15f7d52022-12-07 15:38:01 +0000242 # min/max float attributes serialized as uint8 vectors
Tai Ly0b6d7c22024-03-08 17:03:25 +0000243 serialized_min_val = ts.TosaSerializer.serializeUint8Vec(
244 serializer_builder, min_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000245 )
Tai Ly0b6d7c22024-03-08 17:03:25 +0000246 serialized_max_val = ts.TosaSerializer.serializeUint8Vec(
247 serializer_builder, max_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000248 )
249
Tai Ly0b6d7c22024-03-08 17:03:25 +0000250 self.floats.append((a.AddMinVal, serialized_min_val))
251 self.floats.append((a.AddMaxVal, serialized_max_val))
Kevin Chengfea5a372021-10-11 18:38:47 +0000252
253 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000254 self,
255 input_zp,
256 output_zp,
James Ward92358fc2023-11-21 18:14:43 +0000257 scale32,
258 double_round,
259 per_channel,
260 input_unsigned,
261 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000262 ):
263 from tosa import RescaleAttribute as a, Attribute
264
265 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800266 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000267
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800268 self.ints.append((a.AddInputZp, input_zp))
269 self.ints.append((a.AddOutputZp, output_zp))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800270 self.bools.append((a.AddScale32, scale32))
271 self.bools.append((a.AddDoubleRound, double_round))
272 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000273 self.bools.append((a.AddInputUnsigned, input_unsigned))
274 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000275
276 def MulAttribute(self, shift):
277 from tosa import MulAttribute as a, Attribute
278
279 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800280 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000281
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800282 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000283
284 def ArithmeticRightShiftAttribute(self, round):
285 from tosa import ArithmeticRightShiftAttribute as a, Attribute
286
287 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
288 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800289 a.Start,
290 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000291 )
292
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800293 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000294
Tai Ly81db8ee2024-02-14 19:57:38 +0000295 def CondIfAttribute(self, then_graph, else_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000296 from tosa import CondIfAttribute as a, Attribute
297
298 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800299 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000300
Tai Ly81db8ee2024-02-14 19:57:38 +0000301 self.strings.append((a.AddThenGraph, then_graph))
302 self.strings.append((a.AddElseGraph, else_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000303
Tai Ly81db8ee2024-02-14 19:57:38 +0000304 def WhileLoopAttribute(self, cond_graph, body_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000305 from tosa import WhileLoopAttribute as a, Attribute
306
307 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800308 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000309
Tai Ly81db8ee2024-02-14 19:57:38 +0000310 self.strings.append((a.AddCondGraph, cond_graph))
311 self.strings.append((a.AddBodyGraph, body_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000312
TatWai Chong7be71652022-05-10 17:26:20 -0700313 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700314 from tosa import TransposeAttribute as a, Attribute
315
316 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800317 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700318
TatWai Chong7be71652022-05-10 17:26:20 -0700319 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700320
321 def TableAttribute(self, table):
322 from tosa import TableAttribute as a, Attribute
323
324 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800325 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700326
Jerry Gee7b8eb72023-09-15 17:19:50 +0000327 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000328
James Wardea00fd02023-01-20 16:03:50 +0000329 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000330 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000331
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000332 self.utype = Attribute.Attribute().MatMulAttribute
333 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000334
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000335 self.ints.append((a.AddAZp, A_zp))
336 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000337
James Wardea00fd02023-01-20 16:03:50 +0000338 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000339 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000340
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000341 self.utype = Attribute.Attribute().FullyConnectedAttribute
342 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000343
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000344 self.ints.append((a.AddInputZp, input_zp))
345 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000346
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000347 def NegateAttribute(self, input1_zp, output_zp):
348 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000349
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000350 self.utype = Attribute.Attribute().NegateAttribute
351 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000352
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000353 self.ints.append((a.AddInput1Zp, input1_zp))
354 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000355
Tai Lyf5dfad12023-11-15 21:09:58 +0000356 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000357 from tosa import FFTAttribute as a, Attribute
358
359 self.utype = Attribute.Attribute().FFTAttribute
360 self.optFcns = (a.Start, a.End)
361
362 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000363 self.bools.append((a.AddLocalBound, local_bound))
364
365 def RFFTAttribute(self, local_bound):
366 from tosa import RFFTAttribute as a, Attribute
367
368 self.utype = Attribute.Attribute().RFFTAttribute
369 self.optFcns = (a.Start, a.End)
370
371 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000372
Kevin Chengfea5a372021-10-11 18:38:47 +0000373
374class TosaSerializerTensor:
375 def __init__(
376 self,
377 name,
378 shape,
379 dtype,
380 data=None,
381 placeholderFilename=None,
382 ):
383 self.name = name
384
385 if isinstance(shape, np.ndarray):
386 shape = shape.astype(int).tolist()
387 shape = list(map(int, shape))
388
389 self.shape = shape
390 self.dtype = dtype
391
Won Jeona8141522024-04-29 23:57:27 +0000392 if dtype == DType.FP32:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100393 fntype = np.float32
Won Jeona8141522024-04-29 23:57:27 +0000394 elif dtype == DType.BF16:
395 fntype = bfloat16
396 elif dtype == DType.FP8E4M3:
397 fntype = float8_e4m3fn
398 elif dtype == DType.FP8E5M2:
399 fntype = float8_e5m2
James Ward485a11d2022-08-05 13:48:37 +0100400 elif dtype == DType.FP16:
401 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100402 else:
403 fntype = int
404
Kevin Chengfea5a372021-10-11 18:38:47 +0000405 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100406 data = data.flatten().astype(fntype).tolist()
407 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000408 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100409 data = list(map(fntype, data))
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100410 elif data is not None:
411 # Assume data is rank 0 data type
412 data = list(map(fntype, [data]))
Kevin Chengfea5a372021-10-11 18:38:47 +0000413 else:
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100414 data = None
415
416 self.data = data
Kevin Chengfea5a372021-10-11 18:38:47 +0000417
418 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000419 # process and are written to disk, but are considered input tensors by the
420 # network so they do not appear in the TOSA serialiazation. However, if we
421 # want to form a unit test around these input tensors, we can get the filename
422 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000423 self.placeholderFilename = placeholderFilename
424
425 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800426 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000427 self.name,
428 self.shape,
429 DTypeNames[self.dtype],
430 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800431 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000432
433 def setDtype(self, dtype):
434 self.dtype = dtype
435
436 def serialize(self, builder):
437 fb_name = builder.CreateString(self.name)
438 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
439 if self.data:
Tai Lyce911a22024-03-21 17:01:14 +0000440 u8_data = TosaSerializer.convertDataToUint8Vec(self.dtype, self.data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000441 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
442
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800443 TosaTensor.Start(builder)
444 TosaTensor.AddName(builder, fb_name)
445 TosaTensor.AddShape(builder, fb_shapes)
446 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000447 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800448 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000449
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800450 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000451
452
453class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000454 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000455 self.op = op
456 self.attributes = attributes
457 self.inputs = TosaSerializer.toList(inputs)
458 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000459
460 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800461 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000462
463 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800464 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000465 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800466 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000467
Jerry Ge1eb85042023-01-06 14:19:14 -0800468 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000469
470 def serialize(self, builder):
471 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800472 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000473 )
474 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800475 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000476 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000477 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000478 if self.attributes is not None:
479 fb_attributes = self.attributes.serialize(builder)
480
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800481 TosaOperator.Start(builder)
482 TosaOperator.AddOp(builder, self.op)
483 TosaOperator.AddInputs(builder, fb_inputs)
484 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000485 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800486 TosaOperator.AddAttributeType(builder, self.attributes.utype)
487 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000488
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800489 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000490
491
492class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000493 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000494 self.name = name
495 self.operators = []
496
497 # Dict assures uniqueness, but allows us to look up by name
498 self.tensors = dict()
499
500 self.inputs = []
501 self.outputs = []
502
503 def addTensor(
504 self,
505 name,
506 shape,
507 dtype,
508 data=None,
509 placeholderFilename=None,
510 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000511 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000512 self.tensors[name] = TosaSerializerTensor(
513 name, shape, dtype, data, placeholderFilename
514 )
515
516 return self.tensors[name]
517
518 def addInput(self, name):
519 self.inputs.append(name)
520
521 def addOutput(self, name):
522 self.outputs.append(name)
523
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000524 def addOperator(self, op, inputs, outputs, attributes=None):
525 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000526
527 def serialize(self, builder):
528 fb_name = builder.CreateString(self.name)
529 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800530 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000531 )
532 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800533 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000534 )
535 fbv_tensors = TosaSerializer.serializeObjVec(
536 builder,
537 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800538 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000539 )
540 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800541 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000542 )
543
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800544 TosaBasicBlock.Start(builder)
545 TosaBasicBlock.AddName(builder, fb_name)
546 TosaBasicBlock.AddInputs(builder, fbv_inputs)
547 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
548 TosaBasicBlock.AddTensors(builder, fbv_tensors)
549 TosaBasicBlock.AddOperators(builder, fbv_operators)
550 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000551
552
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100553# How CONSTs are treated in the flatbuffer
554@unique
555class ConstMode(IntEnum):
556 EMBED = 0
557 EMBED_DUMP = 1
558 INPUTS = 2
559
560
Jerry Ge1eb85042023-01-06 14:19:14 -0800561class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100562 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800563 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000564 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000565 self.currInputIdx = 0
566 self.currConstIdx = 0
567 self.currLayerIdx = 1
568 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800569 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100570 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000571
Jerry Geca7ce0e2023-01-10 17:24:38 +0000572 def addBasicBlock(self, name):
573 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800574 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000575
Jerry Ge1eb85042023-01-06 14:19:14 -0800576 def serialize(self, builder):
577 fb_name = builder.CreateString(self.name)
578 fbv_basicBlocks = TosaSerializer.serializeObjVec(
579 builder, self.basicBlocks, TosaRegion.StartBlocksVector
580 )
581
582 TosaRegion.Start(builder)
583 TosaRegion.AddName(builder, fb_name)
584 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
585 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000586
587 def addPlaceholder(self, shape, dtype, vals):
588 if not self.currBasicBlock:
589 raise Exception("addTensor called without valid basic block")
590
591 name = "input-{}".format(self.currInputIdx)
592 filename = "{}.npy".format(name)
593 self.currInputIdx = self.currInputIdx + 1
594
595 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
596 # This is always an input to the block
597 self.currBasicBlock.addInput(name)
598
599 if vals is not None:
600 np.save(os.path.join(self.pathPrefix, filename), vals, False)
601
602 return tens
603
Jerry Ge53ceb482023-08-14 20:15:10 +0000604 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000605 if not self.currBasicBlock:
606 raise Exception("addTensor called without valid basic block")
607
Jerry Ge53ceb482023-08-14 20:15:10 +0000608 if name is None:
609 name = "const-{}".format(self.currInputIdx)
610 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000611
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100612 if self.constMode == ConstMode.INPUTS:
613 # Save const as input file
614 filename = "{}.npy".format(name)
615 tensor_vals = None
616 self.currBasicBlock.addInput(name)
617 else:
618 # Embed const in flatbuffer
619 filename = None
620 tensor_vals = vals
621
622 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000623 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000624 if dtype == DType.SHAPE:
625 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
626 else:
627 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000628
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100629 # Save the const data to file for debug or as input files
630 if vals is not None and self.constMode in [
631 ConstMode.EMBED_DUMP,
632 ConstMode.INPUTS,
633 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100634 filename = "{}.npy".format(name)
635 np.save(os.path.join(self.pathPrefix, filename), vals, False)
636
Kevin Chengfea5a372021-10-11 18:38:47 +0000637 return tens
638
639 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000640 if not self.currBasicBlock:
641 raise Exception("addTensor called without valid basic block")
642
643 name = "layer-{}".format(self.currLayerIdx)
644 self.currLayerIdx = self.currLayerIdx + 1
645
646 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
647
648 return tens
649
650 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700651 self.currBasicBlock.addTensor(
652 tensor.name,
653 tensor.shape,
654 tensor.dtype,
655 tensor.data,
656 tensor.placeholderFilename,
657 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000658 self.currBasicBlock.addInput(tensor.name)
659
660 def addOutputTensor(self, tensor):
661 self.currBasicBlock.addOutput(tensor.name)
662
663 def addOutput(self, shape, dtype):
664 if not self.currBasicBlock:
665 raise Exception("addTensor called without valid basic block")
666
667 name = "result-{}".format(self.currResultIdx)
668 self.currResultIdx = self.currResultIdx + 1
669
670 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
671 self.currBasicBlock.addOutput(name)
672 return tens
673
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000674 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000675 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000676 raise Exception("Use addConstTensor() to add CONST ops")
677
678 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000679 op,
680 inputs,
681 outputs,
682 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000683 )
684
Jerry Ge1eb85042023-01-06 14:19:14 -0800685
686@unique
687class TensorDir(IntEnum):
688 PLACEHOLDER = 0
689 CONST = 1
690 INTERMEDIATE = 2
691 RESULT = 3
692
693
694class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100695 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800696 self.builder = flatbuffers.Builder(0)
697
Jerry Ge1eb85042023-01-06 14:19:14 -0800698 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100699 self.constMode = constMode
700
701 self.regions = []
702 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800703
Jerry Geca7ce0e2023-01-10 17:24:38 +0000704 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800705
706 # Is this an illegal test that is expected to fail?
707 self.expectedReturnCode = 0
708 self.expectedFailure = False
709 self.expectedFailureDesc = ""
710
711 def __str__(self):
712 concatString = ""
713 for region in self.regions:
714 concatString = concatString + str(region)
715 return concatString
716
717 def addPlaceholder(self, shape, dtype, vals):
718 return self.currRegion.addPlaceholder(shape, dtype, vals)
719
Jerry Ge53ceb482023-08-14 20:15:10 +0000720 def addConst(self, shape, dtype, vals, name=None):
721 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800722
723 def addIntermediate(self, shape, dtype):
724 return self.currRegion.addIntermediate(shape, dtype)
725
726 def addInputTensor(self, tensor):
727 self.currRegion.addInputTensor(tensor)
728
729 def addOutputTensor(self, tensor):
730 self.currRegion.addOutputTensor(tensor)
731
732 def addOutput(self, shape, dtype):
733 return self.currRegion.addOutput(shape, dtype)
734
735 def addOperator(self, op, inputs, outputs, attributes=None):
736 return self.currRegion.addOperator(op, inputs, outputs, attributes)
737
Jerry Geca7ce0e2023-01-10 17:24:38 +0000738 def addBasicBlock(self, name):
739 self.currRegion.addBasicBlock(name)
740
Jeremy Johnson9b225172021-12-14 16:34:47 +0000741 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000742
743 self.expectedReturnCode = val
744 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000745 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000746
747 def serialize(self):
748
749 builder = self.builder
750
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800751 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000752 Version.Add_Major(builder, TOSA_VERSION[0])
753 Version.Add_Minor(builder, TOSA_VERSION[1])
754 Version.Add_Patch(builder, TOSA_VERSION[2])
755 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800756 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000757
Jerry Ge1eb85042023-01-06 14:19:14 -0800758 fbv_region = TosaSerializer.serializeObjVec(
759 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000760 )
761
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800762 TosaGraph.Start(builder)
763 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800764 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800765 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000766
Eric Kunzee6596402022-06-09 21:27:36 +0000767 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000768 return self.builder.Output()
769
770 def writeJson(self, tosa_filename):
771 """Write a json test file so that it is fairly easy to pick up the test
772 and generate commands for third party tool"""
773 test_desc = dict()
774
775 test_desc["tosa_file"] = tosa_filename
776 ifm_name = []
777 ifm_file = []
778 ofm_name = []
779 ofm_file = []
780
Jerry Ge1eb85042023-01-06 14:19:14 -0800781 for region in self.regions:
782 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000783 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800784 for i in block.inputs:
785 ifm_name.append(i)
786 ifm_file.append(block.tensors[i].placeholderFilename)
787 for o in block.outputs:
788 ofm_name.append(o)
789 # Make up an OFM filename here. One isn't generated until the
790 # reference tool is run, so any name is a good name
791 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000792
793 test_desc["ifm_name"] = ifm_name
794 test_desc["ifm_file"] = ifm_file
795 test_desc["ofm_name"] = ofm_name
796 test_desc["ofm_file"] = ofm_file
797 test_desc["expected_return_code"] = self.expectedReturnCode
798 test_desc["expected_failure"] = self.expectedFailure
799 if self.expectedFailureDesc:
800 test_desc["expected_failure_desc"] = self.expectedFailureDesc
801
802 return json.dumps(test_desc, indent=" ")
803
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100804 def startRegion(self, name, pathPrefix):
805 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800806 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000807
808 @staticmethod
809 def serializeStrVec(builder, vec, start_fcn):
810 fb_strs = [builder.CreateString(i) for i in vec]
811 start_fcn(builder, len(fb_strs))
812 for s in fb_strs[::-1]:
813 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700814 try:
815 return builder.EndVector()
816 except TypeError:
817 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000818
819 @staticmethod
820 def serializeUint8Vec(builder, vec):
821 builder.StartVector(1, len(vec), 8)
822 for v in vec[::-1]:
823 builder.PrependUint8(v)
824 try:
825 return builder.EndVector()
826 except TypeError:
827 return builder.EndVector(len(vec))
828
829 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700830 def serializeInt16Vec(builder, vec):
831 builder.StartVector(2, len(vec), 4)
832 for v in vec[::-1]:
833 builder.PrependInt16(v)
834 try:
835 return builder.EndVector()
836 except TypeError:
837 return builder.EndVector(len(vec))
838
839 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000840 def serializeInt32Vec(builder, vec):
841 builder.StartVector(4, len(vec), 4)
842 for v in vec[::-1]:
843 builder.PrependInt32(v)
844 try:
845 return builder.EndVector()
846 except TypeError:
847 return builder.EndVector(len(vec))
848
849 @staticmethod
850 def serializeFpVec(builder, vec):
851 builder.StartVector(4, len(vec), 4)
852 for v in vec[::-1]:
853 builder.PrependFloat32(v)
854 try:
855 return builder.EndVector()
856 except TypeError:
857 return builder.EndVector(len(vec))
858
859 @staticmethod
860 def serializeObjVec(builder, vec, start_fcn):
861 serialized_vec = []
862 for v in vec[::-1]:
863 serialized_vec.append(v.serialize(builder))
864
865 start_fcn(builder, len(vec))
866 for v in serialized_vec:
867 builder.PrependUOffsetTRelative(v)
868 try:
869 return builder.EndVector()
870 except TypeError:
871 return builder.EndVector(len(vec))
872
873 @staticmethod
874 def toList(val):
875 if isinstance(val, list):
876 return val
877 else:
878 return [val]
Tai Lyce911a22024-03-21 17:01:14 +0000879
880 @staticmethod
881 def convertDataToUint8Vec(dtype, data):
882 u8_data = list()
883 # little endianess
884 if dtype == DType.BOOL:
885 for val in data:
886 val_u8 = np.uint8(val)
887 u8_data.append(val_u8)
888 elif dtype == DType.INT4:
889 in_size = len(data)
890 out_size = (in_size + 1) // 2
891 for i in range(out_size):
892 val_0 = data[2 * i]
893 if (2 * i + 1) < in_size:
894 val_1 = data[2 * i + 1]
895 else:
896 val_1 = 0
897 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
898 val_u8 = np.uint8(val_i8)
899 u8_data.append(val_u8)
900 elif dtype == DType.INT8:
901 for val in data:
902 val_u8 = np.array(val).astype(dtype=np.uint8)
903 u8_data.append(val_u8)
904 elif dtype == DType.INT16:
905 for val in data:
906 val_u16 = np.array(val).astype(dtype=np.uint16)
907 b0 = val_u16 & ByteMask
908 b1 = (val_u16 >> np.uint16(8)) & ByteMask
909 u8_data.extend([b0, b1])
910 elif dtype == DType.INT32:
911 for val in data:
912 val_u32 = np.array(val).astype(dtype=np.uint32)
913 b0 = val_u32 & ByteMask
914 b1 = (val_u32 >> np.uint32(8)) & ByteMask
915 b2 = (val_u32 >> np.uint32(16)) & ByteMask
916 b3 = (val_u32 >> np.uint32(24)) & ByteMask
917 u8_data.extend([b0, b1, b2, b3])
918 elif dtype == DType.INT48:
919 for val in data:
920 val_u64 = np.uint64(val)
921 b0 = val_u64 & ByteMask
922 b1 = (val_u64 >> np.uint64(8)) & ByteMask
923 b2 = (val_u64 >> np.uint64(16)) & ByteMask
924 b3 = (val_u64 >> np.uint64(24)) & ByteMask
925 b4 = (val_u64 >> np.uint64(32)) & ByteMask
926 b5 = (val_u64 >> np.uint64(40)) & ByteMask
927 u8_data.extend([b0, b1, b2, b3, b4, b5])
928 elif dtype == DType.SHAPE:
929 for val in data:
930 val_u64 = np.uint64(val)
931 b0 = val_u64 & ByteMask
932 b1 = (val_u64 >> np.uint64(8)) & ByteMask
933 b2 = (val_u64 >> np.uint64(16)) & ByteMask
934 b3 = (val_u64 >> np.uint64(24)) & ByteMask
935 b4 = (val_u64 >> np.uint64(32)) & ByteMask
936 b5 = (val_u64 >> np.uint64(40)) & ByteMask
937 b6 = (val_u64 >> np.uint64(48)) & ByteMask
938 b7 = (val_u64 >> np.uint64(56)) & ByteMask
939 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
940 elif dtype == DType.FP16:
941 np_arr = np.array(data, dtype=np.float16)
942 u8_data.extend(np_arr.view(np.uint8))
943 elif dtype == DType.FP32:
Tai Lyce911a22024-03-21 17:01:14 +0000944 np_arr = np.array(data, dtype=np.float32)
945 u8_data.extend(np_arr.view(np.uint8))
946 elif dtype == DType.BF16:
Won Jeon07098d62024-05-09 06:00:31 +0000947 np_arr = np.array(data, dtype=bfloat16)
948 u8_data.extend(np_arr.view(np.uint8))
Tai Lyce911a22024-03-21 17:01:14 +0000949 elif dtype == DType.FP8E4M3:
950 for val in data:
Won Jeona8141522024-04-29 23:57:27 +0000951 val_f8 = np.array(val).astype(float8_e4m3fn).view(np.uint8)
952 u8_data.append(val_f8)
Tai Lyce911a22024-03-21 17:01:14 +0000953 elif dtype == DType.FP8E5M2:
954 for val in data:
Won Jeona8141522024-04-29 23:57:27 +0000955 val_f8 = np.array(val).astype(float8_e5m2).view(np.uint8)
956 u8_data.append(val_f8)
Tai Lyce911a22024-03-21 17:01:14 +0000957 elif dtype == TosaDType.DType:
958 # Serialize DType enum data as uint8 bytes
959 for val in data:
960 np_arr = np.array(data, dtype=np.uint32)
961 u8_data.extend(np_arr.view(np.uint8))
962 else:
963 raise Exception("unsupported data type {}".format(DTypeNames[dtype]))
964 return u8_data