blob: c3216785bcad2794d90616e293df09788262b9ca [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim 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
Diego Russoea6111a2020-04-14 18:41:58 +010020
21import numpy as np
22
Louis Verhaardd7911c42020-08-25 13:36:41 +020023from . import fp_math
Louis Verhaardb9fc33c2020-08-13 11:47:36 +020024from . import lut
Diego Russoea6111a2020-04-14 18:41:58 +010025from . import rewrite_graph
Louis Verhaardd7911c42020-08-25 13:36:41 +020026from . import scaling
Diego Russoea6111a2020-04-14 18:41:58 +010027from .data_type import DataType
Tim Halle6ccd872020-11-09 16:46:37 +000028from .debug_database import DebugDatabase
Louis Verhaard7db78962020-05-25 15:05:26 +020029from .errors import UnsupportedFeatureError
Dwight Lidman42fed942020-05-29 09:37:03 +020030from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaard8912c532020-09-30 12:11:49 +020031from .numeric_util import clamp_sigmoid
Louis Verhaarde0ef2732020-06-03 08:56:44 +020032from .numeric_util import full_shape
Louis Verhaardf03bad32020-09-25 08:30:44 +020033from .numeric_util import round_away_zero
Louis Verhaarde8a5a782020-11-02 18:04:27 +010034from .operation import create_activation_function
Diego Russoe8a10452020-04-21 17:39:10 +010035from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020036from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010037from .operation import Operation
Michael McGeagh16895482020-12-14 15:51:20 +000038from .operation import Padding
Fredrik Svedbergd9c2c422020-12-01 16:33:45 +010039from .operation_util import create_avgpool_nop
patrik.gustavssoneeb85152020-12-21 17:10:40 +000040from .shape4d import Shape4D
Fredrik Svedberga0c36242020-06-03 15:43:31 +020041from .softmax import SoftMax
Tim Hall93582962020-09-09 21:58:15 +010042from .tensor import check_quantized_tens_scaling_equal
Michael McGeaghc5b549b2020-08-07 11:54:28 +010043from .tensor import create_const_tensor
44from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020045from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010046from .tensor import Tensor
Michael McGeagh7a6f8432020-12-02 15:29:22 +000047from .tflite_mapping import optype_to_builtintype
Tim Hall79d07d22020-04-27 18:20:16 +010048
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000049passthrough_nodes = (Op.Identity,)
Tim Hall79d07d22020-04-27 18:20:16 +010050
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000051memory_only_ops = (Op.Reshape,)
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010052
Tim Hall79d07d22020-04-27 18:20:16 +010053
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020054def remove_passthrough_tensor(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010055 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
56 assert len(tens.ops[0].inputs) == 1
57 tens = tens.ops[0].inputs[0]
58 return tens
59
60
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020061def rewrite_concat(tens, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +020062 if len(tens.ops) == 1 and tens.ops[0].type.is_concat_op():
Tim Hall79d07d22020-04-27 18:20:16 +010063 concat_op = tens.ops[0]
64 if tens != concat_op.outputs[0]:
65 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
66
67 # Not supported so leave it and run on CPU
68 if not concat_op.run_on_npu:
69 return tens
70
71 inputs, axis = concat_op.get_concat_inputs_axis()
72
73 tens.ops = []
74 offset = 0
75 for idx, inp in enumerate(inputs):
Patrik Gustavsson3d737172020-12-22 10:40:51 +010076 if axis >= 0:
77 axis_4D = axis + (4 - len(inp.shape))
78 else:
79 axis_4D = axis
Louis Verhaardaee5d752020-09-30 09:01:52 +020080 new_op = Operation(Op.ConcatSliceWrite, concat_op.name + str(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010081 new_op.inputs = [inp]
82 new_op.outputs = [tens]
Patrik Gustavsson3d737172020-12-22 10:40:51 +010083 new_op.attrs["concat_axis"] = axis_4D
Tim Hall79d07d22020-04-27 18:20:16 +010084 new_op.attrs["concat_start"] = offset
85 offset += inp.shape[axis]
86 new_op.attrs["concat_end"] = offset
87 new_op.run_on_npu = True
88 tens.ops.append(new_op)
Tim Halle6ccd872020-11-09 16:46:37 +000089 DebugDatabase.add_optimised(concat_op, new_op)
patrik.gustavssoneeb85152020-12-21 17:10:40 +000090 new_op.set_ifm_ofm_shapes()
Tim Hall79d07d22020-04-27 18:20:16 +010091 assert tens.shape[axis] == offset
92
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020093 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
94 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
95 # aligned. For other values of axis the address offsets will be 16 byte aligned, as they are all based on c = 0
Patrik Gustavsson458a2082020-08-13 13:41:05 +020096 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson6c97e9a2020-09-23 11:02:18 +020097 if axis == -1 or axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +020098 for op in tens.ops:
99 if op.attrs["concat_start"] % 16 != 0:
100 tens.avoid_NHCWB16 = True
101 break
102
Tim Hall79d07d22020-04-27 18:20:16 +0100103 return tens
104
105
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200106def rewrite_split(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100107
Louis Verhaardaee5d752020-09-30 09:01:52 +0200108 if len(tens.ops) == 1 and tens.ops[0].type.is_split_op():
Tim Hall79d07d22020-04-27 18:20:16 +0100109 split_op = tens.ops[0]
110
111 # Not supported so leave it and run on CPU
112 if not split_op.run_on_npu:
113 return tens
114
115 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
116
117 tens.ops = []
Louis Verhaardaee5d752020-09-30 09:01:52 +0200118 new_op = Operation(Op.SplitSliceRead, split_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100119 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100120
121 # For Split the offset cannot be extracted from the tensor so it has to
122 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100123 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100124 # Get the start and end of the split
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100125 offset_start = [0] * 4
126 for idx, out in enumerate(outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100127 if out == tens:
128 break
Patrik Gustavsson3d737172020-12-22 10:40:51 +0100129 if axis >= 0:
130 axis_4D = axis + (4 - len(out.shape))
131 else:
132 axis_4D = axis
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000133
134 offset_start[axis_4D] += split_op.ofm_shapes[idx].get_dim(axis_4D)
Tim Hall79d07d22020-04-27 18:20:16 +0100135
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200136 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
137 if (offset_start[-1] % 16) != 0:
138 inp.avoid_NHCWB16 = True
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100139 else:
140 offset_start = full_shape(4, offset_start, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100141
142 new_op.attrs["split_start"] = offset_start
Tim Hall79d07d22020-04-27 18:20:16 +0100143 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100144 new_op.set_output_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000145 new_op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000146 DebugDatabase.add_optimised(split_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100147
148 return tens
149
150
151def needed_total_padding(input_size, stride, filter_size):
152 out_size = (input_size + stride - 1) // stride
153 needed_input = (out_size - 1) * stride + filter_size
154 total_padding = max(0, needed_input - input_size)
155 return total_padding
156
157
158def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
159 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
160 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
Michael McGeagh16895482020-12-14 15:51:20 +0000161 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100162 left_pad = (xpad + 0) // 2
163 right_pad = (xpad + 1) // 2
164 top_pad = (ypad + 0) // 2
165 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000166 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100167 left_pad = 0
168 right_pad = 0
169 top_pad = 0
170 bottom_pad = 0
171 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000172 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100173 padding = (top_pad, left_pad, bottom_pad, right_pad)
174 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
175 return padding, skirt
176
Tim Hallc30f4952020-06-15 20:47:35 +0100177
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200178def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
179 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000180 if padding_type == Padding.SAME:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200181 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
182 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200183 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
184 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200185 left_pad = max(kernel_width - 1 - right_pad, 0)
186 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000187 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200188 right_pad = max(kernel_width - 2, 0)
189 bottom_pad = max(kernel_height - 2, 0)
190 left_pad = kernel_width - 1
191 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200192 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000193 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200194 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200195 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200196 return padding, skirt
197
Tim Hall79d07d22020-04-27 18:20:16 +0100198
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200199def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200200 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100201 # flip the inputs
202 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000203 op.set_ifm_ofm_shapes()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200204 op.type = Op.Conv2DBackpropInputSwitchedBias
Jacob Bohlincf7da102020-05-20 09:03:40 +0200205
206 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100207 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100208
209 return op
210
211
Charles Xu9a03fdf2020-07-02 15:12:40 +0200212# Convert the op to an elementwise add
213def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200214 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200215 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200216 op.attrs["resizebilinear"] = True
217 # Create an input tensor filled with zeros
218 shape = op.outputs[0].shape
219 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
220 tens.values = np.zeros(shape)
221 tens.quant_values = np.zeros(shape, np.uint8)
222 tens.quantization = QuantizationParameters(0.0, 255.0)
223 tens.quantization.scale_f32 = 1.0
224 tens.quantization.zero_point = 0
225 tens.consumer_list = [op]
226 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100227 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200228 # Set the add inputs
229 op.inputs[1] = op.inputs[0]
230 op.inputs[0] = tens
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000231 op.set_ifm_ofm_shapes()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200232
233 return op
234
235
Charles Xu87c13502020-08-06 12:17:26 +0200236# Convert ResizeBilinear to a number of 2x2 pool ops
237def convert_resizebilinear_to_2x2_pool(op):
238 count = 0
239 pre_op = op
240 outputs = op.outputs
241
242 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
243 if op.attrs["align_corners"]:
244 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000245 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200246 else:
247 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000248 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200249 op.inputs[0].resampling_mode = resampling_mode.NEAREST
250
251 upscaled_shape = np.array(op.inputs[0].shape[1:3])
252 out_shape = np.array(op.outputs[0].shape[1:3])
253 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
254 return op
255
256 while (upscaled_shape < out_shape).all():
257 if count == 0:
258 scaled_op = pre_op
259 else:
260 scaled_op = op.clone("_{}".format(count))
261 scaled_op.inputs[0] = pre_op.outputs[0]
262
263 upscaled_shape = upscaled_shape * 2 - shape_modifier
264
265 if (upscaled_shape == out_shape).all():
266 scaled_op.outputs = outputs
267 scaled_op.outputs[0].ops = [scaled_op]
268 else:
269 shape = outputs[0].shape.copy()
270 shape[1:3] = upscaled_shape[0:2]
271 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
272 out_tens.quantization = op.outputs[0].quantization.clone()
273 out_tens.quantization.quant_min = np.iinfo(np.int16).min
274 out_tens.quantization.quant_max = np.iinfo(np.int16).max
275 scaled_op.set_output_tensor(out_tens)
276 pre_op = scaled_op
277 count += 1
278
279 # Setup the scale value
280 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
281 scaled_op.attrs["rescale"] = 128
282 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
283 scaled_op.attrs["rescale"] = 1 / 128
284 elif "rescale" in scaled_op.attrs:
285 del scaled_op.attrs["rescale"]
Patrik Gustavssoncc6915c2020-12-22 09:16:50 +0100286 scaled_op.set_ifm_ofm_shapes()
Charles Xu87c13502020-08-06 12:17:26 +0200287
288 return op
289
290
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200291def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200292 if op.type == Op.ResizeBilinear and op.run_on_npu:
Charles Xu87c13502020-08-06 12:17:26 +0200293 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200294 # Bypass nop resizebilinear
295 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200296 op.type = Op.Identity
Charles Xu87c13502020-08-06 12:17:26 +0200297 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
298 convert_resizebilinear_1x1_to_add(op)
299 else:
300 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200301
302 return op
303
304
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200305def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200306 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200307 # the list comprehension should return a list with a single tensor
308 # if it shouldn't, remove_passthrough_tensor will fail appropriately
309 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200310 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200311 return op
312
313
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200314def fixup_fully_connected_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200315 if op.type == Op.FullyConnected:
Tim Hall79d07d22020-04-27 18:20:16 +0100316 inp = op.inputs[0]
317 weights = op.inputs[1]
318
319 n_in_elems = weights.shape[-2]
320 elms = inp.elements()
321 batch_size = elms // n_in_elems
322 assert batch_size * n_in_elems == elms
323
324 desired_shape = [batch_size, n_in_elems]
325 if inp.shape != desired_shape:
326 # mismatch, insert a reshape to fix this.
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200327 op.set_input_tensor(create_reshape_tensor(inp, desired_shape), 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100328
329 return op
330
331
Diqing Zhong94457b12020-12-09 15:22:40 +0100332def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200333 if op.type == Op.FullyConnected:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200334 ifm = op.inputs[0]
335 ofm = op.outputs[0]
336 # Check if the FC is 2D and first dimension indicates batching
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100337 # TOD0 op.ifm_shape[0] > 1 is enough when refactory is complete
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000338 if len(ifm.shape) == len(ofm.shape) == 2 and ifm.shape[0] > 1 and op.ifm_shapes[0].batch > 1:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200339 n = ifm.shape[0]
340 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
341 h, w = batching_split.get(n, (1, n))
342
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200343 prev_op = ifm.ops[0]
344 desired_shape = [1, h, w, ifm.shape[-1]]
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000345 op.ifm_shapes[0] = Shape4D(desired_shape)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100346
Louis Verhaardaee5d752020-09-30 09:01:52 +0200347 if len(ifm.consumer_list) == 1 and prev_op is not None and prev_op.type == Op.Reshape:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200348 # There is a preceding Reshape
349 # Compare input of prev_op and input of op, to see if prev_op can be removed
350 ifm_prev_op = prev_op.inputs[0]
Tim Hall89567612020-10-27 11:57:57 +0000351 if ifm_prev_op.shape == ifm.shape and check_quantized_tens_scaling_equal(ifm_prev_op, ifm):
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200352 # prev_op can be removed
353 op.set_input_tensor(ifm_prev_op, 0)
354 else:
355 op.inputs[0].set_all_shapes(desired_shape)
356 prev_op.set_input_tensor(
357 create_const_tensor(prev_op.inputs[1].name, [1], DataType.int32, desired_shape), 1
358 )
359 prev_op.attrs["new_shape"] = desired_shape
360 else:
361 # Add reshape op to the input if there is no preceding reshape
362 ifm.consumer_list.remove(op)
363 op.set_input_tensor(create_reshape_tensor(ifm, desired_shape), 0)
364
365 # Reshape Weights to be 4D. IO becomes HWIO
366 weight_tensor = op.inputs[1]
367 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
368 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
369
370 desired_shape = [1, h, w, ofm.shape[-1]]
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000371 op.ofm_shapes[0] = Shape4D(desired_shape)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100372
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200373 if (
374 len(ofm.consumer_list) == 1
375 and ofm.consumer_list[0] is not None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200376 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200377 ):
378 # There is a subsequent Reshape
379 # Compare desired shape and output of consumer op, to see if consumer op can be removed
380 ofm_cons_op = ofm.consumer_list[0].outputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100381 if desired_shape == ofm_cons_op.shape and check_quantized_tens_scaling_equal(ofm, ofm_cons_op):
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200382 op.outputs[0] = ofm_cons_op
383 op.outputs[0].ops = [op]
384 else:
385 op.outputs[0].set_all_shapes(desired_shape)
386 else:
Diqing Zhong94457b12020-12-09 15:22:40 +0100387 # Add reshape op to the output
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200388 op.set_output_tensor(create_reshape_tensor(ofm, desired_shape, False))
389 return op
390
391
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200392def fixup_pack_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200393 if op.type == Op.Pack:
Tim Hall79d07d22020-04-27 18:20:16 +0100394 # Pack is also referred to as Stack
395 # Requires the rewrite_concat function to be called on the op afterwards
396 axis = int(op.attrs["axis"])
397 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
398
399 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100400 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100401
402 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100403 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100404 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100405
Louis Verhaardaee5d752020-09-30 09:01:52 +0200406 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100407 reshape_op.attrs["new_shape"] = desired_shape
408 reshape_op.inputs = [inp, new_shape_tens]
409 reshape_op.set_output_tensor(reshape_out)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000410 reshape_op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000411 DebugDatabase.add_optimised(op, reshape_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100412
413 op.inputs[idx] = reshape_out
414
Louis Verhaardaee5d752020-09-30 09:01:52 +0200415 op.type = Op.PackReshaped
Tim Hall79d07d22020-04-27 18:20:16 +0100416
417 return op
418
419
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200420def unfuse_activation_function(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200421 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100422 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200423 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200424 out_tens = op.outputs[0]
425 intermediate_tens = out_tens.clone("_act_intermediate")
426 act_op.set_output_tensor(out_tens)
427 act_op.add_input_tensor(intermediate_tens)
428 op.set_output_tensor(intermediate_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000429 act_op.set_ifm_ofm_shapes()
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200430
431 return op
432
Louis Verhaard8912c532020-09-30 12:11:49 +0200433
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100434def fixup_stridedslice_output(tens, arch, nng):
435 op = tens.ops[0]
Dwight Lidman73320a42020-11-05 10:34:41 +0100436 if op.run_on_npu and op.type == Op.StridedSlice:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100437 reshape_input_shape = tens.shape
438 new_axis_mask = op.attrs["new_axis_mask"]
439 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100440
Dwight Lidman73320a42020-11-05 10:34:41 +0100441 if shrink_axis_mask != 0:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100442 n = 0
443 axis = 0
444 while shrink_axis_mask:
445 prev_mask = shrink_axis_mask
446 n += 1
447 shrink_axis_mask &= shrink_axis_mask - 1
448 axis = int(math.log2(prev_mask - shrink_axis_mask))
449 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
450
451 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
452 op.attrs["shrink_axis_mask"] = 0
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100453 elif new_axis_mask != 0:
454 n = 0
455 axis = 0
456 while new_axis_mask:
457 prev_mask = new_axis_mask
458 n += 1
459 new_axis_mask &= new_axis_mask - 1
460 axis = int(math.log2(prev_mask - new_axis_mask))
461 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
462 new_axis_mask >>= 1
463
464 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
465 op.attrs["new_axis_mask"] = 0
Dwight Lidmandda21af2020-11-11 15:44:57 +0100466 else:
467 # Equal Rank StridedSlice, no need to insert reshape
468 return tens
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100469
470 # Construct 1 shape tensor to be used by all inserted reshape ops
471 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
472
473 for idx, out_tens in enumerate(op.outputs):
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000474 op.ofm_shapes[idx] = Shape4D(new_shape_tens.shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100475 reshape_in = out_tens.clone("_reshaped")
476 reshape_in.set_all_shapes(reshape_input_shape)
477 reshape_in.ops = [op]
478
479 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
480 reshape_op.attrs["new_shape"] = reshape_input_shape
481 reshape_op.inputs = [reshape_in, new_shape_tens]
482 reshape_op.set_output_tensor(out_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000483 reshape_op.set_ifm_ofm_shapes()
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100484
485 op.outputs[idx] = reshape_in
486
487 return tens
488
489
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200490def fixup_unpack_output(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100491 op = tens.ops[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100492 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100493 # Unpack is also referred to as Unstack
494 # Requires the rewrite_split function to be called on the op afterwards
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100495 axis = int(op.attrs["axis"])
496 op.type = Op.UnpackReshaped
497 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100498
499 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100500 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100501
502 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100503 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100504 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100505 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100506
Louis Verhaardaee5d752020-09-30 09:01:52 +0200507 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100508 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100509 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100510 reshape_op.set_output_tensor(out_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000511 reshape_op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000512 DebugDatabase.add_optimised(op, reshape_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100513
514 op.outputs[idx] = reshape_in
Tim Hall79d07d22020-04-27 18:20:16 +0100515 return tens
516
517
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200518def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200519 if op.run_on_npu:
520 if "padding" in op.attrs:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200521 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200522 kernel_size = op.inputs[1].shape[:2]
523 input_shape = op.inputs[0].shape
Louis Verhaardaee5d752020-09-30 09:01:52 +0200524 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200525 kernel_size = op.attrs["ksize"][1:3]
526 input_shape = op.inputs[0].shape
Jacob Bohlin90033f32020-08-28 15:45:44 +0200527 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000528 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100529
Louis Verhaardaee5d752020-09-30 09:01:52 +0200530 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200531 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
532 padding, skirt = calc_upscaled_padding_and_skirt(
533 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
534 )
535 else:
536 dilation_h, dilation_w = op.get_dilation_h_w()
537 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
538 padding, skirt = calc_padding_and_skirt(
539 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
540 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200541
Jacob Bohlin90033f32020-08-28 15:45:44 +0200542 op.attrs["explicit_padding"] = padding
543 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200544
Tim Hall79d07d22020-04-27 18:20:16 +0100545 return op
546
547
Tim Hall79d07d22020-04-27 18:20:16 +0100548# Check if the op can be reordered
549def get_prepend_op(op):
550 inp = op.inputs[0]
551 # The op should be reordered between prev_op and prep_op
552 prev_op = inp.ops[-1]
553 prep_op = None
554 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
555 prep_op = prev_op
556 inp = prev_op.inputs[0]
557 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100558 if prev_op is not None and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100559 return prep_op
560
561 return None
562
563
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200564def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100565 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
566 # the ofm depth equals the depth multipler.
567 # If those conditions are true, then we can perform a simple
568 # switch of the operator type (and weight order)
569
Louis Verhaardaee5d752020-09-30 09:01:52 +0200570 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Tim Hall79d07d22020-04-27 18:20:16 +0100571 ifm_tensor = op.inputs[0]
572 weight_tensor = op.inputs[1]
573 ofm_tensor = op.outputs[0]
574 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
575 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200576 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100577 del op.attrs["channel_multiplier"]
578 del op.attrs["depth_multiplier"]
579
580 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100581 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100582 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200583 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000584 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
585 f" ifm channels = {ifm_tensor.shape[3]}, ofm channels = {ofm_tensor.shape[3]}",
Tim Hall79d07d22020-04-27 18:20:16 +0100586 )
Tim Halle6ccd872020-11-09 16:46:37 +0000587 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100588 return op
589
590
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200591def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200592 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200593 weight_tensor = op.inputs[1]
594 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100595 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200596 weight_tensor.weight_transpose_depthwise = True
597
598 return op
599
600
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200601def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100602 # Conv 1x1 can be equivalent to Fully Connected.
603 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
604 # caching/double buffering for the weights.
605 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200606 if op.type == Op.Conv2DBias:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000607 h = op.ifm_shapes[0].height
608 w = op.ifm_shapes[0].width
Michael McGeagh8d939c02020-07-29 13:11:43 +0100609 kh, kw, _, _ = op.inputs[1].shape
610 if h == 1 and w == 1 and kh == 1 and kw == 1:
611 # Overwrite this op as a Fully Connected Op
612 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200613 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100614 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100615 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100616 }
617 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
618 weight_tensor = op.inputs[1]
619 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
620 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100621
Michael McGeagh8d939c02020-07-29 13:11:43 +0100622 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
623 # back to 4D afterwards as the next layer is expecting that shape
624 orig_ofm_tensor = op.outputs[0]
625 # Reshape this ops output to be 2D: {(N*H*W), C} (We know N H and W are all 1 so this becomes {1, C})
626 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
627 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
628 fc_ofm_tensor.ops = [op]
629 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100630 reshape_name = op.name + "_reshape"
631 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200632 reshape_op = Operation(Op.Reshape, reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100633 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100634 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
635 reshape_op.set_output_tensor(orig_ofm_tensor)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000636 reshape_op.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100637
Michael McGeagh8d939c02020-07-29 13:11:43 +0100638 # Replace this ops OFM to point to the 2D tensor
639 op.outputs[0] = fc_ofm_tensor
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000640 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000641 # Record optimisation in debug database
642 DebugDatabase.add_optimised(op, reshape_op)
643 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100644 return op
645
646
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200647def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200648 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100649 ifm = op.inputs[0]
650 ofm = op.outputs[0]
651 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
652 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100653 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100654 # Override this op with its own primary op (avgpool)
655 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
656 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100657 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100658 # Tidy up and assign the ifm and ofm to the new op
659 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200660
661 # if not 4d, reshape ifm/ofm
662 if len(ifm.shape) < 4:
663 ifm_shaped = create_reshape_tensor(ifm, full_shape(4, ifm.shape, 1))
664 ifm = ifm_shaped
665 if len(ofm.shape) < 4:
666 ofm_shaped = create_reshape_tensor(ofm, full_shape(4, ofm.shape, 1), False)
667 ofm = ofm_shaped
668
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100669 relu_fused_op.add_input_tensor(ifm)
670 relu_fused_op.set_output_tensor(ofm)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000671 relu_fused_op.set_ifm_ofm_shapes()
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100672 op = relu_fused_op
673 return op
674
675
Tim Hall79d07d22020-04-27 18:20:16 +0100676# Reorder activation op if it's after the memory only operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200677def fixup_act_reorder(op, arch, nng):
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000678 if op.type.is_relu_op() or op.type in (Op.Sigmoid, Op.Tanh):
Tim Hall79d07d22020-04-27 18:20:16 +0100679 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100680 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100681 act_op = op.clone("_reordered")
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100682 act_op.ifm_shapes = list(op.ifm_shapes)
683 act_op.ofm_shapes = list(op.ofm_shapes)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200684
685 # There is only one input tensor, overwrite it
686 act_op.set_input_tensor(prep_op.inputs[0], 0)
687
Tim Hall79d07d22020-04-27 18:20:16 +0100688 act_op_out = act_op.inputs[0].clone("_acted")
689 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100690 act_op.set_output_tensor(act_op_out)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000691 act_op.ifm_shapes[0] = Shape4D(prep_op.inputs[0].shape)
692 act_op.ofm_shapes[0] = Shape4D(act_op_out.shape)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200693
694 # Update the consumer list
695 act_op_out.consumer_list = op.outputs[0].consumer_list.copy()
696 act_op_out.consumer_list.append(prep_op)
697
Tim Hall79d07d22020-04-27 18:20:16 +0100698 prep_op.inputs[0] = act_op_out
699 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
700
701 # Mark the op so that it will be removed as passthrough later on
Louis Verhaardaee5d752020-09-30 09:01:52 +0200702 op.type = Op.Identity
Tim Halle6ccd872020-11-09 16:46:37 +0000703
704 # Record optimisation in debug database
705 DebugDatabase.add_optimised(op, act_op)
706 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100707 return op
708
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200709
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200710def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200711 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200712 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200713 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
714 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
715 if diff > 0:
716 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
717 elif diff < 0:
718 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200719 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
720 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
721 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
722 ifm_tensor.storage_shape = ifm_tensor.shape
723 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
724 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
725 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
726 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200727 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100728
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200729
Tim Hall4e127762020-05-15 16:05:49 +0100730# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200731def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100732 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100733 eid = op.outputs[0].equivalence_id
734 for inp in op.inputs:
735 inp.equivalence_id = eid
736 return op
737
738
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100739def set_ifm_ofm_op_shapes(op, arch, nng):
740 if op.run_on_npu and op.type.needs_shapes():
741 if op.ifm_shapes or op.ofm_shapes:
742 # Shapes already set
743 return op
744 op.set_ifm_ofm_shapes()
745 return op
746
747
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200748def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200749 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200750 softmax = SoftMax(op)
751 op = softmax.get_graph()
752 return op
753
754
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200755def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100756 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100757
758 Input X For X = -1 or X > 0
759 | \ / This subgraph can be replaced with either
760 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
761 | /
762 Max
763 """
764
Louis Verhaardaee5d752020-09-30 09:01:52 +0200765 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100766 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200767 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100768 if len(muls) == 1:
769 mul = muls[0].ops[0]
770 elif len(muls) == 2:
771 # In the case both inputs are Muls, find the one with the same input as the Max
772 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
773 else:
774 # No Mul inputs
775 return op
776
777 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200778 mul_ofm = mul.outputs[0]
779 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100780 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200781 # make sure the Mul doesn't have a fused activation function
782 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100783 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200784 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100785 if ifm is None or ofm is None:
786 return op
787
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200788 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
789 return op
Tim Hall93582962020-09-09 21:58:15 +0100790 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 +0200791 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
792 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100793
794 # finds the branched input that goes to both the Max and the Mul
795 shared = set(op.inputs) & set(mul.inputs)
796 if len(shared) == 1:
797 shared_in = shared.pop()
798 # find the constant scalar input to the Mul
799 const_tens = (set(mul.inputs) - {shared_in}).pop()
800 # check that it is a scalar
801 if const_tens.shape != []:
802 return op
803 const = const_tens.ops[0]
804 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200805 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100806 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200807 # Remove the Mul from the shared input's consumers
808 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100809 else:
810 return op
811
812 val = const.outputs[0].values
813 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200814 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100815 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200816 # to produce bit exact results, the alpha is not enough;
817 # save additional scaling info in attr "alpha_scale", to be used as input
818 # to the LUT construction
819 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
820 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
821 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
822 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
823 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
824 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100825 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200826 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100827 else:
828 return op
829
Louis Verhaardaee5d752020-09-30 09:01:52 +0200830 op.type = new_op
831 op.name = op.name.replace("Maximum", new_op.name)
832 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100833 op.inputs = [shared_in]
Tim Halle6ccd872020-11-09 16:46:37 +0000834
835 # Record optimisation in debug database
836 DebugDatabase.add_optimised(op, op)
837
Tim Hall79d07d22020-04-27 18:20:16 +0100838 return op
839
840
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200841def convert_lrelu_to_mul_max(op, arch):
842 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
843 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200844 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100845 if ifm is None or ofm is None:
846 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200847
848 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200849 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200850 mul_alpha.add_input_tensor(ifm)
851 # Create const tensor containing alpha as scalar
852 alpha = op.attrs["alpha"]
853 quantization = ifm.quantization.clone()
854 quantization.min = 0
855 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
856 quantization.scale_f32 = alpha
857 quantization.zero_point = 0
858 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
859 mul_alpha.add_input_tensor(alpha_tens)
860 fm_alpha = ofm.clone(op.name + "_alpha")
861 mul_alpha.set_output_tensor(fm_alpha)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000862 mul_alpha.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000863 DebugDatabase.add_optimised(op, mul_alpha)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200864
Tim Hall93582962020-09-09 21:58:15 +0100865 if check_quantized_tens_scaling_equal(ifm, ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200866 # No identity multiplication is needed
867 fm_id = ifm
868 else:
869 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200870 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200871 mul_identity.add_input_tensor(ifm)
872 # Create const tensor containing identity as scalar
873 quantization = ifm.quantization.clone()
874 quantization.min = 0
875 quantization.max = quantization.quant_max - quantization.quant_min
876 quantization.scale_f32 = 1
877 quantization.zero_point = 0
878 identity_tens = create_const_tensor(
879 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
880 )
881 mul_identity.add_input_tensor(identity_tens)
882 fm_id = ofm.clone(op.name + "_id")
883 mul_identity.set_output_tensor(fm_id)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000884 mul_identity.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100885 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200886
887 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200888 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200889 op.name = op.name.replace("LeakyRelu", "Maximum")
890 op.inputs = []
891 ifm.consumer_list.remove(op)
892 op.add_input_tensor(fm_alpha)
893 op.add_input_tensor(fm_id)
Tim Halle6ccd872020-11-09 16:46:37 +0000894
895 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200896 return op
897
898
Louis Verhaard2e186c72020-10-09 10:47:04 +0200899def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200900 # Rewrite the operation by Add with scalar 0 + LUT activation
901 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100902 if ifm is None:
903 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200904 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200905 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200906 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200907 # Mark as no-op to enable potential fusing optimizations
908 op.attrs["is_nop"] = True
909 # Create an input tensor containing scalar zero
910 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200911 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200912 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +0200913 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200914 op.add_input_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000915 op.ifm_shapes.append(Shape4D(tens.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100916
Louis Verhaardf03bad32020-09-25 08:30:44 +0200917 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
918 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
919 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +0200920 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +0200921 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200922 op.set_activation_lut(lut_tensor)
923 return op
924
925
Louis Verhaard2e186c72020-10-09 10:47:04 +0200926def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200927 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
928 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +0200929 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200930 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
931 return op
932 # Generate the LUT
933 ifm_scale = np.double(ifm.quantization.scale_f32)
934 ofm_scale = np.double(ofm.quantization.scale_f32)
935 zp_in = ifm.quantization.zero_point
936 zp_out = ofm.quantization.zero_point
937 values = []
938 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
939 quantized_min = min(ix)
940 quantized_max = max(ix)
941 for x in ix:
942 x_real = ifm_scale * (x - zp_in)
943 y_real = fn(x_real)
944 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
945 lut_result = min(quantized_max, max(quantized_min, lut_result))
946 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200947 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200948
949
950def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200951 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200952 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200953 alpha = op.attrs["alpha"]
954 ifm_scale = np.double(ifm.quantization.scale_f32)
955 ofm_scale = np.double(ofm.quantization.scale_f32)
956 zp_in = ifm.quantization.zero_point
957 zp_out = ofm.quantization.zero_point
958 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
959 alpha_scalar = 1
960 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
961 if "alpha_scaling" in op.attrs:
962 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
963 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
964 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200965 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200966 quantized_min = min(ix)
967 quantized_max = max(ix)
968 for x in ix:
969 if x < zp_in:
970 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
971 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
972 )
973 else:
974 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
975 lut_result = min(quantized_max, max(quantized_min, lut_result))
976 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200977 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200978
979
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200980def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200981 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200982 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200983 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200984 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100985 if ifm is None or ofm is None:
986 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200987 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
988 # use LUT for int8/uint8
989 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +0100990 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +0200991 # use LeakyRelu unmodified for int16 with equal input/output scaling
992 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200993 return convert_lrelu_to_mul_max(op, arch)
994
995
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200996def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200997 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +0200998 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +0200999 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +02001000 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001001 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +02001002 return op
1003
1004
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001005def remove_unwanted_reshapes(op, arch, nng):
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001006 # Try to remove reshapes enclosing ElementWise operator with only one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +02001007 if not op.run_on_npu or not op.type.is_elementwise_op():
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001008 return op
1009
1010 # Check if the ElementWise operator only have one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +02001011 non_const_tens = [x for x in op.inputs if x.ops[0].type != Op.Const]
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001012 if len(non_const_tens) != 1:
1013 return op
1014 ifm = non_const_tens[0]
1015
1016 # Check if operation is enclosed by Reshapes that can be removed
1017 ofm = op.outputs[0]
1018 prev_op = ifm.ops[0]
1019 if (
1020 len(ifm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001021 and prev_op.type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001022 and len(ofm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001023 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001024 ):
1025 # Operation is enclosed by reshapes, check if they can be removed
Louis Verhaardaee5d752020-09-30 09:01:52 +02001026 prev_op_ifm, prev_op_ofm = prev_op.get_ifm_ofm()
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001027 cons_op = ofm.consumer_list[0]
1028 cons_op_ifm = ofm
1029 cons_op_ofm = cons_op.outputs[0]
1030 if len(prev_op_ifm.shape) == len(cons_op_ofm.shape):
1031 # Check if quantization is the same in the input and output for the reshape ops
Tim Hall93582962020-09-09 21:58:15 +01001032 if check_quantized_tens_scaling_equal(prev_op_ifm, prev_op_ofm) and check_quantized_tens_scaling_equal(
1033 cons_op_ifm, cons_op_ofm
1034 ):
Patrik Gustavsson7ad862a2020-09-29 14:09:43 +02001035 op.set_input_tensor(prev_op_ifm, 0)
1036 op.set_output_tensor(cons_op_ofm)
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001037 return op
1038
1039
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001040def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001041 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001042 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001043 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001044 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001045 if ifm is None or ofm is None:
1046 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001047 # finds the input(s) to the operation
1048 prev_op = ifm.ops[0]
1049 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1050 fuse = (
1051 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001052 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001053 and len(ifm.ops) == 1
1054 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001055 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001056 )
1057 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1058 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1059 # LUT currently only works correctly for elementwise ops
1060 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001061 if not fuse:
1062 return op
1063 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001064 prev_op.activation = op.activation
1065 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001066 if op.activation_lut is not None:
1067 prev_op.set_activation_lut(op.activation_lut)
1068 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001069 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001070 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001071 return op
1072
1073
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001074def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001075 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001076 input_tensor = op.inputs[0]
1077 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
1078 out_shape = op.outputs[0].shape[1:3]
1079 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
1080 # this means the output is supposed to be a x2 upscale,
1081 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001082 op.attrs["padding"] = Padding.SAME
Dwight Lidman42fed942020-05-29 09:37:03 +02001083 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
1084 # here we can just run the avg pool without padding and
1085 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001086 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001087 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001088 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001089 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001090 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001091 return op
1092
1093
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001094def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001095 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001096 # Op has no bias, add bias tensor filled with zeros
1097 nr_biases = op.inputs[1].shape[-1]
1098 bias_values = [0] * nr_biases
1099 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1100 bias_tensor.quant_values = bias_tensor.values
1101 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001102
1103 return op
1104
1105
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001106def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001107 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1108 return op
1109
1110
Tim Halle6ccd872020-11-09 16:46:37 +00001111def _record_optimised(op, arch):
1112 if op.type != Op.Const:
1113 DebugDatabase.add_optimised(op, op)
1114
1115
Tim Hall79d07d22020-04-27 18:20:16 +01001116def optimise_graph_a(nng, arch, verbose_graph=False):
1117 if verbose_graph:
1118 nng.print_graph()
1119
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001120 pre_process_list = [
1121 supported_operator_check,
1122 set_ifm_ofm_op_shapes,
1123 # TODO: memory-only Op removal
1124 ]
1125
1126 for idx, sg in enumerate(nng.subgraphs):
1127 # rewrite graph pass
1128 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1129 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1130 )
1131
Tim Hall79d07d22020-04-27 18:20:16 +01001132 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001133 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001134 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001135 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001136 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +01001137 fixup_fully_connected_input,
Diqing Zhong94457b12020-12-09 15:22:40 +01001138 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001139 fixup_pack_input,
Fredrik Svedberg0f98b362020-09-29 10:00:39 +02001140 unfuse_activation_function,
Tim Hall79d07d22020-04-27 18:20:16 +01001141 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001142 fixup_relus_with_differing_ifm_ofm_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +01001143 fixup_act_reorder,
Charles Xu78792222020-05-13 10:15:26 +02001144 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +02001145 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001146 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001147 fixup_bias_tensors,
Dwight Lidmanc3862c22020-09-14 15:22:33 +02001148 convert_nop_split_to_identity,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001149 convert_mul_max_to_abs_or_lrelu,
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001150 remove_unwanted_reshapes,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001151 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001152 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001153 ]
1154
1155 for idx, sg in enumerate(nng.subgraphs):
1156 # rewrite graph pass
1157 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001158 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001159 )
1160
1161 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001162 # remove passthrough tensors and attempt further optimizations
1163 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001164 nng, sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001165 )
Tim Hall79d07d22020-04-27 18:20:16 +01001166
Tim Halle6ccd872020-11-09 16:46:37 +00001167 # Post-optimisation operator debug tracing
1168 for sg in nng.subgraphs:
1169 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [_record_optimised])
1170
Tim Hall79d07d22020-04-27 18:20:16 +01001171 if verbose_graph:
1172 nng.print_graph()
1173 return nng
1174
Diego Russoea6111a2020-04-14 18:41:58 +01001175
Tim Hall79d07d22020-04-27 18:20:16 +01001176def optimise_graph_b(nng, arch, verbose_graph=False):
1177 if verbose_graph:
1178 nng.print_graph()
1179
1180 for idx, sg in enumerate(nng.subgraphs):
1181 # combined rewrite graph pass
Dwight Lidmanc6ac1942020-10-02 14:55:45 +02001182 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
patrik.gustavssoneeb85152020-12-21 17:10:40 +00001183 nng, sg, arch, [fixup_unpack_output, fixup_stridedslice_output, rewrite_concat, rewrite_split], [],
Dwight Lidmanc6ac1942020-10-02 14:55:45 +02001184 )
Tim Hall79d07d22020-04-27 18:20:16 +01001185
1186 if verbose_graph:
1187 nng.print_graph()
1188 return nng