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