blob: afc02d4164b9de75f87a2657090b176ea2fc785a [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
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
Dwight Lidman9b43f842020-12-08 17:56:44 +010025from typing import TYPE_CHECKING
Tim Hall79d07d22020-04-27 18:20:16 +010026
Tim Hall4ed38bc2020-10-20 18:54:20 +010027from .numeric_util import full_shape
28
Dwight Lidman9b43f842020-12-08 17:56:44 +010029if TYPE_CHECKING:
30 from .tensor import Tensor
31
Tim Hall4ed38bc2020-10-20 18:54:20 +010032PointXY = namedtuple("PointXY", "x y")
33PointXYZ = namedtuple("PointXYZ", "x y z")
34
Tim Hall79d07d22020-04-27 18:20:16 +010035
Louis Verhaardaee5d752020-09-30 09:01:52 +020036class NpuBlockType(Enum):
Tim Hall79d07d22020-04-27 18:20:16 +010037 Default = 0
38 ConvolutionMxN = 1
39 VectorProduct = 2
40 Pooling = 3
41 ConvolutionDepthWise = 4
42 ElementWise = 5
Fredrik Svedberga0c36242020-06-03 15:43:31 +020043 ReduceSum = 6
Tim Hall79d07d22020-04-27 18:20:16 +010044
45
Tim Hall4ed38bc2020-10-20 18:54:20 +010046class Kernel:
Louis Verhaarde8a5a782020-11-02 18:04:27 +010047 """
48 Kernel information for NPU operations
49 """
50
51 def __init__(self, w: int, h: int, stride_x: int = 1, stride_y: int = 1, dilation_x: int = 1, dilation_y: int = 1):
52 assert stride_x > 0 and stride_y > 0
53 assert dilation_x > 0 and dilation_y > 0
Tim Hall4ed38bc2020-10-20 18:54:20 +010054 self.width = w
55 self.height = h
Louis Verhaarde8a5a782020-11-02 18:04:27 +010056 self.stride = PointXY(stride_x, stride_y)
57 self.dilation = PointXY(dilation_x, dilation_y)
Tim Hall4ed38bc2020-10-20 18:54:20 +010058
Louis Verhaarde8a5a782020-11-02 18:04:27 +010059 def elements_wh(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010060 return self.width * self.height
61
Louis Verhaarde8a5a782020-11-02 18:04:27 +010062 def area_width(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010063 return (self.width - 1) * self.dilation.x + 1
64
Louis Verhaarde8a5a782020-11-02 18:04:27 +010065 def area_height(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010066 return (self.height - 1) * self.dilation.y + 1
67
Louis Verhaarde8a5a782020-11-02 18:04:27 +010068 def __str__(self):
69 return f"w={self.width}, h={self.height}, stride={tuple(self.stride)}, dilation={tuple(self.dilation)}"
70
Tim Hall4ed38bc2020-10-20 18:54:20 +010071
Louis Verhaardaee5d752020-09-30 09:01:52 +020072# Classifies operators of type Custom
73class CustomType(Enum):
74 ThirdPartyOp = 0 # Third party custom op
75 NpuOp = 1 # NPU op
76 ExistingNpuOp = 2 # NPU op that was part of the input network
77
78
79TensorIndices = namedtuple("TensorIndices", ["ifms", "weights", "biases"])
80
81NO_INDICES = TensorIndices([], [], [])
82IFM_INDICES = TensorIndices([0], [], [])
83IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
84IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
85IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
86CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
87TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
88CONCAT_INDICES = TensorIndices([1, 2], [], [])
89SPLIT_IFM_INDICES = TensorIndices([1], [], [])
90BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
91
92
93# Static information related to operation codes
94class OperatorInfo:
95 __slots__ = ("id", "block_type", "indices", "is_unary")
96 _id = 0
97
98 def __init__(self, block_type=NpuBlockType.Default, indices=NO_INDICES, is_unary=False):
99 OperatorInfo._id += 1
100 self.id = OperatorInfo._id
101 self.block_type = block_type
102 self.indices = indices # Indices of the different tensor purposes
103 self.is_unary = is_unary # Classifies elementwise operators
104
105
106# Internally used operation codes
107class Op(Enum):
108 Abs = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True)
109 Add = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
110 AddN = OperatorInfo()
111 Any = OperatorInfo()
112 ArgMax = OperatorInfo()
113 ArgMin = OperatorInfo()
114 AvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
115 BatchMatMul = OperatorInfo()
116 BatchToSpaceND = OperatorInfo()
117 BidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
118 BidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
119 BlockLSTM = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=BLOCK_LSTM_INDICES)
120
121 CLZ = OperatorInfo(
122 block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True
123 ) # NPU specific operation
124 Call = OperatorInfo()
125 Cast = OperatorInfo()
126 Ceil = OperatorInfo()
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100127 Clip = OperatorInfo() # NPU specific fused activation function for clipping between activation.min/max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200128 Concat = OperatorInfo(indices=CONCAT_INDICES)
129 ConcatEmbeddings = OperatorInfo()
130 ConcatSliceWrite = OperatorInfo(indices=IFM_INDICES)
131 ConcatTFLite = OperatorInfo()
132 Const = OperatorInfo() # Constant tensor, only used in CPU subgraphs
133 Conv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES)
134 Conv2DBackpropInput = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=CONV2D_BACKPROP_INDICES)
135 Conv2DBackpropInputSwitchedBias = OperatorInfo(
136 block_type=NpuBlockType.ConvolutionMxN, indices=TRANSPOSE_CONV_INDICES
137 )
138 Conv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_BIAS_INDICES)
139 Cos = OperatorInfo()
140 Custom = OperatorInfo() # Custom 3rd party operator, only used in CPU subgraphs
141 CustomNpuOp = OperatorInfo() # NPU custom operator, only used in CPU subgraphs
142 DMA = OperatorInfo()
143 Delegate = OperatorInfo()
144 Densify = OperatorInfo()
145 DepthToSpace = OperatorInfo()
146 DepthwiseConv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionDepthWise, indices=IFM_WEIGHTS_BIAS_INDICES)
Louis Verhaard04f8c002020-10-09 11:40:21 +0200147 Dequantize = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200148 Div = OperatorInfo()
149 Elu = OperatorInfo()
150 EmbeddingLookup = OperatorInfo()
151 EmbeddingLookupSparse = OperatorInfo()
152 Equal = OperatorInfo()
153 Exp = OperatorInfo()
154 ExpandDims = OperatorInfo(indices=IFM_INDICES)
155 FakeQuantWithMinMaxArgs = OperatorInfo()
156 Fill = OperatorInfo()
157 Floor = OperatorInfo()
158 FloorDiv = OperatorInfo()
159 FloorMod = OperatorInfo()
160 FullyConnected = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_BIAS_INDICES)
161 GatherNd = OperatorInfo()
162 GatherV2 = OperatorInfo()
163 Greater = OperatorInfo()
164 GreaterEqual = OperatorInfo()
165 HardSwish = OperatorInfo()
166 HashtableLookup = OperatorInfo()
167 Identity = OperatorInfo()
168 If = OperatorInfo()
169 L2Norm = OperatorInfo()
170 L2Pool2D = OperatorInfo()
171 LRN = OperatorInfo()
172 LSHProjection = OperatorInfo()
173 LeakyRelu = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True)
174 Less = OperatorInfo()
175 LessEqual = OperatorInfo()
176 Log = OperatorInfo()
177 LogSoftmax = OperatorInfo()
178 LogicalAnd = OperatorInfo()
179 LogicalNot = OperatorInfo()
180 LogicalOr = OperatorInfo()
181 Lstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
182 LUT = OperatorInfo() # NPU specific, operator has LUT, only used in fused activation functions
183 MatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
184 MatrixDiag = OperatorInfo()
185 MatrixSetDiag = OperatorInfo()
186 Max = OperatorInfo()
187 MaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
188 Maximum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
189 Mean = OperatorInfo()
190 Min = OperatorInfo()
191 Minimum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
192 MirrorPad = OperatorInfo()
193 Mul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
194 Neg = OperatorInfo()
195 NonMaxSuppressionV4 = OperatorInfo()
196 NonMaxSuppressionV5 = OperatorInfo()
197 NotEqual = OperatorInfo()
198 OneHot = OperatorInfo()
199 Pack = OperatorInfo()
200 PackReshaped = OperatorInfo(indices=IFM_INDICES)
201 Pad = OperatorInfo()
202 PadV2 = OperatorInfo()
203 Placeholder = OperatorInfo() # Only used in CPU subgraphs
204 Pow = OperatorInfo()
205 Prelu = OperatorInfo()
206 Prod = OperatorInfo()
Louis Verhaard04f8c002020-10-09 11:40:21 +0200207 Quantize = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200208 QuantizedAvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
209 QuantizedConv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES)
210 QuantizedMatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
211 QuantizedMaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
212 QuantizedReshape = OperatorInfo(indices=IFM_INDICES)
213 Range = OperatorInfo()
214 Rank = OperatorInfo()
215 ReduceSum = OperatorInfo(block_type=NpuBlockType.ReduceSum, indices=IFM_INDICES)
216 Relu = OperatorInfo(indices=IFM_INDICES)
217 Relu6 = OperatorInfo(indices=IFM_INDICES)
218 ReluN1To1 = OperatorInfo(indices=IFM_INDICES)
219 Reshape = OperatorInfo(indices=IFM_INDICES)
220 ResizeBilinear = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
221 ResizeNearestNeighbor = OperatorInfo()
222 ReverseSequence = OperatorInfo()
223 ReverseV2 = OperatorInfo()
224 Rnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
225 Round = OperatorInfo()
226 Rsqrt = OperatorInfo()
227 SHL = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation
228 SHR = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation
229 ScatterNd = OperatorInfo()
230 SegmentSum = OperatorInfo()
231 Select = OperatorInfo()
232 SelectV2 = OperatorInfo()
233 Shape = OperatorInfo()
234 Sigmoid = OperatorInfo(indices=IFM_INDICES)
235 SignBit = OperatorInfo()
236 Sin = OperatorInfo()
237 SkipGram = OperatorInfo()
238 Slice = OperatorInfo(indices=IFM_INDICES)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100239 Softmax = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200240 SpaceToBatchND = OperatorInfo()
241 SpaceToDepth = OperatorInfo()
242 SparseToDense = OperatorInfo()
243 Split = OperatorInfo(indices=SPLIT_IFM_INDICES)
244 SplitSliceRead = OperatorInfo(indices=IFM_INDICES)
Jacob Bohline3de4e52020-11-27 14:52:06 +0100245 SplitV = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200246 Sqrt = OperatorInfo()
247 Square = OperatorInfo()
248 SquaredDifference = OperatorInfo()
249 Squeeze = OperatorInfo(indices=IFM_INDICES)
250 StridedSlice = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200251 Sub = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
252 SubgraphInput = OperatorInfo() # Only used in CPU subgraphs
253 Sum = OperatorInfo()
254 Svdf = OperatorInfo()
255 Tanh = OperatorInfo(indices=IFM_INDICES)
256 Tile = OperatorInfo()
257 TopKV2 = OperatorInfo()
258 Transpose = OperatorInfo()
259 UnidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
260 UnidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
261 Unique = OperatorInfo()
262 Unpack = OperatorInfo()
263 UnpackReshaped = OperatorInfo(indices=IFM_INDICES)
264 Where = OperatorInfo()
265 While = OperatorInfo()
266 ZerosLike = OperatorInfo()
267
268 @property
269 def info(self):
270 return self.value
271
272 @property
273 def npu_block_type(self):
274 return self.info.block_type
275
276 def is_conv2d_op(self):
277 return self.info.block_type == NpuBlockType.ConvolutionMxN
278
279 def is_depthwise_conv2d_op(self):
280 return self.info.block_type == NpuBlockType.ConvolutionDepthWise
281
282 def is_pool_op(self):
283 return self.info.block_type == NpuBlockType.Pooling
284
285 def is_maxpool_op(self):
286 return self in (Op.MaxPool, Op.QuantizedMaxPool)
287
288 def is_avgpool_op(self):
289 return self in (Op.QuantizedAvgPool, Op.AvgPool)
290
291 def is_elementwise_op(self):
292 return self.info.block_type == NpuBlockType.ElementWise
293
294 def is_unary_elementwise_op(self):
295 return self.info.block_type == NpuBlockType.ElementWise and self.info.is_unary
296
297 def is_binary_elementwise_op(self):
298 return self.info.block_type == NpuBlockType.ElementWise and not self.info.is_unary
299
300 def is_relu_op(self):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100301 return self in (Op.Relu, Op.Relu6, Op.ReluN1To1, Op.Clip)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200302
303 def is_activation_op(self):
304 return self.is_relu_op() or self in (Op.Tanh, Op.Sigmoid, Op.Softmax, Op.LUT)
305
306 def is_split_op(self):
307 return self in (Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped)
308
309 def is_concat_op(self):
310 return self in (Op.Concat, Op.ConcatTFLite, Op.PackReshaped)
311
312 def needs_bias(self):
313 return bool(self.info.indices.biases)
314
315 @classmethod
316 def op_set(cls, predicate):
317 # Returns the set of all operator codes that fulfill the given predicate
318 return {op_type for op_type in Op if predicate(op_type)}
319
320 def __str__(self):
321 return self.name
322
323 __repr__ = __str__
324
325 def __lt__(self, other):
326 return self.value.id < other.value.id
327
328
Michael McGeagh16895482020-12-14 15:51:20 +0000329class Padding(Enum):
330 SAME = 0
331 VALID = 1
332
333
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100334class ActivationFunction:
335 """Fused activation function"""
336
337 def __init__(self, op_type: Op):
338 self.op_type = op_type # The activation operation to be performed
339 # min/max are optional; if present they are non-quantized values
340 self.min: Optional[float] = None
341 self.max: Optional[float] = None
342 # Table lookup index, only applicable for Op.LUT activation, 0-7
343 self.lut_index: int = 0
344
345 def clone(self):
346 res = copy.copy(self)
347 return res
348
349
350def create_activation_function(op_type: Op) -> ActivationFunction:
351 """Creates activation function with min/max depending on op_type"""
352 act = ActivationFunction(op_type)
353 if op_type == Op.Relu:
354 act.min = 0.0
355 elif op_type == Op.Relu6:
356 act.min = 0.0
357 act.max = 6.0
358 elif op_type == Op.ReluN1To1:
359 act.min = -1.0
360 act.max = 1.0
361 elif op_type == Op.Tanh:
362 act.min = -1.0
363 act.max = 1.0
364 elif op_type == Op.Sigmoid:
365 act.min = 0.0
366 act.max = 1.0
367 return act
368
369
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200370def get_slice_offsets(input_shape, offset_tens, offset_mask, is_begin=True):
371 # For strided slice operator: get start or end offsets
372 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
373 for idx in range(len(input_shape)):
374 # If the i:th bit in the mask is set then the value on offset_tens[i] should be ignored
375 if (offset_mask & (1 << idx)) == 0:
376 offsets[idx] = offset_tens.values[idx]
377 if offsets[idx] < 0:
378 # Convert offset to positive value
379 offsets[idx] += input_shape[idx]
380 return offsets
381
382
Tim Hall79d07d22020-04-27 18:20:16 +0100383class Operation:
384 """Class representing a Neural Network operation. Has a name, a type,
Dwight Lidmanc6ac1942020-10-02 14:55:45 +0200385 input and output tensors, as well as an attribute dictionary."""
Tim Hall79d07d22020-04-27 18:20:16 +0100386
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200387 __slots__ = (
388 "type",
389 "name",
390 "op_index",
391 "attrs",
392 "inputs",
393 "outputs",
394 "flops",
395 "scheduled_pass",
396 "run_on_npu",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200397 "activation",
398 "memory_function",
399 "forced_output_quantization",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200400 "activation_lut",
Tim Hall4ed38bc2020-10-20 18:54:20 +0100401 "_kernel",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200402 )
Tim Hall79d07d22020-04-27 18:20:16 +0100403
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100404 def __init__(self, op_type: Op, name: str):
Tim Hall79d07d22020-04-27 18:20:16 +0100405 self.type = op_type
406 self.name = name
Dwight Lidman9b43f842020-12-08 17:56:44 +0100407 self.attrs: Dict[str, Any] = {}
408 self.inputs: List[Tensor] = []
409 self.outputs: List[Tensor] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100410 self.flops = 0
411 self.run_on_npu = True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200412 # Fused activation function. If not none: operator code.
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100413 self.activation: Optional[ActivationFunction] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200414 # Fused memory function, if not None: operator code
415 self.memory_function = None
416 # If not none: contains QuantizationParameters to be used as output quantization
417 # (which overrides the ofm tensor's quantization), used in LUT
418 self.forced_output_quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100419 self.scheduled_pass = None
Tim Hallc8310b12020-06-17 14:53:11 +0100420 self.op_index = None # input network operator index
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200421 self.activation_lut = None
Tim Hall4ed38bc2020-10-20 18:54:20 +0100422 self._kernel = None
Tim Hall79d07d22020-04-27 18:20:16 +0100423
424 def clone(self, suffix="_clone"):
425 res = Operation(self.type, self.name + suffix)
426
427 res.attrs = dict(self.attrs)
428 res.inputs = list(self.inputs)
429 res.outputs = list(self.outputs)
430 res.flops = self.flops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200431 res.run_on_npu = self.run_on_npu
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100432 res.activation = None if self.activation is None else self.activation.clone()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200433 res.memory_function = self.memory_function
434 res.forced_output_quantization = self.forced_output_quantization
Tim Hall79d07d22020-04-27 18:20:16 +0100435 res.scheduled_pass = self.scheduled_pass
Tim Hallc8310b12020-06-17 14:53:11 +0100436 res.op_index = None # not relevant as not part of input network
Tim Hall79d07d22020-04-27 18:20:16 +0100437
438 return res
439
440 def __str__(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200441 return "<nng.Operation '{}' type={}>".format(self.name, self.type)
Tim Hall79d07d22020-04-27 18:20:16 +0100442
443 __repr__ = __str__
444
Michael McGeagh65fd9982020-10-20 11:49:28 +0100445 def get_kernel_size(self):
Tim Hall4ed38bc2020-10-20 18:54:20 +0100446 weights = self.weights
447 if weights and self.type.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.ConvolutionMxN):
448 weight_shape = full_shape(4, weights.shape, 1)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100449 h = weight_shape[-4]
450 w = weight_shape[-3]
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100451 elif self.type.npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum) and "ksize" in self.attrs:
452 h, w = self.attrs["ksize"][1:3]
Tim Hall4ed38bc2020-10-20 18:54:20 +0100453 else:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100454 h = self.attrs.get("filter_height", 1)
455 w = self.attrs.get("filter_width", 1)
456 return w, h
457
458 def get_kernel_stride(self):
459 if "strides" in self.attrs:
460 _, h, w, _ = self.attrs["strides"]
461 else:
462 h = self.attrs.get("stride_h", 1)
463 w = self.attrs.get("stride_w", 1)
464 return w, h
465
466 def get_kernel_dilation(self):
467 if "dilation" in self.attrs:
468 _, h, w, _ = self.attrs["dilation"]
469 else:
470 h = self.attrs.get("dilation_h_factor", 1)
471 w = self.attrs.get("dilation_w_factor", 1)
472 return w, h
473
474 @property
475 def kernel(self):
476 k_w, k_h = self.get_kernel_size()
477 s_w, s_h = self.get_kernel_stride()
478 d_w, d_h = self.get_kernel_dilation()
479 self._kernel = Kernel(k_w, k_h, s_w, s_h, d_w, d_h)
Tim Hall4ed38bc2020-10-20 18:54:20 +0100480 return self._kernel
481
Tim Hall79d07d22020-04-27 18:20:16 +0100482 def get_ifm_ifm2_weights_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200483 return self.ifm, self.ifm2, self.weights, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100484
485 def get_ifm_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200486 return self.ifm, self.weights, self.bias, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100487
Jacob Bohlin49d92122020-08-19 14:36:46 +0200488 def get_ifm_ifm2_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200489 return self.ifm, self.ifm2, self.weights, self.bias, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200490
Louis Verhaardaee5d752020-09-30 09:01:52 +0200491 def get_ifm_ofm(self):
492 return self.ifm, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200493
Louis Verhaardaee5d752020-09-30 09:01:52 +0200494 @property
495 def ifm(self):
496 # Gets the IFM tensor, or None if not applicable
497 return self.get_input(self.type.info.indices.ifms, 0)
Jacob Bohlin49d92122020-08-19 14:36:46 +0200498
Louis Verhaardaee5d752020-09-30 09:01:52 +0200499 @property
500 def ifm2(self):
501 # Gets the IFM2 tensor, or None if not applicable
502 return self.get_input(self.type.info.indices.ifms, 1)
Louis Verhaard98a34992020-09-01 10:39:04 +0200503
Louis Verhaardaee5d752020-09-30 09:01:52 +0200504 @property
505 def bias(self):
506 # Gets the bias tensor, or None if not applicable
507 return self.get_input(self.type.info.indices.biases, 0)
508
509 @property
510 def weights(self):
511 # Gets the weight tensor, or None if not applicable
512 return self.get_input(self.type.info.indices.weights, 0)
513
514 def get_ifm_tensors(self):
515 # Gets the IFM tensors, or empty list if not applicable
516 return self._index_list_to_tensors(self.type.info.indices.ifms)
517
518 def get_weight_tensors(self):
519 # Gets the weight tensors, or empty list if not applicable
520 return self._index_list_to_tensors(self.type.info.indices.weights)
521
522 def get_bias_tensors(self):
523 # Gets the bias tensors, or empty list if not applicable
524 return self._index_list_to_tensors(self.type.info.indices.biases)
525
526 def _index_list_to_tensors(self, index_list):
527 return [self.inputs[ix] for ix in index_list if ix < len(self.inputs)]
528
529 def get_input(self, index_list, ix):
530 if ix >= len(index_list):
531 return None
532 if index_list[ix] >= len(self.inputs):
533 return None
534 return self.inputs[index_list[ix]]
535
536 @property
537 def ofm(self):
538 # Gets the OFM tensor, or None if not applicable
539 return self.outputs[0] if self.outputs else None
Tim Hall79d07d22020-04-27 18:20:16 +0100540
541 def get_concat_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200542 assert self.type.is_concat_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100543
Louis Verhaardaee5d752020-09-30 09:01:52 +0200544 if self.type == Op.Concat:
Tim Hall79d07d22020-04-27 18:20:16 +0100545 axis_tensor = self.inputs[0]
546 inputs = self.inputs[1:]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200547 elif self.type == Op.ConcatTFLite:
Tim Hall79d07d22020-04-27 18:20:16 +0100548 inputs = self.inputs
549 axis = self.attrs["axis"]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200550 elif self.type == Op.PackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100551 # Requires fixup_pack_input to be called before this point
552 inputs = self.inputs
553 axis = self.attrs["axis"]
554 assert len(self.inputs) == self.attrs["values_count"]
555 else:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200556 assert len(axis_tensor.ops) == 1 and axis_tensor.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100557 axis = int(axis_tensor.values)
558
559 return inputs, axis
560
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200561 def get_dilation_h_w(self):
562 _, dilation_h, dilation_w, _ = self.attrs.get("dilation", (1, 1, 1, 1))
563 return dilation_h, dilation_w
564
Tim Hall79d07d22020-04-27 18:20:16 +0100565 def get_split_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200566 assert self.type.is_split_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100567
568 offset_start = None
569 offset_end = None
570 axis = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200571 if self.type == Op.Split:
Tim Hall79d07d22020-04-27 18:20:16 +0100572 num_splits = self.attrs.get("num_splits")
573 axis_tens = self.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200574 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100575 axis = int(axis_tens.values)
576 input_tens = self.inputs[1]
577 outputs = self.outputs
578 assert num_splits == len(outputs)
579
Louis Verhaardaee5d752020-09-30 09:01:52 +0200580 elif self.type == Op.SplitV:
Charles Xu53d47522020-05-04 11:32:05 +0200581 num_splits = self.attrs.get("num_splits")
582 input_tens = self.inputs[0]
583 size_tens = self.inputs[1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200584 assert len(size_tens.ops) == 1 and size_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200585 sizes = size_tens.values
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200586
Charles Xu53d47522020-05-04 11:32:05 +0200587 axis_tens = self.inputs[2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200588 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200589 axis = int(axis_tens.values)
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200590
591 for idx, size in enumerate(sizes):
592 # One but only one size might be set to -1, indicating that size should be inferred
593 if size == -1:
594 sizes[idx] = input_tens.shape[axis] - (sum(sizes) + 1)
595 break
596
Charles Xu53d47522020-05-04 11:32:05 +0200597 outputs = self.outputs
598 assert num_splits == len(outputs)
599 assert sum(sizes) == input_tens.shape[axis]
600
Louis Verhaardaee5d752020-09-30 09:01:52 +0200601 elif self.type == Op.Slice:
Tim Hall79d07d22020-04-27 18:20:16 +0100602 input_tens, begin_tens, size_tens = self.inputs
603 outputs = self.outputs
604 offset_start = [0] * len(input_tens.shape)
605 offset_end = [0] * len(input_tens.shape)
606
607 for idx in range(len(begin_tens.values)):
608 # Check if the op should slice in dimension idx
609 if size_tens.values[idx] != input_tens.shape[idx]:
610 offset_start[idx] = begin_tens.values[idx]
611 offset_end[idx] = size_tens.values[idx] + offset_start[idx]
612
Louis Verhaardaee5d752020-09-30 09:01:52 +0200613 elif self.type == Op.StridedSlice:
Tim Hall79d07d22020-04-27 18:20:16 +0100614 input_tens, begin_tens, end_tens, strides_tens = self.inputs
615 outputs = self.outputs
616 out_tens = outputs[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100617
618 # Extract masks
619 begin_mask = self.attrs["begin_mask"]
620 ellipsis_mask = self.attrs["ellipsis_mask"]
621 end_mask = self.attrs["end_mask"]
622 new_axis_mask = self.attrs["new_axis_mask"]
623 shrink_axis_mask = self.attrs["shrink_axis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200624
625 # 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 +0100626 # may have the attribute modified and handled in the graph optimization phase.
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200627 assert shrink_axis_mask == new_axis_mask == ellipsis_mask == 0
Tim Hall79d07d22020-04-27 18:20:16 +0100628 assert len(input_tens.shape) == len(out_tens.shape)
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200629 offset_start = get_slice_offsets(input_tens.shape, begin_tens, begin_mask, is_begin=True)
630 offset_end = get_slice_offsets(input_tens.shape, end_tens, end_mask, is_begin=False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200631 elif self.type == Op.UnpackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100632 # Requires fixup_unpack_output to be called before this point
633 input_tens = self.inputs[0]
634 outputs = self.outputs
635 axis = self.attrs["axis"]
636 num_splits = self.attrs["num"]
637 # Number of outputs have to equal the value of the dimension to unpack
638 assert num_splits == len(outputs) == input_tens.shape[axis]
639 else:
640 assert False
641
642 return input_tens, outputs, axis, offset_start, offset_end
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200643
644 def set_activation_lut(self, lut_tensor):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100645 self.activation = ActivationFunction(Op.LUT)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200646 self.activation_lut = lut_tensor
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100647 self.add_input_tensor(lut_tensor)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100648
649 def add_input_tensor(self, tens):
650 self.inputs.append(tens)
651 if self not in tens.consumer_list:
652 tens.consumer_list.append(self)
653
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200654 def set_input_tensor(self, tens, idx):
655 tens_to_remove = self.inputs[idx]
656 if tens_to_remove in tens.consumer_list:
657 tens.consumer_list.remove(tens_to_remove)
658
659 self.inputs[idx] = tens
660 if self not in tens.consumer_list:
661 tens.consumer_list.append(self)
662
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100663 def set_output_tensor(self, tens):
664 tens.ops = [self]
665 self.outputs = [tens]
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200666
Louis Verhaard98a34992020-09-01 10:39:04 +0200667 def get_output_quantization(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200668 if self.forced_output_quantization is not None:
669 return self.forced_output_quantization
670 return self.ofm.quantization