blob: c250305b7200c3ea692c7caf58fb182f2e62a231 [file] [log] [blame]
Kevin Chengfea5a372021-10-11 18:38:47 +00001# Copyright (c) 2020-2021, ARM Limited.
2#
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
17import os
18import sys
19import json
20import flatbuffers
21import numpy as np
22import struct
23from enum import Enum, IntEnum, unique
24from tosa import (
25 TosaGraph,
26 TosaBasicBlock,
27 TosaTensor,
28 TosaOperator,
29 DType,
30 Op,
31 ResizeMode,
32 Version,
33)
34from tosa_ref_run import TosaReturnCode
35
36import tosa
37
Kevin Chenge6563f52021-10-20 12:12:02 -070038# Keep version number in sync with the version default value with schema/tosa.fbs
Kevin Chengb97cb1d2021-10-14 11:53:39 -070039TOSA_VERSION_MAJOR = 0
40TOSA_VERSION_MINOR = 23
41TOSA_VERSION_PATCH = 0
Eric Kunze5867c9a2021-10-29 16:53:32 -070042TOSA_VERSION_DRAFT = False
Kevin Chengb97cb1d2021-10-14 11:53:39 -070043TOSA_VERSION = [TOSA_VERSION_MAJOR,
44 TOSA_VERSION_MINOR,
45 TOSA_VERSION_PATCH,
46 TOSA_VERSION_DRAFT]
Kevin Chengfea5a372021-10-11 18:38:47 +000047# With the way flatc generates its python types, there is no programatic way
48# to get string names for the integer types. Manually maintain a string table
49# here.
50DType = tosa.DType.DType()
51DTypeNames = [
52 "UNKNOWN",
53 "BOOL",
54 "UINT8",
55 "INT4",
56 "INT8",
57 "INT16",
58 "INT32",
59 "INT48",
60 "FLOAT",
61]
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
79 # A tuple of the start and end functions. Set by the options constructors below
80 self.optFcns = None
81
82 # The type from the tosa.Options enumeration. Set by the options constructors below.
83 self.utype = None
84
85 # Each of these lists is a tuple of the add function and the
86 # value being added. Set by the options constructors below.
87 self.ints = []
88 self.bools = []
89 self.floats = []
90 self.strings = []
91 self.intvecs = []
92 self.fpvecs = []
93
94 def serialize(self, builder):
95
96 # We have to build strings and vectors first
97 strList = []
98 intVecList = []
99 fpVecList = []
100
101 for fcn, val in self.strings:
102 strList.append((fcn, builder.CreateString(val)))
103
104 for fcn, val in self.intvecs:
105 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
106
107 for fcn, val in self.fpvecs:
108 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
109
110 startFcn, endFcn = self.optFcns
111
112 # Then serialize the options object from the list of primitives and
113 # other serialized values
114 startFcn(builder)
115 for fcn, val in self.ints:
116 fcn(builder, val)
117
118 for fcn, val in self.bools:
119 fcn(builder, val)
120
121 for fcn, val in self.floats:
122 fcn(builder, val)
123
124 for fcn, val in strList:
125 fcn(builder, val)
126
127 for fcn, val in intVecList:
128 fcn(builder, val)
129
130 for fcn, val in fpVecList:
131 fcn(builder, val)
132
133 return endFcn(builder)
134
135
136class TosaSerializerAttribute(TosaSerializerUnion):
137 """This class handles encapsulating all of the enumerated types for attributes"""
138
139 def __init__(self):
140 super().__init__()
141
142 def PoolAttribute(self, kernel, stride, padding):
143 from tosa import PoolAttribute as a, Attribute
144
145 self.utype = Attribute.Attribute().PoolAttribute
146
147 self.optFcns = (a.PoolAttributeStart, a.PoolAttributeEnd)
148 self.intvecs.append((a.PoolAttributeAddPadding, padding))
149 self.intvecs.append((a.PoolAttributeAddKernel, kernel))
150 self.intvecs.append((a.PoolAttributeAddStride, stride))
151
152 def ConvAttribute(self, padding, stride, dilation):
153 from tosa import ConvAttribute as a, Attribute
154
155 self.utype = Attribute.Attribute().ConvAttribute
156 self.optFcns = (a.ConvAttributeStart, a.ConvAttributeEnd)
157
158 self.intvecs.append((a.ConvAttributeAddPadding, padding))
159 self.intvecs.append((a.ConvAttributeAddStride, stride))
160 self.intvecs.append((a.ConvAttributeAddDilation, dilation))
161
162 def TransposeConvAttribute(self, outpad, stride, dilation, output_shape):
163 from tosa import TransposeConvAttribute as a, Attribute
164
165 self.utype = Attribute.Attribute().TransposeConvAttribute
166 self.optFcns = (a.TransposeConvAttributeStart, a.TransposeConvAttributeEnd)
167
168 self.intvecs.append((a.TransposeConvAttributeAddOutpad, outpad))
169 self.intvecs.append((a.TransposeConvAttributeAddStride, stride))
170 self.intvecs.append((a.TransposeConvAttributeAddDilation, dilation))
171 self.intvecs.append((a.TransposeConvAttributeAddOutputShape, output_shape))
172
Kevin Cheng38d214c2021-10-15 15:49:19 -0700173 def PadAttribute(self, padding, pad_const_int, pad_const_fp):
174 from tosa import PadAttribute as a, Attribute
Kevin Chengfea5a372021-10-11 18:38:47 +0000175
Kevin Cheng38d214c2021-10-15 15:49:19 -0700176 self.utype = Attribute.Attribute().PadAttribute
177 self.optFcns = (a.PadAttributeStart, a.PadAttributeEnd)
Kevin Chengfea5a372021-10-11 18:38:47 +0000178
Kevin Cheng38d214c2021-10-15 15:49:19 -0700179 self.intvecs.append((a.PadAttributeAddPadding, padding))
180 self.ints.append((a.PadAttributeAddPadConstInt, pad_const_int))
181 self.floats.append((a.PadAttributeAddPadConstFp, pad_const_fp))
Kevin Chengfea5a372021-10-11 18:38:47 +0000182
183 def AxisAttribute(self, axis):
184 from tosa import AxisAttribute as a, Attribute
185
186 self.utype = Attribute.Attribute().AxisAttribute
187 self.optFcns = (a.AxisAttributeStart, a.AxisAttributeEnd)
188
189 self.ints.append((a.AxisAttributeAddAxis, axis))
190
191 def ReshapeAttribute(self, shape):
192 from tosa import ReshapeAttribute as a, Attribute
193
194 self.utype = Attribute.Attribute().ReshapeAttribute
195 self.optFcns = (a.ReshapeAttributeStart, a.ReshapeAttributeEnd)
196
197 self.intvecs.append((a.ReshapeAttributeAddShape, shape))
198
199 def SliceAttribute(self, begin, size):
200 from tosa import SliceAttribute as a, Attribute
201
202 self.utype = Attribute.Attribute().SliceAttribute
203 self.optFcns = (a.SliceAttributeStart, a.SliceAttributeEnd)
204
205 self.intvecs.append((a.SliceAttributeAddBegin, begin))
206 self.intvecs.append((a.SliceAttributeAddSize, size))
207
208 def TileAttribute(self, multiples):
209 from tosa import TileAttribute as a, Attribute
210
211 self.utype = Attribute.Attribute().TileAttribute
212 self.optFcns = (a.TileAttributeStart, a.TileAttributeEnd)
213
214 self.intvecs.append((a.TileAttributeAddMultiples, multiples))
215
216 def ResizeAttribute(
217 self, output_size, stride, offset, shift, stride_fp, offset_fp, mode
218 ):
219 from tosa import ResizeAttribute as a, Attribute
220
221 self.utype = Attribute.Attribute().ResizeAttribute
222 self.optFcns = (a.ResizeAttributeStart, a.ResizeAttributeEnd)
223
224 self.intvecs.append((a.ResizeAttributeAddOutputSize, output_size))
225 self.intvecs.append((a.ResizeAttributeAddStride, stride))
226 self.intvecs.append((a.ResizeAttributeAddOffset, offset))
227 self.ints.append((a.ResizeAttributeAddShift, shift))
228 self.fpvecs.append((a.ResizeAttributeAddStrideFp, stride_fp))
229 self.fpvecs.append((a.ResizeAttributeAddOffsetFp, offset_fp))
230 self.ints.append((a.ResizeAttributeAddMode, mode))
231
232 def ClampAttribute(self, minint, maxint, minfp, maxfp):
233 from tosa import ClampAttribute as a, Attribute
234
235 self.utype = Attribute.Attribute().ClampAttribute
236 self.optFcns = (a.ClampAttributeStart, a.ClampAttributeEnd)
237
238 self.ints.append((a.ClampAttributeAddMinInt, minint))
239 self.ints.append((a.ClampAttributeAddMaxInt, maxint))
240
241 self.ints.append((a.ClampAttributeAddMinFp, minfp))
242 self.ints.append((a.ClampAttributeAddMaxFp, maxfp))
243
244 def RescaleAttribute(
245 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
246 ):
247 from tosa import RescaleAttribute as a, Attribute
248
249 self.utype = Attribute.Attribute().RescaleAttribute
250 self.optFcns = (a.RescaleAttributeStart, a.RescaleAttributeEnd)
251
252 self.ints.append((a.RescaleAttributeAddInputZp, input_zp))
253 self.ints.append((a.RescaleAttributeAddOutputZp, output_zp))
254 self.intvecs.append((a.RescaleAttributeAddMultiplier, multiplier))
255 self.intvecs.append((a.RescaleAttributeAddShift, shift))
256 self.bools.append((a.RescaleAttributeAddScale32, scale32))
257 self.bools.append((a.RescaleAttributeAddDoubleRound, double_round))
258 self.bools.append((a.RescaleAttributeAddPerChannel, per_channel))
259
260 def MulAttribute(self, shift):
261 from tosa import MulAttribute as a, Attribute
262
263 self.utype = Attribute.Attribute().MulAttribute
264 self.optFcns = (a.MulAttributeStart, a.MulAttributeEnd)
265
266 self.ints.append((a.MulAttributeAddShift, shift))
267
268 def ArithmeticRightShiftAttribute(self, round):
269 from tosa import ArithmeticRightShiftAttribute as a, Attribute
270
271 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
272 self.optFcns = (
273 a.ArithmeticRightShiftAttributeStart,
274 a.ArithmeticRightShiftAttributeEnd,
275 )
276
277 self.bools.append((a.ArithmeticRightShiftAttributeAddRound, round))
278
Kevin Chengfea5a372021-10-11 18:38:47 +0000279 def CondIfAttribute(self, then_branch, else_branch):
280 from tosa import CondIfAttribute as a, Attribute
281
282 self.utype = Attribute.Attribute().CondIfAttribute
283 self.optFcns = (a.CondIfAttributeStart, a.CondIfAttributeEnd)
284
285 self.strings.append((a.CondIfAttributeAddThenBranch, then_branch))
286 self.strings.append((a.CondIfAttributeAddElseBranch, else_branch))
287
288 def WhileLoopAttribute(self, cond_branch, body_branch):
289 from tosa import WhileLoopAttribute as a, Attribute
290
291 self.utype = Attribute.Attribute().WhileLoopAttribute
292 self.optFcns = (a.WhileLoopAttributeStart, a.WhileLoopAttributeEnd)
293
294 self.strings.append((a.WhileLoopAttributeAddCondBranch, cond_branch))
295 self.strings.append((a.WhileLoopAttributeAddBodyBranch, body_branch))
296
Kevin Cheng38d214c2021-10-15 15:49:19 -0700297 def TransposeAttribute(self, perm):
298 from tosa import TransposeAttribute as a, Attribute
299
300 self.utype = Attribute.Attribute().TransposeAttribute
301 self.optFcns = (a.TransposeAttributeStart, a.TransposeAttributeEnd)
302
303 self.intvecs.append((a.TransposeAttributeAddPerm, perm))
304
305 def TableAttribute(self, table):
306 from tosa import TableAttribute as a, Attribute
307
308 self.utype = Attribute.Attribute().TableAttribute
309 self.optFcns = (a.TableAttributeStart, a.TableAttributeEnd)
310
311 self.intvecs.append((a.TableAttributeAddTable, table))
Kevin Chengfea5a372021-10-11 18:38:47 +0000312
313class TosaSerializerQuantInfo(TosaSerializerUnion):
314 """This class handles encapsulating all of the enumerated types for quantinfo types"""
315
316 def __init__(self):
317 super().__init__()
318
319 def ConvQuantInfo(self, input_zp, weight_zp):
320 from tosa import ConvQuantInfo as q, QuantInfo
321
322 self.utype = QuantInfo.QuantInfo().ConvQuantInfo
323 self.optFcns = (q.ConvQuantInfoStart, q.ConvQuantInfoEnd)
324 self.ints.append((q.ConvQuantInfoAddInputZp, input_zp))
325 self.ints.append((q.ConvQuantInfoAddWeightZp, weight_zp))
326
327 def UnaryQuantInfo(self, input_zp, output_zp):
328 from tosa import UnaryQuantInfo as q, QuantInfo
329
330 self.utype = QuantInfo.QuantInfo().UnaryQuantInfo
331 self.optFcns = (q.UnaryQuantInfoStart, q.UnaryQuantInfoEnd)
332 self.ints.append((q.UnaryQuantInfoAddInputZp, input_zp))
333 self.ints.append((q.UnaryQuantInfoAddOutputZp, output_zp))
334
335 def MatMulQuantInfo(self, a_zp, b_zp):
336 from tosa import MatMulQuantInfo as q, QuantInfo
337
338 self.utype = QuantInfo.QuantInfo().MatMulQuantInfo
339 self.optFcns = (q.MatMulQuantInfoStart, q.MatMulQuantInfoEnd)
340 self.ints.append((q.MatMulQuantInfoAddAZp, a_zp))
341 self.ints.append((q.MatMulQuantInfoAddBZp, b_zp))
342
343 def PadQuantInfo(self, input_zp):
344 from tosa import PadQuantInfo as q, QuantInfo
345
346 self.utype = QuantInfo.QuantInfo().PadQuantInfo
347 self.optFcns = (q.PadQuantInfoStart, q.PadQuantInfoEnd)
348 self.ints.append((q.PadQuantInfoAddInputZp, input_zp))
349
350
351class TosaSerializerTensor:
352 def __init__(
353 self,
354 name,
355 shape,
356 dtype,
357 data=None,
358 placeholderFilename=None,
359 ):
360 self.name = name
361
362 if isinstance(shape, np.ndarray):
363 shape = shape.astype(int).tolist()
364 shape = list(map(int, shape))
365
366 self.shape = shape
367 self.dtype = dtype
368
369 if isinstance(data, np.ndarray):
370 data = data.flatten().astype(int).tolist()
371 data = list(map(int, data))
372 self.data = data
373 elif isinstance(data, list):
374 data = list(map(int, data))
375 self.data = data
376 else:
377 self.data = None
378
379 # Filename for placeholder tensors. These get generated by the test generation
380 # process and are written to disk, but are considered input tensors by the network
381 # so they do not appear in the TOSA serialiazation. However, if we want to form a unit
382 # test around these input tensors, we can get the filename from here.
383 self.placeholderFilename = placeholderFilename
384
385 def __str__(self):
386 str = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
387 self.name,
388 self.shape,
389 DTypeNames[self.dtype],
390 )
391 return str
392
393 def setDtype(self, dtype):
394 self.dtype = dtype
395
396 def serialize(self, builder):
397 fb_name = builder.CreateString(self.name)
398 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
399 if self.data:
400 u8_data = list()
401 # little endianess
402 if self.dtype == DType.BOOL:
403 for val in self.data:
404 val_u8 = np.uint8(val)
405 u8_data.append(val_u8)
406 elif self.dtype == DType.INT4:
407 in_size = len(self.data)
408 out_size = (in_size + 1) // 2
409 for i in range(out_size):
410 val_0 = self.data[2 * i]
411 if (2 * i + 1) < in_size:
412 val_1 = self.data[2 * i + 1]
413 else:
414 val_1 = 0
415 val_i8 = (val_0 & 0xF) | ((val_1 & 0xF) << 4)
416 val_u8 = np.uint8(val_i8)
417 u8_data.append(val_u8)
418 elif self.dtype == DType.INT8:
419 for val in self.data:
420 val_u8 = np.uint8(val)
421 u8_data.append(val_u8)
422 elif self.dtype == DType.INT16:
423 for val in self.data:
424 val_u16 = np.uint16(val)
425 b0 = val_u16 & ByteMask
426 b1 = (val_u16 >> np.uint16(8)) & ByteMask
427 u8_data.extend([b0, b1])
428 elif self.dtype == DType.INT32:
429 for val in self.data:
430 val_u32 = np.uint32(val)
431 b0 = val_u32 & ByteMask
432 b1 = (val_u32 >> np.uint32(8)) & ByteMask
433 b2 = (val_u32 >> np.uint32(16)) & ByteMask
Kevin Cheng6b078ca2021-10-13 23:12:50 -0700434 b3 = (val_u32 >> np.uint32(24)) & ByteMask
Kevin Chengfea5a372021-10-11 18:38:47 +0000435 u8_data.extend([b0, b1, b2, b3])
436 elif self.dtype == DType.INT48:
437 for val in self.data:
438 val_u64 = np.uint64(val)
439 b0 = val_u64 & ByteMask
440 b1 = (val_u64 >> np.uint64(8)) & ByteMask
441 b2 = (val_u64 >> np.uint64(16)) & ByteMask
442 b3 = (val_u64 >> np.uint64(24)) & ByteMask
443 b4 = (val_u64 >> np.uint64(32)) & ByteMask
444 b5 = (val_u64 >> np.uint64(40)) & ByteMask
445 u8_data.extend([b0, b1, b2, b3, b4, b5])
446 elif self.dtype == DType.FLOAT:
447 for val in self.data:
448 b = struct.pack("!f", val)
449 u8_data.extend([b[3], b[2], b[1], b[0]])
450 else:
451 raise Exception(
452 "unsupported data type {}".format(DTypeNames[self.dtype])
453 )
454 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
455
456 TosaTensor.TosaTensorStart(builder)
457 TosaTensor.TosaTensorAddName(builder, fb_name)
458 TosaTensor.TosaTensorAddShape(builder, fb_shapes)
459 TosaTensor.TosaTensorAddType(builder, self.dtype)
460 if self.data:
461 TosaTensor.TosaTensorAddData(builder, fb_data)
462
463 return TosaTensor.TosaTensorEnd(builder)
464
465
466class TosaSerializerOperator:
467 def __init__(self, op, inputs, outputs, attributes=None, quantInfo=None):
468 self.op = op
469 self.attributes = attributes
470 self.inputs = TosaSerializer.toList(inputs)
471 self.outputs = TosaSerializer.toList(outputs)
472 self.quantInfo = quantInfo
473
474 def __str__(self):
475 str = "Op {}\n----\n".format(self.op)
476
477 for i in self.inputs:
478 str = str + " Input: {}\n".format(i)
479 for o in self.outputs:
480 str = str + " Output: {}\n".format(o)
481
482 return str
483
484 def serialize(self, builder):
485 fb_inputs = TosaSerializer.serializeStrVec(
486 builder, self.inputs, TosaOperator.TosaOperatorStartInputsVector
487 )
488 fb_outputs = TosaSerializer.serializeStrVec(
489 builder, self.outputs, TosaOperator.TosaOperatorStartOutputsVector
490 )
491 # Need to serialize quant_info and attributes enums still
492 if self.attributes is not None:
493 fb_attributes = self.attributes.serialize(builder)
494
495 if self.quantInfo is not None:
496 fb_qinfo = self.quantInfo.serialize(builder)
497
498 TosaOperator.TosaOperatorStart(builder)
499 TosaOperator.TosaOperatorAddOp(builder, self.op)
500 TosaOperator.TosaOperatorAddInputs(builder, fb_inputs)
501 TosaOperator.TosaOperatorAddOutputs(builder, fb_outputs)
502 if self.attributes is not None:
503 TosaOperator.TosaOperatorAddAttributeType(builder, self.attributes.utype)
504 TosaOperator.TosaOperatorAddAttribute(builder, fb_attributes)
505 if self.quantInfo is not None:
506 TosaOperator.TosaOperatorAddQuantInfoType(builder, self.quantInfo.utype)
507 TosaOperator.TosaOperatorAddQuantInfo(builder, fb_qinfo)
508
509 return TosaOperator.TosaOperatorEnd(builder)
510
511
512class TosaSerializerBasicBlock:
513 def __init__(self, name):
514 self.name = name
515 self.operators = []
516
517 # Dict assures uniqueness, but allows us to look up by name
518 self.tensors = dict()
519
520 self.inputs = []
521 self.outputs = []
522
523 def addTensor(
524 self,
525 name,
526 shape,
527 dtype,
528 data=None,
529 placeholderFilename=None,
530 ):
531 try:
532 # Someone already added this tensor.
533 tens = self.tensors[name]
534 except KeyError:
535 self.tensors[name] = TosaSerializerTensor(
536 name, shape, dtype, data, placeholderFilename
537 )
538
539 return self.tensors[name]
540
541 def addInput(self, name):
542 self.inputs.append(name)
543
544 def addOutput(self, name):
545 self.outputs.append(name)
546
547 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
548 self.operators.append(
549 TosaSerializerOperator(op, inputs, outputs, attributes, quant_info)
550 )
551
552 def serialize(self, builder):
553 fb_name = builder.CreateString(self.name)
554 fbv_inputs = TosaSerializer.serializeStrVec(
555 builder, list(self.inputs), TosaBasicBlock.TosaBasicBlockStartInputsVector
556 )
557 fbv_outputs = TosaSerializer.serializeStrVec(
558 builder, list(self.outputs), TosaBasicBlock.TosaBasicBlockStartOutputsVector
559 )
560 fbv_tensors = TosaSerializer.serializeObjVec(
561 builder,
562 list(self.tensors.values()),
563 TosaBasicBlock.TosaBasicBlockStartTensorsVector,
564 )
565 fbv_operators = TosaSerializer.serializeObjVec(
566 builder, self.operators, TosaBasicBlock.TosaBasicBlockStartOperatorsVector
567 )
568
569 TosaBasicBlock.TosaBasicBlockStart(builder)
570 TosaBasicBlock.TosaBasicBlockAddName(builder, fb_name)
571 TosaBasicBlock.TosaBasicBlockAddInputs(builder, fbv_inputs)
572 TosaBasicBlock.TosaBasicBlockAddOutputs(builder, fbv_outputs)
573 TosaBasicBlock.TosaBasicBlockAddTensors(builder, fbv_tensors)
574 TosaBasicBlock.TosaBasicBlockAddOperators(builder, fbv_operators)
575 return TosaBasicBlock.TosaBasicBlockEnd(builder)
576
577
578@unique
579class TensorDir(IntEnum):
580 PLACEHOLDER = 0
581 CONST = 1
582 INTERMEDIATE = 2
583 RESULT = 3
584
585
586class TosaSerializer:
587 def __init__(self, pathPrefix):
588
589 # Get the global TOSA version if not already defined
Kevin Chengfea5a372021-10-11 18:38:47 +0000590
591 self.builder = flatbuffers.Builder(0)
592
593 self.basicBlocks = []
594 self.startBasicBlock("main")
595 self.pathPrefix = pathPrefix
596
597 # Indicies used for adding/naming tensors
598 self.currInputIdx = 0
599 self.currConstIdx = 0
600 self.currLayerIdx = 1
601 self.currResultIdx = 0
602
603 # Is this an illegal test that is expected to fail?
604 self.expectedReturnCode = TosaReturnCode.VALID
605 self.expectedFailure = False
606 self.expectedFailureDesc = ""
607
608 def __str__(self):
609 str = ""
610 for bb in self.basicBlocks:
611 str = str + bb.__str__()
612 return str
613
614 def addPlaceholder(self, shape, dtype, vals):
615 if not self.currBasicBlock:
616 raise Exception("addTensor called without valid basic block")
617
618 name = "input-{}".format(self.currInputIdx)
619 filename = "{}.npy".format(name)
620 self.currInputIdx = self.currInputIdx + 1
621
622 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
623 # This is always an input to the block
624 self.currBasicBlock.addInput(name)
625
626 if vals is not None:
627 np.save(os.path.join(self.pathPrefix, filename), vals, False)
628
629 return tens
630
631 def addConst(self, shape, dtype, vals):
632 if not self.currBasicBlock:
633 raise Exception("addTensor called without valid basic block")
634
635 name = "const-{}".format(self.currInputIdx)
636 filename = "{}.npy".format(name)
637 self.currInputIdx = self.currInputIdx + 1
638
639 tens = self.currBasicBlock.addTensor(name, shape, dtype, vals)
640 # Add the operator now
641 self.currBasicBlock.addOperator(tosa.Op.Op().CONST, [], name)
642
643 return tens
644
645 def addIntermediate(self, shape, dtype):
646
647 if not self.currBasicBlock:
648 raise Exception("addTensor called without valid basic block")
649
650 name = "layer-{}".format(self.currLayerIdx)
651 self.currLayerIdx = self.currLayerIdx + 1
652
653 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
654
655 return tens
656
657 def addInputTensor(self, tensor):
658 self.currBasicBlock.addTensor(tensor.name, tensor.shape, tensor.dtype)
659 self.currBasicBlock.addInput(tensor.name)
660
661 def addOutputTensor(self, tensor):
662 self.currBasicBlock.addOutput(tensor.name)
663
664 def addOutput(self, shape, dtype):
665 if not self.currBasicBlock:
666 raise Exception("addTensor called without valid basic block")
667
668 name = "result-{}".format(self.currResultIdx)
669 self.currResultIdx = self.currResultIdx + 1
670
671 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
672 self.currBasicBlock.addOutput(name)
673 return tens
674
675 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
676
677 if op == tosa.Op.Op().CONST:
678 raise Exception("Use addConstTensor() to add CONST ops")
679
680 return self.currBasicBlock.addOperator(
681 op, inputs, outputs, attributes, quant_info
682 )
683
684 def setExpectedReturnCode(self, val, desc=""):
685
686 self.expectedReturnCode = val
687 self.expectedFailureDesc = desc
688
689 if val == TosaReturnCode.VALID:
690 self.expectedFailure = False
691 else:
692 # Unpredictable or error results are considered expected failures
693 # for conformance
694 self.expectedFailure = True
695
696 def serialize(self):
697
698 builder = self.builder
699
700 Version.VersionStart(builder)
701 Version.VersionAdd_major(builder, TOSA_VERSION[0])
702 Version.VersionAdd_minor(builder, TOSA_VERSION[1])
703 Version.VersionAdd_patch(builder, TOSA_VERSION[2])
Kevin Chengb97cb1d2021-10-14 11:53:39 -0700704 Version.VersionAdd_draft(builder, TOSA_VERSION[3])
Kevin Chengfea5a372021-10-11 18:38:47 +0000705 version = Version.VersionEnd(builder)
706
707 fbv_bb = TosaSerializer.serializeObjVec(
708 builder, self.basicBlocks, TosaGraph.TosaGraphStartBlocksVector
709 )
710
711 TosaGraph.TosaGraphStart(builder)
712 TosaGraph.TosaGraphAddVersion(builder, version)
713 TosaGraph.TosaGraphAddBlocks(builder, fbv_bb)
714 graph = TosaGraph.TosaGraphEnd(builder)
715
716 self.builder.Finish(graph)
717 return self.builder.Output()
718
719 def writeJson(self, tosa_filename):
720 """Write a json test file so that it is fairly easy to pick up the test
721 and generate commands for third party tool"""
722 test_desc = dict()
723
724 test_desc["tosa_file"] = tosa_filename
725 ifm_name = []
726 ifm_file = []
727 ofm_name = []
728 ofm_file = []
729
730 for b in self.basicBlocks:
731 if b.name == "main":
732 for i in b.inputs:
733 ifm_name.append(i)
734 ifm_file.append(b.tensors[i].placeholderFilename)
735 for o in b.outputs:
736 ofm_name.append(o)
737 # Make up an OFM filename here. One isn't generated until the reference tool is
738 # run, so any name is a good name
739 ofm_file.append("ref-{}.npy".format(o))
740
741 test_desc["ifm_name"] = ifm_name
742 test_desc["ifm_file"] = ifm_file
743 test_desc["ofm_name"] = ofm_name
744 test_desc["ofm_file"] = ofm_file
745 test_desc["expected_return_code"] = self.expectedReturnCode
746 test_desc["expected_failure"] = self.expectedFailure
747 if self.expectedFailureDesc:
748 test_desc["expected_failure_desc"] = self.expectedFailureDesc
749
750 return json.dumps(test_desc, indent=" ")
751
752 def startBasicBlock(self, name):
753 self.currBasicBlock = TosaSerializerBasicBlock(name)
754 self.basicBlocks.append(self.currBasicBlock)
755
756 @staticmethod
757 def serializeStrVec(builder, vec, start_fcn):
758 fb_strs = [builder.CreateString(i) for i in vec]
759 start_fcn(builder, len(fb_strs))
760 for s in fb_strs[::-1]:
761 builder.PrependUOffsetTRelative(s)
762 # This try/except block supports both the Flatbuffers 2.x and 1.x APIs,
763 # defaulting to 2.x. If/when Flatbuffers 1.x support is deprecated, the
764 # try block and builder.EndVector(len) function calls can be removed.
765 try:
766 return builder.EndVector()
767 except TypeError:
768 return builder.EndVector(len(fb_strs))
769
770 @staticmethod
771 def serializeUint8Vec(builder, vec):
772 builder.StartVector(1, len(vec), 8)
773 for v in vec[::-1]:
774 builder.PrependUint8(v)
775 try:
776 return builder.EndVector()
777 except TypeError:
778 return builder.EndVector(len(vec))
779
780 @staticmethod
781 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]
820