blob: d5b92d8d0889a71e2b267f41daa85ed6e91842c8 [file] [log] [blame]
Louis Verhaardebf4af62021-01-27 15:57:57 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Internal representation of a Neural Network Operation.
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
Jonas Ohlsson845e2322022-03-01 12:39:55 +010030from typing import Union
Tim Hall79d07d22020-04-27 18:20:16 +010031
Louis Verhaard1a92f782021-02-09 16:08:26 +010032from .api import NpuRoundingMode
Michael McGeagh528a56d2020-12-16 11:33:21 +000033from .errors import VelaError
Tim Hall3c5cfe92022-03-16 16:31:57 +000034from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Tim Hall4ed38bc2020-10-20 18:54:20 +010035from .numeric_util import full_shape
patrik.gustavssoneeb85152020-12-21 17:10:40 +000036from .shape4d import Shape4D
Tim Hall4ed38bc2020-10-20 18:54:20 +010037
Jonas Ohlsson845e2322022-03-01 12:39:55 +010038# 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 +010039if TYPE_CHECKING:
40 from .tensor import Tensor
41
Tim Hall4ed38bc2020-10-20 18:54:20 +010042PointXY = namedtuple("PointXY", "x y")
43PointXYZ = namedtuple("PointXYZ", "x y z")
44
Tim Hall79d07d22020-04-27 18:20:16 +010045
Louis Verhaardaee5d752020-09-30 09:01:52 +020046class NpuBlockType(Enum):
Tim Hall79d07d22020-04-27 18:20:16 +010047 Default = 0
48 ConvolutionMxN = 1
49 VectorProduct = 2
50 Pooling = 3
51 ConvolutionDepthWise = 4
52 ElementWise = 5
Fredrik Svedberga0c36242020-06-03 15:43:31 +020053 ReduceSum = 6
Tim Hall79d07d22020-04-27 18:20:16 +010054
55
Tim Hall4ed38bc2020-10-20 18:54:20 +010056class Kernel:
Louis Verhaarde8a5a782020-11-02 18:04:27 +010057 """
58 Kernel information for NPU operations
59 """
60
Tim Halld8339a72021-05-27 18:49:40 +010061 def __init__(
62 self,
63 w: int,
64 h: int,
65 stride_x: int = 1,
66 stride_y: int = 1,
67 dilation_x: int = 1,
68 dilation_y: int = 1,
69 valid_padding=False,
70 ):
Louis Verhaarde8a5a782020-11-02 18:04:27 +010071 assert stride_x > 0 and stride_y > 0
72 assert dilation_x > 0 and dilation_y > 0
Tim Hall4ed38bc2020-10-20 18:54:20 +010073 self.width = w
74 self.height = h
Louis Verhaarde8a5a782020-11-02 18:04:27 +010075 self.stride = PointXY(stride_x, stride_y)
76 self.dilation = PointXY(dilation_x, dilation_y)
Tim Halld8339a72021-05-27 18:49:40 +010077 self.valid_padding = valid_padding
Tim Hall4ed38bc2020-10-20 18:54:20 +010078
Louis Verhaarde8a5a782020-11-02 18:04:27 +010079 def elements_wh(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010080 return self.width * self.height
81
Louis Verhaarde8a5a782020-11-02 18:04:27 +010082 def area_width(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010083 return (self.width - 1) * self.dilation.x + 1
84
Louis Verhaarde8a5a782020-11-02 18:04:27 +010085 def area_height(self) -> int:
Tim Hall4ed38bc2020-10-20 18:54:20 +010086 return (self.height - 1) * self.dilation.y + 1
87
Louis Verhaardebf4af62021-01-27 15:57:57 +010088 def dilated_wh(self) -> Tuple[int, int]:
89 """Returns the dilated kernel width/height"""
90 return self.dilation.x * (self.width - 1) + 1, self.dilation.y * (self.height - 1) + 1
91
Louis Verhaarde8a5a782020-11-02 18:04:27 +010092 def __str__(self):
93 return f"w={self.width}, h={self.height}, stride={tuple(self.stride)}, dilation={tuple(self.dilation)}"
94
Tim Hall4ed38bc2020-10-20 18:54:20 +010095
Louis Verhaardaee5d752020-09-30 09:01:52 +020096# Classifies operators of type Custom
97class CustomType(Enum):
98 ThirdPartyOp = 0 # Third party custom op
99 NpuOp = 1 # NPU op
100 ExistingNpuOp = 2 # NPU op that was part of the input network
101
102
103TensorIndices = namedtuple("TensorIndices", ["ifms", "weights", "biases"])
104
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200105NNG_NO_INDICES = TensorIndices([], [], [])
106NNG_IFM_INDICES = TensorIndices([0], [], [])
107NNG_IFM_WEIGHTS_INDICES = TensorIndices([0], [1], [])
108NNG_IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2])
109NNG_IFM_IFM2_INDICES = TensorIndices([0, 1], [], [])
110NNG_CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3])
111NNG_TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3])
112NNG_CONCAT_INDICES = TensorIndices([1, 2], [], [])
113NNG_SPLIT_IFM_INDICES = TensorIndices([1], [], [])
114NNG_BLOCK_LSTM_INDICES = TensorIndices([3], [4], [])
Louis Verhaardaee5d752020-09-30 09:01:52 +0200115
116
117# Static information related to operation codes
118class OperatorInfo:
119 __slots__ = ("id", "block_type", "indices", "is_unary")
120 _id = 0
121
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200122 def __init__(self, block_type=NpuBlockType.Default, indices=NNG_NO_INDICES, is_unary=False):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200123 OperatorInfo._id += 1
124 self.id = OperatorInfo._id
125 self.block_type = block_type
126 self.indices = indices # Indices of the different tensor purposes
127 self.is_unary = is_unary # Classifies elementwise operators
128
129
130# Internally used operation codes
131class Op(Enum):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200132 Abs = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_INDICES, is_unary=True)
133 Add = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200134 AddN = OperatorInfo()
135 Any = OperatorInfo()
136 ArgMax = OperatorInfo()
137 ArgMin = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200138 AvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_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()
232 Prelu = OperatorInfo()
233 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)
244 Relu6 = OperatorInfo(indices=NNG_IFM_INDICES)
245 ReluN1To1 = OperatorInfo(indices=NNG_IFM_INDICES)
246 ReluN = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
247 Rescale = OperatorInfo(indices=NNG_IFM_INDICES) # TOSA specific
248 RescaleAdd = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Patrik Gustavssonb081d672021-08-25 13:49:25 +0200249 RescaleMul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200250 Reshape = OperatorInfo(indices=NNG_IFM_INDICES)
251 ResizeBilinear = OperatorInfo(block_type=NpuBlockType.Pooling, indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200252 ResizeNearestNeighbor = OperatorInfo()
253 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()
264 Shape = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200265 Sigmoid = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200266 SignBit = OperatorInfo()
267 Sin = OperatorInfo()
268 SkipGram = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200269 Slice = OperatorInfo(indices=NNG_IFM_INDICES)
270 Softmax = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200271 SpaceToBatchND = OperatorInfo()
272 SpaceToDepth = OperatorInfo()
273 SparseToDense = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200274 Split = OperatorInfo(indices=NNG_SPLIT_IFM_INDICES)
275 SplitSliceRead = OperatorInfo(indices=NNG_IFM_INDICES)
276 SplitV = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200277 Sqrt = OperatorInfo()
278 Square = OperatorInfo()
279 SquaredDifference = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200280 Squeeze = OperatorInfo(indices=NNG_IFM_INDICES)
281 StridedSlice = OperatorInfo(indices=NNG_IFM_INDICES)
282 Sub = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=NNG_IFM_IFM2_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200283 SubgraphInput = OperatorInfo() # Only used in CPU subgraphs
284 Sum = OperatorInfo()
285 Svdf = OperatorInfo()
Patrik Gustavssonf436ada2021-09-14 14:56:48 +0200286 Table = OperatorInfo(indices=NNG_IFM_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200287 Tanh = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200288 Tile = OperatorInfo()
289 TopKV2 = OperatorInfo()
James Ward6bf16132021-09-08 11:14:20 +0100290 Transpose = OperatorInfo(indices=NNG_IFM_IFM2_INDICES)
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200291 UnidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
292 UnidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=NNG_IFM_WEIGHTS_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200293 Unique = OperatorInfo()
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200294 Unpack = OperatorInfo(indices=NNG_IFM_INDICES)
295 UnpackReshaped = OperatorInfo(indices=NNG_IFM_INDICES)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200296 Where = OperatorInfo()
297 While = OperatorInfo()
298 ZerosLike = OperatorInfo()
Dwight Lidman8a12da12021-07-19 13:43:05 +0200299 CallOnce = OperatorInfo()
300 BroadcastTo = OperatorInfo()
301 Rfft2D = OperatorInfo()
302 Conv3D = OperatorInfo()
303 Imag = OperatorInfo()
304 Real = OperatorInfo()
305 ComplexAbs = OperatorInfo()
306 Hashtable = OperatorInfo()
307 HashtableFind = OperatorInfo()
308 HashtableImport = OperatorInfo()
309 HashtableSize = OperatorInfo()
310 ReduceAll = OperatorInfo()
311 Conv3DTranspose = OperatorInfo()
Rickard Bolin2de898a2021-12-20 08:35:23 +0000312 VarHandle = OperatorInfo()
313 ReadVariable = OperatorInfo()
314 AssignVariable = OperatorInfo()
315 BroadcastArgs = OperatorInfo()
316 RandomStandardNormal = OperatorInfo()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200317
318 @property
319 def info(self):
320 return self.value
321
322 @property
323 def npu_block_type(self):
324 return self.info.block_type
325
326 def is_conv2d_op(self):
327 return self.info.block_type == NpuBlockType.ConvolutionMxN
328
329 def is_depthwise_conv2d_op(self):
330 return self.info.block_type == NpuBlockType.ConvolutionDepthWise
331
332 def is_pool_op(self):
333 return self.info.block_type == NpuBlockType.Pooling
334
335 def is_maxpool_op(self):
336 return self in (Op.MaxPool, Op.QuantizedMaxPool)
337
338 def is_avgpool_op(self):
339 return self in (Op.QuantizedAvgPool, Op.AvgPool)
340
341 def is_elementwise_op(self):
342 return self.info.block_type == NpuBlockType.ElementWise
343
344 def is_unary_elementwise_op(self):
345 return self.info.block_type == NpuBlockType.ElementWise and self.info.is_unary
346
347 def is_binary_elementwise_op(self):
348 return self.info.block_type == NpuBlockType.ElementWise and not self.info.is_unary
349
350 def is_relu_op(self):
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200351 return self in (Op.Relu, Op.Relu6, Op.ReluN1To1, Op.ReluN, Op.Clip, Op.Clamp)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200352
353 def is_activation_op(self):
Diqing Zhong189f7482021-01-26 12:12:51 +0100354 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 +0200355
356 def is_split_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100357 return self in (Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200358
359 def is_concat_op(self):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100360 return self in (Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200361
362 def needs_bias(self):
363 return bool(self.info.indices.biases)
364
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100365 def needs_shapes(self):
366 return bool(self.info.indices.ifms)
367
Louis Verhaardaee5d752020-09-30 09:01:52 +0200368 @classmethod
369 def op_set(cls, predicate):
370 # Returns the set of all operator codes that fulfill the given predicate
371 return {op_type for op_type in Op if predicate(op_type)}
372
373 def __str__(self):
374 return self.name
375
376 __repr__ = __str__
377
378 def __lt__(self, other):
379 return self.value.id < other.value.id
380
381
Michael McGeagh16895482020-12-14 15:51:20 +0000382class Padding(Enum):
383 SAME = 0
384 VALID = 1
Louis Verhaardae2d5532020-12-11 17:19:54 +0100385 EXPLICIT = 2 # Padding is specified in a PAD operation (only used for NPU operations)
Michael McGeagh16895482020-12-14 15:51:20 +0000386
387
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100388class ActivationFunction:
389 """Fused activation function"""
390
391 def __init__(self, op_type: Op):
392 self.op_type = op_type # The activation operation to be performed
393 # min/max are optional; if present they are non-quantized values
394 self.min: Optional[float] = None
395 self.max: Optional[float] = None
396 # Table lookup index, only applicable for Op.LUT activation, 0-7
397 self.lut_index: int = 0
398
399 def clone(self):
400 res = copy.copy(self)
401 return res
402
403
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200404class ExplicitScaling:
405 """Explicit scaling parameters"""
406
407 def __init__(self, per_channel, shift, multiplier):
408 self.per_channel = per_channel
409 self.shift = shift
410 self.multiplier = multiplier
411
412 def clone(self):
413 res = copy.copy(self)
414 return res
415
416
417def create_activation_function(op_type: Op, min=None, max=None) -> ActivationFunction:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100418 """Creates activation function with min/max depending on op_type"""
419 act = ActivationFunction(op_type)
420 if op_type == Op.Relu:
421 act.min = 0.0
422 elif op_type == Op.Relu6:
423 act.min = 0.0
424 act.max = 6.0
425 elif op_type == Op.ReluN1To1:
426 act.min = -1.0
427 act.max = 1.0
428 elif op_type == Op.Tanh:
429 act.min = -1.0
430 act.max = 1.0
431 elif op_type == Op.Sigmoid:
432 act.min = 0.0
433 act.max = 1.0
Diqing Zhong189f7482021-01-26 12:12:51 +0100434 elif op_type == Op.HardSwish:
435 act.min = 0.0
Patrik Gustavsson5e26eda2021-06-30 09:07:16 +0200436 if op_type == Op.Clamp:
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200437 assert min is not None and max is not None
438 act.min = min
439 act.max = max
440 elif op_type == Op.ReluN:
441 assert max is not None
442 act.min = 0.0
443 act.max = max
444
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100445 return act
446
447
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100448def get_slice_offsets(input_shape: List[int], offset_tens: Tensor, offset_mask: int, is_begin: bool = True):
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200449 # For strided slice operator: get start or end offsets
450 offsets = len(input_shape) * [0] if is_begin else input_shape[:]
451 for idx in range(len(input_shape)):
452 # If the i:th bit in the mask is set then the value on offset_tens[i] should be ignored
453 if (offset_mask & (1 << idx)) == 0:
454 offsets[idx] = offset_tens.values[idx]
455 if offsets[idx] < 0:
456 # Convert offset to positive value
457 offsets[idx] += input_shape[idx]
458 return offsets
459
460
Tim Hall79d07d22020-04-27 18:20:16 +0100461class Operation:
462 """Class representing a Neural Network operation. Has a name, a type,
Dwight Lidmanc6ac1942020-10-02 14:55:45 +0200463 input and output tensors, as well as an attribute dictionary."""
Tim Hall79d07d22020-04-27 18:20:16 +0100464
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200465 __slots__ = (
466 "type",
467 "name",
468 "op_index",
469 "attrs",
470 "inputs",
471 "outputs",
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100472 "intermediates",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200473 "flops",
474 "scheduled_pass",
475 "run_on_npu",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200476 "activation",
477 "memory_function",
Dwight Lidman4f728c02020-12-17 15:14:45 +0100478 "forced_input_quantization",
Louis Verhaardaee5d752020-09-30 09:01:52 +0200479 "forced_output_quantization",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200480 "activation_lut",
Tim Hall4ed38bc2020-10-20 18:54:20 +0100481 "_kernel",
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100482 "ifm_shapes",
483 "ofm_shapes",
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100484 "rescale",
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100485 "read_offsets",
Tim Halld8339a72021-05-27 18:49:40 +0100486 "read_shapes",
Louis Verhaard1a92f782021-02-09 16:08:26 +0100487 "rounding_mode",
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200488 "explicit_scaling",
Dwight Lidman4f728c02020-12-17 15:14:45 +0100489 "low_precision_scaling",
Louis Verhaardc822d622021-03-11 14:59:06 +0100490 "write_offset",
491 "write_shape",
Tim Hall3c5cfe92022-03-16 16:31:57 +0000492 "ifm_resampling_mode",
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200493 )
Tim Hall79d07d22020-04-27 18:20:16 +0100494
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100495 def __init__(self, op_type: Op, name: str):
Tim Hall79d07d22020-04-27 18:20:16 +0100496 self.type = op_type
497 self.name = name
Dwight Lidman9b43f842020-12-08 17:56:44 +0100498 self.attrs: Dict[str, Any] = {}
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100499 self.inputs: List[Optional[Tensor]] = []
Dwight Lidman9b43f842020-12-08 17:56:44 +0100500 self.outputs: List[Tensor] = []
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100501 self.intermediates: List[Tensor] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100502 self.flops = 0
503 self.run_on_npu = True
Louis Verhaardaee5d752020-09-30 09:01:52 +0200504 # Fused activation function. If not none: operator code.
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100505 self.activation: Optional[ActivationFunction] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200506 # Fused memory function, if not None: operator code
Louis Verhaardc822d622021-03-11 14:59:06 +0100507 self.memory_function: Optional[Op] = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200508 # If not none: contains QuantizationParameters to be used as output quantization
509 # (which overrides the ofm tensor's quantization), used in LUT
Dwight Lidman4f728c02020-12-17 15:14:45 +0100510 self.forced_input_quantization = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200511 self.forced_output_quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100512 self.scheduled_pass = None
Tim Hallc8310b12020-06-17 14:53:11 +0100513 self.op_index = None # input network operator index
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200514 self.activation_lut = None
Tim Hall4ed38bc2020-10-20 18:54:20 +0100515 self._kernel = None
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000516 self.ifm_shapes: List[Shape4D] = []
517 self.ofm_shapes: List[Shape4D] = []
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100518 # If not none: contains rescale to be used as output scaling
519 # (which overrides the ofm tensor's scale)
Jonas Ohlsson845e2322022-03-01 12:39:55 +0100520 self.rescale: Optional[Union[Tuple[int, int], ExplicitScaling]] = None
521 self.read_offsets: List[Optional[Shape4D]] = [None, None] # offset for [ifm, ifm2]
522 self.read_shapes: List[Optional[Shape4D]] = [None, None] # read shape for [ifm, ifm2]
Louis Verhaard1a92f782021-02-09 16:08:26 +0100523 self.rounding_mode: Optional[NpuRoundingMode] = None
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200524 # Rescale op in TOSA supplies explicit multiplier and shift values
525 self.explicit_scaling: Optional[ExplicitScaling] = None
Dwight Lidman4f728c02020-12-17 15:14:45 +0100526 # The Mean operator (implemented as a depthwise convolution) requires scaling
527 # to be calculated differently in one case. In that case, this is set to True.
528 self.low_precision_scaling = False
Louis Verhaardc822d622021-03-11 14:59:06 +0100529 # Write offset, for operations that only produce a part of the OFM
530 self.write_offset: Optional[Shape4D] = None
531 # The amount of OFM that is produced by the operation (only if write_offset is not None).
532 # E.g. an operation that only fills the bottom row of an OFM of size 1x10x8x1 would have
533 # write_offset 0,9,0,0, write_shape 1,1,8,1
534 self.write_shape: Optional[Shape4D] = None
Tim Hall3c5cfe92022-03-16 16:31:57 +0000535 self.ifm_resampling_mode: resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100536
537 def clone(self, suffix="_clone"):
538 res = Operation(self.type, self.name + suffix)
539
540 res.attrs = dict(self.attrs)
541 res.inputs = list(self.inputs)
542 res.outputs = list(self.outputs)
Fredrik Svedberg8d0f4892021-02-16 21:59:50 +0100543 res.intermediates = list(self.intermediates)
Tim Hall79d07d22020-04-27 18:20:16 +0100544 res.flops = self.flops
Louis Verhaardaee5d752020-09-30 09:01:52 +0200545 res.run_on_npu = self.run_on_npu
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100546 res.activation = None if self.activation is None else self.activation.clone()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200547 res.memory_function = self.memory_function
Dwight Lidman4f728c02020-12-17 15:14:45 +0100548 res.forced_input_quantization = self.forced_input_quantization
Louis Verhaardaee5d752020-09-30 09:01:52 +0200549 res.forced_output_quantization = self.forced_output_quantization
Tim Hall79d07d22020-04-27 18:20:16 +0100550 res.scheduled_pass = self.scheduled_pass
Tim Hallc8310b12020-06-17 14:53:11 +0100551 res.op_index = None # not relevant as not part of input network
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100552 res.read_offsets = list(self.read_offsets)
Tim Halld8339a72021-05-27 18:49:40 +0100553 res.read_shapes = list(self.read_shapes)
Louis Verhaard1a92f782021-02-09 16:08:26 +0100554 res.rounding_mode = self.rounding_mode
Patrik Gustavsson8f1f9aa2021-06-28 07:41:58 +0200555 res.explicit_scaling = self.explicit_scaling
Dwight Lidman4f728c02020-12-17 15:14:45 +0100556 res.low_precision_scaling = self.low_precision_scaling
Patrik Gustavsson46408a82021-09-20 10:47:47 +0200557 res.rescale = self.rescale
Tim Hall79d07d22020-04-27 18:20:16 +0100558
559 return res
560
561 def __str__(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200562 return "<nng.Operation '{}' type={}>".format(self.name, self.type)
Tim Hall79d07d22020-04-27 18:20:16 +0100563
564 __repr__ = __str__
565
Michael McGeagh65fd9982020-10-20 11:49:28 +0100566 def get_kernel_size(self):
Tim Hall4ed38bc2020-10-20 18:54:20 +0100567 weights = self.weights
568 if weights and self.type.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.ConvolutionMxN):
569 weight_shape = full_shape(4, weights.shape, 1)
Michael McGeagh65fd9982020-10-20 11:49:28 +0100570 h = weight_shape[-4]
571 w = weight_shape[-3]
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100572 elif self.type.npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum) and "ksize" in self.attrs:
573 h, w = self.attrs["ksize"][1:3]
Tim Hall4ed38bc2020-10-20 18:54:20 +0100574 else:
Michael McGeagh65fd9982020-10-20 11:49:28 +0100575 h = self.attrs.get("filter_height", 1)
576 w = self.attrs.get("filter_width", 1)
577 return w, h
578
579 def get_kernel_stride(self):
580 if "strides" in self.attrs:
581 _, h, w, _ = self.attrs["strides"]
582 else:
583 h = self.attrs.get("stride_h", 1)
584 w = self.attrs.get("stride_w", 1)
585 return w, h
586
587 def get_kernel_dilation(self):
588 if "dilation" in self.attrs:
589 _, h, w, _ = self.attrs["dilation"]
590 else:
591 h = self.attrs.get("dilation_h_factor", 1)
592 w = self.attrs.get("dilation_w_factor", 1)
593 return w, h
594
595 @property
596 def kernel(self):
597 k_w, k_h = self.get_kernel_size()
598 s_w, s_h = self.get_kernel_stride()
599 d_w, d_h = self.get_kernel_dilation()
600 self._kernel = Kernel(k_w, k_h, s_w, s_h, d_w, d_h)
Tim Hall4ed38bc2020-10-20 18:54:20 +0100601 return self._kernel
602
Tim Hall79d07d22020-04-27 18:20:16 +0100603 def get_ifm_ifm2_weights_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200604 return self.ifm, self.ifm2, self.weights, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100605
Patrik Gustavssone2bfa7e2021-09-08 15:04:11 +0200606 def get_ifm_ifm2_ofm(self):
607 return self.ifm, self.ifm2, self.ofm
608
Tim Hall79d07d22020-04-27 18:20:16 +0100609 def get_ifm_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200610 return self.ifm, self.weights, self.bias, self.ofm
Tim Hall79d07d22020-04-27 18:20:16 +0100611
Jacob Bohlin49d92122020-08-19 14:36:46 +0200612 def get_ifm_ifm2_weights_biases_ofm(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200613 return self.ifm, self.ifm2, self.weights, self.bias, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200614
Louis Verhaardaee5d752020-09-30 09:01:52 +0200615 def get_ifm_ofm(self):
616 return self.ifm, self.ofm
Jacob Bohlin49d92122020-08-19 14:36:46 +0200617
Louis Verhaardaee5d752020-09-30 09:01:52 +0200618 @property
619 def ifm(self):
620 # Gets the IFM tensor, or None if not applicable
621 return self.get_input(self.type.info.indices.ifms, 0)
Jacob Bohlin49d92122020-08-19 14:36:46 +0200622
Louis Verhaardaee5d752020-09-30 09:01:52 +0200623 @property
624 def ifm2(self):
625 # Gets the IFM2 tensor, or None if not applicable
626 return self.get_input(self.type.info.indices.ifms, 1)
Louis Verhaard98a34992020-09-01 10:39:04 +0200627
Louis Verhaardaee5d752020-09-30 09:01:52 +0200628 @property
629 def bias(self):
630 # Gets the bias tensor, or None if not applicable
631 return self.get_input(self.type.info.indices.biases, 0)
632
633 @property
634 def weights(self):
635 # Gets the weight tensor, or None if not applicable
636 return self.get_input(self.type.info.indices.weights, 0)
637
638 def get_ifm_tensors(self):
639 # Gets the IFM tensors, or empty list if not applicable
640 return self._index_list_to_tensors(self.type.info.indices.ifms)
641
642 def get_weight_tensors(self):
643 # Gets the weight tensors, or empty list if not applicable
644 return self._index_list_to_tensors(self.type.info.indices.weights)
645
646 def get_bias_tensors(self):
647 # Gets the bias tensors, or empty list if not applicable
648 return self._index_list_to_tensors(self.type.info.indices.biases)
649
650 def _index_list_to_tensors(self, index_list):
651 return [self.inputs[ix] for ix in index_list if ix < len(self.inputs)]
652
653 def get_input(self, index_list, ix):
654 if ix >= len(index_list):
655 return None
656 if index_list[ix] >= len(self.inputs):
657 return None
658 return self.inputs[index_list[ix]]
659
660 @property
661 def ofm(self):
662 # Gets the OFM tensor, or None if not applicable
663 return self.outputs[0] if self.outputs else None
Tim Hall79d07d22020-04-27 18:20:16 +0100664
665 def get_concat_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200666 assert self.type.is_concat_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100667
Louis Verhaardaee5d752020-09-30 09:01:52 +0200668 if self.type == Op.Concat:
Tim Hall79d07d22020-04-27 18:20:16 +0100669 axis_tensor = self.inputs[0]
670 inputs = self.inputs[1:]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200671 elif self.type == Op.ConcatTFLite:
Tim Hall79d07d22020-04-27 18:20:16 +0100672 inputs = self.inputs
673 axis = self.attrs["axis"]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200674 elif self.type == Op.PackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100675 # Requires fixup_pack_input to be called before this point
676 inputs = self.inputs
677 axis = self.attrs["axis"]
678 assert len(self.inputs) == self.attrs["values_count"]
679 else:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200680 assert len(axis_tensor.ops) == 1 and axis_tensor.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100681 axis = int(axis_tensor.values)
682
683 return inputs, axis
684
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200685 def get_dilation_h_w(self):
686 _, dilation_h, dilation_w, _ = self.attrs.get("dilation", (1, 1, 1, 1))
687 return dilation_h, dilation_w
688
Tim Hall79d07d22020-04-27 18:20:16 +0100689 def get_split_inputs_axis(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200690 assert self.type.is_split_op()
Tim Hall79d07d22020-04-27 18:20:16 +0100691
692 offset_start = None
693 offset_end = None
694 axis = None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200695 if self.type == Op.Split:
Tim Hall79d07d22020-04-27 18:20:16 +0100696 num_splits = self.attrs.get("num_splits")
697 axis_tens = self.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200698 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Tim Hall79d07d22020-04-27 18:20:16 +0100699 axis = int(axis_tens.values)
700 input_tens = self.inputs[1]
701 outputs = self.outputs
702 assert num_splits == len(outputs)
703
Louis Verhaardaee5d752020-09-30 09:01:52 +0200704 elif self.type == Op.SplitV:
Charles Xu53d47522020-05-04 11:32:05 +0200705 num_splits = self.attrs.get("num_splits")
706 input_tens = self.inputs[0]
707 size_tens = self.inputs[1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200708 assert len(size_tens.ops) == 1 and size_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200709 sizes = size_tens.values
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200710
Charles Xu53d47522020-05-04 11:32:05 +0200711 axis_tens = self.inputs[2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200712 assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const
Charles Xu53d47522020-05-04 11:32:05 +0200713 axis = int(axis_tens.values)
Patrik Gustavsson271ddc32020-09-01 09:15:27 +0200714
715 for idx, size in enumerate(sizes):
716 # One but only one size might be set to -1, indicating that size should be inferred
717 if size == -1:
718 sizes[idx] = input_tens.shape[axis] - (sum(sizes) + 1)
719 break
720
Charles Xu53d47522020-05-04 11:32:05 +0200721 outputs = self.outputs
722 assert num_splits == len(outputs)
723 assert sum(sizes) == input_tens.shape[axis]
724
Louis Verhaardaee5d752020-09-30 09:01:52 +0200725 elif self.type == Op.Slice:
Tim Hall79d07d22020-04-27 18:20:16 +0100726 input_tens, begin_tens, size_tens = self.inputs
727 outputs = self.outputs
728 offset_start = [0] * len(input_tens.shape)
729 offset_end = [0] * len(input_tens.shape)
730
731 for idx in range(len(begin_tens.values)):
732 # Check if the op should slice in dimension idx
733 if size_tens.values[idx] != input_tens.shape[idx]:
734 offset_start[idx] = begin_tens.values[idx]
735 offset_end[idx] = size_tens.values[idx] + offset_start[idx]
736
Louis Verhaardaee5d752020-09-30 09:01:52 +0200737 elif self.type == Op.StridedSlice:
Tim Hall79d07d22020-04-27 18:20:16 +0100738 input_tens, begin_tens, end_tens, strides_tens = self.inputs
739 outputs = self.outputs
Tim Hall79d07d22020-04-27 18:20:16 +0100740
741 # Extract masks
742 begin_mask = self.attrs["begin_mask"]
743 ellipsis_mask = self.attrs["ellipsis_mask"]
744 end_mask = self.attrs["end_mask"]
745 new_axis_mask = self.attrs["new_axis_mask"]
746 shrink_axis_mask = self.attrs["shrink_axis_mask"]
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200747
748 # 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 +0100749 # may have the attribute modified and handled in the graph optimization phase.
Patrik Gustavssoncf728902020-04-30 08:57:23 +0200750 assert shrink_axis_mask == new_axis_mask == ellipsis_mask == 0
Louis Verhaardfa2f92a2020-09-21 11:56:18 +0200751 offset_start = get_slice_offsets(input_tens.shape, begin_tens, begin_mask, is_begin=True)
752 offset_end = get_slice_offsets(input_tens.shape, end_tens, end_mask, is_begin=False)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200753 elif self.type == Op.UnpackReshaped:
Tim Hall79d07d22020-04-27 18:20:16 +0100754 # Requires fixup_unpack_output to be called before this point
755 input_tens = self.inputs[0]
756 outputs = self.outputs
757 axis = self.attrs["axis"]
758 num_splits = self.attrs["num"]
759 # Number of outputs have to equal the value of the dimension to unpack
760 assert num_splits == len(outputs) == input_tens.shape[axis]
761 else:
762 assert False
763
764 return input_tens, outputs, axis, offset_start, offset_end
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200765
766 def set_activation_lut(self, lut_tensor):
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100767 self.activation = ActivationFunction(Op.LUT)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200768 self.activation_lut = lut_tensor
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100769 self.add_input_tensor(lut_tensor)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100770
771 def add_input_tensor(self, tens):
772 self.inputs.append(tens)
773 if self not in tens.consumer_list:
774 tens.consumer_list.append(self)
775
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +0200776 def set_input_tensor(self, tens, idx):
777 tens_to_remove = self.inputs[idx]
778 if tens_to_remove in tens.consumer_list:
779 tens.consumer_list.remove(tens_to_remove)
780
781 self.inputs[idx] = tens
782 if self not in tens.consumer_list:
783 tens.consumer_list.append(self)
784
Dwight Lidman4f728c02020-12-17 15:14:45 +0100785 def get_input_quantization(self):
786 if self.forced_input_quantization is not None:
787 return self.forced_input_quantization
788 return self.ifm.quantization
789
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100790 def set_output_tensor(self, tens):
791 tens.ops = [self]
792 self.outputs = [tens]
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200793
Louis Verhaard98a34992020-09-01 10:39:04 +0200794 def get_output_quantization(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200795 if self.forced_output_quantization is not None:
796 return self.forced_output_quantization
797 return self.ofm.quantization
Michael McGeagh528a56d2020-12-16 11:33:21 +0000798
799 def error(self, msg):
800 """
801 Raises a VelaError exception for errors encountered when parsing an Operation
802
803 :param self: Operation object that resulted in the error
804 :param msg: str object that contains a description of the specific error encountered
805 """
806
807 def _print_tensors(tensors):
808 lines = []
809 for idx, tens in enumerate(tensors):
810 tens_name = getattr(tens, "name", "Not a Tensor")
811 lines.append(f" {idx} = {tens_name}")
812 return lines
813
814 if self.op_index is None:
815 lines = [f"Invalid {self.type} (name = {self.name}) operator in the internal representation. {msg}"]
816 else:
817 lines = [f"Invalid {self.type} (op_index = {self.op_index}) operator in the input network. {msg}"]
818
819 lines += [" Input tensors:"]
820 lines += _print_tensors(self.inputs)
821
822 lines += [" Output tensors:"]
823 lines += _print_tensors(self.outputs)
824
825 raise VelaError("\n".join(lines))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100826
827 def set_ifm_ofm_shapes(self):
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000828 self.ifm_shapes = []
829 self.ofm_shapes = []
830
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100831 ifm_tensor, ifm2_tensor, weight_tensor, ofm_tensor = self.get_ifm_ifm2_weights_ofm()
832
833 # set all shapes to op, as 4D
834 if self.type == Op.FullyConnected:
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100835 if len(self.ifm.shape) == 2:
836 self.ifm_shapes.append(Shape4D([self.ifm.shape[0], 1, 1, self.ifm.shape[1]]))
837 else:
838 # Special case, handled in graph optimization
839 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
840 if len(self.ofm.shape) == 2:
841 self.ofm_shapes.append(Shape4D([self.ofm.shape[0], 1, 1, self.ofm.shape[1]]))
842 else:
843 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
844 if self.type == Op.Softmax:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000845 self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape()))
846 self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape()))
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100847 elif self.type.is_split_op() or self.type.is_concat_op():
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100848 for inp in self.inputs:
849 if inp is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000850 self.ifm_shapes.append(Shape4D(full_shape(4, inp.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100851 else:
852 self.ifm_shapes.append(None)
853 for out in self.outputs:
854 if out is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000855 self.ofm_shapes.append(Shape4D(full_shape(4, out.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100856 else:
857 self.ofm_shapes.append(None)
858 else:
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100859 if ifm_tensor is not None:
860 self.ifm_shapes.append(Shape4D(full_shape(4, ifm_tensor.shape, 1)))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100861 if ifm2_tensor is not None:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000862 self.ifm_shapes.append(Shape4D(full_shape(4, ifm2_tensor.shape, 1)))
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100863 if ofm_tensor is not None:
864 self.ofm_shapes.append(Shape4D(full_shape(4, ofm_tensor.shape, 1)))
Tim Halld8339a72021-05-27 18:49:40 +0100865
866 def has_scaling(self):
867 scaled = True
868 for tensor in [self.ifm, self.ifm2, self.ofm]:
869 if tensor is not None:
870 if tensor.quantization is None:
871 scaled = False
872 break
873
874 return scaled