blob: b29f9636b8ef9fac2233955437f3a2cdff978457 [file] [log] [blame]
Jeremy Johnson9b225172021-12-14 16:34:47 +00001# Copyright (c) 2020-2022, 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
Kevin Chengfea5a372021-10-11 18:38:47 +000016import json
17import flatbuffers
18import numpy as np
19import struct
Jeremy Johnson9b225172021-12-14 16:34:47 +000020from enum import IntEnum, unique
Kevin Chengfea5a372021-10-11 18:38:47 +000021from tosa import (
22 TosaGraph,
23 TosaBasicBlock,
24 TosaTensor,
25 TosaOperator,
Kevin Chengfea5a372021-10-11 18:38:47 +000026 Version,
27)
Jeremy Johnson9b225172021-12-14 16:34:47 +000028import tosa.DType as TosaDType
29import tosa.Op as TosaOp
Kevin Chengfea5a372021-10-11 18:38:47 +000030
Kevin Chenge6563f52021-10-20 12:12:02 -070031# Keep version number in sync with the version default value with schema/tosa.fbs
Kevin Chengb97cb1d2021-10-14 11:53:39 -070032TOSA_VERSION_MAJOR = 0
Eric Kunzea687b612021-11-03 17:02:57 -070033TOSA_VERSION_MINOR = 24
Kevin Chengb97cb1d2021-10-14 11:53:39 -070034TOSA_VERSION_PATCH = 0
Eric Kunzea687b612021-11-03 17:02:57 -070035TOSA_VERSION_DRAFT = True
Jeremy Johnson9b225172021-12-14 16:34:47 +000036TOSA_VERSION = [
37 TOSA_VERSION_MAJOR,
38 TOSA_VERSION_MINOR,
39 TOSA_VERSION_PATCH,
40 TOSA_VERSION_DRAFT,
41]
Kevin Chengfea5a372021-10-11 18:38:47 +000042# With the way flatc generates its python types, there is no programatic way
43# to get string names for the integer types. Manually maintain a string table
44# here.
Jeremy Johnson9b225172021-12-14 16:34:47 +000045DType = TosaDType.DType()
Kevin Chengfea5a372021-10-11 18:38:47 +000046DTypeNames = [
47 "UNKNOWN",
48 "BOOL",
49 "UINT8",
50 "INT4",
51 "INT8",
52 "INT16",
53 "INT32",
54 "INT48",
55 "FLOAT",
56]
57
58ByteMask = np.uint64(0xFF)
59
60
61def dtype_str_to_val(name):
62
63 for i in range(len(DTypeNames)):
64 if name.casefold() == DTypeNames[i].casefold():
65 return i
66 raise Exception("Unable to parse DType name {}".format(name))
67
68
69class TosaSerializerUnion:
70 """This class handles encapsulating and serializing union types into flatbuffers"""
71
72 def __init__(self):
73
Jeremy Johnson9b225172021-12-14 16:34:47 +000074 # A tuple of the start and end functions.
75 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000076 self.optFcns = None
77
Jeremy Johnson9b225172021-12-14 16:34:47 +000078 # The type from the tosa.Options enumeration.
79 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000080 self.utype = None
81
82 # Each of these lists is a tuple of the add function and the
83 # value being added. Set by the options constructors below.
84 self.ints = []
85 self.bools = []
86 self.floats = []
87 self.strings = []
88 self.intvecs = []
89 self.fpvecs = []
90
91 def serialize(self, builder):
92
93 # We have to build strings and vectors first
94 strList = []
95 intVecList = []
96 fpVecList = []
97
98 for fcn, val in self.strings:
99 strList.append((fcn, builder.CreateString(val)))
100
101 for fcn, val in self.intvecs:
102 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
103
104 for fcn, val in self.fpvecs:
105 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
106
107 startFcn, endFcn = self.optFcns
108
109 # Then serialize the options object from the list of primitives and
110 # other serialized values
111 startFcn(builder)
112 for fcn, val in self.ints:
113 fcn(builder, val)
114
115 for fcn, val in self.bools:
116 fcn(builder, val)
117
118 for fcn, val in self.floats:
119 fcn(builder, val)
120
121 for fcn, val in strList:
122 fcn(builder, val)
123
124 for fcn, val in intVecList:
125 fcn(builder, val)
126
127 for fcn, val in fpVecList:
128 fcn(builder, val)
129
130 return endFcn(builder)
131
132
133class TosaSerializerAttribute(TosaSerializerUnion):
134 """This class handles encapsulating all of the enumerated types for attributes"""
135
136 def __init__(self):
137 super().__init__()
138
139 def PoolAttribute(self, kernel, stride, padding):
140 from tosa import PoolAttribute as a, Attribute
141
142 self.utype = Attribute.Attribute().PoolAttribute
143
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800144 self.optFcns = (a.Start, a.End)
145 self.intvecs.append((a.AddPadding, padding))
146 self.intvecs.append((a.AddKernel, kernel))
147 self.intvecs.append((a.AddStride, stride))
Kevin Chengfea5a372021-10-11 18:38:47 +0000148
149 def ConvAttribute(self, padding, stride, dilation):
150 from tosa import ConvAttribute as a, Attribute
151
152 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800153 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000154
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800155 self.intvecs.append((a.AddPadding, padding))
156 self.intvecs.append((a.AddStride, stride))
157 self.intvecs.append((a.AddDilation, dilation))
Kevin Chengfea5a372021-10-11 18:38:47 +0000158
159 def TransposeConvAttribute(self, outpad, stride, dilation, output_shape):
160 from tosa import TransposeConvAttribute as a, Attribute
161
162 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800163 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000164
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800165 self.intvecs.append((a.AddOutpad, outpad))
166 self.intvecs.append((a.AddStride, stride))
167 self.intvecs.append((a.AddDilation, dilation))
168 self.intvecs.append((a.AddOutputShape, output_shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000169
Kevin Cheng38d214c2021-10-15 15:49:19 -0700170 def PadAttribute(self, padding, pad_const_int, pad_const_fp):
171 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000172
Kevin Cheng38d214c2021-10-15 15:49:19 -0700173 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800174 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000175
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800176 self.intvecs.append((a.AddPadding, padding))
177 self.ints.append((a.AddPadConstInt, pad_const_int))
178 self.floats.append((a.AddPadConstFp, pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000179
180 def AxisAttribute(self, axis):
181 from tosa import AxisAttribute as a, Attribute
182
183 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800184 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000185
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800186 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000187
188 def ReshapeAttribute(self, shape):
189 from tosa import ReshapeAttribute as a, Attribute
190
191 self.utype = Attribute.Attribute().ReshapeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800192 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000193
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800194 self.intvecs.append((a.AddShape, shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000195
196 def SliceAttribute(self, begin, size):
197 from tosa import SliceAttribute as a, Attribute
198
199 self.utype = Attribute.Attribute().SliceAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800200 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000201
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800202 self.intvecs.append((a.AddBegin, begin))
203 self.intvecs.append((a.AddSize, size))
Kevin Chengfea5a372021-10-11 18:38:47 +0000204
205 def TileAttribute(self, multiples):
206 from tosa import TileAttribute as a, Attribute
207
208 self.utype = Attribute.Attribute().TileAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800209 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000210
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800211 self.intvecs.append((a.AddMultiples, multiples))
Kevin Chengfea5a372021-10-11 18:38:47 +0000212
213 def ResizeAttribute(
214 self, output_size, stride, offset, shift, stride_fp, offset_fp, mode
215 ):
216 from tosa import ResizeAttribute as a, Attribute
217
218 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800219 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000220
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800221 self.intvecs.append((a.AddOutputSize, output_size))
222 self.intvecs.append((a.AddStride, stride))
223 self.intvecs.append((a.AddOffset, offset))
224 self.ints.append((a.AddShift, shift))
225 self.fpvecs.append((a.AddStrideFp, stride_fp))
226 self.fpvecs.append((a.AddOffsetFp, offset_fp))
227 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000228
229 def ClampAttribute(self, minint, maxint, minfp, maxfp):
230 from tosa import ClampAttribute as a, Attribute
231
232 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800233 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000234
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800235 self.ints.append((a.AddMinInt, minint))
236 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000237
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800238 self.ints.append((a.AddMinFp, minfp))
239 self.ints.append((a.AddMaxFp, maxfp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000240
241 def RescaleAttribute(
242 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
243 ):
244 from tosa import RescaleAttribute as a, Attribute
245
246 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800247 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000248
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800249 self.ints.append((a.AddInputZp, input_zp))
250 self.ints.append((a.AddOutputZp, output_zp))
251 self.intvecs.append((a.AddMultiplier, multiplier))
252 self.intvecs.append((a.AddShift, shift))
253 self.bools.append((a.AddScale32, scale32))
254 self.bools.append((a.AddDoubleRound, double_round))
255 self.bools.append((a.AddPerChannel, per_channel))
Kevin Chengfea5a372021-10-11 18:38:47 +0000256
257 def MulAttribute(self, shift):
258 from tosa import MulAttribute as a, Attribute
259
260 self.utype = Attribute.Attribute().MulAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800261 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000262
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800263 self.ints.append((a.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000264
265 def ArithmeticRightShiftAttribute(self, round):
266 from tosa import ArithmeticRightShiftAttribute as a, Attribute
267
268 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
269 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800270 a.Start,
271 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000272 )
273
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800274 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000275
Kevin Chengfea5a372021-10-11 18:38:47 +0000276 def CondIfAttribute(self, then_branch, else_branch):
277 from tosa import CondIfAttribute as a, Attribute
278
279 self.utype = Attribute.Attribute().CondIfAttribute
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.strings.append((a.AddThenBranch, then_branch))
283 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000284
285 def WhileLoopAttribute(self, cond_branch, body_branch):
286 from tosa import WhileLoopAttribute as a, Attribute
287
288 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800289 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000290
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800291 self.strings.append((a.AddCondBranch, cond_branch))
292 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000293
Kevin Cheng38d214c2021-10-15 15:49:19 -0700294 def TransposeAttribute(self, perm):
295 from tosa import TransposeAttribute as a, Attribute
296
297 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800298 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700299
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800300 self.intvecs.append((a.AddPerm, perm))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700301
302 def TableAttribute(self, table):
303 from tosa import TableAttribute as a, Attribute
304
305 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800306 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700307
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800308 self.intvecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000309
Jeremy Johnson9b225172021-12-14 16:34:47 +0000310
Kevin Chengfea5a372021-10-11 18:38:47 +0000311class TosaSerializerQuantInfo(TosaSerializerUnion):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000312 """This class handles encapsulating all of the enumerated types for quantinfo"""
Kevin Chengfea5a372021-10-11 18:38:47 +0000313
314 def __init__(self):
315 super().__init__()
316
317 def ConvQuantInfo(self, input_zp, weight_zp):
318 from tosa import ConvQuantInfo as q, QuantInfo
319
320 self.utype = QuantInfo.QuantInfo().ConvQuantInfo
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800321 self.optFcns = (q.Start, q.End)
322 self.ints.append((q.AddInputZp, input_zp))
323 self.ints.append((q.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000324
325 def UnaryQuantInfo(self, input_zp, output_zp):
326 from tosa import UnaryQuantInfo as q, QuantInfo
327
328 self.utype = QuantInfo.QuantInfo().UnaryQuantInfo
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800329 self.optFcns = (q.Start, q.End)
330 self.ints.append((q.AddInputZp, input_zp))
331 self.ints.append((q.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000332
333 def MatMulQuantInfo(self, a_zp, b_zp):
334 from tosa import MatMulQuantInfo as q, QuantInfo
335
336 self.utype = QuantInfo.QuantInfo().MatMulQuantInfo
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800337 self.optFcns = (q.Start, q.End)
338 self.ints.append((q.AddAZp, a_zp))
339 self.ints.append((q.AddBZp, b_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000340
341 def PadQuantInfo(self, input_zp):
342 from tosa import PadQuantInfo as q, QuantInfo
343
344 self.utype = QuantInfo.QuantInfo().PadQuantInfo
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800345 self.optFcns = (q.Start, q.End)
346 self.ints.append((q.AddInputZp, input_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000347
348
349class TosaSerializerTensor:
350 def __init__(
351 self,
352 name,
353 shape,
354 dtype,
355 data=None,
356 placeholderFilename=None,
357 ):
358 self.name = name
359
360 if isinstance(shape, np.ndarray):
361 shape = shape.astype(int).tolist()
362 shape = list(map(int, shape))
363
364 self.shape = shape
365 self.dtype = dtype
366
367 if isinstance(data, np.ndarray):
368 data = data.flatten().astype(int).tolist()
369 data = list(map(int, data))
370 self.data = data
371 elif isinstance(data, list):
372 data = list(map(int, data))
373 self.data = data
374 else:
375 self.data = None
376
377 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000378 # process and are written to disk, but are considered input tensors by the
379 # network so they do not appear in the TOSA serialiazation. However, if we
380 # want to form a unit test around these input tensors, we can get the filename
381 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000382 self.placeholderFilename = placeholderFilename
383
384 def __str__(self):
385 str = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
386 self.name,
387 self.shape,
388 DTypeNames[self.dtype],
389 )
390 return str
391
392 def setDtype(self, dtype):
393 self.dtype = dtype
394
395 def serialize(self, builder):
396 fb_name = builder.CreateString(self.name)
397 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
398 if self.data:
399 u8_data = list()
400 # little endianess
401 if self.dtype == DType.BOOL:
402 for val in self.data:
403 val_u8 = np.uint8(val)
404 u8_data.append(val_u8)
405 elif self.dtype == DType.INT4:
406 in_size = len(self.data)
407 out_size = (in_size + 1) // 2
408 for i in range(out_size):
409 val_0 = self.data[2 * i]
410 if (2 * i + 1) < in_size:
411 val_1 = self.data[2 * i + 1]
412 else:
413 val_1 = 0
414 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
415 val_u8 = np.uint8(val_i8)
416 u8_data.append(val_u8)
417 elif self.dtype == DType.INT8:
418 for val in self.data:
419 val_u8 = np.uint8(val)
420 u8_data.append(val_u8)
421 elif self.dtype == DType.INT16:
422 for val in self.data:
423 val_u16 = np.uint16(val)
424 b0 = val_u16 & ByteMask
425 b1 = (val_u16 >> np.uint16(8)) & ByteMask
426 u8_data.extend([b0, b1])
427 elif self.dtype == DType.INT32:
428 for val in self.data:
429 val_u32 = np.uint32(val)
430 b0 = val_u32 & ByteMask
431 b1 = (val_u32 >> np.uint32(8)) & ByteMask
432 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700433 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000434 u8_data.extend([b0, b1, b2, b3])
435 elif self.dtype == DType.INT48:
436 for val in self.data:
437 val_u64 = np.uint64(val)
438 b0 = val_u64 & ByteMask
439 b1 = (val_u64 >> np.uint64(8)) & ByteMask
440 b2 = (val_u64 >> np.uint64(16)) & ByteMask
441 b3 = (val_u64 >> np.uint64(24)) & ByteMask
442 b4 = (val_u64 >> np.uint64(32)) & ByteMask
443 b5 = (val_u64 >> np.uint64(40)) & ByteMask
444 u8_data.extend([b0, b1, b2, b3, b4, b5])
445 elif self.dtype == DType.FLOAT:
446 for val in self.data:
447 b = struct.pack("!f", val)
448 u8_data.extend([b[3], b[2], b[1], b[0]])
449 else:
450 raise Exception(
451 "unsupported data type {}".format(DTypeNames[self.dtype])
452 )
453 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
454
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800455 TosaTensor.Start(builder)
456 TosaTensor.AddName(builder, fb_name)
457 TosaTensor.AddShape(builder, fb_shapes)
458 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000459 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800460 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000461
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800462 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000463
464
465class TosaSerializerOperator:
466 def __init__(self, op, inputs, outputs, attributes=None, quantInfo=None):
467 self.op = op
468 self.attributes = attributes
469 self.inputs = TosaSerializer.toList(inputs)
470 self.outputs = TosaSerializer.toList(outputs)
471 self.quantInfo = quantInfo
472
473 def __str__(self):
474 str = "Op {}\n----\n".format(self.op)
475
476 for i in self.inputs:
477 str = str + " Input: {}\n".format(i)
478 for o in self.outputs:
479 str = str + " Output: {}\n".format(o)
480
481 return str
482
483 def serialize(self, builder):
484 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800485 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000486 )
487 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800488 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000489 )
490 # Need to serialize quant_info and attributes enums still
491 if self.attributes is not None:
492 fb_attributes = self.attributes.serialize(builder)
493
494 if self.quantInfo is not None:
495 fb_qinfo = self.quantInfo.serialize(builder)
496
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800497 TosaOperator.Start(builder)
498 TosaOperator.AddOp(builder, self.op)
499 TosaOperator.AddInputs(builder, fb_inputs)
500 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000501 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800502 TosaOperator.AddAttributeType(builder, self.attributes.utype)
503 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000504 if self.quantInfo is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800505 TosaOperator.AddQuantInfoType(builder, self.quantInfo.utype)
506 TosaOperator.AddQuantInfo(builder, fb_qinfo)
Kevin Chengfea5a372021-10-11 18:38:47 +0000507
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800508 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000509
510
511class TosaSerializerBasicBlock:
512 def __init__(self, name):
513 self.name = name
514 self.operators = []
515
516 # Dict assures uniqueness, but allows us to look up by name
517 self.tensors = dict()
518
519 self.inputs = []
520 self.outputs = []
521
522 def addTensor(
523 self,
524 name,
525 shape,
526 dtype,
527 data=None,
528 placeholderFilename=None,
529 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000530 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000531 self.tensors[name] = TosaSerializerTensor(
532 name, shape, dtype, data, placeholderFilename
533 )
534
535 return self.tensors[name]
536
537 def addInput(self, name):
538 self.inputs.append(name)
539
540 def addOutput(self, name):
541 self.outputs.append(name)
542
543 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
544 self.operators.append(
545 TosaSerializerOperator(op, inputs, outputs, attributes, quant_info)
546 )
547
548 def serialize(self, builder):
549 fb_name = builder.CreateString(self.name)
550 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800551 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000552 )
553 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800554 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000555 )
556 fbv_tensors = TosaSerializer.serializeObjVec(
557 builder,
558 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800559 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000560 )
561 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800562 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000563 )
564
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800565 TosaBasicBlock.Start(builder)
566 TosaBasicBlock.AddName(builder, fb_name)
567 TosaBasicBlock.AddInputs(builder, fbv_inputs)
568 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
569 TosaBasicBlock.AddTensors(builder, fbv_tensors)
570 TosaBasicBlock.AddOperators(builder, fbv_operators)
571 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000572
573
574@unique
575class TensorDir(IntEnum):
576 PLACEHOLDER = 0
577 CONST = 1
578 INTERMEDIATE = 2
579 RESULT = 3
580
581
582class TosaSerializer:
583 def __init__(self, pathPrefix):
584
585 # Get the global TOSA version if not already defined
Kevin Chengfea5a372021-10-11 18:38:47 +0000586
587 self.builder = flatbuffers.Builder(0)
588
589 self.basicBlocks = []
590 self.startBasicBlock("main")
591 self.pathPrefix = pathPrefix
592
593 # Indicies used for adding/naming tensors
594 self.currInputIdx = 0
595 self.currConstIdx = 0
596 self.currLayerIdx = 1
597 self.currResultIdx = 0
598
599 # Is this an illegal test that is expected to fail?
Jeremy Johnson9b225172021-12-14 16:34:47 +0000600 self.expectedReturnCode = 0
Kevin Chengfea5a372021-10-11 18:38:47 +0000601 self.expectedFailure = False
602 self.expectedFailureDesc = ""
603
604 def __str__(self):
605 str = ""
606 for bb in self.basicBlocks:
607 str = str + bb.__str__()
608 return str
609
610 def addPlaceholder(self, shape, dtype, vals):
611 if not self.currBasicBlock:
612 raise Exception("addTensor called without valid basic block")
613
614 name = "input-{}".format(self.currInputIdx)
615 filename = "{}.npy".format(name)
616 self.currInputIdx = self.currInputIdx + 1
617
618 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
619 # This is always an input to the block
620 self.currBasicBlock.addInput(name)
621
622 if vals is not None:
623 np.save(os.path.join(self.pathPrefix, filename), vals, False)
624
625 return tens
626
627 def addConst(self, shape, dtype, vals):
628 if not self.currBasicBlock:
629 raise Exception("addTensor called without valid basic block")
630
631 name = "const-{}".format(self.currInputIdx)
Kevin Chengfea5a372021-10-11 18:38:47 +0000632 self.currInputIdx = self.currInputIdx + 1
633
634 tens = self.currBasicBlock.addTensor(name, shape, dtype, vals)
635 # Add the operator now
Jeremy Johnson9b225172021-12-14 16:34:47 +0000636 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000637
638 return tens
639
640 def addIntermediate(self, shape, dtype):
641
642 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):
653 self.currBasicBlock.addTensor(tensor.name, tensor.shape, tensor.dtype)
654 self.currBasicBlock.addInput(tensor.name)
655
656 def addOutputTensor(self, tensor):
657 self.currBasicBlock.addOutput(tensor.name)
658
659 def addOutput(self, shape, dtype):
660 if not self.currBasicBlock:
661 raise Exception("addTensor called without valid basic block")
662
663 name = "result-{}".format(self.currResultIdx)
664 self.currResultIdx = self.currResultIdx + 1
665
666 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
667 self.currBasicBlock.addOutput(name)
668 return tens
669
670 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
671
Jeremy Johnson9b225172021-12-14 16:34:47 +0000672 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000673 raise Exception("Use addConstTensor() to add CONST ops")
674
675 return self.currBasicBlock.addOperator(
676 op, inputs, outputs, attributes, quant_info
677 )
678
Jeremy Johnson9b225172021-12-14 16:34:47 +0000679 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000680
681 self.expectedReturnCode = val
682 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000683 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000684
685 def serialize(self):
686
687 builder = self.builder
688
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800689 Version.Start(builder)
690 Version.Add_major(builder, TOSA_VERSION[0])
691 Version.Add_minor(builder, TOSA_VERSION[1])
692 Version.Add_patch(builder, TOSA_VERSION[2])
693 Version.Add_draft(builder, TOSA_VERSION[3])
694 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000695
696 fbv_bb = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800697 builder, self.basicBlocks, TosaGraph.StartBlocksVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000698 )
699
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800700 TosaGraph.Start(builder)
701 TosaGraph.AddVersion(builder, version)
702 TosaGraph.AddBlocks(builder, fbv_bb)
703 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000704
705 self.builder.Finish(graph)
706 return self.builder.Output()
707
708 def writeJson(self, tosa_filename):
709 """Write a json test file so that it is fairly easy to pick up the test
710 and generate commands for third party tool"""
711 test_desc = dict()
712
713 test_desc["tosa_file"] = tosa_filename
714 ifm_name = []
715 ifm_file = []
716 ofm_name = []
717 ofm_file = []
718
719 for b in self.basicBlocks:
720 if b.name == "main":
721 for i in b.inputs:
722 ifm_name.append(i)
723 ifm_file.append(b.tensors[i].placeholderFilename)
724 for o in b.outputs:
725 ofm_name.append(o)
Jeremy Johnson9b225172021-12-14 16:34:47 +0000726 # Make up an OFM filename here. One isn't generated until the
727 # reference tool is run, so any name is a good name
Kevin Chengfea5a372021-10-11 18:38:47 +0000728 ofm_file.append("ref-{}.npy".format(o))
729
730 test_desc["ifm_name"] = ifm_name
731 test_desc["ifm_file"] = ifm_file
732 test_desc["ofm_name"] = ofm_name
733 test_desc["ofm_file"] = ofm_file
734 test_desc["expected_return_code"] = self.expectedReturnCode
735 test_desc["expected_failure"] = self.expectedFailure
736 if self.expectedFailureDesc:
737 test_desc["expected_failure_desc"] = self.expectedFailureDesc
738
739 return json.dumps(test_desc, indent=" ")
740
741 def startBasicBlock(self, name):
742 self.currBasicBlock = TosaSerializerBasicBlock(name)
743 self.basicBlocks.append(self.currBasicBlock)
744
745 @staticmethod
746 def serializeStrVec(builder, vec, start_fcn):
747 fb_strs = [builder.CreateString(i) for i in vec]
748 start_fcn(builder, len(fb_strs))
749 for s in fb_strs[::-1]:
750 builder.PrependUOffsetTRelative(s)
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800751 return builder.EndVector()
Kevin Chengfea5a372021-10-11 18:38:47 +0000752
753 @staticmethod
754 def serializeUint8Vec(builder, vec):
755 builder.StartVector(1, len(vec), 8)
756 for v in vec[::-1]:
757 builder.PrependUint8(v)
758 try:
759 return builder.EndVector()
760 except TypeError:
761 return builder.EndVector(len(vec))
762
763 @staticmethod
764 def serializeInt32Vec(builder, vec):
765 builder.StartVector(4, len(vec), 4)
766 for v in vec[::-1]:
767 builder.PrependInt32(v)
768 try:
769 return builder.EndVector()
770 except TypeError:
771 return builder.EndVector(len(vec))
772
773 @staticmethod
774 def serializeFpVec(builder, vec):
775 builder.StartVector(4, len(vec), 4)
776 for v in vec[::-1]:
777 builder.PrependFloat32(v)
778 try:
779 return builder.EndVector()
780 except TypeError:
781 return builder.EndVector(len(vec))
782
783 @staticmethod
784 def serializeObjVec(builder, vec, start_fcn):
785 serialized_vec = []
786 for v in vec[::-1]:
787 serialized_vec.append(v.serialize(builder))
788
789 start_fcn(builder, len(vec))
790 for v in serialized_vec:
791 builder.PrependUOffsetTRelative(v)
792 try:
793 return builder.EndVector()
794 except TypeError:
795 return builder.EndVector(len(vec))
796
797 @staticmethod
798 def toList(val):
799 if isinstance(val, list):
800 return val
801 else:
802 return [val]