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