blob: 05c236a5dab7cd57e3fb5a0bd224ed5500f87813 [file] [log] [blame]
Rickard Bolinfea15162022-07-04 16:19:16 +00001# Copyright (C) 2020-2022 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.
Jonas Ohlsson845e2322022-03-01 12:39:55 +010018# For Class name forward references for the type annotations. (see PEP 563).
19from __future__ import annotations
20
Louis Verhaarde8a5a782020-11-02 18:04:27 +010021import copy
Louis Verhaardaee5d752020-09-30 09:01:52 +020022from collections import namedtuple
23from enum import Enum
Dwight Lidman9b43f842020-12-08 17:56:44 +010024from typing import Any
25from typing import Dict
26from typing import List
Louis Verhaarde8a5a782020-11-02 18:04:27 +010027from typing import Optional
Louis Verhaardebf4af62021-01-27 15:57:57 +010028from typing import Tuple
Dwight Lidman9b43f842020-12-08 17:56:44 +010029from typing import TYPE_CHECKING
Tim Hall79d07d22020-04-27 18:20:16 +010030
Louis Verhaard1a92f782021-02-09 16:08:26 +010031from .api import NpuRoundingMode
Michael McGeagh528a56d2020-12-16 11:33:21 +000032from .errors import VelaError
Tim Hall3c5cfe92022-03-16 16:31:57 +000033from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Tim Hall4ed38bc2020-10-20 18:54:20 +010034from .numeric_util import full_shape
patrik.gustavssoneeb85152020-12-21 17:10:40 +000035from .shape4d import Shape4D
Tim Hall4ed38bc2020-10-20 18:54:20 +010036
Jonas Ohlsson845e2322022-03-01 12:39:55 +010037# Import needed for Type annotations. Only import for Type checking to avoid run-time errors due to cyclic import.
Dwight Lidman9b43f842020-12-08 17:56:44 +010038if TYPE_CHECKING:
39 from .tensor import Tensor
40
Tim Hall4ed38bc2020-10-20 18:54:20 +010041PointXY = namedtuple("PointXY", "x y")
42PointXYZ = namedtuple("PointXYZ", "x y z")
43
Tim Hall79d07d22020-04-27 18:20:16 +010044
Louis Verhaardaee5d752020-09-30 09:01:52 +020045class NpuBlockType(Enum):
Tim Hall79d07d22020-04-27 18:20:16 +010046 Default = 0
47 ConvolutionMxN = 1
48 VectorProduct = 2
49 Pooling = 3
50 ConvolutionDepthWise = 4
51 ElementWise = 5
Fredrik Svedberga0c36242020-06-03 15:43:31 +020052 ReduceSum = 6
Tim Hall79d07d22020-04-27 18:20:16 +010053
54
Tim Hall4ed38bc2020-10-20 18:54:20 +010055class Kernel:
Louis Verhaarde8a5a782020-11-02 18:04:27 +010056 """
57 Kernel information for NPU operations
58 """
59
Tim Halld8339a72021-05-27 18:49:40 +010060 def __init__(
61 self,
62 w: int,
63 h: int,
64 stride_x: int = 1,
65 stride_y: int = 1,
66 dilation_x: int = 1,
67 dilation_y: int = 1,
68 valid_padding=False,
69 ):
Louis Verhaarde8a5a782020-11-02 18:04:27 +010070 assert stride_x > 0 and stride_y > 0
71 assert dilation_x > 0 and dilation_y > 0
Tim Hall4ed38bc2020-10-20 18:54:20 +010072 self.width = w
73 self.height = h
Louis Verhaarde8a5a782020-11-02 18:04:27 +010074 self.stride = PointXY(stride_x, stride_y)
75 self.dilation = PointXY(dilation_x, dilation_y)
Tim Halld8339a72021-05-27 18:49:40 +010076 self.valid_padding = valid_padding
Tim Hall4ed38bc2020-10-20 18:54:20 +010077
Louis Verhaarde8a5a782020-11-02 18:04:27 +010078 def elements_wh(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010079 return self.width * self.height
80
Louis Verhaarde8a5a782020-11-02 18:04:27 +010081 def area_width(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010082 return (self.width - 1) * self.dilation.x + 1
83
Louis Verhaarde8a5a782020-11-02 18:04:27 +010084 def area_height(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010085 return (self.height - 1) * self.dilation.y + 1
86
Louis Verhaardebf4af62021-01-27 15:57:57 +010087 def dilated_wh(self) -> Tuple[int, int]:
88 """Returns the dilated kernel width/height"""
89 return self.dilation.x * (self.width - 1) + 1, self.dilation.y * (self.height - 1) + 1
90
Louis Verhaarde8a5a782020-11-02 18:04:27 +010091 def __str__(self):
92 return f"w={self.width}, h={self.height}, stride={tuple(self.stride)}, dilation={tuple(self.dilation)}"
93
Tim Hall4ed38bc2020-10-20 18:54:20 +010094
Louis Verhaardaee5d752020-09-30 09:01:52 +020095# Classifies operators of type Custom
96class CustomType(Enum):
97 ThirdPartyOp = 0 # Third party custom op
98 NpuOp = 1 # NPU op
99 ExistingNpuOp = 2 # NPU op that was part of the input network
100
101
102TensorIndices = namedtuple("TensorIndices", ["ifms", "weights", "biases"])
103
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200104NNG_NO_INDICES = TensorIndices([], [], [])
105NNG_IFM_INDICES = TensorIndices([0], [], [])
106NNG_IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
107NNG_IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
108NNG_IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
109NNG_CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
110NNG_TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
111NNG_CONCAT_INDICES = TensorIndices([1, 2], [], [])
112NNG_SPLIT_IFM_INDICES = TensorIndices([1], [], [])
113NNG_BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
Louis Verhaardaee5d752020-09-30 09:01:52 +0200114
115
116# Static information related to operation codes
117class OperatorInfo:
118 __slots__ = ("id", "block_type", "indices", "is_unary")
119 _id = 0
120
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200121 def __init__(self, block_type=NpuBlockType.Default, indices=NNG_NO_INDICES, is_unary=False):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200122 OperatorInfo._id += 1
123 self.id = OperatorInfo._id
124 self.block_type = block_type
125 self.indices = indices # Indices of the different tensor purposes
126 self.is_unary = is_unary # Classifies elementwise operators
127
128
129# Internally used operation codes
130class Op(Enum):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200131 Abs = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_INDICES, is_unary=True)
132 Add = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200133 AddN = OperatorInfo()
134 Any = OperatorInfo()
135 ArgMax = OperatorInfo()
136 ArgMin = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200137 AvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
erik.andersson@arm.com61f05d92022-09-27 12:06:32 +0200138 Atan2 = OperatorInfo(indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200139 BatchMatMul = OperatorInfo()
140 BatchToSpaceND = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200141 BidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
142 BidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
143 BlockLSTM = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_BLOCK_LSTM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200144
145 CLZ = OperatorInfo(
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200146 block_type=NpuBlockType.ElementWise, indices=NNG_IFM_INDICES, is_unary=True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200147 ) # NPU specific operation
148 Call = OperatorInfo()
149 Cast = OperatorInfo()
150 Ceil = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200151 Clamp = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100152 Clip = OperatorInfo() # NPU specific fused activation function for clipping between activation.min/max
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200153 Concat = OperatorInfo(indices=NNG_CONCAT_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200154 ConcatEmbeddings = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200155 ConcatSliceWrite = OperatorInfo(indices=NNG_IFM_INDICES)
156 ConcatTFLite = OperatorInfo(indices=NNG_CONCAT_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200157 Const = OperatorInfo() # Constant tensor, only used in CPU subgraphs
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200158 Conv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_IFM_WEIGHTS_INDICES)
159 Conv2DBackpropInput = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_CONV2D_BACKPROP_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200160 Conv2DBackpropInputSwitchedBias = OperatorInfo(
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200161 block_type=NpuBlockType.ConvolutionMxN, indices=NNG_TRANSPOSE_CONV_INDICES
Louis Verhaardaee5d752020-09-30 09:01:52 +0200162 )
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200163 Conv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_IFM_WEIGHTS_BIAS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200164 Cos = OperatorInfo()
Tim Hall42abec12021-02-04 21:31:57 +0000165 Cumsum = OperatorInfo()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200166 Custom = OperatorInfo() # Custom 3rd party operator, only used in CPU subgraphs
167 CustomNpuOp = OperatorInfo() # NPU custom operator, only used in CPU subgraphs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200168 Delegate = OperatorInfo()
169 Densify = OperatorInfo()
170 DepthToSpace = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200171 DepthwiseConv2DBias = OperatorInfo(
172 block_type=NpuBlockType.ConvolutionDepthWise, indices=NNG_IFM_WEIGHTS_BIAS_INDICES
173 )
174 Dequantize = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200175 Div = OperatorInfo()
176 Elu = OperatorInfo()
177 EmbeddingLookup = OperatorInfo()
178 EmbeddingLookupSparse = OperatorInfo()
179 Equal = OperatorInfo()
180 Exp = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200181 ExpandDims = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200182 FakeQuantWithMinMaxArgs = OperatorInfo()
183 Fill = OperatorInfo()
184 Floor = OperatorInfo()
185 FloorDiv = OperatorInfo()
186 FloorMod = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200187 FullyConnected = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_BIAS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200188 GatherNd = OperatorInfo()
189 GatherV2 = OperatorInfo()
190 Greater = OperatorInfo()
191 GreaterEqual = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200192 HardSwish = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200193 HashtableLookup = OperatorInfo()
Patrik Gustavssonef3ebdd2021-10-01 11:10:25 +0200194 Identity = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200195 If = OperatorInfo()
196 L2Norm = OperatorInfo()
197 L2Pool2D = OperatorInfo()
198 LRN = OperatorInfo()
199 LSHProjection = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200200 LeakyRelu = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_INDICES, is_unary=True)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200201 Less = OperatorInfo()
202 LessEqual = OperatorInfo()
203 Log = OperatorInfo()
204 LogSoftmax = OperatorInfo()
205 LogicalAnd = OperatorInfo()
206 LogicalNot = OperatorInfo()
207 LogicalOr = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200208 Lstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200209 LUT = OperatorInfo() # NPU specific, operator has LUT, only used in fused activation functions
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200210 MatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200211 MatrixDiag = OperatorInfo()
212 MatrixSetDiag = OperatorInfo()
213 Max = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200214 MaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
215 Maximum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
216 Mean = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200217 Min = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200218 Minimum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200219 MirrorPad = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200220 Mul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200221 Neg = OperatorInfo()
222 NonMaxSuppressionV4 = OperatorInfo()
223 NonMaxSuppressionV5 = OperatorInfo()
224 NotEqual = OperatorInfo()
225 OneHot = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200226 Pack = OperatorInfo(indices=NNG_IFM_INDICES)
227 PackReshaped = OperatorInfo(indices=NNG_IFM_INDICES)
228 Pad = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200229 PadV2 = OperatorInfo()
230 Placeholder = OperatorInfo() # Only used in CPU subgraphs
231 Pow = OperatorInfo()
Fredrik Svedberg8ddd4892022-08-19 16:06:04 +0200232 Prelu = OperatorInfo(indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200233 Prod = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200234 Quantize = OperatorInfo(indices=NNG_IFM_INDICES)
235 QuantizedAvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
236 QuantizedConv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=NNG_IFM_WEIGHTS_INDICES)
237 QuantizedMatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
238 QuantizedMaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
239 QuantizedReshape = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200240 Range = OperatorInfo()
241 Rank = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200242 ReduceSum = OperatorInfo(block_type=NpuBlockType.ReduceSum, indices=NNG_IFM_INDICES)
243 Relu = OperatorInfo(indices=NNG_IFM_INDICES)
erik.andersson@arm.comdd49a722022-08-10 15:26:48 +0200244 Relu0To1 = OperatorInfo(indices=NNG_IFM_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200245 Relu6 = OperatorInfo(indices=NNG_IFM_INDICES)
246 ReluN1To1 = OperatorInfo(indices=NNG_IFM_INDICES)
247 ReluN = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
248 Rescale = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200249 Reshape = OperatorInfo(indices=NNG_IFM_INDICES)
Tim Hall885033b2022-07-21 11:46:03 +0100250 # resize ops map to pooling operations unless explicitly converted to other operations in the graph optimiser
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200251 ResizeBilinear = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
Tim Hall885033b2022-07-21 11:46:03 +0100252 ResizeNearestNeighbor = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200253 ReverseSequence = OperatorInfo()
254 ReverseV2 = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200255 Rnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200256 Round = OperatorInfo()
257 Rsqrt = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200258 SHL = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES) # NPU specific operation
259 SHR = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES) # NPU specific operation
Louis Verhaardaee5d752020-09-30 09:01:52 +0200260 ScatterNd = OperatorInfo()
261 SegmentSum = OperatorInfo()
262 Select = OperatorInfo()
263 SelectV2 = OperatorInfo()
Ayaan Masood4965fae2022-06-29 11:30:57 +0100264 Shape = OperatorInfo(indices=NNG_IFM_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200265 Sigmoid = OperatorInfo(indices=NNG_IFM_INDICES)
erik.andersson@arm.com61f05d92022-09-27 12:06:32 +0200266 Sign = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200267 SignBit = OperatorInfo()
268 Sin = OperatorInfo()
269 SkipGram = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200270 Slice = OperatorInfo(indices=NNG_IFM_INDICES)
271 Softmax = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200272 SpaceToBatchND = OperatorInfo()
273 SpaceToDepth = OperatorInfo()
274 SparseToDense = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200275 Split = OperatorInfo(indices=NNG_SPLIT_IFM_INDICES)
276 SplitSliceRead = OperatorInfo(indices=NNG_IFM_INDICES)
277 SplitV = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200278 Sqrt = OperatorInfo()
279 Square = OperatorInfo()
280 SquaredDifference = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200281 Squeeze = OperatorInfo(indices=NNG_IFM_INDICES)
282 StridedSlice = OperatorInfo(indices=NNG_IFM_INDICES)
283 Sub = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200284 SubgraphInput = OperatorInfo() # Only used in CPU subgraphs
285 Sum = OperatorInfo()
286 Svdf = OperatorInfo()
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200287 Table = OperatorInfo(indices=NNG_IFM_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200288 Tanh = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200289 Tile = OperatorInfo()
290 TopKV2 = OperatorInfo()
James Ward6bf16132021-09-08 11:14:20 +0100291 Transpose = OperatorInfo(indices=NNG_IFM_IFM2_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200292 UnidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
293 UnidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200294 Unique = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200295 Unpack = OperatorInfo(indices=NNG_IFM_INDICES)
296 UnpackReshaped = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200297 Where = OperatorInfo()
298 While = OperatorInfo()
299 ZerosLike = OperatorInfo()
Dwight Lidman8a12da12021-07-19 13:43:05 +0200300 CallOnce = OperatorInfo()
301 BroadcastTo = OperatorInfo()
302 Rfft2D = OperatorInfo()
303 Conv3D = OperatorInfo()
304 Imag = OperatorInfo()
305 Real = OperatorInfo()
306 ComplexAbs = OperatorInfo()
307 Hashtable = OperatorInfo()
308 HashtableFind = OperatorInfo()
309 HashtableImport = OperatorInfo()
310 HashtableSize = OperatorInfo()
311 ReduceAll = OperatorInfo()
312 Conv3DTranspose = OperatorInfo()
Rickard Bolin2de898a2021-12-20 08:35:23 +0000313 VarHandle = OperatorInfo()
314 ReadVariable = OperatorInfo()
315 AssignVariable = OperatorInfo()
316 BroadcastArgs = OperatorInfo()
317 RandomStandardNormal = OperatorInfo()
Rickard Bolind66f8012022-04-21 07:36:55 +0000318 Bucketize = OperatorInfo()
319 RandomUniform = OperatorInfo()
320 Multinomial = OperatorInfo()
321 Gelu = OperatorInfo()
322 DynamicUpdateSlice = OperatorInfo()
erik.andersson@arm.comdd49a722022-08-10 15:26:48 +0200323 UnsortedSegmentProd = OperatorInfo()
erik.andersson@arm.com61f05d92022-09-27 12:06:32 +0200324 UnsortedSegmentMax = OperatorInfo()
325 UnsortedSegmentMin = OperatorInfo()
326 UnsortedSegmentSum = OperatorInfo()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200327
328 @property
329 def info(self):
330 return self.value
331
332 @property
333 def npu_block_type(self):
334 return self.info.block_type
335
336 def is_conv2d_op(self):
337 return self.info.block_type == NpuBlockType.ConvolutionMxN
338
339 def is_depthwise_conv2d_op(self):
340 return self.info.block_type == NpuBlockType.ConvolutionDepthWise
341
342 def is_pool_op(self):
343 return self.info.block_type == NpuBlockType.Pooling
344
345 def is_maxpool_op(self):
346 return self in (Op.MaxPool, Op.QuantizedMaxPool)
347
348 def is_avgpool_op(self):
349 return self in (Op.QuantizedAvgPool, Op.AvgPool)
350
351 def is_elementwise_op(self):
352 return self.info.block_type == NpuBlockType.ElementWise
353
354 def is_unary_elementwise_op(self):
355 return self.info.block_type == NpuBlockType.ElementWise and self.info.is_unary
356
357 def is_binary_elementwise_op(self):
358 return self.info.block_type == NpuBlockType.ElementWise and not self.info.is_unary
359
360 def is_relu_op(self):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200361 return self in (Op.Relu, Op.Relu6, Op.ReluN1To1, Op.ReluN, Op.Clip, Op.Clamp)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200362
363 def is_activation_op(self):
Diqing Zhong189f7482021-01-26 12:12:51 +0100364 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 +0200365
366 def is_split_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100367 return self in (Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200368
369 def is_concat_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100370 return self in (Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200371
Tim Hall885033b2022-07-21 11:46:03 +0100372 def is_resize_op(self):
373 return self in (Op.ResizeBilinear, Op.ResizeNearestNeighbor)
374
Louis Verhaardaee5d752020-09-30 09:01:52 +0200375 def needs_bias(self):
376 return bool(self.info.indices.biases)
377
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100378 def needs_shapes(self):
379 return bool(self.info.indices.ifms)
380
Louis Verhaardaee5d752020-09-30 09:01:52 +0200381 @classmethod
382 def op_set(cls, predicate):
383 # Returns the set of all operator codes that fulfill the given predicate
384 return {op_type for op_type in Op if predicate(op_type)}
385
386 def __str__(self):
387 return self.name
388
389 __repr__ = __str__
390
391 def __lt__(self, other):
392 return self.value.id < other.value.id
393
394
Michael McGeagh16895482020-12-14 15:51:20 +0000395class Padding(Enum):
396 SAME = 0
397 VALID = 1
Louis Verhaardae2d5532020-12-11 17:19:54 +0100398 EXPLICIT = 2 # Padding is specified in a PAD operation (only used for NPU operations)
Rickard Bolin9ae34552022-06-09 13:07:17 +0000399 TILE = 3 # Uses hardware tiles to pad by 1 with edge values on two sides of the IFM specified in explicit_padding
Michael McGeagh16895482020-12-14 15:51:20 +0000400
401
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100402class ActivationFunction:
403 """Fused activation function"""
404
405 def __init__(self, op_type: Op):
406 self.op_type = op_type # The activation operation to be performed
407 # min/max are optional; if present they are non-quantized values
408 self.min: Optional[float] = None
409 self.max: Optional[float] = None
410 # Table lookup index, only applicable for Op.LUT activation, 0-7
411 self.lut_index: int = 0
412
413 def clone(self):
414 res = copy.copy(self)
415 return res
416
417
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200418class ExplicitScaling:
419 """Explicit scaling parameters"""
420
421 def __init__(self, per_channel, shift, multiplier):
422 self.per_channel = per_channel
423 self.shift = shift
424 self.multiplier = multiplier
425
426 def clone(self):
427 res = copy.copy(self)
428 return res
429
430
431def create_activation_function(op_type: Op, min=None, max=None) -> ActivationFunction:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100432 """Creates activation function with min/max depending on op_type"""
433 act = ActivationFunction(op_type)
434 if op_type == Op.Relu:
435 act.min = 0.0
436 elif op_type == Op.Relu6:
437 act.min = 0.0
438 act.max = 6.0
439 elif op_type == Op.ReluN1To1:
440 act.min = -1.0
441 act.max = 1.0
442 elif op_type == Op.Tanh:
443 act.min = -1.0
444 act.max = 1.0
445 elif op_type == Op.Sigmoid:
446 act.min = 0.0
447 act.max = 1.0
oliper01c4d35eb2022-06-21 08:51:01 +0000448 elif op_type == Op.Clamp:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200449 assert min is not None and max is not None
450 act.min = min
451 act.max = max
452 elif op_type == Op.ReluN:
453 assert max is not None
454 act.min = 0.0
455 act.max = max
456
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100457 return act
458
459
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100460def get_slice_offsets(input_shape: List[int], offset_tens: Tensor, offset_mask: int, is_begin: bool = True):
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200461 # For strided slice operator: get start or end offsets
462 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
463 for idx in range(len(input_shape)):
464 # If the i:th bit in the mask is set then the value on offset_tens[i] should be ignored
465 if (offset_mask & (1 << idx)) == 0:
466 offsets[idx] = offset_tens.values[idx]
467 if offsets[idx] < 0:
468 # Convert offset to positive value
469 offsets[idx] += input_shape[idx]
470 return offsets
471
472
Tim Hall79d07d22020-04-27 18:20:16 +0100473class Operation:
474 """Class representing a Neural Network operation. Has a name, a type,
Dwight Lidmanc6ac1942020-10-02 14:55:45 +0200475 input and output tensors, as well as an attribute dictionary."""
Tim Hall79d07d22020-04-27 18:20:16 +0100476
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200477 __slots__ = (
478 "type",
Rickard Bolinfea15162022-07-04 16:19:16 +0000479 "_original_type",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200480 "name",
481 "op_index",
482 "attrs",
483 "inputs",
484 "outputs",
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100485 "intermediates",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200486 "flops",
487 "scheduled_pass",
488 "run_on_npu",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200489 "activation",
490 "memory_function",
Dwight Lidman4f728c02020-12-17 15:14:45 +0100491 "forced_input_quantization",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200492 "forced_output_quantization",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200493 "activation_lut",
Tim Hall4ed38bc2020-10-20 18:54:20 +0100494 "_kernel",
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100495 "ifm_shapes",
496 "ofm_shapes",
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100497 "rescale",
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100498 "read_offsets",
Tim Halld8339a72021-05-27 18:49:40 +0100499 "read_shapes",
Louis Verhaard1a92f782021-02-09 16:08:26 +0100500 "rounding_mode",
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200501 "explicit_scaling",
Dwight Lidman4f728c02020-12-17 15:14:45 +0100502 "low_precision_scaling",
Louis Verhaardc822d622021-03-11 14:59:06 +0100503 "write_offset",
504 "write_shape",
Tim Hall3c5cfe92022-03-16 16:31:57 +0000505 "ifm_resampling_mode",
Rickard Bolinfea15162022-07-04 16:19:16 +0000506 "tile_base_offsets_ifm",
507 "tile_base_offsets_ofm",
Rickard Bolin17e53b52022-09-06 16:09:01 +0000508 "ofm_stride_multiplier",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200509 )
Tim Hall79d07d22020-04-27 18:20:16 +0100510
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100511 def __init__(self, op_type: Op, name: str):
Tim Hall79d07d22020-04-27 18:20:16 +0100512 self.type = op_type
Rickard Bolinfea15162022-07-04 16:19:16 +0000513 self._original_type = op_type # the original type of the operation. once set this shouldn't be changed
Tim Hall79d07d22020-04-27 18:20:16 +0100514 self.name = name
Dwight Lidman9b43f842020-12-08 17:56:44 +0100515 self.attrs: Dict[str, Any] = {}
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100516 self.inputs: List[Optional[Tensor]] = []
Dwight Lidman9b43f842020-12-08 17:56:44 +0100517 self.outputs: List[Tensor] = []
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100518 self.intermediates: List[Tensor] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100519 self.flops = 0
520 self.run_on_npu = True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200521 # Fused activation function. If not none: operator code.
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100522 self.activation: Optional[ActivationFunction] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200523 # Fused memory function, if not None: operator code
Louis Verhaardc822d622021-03-11 14:59:06 +0100524 self.memory_function: Optional[Op] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200525 # If not none: contains QuantizationParameters to be used as output quantization
526 # (which overrides the ofm tensor's quantization), used in LUT
Dwight Lidman4f728c02020-12-17 15:14:45 +0100527 self.forced_input_quantization = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200528 self.forced_output_quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100529 self.scheduled_pass = None
Tim Hallc8310b12020-06-17 14:53:11 +0100530 self.op_index = None # input network operator index
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200531 self.activation_lut = None
Tim Hall4ed38bc2020-10-20 18:54:20 +0100532 self._kernel = None
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000533 self.ifm_shapes: List[Shape4D] = []
534 self.ofm_shapes: List[Shape4D] = []
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100535 self.read_offsets: List[Optional[Shape4D]] = [None, None] # offset for [ifm, ifm2]
536 self.read_shapes: List[Optional[Shape4D]] = [None, None] # read shape for [ifm, ifm2]
Louis Verhaard1a92f782021-02-09 16:08:26 +0100537 self.rounding_mode: Optional[NpuRoundingMode] = None
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200538 # Rescale op in TOSA supplies explicit multiplier and shift values
539 self.explicit_scaling: Optional[ExplicitScaling] = None
Dwight Lidman4f728c02020-12-17 15:14:45 +0100540 # The Mean operator (implemented as a depthwise convolution) requires scaling
541 # to be calculated differently in one case. In that case, this is set to True.
542 self.low_precision_scaling = False
Louis Verhaardc822d622021-03-11 14:59:06 +0100543 # Write offset, for operations that only produce a part of the OFM
544 self.write_offset: Optional[Shape4D] = None
545 # The amount of OFM that is produced by the operation (only if write_offset is not None).
546 # E.g. an operation that only fills the bottom row of an OFM of size 1x10x8x1 would have
547 # write_offset 0,9,0,0, write_shape 1,1,8,1
548 self.write_shape: Optional[Shape4D] = None
Tim Hall3c5cfe92022-03-16 16:31:57 +0000549 self.ifm_resampling_mode: resampling_mode = resampling_mode.NONE
Rickard Bolinfea15162022-07-04 16:19:16 +0000550 # ifm (nhwc), ifm2 (nhwc)
551 self.tile_base_offsets_ifm: List[List[int]] = [[0, 0, 0, 0], [0, 0, 0, 0]]
552 # ofm (nhwc)
553 self.tile_base_offsets_ofm: List[int] = [0, 0, 0, 0]
Rickard Bolin17e53b52022-09-06 16:09:01 +0000554 # For interleaved/sparse outputs - stride is multiplied with the stride factor of the corresponding axis
555 # Order is [C, H, W] - default is no multiplication
556 self.ofm_stride_multiplier: List[int] = [1, 1, 1]
Tim Hall79d07d22020-04-27 18:20:16 +0100557
558 def clone(self, suffix="_clone"):
559 res = Operation(self.type, self.name + suffix)
560
Rickard Bolinfea15162022-07-04 16:19:16 +0000561 # maintain the original type, in cases where the type was changed to something different
562 res._original_type = self._original_type
563
Tim Hall79d07d22020-04-27 18:20:16 +0100564 res.attrs = dict(self.attrs)
565 res.inputs = list(self.inputs)
566 res.outputs = list(self.outputs)
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100567 res.intermediates = list(self.intermediates)
Tim Hall79d07d22020-04-27 18:20:16 +0100568 res.flops = self.flops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200569 res.run_on_npu = self.run_on_npu
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100570 res.activation = None if self.activation is None else self.activation.clone()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200571 res.memory_function = self.memory_function
Dwight Lidman4f728c02020-12-17 15:14:45 +0100572 res.forced_input_quantization = self.forced_input_quantization
Louis Verhaardaee5d752020-09-30 09:01:52 +0200573 res.forced_output_quantization = self.forced_output_quantization
Tim Hall79d07d22020-04-27 18:20:16 +0100574 res.scheduled_pass = self.scheduled_pass
Tim Hallc8310b12020-06-17 14:53:11 +0100575 res.op_index = None # not relevant as not part of input network
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100576 res.read_offsets = list(self.read_offsets)
Tim Halld8339a72021-05-27 18:49:40 +0100577 res.read_shapes = list(self.read_shapes)
Rickard Bolinfea15162022-07-04 16:19:16 +0000578 res.write_offset = Shape4D(*self.write_offset) if self.write_offset else None
579 res.write_shape = Shape4D(*self.write_shape) if self.write_shape else None
Louis Verhaard1a92f782021-02-09 16:08:26 +0100580 res.rounding_mode = self.rounding_mode
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200581 res.explicit_scaling = self.explicit_scaling
Dwight Lidman4f728c02020-12-17 15:14:45 +0100582 res.low_precision_scaling = self.low_precision_scaling
Rickard Bolin814d01f2022-04-19 11:48:46 +0000583 res.ifm_resampling_mode = self.ifm_resampling_mode
Rickard Bolinfea15162022-07-04 16:19:16 +0000584 res.tile_base_offsets_ifm = [_ifm.copy() for _ifm in self.tile_base_offsets_ifm]
585 res.tile_base_offsets_ofm = self.tile_base_offsets_ofm.copy()
Rickard Bolin17e53b52022-09-06 16:09:01 +0000586 res.ofm_stride_multiplier = self.ofm_stride_multiplier.copy()
Tim Hall79d07d22020-04-27 18:20:16 +0100587
588 return res
589
590 def __str__(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200591 return "<nng.Operation '{}' type={}>".format(self.name, self.type)
Tim Hall79d07d22020-04-27 18:20:16 +0100592
593 __repr__ = __str__
594
Rickard Bolinfea15162022-07-04 16:19:16 +0000595 @property
596 def original_type(self):
597 return self._original_type
598
Fredrik Svedbergf3c7d552022-11-04 09:48:49 +0100599 @property
600 def type_changed(self):
601 return self.type != self.original_type
602
Michael McGeagh65fd9982020-10-20 11:49:28 +0100603 def get_kernel_size(self):
Tim Hall4ed38bc2020-10-20 18:54:20 +0100604 weights = self.weights
605 if weights and self.type.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.ConvolutionMxN):
606 weight_shape = full_shape(4, weights.shape, 1)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100607 h = weight_shape[-4]
608 w = weight_shape[-3]
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100609 elif self.type.npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum) and "ksize" in self.attrs:
610 h, w = self.attrs["ksize"][1:3]
Tim Hall4ed38bc2020-10-20 18:54:20 +0100611 else:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100612 h = self.attrs.get("filter_height", 1)
613 w = self.attrs.get("filter_width", 1)
614 return w, h
615
616 def get_kernel_stride(self):
617 if "strides" in self.attrs:
618 _, h, w, _ = self.attrs["strides"]
619 else:
620 h = self.attrs.get("stride_h", 1)
621 w = self.attrs.get("stride_w", 1)
622 return w, h
623
624 def get_kernel_dilation(self):
625 if "dilation" in self.attrs:
626 _, h, w, _ = self.attrs["dilation"]
627 else:
628 h = self.attrs.get("dilation_h_factor", 1)
629 w = self.attrs.get("dilation_w_factor", 1)
630 return w, h
631
632 @property
633 def kernel(self):
634 k_w, k_h = self.get_kernel_size()
635 s_w, s_h = self.get_kernel_stride()
636 d_w, d_h = self.get_kernel_dilation()
637 self._kernel = Kernel(k_w, k_h, s_w, s_h, d_w, d_h)
Tim Hall4ed38bc2020-10-20 18:54:20 +0100638 return self._kernel
639
Tim Hall79d07d22020-04-27 18:20:16 +0100640 def get_ifm_ifm2_weights_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200641 return self.ifm, self.ifm2, self.weights, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100642
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200643 def get_ifm_ifm2_ofm(self):
644 return self.ifm, self.ifm2, self.ofm
645
Tim Hall79d07d22020-04-27 18:20:16 +0100646 def get_ifm_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200647 return self.ifm, self.weights, self.bias, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100648
Jacob Bohlin49d92122020-08-19 14:36:46 +0200649 def get_ifm_ifm2_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200650 return self.ifm, self.ifm2, self.weights, self.bias, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200651
Louis Verhaardaee5d752020-09-30 09:01:52 +0200652 def get_ifm_ofm(self):
653 return self.ifm, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200654
Louis Verhaardaee5d752020-09-30 09:01:52 +0200655 @property
656 def ifm(self):
657 # Gets the IFM tensor, or None if not applicable
658 return self.get_input(self.type.info.indices.ifms, 0)
Jacob Bohlin49d92122020-08-19 14:36:46 +0200659
Louis Verhaardaee5d752020-09-30 09:01:52 +0200660 @property
661 def ifm2(self):
662 # Gets the IFM2 tensor, or None if not applicable
663 return self.get_input(self.type.info.indices.ifms, 1)
Louis Verhaard98a34992020-09-01 10:39:04 +0200664
Louis Verhaardaee5d752020-09-30 09:01:52 +0200665 @property
666 def bias(self):
667 # Gets the bias tensor, or None if not applicable
668 return self.get_input(self.type.info.indices.biases, 0)
669
670 @property
671 def weights(self):
672 # Gets the weight tensor, or None if not applicable
673 return self.get_input(self.type.info.indices.weights, 0)
674
675 def get_ifm_tensors(self):
676 # Gets the IFM tensors, or empty list if not applicable
677 return self._index_list_to_tensors(self.type.info.indices.ifms)
678
679 def get_weight_tensors(self):
680 # Gets the weight tensors, or empty list if not applicable
681 return self._index_list_to_tensors(self.type.info.indices.weights)
682
683 def get_bias_tensors(self):
684 # Gets the bias tensors, or empty list if not applicable
685 return self._index_list_to_tensors(self.type.info.indices.biases)
686
687 def _index_list_to_tensors(self, index_list):
688 return [self.inputs[ix] for ix in index_list if ix < len(self.inputs)]
689
690 def get_input(self, index_list, ix):
691 if ix >= len(index_list):
692 return None
693 if index_list[ix] >= len(self.inputs):
694 return None
695 return self.inputs[index_list[ix]]
696
697 @property
698 def ofm(self):
699 # Gets the OFM tensor, or None if not applicable
700 return self.outputs[0] if self.outputs else None
Tim Hall79d07d22020-04-27 18:20:16 +0100701
702 def get_concat_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200703 assert self.type.is_concat_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100704
Louis Verhaardaee5d752020-09-30 09:01:52 +0200705 if self.type == Op.Concat:
Tim Hall79d07d22020-04-27 18:20:16 +0100706 axis_tensor = self.inputs[0]
707 inputs = self.inputs[1:]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200708 elif self.type == Op.ConcatTFLite:
Tim Hall79d07d22020-04-27 18:20:16 +0100709 inputs = self.inputs
710 axis = self.attrs["axis"]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200711 elif self.type == Op.PackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100712 # Requires fixup_pack_input to be called before this point
713 inputs = self.inputs
714 axis = self.attrs["axis"]
715 assert len(self.inputs) == self.attrs["values_count"]
716 else:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200717 assert len(axis_tensor.ops) == 1 and axis_tensor.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100718 axis = int(axis_tensor.values)
719
720 return inputs, axis
721
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200722 def get_dilation_h_w(self):
723 _, dilation_h, dilation_w, _ = self.attrs.get("dilation", (1, 1, 1, 1))
724 return dilation_h, dilation_w
725
Tim Hall79d07d22020-04-27 18:20:16 +0100726 def get_split_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200727 assert self.type.is_split_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100728
729 offset_start = None
730 offset_end = None
731 axis = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200732 if self.type == Op.Split:
Tim Hall79d07d22020-04-27 18:20:16 +0100733 num_splits = self.attrs.get("num_splits")
734 axis_tens = self.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200735 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100736 axis = int(axis_tens.values)
737 input_tens = self.inputs[1]
738 outputs = self.outputs
739 assert num_splits == len(outputs)
740
Louis Verhaardaee5d752020-09-30 09:01:52 +0200741 elif self.type == Op.SplitV:
Charles Xu53d47522020-05-04 11:32:05 +0200742 num_splits = self.attrs.get("num_splits")
743 input_tens = self.inputs[0]
744 size_tens = self.inputs[1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200745 assert len(size_tens.ops) == 1 and size_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200746 sizes = size_tens.values
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200747
Charles Xu53d47522020-05-04 11:32:05 +0200748 axis_tens = self.inputs[2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200749 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200750 axis = int(axis_tens.values)
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200751
752 for idx, size in enumerate(sizes):
753 # One but only one size might be set to -1, indicating that size should be inferred
754 if size == -1:
755 sizes[idx] = input_tens.shape[axis] - (sum(sizes) + 1)
756 break
757
Charles Xu53d47522020-05-04 11:32:05 +0200758 outputs = self.outputs
759 assert num_splits == len(outputs)
760 assert sum(sizes) == input_tens.shape[axis]
761
Louis Verhaardaee5d752020-09-30 09:01:52 +0200762 elif self.type == Op.Slice:
Tim Hall79d07d22020-04-27 18:20:16 +0100763 input_tens, begin_tens, size_tens = self.inputs
764 outputs = self.outputs
765 offset_start = [0] * len(input_tens.shape)
766 offset_end = [0] * len(input_tens.shape)
767
768 for idx in range(len(begin_tens.values)):
Johan Alfvén0b799e42022-10-25 16:22:58 +0200769 offset_start[idx] = begin_tens.values[idx]
770 offset_end[idx] = size_tens.values[idx] + offset_start[idx]
Tim Hall79d07d22020-04-27 18:20:16 +0100771
Louis Verhaardaee5d752020-09-30 09:01:52 +0200772 elif self.type == Op.StridedSlice:
Tim Hall79d07d22020-04-27 18:20:16 +0100773 input_tens, begin_tens, end_tens, strides_tens = self.inputs
774 outputs = self.outputs
Tim Hall79d07d22020-04-27 18:20:16 +0100775
776 # Extract masks
777 begin_mask = self.attrs["begin_mask"]
778 ellipsis_mask = self.attrs["ellipsis_mask"]
779 end_mask = self.attrs["end_mask"]
780 new_axis_mask = self.attrs["new_axis_mask"]
781 shrink_axis_mask = self.attrs["shrink_axis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200782
783 # 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 +0100784 # may have the attribute modified and handled in the graph optimization phase.
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200785 assert shrink_axis_mask == new_axis_mask == ellipsis_mask == 0
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200786 offset_start = get_slice_offsets(input_tens.shape, begin_tens, begin_mask, is_begin=True)
787 offset_end = get_slice_offsets(input_tens.shape, end_tens, end_mask, is_begin=False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200788 elif self.type == Op.UnpackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100789 # Requires fixup_unpack_output to be called before this point
790 input_tens = self.inputs[0]
791 outputs = self.outputs
792 axis = self.attrs["axis"]
793 num_splits = self.attrs["num"]
794 # Number of outputs have to equal the value of the dimension to unpack
795 assert num_splits == len(outputs) == input_tens.shape[axis]
796 else:
797 assert False
798
799 return input_tens, outputs, axis, offset_start, offset_end
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200800
801 def set_activation_lut(self, lut_tensor):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100802 self.activation = ActivationFunction(Op.LUT)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200803 self.activation_lut = lut_tensor
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100804 self.add_input_tensor(lut_tensor)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100805
806 def add_input_tensor(self, tens):
807 self.inputs.append(tens)
808 if self not in tens.consumer_list:
809 tens.consumer_list.append(self)
810
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200811 def set_input_tensor(self, tens, idx):
812 tens_to_remove = self.inputs[idx]
813 if tens_to_remove in tens.consumer_list:
814 tens.consumer_list.remove(tens_to_remove)
815
816 self.inputs[idx] = tens
817 if self not in tens.consumer_list:
818 tens.consumer_list.append(self)
819
Dwight Lidman4f728c02020-12-17 15:14:45 +0100820 def get_input_quantization(self):
821 if self.forced_input_quantization is not None:
822 return self.forced_input_quantization
823 return self.ifm.quantization
824
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100825 def set_output_tensor(self, tens):
826 tens.ops = [self]
827 self.outputs = [tens]
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200828
Louis Verhaard98a34992020-09-01 10:39:04 +0200829 def get_output_quantization(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200830 if self.forced_output_quantization is not None:
831 return self.forced_output_quantization
832 return self.ofm.quantization
Michael McGeagh528a56d2020-12-16 11:33:21 +0000833
834 def error(self, msg):
835 """
836 Raises a VelaError exception for errors encountered when parsing an Operation
837
838 :param self: Operation object that resulted in the error
839 :param msg: str object that contains a description of the specific error encountered
840 """
841
842 def _print_tensors(tensors):
843 lines = []
844 for idx, tens in enumerate(tensors):
845 tens_name = getattr(tens, "name", "Not a Tensor")
846 lines.append(f" {idx} = {tens_name}")
847 return lines
848
849 if self.op_index is None:
850 lines = [f"Invalid {self.type} (name = {self.name}) operator in the internal representation. {msg}"]
851 else:
852 lines = [f"Invalid {self.type} (op_index = {self.op_index}) operator in the input network. {msg}"]
853
854 lines += [" Input tensors:"]
855 lines += _print_tensors(self.inputs)
856
857 lines += [" Output tensors:"]
858 lines += _print_tensors(self.outputs)
859
860 raise VelaError("\n".join(lines))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100861
862 def set_ifm_ofm_shapes(self):
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000863 self.ifm_shapes = []
864 self.ofm_shapes = []
865
Fredrik Svedberg11563172022-07-06 14:54:12 +0200866 ifm_tensor, ifm2_tensor, ofm_tensor = self.get_ifm_ifm2_ofm()
867
868 if self.type == Op.Reshape:
869 # Set ofm shape
870 if len(self.inputs) > 1 and self.inputs[1].values is not None:
871 ofm_tensor.shape = self.inputs[1].values.flatten().tolist()
872 ofm_elements = ofm_tensor.elements()
873 # Stretch dimension
874 if ofm_elements < 0:
875 ofm_tensor.shape[ofm_tensor.shape.index(-1)] = int(ifm_tensor.elements() / abs(ofm_elements))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100876
877 # set all shapes to op, as 4D
878 if self.type == Op.FullyConnected:
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100879 if len(self.ifm.shape) == 2:
880 self.ifm_shapes.append(Shape4D([self.ifm.shape[0], 1, 1, self.ifm.shape[1]]))
881 else:
882 # Special case, handled in graph optimization
883 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
Johan Alfvén65835e02022-10-13 10:49:30 +0200884 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
885
Fredrik Svedberg11563172022-07-06 14:54:12 +0200886 elif self.type == Op.Softmax:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000887 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
888 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100889 elif self.type.is_split_op() or self.type.is_concat_op():
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100890 for inp in self.inputs:
891 if inp is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000892 self.ifm_shapes.append(Shape4D(full_shape(4, inp.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100893 else:
894 self.ifm_shapes.append(None)
895 for out in self.outputs:
896 if out is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000897 self.ofm_shapes.append(Shape4D(full_shape(4, out.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100898 else:
899 self.ofm_shapes.append(None)
900 else:
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100901 if ifm_tensor is not None:
902 self.ifm_shapes.append(Shape4D(full_shape(4, ifm_tensor.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100903 if ifm2_tensor is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000904 self.ifm_shapes.append(Shape4D(full_shape(4, ifm2_tensor.shape, 1)))
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100905 if ofm_tensor is not None:
906 self.ofm_shapes.append(Shape4D(full_shape(4, ofm_tensor.shape, 1)))
Tim Halld8339a72021-05-27 18:49:40 +0100907
908 def has_scaling(self):
909 scaled = True
910 for tensor in [self.ifm, self.ifm2, self.ofm]:
911 if tensor is not None:
912 if tensor.quantization is None:
913 scaled = False
914 break
915
916 return scaled