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