blob: 6d2696c4126734f97615709d6fd1ea9641fb2d35 [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
Diqing Zhong016b8272020-12-16 16:46:06 +010020import uuid
Diego Russoea6111a2020-04-14 18:41:58 +010021
22import numpy as np
23
Louis Verhaardd7911c42020-08-25 13:36:41 +020024from . import fp_math
Louis Verhaardb9fc33c2020-08-13 11:47:36 +020025from . import lut
Diego Russoea6111a2020-04-14 18:41:58 +010026from . import rewrite_graph
Louis Verhaardd7911c42020-08-25 13:36:41 +020027from . import scaling
Diego Russoea6111a2020-04-14 18:41:58 +010028from .data_type import DataType
Tim Halle6ccd872020-11-09 16:46:37 +000029from .debug_database import DebugDatabase
Louis Verhaard7db78962020-05-25 15:05:26 +020030from .errors import UnsupportedFeatureError
Dwight Lidman42fed942020-05-29 09:37:03 +020031from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaard8912c532020-09-30 12:11:49 +020032from .numeric_util import clamp_sigmoid
Louis Verhaarde0ef2732020-06-03 08:56:44 +020033from .numeric_util import full_shape
Louis Verhaardf03bad32020-09-25 08:30:44 +020034from .numeric_util import round_away_zero
Louis Verhaarde8a5a782020-11-02 18:04:27 +010035from .operation import create_activation_function
Diego Russoe8a10452020-04-21 17:39:10 +010036from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020037from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010038from .operation import Operation
Michael McGeagh16895482020-12-14 15:51:20 +000039from .operation import Padding
Fredrik Svedbergd9c2c422020-12-01 16:33:45 +010040from .operation_util import create_avgpool_nop
patrik.gustavssoneeb85152020-12-21 17:10:40 +000041from .shape4d import Shape4D
Fredrik Svedberga0c36242020-06-03 15:43:31 +020042from .softmax import SoftMax
Tim Hall93582962020-09-09 21:58:15 +010043from .tensor import check_quantized_tens_scaling_equal
Michael McGeaghc5b549b2020-08-07 11:54:28 +010044from .tensor import create_const_tensor
45from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020046from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010047from .tensor import Tensor
Michael McGeagh7a6f8432020-12-02 15:29:22 +000048from .tflite_mapping import optype_to_builtintype
Tim Hall79d07d22020-04-27 18:20:16 +010049
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000050passthrough_nodes = (Op.Identity,)
Tim Hall79d07d22020-04-27 18:20:16 +010051
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000052memory_only_ops = (Op.Reshape,)
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010053
Tim Hall79d07d22020-04-27 18:20:16 +010054
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020055def remove_passthrough_tensor(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010056 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
57 assert len(tens.ops[0].inputs) == 1
58 tens = tens.ops[0].inputs[0]
59 return tens
60
61
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020062def rewrite_concat(tens, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +020063 if len(tens.ops) == 1 and tens.ops[0].type.is_concat_op():
Tim Hall79d07d22020-04-27 18:20:16 +010064 concat_op = tens.ops[0]
65 if tens != concat_op.outputs[0]:
66 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
67
68 # Not supported so leave it and run on CPU
69 if not concat_op.run_on_npu:
70 return tens
71
72 inputs, axis = concat_op.get_concat_inputs_axis()
73
74 tens.ops = []
75 offset = 0
76 for idx, inp in enumerate(inputs):
Patrik Gustavsson3d737172020-12-22 10:40:51 +010077 if axis >= 0:
78 axis_4D = axis + (4 - len(inp.shape))
79 else:
80 axis_4D = axis
Louis Verhaardaee5d752020-09-30 09:01:52 +020081 new_op = Operation(Op.ConcatSliceWrite, concat_op.name + str(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010082 new_op.inputs = [inp]
83 new_op.outputs = [tens]
Patrik Gustavsson3d737172020-12-22 10:40:51 +010084 new_op.attrs["concat_axis"] = axis_4D
Tim Hall79d07d22020-04-27 18:20:16 +010085 new_op.attrs["concat_start"] = offset
86 offset += inp.shape[axis]
87 new_op.attrs["concat_end"] = offset
88 new_op.run_on_npu = True
89 tens.ops.append(new_op)
Tim Halle6ccd872020-11-09 16:46:37 +000090 DebugDatabase.add_optimised(concat_op, new_op)
patrik.gustavssoneeb85152020-12-21 17:10:40 +000091 new_op.set_ifm_ofm_shapes()
Tim Hall79d07d22020-04-27 18:20:16 +010092 assert tens.shape[axis] == offset
93
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020094 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
95 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
96 # 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 +020097 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson6c97e9a2020-09-23 11:02:18 +020098 if axis == -1 or axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +020099 for op in tens.ops:
100 if op.attrs["concat_start"] % 16 != 0:
101 tens.avoid_NHCWB16 = True
102 break
103
Tim Hall79d07d22020-04-27 18:20:16 +0100104 return tens
105
106
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200107def rewrite_split(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100108
Louis Verhaardaee5d752020-09-30 09:01:52 +0200109 if len(tens.ops) == 1 and tens.ops[0].type.is_split_op():
Tim Hall79d07d22020-04-27 18:20:16 +0100110 split_op = tens.ops[0]
111
112 # Not supported so leave it and run on CPU
113 if not split_op.run_on_npu:
114 return tens
115
116 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
117
118 tens.ops = []
Louis Verhaardaee5d752020-09-30 09:01:52 +0200119 new_op = Operation(Op.SplitSliceRead, split_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100120 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100121
122 # For Split the offset cannot be extracted from the tensor so it has to
123 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100124 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100125 # Get the start and end of the split
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100126 offset_start = [0] * 4
127 for idx, out in enumerate(outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100128 if out == tens:
129 break
Patrik Gustavsson3d737172020-12-22 10:40:51 +0100130 if axis >= 0:
131 axis_4D = axis + (4 - len(out.shape))
132 else:
133 axis_4D = axis
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000134
135 offset_start[axis_4D] += split_op.ofm_shapes[idx].get_dim(axis_4D)
Tim Hall79d07d22020-04-27 18:20:16 +0100136
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200137 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
138 if (offset_start[-1] % 16) != 0:
139 inp.avoid_NHCWB16 = True
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100140 else:
141 offset_start = full_shape(4, offset_start, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100142
143 new_op.attrs["split_start"] = offset_start
Tim Hall79d07d22020-04-27 18:20:16 +0100144 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100145 new_op.set_output_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000146 new_op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000147 DebugDatabase.add_optimised(split_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100148
149 return tens
150
151
152def needed_total_padding(input_size, stride, filter_size):
153 out_size = (input_size + stride - 1) // stride
154 needed_input = (out_size - 1) * stride + filter_size
155 total_padding = max(0, needed_input - input_size)
156 return total_padding
157
158
Louis Verhaardae2d5532020-12-11 17:19:54 +0100159def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims, explicit_padding):
Tim Hall79d07d22020-04-27 18:20:16 +0100160 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
161 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
Michael McGeagh16895482020-12-14 15:51:20 +0000162 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100163 left_pad = (xpad + 0) // 2
164 right_pad = (xpad + 1) // 2
165 top_pad = (ypad + 0) // 2
166 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000167 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100168 left_pad = 0
169 right_pad = 0
170 top_pad = 0
171 bottom_pad = 0
Louis Verhaardae2d5532020-12-11 17:19:54 +0100172 elif padding_type == Padding.EXPLICIT:
173 # Padding is specified in a PAD operator which has been bypassed.
174 # The top and left padding are taken from the PAD; bottom and right are calculated.
175 top_pad, left_pad, _, _ = explicit_padding
176 bottom_pad = ypad - top_pad
177 right_pad = xpad - left_pad
Tim Hall79d07d22020-04-27 18:20:16 +0100178 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000179 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100180 padding = (top_pad, left_pad, bottom_pad, right_pad)
181 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
182 return padding, skirt
183
Tim Hallc30f4952020-06-15 20:47:35 +0100184
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200185def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
186 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000187 if padding_type == Padding.SAME:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200188 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
189 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200190 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
191 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200192 left_pad = max(kernel_width - 1 - right_pad, 0)
193 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000194 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200195 right_pad = max(kernel_width - 2, 0)
196 bottom_pad = max(kernel_height - 2, 0)
197 left_pad = kernel_width - 1
198 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200199 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000200 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200201 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200202 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200203 return padding, skirt
204
Tim Hall79d07d22020-04-27 18:20:16 +0100205
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200206def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200207 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100208 # flip the inputs
209 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000210 op.set_ifm_ofm_shapes()
Louis Verhaardaee5d752020-09-30 09:01:52 +0200211 op.type = Op.Conv2DBackpropInputSwitchedBias
Louis Verhaard69b84802020-12-16 12:02:28 +0100212 op.ifm.resampling_mode = resampling_mode.TRANSPOSE
Jacob Bohlincf7da102020-05-20 09:03:40 +0200213
214 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100215 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100216
217 return op
218
219
Charles Xu9a03fdf2020-07-02 15:12:40 +0200220# Convert the op to an elementwise add
221def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200222 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200223 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200224 op.attrs["resizebilinear"] = True
225 # Create an input tensor filled with zeros
226 shape = op.outputs[0].shape
227 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
228 tens.values = np.zeros(shape)
229 tens.quant_values = np.zeros(shape, np.uint8)
230 tens.quantization = QuantizationParameters(0.0, 255.0)
231 tens.quantization.scale_f32 = 1.0
232 tens.quantization.zero_point = 0
233 tens.consumer_list = [op]
234 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100235 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200236 # Set the add inputs
237 op.inputs[1] = op.inputs[0]
238 op.inputs[0] = tens
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000239 op.set_ifm_ofm_shapes()
Charles Xu9a03fdf2020-07-02 15:12:40 +0200240
241 return op
242
243
Charles Xu87c13502020-08-06 12:17:26 +0200244# Convert ResizeBilinear to a number of 2x2 pool ops
245def convert_resizebilinear_to_2x2_pool(op):
246 count = 0
247 pre_op = op
248 outputs = op.outputs
249
250 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
251 if op.attrs["align_corners"]:
252 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000253 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200254 else:
255 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000256 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200257 op.inputs[0].resampling_mode = resampling_mode.NEAREST
258
259 upscaled_shape = np.array(op.inputs[0].shape[1:3])
260 out_shape = np.array(op.outputs[0].shape[1:3])
261 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
262 return op
263
264 while (upscaled_shape < out_shape).all():
265 if count == 0:
266 scaled_op = pre_op
267 else:
268 scaled_op = op.clone("_{}".format(count))
269 scaled_op.inputs[0] = pre_op.outputs[0]
270
271 upscaled_shape = upscaled_shape * 2 - shape_modifier
272
273 if (upscaled_shape == out_shape).all():
274 scaled_op.outputs = outputs
275 scaled_op.outputs[0].ops = [scaled_op]
276 else:
277 shape = outputs[0].shape.copy()
278 shape[1:3] = upscaled_shape[0:2]
279 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
280 out_tens.quantization = op.outputs[0].quantization.clone()
281 out_tens.quantization.quant_min = np.iinfo(np.int16).min
282 out_tens.quantization.quant_max = np.iinfo(np.int16).max
283 scaled_op.set_output_tensor(out_tens)
284 pre_op = scaled_op
285 count += 1
286
287 # Setup the scale value
288 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
289 scaled_op.attrs["rescale"] = 128
290 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
291 scaled_op.attrs["rescale"] = 1 / 128
292 elif "rescale" in scaled_op.attrs:
293 del scaled_op.attrs["rescale"]
Patrik Gustavssoncc6915c2020-12-22 09:16:50 +0100294 scaled_op.set_ifm_ofm_shapes()
Charles Xu87c13502020-08-06 12:17:26 +0200295
296 return op
297
298
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200299def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200300 if op.type == Op.ResizeBilinear and op.run_on_npu:
Charles Xu87c13502020-08-06 12:17:26 +0200301 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200302 # Bypass nop resizebilinear
303 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200304 op.type = Op.Identity
Charles Xu87c13502020-08-06 12:17:26 +0200305 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
306 convert_resizebilinear_1x1_to_add(op)
307 else:
308 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200309
310 return op
311
312
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200313def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200314 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200315 # the list comprehension should return a list with a single tensor
316 # if it shouldn't, remove_passthrough_tensor will fail appropriately
317 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200318 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200319 return op
320
321
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200322def fixup_fully_connected_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200323 if op.type == Op.FullyConnected:
Tim Hall79d07d22020-04-27 18:20:16 +0100324 inp = op.inputs[0]
325 weights = op.inputs[1]
326
327 n_in_elems = weights.shape[-2]
328 elms = inp.elements()
329 batch_size = elms // n_in_elems
330 assert batch_size * n_in_elems == elms
331
332 desired_shape = [batch_size, n_in_elems]
333 if inp.shape != desired_shape:
334 # mismatch, insert a reshape to fix this.
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200335 op.set_input_tensor(create_reshape_tensor(inp, desired_shape), 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100336
337 return op
338
339
Diqing Zhong94457b12020-12-09 15:22:40 +0100340def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200341 if op.type == Op.FullyConnected:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200342 ifm = op.inputs[0]
343 ofm = op.outputs[0]
344 # Check if the FC is 2D and first dimension indicates batching
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100345 # TOD0 op.ifm_shape[0] > 1 is enough when refactory is complete
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000346 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 +0200347 n = ifm.shape[0]
348 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
349 h, w = batching_split.get(n, (1, n))
350
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200351 prev_op = ifm.ops[0]
352 desired_shape = [1, h, w, ifm.shape[-1]]
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000353 op.ifm_shapes[0] = Shape4D(desired_shape)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100354
Louis Verhaardaee5d752020-09-30 09:01:52 +0200355 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 +0200356 # There is a preceding Reshape
357 # Compare input of prev_op and input of op, to see if prev_op can be removed
358 ifm_prev_op = prev_op.inputs[0]
Tim Hall89567612020-10-27 11:57:57 +0000359 if ifm_prev_op.shape == ifm.shape and check_quantized_tens_scaling_equal(ifm_prev_op, ifm):
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200360 # prev_op can be removed
361 op.set_input_tensor(ifm_prev_op, 0)
362 else:
363 op.inputs[0].set_all_shapes(desired_shape)
364 prev_op.set_input_tensor(
365 create_const_tensor(prev_op.inputs[1].name, [1], DataType.int32, desired_shape), 1
366 )
367 prev_op.attrs["new_shape"] = desired_shape
368 else:
369 # Add reshape op to the input if there is no preceding reshape
370 ifm.consumer_list.remove(op)
371 op.set_input_tensor(create_reshape_tensor(ifm, desired_shape), 0)
372
373 # Reshape Weights to be 4D. IO becomes HWIO
374 weight_tensor = op.inputs[1]
375 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
376 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
377
378 desired_shape = [1, h, w, ofm.shape[-1]]
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000379 op.ofm_shapes[0] = Shape4D(desired_shape)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100380
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200381 if (
382 len(ofm.consumer_list) == 1
383 and ofm.consumer_list[0] is not None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200384 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200385 ):
386 # There is a subsequent Reshape
387 # Compare desired shape and output of consumer op, to see if consumer op can be removed
388 ofm_cons_op = ofm.consumer_list[0].outputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100389 if desired_shape == ofm_cons_op.shape and check_quantized_tens_scaling_equal(ofm, ofm_cons_op):
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200390 op.outputs[0] = ofm_cons_op
391 op.outputs[0].ops = [op]
392 else:
393 op.outputs[0].set_all_shapes(desired_shape)
394 else:
Diqing Zhong94457b12020-12-09 15:22:40 +0100395 # Add reshape op to the output
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200396 op.set_output_tensor(create_reshape_tensor(ofm, desired_shape, False))
397 return op
398
399
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200400def fixup_pack_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200401 if op.type == Op.Pack:
Tim Hall79d07d22020-04-27 18:20:16 +0100402 # Pack is also referred to as Stack
403 # Requires the rewrite_concat function to be called on the op afterwards
404 axis = int(op.attrs["axis"])
405 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
406
407 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100408 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100409
410 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100411 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100412 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100413
Louis Verhaardaee5d752020-09-30 09:01:52 +0200414 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100415 reshape_op.attrs["new_shape"] = desired_shape
416 reshape_op.inputs = [inp, new_shape_tens]
417 reshape_op.set_output_tensor(reshape_out)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000418 reshape_op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000419 DebugDatabase.add_optimised(op, reshape_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100420
421 op.inputs[idx] = reshape_out
422
Louis Verhaardaee5d752020-09-30 09:01:52 +0200423 op.type = Op.PackReshaped
Tim Hall79d07d22020-04-27 18:20:16 +0100424
425 return op
426
427
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200428def unfuse_activation_function(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200429 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100430 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200431 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200432 out_tens = op.outputs[0]
433 intermediate_tens = out_tens.clone("_act_intermediate")
434 act_op.set_output_tensor(out_tens)
435 act_op.add_input_tensor(intermediate_tens)
436 op.set_output_tensor(intermediate_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000437 act_op.set_ifm_ofm_shapes()
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200438
439 return op
440
Louis Verhaard8912c532020-09-30 12:11:49 +0200441
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100442def fixup_stridedslice_output(tens, arch, nng):
443 op = tens.ops[0]
Dwight Lidman73320a42020-11-05 10:34:41 +0100444 if op.run_on_npu and op.type == Op.StridedSlice:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100445 reshape_input_shape = tens.shape
446 new_axis_mask = op.attrs["new_axis_mask"]
447 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100448
Dwight Lidman73320a42020-11-05 10:34:41 +0100449 if shrink_axis_mask != 0:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100450 n = 0
451 axis = 0
452 while shrink_axis_mask:
453 prev_mask = shrink_axis_mask
454 n += 1
455 shrink_axis_mask &= shrink_axis_mask - 1
456 axis = int(math.log2(prev_mask - shrink_axis_mask))
457 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
458
459 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
460 op.attrs["shrink_axis_mask"] = 0
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100461 elif new_axis_mask != 0:
462 n = 0
463 axis = 0
464 while new_axis_mask:
465 prev_mask = new_axis_mask
466 n += 1
467 new_axis_mask &= new_axis_mask - 1
468 axis = int(math.log2(prev_mask - new_axis_mask))
469 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
470 new_axis_mask >>= 1
471
472 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
473 op.attrs["new_axis_mask"] = 0
Dwight Lidmandda21af2020-11-11 15:44:57 +0100474 else:
475 # Equal Rank StridedSlice, no need to insert reshape
476 return tens
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100477
478 # Construct 1 shape tensor to be used by all inserted reshape ops
479 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
480
481 for idx, out_tens in enumerate(op.outputs):
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000482 op.ofm_shapes[idx] = Shape4D(new_shape_tens.shape)
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100483 reshape_in = out_tens.clone("_reshaped")
484 reshape_in.set_all_shapes(reshape_input_shape)
485 reshape_in.ops = [op]
486
487 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
488 reshape_op.attrs["new_shape"] = reshape_input_shape
489 reshape_op.inputs = [reshape_in, new_shape_tens]
490 reshape_op.set_output_tensor(out_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000491 reshape_op.set_ifm_ofm_shapes()
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100492
493 op.outputs[idx] = reshape_in
494
495 return tens
496
497
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200498def fixup_unpack_output(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100499 op = tens.ops[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100500 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100501 # Unpack is also referred to as Unstack
502 # Requires the rewrite_split function to be called on the op afterwards
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100503 axis = int(op.attrs["axis"])
504 op.type = Op.UnpackReshaped
505 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100506
507 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100508 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100509
510 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100511 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100512 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100513 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100514
Louis Verhaardaee5d752020-09-30 09:01:52 +0200515 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100516 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100517 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100518 reshape_op.set_output_tensor(out_tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000519 reshape_op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000520 DebugDatabase.add_optimised(op, reshape_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100521
522 op.outputs[idx] = reshape_in
Tim Hall79d07d22020-04-27 18:20:16 +0100523 return tens
524
525
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200526def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200527 if op.run_on_npu:
528 if "padding" in op.attrs:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200529 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200530 kernel_size = op.inputs[1].shape[:2]
531 input_shape = op.inputs[0].shape
Louis Verhaardaee5d752020-09-30 09:01:52 +0200532 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200533 kernel_size = op.attrs["ksize"][1:3]
534 input_shape = op.inputs[0].shape
Jacob Bohlin90033f32020-08-28 15:45:44 +0200535 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000536 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100537
Louis Verhaardaee5d752020-09-30 09:01:52 +0200538 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200539 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
540 padding, skirt = calc_upscaled_padding_and_skirt(
541 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
542 )
543 else:
544 dilation_h, dilation_w = op.get_dilation_h_w()
545 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
546 padding, skirt = calc_padding_and_skirt(
Louis Verhaardae2d5532020-12-11 17:19:54 +0100547 op.attrs["padding"],
548 dilated_kernel_size,
549 op.attrs["strides"],
550 input_shape,
551 op.attrs.get("explicit_padding"),
Jacob Bohlin90033f32020-08-28 15:45:44 +0200552 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200553
Jacob Bohlin90033f32020-08-28 15:45:44 +0200554 op.attrs["explicit_padding"] = padding
555 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200556
Tim Hall79d07d22020-04-27 18:20:16 +0100557 return op
558
559
Tim Hall79d07d22020-04-27 18:20:16 +0100560# Check if the op can be reordered
561def get_prepend_op(op):
562 inp = op.inputs[0]
563 # The op should be reordered between prev_op and prep_op
564 prev_op = inp.ops[-1]
565 prep_op = None
566 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
567 prep_op = prev_op
568 inp = prev_op.inputs[0]
569 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100570 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 +0100571 return prep_op
572
573 return None
574
575
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200576def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100577 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
578 # the ofm depth equals the depth multipler.
579 # If those conditions are true, then we can perform a simple
580 # switch of the operator type (and weight order)
581
Louis Verhaardaee5d752020-09-30 09:01:52 +0200582 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Tim Hall79d07d22020-04-27 18:20:16 +0100583 ifm_tensor = op.inputs[0]
584 weight_tensor = op.inputs[1]
585 ofm_tensor = op.outputs[0]
586 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
587 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200588 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100589 del op.attrs["channel_multiplier"]
590 del op.attrs["depth_multiplier"]
591
592 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100593 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100594 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200595 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000596 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
597 f" ifm channels = {ifm_tensor.shape[3]}, ofm channels = {ofm_tensor.shape[3]}",
Tim Hall79d07d22020-04-27 18:20:16 +0100598 )
Tim Halle6ccd872020-11-09 16:46:37 +0000599 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100600 return op
601
602
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200603def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200604 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200605 weight_tensor = op.inputs[1]
606 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100607 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200608 weight_tensor.weight_transpose_depthwise = True
609
610 return op
611
612
Diqing Zhong016b8272020-12-16 16:46:06 +0100613def optimise_strided_conv(op, arch, nng):
614 stride_x, stride_y = op.get_kernel_stride()
615 ifm_tensor, _, weight_tensor, _ = op.get_ifm_ifm2_weights_ofm()
616
617 if (
618 op.type == Op.Conv2DBias
619 and op.op_index == 0
620 and stride_x == 2
621 and len(ifm_tensor.shape) == 4
622 and ifm_tensor.shape[3] <= 4
623 and ifm_tensor.shape[2] % 2 == 0
624 and weight_tensor is not None
625 and weight_tensor.shape[1] >= 2
626 ):
627 # IFM
628 ifm_reshaped = create_reshape_tensor(
629 ifm_tensor, [ifm_tensor.shape[0], ifm_tensor.shape[1], ifm_tensor.shape[2] // 2, ifm_tensor.shape[3] * 2]
630 )
631 op.set_input_tensor(ifm_reshaped, 0)
632
633 # Weights
634 weight_shape = weight_tensor.shape
635 if weight_shape[1] % 2 != 0:
636 weight_shape[1] = weight_shape[1] + 1
637 padded_array = np.zeros(weight_shape)
638 for i in range(weight_shape[0]):
639 padded_array[i] = np.vstack(
640 [
641 weight_tensor.quant_values[i],
642 np.full((1, weight_shape[2], weight_shape[3]), weight_tensor.quantization.zero_point),
643 ]
644 )
645 weight_tensor.quant_values = padded_array
646 weight_shape[1] //= 2
647 weight_shape[2] *= 2
648 weight_tensor.quant_values = np.reshape(weight_tensor.quant_values, weight_shape)
649 weight_tensor.set_all_shapes(weight_shape)
650 # If multiple copies of the weights are used, we could avoid
651 # them having the same address by changing the value_id
652 weight_tensor.value_id = uuid.uuid4()
653
654 # Strides
655 stride_x = 1
656 op.attrs.update({"stride_w": stride_x, "stride_h": stride_y, "strides": (1, stride_y, stride_x, 1)})
657
658 op.set_ifm_ofm_shapes()
659
660 return op
661
662
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200663def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100664 # Conv 1x1 can be equivalent to Fully Connected.
665 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
666 # caching/double buffering for the weights.
667 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200668 if op.type == Op.Conv2DBias:
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000669 h = op.ifm_shapes[0].height
670 w = op.ifm_shapes[0].width
Michael McGeagh8d939c02020-07-29 13:11:43 +0100671 kh, kw, _, _ = op.inputs[1].shape
672 if h == 1 and w == 1 and kh == 1 and kw == 1:
673 # Overwrite this op as a Fully Connected Op
674 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200675 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100676 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100677 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100678 }
679 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
680 weight_tensor = op.inputs[1]
681 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
682 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100683
Michael McGeagh8d939c02020-07-29 13:11:43 +0100684 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
685 # back to 4D afterwards as the next layer is expecting that shape
686 orig_ofm_tensor = op.outputs[0]
687 # 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})
688 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
689 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
690 fc_ofm_tensor.ops = [op]
691 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100692 reshape_name = op.name + "_reshape"
693 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200694 reshape_op = Operation(Op.Reshape, reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100695 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100696 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
697 reshape_op.set_output_tensor(orig_ofm_tensor)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000698 reshape_op.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100699
Michael McGeagh8d939c02020-07-29 13:11:43 +0100700 # Replace this ops OFM to point to the 2D tensor
701 op.outputs[0] = fc_ofm_tensor
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000702 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000703 # Record optimisation in debug database
704 DebugDatabase.add_optimised(op, reshape_op)
705 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100706 return op
707
708
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200709def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200710 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100711 ifm = op.inputs[0]
712 ofm = op.outputs[0]
713 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
714 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100715 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100716 # Override this op with its own primary op (avgpool)
717 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
718 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100719 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100720 # Tidy up and assign the ifm and ofm to the new op
721 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200722
723 # if not 4d, reshape ifm/ofm
724 if len(ifm.shape) < 4:
725 ifm_shaped = create_reshape_tensor(ifm, full_shape(4, ifm.shape, 1))
726 ifm = ifm_shaped
727 if len(ofm.shape) < 4:
728 ofm_shaped = create_reshape_tensor(ofm, full_shape(4, ofm.shape, 1), False)
729 ofm = ofm_shaped
730
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100731 relu_fused_op.add_input_tensor(ifm)
732 relu_fused_op.set_output_tensor(ofm)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000733 relu_fused_op.set_ifm_ofm_shapes()
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100734 op = relu_fused_op
735 return op
736
737
Tim Hall79d07d22020-04-27 18:20:16 +0100738# Reorder activation op if it's after the memory only operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200739def fixup_act_reorder(op, arch, nng):
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000740 if op.type.is_relu_op() or op.type in (Op.Sigmoid, Op.Tanh):
Tim Hall79d07d22020-04-27 18:20:16 +0100741 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100742 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100743 act_op = op.clone("_reordered")
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100744 act_op.ifm_shapes = list(op.ifm_shapes)
745 act_op.ofm_shapes = list(op.ofm_shapes)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200746
747 # There is only one input tensor, overwrite it
748 act_op.set_input_tensor(prep_op.inputs[0], 0)
749
Tim Hall79d07d22020-04-27 18:20:16 +0100750 act_op_out = act_op.inputs[0].clone("_acted")
751 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100752 act_op.set_output_tensor(act_op_out)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000753 act_op.ifm_shapes[0] = Shape4D(prep_op.inputs[0].shape)
754 act_op.ofm_shapes[0] = Shape4D(act_op_out.shape)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200755
756 # Update the consumer list
757 act_op_out.consumer_list = op.outputs[0].consumer_list.copy()
758 act_op_out.consumer_list.append(prep_op)
759
Tim Hall79d07d22020-04-27 18:20:16 +0100760 prep_op.inputs[0] = act_op_out
761 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
762
763 # Mark the op so that it will be removed as passthrough later on
Louis Verhaardaee5d752020-09-30 09:01:52 +0200764 op.type = Op.Identity
Tim Halle6ccd872020-11-09 16:46:37 +0000765
766 # Record optimisation in debug database
767 DebugDatabase.add_optimised(op, act_op)
768 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100769 return op
770
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200771
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200772def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200773 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200774 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200775 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
776 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
777 if diff > 0:
778 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
779 elif diff < 0:
780 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200781 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
782 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
783 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
784 ifm_tensor.storage_shape = ifm_tensor.shape
785 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
786 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
787 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
788 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200789 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100790
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200791
Tim Hall4e127762020-05-15 16:05:49 +0100792# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200793def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100794 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100795 eid = op.outputs[0].equivalence_id
796 for inp in op.inputs:
797 inp.equivalence_id = eid
798 return op
799
800
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100801def set_ifm_ofm_op_shapes(op, arch, nng):
802 if op.run_on_npu and op.type.needs_shapes():
803 if op.ifm_shapes or op.ofm_shapes:
804 # Shapes already set
805 return op
806 op.set_ifm_ofm_shapes()
807 return op
808
809
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200810def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200811 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200812 softmax = SoftMax(op)
813 op = softmax.get_graph()
814 return op
815
816
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200817def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100818 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100819
820 Input X For X = -1 or X > 0
821 | \ / This subgraph can be replaced with either
822 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
823 | /
824 Max
825 """
826
Louis Verhaardaee5d752020-09-30 09:01:52 +0200827 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100828 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200829 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100830 if len(muls) == 1:
831 mul = muls[0].ops[0]
832 elif len(muls) == 2:
833 # In the case both inputs are Muls, find the one with the same input as the Max
834 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
835 else:
836 # No Mul inputs
837 return op
838
839 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200840 mul_ofm = mul.outputs[0]
841 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100842 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200843 # make sure the Mul doesn't have a fused activation function
844 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100845 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200846 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100847 if ifm is None or ofm is None:
848 return op
849
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200850 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
851 return op
Tim Hall93582962020-09-09 21:58:15 +0100852 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 +0200853 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
854 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100855
856 # finds the branched input that goes to both the Max and the Mul
857 shared = set(op.inputs) & set(mul.inputs)
858 if len(shared) == 1:
859 shared_in = shared.pop()
860 # find the constant scalar input to the Mul
861 const_tens = (set(mul.inputs) - {shared_in}).pop()
862 # check that it is a scalar
863 if const_tens.shape != []:
864 return op
865 const = const_tens.ops[0]
866 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200867 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100868 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200869 # Remove the Mul from the shared input's consumers
870 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100871 else:
872 return op
873
874 val = const.outputs[0].values
875 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200876 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100877 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200878 # to produce bit exact results, the alpha is not enough;
879 # save additional scaling info in attr "alpha_scale", to be used as input
880 # to the LUT construction
881 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
882 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
883 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
884 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
885 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
886 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100887 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200888 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100889 else:
890 return op
891
Louis Verhaardaee5d752020-09-30 09:01:52 +0200892 op.type = new_op
893 op.name = op.name.replace("Maximum", new_op.name)
894 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100895 op.inputs = [shared_in]
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100896 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000897
898 # Record optimisation in debug database
899 DebugDatabase.add_optimised(op, op)
900
Tim Hall79d07d22020-04-27 18:20:16 +0100901 return op
902
903
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200904def convert_lrelu_to_mul_max(op, arch):
905 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
906 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200907 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100908 if ifm is None or ofm is None:
909 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200910
911 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200912 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200913 mul_alpha.add_input_tensor(ifm)
914 # Create const tensor containing alpha as scalar
915 alpha = op.attrs["alpha"]
916 quantization = ifm.quantization.clone()
917 quantization.min = 0
918 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
919 quantization.scale_f32 = alpha
920 quantization.zero_point = 0
921 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
922 mul_alpha.add_input_tensor(alpha_tens)
923 fm_alpha = ofm.clone(op.name + "_alpha")
924 mul_alpha.set_output_tensor(fm_alpha)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000925 mul_alpha.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000926 DebugDatabase.add_optimised(op, mul_alpha)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200927
Tim Hall93582962020-09-09 21:58:15 +0100928 if check_quantized_tens_scaling_equal(ifm, ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200929 # No identity multiplication is needed
930 fm_id = ifm
931 else:
932 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200933 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200934 mul_identity.add_input_tensor(ifm)
935 # Create const tensor containing identity as scalar
936 quantization = ifm.quantization.clone()
937 quantization.min = 0
938 quantization.max = quantization.quant_max - quantization.quant_min
939 quantization.scale_f32 = 1
940 quantization.zero_point = 0
941 identity_tens = create_const_tensor(
942 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
943 )
944 mul_identity.add_input_tensor(identity_tens)
945 fm_id = ofm.clone(op.name + "_id")
946 mul_identity.set_output_tensor(fm_id)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000947 mul_identity.set_ifm_ofm_shapes()
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100948 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200949
950 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200951 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200952 op.name = op.name.replace("LeakyRelu", "Maximum")
953 op.inputs = []
954 ifm.consumer_list.remove(op)
955 op.add_input_tensor(fm_alpha)
956 op.add_input_tensor(fm_id)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100957 op.set_ifm_ofm_shapes()
Tim Halle6ccd872020-11-09 16:46:37 +0000958
959 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200960 return op
961
962
Louis Verhaard2e186c72020-10-09 10:47:04 +0200963def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200964 # Rewrite the operation by Add with scalar 0 + LUT activation
965 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100966 if ifm is None:
967 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200968 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200969 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200970 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200971 # Mark as no-op to enable potential fusing optimizations
972 op.attrs["is_nop"] = True
973 # Create an input tensor containing scalar zero
974 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200975 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200976 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +0200977 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200978 op.add_input_tensor(tens)
patrik.gustavssoneeb85152020-12-21 17:10:40 +0000979 op.ifm_shapes.append(Shape4D(tens.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100980
Louis Verhaardf03bad32020-09-25 08:30:44 +0200981 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
982 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
983 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +0200984 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +0200985 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200986 op.set_activation_lut(lut_tensor)
Patrik Gustavssonc509d332020-12-22 13:53:52 +0100987 op.set_ifm_ofm_shapes()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200988 return op
989
990
Louis Verhaard2e186c72020-10-09 10:47:04 +0200991def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200992 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
993 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +0200994 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200995 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
996 return op
997 # Generate the LUT
998 ifm_scale = np.double(ifm.quantization.scale_f32)
999 ofm_scale = np.double(ofm.quantization.scale_f32)
1000 zp_in = ifm.quantization.zero_point
1001 zp_out = ofm.quantization.zero_point
1002 values = []
1003 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
1004 quantized_min = min(ix)
1005 quantized_max = max(ix)
1006 for x in ix:
1007 x_real = ifm_scale * (x - zp_in)
1008 y_real = fn(x_real)
1009 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
1010 lut_result = min(quantized_max, max(quantized_min, lut_result))
1011 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +02001012 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +02001013
1014
1015def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001016 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001017 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +02001018 alpha = op.attrs["alpha"]
1019 ifm_scale = np.double(ifm.quantization.scale_f32)
1020 ofm_scale = np.double(ofm.quantization.scale_f32)
1021 zp_in = ifm.quantization.zero_point
1022 zp_out = ofm.quantization.zero_point
1023 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
1024 alpha_scalar = 1
1025 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
1026 if "alpha_scaling" in op.attrs:
1027 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
1028 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
1029 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +02001030 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +02001031 quantized_min = min(ix)
1032 quantized_max = max(ix)
1033 for x in ix:
1034 if x < zp_in:
1035 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
1036 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
1037 )
1038 else:
1039 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
1040 lut_result = min(quantized_max, max(quantized_min, lut_result))
1041 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +02001042 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001043
1044
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001045def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001046 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +02001047 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001048 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001049 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001050 if ifm is None or ofm is None:
1051 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +02001052 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
1053 # use LUT for int8/uint8
1054 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +01001055 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +02001056 # use LeakyRelu unmodified for int16 with equal input/output scaling
1057 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001058 return convert_lrelu_to_mul_max(op, arch)
1059
1060
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001061def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +02001062 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +02001063 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001064 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +02001065 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +02001066 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +02001067 return op
1068
1069
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001070def remove_unwanted_reshapes(op, arch, nng):
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001071 # Try to remove reshapes enclosing ElementWise operator with only one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +02001072 if not op.run_on_npu or not op.type.is_elementwise_op():
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001073 return op
1074
1075 # Check if the ElementWise operator only have one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +02001076 non_const_tens = [x for x in op.inputs if x.ops[0].type != Op.Const]
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001077 if len(non_const_tens) != 1:
1078 return op
1079 ifm = non_const_tens[0]
1080
1081 # Check if operation is enclosed by Reshapes that can be removed
1082 ofm = op.outputs[0]
1083 prev_op = ifm.ops[0]
1084 if (
1085 len(ifm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001086 and prev_op.type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001087 and len(ofm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001088 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001089 ):
1090 # Operation is enclosed by reshapes, check if they can be removed
Louis Verhaardaee5d752020-09-30 09:01:52 +02001091 prev_op_ifm, prev_op_ofm = prev_op.get_ifm_ofm()
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001092 cons_op = ofm.consumer_list[0]
1093 cons_op_ifm = ofm
1094 cons_op_ofm = cons_op.outputs[0]
1095 if len(prev_op_ifm.shape) == len(cons_op_ofm.shape):
1096 # Check if quantization is the same in the input and output for the reshape ops
Tim Hall93582962020-09-09 21:58:15 +01001097 if check_quantized_tens_scaling_equal(prev_op_ifm, prev_op_ofm) and check_quantized_tens_scaling_equal(
1098 cons_op_ifm, cons_op_ofm
1099 ):
Patrik Gustavsson7ad862a2020-09-29 14:09:43 +02001100 op.set_input_tensor(prev_op_ifm, 0)
1101 op.set_output_tensor(cons_op_ofm)
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001102 return op
1103
1104
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001105def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001106 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001107 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001108 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001109 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001110 if ifm is None or ofm is None:
1111 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001112 # finds the input(s) to the operation
1113 prev_op = ifm.ops[0]
1114 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1115 fuse = (
1116 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001117 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001118 and len(ifm.ops) == 1
1119 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001120 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001121 )
1122 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1123 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1124 # LUT currently only works correctly for elementwise ops
1125 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001126 if not fuse:
1127 return op
1128 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001129 prev_op.activation = op.activation
1130 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001131 if op.activation_lut is not None:
1132 prev_op.set_activation_lut(op.activation_lut)
1133 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001134 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001135 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001136 return op
1137
1138
Louis Verhaardae2d5532020-12-11 17:19:54 +01001139def optimise_pad(op, arch, nng):
1140 """
1141 Converts tens1 -> PAD -> tens2 -> CONV to tens1 -> CONV
1142 if both operations can be run on the NPU.
1143 """
1144 if (
1145 (op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op())
1146 and op.run_on_npu
1147 and op.attrs["padding"] == Padding.VALID
1148 ):
1149 pad_op = op.ifm.ops[0]
1150 if pad_op.type != Op.Pad or not pad_op.run_on_npu:
1151 return op
1152 # Bypass the PAD operator
1153 op.set_input_tensor(pad_op.ifm, 0)
1154 # Adjust the padding attributes of the convolution operator
1155 op.attrs["padding"] = Padding.EXPLICIT
1156 padding = pad_op.inputs[1].values # 4x2 tensor, first dimension is N, H, W, C
1157 top, left, bottom, right = (padding[1][0], padding[2][0], padding[1][1], padding[2][1])
1158 op.attrs["explicit_padding"] = (top, left, bottom, right)
1159 op.set_ifm_ofm_shapes()
1160 return op
1161
1162
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001163def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001164 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001165 input_tensor = op.inputs[0]
1166 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
1167 out_shape = op.outputs[0].shape[1:3]
1168 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
1169 # this means the output is supposed to be a x2 upscale,
1170 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001171 op.attrs["padding"] = Padding.SAME
Dwight Lidman42fed942020-05-29 09:37:03 +02001172 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
1173 # here we can just run the avg pool without padding and
1174 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001175 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001176 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001177 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001178 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001179 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001180 return op
1181
1182
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001183def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001184 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001185 # Op has no bias, add bias tensor filled with zeros
1186 nr_biases = op.inputs[1].shape[-1]
1187 bias_values = [0] * nr_biases
1188 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1189 bias_tensor.quant_values = bias_tensor.values
1190 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001191
1192 return op
1193
1194
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001195def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001196 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1197 return op
1198
1199
Tim Halle6ccd872020-11-09 16:46:37 +00001200def _record_optimised(op, arch):
1201 if op.type != Op.Const:
1202 DebugDatabase.add_optimised(op, op)
1203
1204
Tim Hall79d07d22020-04-27 18:20:16 +01001205def optimise_graph_a(nng, arch, verbose_graph=False):
1206 if verbose_graph:
1207 nng.print_graph()
1208
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001209 pre_process_list = [
1210 supported_operator_check,
1211 set_ifm_ofm_op_shapes,
1212 # TODO: memory-only Op removal
1213 ]
1214
1215 for idx, sg in enumerate(nng.subgraphs):
1216 # rewrite graph pass
1217 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1218 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1219 )
1220
Tim Hall79d07d22020-04-27 18:20:16 +01001221 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001222 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001223 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001224 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001225 convert_softmax,
Diqing Zhong016b8272020-12-16 16:46:06 +01001226 optimise_strided_conv,
Tim Hall79d07d22020-04-27 18:20:16 +01001227 fixup_fully_connected_input,
Diqing Zhong94457b12020-12-09 15:22:40 +01001228 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001229 fixup_pack_input,
Fredrik Svedberg0f98b362020-09-29 10:00:39 +02001230 unfuse_activation_function,
Tim Hall79d07d22020-04-27 18:20:16 +01001231 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001232 fixup_relus_with_differing_ifm_ofm_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +01001233 fixup_act_reorder,
Charles Xu78792222020-05-13 10:15:26 +02001234 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +02001235 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001236 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001237 fixup_bias_tensors,
Dwight Lidmanc3862c22020-09-14 15:22:33 +02001238 convert_nop_split_to_identity,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001239 convert_mul_max_to_abs_or_lrelu,
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001240 remove_unwanted_reshapes,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001241 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001242 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001243 ]
1244
1245 for idx, sg in enumerate(nng.subgraphs):
1246 # rewrite graph pass
1247 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001248 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001249 )
1250
1251 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001252 # remove passthrough tensors and attempt further optimizations
1253 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Louis Verhaardae2d5532020-12-11 17:19:54 +01001254 nng,
1255 sg,
1256 arch,
1257 [remove_passthrough_tensor],
1258 [fuse_activation_function_with_prev, optimise_pad, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001259 )
Tim Hall79d07d22020-04-27 18:20:16 +01001260
Tim Halle6ccd872020-11-09 16:46:37 +00001261 # Post-optimisation operator debug tracing
1262 for sg in nng.subgraphs:
1263 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [_record_optimised])
1264
Tim Hall79d07d22020-04-27 18:20:16 +01001265 if verbose_graph:
1266 nng.print_graph()
1267 return nng
1268
Diego Russoea6111a2020-04-14 18:41:58 +01001269
Tim Hall79d07d22020-04-27 18:20:16 +01001270def optimise_graph_b(nng, arch, verbose_graph=False):
1271 if verbose_graph:
1272 nng.print_graph()
1273
1274 for idx, sg in enumerate(nng.subgraphs):
1275 # combined rewrite graph pass
Dwight Lidmanc6ac1942020-10-02 14:55:45 +02001276 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
patrik.gustavssoneeb85152020-12-21 17:10:40 +00001277 nng, sg, arch, [fixup_unpack_output, fixup_stridedslice_output, rewrite_concat, rewrite_split], [],
Dwight Lidmanc6ac1942020-10-02 14:55:45 +02001278 )
Tim Hall79d07d22020-04-27 18:20:16 +01001279
1280 if verbose_graph:
1281 nng.print_graph()
1282 return nng