blob: acec4b76bdf5381f766be07d3757bb6ad8943947 [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 Kunze24a68bb2022-09-08 23:54:21 +000033TOSA_VERSION_MINOR = 41
Kevin Chengb97cb1d2021-10-14 11:53:39 -070034TOSA_VERSION_PATCH = 0
Eric Kunze24a68bb2022-09-08 23:54:21 +000035TOSA_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]
Eric Kunzee6596402022-06-09 21:27:36 +000042
43# File identifier needs to be kept in sync with schema/tosa.fbs
44TOSA_GRAPH_IDENTIFIER = b"\x54\x4F\x53\x41"
45
Kevin Chengfea5a372021-10-11 18:38:47 +000046# With the way flatc generates its python types, there is no programatic way
47# to get string names for the integer types. Manually maintain a string table
48# here.
Jeremy Johnson9b225172021-12-14 16:34:47 +000049DType = TosaDType.DType()
Kevin Chengfea5a372021-10-11 18:38:47 +000050DTypeNames = [
51 "UNKNOWN",
52 "BOOL",
53 "UINT8",
54 "INT4",
55 "INT8",
56 "INT16",
57 "INT32",
58 "INT48",
59 "FLOAT",
Jeremy Johnson41027732022-05-25 17:52:29 +010060 "UINT16",
Kevin Chengfea5a372021-10-11 18:38:47 +000061]
62
63ByteMask = np.uint64(0xFF)
64
65
66def dtype_str_to_val(name):
67
68 for i in range(len(DTypeNames)):
69 if name.casefold() == DTypeNames[i].casefold():
70 return i
71 raise Exception("Unable to parse DType name {}".format(name))
72
73
74class TosaSerializerUnion:
75 """This class handles encapsulating and serializing union types into flatbuffers"""
76
77 def __init__(self):
78
Jeremy Johnson9b225172021-12-14 16:34:47 +000079 # A tuple of the start and end functions.
80 # Set by the options constructors below
Kevin Chengfea5a372021-10-11 18:38:47 +000081 self.optFcns = None
82
Jeremy Johnson9b225172021-12-14 16:34:47 +000083 # The type from the tosa.Options enumeration.
84 # Set by the options constructors below.
Kevin Chengfea5a372021-10-11 18:38:47 +000085 self.utype = None
86
87 # Each of these lists is a tuple of the add function and the
88 # value being added. Set by the options constructors below.
89 self.ints = []
90 self.bools = []
91 self.floats = []
92 self.strings = []
TatWai Chong49b1ca62022-06-10 01:49:13 -070093 self.int16vecs = []
Kevin Chengfea5a372021-10-11 18:38:47 +000094 self.intvecs = []
95 self.fpvecs = []
96
97 def serialize(self, builder):
98
99 # We have to build strings and vectors first
100 strList = []
101 intVecList = []
102 fpVecList = []
103
104 for fcn, val in self.strings:
105 strList.append((fcn, builder.CreateString(val)))
106
107 for fcn, val in self.intvecs:
108 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
109
TatWai Chong49b1ca62022-06-10 01:49:13 -0700110 for fcn, val in self.int16vecs:
111 intVecList.append((fcn, TosaSerializer.serializeInt16Vec(builder, val)))
112
Kevin Chengfea5a372021-10-11 18:38:47 +0000113 for fcn, val in self.fpvecs:
114 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
115
116 startFcn, endFcn = self.optFcns
117
118 # Then serialize the options object from the list of primitives and
119 # other serialized values
120 startFcn(builder)
121 for fcn, val in self.ints:
122 fcn(builder, val)
123
124 for fcn, val in self.bools:
125 fcn(builder, val)
126
127 for fcn, val in self.floats:
128 fcn(builder, val)
129
130 for fcn, val in strList:
131 fcn(builder, val)
132
133 for fcn, val in intVecList:
134 fcn(builder, val)
135
136 for fcn, val in fpVecList:
137 fcn(builder, val)
138
139 return endFcn(builder)
140
141
142class TosaSerializerAttribute(TosaSerializerUnion):
143 """This class handles encapsulating all of the enumerated types for attributes"""
144
145 def __init__(self):
146 super().__init__()
147
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000148 def PoolAttribute(self, kernel, stride, pad, input_zp, output_zp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000149 from tosa import PoolAttribute as a, Attribute
150
151 self.utype = Attribute.Attribute().PoolAttribute
152
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800153 self.optFcns = (a.Start, a.End)
TatWai Chong7be71652022-05-10 17:26:20 -0700154 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800155 self.intvecs.append((a.AddKernel, kernel))
156 self.intvecs.append((a.AddStride, stride))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000157 self.ints.append((a.AddInputZp, input_zp))
158 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000159
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000160 def ConvAttribute(self, pad, stride, dilation, input_zp, weight_zp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000161 from tosa import ConvAttribute as a, Attribute
162
163 self.utype = Attribute.Attribute().ConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800164 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000165
TatWai Chong7be71652022-05-10 17:26:20 -0700166 self.intvecs.append((a.AddPad, pad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800167 self.intvecs.append((a.AddStride, stride))
168 self.intvecs.append((a.AddDilation, dilation))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000169 self.ints.append((a.AddInputZp, input_zp))
170 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000171
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000172 def TransposeConvAttribute(self, outpad, stride, output_shape, input_zp, weight_zp):
Kevin Chengfea5a372021-10-11 18:38:47 +0000173 from tosa import TransposeConvAttribute as a, Attribute
174
175 self.utype = Attribute.Attribute().TransposeConvAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800176 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000177
Eric Kunze4c3537d2022-06-13 17:21:48 -0700178 self.intvecs.append((a.AddOutPad, outpad))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800179 self.intvecs.append((a.AddStride, stride))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800180 self.intvecs.append((a.AddOutputShape, output_shape))
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000181 self.ints.append((a.AddInputZp, input_zp))
182 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000183
Kevin Cheng38d214c2021-10-15 15:49:19 -0700184 def PadAttribute(self, padding, pad_const_int, pad_const_fp):
185 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000186
Kevin Cheng38d214c2021-10-15 15:49:19 -0700187 self.utype = Attribute.Attribute().PadAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800188 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000189
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800190 self.intvecs.append((a.AddPadding, padding))
191 self.ints.append((a.AddPadConstInt, pad_const_int))
192 self.floats.append((a.AddPadConstFp, pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000193
194 def AxisAttribute(self, axis):
195 from tosa import AxisAttribute as a, Attribute
196
197 self.utype = Attribute.Attribute().AxisAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800198 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000199
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800200 self.ints.append((a.AddAxis, axis))
Kevin Chengfea5a372021-10-11 18:38:47 +0000201
TatWai Chong7be71652022-05-10 17:26:20 -0700202 def ReshapeAttribute(self, new_shape):
Kevin Chengfea5a372021-10-11 18:38:47 +0000203 from tosa import ReshapeAttribute as a, Attribute
204
205 self.utype = Attribute.Attribute().ReshapeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800206 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000207
TatWai Chong7be71652022-05-10 17:26:20 -0700208 self.intvecs.append((a.AddNewShape, new_shape))
Kevin Chengfea5a372021-10-11 18:38:47 +0000209
TatWai Chong7be71652022-05-10 17:26:20 -0700210 def SliceAttribute(self, start, size):
Kevin Chengfea5a372021-10-11 18:38:47 +0000211 from tosa import SliceAttribute as a, Attribute
212
213 self.utype = Attribute.Attribute().SliceAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800214 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000215
TatWai Chong7be71652022-05-10 17:26:20 -0700216 self.intvecs.append((a.AddStart, start))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800217 self.intvecs.append((a.AddSize, size))
Kevin Chengfea5a372021-10-11 18:38:47 +0000218
219 def TileAttribute(self, multiples):
220 from tosa import TileAttribute as a, Attribute
221
222 self.utype = Attribute.Attribute().TileAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800223 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000224
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800225 self.intvecs.append((a.AddMultiples, multiples))
Kevin Chengfea5a372021-10-11 18:38:47 +0000226
TatWai Chong49b1ca62022-06-10 01:49:13 -0700227 def ResizeAttribute(self, scale, offset, border, mode):
Kevin Chengfea5a372021-10-11 18:38:47 +0000228 from tosa import ResizeAttribute as a, Attribute
229
230 self.utype = Attribute.Attribute().ResizeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800231 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000232
TatWai Chong49b1ca62022-06-10 01:49:13 -0700233 self.int16vecs.append((a.AddScale, scale))
234 self.int16vecs.append((a.AddOffset, offset))
235 self.int16vecs.append((a.AddBorder, border))
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800236 self.ints.append((a.AddMode, mode))
Kevin Chengfea5a372021-10-11 18:38:47 +0000237
238 def ClampAttribute(self, minint, maxint, minfp, maxfp):
239 from tosa import ClampAttribute as a, Attribute
240
241 self.utype = Attribute.Attribute().ClampAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800242 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000243
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800244 self.ints.append((a.AddMinInt, minint))
245 self.ints.append((a.AddMaxInt, maxint))
Kevin Chengfea5a372021-10-11 18:38:47 +0000246
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800247 self.ints.append((a.AddMinFp, minfp))
248 self.ints.append((a.AddMaxFp, maxfp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000249
250 def RescaleAttribute(
251 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
252 ):
253 from tosa import RescaleAttribute as a, Attribute
254
255 self.utype = Attribute.Attribute().RescaleAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800256 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000257
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800258 self.ints.append((a.AddInputZp, input_zp))
259 self.ints.append((a.AddOutputZp, output_zp))
260 self.intvecs.append((a.AddMultiplier, multiplier))
261 self.intvecs.append((a.AddShift, shift))
262 self.bools.append((a.AddScale32, scale32))
263 self.bools.append((a.AddDoubleRound, double_round))
264 self.bools.append((a.AddPerChannel, per_channel))
Kevin Chengfea5a372021-10-11 18:38:47 +0000265
266 def MulAttribute(self, shift):
267 from tosa import MulAttribute as a, Attribute
268
269 self.utype = Attribute.Attribute().MulAttribute
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.AddShift, shift))
Kevin Chengfea5a372021-10-11 18:38:47 +0000273
274 def ArithmeticRightShiftAttribute(self, round):
275 from tosa import ArithmeticRightShiftAttribute as a, Attribute
276
277 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
278 self.optFcns = (
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800279 a.Start,
280 a.End,
Kevin Chengfea5a372021-10-11 18:38:47 +0000281 )
282
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800283 self.bools.append((a.AddRound, round))
Kevin Chengfea5a372021-10-11 18:38:47 +0000284
Kevin Chengfea5a372021-10-11 18:38:47 +0000285 def CondIfAttribute(self, then_branch, else_branch):
286 from tosa import CondIfAttribute as a, Attribute
287
288 self.utype = Attribute.Attribute().CondIfAttribute
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.AddThenBranch, then_branch))
292 self.strings.append((a.AddElseBranch, else_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000293
294 def WhileLoopAttribute(self, cond_branch, body_branch):
295 from tosa import WhileLoopAttribute as a, Attribute
296
297 self.utype = Attribute.Attribute().WhileLoopAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800298 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000299
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800300 self.strings.append((a.AddCondBranch, cond_branch))
301 self.strings.append((a.AddBodyBranch, body_branch))
Kevin Chengfea5a372021-10-11 18:38:47 +0000302
TatWai Chong7be71652022-05-10 17:26:20 -0700303 def TransposeAttribute(self, perms):
Kevin Cheng38d214c2021-10-15 15:49:19 -0700304 from tosa import TransposeAttribute as a, Attribute
305
306 self.utype = Attribute.Attribute().TransposeAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800307 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700308
TatWai Chong7be71652022-05-10 17:26:20 -0700309 self.intvecs.append((a.AddPerms, perms))
Kevin Cheng38d214c2021-10-15 15:49:19 -0700310
311 def TableAttribute(self, table):
312 from tosa import TableAttribute as a, Attribute
313
314 self.utype = Attribute.Attribute().TableAttribute
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800315 self.optFcns = (a.Start, a.End)
Kevin Cheng38d214c2021-10-15 15:49:19 -0700316
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800317 self.intvecs.append((a.AddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000318
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000319 def MatMulAttribute(self, A_zp, B_zp):
320 from tosa import MatMulAttribute as a, Attribute
Jeremy Johnson9b225172021-12-14 16:34:47 +0000321
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000322 self.utype = Attribute.Attribute().MatMulAttribute
323 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000324
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000325 self.ints.append((a.AddAZp, A_zp))
326 self.ints.append((a.AddBZp, B_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000327
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000328 def FullyConnectedAttribute(self, input_zp, weight_zp):
329 from tosa import FullyConnectedAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000330
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000331 self.utype = Attribute.Attribute().FullyConnectedAttribute
332 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000333
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000334 self.ints.append((a.AddInputZp, input_zp))
335 self.ints.append((a.AddWeightZp, weight_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000336
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000337 def NegateAttribute(self, input1_zp, output_zp):
338 from tosa import NegateAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000339
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000340 self.utype = Attribute.Attribute().NegateAttribute
341 self.optFcns = (a.Start, a.End)
Kevin Chengfea5a372021-10-11 18:38:47 +0000342
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000343 self.ints.append((a.AddInput1Zp, input1_zp))
344 self.ints.append((a.AddOutputZp, output_zp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000345
346
347class TosaSerializerTensor:
348 def __init__(
349 self,
350 name,
351 shape,
352 dtype,
353 data=None,
354 placeholderFilename=None,
355 ):
356 self.name = name
357
358 if isinstance(shape, np.ndarray):
359 shape = shape.astype(int).tolist()
360 shape = list(map(int, shape))
361
362 self.shape = shape
363 self.dtype = dtype
364
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100365 if dtype == DType.FLOAT:
366 fntype = np.float32
367 else:
368 fntype = int
369
Kevin Chengfea5a372021-10-11 18:38:47 +0000370 if isinstance(data, np.ndarray):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100371 data = data.flatten().astype(fntype).tolist()
372 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000373 self.data = data
374 elif isinstance(data, list):
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100375 data = list(map(fntype, data))
Kevin Chengfea5a372021-10-11 18:38:47 +0000376 self.data = data
377 else:
378 self.data = None
379
380 # Filename for placeholder tensors. These get generated by the test generation
Jeremy Johnson9b225172021-12-14 16:34:47 +0000381 # process and are written to disk, but are considered input tensors by the
382 # network so they do not appear in the TOSA serialiazation. However, if we
383 # want to form a unit test around these input tensors, we can get the filename
384 # from here.
Kevin Chengfea5a372021-10-11 18:38:47 +0000385 self.placeholderFilename = placeholderFilename
386
387 def __str__(self):
388 str = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
389 self.name,
390 self.shape,
391 DTypeNames[self.dtype],
392 )
393 return str
394
395 def setDtype(self, dtype):
396 self.dtype = dtype
397
398 def serialize(self, builder):
399 fb_name = builder.CreateString(self.name)
400 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
401 if self.data:
402 u8_data = list()
403 # little endianess
404 if self.dtype == DType.BOOL:
405 for val in self.data:
406 val_u8 = np.uint8(val)
407 u8_data.append(val_u8)
408 elif self.dtype == DType.INT4:
409 in_size = len(self.data)
410 out_size = (in_size + 1) // 2
411 for i in range(out_size):
412 val_0 = self.data[2 * i]
413 if (2 * i + 1) < in_size:
414 val_1 = self.data[2 * i + 1]
415 else:
416 val_1 = 0
417 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
418 val_u8 = np.uint8(val_i8)
419 u8_data.append(val_u8)
420 elif self.dtype == DType.INT8:
421 for val in self.data:
422 val_u8 = np.uint8(val)
423 u8_data.append(val_u8)
424 elif self.dtype == DType.INT16:
425 for val in self.data:
426 val_u16 = np.uint16(val)
427 b0 = val_u16 & ByteMask
428 b1 = (val_u16 >> np.uint16(8)) & ByteMask
429 u8_data.extend([b0, b1])
430 elif self.dtype == DType.INT32:
431 for val in self.data:
432 val_u32 = np.uint32(val)
433 b0 = val_u32 & ByteMask
434 b1 = (val_u32 >> np.uint32(8)) & ByteMask
435 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700436 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000437 u8_data.extend([b0, b1, b2, b3])
438 elif self.dtype == DType.INT48:
439 for val in self.data:
440 val_u64 = np.uint64(val)
441 b0 = val_u64 & ByteMask
442 b1 = (val_u64 >> np.uint64(8)) & ByteMask
443 b2 = (val_u64 >> np.uint64(16)) & ByteMask
444 b3 = (val_u64 >> np.uint64(24)) & ByteMask
445 b4 = (val_u64 >> np.uint64(32)) & ByteMask
446 b5 = (val_u64 >> np.uint64(40)) & ByteMask
447 u8_data.extend([b0, b1, b2, b3, b4, b5])
448 elif self.dtype == DType.FLOAT:
449 for val in self.data:
450 b = struct.pack("!f", val)
451 u8_data.extend([b[3], b[2], b[1], b[0]])
452 else:
453 raise Exception(
454 "unsupported data type {}".format(DTypeNames[self.dtype])
455 )
456 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
457
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800458 TosaTensor.Start(builder)
459 TosaTensor.AddName(builder, fb_name)
460 TosaTensor.AddShape(builder, fb_shapes)
461 TosaTensor.AddType(builder, self.dtype)
Kevin Chengfea5a372021-10-11 18:38:47 +0000462 if self.data:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800463 TosaTensor.AddData(builder, fb_data)
Kevin Chengfea5a372021-10-11 18:38:47 +0000464
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800465 return TosaTensor.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000466
467
468class TosaSerializerOperator:
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000469 def __init__(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000470 self.op = op
471 self.attributes = attributes
472 self.inputs = TosaSerializer.toList(inputs)
473 self.outputs = TosaSerializer.toList(outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000474
475 def __str__(self):
476 str = "Op {}\n----\n".format(self.op)
477
478 for i in self.inputs:
479 str = str + " Input: {}\n".format(i)
480 for o in self.outputs:
481 str = str + " Output: {}\n".format(o)
482
483 return str
484
485 def serialize(self, builder):
486 fb_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800487 builder, self.inputs, TosaOperator.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000488 )
489 fb_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800490 builder, self.outputs, TosaOperator.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000491 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000492 # Need to serialize attributes enums still
Kevin Chengfea5a372021-10-11 18:38:47 +0000493 if self.attributes is not None:
494 fb_attributes = self.attributes.serialize(builder)
495
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800496 TosaOperator.Start(builder)
497 TosaOperator.AddOp(builder, self.op)
498 TosaOperator.AddInputs(builder, fb_inputs)
499 TosaOperator.AddOutputs(builder, fb_outputs)
Kevin Chengfea5a372021-10-11 18:38:47 +0000500 if self.attributes is not None:
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800501 TosaOperator.AddAttributeType(builder, self.attributes.utype)
502 TosaOperator.AddAttribute(builder, fb_attributes)
Kevin Chengfea5a372021-10-11 18:38:47 +0000503
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800504 return TosaOperator.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000505
506
507class TosaSerializerBasicBlock:
508 def __init__(self, name):
509 self.name = name
510 self.operators = []
511
512 # Dict assures uniqueness, but allows us to look up by name
513 self.tensors = dict()
514
515 self.inputs = []
516 self.outputs = []
517
518 def addTensor(
519 self,
520 name,
521 shape,
522 dtype,
523 data=None,
524 placeholderFilename=None,
525 ):
Jeremy Johnson9b225172021-12-14 16:34:47 +0000526 if name not in self.tensors:
Kevin Chengfea5a372021-10-11 18:38:47 +0000527 self.tensors[name] = TosaSerializerTensor(
528 name, shape, dtype, data, placeholderFilename
529 )
530
531 return self.tensors[name]
532
533 def addInput(self, name):
534 self.inputs.append(name)
535
536 def addOutput(self, name):
537 self.outputs.append(name)
538
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000539 def addOperator(self, op, inputs, outputs, attributes=None):
540 self.operators.append(TosaSerializerOperator(op, inputs, outputs, attributes))
Kevin Chengfea5a372021-10-11 18:38:47 +0000541
542 def serialize(self, builder):
543 fb_name = builder.CreateString(self.name)
544 fbv_inputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800545 builder, list(self.inputs), TosaBasicBlock.StartInputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000546 )
547 fbv_outputs = TosaSerializer.serializeStrVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800548 builder, list(self.outputs), TosaBasicBlock.StartOutputsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000549 )
550 fbv_tensors = TosaSerializer.serializeObjVec(
551 builder,
552 list(self.tensors.values()),
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800553 TosaBasicBlock.StartTensorsVector,
Kevin Chengfea5a372021-10-11 18:38:47 +0000554 )
555 fbv_operators = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800556 builder, self.operators, TosaBasicBlock.StartOperatorsVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000557 )
558
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800559 TosaBasicBlock.Start(builder)
560 TosaBasicBlock.AddName(builder, fb_name)
561 TosaBasicBlock.AddInputs(builder, fbv_inputs)
562 TosaBasicBlock.AddOutputs(builder, fbv_outputs)
563 TosaBasicBlock.AddTensors(builder, fbv_tensors)
564 TosaBasicBlock.AddOperators(builder, fbv_operators)
565 return TosaBasicBlock.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000566
567
568@unique
569class TensorDir(IntEnum):
570 PLACEHOLDER = 0
571 CONST = 1
572 INTERMEDIATE = 2
573 RESULT = 3
574
575
576class TosaSerializer:
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100577 def __init__(self, pathPrefix, saveConstsToFile=False):
Eric Kunzeae906de2022-05-30 22:40:47 -0700578 self.add_compat_methods()
Kevin Chengfea5a372021-10-11 18:38:47 +0000579 # Get the global TOSA version if not already defined
Kevin Chengfea5a372021-10-11 18:38:47 +0000580
581 self.builder = flatbuffers.Builder(0)
582
583 self.basicBlocks = []
584 self.startBasicBlock("main")
585 self.pathPrefix = pathPrefix
586
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100587 # Enables inspection of constant data outside of graph
588 self.saveConstsToFile = saveConstsToFile
589
Kevin Chengfea5a372021-10-11 18:38:47 +0000590 # Indicies used for adding/naming tensors
591 self.currInputIdx = 0
592 self.currConstIdx = 0
593 self.currLayerIdx = 1
594 self.currResultIdx = 0
595
596 # Is this an illegal test that is expected to fail?
Jeremy Johnson9b225172021-12-14 16:34:47 +0000597 self.expectedReturnCode = 0
Kevin Chengfea5a372021-10-11 18:38:47 +0000598 self.expectedFailure = False
599 self.expectedFailureDesc = ""
600
601 def __str__(self):
602 str = ""
603 for bb in self.basicBlocks:
604 str = str + bb.__str__()
605 return str
606
607 def addPlaceholder(self, shape, dtype, vals):
608 if not self.currBasicBlock:
609 raise Exception("addTensor called without valid basic block")
610
611 name = "input-{}".format(self.currInputIdx)
612 filename = "{}.npy".format(name)
613 self.currInputIdx = self.currInputIdx + 1
614
615 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
616 # This is always an input to the block
617 self.currBasicBlock.addInput(name)
618
619 if vals is not None:
620 np.save(os.path.join(self.pathPrefix, filename), vals, False)
621
622 return tens
623
624 def addConst(self, shape, dtype, vals):
625 if not self.currBasicBlock:
626 raise Exception("addTensor called without valid basic block")
627
628 name = "const-{}".format(self.currInputIdx)
Kevin Chengfea5a372021-10-11 18:38:47 +0000629 self.currInputIdx = self.currInputIdx + 1
630
631 tens = self.currBasicBlock.addTensor(name, shape, dtype, vals)
632 # Add the operator now
Jeremy Johnson9b225172021-12-14 16:34:47 +0000633 self.currBasicBlock.addOperator(TosaOp.Op().CONST, [], name)
Kevin Chengfea5a372021-10-11 18:38:47 +0000634
Jeremy Johnsonc92710d2022-09-15 12:16:07 +0100635 if self.saveConstsToFile:
636 filename = "{}.npy".format(name)
637 np.save(os.path.join(self.pathPrefix, filename), vals, False)
638
Kevin Chengfea5a372021-10-11 18:38:47 +0000639 return tens
640
641 def addIntermediate(self, shape, dtype):
642
643 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):
654 self.currBasicBlock.addTensor(tensor.name, tensor.shape, tensor.dtype)
655 self.currBasicBlock.addInput(tensor.name)
656
657 def addOutputTensor(self, tensor):
658 self.currBasicBlock.addOutput(tensor.name)
659
660 def addOutput(self, shape, dtype):
661 if not self.currBasicBlock:
662 raise Exception("addTensor called without valid basic block")
663
664 name = "result-{}".format(self.currResultIdx)
665 self.currResultIdx = self.currResultIdx + 1
666
667 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
668 self.currBasicBlock.addOutput(name)
669 return tens
670
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000671 def addOperator(self, op, inputs, outputs, attributes=None):
Kevin Chengfea5a372021-10-11 18:38:47 +0000672
Jeremy Johnson9b225172021-12-14 16:34:47 +0000673 if op == TosaOp.Op().CONST:
Kevin Chengfea5a372021-10-11 18:38:47 +0000674 raise Exception("Use addConstTensor() to add CONST ops")
675
676 return self.currBasicBlock.addOperator(
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000677 op,
678 inputs,
679 outputs,
680 attributes,
Kevin Chengfea5a372021-10-11 18:38:47 +0000681 )
682
Jeremy Johnson9b225172021-12-14 16:34:47 +0000683 def setExpectedReturnCode(self, val, fail, desc=""):
Kevin Chengfea5a372021-10-11 18:38:47 +0000684
685 self.expectedReturnCode = val
686 self.expectedFailureDesc = desc
Jeremy Johnson9b225172021-12-14 16:34:47 +0000687 self.expectedFailure = fail
Kevin Chengfea5a372021-10-11 18:38:47 +0000688
689 def serialize(self):
690
691 builder = self.builder
692
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800693 Version.Start(builder)
694 Version.Add_major(builder, TOSA_VERSION[0])
695 Version.Add_minor(builder, TOSA_VERSION[1])
696 Version.Add_patch(builder, TOSA_VERSION[2])
697 Version.Add_draft(builder, TOSA_VERSION[3])
698 version = Version.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000699
700 fbv_bb = TosaSerializer.serializeObjVec(
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800701 builder, self.basicBlocks, TosaGraph.StartBlocksVector
Kevin Chengfea5a372021-10-11 18:38:47 +0000702 )
703
Kevin Cheng49faa4e2021-11-08 16:59:18 -0800704 TosaGraph.Start(builder)
705 TosaGraph.AddVersion(builder, version)
706 TosaGraph.AddBlocks(builder, fbv_bb)
707 graph = TosaGraph.End(builder)
Kevin Chengfea5a372021-10-11 18:38:47 +0000708
Eric Kunzee6596402022-06-09 21:27:36 +0000709 self.builder.Finish(graph, TOSA_GRAPH_IDENTIFIER)
Kevin Chengfea5a372021-10-11 18:38:47 +0000710 return self.builder.Output()
711
712 def writeJson(self, tosa_filename):
713 """Write a json test file so that it is fairly easy to pick up the test
714 and generate commands for third party tool"""
715 test_desc = dict()
716
717 test_desc["tosa_file"] = tosa_filename
718 ifm_name = []
719 ifm_file = []
720 ofm_name = []
721 ofm_file = []
722
723 for b in self.basicBlocks:
724 if b.name == "main":
725 for i in b.inputs:
726 ifm_name.append(i)
727 ifm_file.append(b.tensors[i].placeholderFilename)
728 for o in b.outputs:
729 ofm_name.append(o)
Jeremy Johnson9b225172021-12-14 16:34:47 +0000730 # Make up an OFM filename here. One isn't generated until the
731 # reference tool is run, so any name is a good name
Kevin Chengfea5a372021-10-11 18:38:47 +0000732 ofm_file.append("ref-{}.npy".format(o))
733
734 test_desc["ifm_name"] = ifm_name
735 test_desc["ifm_file"] = ifm_file
736 test_desc["ofm_name"] = ofm_name
737 test_desc["ofm_file"] = ofm_file
738 test_desc["expected_return_code"] = self.expectedReturnCode
739 test_desc["expected_failure"] = self.expectedFailure
740 if self.expectedFailureDesc:
741 test_desc["expected_failure_desc"] = self.expectedFailureDesc
742
743 return json.dumps(test_desc, indent=" ")
744
745 def startBasicBlock(self, name):
746 self.currBasicBlock = TosaSerializerBasicBlock(name)
747 self.basicBlocks.append(self.currBasicBlock)
748
749 @staticmethod
750 def serializeStrVec(builder, vec, start_fcn):
751 fb_strs = [builder.CreateString(i) for i in vec]
752 start_fcn(builder, len(fb_strs))
753 for s in fb_strs[::-1]:
754 builder.PrependUOffsetTRelative(s)
Eric Kunzeae906de2022-05-30 22:40:47 -0700755 try:
756 return builder.EndVector()
757 except TypeError:
758 return builder.EndVector(len(vec))
Kevin Chengfea5a372021-10-11 18:38:47 +0000759
760 @staticmethod
761 def serializeUint8Vec(builder, vec):
762 builder.StartVector(1, len(vec), 8)
763 for v in vec[::-1]:
764 builder.PrependUint8(v)
765 try:
766 return builder.EndVector()
767 except TypeError:
768 return builder.EndVector(len(vec))
769
770 @staticmethod
TatWai Chong49b1ca62022-06-10 01:49:13 -0700771 def serializeInt16Vec(builder, vec):
772 builder.StartVector(2, len(vec), 4)
773 for v in vec[::-1]:
774 builder.PrependInt16(v)
775 try:
776 return builder.EndVector()
777 except TypeError:
778 return builder.EndVector(len(vec))
779
780 @staticmethod
Kevin Chengfea5a372021-10-11 18:38:47 +0000781 def serializeInt32Vec(builder, vec):
782 builder.StartVector(4, len(vec), 4)
783 for v in vec[::-1]:
784 builder.PrependInt32(v)
785 try:
786 return builder.EndVector()
787 except TypeError:
788 return builder.EndVector(len(vec))
789
790 @staticmethod
791 def serializeFpVec(builder, vec):
792 builder.StartVector(4, len(vec), 4)
793 for v in vec[::-1]:
794 builder.PrependFloat32(v)
795 try:
796 return builder.EndVector()
797 except TypeError:
798 return builder.EndVector(len(vec))
799
800 @staticmethod
801 def serializeObjVec(builder, vec, start_fcn):
802 serialized_vec = []
803 for v in vec[::-1]:
804 serialized_vec.append(v.serialize(builder))
805
806 start_fcn(builder, len(vec))
807 for v in serialized_vec:
808 builder.PrependUOffsetTRelative(v)
809 try:
810 return builder.EndVector()
811 except TypeError:
812 return builder.EndVector(len(vec))
813
814 @staticmethod
815 def toList(val):
816 if isinstance(val, list):
817 return val
818 else:
819 return [val]
Eric Kunzeae906de2022-05-30 22:40:47 -0700820
821 # Remove when switching to flatbuffers 2.0
822 # contains a mapping of the deprecated 1.12 method to the 2.0 version
823
824 def add_compat_methods(self):
825
826 from tosa import ArithmeticRightShiftAttribute
827
828 if not hasattr(ArithmeticRightShiftAttribute, "Start"):
829 ArithmeticRightShiftAttribute.Start = (
830 ArithmeticRightShiftAttribute.ArithmeticRightShiftAttributeStart
831 )
832 ArithmeticRightShiftAttribute.AddRound = (
833 ArithmeticRightShiftAttribute.ArithmeticRightShiftAttributeAddRound
834 )
835 ArithmeticRightShiftAttribute.End = (
836 ArithmeticRightShiftAttribute.ArithmeticRightShiftAttributeEnd
837 )
838 from tosa import AxisAttribute
839
840 if not hasattr(AxisAttribute, "Start"):
841 AxisAttribute.Start = AxisAttribute.AxisAttributeStart
842 AxisAttribute.AddAxis = AxisAttribute.AxisAttributeAddAxis
843 AxisAttribute.End = AxisAttribute.AxisAttributeEnd
844 from tosa import ClampAttribute
845
846 if not hasattr(ClampAttribute, "Start"):
847 ClampAttribute.Start = ClampAttribute.ClampAttributeStart
848 ClampAttribute.AddMinInt = ClampAttribute.ClampAttributeAddMinInt
849 ClampAttribute.AddMaxInt = ClampAttribute.ClampAttributeAddMaxInt
850 ClampAttribute.AddMinFp = ClampAttribute.ClampAttributeAddMinFp
851 ClampAttribute.AddMaxFp = ClampAttribute.ClampAttributeAddMaxFp
852 ClampAttribute.End = ClampAttribute.ClampAttributeEnd
853 from tosa import CondIfAttribute
854
855 if not hasattr(CondIfAttribute, "Start"):
856 CondIfAttribute.Start = CondIfAttribute.CondIfAttributeStart
857 CondIfAttribute.AddThenBranch = CondIfAttribute.CondIfAttributeAddThenBranch
858 CondIfAttribute.AddElseBranch = CondIfAttribute.CondIfAttributeAddElseBranch
859 CondIfAttribute.End = CondIfAttribute.CondIfAttributeEnd
860 from tosa import ConvAttribute
861
862 if not hasattr(ConvAttribute, "Start"):
863 ConvAttribute.Start = ConvAttribute.ConvAttributeStart
864 ConvAttribute.AddPad = ConvAttribute.ConvAttributeAddPad
865 ConvAttribute.StartPadVector = ConvAttribute.ConvAttributeStartPadVector
866 ConvAttribute.AddStride = ConvAttribute.ConvAttributeAddStride
867 ConvAttribute.StartStrideVector = (
868 ConvAttribute.ConvAttributeStartStrideVector
869 )
870 ConvAttribute.AddDilation = ConvAttribute.ConvAttributeAddDilation
871 ConvAttribute.StartDilationVector = (
872 ConvAttribute.ConvAttributeStartDilationVector
873 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000874 ConvAttribute.AddInputZp = ConvAttribute.ConvAttributeAddInputZp
875 ConvAttribute.AddWeightZp = ConvAttribute.ConvAttributeAddWeightZp
Eric Kunzeae906de2022-05-30 22:40:47 -0700876 ConvAttribute.End = ConvAttribute.ConvAttributeEnd
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000877 from tosa import FullyConnectedAttribute
Eric Kunzeae906de2022-05-30 22:40:47 -0700878
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000879 if not hasattr(FullyConnectedAttribute, "Start"):
880 FullyConnectedAttribute.Start = (
881 FullyConnectedAttribute.FullyConnectedAttributeStart
882 )
883 FullyConnectedAttribute.AddInputZp = (
884 FullyConnectedAttribute.FullyConnectedAttributeAddInputZp
885 )
886 FullyConnectedAttribute.AddWeightZp = (
887 FullyConnectedAttribute.FullyConnectedAttributeAddWeightZp
888 )
889 FullyConnectedAttribute.End = (
890 FullyConnectedAttribute.FullyConnectedAttributeEnd
891 )
892 from tosa import MatMulAttribute
Eric Kunzeae906de2022-05-30 22:40:47 -0700893
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000894 if not hasattr(MatMulAttribute, "Start"):
895 MatMulAttribute.Start = MatMulAttribute.MatMulAttributeStart
896 MatMulAttribute.AddAZp = MatMulAttribute.MatMulAttributeAddAZp
897 MatMulAttribute.AddBZp = MatMulAttribute.MatMulAttributeAddBZp
898 MatMulAttribute.End = MatMulAttribute.MatMulAttributeEnd
899 from tosa import PoolAttribute
900
901 if not hasattr(PoolAttribute, "Start"):
902 PoolAttribute.Start = PoolAttribute.PoolAttributeStart
903 PoolAttribute.AddPad = PoolAttribute.PoolAttributeAddPad
904 PoolAttribute.StartPadVector = PoolAttribute.PoolAttributeStartPadVector
905 PoolAttribute.AddKernel = PoolAttribute.PoolAttributeAddKernel
906 PoolAttribute.StartKernelVector = (
907 PoolAttribute.PoolAttributeStartKernelVector
908 )
909 PoolAttribute.AddStride = PoolAttribute.PoolAttributeAddStride
910 PoolAttribute.StartStrideVector = (
911 PoolAttribute.PoolAttributeStartStrideVector
912 )
913 PoolAttribute.AddInputZp = PoolAttribute.PoolAttributeAddInputZp
914 PoolAttribute.AddOutputZp = PoolAttribute.PoolAttributeAddOutputZp
915 PoolAttribute.End = PoolAttribute.PoolAttributeEnd
Eric Kunzeae906de2022-05-30 22:40:47 -0700916 from tosa import MulAttribute
917
918 if not hasattr(MulAttribute, "Start"):
919 MulAttribute.Start = MulAttribute.MulAttributeStart
920 MulAttribute.AddShift = MulAttribute.MulAttributeAddShift
921 MulAttribute.End = MulAttribute.MulAttributeEnd
922 from tosa import PadAttribute
923
924 if not hasattr(PadAttribute, "Start"):
925 PadAttribute.Start = PadAttribute.PadAttributeStart
926 PadAttribute.AddPadding = PadAttribute.PadAttributeAddPadding
927 PadAttribute.StartPaddingVector = (
928 PadAttribute.PadAttributeStartPaddingVector
929 )
930 PadAttribute.AddPadConstInt = PadAttribute.PadAttributeAddPadConstInt
931 PadAttribute.AddPadConstFp = PadAttribute.PadAttributeAddPadConstFp
932 PadAttribute.End = PadAttribute.PadAttributeEnd
Eric Kunzeae906de2022-05-30 22:40:47 -0700933 from tosa import PoolAttribute
934
935 if not hasattr(PoolAttribute, "Start"):
936 PoolAttribute.Start = PoolAttribute.PoolAttributeStart
937 PoolAttribute.AddPad = PoolAttribute.PoolAttributeAddPad
938 PoolAttribute.StartPadVector = PoolAttribute.PoolAttributeStartPadVector
939 PoolAttribute.AddKernel = PoolAttribute.PoolAttributeAddKernel
940 PoolAttribute.StartKernelVector = (
941 PoolAttribute.PoolAttributeStartKernelVector
942 )
943 PoolAttribute.AddStride = PoolAttribute.PoolAttributeAddStride
944 PoolAttribute.StartStrideVector = (
945 PoolAttribute.PoolAttributeStartStrideVector
946 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +0000947 PoolAttribute.AddInputZp = PoolAttribute.PoolAttributeAddInputZp
948 PoolAttribute.AddOutputZp = PoolAttribute.PoolAttributeAddOutputZp
Eric Kunzeae906de2022-05-30 22:40:47 -0700949 PoolAttribute.End = PoolAttribute.PoolAttributeEnd
950 from tosa import RescaleAttribute
951
952 if not hasattr(RescaleAttribute, "Start"):
953 RescaleAttribute.Start = RescaleAttribute.RescaleAttributeStart
954 RescaleAttribute.AddInputZp = RescaleAttribute.RescaleAttributeAddInputZp
955 RescaleAttribute.AddOutputZp = RescaleAttribute.RescaleAttributeAddOutputZp
956 RescaleAttribute.AddMultiplier = (
957 RescaleAttribute.RescaleAttributeAddMultiplier
958 )
959 RescaleAttribute.StartMultiplierVector = (
960 RescaleAttribute.RescaleAttributeStartMultiplierVector
961 )
962 RescaleAttribute.AddShift = RescaleAttribute.RescaleAttributeAddShift
963 RescaleAttribute.StartShiftVector = (
964 RescaleAttribute.RescaleAttributeStartShiftVector
965 )
966 RescaleAttribute.AddScale32 = RescaleAttribute.RescaleAttributeAddScale32
967 RescaleAttribute.AddDoubleRound = (
968 RescaleAttribute.RescaleAttributeAddDoubleRound
969 )
970 RescaleAttribute.AddPerChannel = (
971 RescaleAttribute.RescaleAttributeAddPerChannel
972 )
973 RescaleAttribute.End = RescaleAttribute.RescaleAttributeEnd
974 from tosa import ReshapeAttribute
975
976 if not hasattr(ReshapeAttribute, "Start"):
977 ReshapeAttribute.Start = ReshapeAttribute.ReshapeAttributeStart
978 ReshapeAttribute.AddNewShape = ReshapeAttribute.ReshapeAttributeAddNewShape
979 ReshapeAttribute.StartNewShapeVector = (
980 ReshapeAttribute.ReshapeAttributeStartNewShapeVector
981 )
982 ReshapeAttribute.End = ReshapeAttribute.ReshapeAttributeEnd
983 from tosa import ResizeAttribute
984
985 if not hasattr(ResizeAttribute, "Start"):
986 ResizeAttribute.Start = ResizeAttribute.ResizeAttributeStart
TatWai Chong49b1ca62022-06-10 01:49:13 -0700987 ResizeAttribute.AddScale = ResizeAttribute.ResizeAttributeAddScale
988 ResizeAttribute.StartScaleVector = (
989 ResizeAttribute.ResizeAttributeStartScaleVector
Eric Kunzeae906de2022-05-30 22:40:47 -0700990 )
991 ResizeAttribute.AddOffset = ResizeAttribute.ResizeAttributeAddOffset
992 ResizeAttribute.StartOffsetVector = (
993 ResizeAttribute.ResizeAttributeStartOffsetVector
994 )
TatWai Chong49b1ca62022-06-10 01:49:13 -0700995 ResizeAttribute.AddBorder = ResizeAttribute.ResizeAttributeAddBorder
996 ResizeAttribute.StartBorderVector = (
997 ResizeAttribute.ResizeAttributeStartBorderVector
Eric Kunzeae906de2022-05-30 22:40:47 -0700998 )
999 ResizeAttribute.AddMode = ResizeAttribute.ResizeAttributeAddMode
1000 ResizeAttribute.End = ResizeAttribute.ResizeAttributeEnd
1001 from tosa import SliceAttribute
1002
1003 if not hasattr(SliceAttribute, "Start"):
1004 SliceAttribute.Start = SliceAttribute.SliceAttributeStart
1005 SliceAttribute.AddStart = SliceAttribute.SliceAttributeAddStart
1006 SliceAttribute.StartStartVector = (
1007 SliceAttribute.SliceAttributeStartStartVector
1008 )
1009 SliceAttribute.AddSize = SliceAttribute.SliceAttributeAddSize
1010 SliceAttribute.StartSizeVector = (
1011 SliceAttribute.SliceAttributeStartSizeVector
1012 )
1013 SliceAttribute.End = SliceAttribute.SliceAttributeEnd
1014 from tosa import TableAttribute
1015
1016 if not hasattr(TableAttribute, "Start"):
1017 TableAttribute.Start = TableAttribute.TableAttributeStart
1018 TableAttribute.AddTable = TableAttribute.TableAttributeAddTable
1019 TableAttribute.StartTableVector = (
1020 TableAttribute.TableAttributeStartTableVector
1021 )
1022 TableAttribute.End = TableAttribute.TableAttributeEnd
1023 from tosa import TileAttribute
1024
1025 if not hasattr(TileAttribute, "Start"):
1026 TileAttribute.Start = TileAttribute.TileAttributeStart
1027 TileAttribute.AddMultiples = TileAttribute.TileAttributeAddMultiples
1028 TileAttribute.StartMultiplesVector = (
1029 TileAttribute.TileAttributeStartMultiplesVector
1030 )
1031 TileAttribute.End = TileAttribute.TileAttributeEnd
1032 from tosa import TosaBasicBlock
1033
1034 if not hasattr(TosaBasicBlock, "Start"):
1035 TosaBasicBlock.Start = TosaBasicBlock.TosaBasicBlockStart
1036 TosaBasicBlock.AddName = TosaBasicBlock.TosaBasicBlockAddName
1037 TosaBasicBlock.AddOperators = TosaBasicBlock.TosaBasicBlockAddOperators
1038 TosaBasicBlock.StartOperatorsVector = (
1039 TosaBasicBlock.TosaBasicBlockStartOperatorsVector
1040 )
1041 TosaBasicBlock.AddTensors = TosaBasicBlock.TosaBasicBlockAddTensors
1042 TosaBasicBlock.StartTensorsVector = (
1043 TosaBasicBlock.TosaBasicBlockStartTensorsVector
1044 )
1045 TosaBasicBlock.AddInputs = TosaBasicBlock.TosaBasicBlockAddInputs
1046 TosaBasicBlock.StartInputsVector = (
1047 TosaBasicBlock.TosaBasicBlockStartInputsVector
1048 )
1049 TosaBasicBlock.AddOutputs = TosaBasicBlock.TosaBasicBlockAddOutputs
1050 TosaBasicBlock.StartOutputsVector = (
1051 TosaBasicBlock.TosaBasicBlockStartOutputsVector
1052 )
1053 TosaBasicBlock.End = TosaBasicBlock.TosaBasicBlockEnd
1054 from tosa import TosaGraph
1055
1056 if not hasattr(TosaGraph, "Start"):
1057 TosaGraph.Start = TosaGraph.TosaGraphStart
1058 TosaGraph.AddVersion = TosaGraph.TosaGraphAddVersion
1059 TosaGraph.AddBlocks = TosaGraph.TosaGraphAddBlocks
1060 TosaGraph.StartBlocksVector = TosaGraph.TosaGraphStartBlocksVector
1061 TosaGraph.End = TosaGraph.TosaGraphEnd
1062 from tosa import TosaOperator
1063
1064 if not hasattr(TosaOperator, "Start"):
1065 TosaOperator.Start = TosaOperator.TosaOperatorStart
1066 TosaOperator.AddOp = TosaOperator.TosaOperatorAddOp
1067 TosaOperator.AddAttributeType = TosaOperator.TosaOperatorAddAttributeType
1068 TosaOperator.AddAttribute = TosaOperator.TosaOperatorAddAttribute
1069 TosaOperator.AddInputs = TosaOperator.TosaOperatorAddInputs
1070 TosaOperator.StartInputsVector = TosaOperator.TosaOperatorStartInputsVector
1071 TosaOperator.AddOutputs = TosaOperator.TosaOperatorAddOutputs
1072 TosaOperator.StartOutputsVector = (
1073 TosaOperator.TosaOperatorStartOutputsVector
1074 )
Eric Kunzeae906de2022-05-30 22:40:47 -07001075 TosaOperator.End = TosaOperator.TosaOperatorEnd
1076 from tosa import TosaTensor
1077
1078 if not hasattr(TosaTensor, "Start"):
1079 TosaTensor.Start = TosaTensor.TosaTensorStart
1080 TosaTensor.AddName = TosaTensor.TosaTensorAddName
1081 TosaTensor.AddShape = TosaTensor.TosaTensorAddShape
1082 TosaTensor.StartShapeVector = TosaTensor.TosaTensorStartShapeVector
1083 TosaTensor.AddType = TosaTensor.TosaTensorAddType
1084 TosaTensor.AddData = TosaTensor.TosaTensorAddData
1085 TosaTensor.StartDataVector = TosaTensor.TosaTensorStartDataVector
1086 TosaTensor.End = TosaTensor.TosaTensorEnd
1087 from tosa import TransposeAttribute
1088
1089 if not hasattr(TransposeAttribute, "Start"):
1090 TransposeAttribute.Start = TransposeAttribute.TransposeAttributeStart
1091 TransposeAttribute.AddPerms = TransposeAttribute.TransposeAttributeAddPerms
1092 TransposeAttribute.StartPermsVector = (
1093 TransposeAttribute.TransposeAttributeStartPermsVector
1094 )
1095 TransposeAttribute.End = TransposeAttribute.TransposeAttributeEnd
1096 from tosa import TransposeConvAttribute
1097
1098 if not hasattr(TransposeConvAttribute, "Start"):
1099 TransposeConvAttribute.Start = (
1100 TransposeConvAttribute.TransposeConvAttributeStart
1101 )
Eric Kunze4c3537d2022-06-13 17:21:48 -07001102 TransposeConvAttribute.AddOutPad = (
1103 TransposeConvAttribute.TransposeConvAttributeAddOutPad
Eric Kunzeae906de2022-05-30 22:40:47 -07001104 )
Eric Kunze4c3537d2022-06-13 17:21:48 -07001105 TransposeConvAttribute.StartOutPadVector = (
1106 TransposeConvAttribute.TransposeConvAttributeStartOutPadVector
Eric Kunzeae906de2022-05-30 22:40:47 -07001107 )
1108 TransposeConvAttribute.AddStride = (
1109 TransposeConvAttribute.TransposeConvAttributeAddStride
1110 )
1111 TransposeConvAttribute.StartStrideVector = (
1112 TransposeConvAttribute.TransposeConvAttributeStartStrideVector
1113 )
Eric Kunzeae906de2022-05-30 22:40:47 -07001114 TransposeConvAttribute.AddOutputShape = (
1115 TransposeConvAttribute.TransposeConvAttributeAddOutputShape
1116 )
1117 TransposeConvAttribute.StartOutputShapeVector = (
1118 TransposeConvAttribute.TransposeConvAttributeStartOutputShapeVector
1119 )
Eric Kunzebdcc3fe2022-06-07 05:17:37 +00001120 TransposeConvAttribute.AddInputZp = (
1121 TransposeConvAttribute.TransposeConvAttributeAddInputZp
1122 )
1123 TransposeConvAttribute.AddWeightZp = (
1124 TransposeConvAttribute.TransposeConvAttributeAddWeightZp
1125 )
Eric Kunzeae906de2022-05-30 22:40:47 -07001126 TransposeConvAttribute.End = (
1127 TransposeConvAttribute.TransposeConvAttributeEnd
1128 )
Eric Kunzeae906de2022-05-30 22:40:47 -07001129 from tosa import Version
1130
1131 if not hasattr(Version, "Start"):
1132 Version.Start = Version.VersionStart
1133 Version.Add_major = Version.VersionAdd_major
1134 Version.Add_minor = Version.VersionAdd_minor
1135 Version.Add_patch = Version.VersionAdd_patch
1136 Version.Add_draft = Version.VersionAdd_draft
1137 Version.End = Version.VersionEnd
Eric Kunzebdcc3fe2022-06-07 05:17:37 +00001138 from tosa import MatMulAttribute
1139
1140 if not hasattr(MatMulAttribute, "Start"):
1141 MatMulAttribute.Start = MatMulAttribute.MatMulAttributeStart
1142 MatMulAttribute.AddAZp = MatMulAttribute.MatMulAttributeAddAZp
1143 MatMulAttribute.AddBZp = MatMulAttribute.MatMulAttributeAddBZp
1144 MatMulAttribute.End = MatMulAttribute.MatMulAttributeEnd
1145 from tosa import FullyConnectedAttribute
1146
1147 if not hasattr(FullyConnectedAttribute, "Start"):
1148 FullyConnectedAttribute.Start = (
1149 FullyConnectedAttribute.FullyConnectedAttributeStart
1150 )
1151 FullyConnectedAttribute.AddInputZp = (
1152 FullyConnectedAttribute.FullyConnectedAttributeAddInputZp
1153 )
1154 FullyConnectedAttribute.AddWeightZp = (
1155 FullyConnectedAttribute.FullyConnectedAttributeAddWeightZp
1156 )
1157 FullyConnectedAttribute.End = (
1158 FullyConnectedAttribute.FullyConnectedAttributeEnd
1159 )
1160 from tosa import NegateAttribute
1161
1162 if not hasattr(NegateAttribute, "Start"):
1163 NegateAttribute.Start = NegateAttribute.NegateAttributeStart
1164 NegateAttribute.AddInput1Zp = NegateAttribute.NegateAttributeAddInput1Zp
1165 NegateAttribute.AddOutputZp = NegateAttribute.NegateAttributeAddOutputZp
1166 NegateAttribute.End = NegateAttribute.NegateAttributeEnd
Eric Kunzeae906de2022-05-30 22:40:47 -07001167 from tosa import WhileLoopAttribute
1168
1169 if not hasattr(WhileLoopAttribute, "Start"):
1170 WhileLoopAttribute.Start = WhileLoopAttribute.WhileLoopAttributeStart
1171 WhileLoopAttribute.AddCondBranch = (
1172 WhileLoopAttribute.WhileLoopAttributeAddCondBranch
1173 )
1174 WhileLoopAttribute.AddBodyBranch = (
1175 WhileLoopAttribute.WhileLoopAttributeAddBodyBranch
1176 )
1177 WhileLoopAttribute.End = WhileLoopAttribute.WhileLoopAttributeEnd