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 | # Early optimisation of the network graph, using the rewrite_graph module to do the traversal of the graph. These are |
| 18 | # split into two parts optimise_graph_a and optimise_graph_b. |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 19 | import math |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 20 | |
| 21 | import numpy as np |
| 22 | |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 23 | from . import fp_math |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 24 | from . import lut |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 25 | from . import rewrite_graph |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 26 | from . import scaling |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 27 | from .data_type import DataType |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 28 | from .errors import UnsupportedFeatureError |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 29 | from .ethos_u55_regs.ethos_u55_regs import resampling_mode |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 30 | from .numeric_util import full_shape |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 31 | from .operation import create_avgpool_nop |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 32 | from .operation import NpuBlockType |
| 33 | from .operation import Operation |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 34 | from .softmax import SoftMax |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 35 | from .tensor import create_const_tensor |
| 36 | from .tensor import create_reshape_tensor |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 37 | from .tensor import QuantizationParameters |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 38 | from .tensor import Tensor |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 39 | |
| 40 | passthrough_nodes = set(("Identity",)) |
| 41 | |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 42 | conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct")) |
| 43 | fc_op = set( |
| 44 | ( |
| 45 | "MatMul", |
| 46 | "QuantizedMatMul", |
| 47 | "BlockLSTM", |
| 48 | "RnnAct", |
| 49 | "UnidirectionalSequenceRnnAct", |
| 50 | "BidirectionalSequenceRnnAct", |
| 51 | "LstmAct", |
| 52 | "UnidirectionalSequenceLstmAct", |
| 53 | "BidirectionalSequenceLstmAct", |
| 54 | "FullyConnectedAct", |
| 55 | ) |
| 56 | ) |
| 57 | depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",)) |
| 58 | pool_op = set( |
| 59 | ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear") |
| 60 | ) |
| 61 | reduce_sum_ops = set(("ReduceSum",)) |
| 62 | binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum")) |
| 63 | elementwise_op = set(("LeakyRelu", "Abs", "CLZ", "SHL", "SHR")) | binary_elementwise_op |
| 64 | relu_ops = set(("Relu", "Relu6", "ReluN1To1")) |
| 65 | activation_ops = set(("Sigmoid", "Tanh")) | relu_ops |
| 66 | memory_only_ops = set(("Reshape",)) |
| 67 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 68 | |
| 69 | def remove_passthrough_tensor(tens, arch): |
| 70 | if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes: |
| 71 | assert len(tens.ops[0].inputs) == 1 |
| 72 | tens = tens.ops[0].inputs[0] |
| 73 | return tens |
| 74 | |
| 75 | |
| 76 | def rewrite_concat(tens, arch): |
| 77 | if len(tens.ops) == 1 and tens.ops[0].is_concat_op(): |
| 78 | concat_op = tens.ops[0] |
| 79 | if tens != concat_op.outputs[0]: |
| 80 | return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat |
| 81 | |
| 82 | # Not supported so leave it and run on CPU |
| 83 | if not concat_op.run_on_npu: |
| 84 | return tens |
| 85 | |
| 86 | inputs, axis = concat_op.get_concat_inputs_axis() |
| 87 | |
| 88 | tens.ops = [] |
| 89 | offset = 0 |
| 90 | for idx, inp in enumerate(inputs): |
| 91 | new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx)) |
| 92 | new_op.inputs = [inp] |
| 93 | new_op.outputs = [tens] |
| 94 | new_op.attrs["concat_axis"] = axis |
| 95 | new_op.attrs["concat_start"] = offset |
| 96 | offset += inp.shape[axis] |
| 97 | new_op.attrs["concat_end"] = offset |
| 98 | new_op.run_on_npu = True |
| 99 | tens.ops.append(new_op) |
| 100 | assert tens.shape[axis] == offset |
| 101 | |
Patrik Gustavsson | 29d568e | 2020-08-18 10:11:21 +0200 | [diff] [blame] | 102 | # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a |
| 103 | # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte |
| 104 | # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0 |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 105 | # and those addresses are always 16 byte aligned due to the NHCWB16 format. |
Patrik Gustavsson | 6c97e9a | 2020-09-23 11:02:18 +0200 | [diff] [blame] | 106 | if axis == -1 or axis == (len(tens.shape) - 1): |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 107 | for op in tens.ops: |
| 108 | if op.attrs["concat_start"] % 16 != 0: |
| 109 | tens.avoid_NHCWB16 = True |
| 110 | break |
| 111 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 112 | return tens |
| 113 | |
| 114 | |
| 115 | def rewrite_split(tens, arch): |
| 116 | |
| 117 | if len(tens.ops) == 1 and tens.ops[0].is_split_op(): |
| 118 | split_op = tens.ops[0] |
| 119 | |
| 120 | # Not supported so leave it and run on CPU |
| 121 | if not split_op.run_on_npu: |
| 122 | return tens |
| 123 | |
| 124 | inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis() |
| 125 | |
| 126 | tens.ops = [] |
| 127 | new_op = Operation("SplitSliceRead", split_op.name) |
| 128 | new_op.inputs = [inp] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 129 | |
| 130 | # For Split the offset cannot be extracted from the tensor so it has to |
| 131 | # be calculated from the index of the output tensor |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 132 | if axis is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 133 | # Get the start and end of the split |
| 134 | offset_start = [0] * len(tens.shape) |
| 135 | offset_end = [0] * len(tens.shape) |
| 136 | for out in outputs: |
| 137 | if out == tens: |
| 138 | break |
| 139 | offset_start[axis] += out.shape[axis] |
| 140 | |
Patrik Gustavsson | eebb1c2 | 2020-08-18 15:03:04 +0200 | [diff] [blame] | 141 | # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input |
| 142 | if (offset_start[-1] % 16) != 0: |
| 143 | inp.avoid_NHCWB16 = True |
| 144 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 145 | offset_end[axis] = offset_start[axis] + tens.shape[axis] |
| 146 | |
| 147 | new_op.attrs["split_start"] = offset_start |
| 148 | new_op.attrs["split_end"] = offset_end |
| 149 | new_op.run_on_npu = True |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 150 | new_op.set_output_tensor(tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 151 | |
| 152 | return tens |
| 153 | |
| 154 | |
| 155 | def needed_total_padding(input_size, stride, filter_size): |
| 156 | out_size = (input_size + stride - 1) // stride |
| 157 | needed_input = (out_size - 1) * stride + filter_size |
| 158 | total_padding = max(0, needed_input - input_size) |
| 159 | return total_padding |
| 160 | |
| 161 | |
| 162 | def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims): |
| 163 | ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0])) |
| 164 | xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1])) |
| 165 | if padding_type == b"SAME": |
| 166 | left_pad = (xpad + 0) // 2 |
| 167 | right_pad = (xpad + 1) // 2 |
| 168 | top_pad = (ypad + 0) // 2 |
| 169 | bottom_pad = (ypad + 1) // 2 |
| 170 | elif padding_type == b"VALID": |
| 171 | left_pad = 0 |
| 172 | right_pad = 0 |
| 173 | top_pad = 0 |
| 174 | bottom_pad = 0 |
| 175 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 176 | raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type))) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 177 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
| 178 | skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad) |
| 179 | return padding, skirt |
| 180 | |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 181 | |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 182 | def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor): |
| 183 | kernel_height, kernel_width = kernel_size[0], kernel_size[1] |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 184 | if padding_type == b"SAME": |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 185 | ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height)) |
| 186 | xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width)) |
| 187 | |
Jacob Bohlin | d47cc27 | 2020-08-24 11:42:14 +0200 | [diff] [blame] | 188 | right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0) |
| 189 | bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0) |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 190 | left_pad = max(kernel_width - 1 - right_pad, 0) |
| 191 | top_pad = max(kernel_height - 1 - bottom_pad, 0) |
| 192 | |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 193 | elif padding_type == b"VALID": |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 194 | right_pad = max(kernel_width - 2, 0) |
| 195 | bottom_pad = max(kernel_height - 2, 0) |
| 196 | left_pad = kernel_width - 1 |
| 197 | top_pad = kernel_height - 1 |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 198 | else: |
| 199 | assert 0, "Unknown padding" |
| 200 | |
| 201 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 202 | skirt = padding |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 203 | return padding, skirt |
| 204 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 205 | |
| 206 | def fixup_conv2d_backprop(op, arch): |
| 207 | if op.type == "Conv2DBackpropInput": |
| 208 | # flip the inputs |
| 209 | op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0] |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 210 | op.type = "Conv2DBackpropInputSwitchedBias" |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 211 | |
| 212 | # Update strides |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 213 | op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)}) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 214 | |
| 215 | return op |
| 216 | |
| 217 | |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 218 | # Convert the op to an elementwise add |
| 219 | def convert_resizebilinear_1x1_to_add(op): |
| 220 | op.type = "AddAct" |
| 221 | op.name = op.name + "_add" |
| 222 | op.attrs.update({"npu_block_type": NpuBlockType.ElementWise}) |
| 223 | op.attrs["resizebilinear"] = True |
| 224 | # Create an input tensor filled with zeros |
| 225 | shape = op.outputs[0].shape |
| 226 | tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add") |
| 227 | tens.values = np.zeros(shape) |
| 228 | tens.quant_values = np.zeros(shape, np.uint8) |
| 229 | tens.quantization = QuantizationParameters(0.0, 255.0) |
| 230 | tens.quantization.scale_f32 = 1.0 |
| 231 | tens.quantization.zero_point = 0 |
| 232 | tens.consumer_list = [op] |
| 233 | tens_op = op.inputs[1].ops[0] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 234 | tens_op.set_output_tensor(tens) |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 235 | # Set the add inputs |
| 236 | op.inputs[1] = op.inputs[0] |
| 237 | op.inputs[0] = tens |
| 238 | |
| 239 | return op |
| 240 | |
| 241 | |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 242 | # Convert ResizeBilinear to a number of 2x2 pool ops |
| 243 | def convert_resizebilinear_to_2x2_pool(op): |
| 244 | count = 0 |
| 245 | pre_op = op |
| 246 | outputs = op.outputs |
| 247 | |
| 248 | op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)}) |
| 249 | if op.attrs["align_corners"]: |
| 250 | shape_modifier = 1 |
| 251 | op.attrs["padding"] = b"VALID" |
| 252 | else: |
| 253 | shape_modifier = 0 |
| 254 | op.attrs["padding"] = b"SAME" |
| 255 | op.inputs[0].resampling_mode = resampling_mode.NEAREST |
| 256 | |
| 257 | upscaled_shape = np.array(op.inputs[0].shape[1:3]) |
| 258 | out_shape = np.array(op.outputs[0].shape[1:3]) |
| 259 | if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all(): |
| 260 | return op |
| 261 | |
| 262 | while (upscaled_shape < out_shape).all(): |
| 263 | if count == 0: |
| 264 | scaled_op = pre_op |
| 265 | else: |
| 266 | scaled_op = op.clone("_{}".format(count)) |
| 267 | scaled_op.inputs[0] = pre_op.outputs[0] |
| 268 | |
| 269 | upscaled_shape = upscaled_shape * 2 - shape_modifier |
| 270 | |
| 271 | if (upscaled_shape == out_shape).all(): |
| 272 | scaled_op.outputs = outputs |
| 273 | scaled_op.outputs[0].ops = [scaled_op] |
| 274 | else: |
| 275 | shape = outputs[0].shape.copy() |
| 276 | shape[1:3] = upscaled_shape[0:2] |
| 277 | out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count)) |
| 278 | out_tens.quantization = op.outputs[0].quantization.clone() |
| 279 | out_tens.quantization.quant_min = np.iinfo(np.int16).min |
| 280 | out_tens.quantization.quant_max = np.iinfo(np.int16).max |
| 281 | scaled_op.set_output_tensor(out_tens) |
| 282 | pre_op = scaled_op |
| 283 | count += 1 |
| 284 | |
| 285 | # Setup the scale value |
| 286 | if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16: |
| 287 | scaled_op.attrs["rescale"] = 128 |
| 288 | elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8: |
| 289 | scaled_op.attrs["rescale"] = 1 / 128 |
| 290 | elif "rescale" in scaled_op.attrs: |
| 291 | del scaled_op.attrs["rescale"] |
| 292 | |
| 293 | return op |
| 294 | |
| 295 | |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 296 | def fixup_resizebilinear(op, arch): |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 297 | if op.type == "ResizeBilinear" and op.run_on_npu: |
| 298 | if op.inputs[0].shape == op.outputs[0].shape: |
Charles Xu | 36ffaf3 | 2020-08-05 15:40:44 +0200 | [diff] [blame] | 299 | # Bypass nop resizebilinear |
| 300 | op.inputs = op.inputs[:1] |
| 301 | op.type = "Identity" |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 302 | elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1: |
| 303 | convert_resizebilinear_1x1_to_add(op) |
| 304 | else: |
| 305 | convert_resizebilinear_to_2x2_pool(op) |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 306 | |
| 307 | return op |
| 308 | |
| 309 | |
Dwight Lidman | c3862c2 | 2020-09-14 15:22:33 +0200 | [diff] [blame] | 310 | def convert_nop_split_to_identity(op, arch): |
| 311 | if op.type == "Split" and op.attrs.get("num_splits") == 1: |
| 312 | # the list comprehension should return a list with a single tensor |
| 313 | # if it shouldn't, remove_passthrough_tensor will fail appropriately |
| 314 | op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape] |
| 315 | op.type = "Identity" |
| 316 | return op |
| 317 | |
| 318 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 319 | def fixup_fully_connected_input(op, arch): |
| 320 | if op.type == "FullyConnectedAct": |
| 321 | inp = op.inputs[0] |
| 322 | weights = op.inputs[1] |
| 323 | |
| 324 | n_in_elems = weights.shape[-2] |
| 325 | elms = inp.elements() |
| 326 | batch_size = elms // n_in_elems |
| 327 | assert batch_size * n_in_elems == elms |
| 328 | |
| 329 | desired_shape = [batch_size, n_in_elems] |
| 330 | if inp.shape != desired_shape: |
| 331 | # mismatch, insert a reshape to fix this. |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 332 | op.set_input_tensor(create_reshape_tensor(inp, desired_shape), 0) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 333 | |
| 334 | return op |
| 335 | |
| 336 | |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 337 | def convert_batched_fc_to_conv(op, arch): |
| 338 | if op.type == "FullyConnectedAct": |
| 339 | ifm = op.inputs[0] |
| 340 | ofm = op.outputs[0] |
| 341 | # Check if the FC is 2D and first dimension indicates batching |
| 342 | if len(ifm.shape) == len(ofm.shape) == 2 and ifm.shape[0] != 1: |
| 343 | n = ifm.shape[0] |
| 344 | batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)} |
| 345 | h, w = batching_split.get(n, (1, n)) |
| 346 | |
| 347 | # Convert to convolution |
| 348 | op.name += "_conv" |
| 349 | op.type = "Conv2DBiasAct" |
| 350 | faf = op.attrs.get("fused_activation_function", None) |
| 351 | op.attrs = { |
| 352 | "dilation": (1, 1, 1, 1), |
| 353 | "dilation_h_factor": 1, |
| 354 | "dilation_w_factor": 1, |
| 355 | "fused_activation_function": faf, |
| 356 | "npu_block_type": NpuBlockType.ConvolutionMxN, |
| 357 | "padding": b"SAME", |
| 358 | "stride_h": 1, |
| 359 | "stride_w": 1, |
| 360 | "strides": (1, 1, 1, 1), |
| 361 | } |
| 362 | |
| 363 | prev_op = ifm.ops[0] |
| 364 | desired_shape = [1, h, w, ifm.shape[-1]] |
| 365 | if len(ifm.consumer_list) == 1 and prev_op is not None and prev_op.type == "Reshape": |
| 366 | # There is a preceding Reshape |
| 367 | # Compare input of prev_op and input of op, to see if prev_op can be removed |
| 368 | ifm_prev_op = prev_op.inputs[0] |
| 369 | if ifm_prev_op.shape == ifm.shape and ifm_prev_op.quantization.is_scaling_equal(ifm.quantization): |
| 370 | # prev_op can be removed |
| 371 | op.set_input_tensor(ifm_prev_op, 0) |
| 372 | else: |
| 373 | op.inputs[0].set_all_shapes(desired_shape) |
| 374 | prev_op.set_input_tensor( |
| 375 | create_const_tensor(prev_op.inputs[1].name, [1], DataType.int32, desired_shape), 1 |
| 376 | ) |
| 377 | prev_op.attrs["new_shape"] = desired_shape |
| 378 | else: |
| 379 | # Add reshape op to the input if there is no preceding reshape |
| 380 | ifm.consumer_list.remove(op) |
| 381 | op.set_input_tensor(create_reshape_tensor(ifm, desired_shape), 0) |
| 382 | |
| 383 | # Reshape Weights to be 4D. IO becomes HWIO |
| 384 | weight_tensor = op.inputs[1] |
| 385 | weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0) |
| 386 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
| 387 | |
| 388 | desired_shape = [1, h, w, ofm.shape[-1]] |
| 389 | if ( |
| 390 | len(ofm.consumer_list) == 1 |
| 391 | and ofm.consumer_list[0] is not None |
| 392 | and ofm.consumer_list[0].type == "Reshape" |
| 393 | ): |
| 394 | # There is a subsequent Reshape |
| 395 | # Compare desired shape and output of consumer op, to see if consumer op can be removed |
| 396 | ofm_cons_op = ofm.consumer_list[0].outputs[0] |
| 397 | if desired_shape == ofm_cons_op.shape and ofm.quantization.is_scaling_equal(ofm_cons_op.quantization): |
| 398 | op.outputs[0] = ofm_cons_op |
| 399 | op.outputs[0].ops = [op] |
| 400 | else: |
| 401 | op.outputs[0].set_all_shapes(desired_shape) |
| 402 | else: |
| 403 | # Add rehape op to the output |
| 404 | op.set_output_tensor(create_reshape_tensor(ofm, desired_shape, False)) |
| 405 | return op |
| 406 | |
| 407 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 408 | def fixup_pack_input(op, arch): |
| 409 | if op.type == "Pack": |
| 410 | # Pack is also referred to as Stack |
| 411 | # Requires the rewrite_concat function to be called on the op afterwards |
| 412 | axis = int(op.attrs["axis"]) |
| 413 | desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:] |
| 414 | |
| 415 | # Construct 1 shape tensor to be used by all inserted reshape ops |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 416 | new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 417 | |
| 418 | for idx, inp in enumerate(op.inputs): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 419 | reshape_out = inp.clone("_reshaped") |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 420 | reshape_out.set_all_shapes(desired_shape) |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 421 | |
| 422 | reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx)) |
| 423 | reshape_op.attrs["new_shape"] = desired_shape |
| 424 | reshape_op.inputs = [inp, new_shape_tens] |
| 425 | reshape_op.set_output_tensor(reshape_out) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 426 | |
| 427 | op.inputs[idx] = reshape_out |
| 428 | |
| 429 | op.type = "PackReshaped" |
| 430 | |
| 431 | return op |
| 432 | |
| 433 | |
| 434 | def fixup_unpack_output(tens, arch): |
| 435 | op = tens.ops[0] |
| 436 | if op.type in set(("Unpack", "StridedSlice")): |
| 437 | # Unpack is also referred to as Unstack |
| 438 | # Requires the rewrite_split function to be called on the op afterwards |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 439 | |
| 440 | reshape_input_shape = tens.shape |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 441 | if op.type == "StridedSlice": |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 442 | new_axis_mask = op.attrs["new_axis_mask"] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 443 | shrink_axis_mask = op.attrs["shrink_axis_mask"] |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 444 | ellipsis_mask = op.attrs["ellipsis_mask"] |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 445 | |
| 446 | if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0: |
| 447 | # Not supported, will be put on CPU |
| 448 | return tens |
| 449 | if shrink_axis_mask == 0 and new_axis_mask == 0: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 450 | # Equal Rank StridedSlice, no need to insert reshape |
| 451 | return tens |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 452 | elif shrink_axis_mask != 0: |
| 453 | n = 0 |
| 454 | axis = 0 |
| 455 | while shrink_axis_mask: |
| 456 | prev_mask = shrink_axis_mask |
| 457 | n += 1 |
| 458 | shrink_axis_mask &= shrink_axis_mask - 1 |
| 459 | axis = int(math.log2(prev_mask - shrink_axis_mask)) |
| 460 | reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 461 | |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 462 | assert len(tens.shape) == (len(op.inputs[0].shape) - n) |
| 463 | op.attrs["shrink_axis_mask"] = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 464 | |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 465 | elif new_axis_mask != 0: |
| 466 | n = 0 |
| 467 | axis = 0 |
| 468 | while new_axis_mask: |
| 469 | prev_mask = new_axis_mask |
| 470 | n += 1 |
| 471 | new_axis_mask &= new_axis_mask - 1 |
| 472 | axis = int(math.log2(prev_mask - new_axis_mask)) |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 473 | reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :] |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 474 | new_axis_mask >>= 1 |
| 475 | |
| 476 | assert len(tens.shape) == (len(op.inputs[0].shape) + n) |
| 477 | op.attrs["new_axis_mask"] = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 478 | else: |
| 479 | axis = int(op.attrs["axis"]) |
| 480 | op.type = "UnpackReshaped" |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 481 | reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 482 | |
| 483 | # Construct 1 shape tensor to be used by all inserted reshape ops |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 484 | new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 485 | |
| 486 | for idx, out_tens in enumerate(op.outputs): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 487 | reshape_in = out_tens.clone("_reshaped") |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 488 | reshape_in.set_all_shapes(reshape_input_shape) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 489 | reshape_in.ops = [op] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 490 | |
| 491 | reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx)) |
| 492 | reshape_op.attrs["new_shape"] = reshape_input_shape |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 493 | reshape_op.inputs = [reshape_in, new_shape_tens] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 494 | reshape_op.set_output_tensor(out_tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 495 | |
| 496 | op.outputs[idx] = reshape_in |
| 497 | |
| 498 | return tens |
| 499 | |
| 500 | |
| 501 | def add_padding_fields(op, arch): |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 502 | if op.run_on_npu: |
| 503 | if "padding" in op.attrs: |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 504 | if op.type in conv_op | depthwise_op: |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 505 | kernel_size = op.inputs[1].shape[:2] |
| 506 | input_shape = op.inputs[0].shape |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 507 | elif op.type in pool_op | reduce_sum_ops: |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 508 | kernel_size = op.attrs["ksize"][1:3] |
| 509 | input_shape = op.inputs[0].shape |
| 510 | elif op.type == "ExtractImagePatches": |
| 511 | kernel_size = op.attrs["ksizes"][1:3] |
| 512 | input_shape = op.inputs[0].shape |
| 513 | else: |
| 514 | raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 515 | |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 516 | if op.type == "Conv2DBackpropInputSwitchedBias": |
| 517 | upscaling_factor = op.outputs[0].shape[1] // input_shape[1] |
| 518 | padding, skirt = calc_upscaled_padding_and_skirt( |
| 519 | op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor |
| 520 | ) |
| 521 | else: |
| 522 | dilation_h, dilation_w = op.get_dilation_h_w() |
| 523 | dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1] |
| 524 | padding, skirt = calc_padding_and_skirt( |
| 525 | op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape |
| 526 | ) |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 527 | |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 528 | op.attrs["explicit_padding"] = padding |
| 529 | op.attrs["skirt"] = skirt |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 530 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 531 | return op |
| 532 | |
| 533 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 534 | # Check if the op can be reordered |
| 535 | def get_prepend_op(op): |
| 536 | inp = op.inputs[0] |
| 537 | # The op should be reordered between prev_op and prep_op |
| 538 | prev_op = inp.ops[-1] |
| 539 | prep_op = None |
| 540 | while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1: |
| 541 | prep_op = prev_op |
| 542 | inp = prev_op.inputs[0] |
| 543 | prev_op = inp.ops[-1] |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 544 | if prev_op is not None and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 545 | return prep_op |
| 546 | |
| 547 | return None |
| 548 | |
| 549 | |
| 550 | def mark_npu_block_type(op, arch): |
| 551 | npu_block_type = NpuBlockType.Default |
| 552 | if op.type in conv_op: |
| 553 | npu_block_type = NpuBlockType.ConvolutionMxN |
| 554 | elif op.type in fc_op: |
| 555 | npu_block_type = NpuBlockType.VectorProduct |
| 556 | elif op.type in depthwise_op: |
| 557 | npu_block_type = NpuBlockType.ConvolutionDepthWise |
| 558 | elif op.type in pool_op: |
| 559 | npu_block_type = NpuBlockType.Pooling |
| 560 | elif op.type in elementwise_op: |
| 561 | npu_block_type = NpuBlockType.ElementWise |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 562 | elif op.type in reduce_sum_ops: |
| 563 | npu_block_type = NpuBlockType.ReduceSum |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 564 | |
| 565 | op.attrs["npu_block_type"] = npu_block_type |
| 566 | return op |
| 567 | |
| 568 | |
| 569 | def convert_depthwise_to_conv(op, arch): |
| 570 | # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and |
| 571 | # the ofm depth equals the depth multipler. |
| 572 | # If those conditions are true, then we can perform a simple |
| 573 | # switch of the operator type (and weight order) |
| 574 | |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 575 | if (op.type in depthwise_op) and (op.attrs["depth_multiplier"] != 1): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 576 | ifm_tensor = op.inputs[0] |
| 577 | weight_tensor = op.inputs[1] |
| 578 | ofm_tensor = op.outputs[0] |
| 579 | if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]): |
| 580 | # Change op type to Conv2d |
| 581 | op.type = op.type.replace("DepthwiseConv2d", "Conv2D") |
| 582 | del op.attrs["channel_multiplier"] |
| 583 | del op.attrs["depth_multiplier"] |
| 584 | |
| 585 | weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2)) |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 586 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 587 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 588 | raise UnsupportedFeatureError( |
| 589 | "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format( |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 590 | op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3] |
| 591 | ) |
| 592 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 593 | return op |
| 594 | |
| 595 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 596 | def reorder_depthwise_weights(op, arch): |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 597 | if op.type in depthwise_op: |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 598 | weight_tensor = op.inputs[1] |
| 599 | weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2)) |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 600 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 601 | weight_tensor.weight_transpose_depthwise = True |
| 602 | |
| 603 | return op |
| 604 | |
| 605 | |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 606 | def convert_conv_to_fc(op, arch): |
| 607 | # Conv 1x1 can be equivalent to Fully Connected. |
| 608 | # By representing certain convs as fully connected layers, Vela can better determine wether or not to use |
| 609 | # caching/double buffering for the weights. |
| 610 | # (Weights dont need to be reloaded for convs when IFM H and W are 1) |
| 611 | if op.type == "Conv2DBiasAct": |
| 612 | _, h, w, _ = op.inputs[0].shape |
| 613 | kh, kw, _, _ = op.inputs[1].shape |
| 614 | if h == 1 and w == 1 and kh == 1 and kw == 1: |
| 615 | # Overwrite this op as a Fully Connected Op |
| 616 | op.name += "_fc" |
| 617 | op.type = "FullyConnectedAct" |
| 618 | faf = op.attrs.get("fused_activation_function", None) |
| 619 | op.attrs = { |
| 620 | "fused_activation_function": faf, |
| 621 | "weights_format": 0, |
| 622 | "npu_block_type": NpuBlockType.VectorProduct, |
| 623 | } |
| 624 | # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped) |
| 625 | weight_tensor = op.inputs[1] |
| 626 | weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1)) |
| 627 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
| 628 | # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it |
| 629 | # back to 4D afterwards as the next layer is expecting that shape |
| 630 | orig_ofm_tensor = op.outputs[0] |
| 631 | # Reshape this ops output to be 2D: {(N*H*W), C} (We know N H and W are all 1 so this becomes {1, C}) |
| 632 | fc_ofm_tensor = orig_ofm_tensor.clone("_fc") |
| 633 | fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]]) |
| 634 | fc_ofm_tensor.ops = [op] |
| 635 | # Add a reshape after the new OFM to convert it back to the original 4D shape |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 636 | reshape_name = op.name + "_reshape" |
| 637 | new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape) |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 638 | reshape_op = Operation("Reshape", reshape_name) |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 639 | reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 640 | reshape_op.inputs = [fc_ofm_tensor, new_shape_tens] |
| 641 | reshape_op.set_output_tensor(orig_ofm_tensor) |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 642 | # Replace this ops OFM to point to the 2D tensor |
| 643 | op.outputs[0] = fc_ofm_tensor |
| 644 | return op |
| 645 | |
| 646 | |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 647 | def fixup_relus_with_differing_ifm_ofm_scaling(op, arch): |
| 648 | if op.run_on_npu and op.type in relu_ops: |
| 649 | ifm = op.inputs[0] |
| 650 | ofm = op.outputs[0] |
| 651 | # Relu with differing IFM and OFM scaling cannot be fused with another primary op |
| 652 | # and requires its own to be inserted |
| 653 | if not ifm.is_scaling_equal(ofm): |
| 654 | # Override this op with its own primary op (avgpool) |
| 655 | relu_fused_op = create_avgpool_nop(op.name + "_avgpool") |
| 656 | # And fuse the original activation function to it |
| 657 | relu_fused_op.attrs["fused_activation_function"] = op.type |
| 658 | # Tidy up and assign the ifm and ofm to the new op |
| 659 | ifm.consumer_list.remove(op) |
Andreas Nevalainen | f3d737e | 2020-09-25 14:12:43 +0200 | [diff] [blame^] | 660 | |
| 661 | # if not 4d, reshape ifm/ofm |
| 662 | if len(ifm.shape) < 4: |
| 663 | ifm_shaped = create_reshape_tensor(ifm, full_shape(4, ifm.shape, 1)) |
| 664 | ifm = ifm_shaped |
| 665 | if len(ofm.shape) < 4: |
| 666 | ofm_shaped = create_reshape_tensor(ofm, full_shape(4, ofm.shape, 1), False) |
| 667 | ofm = ofm_shaped |
| 668 | |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 669 | relu_fused_op.add_input_tensor(ifm) |
| 670 | relu_fused_op.set_output_tensor(ofm) |
| 671 | op = relu_fused_op |
| 672 | return op |
| 673 | |
| 674 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 675 | # Reorder activation op if it's after the memory only operations |
| 676 | def fixup_act_reorder(op, arch): |
| 677 | if op.type in activation_ops: |
| 678 | prep_op = get_prepend_op(op) |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 679 | if prep_op is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 680 | act_op = op.clone("_reordered") |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 681 | |
| 682 | # There is only one input tensor, overwrite it |
| 683 | act_op.set_input_tensor(prep_op.inputs[0], 0) |
| 684 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 685 | act_op_out = act_op.inputs[0].clone("_acted") |
| 686 | act_op_out.quantization = op.outputs[0].quantization.clone() |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 687 | act_op.set_output_tensor(act_op_out) |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 688 | |
| 689 | # Update the consumer list |
| 690 | act_op_out.consumer_list = op.outputs[0].consumer_list.copy() |
| 691 | act_op_out.consumer_list.append(prep_op) |
| 692 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 693 | prep_op.inputs[0] = act_op_out |
| 694 | prep_op.outputs[0].quantization = act_op_out.quantization.clone() |
| 695 | |
| 696 | # Mark the op so that it will be removed as passthrough later on |
| 697 | op.type = "Identity" |
| 698 | return op |
| 699 | |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 700 | |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 701 | def fixup_elementwise_with_scalars(op, arch): |
| 702 | if op.type in binary_elementwise_op: |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 703 | ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm() |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 704 | if ifm2_tensor.shape != [] and ifm_tensor.shape != []: |
| 705 | diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape) |
| 706 | if diff > 0: |
| 707 | ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1) |
| 708 | elif diff < 0: |
| 709 | ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1) |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 710 | elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None: |
| 711 | # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 712 | ifm_tensor.shape = len(ifm2_tensor.shape) * [1] |
| 713 | ifm_tensor.storage_shape = ifm_tensor.shape |
| 714 | elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None: |
| 715 | # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 716 | ifm2_tensor.shape = len(ifm_tensor.shape) * [1] |
| 717 | ifm2_tensor.storage_shape = ifm2_tensor.shape |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 718 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 719 | |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 720 | |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 721 | # Set input/output tensor equivalence to the same id for memory operations |
| 722 | def set_tensor_equivalence(op, arch): |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 723 | if op.type in memory_only_ops: |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 724 | eid = op.outputs[0].equivalence_id |
| 725 | for inp in op.inputs: |
| 726 | inp.equivalence_id = eid |
| 727 | return op |
| 728 | |
| 729 | |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 730 | def convert_softmax(op, arch): |
| 731 | if op.type == "Softmax" and op.run_on_npu: |
| 732 | softmax = SoftMax(op) |
| 733 | op = softmax.get_graph() |
| 734 | return op |
| 735 | |
| 736 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 737 | def convert_mul_max_to_abs_or_lrelu(op, arch): |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 738 | r"""Whenever there is a subgraph with this topology: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 739 | |
| 740 | Input X For X = -1 or X > 0 |
| 741 | | \ / This subgraph can be replaced with either |
| 742 | | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0) |
| 743 | | / |
| 744 | Max |
| 745 | """ |
| 746 | |
| 747 | if op.type == "Maximum": |
| 748 | # finds the Mul input(s) to the Max |
| 749 | muls = [i for i in op.inputs if i.ops[0].type == "MulAct"] |
| 750 | if len(muls) == 1: |
| 751 | mul = muls[0].ops[0] |
| 752 | elif len(muls) == 2: |
| 753 | # In the case both inputs are Muls, find the one with the same input as the Max |
| 754 | mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0] |
| 755 | else: |
| 756 | # No Mul inputs |
| 757 | return op |
| 758 | |
| 759 | # make sure the Mul doesn't have any other consumers |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 760 | mul_ofm = mul.outputs[0] |
| 761 | if len(mul_ofm.consumers()) != 1: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 762 | return op |
| 763 | # make sure the Mul doesn't have a faf |
| 764 | if mul.attrs["fused_activation_function"]: |
| 765 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 766 | ifm, _, _, ofm = op.get_ifm_weights_biases_ofm() |
| 767 | if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype: |
| 768 | return op |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 769 | if not ifm.is_scaling_equal(ofm) or not ifm.is_scaling_equal(mul_ofm): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 770 | # rewrite to LeakyRelu currently only makes sense if the quantization is identical |
| 771 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 772 | |
| 773 | # finds the branched input that goes to both the Max and the Mul |
| 774 | shared = set(op.inputs) & set(mul.inputs) |
| 775 | if len(shared) == 1: |
| 776 | shared_in = shared.pop() |
| 777 | # find the constant scalar input to the Mul |
| 778 | const_tens = (set(mul.inputs) - {shared_in}).pop() |
| 779 | # check that it is a scalar |
| 780 | if const_tens.shape != []: |
| 781 | return op |
| 782 | const = const_tens.ops[0] |
| 783 | # check that it is a constant |
| 784 | if const.type != "Const": |
| 785 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 786 | # Remove the Mul from the shared input's consumers |
| 787 | shared_in.consumer_list.remove(mul) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 788 | else: |
| 789 | return op |
| 790 | |
| 791 | val = const.outputs[0].values |
| 792 | if val >= 0: |
| 793 | new_op = "LeakyRelu" |
| 794 | op.attrs["alpha"] = val |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 795 | # to produce bit exact results, the alpha is not enough; |
| 796 | # save additional scaling info in attr "alpha_scale", to be used as input |
| 797 | # to the LUT construction |
| 798 | alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point |
| 799 | mul_ifm_scale = np.double(ifm.quantization.scale_f32) |
| 800 | mul_ifm2_scale = np.double(const_tens.quantization.scale_f32) |
| 801 | mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32) |
| 802 | alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale) |
| 803 | op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 804 | elif val == -1: |
| 805 | new_op = "Abs" |
| 806 | else: |
| 807 | return op |
| 808 | |
| 809 | op.type = op.type.replace("Maximum", new_op) |
| 810 | op.name = op.name.replace("Maximum", new_op) |
| 811 | op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op) |
| 812 | op.inputs = [shared_in] |
| 813 | return op |
| 814 | |
| 815 | |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 816 | def convert_lrelu_to_mul_max(op, arch): |
| 817 | # Converts LeakyRelu to Max(alpha * IFM, identity * IFM) |
| 818 | # (the opposite of convert_mul_max_to_abs_or_lrelu) |
| 819 | ifm, _, _, ofm = op.get_ifm_weights_biases_ofm() |
| 820 | |
| 821 | # Add multiplication with alpha |
| 822 | mul_alpha = Operation("MulAct", op.name + "_mul_alpha") |
| 823 | mul_alpha.add_input_tensor(ifm) |
| 824 | # Create const tensor containing alpha as scalar |
| 825 | alpha = op.attrs["alpha"] |
| 826 | quantization = ifm.quantization.clone() |
| 827 | quantization.min = 0 |
| 828 | quantization.max = alpha * (quantization.quant_max - quantization.quant_min) |
| 829 | quantization.scale_f32 = alpha |
| 830 | quantization.zero_point = 0 |
| 831 | alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization) |
| 832 | mul_alpha.add_input_tensor(alpha_tens) |
| 833 | fm_alpha = ofm.clone(op.name + "_alpha") |
| 834 | mul_alpha.set_output_tensor(fm_alpha) |
| 835 | |
| 836 | if ifm.is_scaling_equal(ofm): |
| 837 | # No identity multiplication is needed |
| 838 | fm_id = ifm |
| 839 | else: |
| 840 | # Add multiplication with identity |
| 841 | mul_identity = Operation("MulAct", op.name + "_mul_identity") |
| 842 | mul_identity.add_input_tensor(ifm) |
| 843 | # Create const tensor containing identity as scalar |
| 844 | quantization = ifm.quantization.clone() |
| 845 | quantization.min = 0 |
| 846 | quantization.max = quantization.quant_max - quantization.quant_min |
| 847 | quantization.scale_f32 = 1 |
| 848 | quantization.zero_point = 0 |
| 849 | identity_tens = create_const_tensor( |
| 850 | op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization |
| 851 | ) |
| 852 | mul_identity.add_input_tensor(identity_tens) |
| 853 | fm_id = ofm.clone(op.name + "_id") |
| 854 | mul_identity.set_output_tensor(fm_id) |
| 855 | |
| 856 | # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs |
| 857 | op.type = "Maximum" |
| 858 | op.name = op.name.replace("LeakyRelu", "Maximum") |
| 859 | op.inputs = [] |
| 860 | ifm.consumer_list.remove(op) |
| 861 | op.add_input_tensor(fm_alpha) |
| 862 | op.add_input_tensor(fm_id) |
| 863 | return op |
| 864 | |
| 865 | |
| 866 | def convert_lrelu_to_lut(op, arch): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 867 | # Rewrite LeakyRelu by Add with scalar 0 + LUT activation |
Louis Verhaard | 58520b9 | 2020-08-24 16:45:38 +0200 | [diff] [blame] | 868 | ifm, _, _, ofm = op.get_ifm_weights_biases_ofm() |
| 869 | assert ifm.dtype.size_in_bytes() == 1 |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 870 | op.type = "AddAct" |
| 871 | op.name = op.name + "_add" |
| 872 | op.attrs.update({"npu_block_type": NpuBlockType.ElementWise}) |
| 873 | # Mark as no-op to enable potential fusing optimizations |
| 874 | op.attrs["is_nop"] = True |
| 875 | # Create an input tensor containing scalar zero |
| 876 | quantization = QuantizationParameters(0.0, 255.0) |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 877 | quantization.scale_f32 = ifm.quantization.scale_f32 |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 878 | quantization.zero_point = 0 |
| 879 | tens = create_const_tensor(op.inputs[0].name + "_add", [], ifm.dtype, [0], np.uint8, quantization=quantization) |
| 880 | op.add_input_tensor(tens) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 881 | # Generate the LUT |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 882 | alpha = op.attrs["alpha"] |
| 883 | ifm_scale = np.double(ifm.quantization.scale_f32) |
| 884 | ofm_scale = np.double(ofm.quantization.scale_f32) |
| 885 | zp_in = ifm.quantization.zero_point |
| 886 | zp_out = ofm.quantization.zero_point |
| 887 | identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale) |
| 888 | alpha_scalar = 1 |
| 889 | alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale) |
| 890 | if "alpha_scaling" in op.attrs: |
| 891 | # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu |
| 892 | alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"] |
| 893 | values = [] |
Louis Verhaard | 58520b9 | 2020-08-24 16:45:38 +0200 | [diff] [blame] | 894 | ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128) |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 895 | quantized_min = min(ix) |
| 896 | quantized_max = max(ix) |
| 897 | for x in ix: |
| 898 | if x < zp_in: |
| 899 | lut_result = zp_out + fp_math.multiply_by_quantized_multiplier( |
| 900 | alpha_scalar * (x - zp_in), alpha_scale, alpha_shift |
| 901 | ) |
| 902 | else: |
| 903 | lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift) |
| 904 | lut_result = min(quantized_max, max(quantized_min, lut_result)) |
| 905 | values.append(lut_result) |
| 906 | # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale), |
| 907 | # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions |
| 908 | # should be the same as the IFM |
| 909 | op.attrs["forced_output_quantization"] = ifm.quantization |
Louis Verhaard | 58520b9 | 2020-08-24 16:45:38 +0200 | [diff] [blame] | 910 | lut_tensor = lut.create_lut_tensor(op.name + "_lut", values, DataType.int8) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 911 | op.set_activation_lut(lut_tensor) |
| 912 | return op |
| 913 | |
| 914 | |
| 915 | def convert_lrelu(op, arch): |
| 916 | # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max |
| 917 | if op.type != "LeakyRelu": |
| 918 | return op |
| 919 | ifm, _, _, ofm = op.get_ifm_weights_biases_ofm() |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 920 | if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype: |
| 921 | # use LUT for int8/uint8 |
| 922 | return convert_lrelu_to_lut(op, arch) |
| 923 | if ifm.is_scaling_equal(ofm) and ifm.dtype == ofm.dtype and ifm.dtype == DataType.int16: |
| 924 | # use LeakyRelu unmodified for int16 with equal input/output scaling |
| 925 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 926 | return convert_lrelu_to_mul_max(op, arch) |
| 927 | |
| 928 | |
Patrik Gustavsson | fa4cb29 | 2020-09-10 08:19:36 +0200 | [diff] [blame] | 929 | def remove_unwanted_reshapes(op, arch): |
| 930 | # Try to remove reshapes enclosing ElementWise operator with only one non-constant input |
| 931 | if not op.run_on_npu or op.attrs["npu_block_type"] != NpuBlockType.ElementWise: |
| 932 | return op |
| 933 | |
| 934 | # Check if the ElementWise operator only have one non-constant input |
| 935 | non_const_tens = [x for x in op.inputs if x.ops[0].type != "Const"] |
| 936 | if len(non_const_tens) != 1: |
| 937 | return op |
| 938 | ifm = non_const_tens[0] |
| 939 | |
| 940 | # Check if operation is enclosed by Reshapes that can be removed |
| 941 | ofm = op.outputs[0] |
| 942 | prev_op = ifm.ops[0] |
| 943 | if ( |
| 944 | len(ifm.consumer_list) == 1 |
| 945 | and prev_op.type == "Reshape" |
| 946 | and len(ofm.consumer_list) == 1 |
| 947 | and ofm.consumer_list[0].type == "Reshape" |
| 948 | ): |
| 949 | # Operation is enclosed by reshapes, check if they can be removed |
| 950 | prev_op_ifm, _, _, prev_op_ofm = prev_op.get_ifm_weights_biases_ofm() |
| 951 | cons_op = ofm.consumer_list[0] |
| 952 | cons_op_ifm = ofm |
| 953 | cons_op_ofm = cons_op.outputs[0] |
| 954 | if len(prev_op_ifm.shape) == len(cons_op_ofm.shape): |
| 955 | # Check if quantization is the same in the input and output for the reshape ops |
| 956 | if prev_op_ifm.quantization.is_scaling_equal( |
| 957 | prev_op_ofm.quantization |
| 958 | ) and cons_op_ifm.quantization.is_scaling_equal(cons_op_ofm.quantization): |
| 959 | op.inputs[0] = prev_op_ifm |
| 960 | op.outputs[0] = cons_op_ofm |
| 961 | return op |
| 962 | |
| 963 | |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 964 | def fuse_activation_function_with_prev(op, arch): |
| 965 | # if op is a no-op: attempts to move the activation function to the preceding op |
| 966 | if not op.attrs.get("is_nop", False) or op.attrs.get("fused_activation_function", None) is None: |
| 967 | return op |
| 968 | ifm, _, _, ofm = op.get_ifm_weights_biases_ofm() |
| 969 | # finds the input(s) to the operation |
| 970 | prev_op = ifm.ops[0] |
| 971 | # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed |
| 972 | fuse = ( |
| 973 | prev_op.run_on_npu |
| 974 | and prev_op.attrs["npu_block_type"] != NpuBlockType.Default |
| 975 | and len(ifm.ops) == 1 |
| 976 | and len(prev_op.outputs[0].consumers()) == 1 |
| 977 | and prev_op.attrs.get("fused_activation_function", None) is None |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 978 | ) |
| 979 | if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0: |
| 980 | # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC), |
| 981 | # LUT currently only works correctly for elementwise ops |
| 982 | fuse = False |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 983 | if not fuse: |
| 984 | return op |
| 985 | # Move the fused activation function + corresponding info to prev_op |
Louis Verhaard | 98a3499 | 2020-09-01 10:39:04 +0200 | [diff] [blame] | 986 | for attr in ("fused_activation_function", "forced_output_quantization"): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 987 | if attr in op.attrs: |
| 988 | prev_op.attrs[attr] = op.attrs[attr] |
| 989 | if op.activation_lut is not None: |
| 990 | prev_op.set_activation_lut(op.activation_lut) |
| 991 | # Bypass op |
Louis Verhaard | 98a3499 | 2020-09-01 10:39:04 +0200 | [diff] [blame] | 992 | prev_op.set_output_tensor(ofm) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 993 | return op |
| 994 | |
| 995 | |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 996 | def add_attrs_to_resizebilinear(op, arch): |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 997 | if op.type == "ResizeBilinear" and op.run_on_npu: |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 998 | input_tensor = op.inputs[0] |
| 999 | upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2] |
| 1000 | out_shape = op.outputs[0].shape[1:3] |
| 1001 | if not op.attrs["align_corners"] and out_shape == upscaled_shape: |
| 1002 | # this means the output is supposed to be a x2 upscale, |
| 1003 | # so we need to do SAME padding |
| 1004 | op.attrs["padding"] = b"SAME" |
| 1005 | elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]: |
| 1006 | # here we can just run the avg pool without padding and |
| 1007 | # produce a (M * 2 - 1, N * 2 - 1) sized output |
| 1008 | op.attrs["padding"] = b"VALID" |
| 1009 | else: |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 1010 | return op |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1011 | input_tensor.resampling_mode = resampling_mode.NEAREST |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 1012 | op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)}) |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1013 | return op |
| 1014 | |
| 1015 | |
Jacob Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 1016 | def fixup_bias_tensors(op, arch): |
| 1017 | if op.needs_bias() and not op.inputs[-1]: |
| 1018 | # Op has no bias, add bias tensor filled with zeros |
| 1019 | nr_biases = op.inputs[1].shape[-1] |
| 1020 | bias_values = [0] * nr_biases |
| 1021 | bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values) |
| 1022 | bias_tensor.quant_values = bias_tensor.values |
| 1023 | op.set_input_tensor(bias_tensor, -1) |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 1024 | |
| 1025 | return op |
| 1026 | |
| 1027 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1028 | def supported_operator_check(op, arch): |
| 1029 | op.run_on_npu = arch.supported_operators.is_operator_supported(op) |
| 1030 | return op |
| 1031 | |
| 1032 | |
| 1033 | def optimise_graph_a(nng, arch, verbose_graph=False): |
| 1034 | if verbose_graph: |
| 1035 | nng.print_graph() |
| 1036 | |
| 1037 | op_rewrite_list = [ |
| 1038 | # mark block type and check if the operations are supported |
| 1039 | mark_npu_block_type, |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 1040 | set_tensor_equivalence, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1041 | supported_operator_check, |
| 1042 | # then do any rewrites of supported operators |
| 1043 | convert_depthwise_to_conv, |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 1044 | convert_conv_to_fc, |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 1045 | convert_softmax, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1046 | fixup_fully_connected_input, |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 1047 | convert_batched_fc_to_conv, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1048 | fixup_pack_input, |
| 1049 | fixup_conv2d_backprop, |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 1050 | fixup_relus_with_differing_ifm_ofm_scaling, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1051 | fixup_act_reorder, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1052 | mark_npu_block_type, |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 1053 | fixup_elementwise_with_scalars, |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 1054 | reorder_depthwise_weights, |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 1055 | fixup_resizebilinear, |
Jacob Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 1056 | fixup_bias_tensors, |
Dwight Lidman | c3862c2 | 2020-09-14 15:22:33 +0200 | [diff] [blame] | 1057 | convert_nop_split_to_identity, |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1058 | convert_mul_max_to_abs_or_lrelu, |
Patrik Gustavsson | fa4cb29 | 2020-09-10 08:19:36 +0200 | [diff] [blame] | 1059 | remove_unwanted_reshapes, |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1060 | convert_lrelu, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1061 | ] |
| 1062 | |
| 1063 | for idx, sg in enumerate(nng.subgraphs): |
| 1064 | # rewrite graph pass |
| 1065 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 1066 | sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1067 | ) |
| 1068 | |
| 1069 | for idx, sg in enumerate(nng.subgraphs): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1070 | # remove passthrough tensors and attempt further optimizations |
| 1071 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 1072 | sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields] |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1073 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1074 | |
| 1075 | if verbose_graph: |
| 1076 | nng.print_graph() |
| 1077 | return nng |
| 1078 | |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 1079 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1080 | def optimise_graph_b(nng, arch, verbose_graph=False): |
| 1081 | if verbose_graph: |
| 1082 | nng.print_graph() |
| 1083 | |
| 1084 | for idx, sg in enumerate(nng.subgraphs): |
| 1085 | # combined rewrite graph pass |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 1086 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split], []) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1087 | |
| 1088 | if verbose_graph: |
| 1089 | nng.print_graph() |
| 1090 | return nng |