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 | |
| 23 | from . import rewrite_graph |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 24 | from .data_type import DataType |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 25 | from .errors import UnsupportedFeatureError |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 26 | from .ethos_u55_regs.ethos_u55_regs import resampling_mode |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 27 | from .numeric_util import full_shape |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 28 | from .operation import NpuBlockType |
| 29 | from .operation import Operation |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 30 | from .softmax import SoftMax |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 31 | from .tensor import create_const_tensor |
| 32 | from .tensor import create_reshape_tensor |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 33 | from .tensor import QuantizationParameters |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 34 | from .tensor import Tensor |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 35 | |
| 36 | passthrough_nodes = set(("Identity",)) |
| 37 | |
| 38 | |
| 39 | def remove_passthrough_tensor(tens, arch): |
| 40 | if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes: |
| 41 | assert len(tens.ops[0].inputs) == 1 |
| 42 | tens = tens.ops[0].inputs[0] |
| 43 | return tens |
| 44 | |
| 45 | |
| 46 | def rewrite_concat(tens, arch): |
| 47 | if len(tens.ops) == 1 and tens.ops[0].is_concat_op(): |
| 48 | concat_op = tens.ops[0] |
| 49 | if tens != concat_op.outputs[0]: |
| 50 | return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat |
| 51 | |
| 52 | # Not supported so leave it and run on CPU |
| 53 | if not concat_op.run_on_npu: |
| 54 | return tens |
| 55 | |
| 56 | inputs, axis = concat_op.get_concat_inputs_axis() |
| 57 | |
| 58 | tens.ops = [] |
| 59 | offset = 0 |
| 60 | for idx, inp in enumerate(inputs): |
| 61 | new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx)) |
| 62 | new_op.inputs = [inp] |
| 63 | new_op.outputs = [tens] |
| 64 | new_op.attrs["concat_axis"] = axis |
| 65 | new_op.attrs["concat_start"] = offset |
| 66 | offset += inp.shape[axis] |
| 67 | new_op.attrs["concat_end"] = offset |
| 68 | new_op.run_on_npu = True |
| 69 | tens.ops.append(new_op) |
| 70 | assert tens.shape[axis] == offset |
| 71 | |
Patrik Gustavsson | 29d568e | 2020-08-18 10:11:21 +0200 | [diff] [blame] | 72 | # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a |
| 73 | # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte |
| 74 | # 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] | 75 | # and those addresses are always 16 byte aligned due to the NHCWB16 format. |
Patrik Gustavsson | 29d568e | 2020-08-18 10:11:21 +0200 | [diff] [blame] | 76 | if axis == (len(tens.shape) - 1): |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 77 | for op in tens.ops: |
| 78 | if op.attrs["concat_start"] % 16 != 0: |
| 79 | tens.avoid_NHCWB16 = True |
| 80 | break |
| 81 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 82 | return tens |
| 83 | |
| 84 | |
| 85 | def rewrite_split(tens, arch): |
| 86 | |
| 87 | if len(tens.ops) == 1 and tens.ops[0].is_split_op(): |
| 88 | split_op = tens.ops[0] |
| 89 | |
| 90 | # Not supported so leave it and run on CPU |
| 91 | if not split_op.run_on_npu: |
| 92 | return tens |
| 93 | |
| 94 | inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis() |
| 95 | |
| 96 | tens.ops = [] |
| 97 | new_op = Operation("SplitSliceRead", split_op.name) |
| 98 | new_op.inputs = [inp] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 99 | |
| 100 | # For Split the offset cannot be extracted from the tensor so it has to |
| 101 | # be calculated from the index of the output tensor |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 102 | if axis is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 103 | # Get the start and end of the split |
| 104 | offset_start = [0] * len(tens.shape) |
| 105 | offset_end = [0] * len(tens.shape) |
| 106 | for out in outputs: |
| 107 | if out == tens: |
| 108 | break |
| 109 | offset_start[axis] += out.shape[axis] |
| 110 | |
Patrik Gustavsson | eebb1c2 | 2020-08-18 15:03:04 +0200 | [diff] [blame^] | 111 | # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input |
| 112 | if (offset_start[-1] % 16) != 0: |
| 113 | inp.avoid_NHCWB16 = True |
| 114 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 115 | offset_end[axis] = offset_start[axis] + tens.shape[axis] |
| 116 | |
| 117 | new_op.attrs["split_start"] = offset_start |
| 118 | new_op.attrs["split_end"] = offset_end |
| 119 | new_op.run_on_npu = True |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 120 | new_op.set_output_tensor(tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 121 | |
| 122 | return tens |
| 123 | |
| 124 | |
| 125 | def needed_total_padding(input_size, stride, filter_size): |
| 126 | out_size = (input_size + stride - 1) // stride |
| 127 | needed_input = (out_size - 1) * stride + filter_size |
| 128 | total_padding = max(0, needed_input - input_size) |
| 129 | return total_padding |
| 130 | |
| 131 | |
| 132 | def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims): |
| 133 | ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0])) |
| 134 | xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1])) |
| 135 | if padding_type == b"SAME": |
| 136 | left_pad = (xpad + 0) // 2 |
| 137 | right_pad = (xpad + 1) // 2 |
| 138 | top_pad = (ypad + 0) // 2 |
| 139 | bottom_pad = (ypad + 1) // 2 |
| 140 | elif padding_type == b"VALID": |
| 141 | left_pad = 0 |
| 142 | right_pad = 0 |
| 143 | top_pad = 0 |
| 144 | bottom_pad = 0 |
| 145 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 146 | raise UnsupportedFeatureError("Unknown padding {}".format(str(padding_type))) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 147 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
| 148 | skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad) |
| 149 | return padding, skirt |
| 150 | |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 151 | |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 152 | def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor): |
| 153 | kernel_height, kernel_width = kernel_size[0], kernel_size[1] |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 154 | if padding_type == b"SAME": |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 155 | ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height)) |
| 156 | xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width)) |
| 157 | |
| 158 | right_pad = ((xpad + 1) // upscaling_factor) - 1 |
| 159 | bottom_pad = ((ypad + 1) // upscaling_factor) - 1 |
| 160 | left_pad = max(kernel_width - 1 - right_pad, 0) |
| 161 | top_pad = max(kernel_height - 1 - bottom_pad, 0) |
| 162 | |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 163 | elif padding_type == b"VALID": |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 164 | right_pad = max(kernel_width - 2, 0) |
| 165 | bottom_pad = max(kernel_height - 2, 0) |
| 166 | left_pad = kernel_width - 1 |
| 167 | top_pad = kernel_height - 1 |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 168 | else: |
| 169 | assert 0, "Unknown padding" |
| 170 | |
| 171 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 172 | skirt = padding |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 173 | return padding, skirt |
| 174 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 175 | |
| 176 | def fixup_conv2d_backprop(op, arch): |
| 177 | if op.type == "Conv2DBackpropInput": |
| 178 | # flip the inputs |
| 179 | op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0] |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 180 | op.type = "Conv2DBackpropInputSwitchedBias" |
| 181 | weight_shape = op.inputs[1].shape |
| 182 | weight_sets = weight_shape[3] |
| 183 | |
| 184 | if len(op.inputs) < 4: |
| 185 | # Add bias/scale tensor filled with zeros |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 186 | scale_tens = Tensor([weight_sets], DataType.int32, op.name + "_bias_tens") |
| 187 | scale_tens.values = [0] * weight_sets |
| 188 | scale_tens.quant_values = [0] * weight_sets |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 189 | scale_op = Operation("Const", op.name + "_bias") |
| 190 | scale_op.set_output_tensor(scale_tens) |
| 191 | op.add_input_tensor(scale_tens) |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 192 | |
| 193 | # Update strides |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 194 | 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] | 195 | |
| 196 | return op |
| 197 | |
| 198 | |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 199 | # Convert the op to an elementwise add |
| 200 | def convert_resizebilinear_1x1_to_add(op): |
| 201 | op.type = "AddAct" |
| 202 | op.name = op.name + "_add" |
| 203 | op.attrs.update({"npu_block_type": NpuBlockType.ElementWise}) |
| 204 | op.attrs["resizebilinear"] = True |
| 205 | # Create an input tensor filled with zeros |
| 206 | shape = op.outputs[0].shape |
| 207 | tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add") |
| 208 | tens.values = np.zeros(shape) |
| 209 | tens.quant_values = np.zeros(shape, np.uint8) |
| 210 | tens.quantization = QuantizationParameters(0.0, 255.0) |
| 211 | tens.quantization.scale_f32 = 1.0 |
| 212 | tens.quantization.zero_point = 0 |
| 213 | tens.consumer_list = [op] |
| 214 | tens_op = op.inputs[1].ops[0] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 215 | tens_op.set_output_tensor(tens) |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 216 | # Set the add inputs |
| 217 | op.inputs[1] = op.inputs[0] |
| 218 | op.inputs[0] = tens |
| 219 | |
| 220 | return op |
| 221 | |
| 222 | |
| 223 | def fixup_resizebilinear(op, arch): |
| 224 | if op.type == "ResizeBilinear": |
| 225 | if op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1: |
| 226 | convert_resizebilinear_1x1_to_add(op) |
Charles Xu | 36ffaf3 | 2020-08-05 15:40:44 +0200 | [diff] [blame] | 227 | elif op.inputs[0].shape == op.outputs[0].shape: |
| 228 | # Bypass nop resizebilinear |
| 229 | op.inputs = op.inputs[:1] |
| 230 | op.type = "Identity" |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 231 | |
| 232 | return op |
| 233 | |
| 234 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 235 | def fixup_fully_connected_input(op, arch): |
| 236 | if op.type == "FullyConnectedAct": |
| 237 | inp = op.inputs[0] |
| 238 | weights = op.inputs[1] |
| 239 | |
| 240 | n_in_elems = weights.shape[-2] |
| 241 | elms = inp.elements() |
| 242 | batch_size = elms // n_in_elems |
| 243 | assert batch_size * n_in_elems == elms |
| 244 | |
| 245 | desired_shape = [batch_size, n_in_elems] |
| 246 | if inp.shape != desired_shape: |
| 247 | # mismatch, insert a reshape to fix this. |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 248 | op.inputs[0] = create_reshape_tensor(inp, desired_shape) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 249 | |
| 250 | return op |
| 251 | |
| 252 | |
| 253 | def fixup_pack_input(op, arch): |
| 254 | if op.type == "Pack": |
| 255 | # Pack is also referred to as Stack |
| 256 | # Requires the rewrite_concat function to be called on the op afterwards |
| 257 | axis = int(op.attrs["axis"]) |
| 258 | desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:] |
| 259 | |
| 260 | # Construct 1 shape tensor to be used by all inserted reshape ops |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 261 | 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] | 262 | |
| 263 | for idx, inp in enumerate(op.inputs): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 264 | reshape_out = inp.clone("_reshaped") |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 265 | reshape_out.set_all_shapes(desired_shape) |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 266 | |
| 267 | reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx)) |
| 268 | reshape_op.attrs["new_shape"] = desired_shape |
| 269 | reshape_op.inputs = [inp, new_shape_tens] |
| 270 | reshape_op.set_output_tensor(reshape_out) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 271 | |
| 272 | op.inputs[idx] = reshape_out |
| 273 | |
| 274 | op.type = "PackReshaped" |
| 275 | |
| 276 | return op |
| 277 | |
| 278 | |
| 279 | def fixup_unpack_output(tens, arch): |
| 280 | op = tens.ops[0] |
| 281 | if op.type in set(("Unpack", "StridedSlice")): |
| 282 | # Unpack is also referred to as Unstack |
| 283 | # Requires the rewrite_split function to be called on the op afterwards |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 284 | |
| 285 | reshape_input_shape = tens.shape |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 286 | if op.type == "StridedSlice": |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 287 | new_axis_mask = op.attrs["new_axis_mask"] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 288 | shrink_axis_mask = op.attrs["shrink_axis_mask"] |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 289 | ellipsis_mask = op.attrs["ellipsis_mask"] |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 290 | |
| 291 | if (new_axis_mask != 0 and shrink_axis_mask != 0) or ellipsis_mask != 0: |
| 292 | # Not supported, will be put on CPU |
| 293 | return tens |
| 294 | if shrink_axis_mask == 0 and new_axis_mask == 0: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 295 | # Equal Rank StridedSlice, no need to insert reshape |
| 296 | return tens |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 297 | elif shrink_axis_mask != 0: |
| 298 | n = 0 |
| 299 | axis = 0 |
| 300 | while shrink_axis_mask: |
| 301 | prev_mask = shrink_axis_mask |
| 302 | n += 1 |
| 303 | shrink_axis_mask &= shrink_axis_mask - 1 |
| 304 | axis = int(math.log2(prev_mask - shrink_axis_mask)) |
| 305 | reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 306 | |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 307 | assert len(tens.shape) == (len(op.inputs[0].shape) - n) |
| 308 | op.attrs["shrink_axis_mask"] = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 309 | |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 310 | elif new_axis_mask != 0: |
| 311 | n = 0 |
| 312 | axis = 0 |
| 313 | while new_axis_mask: |
| 314 | prev_mask = new_axis_mask |
| 315 | n += 1 |
| 316 | new_axis_mask &= new_axis_mask - 1 |
| 317 | axis = int(math.log2(prev_mask - new_axis_mask)) |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 318 | reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :] |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 319 | new_axis_mask >>= 1 |
| 320 | |
| 321 | assert len(tens.shape) == (len(op.inputs[0].shape) + n) |
| 322 | op.attrs["new_axis_mask"] = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 323 | else: |
| 324 | axis = int(op.attrs["axis"]) |
| 325 | op.type = "UnpackReshaped" |
Patrik Gustavsson | cf72890 | 2020-04-30 08:57:23 +0200 | [diff] [blame] | 326 | reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 327 | |
| 328 | # Construct 1 shape tensor to be used by all inserted reshape ops |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 329 | 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] | 330 | |
| 331 | for idx, out_tens in enumerate(op.outputs): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 332 | reshape_in = out_tens.clone("_reshaped") |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 333 | reshape_in.set_all_shapes(reshape_input_shape) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 334 | reshape_in.ops = [op] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 335 | |
| 336 | reshape_op = Operation("Reshape", "{}{}_reshape".format(op.name, idx)) |
| 337 | reshape_op.attrs["new_shape"] = reshape_input_shape |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 338 | reshape_op.inputs = [reshape_in, new_shape_tens] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 339 | reshape_op.set_output_tensor(out_tens) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 340 | |
| 341 | op.outputs[idx] = reshape_in |
| 342 | |
| 343 | return tens |
| 344 | |
| 345 | |
| 346 | def add_padding_fields(op, arch): |
| 347 | if "padding" in op.attrs: |
| 348 | if "Conv" in op.type: |
| 349 | kernel_size = op.inputs[1].shape[:2] |
| 350 | input_shape = op.inputs[0].shape |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 351 | elif "Pool" in op.type or op.type in ("ResizeBilinear", "ReduceSum"): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 352 | kernel_size = op.attrs["ksize"][1:3] |
| 353 | input_shape = op.inputs[0].shape |
| 354 | elif op.type == "ExtractImagePatches": |
| 355 | kernel_size = op.attrs["ksizes"][1:3] |
| 356 | input_shape = op.inputs[0].shape |
| 357 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 358 | raise UnsupportedFeatureError("Unknown operation that uses padding: {}".format(op.type)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 359 | |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 360 | if op.type == "Conv2DBackpropInputSwitchedBias": |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 361 | upscaling_factor = op.outputs[0].shape[1] // input_shape[1] |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 362 | padding, skirt = calc_upscaled_padding_and_skirt( |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 363 | op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 364 | ) |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 365 | else: |
| 366 | dilation_h, dilation_w = op.get_dilation_h_w() |
| 367 | dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1] |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 368 | padding, skirt = calc_padding_and_skirt( |
| 369 | op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape |
| 370 | ) |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 371 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 372 | op.attrs["explicit_padding"] = padding |
| 373 | op.attrs["skirt"] = skirt |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 374 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 375 | return op |
| 376 | |
| 377 | |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 378 | conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitchedBias", "Conv2DBiasAct")) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 379 | fc_op = set( |
| 380 | ( |
| 381 | "MatMul", |
| 382 | "QuantizedMatMul", |
| 383 | "BlockLSTM", |
| 384 | "RnnAct", |
| 385 | "UnidirectionalSequenceRnnAct", |
| 386 | "BidirectionalSequenceRnnAct", |
| 387 | "LstmAct", |
| 388 | "UnidirectionalSequenceLstmAct", |
| 389 | "BidirectionalSequenceLstmAct", |
| 390 | "FullyConnectedAct", |
| 391 | ) |
| 392 | ) |
| 393 | depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",)) |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 394 | pool_op = set( |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 395 | ("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct", "ResizeBilinear") |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 396 | ) |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 397 | reduce_sum_ops = set(("ReduceSum",)) |
| 398 | elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs", "CLZ", "SHL", "SHR")) |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 399 | binary_elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum")) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 400 | activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh")) |
| 401 | memory_only_ops = set(("Reshape",)) |
| 402 | |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 403 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 404 | # Check if the op can be reordered |
| 405 | def get_prepend_op(op): |
| 406 | inp = op.inputs[0] |
| 407 | # The op should be reordered between prev_op and prep_op |
| 408 | prev_op = inp.ops[-1] |
| 409 | prep_op = None |
| 410 | while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1: |
| 411 | prep_op = prev_op |
| 412 | inp = prev_op.inputs[0] |
| 413 | prev_op = inp.ops[-1] |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 414 | 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] | 415 | return prep_op |
| 416 | |
| 417 | return None |
| 418 | |
| 419 | |
| 420 | def mark_npu_block_type(op, arch): |
| 421 | npu_block_type = NpuBlockType.Default |
| 422 | if op.type in conv_op: |
| 423 | npu_block_type = NpuBlockType.ConvolutionMxN |
| 424 | elif op.type in fc_op: |
| 425 | npu_block_type = NpuBlockType.VectorProduct |
| 426 | elif op.type in depthwise_op: |
| 427 | npu_block_type = NpuBlockType.ConvolutionDepthWise |
| 428 | elif op.type in pool_op: |
| 429 | npu_block_type = NpuBlockType.Pooling |
| 430 | elif op.type in elementwise_op: |
| 431 | npu_block_type = NpuBlockType.ElementWise |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 432 | elif op.type in reduce_sum_ops: |
| 433 | npu_block_type = NpuBlockType.ReduceSum |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 434 | |
| 435 | op.attrs["npu_block_type"] = npu_block_type |
| 436 | return op |
| 437 | |
| 438 | |
| 439 | def convert_depthwise_to_conv(op, arch): |
| 440 | # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and |
| 441 | # the ofm depth equals the depth multipler. |
| 442 | # If those conditions are true, then we can perform a simple |
| 443 | # switch of the operator type (and weight order) |
| 444 | |
| 445 | if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1): |
| 446 | ifm_tensor = op.inputs[0] |
| 447 | weight_tensor = op.inputs[1] |
| 448 | ofm_tensor = op.outputs[0] |
| 449 | if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]): |
| 450 | # Change op type to Conv2d |
| 451 | op.type = op.type.replace("DepthwiseConv2d", "Conv2D") |
| 452 | del op.attrs["channel_multiplier"] |
| 453 | del op.attrs["depth_multiplier"] |
| 454 | |
| 455 | 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] | 456 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 457 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 458 | raise UnsupportedFeatureError( |
| 459 | "Unsupported DepthwiseConv2d with depth_multiplier = {}, ifm channels = {}, ofm channels = {}".format( |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 460 | op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3] |
| 461 | ) |
| 462 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 463 | return op |
| 464 | |
| 465 | |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 466 | def reorder_depthwise_weights(op, arch): |
| 467 | if "DepthwiseConv2d" in op.type: |
| 468 | weight_tensor = op.inputs[1] |
| 469 | 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] | 470 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 471 | weight_tensor.weight_transpose_depthwise = True |
| 472 | |
| 473 | return op |
| 474 | |
| 475 | |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 476 | def convert_conv_to_fc(op, arch): |
| 477 | # Conv 1x1 can be equivalent to Fully Connected. |
| 478 | # By representing certain convs as fully connected layers, Vela can better determine wether or not to use |
| 479 | # caching/double buffering for the weights. |
| 480 | # (Weights dont need to be reloaded for convs when IFM H and W are 1) |
| 481 | if op.type == "Conv2DBiasAct": |
| 482 | _, h, w, _ = op.inputs[0].shape |
| 483 | kh, kw, _, _ = op.inputs[1].shape |
| 484 | if h == 1 and w == 1 and kh == 1 and kw == 1: |
| 485 | # Overwrite this op as a Fully Connected Op |
| 486 | op.name += "_fc" |
| 487 | op.type = "FullyConnectedAct" |
| 488 | faf = op.attrs.get("fused_activation_function", None) |
| 489 | op.attrs = { |
| 490 | "fused_activation_function": faf, |
| 491 | "weights_format": 0, |
| 492 | "npu_block_type": NpuBlockType.VectorProduct, |
| 493 | } |
| 494 | # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped) |
| 495 | weight_tensor = op.inputs[1] |
| 496 | weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1)) |
| 497 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
| 498 | # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it |
| 499 | # back to 4D afterwards as the next layer is expecting that shape |
| 500 | orig_ofm_tensor = op.outputs[0] |
| 501 | # 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}) |
| 502 | fc_ofm_tensor = orig_ofm_tensor.clone("_fc") |
| 503 | fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]]) |
| 504 | fc_ofm_tensor.ops = [op] |
| 505 | # 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] | 506 | reshape_name = op.name + "_reshape" |
| 507 | 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] | 508 | reshape_op = Operation("Reshape", reshape_name) |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 509 | reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 510 | reshape_op.inputs = [fc_ofm_tensor, new_shape_tens] |
| 511 | reshape_op.set_output_tensor(orig_ofm_tensor) |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 512 | # Replace this ops OFM to point to the 2D tensor |
| 513 | op.outputs[0] = fc_ofm_tensor |
| 514 | return op |
| 515 | |
| 516 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 517 | # Reorder activation op if it's after the memory only operations |
| 518 | def fixup_act_reorder(op, arch): |
| 519 | if op.type in activation_ops: |
| 520 | prep_op = get_prepend_op(op) |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 521 | if prep_op is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 522 | act_op = op.clone("_reordered") |
| 523 | act_op.inputs = [prep_op.inputs[0]] |
| 524 | act_op_out = act_op.inputs[0].clone("_acted") |
| 525 | act_op_out.quantization = op.outputs[0].quantization.clone() |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 526 | act_op.set_output_tensor(act_op_out) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 527 | prep_op.inputs[0] = act_op_out |
| 528 | prep_op.outputs[0].quantization = act_op_out.quantization.clone() |
| 529 | |
| 530 | # Mark the op so that it will be removed as passthrough later on |
| 531 | op.type = "Identity" |
| 532 | return op |
| 533 | |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 534 | |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 535 | def fixup_elementwise_with_scalars(op, arch): |
| 536 | if op.type in binary_elementwise_op: |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 537 | ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm() |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 538 | if ifm2_tensor.shape != [] and ifm_tensor.shape != []: |
| 539 | diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape) |
| 540 | if diff > 0: |
| 541 | ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1) |
| 542 | elif diff < 0: |
| 543 | 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] | 544 | elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None: |
| 545 | # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 546 | ifm_tensor.shape = len(ifm2_tensor.shape) * [1] |
| 547 | ifm_tensor.storage_shape = ifm_tensor.shape |
| 548 | elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None: |
| 549 | # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 550 | ifm2_tensor.shape = len(ifm_tensor.shape) * [1] |
| 551 | ifm2_tensor.storage_shape = ifm2_tensor.shape |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 552 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 553 | |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 554 | |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 555 | # Set input/output tensor equivalence to the same id for memory operations |
| 556 | def set_tensor_equivalence(op, arch): |
| 557 | if op.type == "Reshape": |
| 558 | eid = op.outputs[0].equivalence_id |
| 559 | for inp in op.inputs: |
| 560 | inp.equivalence_id = eid |
| 561 | return op |
| 562 | |
| 563 | |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 564 | def convert_softmax(op, arch): |
| 565 | if op.type == "Softmax" and op.run_on_npu: |
| 566 | softmax = SoftMax(op) |
| 567 | op = softmax.get_graph() |
| 568 | return op |
| 569 | |
| 570 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 571 | def convert_mul_max_to_abs_or_lrelu(op, arch): |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 572 | r"""Whenever there is a subgraph with this topology: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 573 | |
| 574 | Input X For X = -1 or X > 0 |
| 575 | | \ / This subgraph can be replaced with either |
| 576 | | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0) |
| 577 | | / |
| 578 | Max |
| 579 | """ |
| 580 | |
| 581 | if op.type == "Maximum": |
| 582 | # finds the Mul input(s) to the Max |
| 583 | muls = [i for i in op.inputs if i.ops[0].type == "MulAct"] |
| 584 | if len(muls) == 1: |
| 585 | mul = muls[0].ops[0] |
| 586 | elif len(muls) == 2: |
| 587 | # In the case both inputs are Muls, find the one with the same input as the Max |
| 588 | mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0] |
| 589 | else: |
| 590 | # No Mul inputs |
| 591 | return op |
| 592 | |
| 593 | # make sure the Mul doesn't have any other consumers |
| 594 | if len(mul.outputs[0].consumers()) != 1: |
| 595 | return op |
| 596 | # make sure the Mul doesn't have a faf |
| 597 | if mul.attrs["fused_activation_function"]: |
| 598 | return op |
| 599 | |
| 600 | # finds the branched input that goes to both the Max and the Mul |
| 601 | shared = set(op.inputs) & set(mul.inputs) |
| 602 | if len(shared) == 1: |
| 603 | shared_in = shared.pop() |
| 604 | # find the constant scalar input to the Mul |
| 605 | const_tens = (set(mul.inputs) - {shared_in}).pop() |
| 606 | # check that it is a scalar |
| 607 | if const_tens.shape != []: |
| 608 | return op |
| 609 | const = const_tens.ops[0] |
| 610 | # check that it is a constant |
| 611 | if const.type != "Const": |
| 612 | return op |
| 613 | else: |
| 614 | return op |
| 615 | |
| 616 | val = const.outputs[0].values |
| 617 | if val >= 0: |
| 618 | new_op = "LeakyRelu" |
| 619 | op.attrs["alpha"] = val |
| 620 | elif val == -1: |
| 621 | new_op = "Abs" |
| 622 | else: |
| 623 | return op |
| 624 | |
| 625 | op.type = op.type.replace("Maximum", new_op) |
| 626 | op.name = op.name.replace("Maximum", new_op) |
| 627 | op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op) |
| 628 | op.inputs = [shared_in] |
| 629 | return op |
| 630 | |
| 631 | |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 632 | def add_attrs_to_resizebilinear(op, arch): |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 633 | if op.type == "ResizeBilinear" and op.run_on_npu: |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 634 | input_tensor = op.inputs[0] |
| 635 | upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2] |
| 636 | out_shape = op.outputs[0].shape[1:3] |
| 637 | if not op.attrs["align_corners"] and out_shape == upscaled_shape: |
| 638 | # this means the output is supposed to be a x2 upscale, |
| 639 | # so we need to do SAME padding |
| 640 | op.attrs["padding"] = b"SAME" |
| 641 | elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]: |
| 642 | # here we can just run the avg pool without padding and |
| 643 | # produce a (M * 2 - 1, N * 2 - 1) sized output |
| 644 | op.attrs["padding"] = b"VALID" |
| 645 | else: |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 646 | return op |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 647 | input_tensor.resampling_mode = resampling_mode.NEAREST |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 648 | 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] | 649 | return op |
| 650 | |
| 651 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 652 | def supported_operator_check(op, arch): |
| 653 | op.run_on_npu = arch.supported_operators.is_operator_supported(op) |
| 654 | return op |
| 655 | |
| 656 | |
| 657 | def optimise_graph_a(nng, arch, verbose_graph=False): |
| 658 | if verbose_graph: |
| 659 | nng.print_graph() |
| 660 | |
| 661 | op_rewrite_list = [ |
| 662 | # mark block type and check if the operations are supported |
| 663 | mark_npu_block_type, |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 664 | set_tensor_equivalence, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 665 | supported_operator_check, |
| 666 | # then do any rewrites of supported operators |
| 667 | convert_depthwise_to_conv, |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 668 | convert_conv_to_fc, |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 669 | convert_softmax, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 670 | fixup_fully_connected_input, |
| 671 | fixup_pack_input, |
| 672 | fixup_conv2d_backprop, |
| 673 | fixup_act_reorder, |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 674 | add_attrs_to_resizebilinear, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 675 | add_padding_fields, |
| 676 | mark_npu_block_type, |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 677 | fixup_elementwise_with_scalars, |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 678 | reorder_depthwise_weights, |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 679 | fixup_resizebilinear, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 680 | # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved |
| 681 | ] |
| 682 | |
| 683 | for idx, sg in enumerate(nng.subgraphs): |
| 684 | # rewrite graph pass |
| 685 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 686 | sg, arch, [fixup_unpack_output], op_rewrite_list, rewrite_unsupported=False |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 687 | ) |
| 688 | |
| 689 | for idx, sg in enumerate(nng.subgraphs): |
| 690 | # remove passthrough tensors |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 691 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor], []) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 692 | |
| 693 | if verbose_graph: |
| 694 | nng.print_graph() |
| 695 | return nng |
| 696 | |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 697 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 698 | def optimise_graph_b(nng, arch, verbose_graph=False): |
| 699 | if verbose_graph: |
| 700 | nng.print_graph() |
| 701 | |
| 702 | for idx, sg in enumerate(nng.subgraphs): |
| 703 | # combined rewrite graph pass |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 704 | 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] | 705 | |
| 706 | if verbose_graph: |
| 707 | nng.print_graph() |
| 708 | return nng |