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. |
| 16 | |
| 17 | |
| 18 | # Description: |
| 19 | # Early optimisation of the network graph, using the rewrite_graph module to do the traversal of the graph. These are |
| 20 | # split into two parts optimise_graph_a and optimise_graph_b. |
| 21 | |
| 22 | from .nn_graph import Operation, NpuBlockType, Tensor |
| 23 | from . import rewrite_graph |
| 24 | from .data_type import BaseType, DataType |
| 25 | import numpy as np |
| 26 | import math |
| 27 | from .numeric_util import round_up_divide |
| 28 | |
| 29 | passthrough_nodes = set(("Identity",)) |
| 30 | |
| 31 | |
| 32 | def remove_passthrough_tensor(tens, arch): |
| 33 | if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes: |
| 34 | assert len(tens.ops[0].inputs) == 1 |
| 35 | tens = tens.ops[0].inputs[0] |
| 36 | return tens |
| 37 | |
| 38 | |
| 39 | def rewrite_concat(tens, arch): |
| 40 | if len(tens.ops) == 1 and tens.ops[0].is_concat_op(): |
| 41 | concat_op = tens.ops[0] |
| 42 | if tens != concat_op.outputs[0]: |
| 43 | return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat |
| 44 | |
| 45 | # Not supported so leave it and run on CPU |
| 46 | if not concat_op.run_on_npu: |
| 47 | return tens |
| 48 | |
| 49 | inputs, axis = concat_op.get_concat_inputs_axis() |
| 50 | |
| 51 | tens.ops = [] |
| 52 | offset = 0 |
| 53 | for idx, inp in enumerate(inputs): |
| 54 | new_op = Operation("ConcatSliceWrite", concat_op.name + str(idx)) |
| 55 | new_op.inputs = [inp] |
| 56 | new_op.outputs = [tens] |
| 57 | new_op.attrs["concat_axis"] = axis |
| 58 | new_op.attrs["concat_start"] = offset |
| 59 | offset += inp.shape[axis] |
| 60 | new_op.attrs["concat_end"] = offset |
| 61 | new_op.run_on_npu = True |
| 62 | tens.ops.append(new_op) |
| 63 | assert tens.shape[axis] == offset |
| 64 | |
| 65 | return tens |
| 66 | |
| 67 | |
| 68 | def rewrite_split(tens, arch): |
| 69 | |
| 70 | if len(tens.ops) == 1 and tens.ops[0].is_split_op(): |
| 71 | split_op = tens.ops[0] |
| 72 | |
| 73 | # Not supported so leave it and run on CPU |
| 74 | if not split_op.run_on_npu: |
| 75 | return tens |
| 76 | |
| 77 | inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis() |
| 78 | |
| 79 | tens.ops = [] |
| 80 | new_op = Operation("SplitSliceRead", split_op.name) |
| 81 | new_op.inputs = [inp] |
| 82 | new_op.outputs = [tens] |
| 83 | |
| 84 | # For Split the offset cannot be extracted from the tensor so it has to |
| 85 | # be calculated from the index of the output tensor |
| 86 | if axis != None: |
| 87 | # Get the start and end of the split |
| 88 | offset_start = [0] * len(tens.shape) |
| 89 | offset_end = [0] * len(tens.shape) |
| 90 | for out in outputs: |
| 91 | if out == tens: |
| 92 | break |
| 93 | offset_start[axis] += out.shape[axis] |
| 94 | |
| 95 | offset_end[axis] = offset_start[axis] + tens.shape[axis] |
| 96 | |
| 97 | new_op.attrs["split_start"] = offset_start |
| 98 | new_op.attrs["split_end"] = offset_end |
| 99 | new_op.run_on_npu = True |
| 100 | tens.ops.append(new_op) |
| 101 | |
| 102 | return tens |
| 103 | |
| 104 | |
| 105 | def needed_total_padding(input_size, stride, filter_size): |
| 106 | out_size = (input_size + stride - 1) // stride |
| 107 | needed_input = (out_size - 1) * stride + filter_size |
| 108 | total_padding = max(0, needed_input - input_size) |
| 109 | return total_padding |
| 110 | |
| 111 | |
| 112 | def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims): |
| 113 | ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0])) |
| 114 | xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1])) |
| 115 | if padding_type == b"SAME": |
| 116 | left_pad = (xpad + 0) // 2 |
| 117 | right_pad = (xpad + 1) // 2 |
| 118 | top_pad = (ypad + 0) // 2 |
| 119 | bottom_pad = (ypad + 1) // 2 |
| 120 | elif padding_type == b"VALID": |
| 121 | left_pad = 0 |
| 122 | right_pad = 0 |
| 123 | top_pad = 0 |
| 124 | bottom_pad = 0 |
| 125 | else: |
| 126 | assert 0, "Unknown padding" |
| 127 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
| 128 | skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad) |
| 129 | return padding, skirt |
| 130 | |
| 131 | |
| 132 | def fixup_conv2d_backprop(op, arch): |
| 133 | if op.type == "Conv2DBackpropInput": |
| 134 | # flip the inputs |
| 135 | op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0] |
| 136 | op.type = "Conv2DBackpropInputSwitched" |
| 137 | |
| 138 | return op |
| 139 | |
| 140 | |
| 141 | def fixup_fully_connected_input(op, arch): |
| 142 | if op.type == "FullyConnectedAct": |
| 143 | inp = op.inputs[0] |
| 144 | weights = op.inputs[1] |
| 145 | |
| 146 | n_in_elems = weights.shape[-2] |
| 147 | elms = inp.elements() |
| 148 | batch_size = elms // n_in_elems |
| 149 | assert batch_size * n_in_elems == elms |
| 150 | |
| 151 | desired_shape = [batch_size, n_in_elems] |
| 152 | if inp.shape != desired_shape: |
| 153 | # mismatch, insert a reshape to fix this. |
| 154 | reshape_name = op.name + "_reshape" |
| 155 | new_shape_tens = Tensor([1], DataType.int32, reshape_name + "_shape") |
| 156 | new_shape_tens.values = np.array(desired_shape) |
| 157 | new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const") |
| 158 | new_shape_tens.ops = [new_shape_tens_const] |
| 159 | new_shape_tens_const.outputs = [new_shape_tens] |
| 160 | |
| 161 | reshape_op = Operation("Reshape", reshape_name) |
| 162 | reshape_op.inputs = [inp, new_shape_tens] |
| 163 | reshape_op.attrs["new_shape"] = desired_shape |
| 164 | reshape_out = inp.clone("_reshaped") |
| 165 | reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape |
| 166 | reshape_out.ops = [reshape_op] |
| 167 | reshape_op.outputs = [reshape_out] |
| 168 | |
| 169 | op.inputs[0] = reshape_out |
| 170 | |
| 171 | return op |
| 172 | |
| 173 | |
| 174 | def fixup_pack_input(op, arch): |
| 175 | if op.type == "Pack": |
| 176 | # Pack is also referred to as Stack |
| 177 | # Requires the rewrite_concat function to be called on the op afterwards |
| 178 | axis = int(op.attrs["axis"]) |
| 179 | desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:] |
| 180 | |
| 181 | # Construct 1 shape tensor to be used by all inserted reshape ops |
| 182 | new_shape_name = op.name + "_reshape_shape" |
| 183 | new_shape_tens = Tensor([1], DataType.int32, new_shape_name) |
| 184 | new_shape_tens.values = np.array(desired_shape) |
| 185 | new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const") |
| 186 | new_shape_tens.ops = [new_shape_tens_const] |
| 187 | new_shape_tens_const.outputs = [new_shape_tens] |
| 188 | |
| 189 | for idx, inp in enumerate(op.inputs): |
| 190 | reshape_name = op.name + str(idx) + "_reshape" |
| 191 | reshape_op = Operation("Reshape", reshape_name) |
| 192 | reshape_op.inputs = [inp, new_shape_tens] |
| 193 | reshape_op.attrs["new_shape"] = desired_shape |
| 194 | reshape_out = inp.clone("_reshaped") |
| 195 | reshape_out.shape = reshape_out.storage_shape = reshape_out.bandwidth_shape = desired_shape |
| 196 | reshape_out.ops = [reshape_op] |
| 197 | reshape_op.outputs = [reshape_out] |
| 198 | |
| 199 | op.inputs[idx] = reshape_out |
| 200 | |
| 201 | op.type = "PackReshaped" |
| 202 | |
| 203 | return op |
| 204 | |
| 205 | |
| 206 | def fixup_unpack_output(tens, arch): |
| 207 | op = tens.ops[0] |
| 208 | if op.type in set(("Unpack", "StridedSlice")): |
| 209 | # Unpack is also referred to as Unstack |
| 210 | # Requires the rewrite_split function to be called on the op afterwards |
| 211 | if op.type == "StridedSlice": |
| 212 | shrink_axis_mask = op.attrs["shrink_axis_mask"] |
| 213 | if shrink_axis_mask == 0: |
| 214 | # Equal Rank StridedSlice, no need to insert reshape |
| 215 | return tens |
| 216 | |
| 217 | # Only allow shrinking 1 axis for now |
| 218 | assert shrink_axis_mask & (shrink_axis_mask - 1) == 0 |
| 219 | assert len(tens.shape) == (len(op.inputs[0].shape) - 1) |
| 220 | |
| 221 | axis = int(math.log2(shrink_axis_mask)) |
| 222 | op.attrs["shrink_axis_mask"] = 0 |
| 223 | else: |
| 224 | axis = int(op.attrs["axis"]) |
| 225 | op.type = "UnpackReshaped" |
| 226 | |
| 227 | desired_shape = tens.shape[:axis] + [1] + tens.shape[axis:] |
| 228 | |
| 229 | # Construct 1 shape tensor to be used by all inserted reshape ops |
| 230 | new_shape_name = op.name + "_reshape_shape" |
| 231 | new_shape_tens = Tensor([1], DataType.int32, new_shape_name) |
| 232 | new_shape_tens.values = np.array(tens.shape) |
| 233 | new_shape_tens_const = Operation("Const", new_shape_tens.name + "_const") |
| 234 | new_shape_tens.ops = [new_shape_tens_const] |
| 235 | new_shape_tens_const.outputs = [new_shape_tens] |
| 236 | |
| 237 | for idx, out_tens in enumerate(op.outputs): |
| 238 | reshape_name = op.name + str(idx) + "_reshape" |
| 239 | reshape_op = Operation("Reshape", reshape_name) |
| 240 | reshape_op.outputs = [out_tens] |
| 241 | reshape_in = out_tens.clone("_reshaped") |
| 242 | reshape_in.shape = reshape_in.storage_shape = reshape_in.bandwidth_shape = desired_shape |
| 243 | reshape_in.ops = [op] |
| 244 | out_tens.ops = [reshape_op] |
| 245 | reshape_op.inputs = [reshape_in, new_shape_tens] |
| 246 | |
| 247 | op.outputs[idx] = reshape_in |
| 248 | |
| 249 | return tens |
| 250 | |
| 251 | |
| 252 | def add_padding_fields(op, arch): |
| 253 | if "padding" in op.attrs: |
| 254 | if "Conv" in op.type: |
| 255 | kernel_size = op.inputs[1].shape[:2] |
| 256 | input_shape = op.inputs[0].shape |
| 257 | elif "Pool" in op.type: |
| 258 | kernel_size = op.attrs["ksize"][1:3] |
| 259 | input_shape = op.inputs[0].shape |
| 260 | elif op.type == "ExtractImagePatches": |
| 261 | kernel_size = op.attrs["ksizes"][1:3] |
| 262 | input_shape = op.inputs[0].shape |
| 263 | else: |
| 264 | assert 0, "Unknown operation that uses padding" |
| 265 | |
| 266 | padding, skirt = calc_padding_and_skirt(op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape) |
| 267 | op.attrs["explicit_padding"] = padding |
| 268 | op.attrs["skirt"] = skirt |
| 269 | return op |
| 270 | |
| 271 | |
| 272 | conv_op = set(("Conv2D", "QuantizedConv2D", "Conv2DBackpropInputSwitched", "Conv2DBiasAct")) |
| 273 | fc_op = set( |
| 274 | ( |
| 275 | "MatMul", |
| 276 | "QuantizedMatMul", |
| 277 | "BlockLSTM", |
| 278 | "RnnAct", |
| 279 | "UnidirectionalSequenceRnnAct", |
| 280 | "BidirectionalSequenceRnnAct", |
| 281 | "LstmAct", |
| 282 | "UnidirectionalSequenceLstmAct", |
| 283 | "BidirectionalSequenceLstmAct", |
| 284 | "FullyConnectedAct", |
| 285 | ) |
| 286 | ) |
| 287 | depthwise_op = set(("DepthwiseConv2dNative", "DepthwiseConv2dBiasAct",)) |
| 288 | pool_op = set(("AvgPool", "MaxPool", "QuantizedAvgPool", "QuantizedMaxPool", "AvgPoolAct", "MaxPoolAct")) |
| 289 | elementwise_op = set(("AddAct", "MulAct", "SubAct", "Maximum", "Minimum", "LeakyRelu", "Abs")) |
| 290 | activation_ops = set(("Relu", "Relu6", "ReluN1To1", "Sigmoid", "Tanh")) |
| 291 | memory_only_ops = set(("Reshape",)) |
| 292 | |
| 293 | # Check if the op can be reordered |
| 294 | def get_prepend_op(op): |
| 295 | inp = op.inputs[0] |
| 296 | # The op should be reordered between prev_op and prep_op |
| 297 | prev_op = inp.ops[-1] |
| 298 | prep_op = None |
| 299 | while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1: |
| 300 | prep_op = prev_op |
| 301 | inp = prev_op.inputs[0] |
| 302 | prev_op = inp.ops[-1] |
| 303 | if prev_op != None and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1: |
| 304 | return prep_op |
| 305 | |
| 306 | return None |
| 307 | |
| 308 | |
| 309 | def mark_npu_block_type(op, arch): |
| 310 | npu_block_type = NpuBlockType.Default |
| 311 | if op.type in conv_op: |
| 312 | npu_block_type = NpuBlockType.ConvolutionMxN |
| 313 | elif op.type in fc_op: |
| 314 | npu_block_type = NpuBlockType.VectorProduct |
| 315 | elif op.type in depthwise_op: |
| 316 | npu_block_type = NpuBlockType.ConvolutionDepthWise |
| 317 | elif op.type in pool_op: |
| 318 | npu_block_type = NpuBlockType.Pooling |
| 319 | elif op.type in elementwise_op: |
| 320 | npu_block_type = NpuBlockType.ElementWise |
| 321 | |
| 322 | op.attrs["npu_block_type"] = npu_block_type |
| 323 | return op |
| 324 | |
| 325 | |
| 326 | def convert_depthwise_to_conv(op, arch): |
| 327 | # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and |
| 328 | # the ofm depth equals the depth multipler. |
| 329 | # If those conditions are true, then we can perform a simple |
| 330 | # switch of the operator type (and weight order) |
| 331 | |
| 332 | if ("DepthwiseConv2d" in op.type) and (op.attrs["depth_multiplier"] != 1): |
| 333 | ifm_tensor = op.inputs[0] |
| 334 | weight_tensor = op.inputs[1] |
| 335 | ofm_tensor = op.outputs[0] |
| 336 | if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]): |
| 337 | # Change op type to Conv2d |
| 338 | op.type = op.type.replace("DepthwiseConv2d", "Conv2D") |
| 339 | del op.attrs["channel_multiplier"] |
| 340 | del op.attrs["depth_multiplier"] |
| 341 | |
| 342 | weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2)) |
| 343 | weight_tensor.shape = weight_tensor.storage_shape = weight_tensor.bandwidth_shape = list( |
| 344 | weight_tensor.quant_values.shape |
| 345 | ) |
| 346 | else: |
| 347 | print( |
| 348 | "Error: Unsupported DepthwiseConv2d with depth_multiplier = {0}, " |
| 349 | "ifm channels = {1}, ofm channels = {2}".format( |
| 350 | op.attrs["depth_multiplier"], ifm_tensor.shape[3], ofm_tensor.shape[3] |
| 351 | ) |
| 352 | ) |
| 353 | assert False |
| 354 | return op |
| 355 | |
| 356 | |
| 357 | # Reorder activation op if it's after the memory only operations |
| 358 | def fixup_act_reorder(op, arch): |
| 359 | if op.type in activation_ops: |
| 360 | prep_op = get_prepend_op(op) |
| 361 | if prep_op != None: |
| 362 | act_op = op.clone("_reordered") |
| 363 | act_op.inputs = [prep_op.inputs[0]] |
| 364 | act_op_out = act_op.inputs[0].clone("_acted") |
| 365 | act_op_out.quantization = op.outputs[0].quantization.clone() |
| 366 | act_op_out.ops = [act_op] |
| 367 | act_op.outputs = [act_op_out] |
| 368 | prep_op.inputs[0] = act_op_out |
| 369 | prep_op.outputs[0].quantization = act_op_out.quantization.clone() |
| 370 | |
| 371 | # Mark the op so that it will be removed as passthrough later on |
| 372 | op.type = "Identity" |
| 373 | return op |
| 374 | |
| 375 | |
| 376 | def convert_mul_max_to_abs_or_lrelu(op, arch): |
| 377 | """Whenever there is a subgraph with this topology: |
| 378 | |
| 379 | Input X For X = -1 or X > 0 |
| 380 | | \ / This subgraph can be replaced with either |
| 381 | | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0) |
| 382 | | / |
| 383 | Max |
| 384 | """ |
| 385 | |
| 386 | if op.type == "Maximum": |
| 387 | # finds the Mul input(s) to the Max |
| 388 | muls = [i for i in op.inputs if i.ops[0].type == "MulAct"] |
| 389 | if len(muls) == 1: |
| 390 | mul = muls[0].ops[0] |
| 391 | elif len(muls) == 2: |
| 392 | # In the case both inputs are Muls, find the one with the same input as the Max |
| 393 | mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0] |
| 394 | else: |
| 395 | # No Mul inputs |
| 396 | return op |
| 397 | |
| 398 | # make sure the Mul doesn't have any other consumers |
| 399 | if len(mul.outputs[0].consumers()) != 1: |
| 400 | return op |
| 401 | # make sure the Mul doesn't have a faf |
| 402 | if mul.attrs["fused_activation_function"]: |
| 403 | return op |
| 404 | |
| 405 | # finds the branched input that goes to both the Max and the Mul |
| 406 | shared = set(op.inputs) & set(mul.inputs) |
| 407 | if len(shared) == 1: |
| 408 | shared_in = shared.pop() |
| 409 | # find the constant scalar input to the Mul |
| 410 | const_tens = (set(mul.inputs) - {shared_in}).pop() |
| 411 | # check that it is a scalar |
| 412 | if const_tens.shape != []: |
| 413 | return op |
| 414 | const = const_tens.ops[0] |
| 415 | # check that it is a constant |
| 416 | if const.type != "Const": |
| 417 | return op |
| 418 | else: |
| 419 | return op |
| 420 | |
| 421 | val = const.outputs[0].values |
| 422 | if val >= 0: |
| 423 | new_op = "LeakyRelu" |
| 424 | op.attrs["alpha"] = val |
| 425 | elif val == -1: |
| 426 | new_op = "Abs" |
| 427 | else: |
| 428 | return op |
| 429 | |
| 430 | op.type = op.type.replace("Maximum", new_op) |
| 431 | op.name = op.name.replace("Maximum", new_op) |
| 432 | op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op) |
| 433 | op.inputs = [shared_in] |
| 434 | return op |
| 435 | |
| 436 | |
| 437 | def supported_operator_check(op, arch): |
| 438 | op.run_on_npu = arch.supported_operators.is_operator_supported(op) |
| 439 | return op |
| 440 | |
| 441 | |
| 442 | def optimise_graph_a(nng, arch, verbose_graph=False): |
| 443 | if verbose_graph: |
| 444 | nng.print_graph() |
| 445 | |
| 446 | op_rewrite_list = [ |
| 447 | # mark block type and check if the operations are supported |
| 448 | mark_npu_block_type, |
| 449 | supported_operator_check, |
| 450 | # then do any rewrites of supported operators |
| 451 | convert_depthwise_to_conv, |
| 452 | fixup_fully_connected_input, |
| 453 | fixup_pack_input, |
| 454 | fixup_conv2d_backprop, |
| 455 | fixup_act_reorder, |
| 456 | add_padding_fields, |
| 457 | mark_npu_block_type, |
| 458 | # convert_mul_max_to_abs_or_lrelu # TODO: enable optimisation once quantisation issues are resolved |
| 459 | ] |
| 460 | |
| 461 | for idx, sg in enumerate(nng.subgraphs): |
| 462 | # rewrite graph pass |
| 463 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 464 | sg, arch, [fixup_unpack_output,], op_rewrite_list, rewrite_unsupported=False |
| 465 | ) |
| 466 | |
| 467 | for idx, sg in enumerate(nng.subgraphs): |
| 468 | # remove passthrough tensors |
| 469 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [remove_passthrough_tensor,], []) |
| 470 | |
| 471 | if verbose_graph: |
| 472 | nng.print_graph() |
| 473 | return nng |
| 474 | |
| 475 | def optimise_graph_b(nng, arch, verbose_graph=False): |
| 476 | if verbose_graph: |
| 477 | nng.print_graph() |
| 478 | |
| 479 | for idx, sg in enumerate(nng.subgraphs): |
| 480 | # combined rewrite graph pass |
| 481 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(sg, arch, [rewrite_concat, rewrite_split,], []) |
| 482 | |
| 483 | if verbose_graph: |
| 484 | nng.print_graph() |
| 485 | return nng |