blob: 4e7c0fd3984741f9216492890180367c6b9f8118 [file] [log] [blame]
Louis Verhaardebf4af62021-01-27 15:57:57 +01001# Copyright (C) 2020-2021 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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 Hall79d07d22020-04-27 18:20:16 +010016# 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 Hall79d07d22020-04-27 18:20:16 +010019import math
Diqing Zhong016b8272020-12-16 16:46:06 +010020import uuid
Louis Verhaardebf4af62021-01-27 15:57:57 +010021from typing import Tuple
Diego Russoea6111a2020-04-14 18:41:58 +010022
23import numpy as np
24
Louis Verhaardd7911c42020-08-25 13:36:41 +020025from . import fp_math
Louis Verhaardb9fc33c2020-08-13 11:47:36 +020026from . import lut
Diego Russoea6111a2020-04-14 18:41:58 +010027from . import rewrite_graph
Louis Verhaardd7911c42020-08-25 13:36:41 +020028from . import scaling
Louis Verhaard1a92f782021-02-09 16:08:26 +010029from .api import NpuRoundingMode
Diego Russoea6111a2020-04-14 18:41:58 +010030from .data_type import DataType
Tim Halle6ccd872020-11-09 16:46:37 +000031from .debug_database import DebugDatabase
Louis Verhaard7db78962020-05-25 15:05:26 +020032from .errors import UnsupportedFeatureError
Patrik Gustavsson3a269202021-01-21 08:28:55 +010033from .errors import VelaError
Dwight Lidman42fed942020-05-29 09:37:03 +020034from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaard8912c532020-09-30 12:11:49 +020035from .numeric_util import clamp_sigmoid
Louis Verhaarde0ef2732020-06-03 08:56:44 +020036from .numeric_util import full_shape
Louis Verhaardf03bad32020-09-25 08:30:44 +020037from .numeric_util import round_away_zero
Louis Verhaarde8a5a782020-11-02 18:04:27 +010038from .operation import create_activation_function
Diego Russoe8a10452020-04-21 17:39:10 +010039from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020040from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010041from .operation import Operation
Michael McGeagh16895482020-12-14 15:51:20 +000042from .operation import Padding
Fredrik Svedbergd9c2c422020-12-01 16:33:45 +010043from .operation_util import create_avgpool_nop
patrik.gustavssoneeb85152020-12-21 17:10:40 +000044from .shape4d import Shape4D
Fredrik Svedberga0c36242020-06-03 15:43:31 +020045from .softmax import SoftMax
Tim Hall93582962020-09-09 21:58:15 +010046from .tensor import check_quantized_tens_scaling_equal
Michael McGeaghc5b549b2020-08-07 11:54:28 +010047from .tensor import create_const_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020048from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010049from .tensor import Tensor
Louis Verhaard1a92f782021-02-09 16:08:26 +010050from .tensor import TensorPurpose
Michael McGeagh7a6f8432020-12-02 15:29:22 +000051from .tflite_mapping import optype_to_builtintype
Tim Hall79d07d22020-04-27 18:20:16 +010052
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000053passthrough_nodes = (Op.Identity,)
Tim Hall79d07d22020-04-27 18:20:16 +010054
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000055memory_only_ops = (Op.Reshape,)
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010056
Tim Hall79d07d22020-04-27 18:20:16 +010057
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020058def remove_passthrough_tensor(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010059 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
60 assert len(tens.ops[0].inputs) == 1
61 tens = tens.ops[0].inputs[0]
62 return tens
63
64
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +010065def rewrite_concat_ops(op, arch):
Patrik Gustavsson3a269202021-01-21 08:28:55 +010066 if not op.run_on_npu or not op.type.is_concat_op():
67 return op
Tim Hall79d07d22020-04-27 18:20:16 +010068
Patrik Gustavsson3a269202021-01-21 08:28:55 +010069 axis_4D = 0
70 ofm = op.ofm
71 ofm.ops = []
72 offset = 0
Tim Hall79d07d22020-04-27 18:20:16 +010073
Patrik Gustavsson7bada402021-01-28 15:46:21 +010074 unfuse_activation_function(op)
75
Patrik Gustavsson3a269202021-01-21 08:28:55 +010076 if op.type == Op.Pack:
77 # Pack is also referred to as Stack
78 axis = int(op.attrs["axis"])
79 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +010080
Patrik Gustavsson3a269202021-01-21 08:28:55 +010081 if axis >= 0:
82 axis_4D = axis + (4 - len(desired_shape))
83 else:
84 axis_4D = axis
85
86 for idx, inp in enumerate(op.inputs):
87 op.ifm_shapes[idx] = Shape4D(desired_shape)
88 if Shape4D(inp.shape) != op.ifm_shapes[idx]:
89 inp.avoid_NHCWB16 = True
90 op.type = Op.PackReshaped
91
92 inputs, axis = op.get_concat_inputs_axis()
93
94 for idx, inp in enumerate(inputs):
95 if op.type != Op.PackReshaped:
96 op.ifm_shapes[idx] = Shape4D(inp.shape)
Patrik Gustavsson3d737172020-12-22 10:40:51 +010097 if axis >= 0:
98 axis_4D = axis + (4 - len(inp.shape))
99 else:
100 axis_4D = axis
Patrik Gustavsson138d47f2021-02-08 10:13:48 +0100101 avgpool_op = create_avgpool_nop(op.name + str(idx) + "_avgpool")
102 avgpool_op.inputs = [inp]
103 avgpool_op.outputs = [ofm]
104 avgpool_op.attrs["concat_axis"] = axis_4D
105 avgpool_op.attrs["concat_start"] = offset
Tim Hall73e843f2021-02-04 22:47:46 +0000106 offset += op.ifm_shapes[idx][axis_4D]
Tim Hall79d07d22020-04-27 18:20:16 +0100107
Patrik Gustavsson138d47f2021-02-08 10:13:48 +0100108 avgpool_op.attrs["concat_end"] = offset
109 avgpool_op.run_on_npu = True
110 ofm.ops.append(avgpool_op)
111 DebugDatabase.add_optimised(op, avgpool_op)
112 avgpool_op.ifm_shapes.append(op.ifm_shapes[idx])
113 avgpool_op.ofm_shapes.append(op.ofm_shapes[0])
Patrik Gustavsson2446e592021-02-11 08:36:12 +0100114 avgpool_op.memory_function = Op.ConcatSliceWrite
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100115 assert ofm.shape[axis] == offset
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200116
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100117 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
118 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
119 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
120 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
121 if axis == -1 or axis == (len(ofm.shape) - 1):
122 for op in ofm.ops:
123 if op.attrs["concat_start"] % 16 != 0:
124 ofm.avoid_NHCWB16 = True
125 break
126 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100127
128
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100129def rewrite_split_ops(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100130
Patrik Gustavsson224e99b2021-01-14 10:55:43 +0100131 if len(tens.ops) == 1 and tens.ops[0].type.is_split_op() and tens.ops[0].type != Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100132 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 Verhaardaee5d752020-09-30 09:01:52 +0200141 new_op = Operation(Op.SplitSliceRead, split_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100142 new_op.inputs = [inp]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100143 ofm_shape_idx = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100144
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 Russoea6111a2020-04-14 18:41:58 +0100147 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100148 # Get the start and end of the split
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100149 offset_start = [0] * 4
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100150 axis_4D_list = split_op.attrs.get("split_axis_4D", None) # Present for UnpackReshaped and some StridedSlice
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100151 for idx, out in enumerate(outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100152 if axis_4D_list is not None:
153 axis_4D = axis_4D_list[idx]
Patrik Gustavsson3d737172020-12-22 10:40:51 +0100154 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100155 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.gustavssoneeb85152020-12-21 17:10:40 +0000164
Tim Hall73e843f2021-02-04 22:47:46 +0000165 offset_start[axis_4D] += split_op.ofm_shapes[idx][axis_4D]
Tim Hall79d07d22020-04-27 18:20:16 +0100166
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200167 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
168 if (offset_start[-1] % 16) != 0:
169 inp.avoid_NHCWB16 = True
Tim Hall79d07d22020-04-27 18:20:16 +0100170
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100171 new_op.read_offsets[0] = Shape4D.from_list(offset_start, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100172 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100173 new_op.set_output_tensor(tens)
Patrik Gustavsson224e99b2021-01-14 10:55:43 +0100174 new_op.ifm_shapes.append(Shape4D(inp.shape))
Tim Hall73e843f2021-02-04 22:47:46 +0000175 new_op.ofm_shapes.append(split_op.ofm_shapes[ofm_shape_idx])
Tim Halle6ccd872020-11-09 16:46:37 +0000176 DebugDatabase.add_optimised(split_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100177
178 return tens
179
180
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100181def remove_SplitSliceRead(op, arch):
182
183 if op.type == Op.SplitSliceRead:
184 # Check if it is possible to put the SplitSliceRead on the tensor consumer, or if an avgpool need to be inserted
185 if (
186 len(op.ofm.consumer_list) == 1
187 and op.ofm.consumer_list[0] is not None
188 and op.ofm.consumer_list[0].run_on_npu
189 and op.ofm.consumer_list[0].type != Op.Reshape
190 and op.ofm_shapes[0] == Shape4D.from_list(op.ofm.shape)
191 ):
192 # SplitSliceRead can be performed by tensor consumer
193 cons_op = op.ofm.consumer_list[0]
194 if cons_op.ifm == op.ofm:
195 cons_op.read_offsets[0] = op.read_offsets[0]
196 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[0])
197 cons_op.ifm_shapes[0] = op.ifm_shapes[0]
198 elif cons_op.type.is_binary_elementwise_op() and cons_op.ifm2 == op.ofm:
199 cons_op.read_offsets[1] = op.read_offsets[0]
200 cons_op.set_input_tensor(op.ifm, cons_op.type.info.indices.ifms[1])
201 cons_op.ifm_shapes[1] = op.ifm_shapes[0]
202
203 op.ofm.consumer_list.remove(cons_op)
204 op.ofm.ops = []
205 op.ifm.consumer_list.remove(op)
206 else:
207 avgpool_op = create_avgpool_nop(op.name + "_avgpool")
208 avgpool_op.add_input_tensor(op.ifm)
209 avgpool_op.outputs = [op.ofm]
210 op.ofm.ops.remove(op)
211 op.ofm.ops.append(avgpool_op)
212 avgpool_op.ifm_shapes.append(op.ifm_shapes[0])
213 avgpool_op.ofm_shapes.append(op.ofm_shapes[0])
214 avgpool_op.read_offsets[0] = op.read_offsets[0]
215
216 op.ifm.consumer_list.remove(op)
217 DebugDatabase.add_optimised(op, avgpool_op)
218
219
Patrik Gustavsson138d47f2021-02-08 10:13:48 +0100220def insert_copy_op_after_tens(tens):
221 tens_cons_list_copy = tens.consumer_list.copy()
222
223 # Create a avg_pool nop op with ifm as input
224 copy_tens = tens.clone()
225 copy_op = create_avgpool_nop(tens.name + "_avgpool")
226 copy_op.add_input_tensor(tens)
227 copy_op.set_output_tensor(copy_tens)
228 copy_op.set_ifm_ofm_shapes()
229 copy_op.run_on_npu = True
230
231 # Set copy_ifm consumers
232 for tens_cons in tens_cons_list_copy:
233 if tens_cons is not None:
234 for ifm_idx, cons_inp in enumerate(tens_cons.inputs):
235 if cons_inp == tens:
236 tens_cons.set_input_tensor(copy_tens, ifm_idx)
237
238 DebugDatabase.add_optimised(tens.ops[0], copy_op)
239
240
241def fix_sg_input_output(op, arch, nng):
242 if not op.run_on_npu or op.type != Op.Reshape:
243 return op
244
Patrik Gustavssone3b1b912021-02-09 15:38:46 +0100245 # For the Reshape operators we want to remove, tensors are removed.
Patrik Gustavsson138d47f2021-02-08 10:13:48 +0100246 # But in order to to do this, they cannot be outputs of the sg,
247 # this need to be fixed prior to the removal.
248 # Solution is to add a avgpool NOP, to maintain the original tensor.
249
250 # Check if operator ifm/ofm are sg ifm/ofm
251 ifm_is_sg_ifm = op.ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
252 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in op.ifm.consumer_list)
253 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in op.ofm.consumer_list)
254
255 if op.type == Op.Reshape and (ifm_is_sg_ofm or ifm_is_sg_ifm) and ofm_is_sg_ofm:
256 # Both ifm and ofm are sg outputs, only ifm need a copy, in order to remove the Reshape
257 insert_copy_op_after_tens(op.ifm)
258
259 return op
260
261
Tim Hall79d07d22020-04-27 18:20:16 +0100262def needed_total_padding(input_size, stride, filter_size):
263 out_size = (input_size + stride - 1) // stride
264 needed_input = (out_size - 1) * stride + filter_size
265 total_padding = max(0, needed_input - input_size)
266 return total_padding
267
268
Louis Verhaardebf4af62021-01-27 15:57:57 +0100269def calc_explicit_padding(input_size, stride, filter_size, pad_before, pad_after) -> Tuple[int, int]:
270 """
271 Based on explicit padding provided in a PAD operation, returns the corresponding hardware padding
272 that provides equivalent results.
273 """
274 total_padding = needed_total_padding(input_size, stride, filter_size)
275 # The top/left padding can be taken as is from the PAD
276 output_pad_before = pad_before
277 # The bottom/right padding might need downward adjustment depending on stride/input size
278 output_pad_after = pad_after
279 while output_pad_after > 0 and output_pad_after % stride != (total_padding - pad_before) % stride:
280 output_pad_after -= 1
281 return output_pad_before, output_pad_after
282
283
284def calc_padding_and_skirt(padding_type, kernel, input_shape, explicit_padding):
285 k_w, k_h = kernel.dilated_wh()
286 s_x, s_y = kernel.stride
287 ypad = needed_total_padding(int(input_shape.height), int(s_y), int(k_h))
288 xpad = needed_total_padding(int(input_shape.width), int(s_x), int(k_w))
Michael McGeagh16895482020-12-14 15:51:20 +0000289 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100290 left_pad = (xpad + 0) // 2
291 right_pad = (xpad + 1) // 2
292 top_pad = (ypad + 0) // 2
293 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000294 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100295 left_pad = 0
296 right_pad = 0
297 top_pad = 0
298 bottom_pad = 0
Louis Verhaardae2d5532020-12-11 17:19:54 +0100299 elif padding_type == Padding.EXPLICIT:
300 # Padding is specified in a PAD operator which has been bypassed.
Louis Verhaardebf4af62021-01-27 15:57:57 +0100301 top, left, bottom, right = explicit_padding
302 top_pad, bottom_pad = calc_explicit_padding(int(input_shape.height), int(s_y), int(k_h), int(top), int(bottom))
303 left_pad, right_pad = calc_explicit_padding(int(input_shape.width), int(s_x), int(k_w), int(left), int(right))
Tim Hall79d07d22020-04-27 18:20:16 +0100304 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000305 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100306 padding = (top_pad, left_pad, bottom_pad, right_pad)
307 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
308 return padding, skirt
309
Tim Hallc30f4952020-06-15 20:47:35 +0100310
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100311def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_shape, upscaling_factor):
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200312 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000313 if padding_type == Padding.SAME:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100314 ypad = needed_total_padding(int(input_shape.height) * upscaling_factor, int(stride[1]), int(kernel_height))
315 xpad = needed_total_padding(int(input_shape.width) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200316 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
317 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200318 left_pad = max(kernel_width - 1 - right_pad, 0)
319 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000320 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200321 right_pad = max(kernel_width - 2, 0)
322 bottom_pad = max(kernel_height - 2, 0)
323 left_pad = kernel_width - 1
324 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200325 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000326 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200327 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200328 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200329 return padding, skirt
330
Tim Hall79d07d22020-04-27 18:20:16 +0100331
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200332def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200333 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100334 # flip the inputs
335 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200336 op.type = Op.Conv2DBackpropInputSwitchedBias
Louis Verhaard69b84802020-12-16 12:02:28 +0100337 op.ifm.resampling_mode = resampling_mode.TRANSPOSE
Jacob Bohlincf7da102020-05-20 09:03:40 +0200338
339 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100340 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100341
342 return op
343
344
Charles Xu9a03fdf2020-07-02 15:12:40 +0200345# Convert the op to an elementwise add
346def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200347 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200348 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200349 op.attrs["resizebilinear"] = True
350 # Create an input tensor filled with zeros
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100351 shape = op.ofm_shapes[0].as_list()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200352 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
353 tens.values = np.zeros(shape)
354 tens.quant_values = np.zeros(shape, np.uint8)
355 tens.quantization = QuantizationParameters(0.0, 255.0)
356 tens.quantization.scale_f32 = 1.0
357 tens.quantization.zero_point = 0
358 tens.consumer_list = [op]
359 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100360 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200361 # Set the add inputs
362 op.inputs[1] = op.inputs[0]
363 op.inputs[0] = tens
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000364 op.set_ifm_ofm_shapes()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200365
366 return op
367
368
Charles Xu87c13502020-08-06 12:17:26 +0200369# Convert ResizeBilinear to a number of 2x2 pool ops
370def convert_resizebilinear_to_2x2_pool(op):
371 count = 0
372 pre_op = op
373 outputs = op.outputs
374
375 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
376 if op.attrs["align_corners"]:
377 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000378 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200379 else:
380 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000381 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200382 op.inputs[0].resampling_mode = resampling_mode.NEAREST
383
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100384 upscaled_shape = np.array(op.ifm_shapes[0].get_hw_as_list())
385 out_shape = np.array(op.ofm_shapes[0].get_hw_as_list())
Charles Xu87c13502020-08-06 12:17:26 +0200386 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
387 return op
388
389 while (upscaled_shape < out_shape).all():
390 if count == 0:
391 scaled_op = pre_op
392 else:
393 scaled_op = op.clone("_{}".format(count))
394 scaled_op.inputs[0] = pre_op.outputs[0]
395
396 upscaled_shape = upscaled_shape * 2 - shape_modifier
397
398 if (upscaled_shape == out_shape).all():
399 scaled_op.outputs = outputs
400 scaled_op.outputs[0].ops = [scaled_op]
401 else:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100402 shape = op.ofm_shapes[0].as_list()
403 shape[1:3] = upscaled_shape
Charles Xu87c13502020-08-06 12:17:26 +0200404 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
405 out_tens.quantization = op.outputs[0].quantization.clone()
406 out_tens.quantization.quant_min = np.iinfo(np.int16).min
407 out_tens.quantization.quant_max = np.iinfo(np.int16).max
408 scaled_op.set_output_tensor(out_tens)
409 pre_op = scaled_op
410 count += 1
411
412 # Setup the scale value
413 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100414 scaled_op.rescale = 128
Charles Xu87c13502020-08-06 12:17:26 +0200415 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
Fredrik Svedberge82be7c2021-01-18 15:21:03 +0100416 scaled_op.rescale = 1 / 128
417 else:
418 scaled_op.rescale = None
Patrik Gustavssoncc6915c2020-12-22 09:16:50 +0100419 scaled_op.set_ifm_ofm_shapes()
Charles Xu87c13502020-08-06 12:17:26 +0200420
421 return op
422
423
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200424def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200425 if op.type == Op.ResizeBilinear and op.run_on_npu:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100426 if op.ifm_shapes[0] == op.ofm_shapes[0]:
Charles Xu36ffaf32020-08-05 15:40:44 +0200427 # Bypass nop resizebilinear
428 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200429 op.type = Op.Identity
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100430 elif op.ifm_shapes[0].height == 1 and op.ifm_shapes[0].width == 1:
Charles Xu87c13502020-08-06 12:17:26 +0200431 convert_resizebilinear_1x1_to_add(op)
432 else:
433 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200434
435 return op
436
437
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200438def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200439 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200440 # the list comprehension should return a list with a single tensor
441 # if it shouldn't, remove_passthrough_tensor will fail appropriately
442 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200443 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200444 return op
445
446
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100447def rewrite_fully_connected_input(op, arch, nng):
448 if op.type == Op.FullyConnected:
449 n_in_elems = op.weights.shape[-2]
450 elms = op.ifm.elements()
451 batch_size = elms // n_in_elems
452 assert batch_size * n_in_elems == elms
453
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100454 op.ifm_shapes[0] = Shape4D([batch_size, 1, 1, n_in_elems])
Patrik Gustavssonda2b0032021-02-04 16:28:29 +0100455 if Shape4D(op.ifm.shape) != op.ifm_shapes[0]:
456 op.ifm.avoid_NHCWB16 = True
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +0100457 return op
458
459
Diqing Zhong94457b12020-12-09 15:22:40 +0100460def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200461 if op.type == Op.FullyConnected:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100462 # Check if the first dimension indicates batching
463 if op.ifm_shapes[0].batch > 1:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200464 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100465 n = op.ifm_shapes[0].batch
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200466 h, w = batching_split.get(n, (1, n))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100467 op.ifm_shapes[0] = Shape4D([1, h, w, op.ifm_shapes[0].depth])
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200468
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100469 op.ifm.avoid_NHCWB16 = True
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200470
471 # Reshape Weights to be 4D. IO becomes HWIO
472 weight_tensor = op.inputs[1]
473 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
474 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
475
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100476 n = op.ofm_shapes[0].batch
477 h, w = batching_split.get(n, (1, n))
478 op.ofm_shapes[0] = Shape4D([1, h, w, op.ofm_shapes[0].depth])
479 op.ofm.avoid_NHCWB16 = True
Tim Hall79d07d22020-04-27 18:20:16 +0100480 return op
481
482
Patrik Gustavsson7bada402021-01-28 15:46:21 +0100483def unfuse_activation_function(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200484 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100485 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200486 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200487 out_tens = op.outputs[0]
488 intermediate_tens = out_tens.clone("_act_intermediate")
489 act_op.set_output_tensor(out_tens)
490 act_op.add_input_tensor(intermediate_tens)
491 op.set_output_tensor(intermediate_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000492 act_op.set_ifm_ofm_shapes()
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200493
Louis Verhaard8912c532020-09-30 12:11:49 +0200494
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100495def rewrite_stridedslice_output(op, arch, nng):
496 if not op.run_on_npu or op.type != Op.StridedSlice:
497 return op
498
499 new_axis_mask = op.attrs["new_axis_mask"]
500 shrink_axis_mask = op.attrs["shrink_axis_mask"]
501
502 if shrink_axis_mask == 0 and new_axis_mask == 0:
503 return op
504
505 axis_4D = [0] * len(op.outputs)
506 for idx, out_tens in enumerate(op.outputs):
507 output_shape = list(out_tens.shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100508
Dwight Lidman73320a42020-11-05 10:34:41 +0100509 if shrink_axis_mask != 0:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100510 n = 0
511 axis = 0
512 while shrink_axis_mask:
513 prev_mask = shrink_axis_mask
514 n += 1
515 shrink_axis_mask &= shrink_axis_mask - 1
516 axis = int(math.log2(prev_mask - shrink_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100517 output_shape = output_shape[:axis] + [1] + output_shape[axis:]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100518
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100519 assert len(out_tens.shape) == (len(op.inputs[0].shape) - n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100520 op.attrs["shrink_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100521 if axis >= 0:
522 axis_4D[idx] = axis + (4 - len(output_shape))
523 else:
524 axis_4D[idx] = axis
525 op.ofm_shapes[idx] = Shape4D(output_shape)
526
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100527 elif new_axis_mask != 0:
528 n = 0
529 axis = 0
530 while new_axis_mask:
531 prev_mask = new_axis_mask
532 n += 1
533 new_axis_mask &= new_axis_mask - 1
534 axis = int(math.log2(prev_mask - new_axis_mask))
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100535 output_shape = output_shape[:axis] + output_shape[(axis + 1) :]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100536 new_axis_mask >>= 1
537
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100538 assert len(out_tens.shape) == (len(op.inputs[0].shape) + n)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100539 op.attrs["new_axis_mask"] = 0
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100540 if axis >= 0:
541 axis_4D[idx] = axis + (4 - len(output_shape))
542 else:
543 axis_4D[idx] = axis
544 op.ofm_shapes[idx] = Shape4D(output_shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100545
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100546 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
547 out_tens.avoid_NHCWB16 = True
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100548
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100549 op.attrs["split_axis_4D"] = axis_4D
550 return op
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100551
552
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100553def rewrite_unpack_output(op, arch, nng):
554 tens = op.outputs[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100555 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100556 # Unpack is also referred to as Unstack
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100557 axis = int(op.attrs["axis"])
558 op.type = Op.UnpackReshaped
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100559 desired_output_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100560
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100561 if axis >= 0:
562 axis_4D = axis + (4 - len(desired_output_shape))
563 else:
564 axis_4D = axis
Tim Hall79d07d22020-04-27 18:20:16 +0100565
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100566 axis_4D_list = [0] * len(op.outputs)
Tim Hall79d07d22020-04-27 18:20:16 +0100567 for idx, out_tens in enumerate(op.outputs):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100568 op.ofm_shapes[idx] = Shape4D(desired_output_shape)
569 axis_4D_list[idx] = axis_4D
570 if op.ofm_shapes[idx] != Shape4D(out_tens.shape):
571 out_tens.avoid_NHCWB16 = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100572
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100573 op.attrs["split_axis_4D"] = axis_4D_list
574 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100575
576
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200577def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200578 if op.run_on_npu:
579 if "padding" in op.attrs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100580 input_shape = op.ifm_shapes[0]
581 output_shape = op.ofm_shapes[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200582 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200583 kernel_size = op.inputs[1].shape[:2]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200584 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200585 kernel_size = op.attrs["ksize"][1:3]
Jacob Bohlin90033f32020-08-28 15:45:44 +0200586 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000587 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100588
Louis Verhaardaee5d752020-09-30 09:01:52 +0200589 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100590 upscaling_factor = output_shape.height // input_shape.height
Jacob Bohlin90033f32020-08-28 15:45:44 +0200591 padding, skirt = calc_upscaled_padding_and_skirt(
592 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
593 )
594 else:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200595 padding, skirt = calc_padding_and_skirt(
Louis Verhaardebf4af62021-01-27 15:57:57 +0100596 op.attrs["padding"], op.kernel, input_shape, op.attrs.get("explicit_padding"),
Jacob Bohlin90033f32020-08-28 15:45:44 +0200597 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200598
Jacob Bohlin90033f32020-08-28 15:45:44 +0200599 op.attrs["explicit_padding"] = padding
600 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200601
Tim Hall79d07d22020-04-27 18:20:16 +0100602 return op
603
604
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200605def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100606 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
607 # the ofm depth equals the depth multipler.
608 # If those conditions are true, then we can perform a simple
609 # switch of the operator type (and weight order)
610
Louis Verhaardaee5d752020-09-30 09:01:52 +0200611 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100612 ifm_shape = op.ifm_shapes[0]
Tim Hall79d07d22020-04-27 18:20:16 +0100613 weight_tensor = op.inputs[1]
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100614 ofm_shape = op.ofm_shapes[0]
615 if (ifm_shape.depth == 1) and (ofm_shape.depth == op.attrs["depth_multiplier"]):
Tim Hall79d07d22020-04-27 18:20:16 +0100616 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200617 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100618 del op.attrs["channel_multiplier"]
619 del op.attrs["depth_multiplier"]
620
621 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100622 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100623 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200624 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000625 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100626 f" ifm channels = {ifm_shape.depth}, ofm channels = {ofm_shape.depth}",
Tim Hall79d07d22020-04-27 18:20:16 +0100627 )
Tim Halle6ccd872020-11-09 16:46:37 +0000628 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100629 return op
630
631
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200632def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200633 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200634 weight_tensor = op.inputs[1]
635 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100636 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200637 weight_tensor.weight_transpose_depthwise = True
638
639 return op
640
641
Diqing Zhong016b8272020-12-16 16:46:06 +0100642def optimise_strided_conv(op, arch, nng):
643 stride_x, stride_y = op.get_kernel_stride()
644 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
645
646 if (
647 op.type == Op.Conv2DBias
648 and op.op_index == 0
649 and stride_x == 2
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100650 and op.ifm_shapes[0].depth <= 4
651 and op.ifm_shapes[0].width % 2 == 0
Diqing Zhong016b8272020-12-16 16:46:06 +0100652 and weight_tensor is not None
653 and weight_tensor.shape[1] >= 2
654 ):
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100655 ifm_shape = op.ifm_shapes[0]
Diqing Zhong016b8272020-12-16 16:46:06 +0100656 # IFM
Patrik Gustavsson3a269202021-01-21 08:28:55 +0100657 op.ifm_shapes[0] = Shape4D([ifm_shape.batch, ifm_shape.height, ifm_shape.width // 2, ifm_shape.depth * 2])
658 op.ifm.avoid_NHCWB16 = True
Diqing Zhong016b8272020-12-16 16:46:06 +0100659
660 # Weights
661 weight_shape = weight_tensor.shape
662 if weight_shape[1] % 2 != 0:
663 weight_shape[1] = weight_shape[1] + 1
664 padded_array = np.zeros(weight_shape)
665 for i in range(weight_shape[0]):
666 padded_array[i] = np.vstack(
667 [
668 weight_tensor.quant_values[i],
669 np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point),
670 ]
671 )
672 weight_tensor.quant_values = padded_array
673 weight_shape[1] //= 2
674 weight_shape[2] *= 2
675 weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape)
676 weight_tensor.set_all_shapes(weight_shape)
677 # If multiple copies of the weights are used, we could avoid
678 # them having the same address by changing the value_id
679 weight_tensor.value_id = uuid.uuid4()
680
681 # Strides
682 stride_x = 1
683 op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)})
684
Diqing Zhong016b8272020-12-16 16:46:06 +0100685 return op
686
687
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200688def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100689 # Conv 1x1 can be equivalent to Fully Connected.
690 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
691 # caching/double buffering for the weights.
692 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200693 if op.type == Op.Conv2DBias:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000694 h = op.ifm_shapes[0].height
695 w = op.ifm_shapes[0].width
Michael McGeagh8d939c02020-07-29 13:11:43 +0100696 kh, kw, _, _ = op.inputs[1].shape
697 if h == 1 and w == 1 and kh == 1 and kw == 1:
698 # Overwrite this op as a Fully Connected Op
699 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200700 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100701 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100702 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100703 }
704 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
705 weight_tensor = op.inputs[1]
706 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
707 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100708
Tim Halle6ccd872020-11-09 16:46:37 +0000709 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100710 return op
711
712
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200713def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200714 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100715 ifm = op.inputs[0]
716 ofm = op.outputs[0]
717 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
718 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100719 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100720 # Override this op with its own primary op (avgpool)
721 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
722 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100723 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100724 # Tidy up and assign the ifm and ofm to the new op
725 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200726
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100727 relu_fused_op.add_input_tensor(ifm)
728 relu_fused_op.set_output_tensor(ofm)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000729 relu_fused_op.set_ifm_ofm_shapes()
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100730 op = relu_fused_op
731 return op
732
733
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200734def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200735 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200736 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200737 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
738 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
739 if diff > 0:
740 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
741 elif diff < 0:
742 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200743 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
744 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
745 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
746 ifm_tensor.storage_shape = ifm_tensor.shape
747 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
748 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
749 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
750 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200751 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100752
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200753
Tim Hall4e127762020-05-15 16:05:49 +0100754# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200755def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100756 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100757 eid = op.outputs[0].equivalence_id
758 for inp in op.inputs:
759 inp.equivalence_id = eid
760 return op
761
762
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100763def set_ifm_ofm_op_shapes(op, arch, nng):
764 if op.run_on_npu and op.type.needs_shapes():
765 if op.ifm_shapes or op.ofm_shapes:
766 # Shapes already set
767 return op
768 op.set_ifm_ofm_shapes()
769 return op
770
771
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200772def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200773 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200774 softmax = SoftMax(op)
775 op = softmax.get_graph()
776 return op
777
778
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200779def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100780 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100781
782 Input X For X = -1 or X > 0
783 | \ / This subgraph can be replaced with either
784 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
785 | /
786 Max
787 """
788
Louis Verhaardaee5d752020-09-30 09:01:52 +0200789 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100790 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200791 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100792 if len(muls) == 1:
793 mul = muls[0].ops[0]
794 elif len(muls) == 2:
795 # In the case both inputs are Muls, find the one with the same input as the Max
796 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
797 else:
798 # No Mul inputs
799 return op
800
801 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200802 mul_ofm = mul.outputs[0]
803 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100804 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200805 # make sure the Mul doesn't have a fused activation function
806 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100807 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200808 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100809 if ifm is None or ofm is None:
810 return op
811
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200812 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
813 return op
Tim Hall93582962020-09-09 21:58:15 +0100814 if not check_quantized_tens_scaling_equal(ifm, ofm) or not check_quantized_tens_scaling_equal(ifm, mul_ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200815 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
816 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100817
818 # finds the branched input that goes to both the Max and the Mul
819 shared = set(op.inputs) & set(mul.inputs)
820 if len(shared) == 1:
821 shared_in = shared.pop()
822 # find the constant scalar input to the Mul
823 const_tens = (set(mul.inputs) - {shared_in}).pop()
824 # check that it is a scalar
825 if const_tens.shape != []:
826 return op
827 const = const_tens.ops[0]
828 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200829 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100830 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200831 # Remove the Mul from the shared input's consumers
832 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100833 else:
834 return op
835
836 val = const.outputs[0].values
837 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200838 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100839 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200840 # to produce bit exact results, the alpha is not enough;
841 # save additional scaling info in attr "alpha_scale", to be used as input
842 # to the LUT construction
843 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
844 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
845 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
846 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
847 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
848 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100849 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200850 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100851 else:
852 return op
853
Louis Verhaardaee5d752020-09-30 09:01:52 +0200854 op.type = new_op
855 op.name = op.name.replace("Maximum", new_op.name)
856 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100857 op.inputs = [shared_in]
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100858 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000859
860 # Record optimisation in debug database
861 DebugDatabase.add_optimised(op, op)
862
Tim Hall79d07d22020-04-27 18:20:16 +0100863 return op
864
865
Diqing Zhong189f7482021-01-26 12:12:51 +0100866def convert_hardswish_to_lut(op, arch, nng):
867 if op.type == Op.HardSwish:
868 ifm, ofm = op.get_ifm_ofm()
869 # Generate the LUT
870 ifm_scale = np.double(ifm.quantization.scale_f32)
871 ofm_scale = np.double(ofm.quantization.scale_f32)
872 zp_in = ifm.quantization.zero_point
873 zp_out = ofm.quantization.zero_point
874 ifm_scale_hires = (1 / 128) * ifm_scale
875 relu_multiplier = np.double(3 / 32768)
876 out_scale, out_shift = scaling.quantise_scale(ifm_scale_hires / ofm_scale)
877 relu_scale, relu_shift = scaling.quantise_scale(ifm_scale_hires / relu_multiplier)
878 # Use 16bit scale
879 out_scale_16 = fp_math.downscale_multiplier_int32_to_int16(out_scale)
880 relu_scale_16 = fp_math.downscale_multiplier_int32_to_int16(relu_scale)
881
882 values = []
883 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
884 quantized_min = min(ix)
885 quantized_max = max(ix)
886 for x in ix:
887 input_value = x - zp_in
888 input_value_hires = input_value * 128
889 # Compute the input value on essentially the output scale, not shifted yet
890 input_value_preshift = fp_math.saturating_rounding_mul16(input_value_hires, out_scale_16)
891 # Compute the "relu-ish multiplier". This matches the code in TensorFlow Lite Micro kernel
892 relu_value = np.int16(input_value_hires)
893 if relu_shift < 31:
894 relu_value = fp_math.shift_left16(relu_value, 30 - relu_shift)
895
896 relu_value = fp_math.saturating_rounding_mul16(relu_value, relu_scale_16)
897
898 if relu_shift < 31:
899 relu_value = fp_math.shift_left16(relu_value, 1)
900
901 if relu_shift > 31:
902 relu_value = fp_math.rounding_divide_by_pot(relu_value, relu_shift - 31)
903
904 # Rescaled the value into a 16bit fixedpoint relu_value in [-1, 1]
905 # Now convert that to a 16bit fixedpoint value in [0, 1]
906 relu_value = (relu_value + (1 << 15)) >> 1
907 lut_result = fp_math.saturating_mul16(relu_value, input_value_preshift)
908 shift = 31 - out_shift
909 shift = -shift if shift < 0 else 0
910 # Finally apply the output shift
911 lut_result = fp_math.rounding_divide_by_pot(lut_result, shift) + zp_out
912 lut_result = min(quantized_max, max(quantized_min, lut_result))
913 values.append(lut_result)
914 return convert_to_lut(op, values, "hardswish")
915 return op
916
917
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200918def convert_lrelu_to_mul_max(op, arch):
919 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
920 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200921 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100922 if ifm is None or ofm is None:
923 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200924
925 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200926 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200927 mul_alpha.add_input_tensor(ifm)
928 # Create const tensor containing alpha as scalar
929 alpha = op.attrs["alpha"]
930 quantization = ifm.quantization.clone()
931 quantization.min = 0
932 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200933 quantization.zero_point = 0
Louis Verhaardece4e652021-01-07 13:35:47 +0100934 if np.isinf(1 / np.float32(alpha)):
935 # Handling of alpha near zero
936 quantization.scale_f32 = 1
937 scalar = 0
938 else:
939 quantization.scale_f32 = alpha
940 scalar = 1
941 alpha_tens = create_const_tensor(
942 op.name + "_alpha_scalar", [], ifm.dtype, [scalar], np.int8, quantization=quantization
943 )
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200944 mul_alpha.add_input_tensor(alpha_tens)
945 fm_alpha = ofm.clone(op.name + "_alpha")
946 mul_alpha.set_output_tensor(fm_alpha)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000947 mul_alpha.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000948 DebugDatabase.add_optimised(op, mul_alpha)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200949
Tim Hall93582962020-09-09 21:58:15 +0100950 if check_quantized_tens_scaling_equal(ifm, ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200951 # No identity multiplication is needed
952 fm_id = ifm
953 else:
954 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200955 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200956 mul_identity.add_input_tensor(ifm)
957 # Create const tensor containing identity as scalar
958 quantization = ifm.quantization.clone()
959 quantization.min = 0
960 quantization.max = quantization.quant_max - quantization.quant_min
961 quantization.scale_f32 = 1
962 quantization.zero_point = 0
963 identity_tens = create_const_tensor(
964 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
965 )
966 mul_identity.add_input_tensor(identity_tens)
Louis Verhaardece4e652021-01-07 13:35:47 +0100967 # Make sure that fm_id is allocated to a different address than fm_alpha
968 fm_id = ofm.clone(op.name + "_id", set_unique=True)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200969 mul_identity.set_output_tensor(fm_id)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000970 mul_identity.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100971 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200972
973 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200974 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200975 op.name = op.name.replace("LeakyRelu", "Maximum")
976 op.inputs = []
977 ifm.consumer_list.remove(op)
978 op.add_input_tensor(fm_alpha)
979 op.add_input_tensor(fm_id)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100980 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000981
982 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200983 return op
984
985
Louis Verhaard2e186c72020-10-09 10:47:04 +0200986def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200987 # Rewrite the operation by Add with scalar 0 + LUT activation
988 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100989 if ifm is None:
990 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200991 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200992 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200993 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200994 # Mark as no-op to enable potential fusing optimizations
995 op.attrs["is_nop"] = True
996 # Create an input tensor containing scalar zero
997 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200998 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200999 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +02001000 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001001 op.add_input_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +00001002 op.ifm_shapes.append(Shape4D(tens.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001003
Louis Verhaardf03bad32020-09-25 08:30:44 +02001004 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
1005 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
1006 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +02001007 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +02001008 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +02001009 op.set_activation_lut(lut_tensor)
Patrik Gustavssonc509d332020-12-22 13:53:52 +01001010 op.set_ifm_ofm_shapes()
Louis Verhaardf03bad32020-09-25 08:30:44 +02001011 return op
1012
1013
Louis Verhaard2e186c72020-10-09 10:47:04 +02001014def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +02001015 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
1016 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +02001017 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +02001018 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
1019 return op
1020 # Generate the LUT
1021 ifm_scale = np.double(ifm.quantization.scale_f32)
1022 ofm_scale = np.double(ofm.quantization.scale_f32)
1023 zp_in = ifm.quantization.zero_point
1024 zp_out = ofm.quantization.zero_point
1025 values = []
1026 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
1027 quantized_min = min(ix)
1028 quantized_max = max(ix)
1029 for x in ix:
1030 x_real = ifm_scale * (x - zp_in)
1031 y_real = fn(x_real)
1032 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
1033 lut_result = min(quantized_max, max(quantized_min, lut_result))
1034 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +02001035 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +02001036
1037
1038def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001039 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001040 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +02001041 alpha = op.attrs["alpha"]
1042 ifm_scale = np.double(ifm.quantization.scale_f32)
1043 ofm_scale = np.double(ofm.quantization.scale_f32)
1044 zp_in = ifm.quantization.zero_point
1045 zp_out = ofm.quantization.zero_point
1046 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
1047 alpha_scalar = 1
1048 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
1049 if "alpha_scaling" in op.attrs:
1050 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
1051 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
1052 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +02001053 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +02001054 quantized_min = min(ix)
1055 quantized_max = max(ix)
1056 for x in ix:
1057 if x < zp_in:
1058 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
1059 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
1060 )
1061 else:
1062 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
1063 lut_result = min(quantized_max, max(quantized_min, lut_result))
1064 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +02001065 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001066
1067
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001068def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001069 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +02001070 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001071 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001072 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001073 if ifm is None or ofm is None:
1074 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +02001075 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
1076 # use LUT for int8/uint8
1077 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +01001078 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +02001079 # use LeakyRelu unmodified for int16 with equal input/output scaling
1080 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001081 return convert_lrelu_to_mul_max(op, arch)
1082
1083
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001084def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +02001085 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +02001086 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001087 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +02001088 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001089 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +02001090 return op
1091
1092
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001093def remove_reshapes(op, arch):
1094 if op.run_on_npu and op.type == Op.Reshape:
1095 ofm = op.ofm
1096 ifm = op.ifm
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001097
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001098 # Check if quantization is the same in the input and output for the reshape ops
1099 if not check_quantized_tens_scaling_equal(ifm, ofm):
1100 # TODO Both tensors are needed, since quantisation properties currently are linked to Tensors.
1101 # In order to remove this reshape either quantization properties need to be moved to Operator,
1102 # or the reshape need to be replace with a NOP.
1103 return
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001104
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001105 # Check if Reshape ifm/ofm are network ifm/ofm
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001106 ifm_is_sg_ifm = ifm.ops[0].type in (Op.Placeholder, Op.SubgraphInput, Op.Const)
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001107 ifm_is_sg_ofm = any(ifm_cons is None for ifm_cons in ifm.consumer_list)
1108 ofm_is_sg_ofm = any(ofm_cons is None for ofm_cons in ofm.consumer_list)
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001109 # This case should be handled prior to this function
1110 assert not ((ifm_is_sg_ifm or ifm_is_sg_ofm) and ofm_is_sg_ofm)
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001111
1112 if ofm_is_sg_ofm:
1113 # Bypassed by replacing ifm with ofm
1114 ofm.ops = []
1115 for prev_op in ifm.ops:
1116 prev_op.outputs = [ofm]
1117 ofm.ops.append(prev_op)
1118
1119 # All ifm consumers need to use ofm as input
1120 for ifm_cons in ifm.consumer_list:
1121 for ifm_idx, cons_ifm in enumerate(ifm_cons.inputs):
1122 if cons_ifm == ifm:
1123 ifm_cons.set_input_tensor(ofm, ifm_idx)
1124 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1125 ofm.avoid_NHCWB16 = True
1126 else:
1127 # Bypassed Reshape by replacing ofm with ifm
1128 for cons in ofm.consumer_list:
1129 for ifm_idx, cons_ifm in enumerate(cons.inputs):
1130 if cons_ifm == ofm:
1131 cons.set_input_tensor(ifm, ifm_idx)
1132 if op.ifm_shapes[0] != op.ofm_shapes[0]:
1133 ifm.avoid_NHCWB16 = True
1134
1135
1136def check_reshapes(op, arch):
1137 if op.run_on_npu and op.type == Op.Reshape:
1138 ofm = op.ofm
1139
1140 if check_quantized_tens_scaling_equal(op.ifm, ofm):
1141 # Reshape should have been removed
1142 raise VelaError(f"Reshape op {op} expected to have been removed, still remains")
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001143
1144
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001145def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001146 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001147 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001148 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001149 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001150 if ifm is None or ofm is None:
1151 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001152 # finds the input(s) to the operation
1153 prev_op = ifm.ops[0]
1154 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1155 fuse = (
1156 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001157 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001158 and len(ifm.ops) == 1
1159 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001160 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001161 )
1162 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1163 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1164 # LUT currently only works correctly for elementwise ops
1165 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001166 if not fuse:
1167 return op
1168 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001169 prev_op.activation = op.activation
1170 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001171 if op.activation_lut is not None:
1172 prev_op.set_activation_lut(op.activation_lut)
1173 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001174 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001175 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001176 return op
1177
1178
Louis Verhaard1a92f782021-02-09 16:08:26 +01001179def optimise_pad(op: Operation, arch, nng):
Louis Verhaardae2d5532020-12-11 17:19:54 +01001180 """
1181 Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV
1182 if both operations can be run on the NPU.
1183 """
1184 if (
Louis Verhaard1a92f782021-02-09 16:08:26 +01001185 (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op() or op.type.is_pool_op())
Louis Verhaardae2d5532020-12-11 17:19:54 +01001186 and op.run_on_npu
1187 and op.attrs["padding"] == Padding.VALID
1188 ):
1189 pad_op = op.ifm.ops[0]
1190 if pad_op.type != Op.Pad or not pad_op.run_on_npu:
1191 return op
Louis Verhaard1a92f782021-02-09 16:08:26 +01001192 if op.type.is_avgpool_op():
1193 # Average pool is converted to depthwise, because NPU average pool + same padding
1194 # has a special implementation that is different from PAD followed by average pool with
1195 # valid padding.
1196 k_w, k_h = op.kernel.width, op.kernel.height
1197 ifm = op.ifm
1198 # Remember other inputs
1199 other_inputs = op.inputs[1:]
1200 # Create a weight tensor, all weights are set to 1/(kernel width * kernel height)
1201 quantization = QuantizationParameters(0.0, 255.0)
1202 quantization.scale_f32 = 1.0 / (k_w * k_h)
1203 quantization.zero_point = 0
1204 shape = [k_h, k_w, 1, op.ofm.shape[-1]]
1205 weights = np.full(shape, 1)
1206
1207 weight_tens = create_const_tensor(
1208 op.name + "_weights",
1209 shape,
1210 op.ifm.dtype,
1211 weights,
1212 np.uint8,
1213 purpose=TensorPurpose.Weights,
1214 quantization=quantization,
1215 )
1216 weight_tens.quant_values = weights
1217 op.type = Op.DepthwiseConv2DBias
1218 op.inputs = []
1219 op.add_input_tensor(ifm)
1220 op.add_input_tensor(weight_tens)
1221 # Add bias tensor, all biases set to 0
1222 op.inputs.append(None)
1223 fixup_bias_tensors(op, arch, nng)
1224 # Add other inputs
1225 op.inputs.extend(other_inputs)
1226 op.rounding_mode = NpuRoundingMode.NATURAL
1227
Louis Verhaardae2d5532020-12-11 17:19:54 +01001228 # Bypass the PAD operator
1229 op.set_input_tensor(pad_op.ifm, 0)
1230 # Adjust the padding attributes of the convolution operator
1231 op.attrs["padding"] = Padding.EXPLICIT
1232 padding = pad_op.inputs[1].values # 4x2 tensor, first dimension is N, H, W, C
1233 top, left, bottom, right = (padding[1][0], padding[2][0], padding[1][1], padding[2][1])
1234 op.attrs["explicit_padding"] = (top, left, bottom, right)
1235 op.set_ifm_ofm_shapes()
1236 return op
1237
1238
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001239def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001240 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001241 input_tensor = op.inputs[0]
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001242 input_shape = op.ifm_shapes[0]
1243 upscaled_height = input_shape.height * 2
1244 upscaled_width = input_shape.width * 2
1245 out_shape = op.ofm_shapes[0]
1246 if not op.attrs["align_corners"] and out_shape.height == upscaled_height and out_shape.width == upscaled_width:
Dwight Lidman42fed942020-05-29 09:37:03 +02001247 # this means the output is supposed to be a x2 upscale,
1248 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001249 op.attrs["padding"] = Padding.SAME
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001250 elif (
1251 op.attrs["align_corners"]
1252 and out_shape.height == (upscaled_height - 1)
1253 and out_shape.width == (upscaled_width - 1)
1254 ):
Dwight Lidman42fed942020-05-29 09:37:03 +02001255 # here we can just run the avg pool without padding and
1256 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001257 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001258 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001259 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001260 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001261 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001262 return op
1263
1264
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001265def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001266 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001267 # Op has no bias, add bias tensor filled with zeros
1268 nr_biases = op.inputs[1].shape[-1]
1269 bias_values = [0] * nr_biases
1270 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1271 bias_tensor.quant_values = bias_tensor.values
Louis Verhaard1a92f782021-02-09 16:08:26 +01001272 op.set_input_tensor(bias_tensor, op.type.info.indices.biases[0])
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001273
1274 return op
1275
1276
Dwight Lidman4f728c02020-12-17 15:14:45 +01001277def convert_mean_to_depthwise_conv(op, arch, nng):
1278 if op.type == Op.Mean and op.run_on_npu:
1279 keep_dims = op.attrs.get("keep_dims", False)
1280 inp, axis = op.inputs
1281 shape = inp.shape
1282 dims = len(shape)
1283
1284 # Height and width axes have different index depending on dimensions
1285 if axis.shape == []: # single axis
1286 axis = int(axis.values)
1287 if dims in (2, 3):
1288 if axis == 0:
1289 h, w = shape[axis], 1
1290 else:
1291 h, w = 1, shape[axis]
1292 else:
1293 if axis == 1:
1294 h, w = shape[axis], 1
1295 else:
1296 h, w = 1, shape[axis]
1297 else: # multiple axes
1298 axis = sorted(axis.values)
1299 h, w = [shape[i] for i in axis]
1300
1301 # Set necessary depthwise attributes
1302 op.attrs.update(
1303 {
1304 "padding": Padding.VALID,
1305 "stride_h": 1,
1306 "stride_w": 1,
1307 "strides": (1, 1, 1, 1),
1308 "depth_multiplier": 1,
1309 "channel_multiplier": 1,
1310 "dilation_h_factor": 1,
1311 "dilation_w_factor": 1,
1312 "dilation": (1, 1, 1, 1),
1313 }
1314 )
1315 # Change op type
1316 op.type = Op.DepthwiseConv2DBias
1317 # Set IFM/OFM shapes after changing op type
1318 op.set_ifm_ofm_shapes()
1319
1320 ofmq, ifmq = op.ofm.quantization, inp.quantization
1321 # Set rounding mode, scaling and zero point based on which reference implementation to match
1322 if len(shape) == 4 and axis == [1, 2] and keep_dims:
1323 if inp.dtype == DataType.uint8:
1324 # This attribute means a different scaling calculation is used in order to match reference
1325 op.low_precision_scaling = True
1326 weight_scale = h * w
1327 foq = ofmq.clone()
1328 foq.zero_point -= int(np.round(ifmq.zero_point * ifmq.scale_f32 / foq.scale_f32))
1329 op.forced_output_quantization = foq
1330 fiq = ifmq.clone()
1331 fiq.zero_point = 0
1332 op.forced_input_quantization = fiq
1333 else:
1334 assert inp.dtype == DataType.int8
1335 # Use a depthwise to calculate the sum,
1336 # followed by a multiplication with 1/N to get the MEAN
1337 op.type = Op.DepthwiseConv2DBias
1338 weight_scale = 1
1339 intermediate = op.ofm.clone(suffix="_intermediate", set_unique=True)
1340 intermediate.dtype = DataType.int16
1341 mul_op = Operation(Op.Mul, op.name + "_mul")
1342 mul_op.add_input_tensor(intermediate)
1343 # Create scalar containing 1/N
1344 quant = QuantizationParameters()
1345 quant.zero_point = 0
1346 # The reference rounds negative numbers downwards, e.g. -1.5 is rounded to -2,
1347 # while rounding mode NATURAL would round this to -1.
1348 # This can only occur if N is even, and can be emulated by
1349 # multiplying with a number that is slightly smaller than 1/N.
1350 # It must be so small that other roundings are not affected;
1351 # the calculated value is based on worst case,
1352 # which is sum 256 * N (the maximum sum that can occur with int8)
1353 n = int(h * w)
1354 eps = 1 / (256 * (n + 1)) if n % 2 == 0 else 0
1355 quant.scale_f32 = 1 / (n - eps)
1356 scalar = create_const_tensor(
1357 op.name + "_scalar", [1, 1, 1, 1], DataType.uint8, [1], np.uint8, quantization=quant
1358 )
1359 mul_op.add_input_tensor(scalar)
1360 mul_op.set_output_tensor(op.ofm)
1361 mul_op.set_ifm_ofm_shapes()
1362 mul_op.rounding_mode = NpuRoundingMode.NATURAL
1363 mul_op.activation = op.activation
1364 op.activation = None
1365 op.set_output_tensor(intermediate)
1366 op.set_ifm_ofm_shapes()
1367 elif ifmq.zero_point == ofmq.zero_point and ifmq.scale_f32 == ofmq.scale_f32:
1368 op.rounding_mode = NpuRoundingMode.TRUNCATE
1369 weight_scale = 1 / (h * w)
1370 foq = ofmq.clone()
1371 foq.zero_point = 0
1372 op.forced_output_quantization = foq
1373 fiq = ifmq.clone()
1374 fiq.zero_point = 0
1375 op.forced_input_quantization = fiq
1376 else:
1377 raise UnsupportedFeatureError("Mean operators with these attributes are currently not supported")
1378
1379 # Change dimensions to 4
1380 if dims < 4:
1381 shape = [1] + shape
1382 if dims == 2:
1383 shape += [1]
1384
1385 # If height is greater than max kernel height, reshape to from HxW to 1x(HxW)
1386 if h > 64:
1387 shape = [shape[0], 1, h * w, shape[3]]
1388 op.ifm_shapes[0] = Shape4D(shape)
1389 inp.avoid_NHCWB16 = True
1390
1391 # Add None bias tensor
1392 op.inputs.append(None)
1393 # Make unit weight tensor quantization
1394 weight_quant = inp.quantization.clone()
1395 weight_quant.min = 0
1396 weight_quant.max = 255
1397 weight_quant.scale_f32 = weight_scale
1398 weight_quant.zero_point = 0
1399
1400 # Set weight shape to [H,W,C,B]
1401 weight_shape = shape[1:4] + [shape[0]]
1402 # Add unit weight tensor
1403 op.set_input_tensor(
1404 create_const_tensor(
1405 "weights",
1406 weight_shape,
1407 inp.dtype,
1408 np.ones(weight_shape),
1409 value_dtype=np.uint8,
1410 quantization=weight_quant,
1411 ),
1412 1,
1413 )
1414 op.inputs[1].quant_values = np.reshape(op.inputs[1].quant_values, weight_shape)
1415
1416 return op
1417
1418
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001419def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001420 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1421 return op
1422
1423
Tim Halle6ccd872020-11-09 16:46:37 +00001424def _record_optimised(op, arch):
1425 if op.type != Op.Const:
1426 DebugDatabase.add_optimised(op, op)
1427
1428
Tim Hall79d07d22020-04-27 18:20:16 +01001429def optimise_graph_a(nng, arch, verbose_graph=False):
1430 if verbose_graph:
1431 nng.print_graph()
1432
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001433 pre_process_list = [
1434 supported_operator_check,
1435 set_ifm_ofm_op_shapes,
1436 # TODO: memory-only Op removal
1437 ]
1438
1439 for idx, sg in enumerate(nng.subgraphs):
1440 # rewrite graph pass
1441 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1442 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1443 )
1444
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001445 # Handle Concat Ops
1446 for idx, sg in enumerate(nng.subgraphs):
1447 # rewrite graph pass
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001448 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [rewrite_concat_ops])
1449 sg.refresh_after_modification()
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001450
1451 # Handle Split Ops
1452 for idx, sg in enumerate(nng.subgraphs):
1453 # rewrite graph pass
1454 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1455 nng,
1456 sg,
1457 arch,
1458 [],
1459 [rewrite_unpack_output, rewrite_stridedslice_output, convert_nop_split_to_identity],
1460 rewrite_unsupported=False,
1461 )
1462
1463 for idx, sg in enumerate(nng.subgraphs):
1464 # rewrite graph pass
1465 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1466 nng, sg, arch, [rewrite_split_ops], [], rewrite_unsupported=False,
1467 )
1468
Patrik Gustavsson138d47f2021-02-08 10:13:48 +01001469 # Handle sg input output
1470 for idx, sg in enumerate(nng.subgraphs):
1471 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1472 nng, sg, arch, [], [fix_sg_input_output], rewrite_unsupported=False,
1473 )
1474
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001475 # Removal of reshapes
1476 for sg in nng.subgraphs:
1477 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_reshapes])
1478 sg.refresh_after_modification()
1479
Tim Hall79d07d22020-04-27 18:20:16 +01001480 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001481 set_tensor_equivalence,
Dwight Lidman4f728c02020-12-17 15:14:45 +01001482 convert_mean_to_depthwise_conv,
Tim Hall79d07d22020-04-27 18:20:16 +01001483 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001484 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001485 convert_softmax,
Diqing Zhong016b8272020-12-16 16:46:06 +01001486 optimise_strided_conv,
Diqing Zhong189f7482021-01-26 12:12:51 +01001487 convert_hardswish_to_lut,
Patrik Gustavsson2c2522d2021-01-29 11:51:31 +01001488 rewrite_fully_connected_input,
Diqing Zhong94457b12020-12-09 15:22:40 +01001489 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001490 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001491 fixup_relus_with_differing_ifm_ofm_scaling,
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001492 fixup_elementwise_with_scalars, # TODO Move to early stage?
Jacob Bohline843d332020-06-23 12:12:56 +02001493 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001494 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001495 fixup_bias_tensors,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001496 convert_mul_max_to_abs_or_lrelu,
1497 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001498 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001499 ]
1500
1501 for idx, sg in enumerate(nng.subgraphs):
1502 # rewrite graph pass
1503 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001504 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001505 )
1506
1507 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001508 # remove passthrough tensors and attempt further optimizations
1509 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Louis Verhaardae2d5532020-12-11 17:19:54 +01001510 nng,
1511 sg,
1512 arch,
1513 [remove_passthrough_tensor],
1514 [fuse_activation_function_with_prev, optimise_pad, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001515 )
Tim Hall79d07d22020-04-27 18:20:16 +01001516
Patrik Gustavssone3b1b912021-02-09 15:38:46 +01001517 # Removal of SplitSliceRead, need to be done after optimisation has been performed,
1518 # since ifm/ofm_shapes are of importance to this function
1519 for sg in nng.subgraphs:
1520 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [remove_SplitSliceRead])
1521 sg.refresh_after_modification()
1522
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001523 # Post-optimisation operator debug tracing, and checking that no undesired reshapes are left in the graph
Tim Halle6ccd872020-11-09 16:46:37 +00001524 for sg in nng.subgraphs:
Patrik Gustavsson3a269202021-01-21 08:28:55 +01001525 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [check_reshapes, _record_optimised])
Tim Hall79d07d22020-04-27 18:20:16 +01001526
1527 if verbose_graph:
1528 nng.print_graph()
1529 return nng