Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame^] | 1 | # Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved. |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 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 |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 20 | import uuid |
Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame^] | 21 | from typing import Tuple |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 22 | |
| 23 | import numpy as np |
| 24 | |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 25 | from . import fp_math |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 26 | from . import lut |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 27 | from . import rewrite_graph |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 28 | from . import scaling |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 29 | from .data_type import DataType |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 30 | from .debug_database import DebugDatabase |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 31 | from .errors import UnsupportedFeatureError |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 32 | from .errors import VelaError |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 33 | from .ethos_u55_regs.ethos_u55_regs import resampling_mode |
Louis Verhaard | 8912c53 | 2020-09-30 12:11:49 +0200 | [diff] [blame] | 34 | from .numeric_util import clamp_sigmoid |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 35 | from .numeric_util import full_shape |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 36 | from .numeric_util import round_away_zero |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 37 | from .operation import create_activation_function |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 38 | from .operation import NpuBlockType |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 39 | from .operation import Op |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 40 | from .operation import Operation |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 41 | from .operation import Padding |
Fredrik Svedberg | d9c2c42 | 2020-12-01 16:33:45 +0100 | [diff] [blame] | 42 | from .operation_util import create_avgpool_nop |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 43 | from .shape4d import Shape4D |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 44 | from .softmax import SoftMax |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 45 | from .tensor import check_quantized_tens_scaling_equal |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 46 | from .tensor import create_const_tensor |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 47 | from .tensor import QuantizationParameters |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 48 | from .tensor import Tensor |
Michael McGeagh | 7a6f843 | 2020-12-02 15:29:22 +0000 | [diff] [blame] | 49 | from .tflite_mapping import optype_to_builtintype |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 50 | |
Michael McGeagh | f3e3ad7 | 2020-12-02 12:39:03 +0000 | [diff] [blame] | 51 | passthrough_nodes = (Op.Identity,) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 52 | |
Michael McGeagh | f3e3ad7 | 2020-12-02 12:39:03 +0000 | [diff] [blame] | 53 | memory_only_ops = (Op.Reshape,) |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 54 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 55 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 56 | def remove_passthrough_tensor(tens, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 57 | if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes: |
| 58 | assert len(tens.ops[0].inputs) == 1 |
| 59 | tens = tens.ops[0].inputs[0] |
| 60 | return tens |
| 61 | |
| 62 | |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 63 | def rewrite_concat_ops(op, arch): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 64 | if not op.run_on_npu or not op.type.is_concat_op(): |
| 65 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 66 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 67 | axis_4D = 0 |
| 68 | ofm = op.ofm |
| 69 | ofm.ops = [] |
| 70 | offset = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 71 | |
Patrik Gustavsson | 7bada40 | 2021-01-28 15:46:21 +0100 | [diff] [blame] | 72 | unfuse_activation_function(op) |
| 73 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 74 | if op.type == Op.Pack: |
| 75 | # Pack is also referred to as Stack |
| 76 | axis = int(op.attrs["axis"]) |
| 77 | desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 78 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 79 | if axis >= 0: |
| 80 | axis_4D = axis + (4 - len(desired_shape)) |
| 81 | else: |
| 82 | axis_4D = axis |
| 83 | |
| 84 | for idx, inp in enumerate(op.inputs): |
| 85 | op.ifm_shapes[idx] = Shape4D(desired_shape) |
| 86 | if Shape4D(inp.shape) != op.ifm_shapes[idx]: |
| 87 | inp.avoid_NHCWB16 = True |
| 88 | op.type = Op.PackReshaped |
| 89 | |
| 90 | inputs, axis = op.get_concat_inputs_axis() |
| 91 | |
| 92 | for idx, inp in enumerate(inputs): |
| 93 | if op.type != Op.PackReshaped: |
| 94 | op.ifm_shapes[idx] = Shape4D(inp.shape) |
Patrik Gustavsson | 3d73717 | 2020-12-22 10:40:51 +0100 | [diff] [blame] | 95 | if axis >= 0: |
| 96 | axis_4D = axis + (4 - len(inp.shape)) |
| 97 | else: |
| 98 | axis_4D = axis |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 99 | new_op = Operation(Op.ConcatSliceWrite, op.name + str(idx)) |
| 100 | new_op.inputs = [inp] |
| 101 | new_op.outputs = [ofm] |
| 102 | new_op.attrs["concat_axis"] = axis_4D |
| 103 | new_op.attrs["concat_start"] = offset |
| 104 | offset += op.ifm_shapes[idx].get_dim(axis_4D) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 105 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 106 | new_op.attrs["concat_end"] = offset |
| 107 | new_op.run_on_npu = True |
| 108 | ofm.ops.append(new_op) |
| 109 | DebugDatabase.add_optimised(op, new_op) |
| 110 | new_op.ifm_shapes.append(op.ifm_shapes[idx].clone()) |
| 111 | new_op.ofm_shapes.append(op.ofm_shapes[0].clone()) |
| 112 | assert ofm.shape[axis] == offset |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 113 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 114 | # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a |
| 115 | # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte |
| 116 | # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0 |
| 117 | # and those addresses are always 16 byte aligned due to the NHCWB16 format. |
| 118 | if axis == -1 or axis == (len(ofm.shape) - 1): |
| 119 | for op in ofm.ops: |
| 120 | if op.attrs["concat_start"] % 16 != 0: |
| 121 | ofm.avoid_NHCWB16 = True |
| 122 | break |
| 123 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 124 | |
| 125 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 126 | def rewrite_split_ops(tens, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 127 | |
Patrik Gustavsson | 224e99b | 2021-01-14 10:55:43 +0100 | [diff] [blame] | 128 | if len(tens.ops) == 1 and tens.ops[0].type.is_split_op() and tens.ops[0].type != Op.Unpack: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 129 | split_op = tens.ops[0] |
| 130 | |
| 131 | # Not supported so leave it and run on CPU |
| 132 | if not split_op.run_on_npu: |
| 133 | return tens |
| 134 | |
| 135 | inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis() |
| 136 | |
| 137 | tens.ops = [] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 138 | new_op = Operation(Op.SplitSliceRead, split_op.name) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 139 | new_op.inputs = [inp] |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 140 | ofm_shape_idx = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 141 | |
| 142 | # For Split the offset cannot be extracted from the tensor so it has to |
| 143 | # be calculated from the index of the output tensor |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 144 | if axis is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 145 | # Get the start and end of the split |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 146 | offset_start = [0] * 4 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 147 | axis_4D_list = split_op.attrs.get("split_axis_4D", None) # Present for UnpackReshaped and some StridedSlice |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 148 | for idx, out in enumerate(outputs): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 149 | if axis_4D_list is not None: |
| 150 | axis_4D = axis_4D_list[idx] |
Patrik Gustavsson | 3d73717 | 2020-12-22 10:40:51 +0100 | [diff] [blame] | 151 | else: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 152 | split_op.ofm_shapes[idx] = Shape4D(out.shape) |
| 153 | if axis >= 0: |
| 154 | axis_4D = axis + (4 - len(out.shape)) |
| 155 | else: |
| 156 | axis_4D = axis |
| 157 | |
| 158 | if out == tens: |
| 159 | ofm_shape_idx = idx |
| 160 | break |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 161 | |
| 162 | offset_start[axis_4D] += split_op.ofm_shapes[idx].get_dim(axis_4D) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 163 | |
Patrik Gustavsson | eebb1c2 | 2020-08-18 15:03:04 +0200 | [diff] [blame] | 164 | # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input |
| 165 | if (offset_start[-1] % 16) != 0: |
| 166 | inp.avoid_NHCWB16 = True |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 167 | else: |
| 168 | offset_start = full_shape(4, offset_start, 0) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 169 | |
| 170 | new_op.attrs["split_start"] = offset_start |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 171 | new_op.run_on_npu = True |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 172 | new_op.set_output_tensor(tens) |
Patrik Gustavsson | 224e99b | 2021-01-14 10:55:43 +0100 | [diff] [blame] | 173 | new_op.ifm_shapes.append(Shape4D(inp.shape)) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 174 | new_op.ofm_shapes.append(split_op.ofm_shapes[ofm_shape_idx].clone()) |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 175 | DebugDatabase.add_optimised(split_op, new_op) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 176 | |
| 177 | return tens |
| 178 | |
| 179 | |
| 180 | def needed_total_padding(input_size, stride, filter_size): |
| 181 | out_size = (input_size + stride - 1) // stride |
| 182 | needed_input = (out_size - 1) * stride + filter_size |
| 183 | total_padding = max(0, needed_input - input_size) |
| 184 | return total_padding |
| 185 | |
| 186 | |
Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame^] | 187 | def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]: |
| 188 | """ |
| 189 | Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding |
| 190 | that provides equivalent results. |
| 191 | """ |
| 192 | total_padding = needed_total_padding(input_size, stride, filter_size) |
| 193 | # The top/left padding can be taken as is from the PAD |
| 194 | output_pad_before = pad_before |
| 195 | # The bottom/right padding might need downward adjustment depending on stride/input size |
| 196 | output_pad_after = pad_after |
| 197 | while output_pad_after > 0 and output_pad_after % stride != (total_padding - pad_before) % stride: |
| 198 | output_pad_after -= 1 |
| 199 | return output_pad_before, output_pad_after |
| 200 | |
| 201 | |
| 202 | def calc_padding_and_skirt(padding_type, kernel, input_shape, explicit_padding): |
| 203 | k_w, k_h = kernel.dilated_wh() |
| 204 | s_x, s_y = kernel.stride |
| 205 | ypad = needed_total_padding(int(input_shape.height), int(s_y), int(k_h)) |
| 206 | xpad = needed_total_padding(int(input_shape.width), int(s_x), int(k_w)) |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 207 | if padding_type == Padding.SAME: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 208 | left_pad = (xpad + 0) // 2 |
| 209 | right_pad = (xpad + 1) // 2 |
| 210 | top_pad = (ypad + 0) // 2 |
| 211 | bottom_pad = (ypad + 1) // 2 |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 212 | elif padding_type == Padding.VALID: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 213 | left_pad = 0 |
| 214 | right_pad = 0 |
| 215 | top_pad = 0 |
| 216 | bottom_pad = 0 |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 217 | elif padding_type == Padding.EXPLICIT: |
| 218 | # Padding is specified in a PAD operator which has been bypassed. |
Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame^] | 219 | top, left, bottom, right = explicit_padding |
| 220 | top_pad, bottom_pad = calc_explicit_padding(int(input_shape.height), int(s_y), int(k_h), int(top), int(bottom)) |
| 221 | left_pad, right_pad = calc_explicit_padding(int(input_shape.width), int(s_x), int(k_w), int(left), int(right)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 222 | else: |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 223 | raise UnsupportedFeatureError(f"Unknown padding") |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 224 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
| 225 | skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad) |
| 226 | return padding, skirt |
| 227 | |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 228 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 229 | def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_shape, upscaling_factor): |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 230 | kernel_height, kernel_width = kernel_size[0], kernel_size[1] |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 231 | if padding_type == Padding.SAME: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 232 | ypad = needed_total_padding(int(input_shape.height) * upscaling_factor, int(stride[1]), int(kernel_height)) |
| 233 | xpad = needed_total_padding(int(input_shape.width) * upscaling_factor, int(stride[2]), int(kernel_width)) |
Jacob Bohlin | d47cc27 | 2020-08-24 11:42:14 +0200 | [diff] [blame] | 234 | right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0) |
| 235 | bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0) |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 236 | left_pad = max(kernel_width - 1 - right_pad, 0) |
| 237 | top_pad = max(kernel_height - 1 - bottom_pad, 0) |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 238 | elif padding_type == Padding.VALID: |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 239 | right_pad = max(kernel_width - 2, 0) |
| 240 | bottom_pad = max(kernel_height - 2, 0) |
| 241 | left_pad = kernel_width - 1 |
| 242 | top_pad = kernel_height - 1 |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 243 | else: |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 244 | raise UnsupportedFeatureError(f"Unknown padding") |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 245 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 246 | skirt = padding |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 247 | return padding, skirt |
| 248 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 249 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 250 | def fixup_conv2d_backprop(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 251 | if op.type == Op.Conv2DBackpropInput: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 252 | # flip the inputs |
| 253 | op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0] |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 254 | op.set_ifm_ofm_shapes() |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 255 | op.type = Op.Conv2DBackpropInputSwitchedBias |
Louis Verhaard | 69b8480 | 2020-12-16 12:02:28 +0100 | [diff] [blame] | 256 | op.ifm.resampling_mode = resampling_mode.TRANSPOSE |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 257 | |
| 258 | # Update strides |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 259 | 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] | 260 | |
| 261 | return op |
| 262 | |
| 263 | |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 264 | # Convert the op to an elementwise add |
| 265 | def convert_resizebilinear_1x1_to_add(op): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 266 | op.type = Op.Add |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 267 | op.name = op.name + "_add" |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 268 | op.attrs["resizebilinear"] = True |
| 269 | # Create an input tensor filled with zeros |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 270 | shape = op.ofm_shapes[0].as_list() |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 271 | tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add") |
| 272 | tens.values = np.zeros(shape) |
| 273 | tens.quant_values = np.zeros(shape, np.uint8) |
| 274 | tens.quantization = QuantizationParameters(0.0, 255.0) |
| 275 | tens.quantization.scale_f32 = 1.0 |
| 276 | tens.quantization.zero_point = 0 |
| 277 | tens.consumer_list = [op] |
| 278 | tens_op = op.inputs[1].ops[0] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 279 | tens_op.set_output_tensor(tens) |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 280 | # Set the add inputs |
| 281 | op.inputs[1] = op.inputs[0] |
| 282 | op.inputs[0] = tens |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 283 | op.set_ifm_ofm_shapes() |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 284 | |
| 285 | return op |
| 286 | |
| 287 | |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 288 | # Convert ResizeBilinear to a number of 2x2 pool ops |
| 289 | def convert_resizebilinear_to_2x2_pool(op): |
| 290 | count = 0 |
| 291 | pre_op = op |
| 292 | outputs = op.outputs |
| 293 | |
| 294 | op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)}) |
| 295 | if op.attrs["align_corners"]: |
| 296 | shape_modifier = 1 |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 297 | op.attrs["padding"] = Padding.VALID |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 298 | else: |
| 299 | shape_modifier = 0 |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 300 | op.attrs["padding"] = Padding.SAME |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 301 | op.inputs[0].resampling_mode = resampling_mode.NEAREST |
| 302 | |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 303 | upscaled_shape = np.array(op.ifm_shapes[0].get_hw_as_list()) |
| 304 | out_shape = np.array(op.ofm_shapes[0].get_hw_as_list()) |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 305 | if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all(): |
| 306 | return op |
| 307 | |
| 308 | while (upscaled_shape < out_shape).all(): |
| 309 | if count == 0: |
| 310 | scaled_op = pre_op |
| 311 | else: |
| 312 | scaled_op = op.clone("_{}".format(count)) |
| 313 | scaled_op.inputs[0] = pre_op.outputs[0] |
| 314 | |
| 315 | upscaled_shape = upscaled_shape * 2 - shape_modifier |
| 316 | |
| 317 | if (upscaled_shape == out_shape).all(): |
| 318 | scaled_op.outputs = outputs |
| 319 | scaled_op.outputs[0].ops = [scaled_op] |
| 320 | else: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 321 | shape = op.ofm_shapes[0].as_list() |
| 322 | shape[1:3] = upscaled_shape |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 323 | out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count)) |
| 324 | out_tens.quantization = op.outputs[0].quantization.clone() |
| 325 | out_tens.quantization.quant_min = np.iinfo(np.int16).min |
| 326 | out_tens.quantization.quant_max = np.iinfo(np.int16).max |
| 327 | scaled_op.set_output_tensor(out_tens) |
| 328 | pre_op = scaled_op |
| 329 | count += 1 |
| 330 | |
| 331 | # Setup the scale value |
| 332 | if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16: |
Fredrik Svedberg | e82be7c | 2021-01-18 15:21:03 +0100 | [diff] [blame] | 333 | scaled_op.rescale = 128 |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 334 | elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8: |
Fredrik Svedberg | e82be7c | 2021-01-18 15:21:03 +0100 | [diff] [blame] | 335 | scaled_op.rescale = 1 / 128 |
| 336 | else: |
| 337 | scaled_op.rescale = None |
Patrik Gustavsson | cc6915c | 2020-12-22 09:16:50 +0100 | [diff] [blame] | 338 | scaled_op.set_ifm_ofm_shapes() |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 339 | |
| 340 | return op |
| 341 | |
| 342 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 343 | def fixup_resizebilinear(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 344 | if op.type == Op.ResizeBilinear and op.run_on_npu: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 345 | if op.ifm_shapes[0] == op.ofm_shapes[0]: |
Charles Xu | 36ffaf3 | 2020-08-05 15:40:44 +0200 | [diff] [blame] | 346 | # Bypass nop resizebilinear |
| 347 | op.inputs = op.inputs[:1] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 348 | op.type = Op.Identity |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 349 | elif op.ifm_shapes[0].height == 1 and op.ifm_shapes[0].width == 1: |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 350 | convert_resizebilinear_1x1_to_add(op) |
| 351 | else: |
| 352 | convert_resizebilinear_to_2x2_pool(op) |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 353 | |
| 354 | return op |
| 355 | |
| 356 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 357 | def convert_nop_split_to_identity(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 358 | if op.type == Op.Split and op.attrs.get("num_splits") == 1: |
Dwight Lidman | c3862c2 | 2020-09-14 15:22:33 +0200 | [diff] [blame] | 359 | # the list comprehension should return a list with a single tensor |
| 360 | # if it shouldn't, remove_passthrough_tensor will fail appropriately |
| 361 | op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 362 | op.type = Op.Identity |
Dwight Lidman | c3862c2 | 2020-09-14 15:22:33 +0200 | [diff] [blame] | 363 | return op |
| 364 | |
| 365 | |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 366 | def rewrite_fully_connected_input(op, arch, nng): |
| 367 | if op.type == Op.FullyConnected: |
| 368 | n_in_elems = op.weights.shape[-2] |
| 369 | elms = op.ifm.elements() |
| 370 | batch_size = elms // n_in_elems |
| 371 | assert batch_size * n_in_elems == elms |
| 372 | |
| 373 | if op.ifm.shape != [batch_size, n_in_elems]: |
| 374 | op.ifm.avoid_NHCWB16 = True |
| 375 | |
| 376 | op.ifm_shapes[0] = Shape4D([batch_size, 1, 1, n_in_elems]) |
| 377 | return op |
| 378 | |
| 379 | |
Diqing Zhong | 94457b1 | 2020-12-09 15:22:40 +0100 | [diff] [blame] | 380 | def convert_batched_fc_shape(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 381 | if op.type == Op.FullyConnected: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 382 | # Check if the first dimension indicates batching |
| 383 | if op.ifm_shapes[0].batch > 1: |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 384 | batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)} |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 385 | n = op.ifm_shapes[0].batch |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 386 | h, w = batching_split.get(n, (1, n)) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 387 | op.ifm_shapes[0] = Shape4D([1, h, w, op.ifm_shapes[0].depth]) |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 388 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 389 | op.ifm.avoid_NHCWB16 = True |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 390 | |
| 391 | # Reshape Weights to be 4D. IO becomes HWIO |
| 392 | weight_tensor = op.inputs[1] |
| 393 | weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0) |
| 394 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
| 395 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 396 | n = op.ofm_shapes[0].batch |
| 397 | h, w = batching_split.get(n, (1, n)) |
| 398 | op.ofm_shapes[0] = Shape4D([1, h, w, op.ofm_shapes[0].depth]) |
| 399 | op.ofm.avoid_NHCWB16 = True |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 400 | return op |
| 401 | |
| 402 | |
Patrik Gustavsson | 7bada40 | 2021-01-28 15:46:21 +0100 | [diff] [blame] | 403 | def unfuse_activation_function(op): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 404 | if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None: |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 405 | act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 406 | op.activation = None |
Fredrik Svedberg | 0f98b36 | 2020-09-29 10:00:39 +0200 | [diff] [blame] | 407 | out_tens = op.outputs[0] |
| 408 | intermediate_tens = out_tens.clone("_act_intermediate") |
| 409 | act_op.set_output_tensor(out_tens) |
| 410 | act_op.add_input_tensor(intermediate_tens) |
| 411 | op.set_output_tensor(intermediate_tens) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 412 | act_op.set_ifm_ofm_shapes() |
Fredrik Svedberg | 0f98b36 | 2020-09-29 10:00:39 +0200 | [diff] [blame] | 413 | |
Louis Verhaard | 8912c53 | 2020-09-30 12:11:49 +0200 | [diff] [blame] | 414 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 415 | def rewrite_stridedslice_output(op, arch, nng): |
| 416 | if not op.run_on_npu or op.type != Op.StridedSlice: |
| 417 | return op |
| 418 | |
| 419 | new_axis_mask = op.attrs["new_axis_mask"] |
| 420 | shrink_axis_mask = op.attrs["shrink_axis_mask"] |
| 421 | |
| 422 | if shrink_axis_mask == 0 and new_axis_mask == 0: |
| 423 | return op |
| 424 | |
| 425 | axis_4D = [0] * len(op.outputs) |
| 426 | for idx, out_tens in enumerate(op.outputs): |
| 427 | output_shape = list(out_tens.shape) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 428 | |
Dwight Lidman | 73320a4 | 2020-11-05 10:34:41 +0100 | [diff] [blame] | 429 | if shrink_axis_mask != 0: |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 430 | n = 0 |
| 431 | axis = 0 |
| 432 | while shrink_axis_mask: |
| 433 | prev_mask = shrink_axis_mask |
| 434 | n += 1 |
| 435 | shrink_axis_mask &= shrink_axis_mask - 1 |
| 436 | axis = int(math.log2(prev_mask - shrink_axis_mask)) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 437 | output_shape = output_shape[:axis] + [1] + output_shape[axis:] |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 438 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 439 | assert len(out_tens.shape) == (len(op.inputs[0].shape) - n) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 440 | op.attrs["shrink_axis_mask"] = 0 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 441 | if axis >= 0: |
| 442 | axis_4D[idx] = axis + (4 - len(output_shape)) |
| 443 | else: |
| 444 | axis_4D[idx] = axis |
| 445 | op.ofm_shapes[idx] = Shape4D(output_shape) |
| 446 | |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 447 | elif new_axis_mask != 0: |
| 448 | n = 0 |
| 449 | axis = 0 |
| 450 | while new_axis_mask: |
| 451 | prev_mask = new_axis_mask |
| 452 | n += 1 |
| 453 | new_axis_mask &= new_axis_mask - 1 |
| 454 | axis = int(math.log2(prev_mask - new_axis_mask)) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 455 | output_shape = output_shape[:axis] + output_shape[(axis + 1) :] |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 456 | new_axis_mask >>= 1 |
| 457 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 458 | assert len(out_tens.shape) == (len(op.inputs[0].shape) + n) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 459 | op.attrs["new_axis_mask"] = 0 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 460 | if axis >= 0: |
| 461 | axis_4D[idx] = axis + (4 - len(output_shape)) |
| 462 | else: |
| 463 | axis_4D[idx] = axis |
| 464 | op.ofm_shapes[idx] = Shape4D(output_shape) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 465 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 466 | if op.ofm_shapes[idx] != Shape4D(out_tens.shape): |
| 467 | out_tens.avoid_NHCWB16 = True |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 468 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 469 | op.attrs["split_axis_4D"] = axis_4D |
| 470 | return op |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 471 | |
| 472 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 473 | def rewrite_unpack_output(op, arch, nng): |
| 474 | tens = op.outputs[0] |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 475 | if op.run_on_npu and op.type == Op.Unpack: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 476 | # Unpack is also referred to as Unstack |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 477 | axis = int(op.attrs["axis"]) |
| 478 | op.type = Op.UnpackReshaped |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 479 | desired_output_shape = tens.shape[:axis] + [1] + tens.shape[axis:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 480 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 481 | if axis >= 0: |
| 482 | axis_4D = axis + (4 - len(desired_output_shape)) |
| 483 | else: |
| 484 | axis_4D = axis |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 485 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 486 | axis_4D_list = [0] * len(op.outputs) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 487 | for idx, out_tens in enumerate(op.outputs): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 488 | op.ofm_shapes[idx] = Shape4D(desired_output_shape) |
| 489 | axis_4D_list[idx] = axis_4D |
| 490 | if op.ofm_shapes[idx] != Shape4D(out_tens.shape): |
| 491 | out_tens.avoid_NHCWB16 = True |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 492 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 493 | op.attrs["split_axis_4D"] = axis_4D_list |
| 494 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 495 | |
| 496 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 497 | def add_padding_fields(op, arch, nng): |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 498 | if op.run_on_npu: |
| 499 | if "padding" in op.attrs: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 500 | input_shape = op.ifm_shapes[0] |
| 501 | output_shape = op.ofm_shapes[0] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 502 | if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op(): |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 503 | kernel_size = op.inputs[1].shape[:2] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 504 | elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum: |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 505 | kernel_size = op.attrs["ksize"][1:3] |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 506 | else: |
Michael McGeagh | 7a6f843 | 2020-12-02 15:29:22 +0000 | [diff] [blame] | 507 | raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}") |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 508 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 509 | if op.type == Op.Conv2DBackpropInputSwitchedBias: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 510 | upscaling_factor = output_shape.height // input_shape.height |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 511 | padding, skirt = calc_upscaled_padding_and_skirt( |
| 512 | op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor |
| 513 | ) |
| 514 | else: |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 515 | padding, skirt = calc_padding_and_skirt( |
Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame^] | 516 | op.attrs["padding"], op.kernel, input_shape, op.attrs.get("explicit_padding"), |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 517 | ) |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 518 | |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 519 | op.attrs["explicit_padding"] = padding |
| 520 | op.attrs["skirt"] = skirt |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 521 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 522 | return op |
| 523 | |
| 524 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 525 | # Check if the op can be reordered |
| 526 | def get_prepend_op(op): |
| 527 | inp = op.inputs[0] |
| 528 | # The op should be reordered between prev_op and prep_op |
| 529 | prev_op = inp.ops[-1] |
| 530 | prep_op = None |
| 531 | while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1: |
| 532 | prep_op = prev_op |
| 533 | inp = prev_op.inputs[0] |
| 534 | prev_op = inp.ops[-1] |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 535 | 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] | 536 | return prep_op |
| 537 | |
| 538 | return None |
| 539 | |
| 540 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 541 | def convert_depthwise_to_conv(op, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 542 | # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and |
| 543 | # the ofm depth equals the depth multipler. |
| 544 | # If those conditions are true, then we can perform a simple |
| 545 | # switch of the operator type (and weight order) |
| 546 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 547 | if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 548 | ifm_shape = op.ifm_shapes[0] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 549 | weight_tensor = op.inputs[1] |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 550 | ofm_shape = op.ofm_shapes[0] |
| 551 | if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 552 | # Change op type to Conv2d |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 553 | op.type = Op.Conv2DBias |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 554 | del op.attrs["channel_multiplier"] |
| 555 | del op.attrs["depth_multiplier"] |
| 556 | |
| 557 | 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] | 558 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 559 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 560 | raise UnsupportedFeatureError( |
Michael McGeagh | 7a6f843 | 2020-12-02 15:29:22 +0000 | [diff] [blame] | 561 | f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},", |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 562 | f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 563 | ) |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 564 | DebugDatabase.add_optimised(op, op) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 565 | return op |
| 566 | |
| 567 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 568 | def reorder_depthwise_weights(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 569 | if op.type.is_depthwise_conv2d_op(): |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 570 | weight_tensor = op.inputs[1] |
| 571 | 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] | 572 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 573 | weight_tensor.weight_transpose_depthwise = True |
| 574 | |
| 575 | return op |
| 576 | |
| 577 | |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 578 | def optimise_strided_conv(op, arch, nng): |
| 579 | stride_x, stride_y = op.get_kernel_stride() |
| 580 | ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm() |
| 581 | |
| 582 | if ( |
| 583 | op.type == Op.Conv2DBias |
| 584 | and op.op_index == 0 |
| 585 | and stride_x == 2 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 586 | and op.ifm_shapes[0].depth <= 4 |
| 587 | and op.ifm_shapes[0].width % 2 == 0 |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 588 | and weight_tensor is not None |
| 589 | and weight_tensor.shape[1] >= 2 |
| 590 | ): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 591 | ifm_shape = op.ifm_shapes[0] |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 592 | # IFM |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 593 | op.ifm_shapes[0] = Shape4D([ifm_shape.batch, ifm_shape.height, ifm_shape.width // 2, ifm_shape.depth * 2]) |
| 594 | op.ifm.avoid_NHCWB16 = True |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 595 | |
| 596 | # Weights |
| 597 | weight_shape = weight_tensor.shape |
| 598 | if weight_shape[1] % 2 != 0: |
| 599 | weight_shape[1] = weight_shape[1] + 1 |
| 600 | padded_array = np.zeros(weight_shape) |
| 601 | for i in range(weight_shape[0]): |
| 602 | padded_array[i] = np.vstack( |
| 603 | [ |
| 604 | weight_tensor.quant_values[i], |
| 605 | np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point), |
| 606 | ] |
| 607 | ) |
| 608 | weight_tensor.quant_values = padded_array |
| 609 | weight_shape[1] //= 2 |
| 610 | weight_shape[2] *= 2 |
| 611 | weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape) |
| 612 | weight_tensor.set_all_shapes(weight_shape) |
| 613 | # If multiple copies of the weights are used, we could avoid |
| 614 | # them having the same address by changing the value_id |
| 615 | weight_tensor.value_id = uuid.uuid4() |
| 616 | |
| 617 | # Strides |
| 618 | stride_x = 1 |
| 619 | op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)}) |
| 620 | |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 621 | return op |
| 622 | |
| 623 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 624 | def convert_conv_to_fc(op, arch, nng): |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 625 | # Conv 1x1 can be equivalent to Fully Connected. |
| 626 | # By representing certain convs as fully connected layers, Vela can better determine wether or not to use |
| 627 | # caching/double buffering for the weights. |
| 628 | # (Weights dont need to be reloaded for convs when IFM H and W are 1) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 629 | if op.type == Op.Conv2DBias: |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 630 | h = op.ifm_shapes[0].height |
| 631 | w = op.ifm_shapes[0].width |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 632 | kh, kw, _, _ = op.inputs[1].shape |
| 633 | if h == 1 and w == 1 and kh == 1 and kw == 1: |
| 634 | # Overwrite this op as a Fully Connected Op |
| 635 | op.name += "_fc" |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 636 | op.type = Op.FullyConnected |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 637 | op.attrs = { |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 638 | "weights_format": 0, |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 639 | } |
| 640 | # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped) |
| 641 | weight_tensor = op.inputs[1] |
| 642 | weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1)) |
| 643 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 644 | |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 645 | DebugDatabase.add_optimised(op, op) |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 646 | return op |
| 647 | |
| 648 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 649 | def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 650 | if op.run_on_npu and op.type.is_relu_op(): |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 651 | ifm = op.inputs[0] |
| 652 | ofm = op.outputs[0] |
| 653 | # Relu with differing IFM and OFM scaling cannot be fused with another primary op |
| 654 | # and requires its own to be inserted |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 655 | if not check_quantized_tens_scaling_equal(ifm, ofm): |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 656 | # Override this op with its own primary op (avgpool) |
| 657 | relu_fused_op = create_avgpool_nop(op.name + "_avgpool") |
| 658 | # And fuse the original activation function to it |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 659 | relu_fused_op.activation = create_activation_function(op.type) |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 660 | # Tidy up and assign the ifm and ofm to the new op |
| 661 | ifm.consumer_list.remove(op) |
Andreas Nevalainen | f3d737e | 2020-09-25 14:12:43 +0200 | [diff] [blame] | 662 | |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 663 | relu_fused_op.add_input_tensor(ifm) |
| 664 | relu_fused_op.set_output_tensor(ofm) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 665 | relu_fused_op.set_ifm_ofm_shapes() |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 666 | op = relu_fused_op |
| 667 | return op |
| 668 | |
| 669 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 670 | # TODO remove if mem only ops can all be removed |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 671 | # Reorder activation op if it's after the memory only operations |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 672 | def fixup_act_reorder(op, arch, nng): |
Michael McGeagh | f3e3ad7 | 2020-12-02 12:39:03 +0000 | [diff] [blame] | 673 | if op.type.is_relu_op() or op.type in (Op.Sigmoid, Op.Tanh): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 674 | prep_op = get_prepend_op(op) |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 675 | if prep_op is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 676 | act_op = op.clone("_reordered") |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 677 | act_op.ifm_shapes = list(op.ifm_shapes) |
| 678 | act_op.ofm_shapes = list(op.ofm_shapes) |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 679 | |
| 680 | # There is only one input tensor, overwrite it |
| 681 | act_op.set_input_tensor(prep_op.inputs[0], 0) |
| 682 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 683 | act_op_out = act_op.inputs[0].clone("_acted") |
| 684 | act_op_out.quantization = op.outputs[0].quantization.clone() |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 685 | act_op.set_output_tensor(act_op_out) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 686 | act_op.ofm_shapes[0] = act_op.ifm_shapes[0].clone() |
| 687 | act_op.ifm_shapes[0] = prep_op.ifm_shapes[0].clone() |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 688 | |
| 689 | # Update the consumer list |
| 690 | act_op_out.consumer_list = op.outputs[0].consumer_list.copy() |
| 691 | act_op_out.consumer_list.append(prep_op) |
| 692 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 693 | prep_op.inputs[0] = act_op_out |
| 694 | prep_op.outputs[0].quantization = act_op_out.quantization.clone() |
| 695 | |
| 696 | # Mark the op so that it will be removed as passthrough later on |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 697 | op.type = Op.Identity |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 698 | |
| 699 | # Record optimisation in debug database |
| 700 | DebugDatabase.add_optimised(op, act_op) |
| 701 | DebugDatabase.add_optimised(op, op) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 702 | return op |
| 703 | |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 704 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 705 | def fixup_elementwise_with_scalars(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 706 | if op.type.is_binary_elementwise_op(): |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 707 | ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm() |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 708 | if ifm2_tensor.shape != [] and ifm_tensor.shape != []: |
| 709 | diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape) |
| 710 | if diff > 0: |
| 711 | ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1) |
| 712 | elif diff < 0: |
| 713 | 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] | 714 | elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None: |
| 715 | # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 716 | ifm_tensor.shape = len(ifm2_tensor.shape) * [1] |
| 717 | ifm_tensor.storage_shape = ifm_tensor.shape |
| 718 | elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None: |
| 719 | # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 720 | ifm2_tensor.shape = len(ifm_tensor.shape) * [1] |
| 721 | ifm2_tensor.storage_shape = ifm2_tensor.shape |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 722 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 723 | |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 724 | |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 725 | # Set input/output tensor equivalence to the same id for memory operations |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 726 | def set_tensor_equivalence(op, arch, nng): |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 727 | if op.type in memory_only_ops: |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 728 | eid = op.outputs[0].equivalence_id |
| 729 | for inp in op.inputs: |
| 730 | inp.equivalence_id = eid |
| 731 | return op |
| 732 | |
| 733 | |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 734 | def set_ifm_ofm_op_shapes(op, arch, nng): |
| 735 | if op.run_on_npu and op.type.needs_shapes(): |
| 736 | if op.ifm_shapes or op.ofm_shapes: |
| 737 | # Shapes already set |
| 738 | return op |
| 739 | op.set_ifm_ofm_shapes() |
| 740 | return op |
| 741 | |
| 742 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 743 | def convert_softmax(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 744 | if op.type == Op.Softmax and op.run_on_npu: |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 745 | softmax = SoftMax(op) |
| 746 | op = softmax.get_graph() |
| 747 | return op |
| 748 | |
| 749 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 750 | def convert_mul_max_to_abs_or_lrelu(op, arch, nng): |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 751 | r"""Whenever there is a subgraph with this topology: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 752 | |
| 753 | Input X For X = -1 or X > 0 |
| 754 | | \ / This subgraph can be replaced with either |
| 755 | | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0) |
| 756 | | / |
| 757 | Max |
| 758 | """ |
| 759 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 760 | if op.type == Op.Maximum: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 761 | # finds the Mul input(s) to the Max |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 762 | muls = [i for i in op.inputs if i.ops[0].type == Op.Mul] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 763 | if len(muls) == 1: |
| 764 | mul = muls[0].ops[0] |
| 765 | elif len(muls) == 2: |
| 766 | # In the case both inputs are Muls, find the one with the same input as the Max |
| 767 | mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0] |
| 768 | else: |
| 769 | # No Mul inputs |
| 770 | return op |
| 771 | |
| 772 | # make sure the Mul doesn't have any other consumers |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 773 | mul_ofm = mul.outputs[0] |
| 774 | if len(mul_ofm.consumers()) != 1: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 775 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 776 | # make sure the Mul doesn't have a fused activation function |
| 777 | if mul.activation: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 778 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 779 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 780 | if ifm is None or ofm is None: |
| 781 | return op |
| 782 | |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 783 | if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype: |
| 784 | return op |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 785 | if not check_quantized_tens_scaling_equal(ifm, ofm) or not check_quantized_tens_scaling_equal(ifm, mul_ofm): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 786 | # rewrite to LeakyRelu currently only makes sense if the quantization is identical |
| 787 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 788 | |
| 789 | # finds the branched input that goes to both the Max and the Mul |
| 790 | shared = set(op.inputs) & set(mul.inputs) |
| 791 | if len(shared) == 1: |
| 792 | shared_in = shared.pop() |
| 793 | # find the constant scalar input to the Mul |
| 794 | const_tens = (set(mul.inputs) - {shared_in}).pop() |
| 795 | # check that it is a scalar |
| 796 | if const_tens.shape != []: |
| 797 | return op |
| 798 | const = const_tens.ops[0] |
| 799 | # check that it is a constant |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 800 | if const.type != Op.Const: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 801 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 802 | # Remove the Mul from the shared input's consumers |
| 803 | shared_in.consumer_list.remove(mul) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 804 | else: |
| 805 | return op |
| 806 | |
| 807 | val = const.outputs[0].values |
| 808 | if val >= 0: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 809 | new_op = Op.LeakyRelu |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 810 | op.attrs["alpha"] = val |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 811 | # to produce bit exact results, the alpha is not enough; |
| 812 | # save additional scaling info in attr "alpha_scale", to be used as input |
| 813 | # to the LUT construction |
| 814 | alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point |
| 815 | mul_ifm_scale = np.double(ifm.quantization.scale_f32) |
| 816 | mul_ifm2_scale = np.double(const_tens.quantization.scale_f32) |
| 817 | mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32) |
| 818 | alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale) |
| 819 | op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 820 | elif val == -1: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 821 | new_op = Op.Abs |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 822 | else: |
| 823 | return op |
| 824 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 825 | op.type = new_op |
| 826 | op.name = op.name.replace("Maximum", new_op.name) |
| 827 | op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 828 | op.inputs = [shared_in] |
Patrik Gustavsson | c509d33 | 2020-12-22 13:53:52 +0100 | [diff] [blame] | 829 | op.set_ifm_ofm_shapes() |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 830 | |
| 831 | # Record optimisation in debug database |
| 832 | DebugDatabase.add_optimised(op, op) |
| 833 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 834 | return op |
| 835 | |
| 836 | |
Diqing Zhong | 189f748 | 2021-01-26 12:12:51 +0100 | [diff] [blame] | 837 | def convert_hardswish_to_lut(op, arch, nng): |
| 838 | if op.type == Op.HardSwish: |
| 839 | ifm, ofm = op.get_ifm_ofm() |
| 840 | # Generate the LUT |
| 841 | ifm_scale = np.double(ifm.quantization.scale_f32) |
| 842 | ofm_scale = np.double(ofm.quantization.scale_f32) |
| 843 | zp_in = ifm.quantization.zero_point |
| 844 | zp_out = ofm.quantization.zero_point |
| 845 | ifm_scale_hires = (1 / 128) * ifm_scale |
| 846 | relu_multiplier = np.double(3 / 32768) |
| 847 | out_scale, out_shift = scaling.quantise_scale(ifm_scale_hires / ofm_scale) |
| 848 | relu_scale, relu_shift = scaling.quantise_scale(ifm_scale_hires / relu_multiplier) |
| 849 | # Use 16bit scale |
| 850 | out_scale_16 = fp_math.downscale_multiplier_int32_to_int16(out_scale) |
| 851 | relu_scale_16 = fp_math.downscale_multiplier_int32_to_int16(relu_scale) |
| 852 | |
| 853 | values = [] |
| 854 | ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128) |
| 855 | quantized_min = min(ix) |
| 856 | quantized_max = max(ix) |
| 857 | for x in ix: |
| 858 | input_value = x - zp_in |
| 859 | input_value_hires = input_value * 128 |
| 860 | # Compute the input value on essentially the output scale, not shifted yet |
| 861 | input_value_preshift = fp_math.saturating_rounding_mul16(input_value_hires, out_scale_16) |
| 862 | # Compute the "relu-ish multiplier". This matches the code in TensorFlow Lite Micro kernel |
| 863 | relu_value = np.int16(input_value_hires) |
| 864 | if relu_shift < 31: |
| 865 | relu_value = fp_math.shift_left16(relu_value, 30 - relu_shift) |
| 866 | |
| 867 | relu_value = fp_math.saturating_rounding_mul16(relu_value, relu_scale_16) |
| 868 | |
| 869 | if relu_shift < 31: |
| 870 | relu_value = fp_math.shift_left16(relu_value, 1) |
| 871 | |
| 872 | if relu_shift > 31: |
| 873 | relu_value = fp_math.rounding_divide_by_pot(relu_value, relu_shift - 31) |
| 874 | |
| 875 | # Rescaled the value into a 16bit fixedpoint relu_value in [-1, 1] |
| 876 | # Now convert that to a 16bit fixedpoint value in [0, 1] |
| 877 | relu_value = (relu_value + (1 << 15)) >> 1 |
| 878 | lut_result = fp_math.saturating_mul16(relu_value, input_value_preshift) |
| 879 | shift = 31 - out_shift |
| 880 | shift = -shift if shift < 0 else 0 |
| 881 | # Finally apply the output shift |
| 882 | lut_result = fp_math.rounding_divide_by_pot(lut_result, shift) + zp_out |
| 883 | lut_result = min(quantized_max, max(quantized_min, lut_result)) |
| 884 | values.append(lut_result) |
| 885 | return convert_to_lut(op, values, "hardswish") |
| 886 | return op |
| 887 | |
| 888 | |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 889 | def convert_lrelu_to_mul_max(op, arch): |
| 890 | # Converts LeakyRelu to Max(alpha * IFM, identity * IFM) |
| 891 | # (the opposite of convert_mul_max_to_abs_or_lrelu) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 892 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 893 | if ifm is None or ofm is None: |
| 894 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 895 | |
| 896 | # Add multiplication with alpha |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 897 | mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha") |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 898 | mul_alpha.add_input_tensor(ifm) |
| 899 | # Create const tensor containing alpha as scalar |
| 900 | alpha = op.attrs["alpha"] |
| 901 | quantization = ifm.quantization.clone() |
| 902 | quantization.min = 0 |
| 903 | quantization.max = alpha * (quantization.quant_max - quantization.quant_min) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 904 | quantization.zero_point = 0 |
Louis Verhaard | ece4e65 | 2021-01-07 13:35:47 +0100 | [diff] [blame] | 905 | if np.isinf(1 / np.float32(alpha)): |
| 906 | # Handling of alpha near zero |
| 907 | quantization.scale_f32 = 1 |
| 908 | scalar = 0 |
| 909 | else: |
| 910 | quantization.scale_f32 = alpha |
| 911 | scalar = 1 |
| 912 | alpha_tens = create_const_tensor( |
| 913 | op.name + "_alpha_scalar", [], ifm.dtype, [scalar], np.int8, quantization=quantization |
| 914 | ) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 915 | mul_alpha.add_input_tensor(alpha_tens) |
| 916 | fm_alpha = ofm.clone(op.name + "_alpha") |
| 917 | mul_alpha.set_output_tensor(fm_alpha) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 918 | mul_alpha.set_ifm_ofm_shapes() |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 919 | DebugDatabase.add_optimised(op, mul_alpha) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 920 | |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 921 | if check_quantized_tens_scaling_equal(ifm, ofm): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 922 | # No identity multiplication is needed |
| 923 | fm_id = ifm |
| 924 | else: |
| 925 | # Add multiplication with identity |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 926 | mul_identity = Operation(Op.Mul, op.name + "_mul_identity") |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 927 | mul_identity.add_input_tensor(ifm) |
| 928 | # Create const tensor containing identity as scalar |
| 929 | quantization = ifm.quantization.clone() |
| 930 | quantization.min = 0 |
| 931 | quantization.max = quantization.quant_max - quantization.quant_min |
| 932 | quantization.scale_f32 = 1 |
| 933 | quantization.zero_point = 0 |
| 934 | identity_tens = create_const_tensor( |
| 935 | op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization |
| 936 | ) |
| 937 | mul_identity.add_input_tensor(identity_tens) |
Louis Verhaard | ece4e65 | 2021-01-07 13:35:47 +0100 | [diff] [blame] | 938 | # Make sure that fm_id is allocated to a different address than fm_alpha |
| 939 | fm_id = ofm.clone(op.name + "_id", set_unique=True) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 940 | mul_identity.set_output_tensor(fm_id) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 941 | mul_identity.set_ifm_ofm_shapes() |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 942 | DebugDatabase.add_optimised(op, mul_identity) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 943 | |
| 944 | # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 945 | op.type = Op.Maximum |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 946 | op.name = op.name.replace("LeakyRelu", "Maximum") |
| 947 | op.inputs = [] |
| 948 | ifm.consumer_list.remove(op) |
| 949 | op.add_input_tensor(fm_alpha) |
| 950 | op.add_input_tensor(fm_id) |
Patrik Gustavsson | c509d33 | 2020-12-22 13:53:52 +0100 | [diff] [blame] | 951 | op.set_ifm_ofm_shapes() |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 952 | |
| 953 | DebugDatabase.add_optimised(op, op) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 954 | return op |
| 955 | |
| 956 | |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 957 | def convert_to_lut(op, lut_values, lut_name): |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 958 | # Rewrite the operation by Add with scalar 0 + LUT activation |
| 959 | ifm = op.inputs[0] |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 960 | if ifm is None: |
| 961 | return op |
Louis Verhaard | 58520b9 | 2020-08-24 16:45:38 +0200 | [diff] [blame] | 962 | assert ifm.dtype.size_in_bytes() == 1 |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 963 | op.type = Op.Add |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 964 | op.name = op.name + "_lut_" + lut_name |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 965 | # Mark as no-op to enable potential fusing optimizations |
| 966 | op.attrs["is_nop"] = True |
| 967 | # Create an input tensor containing scalar zero |
| 968 | quantization = QuantizationParameters(0.0, 255.0) |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 969 | quantization.scale_f32 = ifm.quantization.scale_f32 |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 970 | quantization.zero_point = 0 |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 971 | tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 972 | op.add_input_tensor(tens) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 973 | op.ifm_shapes.append(Shape4D(tens.shape)) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 974 | |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 975 | # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale), |
| 976 | # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions |
| 977 | # should be the same as the IFM |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 978 | op.forced_output_quantization = ifm.quantization |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 979 | lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8) |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 980 | op.set_activation_lut(lut_tensor) |
Patrik Gustavsson | c509d33 | 2020-12-22 13:53:52 +0100 | [diff] [blame] | 981 | op.set_ifm_ofm_shapes() |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 982 | return op |
| 983 | |
| 984 | |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 985 | def convert_to_lut8(op, fn, fn_name): |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 986 | # Converts op to a no-op + int8/uint8 LUT which is generated with the given function. |
| 987 | # fn is a function(real) -> real |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 988 | ifm, ofm = op.get_ifm_ofm() |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 989 | if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype: |
| 990 | return op |
| 991 | # Generate the LUT |
| 992 | ifm_scale = np.double(ifm.quantization.scale_f32) |
| 993 | ofm_scale = np.double(ofm.quantization.scale_f32) |
| 994 | zp_in = ifm.quantization.zero_point |
| 995 | zp_out = ofm.quantization.zero_point |
| 996 | values = [] |
| 997 | ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128) |
| 998 | quantized_min = min(ix) |
| 999 | quantized_max = max(ix) |
| 1000 | for x in ix: |
| 1001 | x_real = ifm_scale * (x - zp_in) |
| 1002 | y_real = fn(x_real) |
| 1003 | lut_result = round_away_zero(zp_out + y_real / ofm_scale) |
| 1004 | lut_result = min(quantized_max, max(quantized_min, lut_result)) |
| 1005 | values.append(lut_result) |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1006 | return convert_to_lut(op, values, fn_name) |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1007 | |
| 1008 | |
| 1009 | def convert_lrelu_to_lut(op, arch): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1010 | ifm, ofm = op.get_ifm_ofm() |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1011 | # Generate the LUT |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1012 | alpha = op.attrs["alpha"] |
| 1013 | ifm_scale = np.double(ifm.quantization.scale_f32) |
| 1014 | ofm_scale = np.double(ofm.quantization.scale_f32) |
| 1015 | zp_in = ifm.quantization.zero_point |
| 1016 | zp_out = ofm.quantization.zero_point |
| 1017 | identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale) |
| 1018 | alpha_scalar = 1 |
| 1019 | alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale) |
| 1020 | if "alpha_scaling" in op.attrs: |
| 1021 | # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu |
| 1022 | alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"] |
| 1023 | values = [] |
Louis Verhaard | 58520b9 | 2020-08-24 16:45:38 +0200 | [diff] [blame] | 1024 | ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128) |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1025 | quantized_min = min(ix) |
| 1026 | quantized_max = max(ix) |
| 1027 | for x in ix: |
| 1028 | if x < zp_in: |
| 1029 | lut_result = zp_out + fp_math.multiply_by_quantized_multiplier( |
| 1030 | alpha_scalar * (x - zp_in), alpha_scale, alpha_shift |
| 1031 | ) |
| 1032 | else: |
| 1033 | lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift) |
| 1034 | lut_result = min(quantized_max, max(quantized_min, lut_result)) |
| 1035 | values.append(lut_result) |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1036 | return convert_to_lut(op, values, "lrelu") |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1037 | |
| 1038 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1039 | def convert_lrelu(op, arch, nng): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1040 | # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1041 | if op.type != Op.LeakyRelu: |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1042 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1043 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 1044 | if ifm is None or ofm is None: |
| 1045 | return op |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1046 | if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype: |
| 1047 | # use LUT for int8/uint8 |
| 1048 | return convert_lrelu_to_lut(op, arch) |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 1049 | if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16: |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1050 | # use LeakyRelu unmodified for int16 with equal input/output scaling |
| 1051 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1052 | return convert_lrelu_to_mul_max(op, arch) |
| 1053 | |
| 1054 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1055 | def convert_tanh_sigmoid_to_lut(op, arch, nng): |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1056 | # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1057 | if op.type == Op.Sigmoid: |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1058 | return convert_to_lut8(op, clamp_sigmoid, "sigmoid") |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1059 | elif op.type == Op.Tanh: |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1060 | return convert_to_lut8(op, math.tanh, "tanh") |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1061 | return op |
| 1062 | |
| 1063 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1064 | def remove_reshapes(op, arch): |
| 1065 | if op.run_on_npu and op.type == Op.Reshape: |
| 1066 | ofm = op.ofm |
| 1067 | ifm = op.ifm |
Patrik Gustavsson | fa4cb29 | 2020-09-10 08:19:36 +0200 | [diff] [blame] | 1068 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1069 | # Check if quantization is the same in the input and output for the reshape ops |
| 1070 | if not check_quantized_tens_scaling_equal(ifm, ofm): |
| 1071 | # TODO Both tensors are needed, since quantisation properties currently are linked to Tensors. |
| 1072 | # In order to remove this reshape either quantization properties need to be moved to Operator, |
| 1073 | # or the reshape need to be replace with a NOP. |
| 1074 | return |
Patrik Gustavsson | fa4cb29 | 2020-09-10 08:19:36 +0200 | [diff] [blame] | 1075 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1076 | # Check if ifm is a sg input |
| 1077 | if ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const): |
| 1078 | # put the reshape on CPU |
| 1079 | op.run_on_npu = False |
| 1080 | return |
| 1081 | |
| 1082 | # Check if Reshape ifm/ofm are network ifm/ofm |
| 1083 | ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list) |
| 1084 | ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list) |
| 1085 | |
| 1086 | if ifm_is_sg_ofm and ofm_is_sg_ofm: |
| 1087 | # Both ifm and ofm are sg outputs,add reshape to the ifm and put it on CPU |
| 1088 | ifm_cons_list_copy = ifm.consumer_list.copy() |
| 1089 | ifm_ops_copy = ifm.ops.copy() |
| 1090 | for ifm_cons in ifm_cons_list_copy: |
| 1091 | if ifm_cons is None: |
| 1092 | # Create a reshape op with ifm as output |
| 1093 | name = ifm.name + "_cpu_reshape" |
| 1094 | reshape_ifm = ifm.clone() |
| 1095 | reshape_op = Operation(Op.Reshape, name) |
| 1096 | reshape_op.attrs["new_shape"] = ifm.shape |
| 1097 | reshape_op.add_input_tensor(reshape_ifm) |
| 1098 | reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, ifm.shape)) |
| 1099 | reshape_op.set_output_tensor(ifm) |
| 1100 | reshape_op.set_ifm_ofm_shapes() |
| 1101 | reshape_op.run_on_npu = False |
| 1102 | reshape_op.ofm.ops = [reshape_op] |
| 1103 | reshape_op.ofm.consumer_list = [None] |
| 1104 | |
| 1105 | # Set reshape_ifm producers |
| 1106 | for prev_op in ifm_ops_copy: |
| 1107 | prev_op.outputs = [reshape_ifm] |
| 1108 | reshape_ifm.ops.append(prev_op) |
| 1109 | |
| 1110 | # Set reshape_ifm consumers |
| 1111 | for ifm_cons in ifm_cons_list_copy: |
| 1112 | if ifm_cons is not None: |
| 1113 | for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs): |
| 1114 | if cons_ifm == ifm: |
| 1115 | ifm_cons.set_input_tensor(reshape_ifm, ifm_idx) |
| 1116 | |
| 1117 | ifm = reshape_ifm |
| 1118 | break |
| 1119 | ifm_is_sg_ofm = False |
| 1120 | |
| 1121 | if ofm_is_sg_ofm: |
| 1122 | # Bypassed by replacing ifm with ofm |
| 1123 | ofm.ops = [] |
| 1124 | for prev_op in ifm.ops: |
| 1125 | prev_op.outputs = [ofm] |
| 1126 | ofm.ops.append(prev_op) |
| 1127 | |
| 1128 | # All ifm consumers need to use ofm as input |
| 1129 | for ifm_cons in ifm.consumer_list: |
| 1130 | for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs): |
| 1131 | if cons_ifm == ifm: |
| 1132 | ifm_cons.set_input_tensor(ofm, ifm_idx) |
| 1133 | if op.ifm_shapes[0] != op.ofm_shapes[0]: |
| 1134 | ofm.avoid_NHCWB16 = True |
| 1135 | else: |
| 1136 | # Bypassed Reshape by replacing ofm with ifm |
| 1137 | for cons in ofm.consumer_list: |
| 1138 | for ifm_idx, cons_ifm in enumerate(cons.inputs): |
| 1139 | if cons_ifm == ofm: |
| 1140 | cons.set_input_tensor(ifm, ifm_idx) |
| 1141 | if op.ifm_shapes[0] != op.ofm_shapes[0]: |
| 1142 | ifm.avoid_NHCWB16 = True |
| 1143 | |
| 1144 | |
| 1145 | def check_reshapes(op, arch): |
| 1146 | if op.run_on_npu and op.type == Op.Reshape: |
| 1147 | ofm = op.ofm |
| 1148 | |
| 1149 | if check_quantized_tens_scaling_equal(op.ifm, ofm): |
| 1150 | # Reshape should have been removed |
| 1151 | raise VelaError(f"Reshape op {op} expected to have been removed, still remains") |
Patrik Gustavsson | fa4cb29 | 2020-09-10 08:19:36 +0200 | [diff] [blame] | 1152 | |
| 1153 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1154 | def fuse_activation_function_with_prev(op, arch, nng): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1155 | # if op is a no-op: attempts to move the activation function to the preceding op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1156 | if not op.attrs.get("is_nop", False) or op.activation is None: |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1157 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1158 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 1159 | if ifm is None or ofm is None: |
| 1160 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1161 | # finds the input(s) to the operation |
| 1162 | prev_op = ifm.ops[0] |
| 1163 | # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed |
| 1164 | fuse = ( |
| 1165 | prev_op.run_on_npu |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1166 | and prev_op.type.npu_block_type != NpuBlockType.Default |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1167 | and len(ifm.ops) == 1 |
| 1168 | and len(prev_op.outputs[0].consumers()) == 1 |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1169 | and prev_op.activation is None |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1170 | ) |
| 1171 | if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0: |
| 1172 | # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC), |
| 1173 | # LUT currently only works correctly for elementwise ops |
| 1174 | fuse = False |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1175 | if not fuse: |
| 1176 | return op |
| 1177 | # Move the fused activation function + corresponding info to prev_op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1178 | prev_op.activation = op.activation |
| 1179 | prev_op.forced_output_quantization = op.forced_output_quantization |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1180 | if op.activation_lut is not None: |
| 1181 | prev_op.set_activation_lut(op.activation_lut) |
| 1182 | # Bypass op |
Louis Verhaard | 98a3499 | 2020-09-01 10:39:04 +0200 | [diff] [blame] | 1183 | prev_op.set_output_tensor(ofm) |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 1184 | DebugDatabase.add_optimised(op, prev_op) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1185 | return op |
| 1186 | |
| 1187 | |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1188 | def optimise_pad(op, arch, nng): |
| 1189 | """ |
| 1190 | Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV |
| 1191 | if both operations can be run on the NPU. |
| 1192 | """ |
| 1193 | if ( |
| 1194 | (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op()) |
| 1195 | and op.run_on_npu |
| 1196 | and op.attrs["padding"] == Padding.VALID |
| 1197 | ): |
| 1198 | pad_op = op.ifm.ops[0] |
| 1199 | if pad_op.type != Op.Pad or not pad_op.run_on_npu: |
| 1200 | return op |
| 1201 | # Bypass the PAD operator |
| 1202 | op.set_input_tensor(pad_op.ifm, 0) |
| 1203 | # Adjust the padding attributes of the convolution operator |
| 1204 | op.attrs["padding"] = Padding.EXPLICIT |
| 1205 | padding = pad_op.inputs[1].values # 4x2 tensor, first dimension is N, H, W, C |
| 1206 | top, left, bottom, right = (padding[1][0], padding[2][0], padding[1][1], padding[2][1]) |
| 1207 | op.attrs["explicit_padding"] = (top, left, bottom, right) |
| 1208 | op.set_ifm_ofm_shapes() |
| 1209 | return op |
| 1210 | |
| 1211 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1212 | def add_attrs_to_resizebilinear(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1213 | if op.type == Op.ResizeBilinear and op.run_on_npu: |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1214 | input_tensor = op.inputs[0] |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1215 | input_shape = op.ifm_shapes[0] |
| 1216 | upscaled_height = input_shape.height * 2 |
| 1217 | upscaled_width = input_shape.width * 2 |
| 1218 | out_shape = op.ofm_shapes[0] |
| 1219 | if not op.attrs["align_corners"] and out_shape.height == upscaled_height and out_shape.width == upscaled_width: |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1220 | # this means the output is supposed to be a x2 upscale, |
| 1221 | # so we need to do SAME padding |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 1222 | op.attrs["padding"] = Padding.SAME |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1223 | elif ( |
| 1224 | op.attrs["align_corners"] |
| 1225 | and out_shape.height == (upscaled_height - 1) |
| 1226 | and out_shape.width == (upscaled_width - 1) |
| 1227 | ): |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1228 | # here we can just run the avg pool without padding and |
| 1229 | # produce a (M * 2 - 1, N * 2 - 1) sized output |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 1230 | op.attrs["padding"] = Padding.VALID |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1231 | else: |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 1232 | return op |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1233 | input_tensor.resampling_mode = resampling_mode.NEAREST |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 1234 | 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] | 1235 | return op |
| 1236 | |
| 1237 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1238 | def fixup_bias_tensors(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1239 | if op.type.needs_bias() and op.bias is None: |
Jacob Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 1240 | # Op has no bias, add bias tensor filled with zeros |
| 1241 | nr_biases = op.inputs[1].shape[-1] |
| 1242 | bias_values = [0] * nr_biases |
| 1243 | bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values) |
| 1244 | bias_tensor.quant_values = bias_tensor.values |
| 1245 | op.set_input_tensor(bias_tensor, -1) |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 1246 | |
| 1247 | return op |
| 1248 | |
| 1249 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1250 | def supported_operator_check(op, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1251 | op.run_on_npu = arch.supported_operators.is_operator_supported(op) |
| 1252 | return op |
| 1253 | |
| 1254 | |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 1255 | def _record_optimised(op, arch): |
| 1256 | if op.type != Op.Const: |
| 1257 | DebugDatabase.add_optimised(op, op) |
| 1258 | |
| 1259 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1260 | def optimise_graph_a(nng, arch, verbose_graph=False): |
| 1261 | if verbose_graph: |
| 1262 | nng.print_graph() |
| 1263 | |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 1264 | pre_process_list = [ |
| 1265 | supported_operator_check, |
| 1266 | set_ifm_ofm_op_shapes, |
| 1267 | # TODO: memory-only Op removal |
| 1268 | ] |
| 1269 | |
| 1270 | for idx, sg in enumerate(nng.subgraphs): |
| 1271 | # rewrite graph pass |
| 1272 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 1273 | nng, sg, arch, [], pre_process_list, rewrite_unsupported=False, |
| 1274 | ) |
| 1275 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1276 | # Handle Concat Ops |
| 1277 | for idx, sg in enumerate(nng.subgraphs): |
| 1278 | # rewrite graph pass |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 1279 | rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [rewrite_concat_ops]) |
| 1280 | sg.refresh_after_modification() |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1281 | |
| 1282 | # Handle Split Ops |
| 1283 | for idx, sg in enumerate(nng.subgraphs): |
| 1284 | # rewrite graph pass |
| 1285 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 1286 | nng, |
| 1287 | sg, |
| 1288 | arch, |
| 1289 | [], |
| 1290 | [rewrite_unpack_output, rewrite_stridedslice_output, convert_nop_split_to_identity], |
| 1291 | rewrite_unsupported=False, |
| 1292 | ) |
| 1293 | |
| 1294 | for idx, sg in enumerate(nng.subgraphs): |
| 1295 | # rewrite graph pass |
| 1296 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 1297 | nng, sg, arch, [rewrite_split_ops], [], rewrite_unsupported=False, |
| 1298 | ) |
| 1299 | |
| 1300 | # Removal of reshapes |
| 1301 | for sg in nng.subgraphs: |
| 1302 | rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_reshapes]) |
| 1303 | sg.refresh_after_modification() |
| 1304 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1305 | op_rewrite_list = [ |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 1306 | set_tensor_equivalence, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1307 | convert_depthwise_to_conv, |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 1308 | convert_conv_to_fc, |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 1309 | convert_softmax, |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 1310 | optimise_strided_conv, |
Diqing Zhong | 189f748 | 2021-01-26 12:12:51 +0100 | [diff] [blame] | 1311 | convert_hardswish_to_lut, |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 1312 | rewrite_fully_connected_input, |
Diqing Zhong | 94457b1 | 2020-12-09 15:22:40 +0100 | [diff] [blame] | 1313 | convert_batched_fc_shape, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1314 | fixup_conv2d_backprop, |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 1315 | fixup_relus_with_differing_ifm_ofm_scaling, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1316 | fixup_act_reorder, |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1317 | fixup_elementwise_with_scalars, # TODO Move to early stage? |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 1318 | reorder_depthwise_weights, |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 1319 | fixup_resizebilinear, |
Jacob Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 1320 | fixup_bias_tensors, |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1321 | convert_mul_max_to_abs_or_lrelu, |
| 1322 | convert_lrelu, |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1323 | convert_tanh_sigmoid_to_lut, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1324 | ] |
| 1325 | |
| 1326 | for idx, sg in enumerate(nng.subgraphs): |
| 1327 | # rewrite graph pass |
| 1328 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
Dwight Lidman | 73320a4 | 2020-11-05 10:34:41 +0100 | [diff] [blame] | 1329 | nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1330 | ) |
| 1331 | |
| 1332 | for idx, sg in enumerate(nng.subgraphs): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1333 | # remove passthrough tensors and attempt further optimizations |
| 1334 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1335 | nng, |
| 1336 | sg, |
| 1337 | arch, |
| 1338 | [remove_passthrough_tensor], |
| 1339 | [fuse_activation_function_with_prev, optimise_pad, add_padding_fields], |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1340 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1341 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1342 | # Post-optimisation operator debug tracing, and checking that no undesired reshapes are left in the graph |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 1343 | for sg in nng.subgraphs: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1344 | rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [check_reshapes, _record_optimised]) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1345 | |
| 1346 | if verbose_graph: |
| 1347 | nng.print_graph() |
| 1348 | return nng |