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