blob: 963d9e69fbd81f95cbe3e8faa25e90da5838b99f [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
Michael McGeagh528a56d2020-12-16 11:33:21 +000028from .errors import VelaError
Tim Hall4ed38bc2020-10-20 18:54:20 +010029from .numeric_util import full_shape
patrik.gustavssoneeb85152020-12-21 17:10:40 +000030from .shape4d import Shape4D
Tim Hall4ed38bc2020-10-20 18:54:20 +010031
Patrik Gustavsson2349d422020-12-01 16:02:29 +010032
Dwight Lidman9b43f842020-12-08 17:56:44 +010033if TYPE_CHECKING:
34 from .tensor import Tensor
35
Tim Hall4ed38bc2020-10-20 18:54:20 +010036PointXY = namedtuple("PointXY", "x y")
37PointXYZ = namedtuple("PointXYZ", "x y z")
38
Tim Hall79d07d22020-04-27 18:20:16 +010039
Louis Verhaardaee5d752020-09-30 09:01:52 +020040class NpuBlockType(Enum):
Tim Hall79d07d22020-04-27 18:20:16 +010041 Default = 0
42 ConvolutionMxN = 1
43 VectorProduct = 2
44 Pooling = 3
45 ConvolutionDepthWise = 4
46 ElementWise = 5
Fredrik Svedberga0c36242020-06-03 15:43:31 +020047 ReduceSum = 6
Tim Hall79d07d22020-04-27 18:20:16 +010048
49
Tim Hall4ed38bc2020-10-20 18:54:20 +010050class Kernel:
Louis Verhaarde8a5a782020-11-02 18:04:27 +010051 """
52 Kernel information for NPU operations
53 """
54
55 def __init__(self, w: int, h: int, stride_x: int = 1, stride_y: int = 1, dilation_x: int = 1, dilation_y: int = 1):
56 assert stride_x > 0 and stride_y > 0
57 assert dilation_x > 0 and dilation_y > 0
Tim Hall4ed38bc2020-10-20 18:54:20 +010058 self.width = w
59 self.height = h
Louis Verhaarde8a5a782020-11-02 18:04:27 +010060 self.stride = PointXY(stride_x, stride_y)
61 self.dilation = PointXY(dilation_x, dilation_y)
Tim Hall4ed38bc2020-10-20 18:54:20 +010062
Louis Verhaarde8a5a782020-11-02 18:04:27 +010063 def elements_wh(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010064 return self.width * self.height
65
Louis Verhaarde8a5a782020-11-02 18:04:27 +010066 def area_width(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010067 return (self.width - 1) * self.dilation.x + 1
68
Louis Verhaarde8a5a782020-11-02 18:04:27 +010069 def area_height(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010070 return (self.height - 1) * self.dilation.y + 1
71
Louis Verhaardebf4af62021-01-27 15:57:57 +010072 def dilated_wh(self) -> Tuple[int, int]:
73 """Returns the dilated kernel width/height"""
74 return self.dilation.x * (self.width - 1) + 1, self.dilation.y * (self.height - 1) + 1
75
Louis Verhaarde8a5a782020-11-02 18:04:27 +010076 def __str__(self):
77 return f"w={self.width}, h={self.height}, stride={tuple(self.stride)}, dilation={tuple(self.dilation)}"
78
Tim Hall4ed38bc2020-10-20 18:54:20 +010079
Louis Verhaardaee5d752020-09-30 09:01:52 +020080# Classifies operators of type Custom
81class CustomType(Enum):
82 ThirdPartyOp = 0 # Third party custom op
83 NpuOp = 1 # NPU op
84 ExistingNpuOp = 2 # NPU op that was part of the input network
85
86
87TensorIndices = namedtuple("TensorIndices", ["ifms", "weights", "biases"])
88
89NO_INDICES = TensorIndices([], [], [])
90IFM_INDICES = TensorIndices([0], [], [])
91IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
92IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
93IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
94CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
95TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
96CONCAT_INDICES = TensorIndices([1, 2], [], [])
97SPLIT_IFM_INDICES = TensorIndices([1], [], [])
98BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
99
100
101# Static information related to operation codes
102class OperatorInfo:
103 __slots__ = ("id", "block_type", "indices", "is_unary")
104 _id = 0
105
106 def __init__(self, block_type=NpuBlockType.Default, indices=NO_INDICES, is_unary=False):
107 OperatorInfo._id += 1
108 self.id = OperatorInfo._id
109 self.block_type = block_type
110 self.indices = indices # Indices of the different tensor purposes
111 self.is_unary = is_unary # Classifies elementwise operators
112
113
114# Internally used operation codes
115class Op(Enum):
116 Abs = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True)
117 Add = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
118 AddN = OperatorInfo()
119 Any = OperatorInfo()
120 ArgMax = OperatorInfo()
121 ArgMin = OperatorInfo()
122 AvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
123 BatchMatMul = OperatorInfo()
124 BatchToSpaceND = OperatorInfo()
125 BidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
126 BidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
127 BlockLSTM = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=BLOCK_LSTM_INDICES)
128
129 CLZ = OperatorInfo(
130 block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True
131 ) # NPU specific operation
132 Call = OperatorInfo()
133 Cast = OperatorInfo()
134 Ceil = OperatorInfo()
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100135 Clip = OperatorInfo() # NPU specific fused activation function for clipping between activation.min/max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200136 Concat = OperatorInfo(indices=CONCAT_INDICES)
137 ConcatEmbeddings = OperatorInfo()
138 ConcatSliceWrite = OperatorInfo(indices=IFM_INDICES)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100139 ConcatTFLite = OperatorInfo(indices=CONCAT_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200140 Const = OperatorInfo() # Constant tensor, only used in CPU subgraphs
141 Conv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES)
142 Conv2DBackpropInput = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=CONV2D_BACKPROP_INDICES)
143 Conv2DBackpropInputSwitchedBias = OperatorInfo(
144 block_type=NpuBlockType.ConvolutionMxN, indices=TRANSPOSE_CONV_INDICES
145 )
146 Conv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_BIAS_INDICES)
147 Cos = OperatorInfo()
148 Custom = OperatorInfo() # Custom 3rd party operator, only used in CPU subgraphs
149 CustomNpuOp = OperatorInfo() # NPU custom operator, only used in CPU subgraphs
150 DMA = OperatorInfo()
151 Delegate = OperatorInfo()
152 Densify = OperatorInfo()
153 DepthToSpace = OperatorInfo()
154 DepthwiseConv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionDepthWise, indices=IFM_WEIGHTS_BIAS_INDICES)
Louis Verhaard04f8c002020-10-09 11:40:21 +0200155 Dequantize = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200156 Div = OperatorInfo()
157 Elu = OperatorInfo()
158 EmbeddingLookup = OperatorInfo()
159 EmbeddingLookupSparse = OperatorInfo()
160 Equal = OperatorInfo()
161 Exp = OperatorInfo()
162 ExpandDims = OperatorInfo(indices=IFM_INDICES)
163 FakeQuantWithMinMaxArgs = OperatorInfo()
164 Fill = OperatorInfo()
165 Floor = OperatorInfo()
166 FloorDiv = OperatorInfo()
167 FloorMod = OperatorInfo()
168 FullyConnected = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_BIAS_INDICES)
169 GatherNd = OperatorInfo()
170 GatherV2 = OperatorInfo()
171 Greater = OperatorInfo()
172 GreaterEqual = OperatorInfo()
Diqing Zhong189f7482021-01-26 12:12:51 +0100173 HardSwish = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200174 HashtableLookup = OperatorInfo()
175 Identity = OperatorInfo()
176 If = OperatorInfo()
177 L2Norm = OperatorInfo()
178 L2Pool2D = OperatorInfo()
179 LRN = OperatorInfo()
180 LSHProjection = OperatorInfo()
181 LeakyRelu = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True)
182 Less = OperatorInfo()
183 LessEqual = OperatorInfo()
184 Log = OperatorInfo()
185 LogSoftmax = OperatorInfo()
186 LogicalAnd = OperatorInfo()
187 LogicalNot = OperatorInfo()
188 LogicalOr = OperatorInfo()
189 Lstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
190 LUT = OperatorInfo() # NPU specific, operator has LUT, only used in fused activation functions
191 MatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
192 MatrixDiag = OperatorInfo()
193 MatrixSetDiag = OperatorInfo()
194 Max = OperatorInfo()
195 MaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
196 Maximum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
197 Mean = OperatorInfo()
198 Min = OperatorInfo()
199 Minimum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
200 MirrorPad = OperatorInfo()
201 Mul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
202 Neg = OperatorInfo()
203 NonMaxSuppressionV4 = OperatorInfo()
204 NonMaxSuppressionV5 = OperatorInfo()
205 NotEqual = OperatorInfo()
206 OneHot = OperatorInfo()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100207 Pack = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200208 PackReshaped = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardae2d5532020-12-11 17:19:54 +0100209 Pad = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200210 PadV2 = OperatorInfo()
211 Placeholder = OperatorInfo() # Only used in CPU subgraphs
212 Pow = OperatorInfo()
213 Prelu = OperatorInfo()
214 Prod = OperatorInfo()
Louis Verhaard04f8c002020-10-09 11:40:21 +0200215 Quantize = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200216 QuantizedAvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
217 QuantizedConv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES)
218 QuantizedMatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
219 QuantizedMaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
220 QuantizedReshape = OperatorInfo(indices=IFM_INDICES)
221 Range = OperatorInfo()
222 Rank = OperatorInfo()
223 ReduceSum = OperatorInfo(block_type=NpuBlockType.ReduceSum, indices=IFM_INDICES)
224 Relu = OperatorInfo(indices=IFM_INDICES)
225 Relu6 = OperatorInfo(indices=IFM_INDICES)
226 ReluN1To1 = OperatorInfo(indices=IFM_INDICES)
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100227 RescaleAdd = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200228 Reshape = OperatorInfo(indices=IFM_INDICES)
229 ResizeBilinear = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
230 ResizeNearestNeighbor = OperatorInfo()
231 ReverseSequence = OperatorInfo()
232 ReverseV2 = OperatorInfo()
233 Rnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
234 Round = OperatorInfo()
235 Rsqrt = OperatorInfo()
236 SHL = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation
237 SHR = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation
238 ScatterNd = OperatorInfo()
239 SegmentSum = OperatorInfo()
240 Select = OperatorInfo()
241 SelectV2 = OperatorInfo()
242 Shape = OperatorInfo()
243 Sigmoid = OperatorInfo(indices=IFM_INDICES)
244 SignBit = OperatorInfo()
245 Sin = OperatorInfo()
246 SkipGram = OperatorInfo()
247 Slice = OperatorInfo(indices=IFM_INDICES)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100248 Softmax = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200249 SpaceToBatchND = OperatorInfo()
250 SpaceToDepth = OperatorInfo()
251 SparseToDense = OperatorInfo()
252 Split = OperatorInfo(indices=SPLIT_IFM_INDICES)
253 SplitSliceRead = OperatorInfo(indices=IFM_INDICES)
Jacob Bohline3de4e52020-11-27 14:52:06 +0100254 SplitV = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200255 Sqrt = OperatorInfo()
256 Square = OperatorInfo()
257 SquaredDifference = OperatorInfo()
258 Squeeze = OperatorInfo(indices=IFM_INDICES)
259 StridedSlice = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200260 Sub = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
261 SubgraphInput = OperatorInfo() # Only used in CPU subgraphs
262 Sum = OperatorInfo()
263 Svdf = OperatorInfo()
264 Tanh = OperatorInfo(indices=IFM_INDICES)
265 Tile = OperatorInfo()
266 TopKV2 = OperatorInfo()
267 Transpose = OperatorInfo()
268 UnidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
269 UnidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
270 Unique = OperatorInfo()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100271 Unpack = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200272 UnpackReshaped = OperatorInfo(indices=IFM_INDICES)
273 Where = OperatorInfo()
274 While = OperatorInfo()
275 ZerosLike = OperatorInfo()
276
277 @property
278 def info(self):
279 return self.value
280
281 @property
282 def npu_block_type(self):
283 return self.info.block_type
284
285 def is_conv2d_op(self):
286 return self.info.block_type == NpuBlockType.ConvolutionMxN
287
288 def is_depthwise_conv2d_op(self):
289 return self.info.block_type == NpuBlockType.ConvolutionDepthWise
290
291 def is_pool_op(self):
292 return self.info.block_type == NpuBlockType.Pooling
293
294 def is_maxpool_op(self):
295 return self in (Op.MaxPool, Op.QuantizedMaxPool)
296
297 def is_avgpool_op(self):
298 return self in (Op.QuantizedAvgPool, Op.AvgPool)
299
300 def is_elementwise_op(self):
301 return self.info.block_type == NpuBlockType.ElementWise
302
303 def is_unary_elementwise_op(self):
304 return self.info.block_type == NpuBlockType.ElementWise and self.info.is_unary
305
306 def is_binary_elementwise_op(self):
307 return self.info.block_type == NpuBlockType.ElementWise and not self.info.is_unary
308
309 def is_relu_op(self):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100310 return self in (Op.Relu, Op.Relu6, Op.ReluN1To1, Op.Clip)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200311
312 def is_activation_op(self):
Diqing Zhong189f7482021-01-26 12:12:51 +0100313 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 +0200314
315 def is_split_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100316 return self in (Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200317
318 def is_concat_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100319 return self in (Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200320
321 def needs_bias(self):
322 return bool(self.info.indices.biases)
323
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100324 def needs_shapes(self):
325 return bool(self.info.indices.ifms)
326
Louis Verhaardaee5d752020-09-30 09:01:52 +0200327 @classmethod
328 def op_set(cls, predicate):
329 # Returns the set of all operator codes that fulfill the given predicate
330 return {op_type for op_type in Op if predicate(op_type)}
331
332 def __str__(self):
333 return self.name
334
335 __repr__ = __str__
336
337 def __lt__(self, other):
338 return self.value.id < other.value.id
339
340
Michael McGeagh16895482020-12-14 15:51:20 +0000341class Padding(Enum):
342 SAME = 0
343 VALID = 1
Louis Verhaardae2d5532020-12-11 17:19:54 +0100344 EXPLICIT = 2 # Padding is specified in a PAD operation (only used for NPU operations)
Michael McGeagh16895482020-12-14 15:51:20 +0000345
346
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100347class ActivationFunction:
348 """Fused activation function"""
349
350 def __init__(self, op_type: Op):
351 self.op_type = op_type # The activation operation to be performed
352 # min/max are optional; if present they are non-quantized values
353 self.min: Optional[float] = None
354 self.max: Optional[float] = None
355 # Table lookup index, only applicable for Op.LUT activation, 0-7
356 self.lut_index: int = 0
357
358 def clone(self):
359 res = copy.copy(self)
360 return res
361
362
363def create_activation_function(op_type: Op) -> ActivationFunction:
364 """Creates activation function with min/max depending on op_type"""
365 act = ActivationFunction(op_type)
366 if op_type == Op.Relu:
367 act.min = 0.0
368 elif op_type == Op.Relu6:
369 act.min = 0.0
370 act.max = 6.0
371 elif op_type == Op.ReluN1To1:
372 act.min = -1.0
373 act.max = 1.0
374 elif op_type == Op.Tanh:
375 act.min = -1.0
376 act.max = 1.0
377 elif op_type == Op.Sigmoid:
378 act.min = 0.0
379 act.max = 1.0
Diqing Zhong189f7482021-01-26 12:12:51 +0100380 elif op_type == Op.HardSwish:
381 act.min = 0.0
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100382 return act
383
384
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000385def get_slice_offsets(input_shape: List[int], offset_tens: int, offset_mask: int, is_begin: bool = True):
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200386 # For strided slice operator: get start or end offsets
387 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
388 for idx in range(len(input_shape)):
389 # If the i:th bit in the mask is set then the value on offset_tens[i] should be ignored
390 if (offset_mask & (1 << idx)) == 0:
391 offsets[idx] = offset_tens.values[idx]
392 if offsets[idx] < 0:
393 # Convert offset to positive value
394 offsets[idx] += input_shape[idx]
395 return offsets
396
397
Tim Hall79d07d22020-04-27 18:20:16 +0100398class Operation:
399 """Class representing a Neural Network operation. Has a name, a type,
Dwight Lidmanc6ac1942020-10-02 14:55:45 +0200400 input and output tensors, as well as an attribute dictionary."""
Tim Hall79d07d22020-04-27 18:20:16 +0100401
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200402 __slots__ = (
403 "type",
404 "name",
405 "op_index",
406 "attrs",
407 "inputs",
408 "outputs",
409 "flops",
410 "scheduled_pass",
411 "run_on_npu",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200412 "activation",
413 "memory_function",
414 "forced_output_quantization",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200415 "activation_lut",
Tim Hall4ed38bc2020-10-20 18:54:20 +0100416 "_kernel",
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100417 "ifm_shapes",
418 "ofm_shapes",
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100419 "rescale",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200420 )
Tim Hall79d07d22020-04-27 18:20:16 +0100421
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100422 def __init__(self, op_type: Op, name: str):
Tim Hall79d07d22020-04-27 18:20:16 +0100423 self.type = op_type
424 self.name = name
Dwight Lidman9b43f842020-12-08 17:56:44 +0100425 self.attrs: Dict[str, Any] = {}
426 self.inputs: List[Tensor] = []
427 self.outputs: List[Tensor] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100428 self.flops = 0
429 self.run_on_npu = True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200430 # Fused activation function. If not none: operator code.
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100431 self.activation: Optional[ActivationFunction] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200432 # Fused memory function, if not None: operator code
433 self.memory_function = None
434 # If not none: contains QuantizationParameters to be used as output quantization
435 # (which overrides the ofm tensor's quantization), used in LUT
436 self.forced_output_quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100437 self.scheduled_pass = None
Tim Hallc8310b12020-06-17 14:53:11 +0100438 self.op_index = None # input network operator index
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200439 self.activation_lut = None
Tim Hall4ed38bc2020-10-20 18:54:20 +0100440 self._kernel = None
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000441 self.ifm_shapes: List[Shape4D] = []
442 self.ofm_shapes: List[Shape4D] = []
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100443 # If not none: contains rescale to be used as output scaling
444 # (which overrides the ofm tensor's scale)
445 self.rescale = None
Tim Hall79d07d22020-04-27 18:20:16 +0100446
447 def clone(self, suffix="_clone"):
448 res = Operation(self.type, self.name + suffix)
449
450 res.attrs = dict(self.attrs)
451 res.inputs = list(self.inputs)
452 res.outputs = list(self.outputs)
453 res.flops = self.flops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200454 res.run_on_npu = self.run_on_npu
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100455 res.activation = None if self.activation is None else self.activation.clone()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200456 res.memory_function = self.memory_function
457 res.forced_output_quantization = self.forced_output_quantization
Tim Hall79d07d22020-04-27 18:20:16 +0100458 res.scheduled_pass = self.scheduled_pass
Tim Hallc8310b12020-06-17 14:53:11 +0100459 res.op_index = None # not relevant as not part of input network
Tim Hall79d07d22020-04-27 18:20:16 +0100460
461 return res
462
463 def __str__(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200464 return "<nng.Operation '{}' type={}>".format(self.name, self.type)
Tim Hall79d07d22020-04-27 18:20:16 +0100465
466 __repr__ = __str__
467
Michael McGeagh65fd9982020-10-20 11:49:28 +0100468 def get_kernel_size(self):
Tim Hall4ed38bc2020-10-20 18:54:20 +0100469 weights = self.weights
470 if weights and self.type.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.ConvolutionMxN):
471 weight_shape = full_shape(4, weights.shape, 1)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100472 h = weight_shape[-4]
473 w = weight_shape[-3]
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100474 elif self.type.npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum) and "ksize" in self.attrs:
475 h, w = self.attrs["ksize"][1:3]
Tim Hall4ed38bc2020-10-20 18:54:20 +0100476 else:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100477 h = self.attrs.get("filter_height", 1)
478 w = self.attrs.get("filter_width", 1)
479 return w, h
480
481 def get_kernel_stride(self):
482 if "strides" in self.attrs:
483 _, h, w, _ = self.attrs["strides"]
484 else:
485 h = self.attrs.get("stride_h", 1)
486 w = self.attrs.get("stride_w", 1)
487 return w, h
488
489 def get_kernel_dilation(self):
490 if "dilation" in self.attrs:
491 _, h, w, _ = self.attrs["dilation"]
492 else:
493 h = self.attrs.get("dilation_h_factor", 1)
494 w = self.attrs.get("dilation_w_factor", 1)
495 return w, h
496
497 @property
498 def kernel(self):
499 k_w, k_h = self.get_kernel_size()
500 s_w, s_h = self.get_kernel_stride()
501 d_w, d_h = self.get_kernel_dilation()
502 self._kernel = Kernel(k_w, k_h, s_w, s_h, d_w, d_h)
Tim Hall4ed38bc2020-10-20 18:54:20 +0100503 return self._kernel
504
Tim Hall79d07d22020-04-27 18:20:16 +0100505 def get_ifm_ifm2_weights_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200506 return self.ifm, self.ifm2, self.weights, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100507
508 def get_ifm_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200509 return self.ifm, self.weights, self.bias, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100510
Jacob Bohlin49d92122020-08-19 14:36:46 +0200511 def get_ifm_ifm2_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200512 return self.ifm, self.ifm2, self.weights, self.bias, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200513
Louis Verhaardaee5d752020-09-30 09:01:52 +0200514 def get_ifm_ofm(self):
515 return self.ifm, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200516
Louis Verhaardaee5d752020-09-30 09:01:52 +0200517 @property
518 def ifm(self):
519 # Gets the IFM tensor, or None if not applicable
520 return self.get_input(self.type.info.indices.ifms, 0)
Jacob Bohlin49d92122020-08-19 14:36:46 +0200521
Louis Verhaardaee5d752020-09-30 09:01:52 +0200522 @property
523 def ifm2(self):
524 # Gets the IFM2 tensor, or None if not applicable
525 return self.get_input(self.type.info.indices.ifms, 1)
Louis Verhaard98a34992020-09-01 10:39:04 +0200526
Louis Verhaardaee5d752020-09-30 09:01:52 +0200527 @property
528 def bias(self):
529 # Gets the bias tensor, or None if not applicable
530 return self.get_input(self.type.info.indices.biases, 0)
531
532 @property
533 def weights(self):
534 # Gets the weight tensor, or None if not applicable
535 return self.get_input(self.type.info.indices.weights, 0)
536
537 def get_ifm_tensors(self):
538 # Gets the IFM tensors, or empty list if not applicable
539 return self._index_list_to_tensors(self.type.info.indices.ifms)
540
541 def get_weight_tensors(self):
542 # Gets the weight tensors, or empty list if not applicable
543 return self._index_list_to_tensors(self.type.info.indices.weights)
544
545 def get_bias_tensors(self):
546 # Gets the bias tensors, or empty list if not applicable
547 return self._index_list_to_tensors(self.type.info.indices.biases)
548
549 def _index_list_to_tensors(self, index_list):
550 return [self.inputs[ix] for ix in index_list if ix < len(self.inputs)]
551
552 def get_input(self, index_list, ix):
553 if ix >= len(index_list):
554 return None
555 if index_list[ix] >= len(self.inputs):
556 return None
557 return self.inputs[index_list[ix]]
558
559 @property
560 def ofm(self):
561 # Gets the OFM tensor, or None if not applicable
562 return self.outputs[0] if self.outputs else None
Tim Hall79d07d22020-04-27 18:20:16 +0100563
564 def get_concat_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200565 assert self.type.is_concat_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100566
Louis Verhaardaee5d752020-09-30 09:01:52 +0200567 if self.type == Op.Concat:
Tim Hall79d07d22020-04-27 18:20:16 +0100568 axis_tensor = self.inputs[0]
569 inputs = self.inputs[1:]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200570 elif self.type == Op.ConcatTFLite:
Tim Hall79d07d22020-04-27 18:20:16 +0100571 inputs = self.inputs
572 axis = self.attrs["axis"]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200573 elif self.type == Op.PackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100574 # Requires fixup_pack_input to be called before this point
575 inputs = self.inputs
576 axis = self.attrs["axis"]
577 assert len(self.inputs) == self.attrs["values_count"]
578 else:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200579 assert len(axis_tensor.ops) == 1 and axis_tensor.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100580 axis = int(axis_tensor.values)
581
582 return inputs, axis
583
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200584 def get_dilation_h_w(self):
585 _, dilation_h, dilation_w, _ = self.attrs.get("dilation", (1, 1, 1, 1))
586 return dilation_h, dilation_w
587
Tim Hall79d07d22020-04-27 18:20:16 +0100588 def get_split_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200589 assert self.type.is_split_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100590
591 offset_start = None
592 offset_end = None
593 axis = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200594 if self.type == Op.Split:
Tim Hall79d07d22020-04-27 18:20:16 +0100595 num_splits = self.attrs.get("num_splits")
596 axis_tens = self.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200597 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100598 axis = int(axis_tens.values)
599 input_tens = self.inputs[1]
600 outputs = self.outputs
601 assert num_splits == len(outputs)
602
Louis Verhaardaee5d752020-09-30 09:01:52 +0200603 elif self.type == Op.SplitV:
Charles Xu53d47522020-05-04 11:32:05 +0200604 num_splits = self.attrs.get("num_splits")
605 input_tens = self.inputs[0]
606 size_tens = self.inputs[1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200607 assert len(size_tens.ops) == 1 and size_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200608 sizes = size_tens.values
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200609
Charles Xu53d47522020-05-04 11:32:05 +0200610 axis_tens = self.inputs[2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200611 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200612 axis = int(axis_tens.values)
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200613
614 for idx, size in enumerate(sizes):
615 # One but only one size might be set to -1, indicating that size should be inferred
616 if size == -1:
617 sizes[idx] = input_tens.shape[axis] - (sum(sizes) + 1)
618 break
619
Charles Xu53d47522020-05-04 11:32:05 +0200620 outputs = self.outputs
621 assert num_splits == len(outputs)
622 assert sum(sizes) == input_tens.shape[axis]
623
Louis Verhaardaee5d752020-09-30 09:01:52 +0200624 elif self.type == Op.Slice:
Tim Hall79d07d22020-04-27 18:20:16 +0100625 input_tens, begin_tens, size_tens = self.inputs
626 outputs = self.outputs
627 offset_start = [0] * len(input_tens.shape)
628 offset_end = [0] * len(input_tens.shape)
629
630 for idx in range(len(begin_tens.values)):
631 # Check if the op should slice in dimension idx
632 if size_tens.values[idx] != input_tens.shape[idx]:
633 offset_start[idx] = begin_tens.values[idx]
634 offset_end[idx] = size_tens.values[idx] + offset_start[idx]
635
Louis Verhaardaee5d752020-09-30 09:01:52 +0200636 elif self.type == Op.StridedSlice:
Tim Hall79d07d22020-04-27 18:20:16 +0100637 input_tens, begin_tens, end_tens, strides_tens = self.inputs
638 outputs = self.outputs
Tim Hall79d07d22020-04-27 18:20:16 +0100639
640 # Extract masks
641 begin_mask = self.attrs["begin_mask"]
642 ellipsis_mask = self.attrs["ellipsis_mask"]
643 end_mask = self.attrs["end_mask"]
644 new_axis_mask = self.attrs["new_axis_mask"]
645 shrink_axis_mask = self.attrs["shrink_axis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200646
647 # 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 +0100648 # may have the attribute modified and handled in the graph optimization phase.
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200649 assert shrink_axis_mask == new_axis_mask == ellipsis_mask == 0
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200650 offset_start = get_slice_offsets(input_tens.shape, begin_tens, begin_mask, is_begin=True)
651 offset_end = get_slice_offsets(input_tens.shape, end_tens, end_mask, is_begin=False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200652 elif self.type == Op.UnpackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100653 # Requires fixup_unpack_output to be called before this point
654 input_tens = self.inputs[0]
655 outputs = self.outputs
656 axis = self.attrs["axis"]
657 num_splits = self.attrs["num"]
658 # Number of outputs have to equal the value of the dimension to unpack
659 assert num_splits == len(outputs) == input_tens.shape[axis]
660 else:
661 assert False
662
663 return input_tens, outputs, axis, offset_start, offset_end
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200664
665 def set_activation_lut(self, lut_tensor):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100666 self.activation = ActivationFunction(Op.LUT)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200667 self.activation_lut = lut_tensor
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100668 self.add_input_tensor(lut_tensor)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100669
670 def add_input_tensor(self, tens):
671 self.inputs.append(tens)
672 if self not in tens.consumer_list:
673 tens.consumer_list.append(self)
674
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200675 def set_input_tensor(self, tens, idx):
676 tens_to_remove = self.inputs[idx]
677 if tens_to_remove in tens.consumer_list:
678 tens.consumer_list.remove(tens_to_remove)
679
680 self.inputs[idx] = tens
681 if self not in tens.consumer_list:
682 tens.consumer_list.append(self)
683
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100684 def set_output_tensor(self, tens):
685 tens.ops = [self]
686 self.outputs = [tens]
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200687
Louis Verhaard98a34992020-09-01 10:39:04 +0200688 def get_output_quantization(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200689 if self.forced_output_quantization is not None:
690 return self.forced_output_quantization
691 return self.ofm.quantization
Michael McGeagh528a56d2020-12-16 11:33:21 +0000692
693 def error(self, msg):
694 """
695 Raises a VelaError exception for errors encountered when parsing an Operation
696
697 :param self: Operation object that resulted in the error
698 :param msg: str object that contains a description of the specific error encountered
699 """
700
701 def _print_tensors(tensors):
702 lines = []
703 for idx, tens in enumerate(tensors):
704 tens_name = getattr(tens, "name", "Not a Tensor")
705 lines.append(f" {idx} = {tens_name}")
706 return lines
707
708 if self.op_index is None:
709 lines = [f"Invalid {self.type} (name = {self.name}) operator in the internal representation. {msg}"]
710 else:
711 lines = [f"Invalid {self.type} (op_index = {self.op_index}) operator in the input network. {msg}"]
712
713 lines += [" Input tensors:"]
714 lines += _print_tensors(self.inputs)
715
716 lines += [" Output tensors:"]
717 lines += _print_tensors(self.outputs)
718
719 raise VelaError("\n".join(lines))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100720
721 def set_ifm_ofm_shapes(self):
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000722 self.ifm_shapes = []
723 self.ofm_shapes = []
724
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100725 ifm_tensor, ifm2_tensor, weight_tensor, ofm_tensor = self.get_ifm_ifm2_weights_ofm()
726
727 # set all shapes to op, as 4D
728 if self.type == Op.FullyConnected:
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100729 if len(self.ifm.shape) == 2:
730 self.ifm_shapes.append(Shape4D([self.ifm.shape[0], 1, 1, self.ifm.shape[1]]))
731 else:
732 # Special case, handled in graph optimization
733 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
734 if len(self.ofm.shape) == 2:
735 self.ofm_shapes.append(Shape4D([self.ofm.shape[0], 1, 1, self.ofm.shape[1]]))
736 else:
737 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
738 if self.type == Op.Softmax:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000739 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
740 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100741 elif self.type.is_split_op or self.type.is_concat_op():
742 for inp in self.inputs:
743 if inp is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000744 self.ifm_shapes.append(Shape4D(full_shape(4, inp.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100745 else:
746 self.ifm_shapes.append(None)
747 for out in self.outputs:
748 if out is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000749 self.ofm_shapes.append(Shape4D(full_shape(4, out.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100750 else:
751 self.ofm_shapes.append(None)
752 else:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000753 self.ifm_shapes.append(Shape4D(full_shape(4, ifm_tensor.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100754 if ifm2_tensor is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000755 self.ifm_shapes.append(Shape4D(full_shape(4, ifm2_tensor.shape, 1)))
756 self.ofm_shapes.append(Shape4D(full_shape(4, ofm_tensor.shape, 1)))