blob: b4daaad311b44783e923903588cfbcbb218fa0e1 [file] [log] [blame]
Kevin Cheng3a478572021-01-22 17:21:02 -08001# Copyright (c) 2020-2021, ARM Limited.
Eric Kunzee5e26762020-10-13 16:11:07 -07002#
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
15#!/usr/bin/env python3
16
Kevin Cheng550ccc52021-03-03 11:21:43 -080017import os
18import sys
19import json
Eric Kunzee5e26762020-10-13 16:11:07 -070020import flatbuffers
21import numpy as np
Kevin Cheng82507d72021-06-17 16:01:59 -070022import struct
Eric Kunzee5e26762020-10-13 16:11:07 -070023from enum import Enum, IntEnum, unique
Kevin Cheng550ccc52021-03-03 11:21:43 -080024from tosa import (
25 TosaGraph,
26 TosaBasicBlock,
27 TosaTensor,
28 TosaOperator,
29 DType,
30 Op,
31 ResizeMode,
32 Version,
33)
34
35# Include the ../thirdparty/serialization_lib/python directory in PYTHONPATH
36parent_dir = os.path.dirname(os.path.realpath(__file__))
37sys.path.append(
38 os.path.join(parent_dir, "..", "thirdparty", "serialization_lib", "python")
39)
Eric Kunzee5e26762020-10-13 16:11:07 -070040import tosa
Eric Kunzee5e26762020-10-13 16:11:07 -070041
42# 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.
Kevin Cheng82507d72021-06-17 16:01:59 -070045DType = tosa.DType.DType()
Kevin Cheng550ccc52021-03-03 11:21:43 -080046DTypeNames = [
47 "UNKNOWN",
48 "BOOL",
49 "UINT8",
50 "INT4",
51 "INT8",
52 "INT16",
53 "INT32",
54 "INT48",
55 "FLOAT",
56]
57
Kevin Cheng82507d72021-06-17 16:01:59 -070058ByteMask = np.uint64(0xFF)
Eric Kunzee5e26762020-10-13 16:11:07 -070059
60def dtype_str_to_val(name):
61
62 for i in range(len(DTypeNames)):
63 if name.casefold() == DTypeNames[i].casefold():
64 return i
Kevin Cheng550ccc52021-03-03 11:21:43 -080065 raise Exception("Unable to parse DType name {}".format(name))
Eric Kunzee5e26762020-10-13 16:11:07 -070066
67
68class TosaSerializerUnion:
Kevin Cheng550ccc52021-03-03 11:21:43 -080069 """This class handles encapsulating and serializing union types into flatbuffers"""
70
Eric Kunzee5e26762020-10-13 16:11:07 -070071 def __init__(self):
72
73 # A tuple of the start and end functions. Set by the options constructors below
74 self.optFcns = None
75
76 # The type from the tosa.Options enumeration. Set by the options constructors below.
77 self.utype = None
78
79 # Each of these lists is a tuple of the add function and the
80 # value being added. Set by the options constructors below.
81 self.ints = []
82 self.bools = []
83 self.floats = []
84 self.strings = []
85 self.intvecs = []
Kevin Cheng77d0f762020-11-24 10:26:32 -080086 self.fpvecs = []
Eric Kunzee5e26762020-10-13 16:11:07 -070087
88 def serialize(self, builder):
89
90 # We have to build strings and vectors first
91 strList = []
92 intVecList = []
Kevin Cheng77d0f762020-11-24 10:26:32 -080093 fpVecList = []
Eric Kunzee5e26762020-10-13 16:11:07 -070094
95 for fcn, val in self.strings:
96 strList.append((fcn, builder.CreateString(val)))
97
98 for fcn, val in self.intvecs:
99 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
100
Kevin Cheng77d0f762020-11-24 10:26:32 -0800101 for fcn, val in self.fpvecs:
102 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
103
Eric Kunzee5e26762020-10-13 16:11:07 -0700104 startFcn, endFcn = self.optFcns
105
106 # Then serialize the options object from the list of primitives and
107 # other serialized values
108 startFcn(builder)
109 for fcn, val in self.ints:
110 fcn(builder, val)
111
112 for fcn, val in self.bools:
113 fcn(builder, val)
114
115 for fcn, val in self.floats:
116 fcn(builder, val)
117
118 for fcn, val in strList:
119 fcn(builder, val)
120
121 for fcn, val in intVecList:
122 fcn(builder, val)
123
Kevin Cheng77d0f762020-11-24 10:26:32 -0800124 for fcn, val in fpVecList:
125 fcn(builder, val)
126
Eric Kunzee5e26762020-10-13 16:11:07 -0700127 return endFcn(builder)
128
Kevin Cheng550ccc52021-03-03 11:21:43 -0800129
Eric Kunzee5e26762020-10-13 16:11:07 -0700130class TosaSerializerAttribute(TosaSerializerUnion):
Kevin Cheng550ccc52021-03-03 11:21:43 -0800131 """This class handles encapsulating all of the enumerated types for attributes"""
Eric Kunzee5e26762020-10-13 16:11:07 -0700132
133 def __init__(self):
134 super().__init__()
135
136 def Pool2dAttribute(self, kernel, stride, padding):
137 from tosa import Pool2dAttribute as a, Attribute
138
139 self.utype = Attribute.Attribute().Pool2dAttribute
140
141 self.optFcns = (a.Pool2dAttributeStart, a.Pool2dAttributeEnd)
Kevin Cheng550ccc52021-03-03 11:21:43 -0800142 self.intvecs.append((a.Pool2dAttributeAddPadding, padding))
143 self.intvecs.append((a.Pool2dAttributeAddKernel, kernel))
144 self.intvecs.append((a.Pool2dAttributeAddStride, stride))
Eric Kunzee5e26762020-10-13 16:11:07 -0700145
146 def Conv2dAttribute(self, padding, stride, dilation):
147 from tosa import Conv2dAttribute as a, Attribute
148
149 self.utype = Attribute.Attribute().Conv2dAttribute
150 self.optFcns = (a.Conv2dAttributeStart, a.Conv2dAttributeEnd)
151
Kevin Cheng550ccc52021-03-03 11:21:43 -0800152 self.intvecs.append((a.Conv2dAttributeAddPadding, padding))
153 self.intvecs.append((a.Conv2dAttributeAddStride, stride))
154 self.intvecs.append((a.Conv2dAttributeAddDilation, dilation))
Eric Kunzee5e26762020-10-13 16:11:07 -0700155
156 def TransposeConv2DAttribute(self, outpad, stride, dilation, output_shape):
157 from tosa import TransposeConv2dAttribute as a, Attribute
158
159 self.utype = Attribute.Attribute().TransposeConv2dAttribute
160 self.optFcns = (a.TransposeConv2dAttributeStart, a.TransposeConv2dAttributeEnd)
161
Kevin Cheng550ccc52021-03-03 11:21:43 -0800162 self.intvecs.append((a.TransposeConv2dAttributeAddOutpad, outpad))
163 self.intvecs.append((a.TransposeConv2dAttributeAddStride, stride))
164 self.intvecs.append((a.TransposeConv2dAttributeAddDilation, dilation))
165 self.intvecs.append((a.TransposeConv2dAttributeAddOutputShape, output_shape))
Eric Kunzee5e26762020-10-13 16:11:07 -0700166
167 def ReluNAttribute(self, maxint, maxfp):
168 from tosa import ReluNAttribute as a, Attribute
169
170 self.utype = Attribute.Attribute().ReluNAttribute
171 self.optFcns = (a.ReluNAttributeStart, a.ReluNAttributeEnd)
172
173 self.ints.append((a.ReluNAttributeAddMaxInt, maxint))
174 self.ints.append((a.ReluNAttributeAddMaxFp, maxfp))
175
Eric Kunzee5e26762020-10-13 16:11:07 -0700176 def AxisAttribute(self, axis):
177 from tosa import AxisAttribute as a, Attribute
178
179 self.utype = Attribute.Attribute().AxisAttribute
180 self.optFcns = (a.AxisAttributeStart, a.AxisAttributeEnd)
181
Kevin Cheng550ccc52021-03-03 11:21:43 -0800182 self.ints.append((a.AxisAttributeAddAxis, axis))
Eric Kunzee5e26762020-10-13 16:11:07 -0700183
184 def ReshapeAttribute(self, shape):
185 from tosa import ReshapeAttribute as a, Attribute
186
187 self.utype = Attribute.Attribute().ReshapeAttribute
188 self.optFcns = (a.ReshapeAttributeStart, a.ReshapeAttributeEnd)
189
Kevin Cheng550ccc52021-03-03 11:21:43 -0800190 self.intvecs.append((a.ReshapeAttributeAddShape, shape))
Eric Kunzee5e26762020-10-13 16:11:07 -0700191
192 def SliceAttribute(self, begin, size):
193 from tosa import SliceAttribute as a, Attribute
194
195 self.utype = Attribute.Attribute().SliceAttribute
196 self.optFcns = (a.SliceAttributeStart, a.SliceAttributeEnd)
197
Kevin Cheng550ccc52021-03-03 11:21:43 -0800198 self.intvecs.append((a.SliceAttributeAddBegin, begin))
199 self.intvecs.append((a.SliceAttributeAddSize, size))
Eric Kunzee5e26762020-10-13 16:11:07 -0700200
201 def TileAttribute(self, multiples):
202 from tosa import TileAttribute as a, Attribute
203
204 self.utype = Attribute.Attribute().TileAttribute
205 self.optFcns = (a.TileAttributeStart, a.TileAttributeEnd)
206
Kevin Cheng550ccc52021-03-03 11:21:43 -0800207 self.intvecs.append((a.TileAttributeAddMultiples, multiples))
Eric Kunzee5e26762020-10-13 16:11:07 -0700208
Kevin Cheng550ccc52021-03-03 11:21:43 -0800209 def ResizeAttribute(
210 self, output_size, stride, offset, shift, stride_fp, offset_fp, mode
211 ):
Eric Kunzee5e26762020-10-13 16:11:07 -0700212 from tosa import ResizeAttribute as a, Attribute
213
214 self.utype = Attribute.Attribute().ResizeAttribute
215 self.optFcns = (a.ResizeAttributeStart, a.ResizeAttributeEnd)
216
Kevin Cheng550ccc52021-03-03 11:21:43 -0800217 self.intvecs.append((a.ResizeAttributeAddOutputSize, output_size))
218 self.intvecs.append((a.ResizeAttributeAddStride, stride))
219 self.intvecs.append((a.ResizeAttributeAddOffset, offset))
220 self.ints.append((a.ResizeAttributeAddShift, shift))
221 self.fpvecs.append((a.ResizeAttributeAddStrideFp, stride_fp))
222 self.fpvecs.append((a.ResizeAttributeAddOffsetFp, offset_fp))
223 self.ints.append((a.ResizeAttributeAddMode, mode))
Eric Kunzee5e26762020-10-13 16:11:07 -0700224
225 def ClampAttribute(self, minint, maxint, minfp, maxfp):
226 from tosa import ClampAttribute as a, Attribute
227
228 self.utype = Attribute.Attribute().ClampAttribute
229 self.optFcns = (a.ClampAttributeStart, a.ClampAttributeEnd)
230
Kevin Cheng550ccc52021-03-03 11:21:43 -0800231 self.ints.append((a.ClampAttributeAddMinInt, minint))
232 self.ints.append((a.ClampAttributeAddMaxInt, maxint))
Eric Kunzee5e26762020-10-13 16:11:07 -0700233
Kevin Cheng550ccc52021-03-03 11:21:43 -0800234 self.ints.append((a.ClampAttributeAddMinFp, minfp))
235 self.ints.append((a.ClampAttributeAddMaxFp, maxfp))
Eric Kunzee5e26762020-10-13 16:11:07 -0700236
Kevin Cheng550ccc52021-03-03 11:21:43 -0800237 def RescaleAttribute(
238 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
239 ):
Eric Kunzee5e26762020-10-13 16:11:07 -0700240 from tosa import RescaleAttribute as a, Attribute
241
242 self.utype = Attribute.Attribute().RescaleAttribute
243 self.optFcns = (a.RescaleAttributeStart, a.RescaleAttributeEnd)
244
Kevin Cheng550ccc52021-03-03 11:21:43 -0800245 self.ints.append((a.RescaleAttributeAddInputZp, input_zp))
246 self.ints.append((a.RescaleAttributeAddOutputZp, output_zp))
247 self.intvecs.append((a.RescaleAttributeAddMultiplier, multiplier))
248 self.intvecs.append((a.RescaleAttributeAddShift, shift))
249 self.bools.append((a.RescaleAttributeAddScale32, scale32))
250 self.bools.append((a.RescaleAttributeAddDoubleRound, double_round))
251 self.bools.append((a.RescaleAttributeAddPerChannel, per_channel))
Eric Kunzee5e26762020-10-13 16:11:07 -0700252
Kevin Chengaee1fac2020-11-11 13:54:06 -0800253 def MulAttribute(self, shift):
254 from tosa import MulAttribute as a, Attribute
255
256 self.utype = Attribute.Attribute().MulAttribute
257 self.optFcns = (a.MulAttributeStart, a.MulAttributeEnd)
258
Kevin Cheng550ccc52021-03-03 11:21:43 -0800259 self.ints.append((a.MulAttributeAddShift, shift))
Kevin Chengaee1fac2020-11-11 13:54:06 -0800260
261 def ArithmeticRightShiftAttribute(self, round):
262 from tosa import ArithmeticRightShiftAttribute as a, Attribute
263
264 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
Kevin Cheng550ccc52021-03-03 11:21:43 -0800265 self.optFcns = (
266 a.ArithmeticRightShiftAttributeStart,
267 a.ArithmeticRightShiftAttributeEnd,
268 )
Kevin Chengaee1fac2020-11-11 13:54:06 -0800269
Kevin Cheng550ccc52021-03-03 11:21:43 -0800270 self.bools.append((a.ArithmeticRightShiftAttributeAddRound, round))
Kevin Chengaee1fac2020-11-11 13:54:06 -0800271
Eric Kunzee5e26762020-10-13 16:11:07 -0700272 def CustomAttribute(self, identifier):
273 from tosa import CustomAttribute as a, Attribute
274
275 self.utype = Attribute.Attribute().CustomAttribute
276 self.optFcns = (a.CustomAttributeStart, a.CustomAttributeEnd)
277
Kevin Cheng550ccc52021-03-03 11:21:43 -0800278 self.strings.append((a.CustomAttributeAddIdentifier, identifier))
Eric Kunzee5e26762020-10-13 16:11:07 -0700279
280 def CondIfAttribute(self, then_branch, else_branch):
281 from tosa import CondIfAttribute as a, Attribute
282
283 self.utype = Attribute.Attribute().CondIfAttribute
284 self.optFcns = (a.CondIfAttributeStart, a.CondIfAttributeEnd)
285
Kevin Cheng550ccc52021-03-03 11:21:43 -0800286 self.strings.append((a.CondIfAttributeAddThenBranch, then_branch))
287 self.strings.append((a.CondIfAttributeAddElseBranch, else_branch))
Eric Kunzee5e26762020-10-13 16:11:07 -0700288
289 def WhileLoopAttribute(self, cond_branch, body_branch):
290 from tosa import WhileLoopAttribute as a, Attribute
291
292 self.utype = Attribute.Attribute().WhileLoopAttribute
293 self.optFcns = (a.WhileLoopAttributeStart, a.WhileLoopAttributeEnd)
294
Kevin Cheng550ccc52021-03-03 11:21:43 -0800295 self.strings.append((a.WhileLoopAttributeAddCondBranch, cond_branch))
296 self.strings.append((a.WhileLoopAttributeAddBodyBranch, body_branch))
297
Eric Kunzee5e26762020-10-13 16:11:07 -0700298
299class TosaSerializerQuantInfo(TosaSerializerUnion):
Kevin Cheng550ccc52021-03-03 11:21:43 -0800300 """This class handles encapsulating all of the enumerated types for quantinfo types"""
301
Eric Kunzee5e26762020-10-13 16:11:07 -0700302 def __init__(self):
303 super().__init__()
304
305 def ConvQuantInfo(self, input_zp, weight_zp):
306 from tosa import ConvQuantInfo as q, QuantInfo
307
308 self.utype = QuantInfo.QuantInfo().ConvQuantInfo
309 self.optFcns = (q.ConvQuantInfoStart, q.ConvQuantInfoEnd)
310 self.ints.append((q.ConvQuantInfoAddInputZp, input_zp))
311 self.ints.append((q.ConvQuantInfoAddWeightZp, weight_zp))
312
313 def UnaryQuantInfo(self, input_zp, output_zp):
314 from tosa import UnaryQuantInfo as q, QuantInfo
315
316 self.utype = QuantInfo.QuantInfo().UnaryQuantInfo
317 self.optFcns = (q.UnaryQuantInfoStart, q.UnaryQuantInfoEnd)
318 self.ints.append((q.UnaryQuantInfoAddInputZp, input_zp))
319 self.ints.append((q.UnaryQuantInfoAddOutputZp, output_zp))
320
321 def MatMulQuantInfo(self, a_zp, b_zp):
322 from tosa import MatMulQuantInfo as q, QuantInfo
323
324 self.utype = QuantInfo.QuantInfo().MatMulQuantInfo
325 self.optFcns = (q.MatMulQuantInfoStart, q.MatMulQuantInfoEnd)
326 self.ints.append((q.MatMulQuantInfoAddAZp, a_zp))
327 self.ints.append((q.MatMulQuantInfoAddBZp, b_zp))
328
329 def PadQuantInfo(self, input_zp):
330 from tosa import PadQuantInfo as q, QuantInfo
331
332 self.utype = QuantInfo.QuantInfo().PadQuantInfo
333 self.optFcns = (q.PadQuantInfoStart, q.PadQuantInfoEnd)
334 self.ints.append((q.PadQuantInfoAddInputZp, input_zp))
335
Kevin Cheng550ccc52021-03-03 11:21:43 -0800336
Eric Kunzee5e26762020-10-13 16:11:07 -0700337class TosaSerializerTensor:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800338 def __init__(
339 self,
340 name,
341 shape,
342 dtype,
Kevin Cheng82507d72021-06-17 16:01:59 -0700343 data=None,
Kevin Cheng550ccc52021-03-03 11:21:43 -0800344 placeholderFilename=None,
345 ):
Eric Kunzee5e26762020-10-13 16:11:07 -0700346 self.name = name
347
348 if isinstance(shape, np.ndarray):
349 shape = shape.astype(int).tolist()
350 shape = list(map(int, shape))
351
352 self.shape = shape
353 self.dtype = dtype
Eric Kunzee5e26762020-10-13 16:11:07 -0700354
Kevin Cheng82507d72021-06-17 16:01:59 -0700355 if isinstance(data, np.ndarray):
356 data = data.flatten().astype(int).tolist()
357 data = list(map(int, data))
358 self.data = data
359 else:
360 self.data = None
Eric Kunzee5e26762020-10-13 16:11:07 -0700361
362 # Filename for placeholder tensors. These get generated by the test generation
363 # process and are written to disk, but are considered input tensors by the network
364 # so they do not appear in the TOSA serialiazation. However, if we want to form a unit
365 # test around these input tensors, we can get the filename from here.
366 self.placeholderFilename = placeholderFilename
367
368 def __str__(self):
Kevin Cheng82507d72021-06-17 16:01:59 -0700369 str = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
Kevin Cheng550ccc52021-03-03 11:21:43 -0800370 self.name,
371 self.shape,
372 DTypeNames[self.dtype],
Kevin Cheng550ccc52021-03-03 11:21:43 -0800373 )
Eric Kunzee5e26762020-10-13 16:11:07 -0700374 return str
375
Eric Kunzee5e26762020-10-13 16:11:07 -0700376 def setDtype(self, dtype):
377 self.dtype = dtype
378
Eric Kunzee5e26762020-10-13 16:11:07 -0700379 def serialize(self, builder):
380 fb_name = builder.CreateString(self.name)
Eric Kunzee5e26762020-10-13 16:11:07 -0700381 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
Kevin Cheng82507d72021-06-17 16:01:59 -0700382 if self.data:
383 u8_data = list()
384 # little endianess
385 if self.dtype == DType.BOOL:
386 for val in self.data:
387 val_u8 = np.uint8(val)
388 u8_data.append(val_u8)
Kevin Chenga9017402021-07-28 17:19:23 -0700389 elif self.dtype == DType.INT4:
390 in_size = len(self.data)
391 out_size = (in_size + 1) // 2
392 for i in range(out_size):
393 val_0 = self.data[2 * i]
394 if (2 * i + 1) < in_size:
395 val_1 = self.data[2 * i + 1]
396 else:
397 val_1 = 0
398 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
399 val_u8 = np.uint8(val_i8)
400 u8_data.append(val_u8)
Kevin Cheng82507d72021-06-17 16:01:59 -0700401 elif self.dtype == DType.INT8:
402 for val in self.data:
403 val_u8 = np.uint8(val)
404 u8_data.append(val_u8)
405 elif self.dtype == DType.INT16:
406 for val in self.data:
407 val_u16 = np.uint16(val)
408 b0 = val_u16 & ByteMask
409 b1 = (val_u16 >> np.uint16(8)) & ByteMask
410 u8_data.extend([b0, b1])
411 elif self.dtype == DType.INT32:
412 for val in self.data:
413 val_u32 = np.uint32(val)
414 b0 = val_u32 & ByteMask
415 b1 = (val_u32 >> np.uint32(8)) & ByteMask
416 b2 = (val_u32 >> np.uint32(16)) & ByteMask
417 b3 = (val_u32 >> np.uint32(32)) & ByteMask
418 u8_data.extend([b0, b1, b2, b3])
419 elif self.dtype == DType.INT48:
420 for val in self.data:
421 val_u64 = np.uint64(val)
422 b0 = val_u64 & ByteMask
423 b1 = (val_u64 >> np.uint64(8)) & ByteMask
424 b2 = (val_u64 >> np.uint64(16)) & ByteMask
425 b3 = (val_u64 >> np.uint64(24)) & ByteMask
426 b4 = (val_u64 >> np.uint64(32)) & ByteMask
427 b5 = (val_u64 >> np.uint64(40)) & ByteMask
428 u8_data.extend([b0, b1, b2, b3, b4, b5])
429 elif self.dtype == DType.FLOAT:
430 for val in self.data:
431 b = struct.pack('!f', val)
432 u8_data.extend([b[3], b[2], b[1], b[0]])
433 else:
434 raise Exception("unsupported data type {}".format(DTypeNames[self.dtype]))
435 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
Eric Kunzee5e26762020-10-13 16:11:07 -0700436
437 TosaTensor.TosaTensorStart(builder)
438 TosaTensor.TosaTensorAddName(builder, fb_name)
439 TosaTensor.TosaTensorAddShape(builder, fb_shapes)
440 TosaTensor.TosaTensorAddType(builder, self.dtype)
Kevin Cheng82507d72021-06-17 16:01:59 -0700441 if self.data:
442 TosaTensor.TosaTensorAddData(builder, fb_data)
Eric Kunzee5e26762020-10-13 16:11:07 -0700443
444 return TosaTensor.TosaTensorEnd(builder)
445
Kevin Cheng550ccc52021-03-03 11:21:43 -0800446
Eric Kunzee5e26762020-10-13 16:11:07 -0700447class TosaSerializerOperator:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800448 def __init__(self, op, inputs, outputs, attributes=None, quantInfo=None):
Eric Kunzee5e26762020-10-13 16:11:07 -0700449 self.op = op
450 self.attributes = attributes
451 self.inputs = TosaSerializer.toList(inputs)
452 self.outputs = TosaSerializer.toList(outputs)
453 self.quantInfo = quantInfo
454
455 def __str__(self):
Kevin Cheng550ccc52021-03-03 11:21:43 -0800456 str = "Op {}\n----\n".format(self.op)
Eric Kunzee5e26762020-10-13 16:11:07 -0700457
458 for i in self.inputs:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800459 str = str + " Input: {}\n".format(i)
Eric Kunzee5e26762020-10-13 16:11:07 -0700460 for o in self.outputs:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800461 str = str + " Output: {}\n".format(o)
Eric Kunzee5e26762020-10-13 16:11:07 -0700462
463 return str
464
465 def serialize(self, builder):
Kevin Cheng550ccc52021-03-03 11:21:43 -0800466 fb_inputs = TosaSerializer.serializeStrVec(
467 builder, self.inputs, TosaOperator.TosaOperatorStartInputsVector
468 )
469 fb_outputs = TosaSerializer.serializeStrVec(
470 builder, self.outputs, TosaOperator.TosaOperatorStartOutputsVector
471 )
Eric Kunzee5e26762020-10-13 16:11:07 -0700472 # Need to serialize quant_info and attributes enums still
473 if self.attributes is not None:
474 fb_attributes = self.attributes.serialize(builder)
475
476 if self.quantInfo is not None:
477 fb_qinfo = self.quantInfo.serialize(builder)
478
479 TosaOperator.TosaOperatorStart(builder)
480 TosaOperator.TosaOperatorAddOp(builder, self.op)
481 TosaOperator.TosaOperatorAddInputs(builder, fb_inputs)
482 TosaOperator.TosaOperatorAddOutputs(builder, fb_outputs)
483 if self.attributes is not None:
484 TosaOperator.TosaOperatorAddAttributeType(builder, self.attributes.utype)
485 TosaOperator.TosaOperatorAddAttribute(builder, fb_attributes)
486 if self.quantInfo is not None:
487 TosaOperator.TosaOperatorAddQuantInfoType(builder, self.quantInfo.utype)
488 TosaOperator.TosaOperatorAddQuantInfo(builder, fb_qinfo)
489
490 return TosaOperator.TosaOperatorEnd(builder)
491
Kevin Cheng550ccc52021-03-03 11:21:43 -0800492
Eric Kunzee5e26762020-10-13 16:11:07 -0700493class TosaSerializerBasicBlock:
494 def __init__(self, name):
495 self.name = name
496 self.operators = []
497
498 # Dict assures uniqueness, but allows us to look up by name
499 self.tensors = dict()
500
501 self.inputs = []
502 self.outputs = []
503
Kevin Cheng550ccc52021-03-03 11:21:43 -0800504 def addTensor(
505 self,
506 name,
507 shape,
508 dtype,
Kevin Cheng82507d72021-06-17 16:01:59 -0700509 data=None,
Kevin Cheng550ccc52021-03-03 11:21:43 -0800510 placeholderFilename=None,
511 ):
Eric Kunzee5e26762020-10-13 16:11:07 -0700512 try:
513 # Someone already added this tensor.
Eric Kunzee5e26762020-10-13 16:11:07 -0700514 tens = self.tensors[name]
Eric Kunzee5e26762020-10-13 16:11:07 -0700515 except KeyError:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800516 self.tensors[name] = TosaSerializerTensor(
Kevin Cheng82507d72021-06-17 16:01:59 -0700517 name, shape, dtype, data, placeholderFilename
Kevin Cheng550ccc52021-03-03 11:21:43 -0800518 )
Eric Kunzee5e26762020-10-13 16:11:07 -0700519
520 return self.tensors[name]
521
522 def addInput(self, name):
523 self.inputs.append(name)
524
525 def addOutput(self, name):
526 self.outputs.append(name)
527
Kevin Cheng550ccc52021-03-03 11:21:43 -0800528 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
529 self.operators.append(
530 TosaSerializerOperator(op, inputs, outputs, attributes, quant_info)
531 )
Eric Kunzee5e26762020-10-13 16:11:07 -0700532
533 def serialize(self, builder):
534 fb_name = builder.CreateString(self.name)
Kevin Cheng550ccc52021-03-03 11:21:43 -0800535 fbv_inputs = TosaSerializer.serializeStrVec(
536 builder, list(self.inputs), TosaBasicBlock.TosaBasicBlockStartInputsVector
537 )
538 fbv_outputs = TosaSerializer.serializeStrVec(
539 builder, list(self.outputs), TosaBasicBlock.TosaBasicBlockStartOutputsVector
540 )
541 fbv_tensors = TosaSerializer.serializeObjVec(
542 builder,
543 list(self.tensors.values()),
544 TosaBasicBlock.TosaBasicBlockStartTensorsVector,
545 )
546 fbv_operators = TosaSerializer.serializeObjVec(
547 builder, self.operators, TosaBasicBlock.TosaBasicBlockStartOperatorsVector
548 )
Eric Kunzee5e26762020-10-13 16:11:07 -0700549
550 TosaBasicBlock.TosaBasicBlockStart(builder)
551 TosaBasicBlock.TosaBasicBlockAddName(builder, fb_name)
552 TosaBasicBlock.TosaBasicBlockAddInputs(builder, fbv_inputs)
553 TosaBasicBlock.TosaBasicBlockAddOutputs(builder, fbv_outputs)
554 TosaBasicBlock.TosaBasicBlockAddTensors(builder, fbv_tensors)
555 TosaBasicBlock.TosaBasicBlockAddOperators(builder, fbv_operators)
556 return TosaBasicBlock.TosaBasicBlockEnd(builder)
557
Kevin Cheng550ccc52021-03-03 11:21:43 -0800558
Eric Kunzee5e26762020-10-13 16:11:07 -0700559@unique
560class TensorDir(IntEnum):
561 PLACEHOLDER = 0
562 CONST = 1
563 INTERMEDIATE = 2
564 RESULT = 3
565
Kevin Cheng550ccc52021-03-03 11:21:43 -0800566
Eric Kunzee5e26762020-10-13 16:11:07 -0700567class TosaSerializer:
568 def __init__(self, pathPrefix):
569
570 # Get the global TOSA version if not already defined
571 try:
572 TOSA_VERSION
573 except NameError:
574 TosaSerializer.setTosaVersion()
575
576 self.builder = flatbuffers.Builder(0)
577
578 self.basicBlocks = []
Kevin Cheng550ccc52021-03-03 11:21:43 -0800579 self.startBasicBlock("main")
Eric Kunzee5e26762020-10-13 16:11:07 -0700580 self.pathPrefix = pathPrefix
581
582 # Indicies used for adding/naming tensors
583 self.currInputIdx = 0
584 self.currConstIdx = 0
585 self.currLayerIdx = 1
586 self.currResultIdx = 0
587
588 # Is this an illegal test that is expected to fail?
589 self.expectedFailure = False
Kevin Cheng550ccc52021-03-03 11:21:43 -0800590 self.expectedFailureDesc = ""
Eric Kunzee5e26762020-10-13 16:11:07 -0700591
592 def __str__(self):
Kevin Cheng550ccc52021-03-03 11:21:43 -0800593 str = ""
Eric Kunzee5e26762020-10-13 16:11:07 -0700594 for bb in self.basicBlocks:
595 str = str + bb.__str__()
596 return str
597
Kevin Cheng550ccc52021-03-03 11:21:43 -0800598 def addPlaceholder(self, shape, dtype, vals):
Eric Kunzee5e26762020-10-13 16:11:07 -0700599 if not self.currBasicBlock:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800600 raise Exception("addTensor called without valid basic block")
Eric Kunzee5e26762020-10-13 16:11:07 -0700601
Kevin Cheng550ccc52021-03-03 11:21:43 -0800602 name = "input-{}".format(self.currInputIdx)
603 filename = "{}.npy".format(name)
Eric Kunzee5e26762020-10-13 16:11:07 -0700604 self.currInputIdx = self.currInputIdx + 1
605
Kevin Cheng550ccc52021-03-03 11:21:43 -0800606 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
Eric Kunzee5e26762020-10-13 16:11:07 -0700607 # This is always an input to the block
608 self.currBasicBlock.addInput(name)
Eric Kunzee5e26762020-10-13 16:11:07 -0700609
610 if vals is not None:
611 np.save(os.path.join(self.pathPrefix, filename), vals, False)
612
613 return tens
614
Kevin Cheng550ccc52021-03-03 11:21:43 -0800615 def addConst(self, shape, dtype, vals):
Eric Kunzee5e26762020-10-13 16:11:07 -0700616 if not self.currBasicBlock:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800617 raise Exception("addTensor called without valid basic block")
Eric Kunzee5e26762020-10-13 16:11:07 -0700618
Kevin Cheng550ccc52021-03-03 11:21:43 -0800619 name = "const-{}".format(self.currInputIdx)
620 filename = "{}.npy".format(name)
Eric Kunzee5e26762020-10-13 16:11:07 -0700621 self.currInputIdx = self.currInputIdx + 1
622
Kevin Cheng82507d72021-06-17 16:01:59 -0700623 tens = self.currBasicBlock.addTensor(name, shape, dtype, vals)
Eric Kunzee5e26762020-10-13 16:11:07 -0700624 # Add the operator now
625 self.currBasicBlock.addOperator(tosa.Op.Op().CONST, [], name)
626
Eric Kunzee5e26762020-10-13 16:11:07 -0700627 return tens
628
Kevin Cheng550ccc52021-03-03 11:21:43 -0800629 def addIntermediate(self, shape, dtype):
Eric Kunzee5e26762020-10-13 16:11:07 -0700630
631 if not self.currBasicBlock:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800632 raise Exception("addTensor called without valid basic block")
Eric Kunzee5e26762020-10-13 16:11:07 -0700633
Kevin Cheng550ccc52021-03-03 11:21:43 -0800634 name = "layer-{}".format(self.currLayerIdx)
Eric Kunzee5e26762020-10-13 16:11:07 -0700635 self.currLayerIdx = self.currLayerIdx + 1
636
Kevin Cheng82507d72021-06-17 16:01:59 -0700637 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
Eric Kunzee5e26762020-10-13 16:11:07 -0700638
639 return tens
640
641 def addInputTensor(self, tensor):
Kevin Cheng550ccc52021-03-03 11:21:43 -0800642 self.currBasicBlock.addTensor(tensor.name, tensor.shape, tensor.dtype)
Eric Kunzee5e26762020-10-13 16:11:07 -0700643 self.currBasicBlock.addInput(tensor.name)
644
645 def addOutputTensor(self, tensor):
646 self.currBasicBlock.addOutput(tensor.name)
647
Kevin Cheng550ccc52021-03-03 11:21:43 -0800648 def addOutput(self, shape, dtype):
Eric Kunzee5e26762020-10-13 16:11:07 -0700649 if not self.currBasicBlock:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800650 raise Exception("addTensor called without valid basic block")
Eric Kunzee5e26762020-10-13 16:11:07 -0700651
Kevin Cheng550ccc52021-03-03 11:21:43 -0800652 name = "result-{}".format(self.currResultIdx)
Eric Kunzee5e26762020-10-13 16:11:07 -0700653 self.currResultIdx = self.currResultIdx + 1
654
Kevin Cheng550ccc52021-03-03 11:21:43 -0800655 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
Eric Kunzee5e26762020-10-13 16:11:07 -0700656 self.currBasicBlock.addOutput(name)
657 return tens
658
Kevin Cheng550ccc52021-03-03 11:21:43 -0800659 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
Eric Kunzee5e26762020-10-13 16:11:07 -0700660
Kevin Cheng14d7f7a2021-05-12 10:44:49 -0700661 if op == tosa.Op.Op().CONST:
662 raise Exception("Use addConstTensor() to add CONST ops")
Eric Kunzee5e26762020-10-13 16:11:07 -0700663
Kevin Cheng550ccc52021-03-03 11:21:43 -0800664 return self.currBasicBlock.addOperator(
665 op, inputs, outputs, attributes, quant_info
666 )
Eric Kunzee5e26762020-10-13 16:11:07 -0700667
Kevin Cheng550ccc52021-03-03 11:21:43 -0800668 def setExpectedFailure(self, desc="", val=True):
Eric Kunzee5e26762020-10-13 16:11:07 -0700669
Eric Kunzee5e26762020-10-13 16:11:07 -0700670 self.expectedFailure = val
671 self.expectedFailureDesc = desc
672
673 def serialize(self):
674
675 builder = self.builder
676
677 Version.VersionStart(builder)
678 Version.VersionAdd_major(builder, TOSA_VERSION[0])
679 Version.VersionAdd_minor(builder, TOSA_VERSION[1])
680 Version.VersionAdd_patch(builder, TOSA_VERSION[2])
681 Version.VersionAdd_experimental(builder, TOSA_VERSION[3])
682 version = Version.VersionEnd(builder)
683
Kevin Cheng550ccc52021-03-03 11:21:43 -0800684 fbv_bb = TosaSerializer.serializeObjVec(
685 builder, self.basicBlocks, TosaGraph.TosaGraphStartBlocksVector
686 )
Eric Kunzee5e26762020-10-13 16:11:07 -0700687
688 TosaGraph.TosaGraphStart(builder)
689 TosaGraph.TosaGraphAddVersion(builder, version)
690 TosaGraph.TosaGraphAddBlocks(builder, fbv_bb)
691 graph = TosaGraph.TosaGraphEnd(builder)
692
693 self.builder.Finish(graph)
694 return self.builder.Output()
695
696 def writeJson(self, tosa_filename):
Kevin Cheng550ccc52021-03-03 11:21:43 -0800697 """Write a json test file so that it is fairly easy to pick up the test
698 and generate commands for third party tool"""
Eric Kunzee5e26762020-10-13 16:11:07 -0700699 test_desc = dict()
700
Kevin Cheng550ccc52021-03-03 11:21:43 -0800701 test_desc["tosa_file"] = tosa_filename
Eric Kunzee5e26762020-10-13 16:11:07 -0700702 ifm_name = []
Eric Kunzee5e26762020-10-13 16:11:07 -0700703 ifm_file = []
704 ofm_name = []
705 ofm_file = []
Eric Kunzee5e26762020-10-13 16:11:07 -0700706
707 for b in self.basicBlocks:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800708 if b.name == "main":
Eric Kunzee5e26762020-10-13 16:11:07 -0700709 for i in b.inputs:
710 ifm_name.append(i)
Eric Kunzee5e26762020-10-13 16:11:07 -0700711 ifm_file.append(b.tensors[i].placeholderFilename)
712 for o in b.outputs:
713 ofm_name.append(o)
Eric Kunzee5e26762020-10-13 16:11:07 -0700714 # Make up an OFM filename here. One isn't generated until the reference tool is
715 # run, so any name is a good name
Kevin Cheng550ccc52021-03-03 11:21:43 -0800716 ofm_file.append("ref-{}.npy".format(o))
Eric Kunzee5e26762020-10-13 16:11:07 -0700717
Kevin Chengcd79f0e2021-06-03 15:00:34 -0700718 test_desc["ifm_name"] = ifm_name
Kevin Cheng550ccc52021-03-03 11:21:43 -0800719 test_desc["ifm_file"] = ifm_file
Kevin Cheng550ccc52021-03-03 11:21:43 -0800720 test_desc["ofm_name"] = ofm_name
Kevin Cheng550ccc52021-03-03 11:21:43 -0800721 test_desc["ofm_file"] = ofm_file
722 test_desc["expected_failure"] = self.expectedFailure
Eric Kunzee5e26762020-10-13 16:11:07 -0700723 if self.expectedFailureDesc:
Kevin Cheng550ccc52021-03-03 11:21:43 -0800724 test_desc["expected_failure_desc"] = self.expectedFailureDesc
Eric Kunzee5e26762020-10-13 16:11:07 -0700725
Kevin Cheng550ccc52021-03-03 11:21:43 -0800726 return json.dumps(test_desc, indent=" ")
Eric Kunzee5e26762020-10-13 16:11:07 -0700727
728 def startBasicBlock(self, name):
729 self.currBasicBlock = TosaSerializerBasicBlock(name)
730 self.basicBlocks.append(self.currBasicBlock)
731
732 @staticmethod
733 def serializeStrVec(builder, vec, start_fcn):
734 fb_strs = [builder.CreateString(i) for i in vec]
735 start_fcn(builder, len(fb_strs))
736 for s in fb_strs[::-1]:
737 builder.PrependUOffsetTRelative(s)
738 return builder.EndVector(len(fb_strs))
739
740 @staticmethod
Kevin Cheng82507d72021-06-17 16:01:59 -0700741 def serializeUint8Vec(builder, vec):
742 builder.StartVector(1, len(vec), 8)
743 for v in vec[::-1]:
744 builder.PrependUint8(v)
745 return builder.EndVector(len(vec))
746
747 @staticmethod
Eric Kunzee5e26762020-10-13 16:11:07 -0700748 def serializeInt32Vec(builder, vec):
749 builder.StartVector(4, len(vec), 4)
750 for v in vec[::-1]:
751 builder.PrependInt32(v)
752 return builder.EndVector(len(vec))
753
754 @staticmethod
Kevin Cheng77d0f762020-11-24 10:26:32 -0800755 def serializeFpVec(builder, vec):
756 builder.StartVector(4, len(vec), 4)
757 for v in vec[::-1]:
758 builder.PrependFloat32(v)
759 return builder.EndVector(len(vec))
760
761 @staticmethod
Eric Kunzee5e26762020-10-13 16:11:07 -0700762 def serializeObjVec(builder, vec, start_fcn):
763 serialized_vec = []
764 for v in vec[::-1]:
765 serialized_vec.append(v.serialize(builder))
766
767 start_fcn(builder, len(vec))
768 for v in serialized_vec:
769 builder.PrependUOffsetTRelative(v)
770 return builder.EndVector(len(vec))
771
772 @staticmethod
773 def toList(val):
774 if isinstance(val, list):
775 return val
776 else:
777 return [val]
778
779 @staticmethod
780 def setTosaVersion():
781 # Create a dummy flatbuffers file with the default version information
782 # There does not appear to be a better way to get a constant from a
783 # flatbuffer schema file
784 builder = flatbuffers.Builder(0)
785 Version.VersionStart(builder)
786 ver = Version.VersionEnd(builder)
787 TosaGraph.TosaGraphStart(builder)
788 TosaGraph.TosaGraphAddVersion(builder, ver)
789 gr = TosaGraph.TosaGraphEnd(builder)
790 builder.Finish(gr)
791
792 out = builder.Output()
793
794 gr = TosaGraph.TosaGraph()
795 root = gr.GetRootAsTosaGraph(out, 0)
796
797 # Store the version as a global variable so that it only needs to be
798 # generated once per process.
799 global TOSA_VERSION
Kevin Cheng550ccc52021-03-03 11:21:43 -0800800 TOSA_VERSION = [
801 root.Version()._major(),
802 root.Version()._minor(),
803 root.Version()._patch(),
804 root.Version()._experimental(),
805 ]