blob: 681f498971c38c03abb2c2ea5f8b11e1a999bf53 [file] [log] [blame]
Louis Verhaardebf4af62021-01-27 15:57:57 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Internal representation of a Neural Network Operation.
Louis Verhaarde8a5a782020-11-02 18:04:27 +010018import copy
Louis Verhaardaee5d752020-09-30 09:01:52 +020019from collections import namedtuple
20from enum import Enum
Dwight Lidman9b43f842020-12-08 17:56:44 +010021from typing import Any
22from typing import Dict
23from typing import List
Louis Verhaarde8a5a782020-11-02 18:04:27 +010024from typing import Optional
Louis Verhaardebf4af62021-01-27 15:57:57 +010025from typing import Tuple
Dwight Lidman9b43f842020-12-08 17:56:44 +010026from typing import TYPE_CHECKING
Tim Hall79d07d22020-04-27 18:20:16 +010027
Louis Verhaard1a92f782021-02-09 16:08:26 +010028from .api import NpuRoundingMode
Michael McGeagh528a56d2020-12-16 11:33:21 +000029from .errors import VelaError
Tim Hall4ed38bc2020-10-20 18:54:20 +010030from .numeric_util import full_shape
patrik.gustavssoneeb85152020-12-21 17:10:40 +000031from .shape4d import Shape4D
Tim Hall4ed38bc2020-10-20 18:54:20 +010032
Patrik Gustavsson2349d422020-12-01 16:02:29 +010033
Dwight Lidman9b43f842020-12-08 17:56:44 +010034if TYPE_CHECKING:
35 from .tensor import Tensor
36
Tim Hall4ed38bc2020-10-20 18:54:20 +010037PointXY = namedtuple("PointXY", "x y")
38PointXYZ = namedtuple("PointXYZ", "x y z")
39
Tim Hall79d07d22020-04-27 18:20:16 +010040
Louis Verhaardaee5d752020-09-30 09:01:52 +020041class NpuBlockType(Enum):
Tim Hall79d07d22020-04-27 18:20:16 +010042 Default = 0
43 ConvolutionMxN = 1
44 VectorProduct = 2
45 Pooling = 3
46 ConvolutionDepthWise = 4
47 ElementWise = 5
Fredrik Svedberga0c36242020-06-03 15:43:31 +020048 ReduceSum = 6
Tim Hall79d07d22020-04-27 18:20:16 +010049
50
Tim Hall4ed38bc2020-10-20 18:54:20 +010051class Kernel:
Louis Verhaarde8a5a782020-11-02 18:04:27 +010052 """
53 Kernel information for NPU operations
54 """
55
Tim Halld8339a72021-05-27 18:49:40 +010056 def __init__(
57 self,
58 w: int,
59 h: int,
60 stride_x: int = 1,
61 stride_y: int = 1,
62 dilation_x: int = 1,
63 dilation_y: int = 1,
64 valid_padding=False,
65 ):
Louis Verhaarde8a5a782020-11-02 18:04:27 +010066 assert stride_x > 0 and stride_y > 0
67 assert dilation_x > 0 and dilation_y > 0
Tim Hall4ed38bc2020-10-20 18:54:20 +010068 self.width = w
69 self.height = h
Louis Verhaarde8a5a782020-11-02 18:04:27 +010070 self.stride = PointXY(stride_x, stride_y)
71 self.dilation = PointXY(dilation_x, dilation_y)
Tim Halld8339a72021-05-27 18:49:40 +010072 self.valid_padding = valid_padding
Tim Hall4ed38bc2020-10-20 18:54:20 +010073
Louis Verhaarde8a5a782020-11-02 18:04:27 +010074 def elements_wh(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010075 return self.width * self.height
76
Louis Verhaarde8a5a782020-11-02 18:04:27 +010077 def area_width(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010078 return (self.width - 1) * self.dilation.x + 1
79
Louis Verhaarde8a5a782020-11-02 18:04:27 +010080 def area_height(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010081 return (self.height - 1) * self.dilation.y + 1
82
Tim Halld8339a72021-05-27 18:49:40 +010083 def dilation(self) -> PointXY:
84 return self.dilation
85
Louis Verhaardebf4af62021-01-27 15:57:57 +010086 def dilated_wh(self) -> Tuple[int, int]:
87 """Returns the dilated kernel width/height"""
88 return self.dilation.x * (self.width - 1) + 1, self.dilation.y * (self.height - 1) + 1
89
Louis Verhaarde8a5a782020-11-02 18:04:27 +010090 def __str__(self):
91 return f"w={self.width}, h={self.height}, stride={tuple(self.stride)}, dilation={tuple(self.dilation)}"
92
Tim Hall4ed38bc2020-10-20 18:54:20 +010093
Louis Verhaardaee5d752020-09-30 09:01:52 +020094# Classifies operators of type Custom
95class CustomType(Enum):
96 ThirdPartyOp = 0 # Third party custom op
97 NpuOp = 1 # NPU op
98 ExistingNpuOp = 2 # NPU op that was part of the input network
99
100
101TensorIndices = namedtuple("TensorIndices", ["ifms", "weights", "biases"])
102
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200103NNG_NO_INDICES = TensorIndices([], [], [])
104NNG_IFM_INDICES = TensorIndices([0], [], [])
105NNG_IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
106NNG_IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
107NNG_IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
108NNG_CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
109NNG_TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
110NNG_CONCAT_INDICES = TensorIndices([1, 2], [], [])
111NNG_SPLIT_IFM_INDICES = TensorIndices([1], [], [])
112NNG_BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
Louis Verhaardaee5d752020-09-30 09:01:52 +0200113
114
115# Static information related to operation codes
116class OperatorInfo:
117 __slots__ = ("id", "block_type", "indices", "is_unary")
118 _id = 0
119
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200120 def __init__(self, block_type=NpuBlockType.Default, indices=NNG_NO_INDICES, is_unary=False):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200121 OperatorInfo._id += 1
122 self.id = OperatorInfo._id
123 self.block_type = block_type
124 self.indices = indices # Indices of the different tensor purposes
125 self.is_unary = is_unary # Classifies elementwise operators
126
127
128# Internally used operation codes
129class Op(Enum):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200130 Abs = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_INDICES, is_unary=True)
131 Add = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200132 AddN = OperatorInfo()
133 Any = OperatorInfo()
134 ArgMax = OperatorInfo()
135 ArgMin = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200136 AvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200137 BatchMatMul = OperatorInfo()
138 BatchToSpaceND = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200139 BidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
140 BidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
141 BlockLSTM = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_BLOCK_LSTM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200142
143 CLZ = OperatorInfo(
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200144 block_type=NpuBlockType.ElementWise, indices=NNG_IFM_INDICES, is_unary=True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200145 ) # NPU specific operation
146 Call = OperatorInfo()
147 Cast = OperatorInfo()
148 Ceil = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200149 Clamp = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100150 Clip = OperatorInfo() # NPU specific fused activation function for clipping between activation.min/max
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200151 Concat = OperatorInfo(indices=NNG_CONCAT_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200152 ConcatEmbeddings = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200153 ConcatSliceWrite = OperatorInfo(indices=NNG_IFM_INDICES)
154 ConcatTFLite = OperatorInfo(indices=NNG_CONCAT_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200155 Const = OperatorInfo() # Constant tensor, only used in CPU subgraphs
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200156 Conv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_IFM_WEIGHTS_INDICES)
157 Conv2DBackpropInput = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_CONV2D_BACKPROP_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200158 Conv2DBackpropInputSwitchedBias = OperatorInfo(
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200159 block_type=NpuBlockType.ConvolutionMxN, indices=NNG_TRANSPOSE_CONV_INDICES
Louis Verhaardaee5d752020-09-30 09:01:52 +0200160 )
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200161 Conv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_IFM_WEIGHTS_BIAS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200162 Cos = OperatorInfo()
Tim Hall42abec12021-02-04 21:31:57 +0000163 Cumsum = OperatorInfo()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200164 Custom = OperatorInfo() # Custom 3rd party operator, only used in CPU subgraphs
165 CustomNpuOp = OperatorInfo() # NPU custom operator, only used in CPU subgraphs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200166 Delegate = OperatorInfo()
167 Densify = OperatorInfo()
168 DepthToSpace = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200169 DepthwiseConv2DBias = OperatorInfo(
170 block_type=NpuBlockType.ConvolutionDepthWise, indices=NNG_IFM_WEIGHTS_BIAS_INDICES
171 )
172 Dequantize = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200173 Div = OperatorInfo()
174 Elu = OperatorInfo()
175 EmbeddingLookup = OperatorInfo()
176 EmbeddingLookupSparse = OperatorInfo()
177 Equal = OperatorInfo()
178 Exp = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200179 ExpandDims = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200180 FakeQuantWithMinMaxArgs = OperatorInfo()
181 Fill = OperatorInfo()
182 Floor = OperatorInfo()
183 FloorDiv = OperatorInfo()
184 FloorMod = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200185 FullyConnected = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_BIAS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200186 GatherNd = OperatorInfo()
187 GatherV2 = OperatorInfo()
188 Greater = OperatorInfo()
189 GreaterEqual = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200190 HardSwish = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200191 HashtableLookup = OperatorInfo()
192 Identity = OperatorInfo()
193 If = OperatorInfo()
194 L2Norm = OperatorInfo()
195 L2Pool2D = OperatorInfo()
196 LRN = OperatorInfo()
197 LSHProjection = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200198 LeakyRelu = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_INDICES, is_unary=True)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200199 Less = OperatorInfo()
200 LessEqual = OperatorInfo()
201 Log = OperatorInfo()
202 LogSoftmax = OperatorInfo()
203 LogicalAnd = OperatorInfo()
204 LogicalNot = OperatorInfo()
205 LogicalOr = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200206 Lstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200207 LUT = OperatorInfo() # NPU specific, operator has LUT, only used in fused activation functions
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200208 MatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200209 MatrixDiag = OperatorInfo()
210 MatrixSetDiag = OperatorInfo()
211 Max = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200212 MaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
213 Maximum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
214 Mean = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200215 Min = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200216 Minimum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200217 MirrorPad = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200218 Mul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200219 Neg = OperatorInfo()
220 NonMaxSuppressionV4 = OperatorInfo()
221 NonMaxSuppressionV5 = OperatorInfo()
222 NotEqual = OperatorInfo()
223 OneHot = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200224 Pack = OperatorInfo(indices=NNG_IFM_INDICES)
225 PackReshaped = OperatorInfo(indices=NNG_IFM_INDICES)
226 Pad = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200227 PadV2 = OperatorInfo()
228 Placeholder = OperatorInfo() # Only used in CPU subgraphs
229 Pow = OperatorInfo()
230 Prelu = OperatorInfo()
231 Prod = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200232 Quantize = OperatorInfo(indices=NNG_IFM_INDICES)
233 QuantizedAvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
234 QuantizedConv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_IFM_WEIGHTS_INDICES)
235 QuantizedMatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
236 QuantizedMaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
237 QuantizedReshape = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200238 Range = OperatorInfo()
239 Rank = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200240 ReduceSum = OperatorInfo(block_type=NpuBlockType.ReduceSum, indices=NNG_IFM_INDICES)
241 Relu = OperatorInfo(indices=NNG_IFM_INDICES)
242 Relu6 = OperatorInfo(indices=NNG_IFM_INDICES)
243 ReluN1To1 = OperatorInfo(indices=NNG_IFM_INDICES)
244 ReluN = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
245 Rescale = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
246 RescaleAdd = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200247 RescaleMul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200248 Reshape = OperatorInfo(indices=NNG_IFM_INDICES)
249 ResizeBilinear = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200250 ResizeNearestNeighbor = OperatorInfo()
251 ReverseSequence = OperatorInfo()
252 ReverseV2 = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200253 Rnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200254 Round = OperatorInfo()
255 Rsqrt = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200256 SHL = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES) # NPU specific operation
257 SHR = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES) # NPU specific operation
Louis Verhaardaee5d752020-09-30 09:01:52 +0200258 ScatterNd = OperatorInfo()
259 SegmentSum = OperatorInfo()
260 Select = OperatorInfo()
261 SelectV2 = OperatorInfo()
262 Shape = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200263 Sigmoid = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200264 SignBit = OperatorInfo()
265 Sin = OperatorInfo()
266 SkipGram = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200267 Slice = OperatorInfo(indices=NNG_IFM_INDICES)
268 Softmax = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200269 SpaceToBatchND = OperatorInfo()
270 SpaceToDepth = OperatorInfo()
271 SparseToDense = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200272 Split = OperatorInfo(indices=NNG_SPLIT_IFM_INDICES)
273 SplitSliceRead = OperatorInfo(indices=NNG_IFM_INDICES)
274 SplitV = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200275 Sqrt = OperatorInfo()
276 Square = OperatorInfo()
277 SquaredDifference = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200278 Squeeze = OperatorInfo(indices=NNG_IFM_INDICES)
279 StridedSlice = OperatorInfo(indices=NNG_IFM_INDICES)
280 Sub = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200281 SubgraphInput = OperatorInfo() # Only used in CPU subgraphs
282 Sum = OperatorInfo()
283 Svdf = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200284 Tanh = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200285 Tile = OperatorInfo()
286 TopKV2 = OperatorInfo()
Patrik Gustavssondf995102021-08-23 15:33:59 +0200287 Transpose = OperatorInfo(indices=NNG_IFM_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200288 UnidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
289 UnidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200290 Unique = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200291 Unpack = OperatorInfo(indices=NNG_IFM_INDICES)
292 UnpackReshaped = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200293 Where = OperatorInfo()
294 While = OperatorInfo()
295 ZerosLike = OperatorInfo()
Dwight Lidman8a12da12021-07-19 13:43:05 +0200296 CallOnce = OperatorInfo()
297 BroadcastTo = OperatorInfo()
298 Rfft2D = OperatorInfo()
299 Conv3D = OperatorInfo()
300 Imag = OperatorInfo()
301 Real = OperatorInfo()
302 ComplexAbs = OperatorInfo()
303 Hashtable = OperatorInfo()
304 HashtableFind = OperatorInfo()
305 HashtableImport = OperatorInfo()
306 HashtableSize = OperatorInfo()
307 ReduceAll = OperatorInfo()
308 Conv3DTranspose = OperatorInfo()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200309
310 @property
311 def info(self):
312 return self.value
313
314 @property
315 def npu_block_type(self):
316 return self.info.block_type
317
318 def is_conv2d_op(self):
319 return self.info.block_type == NpuBlockType.ConvolutionMxN
320
321 def is_depthwise_conv2d_op(self):
322 return self.info.block_type == NpuBlockType.ConvolutionDepthWise
323
324 def is_pool_op(self):
325 return self.info.block_type == NpuBlockType.Pooling
326
327 def is_maxpool_op(self):
328 return self in (Op.MaxPool, Op.QuantizedMaxPool)
329
330 def is_avgpool_op(self):
331 return self in (Op.QuantizedAvgPool, Op.AvgPool)
332
333 def is_elementwise_op(self):
334 return self.info.block_type == NpuBlockType.ElementWise
335
336 def is_unary_elementwise_op(self):
337 return self.info.block_type == NpuBlockType.ElementWise and self.info.is_unary
338
339 def is_binary_elementwise_op(self):
340 return self.info.block_type == NpuBlockType.ElementWise and not self.info.is_unary
341
342 def is_relu_op(self):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200343 return self in (Op.Relu, Op.Relu6, Op.ReluN1To1, Op.ReluN, Op.Clip, Op.Clamp)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200344
345 def is_activation_op(self):
Diqing Zhong189f7482021-01-26 12:12:51 +0100346 return self.is_relu_op() or self in (Op.Tanh, Op.Sigmoid, Op.Softmax, Op.LUT, Op.HardSwish)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200347
348 def is_split_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100349 return self in (Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200350
351 def is_concat_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100352 return self in (Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200353
354 def needs_bias(self):
355 return bool(self.info.indices.biases)
356
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100357 def needs_shapes(self):
358 return bool(self.info.indices.ifms)
359
Louis Verhaardaee5d752020-09-30 09:01:52 +0200360 @classmethod
361 def op_set(cls, predicate):
362 # Returns the set of all operator codes that fulfill the given predicate
363 return {op_type for op_type in Op if predicate(op_type)}
364
365 def __str__(self):
366 return self.name
367
368 __repr__ = __str__
369
370 def __lt__(self, other):
371 return self.value.id < other.value.id
372
373
Michael McGeagh16895482020-12-14 15:51:20 +0000374class Padding(Enum):
375 SAME = 0
376 VALID = 1
Louis Verhaardae2d5532020-12-11 17:19:54 +0100377 EXPLICIT = 2 # Padding is specified in a PAD operation (only used for NPU operations)
Michael McGeagh16895482020-12-14 15:51:20 +0000378
379
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100380class ActivationFunction:
381 """Fused activation function"""
382
383 def __init__(self, op_type: Op):
384 self.op_type = op_type # The activation operation to be performed
385 # min/max are optional; if present they are non-quantized values
386 self.min: Optional[float] = None
387 self.max: Optional[float] = None
388 # Table lookup index, only applicable for Op.LUT activation, 0-7
389 self.lut_index: int = 0
390
391 def clone(self):
392 res = copy.copy(self)
393 return res
394
395
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200396class ExplicitScaling:
397 """Explicit scaling parameters"""
398
399 def __init__(self, per_channel, shift, multiplier):
400 self.per_channel = per_channel
401 self.shift = shift
402 self.multiplier = multiplier
403
404 def clone(self):
405 res = copy.copy(self)
406 return res
407
408
409def create_activation_function(op_type: Op, min=None, max=None) -> ActivationFunction:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100410 """Creates activation function with min/max depending on op_type"""
411 act = ActivationFunction(op_type)
412 if op_type == Op.Relu:
413 act.min = 0.0
414 elif op_type == Op.Relu6:
415 act.min = 0.0
416 act.max = 6.0
417 elif op_type == Op.ReluN1To1:
418 act.min = -1.0
419 act.max = 1.0
420 elif op_type == Op.Tanh:
421 act.min = -1.0
422 act.max = 1.0
423 elif op_type == Op.Sigmoid:
424 act.min = 0.0
425 act.max = 1.0
Diqing Zhong189f7482021-01-26 12:12:51 +0100426 elif op_type == Op.HardSwish:
427 act.min = 0.0
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200428 if op_type == Op.Clamp:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200429 assert min is not None and max is not None
430 act.min = min
431 act.max = max
432 elif op_type == Op.ReluN:
433 assert max is not None
434 act.min = 0.0
435 act.max = max
436
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100437 return act
438
439
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000440def get_slice_offsets(input_shape: List[int], offset_tens: int, offset_mask: int, is_begin: bool = True):
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200441 # For strided slice operator: get start or end offsets
442 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
443 for idx in range(len(input_shape)):
444 # If the i:th bit in the mask is set then the value on offset_tens[i] should be ignored
445 if (offset_mask & (1 << idx)) == 0:
446 offsets[idx] = offset_tens.values[idx]
447 if offsets[idx] < 0:
448 # Convert offset to positive value
449 offsets[idx] += input_shape[idx]
450 return offsets
451
452
Tim Hall79d07d22020-04-27 18:20:16 +0100453class Operation:
454 """Class representing a Neural Network operation. Has a name, a type,
Dwight Lidmanc6ac1942020-10-02 14:55:45 +0200455 input and output tensors, as well as an attribute dictionary."""
Tim Hall79d07d22020-04-27 18:20:16 +0100456
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200457 __slots__ = (
458 "type",
459 "name",
460 "op_index",
461 "attrs",
462 "inputs",
463 "outputs",
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100464 "intermediates",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200465 "flops",
466 "scheduled_pass",
467 "run_on_npu",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200468 "activation",
469 "memory_function",
Dwight Lidman4f728c02020-12-17 15:14:45 +0100470 "forced_input_quantization",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200471 "forced_output_quantization",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200472 "activation_lut",
Tim Hall4ed38bc2020-10-20 18:54:20 +0100473 "_kernel",
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100474 "ifm_shapes",
475 "ofm_shapes",
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100476 "rescale",
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100477 "read_offsets",
Tim Halld8339a72021-05-27 18:49:40 +0100478 "read_shapes",
Louis Verhaard1a92f782021-02-09 16:08:26 +0100479 "rounding_mode",
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200480 "explicit_scaling",
Dwight Lidman4f728c02020-12-17 15:14:45 +0100481 "low_precision_scaling",
Louis Verhaardc822d622021-03-11 14:59:06 +0100482 "write_offset",
483 "write_shape",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200484 )
Tim Hall79d07d22020-04-27 18:20:16 +0100485
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100486 def __init__(self, op_type: Op, name: str):
Tim Hall79d07d22020-04-27 18:20:16 +0100487 self.type = op_type
488 self.name = name
Dwight Lidman9b43f842020-12-08 17:56:44 +0100489 self.attrs: Dict[str, Any] = {}
490 self.inputs: List[Tensor] = []
491 self.outputs: List[Tensor] = []
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100492 self.intermediates: List[Tensor] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100493 self.flops = 0
494 self.run_on_npu = True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200495 # Fused activation function. If not none: operator code.
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100496 self.activation: Optional[ActivationFunction] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200497 # Fused memory function, if not None: operator code
Louis Verhaardc822d622021-03-11 14:59:06 +0100498 self.memory_function: Optional[Op] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200499 # If not none: contains QuantizationParameters to be used as output quantization
500 # (which overrides the ofm tensor's quantization), used in LUT
Dwight Lidman4f728c02020-12-17 15:14:45 +0100501 self.forced_input_quantization = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200502 self.forced_output_quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100503 self.scheduled_pass = None
Tim Hallc8310b12020-06-17 14:53:11 +0100504 self.op_index = None # input network operator index
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200505 self.activation_lut = None
Tim Hall4ed38bc2020-10-20 18:54:20 +0100506 self._kernel = None
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000507 self.ifm_shapes: List[Shape4D] = []
508 self.ofm_shapes: List[Shape4D] = []
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100509 # If not none: contains rescale to be used as output scaling
510 # (which overrides the ofm tensor's scale)
511 self.rescale = None
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100512 self.read_offsets: List[Shape4D] = [None, None] # offset for [ifm, ifm2]
Tim Halld8339a72021-05-27 18:49:40 +0100513 self.read_shapes: List[Shape4D] = [None, None] # read shape for [ifm, ifm2]
Louis Verhaard1a92f782021-02-09 16:08:26 +0100514 self.rounding_mode: Optional[NpuRoundingMode] = None
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200515 # Rescale op in TOSA supplies explicit multiplier and shift values
516 self.explicit_scaling: Optional[ExplicitScaling] = None
Dwight Lidman4f728c02020-12-17 15:14:45 +0100517 # The Mean operator (implemented as a depthwise convolution) requires scaling
518 # to be calculated differently in one case. In that case, this is set to True.
519 self.low_precision_scaling = False
Louis Verhaardc822d622021-03-11 14:59:06 +0100520 # Write offset, for operations that only produce a part of the OFM
521 self.write_offset: Optional[Shape4D] = None
522 # The amount of OFM that is produced by the operation (only if write_offset is not None).
523 # E.g. an operation that only fills the bottom row of an OFM of size 1x10x8x1 would have
524 # write_offset 0,9,0,0, write_shape 1,1,8,1
525 self.write_shape: Optional[Shape4D] = None
Tim Hall79d07d22020-04-27 18:20:16 +0100526
527 def clone(self, suffix="_clone"):
528 res = Operation(self.type, self.name + suffix)
529
530 res.attrs = dict(self.attrs)
531 res.inputs = list(self.inputs)
532 res.outputs = list(self.outputs)
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100533 res.intermediates = list(self.intermediates)
Tim Hall79d07d22020-04-27 18:20:16 +0100534 res.flops = self.flops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200535 res.run_on_npu = self.run_on_npu
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100536 res.activation = None if self.activation is None else self.activation.clone()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200537 res.memory_function = self.memory_function
Dwight Lidman4f728c02020-12-17 15:14:45 +0100538 res.forced_input_quantization = self.forced_input_quantization
Louis Verhaardaee5d752020-09-30 09:01:52 +0200539 res.forced_output_quantization = self.forced_output_quantization
Tim Hall79d07d22020-04-27 18:20:16 +0100540 res.scheduled_pass = self.scheduled_pass
Tim Hallc8310b12020-06-17 14:53:11 +0100541 res.op_index = None # not relevant as not part of input network
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100542 res.read_offsets = list(self.read_offsets)
Tim Halld8339a72021-05-27 18:49:40 +0100543 res.read_shapes = list(self.read_shapes)
Louis Verhaard1a92f782021-02-09 16:08:26 +0100544 res.rounding_mode = self.rounding_mode
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200545 res.explicit_scaling = self.explicit_scaling
Dwight Lidman4f728c02020-12-17 15:14:45 +0100546 res.low_precision_scaling = self.low_precision_scaling
Tim Hall79d07d22020-04-27 18:20:16 +0100547
548 return res
549
550 def __str__(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200551 return "<nng.Operation '{}' type={}>".format(self.name, self.type)
Tim Hall79d07d22020-04-27 18:20:16 +0100552
553 __repr__ = __str__
554
Michael McGeagh65fd9982020-10-20 11:49:28 +0100555 def get_kernel_size(self):
Tim Hall4ed38bc2020-10-20 18:54:20 +0100556 weights = self.weights
557 if weights and self.type.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.ConvolutionMxN):
558 weight_shape = full_shape(4, weights.shape, 1)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100559 h = weight_shape[-4]
560 w = weight_shape[-3]
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100561 elif self.type.npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum) and "ksize" in self.attrs:
562 h, w = self.attrs["ksize"][1:3]
Tim Hall4ed38bc2020-10-20 18:54:20 +0100563 else:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100564 h = self.attrs.get("filter_height", 1)
565 w = self.attrs.get("filter_width", 1)
566 return w, h
567
568 def get_kernel_stride(self):
569 if "strides" in self.attrs:
570 _, h, w, _ = self.attrs["strides"]
571 else:
572 h = self.attrs.get("stride_h", 1)
573 w = self.attrs.get("stride_w", 1)
574 return w, h
575
576 def get_kernel_dilation(self):
577 if "dilation" in self.attrs:
578 _, h, w, _ = self.attrs["dilation"]
579 else:
580 h = self.attrs.get("dilation_h_factor", 1)
581 w = self.attrs.get("dilation_w_factor", 1)
582 return w, h
583
584 @property
585 def kernel(self):
586 k_w, k_h = self.get_kernel_size()
587 s_w, s_h = self.get_kernel_stride()
588 d_w, d_h = self.get_kernel_dilation()
589 self._kernel = Kernel(k_w, k_h, s_w, s_h, d_w, d_h)
Tim Hall4ed38bc2020-10-20 18:54:20 +0100590 return self._kernel
591
Tim Hall79d07d22020-04-27 18:20:16 +0100592 def get_ifm_ifm2_weights_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200593 return self.ifm, self.ifm2, self.weights, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100594
595 def get_ifm_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200596 return self.ifm, self.weights, self.bias, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100597
Jacob Bohlin49d92122020-08-19 14:36:46 +0200598 def get_ifm_ifm2_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200599 return self.ifm, self.ifm2, self.weights, self.bias, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200600
Louis Verhaardaee5d752020-09-30 09:01:52 +0200601 def get_ifm_ofm(self):
602 return self.ifm, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200603
Louis Verhaardaee5d752020-09-30 09:01:52 +0200604 @property
605 def ifm(self):
606 # Gets the IFM tensor, or None if not applicable
607 return self.get_input(self.type.info.indices.ifms, 0)
Jacob Bohlin49d92122020-08-19 14:36:46 +0200608
Louis Verhaardaee5d752020-09-30 09:01:52 +0200609 @property
610 def ifm2(self):
611 # Gets the IFM2 tensor, or None if not applicable
612 return self.get_input(self.type.info.indices.ifms, 1)
Louis Verhaard98a34992020-09-01 10:39:04 +0200613
Louis Verhaardaee5d752020-09-30 09:01:52 +0200614 @property
615 def bias(self):
616 # Gets the bias tensor, or None if not applicable
617 return self.get_input(self.type.info.indices.biases, 0)
618
619 @property
620 def weights(self):
621 # Gets the weight tensor, or None if not applicable
622 return self.get_input(self.type.info.indices.weights, 0)
623
624 def get_ifm_tensors(self):
625 # Gets the IFM tensors, or empty list if not applicable
626 return self._index_list_to_tensors(self.type.info.indices.ifms)
627
628 def get_weight_tensors(self):
629 # Gets the weight tensors, or empty list if not applicable
630 return self._index_list_to_tensors(self.type.info.indices.weights)
631
632 def get_bias_tensors(self):
633 # Gets the bias tensors, or empty list if not applicable
634 return self._index_list_to_tensors(self.type.info.indices.biases)
635
636 def _index_list_to_tensors(self, index_list):
637 return [self.inputs[ix] for ix in index_list if ix < len(self.inputs)]
638
639 def get_input(self, index_list, ix):
640 if ix >= len(index_list):
641 return None
642 if index_list[ix] >= len(self.inputs):
643 return None
644 return self.inputs[index_list[ix]]
645
646 @property
647 def ofm(self):
648 # Gets the OFM tensor, or None if not applicable
649 return self.outputs[0] if self.outputs else None
Tim Hall79d07d22020-04-27 18:20:16 +0100650
651 def get_concat_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200652 assert self.type.is_concat_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100653
Louis Verhaardaee5d752020-09-30 09:01:52 +0200654 if self.type == Op.Concat:
Tim Hall79d07d22020-04-27 18:20:16 +0100655 axis_tensor = self.inputs[0]
656 inputs = self.inputs[1:]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200657 elif self.type == Op.ConcatTFLite:
Tim Hall79d07d22020-04-27 18:20:16 +0100658 inputs = self.inputs
659 axis = self.attrs["axis"]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200660 elif self.type == Op.PackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100661 # Requires fixup_pack_input to be called before this point
662 inputs = self.inputs
663 axis = self.attrs["axis"]
664 assert len(self.inputs) == self.attrs["values_count"]
665 else:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200666 assert len(axis_tensor.ops) == 1 and axis_tensor.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100667 axis = int(axis_tensor.values)
668
669 return inputs, axis
670
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200671 def get_dilation_h_w(self):
672 _, dilation_h, dilation_w, _ = self.attrs.get("dilation", (1, 1, 1, 1))
673 return dilation_h, dilation_w
674
Tim Hall79d07d22020-04-27 18:20:16 +0100675 def get_split_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200676 assert self.type.is_split_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100677
678 offset_start = None
679 offset_end = None
680 axis = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200681 if self.type == Op.Split:
Tim Hall79d07d22020-04-27 18:20:16 +0100682 num_splits = self.attrs.get("num_splits")
683 axis_tens = self.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200684 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100685 axis = int(axis_tens.values)
686 input_tens = self.inputs[1]
687 outputs = self.outputs
688 assert num_splits == len(outputs)
689
Louis Verhaardaee5d752020-09-30 09:01:52 +0200690 elif self.type == Op.SplitV:
Charles Xu53d47522020-05-04 11:32:05 +0200691 num_splits = self.attrs.get("num_splits")
692 input_tens = self.inputs[0]
693 size_tens = self.inputs[1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200694 assert len(size_tens.ops) == 1 and size_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200695 sizes = size_tens.values
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200696
Charles Xu53d47522020-05-04 11:32:05 +0200697 axis_tens = self.inputs[2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200698 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200699 axis = int(axis_tens.values)
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200700
701 for idx, size in enumerate(sizes):
702 # One but only one size might be set to -1, indicating that size should be inferred
703 if size == -1:
704 sizes[idx] = input_tens.shape[axis] - (sum(sizes) + 1)
705 break
706
Charles Xu53d47522020-05-04 11:32:05 +0200707 outputs = self.outputs
708 assert num_splits == len(outputs)
709 assert sum(sizes) == input_tens.shape[axis]
710
Louis Verhaardaee5d752020-09-30 09:01:52 +0200711 elif self.type == Op.Slice:
Tim Hall79d07d22020-04-27 18:20:16 +0100712 input_tens, begin_tens, size_tens = self.inputs
713 outputs = self.outputs
714 offset_start = [0] * len(input_tens.shape)
715 offset_end = [0] * len(input_tens.shape)
716
717 for idx in range(len(begin_tens.values)):
718 # Check if the op should slice in dimension idx
719 if size_tens.values[idx] != input_tens.shape[idx]:
720 offset_start[idx] = begin_tens.values[idx]
721 offset_end[idx] = size_tens.values[idx] + offset_start[idx]
722
Louis Verhaardaee5d752020-09-30 09:01:52 +0200723 elif self.type == Op.StridedSlice:
Tim Hall79d07d22020-04-27 18:20:16 +0100724 input_tens, begin_tens, end_tens, strides_tens = self.inputs
725 outputs = self.outputs
Tim Hall79d07d22020-04-27 18:20:16 +0100726
727 # Extract masks
728 begin_mask = self.attrs["begin_mask"]
729 ellipsis_mask = self.attrs["ellipsis_mask"]
730 end_mask = self.attrs["end_mask"]
731 new_axis_mask = self.attrs["new_axis_mask"]
732 shrink_axis_mask = self.attrs["shrink_axis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200733
734 # shrink_axis_mask/new_axis_mask/ellipsis_mask is not supported by the Operation class but the operation
Tim Hall79d07d22020-04-27 18:20:16 +0100735 # may have the attribute modified and handled in the graph optimization phase.
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200736 assert shrink_axis_mask == new_axis_mask == ellipsis_mask == 0
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200737 offset_start = get_slice_offsets(input_tens.shape, begin_tens, begin_mask, is_begin=True)
738 offset_end = get_slice_offsets(input_tens.shape, end_tens, end_mask, is_begin=False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200739 elif self.type == Op.UnpackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100740 # Requires fixup_unpack_output to be called before this point
741 input_tens = self.inputs[0]
742 outputs = self.outputs
743 axis = self.attrs["axis"]
744 num_splits = self.attrs["num"]
745 # Number of outputs have to equal the value of the dimension to unpack
746 assert num_splits == len(outputs) == input_tens.shape[axis]
747 else:
748 assert False
749
750 return input_tens, outputs, axis, offset_start, offset_end
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200751
752 def set_activation_lut(self, lut_tensor):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100753 self.activation = ActivationFunction(Op.LUT)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200754 self.activation_lut = lut_tensor
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100755 self.add_input_tensor(lut_tensor)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100756
757 def add_input_tensor(self, tens):
758 self.inputs.append(tens)
759 if self not in tens.consumer_list:
760 tens.consumer_list.append(self)
761
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200762 def set_input_tensor(self, tens, idx):
763 tens_to_remove = self.inputs[idx]
764 if tens_to_remove in tens.consumer_list:
765 tens.consumer_list.remove(tens_to_remove)
766
767 self.inputs[idx] = tens
768 if self not in tens.consumer_list:
769 tens.consumer_list.append(self)
770
Dwight Lidman4f728c02020-12-17 15:14:45 +0100771 def get_input_quantization(self):
772 if self.forced_input_quantization is not None:
773 return self.forced_input_quantization
774 return self.ifm.quantization
775
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100776 def set_output_tensor(self, tens):
777 tens.ops = [self]
778 self.outputs = [tens]
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200779
Louis Verhaard98a34992020-09-01 10:39:04 +0200780 def get_output_quantization(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200781 if self.forced_output_quantization is not None:
782 return self.forced_output_quantization
783 return self.ofm.quantization
Michael McGeagh528a56d2020-12-16 11:33:21 +0000784
785 def error(self, msg):
786 """
787 Raises a VelaError exception for errors encountered when parsing an Operation
788
789 :param self: Operation object that resulted in the error
790 :param msg: str object that contains a description of the specific error encountered
791 """
792
793 def _print_tensors(tensors):
794 lines = []
795 for idx, tens in enumerate(tensors):
796 tens_name = getattr(tens, "name", "Not a Tensor")
797 lines.append(f" {idx} = {tens_name}")
798 return lines
799
800 if self.op_index is None:
801 lines = [f"Invalid {self.type} (name = {self.name}) operator in the internal representation. {msg}"]
802 else:
803 lines = [f"Invalid {self.type} (op_index = {self.op_index}) operator in the input network. {msg}"]
804
805 lines += [" Input tensors:"]
806 lines += _print_tensors(self.inputs)
807
808 lines += [" Output tensors:"]
809 lines += _print_tensors(self.outputs)
810
811 raise VelaError("\n".join(lines))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100812
813 def set_ifm_ofm_shapes(self):
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000814 self.ifm_shapes = []
815 self.ofm_shapes = []
816
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100817 ifm_tensor, ifm2_tensor, weight_tensor, ofm_tensor = self.get_ifm_ifm2_weights_ofm()
818
819 # set all shapes to op, as 4D
820 if self.type == Op.FullyConnected:
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100821 if len(self.ifm.shape) == 2:
822 self.ifm_shapes.append(Shape4D([self.ifm.shape[0], 1, 1, self.ifm.shape[1]]))
823 else:
824 # Special case, handled in graph optimization
825 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
826 if len(self.ofm.shape) == 2:
827 self.ofm_shapes.append(Shape4D([self.ofm.shape[0], 1, 1, self.ofm.shape[1]]))
828 else:
829 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
830 if self.type == Op.Softmax:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000831 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
832 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100833 elif self.type.is_split_op() or self.type.is_concat_op():
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100834 for inp in self.inputs:
835 if inp is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000836 self.ifm_shapes.append(Shape4D(full_shape(4, inp.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100837 else:
838 self.ifm_shapes.append(None)
839 for out in self.outputs:
840 if out is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000841 self.ofm_shapes.append(Shape4D(full_shape(4, out.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100842 else:
843 self.ofm_shapes.append(None)
844 else:
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100845 if ifm_tensor is not None:
846 self.ifm_shapes.append(Shape4D(full_shape(4, ifm_tensor.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100847 if ifm2_tensor is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000848 self.ifm_shapes.append(Shape4D(full_shape(4, ifm2_tensor.shape, 1)))
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100849 if ofm_tensor is not None:
850 self.ofm_shapes.append(Shape4D(full_shape(4, ofm_tensor.shape, 1)))
Tim Halld8339a72021-05-27 18:49:40 +0100851
852 def has_scaling(self):
853 scaled = True
854 for tensor in [self.ifm, self.ifm2, self.ofm]:
855 if tensor is not None:
856 if tensor.quantization is None:
857 scaled = False
858 break
859
860 return scaled