blob: bbfb37efd7ebea19d1ea539d224be3fa64ba1a5c [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 Ly57d78182024-04-09 19:31:24 +0000208 def PadAttribute(self, serializer_builder, pad_const_val_as_bytes):
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))
Kevin Chengfea5a372021-10-11 18:38:47 +0000220
221 def AxisAttribute(self, axis):
222 from tosa import AxisAttribute as a, Attribute
223
224 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800225 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000226
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800227 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000228
TatWai Chong49b1ca62022-06-10 01:49:13 -0700229 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000230 from tosa import ResizeAttribute as a, Attribute
231
232 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800233 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000234
TatWai Chong49b1ca62022-06-10 01:49:13 -0700235 self.int16vecs.append((a.AddScale, scale))
236 self.int16vecs.append((a.AddOffset, offset))
237 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800238 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000239
Tai Ly57d78182024-04-09 19:31:24 +0000240 def ClampAttribute(self, serializer_builder, min_val_as_bytes, max_val_as_bytes):
Kevin Chengfea5a372021-10-11 18:38:47 +0000241 from tosa import ClampAttribute as a, Attribute
242
243 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800244 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000245
James Wardc15f7d52022-12-07 15:38:01 +0000246 # min/max float attributes serialized as uint8 vectors
Tai Ly0b6d7c22024-03-08 17:03:25 +0000247 serialized_min_val = ts.TosaSerializer.serializeUint8Vec(
248 serializer_builder, min_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000249 )
Tai Ly0b6d7c22024-03-08 17:03:25 +0000250 serialized_max_val = ts.TosaSerializer.serializeUint8Vec(
251 serializer_builder, max_val_as_bytes
James Wardc15f7d52022-12-07 15:38:01 +0000252 )
253
Tai Ly0b6d7c22024-03-08 17:03:25 +0000254 self.floats.append((a.AddMinVal, serialized_min_val))
255 self.floats.append((a.AddMaxVal, serialized_max_val))
Kevin Chengfea5a372021-10-11 18:38:47 +0000256
257 def RescaleAttribute(
James Ward92358fc2023-11-21 18:14:43 +0000258 self,
259 input_zp,
260 output_zp,
James Ward92358fc2023-11-21 18:14:43 +0000261 scale32,
262 double_round,
263 per_channel,
264 input_unsigned,
265 output_unsigned,
Kevin Chengfea5a372021-10-11 18:38:47 +0000266 ):
267 from tosa import RescaleAttribute as a, Attribute
268
269 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800270 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000271
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800272 self.ints.append((a.AddInputZp, input_zp))
273 self.ints.append((a.AddOutputZp, output_zp))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800274 self.bools.append((a.AddScale32, scale32))
275 self.bools.append((a.AddDoubleRound, double_round))
276 self.bools.append((a.AddPerChannel, per_channel))
James Ward92358fc2023-11-21 18:14:43 +0000277 self.bools.append((a.AddInputUnsigned, input_unsigned))
278 self.bools.append((a.AddOutputUnsigned, output_unsigned))
Kevin Chengfea5a372021-10-11 18:38:47 +0000279
280 def MulAttribute(self, shift):
281 from tosa import MulAttribute as a, Attribute
282
283 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800284 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000285
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800286 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000287
288 def ArithmeticRightShiftAttribute(self, round):
289 from tosa import ArithmeticRightShiftAttribute as a, Attribute
290
291 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
292 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800293 a.Start,
294 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000295 )
296
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800297 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000298
Tai Ly81db8ee2024-02-14 19:57:38 +0000299 def CondIfAttribute(self, then_graph, else_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000300 from tosa import CondIfAttribute as a, Attribute
301
302 self.utype = Attribute.Attribute().CondIfAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800303 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000304
Tai Ly81db8ee2024-02-14 19:57:38 +0000305 self.strings.append((a.AddThenGraph, then_graph))
306 self.strings.append((a.AddElseGraph, else_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000307
Tai Ly81db8ee2024-02-14 19:57:38 +0000308 def WhileLoopAttribute(self, cond_graph, body_graph):
Kevin Chengfea5a372021-10-11 18:38:47 +0000309 from tosa import WhileLoopAttribute as a, Attribute
310
311 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800312 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000313
Tai Ly81db8ee2024-02-14 19:57:38 +0000314 self.strings.append((a.AddCondGraph, cond_graph))
315 self.strings.append((a.AddBodyGraph, body_graph))
Kevin Chengfea5a372021-10-11 18:38:47 +0000316
TatWai Chong7be71652022-05-10 17:26:20 -0700317 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700318 from tosa import TransposeAttribute as a, Attribute
319
320 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800321 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700322
TatWai Chong7be71652022-05-10 17:26:20 -0700323 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700324
325 def TableAttribute(self, table):
326 from tosa import TableAttribute as a, Attribute
327
328 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800329 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700330
Jerry Gee7b8eb72023-09-15 17:19:50 +0000331 self.int16vecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000332
James Wardea00fd02023-01-20 16:03:50 +0000333 def MatMulAttribute(self, A_zp, B_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000334 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000335
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000336 self.utype = Attribute.Attribute().MatMulAttribute
337 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000338
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000339 self.ints.append((a.AddAZp, A_zp))
340 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000341
James Wardea00fd02023-01-20 16:03:50 +0000342 def FullyConnectedAttribute(self, input_zp, weight_zp):
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000343 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000344
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000345 self.utype = Attribute.Attribute().FullyConnectedAttribute
346 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000347
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000348 self.ints.append((a.AddInputZp, input_zp))
349 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000350
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000351 def NegateAttribute(self, input1_zp, output_zp):
352 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000353
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000354 self.utype = Attribute.Attribute().NegateAttribute
355 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000356
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000357 self.ints.append((a.AddInput1Zp, input1_zp))
358 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000359
Tai Lyf5dfad12023-11-15 21:09:58 +0000360 def FFTAttribute(self, inverse, local_bound):
Luke Hutton5e268092023-01-12 22:20:53 +0000361 from tosa import FFTAttribute as a, Attribute
362
363 self.utype = Attribute.Attribute().FFTAttribute
364 self.optFcns = (a.Start, a.End)
365
366 self.bools.append((a.AddInverse, inverse))
Tai Lyf5dfad12023-11-15 21:09:58 +0000367 self.bools.append((a.AddLocalBound, local_bound))
368
369 def RFFTAttribute(self, local_bound):
370 from tosa import RFFTAttribute as a, Attribute
371
372 self.utype = Attribute.Attribute().RFFTAttribute
373 self.optFcns = (a.Start, a.End)
374
375 self.bools.append((a.AddLocalBound, local_bound))
Luke Hutton5e268092023-01-12 22:20:53 +0000376
Kevin Chengfea5a372021-10-11 18:38:47 +0000377
378class TosaSerializerTensor:
379 def __init__(
380 self,
381 name,
382 shape,
383 dtype,
384 data=None,
385 placeholderFilename=None,
386 ):
387 self.name = name
388
389 if isinstance(shape, np.ndarray):
390 shape = shape.astype(int).tolist()
391 shape = list(map(int, shape))
392
393 self.shape = shape
394 self.dtype = dtype
395
Won Jeona029f1f2023-12-29 22:43:11 +0000396 if (
397 dtype == DType.FP32
398 or dtype == DType.BF16
399 or dtype == DType.FP8E4M3
400 or dtype == DType.FP8E5M2
401 ):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100402 fntype = np.float32
James Ward485a11d2022-08-05 13:48:37 +0100403 elif dtype == DType.FP16:
404 fntype = np.float16
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100405 else:
406 fntype = int
407
Kevin Chengfea5a372021-10-11 18:38:47 +0000408 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100409 data = data.flatten().astype(fntype).tolist()
410 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000411 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100412 data = list(map(fntype, data))
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100413 elif data is not None:
414 # Assume data is rank 0 data type
415 data = list(map(fntype, [data]))
Kevin Chengfea5a372021-10-11 18:38:47 +0000416 else:
Jeremy Johnson8f9e2842024-04-04 11:14:06 +0100417 data = None
418
419 self.data = data
Kevin Chengfea5a372021-10-11 18:38:47 +0000420
421 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000422 # process and are written to disk, but are considered input tensors by the
423 # network so they do not appear in the TOSA serialiazation. However, if we
424 # want to form a unit test around these input tensors, we can get the filename
425 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000426 self.placeholderFilename = placeholderFilename
427
428 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800429 concatString = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Chengfea5a372021-10-11 18:38:47 +0000430 self.name,
431 self.shape,
432 DTypeNames[self.dtype],
433 )
Jerry Ge1eb85042023-01-06 14:19:14 -0800434 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000435
436 def setDtype(self, dtype):
437 self.dtype = dtype
438
439 def serialize(self, builder):
440 fb_name = builder.CreateString(self.name)
441 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
442 if self.data:
Tai Lyce911a22024-03-21 17:01:14 +0000443 u8_data = TosaSerializer.convertDataToUint8Vec(self.dtype, self.data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000444 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
445
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800446 TosaTensor.Start(builder)
447 TosaTensor.AddName(builder, fb_name)
448 TosaTensor.AddShape(builder, fb_shapes)
449 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000450 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800451 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000452
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800453 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000454
455
456class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000457 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000458 self.op = op
459 self.attributes = attributes
460 self.inputs = TosaSerializer.toList(inputs)
461 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000462
463 def __str__(self):
Jerry Ge1eb85042023-01-06 14:19:14 -0800464 concatString = "Op {}\n----\n".format(self.op)
Kevin Chengfea5a372021-10-11 18:38:47 +0000465
466 for i in self.inputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800467 concatString = concatString + " Input: {}\n".format(i)
Kevin Chengfea5a372021-10-11 18:38:47 +0000468 for o in self.outputs:
Jerry Ge1eb85042023-01-06 14:19:14 -0800469 concatString = concatString + " Output: {}\n".format(o)
Kevin Chengfea5a372021-10-11 18:38:47 +0000470
Jerry Ge1eb85042023-01-06 14:19:14 -0800471 return concatString
Kevin Chengfea5a372021-10-11 18:38:47 +0000472
473 def serialize(self, builder):
474 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800475 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000476 )
477 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800478 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000479 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000480 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000481 if self.attributes is not None:
482 fb_attributes = self.attributes.serialize(builder)
483
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800484 TosaOperator.Start(builder)
485 TosaOperator.AddOp(builder, self.op)
486 TosaOperator.AddInputs(builder, fb_inputs)
487 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000488 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800489 TosaOperator.AddAttributeType(builder, self.attributes.utype)
490 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000491
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800492 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000493
494
495class TosaSerializerBasicBlock:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000496 def __init__(self, name):
Kevin Chengfea5a372021-10-11 18:38:47 +0000497 self.name = name
498 self.operators = []
499
500 # Dict assures uniqueness, but allows us to look up by name
501 self.tensors = dict()
502
503 self.inputs = []
504 self.outputs = []
505
506 def addTensor(
507 self,
508 name,
509 shape,
510 dtype,
511 data=None,
512 placeholderFilename=None,
513 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000514 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000515 self.tensors[name] = TosaSerializerTensor(
516 name, shape, dtype, data, placeholderFilename
517 )
518
519 return self.tensors[name]
520
521 def addInput(self, name):
522 self.inputs.append(name)
523
524 def addOutput(self, name):
525 self.outputs.append(name)
526
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000527 def addOperator(self, op, inputs, outputs, attributes=None):
528 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000529
530 def serialize(self, builder):
531 fb_name = builder.CreateString(self.name)
532 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800533 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000534 )
535 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800536 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000537 )
538 fbv_tensors = TosaSerializer.serializeObjVec(
539 builder,
540 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800541 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000542 )
543 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800544 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000545 )
546
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800547 TosaBasicBlock.Start(builder)
548 TosaBasicBlock.AddName(builder, fb_name)
549 TosaBasicBlock.AddInputs(builder, fbv_inputs)
550 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
551 TosaBasicBlock.AddTensors(builder, fbv_tensors)
552 TosaBasicBlock.AddOperators(builder, fbv_operators)
553 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000554
555
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100556# How CONSTs are treated in the flatbuffer
557@unique
558class ConstMode(IntEnum):
559 EMBED = 0
560 EMBED_DUMP = 1
561 INPUTS = 2
562
563
Jerry Ge1eb85042023-01-06 14:19:14 -0800564class TosaSerializerRegion:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100565 def __init__(self, name, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800566 self.name = name
Kevin Chengfea5a372021-10-11 18:38:47 +0000567 self.basicBlocks = []
Kevin Chengfea5a372021-10-11 18:38:47 +0000568 self.currInputIdx = 0
569 self.currConstIdx = 0
570 self.currLayerIdx = 1
571 self.currResultIdx = 0
Jerry Ge1eb85042023-01-06 14:19:14 -0800572 self.pathPrefix = pathPrefix
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100573 self.constMode = constMode
Kevin Chengfea5a372021-10-11 18:38:47 +0000574
Jerry Geca7ce0e2023-01-10 17:24:38 +0000575 def addBasicBlock(self, name):
576 self.currBasicBlock = TosaSerializerBasicBlock(name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800577 self.basicBlocks.append(self.currBasicBlock)
Kevin Chengfea5a372021-10-11 18:38:47 +0000578
Jerry Ge1eb85042023-01-06 14:19:14 -0800579 def serialize(self, builder):
580 fb_name = builder.CreateString(self.name)
581 fbv_basicBlocks = TosaSerializer.serializeObjVec(
582 builder, self.basicBlocks, TosaRegion.StartBlocksVector
583 )
584
585 TosaRegion.Start(builder)
586 TosaRegion.AddName(builder, fb_name)
587 TosaRegion.AddBlocks(builder, fbv_basicBlocks)
588 return TosaRegion.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000589
590 def addPlaceholder(self, shape, dtype, vals):
591 if not self.currBasicBlock:
592 raise Exception("addTensor called without valid basic block")
593
594 name = "input-{}".format(self.currInputIdx)
595 filename = "{}.npy".format(name)
596 self.currInputIdx = self.currInputIdx + 1
597
598 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
599 # This is always an input to the block
600 self.currBasicBlock.addInput(name)
601
602 if vals is not None:
603 np.save(os.path.join(self.pathPrefix, filename), vals, False)
604
605 return tens
606
Jerry Ge53ceb482023-08-14 20:15:10 +0000607 def addConst(self, shape, dtype, vals, name=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000608 if not self.currBasicBlock:
609 raise Exception("addTensor called without valid basic block")
610
Jerry Ge53ceb482023-08-14 20:15:10 +0000611 if name is None:
612 name = "const-{}".format(self.currInputIdx)
613 self.currInputIdx = self.currInputIdx + 1
Kevin Chengfea5a372021-10-11 18:38:47 +0000614
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100615 if self.constMode == ConstMode.INPUTS:
616 # Save const as input file
617 filename = "{}.npy".format(name)
618 tensor_vals = None
619 self.currBasicBlock.addInput(name)
620 else:
621 # Embed const in flatbuffer
622 filename = None
623 tensor_vals = vals
624
625 tens = self.currBasicBlock.addTensor(name, shape, dtype, tensor_vals, filename)
Kevin Chengfea5a372021-10-11 18:38:47 +0000626 # Add the operator now
Won Jeon7c22d772024-01-23 07:46:08 +0000627 if dtype == DType.SHAPE:
628 self.currBasicBlock.addOperator(TosaOp.Op().CONST_SHAPE, [], name)
629 else:
630 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000631
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100632 # Save the const data to file for debug or as input files
633 if vals is not None and self.constMode in [
634 ConstMode.EMBED_DUMP,
635 ConstMode.INPUTS,
636 ]:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100637 filename = "{}.npy".format(name)
638 np.save(os.path.join(self.pathPrefix, filename), vals, False)
639
Kevin Chengfea5a372021-10-11 18:38:47 +0000640 return tens
641
642 def addIntermediate(self, shape, dtype):
Kevin Chengfea5a372021-10-11 18:38:47 +0000643 if not self.currBasicBlock:
644 raise Exception("addTensor called without valid basic block")
645
646 name = "layer-{}".format(self.currLayerIdx)
647 self.currLayerIdx = self.currLayerIdx + 1
648
649 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
650
651 return tens
652
653 def addInputTensor(self, tensor):
Won Jeon780ffb52023-08-21 13:32:36 -0700654 self.currBasicBlock.addTensor(
655 tensor.name,
656 tensor.shape,
657 tensor.dtype,
658 tensor.data,
659 tensor.placeholderFilename,
660 )
Kevin Chengfea5a372021-10-11 18:38:47 +0000661 self.currBasicBlock.addInput(tensor.name)
662
663 def addOutputTensor(self, tensor):
664 self.currBasicBlock.addOutput(tensor.name)
665
666 def addOutput(self, shape, dtype):
667 if not self.currBasicBlock:
668 raise Exception("addTensor called without valid basic block")
669
670 name = "result-{}".format(self.currResultIdx)
671 self.currResultIdx = self.currResultIdx + 1
672
673 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
674 self.currBasicBlock.addOutput(name)
675 return tens
676
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000677 def addOperator(self, op, inputs, outputs, attributes=None):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000678 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000679 raise Exception("Use addConstTensor() to add CONST ops")
680
681 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000682 op,
683 inputs,
684 outputs,
685 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000686 )
687
Jerry Ge1eb85042023-01-06 14:19:14 -0800688
689@unique
690class TensorDir(IntEnum):
691 PLACEHOLDER = 0
692 CONST = 1
693 INTERMEDIATE = 2
694 RESULT = 3
695
696
697class TosaSerializer:
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100698 def __init__(self, pathPrefix, constMode=ConstMode.EMBED):
Jerry Ge1eb85042023-01-06 14:19:14 -0800699 self.builder = flatbuffers.Builder(0)
700
Jerry Ge1eb85042023-01-06 14:19:14 -0800701 # Enables inspection of constant data outside of graph
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100702 self.constMode = constMode
703
704 self.regions = []
705 self.startRegion("main", pathPrefix)
Jerry Ge1eb85042023-01-06 14:19:14 -0800706
Jerry Geca7ce0e2023-01-10 17:24:38 +0000707 self.currRegion.addBasicBlock("main")
Jerry Ge1eb85042023-01-06 14:19:14 -0800708
709 # Is this an illegal test that is expected to fail?
710 self.expectedReturnCode = 0
711 self.expectedFailure = False
712 self.expectedFailureDesc = ""
713
714 def __str__(self):
715 concatString = ""
716 for region in self.regions:
717 concatString = concatString + str(region)
718 return concatString
719
720 def addPlaceholder(self, shape, dtype, vals):
721 return self.currRegion.addPlaceholder(shape, dtype, vals)
722
Jerry Ge53ceb482023-08-14 20:15:10 +0000723 def addConst(self, shape, dtype, vals, name=None):
724 return self.currRegion.addConst(shape, dtype, vals, name)
Jerry Ge1eb85042023-01-06 14:19:14 -0800725
726 def addIntermediate(self, shape, dtype):
727 return self.currRegion.addIntermediate(shape, dtype)
728
729 def addInputTensor(self, tensor):
730 self.currRegion.addInputTensor(tensor)
731
732 def addOutputTensor(self, tensor):
733 self.currRegion.addOutputTensor(tensor)
734
735 def addOutput(self, shape, dtype):
736 return self.currRegion.addOutput(shape, dtype)
737
738 def addOperator(self, op, inputs, outputs, attributes=None):
739 return self.currRegion.addOperator(op, inputs, outputs, attributes)
740
Jerry Geca7ce0e2023-01-10 17:24:38 +0000741 def addBasicBlock(self, name):
742 self.currRegion.addBasicBlock(name)
743
Jeremy Johnson9b225172021-12-14 16:34:47 +0000744 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000745
746 self.expectedReturnCode = val
747 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000748 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000749
750 def serialize(self):
751
752 builder = self.builder
753
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800754 Version.Start(builder)
Eric Kunzee2b20e42023-07-27 16:59:44 +0000755 Version.Add_Major(builder, TOSA_VERSION[0])
756 Version.Add_Minor(builder, TOSA_VERSION[1])
757 Version.Add_Patch(builder, TOSA_VERSION[2])
758 Version.Add_Draft(builder, TOSA_VERSION[3])
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800759 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000760
Jerry Ge1eb85042023-01-06 14:19:14 -0800761 fbv_region = TosaSerializer.serializeObjVec(
762 builder, self.regions, TosaGraph.StartRegionsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000763 )
764
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800765 TosaGraph.Start(builder)
766 TosaGraph.AddVersion(builder, version)
Jerry Ge1eb85042023-01-06 14:19:14 -0800767 TosaGraph.AddRegions(builder, fbv_region)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800768 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000769
Eric Kunzee6596402022-06-09 21:27:36 +0000770 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000771 return self.builder.Output()
772
773 def writeJson(self, tosa_filename):
774 """Write a json test file so that it is fairly easy to pick up the test
775 and generate commands for third party tool"""
776 test_desc = dict()
777
778 test_desc["tosa_file"] = tosa_filename
779 ifm_name = []
780 ifm_file = []
781 ofm_name = []
782 ofm_file = []
783
Jerry Ge1eb85042023-01-06 14:19:14 -0800784 for region in self.regions:
785 for block in region.basicBlocks:
Jerry Geca7ce0e2023-01-10 17:24:38 +0000786 if block and block.name == "main":
Jerry Ge1eb85042023-01-06 14:19:14 -0800787 for i in block.inputs:
788 ifm_name.append(i)
789 ifm_file.append(block.tensors[i].placeholderFilename)
790 for o in block.outputs:
791 ofm_name.append(o)
792 # Make up an OFM filename here. One isn't generated until the
793 # reference tool is run, so any name is a good name
794 ofm_file.append("ref-{}.npy".format(o))
Kevin Chengfea5a372021-10-11 18:38:47 +0000795
796 test_desc["ifm_name"] = ifm_name
797 test_desc["ifm_file"] = ifm_file
798 test_desc["ofm_name"] = ofm_name
799 test_desc["ofm_file"] = ofm_file
800 test_desc["expected_return_code"] = self.expectedReturnCode
801 test_desc["expected_failure"] = self.expectedFailure
802 if self.expectedFailureDesc:
803 test_desc["expected_failure_desc"] = self.expectedFailureDesc
804
805 return json.dumps(test_desc, indent=" ")
806
Jeremy Johnson005c46d2023-07-25 13:56:34 +0100807 def startRegion(self, name, pathPrefix):
808 self.currRegion = TosaSerializerRegion(name, pathPrefix, self.constMode)
Jerry Ge1eb85042023-01-06 14:19:14 -0800809 self.regions.append(self.currRegion)
Kevin Chengfea5a372021-10-11 18:38:47 +0000810
811 @staticmethod
812 def serializeStrVec(builder, vec, start_fcn):
813 fb_strs = [builder.CreateString(i) for i in vec]
814 start_fcn(builder, len(fb_strs))
815 for s in fb_strs[::-1]:
816 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700817 try:
818 return builder.EndVector()
819 except TypeError:
820 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000821
822 @staticmethod
823 def serializeUint8Vec(builder, vec):
824 builder.StartVector(1, len(vec), 8)
825 for v in vec[::-1]:
826 builder.PrependUint8(v)
827 try:
828 return builder.EndVector()
829 except TypeError:
830 return builder.EndVector(len(vec))
831
832 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700833 def serializeInt16Vec(builder, vec):
834 builder.StartVector(2, len(vec), 4)
835 for v in vec[::-1]:
836 builder.PrependInt16(v)
837 try:
838 return builder.EndVector()
839 except TypeError:
840 return builder.EndVector(len(vec))
841
842 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000843 def serializeInt32Vec(builder, vec):
844 builder.StartVector(4, len(vec), 4)
845 for v in vec[::-1]:
846 builder.PrependInt32(v)
847 try:
848 return builder.EndVector()
849 except TypeError:
850 return builder.EndVector(len(vec))
851
852 @staticmethod
853 def serializeFpVec(builder, vec):
854 builder.StartVector(4, len(vec), 4)
855 for v in vec[::-1]:
856 builder.PrependFloat32(v)
857 try:
858 return builder.EndVector()
859 except TypeError:
860 return builder.EndVector(len(vec))
861
862 @staticmethod
863 def serializeObjVec(builder, vec, start_fcn):
864 serialized_vec = []
865 for v in vec[::-1]:
866 serialized_vec.append(v.serialize(builder))
867
868 start_fcn(builder, len(vec))
869 for v in serialized_vec:
870 builder.PrependUOffsetTRelative(v)
871 try:
872 return builder.EndVector()
873 except TypeError:
874 return builder.EndVector(len(vec))
875
876 @staticmethod
877 def toList(val):
878 if isinstance(val, list):
879 return val
880 else:
881 return [val]
Tai Lyce911a22024-03-21 17:01:14 +0000882
883 @staticmethod
884 def convertDataToUint8Vec(dtype, data):
885 u8_data = list()
886 # little endianess
887 if dtype == DType.BOOL:
888 for val in data:
889 val_u8 = np.uint8(val)
890 u8_data.append(val_u8)
891 elif dtype == DType.INT4:
892 in_size = len(data)
893 out_size = (in_size + 1) // 2
894 for i in range(out_size):
895 val_0 = data[2 * i]
896 if (2 * i + 1) < in_size:
897 val_1 = data[2 * i + 1]
898 else:
899 val_1 = 0
900 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
901 val_u8 = np.uint8(val_i8)
902 u8_data.append(val_u8)
903 elif dtype == DType.INT8:
904 for val in data:
905 val_u8 = np.array(val).astype(dtype=np.uint8)
906 u8_data.append(val_u8)
907 elif dtype == DType.INT16:
908 for val in data:
909 val_u16 = np.array(val).astype(dtype=np.uint16)
910 b0 = val_u16 & ByteMask
911 b1 = (val_u16 >> np.uint16(8)) & ByteMask
912 u8_data.extend([b0, b1])
913 elif dtype == DType.INT32:
914 for val in data:
915 val_u32 = np.array(val).astype(dtype=np.uint32)
916 b0 = val_u32 & ByteMask
917 b1 = (val_u32 >> np.uint32(8)) & ByteMask
918 b2 = (val_u32 >> np.uint32(16)) & ByteMask
919 b3 = (val_u32 >> np.uint32(24)) & ByteMask
920 u8_data.extend([b0, b1, b2, b3])
921 elif dtype == DType.INT48:
922 for val in data:
923 val_u64 = np.uint64(val)
924 b0 = val_u64 & ByteMask
925 b1 = (val_u64 >> np.uint64(8)) & ByteMask
926 b2 = (val_u64 >> np.uint64(16)) & ByteMask
927 b3 = (val_u64 >> np.uint64(24)) & ByteMask
928 b4 = (val_u64 >> np.uint64(32)) & ByteMask
929 b5 = (val_u64 >> np.uint64(40)) & ByteMask
930 u8_data.extend([b0, b1, b2, b3, b4, b5])
931 elif dtype == DType.SHAPE:
932 for val in data:
933 val_u64 = np.uint64(val)
934 b0 = val_u64 & ByteMask
935 b1 = (val_u64 >> np.uint64(8)) & ByteMask
936 b2 = (val_u64 >> np.uint64(16)) & ByteMask
937 b3 = (val_u64 >> np.uint64(24)) & ByteMask
938 b4 = (val_u64 >> np.uint64(32)) & ByteMask
939 b5 = (val_u64 >> np.uint64(40)) & ByteMask
940 b6 = (val_u64 >> np.uint64(48)) & ByteMask
941 b7 = (val_u64 >> np.uint64(56)) & ByteMask
942 u8_data.extend([b0, b1, b2, b3, b4, b5, b6, b7])
943 elif dtype == DType.FP16:
944 np_arr = np.array(data, dtype=np.float16)
945 u8_data.extend(np_arr.view(np.uint8))
946 elif dtype == DType.FP32:
947 # for val in data:
948 # b = struct.pack("!f", val)
949 # u8_data.extend([b[3], b[2], b[1], b[0]])
950 np_arr = np.array(data, dtype=np.float32)
951 u8_data.extend(np_arr.view(np.uint8))
952 elif dtype == DType.BF16:
953 for val in data:
954 # convert val to little endian byte arrays b
955 b = struct.pack("<f", val)
956 # val => [ b[3], b[2], b[1], b[0] ]
957 # keep only most significant 2 bytes for bf16
958 # in little endian ordering
959 u8_data.extend([b[2], b[3]])
960 elif dtype == DType.FP8E4M3:
961 for val in data:
962 # convert val to fp8_bits then to single byte
963 f32_as_int = struct.unpack(">L", struct.pack(">f", val))[0]
964 f32_bits = f"{f32_as_int:032b}"
965 fp8_bits = f32_bits[0] + f32_bits[1:5] + f32_bits[9:12]
966 fp8_bytes = int(fp8_bits, 2).to_bytes(1, byteorder="little")
967 u8_data.extend(fp8_bytes)
968 elif dtype == DType.FP8E5M2:
969 for val in data:
970 # convert val to fp8_bits then to single byte
971 f32_as_int = struct.unpack(">L", struct.pack(">f", val))[0]
972 f32_bits = f"{f32_as_int:032b}"
973 fp8_bits = f32_bits[0] + f32_bits[1:6] + f32_bits[9:11]
974 fp8_bytes = int(fp8_bits, 2).to_bytes(1, byteorder="little")
975 u8_data.extend(fp8_bytes)
976 elif dtype == TosaDType.DType:
977 # Serialize DType enum data as uint8 bytes
978 for val in data:
979 np_arr = np.array(data, dtype=np.uint32)
980 u8_data.extend(np_arr.view(np.uint8))
981 else:
982 raise Exception("unsupported data type {}".format(DTypeNames[dtype]))
983 return u8_data