blob: b1c5dae72541cae8e1d0653794adb649cff53bcd [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
38# With the way flatc generates its python types, there is no programatic way
39# to get string names for the integer types. Manually maintain a string table
40# here.
41DType = tosa.DType.DType()
42DTypeNames = [
43 "UNKNOWN",
44 "BOOL",
45 "UINT8",
46 "INT4",
47 "INT8",
48 "INT16",
49 "INT32",
50 "INT48",
51 "FLOAT",
52]
53
54ByteMask = np.uint64(0xFF)
55
56
57def dtype_str_to_val(name):
58
59 for i in range(len(DTypeNames)):
60 if name.casefold() == DTypeNames[i].casefold():
61 return i
62 raise Exception("Unable to parse DType name {}".format(name))
63
64
65class TosaSerializerUnion:
66 """This class handles encapsulating and serializing union types into flatbuffers"""
67
68 def __init__(self):
69
70 # A tuple of the start and end functions. Set by the options constructors below
71 self.optFcns = None
72
73 # The type from the tosa.Options enumeration. Set by the options constructors below.
74 self.utype = None
75
76 # Each of these lists is a tuple of the add function and the
77 # value being added. Set by the options constructors below.
78 self.ints = []
79 self.bools = []
80 self.floats = []
81 self.strings = []
82 self.intvecs = []
83 self.fpvecs = []
84
85 def serialize(self, builder):
86
87 # We have to build strings and vectors first
88 strList = []
89 intVecList = []
90 fpVecList = []
91
92 for fcn, val in self.strings:
93 strList.append((fcn, builder.CreateString(val)))
94
95 for fcn, val in self.intvecs:
96 intVecList.append((fcn, TosaSerializer.serializeInt32Vec(builder, val)))
97
98 for fcn, val in self.fpvecs:
99 fpVecList.append((fcn, TosaSerializer.serializeFpVec(builder, val)))
100
101 startFcn, endFcn = self.optFcns
102
103 # Then serialize the options object from the list of primitives and
104 # other serialized values
105 startFcn(builder)
106 for fcn, val in self.ints:
107 fcn(builder, val)
108
109 for fcn, val in self.bools:
110 fcn(builder, val)
111
112 for fcn, val in self.floats:
113 fcn(builder, val)
114
115 for fcn, val in strList:
116 fcn(builder, val)
117
118 for fcn, val in intVecList:
119 fcn(builder, val)
120
121 for fcn, val in fpVecList:
122 fcn(builder, val)
123
124 return endFcn(builder)
125
126
127class TosaSerializerAttribute(TosaSerializerUnion):
128 """This class handles encapsulating all of the enumerated types for attributes"""
129
130 def __init__(self):
131 super().__init__()
132
133 def PoolAttribute(self, kernel, stride, padding):
134 from tosa import PoolAttribute as a, Attribute
135
136 self.utype = Attribute.Attribute().PoolAttribute
137
138 self.optFcns = (a.PoolAttributeStart, a.PoolAttributeEnd)
139 self.intvecs.append((a.PoolAttributeAddPadding, padding))
140 self.intvecs.append((a.PoolAttributeAddKernel, kernel))
141 self.intvecs.append((a.PoolAttributeAddStride, stride))
142
143 def ConvAttribute(self, padding, stride, dilation):
144 from tosa import ConvAttribute as a, Attribute
145
146 self.utype = Attribute.Attribute().ConvAttribute
147 self.optFcns = (a.ConvAttributeStart, a.ConvAttributeEnd)
148
149 self.intvecs.append((a.ConvAttributeAddPadding, padding))
150 self.intvecs.append((a.ConvAttributeAddStride, stride))
151 self.intvecs.append((a.ConvAttributeAddDilation, dilation))
152
153 def TransposeConvAttribute(self, outpad, stride, dilation, output_shape):
154 from tosa import TransposeConvAttribute as a, Attribute
155
156 self.utype = Attribute.Attribute().TransposeConvAttribute
157 self.optFcns = (a.TransposeConvAttributeStart, a.TransposeConvAttributeEnd)
158
159 self.intvecs.append((a.TransposeConvAttributeAddOutpad, outpad))
160 self.intvecs.append((a.TransposeConvAttributeAddStride, stride))
161 self.intvecs.append((a.TransposeConvAttributeAddDilation, dilation))
162 self.intvecs.append((a.TransposeConvAttributeAddOutputShape, output_shape))
163
164 def ReluNAttribute(self, maxint, maxfp):
165 from tosa import ReluNAttribute as a, Attribute
166
167 self.utype = Attribute.Attribute().ReluNAttribute
168 self.optFcns = (a.ReluNAttributeStart, a.ReluNAttributeEnd)
169
170 self.ints.append((a.ReluNAttributeAddMaxInt, maxint))
171 self.ints.append((a.ReluNAttributeAddMaxFp, maxfp))
172
173 def AxisAttribute(self, axis):
174 from tosa import AxisAttribute as a, Attribute
175
176 self.utype = Attribute.Attribute().AxisAttribute
177 self.optFcns = (a.AxisAttributeStart, a.AxisAttributeEnd)
178
179 self.ints.append((a.AxisAttributeAddAxis, axis))
180
181 def ReshapeAttribute(self, shape):
182 from tosa import ReshapeAttribute as a, Attribute
183
184 self.utype = Attribute.Attribute().ReshapeAttribute
185 self.optFcns = (a.ReshapeAttributeStart, a.ReshapeAttributeEnd)
186
187 self.intvecs.append((a.ReshapeAttributeAddShape, shape))
188
189 def SliceAttribute(self, begin, size):
190 from tosa import SliceAttribute as a, Attribute
191
192 self.utype = Attribute.Attribute().SliceAttribute
193 self.optFcns = (a.SliceAttributeStart, a.SliceAttributeEnd)
194
195 self.intvecs.append((a.SliceAttributeAddBegin, begin))
196 self.intvecs.append((a.SliceAttributeAddSize, size))
197
198 def TileAttribute(self, multiples):
199 from tosa import TileAttribute as a, Attribute
200
201 self.utype = Attribute.Attribute().TileAttribute
202 self.optFcns = (a.TileAttributeStart, a.TileAttributeEnd)
203
204 self.intvecs.append((a.TileAttributeAddMultiples, multiples))
205
206 def ResizeAttribute(
207 self, output_size, stride, offset, shift, stride_fp, offset_fp, mode
208 ):
209 from tosa import ResizeAttribute as a, Attribute
210
211 self.utype = Attribute.Attribute().ResizeAttribute
212 self.optFcns = (a.ResizeAttributeStart, a.ResizeAttributeEnd)
213
214 self.intvecs.append((a.ResizeAttributeAddOutputSize, output_size))
215 self.intvecs.append((a.ResizeAttributeAddStride, stride))
216 self.intvecs.append((a.ResizeAttributeAddOffset, offset))
217 self.ints.append((a.ResizeAttributeAddShift, shift))
218 self.fpvecs.append((a.ResizeAttributeAddStrideFp, stride_fp))
219 self.fpvecs.append((a.ResizeAttributeAddOffsetFp, offset_fp))
220 self.ints.append((a.ResizeAttributeAddMode, mode))
221
222 def ClampAttribute(self, minint, maxint, minfp, maxfp):
223 from tosa import ClampAttribute as a, Attribute
224
225 self.utype = Attribute.Attribute().ClampAttribute
226 self.optFcns = (a.ClampAttributeStart, a.ClampAttributeEnd)
227
228 self.ints.append((a.ClampAttributeAddMinInt, minint))
229 self.ints.append((a.ClampAttributeAddMaxInt, maxint))
230
231 self.ints.append((a.ClampAttributeAddMinFp, minfp))
232 self.ints.append((a.ClampAttributeAddMaxFp, maxfp))
233
234 def RescaleAttribute(
235 self, input_zp, output_zp, multiplier, shift, scale32, double_round, per_channel
236 ):
237 from tosa import RescaleAttribute as a, Attribute
238
239 self.utype = Attribute.Attribute().RescaleAttribute
240 self.optFcns = (a.RescaleAttributeStart, a.RescaleAttributeEnd)
241
242 self.ints.append((a.RescaleAttributeAddInputZp, input_zp))
243 self.ints.append((a.RescaleAttributeAddOutputZp, output_zp))
244 self.intvecs.append((a.RescaleAttributeAddMultiplier, multiplier))
245 self.intvecs.append((a.RescaleAttributeAddShift, shift))
246 self.bools.append((a.RescaleAttributeAddScale32, scale32))
247 self.bools.append((a.RescaleAttributeAddDoubleRound, double_round))
248 self.bools.append((a.RescaleAttributeAddPerChannel, per_channel))
249
250 def MulAttribute(self, shift):
251 from tosa import MulAttribute as a, Attribute
252
253 self.utype = Attribute.Attribute().MulAttribute
254 self.optFcns = (a.MulAttributeStart, a.MulAttributeEnd)
255
256 self.ints.append((a.MulAttributeAddShift, shift))
257
258 def ArithmeticRightShiftAttribute(self, round):
259 from tosa import ArithmeticRightShiftAttribute as a, Attribute
260
261 self.utype = Attribute.Attribute().ArithmeticRightShiftAttribute
262 self.optFcns = (
263 a.ArithmeticRightShiftAttributeStart,
264 a.ArithmeticRightShiftAttributeEnd,
265 )
266
267 self.bools.append((a.ArithmeticRightShiftAttributeAddRound, round))
268
269 def CustomAttribute(self, identifier):
270 from tosa import CustomAttribute as a, Attribute
271
272 self.utype = Attribute.Attribute().CustomAttribute
273 self.optFcns = (a.CustomAttributeStart, a.CustomAttributeEnd)
274
275 self.strings.append((a.CustomAttributeAddIdentifier, identifier))
276
277 def CondIfAttribute(self, then_branch, else_branch):
278 from tosa import CondIfAttribute as a, Attribute
279
280 self.utype = Attribute.Attribute().CondIfAttribute
281 self.optFcns = (a.CondIfAttributeStart, a.CondIfAttributeEnd)
282
283 self.strings.append((a.CondIfAttributeAddThenBranch, then_branch))
284 self.strings.append((a.CondIfAttributeAddElseBranch, else_branch))
285
286 def WhileLoopAttribute(self, cond_branch, body_branch):
287 from tosa import WhileLoopAttribute as a, Attribute
288
289 self.utype = Attribute.Attribute().WhileLoopAttribute
290 self.optFcns = (a.WhileLoopAttributeStart, a.WhileLoopAttributeEnd)
291
292 self.strings.append((a.WhileLoopAttributeAddCondBranch, cond_branch))
293 self.strings.append((a.WhileLoopAttributeAddBodyBranch, body_branch))
294
295
296class TosaSerializerQuantInfo(TosaSerializerUnion):
297 """This class handles encapsulating all of the enumerated types for quantinfo types"""
298
299 def __init__(self):
300 super().__init__()
301
302 def ConvQuantInfo(self, input_zp, weight_zp):
303 from tosa import ConvQuantInfo as q, QuantInfo
304
305 self.utype = QuantInfo.QuantInfo().ConvQuantInfo
306 self.optFcns = (q.ConvQuantInfoStart, q.ConvQuantInfoEnd)
307 self.ints.append((q.ConvQuantInfoAddInputZp, input_zp))
308 self.ints.append((q.ConvQuantInfoAddWeightZp, weight_zp))
309
310 def UnaryQuantInfo(self, input_zp, output_zp):
311 from tosa import UnaryQuantInfo as q, QuantInfo
312
313 self.utype = QuantInfo.QuantInfo().UnaryQuantInfo
314 self.optFcns = (q.UnaryQuantInfoStart, q.UnaryQuantInfoEnd)
315 self.ints.append((q.UnaryQuantInfoAddInputZp, input_zp))
316 self.ints.append((q.UnaryQuantInfoAddOutputZp, output_zp))
317
318 def MatMulQuantInfo(self, a_zp, b_zp):
319 from tosa import MatMulQuantInfo as q, QuantInfo
320
321 self.utype = QuantInfo.QuantInfo().MatMulQuantInfo
322 self.optFcns = (q.MatMulQuantInfoStart, q.MatMulQuantInfoEnd)
323 self.ints.append((q.MatMulQuantInfoAddAZp, a_zp))
324 self.ints.append((q.MatMulQuantInfoAddBZp, b_zp))
325
326 def PadQuantInfo(self, input_zp):
327 from tosa import PadQuantInfo as q, QuantInfo
328
329 self.utype = QuantInfo.QuantInfo().PadQuantInfo
330 self.optFcns = (q.PadQuantInfoStart, q.PadQuantInfoEnd)
331 self.ints.append((q.PadQuantInfoAddInputZp, input_zp))
332
333
334class TosaSerializerTensor:
335 def __init__(
336 self,
337 name,
338 shape,
339 dtype,
340 data=None,
341 placeholderFilename=None,
342 ):
343 self.name = name
344
345 if isinstance(shape, np.ndarray):
346 shape = shape.astype(int).tolist()
347 shape = list(map(int, shape))
348
349 self.shape = shape
350 self.dtype = dtype
351
352 if isinstance(data, np.ndarray):
353 data = data.flatten().astype(int).tolist()
354 data = list(map(int, data))
355 self.data = data
356 elif isinstance(data, list):
357 data = list(map(int, data))
358 self.data = data
359 else:
360 self.data = None
361
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):
369 str = "TosaSerializerTensor name: {} shape: {} dtype: {}".format(
370 self.name,
371 self.shape,
372 DTypeNames[self.dtype],
373 )
374 return str
375
376 def setDtype(self, dtype):
377 self.dtype = dtype
378
379 def serialize(self, builder):
380 fb_name = builder.CreateString(self.name)
381 fb_shapes = TosaSerializer.serializeInt32Vec(builder, self.shape)
382 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)
389 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)
401 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(
435 "unsupported data type {}".format(DTypeNames[self.dtype])
436 )
437 fb_data = TosaSerializer.serializeUint8Vec(builder, u8_data)
438
439 TosaTensor.TosaTensorStart(builder)
440 TosaTensor.TosaTensorAddName(builder, fb_name)
441 TosaTensor.TosaTensorAddShape(builder, fb_shapes)
442 TosaTensor.TosaTensorAddType(builder, self.dtype)
443 if self.data:
444 TosaTensor.TosaTensorAddData(builder, fb_data)
445
446 return TosaTensor.TosaTensorEnd(builder)
447
448
449class TosaSerializerOperator:
450 def __init__(self, op, inputs, outputs, attributes=None, quantInfo=None):
451 self.op = op
452 self.attributes = attributes
453 self.inputs = TosaSerializer.toList(inputs)
454 self.outputs = TosaSerializer.toList(outputs)
455 self.quantInfo = quantInfo
456
457 def __str__(self):
458 str = "Op {}\n----\n".format(self.op)
459
460 for i in self.inputs:
461 str = str + " Input: {}\n".format(i)
462 for o in self.outputs:
463 str = str + " Output: {}\n".format(o)
464
465 return str
466
467 def serialize(self, builder):
468 fb_inputs = TosaSerializer.serializeStrVec(
469 builder, self.inputs, TosaOperator.TosaOperatorStartInputsVector
470 )
471 fb_outputs = TosaSerializer.serializeStrVec(
472 builder, self.outputs, TosaOperator.TosaOperatorStartOutputsVector
473 )
474 # Need to serialize quant_info and attributes enums still
475 if self.attributes is not None:
476 fb_attributes = self.attributes.serialize(builder)
477
478 if self.quantInfo is not None:
479 fb_qinfo = self.quantInfo.serialize(builder)
480
481 TosaOperator.TosaOperatorStart(builder)
482 TosaOperator.TosaOperatorAddOp(builder, self.op)
483 TosaOperator.TosaOperatorAddInputs(builder, fb_inputs)
484 TosaOperator.TosaOperatorAddOutputs(builder, fb_outputs)
485 if self.attributes is not None:
486 TosaOperator.TosaOperatorAddAttributeType(builder, self.attributes.utype)
487 TosaOperator.TosaOperatorAddAttribute(builder, fb_attributes)
488 if self.quantInfo is not None:
489 TosaOperator.TosaOperatorAddQuantInfoType(builder, self.quantInfo.utype)
490 TosaOperator.TosaOperatorAddQuantInfo(builder, fb_qinfo)
491
492 return TosaOperator.TosaOperatorEnd(builder)
493
494
495class TosaSerializerBasicBlock:
496 def __init__(self, name):
497 self.name = name
498 self.operators = []
499
500 # Dict assures uniqueness, but allows us to look up by name
501 self.tensors = dict()
502
503 self.inputs = []
504 self.outputs = []
505
506 def addTensor(
507 self,
508 name,
509 shape,
510 dtype,
511 data=None,
512 placeholderFilename=None,
513 ):
514 try:
515 # Someone already added this tensor.
516 tens = self.tensors[name]
517 except KeyError:
518 self.tensors[name] = TosaSerializerTensor(
519 name, shape, dtype, data, placeholderFilename
520 )
521
522 return self.tensors[name]
523
524 def addInput(self, name):
525 self.inputs.append(name)
526
527 def addOutput(self, name):
528 self.outputs.append(name)
529
530 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
531 self.operators.append(
532 TosaSerializerOperator(op, inputs, outputs, attributes, quant_info)
533 )
534
535 def serialize(self, builder):
536 fb_name = builder.CreateString(self.name)
537 fbv_inputs = TosaSerializer.serializeStrVec(
538 builder, list(self.inputs), TosaBasicBlock.TosaBasicBlockStartInputsVector
539 )
540 fbv_outputs = TosaSerializer.serializeStrVec(
541 builder, list(self.outputs), TosaBasicBlock.TosaBasicBlockStartOutputsVector
542 )
543 fbv_tensors = TosaSerializer.serializeObjVec(
544 builder,
545 list(self.tensors.values()),
546 TosaBasicBlock.TosaBasicBlockStartTensorsVector,
547 )
548 fbv_operators = TosaSerializer.serializeObjVec(
549 builder, self.operators, TosaBasicBlock.TosaBasicBlockStartOperatorsVector
550 )
551
552 TosaBasicBlock.TosaBasicBlockStart(builder)
553 TosaBasicBlock.TosaBasicBlockAddName(builder, fb_name)
554 TosaBasicBlock.TosaBasicBlockAddInputs(builder, fbv_inputs)
555 TosaBasicBlock.TosaBasicBlockAddOutputs(builder, fbv_outputs)
556 TosaBasicBlock.TosaBasicBlockAddTensors(builder, fbv_tensors)
557 TosaBasicBlock.TosaBasicBlockAddOperators(builder, fbv_operators)
558 return TosaBasicBlock.TosaBasicBlockEnd(builder)
559
560
561@unique
562class TensorDir(IntEnum):
563 PLACEHOLDER = 0
564 CONST = 1
565 INTERMEDIATE = 2
566 RESULT = 3
567
568
569class TosaSerializer:
570 def __init__(self, pathPrefix):
571
572 # Get the global TOSA version if not already defined
573 try:
574 TOSA_VERSION
575 except NameError:
576 TosaSerializer.setTosaVersion()
577
578 self.builder = flatbuffers.Builder(0)
579
580 self.basicBlocks = []
581 self.startBasicBlock("main")
582 self.pathPrefix = pathPrefix
583
584 # Indicies used for adding/naming tensors
585 self.currInputIdx = 0
586 self.currConstIdx = 0
587 self.currLayerIdx = 1
588 self.currResultIdx = 0
589
590 # Is this an illegal test that is expected to fail?
591 self.expectedReturnCode = TosaReturnCode.VALID
592 self.expectedFailure = False
593 self.expectedFailureDesc = ""
594
595 def __str__(self):
596 str = ""
597 for bb in self.basicBlocks:
598 str = str + bb.__str__()
599 return str
600
601 def addPlaceholder(self, shape, dtype, vals):
602 if not self.currBasicBlock:
603 raise Exception("addTensor called without valid basic block")
604
605 name = "input-{}".format(self.currInputIdx)
606 filename = "{}.npy".format(name)
607 self.currInputIdx = self.currInputIdx + 1
608
609 tens = self.currBasicBlock.addTensor(name, shape, dtype, None, filename)
610 # This is always an input to the block
611 self.currBasicBlock.addInput(name)
612
613 if vals is not None:
614 np.save(os.path.join(self.pathPrefix, filename), vals, False)
615
616 return tens
617
618 def addConst(self, shape, dtype, vals):
619 if not self.currBasicBlock:
620 raise Exception("addTensor called without valid basic block")
621
622 name = "const-{}".format(self.currInputIdx)
623 filename = "{}.npy".format(name)
624 self.currInputIdx = self.currInputIdx + 1
625
626 tens = self.currBasicBlock.addTensor(name, shape, dtype, vals)
627 # Add the operator now
628 self.currBasicBlock.addOperator(tosa.Op.Op().CONST, [], name)
629
630 return tens
631
632 def addIntermediate(self, shape, dtype):
633
634 if not self.currBasicBlock:
635 raise Exception("addTensor called without valid basic block")
636
637 name = "layer-{}".format(self.currLayerIdx)
638 self.currLayerIdx = self.currLayerIdx + 1
639
640 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
641
642 return tens
643
644 def addInputTensor(self, tensor):
645 self.currBasicBlock.addTensor(tensor.name, tensor.shape, tensor.dtype)
646 self.currBasicBlock.addInput(tensor.name)
647
648 def addOutputTensor(self, tensor):
649 self.currBasicBlock.addOutput(tensor.name)
650
651 def addOutput(self, shape, dtype):
652 if not self.currBasicBlock:
653 raise Exception("addTensor called without valid basic block")
654
655 name = "result-{}".format(self.currResultIdx)
656 self.currResultIdx = self.currResultIdx + 1
657
658 tens = self.currBasicBlock.addTensor(name, shape, dtype, None)
659 self.currBasicBlock.addOutput(name)
660 return tens
661
662 def addOperator(self, op, inputs, outputs, attributes=None, quant_info=None):
663
664 if op == tosa.Op.Op().CONST:
665 raise Exception("Use addConstTensor() to add CONST ops")
666
667 return self.currBasicBlock.addOperator(
668 op, inputs, outputs, attributes, quant_info
669 )
670
671 def setExpectedReturnCode(self, val, desc=""):
672
673 self.expectedReturnCode = val
674 self.expectedFailureDesc = desc
675
676 if val == TosaReturnCode.VALID:
677 self.expectedFailure = False
678 else:
679 # Unpredictable or error results are considered expected failures
680 # for conformance
681 self.expectedFailure = True
682
683 def serialize(self):
684
685 builder = self.builder
686
687 Version.VersionStart(builder)
688 Version.VersionAdd_major(builder, TOSA_VERSION[0])
689 Version.VersionAdd_minor(builder, TOSA_VERSION[1])
690 Version.VersionAdd_patch(builder, TOSA_VERSION[2])
691 Version.VersionAdd_experimental(builder, TOSA_VERSION[3])
692 version = Version.VersionEnd(builder)
693
694 fbv_bb = TosaSerializer.serializeObjVec(
695 builder, self.basicBlocks, TosaGraph.TosaGraphStartBlocksVector
696 )
697
698 TosaGraph.TosaGraphStart(builder)
699 TosaGraph.TosaGraphAddVersion(builder, version)
700 TosaGraph.TosaGraphAddBlocks(builder, fbv_bb)
701 graph = TosaGraph.TosaGraphEnd(builder)
702
703 self.builder.Finish(graph)
704 return self.builder.Output()
705
706 def writeJson(self, tosa_filename):
707 """Write a json test file so that it is fairly easy to pick up the test
708 and generate commands for third party tool"""
709 test_desc = dict()
710
711 test_desc["tosa_file"] = tosa_filename
712 ifm_name = []
713 ifm_file = []
714 ofm_name = []
715 ofm_file = []
716
717 for b in self.basicBlocks:
718 if b.name == "main":
719 for i in b.inputs:
720 ifm_name.append(i)
721 ifm_file.append(b.tensors[i].placeholderFilename)
722 for o in b.outputs:
723 ofm_name.append(o)
724 # Make up an OFM filename here. One isn't generated until the reference tool is
725 # run, so any name is a good name
726 ofm_file.append("ref-{}.npy".format(o))
727
728 test_desc["ifm_name"] = ifm_name
729 test_desc["ifm_file"] = ifm_file
730 test_desc["ofm_name"] = ofm_name
731 test_desc["ofm_file"] = ofm_file
732 test_desc["expected_return_code"] = self.expectedReturnCode
733 test_desc["expected_failure"] = self.expectedFailure
734 if self.expectedFailureDesc:
735 test_desc["expected_failure_desc"] = self.expectedFailureDesc
736
737 return json.dumps(test_desc, indent=" ")
738
739 def startBasicBlock(self, name):
740 self.currBasicBlock = TosaSerializerBasicBlock(name)
741 self.basicBlocks.append(self.currBasicBlock)
742
743 @staticmethod
744 def serializeStrVec(builder, vec, start_fcn):
745 fb_strs = [builder.CreateString(i) for i in vec]
746 start_fcn(builder, len(fb_strs))
747 for s in fb_strs[::-1]:
748 builder.PrependUOffsetTRelative(s)
749 # This try/except block supports both the Flatbuffers 2.x and 1.x APIs,
750 # defaulting to 2.x. If/when Flatbuffers 1.x support is deprecated, the
751 # try block and builder.EndVector(len) function calls can be removed.
752 try:
753 return builder.EndVector()
754 except TypeError:
755 return builder.EndVector(len(fb_strs))
756
757 @staticmethod
758 def serializeUint8Vec(builder, vec):
759 builder.StartVector(1, len(vec), 8)
760 for v in vec[::-1]:
761 builder.PrependUint8(v)
762 try:
763 return builder.EndVector()
764 except TypeError:
765 return builder.EndVector(len(vec))
766
767 @staticmethod
768 def serializeInt32Vec(builder, vec):
769 builder.StartVector(4, len(vec), 4)
770 for v in vec[::-1]:
771 builder.PrependInt32(v)
772 try:
773 return builder.EndVector()
774 except TypeError:
775 return builder.EndVector(len(vec))
776
777 @staticmethod
778 def serializeFpVec(builder, vec):
779 builder.StartVector(4, len(vec), 4)
780 for v in vec[::-1]:
781 builder.PrependFloat32(v)
782 try:
783 return builder.EndVector()
784 except TypeError:
785 return builder.EndVector(len(vec))
786
787 @staticmethod
788 def serializeObjVec(builder, vec, start_fcn):
789 serialized_vec = []
790 for v in vec[::-1]:
791 serialized_vec.append(v.serialize(builder))
792
793 start_fcn(builder, len(vec))
794 for v in serialized_vec:
795 builder.PrependUOffsetTRelative(v)
796 try:
797 return builder.EndVector()
798 except TypeError:
799 return builder.EndVector(len(vec))
800
801 @staticmethod
802 def toList(val):
803 if isinstance(val, list):
804 return val
805 else:
806 return [val]
807
808 @staticmethod
809 def setTosaVersion():
810 # Create a dummy flatbuffers file with the default version information
811 # There does not appear to be a better way to get a constant from a
812 # flatbuffer schema file
813 builder = flatbuffers.Builder(0)
814 Version.VersionStart(builder)
815 ver = Version.VersionEnd(builder)
816 TosaGraph.TosaGraphStart(builder)
817 TosaGraph.TosaGraphAddVersion(builder, ver)
818 gr = TosaGraph.TosaGraphEnd(builder)
819 builder.Finish(gr)
820
821 out = builder.Output()
822
823 gr = TosaGraph.TosaGraph()
824 root = gr.GetRootAsTosaGraph(out, 0)
825
826 # Store the version as a global variable so that it only needs to be
827 # generated once per process.
828 global TOSA_VERSION
829 TOSA_VERSION = [
830 root.Version()._major(),
831 root.Version()._minor(),
832 root.Version()._patch(),
833 root.Version()._experimental(),
834 ]