blob: 45fae217a508e60fc4e53f66e15ba509eb0e5ed4 [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
Louis Verhaarde8a5a782020-11-02 18:04:27 +010021from typing import Optional
Tim Hall79d07d22020-04-27 18:20:16 +010022
Tim Hall4ed38bc2020-10-20 18:54:20 +010023from .numeric_util import full_shape
24
25PointXY = namedtuple("PointXY", "x y")
26PointXYZ = namedtuple("PointXYZ", "x y z")
27
Tim Hall79d07d22020-04-27 18:20:16 +010028
Louis Verhaardaee5d752020-09-30 09:01:52 +020029class NpuBlockType(Enum):
Tim Hall79d07d22020-04-27 18:20:16 +010030 Default = 0
31 ConvolutionMxN = 1
32 VectorProduct = 2
33 Pooling = 3
34 ConvolutionDepthWise = 4
35 ElementWise = 5
Fredrik Svedberga0c36242020-06-03 15:43:31 +020036 ReduceSum = 6
Tim Hall79d07d22020-04-27 18:20:16 +010037
38
Tim Hall4ed38bc2020-10-20 18:54:20 +010039class Kernel:
Louis Verhaarde8a5a782020-11-02 18:04:27 +010040 """
41 Kernel information for NPU operations
42 """
43
44 def __init__(self, w: int, h: int, stride_x: int = 1, stride_y: int = 1, dilation_x: int = 1, dilation_y: int = 1):
45 assert stride_x > 0 and stride_y > 0
46 assert dilation_x > 0 and dilation_y > 0
Tim Hall4ed38bc2020-10-20 18:54:20 +010047 self.width = w
48 self.height = h
Louis Verhaarde8a5a782020-11-02 18:04:27 +010049 self.stride = PointXY(stride_x, stride_y)
50 self.dilation = PointXY(dilation_x, dilation_y)
Tim Hall4ed38bc2020-10-20 18:54:20 +010051
Louis Verhaarde8a5a782020-11-02 18:04:27 +010052 def elements_wh(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010053 return self.width * self.height
54
Louis Verhaarde8a5a782020-11-02 18:04:27 +010055 def area_width(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010056 return (self.width - 1) * self.dilation.x + 1
57
Louis Verhaarde8a5a782020-11-02 18:04:27 +010058 def area_height(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010059 return (self.height - 1) * self.dilation.y + 1
60
Louis Verhaarde8a5a782020-11-02 18:04:27 +010061 def __str__(self):
62 return f"w={self.width}, h={self.height}, stride={tuple(self.stride)}, dilation={tuple(self.dilation)}"
63
Tim Hall4ed38bc2020-10-20 18:54:20 +010064
Louis Verhaardaee5d752020-09-30 09:01:52 +020065# Classifies operators of type Custom
66class CustomType(Enum):
67 ThirdPartyOp = 0 # Third party custom op
68 NpuOp = 1 # NPU op
69 ExistingNpuOp = 2 # NPU op that was part of the input network
70
71
72TensorIndices = namedtuple("TensorIndices", ["ifms", "weights", "biases"])
73
74NO_INDICES = TensorIndices([], [], [])
75IFM_INDICES = TensorIndices([0], [], [])
76IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
77IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
78IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
79CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
80TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
81CONCAT_INDICES = TensorIndices([1, 2], [], [])
82SPLIT_IFM_INDICES = TensorIndices([1], [], [])
83BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
84
85
86# Static information related to operation codes
87class OperatorInfo:
88 __slots__ = ("id", "block_type", "indices", "is_unary")
89 _id = 0
90
91 def __init__(self, block_type=NpuBlockType.Default, indices=NO_INDICES, is_unary=False):
92 OperatorInfo._id += 1
93 self.id = OperatorInfo._id
94 self.block_type = block_type
95 self.indices = indices # Indices of the different tensor purposes
96 self.is_unary = is_unary # Classifies elementwise operators
97
98
99# Internally used operation codes
100class Op(Enum):
101 Abs = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True)
102 Add = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
103 AddN = OperatorInfo()
104 Any = OperatorInfo()
105 ArgMax = OperatorInfo()
106 ArgMin = OperatorInfo()
107 AvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
108 BatchMatMul = OperatorInfo()
109 BatchToSpaceND = OperatorInfo()
110 BidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
111 BidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
112 BlockLSTM = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=BLOCK_LSTM_INDICES)
113
114 CLZ = OperatorInfo(
115 block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True
116 ) # NPU specific operation
117 Call = OperatorInfo()
118 Cast = OperatorInfo()
119 Ceil = OperatorInfo()
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100120 Clip = OperatorInfo() # NPU specific fused activation function for clipping between activation.min/max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200121 Concat = OperatorInfo(indices=CONCAT_INDICES)
122 ConcatEmbeddings = OperatorInfo()
123 ConcatSliceWrite = OperatorInfo(indices=IFM_INDICES)
124 ConcatTFLite = OperatorInfo()
125 Const = OperatorInfo() # Constant tensor, only used in CPU subgraphs
126 Conv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES)
127 Conv2DBackpropInput = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=CONV2D_BACKPROP_INDICES)
128 Conv2DBackpropInputSwitchedBias = OperatorInfo(
129 block_type=NpuBlockType.ConvolutionMxN, indices=TRANSPOSE_CONV_INDICES
130 )
131 Conv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_BIAS_INDICES)
132 Cos = OperatorInfo()
133 Custom = OperatorInfo() # Custom 3rd party operator, only used in CPU subgraphs
134 CustomNpuOp = OperatorInfo() # NPU custom operator, only used in CPU subgraphs
135 DMA = OperatorInfo()
136 Delegate = OperatorInfo()
137 Densify = OperatorInfo()
138 DepthToSpace = OperatorInfo()
139 DepthwiseConv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionDepthWise, indices=IFM_WEIGHTS_BIAS_INDICES)
Louis Verhaard04f8c002020-10-09 11:40:21 +0200140 Dequantize = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200141 Div = OperatorInfo()
142 Elu = OperatorInfo()
143 EmbeddingLookup = OperatorInfo()
144 EmbeddingLookupSparse = OperatorInfo()
145 Equal = OperatorInfo()
146 Exp = OperatorInfo()
147 ExpandDims = OperatorInfo(indices=IFM_INDICES)
148 FakeQuantWithMinMaxArgs = OperatorInfo()
149 Fill = OperatorInfo()
150 Floor = OperatorInfo()
151 FloorDiv = OperatorInfo()
152 FloorMod = OperatorInfo()
153 FullyConnected = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_BIAS_INDICES)
154 GatherNd = OperatorInfo()
155 GatherV2 = OperatorInfo()
156 Greater = OperatorInfo()
157 GreaterEqual = OperatorInfo()
158 HardSwish = OperatorInfo()
159 HashtableLookup = OperatorInfo()
160 Identity = OperatorInfo()
161 If = OperatorInfo()
162 L2Norm = OperatorInfo()
163 L2Pool2D = OperatorInfo()
164 LRN = OperatorInfo()
165 LSHProjection = OperatorInfo()
166 LeakyRelu = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True)
167 Less = OperatorInfo()
168 LessEqual = OperatorInfo()
169 Log = OperatorInfo()
170 LogSoftmax = OperatorInfo()
171 LogicalAnd = OperatorInfo()
172 LogicalNot = OperatorInfo()
173 LogicalOr = OperatorInfo()
174 Lstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
175 LUT = OperatorInfo() # NPU specific, operator has LUT, only used in fused activation functions
176 MatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
177 MatrixDiag = OperatorInfo()
178 MatrixSetDiag = OperatorInfo()
179 Max = OperatorInfo()
180 MaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
181 Maximum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
182 Mean = OperatorInfo()
183 Min = OperatorInfo()
184 Minimum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
185 MirrorPad = OperatorInfo()
186 Mul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
187 Neg = OperatorInfo()
188 NonMaxSuppressionV4 = OperatorInfo()
189 NonMaxSuppressionV5 = OperatorInfo()
190 NotEqual = OperatorInfo()
191 OneHot = OperatorInfo()
192 Pack = OperatorInfo()
193 PackReshaped = OperatorInfo(indices=IFM_INDICES)
194 Pad = OperatorInfo()
195 PadV2 = OperatorInfo()
196 Placeholder = OperatorInfo() # Only used in CPU subgraphs
197 Pow = OperatorInfo()
198 Prelu = OperatorInfo()
199 Prod = OperatorInfo()
Louis Verhaard04f8c002020-10-09 11:40:21 +0200200 Quantize = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200201 QuantizedAvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
202 QuantizedConv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES)
203 QuantizedMatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
204 QuantizedMaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
205 QuantizedReshape = OperatorInfo(indices=IFM_INDICES)
206 Range = OperatorInfo()
207 Rank = OperatorInfo()
208 ReduceSum = OperatorInfo(block_type=NpuBlockType.ReduceSum, indices=IFM_INDICES)
209 Relu = OperatorInfo(indices=IFM_INDICES)
210 Relu6 = OperatorInfo(indices=IFM_INDICES)
211 ReluN1To1 = OperatorInfo(indices=IFM_INDICES)
212 Reshape = OperatorInfo(indices=IFM_INDICES)
213 ResizeBilinear = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES)
214 ResizeNearestNeighbor = OperatorInfo()
215 ReverseSequence = OperatorInfo()
216 ReverseV2 = OperatorInfo()
217 Rnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
218 Round = OperatorInfo()
219 Rsqrt = OperatorInfo()
220 SHL = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation
221 SHR = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation
222 ScatterNd = OperatorInfo()
223 SegmentSum = OperatorInfo()
224 Select = OperatorInfo()
225 SelectV2 = OperatorInfo()
226 Shape = OperatorInfo()
227 Sigmoid = OperatorInfo(indices=IFM_INDICES)
228 SignBit = OperatorInfo()
229 Sin = OperatorInfo()
230 SkipGram = OperatorInfo()
231 Slice = OperatorInfo(indices=IFM_INDICES)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100232 Softmax = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200233 SpaceToBatchND = OperatorInfo()
234 SpaceToDepth = OperatorInfo()
235 SparseToDense = OperatorInfo()
236 Split = OperatorInfo(indices=SPLIT_IFM_INDICES)
237 SplitSliceRead = OperatorInfo(indices=IFM_INDICES)
Jacob Bohline3de4e52020-11-27 14:52:06 +0100238 SplitV = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200239 Sqrt = OperatorInfo()
240 Square = OperatorInfo()
241 SquaredDifference = OperatorInfo()
242 Squeeze = OperatorInfo(indices=IFM_INDICES)
243 StridedSlice = OperatorInfo(indices=IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200244 Sub = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES)
245 SubgraphInput = OperatorInfo() # Only used in CPU subgraphs
246 Sum = OperatorInfo()
247 Svdf = OperatorInfo()
248 Tanh = OperatorInfo(indices=IFM_INDICES)
249 Tile = OperatorInfo()
250 TopKV2 = OperatorInfo()
251 Transpose = OperatorInfo()
252 UnidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
253 UnidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES)
254 Unique = OperatorInfo()
255 Unpack = OperatorInfo()
256 UnpackReshaped = OperatorInfo(indices=IFM_INDICES)
257 Where = OperatorInfo()
258 While = OperatorInfo()
259 ZerosLike = OperatorInfo()
260
261 @property
262 def info(self):
263 return self.value
264
265 @property
266 def npu_block_type(self):
267 return self.info.block_type
268
269 def is_conv2d_op(self):
270 return self.info.block_type == NpuBlockType.ConvolutionMxN
271
272 def is_depthwise_conv2d_op(self):
273 return self.info.block_type == NpuBlockType.ConvolutionDepthWise
274
275 def is_pool_op(self):
276 return self.info.block_type == NpuBlockType.Pooling
277
278 def is_maxpool_op(self):
279 return self in (Op.MaxPool, Op.QuantizedMaxPool)
280
281 def is_avgpool_op(self):
282 return self in (Op.QuantizedAvgPool, Op.AvgPool)
283
284 def is_elementwise_op(self):
285 return self.info.block_type == NpuBlockType.ElementWise
286
287 def is_unary_elementwise_op(self):
288 return self.info.block_type == NpuBlockType.ElementWise and self.info.is_unary
289
290 def is_binary_elementwise_op(self):
291 return self.info.block_type == NpuBlockType.ElementWise and not self.info.is_unary
292
293 def is_relu_op(self):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100294 return self in (Op.Relu, Op.Relu6, Op.ReluN1To1, Op.Clip)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200295
296 def is_activation_op(self):
297 return self.is_relu_op() or self in (Op.Tanh, Op.Sigmoid, Op.Softmax, Op.LUT)
298
299 def is_split_op(self):
300 return self in (Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped)
301
302 def is_concat_op(self):
303 return self in (Op.Concat, Op.ConcatTFLite, Op.PackReshaped)
304
305 def needs_bias(self):
306 return bool(self.info.indices.biases)
307
308 @classmethod
309 def op_set(cls, predicate):
310 # Returns the set of all operator codes that fulfill the given predicate
311 return {op_type for op_type in Op if predicate(op_type)}
312
313 def __str__(self):
314 return self.name
315
316 __repr__ = __str__
317
318 def __lt__(self, other):
319 return self.value.id < other.value.id
320
321
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100322class ActivationFunction:
323 """Fused activation function"""
324
325 def __init__(self, op_type: Op):
326 self.op_type = op_type # The activation operation to be performed
327 # min/max are optional; if present they are non-quantized values
328 self.min: Optional[float] = None
329 self.max: Optional[float] = None
330 # Table lookup index, only applicable for Op.LUT activation, 0-7
331 self.lut_index: int = 0
332
333 def clone(self):
334 res = copy.copy(self)
335 return res
336
337
338def create_activation_function(op_type: Op) -> ActivationFunction:
339 """Creates activation function with min/max depending on op_type"""
340 act = ActivationFunction(op_type)
341 if op_type == Op.Relu:
342 act.min = 0.0
343 elif op_type == Op.Relu6:
344 act.min = 0.0
345 act.max = 6.0
346 elif op_type == Op.ReluN1To1:
347 act.min = -1.0
348 act.max = 1.0
349 elif op_type == Op.Tanh:
350 act.min = -1.0
351 act.max = 1.0
352 elif op_type == Op.Sigmoid:
353 act.min = 0.0
354 act.max = 1.0
355 return act
356
357
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200358def get_slice_offsets(input_shape, offset_tens, offset_mask, is_begin=True):
359 # For strided slice operator: get start or end offsets
360 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
361 for idx in range(len(input_shape)):
362 # If the i:th bit in the mask is set then the value on offset_tens[i] should be ignored
363 if (offset_mask & (1 << idx)) == 0:
364 offsets[idx] = offset_tens.values[idx]
365 if offsets[idx] < 0:
366 # Convert offset to positive value
367 offsets[idx] += input_shape[idx]
368 return offsets
369
370
Tim Hall79d07d22020-04-27 18:20:16 +0100371class Operation:
372 """Class representing a Neural Network operation. Has a name, a type,
Dwight Lidmanc6ac1942020-10-02 14:55:45 +0200373 input and output tensors, as well as an attribute dictionary."""
Tim Hall79d07d22020-04-27 18:20:16 +0100374
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200375 __slots__ = (
376 "type",
377 "name",
378 "op_index",
379 "attrs",
380 "inputs",
381 "outputs",
382 "flops",
383 "scheduled_pass",
384 "run_on_npu",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200385 "activation",
386 "memory_function",
387 "forced_output_quantization",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200388 "activation_lut",
Tim Hall4ed38bc2020-10-20 18:54:20 +0100389 "_kernel",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200390 )
Tim Hall79d07d22020-04-27 18:20:16 +0100391
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100392 def __init__(self, op_type: Op, name: str):
Tim Hall79d07d22020-04-27 18:20:16 +0100393 self.type = op_type
394 self.name = name
395 self.attrs = {}
396 self.inputs = []
397 self.outputs = []
398 self.flops = 0
399 self.run_on_npu = True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200400 # Fused activation function. If not none: operator code.
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100401 self.activation: Optional[ActivationFunction] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200402 # Fused memory function, if not None: operator code
403 self.memory_function = None
404 # If not none: contains QuantizationParameters to be used as output quantization
405 # (which overrides the ofm tensor's quantization), used in LUT
406 self.forced_output_quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100407 self.scheduled_pass = None
Tim Hallc8310b12020-06-17 14:53:11 +0100408 self.op_index = None # input network operator index
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200409 self.activation_lut = None
Tim Hall4ed38bc2020-10-20 18:54:20 +0100410 self._kernel = None
Tim Hall79d07d22020-04-27 18:20:16 +0100411
412 def clone(self, suffix="_clone"):
413 res = Operation(self.type, self.name + suffix)
414
415 res.attrs = dict(self.attrs)
416 res.inputs = list(self.inputs)
417 res.outputs = list(self.outputs)
418 res.flops = self.flops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200419 res.run_on_npu = self.run_on_npu
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100420 res.activation = None if self.activation is None else self.activation.clone()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200421 res.memory_function = self.memory_function
422 res.forced_output_quantization = self.forced_output_quantization
Tim Hall79d07d22020-04-27 18:20:16 +0100423 res.scheduled_pass = self.scheduled_pass
Tim Hallc8310b12020-06-17 14:53:11 +0100424 res.op_index = None # not relevant as not part of input network
Tim Hall79d07d22020-04-27 18:20:16 +0100425
426 return res
427
428 def __str__(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200429 return "<nng.Operation '{}' type={}>".format(self.name, self.type)
Tim Hall79d07d22020-04-27 18:20:16 +0100430
431 __repr__ = __str__
432
Michael McGeagh65fd9982020-10-20 11:49:28 +0100433 def get_kernel_size(self):
Tim Hall4ed38bc2020-10-20 18:54:20 +0100434 weights = self.weights
435 if weights and self.type.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.ConvolutionMxN):
436 weight_shape = full_shape(4, weights.shape, 1)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100437 h = weight_shape[-4]
438 w = weight_shape[-3]
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100439 elif self.type.npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum) and "ksize" in self.attrs:
440 h, w = self.attrs["ksize"][1:3]
Tim Hall4ed38bc2020-10-20 18:54:20 +0100441 else:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100442 h = self.attrs.get("filter_height", 1)
443 w = self.attrs.get("filter_width", 1)
444 return w, h
445
446 def get_kernel_stride(self):
447 if "strides" in self.attrs:
448 _, h, w, _ = self.attrs["strides"]
449 else:
450 h = self.attrs.get("stride_h", 1)
451 w = self.attrs.get("stride_w", 1)
452 return w, h
453
454 def get_kernel_dilation(self):
455 if "dilation" in self.attrs:
456 _, h, w, _ = self.attrs["dilation"]
457 else:
458 h = self.attrs.get("dilation_h_factor", 1)
459 w = self.attrs.get("dilation_w_factor", 1)
460 return w, h
461
462 @property
463 def kernel(self):
464 k_w, k_h = self.get_kernel_size()
465 s_w, s_h = self.get_kernel_stride()
466 d_w, d_h = self.get_kernel_dilation()
467 self._kernel = Kernel(k_w, k_h, s_w, s_h, d_w, d_h)
Tim Hall4ed38bc2020-10-20 18:54:20 +0100468 return self._kernel
469
Tim Hall79d07d22020-04-27 18:20:16 +0100470 def get_ifm_ifm2_weights_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200471 return self.ifm, self.ifm2, self.weights, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100472
473 def get_ifm_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200474 return self.ifm, self.weights, self.bias, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100475
Jacob Bohlin49d92122020-08-19 14:36:46 +0200476 def get_ifm_ifm2_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200477 return self.ifm, self.ifm2, self.weights, self.bias, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200478
Louis Verhaardaee5d752020-09-30 09:01:52 +0200479 def get_ifm_ofm(self):
480 return self.ifm, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200481
Louis Verhaardaee5d752020-09-30 09:01:52 +0200482 @property
483 def ifm(self):
484 # Gets the IFM tensor, or None if not applicable
485 return self.get_input(self.type.info.indices.ifms, 0)
Jacob Bohlin49d92122020-08-19 14:36:46 +0200486
Louis Verhaardaee5d752020-09-30 09:01:52 +0200487 @property
488 def ifm2(self):
489 # Gets the IFM2 tensor, or None if not applicable
490 return self.get_input(self.type.info.indices.ifms, 1)
Louis Verhaard98a34992020-09-01 10:39:04 +0200491
Louis Verhaardaee5d752020-09-30 09:01:52 +0200492 @property
493 def bias(self):
494 # Gets the bias tensor, or None if not applicable
495 return self.get_input(self.type.info.indices.biases, 0)
496
497 @property
498 def weights(self):
499 # Gets the weight tensor, or None if not applicable
500 return self.get_input(self.type.info.indices.weights, 0)
501
502 def get_ifm_tensors(self):
503 # Gets the IFM tensors, or empty list if not applicable
504 return self._index_list_to_tensors(self.type.info.indices.ifms)
505
506 def get_weight_tensors(self):
507 # Gets the weight tensors, or empty list if not applicable
508 return self._index_list_to_tensors(self.type.info.indices.weights)
509
510 def get_bias_tensors(self):
511 # Gets the bias tensors, or empty list if not applicable
512 return self._index_list_to_tensors(self.type.info.indices.biases)
513
514 def _index_list_to_tensors(self, index_list):
515 return [self.inputs[ix] for ix in index_list if ix < len(self.inputs)]
516
517 def get_input(self, index_list, ix):
518 if ix >= len(index_list):
519 return None
520 if index_list[ix] >= len(self.inputs):
521 return None
522 return self.inputs[index_list[ix]]
523
524 @property
525 def ofm(self):
526 # Gets the OFM tensor, or None if not applicable
527 return self.outputs[0] if self.outputs else None
Tim Hall79d07d22020-04-27 18:20:16 +0100528
529 def get_concat_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200530 assert self.type.is_concat_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100531
Louis Verhaardaee5d752020-09-30 09:01:52 +0200532 if self.type == Op.Concat:
Tim Hall79d07d22020-04-27 18:20:16 +0100533 axis_tensor = self.inputs[0]
534 inputs = self.inputs[1:]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200535 elif self.type == Op.ConcatTFLite:
Tim Hall79d07d22020-04-27 18:20:16 +0100536 inputs = self.inputs
537 axis = self.attrs["axis"]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200538 elif self.type == Op.PackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100539 # Requires fixup_pack_input to be called before this point
540 inputs = self.inputs
541 axis = self.attrs["axis"]
542 assert len(self.inputs) == self.attrs["values_count"]
543 else:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200544 assert len(axis_tensor.ops) == 1 and axis_tensor.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100545 axis = int(axis_tensor.values)
546
547 return inputs, axis
548
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200549 def get_dilation_h_w(self):
550 _, dilation_h, dilation_w, _ = self.attrs.get("dilation", (1, 1, 1, 1))
551 return dilation_h, dilation_w
552
Tim Hall79d07d22020-04-27 18:20:16 +0100553 def get_split_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200554 assert self.type.is_split_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100555
556 offset_start = None
557 offset_end = None
558 axis = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200559 if self.type == Op.Split:
Tim Hall79d07d22020-04-27 18:20:16 +0100560 num_splits = self.attrs.get("num_splits")
561 axis_tens = self.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200562 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100563 axis = int(axis_tens.values)
564 input_tens = self.inputs[1]
565 outputs = self.outputs
566 assert num_splits == len(outputs)
567
Louis Verhaardaee5d752020-09-30 09:01:52 +0200568 elif self.type == Op.SplitV:
Charles Xu53d47522020-05-04 11:32:05 +0200569 num_splits = self.attrs.get("num_splits")
570 input_tens = self.inputs[0]
571 size_tens = self.inputs[1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200572 assert len(size_tens.ops) == 1 and size_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200573 sizes = size_tens.values
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200574
Charles Xu53d47522020-05-04 11:32:05 +0200575 axis_tens = self.inputs[2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200576 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200577 axis = int(axis_tens.values)
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200578
579 for idx, size in enumerate(sizes):
580 # One but only one size might be set to -1, indicating that size should be inferred
581 if size == -1:
582 sizes[idx] = input_tens.shape[axis] - (sum(sizes) + 1)
583 break
584
Charles Xu53d47522020-05-04 11:32:05 +0200585 outputs = self.outputs
586 assert num_splits == len(outputs)
587 assert sum(sizes) == input_tens.shape[axis]
588
Louis Verhaardaee5d752020-09-30 09:01:52 +0200589 elif self.type == Op.Slice:
Tim Hall79d07d22020-04-27 18:20:16 +0100590 input_tens, begin_tens, size_tens = self.inputs
591 outputs = self.outputs
592 offset_start = [0] * len(input_tens.shape)
593 offset_end = [0] * len(input_tens.shape)
594
595 for idx in range(len(begin_tens.values)):
596 # Check if the op should slice in dimension idx
597 if size_tens.values[idx] != input_tens.shape[idx]:
598 offset_start[idx] = begin_tens.values[idx]
599 offset_end[idx] = size_tens.values[idx] + offset_start[idx]
600
Louis Verhaardaee5d752020-09-30 09:01:52 +0200601 elif self.type == Op.StridedSlice:
Tim Hall79d07d22020-04-27 18:20:16 +0100602 input_tens, begin_tens, end_tens, strides_tens = self.inputs
603 outputs = self.outputs
604 out_tens = outputs[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100605
606 # Extract masks
607 begin_mask = self.attrs["begin_mask"]
608 ellipsis_mask = self.attrs["ellipsis_mask"]
609 end_mask = self.attrs["end_mask"]
610 new_axis_mask = self.attrs["new_axis_mask"]
611 shrink_axis_mask = self.attrs["shrink_axis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200612
613 # 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 +0100614 # may have the attribute modified and handled in the graph optimization phase.
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200615 assert shrink_axis_mask == new_axis_mask == ellipsis_mask == 0
Tim Hall79d07d22020-04-27 18:20:16 +0100616 assert len(input_tens.shape) == len(out_tens.shape)
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200617 offset_start = get_slice_offsets(input_tens.shape, begin_tens, begin_mask, is_begin=True)
618 offset_end = get_slice_offsets(input_tens.shape, end_tens, end_mask, is_begin=False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200619 elif self.type == Op.UnpackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100620 # Requires fixup_unpack_output to be called before this point
621 input_tens = self.inputs[0]
622 outputs = self.outputs
623 axis = self.attrs["axis"]
624 num_splits = self.attrs["num"]
625 # Number of outputs have to equal the value of the dimension to unpack
626 assert num_splits == len(outputs) == input_tens.shape[axis]
627 else:
628 assert False
629
630 return input_tens, outputs, axis, offset_start, offset_end
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200631
632 def set_activation_lut(self, lut_tensor):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100633 self.activation = ActivationFunction(Op.LUT)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200634 self.activation_lut = lut_tensor
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100635 self.add_input_tensor(lut_tensor)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100636
637 def add_input_tensor(self, tens):
638 self.inputs.append(tens)
639 if self not in tens.consumer_list:
640 tens.consumer_list.append(self)
641
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200642 def set_input_tensor(self, tens, idx):
643 tens_to_remove = self.inputs[idx]
644 if tens_to_remove in tens.consumer_list:
645 tens.consumer_list.remove(tens_to_remove)
646
647 self.inputs[idx] = tens
648 if self not in tens.consumer_list:
649 tens.consumer_list.append(self)
650
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100651 def set_output_tensor(self, tens):
652 tens.ops = [self]
653 self.outputs = [tens]
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200654
Louis Verhaard98a34992020-09-01 10:39:04 +0200655 def get_output_quantization(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200656 if self.forced_output_quantization is not None:
657 return self.forced_output_quantization
658 return self.ofm.quantization