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