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