Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1 | # Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved. |
| 2 | # |
| 3 | # SPDX-License-Identifier: Apache-2.0 |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the License); you may |
| 6 | # not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an AS IS BASIS, WITHOUT |
| 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 16 | # Description: |
| 17 | # Internal representation of a Neural Network Operation. |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 18 | import copy |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 19 | from collections import namedtuple |
| 20 | from enum import Enum |
Dwight Lidman | 9b43f84 | 2020-12-08 17:56:44 +0100 | [diff] [blame] | 21 | from typing import Any |
| 22 | from typing import Dict |
| 23 | from typing import List |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 24 | from typing import Optional |
Dwight Lidman | 9b43f84 | 2020-12-08 17:56:44 +0100 | [diff] [blame] | 25 | from typing import TYPE_CHECKING |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 26 | |
Michael McGeagh | 528a56d | 2020-12-16 11:33:21 +0000 | [diff] [blame] | 27 | from .errors import VelaError |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 28 | from .numeric_util import full_shape |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 29 | from .shape4d import Shape4D |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 30 | |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 31 | |
Dwight Lidman | 9b43f84 | 2020-12-08 17:56:44 +0100 | [diff] [blame] | 32 | if TYPE_CHECKING: |
| 33 | from .tensor import Tensor |
| 34 | |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 35 | PointXY = namedtuple("PointXY", "x y") |
| 36 | PointXYZ = namedtuple("PointXYZ", "x y z") |
| 37 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 38 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 39 | class NpuBlockType(Enum): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 40 | Default = 0 |
| 41 | ConvolutionMxN = 1 |
| 42 | VectorProduct = 2 |
| 43 | Pooling = 3 |
| 44 | ConvolutionDepthWise = 4 |
| 45 | ElementWise = 5 |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 46 | ReduceSum = 6 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 47 | |
| 48 | |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 49 | class Kernel: |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 50 | """ |
| 51 | Kernel information for NPU operations |
| 52 | """ |
| 53 | |
| 54 | def __init__(self, w: int, h: int, stride_x: int = 1, stride_y: int = 1, dilation_x: int = 1, dilation_y: int = 1): |
| 55 | assert stride_x > 0 and stride_y > 0 |
| 56 | assert dilation_x > 0 and dilation_y > 0 |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 57 | self.width = w |
| 58 | self.height = h |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 59 | self.stride = PointXY(stride_x, stride_y) |
| 60 | self.dilation = PointXY(dilation_x, dilation_y) |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 61 | |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 62 | def elements_wh(self) -> int: |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 63 | return self.width * self.height |
| 64 | |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 65 | def area_width(self) -> int: |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 66 | return (self.width - 1) * self.dilation.x + 1 |
| 67 | |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 68 | def area_height(self) -> int: |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 69 | return (self.height - 1) * self.dilation.y + 1 |
| 70 | |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 71 | def __str__(self): |
| 72 | return f"w={self.width}, h={self.height}, stride={tuple(self.stride)}, dilation={tuple(self.dilation)}" |
| 73 | |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 74 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 75 | # Classifies operators of type Custom |
| 76 | class CustomType(Enum): |
| 77 | ThirdPartyOp = 0 # Third party custom op |
| 78 | NpuOp = 1 # NPU op |
| 79 | ExistingNpuOp = 2 # NPU op that was part of the input network |
| 80 | |
| 81 | |
| 82 | TensorIndices = namedtuple("TensorIndices", ["ifms", "weights", "biases"]) |
| 83 | |
| 84 | NO_INDICES = TensorIndices([], [], []) |
| 85 | IFM_INDICES = TensorIndices([0], [], []) |
| 86 | IFM_WEIGHTS_INDICES = TensorIndices([0], [1], []) |
| 87 | IFM_WEIGHTS_BIAS_INDICES = TensorIndices([0], [1], [2]) |
| 88 | IFM_IFM2_INDICES = TensorIndices([0, 1], [], []) |
| 89 | CONV2D_BACKPROP_INDICES = TensorIndices([2], [1], [3]) |
| 90 | TRANSPOSE_CONV_INDICES = TensorIndices([0], [1], [3]) |
| 91 | CONCAT_INDICES = TensorIndices([1, 2], [], []) |
| 92 | SPLIT_IFM_INDICES = TensorIndices([1], [], []) |
| 93 | BLOCK_LSTM_INDICES = TensorIndices([3], [4], []) |
| 94 | |
| 95 | |
| 96 | # Static information related to operation codes |
| 97 | class OperatorInfo: |
| 98 | __slots__ = ("id", "block_type", "indices", "is_unary") |
| 99 | _id = 0 |
| 100 | |
| 101 | def __init__(self, block_type=NpuBlockType.Default, indices=NO_INDICES, is_unary=False): |
| 102 | OperatorInfo._id += 1 |
| 103 | self.id = OperatorInfo._id |
| 104 | self.block_type = block_type |
| 105 | self.indices = indices # Indices of the different tensor purposes |
| 106 | self.is_unary = is_unary # Classifies elementwise operators |
| 107 | |
| 108 | |
| 109 | # Internally used operation codes |
| 110 | class Op(Enum): |
| 111 | Abs = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True) |
| 112 | Add = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) |
| 113 | AddN = OperatorInfo() |
| 114 | Any = OperatorInfo() |
| 115 | ArgMax = OperatorInfo() |
| 116 | ArgMin = OperatorInfo() |
| 117 | AvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES) |
| 118 | BatchMatMul = OperatorInfo() |
| 119 | BatchToSpaceND = OperatorInfo() |
| 120 | BidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 121 | BidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 122 | BlockLSTM = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=BLOCK_LSTM_INDICES) |
| 123 | |
| 124 | CLZ = OperatorInfo( |
| 125 | block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True |
| 126 | ) # NPU specific operation |
| 127 | Call = OperatorInfo() |
| 128 | Cast = OperatorInfo() |
| 129 | Ceil = OperatorInfo() |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 130 | Clip = OperatorInfo() # NPU specific fused activation function for clipping between activation.min/max |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 131 | Concat = OperatorInfo(indices=CONCAT_INDICES) |
| 132 | ConcatEmbeddings = OperatorInfo() |
| 133 | ConcatSliceWrite = OperatorInfo(indices=IFM_INDICES) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 134 | ConcatTFLite = OperatorInfo(indices=CONCAT_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 135 | Const = OperatorInfo() # Constant tensor, only used in CPU subgraphs |
| 136 | Conv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES) |
| 137 | Conv2DBackpropInput = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=CONV2D_BACKPROP_INDICES) |
| 138 | Conv2DBackpropInputSwitchedBias = OperatorInfo( |
| 139 | block_type=NpuBlockType.ConvolutionMxN, indices=TRANSPOSE_CONV_INDICES |
| 140 | ) |
| 141 | Conv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_BIAS_INDICES) |
| 142 | Cos = OperatorInfo() |
| 143 | Custom = OperatorInfo() # Custom 3rd party operator, only used in CPU subgraphs |
| 144 | CustomNpuOp = OperatorInfo() # NPU custom operator, only used in CPU subgraphs |
| 145 | DMA = OperatorInfo() |
| 146 | Delegate = OperatorInfo() |
| 147 | Densify = OperatorInfo() |
| 148 | DepthToSpace = OperatorInfo() |
| 149 | DepthwiseConv2DBias = OperatorInfo(block_type=NpuBlockType.ConvolutionDepthWise, indices=IFM_WEIGHTS_BIAS_INDICES) |
Louis Verhaard | 04f8c00 | 2020-10-09 11:40:21 +0200 | [diff] [blame] | 150 | Dequantize = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 151 | Div = OperatorInfo() |
| 152 | Elu = OperatorInfo() |
| 153 | EmbeddingLookup = OperatorInfo() |
| 154 | EmbeddingLookupSparse = OperatorInfo() |
| 155 | Equal = OperatorInfo() |
| 156 | Exp = OperatorInfo() |
| 157 | ExpandDims = OperatorInfo(indices=IFM_INDICES) |
| 158 | FakeQuantWithMinMaxArgs = OperatorInfo() |
| 159 | Fill = OperatorInfo() |
| 160 | Floor = OperatorInfo() |
| 161 | FloorDiv = OperatorInfo() |
| 162 | FloorMod = OperatorInfo() |
| 163 | FullyConnected = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_BIAS_INDICES) |
| 164 | GatherNd = OperatorInfo() |
| 165 | GatherV2 = OperatorInfo() |
| 166 | Greater = OperatorInfo() |
| 167 | GreaterEqual = OperatorInfo() |
Diqing Zhong | 189f748 | 2021-01-26 12:12:51 +0100 | [diff] [blame^] | 168 | HardSwish = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 169 | HashtableLookup = OperatorInfo() |
| 170 | Identity = OperatorInfo() |
| 171 | If = OperatorInfo() |
| 172 | L2Norm = OperatorInfo() |
| 173 | L2Pool2D = OperatorInfo() |
| 174 | LRN = OperatorInfo() |
| 175 | LSHProjection = OperatorInfo() |
| 176 | LeakyRelu = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_INDICES, is_unary=True) |
| 177 | Less = OperatorInfo() |
| 178 | LessEqual = OperatorInfo() |
| 179 | Log = OperatorInfo() |
| 180 | LogSoftmax = OperatorInfo() |
| 181 | LogicalAnd = OperatorInfo() |
| 182 | LogicalNot = OperatorInfo() |
| 183 | LogicalOr = OperatorInfo() |
| 184 | Lstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 185 | LUT = OperatorInfo() # NPU specific, operator has LUT, only used in fused activation functions |
| 186 | MatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 187 | MatrixDiag = OperatorInfo() |
| 188 | MatrixSetDiag = OperatorInfo() |
| 189 | Max = OperatorInfo() |
| 190 | MaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES) |
| 191 | Maximum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) |
| 192 | Mean = OperatorInfo() |
| 193 | Min = OperatorInfo() |
| 194 | Minimum = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) |
| 195 | MirrorPad = OperatorInfo() |
| 196 | Mul = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) |
| 197 | Neg = OperatorInfo() |
| 198 | NonMaxSuppressionV4 = OperatorInfo() |
| 199 | NonMaxSuppressionV5 = OperatorInfo() |
| 200 | NotEqual = OperatorInfo() |
| 201 | OneHot = OperatorInfo() |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 202 | Pack = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 203 | PackReshaped = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 204 | Pad = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 205 | PadV2 = OperatorInfo() |
| 206 | Placeholder = OperatorInfo() # Only used in CPU subgraphs |
| 207 | Pow = OperatorInfo() |
| 208 | Prelu = OperatorInfo() |
| 209 | Prod = OperatorInfo() |
Louis Verhaard | 04f8c00 | 2020-10-09 11:40:21 +0200 | [diff] [blame] | 210 | Quantize = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 211 | QuantizedAvgPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES) |
| 212 | QuantizedConv2D = OperatorInfo(block_type=NpuBlockType.ConvolutionMxN, indices=IFM_WEIGHTS_INDICES) |
| 213 | QuantizedMatMul = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 214 | QuantizedMaxPool = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES) |
| 215 | QuantizedReshape = OperatorInfo(indices=IFM_INDICES) |
| 216 | Range = OperatorInfo() |
| 217 | Rank = OperatorInfo() |
| 218 | ReduceSum = OperatorInfo(block_type=NpuBlockType.ReduceSum, indices=IFM_INDICES) |
| 219 | Relu = OperatorInfo(indices=IFM_INDICES) |
| 220 | Relu6 = OperatorInfo(indices=IFM_INDICES) |
| 221 | ReluN1To1 = OperatorInfo(indices=IFM_INDICES) |
Fredrik Svedberg | e82be7c | 2021-01-18 15:21:03 +0100 | [diff] [blame] | 222 | RescaleAdd = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 223 | Reshape = OperatorInfo(indices=IFM_INDICES) |
| 224 | ResizeBilinear = OperatorInfo(block_type=NpuBlockType.Pooling, indices=IFM_INDICES) |
| 225 | ResizeNearestNeighbor = OperatorInfo() |
| 226 | ReverseSequence = OperatorInfo() |
| 227 | ReverseV2 = OperatorInfo() |
| 228 | Rnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 229 | Round = OperatorInfo() |
| 230 | Rsqrt = OperatorInfo() |
| 231 | SHL = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation |
| 232 | SHR = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) # NPU specific operation |
| 233 | ScatterNd = OperatorInfo() |
| 234 | SegmentSum = OperatorInfo() |
| 235 | Select = OperatorInfo() |
| 236 | SelectV2 = OperatorInfo() |
| 237 | Shape = OperatorInfo() |
| 238 | Sigmoid = OperatorInfo(indices=IFM_INDICES) |
| 239 | SignBit = OperatorInfo() |
| 240 | Sin = OperatorInfo() |
| 241 | SkipGram = OperatorInfo() |
| 242 | Slice = OperatorInfo(indices=IFM_INDICES) |
Michael McGeagh | 65fd998 | 2020-10-20 11:49:28 +0100 | [diff] [blame] | 243 | Softmax = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 244 | SpaceToBatchND = OperatorInfo() |
| 245 | SpaceToDepth = OperatorInfo() |
| 246 | SparseToDense = OperatorInfo() |
| 247 | Split = OperatorInfo(indices=SPLIT_IFM_INDICES) |
| 248 | SplitSliceRead = OperatorInfo(indices=IFM_INDICES) |
Jacob Bohlin | e3de4e5 | 2020-11-27 14:52:06 +0100 | [diff] [blame] | 249 | SplitV = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 250 | Sqrt = OperatorInfo() |
| 251 | Square = OperatorInfo() |
| 252 | SquaredDifference = OperatorInfo() |
| 253 | Squeeze = OperatorInfo(indices=IFM_INDICES) |
| 254 | StridedSlice = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 255 | Sub = OperatorInfo(block_type=NpuBlockType.ElementWise, indices=IFM_IFM2_INDICES) |
| 256 | SubgraphInput = OperatorInfo() # Only used in CPU subgraphs |
| 257 | Sum = OperatorInfo() |
| 258 | Svdf = OperatorInfo() |
| 259 | Tanh = OperatorInfo(indices=IFM_INDICES) |
| 260 | Tile = OperatorInfo() |
| 261 | TopKV2 = OperatorInfo() |
| 262 | Transpose = OperatorInfo() |
| 263 | UnidirectionalSequenceLstm = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 264 | UnidirectionalSequenceRnn = OperatorInfo(block_type=NpuBlockType.VectorProduct, indices=IFM_WEIGHTS_INDICES) |
| 265 | Unique = OperatorInfo() |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 266 | Unpack = OperatorInfo(indices=IFM_INDICES) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 267 | UnpackReshaped = OperatorInfo(indices=IFM_INDICES) |
| 268 | Where = OperatorInfo() |
| 269 | While = OperatorInfo() |
| 270 | ZerosLike = OperatorInfo() |
| 271 | |
| 272 | @property |
| 273 | def info(self): |
| 274 | return self.value |
| 275 | |
| 276 | @property |
| 277 | def npu_block_type(self): |
| 278 | return self.info.block_type |
| 279 | |
| 280 | def is_conv2d_op(self): |
| 281 | return self.info.block_type == NpuBlockType.ConvolutionMxN |
| 282 | |
| 283 | def is_depthwise_conv2d_op(self): |
| 284 | return self.info.block_type == NpuBlockType.ConvolutionDepthWise |
| 285 | |
| 286 | def is_pool_op(self): |
| 287 | return self.info.block_type == NpuBlockType.Pooling |
| 288 | |
| 289 | def is_maxpool_op(self): |
| 290 | return self in (Op.MaxPool, Op.QuantizedMaxPool) |
| 291 | |
| 292 | def is_avgpool_op(self): |
| 293 | return self in (Op.QuantizedAvgPool, Op.AvgPool) |
| 294 | |
| 295 | def is_elementwise_op(self): |
| 296 | return self.info.block_type == NpuBlockType.ElementWise |
| 297 | |
| 298 | def is_unary_elementwise_op(self): |
| 299 | return self.info.block_type == NpuBlockType.ElementWise and self.info.is_unary |
| 300 | |
| 301 | def is_binary_elementwise_op(self): |
| 302 | return self.info.block_type == NpuBlockType.ElementWise and not self.info.is_unary |
| 303 | |
| 304 | def is_relu_op(self): |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 305 | return self in (Op.Relu, Op.Relu6, Op.ReluN1To1, Op.Clip) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 306 | |
| 307 | def is_activation_op(self): |
Diqing Zhong | 189f748 | 2021-01-26 12:12:51 +0100 | [diff] [blame^] | 308 | return self.is_relu_op() or self in (Op.Tanh, Op.Sigmoid, Op.Softmax, Op.LUT, Op.HardSwish) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 309 | |
| 310 | def is_split_op(self): |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 311 | return self in (Op.Split, Op.SplitV, Op.StridedSlice, Op.Slice, Op.UnpackReshaped, Op.Unpack) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 312 | |
| 313 | def is_concat_op(self): |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 314 | return self in (Op.Concat, Op.ConcatTFLite, Op.PackReshaped, Op.Pack) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 315 | |
| 316 | def needs_bias(self): |
| 317 | return bool(self.info.indices.biases) |
| 318 | |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 319 | def needs_shapes(self): |
| 320 | return bool(self.info.indices.ifms) |
| 321 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 322 | @classmethod |
| 323 | def op_set(cls, predicate): |
| 324 | # Returns the set of all operator codes that fulfill the given predicate |
| 325 | return {op_type for op_type in Op if predicate(op_type)} |
| 326 | |
| 327 | def __str__(self): |
| 328 | return self.name |
| 329 | |
| 330 | __repr__ = __str__ |
| 331 | |
| 332 | def __lt__(self, other): |
| 333 | return self.value.id < other.value.id |
| 334 | |
| 335 | |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 336 | class Padding(Enum): |
| 337 | SAME = 0 |
| 338 | VALID = 1 |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 339 | EXPLICIT = 2 # Padding is specified in a PAD operation (only used for NPU operations) |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 340 | |
| 341 | |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 342 | class ActivationFunction: |
| 343 | """Fused activation function""" |
| 344 | |
| 345 | def __init__(self, op_type: Op): |
| 346 | self.op_type = op_type # The activation operation to be performed |
| 347 | # min/max are optional; if present they are non-quantized values |
| 348 | self.min: Optional[float] = None |
| 349 | self.max: Optional[float] = None |
| 350 | # Table lookup index, only applicable for Op.LUT activation, 0-7 |
| 351 | self.lut_index: int = 0 |
| 352 | |
| 353 | def clone(self): |
| 354 | res = copy.copy(self) |
| 355 | return res |
| 356 | |
| 357 | |
| 358 | def create_activation_function(op_type: Op) -> ActivationFunction: |
| 359 | """Creates activation function with min/max depending on op_type""" |
| 360 | act = ActivationFunction(op_type) |
| 361 | if op_type == Op.Relu: |
| 362 | act.min = 0.0 |
| 363 | elif op_type == Op.Relu6: |
| 364 | act.min = 0.0 |
| 365 | act.max = 6.0 |
| 366 | elif op_type == Op.ReluN1To1: |
| 367 | act.min = -1.0 |
| 368 | act.max = 1.0 |
| 369 | elif op_type == Op.Tanh: |
| 370 | act.min = -1.0 |
| 371 | act.max = 1.0 |
| 372 | elif op_type == Op.Sigmoid: |
| 373 | act.min = 0.0 |
| 374 | act.max = 1.0 |
Diqing Zhong | 189f748 | 2021-01-26 12:12:51 +0100 | [diff] [blame^] | 375 | elif op_type == Op.HardSwish: |
| 376 | act.min = 0.0 |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 377 | return act |
| 378 | |
| 379 | |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 380 | def get_slice_offsets(input_shape: List[int], offset_tens: int, offset_mask: int, is_begin: bool = True): |
Louis Verhaard | fa2f92a | 2020-09-21 11:56:18 +0200 | [diff] [blame] | 381 | # For strided slice operator: get start or end offsets |
| 382 | offsets = len(input_shape) * [0] if is_begin else input_shape[:] |
| 383 | for idx in range(len(input_shape)): |
| 384 | # If the i:th bit in the mask is set then the value on offset_tens[i] should be ignored |
| 385 | if (offset_mask & (1 << idx)) == 0: |
| 386 | offsets[idx] = offset_tens.values[idx] |
| 387 | if offsets[idx] < 0: |
| 388 | # Convert offset to positive value |
| 389 | offsets[idx] += input_shape[idx] |
| 390 | return offsets |
| 391 | |
| 392 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 393 | class Operation: |
| 394 | """Class representing a Neural Network operation. Has a name, a type, |
Dwight Lidman | c6ac194 | 2020-10-02 14:55:45 +0200 | [diff] [blame] | 395 | input and output tensors, as well as an attribute dictionary.""" |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 396 | |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 397 | __slots__ = ( |
| 398 | "type", |
| 399 | "name", |
| 400 | "op_index", |
| 401 | "attrs", |
| 402 | "inputs", |
| 403 | "outputs", |
| 404 | "flops", |
| 405 | "scheduled_pass", |
| 406 | "run_on_npu", |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 407 | "activation", |
| 408 | "memory_function", |
| 409 | "forced_output_quantization", |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 410 | "activation_lut", |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 411 | "_kernel", |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 412 | "ifm_shapes", |
| 413 | "ofm_shapes", |
Fredrik Svedberg | e82be7c | 2021-01-18 15:21:03 +0100 | [diff] [blame] | 414 | "rescale", |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 415 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 416 | |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 417 | def __init__(self, op_type: Op, name: str): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 418 | self.type = op_type |
| 419 | self.name = name |
Dwight Lidman | 9b43f84 | 2020-12-08 17:56:44 +0100 | [diff] [blame] | 420 | self.attrs: Dict[str, Any] = {} |
| 421 | self.inputs: List[Tensor] = [] |
| 422 | self.outputs: List[Tensor] = [] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 423 | self.flops = 0 |
| 424 | self.run_on_npu = True |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 425 | # Fused activation function. If not none: operator code. |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 426 | self.activation: Optional[ActivationFunction] = None |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 427 | # Fused memory function, if not None: operator code |
| 428 | self.memory_function = None |
| 429 | # If not none: contains QuantizationParameters to be used as output quantization |
| 430 | # (which overrides the ofm tensor's quantization), used in LUT |
| 431 | self.forced_output_quantization = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 432 | self.scheduled_pass = None |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 433 | self.op_index = None # input network operator index |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 434 | self.activation_lut = None |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 435 | self._kernel = None |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 436 | self.ifm_shapes: List[Shape4D] = [] |
| 437 | self.ofm_shapes: List[Shape4D] = [] |
Fredrik Svedberg | e82be7c | 2021-01-18 15:21:03 +0100 | [diff] [blame] | 438 | # If not none: contains rescale to be used as output scaling |
| 439 | # (which overrides the ofm tensor's scale) |
| 440 | self.rescale = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 441 | |
| 442 | def clone(self, suffix="_clone"): |
| 443 | res = Operation(self.type, self.name + suffix) |
| 444 | |
| 445 | res.attrs = dict(self.attrs) |
| 446 | res.inputs = list(self.inputs) |
| 447 | res.outputs = list(self.outputs) |
| 448 | res.flops = self.flops |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 449 | res.run_on_npu = self.run_on_npu |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 450 | res.activation = None if self.activation is None else self.activation.clone() |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 451 | res.memory_function = self.memory_function |
| 452 | res.forced_output_quantization = self.forced_output_quantization |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 453 | res.scheduled_pass = self.scheduled_pass |
Tim Hall | c8310b1 | 2020-06-17 14:53:11 +0100 | [diff] [blame] | 454 | res.op_index = None # not relevant as not part of input network |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 455 | |
| 456 | return res |
| 457 | |
| 458 | def __str__(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 459 | return "<nng.Operation '{}' type={}>".format(self.name, self.type) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 460 | |
| 461 | __repr__ = __str__ |
| 462 | |
Michael McGeagh | 65fd998 | 2020-10-20 11:49:28 +0100 | [diff] [blame] | 463 | def get_kernel_size(self): |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 464 | weights = self.weights |
| 465 | if weights and self.type.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.ConvolutionMxN): |
| 466 | weight_shape = full_shape(4, weights.shape, 1) |
Michael McGeagh | 65fd998 | 2020-10-20 11:49:28 +0100 | [diff] [blame] | 467 | h = weight_shape[-4] |
| 468 | w = weight_shape[-3] |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 469 | elif self.type.npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum) and "ksize" in self.attrs: |
| 470 | h, w = self.attrs["ksize"][1:3] |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 471 | else: |
Michael McGeagh | 65fd998 | 2020-10-20 11:49:28 +0100 | [diff] [blame] | 472 | h = self.attrs.get("filter_height", 1) |
| 473 | w = self.attrs.get("filter_width", 1) |
| 474 | return w, h |
| 475 | |
| 476 | def get_kernel_stride(self): |
| 477 | if "strides" in self.attrs: |
| 478 | _, h, w, _ = self.attrs["strides"] |
| 479 | else: |
| 480 | h = self.attrs.get("stride_h", 1) |
| 481 | w = self.attrs.get("stride_w", 1) |
| 482 | return w, h |
| 483 | |
| 484 | def get_kernel_dilation(self): |
| 485 | if "dilation" in self.attrs: |
| 486 | _, h, w, _ = self.attrs["dilation"] |
| 487 | else: |
| 488 | h = self.attrs.get("dilation_h_factor", 1) |
| 489 | w = self.attrs.get("dilation_w_factor", 1) |
| 490 | return w, h |
| 491 | |
| 492 | @property |
| 493 | def kernel(self): |
| 494 | k_w, k_h = self.get_kernel_size() |
| 495 | s_w, s_h = self.get_kernel_stride() |
| 496 | d_w, d_h = self.get_kernel_dilation() |
| 497 | self._kernel = Kernel(k_w, k_h, s_w, s_h, d_w, d_h) |
Tim Hall | 4ed38bc | 2020-10-20 18:54:20 +0100 | [diff] [blame] | 498 | return self._kernel |
| 499 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 500 | def get_ifm_ifm2_weights_ofm(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 501 | return self.ifm, self.ifm2, self.weights, self.ofm |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 502 | |
| 503 | def get_ifm_weights_biases_ofm(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 504 | return self.ifm, self.weights, self.bias, self.ofm |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 505 | |
Jacob Bohlin | 49d9212 | 2020-08-19 14:36:46 +0200 | [diff] [blame] | 506 | def get_ifm_ifm2_weights_biases_ofm(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 507 | return self.ifm, self.ifm2, self.weights, self.bias, self.ofm |
Jacob Bohlin | 49d9212 | 2020-08-19 14:36:46 +0200 | [diff] [blame] | 508 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 509 | def get_ifm_ofm(self): |
| 510 | return self.ifm, self.ofm |
Jacob Bohlin | 49d9212 | 2020-08-19 14:36:46 +0200 | [diff] [blame] | 511 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 512 | @property |
| 513 | def ifm(self): |
| 514 | # Gets the IFM tensor, or None if not applicable |
| 515 | return self.get_input(self.type.info.indices.ifms, 0) |
Jacob Bohlin | 49d9212 | 2020-08-19 14:36:46 +0200 | [diff] [blame] | 516 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 517 | @property |
| 518 | def ifm2(self): |
| 519 | # Gets the IFM2 tensor, or None if not applicable |
| 520 | return self.get_input(self.type.info.indices.ifms, 1) |
Louis Verhaard | 98a3499 | 2020-09-01 10:39:04 +0200 | [diff] [blame] | 521 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 522 | @property |
| 523 | def bias(self): |
| 524 | # Gets the bias tensor, or None if not applicable |
| 525 | return self.get_input(self.type.info.indices.biases, 0) |
| 526 | |
| 527 | @property |
| 528 | def weights(self): |
| 529 | # Gets the weight tensor, or None if not applicable |
| 530 | return self.get_input(self.type.info.indices.weights, 0) |
| 531 | |
| 532 | def get_ifm_tensors(self): |
| 533 | # Gets the IFM tensors, or empty list if not applicable |
| 534 | return self._index_list_to_tensors(self.type.info.indices.ifms) |
| 535 | |
| 536 | def get_weight_tensors(self): |
| 537 | # Gets the weight tensors, or empty list if not applicable |
| 538 | return self._index_list_to_tensors(self.type.info.indices.weights) |
| 539 | |
| 540 | def get_bias_tensors(self): |
| 541 | # Gets the bias tensors, or empty list if not applicable |
| 542 | return self._index_list_to_tensors(self.type.info.indices.biases) |
| 543 | |
| 544 | def _index_list_to_tensors(self, index_list): |
| 545 | return [self.inputs[ix] for ix in index_list if ix < len(self.inputs)] |
| 546 | |
| 547 | def get_input(self, index_list, ix): |
| 548 | if ix >= len(index_list): |
| 549 | return None |
| 550 | if index_list[ix] >= len(self.inputs): |
| 551 | return None |
| 552 | return self.inputs[index_list[ix]] |
| 553 | |
| 554 | @property |
| 555 | def ofm(self): |
| 556 | # Gets the OFM tensor, or None if not applicable |
| 557 | return self.outputs[0] if self.outputs else None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 558 | |
| 559 | def get_concat_inputs_axis(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 560 | assert self.type.is_concat_op() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 561 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 562 | if self.type == Op.Concat: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 563 | axis_tensor = self.inputs[0] |
| 564 | inputs = self.inputs[1:] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 565 | elif self.type == Op.ConcatTFLite: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 566 | inputs = self.inputs |
| 567 | axis = self.attrs["axis"] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 568 | elif self.type == Op.PackReshaped: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 569 | # Requires fixup_pack_input to be called before this point |
| 570 | inputs = self.inputs |
| 571 | axis = self.attrs["axis"] |
| 572 | assert len(self.inputs) == self.attrs["values_count"] |
| 573 | else: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 574 | assert len(axis_tensor.ops) == 1 and axis_tensor.ops[0].type == Op.Const |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 575 | axis = int(axis_tensor.values) |
| 576 | |
| 577 | return inputs, axis |
| 578 | |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 579 | def get_dilation_h_w(self): |
| 580 | _, dilation_h, dilation_w, _ = self.attrs.get("dilation", (1, 1, 1, 1)) |
| 581 | return dilation_h, dilation_w |
| 582 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 583 | def get_split_inputs_axis(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 584 | assert self.type.is_split_op() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 585 | |
| 586 | offset_start = None |
| 587 | offset_end = None |
| 588 | axis = None |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 589 | if self.type == Op.Split: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 590 | num_splits = self.attrs.get("num_splits") |
| 591 | axis_tens = self.inputs[0] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 592 | assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 593 | axis = int(axis_tens.values) |
| 594 | input_tens = self.inputs[1] |
| 595 | outputs = self.outputs |
| 596 | assert num_splits == len(outputs) |
| 597 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 598 | elif self.type == Op.SplitV: |
Charles Xu | 53d4752 | 2020-05-04 11:32:05 +0200 | [diff] [blame] | 599 | num_splits = self.attrs.get("num_splits") |
| 600 | input_tens = self.inputs[0] |
| 601 | size_tens = self.inputs[1] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 602 | assert len(size_tens.ops) == 1 and size_tens.ops[0].type == Op.Const |
Charles Xu | 53d4752 | 2020-05-04 11:32:05 +0200 | [diff] [blame] | 603 | sizes = size_tens.values |
Patrik Gustavsson | 271ddc3 | 2020-09-01 09:15:27 +0200 | [diff] [blame] | 604 | |
Charles Xu | 53d4752 | 2020-05-04 11:32:05 +0200 | [diff] [blame] | 605 | axis_tens = self.inputs[2] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 606 | assert len(axis_tens.ops) == 1 and axis_tens.ops[0].type == Op.Const |
Charles Xu | 53d4752 | 2020-05-04 11:32:05 +0200 | [diff] [blame] | 607 | axis = int(axis_tens.values) |
Patrik Gustavsson | 271ddc3 | 2020-09-01 09:15:27 +0200 | [diff] [blame] | 608 | |
| 609 | for idx, size in enumerate(sizes): |
| 610 | # One but only one size might be set to -1, indicating that size should be inferred |
| 611 | if size == -1: |
| 612 | sizes[idx] = input_tens.shape[axis] - (sum(sizes) + 1) |
| 613 | break |
| 614 | |
Charles Xu | 53d4752 | 2020-05-04 11:32:05 +0200 | [diff] [blame] | 615 | outputs = self.outputs |
| 616 | assert num_splits == len(outputs) |
| 617 | assert sum(sizes) == input_tens.shape[axis] |
| 618 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 619 | elif self.type == Op.Slice: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 620 | input_tens, begin_tens, size_tens = self.inputs |
| 621 | outputs = self.outputs |
| 622 | offset_start = [0] * len(input_tens.shape) |
| 623 | offset_end = [0] * len(input_tens.shape) |
| 624 | |
| 625 | for idx in range(len(begin_tens.values)): |
| 626 | # Check if the op should slice in dimension idx |
| 627 | if size_tens.values[idx] != input_tens.shape[idx]: |
| 628 | offset_start[idx] = begin_tens.values[idx] |
| 629 | offset_end[idx] = size_tens.values[idx] + offset_start[idx] |
| 630 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 631 | elif self.type == Op.StridedSlice: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 632 | input_tens, begin_tens, end_tens, strides_tens = self.inputs |
| 633 | outputs = self.outputs |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 634 | |
| 635 | # Extract masks |
| 636 | begin_mask = self.attrs["begin_mask"] |
| 637 | ellipsis_mask = self.attrs["ellipsis_mask"] |
| 638 | end_mask = self.attrs["end_mask"] |
| 639 | new_axis_mask = self.attrs["new_axis_mask"] |
| 640 | shrink_axis_mask = self.attrs["shrink_axis_mask"] |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 641 | |
| 642 | # shrink_axis_mask/new_axis_mask/ellipsis_mask is not supported by the Operation class but the operation |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 643 | # may have the attribute modified and handled in the graph optimization phase. |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 644 | assert shrink_axis_mask == new_axis_mask == ellipsis_mask == 0 |
Louis Verhaard | fa2f92a | 2020-09-21 11:56:18 +0200 | [diff] [blame] | 645 | offset_start = get_slice_offsets(input_tens.shape, begin_tens, begin_mask, is_begin=True) |
| 646 | offset_end = get_slice_offsets(input_tens.shape, end_tens, end_mask, is_begin=False) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 647 | elif self.type == Op.UnpackReshaped: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 648 | # Requires fixup_unpack_output to be called before this point |
| 649 | input_tens = self.inputs[0] |
| 650 | outputs = self.outputs |
| 651 | axis = self.attrs["axis"] |
| 652 | num_splits = self.attrs["num"] |
| 653 | # Number of outputs have to equal the value of the dimension to unpack |
| 654 | assert num_splits == len(outputs) == input_tens.shape[axis] |
| 655 | else: |
| 656 | assert False |
| 657 | |
| 658 | return input_tens, outputs, axis, offset_start, offset_end |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 659 | |
| 660 | def set_activation_lut(self, lut_tensor): |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 661 | self.activation = ActivationFunction(Op.LUT) |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 662 | self.activation_lut = lut_tensor |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 663 | self.add_input_tensor(lut_tensor) |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 664 | |
| 665 | def add_input_tensor(self, tens): |
| 666 | self.inputs.append(tens) |
| 667 | if self not in tens.consumer_list: |
| 668 | tens.consumer_list.append(self) |
| 669 | |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 670 | def set_input_tensor(self, tens, idx): |
| 671 | tens_to_remove = self.inputs[idx] |
| 672 | if tens_to_remove in tens.consumer_list: |
| 673 | tens.consumer_list.remove(tens_to_remove) |
| 674 | |
| 675 | self.inputs[idx] = tens |
| 676 | if self not in tens.consumer_list: |
| 677 | tens.consumer_list.append(self) |
| 678 | |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 679 | def set_output_tensor(self, tens): |
| 680 | tens.ops = [self] |
| 681 | self.outputs = [tens] |
Jacob Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 682 | |
Louis Verhaard | 98a3499 | 2020-09-01 10:39:04 +0200 | [diff] [blame] | 683 | def get_output_quantization(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 684 | if self.forced_output_quantization is not None: |
| 685 | return self.forced_output_quantization |
| 686 | return self.ofm.quantization |
Michael McGeagh | 528a56d | 2020-12-16 11:33:21 +0000 | [diff] [blame] | 687 | |
| 688 | def error(self, msg): |
| 689 | """ |
| 690 | Raises a VelaError exception for errors encountered when parsing an Operation |
| 691 | |
| 692 | :param self: Operation object that resulted in the error |
| 693 | :param msg: str object that contains a description of the specific error encountered |
| 694 | """ |
| 695 | |
| 696 | def _print_tensors(tensors): |
| 697 | lines = [] |
| 698 | for idx, tens in enumerate(tensors): |
| 699 | tens_name = getattr(tens, "name", "Not a Tensor") |
| 700 | lines.append(f" {idx} = {tens_name}") |
| 701 | return lines |
| 702 | |
| 703 | if self.op_index is None: |
| 704 | lines = [f"Invalid {self.type} (name = {self.name}) operator in the internal representation. {msg}"] |
| 705 | else: |
| 706 | lines = [f"Invalid {self.type} (op_index = {self.op_index}) operator in the input network. {msg}"] |
| 707 | |
| 708 | lines += [" Input tensors:"] |
| 709 | lines += _print_tensors(self.inputs) |
| 710 | |
| 711 | lines += [" Output tensors:"] |
| 712 | lines += _print_tensors(self.outputs) |
| 713 | |
| 714 | raise VelaError("\n".join(lines)) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 715 | |
| 716 | def set_ifm_ofm_shapes(self): |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 717 | self.ifm_shapes = [] |
| 718 | self.ofm_shapes = [] |
| 719 | |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 720 | ifm_tensor, ifm2_tensor, weight_tensor, ofm_tensor = self.get_ifm_ifm2_weights_ofm() |
| 721 | |
| 722 | # set all shapes to op, as 4D |
| 723 | if self.type == Op.FullyConnected: |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 724 | if len(self.ifm.shape) == 2: |
| 725 | self.ifm_shapes.append(Shape4D([self.ifm.shape[0], 1, 1, self.ifm.shape[1]])) |
| 726 | else: |
| 727 | # Special case, handled in graph optimization |
| 728 | self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape())) |
| 729 | if len(self.ofm.shape) == 2: |
| 730 | self.ofm_shapes.append(Shape4D([self.ofm.shape[0], 1, 1, self.ofm.shape[1]])) |
| 731 | else: |
| 732 | self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape())) |
| 733 | if self.type == Op.Softmax: |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 734 | self.ifm_shapes.append(Shape4D(ifm_tensor.get_full_shape())) |
| 735 | self.ofm_shapes.append(Shape4D(ofm_tensor.get_full_shape())) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 736 | elif self.type.is_split_op or self.type.is_concat_op(): |
| 737 | for inp in self.inputs: |
| 738 | if inp is not None: |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 739 | self.ifm_shapes.append(Shape4D(full_shape(4, inp.shape, 1))) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 740 | else: |
| 741 | self.ifm_shapes.append(None) |
| 742 | for out in self.outputs: |
| 743 | if out is not None: |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 744 | self.ofm_shapes.append(Shape4D(full_shape(4, out.shape, 1))) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 745 | else: |
| 746 | self.ofm_shapes.append(None) |
| 747 | else: |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 748 | self.ifm_shapes.append(Shape4D(full_shape(4, ifm_tensor.shape, 1))) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 749 | if ifm2_tensor is not None: |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 750 | self.ifm_shapes.append(Shape4D(full_shape(4, ifm2_tensor.shape, 1))) |
| 751 | self.ofm_shapes.append(Shape4D(full_shape(4, ofm_tensor.shape, 1))) |