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 |
Louis Verhaard | 1a92f78 | 2021-02-09 16:08:26 +0100 | [diff] [blame] | 29 | from .api import NpuRoundingMode |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 30 | from .data_type import DataType |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 31 | from .debug_database import DebugDatabase |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 32 | from .errors import UnsupportedFeatureError |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 33 | from .errors import VelaError |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 34 | from .ethos_u55_regs.ethos_u55_regs import resampling_mode |
Louis Verhaard | 8912c53 | 2020-09-30 12:11:49 +0200 | [diff] [blame] | 35 | from .numeric_util import clamp_sigmoid |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 36 | from .numeric_util import full_shape |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 37 | from .numeric_util import round_away_zero |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 38 | from .operation import create_activation_function |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 39 | from .operation import NpuBlockType |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 40 | from .operation import Op |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 41 | from .operation import Operation |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 42 | from .operation import Padding |
Fredrik Svedberg | d9c2c42 | 2020-12-01 16:33:45 +0100 | [diff] [blame] | 43 | from .operation_util import create_avgpool_nop |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 44 | from .operation_util import get_pad_values_from_input |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 45 | from .shape4d import Shape4D |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 46 | from .softmax import SoftMax |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 47 | from .tensor import check_quantized_tens_scaling_equal |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 48 | from .tensor import create_const_tensor |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 49 | from .tensor import create_equivalence_id |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 50 | from .tensor import QuantizationParameters |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 51 | from .tensor import Tensor |
Louis Verhaard | 1a92f78 | 2021-02-09 16:08:26 +0100 | [diff] [blame] | 52 | from .tensor import TensorPurpose |
Michael McGeagh | 7a6f843 | 2020-12-02 15:29:22 +0000 | [diff] [blame] | 53 | from .tflite_mapping import optype_to_builtintype |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 54 | |
Michael McGeagh | f3e3ad7 | 2020-12-02 12:39:03 +0000 | [diff] [blame] | 55 | passthrough_nodes = (Op.Identity,) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 56 | |
Michael McGeagh | f3e3ad7 | 2020-12-02 12:39:03 +0000 | [diff] [blame] | 57 | memory_only_ops = (Op.Reshape,) |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 58 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 59 | |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 60 | def create_avg_pool_for_concat(concat_op, name, ifm, ifm_shape: Shape4D, write_offset: Shape4D): |
| 61 | """Creates an average pool for the given concat op/input feature map""" |
| 62 | ofm = concat_op.ofm |
| 63 | avgpool_op = create_avgpool_nop(name) |
| 64 | avgpool_op.inputs = [ifm] |
| 65 | avgpool_op.outputs = [ofm] |
| 66 | |
| 67 | avgpool_op.write_offset = write_offset |
| 68 | avgpool_op.write_shape = ifm_shape |
| 69 | ofm.ops.append(avgpool_op) |
| 70 | DebugDatabase.add_optimised(concat_op, avgpool_op) |
| 71 | avgpool_op.ifm_shapes.append(ifm_shape) |
| 72 | avgpool_op.ofm_shapes.append(concat_op.ofm_shapes[0]) |
| 73 | avgpool_op.memory_function = Op.ConcatSliceWrite |
| 74 | return avgpool_op |
| 75 | |
| 76 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 77 | def remove_passthrough_tensor(tens, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 78 | if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes: |
| 79 | assert len(tens.ops[0].inputs) == 1 |
| 80 | tens = tens.ops[0].inputs[0] |
| 81 | return tens |
| 82 | |
| 83 | |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 84 | def rewrite_concat_ops(op, arch): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 85 | if not op.run_on_npu or not op.type.is_concat_op(): |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 86 | return |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 87 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 88 | axis_4D = 0 |
| 89 | ofm = op.ofm |
| 90 | ofm.ops = [] |
| 91 | offset = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 92 | |
Patrik Gustavsson | 7bada40 | 2021-01-28 15:46:21 +0100 | [diff] [blame] | 93 | unfuse_activation_function(op) |
| 94 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 95 | if op.type == Op.Pack: |
| 96 | # Pack is also referred to as Stack |
| 97 | axis = int(op.attrs["axis"]) |
| 98 | 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] | 99 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 100 | if axis >= 0: |
| 101 | axis_4D = axis + (4 - len(desired_shape)) |
| 102 | else: |
| 103 | axis_4D = axis |
| 104 | |
| 105 | for idx, inp in enumerate(op.inputs): |
| 106 | op.ifm_shapes[idx] = Shape4D(desired_shape) |
| 107 | if Shape4D(inp.shape) != op.ifm_shapes[idx]: |
| 108 | inp.avoid_NHCWB16 = True |
| 109 | op.type = Op.PackReshaped |
| 110 | |
| 111 | inputs, axis = op.get_concat_inputs_axis() |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 112 | for idx, inp in enumerate(inputs): |
| 113 | if op.type != Op.PackReshaped: |
| 114 | op.ifm_shapes[idx] = Shape4D(inp.shape) |
Patrik Gustavsson | 3d73717 | 2020-12-22 10:40:51 +0100 | [diff] [blame] | 115 | if axis >= 0: |
| 116 | axis_4D = axis + (4 - len(inp.shape)) |
| 117 | else: |
| 118 | axis_4D = axis |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 119 | write_offset = [0, 0, 0, 0] |
| 120 | write_offset[axis_4D] = offset |
| 121 | concat_end = offset + op.ifm_shapes[idx][axis_4D] |
| 122 | create_avg_pool_for_concat( |
| 123 | op, op.name + str(idx) + "_avgpool", inp, op.ifm_shapes[idx], Shape4D.from_list(write_offset) |
| 124 | ) |
| 125 | offset = concat_end |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 126 | assert ofm.shape[axis] == offset |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 127 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 128 | # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a |
| 129 | # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte |
| 130 | # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0 |
| 131 | # and those addresses are always 16 byte aligned due to the NHCWB16 format. |
| 132 | if axis == -1 or axis == (len(ofm.shape) - 1): |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 133 | ofm.avoid_NHCWB16 = any(op2.write_offset.depth % 16 != 0 for op2 in ofm.ops if op2.write_offset is not None) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 134 | |
| 135 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 136 | def rewrite_split_ops(tens, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 137 | |
Patrik Gustavsson | 224e99b | 2021-01-14 10:55:43 +0100 | [diff] [blame] | 138 | 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] | 139 | split_op = tens.ops[0] |
| 140 | |
| 141 | # Not supported so leave it and run on CPU |
| 142 | if not split_op.run_on_npu: |
| 143 | return tens |
| 144 | |
| 145 | inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis() |
| 146 | |
| 147 | tens.ops = [] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 148 | new_op = Operation(Op.SplitSliceRead, split_op.name) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 149 | new_op.inputs = [inp] |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 150 | ofm_shape_idx = 0 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 151 | |
| 152 | # For Split the offset cannot be extracted from the tensor so it has to |
| 153 | # be calculated from the index of the output tensor |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 154 | if axis is not None: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 155 | # Get the start and end of the split |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 156 | offset_start = [0] * 4 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 157 | 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] | 158 | for idx, out in enumerate(outputs): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 159 | if axis_4D_list is not None: |
| 160 | axis_4D = axis_4D_list[idx] |
Patrik Gustavsson | 3d73717 | 2020-12-22 10:40:51 +0100 | [diff] [blame] | 161 | else: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 162 | split_op.ofm_shapes[idx] = Shape4D(out.shape) |
| 163 | if axis >= 0: |
| 164 | axis_4D = axis + (4 - len(out.shape)) |
| 165 | else: |
| 166 | axis_4D = axis |
| 167 | |
| 168 | if out == tens: |
| 169 | ofm_shape_idx = idx |
| 170 | break |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 171 | |
Tim Hall | 73e843f | 2021-02-04 22:47:46 +0000 | [diff] [blame] | 172 | offset_start[axis_4D] += split_op.ofm_shapes[idx][axis_4D] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 173 | |
Patrik Gustavsson | eebb1c2 | 2020-08-18 15:03:04 +0200 | [diff] [blame] | 174 | # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input |
| 175 | if (offset_start[-1] % 16) != 0: |
| 176 | inp.avoid_NHCWB16 = True |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 177 | |
Patrik Gustavsson | e3b1b91 | 2021-02-09 15:38:46 +0100 | [diff] [blame] | 178 | new_op.read_offsets[0] = Shape4D.from_list(offset_start, 0) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 179 | new_op.run_on_npu = True |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 180 | new_op.set_output_tensor(tens) |
Patrik Gustavsson | 224e99b | 2021-01-14 10:55:43 +0100 | [diff] [blame] | 181 | new_op.ifm_shapes.append(Shape4D(inp.shape)) |
Tim Hall | 73e843f | 2021-02-04 22:47:46 +0000 | [diff] [blame] | 182 | new_op.ofm_shapes.append(split_op.ofm_shapes[ofm_shape_idx]) |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 183 | DebugDatabase.add_optimised(split_op, new_op) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 184 | |
| 185 | return tens |
| 186 | |
| 187 | |
Patrik Gustavsson | e3b1b91 | 2021-02-09 15:38:46 +0100 | [diff] [blame] | 188 | def remove_SplitSliceRead(op, arch): |
| 189 | |
| 190 | if op.type == Op.SplitSliceRead: |
| 191 | # Check if it is possible to put the SplitSliceRead on the tensor consumer, or if an avgpool need to be inserted |
| 192 | if ( |
| 193 | len(op.ofm.consumer_list) == 1 |
| 194 | and op.ofm.consumer_list[0] is not None |
| 195 | and op.ofm.consumer_list[0].run_on_npu |
| 196 | and op.ofm.consumer_list[0].type != Op.Reshape |
| 197 | and op.ofm_shapes[0] == Shape4D.from_list(op.ofm.shape) |
| 198 | ): |
| 199 | # SplitSliceRead can be performed by tensor consumer |
| 200 | cons_op = op.ofm.consumer_list[0] |
| 201 | if cons_op.ifm == op.ofm: |
| 202 | cons_op.read_offsets[0] = op.read_offsets[0] |
| 203 | cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[0]) |
| 204 | cons_op.ifm_shapes[0] = op.ifm_shapes[0] |
| 205 | elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == op.ofm: |
| 206 | cons_op.read_offsets[1] = op.read_offsets[0] |
| 207 | cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[1]) |
| 208 | cons_op.ifm_shapes[1] = op.ifm_shapes[0] |
| 209 | |
| 210 | op.ofm.consumer_list.remove(cons_op) |
| 211 | op.ofm.ops = [] |
| 212 | op.ifm.consumer_list.remove(op) |
| 213 | else: |
| 214 | avgpool_op = create_avgpool_nop(op.name + "_avgpool") |
| 215 | avgpool_op.add_input_tensor(op.ifm) |
| 216 | avgpool_op.outputs = [op.ofm] |
| 217 | op.ofm.ops.remove(op) |
| 218 | op.ofm.ops.append(avgpool_op) |
| 219 | avgpool_op.ifm_shapes.append(op.ifm_shapes[0]) |
| 220 | avgpool_op.ofm_shapes.append(op.ofm_shapes[0]) |
| 221 | avgpool_op.read_offsets[0] = op.read_offsets[0] |
| 222 | |
| 223 | op.ifm.consumer_list.remove(op) |
| 224 | DebugDatabase.add_optimised(op, avgpool_op) |
| 225 | |
| 226 | |
Patrik Gustavsson | 138d47f | 2021-02-08 10:13:48 +0100 | [diff] [blame] | 227 | def insert_copy_op_after_tens(tens): |
| 228 | tens_cons_list_copy = tens.consumer_list.copy() |
| 229 | |
| 230 | # Create a avg_pool nop op with ifm as input |
| 231 | copy_tens = tens.clone() |
| 232 | copy_op = create_avgpool_nop(tens.name + "_avgpool") |
| 233 | copy_op.add_input_tensor(tens) |
| 234 | copy_op.set_output_tensor(copy_tens) |
| 235 | copy_op.set_ifm_ofm_shapes() |
| 236 | copy_op.run_on_npu = True |
| 237 | |
| 238 | # Set copy_ifm consumers |
| 239 | for tens_cons in tens_cons_list_copy: |
| 240 | if tens_cons is not None: |
| 241 | for ifm_idx, cons_inp in enumerate(tens_cons.inputs): |
| 242 | if cons_inp == tens: |
| 243 | tens_cons.set_input_tensor(copy_tens, ifm_idx) |
| 244 | |
| 245 | DebugDatabase.add_optimised(tens.ops[0], copy_op) |
| 246 | |
| 247 | |
| 248 | def fix_sg_input_output(op, arch, nng): |
| 249 | if not op.run_on_npu or op.type != Op.Reshape: |
| 250 | return op |
| 251 | |
Patrik Gustavsson | e3b1b91 | 2021-02-09 15:38:46 +0100 | [diff] [blame] | 252 | # For the Reshape operators we want to remove, tensors are removed. |
Patrik Gustavsson | 138d47f | 2021-02-08 10:13:48 +0100 | [diff] [blame] | 253 | # But in order to to do this, they cannot be outputs of the sg, |
| 254 | # this need to be fixed prior to the removal. |
| 255 | # Solution is to add a avgpool NOP, to maintain the original tensor. |
| 256 | |
| 257 | # Check if operator ifm/ofm are sg ifm/ofm |
| 258 | ifm_is_sg_ifm = op.ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const) |
| 259 | ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in op.ifm.consumer_list) |
| 260 | ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in op.ofm.consumer_list) |
| 261 | |
| 262 | if op.type == Op.Reshape and (ifm_is_sg_ofm or ifm_is_sg_ifm) and ofm_is_sg_ofm: |
| 263 | # Both ifm and ofm are sg outputs, only ifm need a copy, in order to remove the Reshape |
| 264 | insert_copy_op_after_tens(op.ifm) |
| 265 | |
| 266 | return op |
| 267 | |
| 268 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 269 | def needed_total_padding(input_size, stride, filter_size): |
| 270 | out_size = (input_size + stride - 1) // stride |
| 271 | needed_input = (out_size - 1) * stride + filter_size |
| 272 | total_padding = max(0, needed_input - input_size) |
| 273 | return total_padding |
| 274 | |
| 275 | |
Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame] | 276 | def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]: |
| 277 | """ |
| 278 | Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding |
| 279 | that provides equivalent results. |
| 280 | """ |
| 281 | total_padding = needed_total_padding(input_size, stride, filter_size) |
| 282 | # The top/left padding can be taken as is from the PAD |
| 283 | output_pad_before = pad_before |
| 284 | # The bottom/right padding might need downward adjustment depending on stride/input size |
| 285 | output_pad_after = pad_after |
| 286 | while output_pad_after > 0 and output_pad_after % stride != (total_padding - pad_before) % stride: |
| 287 | output_pad_after -= 1 |
| 288 | return output_pad_before, output_pad_after |
| 289 | |
| 290 | |
| 291 | def calc_padding_and_skirt(padding_type, kernel, input_shape, explicit_padding): |
| 292 | k_w, k_h = kernel.dilated_wh() |
| 293 | s_x, s_y = kernel.stride |
| 294 | ypad = needed_total_padding(int(input_shape.height), int(s_y), int(k_h)) |
| 295 | 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] | 296 | if padding_type == Padding.SAME: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 297 | left_pad = (xpad + 0) // 2 |
| 298 | right_pad = (xpad + 1) // 2 |
| 299 | top_pad = (ypad + 0) // 2 |
| 300 | bottom_pad = (ypad + 1) // 2 |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 301 | elif padding_type == Padding.VALID: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 302 | left_pad = 0 |
| 303 | right_pad = 0 |
| 304 | top_pad = 0 |
| 305 | bottom_pad = 0 |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 306 | elif padding_type == Padding.EXPLICIT: |
| 307 | # Padding is specified in a PAD operator which has been bypassed. |
Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame] | 308 | top, left, bottom, right = explicit_padding |
| 309 | top_pad, bottom_pad = calc_explicit_padding(int(input_shape.height), int(s_y), int(k_h), int(top), int(bottom)) |
| 310 | 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] | 311 | else: |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 312 | raise UnsupportedFeatureError(f"Unknown padding") |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 313 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
| 314 | skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad) |
| 315 | return padding, skirt |
| 316 | |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 317 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 318 | 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] | 319 | kernel_height, kernel_width = kernel_size[0], kernel_size[1] |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 320 | if padding_type == Padding.SAME: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 321 | ypad = needed_total_padding(int(input_shape.height) * upscaling_factor, int(stride[1]), int(kernel_height)) |
| 322 | 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] | 323 | right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0) |
| 324 | bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0) |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 325 | left_pad = max(kernel_width - 1 - right_pad, 0) |
| 326 | top_pad = max(kernel_height - 1 - bottom_pad, 0) |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 327 | elif padding_type == Padding.VALID: |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 328 | right_pad = max(kernel_width - 2, 0) |
| 329 | bottom_pad = max(kernel_height - 2, 0) |
| 330 | left_pad = kernel_width - 1 |
| 331 | top_pad = kernel_height - 1 |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 332 | else: |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 333 | raise UnsupportedFeatureError(f"Unknown padding") |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 334 | padding = (top_pad, left_pad, bottom_pad, right_pad) |
Jacob Bohlin | 9b64ba0 | 2020-07-07 17:15:22 +0200 | [diff] [blame] | 335 | skirt = padding |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 336 | return padding, skirt |
| 337 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 338 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 339 | def fixup_conv2d_backprop(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 340 | if op.type == Op.Conv2DBackpropInput: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 341 | # flip the inputs |
| 342 | op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 343 | op.type = Op.Conv2DBackpropInputSwitchedBias |
Louis Verhaard | 69b8480 | 2020-12-16 12:02:28 +0100 | [diff] [blame] | 344 | op.ifm.resampling_mode = resampling_mode.TRANSPOSE |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 345 | |
| 346 | # Update strides |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 347 | 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] | 348 | |
| 349 | return op |
| 350 | |
| 351 | |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 352 | # Convert the op to an elementwise add |
| 353 | def convert_resizebilinear_1x1_to_add(op): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 354 | op.type = Op.Add |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 355 | op.name = op.name + "_add" |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 356 | op.attrs["resizebilinear"] = True |
| 357 | # Create an input tensor filled with zeros |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 358 | shape = op.ofm_shapes[0].as_list() |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 359 | tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add") |
| 360 | tens.values = np.zeros(shape) |
| 361 | tens.quant_values = np.zeros(shape, np.uint8) |
| 362 | tens.quantization = QuantizationParameters(0.0, 255.0) |
| 363 | tens.quantization.scale_f32 = 1.0 |
| 364 | tens.quantization.zero_point = 0 |
| 365 | tens.consumer_list = [op] |
| 366 | tens_op = op.inputs[1].ops[0] |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 367 | tens_op.set_output_tensor(tens) |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 368 | # Set the add inputs |
| 369 | op.inputs[1] = op.inputs[0] |
| 370 | op.inputs[0] = tens |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 371 | op.set_ifm_ofm_shapes() |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 372 | |
| 373 | return op |
| 374 | |
| 375 | |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 376 | # Convert ResizeBilinear to a number of 2x2 pool ops |
| 377 | def convert_resizebilinear_to_2x2_pool(op): |
| 378 | count = 0 |
| 379 | pre_op = op |
| 380 | outputs = op.outputs |
| 381 | |
| 382 | op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)}) |
| 383 | if op.attrs["align_corners"]: |
| 384 | shape_modifier = 1 |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 385 | op.attrs["padding"] = Padding.VALID |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 386 | else: |
| 387 | shape_modifier = 0 |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 388 | op.attrs["padding"] = Padding.SAME |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 389 | op.inputs[0].resampling_mode = resampling_mode.NEAREST |
| 390 | |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 391 | upscaled_shape = np.array(op.ifm_shapes[0].get_hw_as_list()) |
| 392 | out_shape = np.array(op.ofm_shapes[0].get_hw_as_list()) |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 393 | if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all(): |
| 394 | return op |
| 395 | |
| 396 | while (upscaled_shape < out_shape).all(): |
| 397 | if count == 0: |
| 398 | scaled_op = pre_op |
| 399 | else: |
| 400 | scaled_op = op.clone("_{}".format(count)) |
| 401 | scaled_op.inputs[0] = pre_op.outputs[0] |
| 402 | |
| 403 | upscaled_shape = upscaled_shape * 2 - shape_modifier |
| 404 | |
| 405 | if (upscaled_shape == out_shape).all(): |
| 406 | scaled_op.outputs = outputs |
| 407 | scaled_op.outputs[0].ops = [scaled_op] |
| 408 | else: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 409 | shape = op.ofm_shapes[0].as_list() |
| 410 | shape[1:3] = upscaled_shape |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 411 | out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count)) |
| 412 | out_tens.quantization = op.outputs[0].quantization.clone() |
| 413 | out_tens.quantization.quant_min = np.iinfo(np.int16).min |
| 414 | out_tens.quantization.quant_max = np.iinfo(np.int16).max |
| 415 | scaled_op.set_output_tensor(out_tens) |
| 416 | pre_op = scaled_op |
| 417 | count += 1 |
| 418 | |
| 419 | # Setup the scale value |
| 420 | 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] | 421 | scaled_op.rescale = 128 |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 422 | 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] | 423 | scaled_op.rescale = 1 / 128 |
| 424 | else: |
| 425 | scaled_op.rescale = None |
Patrik Gustavsson | cc6915c | 2020-12-22 09:16:50 +0100 | [diff] [blame] | 426 | scaled_op.set_ifm_ofm_shapes() |
Charles Xu | 87c1350 | 2020-08-06 12:17:26 +0200 | [diff] [blame] | 427 | |
| 428 | return op |
| 429 | |
| 430 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 431 | def fixup_resizebilinear(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 432 | if op.type == Op.ResizeBilinear and op.run_on_npu: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 433 | if op.ifm_shapes[0] == op.ofm_shapes[0]: |
Charles Xu | 36ffaf3 | 2020-08-05 15:40:44 +0200 | [diff] [blame] | 434 | # Bypass nop resizebilinear |
| 435 | op.inputs = op.inputs[:1] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 436 | op.type = Op.Identity |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 437 | 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] | 438 | convert_resizebilinear_1x1_to_add(op) |
| 439 | else: |
| 440 | convert_resizebilinear_to_2x2_pool(op) |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 441 | |
| 442 | return op |
| 443 | |
| 444 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 445 | def convert_nop_split_to_identity(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 446 | if op.type == Op.Split and op.attrs.get("num_splits") == 1: |
Dwight Lidman | c3862c2 | 2020-09-14 15:22:33 +0200 | [diff] [blame] | 447 | # the list comprehension should return a list with a single tensor |
| 448 | # if it shouldn't, remove_passthrough_tensor will fail appropriately |
| 449 | 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] | 450 | op.type = Op.Identity |
Dwight Lidman | c3862c2 | 2020-09-14 15:22:33 +0200 | [diff] [blame] | 451 | return op |
| 452 | |
| 453 | |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 454 | def rewrite_fully_connected_input(op, arch, nng): |
| 455 | if op.type == Op.FullyConnected: |
| 456 | n_in_elems = op.weights.shape[-2] |
| 457 | elms = op.ifm.elements() |
| 458 | batch_size = elms // n_in_elems |
| 459 | assert batch_size * n_in_elems == elms |
| 460 | |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 461 | op.ifm_shapes[0] = Shape4D([batch_size, 1, 1, n_in_elems]) |
Patrik Gustavsson | da2b003 | 2021-02-04 16:28:29 +0100 | [diff] [blame] | 462 | if Shape4D(op.ifm.shape) != op.ifm_shapes[0]: |
| 463 | op.ifm.avoid_NHCWB16 = True |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 464 | return op |
| 465 | |
| 466 | |
Diqing Zhong | 94457b1 | 2020-12-09 15:22:40 +0100 | [diff] [blame] | 467 | def convert_batched_fc_shape(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 468 | if op.type == Op.FullyConnected: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 469 | # Check if the first dimension indicates batching |
| 470 | if op.ifm_shapes[0].batch > 1: |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 471 | batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)} |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 472 | n = op.ifm_shapes[0].batch |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 473 | h, w = batching_split.get(n, (1, n)) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 474 | 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] | 475 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 476 | op.ifm.avoid_NHCWB16 = True |
Patrik Gustavsson | cb33704 | 2020-09-16 14:55:40 +0200 | [diff] [blame] | 477 | |
| 478 | # Reshape Weights to be 4D. IO becomes HWIO |
| 479 | weight_tensor = op.inputs[1] |
| 480 | weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0) |
| 481 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
| 482 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 483 | n = op.ofm_shapes[0].batch |
| 484 | h, w = batching_split.get(n, (1, n)) |
| 485 | op.ofm_shapes[0] = Shape4D([1, h, w, op.ofm_shapes[0].depth]) |
| 486 | op.ofm.avoid_NHCWB16 = True |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 487 | return op |
| 488 | |
| 489 | |
Patrik Gustavsson | 7bada40 | 2021-01-28 15:46:21 +0100 | [diff] [blame] | 490 | def unfuse_activation_function(op): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 491 | 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] | 492 | 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] | 493 | op.activation = None |
Fredrik Svedberg | 0f98b36 | 2020-09-29 10:00:39 +0200 | [diff] [blame] | 494 | out_tens = op.outputs[0] |
| 495 | intermediate_tens = out_tens.clone("_act_intermediate") |
| 496 | act_op.set_output_tensor(out_tens) |
| 497 | act_op.add_input_tensor(intermediate_tens) |
| 498 | op.set_output_tensor(intermediate_tens) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 499 | act_op.set_ifm_ofm_shapes() |
Fredrik Svedberg | 0f98b36 | 2020-09-29 10:00:39 +0200 | [diff] [blame] | 500 | |
Louis Verhaard | 8912c53 | 2020-09-30 12:11:49 +0200 | [diff] [blame] | 501 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 502 | def rewrite_stridedslice_output(op, arch, nng): |
| 503 | if not op.run_on_npu or op.type != Op.StridedSlice: |
| 504 | return op |
| 505 | |
| 506 | new_axis_mask = op.attrs["new_axis_mask"] |
| 507 | shrink_axis_mask = op.attrs["shrink_axis_mask"] |
| 508 | |
| 509 | if shrink_axis_mask == 0 and new_axis_mask == 0: |
| 510 | return op |
| 511 | |
| 512 | axis_4D = [0] * len(op.outputs) |
| 513 | for idx, out_tens in enumerate(op.outputs): |
| 514 | output_shape = list(out_tens.shape) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 515 | |
Dwight Lidman | 73320a4 | 2020-11-05 10:34:41 +0100 | [diff] [blame] | 516 | if shrink_axis_mask != 0: |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 517 | n = 0 |
| 518 | axis = 0 |
| 519 | while shrink_axis_mask: |
| 520 | prev_mask = shrink_axis_mask |
| 521 | n += 1 |
| 522 | shrink_axis_mask &= shrink_axis_mask - 1 |
| 523 | axis = int(math.log2(prev_mask - shrink_axis_mask)) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 524 | output_shape = output_shape[:axis] + [1] + output_shape[axis:] |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 525 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 526 | assert len(out_tens.shape) == (len(op.inputs[0].shape) - n) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 527 | op.attrs["shrink_axis_mask"] = 0 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 528 | if axis >= 0: |
| 529 | axis_4D[idx] = axis + (4 - len(output_shape)) |
| 530 | else: |
| 531 | axis_4D[idx] = axis |
| 532 | op.ofm_shapes[idx] = Shape4D(output_shape) |
| 533 | |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 534 | elif new_axis_mask != 0: |
| 535 | n = 0 |
| 536 | axis = 0 |
| 537 | while new_axis_mask: |
| 538 | prev_mask = new_axis_mask |
| 539 | n += 1 |
| 540 | new_axis_mask &= new_axis_mask - 1 |
| 541 | axis = int(math.log2(prev_mask - new_axis_mask)) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 542 | output_shape = output_shape[:axis] + output_shape[(axis + 1) :] |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 543 | new_axis_mask >>= 1 |
| 544 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 545 | assert len(out_tens.shape) == (len(op.inputs[0].shape) + n) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 546 | op.attrs["new_axis_mask"] = 0 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 547 | if axis >= 0: |
| 548 | axis_4D[idx] = axis + (4 - len(output_shape)) |
| 549 | else: |
| 550 | axis_4D[idx] = axis |
| 551 | op.ofm_shapes[idx] = Shape4D(output_shape) |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 552 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 553 | if op.ofm_shapes[idx] != Shape4D(out_tens.shape): |
| 554 | out_tens.avoid_NHCWB16 = True |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 555 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 556 | op.attrs["split_axis_4D"] = axis_4D |
| 557 | return op |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 558 | |
| 559 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 560 | def rewrite_unpack_output(op, arch, nng): |
| 561 | tens = op.outputs[0] |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 562 | if op.run_on_npu and op.type == Op.Unpack: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 563 | # Unpack is also referred to as Unstack |
Diqing Zhong | c7c0b1b | 2020-10-26 11:45:25 +0100 | [diff] [blame] | 564 | axis = int(op.attrs["axis"]) |
| 565 | op.type = Op.UnpackReshaped |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 566 | desired_output_shape = tens.shape[:axis] + [1] + tens.shape[axis:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 567 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 568 | if axis >= 0: |
| 569 | axis_4D = axis + (4 - len(desired_output_shape)) |
| 570 | else: |
| 571 | axis_4D = axis |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 572 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 573 | axis_4D_list = [0] * len(op.outputs) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 574 | for idx, out_tens in enumerate(op.outputs): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 575 | op.ofm_shapes[idx] = Shape4D(desired_output_shape) |
| 576 | axis_4D_list[idx] = axis_4D |
| 577 | if op.ofm_shapes[idx] != Shape4D(out_tens.shape): |
| 578 | out_tens.avoid_NHCWB16 = True |
Michael McGeagh | c5b549b | 2020-08-07 11:54:28 +0100 | [diff] [blame] | 579 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 580 | op.attrs["split_axis_4D"] = axis_4D_list |
| 581 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 582 | |
| 583 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 584 | def add_padding_fields(op, arch, nng): |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 585 | if op.run_on_npu: |
| 586 | if "padding" in op.attrs: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 587 | input_shape = op.ifm_shapes[0] |
| 588 | output_shape = op.ofm_shapes[0] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 589 | 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] | 590 | kernel_size = op.inputs[1].shape[:2] |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 591 | 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] | 592 | kernel_size = op.attrs["ksize"][1:3] |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 593 | else: |
Michael McGeagh | 7a6f843 | 2020-12-02 15:29:22 +0000 | [diff] [blame] | 594 | 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] | 595 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 596 | if op.type == Op.Conv2DBackpropInputSwitchedBias: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 597 | upscaling_factor = output_shape.height // input_shape.height |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 598 | padding, skirt = calc_upscaled_padding_and_skirt( |
| 599 | op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor |
| 600 | ) |
| 601 | else: |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 602 | padding, skirt = calc_padding_and_skirt( |
Louis Verhaard | ebf4af6 | 2021-01-27 15:57:57 +0100 | [diff] [blame] | 603 | op.attrs["padding"], op.kernel, input_shape, op.attrs.get("explicit_padding"), |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 604 | ) |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 605 | |
Jacob Bohlin | 90033f3 | 2020-08-28 15:45:44 +0200 | [diff] [blame] | 606 | op.attrs["explicit_padding"] = padding |
| 607 | op.attrs["skirt"] = skirt |
Jacob Bohlin | cf7da10 | 2020-05-20 09:03:40 +0200 | [diff] [blame] | 608 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 609 | return op |
| 610 | |
| 611 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 612 | def convert_depthwise_to_conv(op, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 613 | # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and |
| 614 | # the ofm depth equals the depth multipler. |
| 615 | # If those conditions are true, then we can perform a simple |
| 616 | # switch of the operator type (and weight order) |
| 617 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 618 | if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 619 | ifm_shape = op.ifm_shapes[0] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 620 | weight_tensor = op.inputs[1] |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 621 | ofm_shape = op.ofm_shapes[0] |
| 622 | 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] | 623 | # Change op type to Conv2d |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 624 | op.type = Op.Conv2DBias |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 625 | del op.attrs["channel_multiplier"] |
| 626 | del op.attrs["depth_multiplier"] |
| 627 | |
| 628 | 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] | 629 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 630 | else: |
Louis Verhaard | 7db7896 | 2020-05-25 15:05:26 +0200 | [diff] [blame] | 631 | raise UnsupportedFeatureError( |
Michael McGeagh | 7a6f843 | 2020-12-02 15:29:22 +0000 | [diff] [blame] | 632 | f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},", |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 633 | f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 634 | ) |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 635 | DebugDatabase.add_optimised(op, op) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 636 | return op |
| 637 | |
| 638 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 639 | def reorder_depthwise_weights(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 640 | if op.type.is_depthwise_conv2d_op(): |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 641 | weight_tensor = op.inputs[1] |
| 642 | 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] | 643 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 644 | weight_tensor.weight_transpose_depthwise = True |
| 645 | |
| 646 | return op |
| 647 | |
| 648 | |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 649 | def optimise_strided_conv(op, arch, nng): |
| 650 | stride_x, stride_y = op.get_kernel_stride() |
| 651 | ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm() |
| 652 | |
| 653 | if ( |
| 654 | op.type == Op.Conv2DBias |
| 655 | and op.op_index == 0 |
| 656 | and stride_x == 2 |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 657 | and op.ifm_shapes[0].depth <= 4 |
| 658 | and op.ifm_shapes[0].width % 2 == 0 |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 659 | and weight_tensor is not None |
| 660 | and weight_tensor.shape[1] >= 2 |
| 661 | ): |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 662 | ifm_shape = op.ifm_shapes[0] |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 663 | # IFM |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 664 | op.ifm_shapes[0] = Shape4D([ifm_shape.batch, ifm_shape.height, ifm_shape.width // 2, ifm_shape.depth * 2]) |
| 665 | op.ifm.avoid_NHCWB16 = True |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 666 | |
| 667 | # Weights |
| 668 | weight_shape = weight_tensor.shape |
| 669 | if weight_shape[1] % 2 != 0: |
| 670 | weight_shape[1] = weight_shape[1] + 1 |
| 671 | padded_array = np.zeros(weight_shape) |
| 672 | for i in range(weight_shape[0]): |
| 673 | padded_array[i] = np.vstack( |
| 674 | [ |
| 675 | weight_tensor.quant_values[i], |
| 676 | np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point), |
| 677 | ] |
| 678 | ) |
| 679 | weight_tensor.quant_values = padded_array |
| 680 | weight_shape[1] //= 2 |
| 681 | weight_shape[2] *= 2 |
| 682 | weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape) |
| 683 | weight_tensor.set_all_shapes(weight_shape) |
| 684 | # If multiple copies of the weights are used, we could avoid |
| 685 | # them having the same address by changing the value_id |
| 686 | weight_tensor.value_id = uuid.uuid4() |
| 687 | |
| 688 | # Strides |
| 689 | stride_x = 1 |
| 690 | op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)}) |
| 691 | |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 692 | return op |
| 693 | |
| 694 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 695 | def convert_conv_to_fc(op, arch, nng): |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 696 | # Conv 1x1 can be equivalent to Fully Connected. |
| 697 | # By representing certain convs as fully connected layers, Vela can better determine wether or not to use |
| 698 | # caching/double buffering for the weights. |
| 699 | # (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] | 700 | if op.type == Op.Conv2DBias: |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 701 | h = op.ifm_shapes[0].height |
| 702 | w = op.ifm_shapes[0].width |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 703 | kh, kw, _, _ = op.inputs[1].shape |
| 704 | if h == 1 and w == 1 and kh == 1 and kw == 1: |
| 705 | # Overwrite this op as a Fully Connected Op |
| 706 | op.name += "_fc" |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 707 | op.type = Op.FullyConnected |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 708 | op.attrs = { |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 709 | "weights_format": 0, |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 710 | } |
| 711 | # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped) |
| 712 | weight_tensor = op.inputs[1] |
| 713 | weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1)) |
| 714 | weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape)) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 715 | |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 716 | DebugDatabase.add_optimised(op, op) |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 717 | return op |
| 718 | |
| 719 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 720 | def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 721 | if op.run_on_npu and op.type.is_relu_op(): |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 722 | ifm = op.inputs[0] |
| 723 | ofm = op.outputs[0] |
| 724 | # Relu with differing IFM and OFM scaling cannot be fused with another primary op |
| 725 | # and requires its own to be inserted |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 726 | if not check_quantized_tens_scaling_equal(ifm, ofm): |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 727 | # Override this op with its own primary op (avgpool) |
| 728 | relu_fused_op = create_avgpool_nop(op.name + "_avgpool") |
| 729 | # And fuse the original activation function to it |
Louis Verhaard | e8a5a78 | 2020-11-02 18:04:27 +0100 | [diff] [blame] | 730 | relu_fused_op.activation = create_activation_function(op.type) |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 731 | # Tidy up and assign the ifm and ofm to the new op |
| 732 | ifm.consumer_list.remove(op) |
Andreas Nevalainen | f3d737e | 2020-09-25 14:12:43 +0200 | [diff] [blame] | 733 | |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 734 | relu_fused_op.add_input_tensor(ifm) |
| 735 | relu_fused_op.set_output_tensor(ofm) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 736 | relu_fused_op.set_ifm_ofm_shapes() |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 737 | op = relu_fused_op |
| 738 | return op |
| 739 | |
| 740 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 741 | def fixup_elementwise_with_scalars(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 742 | if op.type.is_binary_elementwise_op(): |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 743 | ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm() |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 744 | if ifm2_tensor.shape != [] and ifm_tensor.shape != []: |
| 745 | diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape) |
| 746 | if diff > 0: |
| 747 | ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1) |
| 748 | elif diff < 0: |
| 749 | 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] | 750 | elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None: |
| 751 | # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 752 | ifm_tensor.shape = len(ifm2_tensor.shape) * [1] |
| 753 | ifm_tensor.storage_shape = ifm_tensor.shape |
| 754 | elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None: |
| 755 | # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1 |
| 756 | ifm2_tensor.shape = len(ifm_tensor.shape) * [1] |
| 757 | ifm2_tensor.storage_shape = ifm2_tensor.shape |
Charles Xu | 7879222 | 2020-05-13 10:15:26 +0200 | [diff] [blame] | 758 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 759 | |
Louis Verhaard | e0ef273 | 2020-06-03 08:56:44 +0200 | [diff] [blame] | 760 | |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 761 | # Set input/output tensor equivalence to the same id for memory operations |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 762 | def set_tensor_equivalence(op, arch, nng): |
Michael McGeagh | 11b0bdb | 2020-09-08 11:07:35 +0100 | [diff] [blame] | 763 | if op.type in memory_only_ops: |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 764 | eid = op.outputs[0].equivalence_id |
| 765 | for inp in op.inputs: |
| 766 | inp.equivalence_id = eid |
| 767 | return op |
| 768 | |
| 769 | |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 770 | def set_ifm_ofm_op_shapes(op, arch, nng): |
| 771 | if op.run_on_npu and op.type.needs_shapes(): |
| 772 | if op.ifm_shapes or op.ofm_shapes: |
| 773 | # Shapes already set |
| 774 | return op |
| 775 | op.set_ifm_ofm_shapes() |
| 776 | return op |
| 777 | |
| 778 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 779 | def convert_softmax(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 780 | if op.type == Op.Softmax and op.run_on_npu: |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 781 | softmax = SoftMax(op) |
| 782 | op = softmax.get_graph() |
| 783 | return op |
| 784 | |
| 785 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 786 | def convert_mul_max_to_abs_or_lrelu(op, arch, nng): |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 787 | r"""Whenever there is a subgraph with this topology: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 788 | |
| 789 | Input X For X = -1 or X > 0 |
| 790 | | \ / This subgraph can be replaced with either |
| 791 | | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0) |
| 792 | | / |
| 793 | Max |
| 794 | """ |
| 795 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 796 | if op.type == Op.Maximum: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 797 | # finds the Mul input(s) to the Max |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 798 | 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] | 799 | if len(muls) == 1: |
| 800 | mul = muls[0].ops[0] |
| 801 | elif len(muls) == 2: |
| 802 | # In the case both inputs are Muls, find the one with the same input as the Max |
| 803 | mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0] |
| 804 | else: |
| 805 | # No Mul inputs |
| 806 | return op |
| 807 | |
| 808 | # make sure the Mul doesn't have any other consumers |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 809 | mul_ofm = mul.outputs[0] |
| 810 | if len(mul_ofm.consumers()) != 1: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 811 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 812 | # make sure the Mul doesn't have a fused activation function |
| 813 | if mul.activation: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 814 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 815 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 816 | if ifm is None or ofm is None: |
| 817 | return op |
| 818 | |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 819 | if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype: |
| 820 | return op |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 821 | 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] | 822 | # rewrite to LeakyRelu currently only makes sense if the quantization is identical |
| 823 | return op |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 824 | |
| 825 | # finds the branched input that goes to both the Max and the Mul |
| 826 | shared = set(op.inputs) & set(mul.inputs) |
| 827 | if len(shared) == 1: |
| 828 | shared_in = shared.pop() |
| 829 | # find the constant scalar input to the Mul |
| 830 | const_tens = (set(mul.inputs) - {shared_in}).pop() |
| 831 | # check that it is a scalar |
| 832 | if const_tens.shape != []: |
| 833 | return op |
| 834 | const = const_tens.ops[0] |
| 835 | # check that it is a constant |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 836 | if const.type != Op.Const: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 837 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 838 | # Remove the Mul from the shared input's consumers |
| 839 | shared_in.consumer_list.remove(mul) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 840 | else: |
| 841 | return op |
| 842 | |
| 843 | val = const.outputs[0].values |
| 844 | if val >= 0: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 845 | new_op = Op.LeakyRelu |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 846 | op.attrs["alpha"] = val |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 847 | # to produce bit exact results, the alpha is not enough; |
| 848 | # save additional scaling info in attr "alpha_scale", to be used as input |
| 849 | # to the LUT construction |
| 850 | alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point |
| 851 | mul_ifm_scale = np.double(ifm.quantization.scale_f32) |
| 852 | mul_ifm2_scale = np.double(const_tens.quantization.scale_f32) |
| 853 | mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32) |
| 854 | alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale) |
| 855 | op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 856 | elif val == -1: |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 857 | new_op = Op.Abs |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 858 | else: |
| 859 | return op |
| 860 | |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 861 | op.type = new_op |
| 862 | op.name = op.name.replace("Maximum", new_op.name) |
| 863 | 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] | 864 | op.inputs = [shared_in] |
Patrik Gustavsson | c509d33 | 2020-12-22 13:53:52 +0100 | [diff] [blame] | 865 | op.set_ifm_ofm_shapes() |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 866 | |
| 867 | # Record optimisation in debug database |
| 868 | DebugDatabase.add_optimised(op, op) |
| 869 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 870 | return op |
| 871 | |
| 872 | |
Diqing Zhong | 189f748 | 2021-01-26 12:12:51 +0100 | [diff] [blame] | 873 | def convert_hardswish_to_lut(op, arch, nng): |
| 874 | if op.type == Op.HardSwish: |
| 875 | ifm, ofm = op.get_ifm_ofm() |
| 876 | # Generate the LUT |
| 877 | ifm_scale = np.double(ifm.quantization.scale_f32) |
| 878 | ofm_scale = np.double(ofm.quantization.scale_f32) |
| 879 | zp_in = ifm.quantization.zero_point |
| 880 | zp_out = ofm.quantization.zero_point |
| 881 | ifm_scale_hires = (1 / 128) * ifm_scale |
| 882 | relu_multiplier = np.double(3 / 32768) |
| 883 | out_scale, out_shift = scaling.quantise_scale(ifm_scale_hires / ofm_scale) |
| 884 | relu_scale, relu_shift = scaling.quantise_scale(ifm_scale_hires / relu_multiplier) |
| 885 | # Use 16bit scale |
| 886 | out_scale_16 = fp_math.downscale_multiplier_int32_to_int16(out_scale) |
| 887 | relu_scale_16 = fp_math.downscale_multiplier_int32_to_int16(relu_scale) |
| 888 | |
| 889 | values = [] |
| 890 | ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128) |
| 891 | quantized_min = min(ix) |
| 892 | quantized_max = max(ix) |
| 893 | for x in ix: |
| 894 | input_value = x - zp_in |
| 895 | input_value_hires = input_value * 128 |
| 896 | # Compute the input value on essentially the output scale, not shifted yet |
| 897 | input_value_preshift = fp_math.saturating_rounding_mul16(input_value_hires, out_scale_16) |
| 898 | # Compute the "relu-ish multiplier". This matches the code in TensorFlow Lite Micro kernel |
| 899 | relu_value = np.int16(input_value_hires) |
| 900 | if relu_shift < 31: |
| 901 | relu_value = fp_math.shift_left16(relu_value, 30 - relu_shift) |
| 902 | |
| 903 | relu_value = fp_math.saturating_rounding_mul16(relu_value, relu_scale_16) |
| 904 | |
| 905 | if relu_shift < 31: |
| 906 | relu_value = fp_math.shift_left16(relu_value, 1) |
| 907 | |
| 908 | if relu_shift > 31: |
| 909 | relu_value = fp_math.rounding_divide_by_pot(relu_value, relu_shift - 31) |
| 910 | |
| 911 | # Rescaled the value into a 16bit fixedpoint relu_value in [-1, 1] |
| 912 | # Now convert that to a 16bit fixedpoint value in [0, 1] |
| 913 | relu_value = (relu_value + (1 << 15)) >> 1 |
| 914 | lut_result = fp_math.saturating_mul16(relu_value, input_value_preshift) |
| 915 | shift = 31 - out_shift |
| 916 | shift = -shift if shift < 0 else 0 |
| 917 | # Finally apply the output shift |
| 918 | lut_result = fp_math.rounding_divide_by_pot(lut_result, shift) + zp_out |
| 919 | lut_result = min(quantized_max, max(quantized_min, lut_result)) |
| 920 | values.append(lut_result) |
| 921 | return convert_to_lut(op, values, "hardswish") |
| 922 | return op |
| 923 | |
| 924 | |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 925 | def convert_lrelu_to_mul_max(op, arch): |
| 926 | # Converts LeakyRelu to Max(alpha * IFM, identity * IFM) |
| 927 | # (the opposite of convert_mul_max_to_abs_or_lrelu) |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 928 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 929 | if ifm is None or ofm is None: |
| 930 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 931 | |
| 932 | # Add multiplication with alpha |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 933 | mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha") |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 934 | mul_alpha.add_input_tensor(ifm) |
| 935 | # Create const tensor containing alpha as scalar |
| 936 | alpha = op.attrs["alpha"] |
| 937 | quantization = ifm.quantization.clone() |
| 938 | quantization.min = 0 |
| 939 | quantization.max = alpha * (quantization.quant_max - quantization.quant_min) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 940 | quantization.zero_point = 0 |
Louis Verhaard | ece4e65 | 2021-01-07 13:35:47 +0100 | [diff] [blame] | 941 | if np.isinf(1 / np.float32(alpha)): |
| 942 | # Handling of alpha near zero |
| 943 | quantization.scale_f32 = 1 |
| 944 | scalar = 0 |
| 945 | else: |
| 946 | quantization.scale_f32 = alpha |
erik.andersson@arm.com | 8ba0792 | 2021-03-10 08:39:23 +0100 | [diff] [blame] | 947 | scalar = alpha |
Louis Verhaard | ece4e65 | 2021-01-07 13:35:47 +0100 | [diff] [blame] | 948 | alpha_tens = create_const_tensor( |
erik.andersson@arm.com | 8ba0792 | 2021-03-10 08:39:23 +0100 | [diff] [blame] | 949 | op.name + "_alpha_scalar", [], ifm.dtype, [scalar], np.float32, quantization=quantization |
Louis Verhaard | ece4e65 | 2021-01-07 13:35:47 +0100 | [diff] [blame] | 950 | ) |
erik.andersson@arm.com | 8ba0792 | 2021-03-10 08:39:23 +0100 | [diff] [blame] | 951 | alpha_tens.quant_values = np.array([1]) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 952 | mul_alpha.add_input_tensor(alpha_tens) |
erik.andersson@arm.com | 8ba0792 | 2021-03-10 08:39:23 +0100 | [diff] [blame] | 953 | fm_alpha = ofm.clone(op.name + "_alpha", set_unique=True) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 954 | mul_alpha.set_output_tensor(fm_alpha) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 955 | mul_alpha.set_ifm_ofm_shapes() |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 956 | DebugDatabase.add_optimised(op, mul_alpha) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 957 | |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 958 | if check_quantized_tens_scaling_equal(ifm, ofm): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 959 | # No identity multiplication is needed |
| 960 | fm_id = ifm |
| 961 | else: |
| 962 | # Add multiplication with identity |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 963 | mul_identity = Operation(Op.Mul, op.name + "_mul_identity") |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 964 | mul_identity.add_input_tensor(ifm) |
| 965 | # Create const tensor containing identity as scalar |
| 966 | quantization = ifm.quantization.clone() |
| 967 | quantization.min = 0 |
| 968 | quantization.max = quantization.quant_max - quantization.quant_min |
| 969 | quantization.scale_f32 = 1 |
| 970 | quantization.zero_point = 0 |
| 971 | identity_tens = create_const_tensor( |
| 972 | op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization |
| 973 | ) |
| 974 | mul_identity.add_input_tensor(identity_tens) |
Louis Verhaard | ece4e65 | 2021-01-07 13:35:47 +0100 | [diff] [blame] | 975 | # Make sure that fm_id is allocated to a different address than fm_alpha |
| 976 | fm_id = ofm.clone(op.name + "_id", set_unique=True) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 977 | mul_identity.set_output_tensor(fm_id) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 978 | mul_identity.set_ifm_ofm_shapes() |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 979 | DebugDatabase.add_optimised(op, mul_identity) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 980 | |
| 981 | # 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] | 982 | op.type = Op.Maximum |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 983 | op.name = op.name.replace("LeakyRelu", "Maximum") |
| 984 | op.inputs = [] |
| 985 | ifm.consumer_list.remove(op) |
| 986 | op.add_input_tensor(fm_alpha) |
| 987 | op.add_input_tensor(fm_id) |
Patrik Gustavsson | c509d33 | 2020-12-22 13:53:52 +0100 | [diff] [blame] | 988 | op.set_ifm_ofm_shapes() |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 989 | |
| 990 | DebugDatabase.add_optimised(op, op) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 991 | return op |
| 992 | |
| 993 | |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 994 | def convert_to_lut(op, lut_values, lut_name): |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 995 | # Rewrite the operation by Add with scalar 0 + LUT activation |
| 996 | ifm = op.inputs[0] |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 997 | if ifm is None: |
| 998 | return op |
Louis Verhaard | 58520b9 | 2020-08-24 16:45:38 +0200 | [diff] [blame] | 999 | assert ifm.dtype.size_in_bytes() == 1 |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1000 | op.type = Op.Add |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1001 | op.name = op.name + "_lut_" + lut_name |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1002 | # Mark as no-op to enable potential fusing optimizations |
| 1003 | op.attrs["is_nop"] = True |
| 1004 | # Create an input tensor containing scalar zero |
| 1005 | quantization = QuantizationParameters(0.0, 255.0) |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1006 | quantization.scale_f32 = ifm.quantization.scale_f32 |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1007 | quantization.zero_point = 0 |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1008 | 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] | 1009 | op.add_input_tensor(tens) |
patrik.gustavsson | eeb8515 | 2020-12-21 17:10:40 +0000 | [diff] [blame] | 1010 | op.ifm_shapes.append(Shape4D(tens.shape)) |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 1011 | |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1012 | # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale), |
| 1013 | # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions |
| 1014 | # should be the same as the IFM |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1015 | op.forced_output_quantization = ifm.quantization |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1016 | 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] | 1017 | op.set_activation_lut(lut_tensor) |
Patrik Gustavsson | c509d33 | 2020-12-22 13:53:52 +0100 | [diff] [blame] | 1018 | op.set_ifm_ofm_shapes() |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1019 | return op |
| 1020 | |
| 1021 | |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1022 | def convert_to_lut8(op, fn, fn_name): |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1023 | # Converts op to a no-op + int8/uint8 LUT which is generated with the given function. |
| 1024 | # fn is a function(real) -> real |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1025 | ifm, ofm = op.get_ifm_ofm() |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1026 | if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype: |
| 1027 | return op |
| 1028 | # Generate the LUT |
| 1029 | ifm_scale = np.double(ifm.quantization.scale_f32) |
| 1030 | ofm_scale = np.double(ofm.quantization.scale_f32) |
| 1031 | zp_in = ifm.quantization.zero_point |
| 1032 | zp_out = ofm.quantization.zero_point |
| 1033 | values = [] |
| 1034 | ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128) |
| 1035 | quantized_min = min(ix) |
| 1036 | quantized_max = max(ix) |
| 1037 | for x in ix: |
| 1038 | x_real = ifm_scale * (x - zp_in) |
| 1039 | y_real = fn(x_real) |
| 1040 | lut_result = round_away_zero(zp_out + y_real / ofm_scale) |
| 1041 | lut_result = min(quantized_max, max(quantized_min, lut_result)) |
| 1042 | values.append(lut_result) |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1043 | return convert_to_lut(op, values, fn_name) |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1044 | |
| 1045 | |
| 1046 | def convert_lrelu_to_lut(op, arch): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1047 | ifm, ofm = op.get_ifm_ofm() |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1048 | # Generate the LUT |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1049 | alpha = op.attrs["alpha"] |
| 1050 | ifm_scale = np.double(ifm.quantization.scale_f32) |
| 1051 | ofm_scale = np.double(ofm.quantization.scale_f32) |
| 1052 | zp_in = ifm.quantization.zero_point |
| 1053 | zp_out = ofm.quantization.zero_point |
| 1054 | identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale) |
| 1055 | alpha_scalar = 1 |
| 1056 | alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale) |
| 1057 | if "alpha_scaling" in op.attrs: |
| 1058 | # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu |
| 1059 | alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"] |
| 1060 | values = [] |
Louis Verhaard | 58520b9 | 2020-08-24 16:45:38 +0200 | [diff] [blame] | 1061 | ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128) |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1062 | quantized_min = min(ix) |
| 1063 | quantized_max = max(ix) |
| 1064 | for x in ix: |
| 1065 | if x < zp_in: |
| 1066 | lut_result = zp_out + fp_math.multiply_by_quantized_multiplier( |
| 1067 | alpha_scalar * (x - zp_in), alpha_scale, alpha_shift |
| 1068 | ) |
| 1069 | else: |
| 1070 | lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift) |
| 1071 | lut_result = min(quantized_max, max(quantized_min, lut_result)) |
| 1072 | values.append(lut_result) |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1073 | return convert_to_lut(op, values, "lrelu") |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1074 | |
| 1075 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1076 | def convert_lrelu(op, arch, nng): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1077 | # 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] | 1078 | if op.type != Op.LeakyRelu: |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1079 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1080 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 1081 | if ifm is None or ofm is None: |
| 1082 | return op |
Louis Verhaard | d7911c4 | 2020-08-25 13:36:41 +0200 | [diff] [blame] | 1083 | if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype: |
| 1084 | # use LUT for int8/uint8 |
| 1085 | return convert_lrelu_to_lut(op, arch) |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 1086 | 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] | 1087 | # use LeakyRelu unmodified for int16 with equal input/output scaling |
| 1088 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1089 | return convert_lrelu_to_mul_max(op, arch) |
| 1090 | |
| 1091 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1092 | def convert_tanh_sigmoid_to_lut(op, arch, nng): |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1093 | # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1094 | if op.type == Op.Sigmoid: |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1095 | return convert_to_lut8(op, clamp_sigmoid, "sigmoid") |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1096 | elif op.type == Op.Tanh: |
Louis Verhaard | 2e186c7 | 2020-10-09 10:47:04 +0200 | [diff] [blame] | 1097 | return convert_to_lut8(op, math.tanh, "tanh") |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1098 | return op |
| 1099 | |
| 1100 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1101 | def remove_reshapes(op, arch): |
| 1102 | if op.run_on_npu and op.type == Op.Reshape: |
| 1103 | ofm = op.ofm |
| 1104 | ifm = op.ifm |
Patrik Gustavsson | fa4cb29 | 2020-09-10 08:19:36 +0200 | [diff] [blame] | 1105 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1106 | # Check if quantization is the same in the input and output for the reshape ops |
| 1107 | if not check_quantized_tens_scaling_equal(ifm, ofm): |
| 1108 | # TODO Both tensors are needed, since quantisation properties currently are linked to Tensors. |
| 1109 | # In order to remove this reshape either quantization properties need to be moved to Operator, |
| 1110 | # or the reshape need to be replace with a NOP. |
| 1111 | return |
Patrik Gustavsson | fa4cb29 | 2020-09-10 08:19:36 +0200 | [diff] [blame] | 1112 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1113 | # Check if Reshape ifm/ofm are network ifm/ofm |
Patrik Gustavsson | 138d47f | 2021-02-08 10:13:48 +0100 | [diff] [blame] | 1114 | ifm_is_sg_ifm = ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1115 | ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list) |
| 1116 | ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list) |
Patrik Gustavsson | 138d47f | 2021-02-08 10:13:48 +0100 | [diff] [blame] | 1117 | # This case should be handled prior to this function |
| 1118 | assert not ((ifm_is_sg_ifm or ifm_is_sg_ofm) and ofm_is_sg_ofm) |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1119 | |
| 1120 | if ofm_is_sg_ofm: |
| 1121 | # Bypassed by replacing ifm with ofm |
| 1122 | ofm.ops = [] |
| 1123 | for prev_op in ifm.ops: |
| 1124 | prev_op.outputs = [ofm] |
| 1125 | ofm.ops.append(prev_op) |
| 1126 | |
| 1127 | # All ifm consumers need to use ofm as input |
| 1128 | for ifm_cons in ifm.consumer_list: |
| 1129 | for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs): |
| 1130 | if cons_ifm == ifm: |
| 1131 | ifm_cons.set_input_tensor(ofm, ifm_idx) |
| 1132 | if op.ifm_shapes[0] != op.ofm_shapes[0]: |
| 1133 | ofm.avoid_NHCWB16 = True |
| 1134 | else: |
| 1135 | # Bypassed Reshape by replacing ofm with ifm |
| 1136 | for cons in ofm.consumer_list: |
| 1137 | for ifm_idx, cons_ifm in enumerate(cons.inputs): |
| 1138 | if cons_ifm == ofm: |
| 1139 | cons.set_input_tensor(ifm, ifm_idx) |
| 1140 | if op.ifm_shapes[0] != op.ofm_shapes[0]: |
| 1141 | ifm.avoid_NHCWB16 = True |
| 1142 | |
| 1143 | |
| 1144 | def check_reshapes(op, arch): |
| 1145 | if op.run_on_npu and op.type == Op.Reshape: |
| 1146 | ofm = op.ofm |
| 1147 | |
| 1148 | if check_quantized_tens_scaling_equal(op.ifm, ofm): |
| 1149 | # Reshape should have been removed |
| 1150 | 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] | 1151 | |
| 1152 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1153 | def fuse_activation_function_with_prev(op, arch, nng): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1154 | # 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] | 1155 | 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] | 1156 | return op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1157 | ifm, ofm = op.get_ifm_ofm() |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 1158 | if ifm is None or ofm is None: |
| 1159 | return op |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1160 | # finds the input(s) to the operation |
| 1161 | prev_op = ifm.ops[0] |
| 1162 | # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed |
| 1163 | fuse = ( |
| 1164 | prev_op.run_on_npu |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1165 | and prev_op.type.npu_block_type != NpuBlockType.Default |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1166 | and len(ifm.ops) == 1 |
| 1167 | and len(prev_op.outputs[0].consumers()) == 1 |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1168 | and prev_op.activation is None |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1169 | ) |
| 1170 | if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0: |
| 1171 | # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC), |
| 1172 | # LUT currently only works correctly for elementwise ops |
| 1173 | fuse = False |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1174 | if not fuse: |
| 1175 | return op |
| 1176 | # Move the fused activation function + corresponding info to prev_op |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1177 | prev_op.activation = op.activation |
| 1178 | prev_op.forced_output_quantization = op.forced_output_quantization |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1179 | if op.activation_lut is not None: |
| 1180 | prev_op.set_activation_lut(op.activation_lut) |
| 1181 | # Bypass op |
Louis Verhaard | 98a3499 | 2020-09-01 10:39:04 +0200 | [diff] [blame] | 1182 | prev_op.set_output_tensor(ofm) |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 1183 | DebugDatabase.add_optimised(op, prev_op) |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1184 | return op |
| 1185 | |
| 1186 | |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1187 | def _leading_pad_ok(leading_pad, stride, kernel_size): |
| 1188 | # If kernel size // 2 > stride, then (left, top) padding must be a multiple of stride, |
| 1189 | # otherwise replacing PAD by hardware padding would iterate the wrong IFM rows/columns |
| 1190 | max_size = kernel_size // 2 |
| 1191 | return leading_pad == max_size or max_size <= stride or leading_pad % stride == 0 |
| 1192 | |
| 1193 | |
| 1194 | def replace_pad_by_hw_pad(op: Operation, arch, nng): |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1195 | """ |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1196 | Tries to completely remove a PAD operator by using hardware padding. |
| 1197 | E.g. a PAD operation that pads 1, followed by a CONV with VALID padding and kernel size 3 |
| 1198 | is rewritten such that the PAD is removed, and the CONV uses SAME padding. |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1199 | Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV |
| 1200 | if both operations can be run on the NPU. |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1201 | This is the most efficient way to implement PAD, but cannot be done for all pad sizes. |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1202 | """ |
| 1203 | if ( |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1204 | (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op() or op.type.is_avgpool_op()) |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1205 | and op.run_on_npu |
| 1206 | and op.attrs["padding"] == Padding.VALID |
| 1207 | ): |
| 1208 | pad_op = op.ifm.ops[0] |
| 1209 | if pad_op.type != Op.Pad or not pad_op.run_on_npu: |
| 1210 | return op |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1211 | if pad_op.ifm.dtype != pad_op.ofm.dtype or not check_quantized_tens_scaling_equal(pad_op.ofm, pad_op.ifm): |
| 1212 | return op |
| 1213 | top, left, bottom, right = get_pad_values_from_input(pad_op.inputs[1].values) |
| 1214 | k = op.kernel |
| 1215 | k_w, k_h = k.dilated_wh() |
| 1216 | |
| 1217 | # Check if the PAD operator can be replaced by hardware padding |
| 1218 | if left > k_w // 2 or right > k_w // 2 or top > k_h // 2 or bottom > k_h // 2: |
| 1219 | # Too much padding, it would require hardware padding to actually insert zeros |
| 1220 | return op |
| 1221 | if not _leading_pad_ok(top, k.stride.y, k_h) or not _leading_pad_ok(left, k.stride.x, k_w): |
| 1222 | return op |
| 1223 | |
Louis Verhaard | 1a92f78 | 2021-02-09 16:08:26 +0100 | [diff] [blame] | 1224 | if op.type.is_avgpool_op(): |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1225 | # For average pool, hardware padding can only be used if padding is 0 or kernel size / 2 |
| 1226 | for pad, k_size in ( |
| 1227 | (left, k_w), |
| 1228 | (right, k_w), |
| 1229 | (top, k_h), |
| 1230 | (bottom, k_h), |
| 1231 | ): |
| 1232 | if pad not in (0, k_size // 2): |
| 1233 | return op |
Louis Verhaard | 1a92f78 | 2021-02-09 16:08:26 +0100 | [diff] [blame] | 1234 | # Average pool is converted to depthwise, because NPU average pool + same padding |
| 1235 | # has a special implementation that is different from PAD followed by average pool with |
| 1236 | # valid padding. |
| 1237 | k_w, k_h = op.kernel.width, op.kernel.height |
| 1238 | ifm = op.ifm |
| 1239 | # Remember other inputs |
| 1240 | other_inputs = op.inputs[1:] |
| 1241 | # Create a weight tensor, all weights are set to 1/(kernel width * kernel height) |
| 1242 | quantization = QuantizationParameters(0.0, 255.0) |
| 1243 | quantization.scale_f32 = 1.0 / (k_w * k_h) |
| 1244 | quantization.zero_point = 0 |
| 1245 | shape = [k_h, k_w, 1, op.ofm.shape[-1]] |
| 1246 | weights = np.full(shape, 1) |
| 1247 | |
| 1248 | weight_tens = create_const_tensor( |
| 1249 | op.name + "_weights", |
| 1250 | shape, |
| 1251 | op.ifm.dtype, |
| 1252 | weights, |
| 1253 | np.uint8, |
| 1254 | purpose=TensorPurpose.Weights, |
| 1255 | quantization=quantization, |
| 1256 | ) |
| 1257 | weight_tens.quant_values = weights |
| 1258 | op.type = Op.DepthwiseConv2DBias |
| 1259 | op.inputs = [] |
| 1260 | op.add_input_tensor(ifm) |
| 1261 | op.add_input_tensor(weight_tens) |
| 1262 | # Add bias tensor, all biases set to 0 |
| 1263 | op.inputs.append(None) |
| 1264 | fixup_bias_tensors(op, arch, nng) |
| 1265 | # Add other inputs |
| 1266 | op.inputs.extend(other_inputs) |
| 1267 | op.rounding_mode = NpuRoundingMode.NATURAL |
| 1268 | |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1269 | # Bypass the PAD operator |
| 1270 | op.set_input_tensor(pad_op.ifm, 0) |
| 1271 | # Adjust the padding attributes of the convolution operator |
| 1272 | op.attrs["padding"] = Padding.EXPLICIT |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1273 | op.attrs["explicit_padding"] = (top, left, bottom, right) |
| 1274 | op.set_ifm_ofm_shapes() |
| 1275 | return op |
| 1276 | |
| 1277 | |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1278 | def convert_pad(op: Operation, arch, nng): |
| 1279 | """ |
| 1280 | Rewrites PAD operator to an average pool that copies the IFM to the OFM |
| 1281 | + up to 4 average pool operators that fill the OFM with zeros at the borders. |
| 1282 | This is done as fall-back for the PAD operators that remain after replace_pad_by_hw_pad |
| 1283 | """ |
| 1284 | if op.type != Op.Pad or not op.run_on_npu: |
| 1285 | return op |
| 1286 | top, left, bottom, right = get_pad_values_from_input(op.inputs[1].values) |
| 1287 | |
| 1288 | ifm = op.ifm |
| 1289 | assert ifm is not None |
| 1290 | ifm_shape = Shape4D(ifm.shape) |
| 1291 | ofm = op.ofm |
| 1292 | assert ofm is not None |
| 1293 | ofm.ops = [] |
| 1294 | ofm_shape = op.ofm_shapes[0] |
| 1295 | |
| 1296 | # Average pool op that copies IFM to the right place inside the OFM |
| 1297 | shp0 = Shape4D(0, 0, 0, 0) |
| 1298 | shp_top = shp0.with_height(top) |
| 1299 | avgpool_op = create_avg_pool_for_concat(op, op.name + "_main", ifm, ifm_shape, shp_top.with_width(left)) |
| 1300 | avgpool_op.activation = op.activation |
| 1301 | quant = ofm.quantization |
| 1302 | pad_value = quant.zero_point |
| 1303 | # Add operations that fill the borders of the OFM |
| 1304 | if top > 0: |
| 1305 | shape = Shape4D(1, top, ofm_shape.width, ofm_shape.depth) |
| 1306 | zero_tens = create_const_tensor( |
| 1307 | op.name + "_top", shape.as_list(), ofm.dtype, shape.elements() * [pad_value], np.uint8, quantization=quant |
| 1308 | ) |
| 1309 | # If top/bottom or left/right are equal, the const tensors can be allocated to the same address |
| 1310 | zero_tens.equivalence_id = create_equivalence_id(tuple(zero_tens.values)) |
| 1311 | create_avg_pool_for_concat(op, op.name + "_top", zero_tens, shape, shp0) |
| 1312 | if bottom > 0: |
| 1313 | shape = Shape4D(1, bottom, ofm_shape.width, ofm_shape.depth) |
| 1314 | zero_tens = create_const_tensor( |
| 1315 | op.name + "_bottom", |
| 1316 | shape.as_list(), |
| 1317 | ofm.dtype, |
| 1318 | shape.elements() * [pad_value], |
| 1319 | np.uint8, |
| 1320 | quantization=quant, |
| 1321 | ) |
| 1322 | zero_tens.equivalence_id = create_equivalence_id(tuple(zero_tens.values)) |
| 1323 | create_avg_pool_for_concat( |
| 1324 | op, op.name + "_bottom", zero_tens, shape, shp0.with_height(ofm_shape.height - bottom) |
| 1325 | ) |
| 1326 | if left > 0: |
| 1327 | shape = Shape4D(1, ifm_shape.height, left, ofm_shape.depth) |
| 1328 | zero_tens = create_const_tensor( |
| 1329 | op.name + "_left", shape.as_list(), ofm.dtype, shape.elements() * [pad_value], np.uint8, quantization=quant |
| 1330 | ) |
| 1331 | zero_tens.equivalence_id = create_equivalence_id(tuple(zero_tens.values)) |
| 1332 | create_avg_pool_for_concat(op, op.name + "_left", zero_tens, shape, shp_top) |
| 1333 | if right > 0: |
| 1334 | shape = Shape4D(1, ifm_shape.height, right, ofm_shape.depth) |
| 1335 | zero_tens = create_const_tensor( |
| 1336 | op.name + "_right", shape.as_list(), ofm.dtype, shape.elements() * [pad_value], np.uint8, quantization=quant |
| 1337 | ) |
| 1338 | zero_tens.equivalence_id = create_equivalence_id(tuple(zero_tens.values)) |
| 1339 | create_avg_pool_for_concat( |
| 1340 | op, op.name + "_right", zero_tens, shape, shp_top.with_width(ofm_shape.width - right) |
| 1341 | ) |
| 1342 | ofm.avoid_NHCWB16 = True |
| 1343 | op.type = Op.ConcatTFLite |
| 1344 | return avgpool_op |
| 1345 | |
| 1346 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1347 | def add_attrs_to_resizebilinear(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1348 | if op.type == Op.ResizeBilinear and op.run_on_npu: |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1349 | input_tensor = op.inputs[0] |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1350 | input_shape = op.ifm_shapes[0] |
| 1351 | upscaled_height = input_shape.height * 2 |
| 1352 | upscaled_width = input_shape.width * 2 |
| 1353 | out_shape = op.ofm_shapes[0] |
| 1354 | 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] | 1355 | # this means the output is supposed to be a x2 upscale, |
| 1356 | # so we need to do SAME padding |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 1357 | op.attrs["padding"] = Padding.SAME |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1358 | elif ( |
| 1359 | op.attrs["align_corners"] |
| 1360 | and out_shape.height == (upscaled_height - 1) |
| 1361 | and out_shape.width == (upscaled_width - 1) |
| 1362 | ): |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1363 | # here we can just run the avg pool without padding and |
| 1364 | # produce a (M * 2 - 1, N * 2 - 1) sized output |
Michael McGeagh | 1689548 | 2020-12-14 15:51:20 +0000 | [diff] [blame] | 1365 | op.attrs["padding"] = Padding.VALID |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1366 | else: |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 1367 | return op |
Dwight Lidman | 42fed94 | 2020-05-29 09:37:03 +0200 | [diff] [blame] | 1368 | input_tensor.resampling_mode = resampling_mode.NEAREST |
Tim Hall | c30f495 | 2020-06-15 20:47:35 +0100 | [diff] [blame] | 1369 | 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] | 1370 | return op |
| 1371 | |
| 1372 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1373 | def fixup_bias_tensors(op, arch, nng): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 1374 | if op.type.needs_bias() and op.bias is None: |
Jacob Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 1375 | # Op has no bias, add bias tensor filled with zeros |
| 1376 | nr_biases = op.inputs[1].shape[-1] |
| 1377 | bias_values = [0] * nr_biases |
| 1378 | bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values) |
| 1379 | bias_tensor.quant_values = bias_tensor.values |
Louis Verhaard | 1a92f78 | 2021-02-09 16:08:26 +0100 | [diff] [blame] | 1380 | op.set_input_tensor(bias_tensor, op.type.info.indices.biases[0]) |
Jacob Bohlin | 67e0d8f | 2020-08-20 10:53:02 +0200 | [diff] [blame] | 1381 | |
| 1382 | return op |
| 1383 | |
| 1384 | |
Dwight Lidman | 95b279f | 2021-03-26 10:53:28 +0100 | [diff] [blame^] | 1385 | def convert_mean_to_depthwise_conv_or_avgpool(op, arch, nng): |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1386 | if op.type == Op.Mean and op.run_on_npu: |
| 1387 | keep_dims = op.attrs.get("keep_dims", False) |
| 1388 | inp, axis = op.inputs |
| 1389 | shape = inp.shape |
| 1390 | dims = len(shape) |
| 1391 | |
| 1392 | # Height and width axes have different index depending on dimensions |
| 1393 | if axis.shape == []: # single axis |
| 1394 | axis = int(axis.values) |
| 1395 | if dims in (2, 3): |
| 1396 | if axis == 0: |
| 1397 | h, w = shape[axis], 1 |
| 1398 | else: |
| 1399 | h, w = 1, shape[axis] |
| 1400 | else: |
| 1401 | if axis == 1: |
| 1402 | h, w = shape[axis], 1 |
| 1403 | else: |
| 1404 | h, w = 1, shape[axis] |
| 1405 | else: # multiple axes |
| 1406 | axis = sorted(axis.values) |
| 1407 | h, w = [shape[i] for i in axis] |
| 1408 | |
| 1409 | # Set necessary depthwise attributes |
| 1410 | op.attrs.update( |
| 1411 | { |
| 1412 | "padding": Padding.VALID, |
| 1413 | "stride_h": 1, |
| 1414 | "stride_w": 1, |
| 1415 | "strides": (1, 1, 1, 1), |
| 1416 | "depth_multiplier": 1, |
| 1417 | "channel_multiplier": 1, |
| 1418 | "dilation_h_factor": 1, |
| 1419 | "dilation_w_factor": 1, |
| 1420 | "dilation": (1, 1, 1, 1), |
| 1421 | } |
| 1422 | ) |
| 1423 | # Change op type |
| 1424 | op.type = Op.DepthwiseConv2DBias |
| 1425 | # Set IFM/OFM shapes after changing op type |
| 1426 | op.set_ifm_ofm_shapes() |
| 1427 | |
Dwight Lidman | 9b37918 | 2021-03-15 19:06:10 +0100 | [diff] [blame] | 1428 | weight_scale, bias = 1, None |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1429 | ofmq, ifmq = op.ofm.quantization, inp.quantization |
| 1430 | # Set rounding mode, scaling and zero point based on which reference implementation to match |
| 1431 | if len(shape) == 4 and axis == [1, 2] and keep_dims: |
| 1432 | if inp.dtype == DataType.uint8: |
| 1433 | # This attribute means a different scaling calculation is used in order to match reference |
| 1434 | op.low_precision_scaling = True |
| 1435 | weight_scale = h * w |
Dwight Lidman | 9bb1e2e | 2021-03-18 14:51:42 +0100 | [diff] [blame] | 1436 | # Set zero points to 0 as they will be adjusted for with bias term |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1437 | foq = ofmq.clone() |
Dwight Lidman | 9bb1e2e | 2021-03-18 14:51:42 +0100 | [diff] [blame] | 1438 | foq.zero_point = 0 |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1439 | fiq = ifmq.clone() |
| 1440 | fiq.zero_point = 0 |
| 1441 | op.forced_input_quantization = fiq |
Dwight Lidman | 9bb1e2e | 2021-03-18 14:51:42 +0100 | [diff] [blame] | 1442 | bias_term = ofmq.zero_point - int(ifmq.zero_point * ifmq.scale_f32 / ofmq.scale_f32) |
| 1443 | # If the bias term is outside uint8 range, we need an Add op to apply it. |
| 1444 | if bias_term < 0 or bias_term > 255: |
| 1445 | intermediate = op.ofm.clone(suffix="_intermediate", set_unique=True) |
| 1446 | # Bias term has higher bitness (i32) than input/output (u8). |
| 1447 | # 16 bits is enough since the bias is added/subtracted from a u8 value, |
| 1448 | # the bias can only effectively assume values in the range [-255, 255]. |
| 1449 | intermediate.dtype = DataType.int16 |
| 1450 | intermediate.quantization.zero_point = 0 |
| 1451 | add_op = Operation(Op.Add, op.name + "_bias") |
| 1452 | add_op.forced_output_quantization = foq |
| 1453 | add_op.add_input_tensor(intermediate) |
| 1454 | quant = QuantizationParameters() |
| 1455 | quant.zero_point = 0 |
| 1456 | bias_term_tens = create_const_tensor( |
| 1457 | op.name + "_bias", |
| 1458 | [1, 1, 1, 1], |
| 1459 | DataType.int16, |
| 1460 | [bias_term], |
| 1461 | np.int16, |
| 1462 | quantization=quant, |
| 1463 | quant_value_dtype=np.int16, |
| 1464 | ) |
| 1465 | add_op.add_input_tensor(bias_term_tens) |
| 1466 | add_op.set_output_tensor(op.ofm) |
| 1467 | add_op.set_ifm_ofm_shapes() |
| 1468 | add_op.activation = op.activation |
| 1469 | op.activation = None |
| 1470 | op.set_output_tensor(intermediate) |
| 1471 | op.set_ifm_ofm_shapes() |
| 1472 | # If not, we can just do it with the OFM zero point. |
| 1473 | else: |
| 1474 | foq.zero_point = bias_term |
| 1475 | op.forced_output_quantization = foq |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1476 | else: |
| 1477 | assert inp.dtype == DataType.int8 |
| 1478 | # Use a depthwise to calculate the sum, |
| 1479 | # followed by a multiplication with 1/N to get the MEAN |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1480 | weight_scale = 1 |
| 1481 | intermediate = op.ofm.clone(suffix="_intermediate", set_unique=True) |
| 1482 | intermediate.dtype = DataType.int16 |
| 1483 | mul_op = Operation(Op.Mul, op.name + "_mul") |
| 1484 | mul_op.add_input_tensor(intermediate) |
| 1485 | # Create scalar containing 1/N |
| 1486 | quant = QuantizationParameters() |
| 1487 | quant.zero_point = 0 |
| 1488 | # The reference rounds negative numbers downwards, e.g. -1.5 is rounded to -2, |
| 1489 | # while rounding mode NATURAL would round this to -1. |
| 1490 | # This can only occur if N is even, and can be emulated by |
| 1491 | # multiplying with a number that is slightly smaller than 1/N. |
| 1492 | # It must be so small that other roundings are not affected; |
| 1493 | # the calculated value is based on worst case, |
| 1494 | # which is sum 256 * N (the maximum sum that can occur with int8) |
| 1495 | n = int(h * w) |
| 1496 | eps = 1 / (256 * (n + 1)) if n % 2 == 0 else 0 |
| 1497 | quant.scale_f32 = 1 / (n - eps) |
| 1498 | scalar = create_const_tensor( |
| 1499 | op.name + "_scalar", [1, 1, 1, 1], DataType.uint8, [1], np.uint8, quantization=quant |
| 1500 | ) |
| 1501 | mul_op.add_input_tensor(scalar) |
| 1502 | mul_op.set_output_tensor(op.ofm) |
| 1503 | mul_op.set_ifm_ofm_shapes() |
| 1504 | mul_op.rounding_mode = NpuRoundingMode.NATURAL |
| 1505 | mul_op.activation = op.activation |
| 1506 | op.activation = None |
| 1507 | op.set_output_tensor(intermediate) |
| 1508 | op.set_ifm_ofm_shapes() |
| 1509 | elif ifmq.zero_point == ofmq.zero_point and ifmq.scale_f32 == ofmq.scale_f32: |
Dwight Lidman | 95b279f | 2021-03-26 10:53:28 +0100 | [diff] [blame^] | 1510 | # Here we can just use a simple AvgPool with truncating rounding, |
| 1511 | # as we're emulating simple integer division. |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1512 | op.rounding_mode = NpuRoundingMode.TRUNCATE |
Dwight Lidman | 95b279f | 2021-03-26 10:53:28 +0100 | [diff] [blame^] | 1513 | op.type = Op.AvgPool |
| 1514 | op.attrs.update({"ksize": (1, h, w, 1), "filter_height": h, "filter_width": w}) |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1515 | else: |
Dwight Lidman | 9b37918 | 2021-03-15 19:06:10 +0100 | [diff] [blame] | 1516 | op.rounding_mode = NpuRoundingMode.NATURAL |
| 1517 | weight_scale = 1 / (h * w) |
| 1518 | # Input zero point is adjusted after mean calculation, so we emulate that with a bias |
| 1519 | bias = -ifmq.zero_point * h * w |
| 1520 | fiq = ifmq.clone() |
| 1521 | fiq.zero_point = 0 |
| 1522 | op.forced_input_quantization = fiq |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1523 | |
| 1524 | # Change dimensions to 4 |
| 1525 | if dims < 4: |
| 1526 | shape = [1] + shape |
| 1527 | if dims == 2: |
| 1528 | shape += [1] |
| 1529 | |
| 1530 | # If height is greater than max kernel height, reshape to from HxW to 1x(HxW) |
| 1531 | if h > 64: |
| 1532 | shape = [shape[0], 1, h * w, shape[3]] |
| 1533 | op.ifm_shapes[0] = Shape4D(shape) |
| 1534 | inp.avoid_NHCWB16 = True |
Dwight Lidman | 95b279f | 2021-03-26 10:53:28 +0100 | [diff] [blame^] | 1535 | if h > 256 and op.type == Op.AvgPool: |
| 1536 | op.attrs.update({"ksize": (1, 1, h * w, 1), "filter_height": 1, "filter_width": h * w}) |
| 1537 | |
| 1538 | # If the AvgPool version is used, we don't need to do anything else |
| 1539 | if op.type == Op.AvgPool: |
| 1540 | return op |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1541 | |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1542 | # Make unit weight tensor quantization |
Dwight Lidman | 9b37918 | 2021-03-15 19:06:10 +0100 | [diff] [blame] | 1543 | weight_quant = ifmq.clone() |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1544 | weight_quant.min = 0 |
| 1545 | weight_quant.max = 255 |
| 1546 | weight_quant.scale_f32 = weight_scale |
| 1547 | weight_quant.zero_point = 0 |
| 1548 | |
| 1549 | # Set weight shape to [H,W,C,B] |
| 1550 | weight_shape = shape[1:4] + [shape[0]] |
| 1551 | # Add unit weight tensor |
| 1552 | op.set_input_tensor( |
| 1553 | create_const_tensor( |
| 1554 | "weights", |
| 1555 | weight_shape, |
| 1556 | inp.dtype, |
| 1557 | np.ones(weight_shape), |
| 1558 | value_dtype=np.uint8, |
| 1559 | quantization=weight_quant, |
| 1560 | ), |
| 1561 | 1, |
| 1562 | ) |
Dwight Lidman | 9b37918 | 2021-03-15 19:06:10 +0100 | [diff] [blame] | 1563 | op.weights.quant_values = np.reshape(op.inputs[1].quant_values, weight_shape) |
| 1564 | |
Dwight Lidman | 95b279f | 2021-03-26 10:53:28 +0100 | [diff] [blame^] | 1565 | # Add None bias tensor |
| 1566 | op.inputs.append(None) |
Dwight Lidman | 9b37918 | 2021-03-15 19:06:10 +0100 | [diff] [blame] | 1567 | # Add bias tensor |
| 1568 | if bias: |
| 1569 | bias_shape = [shape[-1]] |
| 1570 | op.set_input_tensor( |
| 1571 | create_const_tensor( |
| 1572 | "bias", |
| 1573 | bias_shape, |
| 1574 | inp.dtype, |
| 1575 | np.ones(bias_shape) * bias, |
| 1576 | value_dtype=np.int32, |
| 1577 | quant_value_dtype=np.int32, |
| 1578 | quantization=None, |
| 1579 | ), |
| 1580 | 2, |
| 1581 | ) |
Dwight Lidman | 4f728c0 | 2020-12-17 15:14:45 +0100 | [diff] [blame] | 1582 | |
| 1583 | return op |
| 1584 | |
| 1585 | |
Patrik Gustavsson | 3010d9b | 2020-10-01 08:22:10 +0200 | [diff] [blame] | 1586 | def supported_operator_check(op, arch, nng): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1587 | op.run_on_npu = arch.supported_operators.is_operator_supported(op) |
| 1588 | return op |
| 1589 | |
| 1590 | |
Tim Hall | e6ccd87 | 2020-11-09 16:46:37 +0000 | [diff] [blame] | 1591 | def _record_optimised(op, arch): |
| 1592 | if op.type != Op.Const: |
| 1593 | DebugDatabase.add_optimised(op, op) |
| 1594 | |
| 1595 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1596 | def optimise_graph_a(nng, arch, verbose_graph=False): |
| 1597 | if verbose_graph: |
| 1598 | nng.print_graph() |
| 1599 | |
Patrik Gustavsson | 2349d42 | 2020-12-01 16:02:29 +0100 | [diff] [blame] | 1600 | pre_process_list = [ |
| 1601 | supported_operator_check, |
| 1602 | set_ifm_ofm_op_shapes, |
| 1603 | # TODO: memory-only Op removal |
| 1604 | ] |
| 1605 | |
| 1606 | for idx, sg in enumerate(nng.subgraphs): |
| 1607 | # rewrite graph pass |
| 1608 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 1609 | nng, sg, arch, [], pre_process_list, rewrite_unsupported=False, |
| 1610 | ) |
| 1611 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1612 | # Handle Concat Ops |
| 1613 | for idx, sg in enumerate(nng.subgraphs): |
| 1614 | # rewrite graph pass |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 1615 | rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [rewrite_concat_ops]) |
| 1616 | sg.refresh_after_modification() |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1617 | |
| 1618 | # Handle Split Ops |
| 1619 | for idx, sg in enumerate(nng.subgraphs): |
| 1620 | # rewrite graph pass |
| 1621 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 1622 | nng, |
| 1623 | sg, |
| 1624 | arch, |
| 1625 | [], |
| 1626 | [rewrite_unpack_output, rewrite_stridedslice_output, convert_nop_split_to_identity], |
| 1627 | rewrite_unsupported=False, |
| 1628 | ) |
| 1629 | |
| 1630 | for idx, sg in enumerate(nng.subgraphs): |
| 1631 | # rewrite graph pass |
| 1632 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 1633 | nng, sg, arch, [rewrite_split_ops], [], rewrite_unsupported=False, |
| 1634 | ) |
| 1635 | |
Patrik Gustavsson | 138d47f | 2021-02-08 10:13:48 +0100 | [diff] [blame] | 1636 | # Handle sg input output |
| 1637 | for idx, sg in enumerate(nng.subgraphs): |
| 1638 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
| 1639 | nng, sg, arch, [], [fix_sg_input_output], rewrite_unsupported=False, |
| 1640 | ) |
| 1641 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1642 | # Removal of reshapes |
| 1643 | for sg in nng.subgraphs: |
| 1644 | rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_reshapes]) |
| 1645 | sg.refresh_after_modification() |
| 1646 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1647 | op_rewrite_list = [ |
Tim Hall | 4e12776 | 2020-05-15 16:05:49 +0100 | [diff] [blame] | 1648 | set_tensor_equivalence, |
Dwight Lidman | 95b279f | 2021-03-26 10:53:28 +0100 | [diff] [blame^] | 1649 | convert_mean_to_depthwise_conv_or_avgpool, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1650 | convert_depthwise_to_conv, |
Michael McGeagh | 8d939c0 | 2020-07-29 13:11:43 +0100 | [diff] [blame] | 1651 | convert_conv_to_fc, |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 1652 | convert_softmax, |
Diqing Zhong | 016b827 | 2020-12-16 16:46:06 +0100 | [diff] [blame] | 1653 | optimise_strided_conv, |
Diqing Zhong | 189f748 | 2021-01-26 12:12:51 +0100 | [diff] [blame] | 1654 | convert_hardswish_to_lut, |
Patrik Gustavsson | 2c2522d | 2021-01-29 11:51:31 +0100 | [diff] [blame] | 1655 | rewrite_fully_connected_input, |
Diqing Zhong | 94457b1 | 2020-12-09 15:22:40 +0100 | [diff] [blame] | 1656 | convert_batched_fc_shape, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1657 | fixup_conv2d_backprop, |
Michael McGeagh | 8dbf8cf | 2020-09-08 11:09:48 +0100 | [diff] [blame] | 1658 | fixup_relus_with_differing_ifm_ofm_scaling, |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1659 | fixup_elementwise_with_scalars, # TODO Move to early stage? |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 1660 | reorder_depthwise_weights, |
Charles Xu | 9a03fdf | 2020-07-02 15:12:40 +0200 | [diff] [blame] | 1661 | fixup_resizebilinear, |
Jacob Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 1662 | fixup_bias_tensors, |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1663 | convert_mul_max_to_abs_or_lrelu, |
| 1664 | convert_lrelu, |
Louis Verhaard | f03bad3 | 2020-09-25 08:30:44 +0200 | [diff] [blame] | 1665 | convert_tanh_sigmoid_to_lut, |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1666 | replace_pad_by_hw_pad, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1667 | ] |
| 1668 | |
| 1669 | for idx, sg in enumerate(nng.subgraphs): |
| 1670 | # rewrite graph pass |
| 1671 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
Dwight Lidman | 73320a4 | 2020-11-05 10:34:41 +0100 | [diff] [blame] | 1672 | nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False, |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1673 | ) |
| 1674 | |
| 1675 | for idx, sg in enumerate(nng.subgraphs): |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1676 | # remove passthrough tensors and attempt further optimizations |
| 1677 | nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order( |
Louis Verhaard | ae2d553 | 2020-12-11 17:19:54 +0100 | [diff] [blame] | 1678 | nng, |
| 1679 | sg, |
| 1680 | arch, |
| 1681 | [remove_passthrough_tensor], |
Louis Verhaard | c822d62 | 2021-03-11 14:59:06 +0100 | [diff] [blame] | 1682 | [fuse_activation_function_with_prev, convert_pad, add_padding_fields], |
Louis Verhaard | b9fc33c | 2020-08-13 11:47:36 +0200 | [diff] [blame] | 1683 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1684 | |
Patrik Gustavsson | e3b1b91 | 2021-02-09 15:38:46 +0100 | [diff] [blame] | 1685 | # Removal of SplitSliceRead, need to be done after optimisation has been performed, |
| 1686 | # since ifm/ofm_shapes are of importance to this function |
| 1687 | for sg in nng.subgraphs: |
| 1688 | rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_SplitSliceRead]) |
| 1689 | sg.refresh_after_modification() |
| 1690 | |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1691 | # 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] | 1692 | for sg in nng.subgraphs: |
Patrik Gustavsson | 3a26920 | 2021-01-21 08:28:55 +0100 | [diff] [blame] | 1693 | 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] | 1694 | |
| 1695 | if verbose_graph: |
| 1696 | nng.print_graph() |
| 1697 | return nng |