blob: fdb0fae006fa1a428ed82738ccadd32e4991e12f [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
Fredrik Svedberga0c36242020-06-03 15:43:31 +020040from .softmax import SoftMax
Tim Hall93582962020-09-09 21:58:15 +010041from .tensor import check_quantized_tens_scaling_equal
Michael McGeaghc5b549b2020-08-07 11:54:28 +010042from .tensor import create_const_tensor
43from .tensor import create_reshape_tensor
Charles Xu9a03fdf2020-07-02 15:12:40 +020044from .tensor import QuantizationParameters
Diego Russoe8a10452020-04-21 17:39:10 +010045from .tensor import Tensor
Michael McGeagh7a6f8432020-12-02 15:29:22 +000046from .tflite_mapping import optype_to_builtintype
Tim Hall79d07d22020-04-27 18:20:16 +010047
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000048passthrough_nodes = (Op.Identity,)
Tim Hall79d07d22020-04-27 18:20:16 +010049
Michael McGeaghf3e3ad72020-12-02 12:39:03 +000050memory_only_ops = (Op.Reshape,)
Michael McGeagh11b0bdb2020-09-08 11:07:35 +010051
Tim Hall79d07d22020-04-27 18:20:16 +010052
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020053def remove_passthrough_tensor(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +010054 if len(tens.ops) == 1 and tens.ops[0].type in passthrough_nodes:
55 assert len(tens.ops[0].inputs) == 1
56 tens = tens.ops[0].inputs[0]
57 return tens
58
59
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +020060def rewrite_concat(tens, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +020061 if len(tens.ops) == 1 and tens.ops[0].type.is_concat_op():
Tim Hall79d07d22020-04-27 18:20:16 +010062 concat_op = tens.ops[0]
63 if tens != concat_op.outputs[0]:
64 return tens # don't attempt to rewrite the min/max outputs of QuantizedConcat
65
66 # Not supported so leave it and run on CPU
67 if not concat_op.run_on_npu:
68 return tens
69
70 inputs, axis = concat_op.get_concat_inputs_axis()
71
72 tens.ops = []
73 offset = 0
74 for idx, inp in enumerate(inputs):
Louis Verhaardaee5d752020-09-30 09:01:52 +020075 new_op = Operation(Op.ConcatSliceWrite, concat_op.name + str(idx))
Tim Hall79d07d22020-04-27 18:20:16 +010076 new_op.inputs = [inp]
77 new_op.outputs = [tens]
Patrik Gustavsson2349d422020-12-01 16:02:29 +010078 new_op.attrs["concat_axis"] = axis + (4 - len(inp.shape))
Tim Hall79d07d22020-04-27 18:20:16 +010079 new_op.attrs["concat_start"] = offset
80 offset += inp.shape[axis]
81 new_op.attrs["concat_end"] = offset
82 new_op.run_on_npu = True
83 tens.ops.append(new_op)
Tim Halle6ccd872020-11-09 16:46:37 +000084 DebugDatabase.add_optimised(concat_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +010085 assert tens.shape[axis] == offset
86
Patrik Gustavsson29d568e2020-08-18 10:11:21 +020087 # If axis corresponds to C-dimension, NHCWB16 can only be used in the output if all the concat_start's are a
88 # multiple of 16. This as, it is only then the address offset for the ofm, for all operations, will be 16 byte
89 # 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 +020090 # and those addresses are always 16 byte aligned due to the NHCWB16 format.
Patrik Gustavsson6c97e9a2020-09-23 11:02:18 +020091 if axis == -1 or axis == (len(tens.shape) - 1):
Patrik Gustavsson458a2082020-08-13 13:41:05 +020092 for op in tens.ops:
93 if op.attrs["concat_start"] % 16 != 0:
94 tens.avoid_NHCWB16 = True
95 break
96
Tim Hall79d07d22020-04-27 18:20:16 +010097 return tens
98
99
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200100def rewrite_split(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100101
Louis Verhaardaee5d752020-09-30 09:01:52 +0200102 if len(tens.ops) == 1 and tens.ops[0].type.is_split_op():
Tim Hall79d07d22020-04-27 18:20:16 +0100103 split_op = tens.ops[0]
104
105 # Not supported so leave it and run on CPU
106 if not split_op.run_on_npu:
107 return tens
108
109 inp, outputs, axis, offset_start, offset_end = split_op.get_split_inputs_axis()
110
111 tens.ops = []
Louis Verhaardaee5d752020-09-30 09:01:52 +0200112 new_op = Operation(Op.SplitSliceRead, split_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100113 new_op.inputs = [inp]
Tim Hall79d07d22020-04-27 18:20:16 +0100114
115 # For Split the offset cannot be extracted from the tensor so it has to
116 # be calculated from the index of the output tensor
Diego Russoea6111a2020-04-14 18:41:58 +0100117 if axis is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100118 # Get the start and end of the split
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100119 offset_start = [0] * 4
120 for idx, out in enumerate(outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100121 if out == tens:
122 break
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100123 axis_4D = axis + (4 - len(out.shape))
124 offset_start[axis_4D] += split_op.ofm_shapes[idx][axis_4D]
Tim Hall79d07d22020-04-27 18:20:16 +0100125
Patrik Gustavssoneebb1c22020-08-18 15:03:04 +0200126 # If start offset is not a multiple of 16 in the C-dimension, NHCWB16 need to be avoided in the input
127 if (offset_start[-1] % 16) != 0:
128 inp.avoid_NHCWB16 = True
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100129 else:
130 offset_start = full_shape(4, offset_start, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100131
132 new_op.attrs["split_start"] = offset_start
Tim Hall79d07d22020-04-27 18:20:16 +0100133 new_op.run_on_npu = True
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100134 new_op.set_output_tensor(tens)
Tim Halle6ccd872020-11-09 16:46:37 +0000135 DebugDatabase.add_optimised(split_op, new_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100136
137 return tens
138
139
140def needed_total_padding(input_size, stride, filter_size):
141 out_size = (input_size + stride - 1) // stride
142 needed_input = (out_size - 1) * stride + filter_size
143 total_padding = max(0, needed_input - input_size)
144 return total_padding
145
146
147def calc_padding_and_skirt(padding_type, kernel_size, stride, input_dims):
148 ypad = needed_total_padding(int(input_dims[1]), int(stride[1]), int(kernel_size[0]))
149 xpad = needed_total_padding(int(input_dims[2]), int(stride[2]), int(kernel_size[1]))
Michael McGeagh16895482020-12-14 15:51:20 +0000150 if padding_type == Padding.SAME:
Tim Hall79d07d22020-04-27 18:20:16 +0100151 left_pad = (xpad + 0) // 2
152 right_pad = (xpad + 1) // 2
153 top_pad = (ypad + 0) // 2
154 bottom_pad = (ypad + 1) // 2
Michael McGeagh16895482020-12-14 15:51:20 +0000155 elif padding_type == Padding.VALID:
Tim Hall79d07d22020-04-27 18:20:16 +0100156 left_pad = 0
157 right_pad = 0
158 top_pad = 0
159 bottom_pad = 0
160 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000161 raise UnsupportedFeatureError(f"Unknown padding")
Tim Hall79d07d22020-04-27 18:20:16 +0100162 padding = (top_pad, left_pad, bottom_pad, right_pad)
163 skirt = (top_pad, left_pad, ypad - top_pad, xpad - left_pad)
164 return padding, skirt
165
Tim Hallc30f4952020-06-15 20:47:35 +0100166
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200167def calc_upscaled_padding_and_skirt(padding_type, kernel_size, stride, input_dims, upscaling_factor):
168 kernel_height, kernel_width = kernel_size[0], kernel_size[1]
Michael McGeagh16895482020-12-14 15:51:20 +0000169 if padding_type == Padding.SAME:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200170 ypad = needed_total_padding(int(input_dims[1]) * upscaling_factor, int(stride[1]), int(kernel_height))
171 xpad = needed_total_padding(int(input_dims[2]) * upscaling_factor, int(stride[2]), int(kernel_width))
Jacob Bohlind47cc272020-08-24 11:42:14 +0200172 right_pad = max(((xpad + 1) // upscaling_factor) - 1, 0)
173 bottom_pad = max(((ypad + 1) // upscaling_factor) - 1, 0)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200174 left_pad = max(kernel_width - 1 - right_pad, 0)
175 top_pad = max(kernel_height - 1 - bottom_pad, 0)
Michael McGeagh16895482020-12-14 15:51:20 +0000176 elif padding_type == Padding.VALID:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200177 right_pad = max(kernel_width - 2, 0)
178 bottom_pad = max(kernel_height - 2, 0)
179 left_pad = kernel_width - 1
180 top_pad = kernel_height - 1
Jacob Bohlincf7da102020-05-20 09:03:40 +0200181 else:
Michael McGeagh16895482020-12-14 15:51:20 +0000182 raise UnsupportedFeatureError(f"Unknown padding")
Jacob Bohlincf7da102020-05-20 09:03:40 +0200183 padding = (top_pad, left_pad, bottom_pad, right_pad)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200184 skirt = padding
Jacob Bohlincf7da102020-05-20 09:03:40 +0200185 return padding, skirt
186
Tim Hall79d07d22020-04-27 18:20:16 +0100187
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200188def fixup_conv2d_backprop(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200189 if op.type == Op.Conv2DBackpropInput:
Tim Hall79d07d22020-04-27 18:20:16 +0100190 # flip the inputs
191 op.inputs[0], op.inputs[2] = op.inputs[2], op.inputs[0]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200192 op.type = Op.Conv2DBackpropInputSwitchedBias
Jacob Bohlincf7da102020-05-20 09:03:40 +0200193
194 # Update strides
Tim Hallc30f4952020-06-15 20:47:35 +0100195 op.attrs.update({"stride_w": 1, "stride_h": 1, "strides": (1, 1, 1, 1)})
Tim Hall79d07d22020-04-27 18:20:16 +0100196
197 return op
198
199
Charles Xu9a03fdf2020-07-02 15:12:40 +0200200# Convert the op to an elementwise add
201def convert_resizebilinear_1x1_to_add(op):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200202 op.type = Op.Add
Charles Xu9a03fdf2020-07-02 15:12:40 +0200203 op.name = op.name + "_add"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200204 op.attrs["resizebilinear"] = True
205 # Create an input tensor filled with zeros
206 shape = op.outputs[0].shape
207 tens = Tensor(shape, op.inputs[0].dtype, op.inputs[1].name + "_add")
208 tens.values = np.zeros(shape)
209 tens.quant_values = np.zeros(shape, np.uint8)
210 tens.quantization = QuantizationParameters(0.0, 255.0)
211 tens.quantization.scale_f32 = 1.0
212 tens.quantization.zero_point = 0
213 tens.consumer_list = [op]
214 tens_op = op.inputs[1].ops[0]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100215 tens_op.set_output_tensor(tens)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200216 # Set the add inputs
217 op.inputs[1] = op.inputs[0]
218 op.inputs[0] = tens
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100219 op.ifm_shapes = []
220 op.ofm_shapes = []
Charles Xu9a03fdf2020-07-02 15:12:40 +0200221
222 return op
223
224
Charles Xu87c13502020-08-06 12:17:26 +0200225# Convert ResizeBilinear to a number of 2x2 pool ops
226def convert_resizebilinear_to_2x2_pool(op):
227 count = 0
228 pre_op = op
229 outputs = op.outputs
230
231 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
232 if op.attrs["align_corners"]:
233 shape_modifier = 1
Michael McGeagh16895482020-12-14 15:51:20 +0000234 op.attrs["padding"] = Padding.VALID
Charles Xu87c13502020-08-06 12:17:26 +0200235 else:
236 shape_modifier = 0
Michael McGeagh16895482020-12-14 15:51:20 +0000237 op.attrs["padding"] = Padding.SAME
Charles Xu87c13502020-08-06 12:17:26 +0200238 op.inputs[0].resampling_mode = resampling_mode.NEAREST
239
240 upscaled_shape = np.array(op.inputs[0].shape[1:3])
241 out_shape = np.array(op.outputs[0].shape[1:3])
242 if (upscaled_shape == upscaled_shape * 2 - shape_modifier).all():
243 return op
244
245 while (upscaled_shape < out_shape).all():
246 if count == 0:
247 scaled_op = pre_op
248 else:
249 scaled_op = op.clone("_{}".format(count))
250 scaled_op.inputs[0] = pre_op.outputs[0]
251
252 upscaled_shape = upscaled_shape * 2 - shape_modifier
253
254 if (upscaled_shape == out_shape).all():
255 scaled_op.outputs = outputs
256 scaled_op.outputs[0].ops = [scaled_op]
257 else:
258 shape = outputs[0].shape.copy()
259 shape[1:3] = upscaled_shape[0:2]
260 out_tens = Tensor(shape, DataType.int16, "{}_{}".format(op.outputs[0].name, count))
261 out_tens.quantization = op.outputs[0].quantization.clone()
262 out_tens.quantization.quant_min = np.iinfo(np.int16).min
263 out_tens.quantization.quant_max = np.iinfo(np.int16).max
264 scaled_op.set_output_tensor(out_tens)
265 pre_op = scaled_op
266 count += 1
267
268 # Setup the scale value
269 if scaled_op.inputs[0].dtype.bits == 8 and scaled_op.outputs[0].dtype.bits == 16:
270 scaled_op.attrs["rescale"] = 128
271 elif scaled_op.inputs[0].dtype.bits == 16 and scaled_op.outputs[0].dtype.bits == 8:
272 scaled_op.attrs["rescale"] = 1 / 128
273 elif "rescale" in scaled_op.attrs:
274 del scaled_op.attrs["rescale"]
275
276 return op
277
278
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200279def fixup_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200280 if op.type == Op.ResizeBilinear and op.run_on_npu:
Charles Xu87c13502020-08-06 12:17:26 +0200281 if op.inputs[0].shape == op.outputs[0].shape:
Charles Xu36ffaf32020-08-05 15:40:44 +0200282 # Bypass nop resizebilinear
283 op.inputs = op.inputs[:1]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200284 op.type = Op.Identity
Charles Xu87c13502020-08-06 12:17:26 +0200285 elif op.inputs[0].shape[1] == 1 and op.inputs[0].shape[2] == 1:
286 convert_resizebilinear_1x1_to_add(op)
287 else:
288 convert_resizebilinear_to_2x2_pool(op)
Charles Xu9a03fdf2020-07-02 15:12:40 +0200289
290 return op
291
292
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200293def convert_nop_split_to_identity(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200294 if op.type == Op.Split and op.attrs.get("num_splits") == 1:
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200295 # the list comprehension should return a list with a single tensor
296 # if it shouldn't, remove_passthrough_tensor will fail appropriately
297 op.inputs = [i for i in op.inputs if i.shape == op.outputs[0].shape]
Louis Verhaardaee5d752020-09-30 09:01:52 +0200298 op.type = Op.Identity
Dwight Lidmanc3862c22020-09-14 15:22:33 +0200299 return op
300
301
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200302def fixup_fully_connected_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200303 if op.type == Op.FullyConnected:
Tim Hall79d07d22020-04-27 18:20:16 +0100304 inp = op.inputs[0]
305 weights = op.inputs[1]
306
307 n_in_elems = weights.shape[-2]
308 elms = inp.elements()
309 batch_size = elms // n_in_elems
310 assert batch_size * n_in_elems == elms
311
312 desired_shape = [batch_size, n_in_elems]
313 if inp.shape != desired_shape:
314 # mismatch, insert a reshape to fix this.
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200315 op.set_input_tensor(create_reshape_tensor(inp, desired_shape), 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100316
317 return op
318
319
Diqing Zhong94457b12020-12-09 15:22:40 +0100320def convert_batched_fc_shape(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200321 if op.type == Op.FullyConnected:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200322 ifm = op.inputs[0]
323 ofm = op.outputs[0]
324 # Check if the FC is 2D and first dimension indicates batching
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100325 # TOD0 op.ifm_shape[0] > 1 is enough when refactory is complete
326 if len(ifm.shape) == len(ofm.shape) == 2 and ifm.shape[0] > 1 and op.ifm_shapes[0][0] > 1:
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200327 n = ifm.shape[0]
328 batching_split = {4: (2, 2), 8: (2, 4), 16: (4, 4)}
329 h, w = batching_split.get(n, (1, n))
330
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200331 prev_op = ifm.ops[0]
332 desired_shape = [1, h, w, ifm.shape[-1]]
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100333 op.ifm_shapes[0] = desired_shape
334
Louis Verhaardaee5d752020-09-30 09:01:52 +0200335 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 +0200336 # There is a preceding Reshape
337 # Compare input of prev_op and input of op, to see if prev_op can be removed
338 ifm_prev_op = prev_op.inputs[0]
Tim Hall89567612020-10-27 11:57:57 +0000339 if ifm_prev_op.shape == ifm.shape and check_quantized_tens_scaling_equal(ifm_prev_op, ifm):
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200340 # prev_op can be removed
341 op.set_input_tensor(ifm_prev_op, 0)
342 else:
343 op.inputs[0].set_all_shapes(desired_shape)
344 prev_op.set_input_tensor(
345 create_const_tensor(prev_op.inputs[1].name, [1], DataType.int32, desired_shape), 1
346 )
347 prev_op.attrs["new_shape"] = desired_shape
348 else:
349 # Add reshape op to the input if there is no preceding reshape
350 ifm.consumer_list.remove(op)
351 op.set_input_tensor(create_reshape_tensor(ifm, desired_shape), 0)
352
353 # Reshape Weights to be 4D. IO becomes HWIO
354 weight_tensor = op.inputs[1]
355 weight_tensor.quant_values = np.expand_dims(np.expand_dims(weight_tensor.quant_values, axis=0), axis=0)
356 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
357
358 desired_shape = [1, h, w, ofm.shape[-1]]
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100359 op.ofm_shapes[0] = desired_shape
360
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200361 if (
362 len(ofm.consumer_list) == 1
363 and ofm.consumer_list[0] is not None
Louis Verhaardaee5d752020-09-30 09:01:52 +0200364 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200365 ):
366 # There is a subsequent Reshape
367 # Compare desired shape and output of consumer op, to see if consumer op can be removed
368 ofm_cons_op = ofm.consumer_list[0].outputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100369 if desired_shape == ofm_cons_op.shape and check_quantized_tens_scaling_equal(ofm, ofm_cons_op):
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200370 op.outputs[0] = ofm_cons_op
371 op.outputs[0].ops = [op]
372 else:
373 op.outputs[0].set_all_shapes(desired_shape)
374 else:
Diqing Zhong94457b12020-12-09 15:22:40 +0100375 # Add reshape op to the output
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200376 op.set_output_tensor(create_reshape_tensor(ofm, desired_shape, False))
377 return op
378
379
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200380def fixup_pack_input(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200381 if op.type == Op.Pack:
Tim Hall79d07d22020-04-27 18:20:16 +0100382 # Pack is also referred to as Stack
383 # Requires the rewrite_concat function to be called on the op afterwards
384 axis = int(op.attrs["axis"])
385 desired_shape = op.inputs[0].shape[:axis] + [1] + op.inputs[0].shape[axis:]
386
387 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100388 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, desired_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100389
390 for idx, inp in enumerate(op.inputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100391 reshape_out = inp.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100392 reshape_out.set_all_shapes(desired_shape)
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100393
Louis Verhaardaee5d752020-09-30 09:01:52 +0200394 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100395 reshape_op.attrs["new_shape"] = desired_shape
396 reshape_op.inputs = [inp, new_shape_tens]
397 reshape_op.set_output_tensor(reshape_out)
Tim Halle6ccd872020-11-09 16:46:37 +0000398 DebugDatabase.add_optimised(op, reshape_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100399
400 op.inputs[idx] = reshape_out
401
Louis Verhaardaee5d752020-09-30 09:01:52 +0200402 op.type = Op.PackReshaped
Tim Hall79d07d22020-04-27 18:20:16 +0100403
404 return op
405
406
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200407def unfuse_activation_function(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200408 if op.type == Op.ConcatTFLite and op.run_on_npu and op.activation is not None:
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100409 act_op = Operation(op.activation.op_type, op.name + op.activation.op_type.name)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200410 op.activation = None
Fredrik Svedberg0f98b362020-09-29 10:00:39 +0200411 out_tens = op.outputs[0]
412 intermediate_tens = out_tens.clone("_act_intermediate")
413 act_op.set_output_tensor(out_tens)
414 act_op.add_input_tensor(intermediate_tens)
415 op.set_output_tensor(intermediate_tens)
416
417 return op
418
Louis Verhaard8912c532020-09-30 12:11:49 +0200419
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100420def fixup_stridedslice_output(tens, arch, nng):
421 op = tens.ops[0]
Dwight Lidman73320a42020-11-05 10:34:41 +0100422 if op.run_on_npu and op.type == Op.StridedSlice:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100423 reshape_input_shape = tens.shape
424 new_axis_mask = op.attrs["new_axis_mask"]
425 shrink_axis_mask = op.attrs["shrink_axis_mask"]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100426
Dwight Lidman73320a42020-11-05 10:34:41 +0100427 if shrink_axis_mask != 0:
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100428 n = 0
429 axis = 0
430 while shrink_axis_mask:
431 prev_mask = shrink_axis_mask
432 n += 1
433 shrink_axis_mask &= shrink_axis_mask - 1
434 axis = int(math.log2(prev_mask - shrink_axis_mask))
435 reshape_input_shape = reshape_input_shape[:axis] + [1] + reshape_input_shape[axis:]
436
437 assert len(tens.shape) == (len(op.inputs[0].shape) - n)
438 op.attrs["shrink_axis_mask"] = 0
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100439 elif new_axis_mask != 0:
440 n = 0
441 axis = 0
442 while new_axis_mask:
443 prev_mask = new_axis_mask
444 n += 1
445 new_axis_mask &= new_axis_mask - 1
446 axis = int(math.log2(prev_mask - new_axis_mask))
447 reshape_input_shape = reshape_input_shape[:axis] + reshape_input_shape[(axis + 1) :]
448 new_axis_mask >>= 1
449
450 assert len(tens.shape) == (len(op.inputs[0].shape) + n)
451 op.attrs["new_axis_mask"] = 0
Dwight Lidmandda21af2020-11-11 15:44:57 +0100452 else:
453 # Equal Rank StridedSlice, no need to insert reshape
454 return tens
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100455
456 # Construct 1 shape tensor to be used by all inserted reshape ops
457 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
458
459 for idx, out_tens in enumerate(op.outputs):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100460 op.ofm_shapes[idx] = new_shape_tens
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100461 reshape_in = out_tens.clone("_reshaped")
462 reshape_in.set_all_shapes(reshape_input_shape)
463 reshape_in.ops = [op]
464
465 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
466 reshape_op.attrs["new_shape"] = reshape_input_shape
467 reshape_op.inputs = [reshape_in, new_shape_tens]
468 reshape_op.set_output_tensor(out_tens)
469
470 op.outputs[idx] = reshape_in
471
472 return tens
473
474
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200475def fixup_unpack_output(tens, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100476 op = tens.ops[0]
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100477 if op.run_on_npu and op.type == Op.Unpack:
Tim Hall79d07d22020-04-27 18:20:16 +0100478 # Unpack is also referred to as Unstack
479 # Requires the rewrite_split function to be called on the op afterwards
Diqing Zhongc7c0b1b2020-10-26 11:45:25 +0100480 axis = int(op.attrs["axis"])
481 op.type = Op.UnpackReshaped
482 reshape_input_shape = tens.shape[:axis] + [1] + tens.shape[axis:]
Tim Hall79d07d22020-04-27 18:20:16 +0100483
484 # Construct 1 shape tensor to be used by all inserted reshape ops
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100485 new_shape_tens = create_const_tensor(op.name + "_reshape_shape", [1], DataType.int32, tens.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100486
487 for idx, out_tens in enumerate(op.outputs):
Tim Hall79d07d22020-04-27 18:20:16 +0100488 reshape_in = out_tens.clone("_reshaped")
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100489 reshape_in.set_all_shapes(reshape_input_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100490 reshape_in.ops = [op]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100491
Louis Verhaardaee5d752020-09-30 09:01:52 +0200492 reshape_op = Operation(Op.Reshape, "{}{}_reshape".format(op.name, idx))
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100493 reshape_op.attrs["new_shape"] = reshape_input_shape
Tim Hall79d07d22020-04-27 18:20:16 +0100494 reshape_op.inputs = [reshape_in, new_shape_tens]
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100495 reshape_op.set_output_tensor(out_tens)
Tim Halle6ccd872020-11-09 16:46:37 +0000496 DebugDatabase.add_optimised(op, reshape_op)
Tim Hall79d07d22020-04-27 18:20:16 +0100497
498 op.outputs[idx] = reshape_in
Tim Hall79d07d22020-04-27 18:20:16 +0100499 return tens
500
501
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200502def add_padding_fields(op, arch, nng):
Jacob Bohlin90033f32020-08-28 15:45:44 +0200503 if op.run_on_npu:
504 if "padding" in op.attrs:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200505 if op.type.is_conv2d_op() or op.type.is_depthwise_conv2d_op():
Jacob Bohlin90033f32020-08-28 15:45:44 +0200506 kernel_size = op.inputs[1].shape[:2]
507 input_shape = op.inputs[0].shape
Louis Verhaardaee5d752020-09-30 09:01:52 +0200508 elif op.type.is_pool_op() or op.type.npu_block_type == NpuBlockType.ReduceSum:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200509 kernel_size = op.attrs["ksize"][1:3]
510 input_shape = op.inputs[0].shape
Jacob Bohlin90033f32020-08-28 15:45:44 +0200511 else:
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000512 raise UnsupportedFeatureError(f"Unknown operation that uses padding: {optype_to_builtintype(op.type)}")
Tim Hall79d07d22020-04-27 18:20:16 +0100513
Louis Verhaardaee5d752020-09-30 09:01:52 +0200514 if op.type == Op.Conv2DBackpropInputSwitchedBias:
Jacob Bohlin90033f32020-08-28 15:45:44 +0200515 upscaling_factor = op.outputs[0].shape[1] // input_shape[1]
516 padding, skirt = calc_upscaled_padding_and_skirt(
517 op.attrs["padding"], kernel_size, op.attrs["strides"], input_shape, upscaling_factor
518 )
519 else:
520 dilation_h, dilation_w = op.get_dilation_h_w()
521 dilated_kernel_size = [dilation_h * (kernel_size[0] - 1) + 1, dilation_w * (kernel_size[1] - 1) + 1]
522 padding, skirt = calc_padding_and_skirt(
523 op.attrs["padding"], dilated_kernel_size, op.attrs["strides"], input_shape
524 )
Jacob Bohlincf7da102020-05-20 09:03:40 +0200525
Jacob Bohlin90033f32020-08-28 15:45:44 +0200526 op.attrs["explicit_padding"] = padding
527 op.attrs["skirt"] = skirt
Jacob Bohlincf7da102020-05-20 09:03:40 +0200528
Tim Hall79d07d22020-04-27 18:20:16 +0100529 return op
530
531
Tim Hall79d07d22020-04-27 18:20:16 +0100532# Check if the op can be reordered
533def get_prepend_op(op):
534 inp = op.inputs[0]
535 # The op should be reordered between prev_op and prep_op
536 prev_op = inp.ops[-1]
537 prep_op = None
538 while prev_op.type in memory_only_ops and len(prev_op.outputs) == 1 and len(prev_op.outputs[0].consumers()) == 1:
539 prep_op = prev_op
540 inp = prev_op.inputs[0]
541 prev_op = inp.ops[-1]
Diego Russoea6111a2020-04-14 18:41:58 +0100542 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 +0100543 return prep_op
544
545 return None
546
547
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200548def convert_depthwise_to_conv(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +0100549 # Depthwise is equivalent to a single conv2d if the ifm depth is 1 and
550 # the ofm depth equals the depth multipler.
551 # If those conditions are true, then we can perform a simple
552 # switch of the operator type (and weight order)
553
Louis Verhaardaee5d752020-09-30 09:01:52 +0200554 if op.type == Op.DepthwiseConv2DBias and (op.attrs["depth_multiplier"] != 1):
Tim Hall79d07d22020-04-27 18:20:16 +0100555 ifm_tensor = op.inputs[0]
556 weight_tensor = op.inputs[1]
557 ofm_tensor = op.outputs[0]
558 if (ifm_tensor.shape[3] == 1) and (ofm_tensor.shape[3] == op.attrs["depth_multiplier"]):
559 # Change op type to Conv2d
Louis Verhaardaee5d752020-09-30 09:01:52 +0200560 op.type = Op.Conv2DBias
Tim Hall79d07d22020-04-27 18:20:16 +0100561 del op.attrs["channel_multiplier"]
562 del op.attrs["depth_multiplier"]
563
564 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100565 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Tim Hall79d07d22020-04-27 18:20:16 +0100566 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200567 raise UnsupportedFeatureError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000568 f"Unsupported 'DEPTHWISE_CONV_2D' with depth_multiplier = {op.attrs['depth_multiplier']},",
569 f" ifm channels = {ifm_tensor.shape[3]}, ofm channels = {ofm_tensor.shape[3]}",
Tim Hall79d07d22020-04-27 18:20:16 +0100570 )
Tim Halle6ccd872020-11-09 16:46:37 +0000571 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100572 return op
573
574
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200575def reorder_depthwise_weights(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200576 if op.type.is_depthwise_conv2d_op():
Jacob Bohline843d332020-06-23 12:12:56 +0200577 weight_tensor = op.inputs[1]
578 weight_tensor.quant_values = np.transpose(weight_tensor.quant_values, (0, 1, 3, 2))
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100579 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Jacob Bohline843d332020-06-23 12:12:56 +0200580 weight_tensor.weight_transpose_depthwise = True
581
582 return op
583
584
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200585def convert_conv_to_fc(op, arch, nng):
Michael McGeagh8d939c02020-07-29 13:11:43 +0100586 # Conv 1x1 can be equivalent to Fully Connected.
587 # By representing certain convs as fully connected layers, Vela can better determine wether or not to use
588 # caching/double buffering for the weights.
589 # (Weights dont need to be reloaded for convs when IFM H and W are 1)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200590 if op.type == Op.Conv2DBias:
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100591 _, h, w, _ = op.ifm_shapes[0]
Michael McGeagh8d939c02020-07-29 13:11:43 +0100592 kh, kw, _, _ = op.inputs[1].shape
593 if h == 1 and w == 1 and kh == 1 and kw == 1:
594 # Overwrite this op as a Fully Connected Op
595 op.name += "_fc"
Louis Verhaardaee5d752020-09-30 09:01:52 +0200596 op.type = Op.FullyConnected
Michael McGeagh8d939c02020-07-29 13:11:43 +0100597 op.attrs = {
Michael McGeagh8d939c02020-07-29 13:11:43 +0100598 "weights_format": 0,
Michael McGeagh8d939c02020-07-29 13:11:43 +0100599 }
600 # Reshape Weights to be 2D. HWIO becomes just IO (as H and W are 1, they can just be dropped)
601 weight_tensor = op.inputs[1]
602 weight_tensor.quant_values = weight_tensor.quant_values.squeeze(axis=(0, 1))
603 weight_tensor.set_all_shapes(list(weight_tensor.quant_values.shape))
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100604
Michael McGeagh8d939c02020-07-29 13:11:43 +0100605 # The output from a fully connected is expected to be 2D so we need to add a reshape layer to convert it
606 # back to 4D afterwards as the next layer is expecting that shape
607 orig_ofm_tensor = op.outputs[0]
608 # 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})
609 fc_ofm_tensor = orig_ofm_tensor.clone("_fc")
610 fc_ofm_tensor.set_all_shapes([1, fc_ofm_tensor.shape[-1]])
611 fc_ofm_tensor.ops = [op]
612 # Add a reshape after the new OFM to convert it back to the original 4D shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100613 reshape_name = op.name + "_reshape"
614 new_shape_tens = create_const_tensor(reshape_name + "_shape", [1], DataType.int32, orig_ofm_tensor.shape)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200615 reshape_op = Operation(Op.Reshape, reshape_name)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100616 reshape_op.attrs["new_shape"] = orig_ofm_tensor.shape
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100617 reshape_op.inputs = [fc_ofm_tensor, new_shape_tens]
618 reshape_op.set_output_tensor(orig_ofm_tensor)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100619
Michael McGeagh8d939c02020-07-29 13:11:43 +0100620 # Replace this ops OFM to point to the 2D tensor
621 op.outputs[0] = fc_ofm_tensor
Tim Halle6ccd872020-11-09 16:46:37 +0000622 # Record optimisation in debug database
623 DebugDatabase.add_optimised(op, reshape_op)
624 DebugDatabase.add_optimised(op, op)
Michael McGeagh8d939c02020-07-29 13:11:43 +0100625 return op
626
627
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200628def fixup_relus_with_differing_ifm_ofm_scaling(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200629 if op.run_on_npu and op.type.is_relu_op():
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100630 ifm = op.inputs[0]
631 ofm = op.outputs[0]
632 # Relu with differing IFM and OFM scaling cannot be fused with another primary op
633 # and requires its own to be inserted
Tim Hall93582962020-09-09 21:58:15 +0100634 if not check_quantized_tens_scaling_equal(ifm, ofm):
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100635 # Override this op with its own primary op (avgpool)
636 relu_fused_op = create_avgpool_nop(op.name + "_avgpool")
637 # And fuse the original activation function to it
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100638 relu_fused_op.activation = create_activation_function(op.type)
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100639 # Tidy up and assign the ifm and ofm to the new op
640 ifm.consumer_list.remove(op)
Andreas Nevalainenf3d737e2020-09-25 14:12:43 +0200641
642 # if not 4d, reshape ifm/ofm
643 if len(ifm.shape) < 4:
644 ifm_shaped = create_reshape_tensor(ifm, full_shape(4, ifm.shape, 1))
645 ifm = ifm_shaped
646 if len(ofm.shape) < 4:
647 ofm_shaped = create_reshape_tensor(ofm, full_shape(4, ofm.shape, 1), False)
648 ofm = ofm_shaped
649
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +0100650 relu_fused_op.add_input_tensor(ifm)
651 relu_fused_op.set_output_tensor(ofm)
652 op = relu_fused_op
653 return op
654
655
Tim Hall79d07d22020-04-27 18:20:16 +0100656# Reorder activation op if it's after the memory only operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200657def fixup_act_reorder(op, arch, nng):
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000658 if op.type.is_relu_op() or op.type in (Op.Sigmoid, Op.Tanh):
Tim Hall79d07d22020-04-27 18:20:16 +0100659 prep_op = get_prepend_op(op)
Diego Russoea6111a2020-04-14 18:41:58 +0100660 if prep_op is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100661 act_op = op.clone("_reordered")
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100662 act_op.ifm_shapes = list(op.ifm_shapes)
663 act_op.ofm_shapes = list(op.ofm_shapes)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200664
665 # There is only one input tensor, overwrite it
666 act_op.set_input_tensor(prep_op.inputs[0], 0)
667
Tim Hall79d07d22020-04-27 18:20:16 +0100668 act_op_out = act_op.inputs[0].clone("_acted")
669 act_op_out.quantization = op.outputs[0].quantization.clone()
Michael McGeaghc5b549b2020-08-07 11:54:28 +0100670 act_op.set_output_tensor(act_op_out)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100671 act_op.ifm_shapes[0] = full_shape(4, prep_op.inputs[0].shape, 1)
672 act_op.ofm_shapes[0] = full_shape(4, act_op_out.shape, 1)
Patrik Gustavssoncb337042020-09-16 14:55:40 +0200673
674 # Update the consumer list
675 act_op_out.consumer_list = op.outputs[0].consumer_list.copy()
676 act_op_out.consumer_list.append(prep_op)
677
Tim Hall79d07d22020-04-27 18:20:16 +0100678 prep_op.inputs[0] = act_op_out
679 prep_op.outputs[0].quantization = act_op_out.quantization.clone()
680
681 # Mark the op so that it will be removed as passthrough later on
Louis Verhaardaee5d752020-09-30 09:01:52 +0200682 op.type = Op.Identity
Tim Halle6ccd872020-11-09 16:46:37 +0000683
684 # Record optimisation in debug database
685 DebugDatabase.add_optimised(op, act_op)
686 DebugDatabase.add_optimised(op, op)
Tim Hall79d07d22020-04-27 18:20:16 +0100687 return op
688
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200689
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200690def fixup_elementwise_with_scalars(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200691 if op.type.is_binary_elementwise_op():
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200692 ifm_tensor, ifm2_tensor, _, _ = op.get_ifm_ifm2_weights_ofm()
Charles Xu78792222020-05-13 10:15:26 +0200693 if ifm2_tensor.shape != [] and ifm_tensor.shape != []:
694 diff = len(ifm_tensor.shape) - len(ifm2_tensor.shape)
695 if diff > 0:
696 ifm2_tensor.shape = full_shape(len(ifm_tensor.shape), ifm2_tensor.shape, 1)
697 elif diff < 0:
698 ifm_tensor.shape = full_shape(len(ifm2_tensor.shape), ifm_tensor.shape, 1)
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200699 elif ifm_tensor.shape == [] and ifm_tensor.quant_values is None:
700 # IFM is marked as a scalar, but is a result of an operation; change it to a shape of size 1
701 ifm_tensor.shape = len(ifm2_tensor.shape) * [1]
702 ifm_tensor.storage_shape = ifm_tensor.shape
703 elif ifm2_tensor.shape == [] and ifm2_tensor.quant_values is None:
704 # IFM2 is marked as a scalar, but is a result of an operation; change it to a shape of size 1
705 ifm2_tensor.shape = len(ifm_tensor.shape) * [1]
706 ifm2_tensor.storage_shape = ifm2_tensor.shape
Charles Xu78792222020-05-13 10:15:26 +0200707 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100708
Louis Verhaarde0ef2732020-06-03 08:56:44 +0200709
Tim Hall4e127762020-05-15 16:05:49 +0100710# Set input/output tensor equivalence to the same id for memory operations
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200711def set_tensor_equivalence(op, arch, nng):
Michael McGeagh11b0bdb2020-09-08 11:07:35 +0100712 if op.type in memory_only_ops:
Tim Hall4e127762020-05-15 16:05:49 +0100713 eid = op.outputs[0].equivalence_id
714 for inp in op.inputs:
715 inp.equivalence_id = eid
716 return op
717
718
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100719def set_ifm_ofm_op_shapes(op, arch, nng):
720 if op.run_on_npu and op.type.needs_shapes():
721 if op.ifm_shapes or op.ofm_shapes:
722 # Shapes already set
723 return op
724 op.set_ifm_ofm_shapes()
725 return op
726
727
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200728def convert_softmax(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200729 if op.type == Op.Softmax and op.run_on_npu:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200730 softmax = SoftMax(op)
731 op = softmax.get_graph()
732 return op
733
734
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200735def convert_mul_max_to_abs_or_lrelu(op, arch, nng):
Diego Russoea6111a2020-04-14 18:41:58 +0100736 r"""Whenever there is a subgraph with this topology:
Tim Hall79d07d22020-04-27 18:20:16 +0100737
738 Input X For X = -1 or X > 0
739 | \ / This subgraph can be replaced with either
740 | Mul an Abs (if X = -1) or a LeakyReLU (if X > 0)
741 | /
742 Max
743 """
744
Louis Verhaardaee5d752020-09-30 09:01:52 +0200745 if op.type == Op.Maximum:
Tim Hall79d07d22020-04-27 18:20:16 +0100746 # finds the Mul input(s) to the Max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200747 muls = [i for i in op.inputs if i.ops[0].type == Op.Mul]
Tim Hall79d07d22020-04-27 18:20:16 +0100748 if len(muls) == 1:
749 mul = muls[0].ops[0]
750 elif len(muls) == 2:
751 # In the case both inputs are Muls, find the one with the same input as the Max
752 mul = [m for m in muls if len(set(op.inputs + m.ops[0].inputs)) == 1][0].ops[0]
753 else:
754 # No Mul inputs
755 return op
756
757 # make sure the Mul doesn't have any other consumers
Louis Verhaardd7911c42020-08-25 13:36:41 +0200758 mul_ofm = mul.outputs[0]
759 if len(mul_ofm.consumers()) != 1:
Tim Hall79d07d22020-04-27 18:20:16 +0100760 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200761 # make sure the Mul doesn't have a fused activation function
762 if mul.activation:
Tim Hall79d07d22020-04-27 18:20:16 +0100763 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200764 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100765 if ifm is None or ofm is None:
766 return op
767
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200768 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
769 return op
Tim Hall93582962020-09-09 21:58:15 +0100770 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 +0200771 # rewrite to LeakyRelu currently only makes sense if the quantization is identical
772 return op
Tim Hall79d07d22020-04-27 18:20:16 +0100773
774 # finds the branched input that goes to both the Max and the Mul
775 shared = set(op.inputs) & set(mul.inputs)
776 if len(shared) == 1:
777 shared_in = shared.pop()
778 # find the constant scalar input to the Mul
779 const_tens = (set(mul.inputs) - {shared_in}).pop()
780 # check that it is a scalar
781 if const_tens.shape != []:
782 return op
783 const = const_tens.ops[0]
784 # check that it is a constant
Louis Verhaardaee5d752020-09-30 09:01:52 +0200785 if const.type != Op.Const:
Tim Hall79d07d22020-04-27 18:20:16 +0100786 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200787 # Remove the Mul from the shared input's consumers
788 shared_in.consumer_list.remove(mul)
Tim Hall79d07d22020-04-27 18:20:16 +0100789 else:
790 return op
791
792 val = const.outputs[0].values
793 if val >= 0:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200794 new_op = Op.LeakyRelu
Tim Hall79d07d22020-04-27 18:20:16 +0100795 op.attrs["alpha"] = val
Louis Verhaardd7911c42020-08-25 13:36:41 +0200796 # to produce bit exact results, the alpha is not enough;
797 # save additional scaling info in attr "alpha_scale", to be used as input
798 # to the LUT construction
799 alpha_scalar = const_tens.quant_values - const_tens.quantization.zero_point
800 mul_ifm_scale = np.double(ifm.quantization.scale_f32)
801 mul_ifm2_scale = np.double(const_tens.quantization.scale_f32)
802 mul_ofm_scale = np.double(mul_ofm.quantization.scale_f32)
803 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(mul_ifm_scale, mul_ifm2_scale, mul_ofm_scale)
804 op.attrs["alpha_scaling"] = (alpha_scalar, alpha_scale, alpha_shift)
Tim Hall79d07d22020-04-27 18:20:16 +0100805 elif val == -1:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200806 new_op = Op.Abs
Tim Hall79d07d22020-04-27 18:20:16 +0100807 else:
808 return op
809
Louis Verhaardaee5d752020-09-30 09:01:52 +0200810 op.type = new_op
811 op.name = op.name.replace("Maximum", new_op.name)
812 op.outputs[0].name = op.outputs[0].name.replace("Maximum", new_op.name)
Tim Hall79d07d22020-04-27 18:20:16 +0100813 op.inputs = [shared_in]
Tim Halle6ccd872020-11-09 16:46:37 +0000814
815 # Record optimisation in debug database
816 DebugDatabase.add_optimised(op, op)
817
Tim Hall79d07d22020-04-27 18:20:16 +0100818 return op
819
820
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200821def convert_lrelu_to_mul_max(op, arch):
822 # Converts LeakyRelu to Max(alpha * IFM, identity * IFM)
823 # (the opposite of convert_mul_max_to_abs_or_lrelu)
Louis Verhaardaee5d752020-09-30 09:01:52 +0200824 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100825 if ifm is None or ofm is None:
826 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200827
828 # Add multiplication with alpha
Louis Verhaardaee5d752020-09-30 09:01:52 +0200829 mul_alpha = Operation(Op.Mul, op.name + "_mul_alpha")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200830 mul_alpha.add_input_tensor(ifm)
831 # Create const tensor containing alpha as scalar
832 alpha = op.attrs["alpha"]
833 quantization = ifm.quantization.clone()
834 quantization.min = 0
835 quantization.max = alpha * (quantization.quant_max - quantization.quant_min)
836 quantization.scale_f32 = alpha
837 quantization.zero_point = 0
838 alpha_tens = create_const_tensor(op.name + "_alpha_scalar", [], ifm.dtype, [1], np.int8, quantization=quantization)
839 mul_alpha.add_input_tensor(alpha_tens)
840 fm_alpha = ofm.clone(op.name + "_alpha")
841 mul_alpha.set_output_tensor(fm_alpha)
Tim Halle6ccd872020-11-09 16:46:37 +0000842 DebugDatabase.add_optimised(op, mul_alpha)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200843
Tim Hall93582962020-09-09 21:58:15 +0100844 if check_quantized_tens_scaling_equal(ifm, ofm):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200845 # No identity multiplication is needed
846 fm_id = ifm
847 else:
848 # Add multiplication with identity
Louis Verhaardaee5d752020-09-30 09:01:52 +0200849 mul_identity = Operation(Op.Mul, op.name + "_mul_identity")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200850 mul_identity.add_input_tensor(ifm)
851 # Create const tensor containing identity as scalar
852 quantization = ifm.quantization.clone()
853 quantization.min = 0
854 quantization.max = quantization.quant_max - quantization.quant_min
855 quantization.scale_f32 = 1
856 quantization.zero_point = 0
857 identity_tens = create_const_tensor(
858 op.name + "_id_scalar", [], ifm.dtype, [1], np.uint8, quantization=quantization
859 )
860 mul_identity.add_input_tensor(identity_tens)
861 fm_id = ofm.clone(op.name + "_id")
862 mul_identity.set_output_tensor(fm_id)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100863 DebugDatabase.add_optimised(op, mul_identity)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200864
865 # Convert LeakyRelu to Max, add the results of the multiplication(s) as inputs
Louis Verhaardaee5d752020-09-30 09:01:52 +0200866 op.type = Op.Maximum
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200867 op.name = op.name.replace("LeakyRelu", "Maximum")
868 op.inputs = []
869 ifm.consumer_list.remove(op)
870 op.add_input_tensor(fm_alpha)
871 op.add_input_tensor(fm_id)
Tim Halle6ccd872020-11-09 16:46:37 +0000872
873 DebugDatabase.add_optimised(op, op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200874 return op
875
876
Louis Verhaard2e186c72020-10-09 10:47:04 +0200877def convert_to_lut(op, lut_values, lut_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200878 # Rewrite the operation by Add with scalar 0 + LUT activation
879 ifm = op.inputs[0]
Tim Hall93582962020-09-09 21:58:15 +0100880 if ifm is None:
881 return op
Louis Verhaard58520b92020-08-24 16:45:38 +0200882 assert ifm.dtype.size_in_bytes() == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200883 op.type = Op.Add
Louis Verhaard2e186c72020-10-09 10:47:04 +0200884 op.name = op.name + "_lut_" + lut_name
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200885 # Mark as no-op to enable potential fusing optimizations
886 op.attrs["is_nop"] = True
887 # Create an input tensor containing scalar zero
888 quantization = QuantizationParameters(0.0, 255.0)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200889 quantization.scale_f32 = ifm.quantization.scale_f32
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200890 quantization.zero_point = 0
Louis Verhaard2e186c72020-10-09 10:47:04 +0200891 tens = create_const_tensor(op.inputs[0].name + "_scalar0", [], ifm.dtype, [0], np.uint8, quantization=quantization)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200892 op.add_input_tensor(tens)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100893 op.ifm_shapes.append(full_shape(4, tens.shape, 1))
894
Louis Verhaardf03bad32020-09-25 08:30:44 +0200895 # The LUT must be applied without any preceding rescaling (the LUT itself performs the rescale),
896 # so even if the OFM has a different scale than the IFM, the generated OFM scale instructions
897 # should be the same as the IFM
Louis Verhaardaee5d752020-09-30 09:01:52 +0200898 op.forced_output_quantization = ifm.quantization
Louis Verhaard2e186c72020-10-09 10:47:04 +0200899 lut_tensor = lut.create_lut_tensor(op.name + "_values", lut_values, DataType.int8)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200900 op.set_activation_lut(lut_tensor)
901 return op
902
903
Louis Verhaard2e186c72020-10-09 10:47:04 +0200904def convert_to_lut8(op, fn, fn_name):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200905 # Converts op to a no-op + int8/uint8 LUT which is generated with the given function.
906 # fn is a function(real) -> real
Louis Verhaardaee5d752020-09-30 09:01:52 +0200907 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardf03bad32020-09-25 08:30:44 +0200908 if ifm.dtype not in (DataType.uint8, DataType.int8) or ifm.dtype != ofm.dtype:
909 return op
910 # Generate the LUT
911 ifm_scale = np.double(ifm.quantization.scale_f32)
912 ofm_scale = np.double(ofm.quantization.scale_f32)
913 zp_in = ifm.quantization.zero_point
914 zp_out = ofm.quantization.zero_point
915 values = []
916 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
917 quantized_min = min(ix)
918 quantized_max = max(ix)
919 for x in ix:
920 x_real = ifm_scale * (x - zp_in)
921 y_real = fn(x_real)
922 lut_result = round_away_zero(zp_out + y_real / ofm_scale)
923 lut_result = min(quantized_max, max(quantized_min, lut_result))
924 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200925 return convert_to_lut(op, values, fn_name)
Louis Verhaardf03bad32020-09-25 08:30:44 +0200926
927
928def convert_lrelu_to_lut(op, arch):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200929 ifm, ofm = op.get_ifm_ofm()
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200930 # Generate the LUT
Louis Verhaardd7911c42020-08-25 13:36:41 +0200931 alpha = op.attrs["alpha"]
932 ifm_scale = np.double(ifm.quantization.scale_f32)
933 ofm_scale = np.double(ofm.quantization.scale_f32)
934 zp_in = ifm.quantization.zero_point
935 zp_out = ofm.quantization.zero_point
936 identity_scale, identity_shift = scaling.elementwise_mul_scale(ifm_scale, 1, ofm_scale)
937 alpha_scalar = 1
938 alpha_scale, alpha_shift = scaling.elementwise_mul_scale(ifm_scale, alpha, ofm_scale)
939 if "alpha_scaling" in op.attrs:
940 # The LeakyRelu was the result from convert_mul_max_to_abs_or_lrelu
941 alpha_scalar, alpha_scale, alpha_shift = op.attrs["alpha_scaling"]
942 values = []
Louis Verhaard58520b92020-08-24 16:45:38 +0200943 ix = range(256) if ifm.dtype == DataType.uint8 else range(-128, 128)
Louis Verhaardd7911c42020-08-25 13:36:41 +0200944 quantized_min = min(ix)
945 quantized_max = max(ix)
946 for x in ix:
947 if x < zp_in:
948 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(
949 alpha_scalar * (x - zp_in), alpha_scale, alpha_shift
950 )
951 else:
952 lut_result = zp_out + fp_math.multiply_by_quantized_multiplier(x - zp_in, identity_scale, identity_shift)
953 lut_result = min(quantized_max, max(quantized_min, lut_result))
954 values.append(lut_result)
Louis Verhaard2e186c72020-10-09 10:47:04 +0200955 return convert_to_lut(op, values, "lrelu")
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200956
957
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200958def convert_lrelu(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200959 # Converts LeakyRelu to a LUT based solution if possible, otherwise a mul + max
Louis Verhaardaee5d752020-09-30 09:01:52 +0200960 if op.type != Op.LeakyRelu:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200961 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +0200962 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +0100963 if ifm is None or ofm is None:
964 return op
Louis Verhaardd7911c42020-08-25 13:36:41 +0200965 if ifm.dtype in (DataType.uint8, DataType.int8) and ifm.dtype == ofm.dtype:
966 # use LUT for int8/uint8
967 return convert_lrelu_to_lut(op, arch)
Tim Hall93582962020-09-09 21:58:15 +0100968 if check_quantized_tens_scaling_equal(ifm, ofm) and ifm.dtype == ofm.dtype == DataType.int16:
Louis Verhaardd7911c42020-08-25 13:36:41 +0200969 # use LeakyRelu unmodified for int16 with equal input/output scaling
970 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200971 return convert_lrelu_to_mul_max(op, arch)
972
973
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200974def convert_tanh_sigmoid_to_lut(op, arch, nng):
Louis Verhaardf03bad32020-09-25 08:30:44 +0200975 # Converts int8/uint8 Sigmoid and Tanh to a LUT based solution
Louis Verhaardaee5d752020-09-30 09:01:52 +0200976 if op.type == Op.Sigmoid:
Louis Verhaard2e186c72020-10-09 10:47:04 +0200977 return convert_to_lut8(op, clamp_sigmoid, "sigmoid")
Louis Verhaardaee5d752020-09-30 09:01:52 +0200978 elif op.type == Op.Tanh:
Louis Verhaard2e186c72020-10-09 10:47:04 +0200979 return convert_to_lut8(op, math.tanh, "tanh")
Louis Verhaardf03bad32020-09-25 08:30:44 +0200980 return op
981
982
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +0200983def remove_unwanted_reshapes(op, arch, nng):
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200984 # Try to remove reshapes enclosing ElementWise operator with only one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +0200985 if not op.run_on_npu or not op.type.is_elementwise_op():
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200986 return op
987
988 # Check if the ElementWise operator only have one non-constant input
Louis Verhaardaee5d752020-09-30 09:01:52 +0200989 non_const_tens = [x for x in op.inputs if x.ops[0].type != Op.Const]
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +0200990 if len(non_const_tens) != 1:
991 return op
992 ifm = non_const_tens[0]
993
994 # Check if operation is enclosed by Reshapes that can be removed
995 ofm = op.outputs[0]
996 prev_op = ifm.ops[0]
997 if (
998 len(ifm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +0200999 and prev_op.type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001000 and len(ofm.consumer_list) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001001 and ofm.consumer_list[0].type == Op.Reshape
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001002 ):
1003 # Operation is enclosed by reshapes, check if they can be removed
Louis Verhaardaee5d752020-09-30 09:01:52 +02001004 prev_op_ifm, prev_op_ofm = prev_op.get_ifm_ofm()
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001005 cons_op = ofm.consumer_list[0]
1006 cons_op_ifm = ofm
1007 cons_op_ofm = cons_op.outputs[0]
1008 if len(prev_op_ifm.shape) == len(cons_op_ofm.shape):
1009 # Check if quantization is the same in the input and output for the reshape ops
Tim Hall93582962020-09-09 21:58:15 +01001010 if check_quantized_tens_scaling_equal(prev_op_ifm, prev_op_ofm) and check_quantized_tens_scaling_equal(
1011 cons_op_ifm, cons_op_ofm
1012 ):
Patrik Gustavsson7ad862a2020-09-29 14:09:43 +02001013 op.set_input_tensor(prev_op_ifm, 0)
1014 op.set_output_tensor(cons_op_ofm)
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001015 return op
1016
1017
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001018def fuse_activation_function_with_prev(op, arch, nng):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001019 # if op is a no-op: attempts to move the activation function to the preceding op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001020 if not op.attrs.get("is_nop", False) or op.activation is None:
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001021 return op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001022 ifm, ofm = op.get_ifm_ofm()
Tim Hall93582962020-09-09 21:58:15 +01001023 if ifm is None or ofm is None:
1024 return op
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001025 # finds the input(s) to the operation
1026 prev_op = ifm.ops[0]
1027 # Note: the below checks on prev_op require that a first optimize pass on the full graph has been performed
1028 fuse = (
1029 prev_op.run_on_npu
Louis Verhaardaee5d752020-09-30 09:01:52 +02001030 and prev_op.type.npu_block_type != NpuBlockType.Default
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001031 and len(ifm.ops) == 1
1032 and len(prev_op.outputs[0].consumers()) == 1
Louis Verhaardaee5d752020-09-30 09:01:52 +02001033 and prev_op.activation is None
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001034 )
1035 if op.activation_lut is not None and arch.shram_reserved_unused_banks == 0:
1036 # TODO: if SHRAM LUT space is shared with SHRAM ACC (32, 64 MAC),
1037 # LUT currently only works correctly for elementwise ops
1038 fuse = False
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001039 if not fuse:
1040 return op
1041 # Move the fused activation function + corresponding info to prev_op
Louis Verhaardaee5d752020-09-30 09:01:52 +02001042 prev_op.activation = op.activation
1043 prev_op.forced_output_quantization = op.forced_output_quantization
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001044 if op.activation_lut is not None:
1045 prev_op.set_activation_lut(op.activation_lut)
1046 # Bypass op
Louis Verhaard98a34992020-09-01 10:39:04 +02001047 prev_op.set_output_tensor(ofm)
Tim Halle6ccd872020-11-09 16:46:37 +00001048 DebugDatabase.add_optimised(op, prev_op)
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001049 return op
1050
1051
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001052def add_attrs_to_resizebilinear(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001053 if op.type == Op.ResizeBilinear and op.run_on_npu:
Dwight Lidman42fed942020-05-29 09:37:03 +02001054 input_tensor = op.inputs[0]
1055 upscaled_shape = [input_tensor.shape[1] * 2, input_tensor.shape[2] * 2]
1056 out_shape = op.outputs[0].shape[1:3]
1057 if not op.attrs["align_corners"] and out_shape == upscaled_shape:
1058 # this means the output is supposed to be a x2 upscale,
1059 # so we need to do SAME padding
Michael McGeagh16895482020-12-14 15:51:20 +00001060 op.attrs["padding"] = Padding.SAME
Dwight Lidman42fed942020-05-29 09:37:03 +02001061 elif op.attrs["align_corners"] and out_shape == [upscaled_shape[0] - 1, upscaled_shape[1] - 1]:
1062 # here we can just run the avg pool without padding and
1063 # produce a (M * 2 - 1, N * 2 - 1) sized output
Michael McGeagh16895482020-12-14 15:51:20 +00001064 op.attrs["padding"] = Padding.VALID
Dwight Lidman42fed942020-05-29 09:37:03 +02001065 else:
Charles Xu9a03fdf2020-07-02 15:12:40 +02001066 return op
Dwight Lidman42fed942020-05-29 09:37:03 +02001067 input_tensor.resampling_mode = resampling_mode.NEAREST
Tim Hallc30f4952020-06-15 20:47:35 +01001068 op.attrs.update({"strides": (1, 1, 1, 1), "ksize": (1, 2, 2, 1)})
Dwight Lidman42fed942020-05-29 09:37:03 +02001069 return op
1070
1071
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001072def fixup_bias_tensors(op, arch, nng):
Louis Verhaardaee5d752020-09-30 09:01:52 +02001073 if op.type.needs_bias() and op.bias is None:
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001074 # Op has no bias, add bias tensor filled with zeros
1075 nr_biases = op.inputs[1].shape[-1]
1076 bias_values = [0] * nr_biases
1077 bias_tensor = create_const_tensor(op.name + "_bias", [nr_biases], DataType.int32, bias_values)
1078 bias_tensor.quant_values = bias_tensor.values
1079 op.set_input_tensor(bias_tensor, -1)
Jacob Bohlin67e0d8f2020-08-20 10:53:02 +02001080
1081 return op
1082
1083
Patrik Gustavsson3010d9b2020-10-01 08:22:10 +02001084def supported_operator_check(op, arch, nng):
Tim Hall79d07d22020-04-27 18:20:16 +01001085 op.run_on_npu = arch.supported_operators.is_operator_supported(op)
1086 return op
1087
1088
Tim Halle6ccd872020-11-09 16:46:37 +00001089def _record_optimised(op, arch):
1090 if op.type != Op.Const:
1091 DebugDatabase.add_optimised(op, op)
1092
1093
Tim Hall79d07d22020-04-27 18:20:16 +01001094def optimise_graph_a(nng, arch, verbose_graph=False):
1095 if verbose_graph:
1096 nng.print_graph()
1097
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001098 pre_process_list = [
1099 supported_operator_check,
1100 set_ifm_ofm_op_shapes,
1101 # TODO: memory-only Op removal
1102 ]
1103
1104 for idx, sg in enumerate(nng.subgraphs):
1105 # rewrite graph pass
1106 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
1107 nng, sg, arch, [], pre_process_list, rewrite_unsupported=False,
1108 )
1109
Tim Hall79d07d22020-04-27 18:20:16 +01001110 op_rewrite_list = [
Tim Hall4e127762020-05-15 16:05:49 +01001111 set_tensor_equivalence,
Tim Hall79d07d22020-04-27 18:20:16 +01001112 convert_depthwise_to_conv,
Michael McGeagh8d939c02020-07-29 13:11:43 +01001113 convert_conv_to_fc,
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001114 convert_softmax,
Tim Hall79d07d22020-04-27 18:20:16 +01001115 fixup_fully_connected_input,
Diqing Zhong94457b12020-12-09 15:22:40 +01001116 convert_batched_fc_shape,
Tim Hall79d07d22020-04-27 18:20:16 +01001117 fixup_pack_input,
Fredrik Svedberg0f98b362020-09-29 10:00:39 +02001118 unfuse_activation_function,
Tim Hall79d07d22020-04-27 18:20:16 +01001119 fixup_conv2d_backprop,
Michael McGeagh8dbf8cf2020-09-08 11:09:48 +01001120 fixup_relus_with_differing_ifm_ofm_scaling,
Tim Hall79d07d22020-04-27 18:20:16 +01001121 fixup_act_reorder,
Charles Xu78792222020-05-13 10:15:26 +02001122 fixup_elementwise_with_scalars,
Jacob Bohline843d332020-06-23 12:12:56 +02001123 reorder_depthwise_weights,
Charles Xu9a03fdf2020-07-02 15:12:40 +02001124 fixup_resizebilinear,
Jacob Bohlina41cd4d2020-08-26 18:21:28 +02001125 fixup_bias_tensors,
Dwight Lidmanc3862c22020-09-14 15:22:33 +02001126 convert_nop_split_to_identity,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001127 convert_mul_max_to_abs_or_lrelu,
Patrik Gustavssonfa4cb292020-09-10 08:19:36 +02001128 remove_unwanted_reshapes,
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001129 convert_lrelu,
Louis Verhaardf03bad32020-09-25 08:30:44 +02001130 convert_tanh_sigmoid_to_lut,
Tim Hall79d07d22020-04-27 18:20:16 +01001131 ]
1132
1133 for idx, sg in enumerate(nng.subgraphs):
1134 # rewrite graph pass
1135 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Dwight Lidman73320a42020-11-05 10:34:41 +01001136 nng, sg, arch, [], op_rewrite_list, rewrite_unsupported=False,
Tim Hall79d07d22020-04-27 18:20:16 +01001137 )
1138
1139 for idx, sg in enumerate(nng.subgraphs):
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001140 # remove passthrough tensors and attempt further optimizations
1141 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001142 nng, sg, arch, [remove_passthrough_tensor], [fuse_activation_function_with_prev, add_padding_fields],
Louis Verhaardb9fc33c2020-08-13 11:47:36 +02001143 )
Tim Hall79d07d22020-04-27 18:20:16 +01001144
Tim Halle6ccd872020-11-09 16:46:37 +00001145 # Post-optimisation operator debug tracing
1146 for sg in nng.subgraphs:
1147 rewrite_graph.visit_graph_post_order(sg.output_tensors, arch, [], [_record_optimised])
1148
Tim Hall79d07d22020-04-27 18:20:16 +01001149 if verbose_graph:
1150 nng.print_graph()
1151 return nng
1152
Diego Russoea6111a2020-04-14 18:41:58 +01001153
Tim Hall79d07d22020-04-27 18:20:16 +01001154def optimise_graph_b(nng, arch, verbose_graph=False):
1155 if verbose_graph:
1156 nng.print_graph()
1157
1158 for idx, sg in enumerate(nng.subgraphs):
1159 # combined rewrite graph pass
Dwight Lidmanc6ac1942020-10-02 14:55:45 +02001160 nng.subgraphs[idx] = rewrite_graph.rewrite_graph_pre_order(
Patrik Gustavsson2349d422020-12-01 16:02:29 +01001161 nng,
1162 sg,
1163 arch,
1164 [fixup_unpack_output, fixup_stridedslice_output, rewrite_concat, rewrite_split],
1165 [set_ifm_ofm_op_shapes],
Dwight Lidmanc6ac1942020-10-02 14:55:45 +02001166 )
Tim Hall79d07d22020-04-27 18:20:16 +01001167
1168 if verbose_graph:
1169 nng.print_graph()
1170 return nng