blob: d0445aeeaf14ac605da9ab19168d361deb0ca85e [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
Eric Kunze816f60e2024-04-19 19:31:31 +000034TOSA_VERSION_MAJOR = 1
35TOSA_VERSION_MINOR = 0
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
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 Ly57d78182024-04-09 19:31:24 +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:
Tai Lyce911a22024-03-21 17:01:14 +0000442 u8_data = TosaSerializer.convertDataToUint8Vec(self.dtype, self.data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000443 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
444
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800445 TosaTensor.Start(builder)
446 TosaTensor.AddName(builder, fb_name)
447 TosaTensor.AddShape(builder, fb_shapes)
448 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000449 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800450 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000451
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800452 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000453
454
455class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000456 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000457 self.op = op
458 self.attributes = attributes
459 self.inputs = TosaSerializer.toList(inputs)
460 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000461
462 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800463 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000464
465 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800466 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000467 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800468 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000469
Jerry Ge1eb85042023-01-06 14:19:14 -0800470 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000471
472 def serialize(self, builder):
473 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800474 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000475 )
476 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800477 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000478 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000479 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000480 if self.attributes is not None:
481 fb_attributes = self.attributes.serialize(builder)
482
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800483 TosaOperator.Start(builder)
484 TosaOperator.AddOp(builder, self.op)
485 TosaOperator.AddInputs(builder, fb_inputs)
486 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000487 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800488 TosaOperator.AddAttributeType(builder, self.attributes.utype)
489 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000490
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800491 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000492
493
494class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000495 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000496 self.name = name
497 self.operators = []
498
499 # Dict assures uniqueness, but allows us to look up by name
500 self.tensors = dict()
501
502 self.inputs = []
503 self.outputs = []
504
505 def addTensor(
506 self,
507 name,
508 shape,
509 dtype,
510 data=None,
511 placeholderFilename=None,
512 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000513 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000514 self.tensors[name] = TosaSerializerTensor(
515 name, shape, dtype, data, placeholderFilename
516 )
517
518 return self.tensors[name]
519
520 def addInput(self, name):
521 self.inputs.append(name)
522
523 def addOutput(self, name):
524 self.outputs.append(name)
525
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000526 def addOperator(self, op, inputs, outputs, attributes=None):
527 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000528
529 def serialize(self, builder):
530 fb_name = builder.CreateString(self.name)
531 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800532 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000533 )
534 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800535 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000536 )
537 fbv_tensors = TosaSerializer.serializeObjVec(
538 builder,
539 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800540 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000541 )
542 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800543 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000544 )
545
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800546 TosaBasicBlock.Start(builder)
547 TosaBasicBlock.AddName(builder, fb_name)
548 TosaBasicBlock.AddInputs(builder, fbv_inputs)
549 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
550 TosaBasicBlock.AddTensors(builder, fbv_tensors)
551 TosaBasicBlock.AddOperators(builder, fbv_operators)
552 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000553
554
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100555# How CONSTs are treated in the flatbuffer
556@unique
557class ConstMode(IntEnum):
558 EMBED = 0
559 EMBED_DUMP = 1
560 INPUTS = 2
561
562
Jerry Ge1eb85042023-01-06 14:19:14 -0800563class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100564 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800565 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000566 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000567 self.currInputIdx = 0
568 self.currConstIdx = 0
569 self.currLayerIdx = 1
570 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800571 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100572 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000573
Jerry Geca7ce0e2023-01-10 17:24:38 +0000574 def addBasicBlock(self, name):
575 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800576 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000577
Jerry Ge1eb85042023-01-06 14:19:14 -0800578 def serialize(self, builder):
579 fb_name = builder.CreateString(self.name)
580 fbv_basicBlocks = TosaSerializer.serializeObjVec(
581 builder, self.basicBlocks, TosaRegion.StartBlocksVector
582 )
583
584 TosaRegion.Start(builder)
585 TosaRegion.AddName(builder, fb_name)
586 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
587 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000588
589 def addPlaceholder(self, shape, dtype, vals):
590 if not self.currBasicBlock:
591 raise Exception("addTensor called without valid basic block")
592
593 name = "input-{}".format(self.currInputIdx)
594 filename = "{}.npy".format(name)
595 self.currInputIdx = self.currInputIdx + 1
596
597 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
598 # This is always an input to the block
599 self.currBasicBlock.addInput(name)
600
601 if vals is not None:
602 np.save(os.path.join(self.pathPrefix, filename), vals, False)
603
604 return tens
605
Jerry Ge53ceb482023-08-14 20:15:10 +0000606 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000607 if not self.currBasicBlock:
608 raise Exception("addTensor called without valid basic block")
609
Jerry Ge53ceb482023-08-14 20:15:10 +0000610 if name is None:
611 name = "const-{}".format(self.currInputIdx)
612 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000613
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100614 if self.constMode == ConstMode.INPUTS:
615 # Save const as input file
616 filename = "{}.npy".format(name)
617 tensor_vals = None
618 self.currBasicBlock.addInput(name)
619 else:
620 # Embed const in flatbuffer
621 filename = None
622 tensor_vals = vals
623
624 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000625 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000626 if dtype == DType.SHAPE:
627 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
628 else:
629 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000630
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100631 # Save the const data to file for debug or as input files
632 if vals is not None and self.constMode in [
633 ConstMode.EMBED_DUMP,
634 ConstMode.INPUTS,
635 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100636 filename = "{}.npy".format(name)
637 np.save(os.path.join(self.pathPrefix, filename), vals, False)
638
Kevin Chengfea5a372021-10-11 18:38:47 +0000639 return tens
640
641 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000642 if not self.currBasicBlock:
643 raise Exception("addTensor called without valid basic block")
644
645 name = "layer-{}".format(self.currLayerIdx)
646 self.currLayerIdx = self.currLayerIdx + 1
647
648 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
649
650 return tens
651
652 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700653 self.currBasicBlock.addTensor(
654 tensor.name,
655 tensor.shape,
656 tensor.dtype,
657 tensor.data,
658 tensor.placeholderFilename,
659 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000660 self.currBasicBlock.addInput(tensor.name)
661
662 def addOutputTensor(self, tensor):
663 self.currBasicBlock.addOutput(tensor.name)
664
665 def addOutput(self, shape, dtype):
666 if not self.currBasicBlock:
667 raise Exception("addTensor called without valid basic block")
668
669 name = "result-{}".format(self.currResultIdx)
670 self.currResultIdx = self.currResultIdx + 1
671
672 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
673 self.currBasicBlock.addOutput(name)
674 return tens
675
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000676 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000677 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000678 raise Exception("Use addConstTensor() to add CONST ops")
679
680 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000681 op,
682 inputs,
683 outputs,
684 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000685 )
686
Jerry Ge1eb85042023-01-06 14:19:14 -0800687
688@unique
689class TensorDir(IntEnum):
690 PLACEHOLDER = 0
691 CONST = 1
692 INTERMEDIATE = 2
693 RESULT = 3
694
695
696class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100697 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800698 self.builder = flatbuffers.Builder(0)
699
Jerry Ge1eb85042023-01-06 14:19:14 -0800700 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100701 self.constMode = constMode
702
703 self.regions = []
704 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800705
Jerry Geca7ce0e2023-01-10 17:24:38 +0000706 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800707
708 # Is this an illegal test that is expected to fail?
709 self.expectedReturnCode = 0
710 self.expectedFailure = False
711 self.expectedFailureDesc = ""
712
713 def __str__(self):
714 concatString = ""
715 for region in self.regions:
716 concatString = concatString + str(region)
717 return concatString
718
719 def addPlaceholder(self, shape, dtype, vals):
720 return self.currRegion.addPlaceholder(shape, dtype, vals)
721
Jerry Ge53ceb482023-08-14 20:15:10 +0000722 def addConst(self, shape, dtype, vals, name=None):
723 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800724
725 def addIntermediate(self, shape, dtype):
726 return self.currRegion.addIntermediate(shape, dtype)
727
728 def addInputTensor(self, tensor):
729 self.currRegion.addInputTensor(tensor)
730
731 def addOutputTensor(self, tensor):
732 self.currRegion.addOutputTensor(tensor)
733
734 def addOutput(self, shape, dtype):
735 return self.currRegion.addOutput(shape, dtype)
736
737 def addOperator(self, op, inputs, outputs, attributes=None):
738 return self.currRegion.addOperator(op, inputs, outputs, attributes)
739
Jerry Geca7ce0e2023-01-10 17:24:38 +0000740 def addBasicBlock(self, name):
741 self.currRegion.addBasicBlock(name)
742
Jeremy Johnson9b225172021-12-14 16:34:47 +0000743 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000744
745 self.expectedReturnCode = val
746 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000747 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000748
749 def serialize(self):
750
751 builder = self.builder
752
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800753 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000754 Version.Add_Major(builder, TOSA_VERSION[0])
755 Version.Add_Minor(builder, TOSA_VERSION[1])
756 Version.Add_Patch(builder, TOSA_VERSION[2])
757 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800758 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000759
Jerry Ge1eb85042023-01-06 14:19:14 -0800760 fbv_region = TosaSerializer.serializeObjVec(
761 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000762 )
763
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800764 TosaGraph.Start(builder)
765 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800766 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800767 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000768
Eric Kunzee6596402022-06-09 21:27:36 +0000769 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000770 return self.builder.Output()
771
772 def writeJson(self, tosa_filename):
773 """Write a json test file so that it is fairly easy to pick up the test
774 and generate commands for third party tool"""
775 test_desc = dict()
776
777 test_desc["tosa_file"] = tosa_filename
778 ifm_name = []
779 ifm_file = []
780 ofm_name = []
781 ofm_file = []
782
Jerry Ge1eb85042023-01-06 14:19:14 -0800783 for region in self.regions:
784 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000785 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800786 for i in block.inputs:
787 ifm_name.append(i)
788 ifm_file.append(block.tensors[i].placeholderFilename)
789 for o in block.outputs:
790 ofm_name.append(o)
791 # Make up an OFM filename here. One isn't generated until the
792 # reference tool is run, so any name is a good name
793 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000794
795 test_desc["ifm_name"] = ifm_name
796 test_desc["ifm_file"] = ifm_file
797 test_desc["ofm_name"] = ofm_name
798 test_desc["ofm_file"] = ofm_file
799 test_desc["expected_return_code"] = self.expectedReturnCode
800 test_desc["expected_failure"] = self.expectedFailure
801 if self.expectedFailureDesc:
802 test_desc["expected_failure_desc"] = self.expectedFailureDesc
803
804 return json.dumps(test_desc, indent=" ")
805
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100806 def startRegion(self, name, pathPrefix):
807 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800808 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000809
810 @staticmethod
811 def serializeStrVec(builder, vec, start_fcn):
812 fb_strs = [builder.CreateString(i) for i in vec]
813 start_fcn(builder, len(fb_strs))
814 for s in fb_strs[::-1]:
815 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700816 try:
817 return builder.EndVector()
818 except TypeError:
819 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000820
821 @staticmethod
822 def serializeUint8Vec(builder, vec):
823 builder.StartVector(1, len(vec), 8)
824 for v in vec[::-1]:
825 builder.PrependUint8(v)
826 try:
827 return builder.EndVector()
828 except TypeError:
829 return builder.EndVector(len(vec))
830
831 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700832 def serializeInt16Vec(builder, vec):
833 builder.StartVector(2, len(vec), 4)
834 for v in vec[::-1]:
835 builder.PrependInt16(v)
836 try:
837 return builder.EndVector()
838 except TypeError:
839 return builder.EndVector(len(vec))
840
841 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000842 def serializeInt32Vec(builder, vec):
843 builder.StartVector(4, len(vec), 4)
844 for v in vec[::-1]:
845 builder.PrependInt32(v)
846 try:
847 return builder.EndVector()
848 except TypeError:
849 return builder.EndVector(len(vec))
850
851 @staticmethod
852 def serializeFpVec(builder, vec):
853 builder.StartVector(4, len(vec), 4)
854 for v in vec[::-1]:
855 builder.PrependFloat32(v)
856 try:
857 return builder.EndVector()
858 except TypeError:
859 return builder.EndVector(len(vec))
860
861 @staticmethod
862 def serializeObjVec(builder, vec, start_fcn):
863 serialized_vec = []
864 for v in vec[::-1]:
865 serialized_vec.append(v.serialize(builder))
866
867 start_fcn(builder, len(vec))
868 for v in serialized_vec:
869 builder.PrependUOffsetTRelative(v)
870 try:
871 return builder.EndVector()
872 except TypeError:
873 return builder.EndVector(len(vec))
874
875 @staticmethod
876 def toList(val):
877 if isinstance(val, list):
878 return val
879 else:
880 return [val]
Tai Lyce911a22024-03-21 17:01:14 +0000881
882 @staticmethod
883 def convertDataToUint8Vec(dtype, data):
884 u8_data = list()
885 # little endianess
886 if dtype == DType.BOOL:
887 for val in data:
888 val_u8 = np.uint8(val)
889 u8_data.append(val_u8)
890 elif dtype == DType.INT4:
891 in_size = len(data)
892 out_size = (in_size + 1) // 2
893 for i in range(out_size):
894 val_0 = data[2 * i]
895 if (2 * i + 1) < in_size:
896 val_1 = data[2 * i + 1]
897 else:
898 val_1 = 0
899 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
900 val_u8 = np.uint8(val_i8)
901 u8_data.append(val_u8)
902 elif dtype == DType.INT8:
903 for val in data:
904 val_u8 = np.array(val).astype(dtype=np.uint8)
905 u8_data.append(val_u8)
906 elif dtype == DType.INT16:
907 for val in data:
908 val_u16 = np.array(val).astype(dtype=np.uint16)
909 b0 = val_u16 & ByteMask
910 b1 = (val_u16 >> np.uint16(8)) & ByteMask
911 u8_data.extend([b0, b1])
912 elif dtype == DType.INT32:
913 for val in data:
914 val_u32 = np.array(val).astype(dtype=np.uint32)
915 b0 = val_u32 & ByteMask
916 b1 = (val_u32 >> np.uint32(8)) & ByteMask
917 b2 = (val_u32 >> np.uint32(16)) & ByteMask
918 b3 = (val_u32 >> np.uint32(24)) & ByteMask
919 u8_data.extend([b0, b1, b2, b3])
920 elif dtype == DType.INT48:
921 for val in data:
922 val_u64 = np.uint64(val)
923 b0 = val_u64 & ByteMask
924 b1 = (val_u64 >> np.uint64(8)) & ByteMask
925 b2 = (val_u64 >> np.uint64(16)) & ByteMask
926 b3 = (val_u64 >> np.uint64(24)) & ByteMask
927 b4 = (val_u64 >> np.uint64(32)) & ByteMask
928 b5 = (val_u64 >> np.uint64(40)) & ByteMask
929 u8_data.extend([b0, b1, b2, b3, b4, b5])
930 elif dtype == DType.SHAPE:
931 for val in data:
932 val_u64 = np.uint64(val)
933 b0 = val_u64 & ByteMask
934 b1 = (val_u64 >> np.uint64(8)) & ByteMask
935 b2 = (val_u64 >> np.uint64(16)) & ByteMask
936 b3 = (val_u64 >> np.uint64(24)) & ByteMask
937 b4 = (val_u64 >> np.uint64(32)) & ByteMask
938 b5 = (val_u64 >> np.uint64(40)) & ByteMask
939 b6 = (val_u64 >> np.uint64(48)) & ByteMask
940 b7 = (val_u64 >> np.uint64(56)) & ByteMask
941 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
942 elif dtype == DType.FP16:
943 np_arr = np.array(data, dtype=np.float16)
944 u8_data.extend(np_arr.view(np.uint8))
945 elif dtype == DType.FP32:
946 # for val in data:
947 # b = struct.pack("!f", val)
948 # u8_data.extend([b[3], b[2], b[1], b[0]])
949 np_arr = np.array(data, dtype=np.float32)
950 u8_data.extend(np_arr.view(np.uint8))
951 elif dtype == DType.BF16:
952 for val in data:
953 # convert val to little endian byte arrays b
954 b = struct.pack("<f", val)
955 # val => [ b[3], b[2], b[1], b[0] ]
956 # keep only most significant 2 bytes for bf16
957 # in little endian ordering
958 u8_data.extend([b[2], b[3]])
959 elif dtype == DType.FP8E4M3:
960 for val in data:
961 # convert val to fp8_bits then to single byte
962 f32_as_int = struct.unpack(">L", struct.pack(">f", val))[0]
963 f32_bits = f"{f32_as_int:032b}"
964 fp8_bits = f32_bits[0] + f32_bits[1:5] + f32_bits[9:12]
965 fp8_bytes = int(fp8_bits, 2).to_bytes(1, byteorder="little")
966 u8_data.extend(fp8_bytes)
967 elif dtype == DType.FP8E5M2:
968 for val in data:
969 # convert val to fp8_bits then to single byte
970 f32_as_int = struct.unpack(">L", struct.pack(">f", val))[0]
971 f32_bits = f"{f32_as_int:032b}"
972 fp8_bits = f32_bits[0] + f32_bits[1:6] + f32_bits[9:11]
973 fp8_bytes = int(fp8_bits, 2).to_bytes(1, byteorder="little")
974 u8_data.extend(fp8_bytes)
975 elif dtype == TosaDType.DType:
976 # Serialize DType enum data as uint8 bytes
977 for val in data:
978 np_arr = np.array(data, dtype=np.uint32)
979 u8_data.extend(np_arr.view(np.uint8))
980 else:
981 raise Exception("unsupported data type {}".format(DTypeNames[dtype]))
982 return u8_data